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 OCPP16TriggerMessageStatus
,
87 type OCPP16UpdateFirmwareRequest
,
88 type OCPP16UpdateFirmwareResponse
,
89 type OCPPConfigurationKey
,
91 type RemoteStartTransactionRequest
,
92 type RemoteStopTransactionRequest
,
93 ReservationTerminationReason
,
95 type SetChargingProfileRequest
,
96 type SetChargingProfileResponse
,
97 type UnlockConnectorRequest
,
98 type UnlockConnectorResponse
99 } from
'../../../types/index.js'
104 formatDurationMilliSeconds
,
111 } from
'../../../utils/index.js'
112 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService.js'
114 const moduleName
= 'OCPP16IncomingRequestService'
116 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
117 protected payloadValidateFunctions
: Map
<OCPP16IncomingRequestCommand
, ValidateFunction
<JsonType
>>
119 private readonly incomingRequestHandlers
: Map
<
120 OCPP16IncomingRequestCommand
,
121 IncomingRequestHandler
124 public constructor () {
125 // if (new.target.name === moduleName) {
126 // throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
128 super(OCPPVersion
.VERSION_16
)
129 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
131 OCPP16IncomingRequestCommand
.RESET
,
132 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
135 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
136 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
139 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
140 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
143 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
144 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
147 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
148 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
151 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
152 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
155 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
156 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
159 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
160 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
163 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
164 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
167 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
168 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
171 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
172 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
175 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
176 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
179 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
180 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
183 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
184 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
187 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
188 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
191 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
192 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
195 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
196 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
199 this.payloadValidateFunctions
= new Map
<
200 OCPP16IncomingRequestCommand
,
201 ValidateFunction
<JsonType
>
204 OCPP16IncomingRequestCommand
.RESET
,
207 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
208 'assets/json-schemas/ocpp/1.6/Reset.json',
216 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
219 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
220 'assets/json-schemas/ocpp/1.6/ClearCache.json',
228 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
231 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
232 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
240 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
243 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
244 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
252 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
255 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
256 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
264 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
267 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
268 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
276 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
279 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
280 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
288 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
291 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
292 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
300 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
303 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearChargingProfileRequest
>(
304 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
312 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
315 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
316 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
324 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
327 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
328 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
336 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
339 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
340 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
348 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
351 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
352 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
360 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
363 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
364 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
372 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
375 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
376 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
384 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
387 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
388 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
396 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
399 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
400 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
409 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
411 chargingStation
: ChargingStation
,
412 request
: RemoteStartTransactionRequest
,
413 response
: GenericResponse
415 if (response
.status === GenericStatus
.Accepted
) {
416 const { connectorId
, idTag
} = request
417 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
418 chargingStation
.getConnectorStatus(connectorId
)!.transactionRemoteStarted
= true
419 chargingStation
.ocppRequestService
420 .requestHandler
<OCPP16StartTransactionRequest
, OCPP16StartTransactionResponse
>(
422 OCPP16RequestCommand
.START_TRANSACTION
,
429 if (response
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
431 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
435 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
441 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`,
449 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
451 chargingStation
: ChargingStation
,
452 request
: OCPP16TriggerMessageRequest
,
453 response
: OCPP16TriggerMessageResponse
455 if (response
.status !== OCPP16TriggerMessageStatus
.ACCEPTED
) {
458 const { requestedMessage
, connectorId
} = request
459 const errorHandler
= (error
: Error): void => {
461 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger ${requestedMessage} error:`,
465 switch (requestedMessage
) {
466 case OCPP16MessageTrigger
.BootNotification
:
467 chargingStation
.ocppRequestService
468 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
470 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
471 chargingStation
.bootNotificationRequest
,
472 { skipBufferingOnError
: true, triggerMessage
: true }
475 chargingStation
.bootNotificationResponse
= response
479 case OCPP16MessageTrigger
.Heartbeat
:
480 chargingStation
.ocppRequestService
481 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
483 OCPP16RequestCommand
.HEARTBEAT
,
491 case OCPP16MessageTrigger
.StatusNotification
:
492 if (connectorId
!= null) {
493 chargingStation
.ocppRequestService
494 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
496 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
499 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
500 status: chargingStation
.getConnectorStatus(connectorId
)?.status
507 } else if (chargingStation
.hasEvses
) {
508 for (const evseStatus
of chargingStation
.evses
.values()) {
509 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
510 chargingStation
.ocppRequestService
512 OCPP16StatusNotificationRequest
,
513 OCPP16StatusNotificationResponse
516 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
519 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
520 status: connectorStatus
.status
530 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
531 chargingStation
.ocppRequestService
533 OCPP16StatusNotificationRequest
,
534 OCPP16StatusNotificationResponse
537 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
540 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
541 status: connectorStatus
.status
554 this.validatePayload
= this.validatePayload
.bind(this)
557 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
558 chargingStation
: ChargingStation
,
560 commandName
: OCPP16IncomingRequestCommand
,
561 commandPayload
: ReqType
563 let response
: ResType
565 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
566 chargingStation
.inPendingState() &&
567 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
568 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
571 ErrorType
.SECURITY_ERROR
,
572 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
576 )} while the charging station is in pending state on the central server`,
582 chargingStation
.isRegistered() ||
583 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
584 chargingStation
.inUnknownState())
587 this.incomingRequestHandlers
.has(commandName
) &&
588 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
591 this.validatePayload(chargingStation
, commandName
, commandPayload
)
592 // Call the method to build the response
593 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
594 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
598 this.emit(commandName
, chargingStation
, commandPayload
, response
)
602 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
610 ErrorType
.NOT_IMPLEMENTED
,
611 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
622 ErrorType
.SECURITY_ERROR
,
623 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
627 )} while the charging station is not registered on the central server.`,
632 // Send the built response
633 await chargingStation
.ocppRequestService
.sendResponse(
641 private validatePayload (
642 chargingStation
: ChargingStation
,
643 commandName
: OCPP16IncomingRequestCommand
,
644 commandPayload
: JsonType
646 if (this.payloadValidateFunctions
.has(commandName
)) {
647 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
650 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
655 // Simulate charging station restart
656 private handleRequestReset (
657 chargingStation
: ChargingStation
,
658 commandPayload
: ResetRequest
660 const { type } = commandPayload
662 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
663 .catch(Constants
.EMPTY_FUNCTION
)
665 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
666 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
667 chargingStation.stationInfo!.resetTime!
670 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
673 private async handleRequestUnlockConnector (
674 chargingStation
: ChargingStation
,
675 commandPayload
: UnlockConnectorRequest
676 ): Promise
<UnlockConnectorResponse
> {
677 const { connectorId
} = commandPayload
678 if (!chargingStation
.hasConnector(connectorId
)) {
680 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
682 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
684 if (connectorId
=== 0) {
685 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
686 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
688 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
689 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
691 OCPP16StopTransactionReason
.UNLOCK_COMMAND
693 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
694 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
696 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
698 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
701 OCPP16ChargePointStatus
.Available
703 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
706 private handleRequestGetConfiguration (
707 chargingStation
: ChargingStation
,
708 commandPayload
: GetConfigurationRequest
709 ): GetConfigurationResponse
{
710 const { key
} = commandPayload
711 const configurationKey
: OCPPConfigurationKey
[] = []
712 const unknownKey
: string[] = []
714 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
715 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
716 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
719 configurationKey
.push({
721 readonly: configKey
.readonly,
722 value
: configKey
.value
725 } else if (isNotEmptyArray(key
)) {
726 for (const k
of key
) {
727 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
728 if (keyFound
!= null) {
729 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
732 configurationKey
.push({
734 readonly: keyFound
.readonly,
735 value
: keyFound
.value
748 private handleRequestChangeConfiguration (
749 chargingStation
: ChargingStation
,
750 commandPayload
: ChangeConfigurationRequest
751 ): ChangeConfigurationResponse
{
752 const { key
, value
} = commandPayload
753 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
754 if (keyToChange
?.readonly === true) {
755 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
756 } else if (keyToChange
?.readonly === false) {
757 let valueChanged
= false
758 if (keyToChange
.value
!== value
) {
759 setConfigurationKeyValue(chargingStation
, key
, value
, true)
762 let triggerHeartbeatRestart
= false
764 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
765 OCPP16StandardParametersKey
.HeartBeatInterval
&&
768 setConfigurationKeyValue(
770 OCPP16StandardParametersKey
.HeartbeatInterval
,
773 triggerHeartbeatRestart
= true
776 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
777 OCPP16StandardParametersKey
.HeartbeatInterval
&&
780 setConfigurationKeyValue(
782 OCPP16StandardParametersKey
.HeartBeatInterval
,
785 triggerHeartbeatRestart
= true
787 if (triggerHeartbeatRestart
) {
788 chargingStation
.restartHeartbeat()
791 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
792 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
795 chargingStation
.restartWebSocketPing()
797 if (keyToChange
.reboot
=== true) {
798 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
800 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
802 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
805 private handleRequestSetChargingProfile (
806 chargingStation
: ChargingStation
,
807 commandPayload
: SetChargingProfileRequest
808 ): SetChargingProfileResponse
{
810 !OCPP16ServiceUtils
.checkFeatureProfile(
812 OCPP16SupportedFeatureProfiles
.SmartCharging
,
813 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
816 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
818 const { connectorId
, csChargingProfiles
} = commandPayload
819 if (!chargingStation
.hasConnector(connectorId
)) {
821 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
823 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
826 csChargingProfiles
.chargingProfilePurpose
===
827 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
830 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
833 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
837 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
839 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
841 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
843 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
845 connectorStatus
?.transactionStarted
=== false
848 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
850 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
853 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
855 connectorStatus
?.transactionStarted
=== true &&
856 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
859 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
860 csChargingProfiles.transactionId
861 } than the started transaction id ${connectorStatus.transactionId}`
863 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
865 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
867 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
870 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
873 private handleRequestGetCompositeSchedule (
874 chargingStation
: ChargingStation
,
875 commandPayload
: OCPP16GetCompositeScheduleRequest
876 ): OCPP16GetCompositeScheduleResponse
{
878 !OCPP16ServiceUtils
.checkFeatureProfile(
880 OCPP16SupportedFeatureProfiles
.SmartCharging
,
881 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
884 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
886 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
887 if (!chargingStation
.hasConnector(connectorId
)) {
889 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
891 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
893 if (connectorId
=== 0) {
895 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
897 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
899 if (chargingRateUnit
!= null) {
901 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
904 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
906 isEmptyArray(connectorStatus
?.chargingProfiles
) &&
907 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
909 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
911 const currentDate
= new Date()
912 const compositeScheduleInterval
: Interval
= {
914 end
: addSeconds(currentDate
, duration
)
916 // Get charging profiles sorted by connector id then stack level
917 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
921 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
922 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
923 for (const chargingProfile
of chargingProfiles
) {
924 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
926 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
927 chargingProfile.chargingProfileId
928 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
930 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
931 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
933 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
935 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
936 chargingProfile.chargingProfileId
937 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
939 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
940 chargingProfile
.chargingSchedule
.startSchedule
943 if (chargingProfile
.chargingSchedule
.duration
== null) {
945 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
946 chargingProfile.chargingProfileId
947 } has no duration defined and will be set to the maximum time allowed`
949 // OCPP specifies that if duration is not defined, it should be infinite
950 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
952 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
953 chargingProfile
.chargingSchedule
.startSchedule
!
957 !prepareChargingProfileKind(
960 compositeScheduleInterval
.start
,
961 chargingStation
.logPrefix()
967 !canProceedChargingProfile(
969 compositeScheduleInterval
.start
,
970 chargingStation
.logPrefix()
975 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
976 previousCompositeSchedule
,
977 chargingProfile
.chargingSchedule
,
978 compositeScheduleInterval
980 previousCompositeSchedule
= compositeSchedule
982 if (compositeSchedule
!= null) {
984 status: GenericStatus
.Accepted
,
985 scheduleStart
: compositeSchedule
.startSchedule
,
987 chargingSchedule
: compositeSchedule
990 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
993 private handleRequestClearChargingProfile (
994 chargingStation
: ChargingStation
,
995 commandPayload
: OCPP16ClearChargingProfileRequest
996 ): OCPP16ClearChargingProfileResponse
{
998 !OCPP16ServiceUtils
.checkFeatureProfile(
1000 OCPP16SupportedFeatureProfiles
.SmartCharging
,
1001 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
1004 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1006 const { connectorId
} = commandPayload
1007 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1008 if (!chargingStation
.hasConnector(connectorId
!)) {
1010 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
1012 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1014 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1015 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!)
1016 if (connectorId
!= null && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1017 connectorStatus
.chargingProfiles
= []
1019 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1021 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1023 if (connectorId
== null) {
1024 let clearedCP
= false
1025 if (chargingStation
.hasEvses
) {
1026 for (const evseStatus
of chargingStation
.evses
.values()) {
1027 for (const status of evseStatus
.connectors
.values()) {
1028 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1031 status.chargingProfiles
1036 for (const id
of chargingStation
.connectors
.keys()) {
1037 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1040 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1045 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1048 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1051 private async handleRequestChangeAvailability (
1052 chargingStation
: ChargingStation
,
1053 commandPayload
: OCPP16ChangeAvailabilityRequest
1054 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1055 const { connectorId
, type } = commandPayload
1056 if (!chargingStation
.hasConnector(connectorId
)) {
1058 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1060 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1062 const chargePointStatus
: OCPP16ChargePointStatus
=
1063 type === OCPP16AvailabilityType
.Operative
1064 ? OCPP16ChargePointStatus
.Available
1065 : OCPP16ChargePointStatus
.Unavailable
1066 if (connectorId
=== 0) {
1067 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1068 if (chargingStation
.hasEvses
) {
1069 for (const evseStatus
of chargingStation
.evses
.values()) {
1070 response
= await OCPP16ServiceUtils
.changeAvailability(
1072 [...evseStatus
.connectors
.keys()],
1078 response
= await OCPP16ServiceUtils
.changeAvailability(
1080 [...chargingStation
.connectors
.keys()],
1085 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1089 (chargingStation
.isChargingStationAvailable() ||
1090 (!chargingStation
.isChargingStationAvailable() &&
1091 type === OCPP16AvailabilityType
.Inoperative
))
1093 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1094 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1095 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1096 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1098 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1099 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1100 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1105 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1107 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1110 private async handleRequestRemoteStartTransaction (
1111 chargingStation
: ChargingStation
,
1112 commandPayload
: RemoteStartTransactionRequest
1113 ): Promise
<GenericResponse
> {
1114 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1115 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1116 return await this.notifyRemoteStartTransactionRejected(
1118 transactionConnectorId
,
1123 !chargingStation
.isChargingStationAvailable() ||
1124 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1126 return await this.notifyRemoteStartTransactionRejected(
1128 transactionConnectorId
,
1132 // idTag authorization check required
1134 chargingStation
.getAuthorizeRemoteTxRequests() &&
1135 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1137 return await this.notifyRemoteStartTransactionRejected(
1139 transactionConnectorId
,
1143 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1145 transactionConnectorId
,
1146 OCPP16ChargePointStatus
.Preparing
1149 chargingProfile
!= null &&
1150 !this.setRemoteStartTransactionChargingProfile(
1152 transactionConnectorId
,
1156 return await this.notifyRemoteStartTransactionRejected(
1158 transactionConnectorId
,
1162 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1165 private async notifyRemoteStartTransactionRejected (
1166 chargingStation
: ChargingStation
,
1167 connectorId
: number,
1169 ): Promise
<GenericResponse
> {
1170 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1171 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1172 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1175 OCPP16ChargePointStatus
.Available
1179 `${chargingStation.logPrefix()} Remote start transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1181 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1184 private setRemoteStartTransactionChargingProfile (
1185 chargingStation
: ChargingStation
,
1186 connectorId
: number,
1187 chargingProfile
: OCPP16ChargingProfile
1189 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1190 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1192 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1198 `${chargingStation.logPrefix()} Not allowed to set ${
1199 chargingProfile.chargingProfilePurpose
1200 } charging profile(s) at remote start transaction`
1205 private async handleRequestRemoteStopTransaction (
1206 chargingStation
: ChargingStation
,
1207 commandPayload
: RemoteStopTransactionRequest
1208 ): Promise
<GenericResponse
> {
1209 const { transactionId
} = commandPayload
1210 if (chargingStation
.hasEvses
) {
1211 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1213 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1214 if (connectorStatus
.transactionId
=== transactionId
) {
1215 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1221 for (const connectorId
of chargingStation
.connectors
.keys()) {
1224 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1226 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1231 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`
1233 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1236 private handleRequestUpdateFirmware (
1237 chargingStation
: ChargingStation
,
1238 commandPayload
: OCPP16UpdateFirmwareRequest
1239 ): OCPP16UpdateFirmwareResponse
{
1241 !OCPP16ServiceUtils
.checkFeatureProfile(
1243 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1244 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1248 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1250 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1252 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1253 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1254 const { retrieveDate
} = commandPayload
1255 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1257 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1259 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1261 const now
= Date.now()
1262 if (retrieveDate
.getTime() <= now
) {
1263 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1266 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1267 }, retrieveDate
.getTime() - now
)
1269 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1272 private async updateFirmwareSimulation (
1273 chargingStation
: ChargingStation
,
1277 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1280 if (chargingStation
.hasEvses
) {
1281 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1283 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1284 if (connectorStatus
.transactionStarted
=== false) {
1285 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1288 OCPP16ChargePointStatus
.Unavailable
1295 for (const connectorId
of chargingStation
.connectors
.keys()) {
1298 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1300 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1303 OCPP16ChargePointStatus
.Unavailable
1308 await chargingStation
.ocppRequestService
.requestHandler
<
1309 OCPP16FirmwareStatusNotificationRequest
,
1310 OCPP16FirmwareStatusNotificationResponse
1311 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1312 status: OCPP16FirmwareStatus
.Downloading
1314 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1315 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1317 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1318 OCPP16FirmwareStatus
.DownloadFailed
1320 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1321 await chargingStation
.ocppRequestService
.requestHandler
<
1322 OCPP16FirmwareStatusNotificationRequest
,
1323 OCPP16FirmwareStatusNotificationResponse
1324 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1325 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1327 chargingStation
.stationInfo
.firmwareStatus
=
1328 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1331 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1332 await chargingStation
.ocppRequestService
.requestHandler
<
1333 OCPP16FirmwareStatusNotificationRequest
,
1334 OCPP16FirmwareStatusNotificationResponse
1335 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1336 status: OCPP16FirmwareStatus
.Downloaded
1338 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1339 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1340 let wasTransactionsStarted
= false
1341 let transactionsStarted
: boolean
1343 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1344 if (runningTransactions
> 0) {
1345 const waitTime
= secondsToMilliseconds(15)
1347 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1349 )} before continuing firmware update simulation`
1351 await sleep(waitTime
)
1352 transactionsStarted
= true
1353 wasTransactionsStarted
= true
1355 if (chargingStation
.hasEvses
) {
1356 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1358 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1359 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1360 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1363 OCPP16ChargePointStatus
.Unavailable
1370 for (const connectorId
of chargingStation
.connectors
.keys()) {
1373 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1374 OCPP16ChargePointStatus
.Unavailable
1376 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1379 OCPP16ChargePointStatus
.Unavailable
1384 transactionsStarted
= false
1386 } while (transactionsStarted
)
1387 !wasTransactionsStarted
&&
1388 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))))
1389 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1392 await chargingStation
.ocppRequestService
.requestHandler
<
1393 OCPP16FirmwareStatusNotificationRequest
,
1394 OCPP16FirmwareStatusNotificationResponse
1395 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1396 status: OCPP16FirmwareStatus
.Installing
1398 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1399 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1401 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1402 OCPP16FirmwareStatus
.InstallationFailed
1404 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1405 await chargingStation
.ocppRequestService
.requestHandler
<
1406 OCPP16FirmwareStatusNotificationRequest
,
1407 OCPP16FirmwareStatusNotificationResponse
1408 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1409 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1411 chargingStation
.stationInfo
.firmwareStatus
=
1412 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1415 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1416 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1417 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1421 private async handleRequestGetDiagnostics (
1422 chargingStation
: ChargingStation
,
1423 commandPayload
: GetDiagnosticsRequest
1424 ): Promise
<GetDiagnosticsResponse
> {
1426 !OCPP16ServiceUtils
.checkFeatureProfile(
1428 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1429 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1433 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1435 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1437 const { location
} = commandPayload
1438 const uri
= new URL(location
)
1439 if (uri
.protocol
.startsWith('ftp:')) {
1440 let ftpClient
: Client
| undefined
1442 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1443 .filter(file
=> file
.endsWith('.log'))
1444 .map(file
=> join('./', file
))
1445 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1446 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1447 ftpClient
= new Client()
1448 const accessResponse
= await ftpClient
.access({
1450 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1451 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1452 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1454 let uploadResponse
: FTPResponse
| undefined
1455 if (accessResponse
.code
=== 220) {
1456 ftpClient
.trackProgress(info
=> {
1458 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1460 } bytes transferred from diagnostics archive ${info.name}`
1462 chargingStation
.ocppRequestService
1464 OCPP16DiagnosticsStatusNotificationRequest
,
1465 OCPP16DiagnosticsStatusNotificationResponse
1466 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1467 status: OCPP16DiagnosticsStatus
.Uploading
1471 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1472 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1478 uploadResponse
= await ftpClient
.uploadFrom(
1479 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1480 `${uri.pathname}${diagnosticsArchive}`
1482 if (uploadResponse
.code
=== 226) {
1483 await chargingStation
.ocppRequestService
.requestHandler
<
1484 OCPP16DiagnosticsStatusNotificationRequest
,
1485 OCPP16DiagnosticsStatusNotificationResponse
1486 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1487 status: OCPP16DiagnosticsStatus
.Uploaded
1490 return { fileName
: diagnosticsArchive
}
1492 throw new OCPPError(
1493 ErrorType
.GENERIC_ERROR
,
1494 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1495 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1498 throw new OCPPError(
1499 ErrorType
.GENERIC_ERROR
,
1500 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1501 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1504 await chargingStation
.ocppRequestService
.requestHandler
<
1505 OCPP16DiagnosticsStatusNotificationRequest
,
1506 OCPP16DiagnosticsStatusNotificationResponse
1507 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1508 status: OCPP16DiagnosticsStatus
.UploadFailed
1511 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1512 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1514 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1516 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1521 `${chargingStation.logPrefix()} Unsupported protocol ${
1523 } to transfer the diagnostic logs archive`
1525 await chargingStation
.ocppRequestService
.requestHandler
<
1526 OCPP16DiagnosticsStatusNotificationRequest
,
1527 OCPP16DiagnosticsStatusNotificationResponse
1528 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1529 status: OCPP16DiagnosticsStatus
.UploadFailed
1531 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1535 private handleRequestTriggerMessage (
1536 chargingStation
: ChargingStation
,
1537 commandPayload
: OCPP16TriggerMessageRequest
1538 ): OCPP16TriggerMessageResponse
{
1539 const { requestedMessage
, connectorId
} = commandPayload
1541 !OCPP16ServiceUtils
.checkFeatureProfile(
1543 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1544 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1546 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1548 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1551 !OCPP16ServiceUtils
.isConnectorIdValid(
1553 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1554 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1558 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1560 switch (requestedMessage
) {
1561 case OCPP16MessageTrigger
.BootNotification
:
1562 case OCPP16MessageTrigger
.Heartbeat
:
1563 case OCPP16MessageTrigger
.StatusNotification
:
1564 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1566 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1570 private handleRequestDataTransfer (
1571 chargingStation
: ChargingStation
,
1572 commandPayload
: OCPP16DataTransferRequest
1573 ): OCPP16DataTransferResponse
{
1574 const { vendorId
} = commandPayload
1576 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1577 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1579 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1581 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1582 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1584 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1586 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1591 private async handleRequestReserveNow (
1592 chargingStation
: ChargingStation
,
1593 commandPayload
: OCPP16ReserveNowRequest
1594 ): Promise
<OCPP16ReserveNowResponse
> {
1596 !OCPP16ServiceUtils
.checkFeatureProfile(
1598 OCPP16SupportedFeatureProfiles
.Reservation
,
1599 OCPP16IncomingRequestCommand
.RESERVE_NOW
1602 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1604 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1605 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1606 const { reservationId
, idTag
, connectorId
} = commandPayload
1607 let response
: OCPP16ReserveNowResponse
1609 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1610 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1612 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1613 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1615 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1616 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1618 await removeExpiredReservations(chargingStation
)
1619 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1620 case OCPP16ChargePointStatus
.Faulted
:
1621 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1623 case OCPP16ChargePointStatus
.Preparing
:
1624 case OCPP16ChargePointStatus
.Charging
:
1625 case OCPP16ChargePointStatus
.SuspendedEV
:
1626 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1627 case OCPP16ChargePointStatus
.Finishing
:
1628 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1630 case OCPP16ChargePointStatus
.Unavailable
:
1631 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1633 case OCPP16ChargePointStatus
.Reserved
:
1634 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1635 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1638 // eslint-disable-next-line no-fallthrough
1640 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1641 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1644 await chargingStation
.addReservation({
1645 id
: commandPayload
.reservationId
,
1648 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1653 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1654 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1655 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1656 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1658 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1660 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1665 private async handleRequestCancelReservation (
1666 chargingStation
: ChargingStation
,
1667 commandPayload
: OCPP16CancelReservationRequest
1668 ): Promise
<GenericResponse
> {
1670 !OCPP16ServiceUtils
.checkFeatureProfile(
1672 OCPP16SupportedFeatureProfiles
.Reservation
,
1673 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1676 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1679 const { reservationId
} = commandPayload
1680 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1681 if (reservation
== null) {
1683 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1685 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1687 await chargingStation
.removeReservation(
1689 ReservationTerminationReason
.RESERVATION_CANCELED
1691 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1693 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1694 return this.handleIncomingRequestError
<GenericResponse
>(
1696 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1698 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}