1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
4 import path from
'path';
5 import { URL
, fileURLToPath
} from
'url';
7 import type { JSONSchemaType
} from
'ajv';
8 import { Client
, type 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 type 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 type ChangeAvailabilityRequest
,
26 type ChangeConfigurationRequest
,
27 type ClearChargingProfileRequest
,
28 type DiagnosticsStatusNotificationRequest
,
29 type GetConfigurationRequest
,
30 type GetDiagnosticsRequest
,
31 OCPP16AvailabilityType
,
32 type OCPP16BootNotificationRequest
,
33 type OCPP16ClearCacheRequest
,
34 type OCPP16DataTransferRequest
,
35 OCPP16DataTransferVendorId
,
36 type OCPP16HeartbeatRequest
,
37 OCPP16IncomingRequestCommand
,
40 type OCPP16StatusNotificationRequest
,
41 type OCPP16TriggerMessageRequest
,
42 type OCPP16UpdateFirmwareRequest
,
43 type RemoteStartTransactionRequest
,
44 type RemoteStopTransactionRequest
,
46 type SetChargingProfileRequest
,
47 type UnlockConnectorRequest
,
48 } from
'../../../types/ocpp/1.6/Requests';
50 type ChangeAvailabilityResponse
,
51 type ChangeConfigurationResponse
,
52 type ClearChargingProfileResponse
,
53 type DiagnosticsStatusNotificationResponse
,
54 type GetConfigurationResponse
,
55 type GetDiagnosticsResponse
,
56 type OCPP16BootNotificationResponse
,
57 type OCPP16DataTransferResponse
,
58 OCPP16DataTransferStatus
,
59 type OCPP16HeartbeatResponse
,
60 type OCPP16StatusNotificationResponse
,
61 type OCPP16TriggerMessageResponse
,
62 type OCPP16UpdateFirmwareResponse
,
63 type SetChargingProfileResponse
,
64 type UnlockConnectorResponse
,
65 } from
'../../../types/ocpp/1.6/Responses';
67 OCPP16AuthorizationStatus
,
68 type OCPP16AuthorizeRequest
,
69 type OCPP16AuthorizeResponse
,
70 type OCPP16StartTransactionRequest
,
71 type OCPP16StartTransactionResponse
,
72 OCPP16StopTransactionReason
,
73 } from
'../../../types/ocpp/1.6/Transaction';
74 import type { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
75 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
76 import { OCPPVersion
} from
'../../../types/ocpp/OCPPVersion';
77 import type { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
78 import type { DefaultResponse
} from
'../../../types/ocpp/Responses';
79 import Constants from
'../../../utils/Constants';
80 import logger from
'../../../utils/Logger';
81 import Utils from
'../../../utils/Utils';
82 import type ChargingStation from
'../../ChargingStation';
83 import { ChargingStationConfigurationUtils
} from
'../../ChargingStationConfigurationUtils';
84 import { ChargingStationUtils
} from
'../../ChargingStationUtils';
85 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
86 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
88 const moduleName
= 'OCPP16IncomingRequestService';
90 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
91 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
92 private jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
94 public constructor() {
95 if (new.target
?.name
=== moduleName
) {
96 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
98 super(OCPPVersion
.VERSION_16
);
99 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
100 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
101 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
102 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
104 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
105 this.handleRequestGetConfiguration
.bind(this),
108 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
109 this.handleRequestChangeConfiguration
.bind(this),
112 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
113 this.handleRequestSetChargingProfile
.bind(this),
116 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
117 this.handleRequestClearChargingProfile
.bind(this),
120 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
121 this.handleRequestChangeAvailability
.bind(this),
124 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
125 this.handleRequestRemoteStartTransaction
.bind(this),
128 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
129 this.handleRequestRemoteStopTransaction
.bind(this),
131 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
132 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
133 [OCPP16IncomingRequestCommand
.DATA_TRANSFER
, this.handleRequestDataTransfer
.bind(this)],
134 // [OCPP16IncomingRequestCommand.UPDATE_FIRMWARE, this.handleRequestUpdateFirmware.bind(this)],
136 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
138 OCPP16IncomingRequestCommand
.RESET
,
142 path
.dirname(fileURLToPath(import.meta
.url
)),
143 '../../../assets/json-schemas/ocpp/1.6/Reset.json'
147 ) as JSONSchemaType
<ResetRequest
>,
150 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
154 path
.dirname(fileURLToPath(import.meta
.url
)),
155 '../../../assets/json-schemas/ocpp/1.6/ClearCache.json'
159 ) as JSONSchemaType
<OCPP16ClearCacheRequest
>,
162 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
166 path
.dirname(fileURLToPath(import.meta
.url
)),
167 '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json'
171 ) as JSONSchemaType
<UnlockConnectorRequest
>,
174 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
178 path
.dirname(fileURLToPath(import.meta
.url
)),
179 '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json'
183 ) as JSONSchemaType
<GetConfigurationRequest
>,
186 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
190 path
.dirname(fileURLToPath(import.meta
.url
)),
191 '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json'
195 ) as JSONSchemaType
<ChangeConfigurationRequest
>,
198 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
202 path
.dirname(fileURLToPath(import.meta
.url
)),
203 '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json'
207 ) as JSONSchemaType
<GetDiagnosticsRequest
>,
210 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
214 path
.dirname(fileURLToPath(import.meta
.url
)),
215 '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json'
219 ) as JSONSchemaType
<SetChargingProfileRequest
>,
222 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
226 path
.dirname(fileURLToPath(import.meta
.url
)),
227 '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json'
231 ) as JSONSchemaType
<ClearChargingProfileRequest
>,
234 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
238 path
.dirname(fileURLToPath(import.meta
.url
)),
239 '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json'
243 ) as JSONSchemaType
<ChangeAvailabilityRequest
>,
246 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
250 path
.dirname(fileURLToPath(import.meta
.url
)),
251 '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json'
255 ) as JSONSchemaType
<RemoteStartTransactionRequest
>,
258 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
262 path
.dirname(fileURLToPath(import.meta
.url
)),
263 '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json'
267 ) as JSONSchemaType
<RemoteStopTransactionRequest
>,
270 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
274 path
.dirname(fileURLToPath(import.meta
.url
)),
275 '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json'
279 ) as JSONSchemaType
<OCPP16TriggerMessageRequest
>,
282 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
286 path
.dirname(fileURLToPath(import.meta
.url
)),
287 '../../../assets/json-schemas/ocpp/1.6/DataTransfer.json'
291 ) as JSONSchemaType
<OCPP16DataTransferRequest
>,
294 this.validatePayload
.bind(this);
297 public async incomingRequestHandler(
298 chargingStation
: ChargingStation
,
300 commandName
: OCPP16IncomingRequestCommand
,
301 commandPayload
: JsonType
303 let response
: JsonType
;
305 chargingStation
.getOcppStrictCompliance() === true &&
306 chargingStation
.isInPendingState() === true &&
307 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
308 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
311 ErrorType
.SECURITY_ERROR
,
312 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
316 )} while the charging station is in pending state on the central server`,
322 chargingStation
.isRegistered() === true ||
323 (chargingStation
.getOcppStrictCompliance() === false &&
324 chargingStation
.isInUnknownState() === true)
327 this.incomingRequestHandlers
.has(commandName
) === true &&
328 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
331 this.validatePayload(chargingStation
, commandName
, commandPayload
);
332 // Call the method to build the response
333 response
= await this.incomingRequestHandlers
.get(commandName
)(
340 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
348 ErrorType
.NOT_IMPLEMENTED
,
349 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
360 ErrorType
.SECURITY_ERROR
,
361 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
365 )} while the charging station is not registered on the central server.`,
370 // Send the built response
371 await chargingStation
.ocppRequestService
.sendResponse(
379 private validatePayload(
380 chargingStation
: ChargingStation
,
381 commandName
: OCPP16IncomingRequestCommand
,
382 commandPayload
: JsonType
384 if (this.jsonSchemas
.has(commandName
)) {
385 return this.validateIncomingRequestPayload(
388 this.jsonSchemas
.get(commandName
),
393 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
398 // Simulate charging station restart
399 private handleRequestReset(
400 chargingStation
: ChargingStation
,
401 commandPayload
: ResetRequest
405 chargingStation
.reset
.bind(chargingStation
) as (
406 this: ChargingStation
,
410 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
413 /* This is intentional */
416 `${chargingStation.logPrefix()} ${
418 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
419 chargingStation.stationInfo.resetTime
422 return Constants
.OCPP_RESPONSE_ACCEPTED
;
425 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
426 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
427 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
429 return Constants
.OCPP_RESPONSE_ACCEPTED
;
432 private async handleRequestUnlockConnector(
433 chargingStation
: ChargingStation
,
434 commandPayload
: UnlockConnectorRequest
435 ): Promise
<UnlockConnectorResponse
> {
436 const connectorId
= commandPayload
.connectorId
;
437 if (chargingStation
.connectors
.has(connectorId
) === false) {
439 `${chargingStation.logPrefix()} Trying to unlock a non existing connector Id ${connectorId.toString()}`
441 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
443 if (connectorId
=== 0) {
445 chargingStation
.logPrefix() + ' Trying to unlock connector Id ' + connectorId
.toString()
447 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
449 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
450 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
452 OCPP16StopTransactionReason
.UNLOCK_COMMAND
454 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
455 return Constants
.OCPP_RESPONSE_UNLOCKED
;
457 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
459 await chargingStation
.ocppRequestService
.requestHandler
<
460 OCPP16StatusNotificationRequest
,
461 OCPP16StatusNotificationResponse
462 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
464 status: OCPP16ChargePointStatus
.AVAILABLE
,
465 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
467 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
468 return Constants
.OCPP_RESPONSE_UNLOCKED
;
471 private handleRequestGetConfiguration(
472 chargingStation
: ChargingStation
,
473 commandPayload
: GetConfigurationRequest
474 ): GetConfigurationResponse
{
475 const configurationKey
: OCPPConfigurationKey
[] = [];
476 const unknownKey
: string[] = [];
477 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
478 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
479 if (Utils
.isUndefined(configuration
.visible
) === true) {
480 configuration
.visible
= true;
482 if (configuration
.visible
=== false) {
485 configurationKey
.push({
486 key
: configuration
.key
,
487 readonly: configuration
.readonly,
488 value
: configuration
.value
,
492 for (const key
of commandPayload
.key
) {
493 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
498 if (Utils
.isUndefined(keyFound
.visible
) === true) {
499 keyFound
.visible
= true;
501 if (keyFound
.visible
=== false) {
504 configurationKey
.push({
506 readonly: keyFound
.readonly,
507 value
: keyFound
.value
,
510 unknownKey
.push(key
);
520 private handleRequestChangeConfiguration(
521 chargingStation
: ChargingStation
,
522 commandPayload
: ChangeConfigurationRequest
523 ): ChangeConfigurationResponse
{
524 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
530 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
531 } else if (keyToChange
&& keyToChange
.readonly) {
532 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
533 } else if (keyToChange
&& !keyToChange
.readonly) {
534 let valueChanged
= false;
535 if (keyToChange
.value
!== commandPayload
.value
) {
536 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
539 commandPayload
.value
,
544 let triggerHeartbeatRestart
= false;
545 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
546 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
548 OCPP16StandardParametersKey
.HeartbeatInterval
,
551 triggerHeartbeatRestart
= true;
553 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
554 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
556 OCPP16StandardParametersKey
.HeartBeatInterval
,
559 triggerHeartbeatRestart
= true;
561 if (triggerHeartbeatRestart
) {
562 chargingStation
.restartHeartbeat();
564 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
565 chargingStation
.restartWebSocketPing();
567 if (keyToChange
.reboot
) {
568 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
570 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
574 private handleRequestSetChargingProfile(
575 chargingStation
: ChargingStation
,
576 commandPayload
: SetChargingProfileRequest
577 ): SetChargingProfileResponse
{
579 OCPP16ServiceUtils
.checkFeatureProfile(
581 OCPP16SupportedFeatureProfiles
.SmartCharging
,
582 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
585 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
587 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
589 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
590 commandPayload.connectorId
593 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
596 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
597 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
598 commandPayload
.connectorId
!== 0
600 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
603 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
604 ChargingProfilePurposeType
.TX_PROFILE
&&
605 (commandPayload
.connectorId
=== 0 ||
606 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
610 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
611 commandPayload.connectorId
612 } without a started transaction`
614 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
616 OCPP16ServiceUtils
.setChargingProfile(
618 commandPayload
.connectorId
,
619 commandPayload
.csChargingProfiles
622 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
623 commandPayload.connectorId
624 }, dump their stack: %j`,
625 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
627 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
630 private handleRequestClearChargingProfile(
631 chargingStation
: ChargingStation
,
632 commandPayload
: ClearChargingProfileRequest
633 ): ClearChargingProfileResponse
{
635 OCPP16ServiceUtils
.checkFeatureProfile(
637 OCPP16SupportedFeatureProfiles
.SmartCharging
,
638 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
641 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
643 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
645 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
646 commandPayload.connectorId
649 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
651 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
652 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
653 connectorStatus
.chargingProfiles
= [];
655 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
656 commandPayload.connectorId
657 }, dump their stack: %j`,
658 connectorStatus
.chargingProfiles
660 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
662 if (!commandPayload
.connectorId
) {
663 let clearedCP
= false;
664 for (const connectorId
of chargingStation
.connectors
.keys()) {
665 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
667 .getConnectorStatus(connectorId
)
668 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
669 let clearCurrentCP
= false;
670 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
671 clearCurrentCP
= true;
674 !commandPayload
.chargingProfilePurpose
&&
675 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
677 clearCurrentCP
= true;
680 !chargingProfile
.stackLevel
&&
681 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
683 clearCurrentCP
= true;
686 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
687 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
689 clearCurrentCP
= true;
691 if (clearCurrentCP
) {
692 connectorStatus
.chargingProfiles
.splice(index
, 1);
694 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
695 commandPayload.connectorId
696 }, dump their stack: %j`,
697 connectorStatus
.chargingProfiles
705 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
708 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
711 private async handleRequestChangeAvailability(
712 chargingStation
: ChargingStation
,
713 commandPayload
: ChangeAvailabilityRequest
714 ): Promise
<ChangeAvailabilityResponse
> {
715 const connectorId
: number = commandPayload
.connectorId
;
716 if (chargingStation
.connectors
.has(connectorId
) === false) {
718 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
720 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
722 const chargePointStatus
: OCPP16ChargePointStatus
=
723 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
724 ? OCPP16ChargePointStatus
.AVAILABLE
725 : OCPP16ChargePointStatus
.UNAVAILABLE
;
726 if (connectorId
=== 0) {
727 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
728 for (const id
of chargingStation
.connectors
.keys()) {
729 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
730 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
732 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
733 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
734 await chargingStation
.ocppRequestService
.requestHandler
<
735 OCPP16StatusNotificationRequest
,
736 OCPP16StatusNotificationResponse
737 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
739 status: chargePointStatus
,
740 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
742 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
748 (chargingStation
.isChargingStationAvailable() === true ||
749 (chargingStation
.isChargingStationAvailable() === false &&
750 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
752 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
753 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
754 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
756 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
757 await chargingStation
.ocppRequestService
.requestHandler
<
758 OCPP16StatusNotificationRequest
,
759 OCPP16StatusNotificationResponse
760 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
762 status: chargePointStatus
,
763 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
765 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
766 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
768 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
771 private async handleRequestRemoteStartTransaction(
772 chargingStation
: ChargingStation
,
773 commandPayload
: RemoteStartTransactionRequest
774 ): Promise
<DefaultResponse
> {
775 const transactionConnectorId
= commandPayload
.connectorId
;
776 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
777 const remoteStartTransactionLogMsg
=
778 chargingStation
.logPrefix() +
779 ' Transaction remotely STARTED on ' +
780 chargingStation
.stationInfo
.chargingStationId
+
782 transactionConnectorId
.toString() +
784 commandPayload
.idTag
+
786 await chargingStation
.ocppRequestService
.requestHandler
<
787 OCPP16StatusNotificationRequest
,
788 OCPP16StatusNotificationResponse
789 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
790 connectorId
: transactionConnectorId
,
791 status: OCPP16ChargePointStatus
.PREPARING
,
792 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
794 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
795 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
796 if (chargingStation
.isChargingStationAvailable() === true) {
797 // Check if authorized
798 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
799 let authorized
= false;
801 chargingStation
.getLocalAuthListEnabled() === true &&
802 chargingStation
.hasAuthorizedTags() === true &&
803 chargingStation
.authorizedTagsCache
805 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
807 .find((idTag
) => idTag
=== commandPayload
.idTag
)
809 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
810 connectorStatus
.idTagLocalAuthorized
= true;
812 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
813 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
814 const authorizeResponse
: OCPP16AuthorizeResponse
=
815 await chargingStation
.ocppRequestService
.requestHandler
<
816 OCPP16AuthorizeRequest
,
817 OCPP16AuthorizeResponse
818 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
819 idTag
: commandPayload
.idTag
,
821 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
826 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
829 if (authorized
=== true) {
830 // Authorization successful, start transaction
832 this.setRemoteStartTransactionChargingProfile(
834 transactionConnectorId
,
835 commandPayload
.chargingProfile
838 connectorStatus
.transactionRemoteStarted
= true;
841 await chargingStation
.ocppRequestService
.requestHandler
<
842 OCPP16StartTransactionRequest
,
843 OCPP16StartTransactionResponse
844 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
845 connectorId
: transactionConnectorId
,
846 idTag
: commandPayload
.idTag
,
848 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
850 logger
.debug(remoteStartTransactionLogMsg
);
851 return Constants
.OCPP_RESPONSE_ACCEPTED
;
853 return this.notifyRemoteStartTransactionRejected(
855 transactionConnectorId
,
859 return this.notifyRemoteStartTransactionRejected(
861 transactionConnectorId
,
865 return this.notifyRemoteStartTransactionRejected(
867 transactionConnectorId
,
871 // No authorization check required, start transaction
873 this.setRemoteStartTransactionChargingProfile(
875 transactionConnectorId
,
876 commandPayload
.chargingProfile
879 connectorStatus
.transactionRemoteStarted
= true;
882 await chargingStation
.ocppRequestService
.requestHandler
<
883 OCPP16StartTransactionRequest
,
884 OCPP16StartTransactionResponse
885 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
886 connectorId
: transactionConnectorId
,
887 idTag
: commandPayload
.idTag
,
889 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
891 logger
.debug(remoteStartTransactionLogMsg
);
892 return Constants
.OCPP_RESPONSE_ACCEPTED
;
894 return this.notifyRemoteStartTransactionRejected(
896 transactionConnectorId
,
900 return this.notifyRemoteStartTransactionRejected(
902 transactionConnectorId
,
906 return this.notifyRemoteStartTransactionRejected(
908 transactionConnectorId
,
912 return this.notifyRemoteStartTransactionRejected(
914 transactionConnectorId
,
919 private async notifyRemoteStartTransactionRejected(
920 chargingStation
: ChargingStation
,
923 ): Promise
<DefaultResponse
> {
925 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
927 await chargingStation
.ocppRequestService
.requestHandler
<
928 OCPP16StatusNotificationRequest
,
929 OCPP16StatusNotificationResponse
930 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
932 status: OCPP16ChargePointStatus
.AVAILABLE
,
933 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
935 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
938 chargingStation
.logPrefix() +
939 ' Remote starting transaction REJECTED on connector Id ' +
940 connectorId
.toString() +
943 "', availability '" +
944 chargingStation
.getConnectorStatus(connectorId
).availability
+
946 chargingStation
.getConnectorStatus(connectorId
).status +
949 return Constants
.OCPP_RESPONSE_REJECTED
;
952 private setRemoteStartTransactionChargingProfile(
953 chargingStation
: ChargingStation
,
955 cp
: OCPP16ChargingProfile
957 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
958 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
960 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
961 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
964 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
966 `${chargingStation.logPrefix()} Not allowed to set ${
967 cp.chargingProfilePurpose
968 } charging profile(s) at remote start transaction`
976 private async handleRequestRemoteStopTransaction(
977 chargingStation
: ChargingStation
,
978 commandPayload
: RemoteStopTransactionRequest
979 ): Promise
<DefaultResponse
> {
980 const transactionId
= commandPayload
.transactionId
;
981 for (const connectorId
of chargingStation
.connectors
.keys()) {
984 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
986 await chargingStation
.ocppRequestService
.requestHandler
<
987 OCPP16StatusNotificationRequest
,
988 OCPP16StatusNotificationResponse
989 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
991 status: OCPP16ChargePointStatus
.FINISHING
,
992 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
994 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
995 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
997 OCPP16StopTransactionReason
.REMOTE
999 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
1000 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1002 return Constants
.OCPP_RESPONSE_REJECTED
;
1006 chargingStation
.logPrefix() +
1007 ' Trying to remote stop a non existing transaction ' +
1008 transactionId
.toString()
1010 return Constants
.OCPP_RESPONSE_REJECTED
;
1013 private handleRequestUpdateFirmware(
1014 chargingStation
: ChargingStation
,
1015 commandPayload
: OCPP16UpdateFirmwareRequest
1016 ): OCPP16UpdateFirmwareResponse
{
1018 OCPP16ServiceUtils
.checkFeatureProfile(
1020 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1021 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1024 return Constants
.OCPP_RESPONSE_EMPTY
;
1027 chargingStation
.logPrefix() +
1029 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
+
1030 ' request received: %j',
1035 private async handleRequestGetDiagnostics(
1036 chargingStation
: ChargingStation
,
1037 commandPayload
: GetDiagnosticsRequest
1038 ): Promise
<GetDiagnosticsResponse
> {
1040 OCPP16ServiceUtils
.checkFeatureProfile(
1042 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1043 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1046 return Constants
.OCPP_RESPONSE_EMPTY
;
1049 chargingStation
.logPrefix() +
1051 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1052 ' request received: %j',
1055 const uri
= new URL(commandPayload
.location
);
1056 if (uri
.protocol
.startsWith('ftp:')) {
1057 let ftpClient
: Client
;
1060 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1061 .filter((file
) => file
.endsWith('.log'))
1062 .map((file
) => path
.join('./', file
));
1063 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1064 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1065 ftpClient
= new Client();
1066 const accessResponse
= await ftpClient
.access({
1068 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1069 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1070 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1072 let uploadResponse
: FTPResponse
;
1073 if (accessResponse
.code
=== 220) {
1074 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1075 ftpClient
.trackProgress(async (info
) => {
1077 `${chargingStation.logPrefix()} ${
1079 } bytes transferred from diagnostics archive ${info.name}`
1081 await chargingStation
.ocppRequestService
.requestHandler
<
1082 DiagnosticsStatusNotificationRequest
,
1083 DiagnosticsStatusNotificationResponse
1084 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1085 status: OCPP16DiagnosticsStatus
.Uploading
,
1088 uploadResponse
= await ftpClient
.uploadFrom(
1090 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1093 uri
.pathname
+ diagnosticsArchive
1095 if (uploadResponse
.code
=== 226) {
1096 await chargingStation
.ocppRequestService
.requestHandler
<
1097 DiagnosticsStatusNotificationRequest
,
1098 DiagnosticsStatusNotificationResponse
1099 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1100 status: OCPP16DiagnosticsStatus
.Uploaded
,
1105 return { fileName
: diagnosticsArchive
};
1107 throw new OCPPError(
1108 ErrorType
.GENERIC_ERROR
,
1109 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1110 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1112 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1115 throw new OCPPError(
1116 ErrorType
.GENERIC_ERROR
,
1117 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1118 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1120 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1123 await chargingStation
.ocppRequestService
.requestHandler
<
1124 DiagnosticsStatusNotificationRequest
,
1125 DiagnosticsStatusNotificationResponse
1126 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1127 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1132 return this.handleIncomingRequestError(
1134 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1136 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1141 `${chargingStation.logPrefix()} Unsupported protocol ${
1143 } to transfer the diagnostic logs archive`
1145 await chargingStation
.ocppRequestService
.requestHandler
<
1146 DiagnosticsStatusNotificationRequest
,
1147 DiagnosticsStatusNotificationResponse
1148 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1149 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1151 return Constants
.OCPP_RESPONSE_EMPTY
;
1155 private handleRequestTriggerMessage(
1156 chargingStation
: ChargingStation
,
1157 commandPayload
: OCPP16TriggerMessageRequest
1158 ): OCPP16TriggerMessageResponse
{
1160 !OCPP16ServiceUtils
.checkFeatureProfile(
1162 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1163 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1165 !OCPP16ServiceUtils
.isMessageTriggerSupported(
1167 commandPayload
.requestedMessage
1170 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1173 !OCPP16ServiceUtils
.isConnectorIdValid(
1175 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1176 commandPayload
.connectorId
1179 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1182 switch (commandPayload
.requestedMessage
) {
1183 case OCPP16MessageTrigger
.BootNotification
:
1185 chargingStation
.ocppRequestService
1186 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1188 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1189 chargingStation
.bootNotificationRequest
,
1190 { skipBufferingOnError
: true, triggerMessage
: true }
1192 .then((response
) => {
1193 chargingStation
.bootNotificationResponse
= response
;
1196 /* This is intentional */
1198 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1199 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1200 case OCPP16MessageTrigger
.Heartbeat
:
1202 chargingStation
.ocppRequestService
1203 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1205 OCPP16RequestCommand
.HEARTBEAT
,
1208 triggerMessage
: true,
1212 /* This is intentional */
1214 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1215 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1216 case OCPP16MessageTrigger
.StatusNotification
:
1218 if (commandPayload
?.connectorId
) {
1219 chargingStation
.ocppRequestService
1220 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1222 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1224 connectorId
: commandPayload
.connectorId
,
1225 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1226 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1229 triggerMessage
: true,
1233 /* This is intentional */
1236 for (const connectorId
of chargingStation
.connectors
.keys()) {
1237 chargingStation
.ocppRequestService
1239 OCPP16StatusNotificationRequest
,
1240 OCPP16StatusNotificationResponse
1243 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1246 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1247 status: chargingStation
.getConnectorStatus(connectorId
).status,
1250 triggerMessage
: true,
1254 /* This is intentional */
1258 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1259 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1261 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1264 return this.handleIncomingRequestError(
1266 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1268 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}
1273 private handleRequestDataTransfer(
1274 chargingStation
: ChargingStation
,
1275 commandPayload
: OCPP16DataTransferRequest
1276 ): OCPP16DataTransferResponse
{
1278 if (Object.values(OCPP16DataTransferVendorId
).includes(commandPayload
.vendorId
)) {
1280 status: OCPP16DataTransferStatus
.ACCEPTED
,
1284 status: OCPP16DataTransferStatus
.UNKNOWN_VENDOR_ID
,
1287 return this.handleIncomingRequestError(
1289 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1291 { errorResponse
: Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}