1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { createWriteStream
, readdirSync
} from
'node:fs'
4 import { dirname
, join
, resolve
} from
'node:path'
5 import { URL
, fileURLToPath
} from
'node:url'
7 import type { ValidateFunction
} from
'ajv'
8 import { Client
, type FTPResponse
} from
'basic-ftp'
16 import { maxTime
} from
'date-fns/constants'
17 import { create
} from
'tar'
19 import { OCPP16Constants
} from
'./OCPP16Constants.js'
20 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils.js'
23 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
,
38 type GetConfigurationRequest
,
39 type GetConfigurationResponse
,
40 type GetDiagnosticsRequest
,
41 type GetDiagnosticsResponse
,
42 type IncomingRequestHandler
,
44 OCPP16AuthorizationStatus
,
45 OCPP16AvailabilityType
,
46 type OCPP16BootNotificationRequest
,
47 type OCPP16BootNotificationResponse
,
48 type OCPP16CancelReservationRequest
,
49 type OCPP16ChangeAvailabilityRequest
,
50 type OCPP16ChangeAvailabilityResponse
,
51 OCPP16ChargePointErrorCode
,
52 OCPP16ChargePointStatus
,
53 type OCPP16ChargingProfile
,
54 OCPP16ChargingProfilePurposeType
,
55 type OCPP16ChargingSchedule
,
56 type OCPP16ClearCacheRequest
,
57 type OCPP16ClearChargingProfileRequest
,
58 type OCPP16ClearChargingProfileResponse
,
59 type OCPP16DataTransferRequest
,
60 type OCPP16DataTransferResponse
,
61 OCPP16DataTransferVendorId
,
62 OCPP16DiagnosticsStatus
,
63 type OCPP16DiagnosticsStatusNotificationRequest
,
64 type OCPP16DiagnosticsStatusNotificationResponse
,
66 type OCPP16FirmwareStatusNotificationRequest
,
67 type OCPP16FirmwareStatusNotificationResponse
,
68 type OCPP16GetCompositeScheduleRequest
,
69 type OCPP16GetCompositeScheduleResponse
,
70 type OCPP16HeartbeatRequest
,
71 type OCPP16HeartbeatResponse
,
72 OCPP16IncomingRequestCommand
,
75 type OCPP16ReserveNowRequest
,
76 type OCPP16ReserveNowResponse
,
77 OCPP16StandardParametersKey
,
78 type OCPP16StartTransactionRequest
,
79 type OCPP16StartTransactionResponse
,
80 type OCPP16StatusNotificationRequest
,
81 type OCPP16StatusNotificationResponse
,
82 OCPP16StopTransactionReason
,
83 OCPP16SupportedFeatureProfiles
,
84 type OCPP16TriggerMessageRequest
,
85 type OCPP16TriggerMessageResponse
,
86 type OCPP16UpdateFirmwareRequest
,
87 type OCPP16UpdateFirmwareResponse
,
88 type OCPPConfigurationKey
,
90 type RemoteStartTransactionRequest
,
91 type RemoteStopTransactionRequest
,
92 ReservationTerminationReason
,
94 type SetChargingProfileRequest
,
95 type SetChargingProfileResponse
,
96 type UnlockConnectorRequest
,
97 type UnlockConnectorResponse
98 } from
'../../../types/index.js'
103 formatDurationMilliSeconds
,
110 } from
'../../../utils/index.js'
111 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService.js'
113 const moduleName
= 'OCPP16IncomingRequestService'
115 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
116 protected payloadValidateFunctions
: Map
<OCPP16IncomingRequestCommand
, ValidateFunction
<JsonType
>>
118 private readonly incomingRequestHandlers
: Map
<
119 OCPP16IncomingRequestCommand
,
120 IncomingRequestHandler
123 public constructor () {
124 // if (new.target.name === moduleName) {
125 // throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
127 super(OCPPVersion
.VERSION_16
)
128 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
130 OCPP16IncomingRequestCommand
.RESET
,
131 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
134 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
135 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
138 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
139 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
142 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
143 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
146 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
147 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
150 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
151 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
154 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
155 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
158 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
159 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
162 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
163 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
166 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
167 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
170 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
171 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
174 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
175 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
178 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
179 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
182 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
183 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
186 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
187 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
190 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
191 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
194 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
195 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
198 this.payloadValidateFunctions
= new Map
<
199 OCPP16IncomingRequestCommand
,
200 ValidateFunction
<JsonType
>
203 OCPP16IncomingRequestCommand
.RESET
,
206 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
207 'assets/json-schemas/ocpp/1.6/Reset.json',
215 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
218 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
219 'assets/json-schemas/ocpp/1.6/ClearCache.json',
227 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
230 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
231 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
239 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
242 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
243 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
251 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
254 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
255 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
263 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
266 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
267 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
275 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
278 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
279 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
287 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
290 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
291 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
299 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
302 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearChargingProfileRequest
>(
303 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
311 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
314 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
315 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
323 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
326 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
327 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
335 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
338 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
339 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
347 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
350 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
351 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
359 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
362 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
363 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
371 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
374 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
375 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
383 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
386 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
387 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
395 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
398 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
399 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
408 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
409 (chargingStation
: ChargingStation
, connectorId
: number, idTag
: string) => {
410 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
411 chargingStation
.getConnectorStatus(connectorId
)!.transactionRemoteStarted
= true
412 chargingStation
.ocppRequestService
413 .requestHandler
<OCPP16StartTransactionRequest
, OCPP16StartTransactionResponse
>(
415 OCPP16RequestCommand
.START_TRANSACTION
,
422 if (response
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
424 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
428 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
434 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`,
441 `Trigger${OCPP16MessageTrigger.BootNotification}`,
442 (chargingStation
: ChargingStation
) => {
443 chargingStation
.ocppRequestService
444 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
446 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
447 chargingStation
.bootNotificationRequest
,
448 { skipBufferingOnError
: true, triggerMessage
: true }
451 chargingStation
.bootNotificationResponse
= response
455 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger boot notification error:`,
461 this.on(`Trigger${OCPP16MessageTrigger.Heartbeat}`, (chargingStation
: ChargingStation
) => {
462 chargingStation
.ocppRequestService
463 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
465 OCPP16RequestCommand
.HEARTBEAT
,
473 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger heartbeat error:`,
479 `$Trigger${OCPP16MessageTrigger.StatusNotification}`,
480 (chargingStation
: ChargingStation
, connectorId
?: number) => {
481 const errorHandler
= (error
: Error): void => {
483 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger status notification error:`,
487 if (connectorId
!= null) {
488 chargingStation
.ocppRequestService
489 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
491 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
494 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
495 status: chargingStation
.getConnectorStatus(connectorId
)?.status
502 } else if (chargingStation
.hasEvses
) {
503 for (const evseStatus
of chargingStation
.evses
.values()) {
504 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
505 chargingStation
.ocppRequestService
506 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
508 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
511 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
512 status: connectorStatus
.status
522 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
523 chargingStation
.ocppRequestService
524 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
526 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
529 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
530 status: connectorStatus
.status
541 this.validatePayload
= this.validatePayload
.bind(this)
544 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
545 chargingStation
: ChargingStation
,
547 commandName
: OCPP16IncomingRequestCommand
,
548 commandPayload
: ReqType
550 let response
: ResType
552 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
553 chargingStation
.inPendingState() &&
554 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
555 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
558 ErrorType
.SECURITY_ERROR
,
559 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
563 )} while the charging station is in pending state on the central server`,
569 chargingStation
.isRegistered() ||
570 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
571 chargingStation
.inUnknownState())
574 this.incomingRequestHandlers
.has(commandName
) &&
575 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
578 this.validatePayload(chargingStation
, commandName
, commandPayload
)
579 // Call the method to build the response
580 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
581 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
588 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
596 ErrorType
.NOT_IMPLEMENTED
,
597 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
608 ErrorType
.SECURITY_ERROR
,
609 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
613 )} while the charging station is not registered on the central server.`,
618 // Send the built response
619 await chargingStation
.ocppRequestService
.sendResponse(
627 private validatePayload (
628 chargingStation
: ChargingStation
,
629 commandName
: OCPP16IncomingRequestCommand
,
630 commandPayload
: JsonType
632 if (this.payloadValidateFunctions
.has(commandName
)) {
633 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
636 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
641 // Simulate charging station restart
642 private handleRequestReset (
643 chargingStation
: ChargingStation
,
644 commandPayload
: ResetRequest
646 const { type } = commandPayload
648 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
649 .catch(Constants
.EMPTY_FUNCTION
)
651 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
652 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
653 chargingStation.stationInfo!.resetTime!
656 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
659 private async handleRequestUnlockConnector (
660 chargingStation
: ChargingStation
,
661 commandPayload
: UnlockConnectorRequest
662 ): Promise
<UnlockConnectorResponse
> {
663 const { connectorId
} = commandPayload
664 if (!chargingStation
.hasConnector(connectorId
)) {
666 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
668 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
670 if (connectorId
=== 0) {
671 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
672 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
674 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
675 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
677 OCPP16StopTransactionReason
.UNLOCK_COMMAND
679 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
680 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
682 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
684 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
687 OCPP16ChargePointStatus
.Available
689 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
692 private handleRequestGetConfiguration (
693 chargingStation
: ChargingStation
,
694 commandPayload
: GetConfigurationRequest
695 ): GetConfigurationResponse
{
696 const { key
} = commandPayload
697 const configurationKey
: OCPPConfigurationKey
[] = []
698 const unknownKey
: string[] = []
700 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
701 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
702 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
705 configurationKey
.push({
707 readonly: configKey
.readonly,
708 value
: configKey
.value
711 } else if (isNotEmptyArray(key
)) {
712 for (const k
of key
) {
713 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
714 if (keyFound
!= null) {
715 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
718 configurationKey
.push({
720 readonly: keyFound
.readonly,
721 value
: keyFound
.value
734 private handleRequestChangeConfiguration (
735 chargingStation
: ChargingStation
,
736 commandPayload
: ChangeConfigurationRequest
737 ): ChangeConfigurationResponse
{
738 const { key
, value
} = commandPayload
739 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
740 if (keyToChange
?.readonly === true) {
741 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
742 } else if (keyToChange
?.readonly === false) {
743 let valueChanged
= false
744 if (keyToChange
.value
!== value
) {
745 setConfigurationKeyValue(chargingStation
, key
, value
, true)
748 let triggerHeartbeatRestart
= false
750 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
751 OCPP16StandardParametersKey
.HeartBeatInterval
&&
754 setConfigurationKeyValue(
756 OCPP16StandardParametersKey
.HeartbeatInterval
,
759 triggerHeartbeatRestart
= true
762 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
763 OCPP16StandardParametersKey
.HeartbeatInterval
&&
766 setConfigurationKeyValue(
768 OCPP16StandardParametersKey
.HeartBeatInterval
,
771 triggerHeartbeatRestart
= true
773 if (triggerHeartbeatRestart
) {
774 chargingStation
.restartHeartbeat()
777 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
778 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
781 chargingStation
.restartWebSocketPing()
783 if (keyToChange
.reboot
=== true) {
784 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
786 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
788 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
791 private handleRequestSetChargingProfile (
792 chargingStation
: ChargingStation
,
793 commandPayload
: SetChargingProfileRequest
794 ): SetChargingProfileResponse
{
796 !OCPP16ServiceUtils
.checkFeatureProfile(
798 OCPP16SupportedFeatureProfiles
.SmartCharging
,
799 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
802 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
804 const { connectorId
, csChargingProfiles
} = commandPayload
805 if (!chargingStation
.hasConnector(connectorId
)) {
807 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
809 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
812 csChargingProfiles
.chargingProfilePurpose
===
813 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
816 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
819 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
823 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
825 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
827 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
829 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
831 connectorStatus
?.transactionStarted
=== false
834 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
836 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
839 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
841 connectorStatus
?.transactionStarted
=== true &&
842 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
845 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
846 csChargingProfiles.transactionId
847 } than the started transaction id ${connectorStatus.transactionId}`
849 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
851 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
853 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
856 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
859 private handleRequestGetCompositeSchedule (
860 chargingStation
: ChargingStation
,
861 commandPayload
: OCPP16GetCompositeScheduleRequest
862 ): OCPP16GetCompositeScheduleResponse
{
864 !OCPP16ServiceUtils
.checkFeatureProfile(
866 OCPP16SupportedFeatureProfiles
.SmartCharging
,
867 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
870 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
872 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
873 if (!chargingStation
.hasConnector(connectorId
)) {
875 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
877 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
879 if (connectorId
=== 0) {
881 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
883 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
885 if (chargingRateUnit
!= null) {
887 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
890 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
892 isEmptyArray(connectorStatus
?.chargingProfiles
) &&
893 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
895 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
897 const currentDate
= new Date()
898 const compositeScheduleInterval
: Interval
= {
900 end
: addSeconds(currentDate
, duration
)
902 // Get charging profiles sorted by connector id then stack level
903 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
907 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
908 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
909 for (const chargingProfile
of chargingProfiles
) {
910 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
912 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
913 chargingProfile.chargingProfileId
914 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
916 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
917 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
919 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
921 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
922 chargingProfile.chargingProfileId
923 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
925 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
926 chargingProfile
.chargingSchedule
.startSchedule
929 if (chargingProfile
.chargingSchedule
.duration
== null) {
931 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
932 chargingProfile.chargingProfileId
933 } has no duration defined and will be set to the maximum time allowed`
935 // OCPP specifies that if duration is not defined, it should be infinite
936 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
938 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
939 chargingProfile
.chargingSchedule
.startSchedule
!
943 !prepareChargingProfileKind(
946 compositeScheduleInterval
.start
,
947 chargingStation
.logPrefix()
953 !canProceedChargingProfile(
955 compositeScheduleInterval
.start
,
956 chargingStation
.logPrefix()
961 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
962 previousCompositeSchedule
,
963 chargingProfile
.chargingSchedule
,
964 compositeScheduleInterval
966 previousCompositeSchedule
= compositeSchedule
968 if (compositeSchedule
!= null) {
970 status: GenericStatus
.Accepted
,
971 scheduleStart
: compositeSchedule
.startSchedule
,
973 chargingSchedule
: compositeSchedule
976 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
979 private handleRequestClearChargingProfile (
980 chargingStation
: ChargingStation
,
981 commandPayload
: OCPP16ClearChargingProfileRequest
982 ): OCPP16ClearChargingProfileResponse
{
984 !OCPP16ServiceUtils
.checkFeatureProfile(
986 OCPP16SupportedFeatureProfiles
.SmartCharging
,
987 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
990 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
992 const { connectorId
} = commandPayload
993 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
994 if (!chargingStation
.hasConnector(connectorId
!)) {
996 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
998 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1000 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1001 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!)
1002 if (connectorId
!= null && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1003 connectorStatus
.chargingProfiles
= []
1005 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1007 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1009 if (connectorId
== null) {
1010 let clearedCP
= false
1011 if (chargingStation
.hasEvses
) {
1012 for (const evseStatus
of chargingStation
.evses
.values()) {
1013 for (const status of evseStatus
.connectors
.values()) {
1014 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1017 status.chargingProfiles
1022 for (const id
of chargingStation
.connectors
.keys()) {
1023 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1026 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1031 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1034 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1037 private async handleRequestChangeAvailability (
1038 chargingStation
: ChargingStation
,
1039 commandPayload
: OCPP16ChangeAvailabilityRequest
1040 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1041 const { connectorId
, type } = commandPayload
1042 if (!chargingStation
.hasConnector(connectorId
)) {
1044 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1046 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1048 const chargePointStatus
: OCPP16ChargePointStatus
=
1049 type === OCPP16AvailabilityType
.Operative
1050 ? OCPP16ChargePointStatus
.Available
1051 : OCPP16ChargePointStatus
.Unavailable
1052 if (connectorId
=== 0) {
1053 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1054 if (chargingStation
.hasEvses
) {
1055 for (const evseStatus
of chargingStation
.evses
.values()) {
1056 response
= await OCPP16ServiceUtils
.changeAvailability(
1058 [...evseStatus
.connectors
.keys()],
1064 response
= await OCPP16ServiceUtils
.changeAvailability(
1066 [...chargingStation
.connectors
.keys()],
1071 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1075 (chargingStation
.isChargingStationAvailable() ||
1076 (!chargingStation
.isChargingStationAvailable() &&
1077 type === OCPP16AvailabilityType
.Inoperative
))
1079 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1080 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1081 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1082 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1084 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1085 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1086 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1091 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1093 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1096 private async handleRequestRemoteStartTransaction (
1097 chargingStation
: ChargingStation
,
1098 commandPayload
: RemoteStartTransactionRequest
1099 ): Promise
<GenericResponse
> {
1100 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1101 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1102 return await this.notifyRemoteStartTransactionRejected(
1104 transactionConnectorId
,
1109 !chargingStation
.isChargingStationAvailable() ||
1110 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1112 return await this.notifyRemoteStartTransactionRejected(
1114 transactionConnectorId
,
1118 // idTag authorization check required
1120 chargingStation
.getAuthorizeRemoteTxRequests() &&
1121 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1123 return await this.notifyRemoteStartTransactionRejected(
1125 transactionConnectorId
,
1129 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1131 transactionConnectorId
,
1132 OCPP16ChargePointStatus
.Preparing
1135 chargingProfile
!= null &&
1136 !this.setRemoteStartTransactionChargingProfile(
1138 transactionConnectorId
,
1142 return await this.notifyRemoteStartTransactionRejected(
1144 transactionConnectorId
,
1151 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
1153 transactionConnectorId
,
1157 .catch(Constants
.EMPTY_FUNCTION
)
1158 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1161 private async notifyRemoteStartTransactionRejected (
1162 chargingStation
: ChargingStation
,
1163 connectorId
: number,
1165 ): Promise
<GenericResponse
> {
1166 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1167 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1168 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1171 OCPP16ChargePointStatus
.Available
1175 `${chargingStation.logPrefix()} Remote start transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1177 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1180 private setRemoteStartTransactionChargingProfile (
1181 chargingStation
: ChargingStation
,
1182 connectorId
: number,
1183 chargingProfile
: OCPP16ChargingProfile
1185 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1186 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1188 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1194 `${chargingStation.logPrefix()} Not allowed to set ${
1195 chargingProfile.chargingProfilePurpose
1196 } charging profile(s) at remote start transaction`
1201 private async handleRequestRemoteStopTransaction (
1202 chargingStation
: ChargingStation
,
1203 commandPayload
: RemoteStopTransactionRequest
1204 ): Promise
<GenericResponse
> {
1205 const { transactionId
} = commandPayload
1206 if (chargingStation
.hasEvses
) {
1207 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1209 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1210 if (connectorStatus
.transactionId
=== transactionId
) {
1211 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1217 for (const connectorId
of chargingStation
.connectors
.keys()) {
1220 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1222 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1227 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`
1229 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1232 private handleRequestUpdateFirmware (
1233 chargingStation
: ChargingStation
,
1234 commandPayload
: OCPP16UpdateFirmwareRequest
1235 ): OCPP16UpdateFirmwareResponse
{
1237 !OCPP16ServiceUtils
.checkFeatureProfile(
1239 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1240 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1244 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1246 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1248 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1249 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1250 const { retrieveDate
} = commandPayload
1251 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1253 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1255 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1257 const now
= Date.now()
1258 if (retrieveDate
.getTime() <= now
) {
1259 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1262 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1263 }, retrieveDate
.getTime() - now
)
1265 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1268 private async updateFirmwareSimulation (
1269 chargingStation
: ChargingStation
,
1273 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1276 if (chargingStation
.hasEvses
) {
1277 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1279 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1280 if (connectorStatus
.transactionStarted
=== false) {
1281 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1284 OCPP16ChargePointStatus
.Unavailable
1291 for (const connectorId
of chargingStation
.connectors
.keys()) {
1294 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1296 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1299 OCPP16ChargePointStatus
.Unavailable
1304 await chargingStation
.ocppRequestService
.requestHandler
<
1305 OCPP16FirmwareStatusNotificationRequest
,
1306 OCPP16FirmwareStatusNotificationResponse
1307 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1308 status: OCPP16FirmwareStatus
.Downloading
1310 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1311 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1313 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1314 OCPP16FirmwareStatus
.DownloadFailed
1316 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1317 await chargingStation
.ocppRequestService
.requestHandler
<
1318 OCPP16FirmwareStatusNotificationRequest
,
1319 OCPP16FirmwareStatusNotificationResponse
1320 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1321 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1323 chargingStation
.stationInfo
.firmwareStatus
=
1324 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1327 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1328 await chargingStation
.ocppRequestService
.requestHandler
<
1329 OCPP16FirmwareStatusNotificationRequest
,
1330 OCPP16FirmwareStatusNotificationResponse
1331 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1332 status: OCPP16FirmwareStatus
.Downloaded
1334 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1335 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1336 let wasTransactionsStarted
= false
1337 let transactionsStarted
: boolean
1339 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1340 if (runningTransactions
> 0) {
1341 const waitTime
= secondsToMilliseconds(15)
1343 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1345 )} before continuing firmware update simulation`
1347 await sleep(waitTime
)
1348 transactionsStarted
= true
1349 wasTransactionsStarted
= true
1351 if (chargingStation
.hasEvses
) {
1352 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1354 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1355 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1356 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1359 OCPP16ChargePointStatus
.Unavailable
1366 for (const connectorId
of chargingStation
.connectors
.keys()) {
1369 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1370 OCPP16ChargePointStatus
.Unavailable
1372 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1375 OCPP16ChargePointStatus
.Unavailable
1380 transactionsStarted
= false
1382 } while (transactionsStarted
)
1383 !wasTransactionsStarted
&&
1384 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))))
1385 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1388 await chargingStation
.ocppRequestService
.requestHandler
<
1389 OCPP16FirmwareStatusNotificationRequest
,
1390 OCPP16FirmwareStatusNotificationResponse
1391 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1392 status: OCPP16FirmwareStatus
.Installing
1394 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1395 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1397 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1398 OCPP16FirmwareStatus
.InstallationFailed
1400 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1401 await chargingStation
.ocppRequestService
.requestHandler
<
1402 OCPP16FirmwareStatusNotificationRequest
,
1403 OCPP16FirmwareStatusNotificationResponse
1404 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1405 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1407 chargingStation
.stationInfo
.firmwareStatus
=
1408 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1411 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1412 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1413 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1417 private async handleRequestGetDiagnostics (
1418 chargingStation
: ChargingStation
,
1419 commandPayload
: GetDiagnosticsRequest
1420 ): Promise
<GetDiagnosticsResponse
> {
1422 !OCPP16ServiceUtils
.checkFeatureProfile(
1424 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1425 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1429 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1431 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1433 const { location
} = commandPayload
1434 const uri
= new URL(location
)
1435 if (uri
.protocol
.startsWith('ftp:')) {
1436 let ftpClient
: Client
| undefined
1438 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1439 .filter(file
=> file
.endsWith('.log'))
1440 .map(file
=> join('./', file
))
1441 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1442 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1443 ftpClient
= new Client()
1444 const accessResponse
= await ftpClient
.access({
1446 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1447 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1448 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1450 let uploadResponse
: FTPResponse
| undefined
1451 if (accessResponse
.code
=== 220) {
1452 ftpClient
.trackProgress(info
=> {
1454 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1456 } bytes transferred from diagnostics archive ${info.name}`
1458 chargingStation
.ocppRequestService
1460 OCPP16DiagnosticsStatusNotificationRequest
,
1461 OCPP16DiagnosticsStatusNotificationResponse
1462 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1463 status: OCPP16DiagnosticsStatus
.Uploading
1467 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1468 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1474 uploadResponse
= await ftpClient
.uploadFrom(
1475 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1476 `${uri.pathname}${diagnosticsArchive}`
1478 if (uploadResponse
.code
=== 226) {
1479 await chargingStation
.ocppRequestService
.requestHandler
<
1480 OCPP16DiagnosticsStatusNotificationRequest
,
1481 OCPP16DiagnosticsStatusNotificationResponse
1482 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1483 status: OCPP16DiagnosticsStatus
.Uploaded
1486 return { fileName
: diagnosticsArchive
}
1488 throw new OCPPError(
1489 ErrorType
.GENERIC_ERROR
,
1490 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1491 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1494 throw new OCPPError(
1495 ErrorType
.GENERIC_ERROR
,
1496 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1497 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1500 await chargingStation
.ocppRequestService
.requestHandler
<
1501 OCPP16DiagnosticsStatusNotificationRequest
,
1502 OCPP16DiagnosticsStatusNotificationResponse
1503 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1504 status: OCPP16DiagnosticsStatus
.UploadFailed
1507 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1508 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1510 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1512 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1517 `${chargingStation.logPrefix()} Unsupported protocol ${
1519 } to transfer the diagnostic logs archive`
1521 await chargingStation
.ocppRequestService
.requestHandler
<
1522 OCPP16DiagnosticsStatusNotificationRequest
,
1523 OCPP16DiagnosticsStatusNotificationResponse
1524 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1525 status: OCPP16DiagnosticsStatus
.UploadFailed
1527 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1531 private handleRequestTriggerMessage (
1532 chargingStation
: ChargingStation
,
1533 commandPayload
: OCPP16TriggerMessageRequest
1534 ): OCPP16TriggerMessageResponse
{
1535 const { requestedMessage
, connectorId
} = commandPayload
1537 !OCPP16ServiceUtils
.checkFeatureProfile(
1539 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1540 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1542 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1544 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1547 !OCPP16ServiceUtils
.isConnectorIdValid(
1549 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1550 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1554 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1556 switch (requestedMessage
) {
1557 case OCPP16MessageTrigger
.BootNotification
:
1559 .then(() => this.emit(`Trigger${OCPP16MessageTrigger.BootNotification}`, chargingStation
))
1560 .catch(Constants
.EMPTY_FUNCTION
)
1561 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1562 case OCPP16MessageTrigger
.Heartbeat
:
1564 .then(() => this.emit(`Trigger${OCPP16MessageTrigger.Heartbeat}`, chargingStation
))
1565 .catch(Constants
.EMPTY_FUNCTION
)
1566 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1567 case OCPP16MessageTrigger
.StatusNotification
:
1571 `Trigger${OCPP16MessageTrigger.StatusNotification}`,
1576 .catch(Constants
.EMPTY_FUNCTION
)
1577 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1579 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1583 private handleRequestDataTransfer (
1584 chargingStation
: ChargingStation
,
1585 commandPayload
: OCPP16DataTransferRequest
1586 ): OCPP16DataTransferResponse
{
1587 const { vendorId
} = commandPayload
1589 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1590 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1592 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1594 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1595 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1597 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1599 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1604 private async handleRequestReserveNow (
1605 chargingStation
: ChargingStation
,
1606 commandPayload
: OCPP16ReserveNowRequest
1607 ): Promise
<OCPP16ReserveNowResponse
> {
1609 !OCPP16ServiceUtils
.checkFeatureProfile(
1611 OCPP16SupportedFeatureProfiles
.Reservation
,
1612 OCPP16IncomingRequestCommand
.RESERVE_NOW
1615 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1617 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1618 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1619 const { reservationId
, idTag
, connectorId
} = commandPayload
1620 let response
: OCPP16ReserveNowResponse
1622 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1623 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1625 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1626 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1628 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1629 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1631 await removeExpiredReservations(chargingStation
)
1632 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1633 case OCPP16ChargePointStatus
.Faulted
:
1634 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1636 case OCPP16ChargePointStatus
.Preparing
:
1637 case OCPP16ChargePointStatus
.Charging
:
1638 case OCPP16ChargePointStatus
.SuspendedEV
:
1639 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1640 case OCPP16ChargePointStatus
.Finishing
:
1641 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1643 case OCPP16ChargePointStatus
.Unavailable
:
1644 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1646 case OCPP16ChargePointStatus
.Reserved
:
1647 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1648 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1651 // eslint-disable-next-line no-fallthrough
1653 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1654 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1657 await chargingStation
.addReservation({
1658 id
: commandPayload
.reservationId
,
1661 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1666 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1667 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1668 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1669 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1671 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1673 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1678 private async handleRequestCancelReservation (
1679 chargingStation
: ChargingStation
,
1680 commandPayload
: OCPP16CancelReservationRequest
1681 ): Promise
<GenericResponse
> {
1683 !OCPP16ServiceUtils
.checkFeatureProfile(
1685 OCPP16SupportedFeatureProfiles
.Reservation
,
1686 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1689 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1692 const { reservationId
} = commandPayload
1693 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1694 if (reservation
== null) {
1696 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1698 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1700 await chargingStation
.removeReservation(
1702 ReservationTerminationReason
.RESERVATION_CANCELED
1704 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1706 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1707 return this.handleIncomingRequestError
<GenericResponse
>(
1709 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1711 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}