930c4b81dfde1b0ba038dfc8dcc729ee72cb6735
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16IncomingRequestService.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { ChangeAvailabilityRequest, ChangeConfigurationRequest, ClearChargingProfileRequest, GetConfigurationRequest, GetDiagnosticsRequest, MessageTrigger, OCPP16AvailabilityType, OCPP16IncomingRequestCommand, OCPP16TriggerMessageRequest, RemoteStartTransactionRequest, RemoteStopTransactionRequest, ResetRequest, SetChargingProfileRequest, UnlockConnectorRequest } from '../../../types/ocpp/1.6/Requests';
4 import { ChangeAvailabilityResponse, ChangeConfigurationResponse, ClearChargingProfileResponse, GetConfigurationResponse, GetDiagnosticsResponse, OCPP16TriggerMessageResponse, SetChargingProfileResponse, UnlockConnectorResponse } from '../../../types/ocpp/1.6/Responses';
5 import { ChargingProfilePurposeType, OCPP16ChargingProfile } from '../../../types/ocpp/1.6/ChargingProfile';
6 import { Client, FTPResponse } from 'basic-ftp';
7 import { IncomingRequestCommand, RequestCommand } from '../../../types/ocpp/Requests';
8 import { OCPP16AuthorizationStatus, OCPP16StopTransactionReason } from '../../../types/ocpp/1.6/Transaction';
9
10 import Constants from '../../../utils/Constants';
11 import { DefaultResponse } from '../../../types/ocpp/Responses';
12 import { ErrorType } from '../../../types/ocpp/ErrorType';
13 import { MessageType } from '../../../types/ocpp/MessageType';
14 import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
15 import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus';
16 import { OCPP16StandardParametersKey } from '../../../types/ocpp/1.6/Configuration';
17 import { OCPPConfigurationKey } from '../../../types/ocpp/Configuration';
18 import OCPPError from '../OCPPError';
19 import OCPPIncomingRequestService from '../OCPPIncomingRequestService';
20 import { URL } from 'url';
21 import Utils from '../../../utils/Utils';
22 import fs from 'fs';
23 import logger from '../../../utils/Logger';
24 import path from 'path';
25 import tar from 'tar';
26
27 export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
28 public async handleRequest(messageId: string, commandName: OCPP16IncomingRequestCommand, commandPayload: Record<string, unknown>): Promise<void> {
29 let response;
30 const methodName = `handleRequest${commandName}`;
31 // Call
32 if (typeof this[methodName] === 'function') {
33 try {
34 // Call the method to build the response
35 response = await this[methodName](commandPayload);
36 } catch (error) {
37 // Log
38 logger.error(this.chargingStation.logPrefix() + ' Handle request error: %j', error);
39 // Send back an error response to inform backend
40 await this.chargingStation.ocppRequestService.sendError(messageId, error, commandName);
41 throw error;
42 }
43 } else {
44 // Throw exception
45 const error = new OCPPError(ErrorType.NOT_IMPLEMENTED, `${commandName} is not implemented to handle payload ${JSON.stringify(commandPayload, null, 2)}`, commandName);
46 await this.chargingStation.ocppRequestService.sendError(messageId, error, commandName);
47 throw error;
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 {
55 // eslint-disable-next-line @typescript-eslint/no-misused-promises
56 setImmediate(async (): Promise<void> => {
57 await this.chargingStation.stop(commandPayload.type + 'Reset' as OCPP16StopTransactionReason);
58 await Utils.sleep(this.chargingStation.stationInfo.resetTime);
59 this.chargingStation.start();
60 });
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)}`);
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;
77 const stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
78 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
79 this.chargingStation.getTransactionIdTag(transactionId),
80 OCPP16StopTransactionReason.UNLOCK_COMMAND);
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)) {
137 logger.error(`${this.chargingStation.logPrefix()} ${RequestCommand.CHANGE_CONFIGURATION} request key field is not a string:`, commandPayload);
138 }
139 if (!Utils.isString(commandPayload.value)) {
140 logger.error(`${this.chargingStation.logPrefix()} ${RequestCommand.CHANGE_CONFIGURATION} request value field is not a string:`, commandPayload);
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)) {
178 logger.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
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);
188 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
189 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED;
190 }
191
192 private handleRequestClearChargingProfile(commandPayload: ClearChargingProfileRequest): ClearChargingProfileResponse {
193 if (!this.chargingStation.getConnector(commandPayload.connectorId)) {
194 logger.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
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 = [];
199 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
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)) {
206 this.chargingStation.getConnector(Utils.convertToInt(connector)).chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
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;
222 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
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
235 private async handleRequestChangeAvailability(commandPayload: ChangeAvailabilityRequest): Promise<ChangeAvailabilityResponse> {
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) {
245 if (this.chargingStation.getConnector(Utils.convertToInt(connector)).transactionStarted) {
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) {
250 await this.chargingStation.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), chargePointStatus);
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;
261 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, chargePointStatus);
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> {
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)) {
274 // Check if authorized
275 if (this.chargingStation.getAuthorizeRemoteTxRequests()) {
276 let authorized = false;
277 if (this.chargingStation.getLocalAuthListEnabled() && this.chargingStation.hasAuthorizedTags()
278 && this.chargingStation.authorizedTags.find((value) => value === commandPayload.idTag)) {
279 authorized = true;
280 }
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
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 }
296 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
297 }
298 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
299 }
300 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
301 }
302 // No authorization check required, start transaction
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 }
308 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
309 }
310 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
311 }
312 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
313 }
314 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
315 }
316
317 private async notifyRemoteStartTransactionRejected(connectorId: number, idTag: string): Promise<DefaultResponse> {
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);
323 return Constants.OCPP_RESPONSE_REJECTED;
324 }
325
326 private setRemoteStartTransactionChargingProfile(connectorId: number, cp: OCPP16ChargingProfile): boolean {
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) {
332 logger.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${cp.chargingProfilePurpose} charging profile(s) at remote start transaction`);
333 return false;
334 } else if (!cp) {
335 return true;
336 }
337 }
338
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;
345 await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId, this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
346 this.chargingStation.getTransactionIdTag(transactionId));
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 }
353
354 private async handleRequestGetDiagnostics(commandPayload: GetDiagnosticsRequest): Promise<GetDiagnosticsResponse> {
355 logger.debug(this.chargingStation.logPrefix() + ' ' + IncomingRequestCommand.GET_DIAGNOSTICS + ' request received: %j', commandPayload);
356 const uri = new URL(commandPayload.location);
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 }
385 throw new OCPPError(ErrorType.GENERIC_ERROR, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, IncomingRequestCommand.GET_DIAGNOSTICS);
386 }
387 throw new OCPPError(ErrorType.GENERIC_ERROR, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, IncomingRequestCommand.GET_DIAGNOSTICS);
388 } catch (error) {
389 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.UploadFailed);
390 if (ftpClient) {
391 ftpClient.close();
392 }
393 return this.handleIncomingRequestError(IncomingRequestCommand.GET_DIAGNOSTICS, error, Constants.OCPP_RESPONSE_EMPTY);
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 }
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,
409 this.chargingStation.getBootNotificationRequest().firmwareVersion).catch(() => { /* This is intentional */ });
410 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
411 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
412 case MessageTrigger.Heartbeat:
413 setTimeout(() => {
414 this.chargingStation.ocppRequestService.sendHeartbeat().catch(() => { /* This is intentional */ });
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) {
421 return this.handleIncomingRequestError(IncomingRequestCommand.TRIGGER_MESSAGE, error, Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED);
422 }
423 }
424 }