1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { randomInt
} from
'node:crypto'
4 import { createWriteStream
, readdirSync
} from
'node:fs'
5 import { dirname
, extname
, join
, resolve
} from
'node:path'
6 import { fileURLToPath
, URL
} from
'node:url'
8 import type { ValidateFunction
} from
'ajv'
9 import { Client
, type FTPResponse
} from
'basic-ftp'
17 import { maxTime
} from
'date-fns/constants'
18 import { isEmpty
} from
'rambda'
19 import { create
} from
'tar'
22 canProceedChargingProfile
,
26 getConnectorChargingProfiles
,
27 prepareChargingProfileKind
,
28 removeExpiredReservations
,
29 setConfigurationKeyValue
30 } from
'../../../charging-station/index.js'
31 import { OCPPError
} from
'../../../exception/index.js'
33 type ChangeConfigurationRequest
,
34 type ChangeConfigurationResponse
,
39 type GetConfigurationRequest
,
40 type GetConfigurationResponse
,
41 type GetDiagnosticsRequest
,
42 type GetDiagnosticsResponse
,
43 type IncomingRequestHandler
,
45 type LogConfiguration
,
46 OCPP16AuthorizationStatus
,
47 OCPP16AvailabilityType
,
48 type OCPP16BootNotificationRequest
,
49 type OCPP16BootNotificationResponse
,
50 type OCPP16CancelReservationRequest
,
51 type OCPP16ChangeAvailabilityRequest
,
52 type OCPP16ChangeAvailabilityResponse
,
53 OCPP16ChargePointErrorCode
,
54 OCPP16ChargePointStatus
,
55 type OCPP16ChargingProfile
,
56 OCPP16ChargingProfilePurposeType
,
57 type OCPP16ChargingSchedule
,
58 type OCPP16ClearCacheRequest
,
59 type OCPP16ClearChargingProfileRequest
,
60 type OCPP16ClearChargingProfileResponse
,
61 type OCPP16DataTransferRequest
,
62 type OCPP16DataTransferResponse
,
63 OCPP16DataTransferVendorId
,
64 OCPP16DiagnosticsStatus
,
65 type OCPP16DiagnosticsStatusNotificationRequest
,
66 type OCPP16DiagnosticsStatusNotificationResponse
,
68 type OCPP16FirmwareStatusNotificationRequest
,
69 type OCPP16FirmwareStatusNotificationResponse
,
70 type OCPP16GetCompositeScheduleRequest
,
71 type OCPP16GetCompositeScheduleResponse
,
72 type OCPP16HeartbeatRequest
,
73 type OCPP16HeartbeatResponse
,
74 OCPP16IncomingRequestCommand
,
77 type OCPP16ReserveNowRequest
,
78 type OCPP16ReserveNowResponse
,
79 OCPP16StandardParametersKey
,
80 type OCPP16StartTransactionRequest
,
81 type OCPP16StartTransactionResponse
,
82 type OCPP16StatusNotificationRequest
,
83 type OCPP16StatusNotificationResponse
,
84 OCPP16StopTransactionReason
,
85 OCPP16SupportedFeatureProfiles
,
86 type OCPP16TriggerMessageRequest
,
87 type OCPP16TriggerMessageResponse
,
88 OCPP16TriggerMessageStatus
,
89 type OCPP16UpdateFirmwareRequest
,
90 type OCPP16UpdateFirmwareResponse
,
91 type OCPPConfigurationKey
,
93 type RemoteStartTransactionRequest
,
94 type RemoteStopTransactionRequest
,
95 ReservationTerminationReason
,
97 type SetChargingProfileRequest
,
98 type SetChargingProfileResponse
,
99 type UnlockConnectorRequest
,
100 type UnlockConnectorResponse
101 } from
'../../../types/index.js'
107 formatDurationMilliSeconds
,
113 } from
'../../../utils/index.js'
114 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService.js'
115 import { OCPP16Constants
} from
'./OCPP16Constants.js'
116 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils.js'
118 const moduleName
= 'OCPP16IncomingRequestService'
120 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
121 protected payloadValidateFunctions
: Map
<OCPP16IncomingRequestCommand
, ValidateFunction
<JsonType
>>
123 private readonly incomingRequestHandlers
: Map
<
124 OCPP16IncomingRequestCommand
,
125 IncomingRequestHandler
128 public constructor () {
129 // if (new.target.name === moduleName) {
130 // throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
132 super(OCPPVersion
.VERSION_16
)
133 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
135 OCPP16IncomingRequestCommand
.RESET
,
136 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
139 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
140 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
143 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
144 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
147 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
148 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
151 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
152 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
155 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
156 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
159 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
160 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
163 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
164 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
167 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
168 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
171 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
172 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
175 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
176 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
179 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
180 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
183 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
184 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
187 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
188 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
191 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
192 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
195 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
196 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
199 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
200 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
203 this.payloadValidateFunctions
= new Map
<
204 OCPP16IncomingRequestCommand
,
205 ValidateFunction
<JsonType
>
208 OCPP16IncomingRequestCommand
.RESET
,
211 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
212 'assets/json-schemas/ocpp/1.6/Reset.json',
220 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
223 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
224 'assets/json-schemas/ocpp/1.6/ClearCache.json',
232 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
235 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
236 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
244 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
247 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
248 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
256 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
259 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
260 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
268 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
271 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
272 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
280 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
283 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
284 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
292 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
295 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
296 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
304 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
307 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearChargingProfileRequest
>(
308 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
316 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
319 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
320 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
328 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
331 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
332 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
340 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
343 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
344 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
352 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
355 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
356 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
364 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
367 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
368 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
376 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
379 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
380 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
388 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
391 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
392 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
400 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
403 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
404 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
412 // Handle incoming request events
414 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
416 chargingStation
: ChargingStation
,
417 request
: RemoteStartTransactionRequest
,
418 response
: GenericResponse
420 if (response
.status === GenericStatus
.Accepted
) {
421 const { connectorId
, idTag
} = request
422 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
423 chargingStation
.getConnectorStatus(connectorId
)!.transactionRemoteStarted
= true
424 chargingStation
.ocppRequestService
425 .requestHandler
<Partial
<OCPP16StartTransactionRequest
>, OCPP16StartTransactionResponse
>(
427 OCPP16RequestCommand
.START_TRANSACTION
,
434 if (response
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
436 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${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
as OCPP16BootNotificationRequest
,
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
)
538 ?.status as OCPP16ChargePointStatus
545 } else if (chargingStation
.hasEvses
) {
546 for (const evseStatus
of chargingStation
.evses
.values()) {
547 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
548 chargingStation
.ocppRequestService
550 OCPP16StatusNotificationRequest
,
551 OCPP16StatusNotificationResponse
554 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
557 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
558 status: connectorStatus
.status as OCPP16ChargePointStatus
568 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
569 chargingStation
.ocppRequestService
571 OCPP16StatusNotificationRequest
,
572 OCPP16StatusNotificationResponse
575 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
578 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
579 status: connectorStatus
.status as OCPP16ChargePointStatus
592 this.validatePayload
= this.validatePayload
.bind(this)
595 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
596 chargingStation
: ChargingStation
,
598 commandName
: OCPP16IncomingRequestCommand
,
599 commandPayload
: ReqType
601 let response
: ResType
603 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
604 chargingStation
.inPendingState() &&
605 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
606 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
609 ErrorType
.SECURITY_ERROR
,
610 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
614 )} while the charging station is in pending state on the central server`,
620 chargingStation
.isRegistered() ||
621 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
622 chargingStation
.inUnknownState())
625 this.incomingRequestHandlers
.has(commandName
) &&
626 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
629 this.validatePayload(chargingStation
, commandName
, commandPayload
)
630 // Call the method to build the response
631 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
632 const incomingRequestHandler
= this.incomingRequestHandlers
.get(commandName
)!
633 if (isAsyncFunction(incomingRequestHandler
)) {
634 response
= (await incomingRequestHandler(chargingStation
, commandPayload
)) as ResType
636 response
= incomingRequestHandler(chargingStation
, commandPayload
) as ResType
641 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
649 ErrorType
.NOT_IMPLEMENTED
,
650 `'${commandName}' is not implemented to handle request PDU ${JSON.stringify(
661 ErrorType
.SECURITY_ERROR
,
662 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
666 )} while the charging station is not registered on the central server`,
671 // Send the built response
672 await chargingStation
.ocppRequestService
.sendResponse(
678 // Emit command name event to allow delayed handling
679 this.emit(commandName
, chargingStation
, commandPayload
, response
)
682 private validatePayload (
683 chargingStation
: ChargingStation
,
684 commandName
: OCPP16IncomingRequestCommand
,
685 commandPayload
: JsonType
687 if (this.payloadValidateFunctions
.has(commandName
)) {
688 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
691 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
696 // Simulate charging station restart
697 private handleRequestReset (
698 chargingStation
: ChargingStation
,
699 commandPayload
: ResetRequest
701 const { type } = commandPayload
703 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
704 .catch(Constants
.EMPTY_FUNCTION
)
706 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
707 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
708 chargingStation.stationInfo!.resetTime!
711 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
714 private async handleRequestUnlockConnector (
715 chargingStation
: ChargingStation
,
716 commandPayload
: UnlockConnectorRequest
717 ): Promise
<UnlockConnectorResponse
> {
718 const { connectorId
} = commandPayload
719 if (!chargingStation
.hasConnector(connectorId
)) {
721 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
723 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
725 if (connectorId
=== 0) {
726 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
727 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
729 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
730 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
732 OCPP16StopTransactionReason
.UNLOCK_COMMAND
734 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
735 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
737 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
739 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
742 OCPP16ChargePointStatus
.Available
744 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
747 private handleRequestGetConfiguration (
748 chargingStation
: ChargingStation
,
749 commandPayload
: GetConfigurationRequest
750 ): GetConfigurationResponse
{
751 const { key
} = commandPayload
752 const configurationKey
: OCPPConfigurationKey
[] = []
753 const unknownKey
: string[] = []
755 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
756 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
757 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
760 configurationKey
.push({
762 readonly: configKey
.readonly,
763 value
: configKey
.value
766 } else if (isNotEmptyArray(key
)) {
767 for (const k
of key
) {
768 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
769 if (keyFound
!= null) {
770 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
773 configurationKey
.push({
775 readonly: keyFound
.readonly,
776 value
: keyFound
.value
789 private handleRequestChangeConfiguration (
790 chargingStation
: ChargingStation
,
791 commandPayload
: ChangeConfigurationRequest
792 ): ChangeConfigurationResponse
{
793 const { key
, value
} = commandPayload
794 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
795 if (keyToChange
?.readonly === true) {
796 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
797 } else if (keyToChange
?.readonly === false) {
798 let valueChanged
= false
799 if (keyToChange
.value
!== value
) {
800 setConfigurationKeyValue(chargingStation
, key
, value
, true)
803 let triggerHeartbeatRestart
= false
805 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
806 OCPP16StandardParametersKey
.HeartBeatInterval
&&
809 setConfigurationKeyValue(
811 OCPP16StandardParametersKey
.HeartbeatInterval
,
814 triggerHeartbeatRestart
= true
817 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
818 OCPP16StandardParametersKey
.HeartbeatInterval
&&
821 setConfigurationKeyValue(
823 OCPP16StandardParametersKey
.HeartBeatInterval
,
826 triggerHeartbeatRestart
= true
828 if (triggerHeartbeatRestart
) {
829 chargingStation
.restartHeartbeat()
832 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
833 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
836 chargingStation
.restartWebSocketPing()
838 if (keyToChange
.reboot
=== true) {
839 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
841 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
843 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
846 private handleRequestSetChargingProfile (
847 chargingStation
: ChargingStation
,
848 commandPayload
: SetChargingProfileRequest
849 ): SetChargingProfileResponse
{
851 !OCPP16ServiceUtils
.checkFeatureProfile(
853 OCPP16SupportedFeatureProfiles
.SmartCharging
,
854 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
857 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
859 const { connectorId
, csChargingProfiles
} = commandPayload
860 if (!chargingStation
.hasConnector(connectorId
)) {
862 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
864 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
867 csChargingProfiles
.chargingProfilePurpose
===
868 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
871 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
874 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
878 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
880 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
882 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
884 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
886 connectorStatus
?.transactionStarted
=== false
889 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
891 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
894 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
896 connectorStatus
?.transactionStarted
=== true &&
897 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
900 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
901 csChargingProfiles.transactionId
902 } than the started transaction id ${connectorStatus.transactionId}`
904 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
906 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
908 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
911 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
914 private handleRequestGetCompositeSchedule (
915 chargingStation
: ChargingStation
,
916 commandPayload
: OCPP16GetCompositeScheduleRequest
917 ): OCPP16GetCompositeScheduleResponse
{
919 !OCPP16ServiceUtils
.checkFeatureProfile(
921 OCPP16SupportedFeatureProfiles
.SmartCharging
,
922 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
925 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
927 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
928 if (!chargingStation
.hasConnector(connectorId
)) {
930 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
932 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
934 if (connectorId
=== 0) {
936 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
938 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
940 if (chargingRateUnit
!= null) {
942 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
945 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
947 isEmpty(connectorStatus
?.chargingProfiles
) &&
948 isEmpty(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
950 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
952 const currentDate
= new Date()
953 const compositeScheduleInterval
: Interval
= {
955 end
: addSeconds(currentDate
, duration
)
957 // Get charging profiles sorted by connector id then stack level
958 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
962 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
963 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
964 for (const chargingProfile
of chargingProfiles
) {
965 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
967 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
968 chargingProfile.chargingProfileId
969 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
971 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
972 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
974 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
976 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
977 chargingProfile.chargingProfileId
978 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
980 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
981 chargingProfile
.chargingSchedule
.startSchedule
984 if (chargingProfile
.chargingSchedule
.duration
== null) {
986 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
987 chargingProfile.chargingProfileId
988 } has no duration defined and will be set to the maximum time allowed`
990 // OCPP specifies that if duration is not defined, it should be infinite
991 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
993 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
994 chargingProfile
.chargingSchedule
.startSchedule
!
998 !prepareChargingProfileKind(
1001 compositeScheduleInterval
.start
,
1002 chargingStation
.logPrefix()
1008 !canProceedChargingProfile(
1010 compositeScheduleInterval
.start
,
1011 chargingStation
.logPrefix()
1016 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
1017 previousCompositeSchedule
,
1018 chargingProfile
.chargingSchedule
,
1019 compositeScheduleInterval
1021 previousCompositeSchedule
= compositeSchedule
1023 if (compositeSchedule
!= null) {
1025 status: GenericStatus
.Accepted
,
1026 scheduleStart
: compositeSchedule
.startSchedule
,
1028 chargingSchedule
: compositeSchedule
1031 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1034 private handleRequestClearChargingProfile (
1035 chargingStation
: ChargingStation
,
1036 commandPayload
: OCPP16ClearChargingProfileRequest
1037 ): OCPP16ClearChargingProfileResponse
{
1039 !OCPP16ServiceUtils
.checkFeatureProfile(
1041 OCPP16SupportedFeatureProfiles
.SmartCharging
,
1042 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
1045 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1047 const { connectorId
} = commandPayload
1048 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1049 if (!chargingStation
.hasConnector(connectorId
!)) {
1051 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
1053 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1055 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1056 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!)
1057 if (connectorId
!= null && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1058 connectorStatus
.chargingProfiles
= []
1060 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1062 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1064 if (connectorId
== null) {
1065 let clearedCP
= false
1066 if (chargingStation
.hasEvses
) {
1067 for (const evseStatus
of chargingStation
.evses
.values()) {
1068 for (const status of evseStatus
.connectors
.values()) {
1069 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1072 status.chargingProfiles
1077 for (const id
of chargingStation
.connectors
.keys()) {
1078 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1081 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1086 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1089 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1092 private async handleRequestChangeAvailability (
1093 chargingStation
: ChargingStation
,
1094 commandPayload
: OCPP16ChangeAvailabilityRequest
1095 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1096 const { connectorId
, type } = commandPayload
1097 if (!chargingStation
.hasConnector(connectorId
)) {
1099 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1101 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1103 const chargePointStatus
: OCPP16ChargePointStatus
=
1104 type === OCPP16AvailabilityType
.Operative
1105 ? OCPP16ChargePointStatus
.Available
1106 : OCPP16ChargePointStatus
.Unavailable
1107 if (connectorId
=== 0) {
1108 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1109 if (chargingStation
.hasEvses
) {
1110 for (const evseStatus
of chargingStation
.evses
.values()) {
1111 response
= await OCPP16ServiceUtils
.changeAvailability(
1113 [...evseStatus
.connectors
.keys()],
1119 response
= await OCPP16ServiceUtils
.changeAvailability(
1121 [...chargingStation
.connectors
.keys()],
1126 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1130 (chargingStation
.isChargingStationAvailable() ||
1131 (!chargingStation
.isChargingStationAvailable() &&
1132 type === OCPP16AvailabilityType
.Inoperative
))
1134 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1135 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1136 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1137 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1139 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1140 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1141 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1146 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1148 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1151 private async handleRequestRemoteStartTransaction (
1152 chargingStation
: ChargingStation
,
1153 commandPayload
: RemoteStartTransactionRequest
1154 ): Promise
<GenericResponse
> {
1155 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1156 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1157 return this.notifyRemoteStartTransactionRejected(
1159 transactionConnectorId
,
1164 !chargingStation
.isChargingStationAvailable() ||
1165 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1167 return this.notifyRemoteStartTransactionRejected(
1169 transactionConnectorId
,
1173 // idTag authorization check required
1175 chargingStation
.getAuthorizeRemoteTxRequests() &&
1176 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1178 return this.notifyRemoteStartTransactionRejected(
1180 transactionConnectorId
,
1185 chargingProfile
!= null &&
1186 !this.setRemoteStartTransactionChargingProfile(
1188 transactionConnectorId
,
1192 return this.notifyRemoteStartTransactionRejected(
1194 transactionConnectorId
,
1199 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${transactionConnectorId}}, idTag '${idTag}'`
1201 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1204 private notifyRemoteStartTransactionRejected (
1205 chargingStation
: ChargingStation
,
1206 connectorId
: number,
1208 ): GenericResponse
{
1209 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1211 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1213 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1216 private setRemoteStartTransactionChargingProfile (
1217 chargingStation
: ChargingStation
,
1218 connectorId
: number,
1219 chargingProfile
: OCPP16ChargingProfile
1221 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1222 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1224 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on ${chargingStation.stationInfo?.chargingStationId}#${connectorId}`,
1230 `${chargingStation.logPrefix()} Not allowed to set ${
1231 chargingProfile.chargingProfilePurpose
1232 } charging profile(s) at remote start transaction`
1237 private handleRequestRemoteStopTransaction (
1238 chargingStation
: ChargingStation
,
1239 commandPayload
: RemoteStopTransactionRequest
1240 ): GenericResponse
{
1241 const { transactionId
} = commandPayload
1242 if (chargingStation
.getConnectorIdByTransactionId(transactionId
) != null) {
1244 `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED for transactionId '${transactionId}'`
1246 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1249 `${chargingStation.logPrefix()} Remote stop transaction REJECTED for transactionId '${transactionId}'`
1251 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1254 private handleRequestUpdateFirmware (
1255 chargingStation
: ChargingStation
,
1256 commandPayload
: OCPP16UpdateFirmwareRequest
1257 ): OCPP16UpdateFirmwareResponse
{
1259 !OCPP16ServiceUtils
.checkFeatureProfile(
1261 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1262 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1266 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1268 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1270 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1271 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1272 const { retrieveDate
} = commandPayload
1273 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1275 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1277 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1279 const now
= Date.now()
1280 if (retrieveDate
.getTime() <= now
) {
1281 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1284 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1285 }, retrieveDate
.getTime() - now
)
1287 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1290 private async updateFirmwareSimulation (
1291 chargingStation
: ChargingStation
,
1295 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1298 if (chargingStation
.hasEvses
) {
1299 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1301 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1302 if (connectorStatus
.transactionStarted
=== false) {
1303 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1306 OCPP16ChargePointStatus
.Unavailable
1313 for (const connectorId
of chargingStation
.connectors
.keys()) {
1316 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1318 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1321 OCPP16ChargePointStatus
.Unavailable
1326 await chargingStation
.ocppRequestService
.requestHandler
<
1327 OCPP16FirmwareStatusNotificationRequest
,
1328 OCPP16FirmwareStatusNotificationResponse
1329 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1330 status: OCPP16FirmwareStatus
.Downloading
1332 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1333 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1335 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1336 OCPP16FirmwareStatus
.DownloadFailed
1338 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1339 await chargingStation
.ocppRequestService
.requestHandler
<
1340 OCPP16FirmwareStatusNotificationRequest
,
1341 OCPP16FirmwareStatusNotificationResponse
1342 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1343 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1345 chargingStation
.stationInfo
.firmwareStatus
=
1346 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1349 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1350 await chargingStation
.ocppRequestService
.requestHandler
<
1351 OCPP16FirmwareStatusNotificationRequest
,
1352 OCPP16FirmwareStatusNotificationResponse
1353 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1354 status: OCPP16FirmwareStatus
.Downloaded
1356 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1357 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1358 let wasTransactionsStarted
= false
1359 let transactionsStarted
: boolean
1361 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1362 if (runningTransactions
> 0) {
1363 const waitTime
= secondsToMilliseconds(15)
1365 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1367 )} before continuing firmware update simulation`
1369 await sleep(waitTime
)
1370 transactionsStarted
= true
1371 wasTransactionsStarted
= true
1373 if (chargingStation
.hasEvses
) {
1374 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1376 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1377 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1378 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1381 OCPP16ChargePointStatus
.Unavailable
1388 for (const connectorId
of chargingStation
.connectors
.keys()) {
1391 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1392 OCPP16ChargePointStatus
.Unavailable
1394 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1397 OCPP16ChargePointStatus
.Unavailable
1402 transactionsStarted
= false
1404 } while (transactionsStarted
)
1405 !wasTransactionsStarted
&& (await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
))))
1406 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1409 await chargingStation
.ocppRequestService
.requestHandler
<
1410 OCPP16FirmwareStatusNotificationRequest
,
1411 OCPP16FirmwareStatusNotificationResponse
1412 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1413 status: OCPP16FirmwareStatus
.Installing
1415 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1416 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1418 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1419 OCPP16FirmwareStatus
.InstallationFailed
1421 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1422 await chargingStation
.ocppRequestService
.requestHandler
<
1423 OCPP16FirmwareStatusNotificationRequest
,
1424 OCPP16FirmwareStatusNotificationResponse
1425 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1426 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1428 chargingStation
.stationInfo
.firmwareStatus
=
1429 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1432 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1433 await sleep(secondsToMilliseconds(randomInt(minDelay
, maxDelay
)))
1434 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1438 private async handleRequestGetDiagnostics (
1439 chargingStation
: ChargingStation
,
1440 commandPayload
: GetDiagnosticsRequest
1441 ): Promise
<GetDiagnosticsResponse
> {
1443 !OCPP16ServiceUtils
.checkFeatureProfile(
1445 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1446 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1450 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1452 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1454 const { location
} = commandPayload
1455 const uri
= new URL(location
)
1456 if (uri
.protocol
.startsWith('ftp:')) {
1457 let ftpClient
: Client
| undefined
1459 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
1460 ConfigurationSection
.log
1462 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1463 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1464 .filter(file
=> file
.endsWith(extname(logConfiguration
.file
!)))
1465 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1466 .map(file
=> join(dirname(logConfiguration
.file
!), file
))
1467 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1468 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1469 ftpClient
= new Client()
1470 const accessResponse
= await ftpClient
.access({
1472 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1473 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1474 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1476 let uploadResponse
: FTPResponse
| undefined
1477 if (accessResponse
.code
=== 220) {
1478 ftpClient
.trackProgress(info
=> {
1480 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1482 } bytes transferred from diagnostics archive ${info.name}`
1484 chargingStation
.ocppRequestService
1486 OCPP16DiagnosticsStatusNotificationRequest
,
1487 OCPP16DiagnosticsStatusNotificationResponse
1488 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1489 status: OCPP16DiagnosticsStatus
.Uploading
1491 .catch((error
: unknown
) => {
1493 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1494 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1500 uploadResponse
= await ftpClient
.uploadFrom(
1501 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1502 `${uri.pathname}${diagnosticsArchive}`
1504 if (uploadResponse
.code
=== 226) {
1505 await chargingStation
.ocppRequestService
.requestHandler
<
1506 OCPP16DiagnosticsStatusNotificationRequest
,
1507 OCPP16DiagnosticsStatusNotificationResponse
1508 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1509 status: OCPP16DiagnosticsStatus
.Uploaded
1512 return { fileName
: diagnosticsArchive
}
1514 throw new OCPPError(
1515 ErrorType
.GENERIC_ERROR
,
1516 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1517 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1520 throw new OCPPError(
1521 ErrorType
.GENERIC_ERROR
,
1522 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1523 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1526 await chargingStation
.ocppRequestService
.requestHandler
<
1527 OCPP16DiagnosticsStatusNotificationRequest
,
1528 OCPP16DiagnosticsStatusNotificationResponse
1529 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1530 status: OCPP16DiagnosticsStatus
.UploadFailed
1533 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1534 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1536 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1538 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1543 `${chargingStation.logPrefix()} Unsupported protocol ${
1545 } to transfer the diagnostic logs archive`
1547 await chargingStation
.ocppRequestService
.requestHandler
<
1548 OCPP16DiagnosticsStatusNotificationRequest
,
1549 OCPP16DiagnosticsStatusNotificationResponse
1550 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1551 status: OCPP16DiagnosticsStatus
.UploadFailed
1553 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1557 private handleRequestTriggerMessage (
1558 chargingStation
: ChargingStation
,
1559 commandPayload
: OCPP16TriggerMessageRequest
1560 ): OCPP16TriggerMessageResponse
{
1561 const { requestedMessage
, connectorId
} = commandPayload
1563 !OCPP16ServiceUtils
.checkFeatureProfile(
1565 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1566 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1568 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1570 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1573 !OCPP16ServiceUtils
.isConnectorIdValid(
1575 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1576 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1580 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1582 switch (requestedMessage
) {
1583 case OCPP16MessageTrigger
.BootNotification
:
1584 case OCPP16MessageTrigger
.Heartbeat
:
1585 case OCPP16MessageTrigger
.StatusNotification
:
1586 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1588 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1592 private handleRequestDataTransfer (
1593 chargingStation
: ChargingStation
,
1594 commandPayload
: OCPP16DataTransferRequest
1595 ): OCPP16DataTransferResponse
{
1596 const { vendorId
} = commandPayload
1598 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1599 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1601 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1603 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1604 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1606 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1608 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1613 private async handleRequestReserveNow (
1614 chargingStation
: ChargingStation
,
1615 commandPayload
: OCPP16ReserveNowRequest
1616 ): Promise
<OCPP16ReserveNowResponse
> {
1618 !OCPP16ServiceUtils
.checkFeatureProfile(
1620 OCPP16SupportedFeatureProfiles
.Reservation
,
1621 OCPP16IncomingRequestCommand
.RESERVE_NOW
1624 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1626 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1627 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1628 const { reservationId
, idTag
, connectorId
} = commandPayload
1629 let response
: OCPP16ReserveNowResponse
1631 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1632 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1634 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1635 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1637 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1638 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1640 await removeExpiredReservations(chargingStation
)
1641 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1642 case OCPP16ChargePointStatus
.Faulted
:
1643 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1645 case OCPP16ChargePointStatus
.Preparing
:
1646 case OCPP16ChargePointStatus
.Charging
:
1647 case OCPP16ChargePointStatus
.SuspendedEV
:
1648 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1649 case OCPP16ChargePointStatus
.Finishing
:
1650 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1652 case OCPP16ChargePointStatus
.Unavailable
:
1653 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1655 case OCPP16ChargePointStatus
.Reserved
:
1656 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1657 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1660 // eslint-disable-next-line no-fallthrough
1662 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1663 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1666 await chargingStation
.addReservation({
1667 id
: commandPayload
.reservationId
,
1670 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1675 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1676 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1677 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1678 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1680 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1682 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1687 private async handleRequestCancelReservation (
1688 chargingStation
: ChargingStation
,
1689 commandPayload
: OCPP16CancelReservationRequest
1690 ): Promise
<GenericResponse
> {
1692 !OCPP16ServiceUtils
.checkFeatureProfile(
1694 OCPP16SupportedFeatureProfiles
.Reservation
,
1695 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1698 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1701 const { reservationId
} = commandPayload
1702 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1703 if (reservation
== null) {
1705 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1707 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1709 await chargingStation
.removeReservation(
1711 ReservationTerminationReason
.RESERVATION_CANCELED
1713 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1715 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1716 return this.handleIncomingRequestError
<GenericResponse
>(
1718 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1720 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}