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 OCPPConstants from
'../OCPPConstants';
86 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
87 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
89 const moduleName
= 'OCPP16IncomingRequestService';
91 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
92 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
93 private jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
95 public constructor() {
96 if (new.target
?.name
=== moduleName
) {
97 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
99 super(OCPPVersion
.VERSION_16
);
100 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
101 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
102 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
103 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
105 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
106 this.handleRequestGetConfiguration
.bind(this),
109 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
110 this.handleRequestChangeConfiguration
.bind(this),
113 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
114 this.handleRequestSetChargingProfile
.bind(this),
117 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
118 this.handleRequestClearChargingProfile
.bind(this),
121 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
122 this.handleRequestChangeAvailability
.bind(this),
125 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
126 this.handleRequestRemoteStartTransaction
.bind(this),
129 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
130 this.handleRequestRemoteStopTransaction
.bind(this),
132 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
133 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
134 [OCPP16IncomingRequestCommand
.DATA_TRANSFER
, this.handleRequestDataTransfer
.bind(this)],
135 // [OCPP16IncomingRequestCommand.UPDATE_FIRMWARE, this.handleRequestUpdateFirmware.bind(this)],
137 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
139 OCPP16IncomingRequestCommand
.RESET
,
143 path
.dirname(fileURLToPath(import.meta
.url
)),
144 '../../../assets/json-schemas/ocpp/1.6/Reset.json'
148 ) as JSONSchemaType
<ResetRequest
>,
151 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
155 path
.dirname(fileURLToPath(import.meta
.url
)),
156 '../../../assets/json-schemas/ocpp/1.6/ClearCache.json'
160 ) as JSONSchemaType
<OCPP16ClearCacheRequest
>,
163 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
167 path
.dirname(fileURLToPath(import.meta
.url
)),
168 '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json'
172 ) as JSONSchemaType
<UnlockConnectorRequest
>,
175 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
179 path
.dirname(fileURLToPath(import.meta
.url
)),
180 '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json'
184 ) as JSONSchemaType
<GetConfigurationRequest
>,
187 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
191 path
.dirname(fileURLToPath(import.meta
.url
)),
192 '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json'
196 ) as JSONSchemaType
<ChangeConfigurationRequest
>,
199 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
203 path
.dirname(fileURLToPath(import.meta
.url
)),
204 '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json'
208 ) as JSONSchemaType
<GetDiagnosticsRequest
>,
211 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
215 path
.dirname(fileURLToPath(import.meta
.url
)),
216 '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json'
220 ) as JSONSchemaType
<SetChargingProfileRequest
>,
223 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
227 path
.dirname(fileURLToPath(import.meta
.url
)),
228 '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json'
232 ) as JSONSchemaType
<ClearChargingProfileRequest
>,
235 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
239 path
.dirname(fileURLToPath(import.meta
.url
)),
240 '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json'
244 ) as JSONSchemaType
<ChangeAvailabilityRequest
>,
247 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
251 path
.dirname(fileURLToPath(import.meta
.url
)),
252 '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json'
256 ) as JSONSchemaType
<RemoteStartTransactionRequest
>,
259 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
263 path
.dirname(fileURLToPath(import.meta
.url
)),
264 '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json'
268 ) as JSONSchemaType
<RemoteStopTransactionRequest
>,
271 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
275 path
.dirname(fileURLToPath(import.meta
.url
)),
276 '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json'
280 ) as JSONSchemaType
<OCPP16TriggerMessageRequest
>,
283 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
287 path
.dirname(fileURLToPath(import.meta
.url
)),
288 '../../../assets/json-schemas/ocpp/1.6/DataTransfer.json'
292 ) as JSONSchemaType
<OCPP16DataTransferRequest
>,
295 this.validatePayload
.bind(this);
298 public async incomingRequestHandler(
299 chargingStation
: ChargingStation
,
301 commandName
: OCPP16IncomingRequestCommand
,
302 commandPayload
: JsonType
304 let response
: JsonType
;
306 chargingStation
.getOcppStrictCompliance() === true &&
307 chargingStation
.isInPendingState() === true &&
308 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
309 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
312 ErrorType
.SECURITY_ERROR
,
313 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
317 )} while the charging station is in pending state on the central server`,
323 chargingStation
.isRegistered() === true ||
324 (chargingStation
.getOcppStrictCompliance() === false &&
325 chargingStation
.isInUnknownState() === true)
328 this.incomingRequestHandlers
.has(commandName
) === true &&
329 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
332 this.validatePayload(chargingStation
, commandName
, commandPayload
);
333 // Call the method to build the response
334 response
= await this.incomingRequestHandlers
.get(commandName
)(
341 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
349 ErrorType
.NOT_IMPLEMENTED
,
350 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
361 ErrorType
.SECURITY_ERROR
,
362 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
366 )} while the charging station is not registered on the central server.`,
371 // Send the built response
372 await chargingStation
.ocppRequestService
.sendResponse(
380 private validatePayload(
381 chargingStation
: ChargingStation
,
382 commandName
: OCPP16IncomingRequestCommand
,
383 commandPayload
: JsonType
385 if (this.jsonSchemas
.has(commandName
) === true) {
386 return this.validateIncomingRequestPayload(
389 this.jsonSchemas
.get(commandName
),
394 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
399 // Simulate charging station restart
400 private handleRequestReset(
401 chargingStation
: ChargingStation
,
402 commandPayload
: ResetRequest
406 chargingStation
.reset
.bind(chargingStation
) as (
407 this: ChargingStation
,
411 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
414 /* This is intentional */
417 `${chargingStation.logPrefix()} ${
419 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
420 chargingStation.stationInfo.resetTime
423 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
426 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
427 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
428 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
430 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
433 private async handleRequestUnlockConnector(
434 chargingStation
: ChargingStation
,
435 commandPayload
: UnlockConnectorRequest
436 ): Promise
<UnlockConnectorResponse
> {
437 const connectorId
= commandPayload
.connectorId
;
438 if (chargingStation
.connectors
.has(connectorId
) === false) {
440 `${chargingStation.logPrefix()} Trying to unlock a non existing connector Id ${connectorId.toString()}`
442 return OCPPConstants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
444 if (connectorId
=== 0) {
446 chargingStation
.logPrefix() + ' Trying to unlock connector Id ' + connectorId
.toString()
448 return OCPPConstants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
450 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
451 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
453 OCPP16StopTransactionReason
.UNLOCK_COMMAND
455 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
456 return OCPPConstants
.OCPP_RESPONSE_UNLOCKED
;
458 return OCPPConstants
.OCPP_RESPONSE_UNLOCK_FAILED
;
460 await chargingStation
.ocppRequestService
.requestHandler
<
461 OCPP16StatusNotificationRequest
,
462 OCPP16StatusNotificationResponse
463 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
465 status: OCPP16ChargePointStatus
.AVAILABLE
,
466 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
468 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
469 return OCPPConstants
.OCPP_RESPONSE_UNLOCKED
;
472 private handleRequestGetConfiguration(
473 chargingStation
: ChargingStation
,
474 commandPayload
: GetConfigurationRequest
475 ): GetConfigurationResponse
{
476 const configurationKey
: OCPPConfigurationKey
[] = [];
477 const unknownKey
: string[] = [];
478 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
479 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
480 if (Utils
.isUndefined(configuration
.visible
) === true) {
481 configuration
.visible
= true;
483 if (configuration
.visible
=== false) {
486 configurationKey
.push({
487 key
: configuration
.key
,
488 readonly: configuration
.readonly,
489 value
: configuration
.value
,
493 for (const key
of commandPayload
.key
) {
494 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
499 if (Utils
.isUndefined(keyFound
.visible
) === true) {
500 keyFound
.visible
= true;
502 if (keyFound
.visible
=== false) {
505 configurationKey
.push({
507 readonly: keyFound
.readonly,
508 value
: keyFound
.value
,
511 unknownKey
.push(key
);
521 private handleRequestChangeConfiguration(
522 chargingStation
: ChargingStation
,
523 commandPayload
: ChangeConfigurationRequest
524 ): ChangeConfigurationResponse
{
525 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
531 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
532 } else if (keyToChange
&& keyToChange
.readonly) {
533 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
534 } else if (keyToChange
&& !keyToChange
.readonly) {
535 let valueChanged
= false;
536 if (keyToChange
.value
!== commandPayload
.value
) {
537 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
540 commandPayload
.value
,
545 let triggerHeartbeatRestart
= false;
546 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
547 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
549 OCPP16StandardParametersKey
.HeartbeatInterval
,
552 triggerHeartbeatRestart
= true;
554 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
555 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
557 OCPP16StandardParametersKey
.HeartBeatInterval
,
560 triggerHeartbeatRestart
= true;
562 if (triggerHeartbeatRestart
) {
563 chargingStation
.restartHeartbeat();
565 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
566 chargingStation
.restartWebSocketPing();
568 if (keyToChange
.reboot
) {
569 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
571 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
575 private handleRequestSetChargingProfile(
576 chargingStation
: ChargingStation
,
577 commandPayload
: SetChargingProfileRequest
578 ): SetChargingProfileResponse
{
580 OCPP16ServiceUtils
.checkFeatureProfile(
582 OCPP16SupportedFeatureProfiles
.SmartCharging
,
583 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
586 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
588 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
590 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
591 commandPayload.connectorId
594 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
597 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
598 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
599 commandPayload
.connectorId
!== 0
601 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
604 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
605 ChargingProfilePurposeType
.TX_PROFILE
&&
606 (commandPayload
.connectorId
=== 0 ||
607 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
611 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
612 commandPayload.connectorId
613 } without a started transaction`
615 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
617 OCPP16ServiceUtils
.setChargingProfile(
619 commandPayload
.connectorId
,
620 commandPayload
.csChargingProfiles
623 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
624 commandPayload.connectorId
625 }, dump their stack: %j`,
626 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
628 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
631 private handleRequestClearChargingProfile(
632 chargingStation
: ChargingStation
,
633 commandPayload
: ClearChargingProfileRequest
634 ): ClearChargingProfileResponse
{
636 OCPP16ServiceUtils
.checkFeatureProfile(
638 OCPP16SupportedFeatureProfiles
.SmartCharging
,
639 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
642 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
644 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
646 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
647 commandPayload.connectorId
650 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
652 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
653 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
654 connectorStatus
.chargingProfiles
= [];
656 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
657 commandPayload.connectorId
658 }, dump their stack: %j`,
659 connectorStatus
.chargingProfiles
661 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
663 if (!commandPayload
.connectorId
) {
664 let clearedCP
= false;
665 for (const connectorId
of chargingStation
.connectors
.keys()) {
666 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
668 .getConnectorStatus(connectorId
)
669 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
670 let clearCurrentCP
= false;
671 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
672 clearCurrentCP
= true;
675 !commandPayload
.chargingProfilePurpose
&&
676 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
678 clearCurrentCP
= true;
681 !chargingProfile
.stackLevel
&&
682 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
684 clearCurrentCP
= true;
687 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
688 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
690 clearCurrentCP
= true;
692 if (clearCurrentCP
) {
693 connectorStatus
.chargingProfiles
.splice(index
, 1);
695 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
696 commandPayload.connectorId
697 }, dump their stack: %j`,
698 connectorStatus
.chargingProfiles
706 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
709 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
712 private async handleRequestChangeAvailability(
713 chargingStation
: ChargingStation
,
714 commandPayload
: ChangeAvailabilityRequest
715 ): Promise
<ChangeAvailabilityResponse
> {
716 const connectorId
: number = commandPayload
.connectorId
;
717 if (chargingStation
.connectors
.has(connectorId
) === false) {
719 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
721 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
723 const chargePointStatus
: OCPP16ChargePointStatus
=
724 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
725 ? OCPP16ChargePointStatus
.AVAILABLE
726 : OCPP16ChargePointStatus
.UNAVAILABLE
;
727 if (connectorId
=== 0) {
728 let response
: ChangeAvailabilityResponse
= OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
729 for (const id
of chargingStation
.connectors
.keys()) {
730 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
731 response
= OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
733 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
734 if (response
=== OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
735 await chargingStation
.ocppRequestService
.requestHandler
<
736 OCPP16StatusNotificationRequest
,
737 OCPP16StatusNotificationResponse
738 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
740 status: chargePointStatus
,
741 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
743 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
749 (chargingStation
.isChargingStationAvailable() === true ||
750 (chargingStation
.isChargingStationAvailable() === false &&
751 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
753 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
754 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
755 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
757 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
758 await chargingStation
.ocppRequestService
.requestHandler
<
759 OCPP16StatusNotificationRequest
,
760 OCPP16StatusNotificationResponse
761 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
763 status: chargePointStatus
,
764 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
766 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
767 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
769 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
772 private async handleRequestRemoteStartTransaction(
773 chargingStation
: ChargingStation
,
774 commandPayload
: RemoteStartTransactionRequest
775 ): Promise
<DefaultResponse
> {
776 const transactionConnectorId
= commandPayload
.connectorId
;
777 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
778 const remoteStartTransactionLogMsg
=
779 chargingStation
.logPrefix() +
780 ' Transaction remotely STARTED on ' +
781 chargingStation
.stationInfo
.chargingStationId
+
783 transactionConnectorId
.toString() +
785 commandPayload
.idTag
+
787 await chargingStation
.ocppRequestService
.requestHandler
<
788 OCPP16StatusNotificationRequest
,
789 OCPP16StatusNotificationResponse
790 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
791 connectorId
: transactionConnectorId
,
792 status: OCPP16ChargePointStatus
.PREPARING
,
793 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
795 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
796 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
797 if (chargingStation
.isChargingStationAvailable() === true) {
798 // Check if authorized
799 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
800 let authorized
= false;
802 chargingStation
.getLocalAuthListEnabled() === true &&
803 chargingStation
.hasAuthorizedTags() === true &&
804 chargingStation
.authorizedTagsCache
806 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
808 .find((idTag
) => idTag
=== commandPayload
.idTag
)
810 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
811 connectorStatus
.idTagLocalAuthorized
= true;
813 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
814 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
815 const authorizeResponse
: OCPP16AuthorizeResponse
=
816 await chargingStation
.ocppRequestService
.requestHandler
<
817 OCPP16AuthorizeRequest
,
818 OCPP16AuthorizeResponse
819 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
820 idTag
: commandPayload
.idTag
,
822 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
827 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
830 if (authorized
=== true) {
831 // Authorization successful, start transaction
833 this.setRemoteStartTransactionChargingProfile(
835 transactionConnectorId
,
836 commandPayload
.chargingProfile
839 connectorStatus
.transactionRemoteStarted
= true;
842 await chargingStation
.ocppRequestService
.requestHandler
<
843 OCPP16StartTransactionRequest
,
844 OCPP16StartTransactionResponse
845 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
846 connectorId
: transactionConnectorId
,
847 idTag
: commandPayload
.idTag
,
849 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
851 logger
.debug(remoteStartTransactionLogMsg
);
852 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
854 return this.notifyRemoteStartTransactionRejected(
856 transactionConnectorId
,
860 return this.notifyRemoteStartTransactionRejected(
862 transactionConnectorId
,
866 return this.notifyRemoteStartTransactionRejected(
868 transactionConnectorId
,
872 // No authorization check required, start transaction
874 this.setRemoteStartTransactionChargingProfile(
876 transactionConnectorId
,
877 commandPayload
.chargingProfile
880 connectorStatus
.transactionRemoteStarted
= true;
883 await chargingStation
.ocppRequestService
.requestHandler
<
884 OCPP16StartTransactionRequest
,
885 OCPP16StartTransactionResponse
886 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
887 connectorId
: transactionConnectorId
,
888 idTag
: commandPayload
.idTag
,
890 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
892 logger
.debug(remoteStartTransactionLogMsg
);
893 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
895 return this.notifyRemoteStartTransactionRejected(
897 transactionConnectorId
,
901 return this.notifyRemoteStartTransactionRejected(
903 transactionConnectorId
,
907 return this.notifyRemoteStartTransactionRejected(
909 transactionConnectorId
,
913 return this.notifyRemoteStartTransactionRejected(
915 transactionConnectorId
,
920 private async notifyRemoteStartTransactionRejected(
921 chargingStation
: ChargingStation
,
924 ): Promise
<DefaultResponse
> {
926 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
928 await chargingStation
.ocppRequestService
.requestHandler
<
929 OCPP16StatusNotificationRequest
,
930 OCPP16StatusNotificationResponse
931 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
933 status: OCPP16ChargePointStatus
.AVAILABLE
,
934 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
936 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
939 chargingStation
.logPrefix() +
940 ' Remote starting transaction REJECTED on connector Id ' +
941 connectorId
.toString() +
944 "', availability '" +
945 chargingStation
.getConnectorStatus(connectorId
).availability
+
947 chargingStation
.getConnectorStatus(connectorId
).status +
950 return OCPPConstants
.OCPP_RESPONSE_REJECTED
;
953 private setRemoteStartTransactionChargingProfile(
954 chargingStation
: ChargingStation
,
956 cp
: OCPP16ChargingProfile
958 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
959 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
961 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
962 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
965 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
967 `${chargingStation.logPrefix()} Not allowed to set ${
968 cp.chargingProfilePurpose
969 } charging profile(s) at remote start transaction`
977 private async handleRequestRemoteStopTransaction(
978 chargingStation
: ChargingStation
,
979 commandPayload
: RemoteStopTransactionRequest
980 ): Promise
<DefaultResponse
> {
981 const transactionId
= commandPayload
.transactionId
;
982 for (const connectorId
of chargingStation
.connectors
.keys()) {
985 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
987 await chargingStation
.ocppRequestService
.requestHandler
<
988 OCPP16StatusNotificationRequest
,
989 OCPP16StatusNotificationResponse
990 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
992 status: OCPP16ChargePointStatus
.FINISHING
,
993 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
995 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
996 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
998 OCPP16StopTransactionReason
.REMOTE
1000 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
1001 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
1003 return OCPPConstants
.OCPP_RESPONSE_REJECTED
;
1007 chargingStation
.logPrefix() +
1008 ' Trying to remote stop a non existing transaction ' +
1009 transactionId
.toString()
1011 return OCPPConstants
.OCPP_RESPONSE_REJECTED
;
1014 private handleRequestUpdateFirmware(
1015 chargingStation
: ChargingStation
,
1016 commandPayload
: OCPP16UpdateFirmwareRequest
1017 ): OCPP16UpdateFirmwareResponse
{
1019 OCPP16ServiceUtils
.checkFeatureProfile(
1021 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1022 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1025 return OCPPConstants
.OCPP_RESPONSE_EMPTY
;
1028 chargingStation
.logPrefix() +
1030 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
+
1031 ' request received: %j',
1036 private async handleRequestGetDiagnostics(
1037 chargingStation
: ChargingStation
,
1038 commandPayload
: GetDiagnosticsRequest
1039 ): Promise
<GetDiagnosticsResponse
> {
1041 OCPP16ServiceUtils
.checkFeatureProfile(
1043 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1044 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1047 return OCPPConstants
.OCPP_RESPONSE_EMPTY
;
1050 chargingStation
.logPrefix() +
1052 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1053 ' request received: %j',
1056 const uri
= new URL(commandPayload
.location
);
1057 if (uri
.protocol
.startsWith('ftp:')) {
1058 let ftpClient
: Client
;
1061 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1062 .filter((file
) => file
.endsWith('.log'))
1063 .map((file
) => path
.join('./', file
));
1064 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1065 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1066 ftpClient
= new Client();
1067 const accessResponse
= await ftpClient
.access({
1069 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1070 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1071 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1073 let uploadResponse
: FTPResponse
;
1074 if (accessResponse
.code
=== 220) {
1075 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1076 ftpClient
.trackProgress(async (info
) => {
1078 `${chargingStation.logPrefix()} ${
1080 } bytes transferred from diagnostics archive ${info.name}`
1082 await chargingStation
.ocppRequestService
.requestHandler
<
1083 DiagnosticsStatusNotificationRequest
,
1084 DiagnosticsStatusNotificationResponse
1085 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1086 status: OCPP16DiagnosticsStatus
.Uploading
,
1089 uploadResponse
= await ftpClient
.uploadFrom(
1091 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1094 uri
.pathname
+ diagnosticsArchive
1096 if (uploadResponse
.code
=== 226) {
1097 await chargingStation
.ocppRequestService
.requestHandler
<
1098 DiagnosticsStatusNotificationRequest
,
1099 DiagnosticsStatusNotificationResponse
1100 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1101 status: OCPP16DiagnosticsStatus
.Uploaded
,
1106 return { fileName
: diagnosticsArchive
};
1108 throw new OCPPError(
1109 ErrorType
.GENERIC_ERROR
,
1110 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1111 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1113 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1116 throw new OCPPError(
1117 ErrorType
.GENERIC_ERROR
,
1118 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1119 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1121 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1124 await chargingStation
.ocppRequestService
.requestHandler
<
1125 DiagnosticsStatusNotificationRequest
,
1126 DiagnosticsStatusNotificationResponse
1127 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1128 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1133 return this.handleIncomingRequestError(
1135 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1137 { errorResponse
: OCPPConstants
.OCPP_RESPONSE_EMPTY
}
1142 `${chargingStation.logPrefix()} Unsupported protocol ${
1144 } to transfer the diagnostic logs archive`
1146 await chargingStation
.ocppRequestService
.requestHandler
<
1147 DiagnosticsStatusNotificationRequest
,
1148 DiagnosticsStatusNotificationResponse
1149 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1150 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1152 return OCPPConstants
.OCPP_RESPONSE_EMPTY
;
1156 private handleRequestTriggerMessage(
1157 chargingStation
: ChargingStation
,
1158 commandPayload
: OCPP16TriggerMessageRequest
1159 ): OCPP16TriggerMessageResponse
{
1161 !OCPP16ServiceUtils
.checkFeatureProfile(
1163 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1164 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1166 !OCPP16ServiceUtils
.isMessageTriggerSupported(
1168 commandPayload
.requestedMessage
1171 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1174 !OCPP16ServiceUtils
.isConnectorIdValid(
1176 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1177 commandPayload
.connectorId
1180 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1183 switch (commandPayload
.requestedMessage
) {
1184 case OCPP16MessageTrigger
.BootNotification
:
1186 chargingStation
.ocppRequestService
1187 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1189 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1190 chargingStation
.bootNotificationRequest
,
1191 { skipBufferingOnError
: true, triggerMessage
: true }
1193 .then((response
) => {
1194 chargingStation
.bootNotificationResponse
= response
;
1197 /* This is intentional */
1199 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1200 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1201 case OCPP16MessageTrigger
.Heartbeat
:
1203 chargingStation
.ocppRequestService
1204 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1206 OCPP16RequestCommand
.HEARTBEAT
,
1209 triggerMessage
: true,
1213 /* This is intentional */
1215 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1216 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1217 case OCPP16MessageTrigger
.StatusNotification
:
1219 if (commandPayload
?.connectorId
) {
1220 chargingStation
.ocppRequestService
1221 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1223 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1225 connectorId
: commandPayload
.connectorId
,
1226 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1227 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1230 triggerMessage
: true,
1234 /* This is intentional */
1237 for (const connectorId
of chargingStation
.connectors
.keys()) {
1238 chargingStation
.ocppRequestService
1240 OCPP16StatusNotificationRequest
,
1241 OCPP16StatusNotificationResponse
1244 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1247 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1248 status: chargingStation
.getConnectorStatus(connectorId
).status,
1251 triggerMessage
: true,
1255 /* This is intentional */
1259 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1260 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1262 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1265 return this.handleIncomingRequestError(
1267 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1269 { errorResponse
: OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}
1274 private handleRequestDataTransfer(
1275 chargingStation
: ChargingStation
,
1276 commandPayload
: OCPP16DataTransferRequest
1277 ): OCPP16DataTransferResponse
{
1279 if (Object.values(OCPP16DataTransferVendorId
).includes(commandPayload
.vendorId
)) {
1281 status: OCPP16DataTransferStatus
.ACCEPTED
,
1285 status: OCPP16DataTransferStatus
.UNKNOWN_VENDOR_ID
,
1288 return this.handleIncomingRequestError(
1290 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1292 { errorResponse
: OCPPConstants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}