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 this.notifyRemoteStartTransactionRejected(
1158 transactionConnectorId
,
1163 !chargingStation
.isChargingStationAvailable() ||
1164 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1166 return this.notifyRemoteStartTransactionRejected(
1168 transactionConnectorId
,
1172 // idTag authorization check required
1174 chargingStation
.getAuthorizeRemoteTxRequests() &&
1175 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1177 return this.notifyRemoteStartTransactionRejected(
1179 transactionConnectorId
,
1184 chargingProfile
!= null &&
1185 !this.setRemoteStartTransactionChargingProfile(
1187 transactionConnectorId
,
1191 return this.notifyRemoteStartTransactionRejected(
1193 transactionConnectorId
,
1198 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${transactionConnectorId}}, idTag '${idTag}'`
1200 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1203 private notifyRemoteStartTransactionRejected (
1204 chargingStation
: ChargingStation
,
1205 connectorId
: number,
1207 ): GenericResponse
{
1208 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1210 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1212 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1215 private setRemoteStartTransactionChargingProfile (
1216 chargingStation
: ChargingStation
,
1217 connectorId
: number,
1218 chargingProfile
: OCPP16ChargingProfile
1220 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1221 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1223 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on ${chargingStation.stationInfo?.chargingStationId}#${connectorId}`,
1229 `${chargingStation.logPrefix()} Not allowed to set ${
1230 chargingProfile.chargingProfilePurpose
1231 } charging profile(s) at remote start transaction`
1236 private handleRequestRemoteStopTransaction (
1237 chargingStation
: ChargingStation
,
1238 commandPayload
: RemoteStopTransactionRequest
1239 ): GenericResponse
{
1240 const { transactionId
} = commandPayload
1241 if (chargingStation
.getConnectorIdByTransactionId(transactionId
) != null) {
1243 `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED for transactionId '${transactionId}'`
1245 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1248 `${chargingStation.logPrefix()} Remote stop transaction REJECTED for transactionId '${transactionId}'`
1250 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1253 private handleRequestUpdateFirmware (
1254 chargingStation
: ChargingStation
,
1255 commandPayload
: OCPP16UpdateFirmwareRequest
1256 ): OCPP16UpdateFirmwareResponse
{
1258 !OCPP16ServiceUtils
.checkFeatureProfile(
1260 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1261 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1265 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1267 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1269 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1270 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1271 const { retrieveDate
} = commandPayload
1272 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1274 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1276 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1278 const now
= Date.now()
1279 if (retrieveDate
.getTime() <= now
) {
1280 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1283 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1284 }, retrieveDate
.getTime() - now
)
1286 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1289 private async updateFirmwareSimulation (
1290 chargingStation
: ChargingStation
,
1294 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1297 if (chargingStation
.hasEvses
) {
1298 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1300 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1301 if (connectorStatus
.transactionStarted
=== false) {
1302 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1305 OCPP16ChargePointStatus
.Unavailable
1312 for (const connectorId
of chargingStation
.connectors
.keys()) {
1315 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1317 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1320 OCPP16ChargePointStatus
.Unavailable
1325 await chargingStation
.ocppRequestService
.requestHandler
<
1326 OCPP16FirmwareStatusNotificationRequest
,
1327 OCPP16FirmwareStatusNotificationResponse
1328 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1329 status: OCPP16FirmwareStatus
.Downloading
1331 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1332 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1334 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1335 OCPP16FirmwareStatus
.DownloadFailed
1337 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1338 await chargingStation
.ocppRequestService
.requestHandler
<
1339 OCPP16FirmwareStatusNotificationRequest
,
1340 OCPP16FirmwareStatusNotificationResponse
1341 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1342 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1344 chargingStation
.stationInfo
.firmwareStatus
=
1345 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1348 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1349 await chargingStation
.ocppRequestService
.requestHandler
<
1350 OCPP16FirmwareStatusNotificationRequest
,
1351 OCPP16FirmwareStatusNotificationResponse
1352 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1353 status: OCPP16FirmwareStatus
.Downloaded
1355 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1356 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1357 let wasTransactionsStarted
= false
1358 let transactionsStarted
: boolean
1360 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1361 if (runningTransactions
> 0) {
1362 const waitTime
= secondsToMilliseconds(15)
1364 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1366 )} before continuing firmware update simulation`
1368 await sleep(waitTime
)
1369 transactionsStarted
= true
1370 wasTransactionsStarted
= true
1372 if (chargingStation
.hasEvses
) {
1373 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1375 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1376 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1377 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1380 OCPP16ChargePointStatus
.Unavailable
1387 for (const connectorId
of chargingStation
.connectors
.keys()) {
1390 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1391 OCPP16ChargePointStatus
.Unavailable
1393 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1396 OCPP16ChargePointStatus
.Unavailable
1401 transactionsStarted
= false
1403 } while (transactionsStarted
)
1404 !wasTransactionsStarted
&& (await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
))))
1405 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1408 await chargingStation
.ocppRequestService
.requestHandler
<
1409 OCPP16FirmwareStatusNotificationRequest
,
1410 OCPP16FirmwareStatusNotificationResponse
1411 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1412 status: OCPP16FirmwareStatus
.Installing
1414 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1415 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1417 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1418 OCPP16FirmwareStatus
.InstallationFailed
1420 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1421 await chargingStation
.ocppRequestService
.requestHandler
<
1422 OCPP16FirmwareStatusNotificationRequest
,
1423 OCPP16FirmwareStatusNotificationResponse
1424 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1425 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1427 chargingStation
.stationInfo
.firmwareStatus
=
1428 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1431 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1432 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1433 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1437 private async handleRequestGetDiagnostics (
1438 chargingStation
: ChargingStation
,
1439 commandPayload
: GetDiagnosticsRequest
1440 ): Promise
<GetDiagnosticsResponse
> {
1442 !OCPP16ServiceUtils
.checkFeatureProfile(
1444 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1445 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1449 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1451 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1453 const { location
} = commandPayload
1454 const uri
= new URL(location
)
1455 if (uri
.protocol
.startsWith('ftp:')) {
1456 let ftpClient
: Client
| undefined
1458 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
1459 ConfigurationSection
.log
1461 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1462 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1463 .filter(file
=> file
.endsWith(extname(logConfiguration
.file
!)))
1464 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1465 .map(file
=> join(dirname(logConfiguration
.file
!), file
))
1466 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1467 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1468 ftpClient
= new Client()
1469 const accessResponse
= await ftpClient
.access({
1471 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1472 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1473 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1475 let uploadResponse
: FTPResponse
| undefined
1476 if (accessResponse
.code
=== 220) {
1477 ftpClient
.trackProgress(info
=> {
1479 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1481 } bytes transferred from diagnostics archive ${info.name}`
1483 chargingStation
.ocppRequestService
1485 OCPP16DiagnosticsStatusNotificationRequest
,
1486 OCPP16DiagnosticsStatusNotificationResponse
1487 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1488 status: OCPP16DiagnosticsStatus
.Uploading
1490 .catch((error
: unknown
) => {
1492 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1493 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1499 uploadResponse
= await ftpClient
.uploadFrom(
1500 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1501 `${uri.pathname}${diagnosticsArchive}`
1503 if (uploadResponse
.code
=== 226) {
1504 await chargingStation
.ocppRequestService
.requestHandler
<
1505 OCPP16DiagnosticsStatusNotificationRequest
,
1506 OCPP16DiagnosticsStatusNotificationResponse
1507 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1508 status: OCPP16DiagnosticsStatus
.Uploaded
1511 return { fileName
: diagnosticsArchive
}
1513 throw new OCPPError(
1514 ErrorType
.GENERIC_ERROR
,
1515 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1516 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1519 throw new OCPPError(
1520 ErrorType
.GENERIC_ERROR
,
1521 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1522 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1525 await chargingStation
.ocppRequestService
.requestHandler
<
1526 OCPP16DiagnosticsStatusNotificationRequest
,
1527 OCPP16DiagnosticsStatusNotificationResponse
1528 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1529 status: OCPP16DiagnosticsStatus
.UploadFailed
1532 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1533 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1535 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1537 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1542 `${chargingStation.logPrefix()} Unsupported protocol ${
1544 } to transfer the diagnostic logs archive`
1546 await chargingStation
.ocppRequestService
.requestHandler
<
1547 OCPP16DiagnosticsStatusNotificationRequest
,
1548 OCPP16DiagnosticsStatusNotificationResponse
1549 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1550 status: OCPP16DiagnosticsStatus
.UploadFailed
1552 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1556 private handleRequestTriggerMessage (
1557 chargingStation
: ChargingStation
,
1558 commandPayload
: OCPP16TriggerMessageRequest
1559 ): OCPP16TriggerMessageResponse
{
1560 const { requestedMessage
, connectorId
} = commandPayload
1562 !OCPP16ServiceUtils
.checkFeatureProfile(
1564 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1565 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1567 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1569 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1572 !OCPP16ServiceUtils
.isConnectorIdValid(
1574 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1575 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1579 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1581 switch (requestedMessage
) {
1582 case OCPP16MessageTrigger
.BootNotification
:
1583 case OCPP16MessageTrigger
.Heartbeat
:
1584 case OCPP16MessageTrigger
.StatusNotification
:
1585 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1587 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1591 private handleRequestDataTransfer (
1592 chargingStation
: ChargingStation
,
1593 commandPayload
: OCPP16DataTransferRequest
1594 ): OCPP16DataTransferResponse
{
1595 const { vendorId
} = commandPayload
1597 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1598 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1600 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1602 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1603 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1605 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1607 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1612 private async handleRequestReserveNow (
1613 chargingStation
: ChargingStation
,
1614 commandPayload
: OCPP16ReserveNowRequest
1615 ): Promise
<OCPP16ReserveNowResponse
> {
1617 !OCPP16ServiceUtils
.checkFeatureProfile(
1619 OCPP16SupportedFeatureProfiles
.Reservation
,
1620 OCPP16IncomingRequestCommand
.RESERVE_NOW
1623 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1625 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1626 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1627 const { reservationId
, idTag
, connectorId
} = commandPayload
1628 let response
: OCPP16ReserveNowResponse
1630 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1631 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1633 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1634 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1636 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1637 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1639 await removeExpiredReservations(chargingStation
)
1640 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1641 case OCPP16ChargePointStatus
.Faulted
:
1642 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1644 case OCPP16ChargePointStatus
.Preparing
:
1645 case OCPP16ChargePointStatus
.Charging
:
1646 case OCPP16ChargePointStatus
.SuspendedEV
:
1647 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1648 case OCPP16ChargePointStatus
.Finishing
:
1649 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1651 case OCPP16ChargePointStatus
.Unavailable
:
1652 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1654 case OCPP16ChargePointStatus
.Reserved
:
1655 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1656 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1659 // eslint-disable-next-line no-fallthrough
1661 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1662 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1665 await chargingStation
.addReservation({
1666 id
: commandPayload
.reservationId
,
1669 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1674 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1675 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1676 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1677 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1679 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1681 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1686 private async handleRequestCancelReservation (
1687 chargingStation
: ChargingStation
,
1688 commandPayload
: OCPP16CancelReservationRequest
1689 ): Promise
<GenericResponse
> {
1691 !OCPP16ServiceUtils
.checkFeatureProfile(
1693 OCPP16SupportedFeatureProfiles
.Reservation
,
1694 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1697 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1700 const { reservationId
} = commandPayload
1701 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1702 if (reservation
== null) {
1704 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1706 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1708 await chargingStation
.removeReservation(
1710 ReservationTerminationReason
.RESERVATION_CANCELED
1712 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1714 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1715 return this.handleIncomingRequestError
<GenericResponse
>(
1717 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1719 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}