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 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
299 path
.dirname(fileURLToPath(import.meta
.url
)),
300 '../../../assets/json-schemas/ocpp/1.6/UpdateFirmware.json'
304 ) as JSONSchemaType
<OCPP16UpdateFirmwareRequest
>,
307 this.validatePayload
.bind(this);
310 public async incomingRequestHandler(
311 chargingStation
: ChargingStation
,
313 commandName
: OCPP16IncomingRequestCommand
,
314 commandPayload
: JsonType
316 let response
: JsonType
;
318 chargingStation
.getOcppStrictCompliance() === true &&
319 chargingStation
.isInPendingState() === true &&
320 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
321 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
324 ErrorType
.SECURITY_ERROR
,
325 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
329 )} while the charging station is in pending state on the central server`,
335 chargingStation
.isRegistered() === true ||
336 (chargingStation
.getOcppStrictCompliance() === false &&
337 chargingStation
.isInUnknownState() === true)
340 this.incomingRequestHandlers
.has(commandName
) === true &&
341 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
344 this.validatePayload(chargingStation
, commandName
, commandPayload
);
345 // Call the method to build the response
346 response
= await this.incomingRequestHandlers
.get(commandName
)(
353 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
361 ErrorType
.NOT_IMPLEMENTED
,
362 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
373 ErrorType
.SECURITY_ERROR
,
374 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
378 )} while the charging station is not registered on the central server.`,
383 // Send the built response
384 await chargingStation
.ocppRequestService
.sendResponse(
392 private validatePayload(
393 chargingStation
: ChargingStation
,
394 commandName
: OCPP16IncomingRequestCommand
,
395 commandPayload
: JsonType
397 if (this.jsonSchemas
.has(commandName
) === true) {
398 return this.validateIncomingRequestPayload(
401 this.jsonSchemas
.get(commandName
),
406 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
411 // Simulate charging station restart
412 private handleRequestReset(
413 chargingStation
: ChargingStation
,
414 commandPayload
: ResetRequest
418 chargingStation
.reset
.bind(chargingStation
) as (
419 this: ChargingStation
,
423 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
426 /* This is intentional */
429 `${chargingStation.logPrefix()} ${
431 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
432 chargingStation.stationInfo.resetTime
435 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
438 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
439 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
440 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
442 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
445 private async handleRequestUnlockConnector(
446 chargingStation
: ChargingStation
,
447 commandPayload
: UnlockConnectorRequest
448 ): Promise
<UnlockConnectorResponse
> {
449 const connectorId
= commandPayload
.connectorId
;
450 if (chargingStation
.connectors
.has(connectorId
) === false) {
452 `${chargingStation.logPrefix()} Trying to unlock a non existing connector Id ${connectorId.toString()}`
454 return OCPPConstants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
456 if (connectorId
=== 0) {
458 chargingStation
.logPrefix() + ' Trying to unlock connector Id ' + connectorId
.toString()
460 return OCPPConstants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
462 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
463 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
465 OCPP16StopTransactionReason
.UNLOCK_COMMAND
467 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
468 return OCPPConstants
.OCPP_RESPONSE_UNLOCKED
;
470 return OCPPConstants
.OCPP_RESPONSE_UNLOCK_FAILED
;
472 await chargingStation
.ocppRequestService
.requestHandler
<
473 OCPP16StatusNotificationRequest
,
474 OCPP16StatusNotificationResponse
475 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
477 status: OCPP16ChargePointStatus
.AVAILABLE
,
478 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
480 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
481 return OCPPConstants
.OCPP_RESPONSE_UNLOCKED
;
484 private handleRequestGetConfiguration(
485 chargingStation
: ChargingStation
,
486 commandPayload
: GetConfigurationRequest
487 ): GetConfigurationResponse
{
488 const configurationKey
: OCPPConfigurationKey
[] = [];
489 const unknownKey
: string[] = [];
490 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
491 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
492 if (Utils
.isUndefined(configuration
.visible
) === true) {
493 configuration
.visible
= true;
495 if (configuration
.visible
=== false) {
498 configurationKey
.push({
499 key
: configuration
.key
,
500 readonly: configuration
.readonly,
501 value
: configuration
.value
,
505 for (const key
of commandPayload
.key
) {
506 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
511 if (Utils
.isUndefined(keyFound
.visible
) === true) {
512 keyFound
.visible
= true;
514 if (keyFound
.visible
=== false) {
517 configurationKey
.push({
519 readonly: keyFound
.readonly,
520 value
: keyFound
.value
,
523 unknownKey
.push(key
);
533 private handleRequestChangeConfiguration(
534 chargingStation
: ChargingStation
,
535 commandPayload
: ChangeConfigurationRequest
536 ): ChangeConfigurationResponse
{
537 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
543 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
544 } else if (keyToChange
&& keyToChange
.readonly) {
545 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
546 } else if (keyToChange
&& !keyToChange
.readonly) {
547 let valueChanged
= false;
548 if (keyToChange
.value
!== commandPayload
.value
) {
549 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
552 commandPayload
.value
,
557 let triggerHeartbeatRestart
= false;
558 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
559 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
561 OCPP16StandardParametersKey
.HeartbeatInterval
,
564 triggerHeartbeatRestart
= true;
566 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
567 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
569 OCPP16StandardParametersKey
.HeartBeatInterval
,
572 triggerHeartbeatRestart
= true;
574 if (triggerHeartbeatRestart
) {
575 chargingStation
.restartHeartbeat();
577 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
578 chargingStation
.restartWebSocketPing();
580 if (keyToChange
.reboot
) {
581 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
583 return OCPPConstants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
587 private handleRequestSetChargingProfile(
588 chargingStation
: ChargingStation
,
589 commandPayload
: SetChargingProfileRequest
590 ): SetChargingProfileResponse
{
592 OCPP16ServiceUtils
.checkFeatureProfile(
594 OCPP16SupportedFeatureProfiles
.SmartCharging
,
595 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
598 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
600 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
602 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
603 commandPayload.connectorId
606 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
609 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
610 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
611 commandPayload
.connectorId
!== 0
613 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
616 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
617 ChargingProfilePurposeType
.TX_PROFILE
&&
618 (commandPayload
.connectorId
=== 0 ||
619 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
623 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
624 commandPayload.connectorId
625 } without a started transaction`
627 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
629 OCPP16ServiceUtils
.setChargingProfile(
631 commandPayload
.connectorId
,
632 commandPayload
.csChargingProfiles
635 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
636 commandPayload.connectorId
637 }, dump their stack: %j`,
638 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
640 return OCPPConstants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
643 private handleRequestClearChargingProfile(
644 chargingStation
: ChargingStation
,
645 commandPayload
: ClearChargingProfileRequest
646 ): ClearChargingProfileResponse
{
648 OCPP16ServiceUtils
.checkFeatureProfile(
650 OCPP16SupportedFeatureProfiles
.SmartCharging
,
651 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
654 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
656 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
658 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
659 commandPayload.connectorId
662 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
664 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
665 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
666 connectorStatus
.chargingProfiles
= [];
668 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
669 commandPayload.connectorId
670 }, dump their stack: %j`,
671 connectorStatus
.chargingProfiles
673 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
675 if (!commandPayload
.connectorId
) {
676 let clearedCP
= false;
677 for (const connectorId
of chargingStation
.connectors
.keys()) {
678 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
680 .getConnectorStatus(connectorId
)
681 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
682 let clearCurrentCP
= false;
683 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
684 clearCurrentCP
= true;
687 !commandPayload
.chargingProfilePurpose
&&
688 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
690 clearCurrentCP
= true;
693 !chargingProfile
.stackLevel
&&
694 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
696 clearCurrentCP
= true;
699 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
700 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
702 clearCurrentCP
= true;
704 if (clearCurrentCP
) {
705 connectorStatus
.chargingProfiles
.splice(index
, 1);
707 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
708 commandPayload.connectorId
709 }, dump their stack: %j`,
710 connectorStatus
.chargingProfiles
718 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
721 return OCPPConstants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
724 private async handleRequestChangeAvailability(
725 chargingStation
: ChargingStation
,
726 commandPayload
: ChangeAvailabilityRequest
727 ): Promise
<ChangeAvailabilityResponse
> {
728 const connectorId
: number = commandPayload
.connectorId
;
729 if (chargingStation
.connectors
.has(connectorId
) === false) {
731 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
733 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
735 const chargePointStatus
: OCPP16ChargePointStatus
=
736 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
737 ? OCPP16ChargePointStatus
.AVAILABLE
738 : OCPP16ChargePointStatus
.UNAVAILABLE
;
739 if (connectorId
=== 0) {
740 let response
: ChangeAvailabilityResponse
= OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
741 for (const id
of chargingStation
.connectors
.keys()) {
742 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
743 response
= OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
745 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
746 if (response
=== OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
747 await chargingStation
.ocppRequestService
.requestHandler
<
748 OCPP16StatusNotificationRequest
,
749 OCPP16StatusNotificationResponse
750 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
752 status: chargePointStatus
,
753 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
755 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
761 (chargingStation
.isChargingStationAvailable() === true ||
762 (chargingStation
.isChargingStationAvailable() === false &&
763 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
765 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
766 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
767 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
769 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
770 await chargingStation
.ocppRequestService
.requestHandler
<
771 OCPP16StatusNotificationRequest
,
772 OCPP16StatusNotificationResponse
773 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
775 status: chargePointStatus
,
776 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
778 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
779 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
781 return OCPPConstants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
784 private async handleRequestRemoteStartTransaction(
785 chargingStation
: ChargingStation
,
786 commandPayload
: RemoteStartTransactionRequest
787 ): Promise
<DefaultResponse
> {
788 const transactionConnectorId
= commandPayload
.connectorId
;
789 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
790 const remoteStartTransactionLogMsg
=
791 chargingStation
.logPrefix() +
792 ' Transaction remotely STARTED on ' +
793 chargingStation
.stationInfo
.chargingStationId
+
795 transactionConnectorId
.toString() +
797 commandPayload
.idTag
+
799 await chargingStation
.ocppRequestService
.requestHandler
<
800 OCPP16StatusNotificationRequest
,
801 OCPP16StatusNotificationResponse
802 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
803 connectorId
: transactionConnectorId
,
804 status: OCPP16ChargePointStatus
.PREPARING
,
805 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
807 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
808 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
809 if (chargingStation
.isChargingStationAvailable() === true) {
810 // Check if authorized
811 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
812 let authorized
= false;
814 chargingStation
.getLocalAuthListEnabled() === true &&
815 chargingStation
.hasAuthorizedTags() === true &&
816 chargingStation
.authorizedTagsCache
818 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
820 .find((idTag
) => idTag
=== commandPayload
.idTag
)
822 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
823 connectorStatus
.idTagLocalAuthorized
= true;
825 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
826 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
827 const authorizeResponse
: OCPP16AuthorizeResponse
=
828 await chargingStation
.ocppRequestService
.requestHandler
<
829 OCPP16AuthorizeRequest
,
830 OCPP16AuthorizeResponse
831 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
832 idTag
: commandPayload
.idTag
,
834 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
839 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
842 if (authorized
=== true) {
843 // Authorization successful, start transaction
845 this.setRemoteStartTransactionChargingProfile(
847 transactionConnectorId
,
848 commandPayload
.chargingProfile
851 connectorStatus
.transactionRemoteStarted
= true;
854 await chargingStation
.ocppRequestService
.requestHandler
<
855 OCPP16StartTransactionRequest
,
856 OCPP16StartTransactionResponse
857 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
858 connectorId
: transactionConnectorId
,
859 idTag
: commandPayload
.idTag
,
861 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
863 logger
.debug(remoteStartTransactionLogMsg
);
864 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
866 return this.notifyRemoteStartTransactionRejected(
868 transactionConnectorId
,
872 return this.notifyRemoteStartTransactionRejected(
874 transactionConnectorId
,
878 return this.notifyRemoteStartTransactionRejected(
880 transactionConnectorId
,
884 // No authorization check required, start transaction
886 this.setRemoteStartTransactionChargingProfile(
888 transactionConnectorId
,
889 commandPayload
.chargingProfile
892 connectorStatus
.transactionRemoteStarted
= true;
895 await chargingStation
.ocppRequestService
.requestHandler
<
896 OCPP16StartTransactionRequest
,
897 OCPP16StartTransactionResponse
898 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
899 connectorId
: transactionConnectorId
,
900 idTag
: commandPayload
.idTag
,
902 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
904 logger
.debug(remoteStartTransactionLogMsg
);
905 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
907 return this.notifyRemoteStartTransactionRejected(
909 transactionConnectorId
,
913 return this.notifyRemoteStartTransactionRejected(
915 transactionConnectorId
,
919 return this.notifyRemoteStartTransactionRejected(
921 transactionConnectorId
,
925 return this.notifyRemoteStartTransactionRejected(
927 transactionConnectorId
,
932 private async notifyRemoteStartTransactionRejected(
933 chargingStation
: ChargingStation
,
936 ): Promise
<DefaultResponse
> {
938 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
940 await chargingStation
.ocppRequestService
.requestHandler
<
941 OCPP16StatusNotificationRequest
,
942 OCPP16StatusNotificationResponse
943 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
945 status: OCPP16ChargePointStatus
.AVAILABLE
,
946 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
948 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
951 chargingStation
.logPrefix() +
952 ' Remote starting transaction REJECTED on connector Id ' +
953 connectorId
.toString() +
956 "', availability '" +
957 chargingStation
.getConnectorStatus(connectorId
).availability
+
959 chargingStation
.getConnectorStatus(connectorId
).status +
962 return OCPPConstants
.OCPP_RESPONSE_REJECTED
;
965 private setRemoteStartTransactionChargingProfile(
966 chargingStation
: ChargingStation
,
968 cp
: OCPP16ChargingProfile
970 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
971 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
973 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
974 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
977 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
979 `${chargingStation.logPrefix()} Not allowed to set ${
980 cp.chargingProfilePurpose
981 } charging profile(s) at remote start transaction`
989 private async handleRequestRemoteStopTransaction(
990 chargingStation
: ChargingStation
,
991 commandPayload
: RemoteStopTransactionRequest
992 ): Promise
<DefaultResponse
> {
993 const transactionId
= commandPayload
.transactionId
;
994 for (const connectorId
of chargingStation
.connectors
.keys()) {
997 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
999 await chargingStation
.ocppRequestService
.requestHandler
<
1000 OCPP16StatusNotificationRequest
,
1001 OCPP16StatusNotificationResponse
1002 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
1004 status: OCPP16ChargePointStatus
.FINISHING
,
1005 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1007 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
1008 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
1010 OCPP16StopTransactionReason
.REMOTE
1012 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
1013 return OCPPConstants
.OCPP_RESPONSE_ACCEPTED
;
1015 return OCPPConstants
.OCPP_RESPONSE_REJECTED
;
1019 chargingStation
.logPrefix() +
1020 ' Trying to remote stop a non existing transaction ' +
1021 transactionId
.toString()
1023 return OCPPConstants
.OCPP_RESPONSE_REJECTED
;
1026 private handleRequestUpdateFirmware(
1027 chargingStation
: ChargingStation
,
1028 commandPayload
: OCPP16UpdateFirmwareRequest
1029 ): OCPP16UpdateFirmwareResponse
{
1031 OCPP16ServiceUtils
.checkFeatureProfile(
1033 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1034 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1037 return OCPPConstants
.OCPP_RESPONSE_EMPTY
;
1040 chargingStation
.logPrefix() +
1042 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
+
1043 ' request received: %j',
1048 private async handleRequestGetDiagnostics(
1049 chargingStation
: ChargingStation
,
1050 commandPayload
: GetDiagnosticsRequest
1051 ): Promise
<GetDiagnosticsResponse
> {
1053 OCPP16ServiceUtils
.checkFeatureProfile(
1055 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1056 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1059 return OCPPConstants
.OCPP_RESPONSE_EMPTY
;
1062 chargingStation
.logPrefix() +
1064 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1065 ' request received: %j',
1068 const uri
= new URL(commandPayload
.location
);
1069 if (uri
.protocol
.startsWith('ftp:')) {
1070 let ftpClient
: Client
;
1073 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1074 .filter((file
) => file
.endsWith('.log'))
1075 .map((file
) => path
.join('./', file
));
1076 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1077 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1078 ftpClient
= new Client();
1079 const accessResponse
= await ftpClient
.access({
1081 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1082 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1083 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1085 let uploadResponse
: FTPResponse
;
1086 if (accessResponse
.code
=== 220) {
1087 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1088 ftpClient
.trackProgress(async (info
) => {
1090 `${chargingStation.logPrefix()} ${
1092 } bytes transferred from diagnostics archive ${info.name}`
1094 await chargingStation
.ocppRequestService
.requestHandler
<
1095 DiagnosticsStatusNotificationRequest
,
1096 DiagnosticsStatusNotificationResponse
1097 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1098 status: OCPP16DiagnosticsStatus
.Uploading
,
1101 uploadResponse
= await ftpClient
.uploadFrom(
1103 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1106 uri
.pathname
+ diagnosticsArchive
1108 if (uploadResponse
.code
=== 226) {
1109 await chargingStation
.ocppRequestService
.requestHandler
<
1110 DiagnosticsStatusNotificationRequest
,
1111 DiagnosticsStatusNotificationResponse
1112 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1113 status: OCPP16DiagnosticsStatus
.Uploaded
,
1118 return { fileName
: diagnosticsArchive
};
1120 throw new OCPPError(
1121 ErrorType
.GENERIC_ERROR
,
1122 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1123 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1125 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1128 throw new OCPPError(
1129 ErrorType
.GENERIC_ERROR
,
1130 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1131 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1133 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1136 await chargingStation
.ocppRequestService
.requestHandler
<
1137 DiagnosticsStatusNotificationRequest
,
1138 DiagnosticsStatusNotificationResponse
1139 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1140 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1145 return this.handleIncomingRequestError(
1147 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1149 { errorResponse
: OCPPConstants
.OCPP_RESPONSE_EMPTY
}
1154 `${chargingStation.logPrefix()} Unsupported protocol ${
1156 } to transfer the diagnostic logs archive`
1158 await chargingStation
.ocppRequestService
.requestHandler
<
1159 DiagnosticsStatusNotificationRequest
,
1160 DiagnosticsStatusNotificationResponse
1161 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1162 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1164 return OCPPConstants
.OCPP_RESPONSE_EMPTY
;
1168 private handleRequestTriggerMessage(
1169 chargingStation
: ChargingStation
,
1170 commandPayload
: OCPP16TriggerMessageRequest
1171 ): OCPP16TriggerMessageResponse
{
1173 !OCPP16ServiceUtils
.checkFeatureProfile(
1175 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1176 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1178 !OCPP16ServiceUtils
.isMessageTriggerSupported(
1180 commandPayload
.requestedMessage
1183 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1186 !OCPP16ServiceUtils
.isConnectorIdValid(
1188 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1189 commandPayload
.connectorId
1192 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1195 switch (commandPayload
.requestedMessage
) {
1196 case OCPP16MessageTrigger
.BootNotification
:
1198 chargingStation
.ocppRequestService
1199 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1201 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1202 chargingStation
.bootNotificationRequest
,
1203 { skipBufferingOnError
: true, triggerMessage
: true }
1205 .then((response
) => {
1206 chargingStation
.bootNotificationResponse
= response
;
1209 /* This is intentional */
1211 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1212 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1213 case OCPP16MessageTrigger
.Heartbeat
:
1215 chargingStation
.ocppRequestService
1216 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1218 OCPP16RequestCommand
.HEARTBEAT
,
1221 triggerMessage
: true,
1225 /* This is intentional */
1227 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1228 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1229 case OCPP16MessageTrigger
.StatusNotification
:
1231 if (commandPayload
?.connectorId
) {
1232 chargingStation
.ocppRequestService
1233 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1235 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1237 connectorId
: commandPayload
.connectorId
,
1238 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1239 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1242 triggerMessage
: true,
1246 /* This is intentional */
1249 for (const connectorId
of chargingStation
.connectors
.keys()) {
1250 chargingStation
.ocppRequestService
1252 OCPP16StatusNotificationRequest
,
1253 OCPP16StatusNotificationResponse
1256 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1259 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1260 status: chargingStation
.getConnectorStatus(connectorId
).status,
1263 triggerMessage
: true,
1267 /* This is intentional */
1271 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1272 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1274 return OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1277 return this.handleIncomingRequestError(
1279 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1281 { errorResponse
: OCPPConstants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}
1286 private handleRequestDataTransfer(
1287 chargingStation
: ChargingStation
,
1288 commandPayload
: OCPP16DataTransferRequest
1289 ): OCPP16DataTransferResponse
{
1291 if (Object.values(OCPP16DataTransferVendorId
).includes(commandPayload
.vendorId
)) {
1293 status: OCPP16DataTransferStatus
.ACCEPTED
,
1297 status: OCPP16DataTransferStatus
.UNKNOWN_VENDOR_ID
,
1300 return this.handleIncomingRequestError(
1302 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1304 { errorResponse
: OCPPConstants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}