1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { randomInt
} from
'node:crypto'
4 import { createWriteStream
, readdirSync
} from
'node:fs'
5 import { dirname
, extname
, join
, resolve
} from
'node:path'
6 import { fileURLToPath
, URL
} from
'node:url'
8 import type { ValidateFunction
} from
'ajv'
9 import { Client
, type FTPResponse
} from
'basic-ftp'
17 import { maxTime
} from
'date-fns/constants'
18 import { isEmpty
} from
'rambda'
19 import { create
} from
'tar'
22 canProceedChargingProfile
,
26 getConnectorChargingProfiles
,
27 prepareChargingProfileKind
,
28 removeExpiredReservations
,
29 setConfigurationKeyValue
30 } from
'../../../charging-station/index.js'
31 import { OCPPError
} from
'../../../exception/index.js'
33 type ChangeConfigurationRequest
,
34 type ChangeConfigurationResponse
,
39 type GetConfigurationRequest
,
40 type GetConfigurationResponse
,
41 type GetDiagnosticsRequest
,
42 type GetDiagnosticsResponse
,
43 type IncomingRequestHandler
,
45 type LogConfiguration
,
46 OCPP16AuthorizationStatus
,
47 OCPP16AvailabilityType
,
48 type OCPP16BootNotificationRequest
,
49 type OCPP16BootNotificationResponse
,
50 type OCPP16CancelReservationRequest
,
51 type OCPP16ChangeAvailabilityRequest
,
52 type OCPP16ChangeAvailabilityResponse
,
53 OCPP16ChargePointErrorCode
,
54 OCPP16ChargePointStatus
,
55 type OCPP16ChargingProfile
,
56 OCPP16ChargingProfilePurposeType
,
57 type OCPP16ChargingSchedule
,
58 type OCPP16ClearCacheRequest
,
59 type OCPP16ClearChargingProfileRequest
,
60 type OCPP16ClearChargingProfileResponse
,
61 type OCPP16DataTransferRequest
,
62 type OCPP16DataTransferResponse
,
63 OCPP16DataTransferVendorId
,
64 OCPP16DiagnosticsStatus
,
65 type OCPP16DiagnosticsStatusNotificationRequest
,
66 type OCPP16DiagnosticsStatusNotificationResponse
,
68 type OCPP16FirmwareStatusNotificationRequest
,
69 type OCPP16FirmwareStatusNotificationResponse
,
70 type OCPP16GetCompositeScheduleRequest
,
71 type OCPP16GetCompositeScheduleResponse
,
72 type OCPP16HeartbeatRequest
,
73 type OCPP16HeartbeatResponse
,
74 OCPP16IncomingRequestCommand
,
77 type OCPP16ReserveNowRequest
,
78 type OCPP16ReserveNowResponse
,
79 OCPP16StandardParametersKey
,
80 type OCPP16StartTransactionRequest
,
81 type OCPP16StartTransactionResponse
,
82 type OCPP16StatusNotificationRequest
,
83 type OCPP16StatusNotificationResponse
,
84 OCPP16StopTransactionReason
,
85 OCPP16SupportedFeatureProfiles
,
86 type OCPP16TriggerMessageRequest
,
87 type OCPP16TriggerMessageResponse
,
88 OCPP16TriggerMessageStatus
,
89 type OCPP16UpdateFirmwareRequest
,
90 type OCPP16UpdateFirmwareResponse
,
91 type OCPPConfigurationKey
,
93 type RemoteStartTransactionRequest
,
94 type RemoteStopTransactionRequest
,
95 ReservationTerminationReason
,
97 type SetChargingProfileRequest
,
98 type SetChargingProfileResponse
,
99 type UnlockConnectorRequest
,
100 type UnlockConnectorResponse
101 } from
'../../../types/index.js'
107 formatDurationMilliSeconds
,
113 } from
'../../../utils/index.js'
114 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService.js'
115 import { OCPP16Constants
} from
'./OCPP16Constants.js'
116 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils.js'
118 const moduleName
= 'OCPP16IncomingRequestService'
120 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
121 protected payloadValidateFunctions
: Map
<OCPP16IncomingRequestCommand
, ValidateFunction
<JsonType
>>
123 private readonly incomingRequestHandlers
: Map
<
124 OCPP16IncomingRequestCommand
,
125 IncomingRequestHandler
128 public constructor () {
129 // if (new.target.name === moduleName) {
130 // throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
132 super(OCPPVersion
.VERSION_16
)
133 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
135 OCPP16IncomingRequestCommand
.RESET
,
136 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
139 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
140 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
143 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
144 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
147 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
148 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
151 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
152 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
155 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
156 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
159 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
160 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
163 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
164 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
167 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
168 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
171 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
172 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
175 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
176 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
179 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
180 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
183 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
184 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
187 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
188 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
191 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
192 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
195 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
196 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
199 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
200 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
203 this.payloadValidateFunctions
= new Map
<
204 OCPP16IncomingRequestCommand
,
205 ValidateFunction
<JsonType
>
208 OCPP16IncomingRequestCommand
.RESET
,
211 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
212 'assets/json-schemas/ocpp/1.6/Reset.json',
220 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
223 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
224 'assets/json-schemas/ocpp/1.6/ClearCache.json',
232 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
235 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
236 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
244 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
247 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
248 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
256 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
259 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
260 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
268 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
271 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
272 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
280 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
283 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
284 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
292 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
295 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
296 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
304 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
307 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearChargingProfileRequest
>(
308 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
316 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
319 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
320 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
328 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
331 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
332 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
340 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
343 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
344 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
352 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
355 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
356 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
364 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
367 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
368 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
376 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
379 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
380 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
388 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
391 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
392 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
400 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
403 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
404 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
412 // Handle incoming request events
414 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
416 chargingStation
: ChargingStation
,
417 request
: RemoteStartTransactionRequest
,
418 response
: GenericResponse
420 if (response
.status === GenericStatus
.Accepted
) {
421 const { connectorId
, idTag
} = request
422 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
423 chargingStation
.getConnectorStatus(connectorId
!)!.transactionRemoteStarted
= true
424 chargingStation
.ocppRequestService
425 .requestHandler
<Partial
<OCPP16StartTransactionRequest
>, OCPP16StartTransactionResponse
>(
427 OCPP16RequestCommand
.START_TRANSACTION
,
434 if (response
.idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
436 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${
437 chargingStation.stationInfo?.chargingStationId
438 }#${connectorId} for idTag '${idTag}'`
442 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${
443 chargingStation.stationInfo?.chargingStationId
444 }#${connectorId} for idTag '${idTag}'`
448 .catch((error
: unknown
) => {
450 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`,
458 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
460 chargingStation
: ChargingStation
,
461 request
: RemoteStopTransactionRequest
,
462 response
: GenericResponse
464 if (response
.status === GenericStatus
.Accepted
) {
465 const { transactionId
} = request
466 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
467 const connectorId
= chargingStation
.getConnectorIdByTransactionId(transactionId
)!
468 OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
470 if (response
.status === GenericStatus
.Accepted
) {
472 `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED on ${
473 chargingStation.stationInfo?.chargingStationId
474 }#${connectorId} for transaction '${transactionId}'`
478 `${chargingStation.logPrefix()} Remote stop transaction REJECTED on ${
479 chargingStation.stationInfo?.chargingStationId
480 }#${connectorId} for transaction '${transactionId}'`
484 .catch((error
: unknown
) => {
486 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote stop transaction error:`,
494 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
496 chargingStation
: ChargingStation
,
497 request
: OCPP16TriggerMessageRequest
,
498 response
: OCPP16TriggerMessageResponse
500 if (response
.status !== OCPP16TriggerMessageStatus
.ACCEPTED
) {
503 const { requestedMessage
, connectorId
} = request
504 const errorHandler
= (error
: unknown
): void => {
506 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger ${requestedMessage} error:`,
510 switch (requestedMessage
) {
511 case OCPP16MessageTrigger
.BootNotification
:
512 chargingStation
.ocppRequestService
514 OCPP16BootNotificationRequest
,
515 OCPP16BootNotificationResponse
516 >(chargingStation
, OCPP16RequestCommand
.BOOT_NOTIFICATION
, chargingStation
.bootNotificationRequest
as OCPP16BootNotificationRequest
, { skipBufferingOnError
: true, triggerMessage
: true })
519 case OCPP16MessageTrigger
.Heartbeat
:
520 chargingStation
.ocppRequestService
521 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
523 OCPP16RequestCommand
.HEARTBEAT
,
531 case OCPP16MessageTrigger
.StatusNotification
:
532 if (connectorId
!= null) {
533 chargingStation
.ocppRequestService
534 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
536 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
539 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
540 status: chargingStation
.getConnectorStatus(connectorId
)
541 ?.status as OCPP16ChargePointStatus
548 } else if (chargingStation
.hasEvses
) {
549 for (const evseStatus
of chargingStation
.evses
.values()) {
550 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
551 chargingStation
.ocppRequestService
553 OCPP16StatusNotificationRequest
,
554 OCPP16StatusNotificationResponse
557 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
560 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
561 status: connectorStatus
.status as OCPP16ChargePointStatus
571 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
572 chargingStation
.ocppRequestService
574 OCPP16StatusNotificationRequest
,
575 OCPP16StatusNotificationResponse
578 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
581 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
582 status: connectorStatus
.status as OCPP16ChargePointStatus
595 this.validatePayload
= this.validatePayload
.bind(this)
598 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
599 chargingStation
: ChargingStation
,
601 commandName
: OCPP16IncomingRequestCommand
,
602 commandPayload
: ReqType
604 let response
: ResType
606 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
607 chargingStation
.inPendingState() &&
608 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
609 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
612 ErrorType
.SECURITY_ERROR
,
613 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
617 )} while the charging station is in pending state on the central server`,
623 chargingStation
.isRegistered() ||
624 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
625 chargingStation
.inUnknownState())
628 this.incomingRequestHandlers
.has(commandName
) &&
629 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
632 this.validatePayload(chargingStation
, commandName
, commandPayload
)
633 // Call the method to build the response
634 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
635 const incomingRequestHandler
= this.incomingRequestHandlers
.get(commandName
)!
636 if (isAsyncFunction(incomingRequestHandler
)) {
637 response
= (await incomingRequestHandler(chargingStation
, commandPayload
)) as ResType
639 response
= incomingRequestHandler(chargingStation
, commandPayload
) as ResType
644 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
652 ErrorType
.NOT_IMPLEMENTED
,
653 `'${commandName}' is not implemented to handle request PDU ${JSON.stringify(
664 ErrorType
.SECURITY_ERROR
,
665 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
669 )} while the charging station is not registered on the central server`,
674 // Send the built response
675 await chargingStation
.ocppRequestService
.sendResponse(
681 // Emit command name event to allow delayed handling
682 this.emit(commandName
, chargingStation
, commandPayload
, response
)
685 private validatePayload (
686 chargingStation
: ChargingStation
,
687 commandName
: OCPP16IncomingRequestCommand
,
688 commandPayload
: JsonType
690 if (this.payloadValidateFunctions
.has(commandName
)) {
691 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
694 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
699 // Simulate charging station restart
700 private handleRequestReset (
701 chargingStation
: ChargingStation
,
702 commandPayload
: ResetRequest
704 const { type } = commandPayload
706 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
707 .catch(Constants
.EMPTY_FUNCTION
)
709 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
710 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
711 chargingStation.stationInfo!.resetTime!
714 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
717 private async handleRequestUnlockConnector (
718 chargingStation
: ChargingStation
,
719 commandPayload
: UnlockConnectorRequest
720 ): Promise
<UnlockConnectorResponse
> {
721 const { connectorId
} = commandPayload
722 if (!chargingStation
.hasConnector(connectorId
)) {
724 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
726 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
728 if (connectorId
=== 0) {
729 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
730 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
732 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
733 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
735 OCPP16StopTransactionReason
.UNLOCK_COMMAND
737 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
738 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
740 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
742 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
745 OCPP16ChargePointStatus
.Available
747 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
750 private handleRequestGetConfiguration (
751 chargingStation
: ChargingStation
,
752 commandPayload
: GetConfigurationRequest
753 ): GetConfigurationResponse
{
754 const { key
} = commandPayload
755 const configurationKey
: OCPPConfigurationKey
[] = []
756 const unknownKey
: string[] = []
758 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
759 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
760 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
763 configurationKey
.push({
765 readonly: configKey
.readonly,
766 value
: configKey
.value
769 } else if (isNotEmptyArray(key
)) {
770 for (const k
of key
) {
771 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
772 if (keyFound
!= null) {
773 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
776 configurationKey
.push({
778 readonly: keyFound
.readonly,
779 value
: keyFound
.value
792 private handleRequestChangeConfiguration (
793 chargingStation
: ChargingStation
,
794 commandPayload
: ChangeConfigurationRequest
795 ): ChangeConfigurationResponse
{
796 const { key
, value
} = commandPayload
797 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
798 if (keyToChange
?.readonly === true) {
799 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
800 } else if (keyToChange
?.readonly === false) {
801 let valueChanged
= false
802 if (keyToChange
.value
!== value
) {
803 setConfigurationKeyValue(chargingStation
, key
, value
, true)
806 let triggerHeartbeatRestart
= false
808 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
809 OCPP16StandardParametersKey
.HeartBeatInterval
&&
812 setConfigurationKeyValue(
814 OCPP16StandardParametersKey
.HeartbeatInterval
,
817 triggerHeartbeatRestart
= true
820 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
821 OCPP16StandardParametersKey
.HeartbeatInterval
&&
824 setConfigurationKeyValue(
826 OCPP16StandardParametersKey
.HeartBeatInterval
,
829 triggerHeartbeatRestart
= true
831 if (triggerHeartbeatRestart
) {
832 chargingStation
.restartHeartbeat()
835 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
836 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
839 chargingStation
.restartWebSocketPing()
841 if (keyToChange
.reboot
=== true) {
842 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
844 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
846 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
849 private handleRequestSetChargingProfile (
850 chargingStation
: ChargingStation
,
851 commandPayload
: SetChargingProfileRequest
852 ): SetChargingProfileResponse
{
854 !OCPP16ServiceUtils
.checkFeatureProfile(
856 OCPP16SupportedFeatureProfiles
.SmartCharging
,
857 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
860 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
862 const { connectorId
, csChargingProfiles
} = commandPayload
863 if (!chargingStation
.hasConnector(connectorId
)) {
865 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
867 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
870 csChargingProfiles
.chargingProfilePurpose
===
871 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
874 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
877 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
881 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
883 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
885 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
887 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
889 connectorStatus
?.transactionStarted
=== false
892 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
894 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
897 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
899 connectorStatus
?.transactionStarted
=== true &&
900 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
903 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
904 csChargingProfiles.transactionId
905 } than the started transaction id ${connectorStatus.transactionId}`
907 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
909 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
911 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
914 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
917 private handleRequestGetCompositeSchedule (
918 chargingStation
: ChargingStation
,
919 commandPayload
: OCPP16GetCompositeScheduleRequest
920 ): OCPP16GetCompositeScheduleResponse
{
922 !OCPP16ServiceUtils
.checkFeatureProfile(
924 OCPP16SupportedFeatureProfiles
.SmartCharging
,
925 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
928 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
930 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
931 if (!chargingStation
.hasConnector(connectorId
)) {
933 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
935 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
937 if (connectorId
=== 0) {
939 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
941 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
943 if (chargingRateUnit
!= null) {
945 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
948 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
950 isEmpty(connectorStatus
?.chargingProfiles
) &&
951 isEmpty(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
953 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
955 const currentDate
= new Date()
956 const compositeScheduleInterval
: Interval
= {
958 end
: addSeconds(currentDate
, duration
)
960 // Get charging profiles sorted by connector id then stack level
961 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
965 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
966 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
967 for (const chargingProfile
of chargingProfiles
) {
968 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
970 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
971 chargingProfile.chargingProfileId
972 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
974 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
975 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
977 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
979 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
980 chargingProfile.chargingProfileId
981 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
983 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
984 chargingProfile
.chargingSchedule
.startSchedule
987 if (chargingProfile
.chargingSchedule
.duration
== null) {
989 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
990 chargingProfile.chargingProfileId
991 } has no duration defined and will be set to the maximum time allowed`
993 // OCPP specifies that if duration is not defined, it should be infinite
994 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
996 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
997 chargingProfile
.chargingSchedule
.startSchedule
!
1001 !prepareChargingProfileKind(
1004 compositeScheduleInterval
.start
,
1005 chargingStation
.logPrefix()
1011 !canProceedChargingProfile(
1013 compositeScheduleInterval
.start
,
1014 chargingStation
.logPrefix()
1019 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
1020 previousCompositeSchedule
,
1021 chargingProfile
.chargingSchedule
,
1022 compositeScheduleInterval
1024 previousCompositeSchedule
= compositeSchedule
1026 if (compositeSchedule
!= null) {
1028 status: GenericStatus
.Accepted
,
1029 scheduleStart
: compositeSchedule
.startSchedule
,
1031 chargingSchedule
: compositeSchedule
1034 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1037 private handleRequestClearChargingProfile (
1038 chargingStation
: ChargingStation
,
1039 commandPayload
: OCPP16ClearChargingProfileRequest
1040 ): OCPP16ClearChargingProfileResponse
{
1042 !OCPP16ServiceUtils
.checkFeatureProfile(
1044 OCPP16SupportedFeatureProfiles
.SmartCharging
,
1045 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
1048 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1050 const { connectorId
} = commandPayload
1051 if (connectorId
!= null) {
1052 if (!chargingStation
.hasConnector(connectorId
)) {
1054 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
1056 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1058 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1059 if (isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1060 connectorStatus
.chargingProfiles
= []
1062 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1064 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1067 let clearedCP
= false
1068 if (chargingStation
.hasEvses
) {
1069 for (const evseStatus
of chargingStation
.evses
.values()) {
1070 for (const status of evseStatus
.connectors
.values()) {
1071 const clearedConnectorCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1074 status.chargingProfiles
1076 if (clearedConnectorCP
&& !clearedCP
) {
1082 for (const id
of chargingStation
.connectors
.keys()) {
1083 const clearedConnectorCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1086 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1088 if (clearedConnectorCP
&& !clearedCP
) {
1094 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1097 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1100 private async handleRequestChangeAvailability (
1101 chargingStation
: ChargingStation
,
1102 commandPayload
: OCPP16ChangeAvailabilityRequest
1103 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1104 const { connectorId
, type } = commandPayload
1105 if (!chargingStation
.hasConnector(connectorId
)) {
1107 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1109 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1111 const chargePointStatus
: OCPP16ChargePointStatus
=
1112 type === OCPP16AvailabilityType
.Operative
1113 ? OCPP16ChargePointStatus
.Available
1114 : OCPP16ChargePointStatus
.Unavailable
1115 if (connectorId
=== 0) {
1116 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1117 if (chargingStation
.hasEvses
) {
1118 for (const evseStatus
of chargingStation
.evses
.values()) {
1119 response
= await OCPP16ServiceUtils
.changeAvailability(
1121 [...evseStatus
.connectors
.keys()],
1127 response
= await OCPP16ServiceUtils
.changeAvailability(
1129 [...chargingStation
.connectors
.keys()],
1134 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1138 (chargingStation
.isChargingStationAvailable() ||
1139 (!chargingStation
.isChargingStationAvailable() &&
1140 type === OCPP16AvailabilityType
.Inoperative
))
1142 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1143 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1144 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1145 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1147 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1148 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1149 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1154 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1156 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1159 private async handleRequestRemoteStartTransaction (
1160 chargingStation
: ChargingStation
,
1161 commandPayload
: RemoteStartTransactionRequest
1162 ): Promise
<GenericResponse
> {
1163 if (commandPayload
.connectorId
== null) {
1165 commandPayload
.connectorId
= randomInt(1, chargingStation
.getNumberOfConnectors())
1167 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
1169 OCPP16ServiceUtils
.hasReservation(
1171 commandPayload
.connectorId
,
1172 commandPayload
.idTag
1176 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1177 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1178 return this.notifyRemoteStartTransactionRejected(
1180 transactionConnectorId
,
1185 !chargingStation
.isChargingStationAvailable() ||
1186 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1188 return this.notifyRemoteStartTransactionRejected(
1190 transactionConnectorId
,
1194 // idTag authorization check required
1196 chargingStation
.getAuthorizeRemoteTxRequests() &&
1197 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1199 return this.notifyRemoteStartTransactionRejected(
1201 transactionConnectorId
,
1206 chargingProfile
!= null &&
1207 !this.setRemoteStartTransactionChargingProfile(
1209 transactionConnectorId
,
1213 return this.notifyRemoteStartTransactionRejected(
1215 transactionConnectorId
,
1220 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${
1221 chargingStation.stationInfo?.chargingStationId
1222 }#${transactionConnectorId}}, idTag '${idTag}'`
1224 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1227 private notifyRemoteStartTransactionRejected (
1228 chargingStation
: ChargingStation
,
1229 connectorId
: number,
1231 ): GenericResponse
{
1232 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1234 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${
1235 chargingStation.stationInfo?.chargingStationId
1236 }#${connectorId}, idTag '${idTag}', availability '${
1237 connectorStatus?.availability
1238 }', status '${connectorStatus?.status}'`
1240 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1243 private setRemoteStartTransactionChargingProfile (
1244 chargingStation
: ChargingStation
,
1245 connectorId
: number,
1246 chargingProfile
: OCPP16ChargingProfile
1248 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1249 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1251 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on ${
1252 chargingStation.stationInfo?.chargingStationId
1259 `${chargingStation.logPrefix()} Not allowed to set ${
1260 chargingProfile.chargingProfilePurpose
1261 } charging profile(s) at remote start transaction`
1266 private handleRequestRemoteStopTransaction (
1267 chargingStation
: ChargingStation
,
1268 commandPayload
: RemoteStopTransactionRequest
1269 ): GenericResponse
{
1270 const { transactionId
} = commandPayload
1271 if (chargingStation
.getConnectorIdByTransactionId(transactionId
) != null) {
1273 `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED for transactionId '${transactionId}'`
1275 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1278 `${chargingStation.logPrefix()} Remote stop transaction REJECTED for transactionId '${transactionId}'`
1280 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1283 private handleRequestUpdateFirmware (
1284 chargingStation
: ChargingStation
,
1285 commandPayload
: OCPP16UpdateFirmwareRequest
1286 ): OCPP16UpdateFirmwareResponse
{
1288 !OCPP16ServiceUtils
.checkFeatureProfile(
1290 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1291 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1295 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1297 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1299 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1300 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1301 const { retrieveDate
} = commandPayload
1303 chargingStation
.stationInfo
?.firmwareStatus
!= null &&
1304 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1307 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1309 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1311 const now
= Date.now()
1312 if (retrieveDate
.getTime() <= now
) {
1313 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1316 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1317 }, retrieveDate
.getTime() - now
)
1319 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1322 private async updateFirmwareSimulation (
1323 chargingStation
: ChargingStation
,
1327 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1330 if (chargingStation
.hasEvses
) {
1331 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1333 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1334 if (connectorStatus
.transactionStarted
=== false) {
1335 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1338 OCPP16ChargePointStatus
.Unavailable
1345 for (const connectorId
of chargingStation
.connectors
.keys()) {
1348 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1350 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1353 OCPP16ChargePointStatus
.Unavailable
1358 await chargingStation
.ocppRequestService
.requestHandler
<
1359 OCPP16FirmwareStatusNotificationRequest
,
1360 OCPP16FirmwareStatusNotificationResponse
1361 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1362 status: OCPP16FirmwareStatus
.Downloading
1364 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1365 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1367 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1368 OCPP16FirmwareStatus
.DownloadFailed
1370 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1371 await chargingStation
.ocppRequestService
.requestHandler
<
1372 OCPP16FirmwareStatusNotificationRequest
,
1373 OCPP16FirmwareStatusNotificationResponse
1374 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1375 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1377 chargingStation
.stationInfo
.firmwareStatus
=
1378 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1381 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1382 await chargingStation
.ocppRequestService
.requestHandler
<
1383 OCPP16FirmwareStatusNotificationRequest
,
1384 OCPP16FirmwareStatusNotificationResponse
1385 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1386 status: OCPP16FirmwareStatus
.Downloaded
1388 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1389 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1390 let wasTransactionsStarted
= false
1391 let transactionsStarted
: boolean
1393 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1394 if (runningTransactions
> 0) {
1395 const waitTime
= secondsToMilliseconds(15)
1397 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1399 )} before continuing firmware update simulation`
1401 await sleep(waitTime
)
1402 transactionsStarted
= true
1403 wasTransactionsStarted
= true
1405 if (chargingStation
.hasEvses
) {
1406 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1408 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1409 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1410 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1413 OCPP16ChargePointStatus
.Unavailable
1420 for (const connectorId
of chargingStation
.connectors
.keys()) {
1423 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1424 OCPP16ChargePointStatus
.Unavailable
1426 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1429 OCPP16ChargePointStatus
.Unavailable
1434 transactionsStarted
= false
1436 } while (transactionsStarted
)
1437 !wasTransactionsStarted
&& (await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
))))
1438 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1441 await chargingStation
.ocppRequestService
.requestHandler
<
1442 OCPP16FirmwareStatusNotificationRequest
,
1443 OCPP16FirmwareStatusNotificationResponse
1444 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1445 status: OCPP16FirmwareStatus
.Installing
1447 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1448 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1450 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1451 OCPP16FirmwareStatus
.InstallationFailed
1453 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1454 await chargingStation
.ocppRequestService
.requestHandler
<
1455 OCPP16FirmwareStatusNotificationRequest
,
1456 OCPP16FirmwareStatusNotificationResponse
1457 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1458 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1460 chargingStation
.stationInfo
.firmwareStatus
=
1461 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1464 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1465 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1466 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1470 private async handleRequestGetDiagnostics (
1471 chargingStation
: ChargingStation
,
1472 commandPayload
: GetDiagnosticsRequest
1473 ): Promise
<GetDiagnosticsResponse
> {
1475 !OCPP16ServiceUtils
.checkFeatureProfile(
1477 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1478 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1482 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1484 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1486 const { location
} = commandPayload
1487 const uri
= new URL(location
)
1488 if (uri
.protocol
.startsWith('ftp:')) {
1489 let ftpClient
: Client
| undefined
1491 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
1492 ConfigurationSection
.log
1494 const logFiles
= readdirSync(
1495 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1496 resolve((fileURLToPath(import.meta
.url
), '../', dirname(logConfiguration
.file
!)))
1498 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1499 .filter(file
=> file
.endsWith(extname(logConfiguration
.file
!)))
1500 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1501 .map(file
=> join(dirname(logConfiguration
.file
!), file
))
1502 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1503 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1504 ftpClient
= new Client()
1505 const accessResponse
= await ftpClient
.access({
1507 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1508 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1509 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1511 let uploadResponse
: FTPResponse
| undefined
1512 if (accessResponse
.code
=== 220) {
1513 ftpClient
.trackProgress(info
=> {
1515 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1517 } bytes transferred from diagnostics archive ${info.name}`
1519 chargingStation
.ocppRequestService
1521 OCPP16DiagnosticsStatusNotificationRequest
,
1522 OCPP16DiagnosticsStatusNotificationResponse
1523 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1524 status: OCPP16DiagnosticsStatus
.Uploading
1526 .catch((error
: unknown
) => {
1528 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1529 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1535 uploadResponse
= await ftpClient
.uploadFrom(
1536 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1537 `${uri.pathname}${diagnosticsArchive}`
1539 if (uploadResponse
.code
=== 226) {
1540 await chargingStation
.ocppRequestService
.requestHandler
<
1541 OCPP16DiagnosticsStatusNotificationRequest
,
1542 OCPP16DiagnosticsStatusNotificationResponse
1543 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1544 status: OCPP16DiagnosticsStatus
.Uploaded
1547 return { fileName
: diagnosticsArchive
}
1549 throw new OCPPError(
1550 ErrorType
.GENERIC_ERROR
,
1551 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1552 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1555 throw new OCPPError(
1556 ErrorType
.GENERIC_ERROR
,
1557 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1558 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1561 await chargingStation
.ocppRequestService
.requestHandler
<
1562 OCPP16DiagnosticsStatusNotificationRequest
,
1563 OCPP16DiagnosticsStatusNotificationResponse
1564 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1565 status: OCPP16DiagnosticsStatus
.UploadFailed
1568 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1569 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1571 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1573 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1578 `${chargingStation.logPrefix()} Unsupported protocol ${
1580 } to transfer the diagnostic logs archive`
1582 await chargingStation
.ocppRequestService
.requestHandler
<
1583 OCPP16DiagnosticsStatusNotificationRequest
,
1584 OCPP16DiagnosticsStatusNotificationResponse
1585 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1586 status: OCPP16DiagnosticsStatus
.UploadFailed
1588 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1592 private handleRequestTriggerMessage (
1593 chargingStation
: ChargingStation
,
1594 commandPayload
: OCPP16TriggerMessageRequest
1595 ): OCPP16TriggerMessageResponse
{
1596 const { requestedMessage
, connectorId
} = commandPayload
1598 !OCPP16ServiceUtils
.checkFeatureProfile(
1600 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1601 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1603 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1605 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1608 !OCPP16ServiceUtils
.isConnectorIdValid(
1610 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1611 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1615 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1617 switch (requestedMessage
) {
1618 case OCPP16MessageTrigger
.BootNotification
:
1619 case OCPP16MessageTrigger
.Heartbeat
:
1620 case OCPP16MessageTrigger
.StatusNotification
:
1621 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1623 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1627 private handleRequestDataTransfer (
1628 chargingStation
: ChargingStation
,
1629 commandPayload
: OCPP16DataTransferRequest
1630 ): OCPP16DataTransferResponse
{
1631 const { vendorId
} = commandPayload
1633 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1634 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1636 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1638 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1639 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1641 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1643 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1648 private async handleRequestReserveNow (
1649 chargingStation
: ChargingStation
,
1650 commandPayload
: OCPP16ReserveNowRequest
1651 ): Promise
<OCPP16ReserveNowResponse
> {
1653 !OCPP16ServiceUtils
.checkFeatureProfile(
1655 OCPP16SupportedFeatureProfiles
.Reservation
,
1656 OCPP16IncomingRequestCommand
.RESERVE_NOW
1659 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1661 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1662 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1663 const { reservationId
, idTag
, connectorId
} = commandPayload
1664 let response
: OCPP16ReserveNowResponse
1666 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1667 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1669 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1670 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1672 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1673 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1675 await removeExpiredReservations(chargingStation
)
1676 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1677 case OCPP16ChargePointStatus
.Faulted
:
1678 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1680 case OCPP16ChargePointStatus
.Preparing
:
1681 case OCPP16ChargePointStatus
.Charging
:
1682 case OCPP16ChargePointStatus
.SuspendedEV
:
1683 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1684 case OCPP16ChargePointStatus
.Finishing
:
1685 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1687 case OCPP16ChargePointStatus
.Unavailable
:
1688 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1690 case OCPP16ChargePointStatus
.Reserved
:
1691 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1692 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1695 // eslint-disable-next-line no-fallthrough
1697 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1698 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1701 await chargingStation
.addReservation({
1702 id
: commandPayload
.reservationId
,
1705 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1710 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1711 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1712 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1713 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1715 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1717 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1722 private async handleRequestCancelReservation (
1723 chargingStation
: ChargingStation
,
1724 commandPayload
: OCPP16CancelReservationRequest
1725 ): Promise
<GenericResponse
> {
1727 !OCPP16ServiceUtils
.checkFeatureProfile(
1729 OCPP16SupportedFeatureProfiles
.Reservation
,
1730 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1733 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1736 const { reservationId
} = commandPayload
1737 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1738 if (reservation
== null) {
1740 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1742 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1744 await chargingStation
.removeReservation(
1746 ReservationTerminationReason
.RESERVATION_CANCELED
1748 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1750 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1751 return this.handleIncomingRequestError
<GenericResponse
>(
1753 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1756 errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED