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',
408 // Handle incoming request events
410 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
412 chargingStation
: ChargingStation
,
413 request
: RemoteStartTransactionRequest
,
414 response
: GenericResponse
416 if (response
.status === GenericStatus
.Accepted
) {
417 const { connectorId
, idTag
} = request
418 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
419 chargingStation
.getConnectorStatus(connectorId
)!.transactionRemoteStarted
= true
420 chargingStation
.ocppRequestService
421 .requestHandler
<OCPP16StartTransactionRequest
, OCPP16StartTransactionResponse
>(
423 OCPP16RequestCommand
.START_TRANSACTION
,
430 if (response
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
432 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
436 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
442 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`,
450 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
452 chargingStation
: ChargingStation
,
453 request
: OCPP16TriggerMessageRequest
,
454 response
: OCPP16TriggerMessageResponse
456 if (response
.status !== OCPP16TriggerMessageStatus
.ACCEPTED
) {
459 const { requestedMessage
, connectorId
} = request
460 const errorHandler
= (error
: Error): void => {
462 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger ${requestedMessage} error:`,
466 switch (requestedMessage
) {
467 case OCPP16MessageTrigger
.BootNotification
:
468 chargingStation
.ocppRequestService
469 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
471 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
472 chargingStation
.bootNotificationRequest
,
473 { skipBufferingOnError
: true, triggerMessage
: true }
476 chargingStation
.bootNotificationResponse
= response
480 case OCPP16MessageTrigger
.Heartbeat
:
481 chargingStation
.ocppRequestService
482 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
484 OCPP16RequestCommand
.HEARTBEAT
,
492 case OCPP16MessageTrigger
.StatusNotification
:
493 if (connectorId
!= null) {
494 chargingStation
.ocppRequestService
495 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
497 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
500 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
501 status: chargingStation
.getConnectorStatus(connectorId
)?.status
508 } else if (chargingStation
.hasEvses
) {
509 for (const evseStatus
of chargingStation
.evses
.values()) {
510 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
511 chargingStation
.ocppRequestService
513 OCPP16StatusNotificationRequest
,
514 OCPP16StatusNotificationResponse
517 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
520 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
521 status: connectorStatus
.status
531 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
532 chargingStation
.ocppRequestService
534 OCPP16StatusNotificationRequest
,
535 OCPP16StatusNotificationResponse
538 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
541 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
542 status: connectorStatus
.status
555 this.validatePayload
= this.validatePayload
.bind(this)
558 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
559 chargingStation
: ChargingStation
,
561 commandName
: OCPP16IncomingRequestCommand
,
562 commandPayload
: ReqType
564 let response
: ResType
566 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
567 chargingStation
.inPendingState() &&
568 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
569 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
572 ErrorType
.SECURITY_ERROR
,
573 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
577 )} while the charging station is in pending state on the central server`,
583 chargingStation
.isRegistered() ||
584 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
585 chargingStation
.inUnknownState())
588 this.incomingRequestHandlers
.has(commandName
) &&
589 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
592 this.validatePayload(chargingStation
, commandName
, commandPayload
)
593 // Call the method to build the response
594 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
595 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
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(
639 // Emit command name event to allow delayed handling
640 this.emit(commandName
, chargingStation
, commandPayload
, response
)
643 private validatePayload (
644 chargingStation
: ChargingStation
,
645 commandName
: OCPP16IncomingRequestCommand
,
646 commandPayload
: JsonType
648 if (this.payloadValidateFunctions
.has(commandName
)) {
649 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
652 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
657 // Simulate charging station restart
658 private handleRequestReset (
659 chargingStation
: ChargingStation
,
660 commandPayload
: ResetRequest
662 const { type } = commandPayload
664 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
665 .catch(Constants
.EMPTY_FUNCTION
)
667 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
668 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
669 chargingStation.stationInfo!.resetTime!
672 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
675 private async handleRequestUnlockConnector (
676 chargingStation
: ChargingStation
,
677 commandPayload
: UnlockConnectorRequest
678 ): Promise
<UnlockConnectorResponse
> {
679 const { connectorId
} = commandPayload
680 if (!chargingStation
.hasConnector(connectorId
)) {
682 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
684 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
686 if (connectorId
=== 0) {
687 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
688 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
690 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
691 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
693 OCPP16StopTransactionReason
.UNLOCK_COMMAND
695 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
696 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
698 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
700 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
703 OCPP16ChargePointStatus
.Available
705 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
708 private handleRequestGetConfiguration (
709 chargingStation
: ChargingStation
,
710 commandPayload
: GetConfigurationRequest
711 ): GetConfigurationResponse
{
712 const { key
} = commandPayload
713 const configurationKey
: OCPPConfigurationKey
[] = []
714 const unknownKey
: string[] = []
716 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
717 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
718 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
721 configurationKey
.push({
723 readonly: configKey
.readonly,
724 value
: configKey
.value
727 } else if (isNotEmptyArray(key
)) {
728 for (const k
of key
) {
729 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
730 if (keyFound
!= null) {
731 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
734 configurationKey
.push({
736 readonly: keyFound
.readonly,
737 value
: keyFound
.value
750 private handleRequestChangeConfiguration (
751 chargingStation
: ChargingStation
,
752 commandPayload
: ChangeConfigurationRequest
753 ): ChangeConfigurationResponse
{
754 const { key
, value
} = commandPayload
755 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
756 if (keyToChange
?.readonly === true) {
757 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
758 } else if (keyToChange
?.readonly === false) {
759 let valueChanged
= false
760 if (keyToChange
.value
!== value
) {
761 setConfigurationKeyValue(chargingStation
, key
, value
, true)
764 let triggerHeartbeatRestart
= false
766 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
767 OCPP16StandardParametersKey
.HeartBeatInterval
&&
770 setConfigurationKeyValue(
772 OCPP16StandardParametersKey
.HeartbeatInterval
,
775 triggerHeartbeatRestart
= true
778 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
779 OCPP16StandardParametersKey
.HeartbeatInterval
&&
782 setConfigurationKeyValue(
784 OCPP16StandardParametersKey
.HeartBeatInterval
,
787 triggerHeartbeatRestart
= true
789 if (triggerHeartbeatRestart
) {
790 chargingStation
.restartHeartbeat()
793 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
794 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
797 chargingStation
.restartWebSocketPing()
799 if (keyToChange
.reboot
=== true) {
800 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
802 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
804 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
807 private handleRequestSetChargingProfile (
808 chargingStation
: ChargingStation
,
809 commandPayload
: SetChargingProfileRequest
810 ): SetChargingProfileResponse
{
812 !OCPP16ServiceUtils
.checkFeatureProfile(
814 OCPP16SupportedFeatureProfiles
.SmartCharging
,
815 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
818 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
820 const { connectorId
, csChargingProfiles
} = commandPayload
821 if (!chargingStation
.hasConnector(connectorId
)) {
823 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
825 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
828 csChargingProfiles
.chargingProfilePurpose
===
829 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
832 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
835 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
839 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
841 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
843 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
845 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
847 connectorStatus
?.transactionStarted
=== false
850 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
852 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
855 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
857 connectorStatus
?.transactionStarted
=== true &&
858 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
861 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
862 csChargingProfiles.transactionId
863 } than the started transaction id ${connectorStatus.transactionId}`
865 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
867 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
869 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
872 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
875 private handleRequestGetCompositeSchedule (
876 chargingStation
: ChargingStation
,
877 commandPayload
: OCPP16GetCompositeScheduleRequest
878 ): OCPP16GetCompositeScheduleResponse
{
880 !OCPP16ServiceUtils
.checkFeatureProfile(
882 OCPP16SupportedFeatureProfiles
.SmartCharging
,
883 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
886 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
888 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
889 if (!chargingStation
.hasConnector(connectorId
)) {
891 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
893 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
895 if (connectorId
=== 0) {
897 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
899 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
901 if (chargingRateUnit
!= null) {
903 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
906 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
908 isEmptyArray(connectorStatus
?.chargingProfiles
) &&
909 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
911 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
913 const currentDate
= new Date()
914 const compositeScheduleInterval
: Interval
= {
916 end
: addSeconds(currentDate
, duration
)
918 // Get charging profiles sorted by connector id then stack level
919 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
923 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
924 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
925 for (const chargingProfile
of chargingProfiles
) {
926 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
928 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
929 chargingProfile.chargingProfileId
930 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
932 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
933 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
935 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
937 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
938 chargingProfile.chargingProfileId
939 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
941 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
942 chargingProfile
.chargingSchedule
.startSchedule
945 if (chargingProfile
.chargingSchedule
.duration
== null) {
947 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
948 chargingProfile.chargingProfileId
949 } has no duration defined and will be set to the maximum time allowed`
951 // OCPP specifies that if duration is not defined, it should be infinite
952 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
954 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
955 chargingProfile
.chargingSchedule
.startSchedule
!
959 !prepareChargingProfileKind(
962 compositeScheduleInterval
.start
,
963 chargingStation
.logPrefix()
969 !canProceedChargingProfile(
971 compositeScheduleInterval
.start
,
972 chargingStation
.logPrefix()
977 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
978 previousCompositeSchedule
,
979 chargingProfile
.chargingSchedule
,
980 compositeScheduleInterval
982 previousCompositeSchedule
= compositeSchedule
984 if (compositeSchedule
!= null) {
986 status: GenericStatus
.Accepted
,
987 scheduleStart
: compositeSchedule
.startSchedule
,
989 chargingSchedule
: compositeSchedule
992 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
995 private handleRequestClearChargingProfile (
996 chargingStation
: ChargingStation
,
997 commandPayload
: OCPP16ClearChargingProfileRequest
998 ): OCPP16ClearChargingProfileResponse
{
1000 !OCPP16ServiceUtils
.checkFeatureProfile(
1002 OCPP16SupportedFeatureProfiles
.SmartCharging
,
1003 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
1006 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1008 const { connectorId
} = commandPayload
1009 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1010 if (!chargingStation
.hasConnector(connectorId
!)) {
1012 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
1014 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1016 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1017 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!)
1018 if (connectorId
!= null && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1019 connectorStatus
.chargingProfiles
= []
1021 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1023 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1025 if (connectorId
== null) {
1026 let clearedCP
= false
1027 if (chargingStation
.hasEvses
) {
1028 for (const evseStatus
of chargingStation
.evses
.values()) {
1029 for (const status of evseStatus
.connectors
.values()) {
1030 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1033 status.chargingProfiles
1038 for (const id
of chargingStation
.connectors
.keys()) {
1039 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1042 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1047 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1050 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1053 private async handleRequestChangeAvailability (
1054 chargingStation
: ChargingStation
,
1055 commandPayload
: OCPP16ChangeAvailabilityRequest
1056 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1057 const { connectorId
, type } = commandPayload
1058 if (!chargingStation
.hasConnector(connectorId
)) {
1060 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1062 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1064 const chargePointStatus
: OCPP16ChargePointStatus
=
1065 type === OCPP16AvailabilityType
.Operative
1066 ? OCPP16ChargePointStatus
.Available
1067 : OCPP16ChargePointStatus
.Unavailable
1068 if (connectorId
=== 0) {
1069 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1070 if (chargingStation
.hasEvses
) {
1071 for (const evseStatus
of chargingStation
.evses
.values()) {
1072 response
= await OCPP16ServiceUtils
.changeAvailability(
1074 [...evseStatus
.connectors
.keys()],
1080 response
= await OCPP16ServiceUtils
.changeAvailability(
1082 [...chargingStation
.connectors
.keys()],
1087 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1091 (chargingStation
.isChargingStationAvailable() ||
1092 (!chargingStation
.isChargingStationAvailable() &&
1093 type === OCPP16AvailabilityType
.Inoperative
))
1095 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1096 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1097 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1098 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1100 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1101 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1102 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1107 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1109 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1112 private async handleRequestRemoteStartTransaction (
1113 chargingStation
: ChargingStation
,
1114 commandPayload
: RemoteStartTransactionRequest
1115 ): Promise
<GenericResponse
> {
1116 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1117 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1118 return await this.notifyRemoteStartTransactionRejected(
1120 transactionConnectorId
,
1125 !chargingStation
.isChargingStationAvailable() ||
1126 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1128 return await this.notifyRemoteStartTransactionRejected(
1130 transactionConnectorId
,
1134 // idTag authorization check required
1136 chargingStation
.getAuthorizeRemoteTxRequests() &&
1137 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1139 return await this.notifyRemoteStartTransactionRejected(
1141 transactionConnectorId
,
1145 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1147 transactionConnectorId
,
1148 OCPP16ChargePointStatus
.Preparing
1151 chargingProfile
!= null &&
1152 !this.setRemoteStartTransactionChargingProfile(
1154 transactionConnectorId
,
1158 return await this.notifyRemoteStartTransactionRejected(
1160 transactionConnectorId
,
1164 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1167 private async notifyRemoteStartTransactionRejected (
1168 chargingStation
: ChargingStation
,
1169 connectorId
: number,
1171 ): Promise
<GenericResponse
> {
1172 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1173 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1174 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1177 OCPP16ChargePointStatus
.Available
1181 `${chargingStation.logPrefix()} Remote start transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1183 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1186 private setRemoteStartTransactionChargingProfile (
1187 chargingStation
: ChargingStation
,
1188 connectorId
: number,
1189 chargingProfile
: OCPP16ChargingProfile
1191 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1192 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1194 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1200 `${chargingStation.logPrefix()} Not allowed to set ${
1201 chargingProfile.chargingProfilePurpose
1202 } charging profile(s) at remote start transaction`
1207 private async handleRequestRemoteStopTransaction (
1208 chargingStation
: ChargingStation
,
1209 commandPayload
: RemoteStopTransactionRequest
1210 ): Promise
<GenericResponse
> {
1211 const { transactionId
} = commandPayload
1212 if (chargingStation
.hasEvses
) {
1213 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1215 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1216 if (connectorStatus
.transactionId
=== transactionId
) {
1217 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1223 for (const connectorId
of chargingStation
.connectors
.keys()) {
1226 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1228 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1233 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`
1235 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1238 private handleRequestUpdateFirmware (
1239 chargingStation
: ChargingStation
,
1240 commandPayload
: OCPP16UpdateFirmwareRequest
1241 ): OCPP16UpdateFirmwareResponse
{
1243 !OCPP16ServiceUtils
.checkFeatureProfile(
1245 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1246 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1250 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1252 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1254 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1255 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1256 const { retrieveDate
} = commandPayload
1257 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1259 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1261 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1263 const now
= Date.now()
1264 if (retrieveDate
.getTime() <= now
) {
1265 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1268 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1269 }, retrieveDate
.getTime() - now
)
1271 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1274 private async updateFirmwareSimulation (
1275 chargingStation
: ChargingStation
,
1279 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1282 if (chargingStation
.hasEvses
) {
1283 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1285 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1286 if (connectorStatus
.transactionStarted
=== false) {
1287 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1290 OCPP16ChargePointStatus
.Unavailable
1297 for (const connectorId
of chargingStation
.connectors
.keys()) {
1300 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1302 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1305 OCPP16ChargePointStatus
.Unavailable
1310 await chargingStation
.ocppRequestService
.requestHandler
<
1311 OCPP16FirmwareStatusNotificationRequest
,
1312 OCPP16FirmwareStatusNotificationResponse
1313 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1314 status: OCPP16FirmwareStatus
.Downloading
1316 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1317 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1319 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1320 OCPP16FirmwareStatus
.DownloadFailed
1322 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1323 await chargingStation
.ocppRequestService
.requestHandler
<
1324 OCPP16FirmwareStatusNotificationRequest
,
1325 OCPP16FirmwareStatusNotificationResponse
1326 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1327 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1329 chargingStation
.stationInfo
.firmwareStatus
=
1330 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1333 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1334 await chargingStation
.ocppRequestService
.requestHandler
<
1335 OCPP16FirmwareStatusNotificationRequest
,
1336 OCPP16FirmwareStatusNotificationResponse
1337 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1338 status: OCPP16FirmwareStatus
.Downloaded
1340 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1341 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1342 let wasTransactionsStarted
= false
1343 let transactionsStarted
: boolean
1345 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1346 if (runningTransactions
> 0) {
1347 const waitTime
= secondsToMilliseconds(15)
1349 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1351 )} before continuing firmware update simulation`
1353 await sleep(waitTime
)
1354 transactionsStarted
= true
1355 wasTransactionsStarted
= true
1357 if (chargingStation
.hasEvses
) {
1358 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1360 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1361 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1362 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1365 OCPP16ChargePointStatus
.Unavailable
1372 for (const connectorId
of chargingStation
.connectors
.keys()) {
1375 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1376 OCPP16ChargePointStatus
.Unavailable
1378 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1381 OCPP16ChargePointStatus
.Unavailable
1386 transactionsStarted
= false
1388 } while (transactionsStarted
)
1389 !wasTransactionsStarted
&&
1390 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))))
1391 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1394 await chargingStation
.ocppRequestService
.requestHandler
<
1395 OCPP16FirmwareStatusNotificationRequest
,
1396 OCPP16FirmwareStatusNotificationResponse
1397 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1398 status: OCPP16FirmwareStatus
.Installing
1400 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1401 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1403 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1404 OCPP16FirmwareStatus
.InstallationFailed
1406 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1407 await chargingStation
.ocppRequestService
.requestHandler
<
1408 OCPP16FirmwareStatusNotificationRequest
,
1409 OCPP16FirmwareStatusNotificationResponse
1410 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1411 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1413 chargingStation
.stationInfo
.firmwareStatus
=
1414 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1417 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1418 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1419 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1423 private async handleRequestGetDiagnostics (
1424 chargingStation
: ChargingStation
,
1425 commandPayload
: GetDiagnosticsRequest
1426 ): Promise
<GetDiagnosticsResponse
> {
1428 !OCPP16ServiceUtils
.checkFeatureProfile(
1430 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1431 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1435 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1437 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1439 const { location
} = commandPayload
1440 const uri
= new URL(location
)
1441 if (uri
.protocol
.startsWith('ftp:')) {
1442 let ftpClient
: Client
| undefined
1444 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1445 .filter(file
=> file
.endsWith('.log'))
1446 .map(file
=> join('./', file
))
1447 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1448 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1449 ftpClient
= new Client()
1450 const accessResponse
= await ftpClient
.access({
1452 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1453 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1454 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1456 let uploadResponse
: FTPResponse
| undefined
1457 if (accessResponse
.code
=== 220) {
1458 ftpClient
.trackProgress(info
=> {
1460 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1462 } bytes transferred from diagnostics archive ${info.name}`
1464 chargingStation
.ocppRequestService
1466 OCPP16DiagnosticsStatusNotificationRequest
,
1467 OCPP16DiagnosticsStatusNotificationResponse
1468 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1469 status: OCPP16DiagnosticsStatus
.Uploading
1473 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1474 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1480 uploadResponse
= await ftpClient
.uploadFrom(
1481 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1482 `${uri.pathname}${diagnosticsArchive}`
1484 if (uploadResponse
.code
=== 226) {
1485 await chargingStation
.ocppRequestService
.requestHandler
<
1486 OCPP16DiagnosticsStatusNotificationRequest
,
1487 OCPP16DiagnosticsStatusNotificationResponse
1488 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1489 status: OCPP16DiagnosticsStatus
.Uploaded
1492 return { fileName
: diagnosticsArchive
}
1494 throw new OCPPError(
1495 ErrorType
.GENERIC_ERROR
,
1496 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1497 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1500 throw new OCPPError(
1501 ErrorType
.GENERIC_ERROR
,
1502 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1503 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1506 await chargingStation
.ocppRequestService
.requestHandler
<
1507 OCPP16DiagnosticsStatusNotificationRequest
,
1508 OCPP16DiagnosticsStatusNotificationResponse
1509 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1510 status: OCPP16DiagnosticsStatus
.UploadFailed
1513 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1514 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1516 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1518 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1523 `${chargingStation.logPrefix()} Unsupported protocol ${
1525 } to transfer the diagnostic logs archive`
1527 await chargingStation
.ocppRequestService
.requestHandler
<
1528 OCPP16DiagnosticsStatusNotificationRequest
,
1529 OCPP16DiagnosticsStatusNotificationResponse
1530 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1531 status: OCPP16DiagnosticsStatus
.UploadFailed
1533 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1537 private handleRequestTriggerMessage (
1538 chargingStation
: ChargingStation
,
1539 commandPayload
: OCPP16TriggerMessageRequest
1540 ): OCPP16TriggerMessageResponse
{
1541 const { requestedMessage
, connectorId
} = commandPayload
1543 !OCPP16ServiceUtils
.checkFeatureProfile(
1545 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1546 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1548 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1550 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1553 !OCPP16ServiceUtils
.isConnectorIdValid(
1555 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1556 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1560 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1562 switch (requestedMessage
) {
1563 case OCPP16MessageTrigger
.BootNotification
:
1564 case OCPP16MessageTrigger
.Heartbeat
:
1565 case OCPP16MessageTrigger
.StatusNotification
:
1566 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1568 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1572 private handleRequestDataTransfer (
1573 chargingStation
: ChargingStation
,
1574 commandPayload
: OCPP16DataTransferRequest
1575 ): OCPP16DataTransferResponse
{
1576 const { vendorId
} = commandPayload
1578 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1579 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1581 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1583 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1584 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1586 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1588 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1593 private async handleRequestReserveNow (
1594 chargingStation
: ChargingStation
,
1595 commandPayload
: OCPP16ReserveNowRequest
1596 ): Promise
<OCPP16ReserveNowResponse
> {
1598 !OCPP16ServiceUtils
.checkFeatureProfile(
1600 OCPP16SupportedFeatureProfiles
.Reservation
,
1601 OCPP16IncomingRequestCommand
.RESERVE_NOW
1604 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1606 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1607 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1608 const { reservationId
, idTag
, connectorId
} = commandPayload
1609 let response
: OCPP16ReserveNowResponse
1611 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1612 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1614 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1615 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1617 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1618 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1620 await removeExpiredReservations(chargingStation
)
1621 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1622 case OCPP16ChargePointStatus
.Faulted
:
1623 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1625 case OCPP16ChargePointStatus
.Preparing
:
1626 case OCPP16ChargePointStatus
.Charging
:
1627 case OCPP16ChargePointStatus
.SuspendedEV
:
1628 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1629 case OCPP16ChargePointStatus
.Finishing
:
1630 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1632 case OCPP16ChargePointStatus
.Unavailable
:
1633 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1635 case OCPP16ChargePointStatus
.Reserved
:
1636 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1637 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1640 // eslint-disable-next-line no-fallthrough
1642 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1643 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1646 await chargingStation
.addReservation({
1647 id
: commandPayload
.reservationId
,
1650 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1655 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1656 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1657 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1658 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1660 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1662 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1667 private async handleRequestCancelReservation (
1668 chargingStation
: ChargingStation
,
1669 commandPayload
: OCPP16CancelReservationRequest
1670 ): Promise
<GenericResponse
> {
1672 !OCPP16ServiceUtils
.checkFeatureProfile(
1674 OCPP16SupportedFeatureProfiles
.Reservation
,
1675 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1678 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1681 const { reservationId
} = commandPayload
1682 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1683 if (reservation
== null) {
1685 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1687 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1689 await chargingStation
.removeReservation(
1691 ReservationTerminationReason
.RESERVATION_CANCELED
1693 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1695 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1696 return this.handleIncomingRequestError
<GenericResponse
>(
1698 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1700 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}