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
<OCPP16StartTransactionRequest
, OCPP16StartTransactionResponse
>(
427 OCPP16RequestCommand
.START_TRANSACTION
,
434 if (response
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
436 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
440 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
444 .catch((error
: unknown
) => {
446 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`,
454 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
456 chargingStation
: ChargingStation
,
457 request
: RemoteStopTransactionRequest
,
458 response
: GenericResponse
460 if (response
.status === GenericStatus
.Accepted
) {
461 const { transactionId
} = request
462 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
463 const connectorId
= chargingStation
.getConnectorIdByTransactionId(transactionId
)!
464 OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
466 if (response
.status === GenericStatus
.Accepted
) {
468 `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for transaction '${transactionId}'`
472 `${chargingStation.logPrefix()} Remote stop transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for transaction '${transactionId}'`
476 .catch((error
: unknown
) => {
478 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote stop transaction error:`,
486 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
488 chargingStation
: ChargingStation
,
489 request
: OCPP16TriggerMessageRequest
,
490 response
: OCPP16TriggerMessageResponse
492 if (response
.status !== OCPP16TriggerMessageStatus
.ACCEPTED
) {
495 const { requestedMessage
, connectorId
} = request
496 const errorHandler
= (error
: unknown
): void => {
498 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger ${requestedMessage} error:`,
502 switch (requestedMessage
) {
503 case OCPP16MessageTrigger
.BootNotification
:
504 chargingStation
.ocppRequestService
505 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
507 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
508 chargingStation
.bootNotificationRequest
,
509 { skipBufferingOnError
: true, triggerMessage
: true }
512 chargingStation
.bootNotificationResponse
= response
516 case OCPP16MessageTrigger
.Heartbeat
:
517 chargingStation
.ocppRequestService
518 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
520 OCPP16RequestCommand
.HEARTBEAT
,
528 case OCPP16MessageTrigger
.StatusNotification
:
529 if (connectorId
!= null) {
530 chargingStation
.ocppRequestService
531 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
533 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
536 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
537 status: chargingStation
.getConnectorStatus(connectorId
)?.status
544 } else if (chargingStation
.hasEvses
) {
545 for (const evseStatus
of chargingStation
.evses
.values()) {
546 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
547 chargingStation
.ocppRequestService
549 OCPP16StatusNotificationRequest
,
550 OCPP16StatusNotificationResponse
553 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
556 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
557 status: connectorStatus
.status
567 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
568 chargingStation
.ocppRequestService
570 OCPP16StatusNotificationRequest
,
571 OCPP16StatusNotificationResponse
574 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
577 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
578 status: connectorStatus
.status
591 this.validatePayload
= this.validatePayload
.bind(this)
594 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
595 chargingStation
: ChargingStation
,
597 commandName
: OCPP16IncomingRequestCommand
,
598 commandPayload
: ReqType
600 let response
: ResType
602 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
603 chargingStation
.inPendingState() &&
604 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
605 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
608 ErrorType
.SECURITY_ERROR
,
609 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
613 )} while the charging station is in pending state on the central server`,
619 chargingStation
.isRegistered() ||
620 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
621 chargingStation
.inUnknownState())
624 this.incomingRequestHandlers
.has(commandName
) &&
625 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
628 this.validatePayload(chargingStation
, commandName
, commandPayload
)
629 // Call the method to build the response
630 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
631 const incomingRequestHandler
= this.incomingRequestHandlers
.get(commandName
)!
632 if (isAsyncFunction(incomingRequestHandler
)) {
633 response
= (await incomingRequestHandler(chargingStation
, commandPayload
)) as ResType
635 response
= incomingRequestHandler(chargingStation
, commandPayload
) as ResType
640 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
648 ErrorType
.NOT_IMPLEMENTED
,
649 `'${commandName}' is not implemented to handle request PDU ${JSON.stringify(
660 ErrorType
.SECURITY_ERROR
,
661 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
665 )} while the charging station is not registered on the central server`,
670 // Send the built response
671 await chargingStation
.ocppRequestService
.sendResponse(
677 // Emit command name event to allow delayed handling
678 this.emit(commandName
, chargingStation
, commandPayload
, response
)
681 private validatePayload (
682 chargingStation
: ChargingStation
,
683 commandName
: OCPP16IncomingRequestCommand
,
684 commandPayload
: JsonType
686 if (this.payloadValidateFunctions
.has(commandName
)) {
687 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
690 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
695 // Simulate charging station restart
696 private handleRequestReset (
697 chargingStation
: ChargingStation
,
698 commandPayload
: ResetRequest
700 const { type } = commandPayload
702 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
703 .catch(Constants
.EMPTY_FUNCTION
)
705 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
706 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
707 chargingStation.stationInfo!.resetTime!
710 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
713 private async handleRequestUnlockConnector (
714 chargingStation
: ChargingStation
,
715 commandPayload
: UnlockConnectorRequest
716 ): Promise
<UnlockConnectorResponse
> {
717 const { connectorId
} = commandPayload
718 if (!chargingStation
.hasConnector(connectorId
)) {
720 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
722 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
724 if (connectorId
=== 0) {
725 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
726 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
728 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
729 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
731 OCPP16StopTransactionReason
.UNLOCK_COMMAND
733 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
734 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
736 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
738 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
741 OCPP16ChargePointStatus
.Available
743 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
746 private handleRequestGetConfiguration (
747 chargingStation
: ChargingStation
,
748 commandPayload
: GetConfigurationRequest
749 ): GetConfigurationResponse
{
750 const { key
} = commandPayload
751 const configurationKey
: OCPPConfigurationKey
[] = []
752 const unknownKey
: string[] = []
754 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
755 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
756 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
759 configurationKey
.push({
761 readonly: configKey
.readonly,
762 value
: configKey
.value
765 } else if (isNotEmptyArray(key
)) {
766 for (const k
of key
) {
767 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
768 if (keyFound
!= null) {
769 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
772 configurationKey
.push({
774 readonly: keyFound
.readonly,
775 value
: keyFound
.value
788 private handleRequestChangeConfiguration (
789 chargingStation
: ChargingStation
,
790 commandPayload
: ChangeConfigurationRequest
791 ): ChangeConfigurationResponse
{
792 const { key
, value
} = commandPayload
793 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
794 if (keyToChange
?.readonly === true) {
795 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
796 } else if (keyToChange
?.readonly === false) {
797 let valueChanged
= false
798 if (keyToChange
.value
!== value
) {
799 setConfigurationKeyValue(chargingStation
, key
, value
, true)
802 let triggerHeartbeatRestart
= false
804 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
805 OCPP16StandardParametersKey
.HeartBeatInterval
&&
808 setConfigurationKeyValue(
810 OCPP16StandardParametersKey
.HeartbeatInterval
,
813 triggerHeartbeatRestart
= true
816 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
817 OCPP16StandardParametersKey
.HeartbeatInterval
&&
820 setConfigurationKeyValue(
822 OCPP16StandardParametersKey
.HeartBeatInterval
,
825 triggerHeartbeatRestart
= true
827 if (triggerHeartbeatRestart
) {
828 chargingStation
.restartHeartbeat()
831 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
832 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
835 chargingStation
.restartWebSocketPing()
837 if (keyToChange
.reboot
=== true) {
838 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
840 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
842 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
845 private handleRequestSetChargingProfile (
846 chargingStation
: ChargingStation
,
847 commandPayload
: SetChargingProfileRequest
848 ): SetChargingProfileResponse
{
850 !OCPP16ServiceUtils
.checkFeatureProfile(
852 OCPP16SupportedFeatureProfiles
.SmartCharging
,
853 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
856 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
858 const { connectorId
, csChargingProfiles
} = commandPayload
859 if (!chargingStation
.hasConnector(connectorId
)) {
861 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
863 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
866 csChargingProfiles
.chargingProfilePurpose
===
867 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
870 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
873 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
877 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
879 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
881 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
883 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
885 connectorStatus
?.transactionStarted
=== false
888 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
890 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
893 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
895 connectorStatus
?.transactionStarted
=== true &&
896 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
899 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
900 csChargingProfiles.transactionId
901 } than the started transaction id ${connectorStatus.transactionId}`
903 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
905 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
907 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
910 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
913 private handleRequestGetCompositeSchedule (
914 chargingStation
: ChargingStation
,
915 commandPayload
: OCPP16GetCompositeScheduleRequest
916 ): OCPP16GetCompositeScheduleResponse
{
918 !OCPP16ServiceUtils
.checkFeatureProfile(
920 OCPP16SupportedFeatureProfiles
.SmartCharging
,
921 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
924 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
926 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
927 if (!chargingStation
.hasConnector(connectorId
)) {
929 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
931 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
933 if (connectorId
=== 0) {
935 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
937 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
939 if (chargingRateUnit
!= null) {
941 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
944 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
946 isEmpty(connectorStatus
?.chargingProfiles
) &&
947 isEmpty(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
949 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
951 const currentDate
= new Date()
952 const compositeScheduleInterval
: Interval
= {
954 end
: addSeconds(currentDate
, duration
)
956 // Get charging profiles sorted by connector id then stack level
957 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
961 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
962 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
963 for (const chargingProfile
of chargingProfiles
) {
964 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
966 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
967 chargingProfile.chargingProfileId
968 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
970 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
971 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
973 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
975 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
976 chargingProfile.chargingProfileId
977 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
979 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
980 chargingProfile
.chargingSchedule
.startSchedule
983 if (chargingProfile
.chargingSchedule
.duration
== null) {
985 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
986 chargingProfile.chargingProfileId
987 } has no duration defined and will be set to the maximum time allowed`
989 // OCPP specifies that if duration is not defined, it should be infinite
990 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
992 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
993 chargingProfile
.chargingSchedule
.startSchedule
!
997 !prepareChargingProfileKind(
1000 compositeScheduleInterval
.start
,
1001 chargingStation
.logPrefix()
1007 !canProceedChargingProfile(
1009 compositeScheduleInterval
.start
,
1010 chargingStation
.logPrefix()
1015 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
1016 previousCompositeSchedule
,
1017 chargingProfile
.chargingSchedule
,
1018 compositeScheduleInterval
1020 previousCompositeSchedule
= compositeSchedule
1022 if (compositeSchedule
!= null) {
1024 status: GenericStatus
.Accepted
,
1025 scheduleStart
: compositeSchedule
.startSchedule
,
1027 chargingSchedule
: compositeSchedule
1030 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1033 private handleRequestClearChargingProfile (
1034 chargingStation
: ChargingStation
,
1035 commandPayload
: OCPP16ClearChargingProfileRequest
1036 ): OCPP16ClearChargingProfileResponse
{
1038 !OCPP16ServiceUtils
.checkFeatureProfile(
1040 OCPP16SupportedFeatureProfiles
.SmartCharging
,
1041 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
1044 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1046 const { connectorId
} = commandPayload
1047 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1048 if (!chargingStation
.hasConnector(connectorId
!)) {
1050 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
1052 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1054 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1055 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!)
1056 if (connectorId
!= null && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1057 connectorStatus
.chargingProfiles
= []
1059 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1061 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1063 if (connectorId
== null) {
1064 let clearedCP
= false
1065 if (chargingStation
.hasEvses
) {
1066 for (const evseStatus
of chargingStation
.evses
.values()) {
1067 for (const status of evseStatus
.connectors
.values()) {
1068 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1071 status.chargingProfiles
1076 for (const id
of chargingStation
.connectors
.keys()) {
1077 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1080 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1085 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1088 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1091 private async handleRequestChangeAvailability (
1092 chargingStation
: ChargingStation
,
1093 commandPayload
: OCPP16ChangeAvailabilityRequest
1094 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1095 const { connectorId
, type } = commandPayload
1096 if (!chargingStation
.hasConnector(connectorId
)) {
1098 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1100 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1102 const chargePointStatus
: OCPP16ChargePointStatus
=
1103 type === OCPP16AvailabilityType
.Operative
1104 ? OCPP16ChargePointStatus
.Available
1105 : OCPP16ChargePointStatus
.Unavailable
1106 if (connectorId
=== 0) {
1107 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1108 if (chargingStation
.hasEvses
) {
1109 for (const evseStatus
of chargingStation
.evses
.values()) {
1110 response
= await OCPP16ServiceUtils
.changeAvailability(
1112 [...evseStatus
.connectors
.keys()],
1118 response
= await OCPP16ServiceUtils
.changeAvailability(
1120 [...chargingStation
.connectors
.keys()],
1125 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1129 (chargingStation
.isChargingStationAvailable() ||
1130 (!chargingStation
.isChargingStationAvailable() &&
1131 type === OCPP16AvailabilityType
.Inoperative
))
1133 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1134 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1135 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1136 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1138 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1139 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1140 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1145 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1147 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1150 private async handleRequestRemoteStartTransaction (
1151 chargingStation
: ChargingStation
,
1152 commandPayload
: RemoteStartTransactionRequest
1153 ): Promise
<GenericResponse
> {
1154 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1155 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1156 return await this.notifyRemoteStartTransactionRejected(
1158 transactionConnectorId
,
1163 !chargingStation
.isChargingStationAvailable() ||
1164 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1166 return await this.notifyRemoteStartTransactionRejected(
1168 transactionConnectorId
,
1172 // idTag authorization check required
1174 chargingStation
.getAuthorizeRemoteTxRequests() &&
1175 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1177 return await this.notifyRemoteStartTransactionRejected(
1179 transactionConnectorId
,
1183 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1185 transactionConnectorId
,
1186 OCPP16ChargePointStatus
.Preparing
1189 chargingProfile
!= null &&
1190 !this.setRemoteStartTransactionChargingProfile(
1192 transactionConnectorId
,
1196 return await this.notifyRemoteStartTransactionRejected(
1198 transactionConnectorId
,
1203 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on connector id ${transactionConnectorId}, idTag '${idTag}'`
1205 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1208 private async notifyRemoteStartTransactionRejected (
1209 chargingStation
: ChargingStation
,
1210 connectorId
: number,
1212 ): Promise
<GenericResponse
> {
1213 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1214 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1215 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1218 OCPP16ChargePointStatus
.Available
1222 `${chargingStation.logPrefix()} Remote start transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1224 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1227 private setRemoteStartTransactionChargingProfile (
1228 chargingStation
: ChargingStation
,
1229 connectorId
: number,
1230 chargingProfile
: OCPP16ChargingProfile
1232 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1233 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1235 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1241 `${chargingStation.logPrefix()} Not allowed to set ${
1242 chargingProfile.chargingProfilePurpose
1243 } charging profile(s) at remote start transaction`
1248 private handleRequestRemoteStopTransaction (
1249 chargingStation
: ChargingStation
,
1250 commandPayload
: RemoteStopTransactionRequest
1251 ): GenericResponse
{
1252 const { transactionId
} = commandPayload
1253 if (chargingStation
.getConnectorIdByTransactionId(transactionId
) != null) {
1255 `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED for transactionId '${transactionId}'`
1257 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1260 `${chargingStation.logPrefix()} Remote stop transaction REJECTED for transactionId '${transactionId}'`
1262 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1265 private handleRequestUpdateFirmware (
1266 chargingStation
: ChargingStation
,
1267 commandPayload
: OCPP16UpdateFirmwareRequest
1268 ): OCPP16UpdateFirmwareResponse
{
1270 !OCPP16ServiceUtils
.checkFeatureProfile(
1272 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1273 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1277 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1279 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1281 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1282 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1283 const { retrieveDate
} = commandPayload
1284 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1286 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1288 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1290 const now
= Date.now()
1291 if (retrieveDate
.getTime() <= now
) {
1292 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1295 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1296 }, retrieveDate
.getTime() - now
)
1298 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1301 private async updateFirmwareSimulation (
1302 chargingStation
: ChargingStation
,
1306 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1309 if (chargingStation
.hasEvses
) {
1310 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1312 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1313 if (connectorStatus
.transactionStarted
=== false) {
1314 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1317 OCPP16ChargePointStatus
.Unavailable
1324 for (const connectorId
of chargingStation
.connectors
.keys()) {
1327 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1329 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1332 OCPP16ChargePointStatus
.Unavailable
1337 await chargingStation
.ocppRequestService
.requestHandler
<
1338 OCPP16FirmwareStatusNotificationRequest
,
1339 OCPP16FirmwareStatusNotificationResponse
1340 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1341 status: OCPP16FirmwareStatus
.Downloading
1343 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1344 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1346 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1347 OCPP16FirmwareStatus
.DownloadFailed
1349 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1350 await chargingStation
.ocppRequestService
.requestHandler
<
1351 OCPP16FirmwareStatusNotificationRequest
,
1352 OCPP16FirmwareStatusNotificationResponse
1353 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1354 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1356 chargingStation
.stationInfo
.firmwareStatus
=
1357 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1360 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1361 await chargingStation
.ocppRequestService
.requestHandler
<
1362 OCPP16FirmwareStatusNotificationRequest
,
1363 OCPP16FirmwareStatusNotificationResponse
1364 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1365 status: OCPP16FirmwareStatus
.Downloaded
1367 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1368 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1369 let wasTransactionsStarted
= false
1370 let transactionsStarted
: boolean
1372 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1373 if (runningTransactions
> 0) {
1374 const waitTime
= secondsToMilliseconds(15)
1376 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1378 )} before continuing firmware update simulation`
1380 await sleep(waitTime
)
1381 transactionsStarted
= true
1382 wasTransactionsStarted
= true
1384 if (chargingStation
.hasEvses
) {
1385 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1387 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1388 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1389 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1392 OCPP16ChargePointStatus
.Unavailable
1399 for (const connectorId
of chargingStation
.connectors
.keys()) {
1402 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1403 OCPP16ChargePointStatus
.Unavailable
1405 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1408 OCPP16ChargePointStatus
.Unavailable
1413 transactionsStarted
= false
1415 } while (transactionsStarted
)
1416 !wasTransactionsStarted
&& (await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
))))
1417 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1420 await chargingStation
.ocppRequestService
.requestHandler
<
1421 OCPP16FirmwareStatusNotificationRequest
,
1422 OCPP16FirmwareStatusNotificationResponse
1423 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1424 status: OCPP16FirmwareStatus
.Installing
1426 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1427 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1429 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1430 OCPP16FirmwareStatus
.InstallationFailed
1432 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1433 await chargingStation
.ocppRequestService
.requestHandler
<
1434 OCPP16FirmwareStatusNotificationRequest
,
1435 OCPP16FirmwareStatusNotificationResponse
1436 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1437 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1439 chargingStation
.stationInfo
.firmwareStatus
=
1440 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1443 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1444 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1445 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1449 private async handleRequestGetDiagnostics (
1450 chargingStation
: ChargingStation
,
1451 commandPayload
: GetDiagnosticsRequest
1452 ): Promise
<GetDiagnosticsResponse
> {
1454 !OCPP16ServiceUtils
.checkFeatureProfile(
1456 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1457 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1461 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1463 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1465 const { location
} = commandPayload
1466 const uri
= new URL(location
)
1467 if (uri
.protocol
.startsWith('ftp:')) {
1468 let ftpClient
: Client
| undefined
1470 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
1471 ConfigurationSection
.log
1473 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1474 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1475 .filter(file
=> file
.endsWith(extname(logConfiguration
.file
!)))
1476 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1477 .map(file
=> join(dirname(logConfiguration
.file
!), file
))
1478 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1479 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1480 ftpClient
= new Client()
1481 const accessResponse
= await ftpClient
.access({
1483 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1484 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1485 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1487 let uploadResponse
: FTPResponse
| undefined
1488 if (accessResponse
.code
=== 220) {
1489 ftpClient
.trackProgress(info
=> {
1491 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1493 } bytes transferred from diagnostics archive ${info.name}`
1495 chargingStation
.ocppRequestService
1497 OCPP16DiagnosticsStatusNotificationRequest
,
1498 OCPP16DiagnosticsStatusNotificationResponse
1499 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1500 status: OCPP16DiagnosticsStatus
.Uploading
1502 .catch((error
: unknown
) => {
1504 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1505 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1511 uploadResponse
= await ftpClient
.uploadFrom(
1512 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1513 `${uri.pathname}${diagnosticsArchive}`
1515 if (uploadResponse
.code
=== 226) {
1516 await chargingStation
.ocppRequestService
.requestHandler
<
1517 OCPP16DiagnosticsStatusNotificationRequest
,
1518 OCPP16DiagnosticsStatusNotificationResponse
1519 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1520 status: OCPP16DiagnosticsStatus
.Uploaded
1523 return { fileName
: diagnosticsArchive
}
1525 throw new OCPPError(
1526 ErrorType
.GENERIC_ERROR
,
1527 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1528 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1531 throw new OCPPError(
1532 ErrorType
.GENERIC_ERROR
,
1533 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1534 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1537 await chargingStation
.ocppRequestService
.requestHandler
<
1538 OCPP16DiagnosticsStatusNotificationRequest
,
1539 OCPP16DiagnosticsStatusNotificationResponse
1540 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1541 status: OCPP16DiagnosticsStatus
.UploadFailed
1544 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1545 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1547 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1549 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1554 `${chargingStation.logPrefix()} Unsupported protocol ${
1556 } to transfer the diagnostic logs archive`
1558 await chargingStation
.ocppRequestService
.requestHandler
<
1559 OCPP16DiagnosticsStatusNotificationRequest
,
1560 OCPP16DiagnosticsStatusNotificationResponse
1561 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1562 status: OCPP16DiagnosticsStatus
.UploadFailed
1564 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1568 private handleRequestTriggerMessage (
1569 chargingStation
: ChargingStation
,
1570 commandPayload
: OCPP16TriggerMessageRequest
1571 ): OCPP16TriggerMessageResponse
{
1572 const { requestedMessage
, connectorId
} = commandPayload
1574 !OCPP16ServiceUtils
.checkFeatureProfile(
1576 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1577 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1579 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1581 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1584 !OCPP16ServiceUtils
.isConnectorIdValid(
1586 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1587 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1591 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1593 switch (requestedMessage
) {
1594 case OCPP16MessageTrigger
.BootNotification
:
1595 case OCPP16MessageTrigger
.Heartbeat
:
1596 case OCPP16MessageTrigger
.StatusNotification
:
1597 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1599 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1603 private handleRequestDataTransfer (
1604 chargingStation
: ChargingStation
,
1605 commandPayload
: OCPP16DataTransferRequest
1606 ): OCPP16DataTransferResponse
{
1607 const { vendorId
} = commandPayload
1609 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1610 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1612 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1614 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1615 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1617 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1619 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1624 private async handleRequestReserveNow (
1625 chargingStation
: ChargingStation
,
1626 commandPayload
: OCPP16ReserveNowRequest
1627 ): Promise
<OCPP16ReserveNowResponse
> {
1629 !OCPP16ServiceUtils
.checkFeatureProfile(
1631 OCPP16SupportedFeatureProfiles
.Reservation
,
1632 OCPP16IncomingRequestCommand
.RESERVE_NOW
1635 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1637 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1638 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1639 const { reservationId
, idTag
, connectorId
} = commandPayload
1640 let response
: OCPP16ReserveNowResponse
1642 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1643 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1645 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1646 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1648 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1649 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1651 await removeExpiredReservations(chargingStation
)
1652 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1653 case OCPP16ChargePointStatus
.Faulted
:
1654 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1656 case OCPP16ChargePointStatus
.Preparing
:
1657 case OCPP16ChargePointStatus
.Charging
:
1658 case OCPP16ChargePointStatus
.SuspendedEV
:
1659 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1660 case OCPP16ChargePointStatus
.Finishing
:
1661 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1663 case OCPP16ChargePointStatus
.Unavailable
:
1664 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1666 case OCPP16ChargePointStatus
.Reserved
:
1667 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1668 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1671 // eslint-disable-next-line no-fallthrough
1673 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1674 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1677 await chargingStation
.addReservation({
1678 id
: commandPayload
.reservationId
,
1681 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1686 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1687 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1688 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1689 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1691 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1693 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1698 private async handleRequestCancelReservation (
1699 chargingStation
: ChargingStation
,
1700 commandPayload
: OCPP16CancelReservationRequest
1701 ): Promise
<GenericResponse
> {
1703 !OCPP16ServiceUtils
.checkFeatureProfile(
1705 OCPP16SupportedFeatureProfiles
.Reservation
,
1706 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1709 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1712 const { reservationId
} = commandPayload
1713 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1714 if (reservation
== null) {
1716 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1718 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1720 await chargingStation
.removeReservation(
1722 ReservationTerminationReason
.RESERVATION_CANCELED
1724 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1726 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1727 return this.handleIncomingRequestError
<GenericResponse
>(
1729 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1731 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}