0e5918db515068f4dee02a9a1e98f952b6de11f1
[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 {
4 ChangeAvailabilityRequest,
5 ChangeConfigurationRequest,
6 ClearChargingProfileRequest,
7 GetConfigurationRequest,
8 GetDiagnosticsRequest,
9 MessageTrigger,
10 OCPP16AvailabilityType,
11 OCPP16IncomingRequestCommand,
12 OCPP16TriggerMessageRequest,
13 RemoteStartTransactionRequest,
14 RemoteStopTransactionRequest,
15 ResetRequest,
16 SetChargingProfileRequest,
17 UnlockConnectorRequest,
18 } from '../../../types/ocpp/1.6/Requests';
19 import {
20 ChangeAvailabilityResponse,
21 ChangeConfigurationResponse,
22 ClearChargingProfileResponse,
23 GetConfigurationResponse,
24 GetDiagnosticsResponse,
25 OCPP16TriggerMessageResponse,
26 SetChargingProfileResponse,
27 UnlockConnectorResponse,
28 } from '../../../types/ocpp/1.6/Responses';
29 import {
30 ChargingProfilePurposeType,
31 OCPP16ChargingProfile,
32 } from '../../../types/ocpp/1.6/ChargingProfile';
33 import { Client, FTPResponse } from 'basic-ftp';
34 import {
35 OCPP16AuthorizationStatus,
36 OCPP16StopTransactionReason,
37 } from '../../../types/ocpp/1.6/Transaction';
38
39 import type ChargingStation from '../../ChargingStation';
40 import Constants from '../../../utils/Constants';
41 import { DefaultResponse } from '../../../types/ocpp/Responses';
42 import { ErrorType } from '../../../types/ocpp/ErrorType';
43 import { IncomingRequestHandler } from '../../../types/ocpp/Requests';
44 import { JsonType } from '../../../types/JsonType';
45 import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
46 import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus';
47 import { OCPP16StandardParametersKey } from '../../../types/ocpp/1.6/Configuration';
48 import { OCPPConfigurationKey } from '../../../types/ocpp/Configuration';
49 import OCPPError from '../../../exception/OCPPError';
50 import OCPPIncomingRequestService from '../OCPPIncomingRequestService';
51 import { URL } from 'url';
52 import Utils from '../../../utils/Utils';
53 import fs from 'fs';
54 import logger from '../../../utils/Logger';
55 import path from 'path';
56 import tar from 'tar';
57
58 const moduleName = 'OCPP16IncomingRequestService';
59
60 export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
61 private incomingRequestHandlers: Map<OCPP16IncomingRequestCommand, IncomingRequestHandler>;
62
63 public constructor(chargingStation: ChargingStation) {
64 if (new.target?.name === moduleName) {
65 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
66 }
67 super(chargingStation);
68 this.incomingRequestHandlers = new Map<OCPP16IncomingRequestCommand, IncomingRequestHandler>([
69 [OCPP16IncomingRequestCommand.RESET, this.handleRequestReset.bind(this)],
70 [OCPP16IncomingRequestCommand.CLEAR_CACHE, this.handleRequestClearCache.bind(this)],
71 [OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR, this.handleRequestUnlockConnector.bind(this)],
72 [
73 OCPP16IncomingRequestCommand.GET_CONFIGURATION,
74 this.handleRequestGetConfiguration.bind(this),
75 ],
76 [
77 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION,
78 this.handleRequestChangeConfiguration.bind(this),
79 ],
80 [
81 OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE,
82 this.handleRequestSetChargingProfile.bind(this),
83 ],
84 [
85 OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE,
86 this.handleRequestClearChargingProfile.bind(this),
87 ],
88 [
89 OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY,
90 this.handleRequestChangeAvailability.bind(this),
91 ],
92 [
93 OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION,
94 this.handleRequestRemoteStartTransaction.bind(this),
95 ],
96 [
97 OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION,
98 this.handleRequestRemoteStopTransaction.bind(this),
99 ],
100 [OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, this.handleRequestGetDiagnostics.bind(this)],
101 [OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, this.handleRequestTriggerMessage.bind(this)],
102 ]);
103 }
104
105 public async handleRequest(
106 messageId: string,
107 commandName: OCPP16IncomingRequestCommand,
108 commandPayload: JsonType
109 ): Promise<void> {
110 let result: JsonType;
111 if (
112 this.chargingStation.getOcppStrictCompliance() &&
113 this.chargingStation.isInPendingState() &&
114 (commandName === OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION ||
115 commandName === OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION)
116 ) {
117 throw new OCPPError(
118 ErrorType.SECURITY_ERROR,
119 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
120 commandPayload,
121 null,
122 2
123 )} while the charging station is in pending state on the central server`,
124 commandName
125 );
126 }
127 if (
128 this.chargingStation.isRegistered() ||
129 (!this.chargingStation.getOcppStrictCompliance() && this.chargingStation.isInUnknownState())
130 ) {
131 if (this.incomingRequestHandlers.has(commandName)) {
132 try {
133 // Call the method to build the result
134 result = await this.incomingRequestHandlers.get(commandName)(commandPayload);
135 } catch (error) {
136 // Log
137 logger.error(this.chargingStation.logPrefix() + ' Handle request error: %j', error);
138 throw error;
139 }
140 } else {
141 // Throw exception
142 throw new OCPPError(
143 ErrorType.NOT_IMPLEMENTED,
144 `${commandName} is not implemented to handle request payload ${JSON.stringify(
145 commandPayload,
146 null,
147 2
148 )}`,
149 commandName
150 );
151 }
152 } else {
153 throw new OCPPError(
154 ErrorType.SECURITY_ERROR,
155 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
156 commandPayload,
157 null,
158 2
159 )} while the charging station is not registered on the central server.`,
160 commandName
161 );
162 }
163 // Send the built result
164 await this.chargingStation.ocppRequestService.sendResult(messageId, result, commandName);
165 }
166
167 // Simulate charging station restart
168 private handleRequestReset(commandPayload: ResetRequest): DefaultResponse {
169 // eslint-disable-next-line @typescript-eslint/no-misused-promises
170 setImmediate(async (): Promise<void> => {
171 await this.chargingStation.stop(
172 (commandPayload.type + 'Reset') as OCPP16StopTransactionReason
173 );
174 await Utils.sleep(this.chargingStation.stationInfo.resetTime);
175 this.chargingStation.start();
176 });
177 logger.info(
178 `${this.chargingStation.logPrefix()} ${
179 commandPayload.type
180 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
181 this.chargingStation.stationInfo.resetTime
182 )}`
183 );
184 return Constants.OCPP_RESPONSE_ACCEPTED;
185 }
186
187 private handleRequestClearCache(): DefaultResponse {
188 return Constants.OCPP_RESPONSE_ACCEPTED;
189 }
190
191 private async handleRequestUnlockConnector(
192 commandPayload: UnlockConnectorRequest
193 ): Promise<UnlockConnectorResponse> {
194 const connectorId = commandPayload.connectorId;
195 if (connectorId === 0) {
196 logger.error(
197 this.chargingStation.logPrefix() + ' Trying to unlock connector ' + connectorId.toString()
198 );
199 return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
200 }
201 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
202 const transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
203 const stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(
204 transactionId,
205 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
206 this.chargingStation.getTransactionIdTag(transactionId),
207 OCPP16StopTransactionReason.UNLOCK_COMMAND
208 );
209 if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
210 return Constants.OCPP_RESPONSE_UNLOCKED;
211 }
212 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
213 }
214 await this.chargingStation.ocppRequestService.sendStatusNotification(
215 connectorId,
216 OCPP16ChargePointStatus.AVAILABLE
217 );
218 this.chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
219 return Constants.OCPP_RESPONSE_UNLOCKED;
220 }
221
222 private handleRequestGetConfiguration(
223 commandPayload: GetConfigurationRequest
224 ): GetConfigurationResponse {
225 const configurationKey: OCPPConfigurationKey[] = [];
226 const unknownKey: string[] = [];
227 if (Utils.isEmptyArray(commandPayload.key)) {
228 for (const configuration of this.chargingStation.configuration.configurationKey) {
229 if (Utils.isUndefined(configuration.visible)) {
230 configuration.visible = true;
231 }
232 if (!configuration.visible) {
233 continue;
234 }
235 configurationKey.push({
236 key: configuration.key,
237 readonly: configuration.readonly,
238 value: configuration.value,
239 });
240 }
241 } else {
242 for (const key of commandPayload.key) {
243 const keyFound = this.chargingStation.getConfigurationKey(key);
244 if (keyFound) {
245 if (Utils.isUndefined(keyFound.visible)) {
246 keyFound.visible = true;
247 }
248 if (!keyFound.visible) {
249 continue;
250 }
251 configurationKey.push({
252 key: keyFound.key,
253 readonly: keyFound.readonly,
254 value: keyFound.value,
255 });
256 } else {
257 unknownKey.push(key);
258 }
259 }
260 }
261 return {
262 configurationKey,
263 unknownKey,
264 };
265 }
266
267 private handleRequestChangeConfiguration(
268 commandPayload: ChangeConfigurationRequest
269 ): ChangeConfigurationResponse {
270 // JSON request fields type sanity check
271 if (!Utils.isString(commandPayload.key)) {
272 logger.error(
273 `${this.chargingStation.logPrefix()} ${
274 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
275 } request key field is not a string:`,
276 commandPayload
277 );
278 }
279 if (!Utils.isString(commandPayload.value)) {
280 logger.error(
281 `${this.chargingStation.logPrefix()} ${
282 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
283 } request value field is not a string:`,
284 commandPayload
285 );
286 }
287 const keyToChange = this.chargingStation.getConfigurationKey(commandPayload.key, true);
288 if (!keyToChange) {
289 return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED;
290 } else if (keyToChange && keyToChange.readonly) {
291 return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED;
292 } else if (keyToChange && !keyToChange.readonly) {
293 const keyIndex = this.chargingStation.configuration.configurationKey.indexOf(keyToChange);
294 let valueChanged = false;
295 if (
296 this.chargingStation.configuration.configurationKey[keyIndex].value !== commandPayload.value
297 ) {
298 this.chargingStation.configuration.configurationKey[keyIndex].value = commandPayload.value;
299 valueChanged = true;
300 }
301 let triggerHeartbeatRestart = false;
302 if (keyToChange.key === OCPP16StandardParametersKey.HeartBeatInterval && valueChanged) {
303 this.chargingStation.setConfigurationKeyValue(
304 OCPP16StandardParametersKey.HeartbeatInterval,
305 commandPayload.value
306 );
307 triggerHeartbeatRestart = true;
308 }
309 if (keyToChange.key === OCPP16StandardParametersKey.HeartbeatInterval && valueChanged) {
310 this.chargingStation.setConfigurationKeyValue(
311 OCPP16StandardParametersKey.HeartBeatInterval,
312 commandPayload.value
313 );
314 triggerHeartbeatRestart = true;
315 }
316 if (triggerHeartbeatRestart) {
317 this.chargingStation.restartHeartbeat();
318 }
319 if (keyToChange.key === OCPP16StandardParametersKey.WebSocketPingInterval && valueChanged) {
320 this.chargingStation.restartWebSocketPing();
321 }
322 if (keyToChange.reboot) {
323 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
324 }
325 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
326 }
327 }
328
329 private handleRequestSetChargingProfile(
330 commandPayload: SetChargingProfileRequest
331 ): SetChargingProfileResponse {
332 if (!this.chargingStation.getConnectorStatus(commandPayload.connectorId)) {
333 logger.error(
334 `${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
335 commandPayload.connectorId
336 }`
337 );
338 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
339 }
340 if (
341 commandPayload.csChargingProfiles.chargingProfilePurpose ===
342 ChargingProfilePurposeType.CHARGE_POINT_MAX_PROFILE &&
343 commandPayload.connectorId !== 0
344 ) {
345 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
346 }
347 if (
348 commandPayload.csChargingProfiles.chargingProfilePurpose ===
349 ChargingProfilePurposeType.TX_PROFILE &&
350 (commandPayload.connectorId === 0 ||
351 !this.chargingStation.getConnectorStatus(commandPayload.connectorId)?.transactionStarted)
352 ) {
353 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
354 }
355 this.chargingStation.setChargingProfile(
356 commandPayload.connectorId,
357 commandPayload.csChargingProfiles
358 );
359 logger.debug(
360 `${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`,
361 this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles
362 );
363 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED;
364 }
365
366 private handleRequestClearChargingProfile(
367 commandPayload: ClearChargingProfileRequest
368 ): ClearChargingProfileResponse {
369 if (!this.chargingStation.getConnectorStatus(commandPayload.connectorId)) {
370 logger.error(
371 `${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
372 commandPayload.connectorId
373 }`
374 );
375 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
376 }
377 if (
378 commandPayload.connectorId &&
379 !Utils.isEmptyArray(
380 this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles
381 )
382 ) {
383 this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles = [];
384 logger.debug(
385 `${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`,
386 this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles
387 );
388 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
389 }
390 if (!commandPayload.connectorId) {
391 let clearedCP = false;
392 for (const connectorId of this.chargingStation.connectors.keys()) {
393 if (
394 !Utils.isEmptyArray(this.chargingStation.getConnectorStatus(connectorId).chargingProfiles)
395 ) {
396 this.chargingStation
397 .getConnectorStatus(connectorId)
398 .chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
399 let clearCurrentCP = false;
400 if (chargingProfile.chargingProfileId === commandPayload.id) {
401 clearCurrentCP = true;
402 }
403 if (
404 !commandPayload.chargingProfilePurpose &&
405 chargingProfile.stackLevel === commandPayload.stackLevel
406 ) {
407 clearCurrentCP = true;
408 }
409 if (
410 !chargingProfile.stackLevel &&
411 chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose
412 ) {
413 clearCurrentCP = true;
414 }
415 if (
416 chargingProfile.stackLevel === commandPayload.stackLevel &&
417 chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose
418 ) {
419 clearCurrentCP = true;
420 }
421 if (clearCurrentCP) {
422 this.chargingStation.getConnectorStatus(
423 commandPayload.connectorId
424 ).chargingProfiles[index] = {} as OCPP16ChargingProfile;
425 logger.debug(
426 `${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`,
427 this.chargingStation.getConnectorStatus(commandPayload.connectorId)
428 .chargingProfiles
429 );
430 clearedCP = true;
431 }
432 });
433 }
434 }
435 if (clearedCP) {
436 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
437 }
438 }
439 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
440 }
441
442 private async handleRequestChangeAvailability(
443 commandPayload: ChangeAvailabilityRequest
444 ): Promise<ChangeAvailabilityResponse> {
445 const connectorId: number = commandPayload.connectorId;
446 if (!this.chargingStation.getConnectorStatus(connectorId)) {
447 logger.error(
448 `${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
449 );
450 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
451 }
452 const chargePointStatus: OCPP16ChargePointStatus =
453 commandPayload.type === OCPP16AvailabilityType.OPERATIVE
454 ? OCPP16ChargePointStatus.AVAILABLE
455 : OCPP16ChargePointStatus.UNAVAILABLE;
456 if (connectorId === 0) {
457 let response: ChangeAvailabilityResponse = Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
458 for (const id of this.chargingStation.connectors.keys()) {
459 if (this.chargingStation.getConnectorStatus(id)?.transactionStarted) {
460 response = Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
461 }
462 this.chargingStation.getConnectorStatus(id).availability = commandPayload.type;
463 if (response === Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED) {
464 await this.chargingStation.ocppRequestService.sendStatusNotification(
465 id,
466 chargePointStatus
467 );
468 this.chargingStation.getConnectorStatus(id).status = chargePointStatus;
469 }
470 }
471 return response;
472 } else if (
473 connectorId > 0 &&
474 (this.chargingStation.getConnectorStatus(0).availability ===
475 OCPP16AvailabilityType.OPERATIVE ||
476 (this.chargingStation.getConnectorStatus(0).availability ===
477 OCPP16AvailabilityType.INOPERATIVE &&
478 commandPayload.type === OCPP16AvailabilityType.INOPERATIVE))
479 ) {
480 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
481 this.chargingStation.getConnectorStatus(connectorId).availability = commandPayload.type;
482 return Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
483 }
484 this.chargingStation.getConnectorStatus(connectorId).availability = commandPayload.type;
485 await this.chargingStation.ocppRequestService.sendStatusNotification(
486 connectorId,
487 chargePointStatus
488 );
489 this.chargingStation.getConnectorStatus(connectorId).status = chargePointStatus;
490 return Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
491 }
492 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
493 }
494
495 private async handleRequestRemoteStartTransaction(
496 commandPayload: RemoteStartTransactionRequest
497 ): Promise<DefaultResponse> {
498 const transactionConnectorId: number = commandPayload.connectorId;
499 if (transactionConnectorId) {
500 await this.chargingStation.ocppRequestService.sendStatusNotification(
501 transactionConnectorId,
502 OCPP16ChargePointStatus.PREPARING
503 );
504 this.chargingStation.getConnectorStatus(transactionConnectorId).status =
505 OCPP16ChargePointStatus.PREPARING;
506 if (
507 this.chargingStation.isChargingStationAvailable() &&
508 this.chargingStation.isConnectorAvailable(transactionConnectorId)
509 ) {
510 // Check if authorized
511 if (this.chargingStation.getAuthorizeRemoteTxRequests()) {
512 let authorized = false;
513 if (
514 this.chargingStation.getLocalAuthListEnabled() &&
515 this.chargingStation.hasAuthorizedTags() &&
516 this.chargingStation.authorizedTags.find((value) => value === commandPayload.idTag)
517 ) {
518 this.chargingStation.getConnectorStatus(transactionConnectorId).localAuthorizeIdTag =
519 commandPayload.idTag;
520 this.chargingStation.getConnectorStatus(transactionConnectorId).idTagLocalAuthorized =
521 true;
522 authorized = true;
523 } else if (this.chargingStation.getMayAuthorizeAtRemoteStart()) {
524 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(
525 transactionConnectorId,
526 commandPayload.idTag
527 );
528 if (authorizeResponse?.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
529 authorized = true;
530 }
531 } else {
532 logger.warn(
533 `${this.chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
534 );
535 }
536 if (authorized) {
537 // Authorization successful, start transaction
538 if (
539 this.setRemoteStartTransactionChargingProfile(
540 transactionConnectorId,
541 commandPayload.chargingProfile
542 )
543 ) {
544 this.chargingStation.getConnectorStatus(
545 transactionConnectorId
546 ).transactionRemoteStarted = true;
547 if (
548 (
549 await this.chargingStation.ocppRequestService.sendStartTransaction(
550 transactionConnectorId,
551 commandPayload.idTag
552 )
553 ).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED
554 ) {
555 logger.debug(
556 this.chargingStation.logPrefix() +
557 ' Transaction remotely STARTED on ' +
558 this.chargingStation.stationInfo.chargingStationId +
559 '#' +
560 transactionConnectorId.toString() +
561 ' for idTag ' +
562 commandPayload.idTag
563 );
564 return Constants.OCPP_RESPONSE_ACCEPTED;
565 }
566 return this.notifyRemoteStartTransactionRejected(
567 transactionConnectorId,
568 commandPayload.idTag
569 );
570 }
571 return this.notifyRemoteStartTransactionRejected(
572 transactionConnectorId,
573 commandPayload.idTag
574 );
575 }
576 return this.notifyRemoteStartTransactionRejected(
577 transactionConnectorId,
578 commandPayload.idTag
579 );
580 }
581 // No authorization check required, start transaction
582 if (
583 this.setRemoteStartTransactionChargingProfile(
584 transactionConnectorId,
585 commandPayload.chargingProfile
586 )
587 ) {
588 this.chargingStation.getConnectorStatus(transactionConnectorId).transactionRemoteStarted =
589 true;
590 if (
591 (
592 await this.chargingStation.ocppRequestService.sendStartTransaction(
593 transactionConnectorId,
594 commandPayload.idTag
595 )
596 ).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED
597 ) {
598 logger.debug(
599 this.chargingStation.logPrefix() +
600 ' Transaction remotely STARTED on ' +
601 this.chargingStation.stationInfo.chargingStationId +
602 '#' +
603 transactionConnectorId.toString() +
604 ' for idTag ' +
605 commandPayload.idTag
606 );
607 return Constants.OCPP_RESPONSE_ACCEPTED;
608 }
609 return this.notifyRemoteStartTransactionRejected(
610 transactionConnectorId,
611 commandPayload.idTag
612 );
613 }
614 return this.notifyRemoteStartTransactionRejected(
615 transactionConnectorId,
616 commandPayload.idTag
617 );
618 }
619 return this.notifyRemoteStartTransactionRejected(
620 transactionConnectorId,
621 commandPayload.idTag
622 );
623 }
624 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
625 }
626
627 private async notifyRemoteStartTransactionRejected(
628 connectorId: number,
629 idTag: string
630 ): Promise<DefaultResponse> {
631 if (
632 this.chargingStation.getConnectorStatus(connectorId).status !==
633 OCPP16ChargePointStatus.AVAILABLE
634 ) {
635 await this.chargingStation.ocppRequestService.sendStatusNotification(
636 connectorId,
637 OCPP16ChargePointStatus.AVAILABLE
638 );
639 this.chargingStation.getConnectorStatus(connectorId).status =
640 OCPP16ChargePointStatus.AVAILABLE;
641 }
642 logger.warn(
643 this.chargingStation.logPrefix() +
644 ' Remote starting transaction REJECTED on connector Id ' +
645 connectorId.toString() +
646 ', idTag ' +
647 idTag +
648 ', availability ' +
649 this.chargingStation.getConnectorStatus(connectorId).availability +
650 ', status ' +
651 this.chargingStation.getConnectorStatus(connectorId).status
652 );
653 return Constants.OCPP_RESPONSE_REJECTED;
654 }
655
656 private setRemoteStartTransactionChargingProfile(
657 connectorId: number,
658 cp: OCPP16ChargingProfile
659 ): boolean {
660 if (cp && cp.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE) {
661 this.chargingStation.setChargingProfile(connectorId, cp);
662 logger.debug(
663 `${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`,
664 this.chargingStation.getConnectorStatus(connectorId).chargingProfiles
665 );
666 return true;
667 } else if (cp && cp.chargingProfilePurpose !== ChargingProfilePurposeType.TX_PROFILE) {
668 logger.warn(
669 `${this.chargingStation.logPrefix()} Not allowed to set ${
670 cp.chargingProfilePurpose
671 } charging profile(s) at remote start transaction`
672 );
673 return false;
674 } else if (!cp) {
675 return true;
676 }
677 }
678
679 private async handleRequestRemoteStopTransaction(
680 commandPayload: RemoteStopTransactionRequest
681 ): Promise<DefaultResponse> {
682 const transactionId = commandPayload.transactionId;
683 for (const connectorId of this.chargingStation.connectors.keys()) {
684 if (
685 connectorId > 0 &&
686 this.chargingStation.getConnectorStatus(connectorId)?.transactionId === transactionId
687 ) {
688 await this.chargingStation.ocppRequestService.sendStatusNotification(
689 connectorId,
690 OCPP16ChargePointStatus.FINISHING
691 );
692 this.chargingStation.getConnectorStatus(connectorId).status =
693 OCPP16ChargePointStatus.FINISHING;
694 await this.chargingStation.ocppRequestService.sendStopTransaction(
695 transactionId,
696 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
697 this.chargingStation.getTransactionIdTag(transactionId)
698 );
699 return Constants.OCPP_RESPONSE_ACCEPTED;
700 }
701 }
702 logger.info(
703 this.chargingStation.logPrefix() +
704 ' Trying to remote stop a non existing transaction ' +
705 transactionId.toString()
706 );
707 return Constants.OCPP_RESPONSE_REJECTED;
708 }
709
710 private async handleRequestGetDiagnostics(
711 commandPayload: GetDiagnosticsRequest
712 ): Promise<GetDiagnosticsResponse> {
713 logger.debug(
714 this.chargingStation.logPrefix() +
715 ' ' +
716 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS +
717 ' request received: %j',
718 commandPayload
719 );
720 const uri = new URL(commandPayload.location);
721 if (uri.protocol.startsWith('ftp:')) {
722 let ftpClient: Client;
723 try {
724 const logFiles = fs
725 .readdirSync(path.resolve(__dirname, '../../../../'))
726 .filter((file) => file.endsWith('.log'))
727 .map((file) => path.join('./', file));
728 const diagnosticsArchive =
729 this.chargingStation.stationInfo.chargingStationId + '_logs.tar.gz';
730 tar.create({ gzip: true }, logFiles).pipe(fs.createWriteStream(diagnosticsArchive));
731 ftpClient = new Client();
732 const accessResponse = await ftpClient.access({
733 host: uri.host,
734 ...(!Utils.isEmptyString(uri.port) && { port: Utils.convertToInt(uri.port) }),
735 ...(!Utils.isEmptyString(uri.username) && { user: uri.username }),
736 ...(!Utils.isEmptyString(uri.password) && { password: uri.password }),
737 });
738 let uploadResponse: FTPResponse;
739 if (accessResponse.code === 220) {
740 // eslint-disable-next-line @typescript-eslint/no-misused-promises
741 ftpClient.trackProgress(async (info) => {
742 logger.info(
743 `${this.chargingStation.logPrefix()} ${
744 info.bytes / 1024
745 } bytes transferred from diagnostics archive ${info.name}`
746 );
747 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(
748 OCPP16DiagnosticsStatus.Uploading
749 );
750 });
751 uploadResponse = await ftpClient.uploadFrom(
752 path.join(path.resolve(__dirname, '../../../../'), diagnosticsArchive),
753 uri.pathname + diagnosticsArchive
754 );
755 if (uploadResponse.code === 226) {
756 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(
757 OCPP16DiagnosticsStatus.Uploaded
758 );
759 if (ftpClient) {
760 ftpClient.close();
761 }
762 return { fileName: diagnosticsArchive };
763 }
764 throw new OCPPError(
765 ErrorType.GENERIC_ERROR,
766 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
767 uploadResponse?.code && '|' + uploadResponse?.code.toString()
768 }`,
769 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS
770 );
771 }
772 throw new OCPPError(
773 ErrorType.GENERIC_ERROR,
774 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
775 uploadResponse?.code && '|' + uploadResponse?.code.toString()
776 }`,
777 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS
778 );
779 } catch (error) {
780 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(
781 OCPP16DiagnosticsStatus.UploadFailed
782 );
783 if (ftpClient) {
784 ftpClient.close();
785 }
786 return this.handleIncomingRequestError(
787 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
788 error as Error,
789 { errorResponse: Constants.OCPP_RESPONSE_EMPTY }
790 );
791 }
792 } else {
793 logger.error(
794 `${this.chargingStation.logPrefix()} Unsupported protocol ${
795 uri.protocol
796 } to transfer the diagnostic logs archive`
797 );
798 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(
799 OCPP16DiagnosticsStatus.UploadFailed
800 );
801 return Constants.OCPP_RESPONSE_EMPTY;
802 }
803 }
804
805 private handleRequestTriggerMessage(
806 commandPayload: OCPP16TriggerMessageRequest
807 ): OCPP16TriggerMessageResponse {
808 try {
809 switch (commandPayload.requestedMessage) {
810 case MessageTrigger.BootNotification:
811 setTimeout(() => {
812 this.chargingStation.ocppRequestService
813 .sendBootNotification(
814 this.chargingStation.getBootNotificationRequest().chargePointModel,
815 this.chargingStation.getBootNotificationRequest().chargePointVendor,
816 this.chargingStation.getBootNotificationRequest().chargeBoxSerialNumber,
817 this.chargingStation.getBootNotificationRequest().firmwareVersion,
818 this.chargingStation.getBootNotificationRequest().chargePointSerialNumber,
819 this.chargingStation.getBootNotificationRequest().iccid,
820 this.chargingStation.getBootNotificationRequest().imsi,
821 this.chargingStation.getBootNotificationRequest().meterSerialNumber,
822 this.chargingStation.getBootNotificationRequest().meterType,
823 { triggerMessage: true }
824 )
825 .catch(() => {
826 /* This is intentional */
827 });
828 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
829 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
830 case MessageTrigger.Heartbeat:
831 setTimeout(() => {
832 this.chargingStation.ocppRequestService
833 .sendHeartbeat({ triggerMessage: true })
834 .catch(() => {
835 /* This is intentional */
836 });
837 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
838 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
839 default:
840 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED;
841 }
842 } catch (error) {
843 return this.handleIncomingRequestError(
844 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
845 error as Error,
846 { errorResponse: Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED }
847 );
848 }
849 }
850 }