1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 import path from
'path';
5 import { URL
, fileURLToPath
} from
'url';
7 import type { JSONSchemaType
} from
'ajv';
8 import { Client
, FTPResponse
} from
'basic-ftp';
11 import OCPPError from
'../../../exception/OCPPError';
12 import type { JsonObject
, JsonType
} from
'../../../types/JsonType';
13 import { OCPP16ChargePointErrorCode
} from
'../../../types/ocpp/1.6/ChargePointErrorCode';
14 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
16 ChargingProfilePurposeType
,
17 OCPP16ChargingProfile
,
18 } from
'../../../types/ocpp/1.6/ChargingProfile';
20 OCPP16StandardParametersKey
,
21 OCPP16SupportedFeatureProfiles
,
22 } from
'../../../types/ocpp/1.6/Configuration';
23 import { OCPP16DiagnosticsStatus
} from
'../../../types/ocpp/1.6/DiagnosticsStatus';
25 ChangeAvailabilityRequest
,
26 ChangeConfigurationRequest
,
27 ClearChargingProfileRequest
,
28 DiagnosticsStatusNotificationRequest
,
29 GetConfigurationRequest
,
30 GetDiagnosticsRequest
,
31 OCPP16AvailabilityType
,
32 OCPP16BootNotificationRequest
,
33 OCPP16ClearCacheRequest
,
34 OCPP16DataTransferRequest
,
35 OCPP16DataTransferVendorId
,
36 OCPP16HeartbeatRequest
,
37 OCPP16IncomingRequestCommand
,
40 OCPP16StatusNotificationRequest
,
41 OCPP16TriggerMessageRequest
,
42 RemoteStartTransactionRequest
,
43 RemoteStopTransactionRequest
,
45 SetChargingProfileRequest
,
46 UnlockConnectorRequest
,
47 } from
'../../../types/ocpp/1.6/Requests';
49 ChangeAvailabilityResponse
,
50 ChangeConfigurationResponse
,
51 ClearChargingProfileResponse
,
52 DiagnosticsStatusNotificationResponse
,
53 GetConfigurationResponse
,
54 GetDiagnosticsResponse
,
55 OCPP16BootNotificationResponse
,
56 OCPP16DataTransferResponse
,
57 OCPP16DataTransferStatus
,
58 OCPP16HeartbeatResponse
,
59 OCPP16StatusNotificationResponse
,
60 OCPP16TriggerMessageResponse
,
61 SetChargingProfileResponse
,
62 UnlockConnectorResponse
,
63 } from
'../../../types/ocpp/1.6/Responses';
65 OCPP16AuthorizationStatus
,
66 OCPP16AuthorizeRequest
,
67 OCPP16AuthorizeResponse
,
68 OCPP16StartTransactionRequest
,
69 OCPP16StartTransactionResponse
,
70 OCPP16StopTransactionReason
,
71 } from
'../../../types/ocpp/1.6/Transaction';
72 import type { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
73 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
74 import type { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
75 import type { DefaultResponse
} from
'../../../types/ocpp/Responses';
76 import Constants from
'../../../utils/Constants';
77 import logger from
'../../../utils/Logger';
78 import Utils from
'../../../utils/Utils';
79 import type ChargingStation from
'../../ChargingStation';
80 import { ChargingStationConfigurationUtils
} from
'../../ChargingStationConfigurationUtils';
81 import { ChargingStationUtils
} from
'../../ChargingStationUtils';
82 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
83 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
85 const moduleName
= 'OCPP16IncomingRequestService';
87 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
88 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
89 private jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
91 public constructor() {
92 if (new.target
?.name
=== moduleName
) {
93 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
96 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
97 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
98 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
99 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
101 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
102 this.handleRequestGetConfiguration
.bind(this),
105 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
106 this.handleRequestChangeConfiguration
.bind(this),
109 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
110 this.handleRequestSetChargingProfile
.bind(this),
113 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
114 this.handleRequestClearChargingProfile
.bind(this),
117 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
118 this.handleRequestChangeAvailability
.bind(this),
121 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
122 this.handleRequestRemoteStartTransaction
.bind(this),
125 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
126 this.handleRequestRemoteStopTransaction
.bind(this),
128 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
129 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
130 [OCPP16IncomingRequestCommand
.DATA_TRANSFER
, this.handleRequestDataTransfer
.bind(this)],
132 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
134 OCPP16IncomingRequestCommand
.RESET
,
138 path
.dirname(fileURLToPath(import.meta
.url
)),
139 '../../../assets/json-schemas/ocpp/1.6/Reset.json'
143 ) as JSONSchemaType
<ResetRequest
>,
146 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
150 path
.dirname(fileURLToPath(import.meta
.url
)),
151 '../../../assets/json-schemas/ocpp/1.6/ClearCache.json'
155 ) as JSONSchemaType
<OCPP16ClearCacheRequest
>,
158 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
162 path
.dirname(fileURLToPath(import.meta
.url
)),
163 '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json'
167 ) as JSONSchemaType
<UnlockConnectorRequest
>,
170 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
174 path
.dirname(fileURLToPath(import.meta
.url
)),
175 '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json'
179 ) as JSONSchemaType
<GetConfigurationRequest
>,
182 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
186 path
.dirname(fileURLToPath(import.meta
.url
)),
187 '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json'
191 ) as JSONSchemaType
<ChangeConfigurationRequest
>,
194 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
198 path
.dirname(fileURLToPath(import.meta
.url
)),
199 '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json'
203 ) as JSONSchemaType
<GetDiagnosticsRequest
>,
206 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
210 path
.dirname(fileURLToPath(import.meta
.url
)),
211 '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json'
215 ) as JSONSchemaType
<SetChargingProfileRequest
>,
218 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
222 path
.dirname(fileURLToPath(import.meta
.url
)),
223 '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json'
227 ) as JSONSchemaType
<ClearChargingProfileRequest
>,
230 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
234 path
.dirname(fileURLToPath(import.meta
.url
)),
235 '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json'
239 ) as JSONSchemaType
<ChangeAvailabilityRequest
>,
242 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
246 path
.dirname(fileURLToPath(import.meta
.url
)),
247 '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json'
251 ) as JSONSchemaType
<RemoteStartTransactionRequest
>,
254 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
258 path
.dirname(fileURLToPath(import.meta
.url
)),
259 '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json'
263 ) as JSONSchemaType
<RemoteStopTransactionRequest
>,
266 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
270 path
.dirname(fileURLToPath(import.meta
.url
)),
271 '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json'
275 ) as JSONSchemaType
<OCPP16TriggerMessageRequest
>,
278 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
282 path
.dirname(fileURLToPath(import.meta
.url
)),
283 '../../../assets/json-schemas/ocpp/1.6/DataTransfer.json'
287 ) as JSONSchemaType
<OCPP16DataTransferRequest
>,
290 this.validatePayload
.bind(this);
293 public async incomingRequestHandler(
294 chargingStation
: ChargingStation
,
296 commandName
: OCPP16IncomingRequestCommand
,
297 commandPayload
: JsonType
299 let response
: JsonType
;
301 chargingStation
.getOcppStrictCompliance() === true &&
302 chargingStation
.isInPendingState() === true &&
303 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
304 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
307 ErrorType
.SECURITY_ERROR
,
308 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
312 )} while the charging station is in pending state on the central server`,
318 chargingStation
.isRegistered() === true ||
319 (chargingStation
.getOcppStrictCompliance() === false &&
320 chargingStation
.isInUnknownState() === true)
323 this.incomingRequestHandlers
.has(commandName
) === true &&
324 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
327 this.validatePayload(chargingStation
, commandName
, commandPayload
);
328 // Call the method to build the response
329 response
= await this.incomingRequestHandlers
.get(commandName
)(
336 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
344 ErrorType
.NOT_IMPLEMENTED
,
345 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
356 ErrorType
.SECURITY_ERROR
,
357 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
361 )} while the charging station is not registered on the central server.`,
366 // Send the built response
367 await chargingStation
.ocppRequestService
.sendResponse(
375 private validatePayload(
376 chargingStation
: ChargingStation
,
377 commandName
: OCPP16IncomingRequestCommand
,
378 commandPayload
: JsonType
380 if (this.jsonSchemas
.has(commandName
)) {
381 return this.validateIncomingRequestPayload(
384 this.jsonSchemas
.get(commandName
),
389 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
394 // Simulate charging station restart
395 private handleRequestReset(
396 chargingStation
: ChargingStation
,
397 commandPayload
: ResetRequest
401 chargingStation
.reset
.bind(chargingStation
) as (
402 this: ChargingStation
,
406 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
409 /* This is intentional */
412 `${chargingStation.logPrefix()} ${
414 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
415 chargingStation.stationInfo.resetTime
418 return Constants
.OCPP_RESPONSE_ACCEPTED
;
421 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
422 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
423 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
425 return Constants
.OCPP_RESPONSE_ACCEPTED
;
428 private async handleRequestUnlockConnector(
429 chargingStation
: ChargingStation
,
430 commandPayload
: UnlockConnectorRequest
431 ): Promise
<UnlockConnectorResponse
> {
432 const connectorId
= commandPayload
.connectorId
;
433 if (chargingStation
.connectors
.has(connectorId
) === false) {
435 `${chargingStation.logPrefix()} Trying to unlock a non existing connector Id ${connectorId.toString()}`
437 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
439 if (connectorId
=== 0) {
441 chargingStation
.logPrefix() + ' Trying to unlock connector Id ' + connectorId
.toString()
443 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
445 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
446 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
448 OCPP16StopTransactionReason
.UNLOCK_COMMAND
450 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
451 return Constants
.OCPP_RESPONSE_UNLOCKED
;
453 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
455 await chargingStation
.ocppRequestService
.requestHandler
<
456 OCPP16StatusNotificationRequest
,
457 OCPP16StatusNotificationResponse
458 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
460 status: OCPP16ChargePointStatus
.AVAILABLE
,
461 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
463 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
464 return Constants
.OCPP_RESPONSE_UNLOCKED
;
467 private handleRequestGetConfiguration(
468 chargingStation
: ChargingStation
,
469 commandPayload
: GetConfigurationRequest
470 ): GetConfigurationResponse
{
471 const configurationKey
: OCPPConfigurationKey
[] = [];
472 const unknownKey
: string[] = [];
473 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
474 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
475 if (Utils
.isUndefined(configuration
.visible
) === true) {
476 configuration
.visible
= true;
478 if (configuration
.visible
=== false) {
481 configurationKey
.push({
482 key
: configuration
.key
,
483 readonly: configuration
.readonly,
484 value
: configuration
.value
,
488 for (const key
of commandPayload
.key
) {
489 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
494 if (Utils
.isUndefined(keyFound
.visible
) === true) {
495 keyFound
.visible
= true;
497 if (keyFound
.visible
=== false) {
500 configurationKey
.push({
502 readonly: keyFound
.readonly,
503 value
: keyFound
.value
,
506 unknownKey
.push(key
);
516 private handleRequestChangeConfiguration(
517 chargingStation
: ChargingStation
,
518 commandPayload
: ChangeConfigurationRequest
519 ): ChangeConfigurationResponse
{
520 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
526 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
527 } else if (keyToChange
&& keyToChange
.readonly) {
528 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
529 } else if (keyToChange
&& !keyToChange
.readonly) {
530 let valueChanged
= false;
531 if (keyToChange
.value
!== commandPayload
.value
) {
532 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
535 commandPayload
.value
,
540 let triggerHeartbeatRestart
= false;
541 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
542 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
544 OCPP16StandardParametersKey
.HeartbeatInterval
,
547 triggerHeartbeatRestart
= true;
549 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
550 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
552 OCPP16StandardParametersKey
.HeartBeatInterval
,
555 triggerHeartbeatRestart
= true;
557 if (triggerHeartbeatRestart
) {
558 chargingStation
.restartHeartbeat();
560 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
561 chargingStation
.restartWebSocketPing();
563 if (keyToChange
.reboot
) {
564 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
566 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
570 private handleRequestSetChargingProfile(
571 chargingStation
: ChargingStation
,
572 commandPayload
: SetChargingProfileRequest
573 ): SetChargingProfileResponse
{
575 OCPP16ServiceUtils
.checkFeatureProfile(
577 OCPP16SupportedFeatureProfiles
.SmartCharging
,
578 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
581 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
583 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
585 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
586 commandPayload.connectorId
589 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
592 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
593 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
594 commandPayload
.connectorId
!== 0
596 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
599 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
600 ChargingProfilePurposeType
.TX_PROFILE
&&
601 (commandPayload
.connectorId
=== 0 ||
602 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
606 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
607 commandPayload.connectorId
608 } without a started transaction`
610 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
612 OCPP16ServiceUtils
.setChargingProfile(
614 commandPayload
.connectorId
,
615 commandPayload
.csChargingProfiles
618 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
619 commandPayload.connectorId
620 }, dump their stack: %j`,
621 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
623 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
626 private handleRequestClearChargingProfile(
627 chargingStation
: ChargingStation
,
628 commandPayload
: ClearChargingProfileRequest
629 ): ClearChargingProfileResponse
{
631 OCPP16ServiceUtils
.checkFeatureProfile(
633 OCPP16SupportedFeatureProfiles
.SmartCharging
,
634 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
637 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
639 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
641 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
642 commandPayload.connectorId
645 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
647 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
648 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
649 connectorStatus
.chargingProfiles
= [];
651 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
652 commandPayload.connectorId
653 }, dump their stack: %j`,
654 connectorStatus
.chargingProfiles
656 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
658 if (!commandPayload
.connectorId
) {
659 let clearedCP
= false;
660 for (const connectorId
of chargingStation
.connectors
.keys()) {
661 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
663 .getConnectorStatus(connectorId
)
664 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
665 let clearCurrentCP
= false;
666 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
667 clearCurrentCP
= true;
670 !commandPayload
.chargingProfilePurpose
&&
671 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
673 clearCurrentCP
= true;
676 !chargingProfile
.stackLevel
&&
677 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
679 clearCurrentCP
= true;
682 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
683 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
685 clearCurrentCP
= true;
687 if (clearCurrentCP
) {
688 connectorStatus
.chargingProfiles
.splice(index
, 1);
690 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
691 commandPayload.connectorId
692 }, dump their stack: %j`,
693 connectorStatus
.chargingProfiles
701 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
704 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
707 private async handleRequestChangeAvailability(
708 chargingStation
: ChargingStation
,
709 commandPayload
: ChangeAvailabilityRequest
710 ): Promise
<ChangeAvailabilityResponse
> {
711 const connectorId
: number = commandPayload
.connectorId
;
712 if (chargingStation
.connectors
.has(connectorId
) === false) {
714 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
716 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
718 const chargePointStatus
: OCPP16ChargePointStatus
=
719 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
720 ? OCPP16ChargePointStatus
.AVAILABLE
721 : OCPP16ChargePointStatus
.UNAVAILABLE
;
722 if (connectorId
=== 0) {
723 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
724 for (const id
of chargingStation
.connectors
.keys()) {
725 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
726 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
728 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
729 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
730 await chargingStation
.ocppRequestService
.requestHandler
<
731 OCPP16StatusNotificationRequest
,
732 OCPP16StatusNotificationResponse
733 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
735 status: chargePointStatus
,
736 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
738 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
744 (chargingStation
.isChargingStationAvailable() === true ||
745 (chargingStation
.isChargingStationAvailable() === false &&
746 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
748 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
749 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
750 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
752 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
753 await chargingStation
.ocppRequestService
.requestHandler
<
754 OCPP16StatusNotificationRequest
,
755 OCPP16StatusNotificationResponse
756 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
758 status: chargePointStatus
,
759 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
761 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
762 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
764 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
767 private async handleRequestRemoteStartTransaction(
768 chargingStation
: ChargingStation
,
769 commandPayload
: RemoteStartTransactionRequest
770 ): Promise
<DefaultResponse
> {
771 const transactionConnectorId
= commandPayload
.connectorId
;
772 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
773 const remoteStartTransactionLogMsg
=
774 chargingStation
.logPrefix() +
775 ' Transaction remotely STARTED on ' +
776 chargingStation
.stationInfo
.chargingStationId
+
778 transactionConnectorId
.toString() +
780 commandPayload
.idTag
+
782 await chargingStation
.ocppRequestService
.requestHandler
<
783 OCPP16StatusNotificationRequest
,
784 OCPP16StatusNotificationResponse
785 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
786 connectorId
: transactionConnectorId
,
787 status: OCPP16ChargePointStatus
.PREPARING
,
788 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
790 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
791 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
792 if (chargingStation
.isChargingStationAvailable() === true) {
793 // Check if authorized
794 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
795 let authorized
= false;
797 chargingStation
.getLocalAuthListEnabled() === true &&
798 chargingStation
.hasAuthorizedTags() === true &&
799 chargingStation
.authorizedTagsCache
801 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
803 .find((idTag
) => idTag
=== commandPayload
.idTag
)
805 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
806 connectorStatus
.idTagLocalAuthorized
= true;
808 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
809 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
810 const authorizeResponse
: OCPP16AuthorizeResponse
=
811 await chargingStation
.ocppRequestService
.requestHandler
<
812 OCPP16AuthorizeRequest
,
813 OCPP16AuthorizeResponse
814 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
815 idTag
: commandPayload
.idTag
,
817 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
822 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
825 if (authorized
=== true) {
826 // Authorization successful, start transaction
828 this.setRemoteStartTransactionChargingProfile(
830 transactionConnectorId
,
831 commandPayload
.chargingProfile
834 connectorStatus
.transactionRemoteStarted
= true;
837 await chargingStation
.ocppRequestService
.requestHandler
<
838 OCPP16StartTransactionRequest
,
839 OCPP16StartTransactionResponse
840 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
841 connectorId
: transactionConnectorId
,
842 idTag
: commandPayload
.idTag
,
844 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
846 logger
.debug(remoteStartTransactionLogMsg
);
847 return Constants
.OCPP_RESPONSE_ACCEPTED
;
849 return this.notifyRemoteStartTransactionRejected(
851 transactionConnectorId
,
855 return this.notifyRemoteStartTransactionRejected(
857 transactionConnectorId
,
861 return this.notifyRemoteStartTransactionRejected(
863 transactionConnectorId
,
867 // No authorization check required, start transaction
869 this.setRemoteStartTransactionChargingProfile(
871 transactionConnectorId
,
872 commandPayload
.chargingProfile
875 connectorStatus
.transactionRemoteStarted
= true;
878 await chargingStation
.ocppRequestService
.requestHandler
<
879 OCPP16StartTransactionRequest
,
880 OCPP16StartTransactionResponse
881 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
882 connectorId
: transactionConnectorId
,
883 idTag
: commandPayload
.idTag
,
885 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
887 logger
.debug(remoteStartTransactionLogMsg
);
888 return Constants
.OCPP_RESPONSE_ACCEPTED
;
890 return this.notifyRemoteStartTransactionRejected(
892 transactionConnectorId
,
896 return this.notifyRemoteStartTransactionRejected(
898 transactionConnectorId
,
902 return this.notifyRemoteStartTransactionRejected(
904 transactionConnectorId
,
908 return this.notifyRemoteStartTransactionRejected(
910 transactionConnectorId
,
915 private async notifyRemoteStartTransactionRejected(
916 chargingStation
: ChargingStation
,
919 ): Promise
<DefaultResponse
> {
921 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
923 await chargingStation
.ocppRequestService
.requestHandler
<
924 OCPP16StatusNotificationRequest
,
925 OCPP16StatusNotificationResponse
926 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
928 status: OCPP16ChargePointStatus
.AVAILABLE
,
929 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
931 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
934 chargingStation
.logPrefix() +
935 ' Remote starting transaction REJECTED on connector Id ' +
936 connectorId
.toString() +
939 "', availability '" +
940 chargingStation
.getConnectorStatus(connectorId
).availability
+
942 chargingStation
.getConnectorStatus(connectorId
).status +
945 return Constants
.OCPP_RESPONSE_REJECTED
;
948 private setRemoteStartTransactionChargingProfile(
949 chargingStation
: ChargingStation
,
951 cp
: OCPP16ChargingProfile
953 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
954 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
956 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
957 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
960 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
962 `${chargingStation.logPrefix()} Not allowed to set ${
963 cp.chargingProfilePurpose
964 } charging profile(s) at remote start transaction`
972 private async handleRequestRemoteStopTransaction(
973 chargingStation
: ChargingStation
,
974 commandPayload
: RemoteStopTransactionRequest
975 ): Promise
<DefaultResponse
> {
976 const transactionId
= commandPayload
.transactionId
;
977 for (const connectorId
of chargingStation
.connectors
.keys()) {
980 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
982 await chargingStation
.ocppRequestService
.requestHandler
<
983 OCPP16StatusNotificationRequest
,
984 OCPP16StatusNotificationResponse
985 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
987 status: OCPP16ChargePointStatus
.FINISHING
,
988 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
990 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
991 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
993 OCPP16StopTransactionReason
.REMOTE
995 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
996 return Constants
.OCPP_RESPONSE_ACCEPTED
;
998 return Constants
.OCPP_RESPONSE_REJECTED
;
1002 chargingStation
.logPrefix() +
1003 ' Trying to remote stop a non existing transaction ' +
1004 transactionId
.toString()
1006 return Constants
.OCPP_RESPONSE_REJECTED
;
1009 private async handleRequestGetDiagnostics(
1010 chargingStation
: ChargingStation
,
1011 commandPayload
: GetDiagnosticsRequest
1012 ): Promise
<GetDiagnosticsResponse
> {
1014 OCPP16ServiceUtils
.checkFeatureProfile(
1016 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1017 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1020 return Constants
.OCPP_RESPONSE_EMPTY
;
1023 chargingStation
.logPrefix() +
1025 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1026 ' request received: %j',
1029 const uri
= new URL(commandPayload
.location
);
1030 if (uri
.protocol
.startsWith('ftp:')) {
1031 let ftpClient
: Client
;
1034 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1035 .filter((file
) => file
.endsWith('.log'))
1036 .map((file
) => path
.join('./', file
));
1037 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1038 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1039 ftpClient
= new Client();
1040 const accessResponse
= await ftpClient
.access({
1042 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1043 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1044 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1046 let uploadResponse
: FTPResponse
;
1047 if (accessResponse
.code
=== 220) {
1048 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1049 ftpClient
.trackProgress(async (info
) => {
1051 `${chargingStation.logPrefix()} ${
1053 } bytes transferred from diagnostics archive ${info.name}`
1055 await chargingStation
.ocppRequestService
.requestHandler
<
1056 DiagnosticsStatusNotificationRequest
,
1057 DiagnosticsStatusNotificationResponse
1058 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1059 status: OCPP16DiagnosticsStatus
.Uploading
,
1062 uploadResponse
= await ftpClient
.uploadFrom(
1064 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1067 uri
.pathname
+ diagnosticsArchive
1069 if (uploadResponse
.code
=== 226) {
1070 await chargingStation
.ocppRequestService
.requestHandler
<
1071 DiagnosticsStatusNotificationRequest
,
1072 DiagnosticsStatusNotificationResponse
1073 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1074 status: OCPP16DiagnosticsStatus
.Uploaded
,
1079 return { fileName
: diagnosticsArchive
};
1081 throw new OCPPError(
1082 ErrorType
.GENERIC_ERROR
,
1083 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1084 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1086 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1089 throw new OCPPError(
1090 ErrorType
.GENERIC_ERROR
,
1091 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1092 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1094 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1097 await chargingStation
.ocppRequestService
.requestHandler
<
1098 DiagnosticsStatusNotificationRequest
,
1099 DiagnosticsStatusNotificationResponse
1100 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1101 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1106 return this.handleIncomingRequestError(
1108 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1110 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1115 `${chargingStation.logPrefix()} Unsupported protocol ${
1117 } to transfer the diagnostic logs archive`
1119 await chargingStation
.ocppRequestService
.requestHandler
<
1120 DiagnosticsStatusNotificationRequest
,
1121 DiagnosticsStatusNotificationResponse
1122 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1123 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1125 return Constants
.OCPP_RESPONSE_EMPTY
;
1129 private handleRequestTriggerMessage(
1130 chargingStation
: ChargingStation
,
1131 commandPayload
: OCPP16TriggerMessageRequest
1132 ): OCPP16TriggerMessageResponse
{
1134 !OCPP16ServiceUtils
.checkFeatureProfile(
1136 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1137 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1139 !OCPP16ServiceUtils
.isMessageTriggerSupported(
1141 commandPayload
.requestedMessage
1144 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1147 !OCPP16ServiceUtils
.isConnectorIdValid(
1149 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1150 commandPayload
.connectorId
1153 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1156 switch (commandPayload
.requestedMessage
) {
1157 case OCPP16MessageTrigger
.BootNotification
:
1159 chargingStation
.ocppRequestService
1160 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1162 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1163 chargingStation
.bootNotificationRequest
,
1164 { skipBufferingOnError
: true, triggerMessage
: true }
1166 .then((response
) => {
1167 chargingStation
.bootNotificationResponse
= response
;
1170 /* This is intentional */
1172 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1173 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1174 case OCPP16MessageTrigger
.Heartbeat
:
1176 chargingStation
.ocppRequestService
1177 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1179 OCPP16RequestCommand
.HEARTBEAT
,
1182 triggerMessage
: true,
1186 /* This is intentional */
1188 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1189 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1190 case OCPP16MessageTrigger
.StatusNotification
:
1192 if (commandPayload
?.connectorId
) {
1193 chargingStation
.ocppRequestService
1194 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1196 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1198 connectorId
: commandPayload
.connectorId
,
1199 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1200 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1203 triggerMessage
: true,
1207 /* This is intentional */
1210 for (const connectorId
of chargingStation
.connectors
.keys()) {
1211 chargingStation
.ocppRequestService
1213 OCPP16StatusNotificationRequest
,
1214 OCPP16StatusNotificationResponse
1217 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1220 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1221 status: chargingStation
.getConnectorStatus(connectorId
).status,
1224 triggerMessage
: true,
1228 /* This is intentional */
1232 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1233 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1235 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1238 return this.handleIncomingRequestError(
1240 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1242 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}
1247 private handleRequestDataTransfer(
1248 chargingStation
: ChargingStation
,
1249 commandPayload
: OCPP16DataTransferRequest
1250 ): OCPP16DataTransferResponse
{
1252 if (Object.values(OCPP16DataTransferVendorId
).includes(commandPayload
.vendorId
)) {
1254 status: OCPP16DataTransferStatus
.ACCEPTED
,
1258 status: OCPP16DataTransferStatus
.UNKNOWN_VENDOR_ID
,
1261 return this.handleIncomingRequestError(
1263 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1265 { errorResponse
: Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}