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
.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
513 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
515 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
516 chargingStation
.bootNotificationRequest
as OCPP16BootNotificationRequest
,
517 { skipBufferingOnError
: true, triggerMessage
: true }
520 chargingStation
.bootNotificationResponse
= response
524 case OCPP16MessageTrigger
.Heartbeat
:
525 chargingStation
.ocppRequestService
526 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
528 OCPP16RequestCommand
.HEARTBEAT
,
536 case OCPP16MessageTrigger
.StatusNotification
:
537 if (connectorId
!= null) {
538 chargingStation
.ocppRequestService
539 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
541 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
544 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
545 status: chargingStation
.getConnectorStatus(connectorId
)
546 ?.status as OCPP16ChargePointStatus
553 } else if (chargingStation
.hasEvses
) {
554 for (const evseStatus
of chargingStation
.evses
.values()) {
555 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
556 chargingStation
.ocppRequestService
558 OCPP16StatusNotificationRequest
,
559 OCPP16StatusNotificationResponse
562 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
565 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
566 status: connectorStatus
.status as OCPP16ChargePointStatus
576 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
577 chargingStation
.ocppRequestService
579 OCPP16StatusNotificationRequest
,
580 OCPP16StatusNotificationResponse
583 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
586 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
587 status: connectorStatus
.status as OCPP16ChargePointStatus
600 this.validatePayload
= this.validatePayload
.bind(this)
603 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
604 chargingStation
: ChargingStation
,
606 commandName
: OCPP16IncomingRequestCommand
,
607 commandPayload
: ReqType
609 let response
: ResType
611 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
612 chargingStation
.inPendingState() &&
613 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
614 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
617 ErrorType
.SECURITY_ERROR
,
618 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
622 )} while the charging station is in pending state on the central server`,
628 chargingStation
.isRegistered() ||
629 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
630 chargingStation
.inUnknownState())
633 this.incomingRequestHandlers
.has(commandName
) &&
634 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
637 this.validatePayload(chargingStation
, commandName
, commandPayload
)
638 // Call the method to build the response
639 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
640 const incomingRequestHandler
= this.incomingRequestHandlers
.get(commandName
)!
641 if (isAsyncFunction(incomingRequestHandler
)) {
642 response
= (await incomingRequestHandler(chargingStation
, commandPayload
)) as ResType
644 response
= incomingRequestHandler(chargingStation
, commandPayload
) as ResType
649 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
657 ErrorType
.NOT_IMPLEMENTED
,
658 `'${commandName}' is not implemented to handle request PDU ${JSON.stringify(
669 ErrorType
.SECURITY_ERROR
,
670 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
674 )} while the charging station is not registered on the central server`,
679 // Send the built response
680 await chargingStation
.ocppRequestService
.sendResponse(
686 // Emit command name event to allow delayed handling
687 this.emit(commandName
, chargingStation
, commandPayload
, response
)
690 private validatePayload (
691 chargingStation
: ChargingStation
,
692 commandName
: OCPP16IncomingRequestCommand
,
693 commandPayload
: JsonType
695 if (this.payloadValidateFunctions
.has(commandName
)) {
696 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
699 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
704 // Simulate charging station restart
705 private handleRequestReset (
706 chargingStation
: ChargingStation
,
707 commandPayload
: ResetRequest
709 const { type } = commandPayload
711 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
712 .catch(Constants
.EMPTY_FUNCTION
)
714 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
715 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
716 chargingStation.stationInfo!.resetTime!
719 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
722 private async handleRequestUnlockConnector (
723 chargingStation
: ChargingStation
,
724 commandPayload
: UnlockConnectorRequest
725 ): Promise
<UnlockConnectorResponse
> {
726 const { connectorId
} = commandPayload
727 if (!chargingStation
.hasConnector(connectorId
)) {
729 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
731 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
733 if (connectorId
=== 0) {
734 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
735 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
737 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
738 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
740 OCPP16StopTransactionReason
.UNLOCK_COMMAND
742 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
743 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
745 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
747 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
750 OCPP16ChargePointStatus
.Available
752 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
755 private handleRequestGetConfiguration (
756 chargingStation
: ChargingStation
,
757 commandPayload
: GetConfigurationRequest
758 ): GetConfigurationResponse
{
759 const { key
} = commandPayload
760 const configurationKey
: OCPPConfigurationKey
[] = []
761 const unknownKey
: string[] = []
763 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
764 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
765 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
768 configurationKey
.push({
770 readonly: configKey
.readonly,
771 value
: configKey
.value
774 } else if (isNotEmptyArray(key
)) {
775 for (const k
of key
) {
776 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
777 if (keyFound
!= null) {
778 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
781 configurationKey
.push({
783 readonly: keyFound
.readonly,
784 value
: keyFound
.value
797 private handleRequestChangeConfiguration (
798 chargingStation
: ChargingStation
,
799 commandPayload
: ChangeConfigurationRequest
800 ): ChangeConfigurationResponse
{
801 const { key
, value
} = commandPayload
802 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
803 if (keyToChange
?.readonly === true) {
804 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
805 } else if (keyToChange
?.readonly === false) {
806 let valueChanged
= false
807 if (keyToChange
.value
!== value
) {
808 setConfigurationKeyValue(chargingStation
, key
, value
, true)
811 let triggerHeartbeatRestart
= false
813 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
814 OCPP16StandardParametersKey
.HeartBeatInterval
&&
817 setConfigurationKeyValue(
819 OCPP16StandardParametersKey
.HeartbeatInterval
,
822 triggerHeartbeatRestart
= true
825 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
826 OCPP16StandardParametersKey
.HeartbeatInterval
&&
829 setConfigurationKeyValue(
831 OCPP16StandardParametersKey
.HeartBeatInterval
,
834 triggerHeartbeatRestart
= true
836 if (triggerHeartbeatRestart
) {
837 chargingStation
.restartHeartbeat()
840 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
841 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
844 chargingStation
.restartWebSocketPing()
846 if (keyToChange
.reboot
=== true) {
847 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
849 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
851 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
854 private handleRequestSetChargingProfile (
855 chargingStation
: ChargingStation
,
856 commandPayload
: SetChargingProfileRequest
857 ): SetChargingProfileResponse
{
859 !OCPP16ServiceUtils
.checkFeatureProfile(
861 OCPP16SupportedFeatureProfiles
.SmartCharging
,
862 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
865 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
867 const { connectorId
, csChargingProfiles
} = commandPayload
868 if (!chargingStation
.hasConnector(connectorId
)) {
870 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
872 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
875 csChargingProfiles
.chargingProfilePurpose
===
876 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
879 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
882 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
886 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
888 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
890 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
892 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
894 connectorStatus
?.transactionStarted
=== false
897 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
899 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
902 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
904 connectorStatus
?.transactionStarted
=== true &&
905 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
908 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
909 csChargingProfiles.transactionId
910 } than the started transaction id ${connectorStatus.transactionId}`
912 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
914 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
916 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
919 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
922 private handleRequestGetCompositeSchedule (
923 chargingStation
: ChargingStation
,
924 commandPayload
: OCPP16GetCompositeScheduleRequest
925 ): OCPP16GetCompositeScheduleResponse
{
927 !OCPP16ServiceUtils
.checkFeatureProfile(
929 OCPP16SupportedFeatureProfiles
.SmartCharging
,
930 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
933 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
935 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
936 if (!chargingStation
.hasConnector(connectorId
)) {
938 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
940 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
942 if (connectorId
=== 0) {
944 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
946 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
948 if (chargingRateUnit
!= null) {
950 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
953 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
955 isEmpty(connectorStatus
?.chargingProfiles
) &&
956 isEmpty(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
958 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
960 const currentDate
= new Date()
961 const compositeScheduleInterval
: Interval
= {
963 end
: addSeconds(currentDate
, duration
)
965 // Get charging profiles sorted by connector id then stack level
966 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
970 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
971 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
972 for (const chargingProfile
of chargingProfiles
) {
973 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
975 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
976 chargingProfile.chargingProfileId
977 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
979 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
980 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
982 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
984 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
985 chargingProfile.chargingProfileId
986 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
988 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
989 chargingProfile
.chargingSchedule
.startSchedule
992 if (chargingProfile
.chargingSchedule
.duration
== null) {
994 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
995 chargingProfile.chargingProfileId
996 } has no duration defined and will be set to the maximum time allowed`
998 // OCPP specifies that if duration is not defined, it should be infinite
999 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
1001 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1002 chargingProfile
.chargingSchedule
.startSchedule
!
1006 !prepareChargingProfileKind(
1009 compositeScheduleInterval
.start
,
1010 chargingStation
.logPrefix()
1016 !canProceedChargingProfile(
1018 compositeScheduleInterval
.start
,
1019 chargingStation
.logPrefix()
1024 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
1025 previousCompositeSchedule
,
1026 chargingProfile
.chargingSchedule
,
1027 compositeScheduleInterval
1029 previousCompositeSchedule
= compositeSchedule
1031 if (compositeSchedule
!= null) {
1033 status: GenericStatus
.Accepted
,
1034 scheduleStart
: compositeSchedule
.startSchedule
,
1036 chargingSchedule
: compositeSchedule
1039 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1042 private handleRequestClearChargingProfile (
1043 chargingStation
: ChargingStation
,
1044 commandPayload
: OCPP16ClearChargingProfileRequest
1045 ): OCPP16ClearChargingProfileResponse
{
1047 !OCPP16ServiceUtils
.checkFeatureProfile(
1049 OCPP16SupportedFeatureProfiles
.SmartCharging
,
1050 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
1053 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1055 const { connectorId
} = commandPayload
1056 if (connectorId
!= null) {
1057 if (!chargingStation
.hasConnector(connectorId
)) {
1059 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
1061 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1063 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1064 if (isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1065 connectorStatus
.chargingProfiles
= []
1067 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1069 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1072 let clearedCP
= false
1073 if (chargingStation
.hasEvses
) {
1074 for (const evseStatus
of chargingStation
.evses
.values()) {
1075 for (const status of evseStatus
.connectors
.values()) {
1076 const clearedConnectorCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1079 status.chargingProfiles
1081 if (clearedConnectorCP
&& !clearedCP
) {
1087 for (const id
of chargingStation
.connectors
.keys()) {
1088 const clearedConnectorCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1091 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1093 if (clearedConnectorCP
&& !clearedCP
) {
1099 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1102 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1105 private async handleRequestChangeAvailability (
1106 chargingStation
: ChargingStation
,
1107 commandPayload
: OCPP16ChangeAvailabilityRequest
1108 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1109 const { connectorId
, type } = commandPayload
1110 if (!chargingStation
.hasConnector(connectorId
)) {
1112 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1114 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1116 const chargePointStatus
: OCPP16ChargePointStatus
=
1117 type === OCPP16AvailabilityType
.Operative
1118 ? OCPP16ChargePointStatus
.Available
1119 : OCPP16ChargePointStatus
.Unavailable
1120 if (connectorId
=== 0) {
1121 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1122 if (chargingStation
.hasEvses
) {
1123 for (const evseStatus
of chargingStation
.evses
.values()) {
1124 response
= await OCPP16ServiceUtils
.changeAvailability(
1126 [...evseStatus
.connectors
.keys()],
1132 response
= await OCPP16ServiceUtils
.changeAvailability(
1134 [...chargingStation
.connectors
.keys()],
1139 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1143 (chargingStation
.isChargingStationAvailable() ||
1144 (!chargingStation
.isChargingStationAvailable() &&
1145 type === OCPP16AvailabilityType
.Inoperative
))
1147 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1148 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1149 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1150 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1152 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1153 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1154 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1159 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1161 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1164 private async handleRequestRemoteStartTransaction (
1165 chargingStation
: ChargingStation
,
1166 commandPayload
: RemoteStartTransactionRequest
1167 ): Promise
<GenericResponse
> {
1168 if (commandPayload
.connectorId
== null) {
1170 commandPayload
.connectorId
= randomInt(1, chargingStation
.getNumberOfConnectors())
1172 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
1174 OCPP16ServiceUtils
.hasReservation(
1176 commandPayload
.connectorId
,
1177 commandPayload
.idTag
1181 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1182 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1183 return this.notifyRemoteStartTransactionRejected(
1185 transactionConnectorId
,
1190 !chargingStation
.isChargingStationAvailable() ||
1191 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1193 return this.notifyRemoteStartTransactionRejected(
1195 transactionConnectorId
,
1199 // idTag authorization check required
1201 chargingStation
.getAuthorizeRemoteTxRequests() &&
1202 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1204 return this.notifyRemoteStartTransactionRejected(
1206 transactionConnectorId
,
1211 chargingProfile
!= null &&
1212 !this.setRemoteStartTransactionChargingProfile(
1214 transactionConnectorId
,
1218 return this.notifyRemoteStartTransactionRejected(
1220 transactionConnectorId
,
1225 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${
1226 chargingStation.stationInfo?.chargingStationId
1227 }#${transactionConnectorId}}, idTag '${idTag}'`
1229 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1232 private notifyRemoteStartTransactionRejected (
1233 chargingStation
: ChargingStation
,
1234 connectorId
: number,
1236 ): GenericResponse
{
1237 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1239 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${
1240 chargingStation.stationInfo?.chargingStationId
1241 }#${connectorId}, idTag '${idTag}', availability '${
1242 connectorStatus?.availability
1243 }', status '${connectorStatus?.status}'`
1245 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1248 private setRemoteStartTransactionChargingProfile (
1249 chargingStation
: ChargingStation
,
1250 connectorId
: number,
1251 chargingProfile
: OCPP16ChargingProfile
1253 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1254 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1256 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on ${
1257 chargingStation.stationInfo?.chargingStationId
1264 `${chargingStation.logPrefix()} Not allowed to set ${
1265 chargingProfile.chargingProfilePurpose
1266 } charging profile(s) at remote start transaction`
1271 private handleRequestRemoteStopTransaction (
1272 chargingStation
: ChargingStation
,
1273 commandPayload
: RemoteStopTransactionRequest
1274 ): GenericResponse
{
1275 const { transactionId
} = commandPayload
1276 if (chargingStation
.getConnectorIdByTransactionId(transactionId
) != null) {
1278 `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED for transactionId '${transactionId}'`
1280 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1283 `${chargingStation.logPrefix()} Remote stop transaction REJECTED for transactionId '${transactionId}'`
1285 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1288 private handleRequestUpdateFirmware (
1289 chargingStation
: ChargingStation
,
1290 commandPayload
: OCPP16UpdateFirmwareRequest
1291 ): OCPP16UpdateFirmwareResponse
{
1293 !OCPP16ServiceUtils
.checkFeatureProfile(
1295 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1296 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1300 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1302 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1304 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1305 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1306 const { retrieveDate
} = commandPayload
1307 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1309 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1311 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1313 const now
= Date.now()
1314 if (retrieveDate
.getTime() <= now
) {
1315 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1318 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1319 }, retrieveDate
.getTime() - now
)
1321 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1324 private async updateFirmwareSimulation (
1325 chargingStation
: ChargingStation
,
1329 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1332 if (chargingStation
.hasEvses
) {
1333 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1335 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1336 if (connectorStatus
.transactionStarted
=== false) {
1337 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1340 OCPP16ChargePointStatus
.Unavailable
1347 for (const connectorId
of chargingStation
.connectors
.keys()) {
1350 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1352 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1355 OCPP16ChargePointStatus
.Unavailable
1360 await chargingStation
.ocppRequestService
.requestHandler
<
1361 OCPP16FirmwareStatusNotificationRequest
,
1362 OCPP16FirmwareStatusNotificationResponse
1363 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1364 status: OCPP16FirmwareStatus
.Downloading
1366 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1367 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1369 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1370 OCPP16FirmwareStatus
.DownloadFailed
1372 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1373 await chargingStation
.ocppRequestService
.requestHandler
<
1374 OCPP16FirmwareStatusNotificationRequest
,
1375 OCPP16FirmwareStatusNotificationResponse
1376 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1377 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1379 chargingStation
.stationInfo
.firmwareStatus
=
1380 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1383 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1384 await chargingStation
.ocppRequestService
.requestHandler
<
1385 OCPP16FirmwareStatusNotificationRequest
,
1386 OCPP16FirmwareStatusNotificationResponse
1387 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1388 status: OCPP16FirmwareStatus
.Downloaded
1390 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1391 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1392 let wasTransactionsStarted
= false
1393 let transactionsStarted
: boolean
1395 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1396 if (runningTransactions
> 0) {
1397 const waitTime
= secondsToMilliseconds(15)
1399 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1401 )} before continuing firmware update simulation`
1403 await sleep(waitTime
)
1404 transactionsStarted
= true
1405 wasTransactionsStarted
= true
1407 if (chargingStation
.hasEvses
) {
1408 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1410 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1411 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1412 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1415 OCPP16ChargePointStatus
.Unavailable
1422 for (const connectorId
of chargingStation
.connectors
.keys()) {
1425 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1426 OCPP16ChargePointStatus
.Unavailable
1428 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1431 OCPP16ChargePointStatus
.Unavailable
1436 transactionsStarted
= false
1438 } while (transactionsStarted
)
1439 !wasTransactionsStarted
&& (await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
))))
1440 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1443 await chargingStation
.ocppRequestService
.requestHandler
<
1444 OCPP16FirmwareStatusNotificationRequest
,
1445 OCPP16FirmwareStatusNotificationResponse
1446 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1447 status: OCPP16FirmwareStatus
.Installing
1449 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1450 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1452 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1453 OCPP16FirmwareStatus
.InstallationFailed
1455 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1456 await chargingStation
.ocppRequestService
.requestHandler
<
1457 OCPP16FirmwareStatusNotificationRequest
,
1458 OCPP16FirmwareStatusNotificationResponse
1459 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1460 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1462 chargingStation
.stationInfo
.firmwareStatus
=
1463 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1466 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1467 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1468 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1472 private async handleRequestGetDiagnostics (
1473 chargingStation
: ChargingStation
,
1474 commandPayload
: GetDiagnosticsRequest
1475 ): Promise
<GetDiagnosticsResponse
> {
1477 !OCPP16ServiceUtils
.checkFeatureProfile(
1479 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1480 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1484 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1486 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1488 const { location
} = commandPayload
1489 const uri
= new URL(location
)
1490 if (uri
.protocol
.startsWith('ftp:')) {
1491 let ftpClient
: Client
| undefined
1493 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
1494 ConfigurationSection
.log
1496 const logFiles
= readdirSync(
1497 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1498 resolve((fileURLToPath(import.meta
.url
), '../', dirname(logConfiguration
.file
!)))
1500 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1501 .filter(file
=> file
.endsWith(extname(logConfiguration
.file
!)))
1502 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1503 .map(file
=> join(dirname(logConfiguration
.file
!), file
))
1504 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1505 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1506 ftpClient
= new Client()
1507 const accessResponse
= await ftpClient
.access({
1509 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1510 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1511 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1513 let uploadResponse
: FTPResponse
| undefined
1514 if (accessResponse
.code
=== 220) {
1515 ftpClient
.trackProgress(info
=> {
1517 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1519 } bytes transferred from diagnostics archive ${info.name}`
1521 chargingStation
.ocppRequestService
1523 OCPP16DiagnosticsStatusNotificationRequest
,
1524 OCPP16DiagnosticsStatusNotificationResponse
1525 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1526 status: OCPP16DiagnosticsStatus
.Uploading
1528 .catch((error
: unknown
) => {
1530 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1531 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1537 uploadResponse
= await ftpClient
.uploadFrom(
1538 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1539 `${uri.pathname}${diagnosticsArchive}`
1541 if (uploadResponse
.code
=== 226) {
1542 await chargingStation
.ocppRequestService
.requestHandler
<
1543 OCPP16DiagnosticsStatusNotificationRequest
,
1544 OCPP16DiagnosticsStatusNotificationResponse
1545 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1546 status: OCPP16DiagnosticsStatus
.Uploaded
1549 return { fileName
: diagnosticsArchive
}
1551 throw new OCPPError(
1552 ErrorType
.GENERIC_ERROR
,
1553 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1554 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1557 throw new OCPPError(
1558 ErrorType
.GENERIC_ERROR
,
1559 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1560 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1563 await chargingStation
.ocppRequestService
.requestHandler
<
1564 OCPP16DiagnosticsStatusNotificationRequest
,
1565 OCPP16DiagnosticsStatusNotificationResponse
1566 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1567 status: OCPP16DiagnosticsStatus
.UploadFailed
1570 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1571 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1573 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1575 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1580 `${chargingStation.logPrefix()} Unsupported protocol ${
1582 } to transfer the diagnostic logs archive`
1584 await chargingStation
.ocppRequestService
.requestHandler
<
1585 OCPP16DiagnosticsStatusNotificationRequest
,
1586 OCPP16DiagnosticsStatusNotificationResponse
1587 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1588 status: OCPP16DiagnosticsStatus
.UploadFailed
1590 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1594 private handleRequestTriggerMessage (
1595 chargingStation
: ChargingStation
,
1596 commandPayload
: OCPP16TriggerMessageRequest
1597 ): OCPP16TriggerMessageResponse
{
1598 const { requestedMessage
, connectorId
} = commandPayload
1600 !OCPP16ServiceUtils
.checkFeatureProfile(
1602 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1603 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1605 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1607 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1610 !OCPP16ServiceUtils
.isConnectorIdValid(
1612 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1613 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1617 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1619 switch (requestedMessage
) {
1620 case OCPP16MessageTrigger
.BootNotification
:
1621 case OCPP16MessageTrigger
.Heartbeat
:
1622 case OCPP16MessageTrigger
.StatusNotification
:
1623 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1625 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1629 private handleRequestDataTransfer (
1630 chargingStation
: ChargingStation
,
1631 commandPayload
: OCPP16DataTransferRequest
1632 ): OCPP16DataTransferResponse
{
1633 const { vendorId
} = commandPayload
1635 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1636 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1638 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1640 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1641 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1643 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1645 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1650 private async handleRequestReserveNow (
1651 chargingStation
: ChargingStation
,
1652 commandPayload
: OCPP16ReserveNowRequest
1653 ): Promise
<OCPP16ReserveNowResponse
> {
1655 !OCPP16ServiceUtils
.checkFeatureProfile(
1657 OCPP16SupportedFeatureProfiles
.Reservation
,
1658 OCPP16IncomingRequestCommand
.RESERVE_NOW
1661 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1663 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1664 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1665 const { reservationId
, idTag
, connectorId
} = commandPayload
1666 let response
: OCPP16ReserveNowResponse
1668 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1669 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1671 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1672 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1674 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1675 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1677 await removeExpiredReservations(chargingStation
)
1678 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1679 case OCPP16ChargePointStatus
.Faulted
:
1680 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1682 case OCPP16ChargePointStatus
.Preparing
:
1683 case OCPP16ChargePointStatus
.Charging
:
1684 case OCPP16ChargePointStatus
.SuspendedEV
:
1685 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1686 case OCPP16ChargePointStatus
.Finishing
:
1687 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1689 case OCPP16ChargePointStatus
.Unavailable
:
1690 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1692 case OCPP16ChargePointStatus
.Reserved
:
1693 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1694 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1697 // eslint-disable-next-line no-fallthrough
1699 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1700 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1703 await chargingStation
.addReservation({
1704 id
: commandPayload
.reservationId
,
1707 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1712 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1713 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1714 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1715 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1717 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1719 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1724 private async handleRequestCancelReservation (
1725 chargingStation
: ChargingStation
,
1726 commandPayload
: OCPP16CancelReservationRequest
1727 ): Promise
<GenericResponse
> {
1729 !OCPP16ServiceUtils
.checkFeatureProfile(
1731 OCPP16SupportedFeatureProfiles
.Reservation
,
1732 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1735 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1738 const { reservationId
} = commandPayload
1739 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1740 if (reservation
== null) {
1742 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1744 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1746 await chargingStation
.removeReservation(
1748 ReservationTerminationReason
.RESERVATION_CANCELED
1750 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1752 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1753 return this.handleIncomingRequestError
<GenericResponse
>(
1755 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1758 errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED