Remove uneeded condition on transaction status in ATG
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16IncomingRequestService.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
802cfa13
JB
3import { ChangeAvailabilityRequest, ChangeConfigurationRequest, ClearChargingProfileRequest, GetConfigurationRequest, GetDiagnosticsRequest, MessageTrigger, OCPP16AvailabilityType, OCPP16IncomingRequestCommand, OCPP16TriggerMessageRequest, RemoteStartTransactionRequest, RemoteStopTransactionRequest, ResetRequest, SetChargingProfileRequest, UnlockConnectorRequest } from '../../../types/ocpp/1.6/Requests';
4import { ChangeAvailabilityResponse, ChangeConfigurationResponse, ClearChargingProfileResponse, GetConfigurationResponse, GetDiagnosticsResponse, OCPP16TriggerMessageResponse, SetChargingProfileResponse, UnlockConnectorResponse } from '../../../types/ocpp/1.6/Responses';
c0560973 5import { ChargingProfilePurposeType, OCPP16ChargingProfile } from '../../../types/ocpp/1.6/ChargingProfile';
47e22477 6import { Client, FTPResponse } from 'basic-ftp';
290d006c 7import { IncomingRequestCommand, RequestCommand } from '../../../types/ocpp/Requests';
c0560973
JB
8import { OCPP16AuthorizationStatus, OCPP16StopTransactionReason } from '../../../types/ocpp/1.6/Transaction';
9
10import Constants from '../../../utils/Constants';
9ccca265 11import { DefaultResponse } from '../../../types/ocpp/Responses';
c0560973
JB
12import { ErrorType } from '../../../types/ocpp/ErrorType';
13import { MessageType } from '../../../types/ocpp/MessageType';
14import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
47e22477 15import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus';
c0560973
JB
16import { OCPP16StandardParametersKey } from '../../../types/ocpp/1.6/Configuration';
17import { OCPPConfigurationKey } from '../../../types/ocpp/Configuration';
14763b46 18import OCPPError from '../OCPPError';
c0560973 19import OCPPIncomingRequestService from '../OCPPIncomingRequestService';
a3868ec4 20import { URL } from 'url';
c0560973 21import Utils from '../../../utils/Utils';
47e22477 22import fs from 'fs';
c0560973 23import logger from '../../../utils/Logger';
47e22477
JB
24import path from 'path';
25import tar from 'tar';
c0560973
JB
26
27export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
28 public async handleRequest(messageId: string, commandName: OCPP16IncomingRequestCommand, commandPayload: Record<string, unknown>): Promise<void> {
29 let response;
35ff6ec4 30 const methodName = `handleRequest${commandName}`;
c0560973 31 // Call
35ff6ec4 32 if (typeof this[methodName] === 'function') {
c0560973
JB
33 try {
34 // Call the method to build the response
35ff6ec4 35 response = await this[methodName](commandPayload);
c0560973
JB
36 } catch (error) {
37 // Log
38 logger.error(this.chargingStation.logPrefix() + ' Handle request error: %j', error);
a4cc42ea 39 // Send back an error response to inform backend
c0560973
JB
40 await this.chargingStation.ocppRequestService.sendError(messageId, error, commandName);
41 throw error;
42 }
43 } else {
44 // Throw exception
a6b3c6c3 45 const error = new OCPPError(ErrorType.NOT_IMPLEMENTED, `${commandName} is not implemented to handle payload ${JSON.stringify(commandPayload, null, 2)}`, commandName);
821c6c82
JB
46 await this.chargingStation.ocppRequestService.sendError(messageId, error, commandName);
47 throw error;
c0560973
JB
48 }
49 // Send the built response
50 await this.chargingStation.ocppRequestService.sendMessage(messageId, response, MessageType.CALL_RESULT_MESSAGE, commandName);
51 }
52
53 // Simulate charging station restart
54 private handleRequestReset(commandPayload: ResetRequest): DefaultResponse {
71623267
JB
55 // eslint-disable-next-line @typescript-eslint/no-misused-promises
56 setImmediate(async (): Promise<void> => {
c0560973
JB
57 await this.chargingStation.stop(commandPayload.type + 'Reset' as OCPP16StopTransactionReason);
58 await Utils.sleep(this.chargingStation.stationInfo.resetTime);
71623267 59 this.chargingStation.start();
c0560973 60 });
d7d1db72 61 logger.info(`${this.chargingStation.logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(this.chargingStation.stationInfo.resetTime)}`);
c0560973
JB
62 return Constants.OCPP_RESPONSE_ACCEPTED;
63 }
64
65 private handleRequestClearCache(): DefaultResponse {
66 return Constants.OCPP_RESPONSE_ACCEPTED;
67 }
68
69 private async handleRequestUnlockConnector(commandPayload: UnlockConnectorRequest): Promise<UnlockConnectorResponse> {
70 const connectorId = commandPayload.connectorId;
71 if (connectorId === 0) {
72 logger.error(this.chargingStation.logPrefix() + ' Trying to unlock connector ' + connectorId.toString());
73 return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
74 }
75 if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
76 const transactionId = this.chargingStation.getConnector(connectorId).transactionId;
6ed92bc1
JB
77 const stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
78 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
79 this.chargingStation.getTransactionIdTag(transactionId),
80 OCPP16StopTransactionReason.UNLOCK_COMMAND);
c0560973
JB
81 if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
82 return Constants.OCPP_RESPONSE_UNLOCKED;
83 }
84 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
85 }
86 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.AVAILABLE);
87 this.chargingStation.getConnector(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
88 return Constants.OCPP_RESPONSE_UNLOCKED;
89 }
90
91 private handleRequestGetConfiguration(commandPayload: GetConfigurationRequest): GetConfigurationResponse {
92 const configurationKey: OCPPConfigurationKey[] = [];
93 const unknownKey: string[] = [];
94 if (Utils.isEmptyArray(commandPayload.key)) {
95 for (const configuration of this.chargingStation.configuration.configurationKey) {
96 if (Utils.isUndefined(configuration.visible)) {
97 configuration.visible = true;
98 }
99 if (!configuration.visible) {
100 continue;
101 }
102 configurationKey.push({
103 key: configuration.key,
104 readonly: configuration.readonly,
105 value: configuration.value,
106 });
107 }
108 } else {
109 for (const key of commandPayload.key) {
110 const keyFound = this.chargingStation.getConfigurationKey(key);
111 if (keyFound) {
112 if (Utils.isUndefined(keyFound.visible)) {
113 keyFound.visible = true;
114 }
115 if (!keyFound.visible) {
116 continue;
117 }
118 configurationKey.push({
119 key: keyFound.key,
120 readonly: keyFound.readonly,
121 value: keyFound.value,
122 });
123 } else {
124 unknownKey.push(key);
125 }
126 }
127 }
128 return {
129 configurationKey,
130 unknownKey,
131 };
132 }
133
134 private handleRequestChangeConfiguration(commandPayload: ChangeConfigurationRequest): ChangeConfigurationResponse {
135 // JSON request fields type sanity check
136 if (!Utils.isString(commandPayload.key)) {
290d006c 137 logger.error(`${this.chargingStation.logPrefix()} ${RequestCommand.CHANGE_CONFIGURATION} request key field is not a string:`, commandPayload);
c0560973
JB
138 }
139 if (!Utils.isString(commandPayload.value)) {
290d006c 140 logger.error(`${this.chargingStation.logPrefix()} ${RequestCommand.CHANGE_CONFIGURATION} request value field is not a string:`, commandPayload);
c0560973
JB
141 }
142 const keyToChange = this.chargingStation.getConfigurationKey(commandPayload.key, true);
143 if (!keyToChange) {
144 return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED;
145 } else if (keyToChange && keyToChange.readonly) {
146 return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED;
147 } else if (keyToChange && !keyToChange.readonly) {
148 const keyIndex = this.chargingStation.configuration.configurationKey.indexOf(keyToChange);
149 let valueChanged = false;
150 if (this.chargingStation.configuration.configurationKey[keyIndex].value !== commandPayload.value) {
151 this.chargingStation.configuration.configurationKey[keyIndex].value = commandPayload.value;
152 valueChanged = true;
153 }
154 let triggerHeartbeatRestart = false;
155 if (keyToChange.key === OCPP16StandardParametersKey.HeartBeatInterval && valueChanged) {
156 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartbeatInterval, commandPayload.value);
157 triggerHeartbeatRestart = true;
158 }
159 if (keyToChange.key === OCPP16StandardParametersKey.HeartbeatInterval && valueChanged) {
160 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartBeatInterval, commandPayload.value);
161 triggerHeartbeatRestart = true;
162 }
163 if (triggerHeartbeatRestart) {
164 this.chargingStation.restartHeartbeat();
165 }
166 if (keyToChange.key === OCPP16StandardParametersKey.WebSocketPingInterval && valueChanged) {
167 this.chargingStation.restartWebSocketPing();
168 }
169 if (keyToChange.reboot) {
170 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
171 }
172 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
173 }
174 }
175
176 private handleRequestSetChargingProfile(commandPayload: SetChargingProfileRequest): SetChargingProfileResponse {
177 if (!this.chargingStation.getConnector(commandPayload.connectorId)) {
a4cc42ea 178 logger.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
c0560973
JB
179 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
180 }
181 if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.CHARGE_POINT_MAX_PROFILE && commandPayload.connectorId !== 0) {
182 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
183 }
184 if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE && (commandPayload.connectorId === 0 || !this.chargingStation.getConnector(commandPayload.connectorId)?.transactionStarted)) {
185 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
186 }
187 this.chargingStation.setChargingProfile(commandPayload.connectorId, commandPayload.csChargingProfiles);
a4cc42ea 188 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
c0560973
JB
189 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED;
190 }
191
192 private handleRequestClearChargingProfile(commandPayload: ClearChargingProfileRequest): ClearChargingProfileResponse {
193 if (!this.chargingStation.getConnector(commandPayload.connectorId)) {
a4cc42ea 194 logger.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
c0560973
JB
195 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
196 }
197 if (commandPayload.connectorId && !Utils.isEmptyArray(this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles)) {
198 this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles = [];
a4cc42ea 199 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
c0560973
JB
200 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
201 }
202 if (!commandPayload.connectorId) {
203 let clearedCP = false;
204 for (const connector in this.chargingStation.connectors) {
205 if (!Utils.isEmptyArray(this.chargingStation.getConnector(Utils.convertToInt(connector)).chargingProfiles)) {
6e0964c8 206 this.chargingStation.getConnector(Utils.convertToInt(connector)).chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
c0560973
JB
207 let clearCurrentCP = false;
208 if (chargingProfile.chargingProfileId === commandPayload.id) {
209 clearCurrentCP = true;
210 }
211 if (!commandPayload.chargingProfilePurpose && chargingProfile.stackLevel === commandPayload.stackLevel) {
212 clearCurrentCP = true;
213 }
214 if (!chargingProfile.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
215 clearCurrentCP = true;
216 }
217 if (chargingProfile.stackLevel === commandPayload.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
218 clearCurrentCP = true;
219 }
220 if (clearCurrentCP) {
221 this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles[index] = {} as OCPP16ChargingProfile;
a4cc42ea 222 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
c0560973
JB
223 clearedCP = true;
224 }
225 });
226 }
227 }
228 if (clearedCP) {
229 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
230 }
231 }
232 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
233 }
234
e268356b 235 private async handleRequestChangeAvailability(commandPayload: ChangeAvailabilityRequest): Promise<ChangeAvailabilityResponse> {
c0560973
JB
236 const connectorId: number = commandPayload.connectorId;
237 if (!this.chargingStation.getConnector(connectorId)) {
238 logger.error(`${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
239 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
240 }
241 const chargePointStatus: OCPP16ChargePointStatus = commandPayload.type === OCPP16AvailabilityType.OPERATIVE ? OCPP16ChargePointStatus.AVAILABLE : OCPP16ChargePointStatus.UNAVAILABLE;
242 if (connectorId === 0) {
243 let response: ChangeAvailabilityResponse = Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
244 for (const connector in this.chargingStation.connectors) {
85d20667 245 if (this.chargingStation.getConnector(Utils.convertToInt(connector))?.transactionStarted) {
c0560973
JB
246 response = Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
247 }
248 this.chargingStation.getConnector(Utils.convertToInt(connector)).availability = commandPayload.type;
249 if (response === Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED) {
e268356b 250 await this.chargingStation.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), chargePointStatus);
c0560973
JB
251 this.chargingStation.getConnector(Utils.convertToInt(connector)).status = chargePointStatus;
252 }
253 }
254 return response;
255 } else if (connectorId > 0 && (this.chargingStation.getConnector(0).availability === OCPP16AvailabilityType.OPERATIVE || (this.chargingStation.getConnector(0).availability === OCPP16AvailabilityType.INOPERATIVE && commandPayload.type === OCPP16AvailabilityType.INOPERATIVE))) {
256 if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
257 this.chargingStation.getConnector(connectorId).availability = commandPayload.type;
258 return Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
259 }
260 this.chargingStation.getConnector(connectorId).availability = commandPayload.type;
e268356b 261 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, chargePointStatus);
c0560973
JB
262 this.chargingStation.getConnector(connectorId).status = chargePointStatus;
263 return Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
264 }
265 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
266 }
267
268 private async handleRequestRemoteStartTransaction(commandPayload: RemoteStartTransactionRequest): Promise<DefaultResponse> {
a7fc8211
JB
269 const transactionConnectorId: number = commandPayload.connectorId;
270 if (transactionConnectorId) {
271 await this.chargingStation.ocppRequestService.sendStatusNotification(transactionConnectorId, OCPP16ChargePointStatus.PREPARING);
272 this.chargingStation.getConnector(transactionConnectorId).status = OCPP16ChargePointStatus.PREPARING;
273 if (this.chargingStation.isChargingStationAvailable() && this.chargingStation.isConnectorAvailable(transactionConnectorId)) {
e060fe58 274 // Check if authorized
a7fc8211
JB
275 if (this.chargingStation.getAuthorizeRemoteTxRequests()) {
276 let authorized = false;
a7fc8211
JB
277 if (this.chargingStation.getLocalAuthListEnabled() && this.chargingStation.hasAuthorizedTags()
278 && this.chargingStation.authorizedTags.find((value) => value === commandPayload.idTag)) {
36f6a92e
JB
279 authorized = true;
280 }
a7fc8211
JB
281 if (!authorized || (authorized && this.chargingStation.getMayAuthorizeAtRemoteStart())) {
282 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(transactionConnectorId, commandPayload.idTag);
283 if (authorizeResponse?.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
284 authorized = true;
285 } else {
286 authorized = false;
287 }
288 }
289 if (authorized) {
290 // Authorization successful, start transaction
e060fe58
JB
291 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId, commandPayload.chargingProfile)) {
292 if ((await this.chargingStation.ocppRequestService.sendStartTransaction(transactionConnectorId, commandPayload.idTag)).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
293 logger.debug(this.chargingStation.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation.stationInfo.chargingStationId + '#' + transactionConnectorId.toString() + ' for idTag ' + commandPayload.idTag);
294 return Constants.OCPP_RESPONSE_ACCEPTED;
295 }
57939a9d 296 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
e060fe58 297 }
57939a9d 298 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
a7fc8211 299 }
57939a9d 300 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
36f6a92e 301 }
a7fc8211 302 // No authorization check required, start transaction
e060fe58
JB
303 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId, commandPayload.chargingProfile)) {
304 if ((await this.chargingStation.ocppRequestService.sendStartTransaction(transactionConnectorId, commandPayload.idTag)).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
305 logger.debug(this.chargingStation.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation.stationInfo.chargingStationId + '#' + transactionConnectorId.toString() + ' for idTag ' + commandPayload.idTag);
306 return Constants.OCPP_RESPONSE_ACCEPTED;
307 }
57939a9d 308 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
e060fe58 309 }
57939a9d 310 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
c0560973 311 }
57939a9d 312 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
c0560973 313 }
57939a9d 314 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
a7fc8211
JB
315 }
316
317 private async notifyRemoteStartTransactionRejected(connectorId: number, idTag: string): Promise<DefaultResponse> {
e060fe58
JB
318 if (this.chargingStation.getConnector(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE) {
319 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.AVAILABLE);
320 this.chargingStation.getConnector(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
321 }
322 logger.warn(this.chargingStation.logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + connectorId.toString() + ', idTag ' + idTag + ', availability ' + this.chargingStation.getConnector(connectorId).availability + ', status ' + this.chargingStation.getConnector(connectorId).status);
c0560973
JB
323 return Constants.OCPP_RESPONSE_REJECTED;
324 }
325
e060fe58 326 private setRemoteStartTransactionChargingProfile(connectorId: number, cp: OCPP16ChargingProfile): boolean {
a7fc8211
JB
327 if (cp && cp.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE) {
328 this.chargingStation.setChargingProfile(connectorId, cp);
329 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation.getConnector(connectorId).chargingProfiles);
330 return true;
331 } else if (cp && cp.chargingProfilePurpose !== ChargingProfilePurposeType.TX_PROFILE) {
a7fc8211
JB
332 logger.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${cp.chargingProfilePurpose} charging profile(s) at remote start transaction`);
333 return false;
e060fe58
JB
334 } else if (!cp) {
335 return true;
a7fc8211
JB
336 }
337 }
338
c0560973
JB
339 private async handleRequestRemoteStopTransaction(commandPayload: RemoteStopTransactionRequest): Promise<DefaultResponse> {
340 const transactionId = commandPayload.transactionId;
341 for (const connector in this.chargingStation.connectors) {
342 if (Utils.convertToInt(connector) > 0 && this.chargingStation.getConnector(Utils.convertToInt(connector))?.transactionId === transactionId) {
343 await this.chargingStation.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), OCPP16ChargePointStatus.FINISHING);
344 this.chargingStation.getConnector(Utils.convertToInt(connector)).status = OCPP16ChargePointStatus.FINISHING;
6ed92bc1 345 await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId, this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
035742f7 346 this.chargingStation.getTransactionIdTag(transactionId));
c0560973
JB
347 return Constants.OCPP_RESPONSE_ACCEPTED;
348 }
349 }
350 logger.info(this.chargingStation.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString());
351 return Constants.OCPP_RESPONSE_REJECTED;
352 }
47e22477
JB
353
354 private async handleRequestGetDiagnostics(commandPayload: GetDiagnosticsRequest): Promise<GetDiagnosticsResponse> {
355 logger.debug(this.chargingStation.logPrefix() + ' ' + IncomingRequestCommand.GET_DIAGNOSTICS + ' request received: %j', commandPayload);
a3868ec4 356 const uri = new URL(commandPayload.location);
47e22477
JB
357 if (uri.protocol.startsWith('ftp:')) {
358 let ftpClient: Client;
359 try {
360 const logFiles = fs.readdirSync(path.resolve(__dirname, '../../../../')).filter((file) => file.endsWith('.log')).map((file) => path.join('./', file));
361 const diagnosticsArchive = this.chargingStation.stationInfo.chargingStationId + '_logs.tar.gz';
362 tar.create({ gzip: true }, logFiles).pipe(fs.createWriteStream(diagnosticsArchive));
363 ftpClient = new Client();
364 const accessResponse = await ftpClient.access({
365 host: uri.host,
366 ...(uri.port !== '') && { port: Utils.convertToInt(uri.port) },
367 ...(uri.username !== '') && { user: uri.username },
368 ...(uri.password !== '') && { password: uri.password },
369 });
370 let uploadResponse: FTPResponse;
371 if (accessResponse.code === 220) {
372 // eslint-disable-next-line @typescript-eslint/no-misused-promises
373 ftpClient.trackProgress(async (info) => {
374 logger.info(`${this.chargingStation.logPrefix()} ${info.bytes / 1024} bytes transferred from diagnostics archive ${info.name}`);
375 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.Uploading);
376 });
377 uploadResponse = await ftpClient.uploadFrom(path.join(path.resolve(__dirname, '../../../../'), diagnosticsArchive), uri.pathname + diagnosticsArchive);
378 if (uploadResponse.code === 226) {
379 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.Uploaded);
380 if (ftpClient) {
381 ftpClient.close();
382 }
383 return { fileName: diagnosticsArchive };
384 }
a6b3c6c3 385 throw new OCPPError(ErrorType.GENERIC_ERROR, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, IncomingRequestCommand.GET_DIAGNOSTICS);
47e22477 386 }
a6b3c6c3 387 throw new OCPPError(ErrorType.GENERIC_ERROR, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, IncomingRequestCommand.GET_DIAGNOSTICS);
47e22477
JB
388 } catch (error) {
389 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.UploadFailed);
47e22477
JB
390 if (ftpClient) {
391 ftpClient.close();
392 }
e64c0923 393 return this.handleIncomingRequestError(IncomingRequestCommand.GET_DIAGNOSTICS, error, Constants.OCPP_RESPONSE_EMPTY);
47e22477
JB
394 }
395 } else {
396 logger.error(`${this.chargingStation.logPrefix()} Unsupported protocol ${uri.protocol} to transfer the diagnostic logs archive`);
397 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.UploadFailed);
398 return Constants.OCPP_RESPONSE_EMPTY;
399 }
400 }
802cfa13
JB
401
402 private handleRequestTriggerMessage(commandPayload: OCPP16TriggerMessageRequest): OCPP16TriggerMessageResponse {
403 try {
404 switch (commandPayload.requestedMessage) {
405 case MessageTrigger.BootNotification:
406 setTimeout(() => {
407 this.chargingStation.ocppRequestService.sendBootNotification(this.chargingStation.getBootNotificationRequest().chargePointModel,
408 this.chargingStation.getBootNotificationRequest().chargePointVendor, this.chargingStation.getBootNotificationRequest().chargeBoxSerialNumber,
0dad4bda 409 this.chargingStation.getBootNotificationRequest().firmwareVersion).catch(() => { /* This is intentional */ });
802cfa13
JB
410 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
411 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
412 case MessageTrigger.Heartbeat:
413 setTimeout(() => {
0dad4bda 414 this.chargingStation.ocppRequestService.sendHeartbeat().catch(() => { /* This is intentional */ });
802cfa13
JB
415 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
416 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
417 default:
418 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED;
419 }
420 } catch (error) {
d4bc21e0 421 return this.handleIncomingRequestError(IncomingRequestCommand.TRIGGER_MESSAGE, error, Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED);
802cfa13
JB
422 }
423 }
c0560973 424}