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 { nextTick
} from
'node:process'
6 import { URL
, fileURLToPath
} from
'node:url'
8 import type { ValidateFunction
} from
'ajv'
9 import { Client
, type FTPResponse
} from
'basic-ftp'
17 import { maxTime
} from
'date-fns/constants'
18 import { create
} from
'tar'
20 import { OCPP16Constants
} from
'./OCPP16Constants.js'
21 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils.js'
24 canProceedChargingProfile
,
27 getConnectorChargingProfiles
,
28 prepareChargingProfileKind
,
29 removeExpiredReservations
,
30 setConfigurationKeyValue
31 } from
'../../../charging-station/index.js'
32 import { OCPPError
} from
'../../../exception/index.js'
34 type ChangeConfigurationRequest
,
35 type ChangeConfigurationResponse
,
39 type GetConfigurationRequest
,
40 type GetConfigurationResponse
,
41 type GetDiagnosticsRequest
,
42 type GetDiagnosticsResponse
,
43 type IncomingRequestHandler
,
45 OCPP16AuthorizationStatus
,
46 OCPP16AvailabilityType
,
47 type OCPP16BootNotificationRequest
,
48 type OCPP16BootNotificationResponse
,
49 type OCPP16CancelReservationRequest
,
50 type OCPP16ChangeAvailabilityRequest
,
51 type OCPP16ChangeAvailabilityResponse
,
52 OCPP16ChargePointErrorCode
,
53 OCPP16ChargePointStatus
,
54 type OCPP16ChargingProfile
,
55 OCPP16ChargingProfilePurposeType
,
56 type OCPP16ChargingSchedule
,
57 type OCPP16ClearCacheRequest
,
58 type OCPP16ClearChargingProfileRequest
,
59 type OCPP16ClearChargingProfileResponse
,
60 type OCPP16DataTransferRequest
,
61 type OCPP16DataTransferResponse
,
62 OCPP16DataTransferVendorId
,
63 OCPP16DiagnosticsStatus
,
64 type OCPP16DiagnosticsStatusNotificationRequest
,
65 type OCPP16DiagnosticsStatusNotificationResponse
,
67 type OCPP16FirmwareStatusNotificationRequest
,
68 type OCPP16FirmwareStatusNotificationResponse
,
69 type OCPP16GetCompositeScheduleRequest
,
70 type OCPP16GetCompositeScheduleResponse
,
71 type OCPP16HeartbeatRequest
,
72 type OCPP16HeartbeatResponse
,
73 OCPP16IncomingRequestCommand
,
76 type OCPP16ReserveNowRequest
,
77 type OCPP16ReserveNowResponse
,
78 OCPP16StandardParametersKey
,
79 type OCPP16StartTransactionRequest
,
80 type OCPP16StartTransactionResponse
,
81 type OCPP16StatusNotificationRequest
,
82 type OCPP16StatusNotificationResponse
,
83 OCPP16StopTransactionReason
,
84 OCPP16SupportedFeatureProfiles
,
85 type OCPP16TriggerMessageRequest
,
86 type OCPP16TriggerMessageResponse
,
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
,
410 (chargingStation
: ChargingStation
, connectorId
: number, idTag
: string) => {
411 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
412 chargingStation
.getConnectorStatus(connectorId
)!.transactionRemoteStarted
= true
413 chargingStation
.ocppRequestService
414 .requestHandler
<OCPP16StartTransactionRequest
, OCPP16StartTransactionResponse
>(
416 OCPP16RequestCommand
.START_TRANSACTION
,
423 if (response
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
425 `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
429 `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'`
435 `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`,
442 `Trigger${OCPP16MessageTrigger.BootNotification}`,
443 (chargingStation
: ChargingStation
) => {
444 chargingStation
.ocppRequestService
445 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
447 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
448 chargingStation
.bootNotificationRequest
,
449 { skipBufferingOnError
: true, triggerMessage
: true }
452 chargingStation
.bootNotificationResponse
= response
456 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger boot notification error:`,
462 this.on(`Trigger${OCPP16MessageTrigger.Heartbeat}`, (chargingStation
: ChargingStation
) => {
463 chargingStation
.ocppRequestService
464 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
466 OCPP16RequestCommand
.HEARTBEAT
,
474 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger heartbeat error:`,
480 `$Trigger${OCPP16MessageTrigger.StatusNotification}`,
481 (chargingStation
: ChargingStation
, connectorId
?: number) => {
482 const errorHandler
= (error
: Error): void => {
484 `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger status notification error:`,
488 if (connectorId
!= null) {
489 chargingStation
.ocppRequestService
490 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
492 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
495 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
496 status: chargingStation
.getConnectorStatus(connectorId
)?.status
503 } else if (chargingStation
.hasEvses
) {
504 for (const evseStatus
of chargingStation
.evses
.values()) {
505 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
506 chargingStation
.ocppRequestService
507 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
509 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
512 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
513 status: connectorStatus
.status
523 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
524 chargingStation
.ocppRequestService
525 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
527 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
530 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
531 status: connectorStatus
.status
542 this.validatePayload
= this.validatePayload
.bind(this)
545 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
546 chargingStation
: ChargingStation
,
548 commandName
: OCPP16IncomingRequestCommand
,
549 commandPayload
: ReqType
551 let response
: ResType
553 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
554 chargingStation
.inPendingState() &&
555 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
556 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
559 ErrorType
.SECURITY_ERROR
,
560 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
564 )} while the charging station is in pending state on the central server`,
570 chargingStation
.isRegistered() ||
571 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
572 chargingStation
.inUnknownState())
575 this.incomingRequestHandlers
.has(commandName
) &&
576 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
579 this.validatePayload(chargingStation
, commandName
, commandPayload
)
580 // Call the method to build the response
581 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
582 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
589 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
597 ErrorType
.NOT_IMPLEMENTED
,
598 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
609 ErrorType
.SECURITY_ERROR
,
610 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
614 )} while the charging station is not registered on the central server.`,
619 // Send the built response
620 await chargingStation
.ocppRequestService
.sendResponse(
628 private validatePayload (
629 chargingStation
: ChargingStation
,
630 commandName
: OCPP16IncomingRequestCommand
,
631 commandPayload
: JsonType
633 if (this.payloadValidateFunctions
.has(commandName
)) {
634 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
637 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
642 // Simulate charging station restart
643 private handleRequestReset (
644 chargingStation
: ChargingStation
,
645 commandPayload
: ResetRequest
647 const { type } = commandPayload
649 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
650 .catch(Constants
.EMPTY_FUNCTION
)
652 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
653 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
654 chargingStation.stationInfo!.resetTime!
657 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
660 private async handleRequestUnlockConnector (
661 chargingStation
: ChargingStation
,
662 commandPayload
: UnlockConnectorRequest
663 ): Promise
<UnlockConnectorResponse
> {
664 const { connectorId
} = commandPayload
665 if (!chargingStation
.hasConnector(connectorId
)) {
667 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
669 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
671 if (connectorId
=== 0) {
672 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
673 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
675 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
676 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
678 OCPP16StopTransactionReason
.UNLOCK_COMMAND
680 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
681 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
683 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
685 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
688 OCPP16ChargePointStatus
.Available
690 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
693 private handleRequestGetConfiguration (
694 chargingStation
: ChargingStation
,
695 commandPayload
: GetConfigurationRequest
696 ): GetConfigurationResponse
{
697 const { key
} = commandPayload
698 const configurationKey
: OCPPConfigurationKey
[] = []
699 const unknownKey
: string[] = []
701 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
702 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
703 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
706 configurationKey
.push({
708 readonly: configKey
.readonly,
709 value
: configKey
.value
712 } else if (isNotEmptyArray(key
)) {
713 for (const k
of key
) {
714 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
715 if (keyFound
!= null) {
716 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
719 configurationKey
.push({
721 readonly: keyFound
.readonly,
722 value
: keyFound
.value
735 private handleRequestChangeConfiguration (
736 chargingStation
: ChargingStation
,
737 commandPayload
: ChangeConfigurationRequest
738 ): ChangeConfigurationResponse
{
739 const { key
, value
} = commandPayload
740 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
741 if (keyToChange
?.readonly === true) {
742 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
743 } else if (keyToChange
?.readonly === false) {
744 let valueChanged
= false
745 if (keyToChange
.value
!== value
) {
746 setConfigurationKeyValue(chargingStation
, key
, value
, true)
749 let triggerHeartbeatRestart
= false
751 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
752 OCPP16StandardParametersKey
.HeartBeatInterval
&&
755 setConfigurationKeyValue(
757 OCPP16StandardParametersKey
.HeartbeatInterval
,
760 triggerHeartbeatRestart
= true
763 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
764 OCPP16StandardParametersKey
.HeartbeatInterval
&&
767 setConfigurationKeyValue(
769 OCPP16StandardParametersKey
.HeartBeatInterval
,
772 triggerHeartbeatRestart
= true
774 if (triggerHeartbeatRestart
) {
775 chargingStation
.restartHeartbeat()
778 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
779 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
782 chargingStation
.restartWebSocketPing()
784 if (keyToChange
.reboot
=== true) {
785 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
787 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
789 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
792 private handleRequestSetChargingProfile (
793 chargingStation
: ChargingStation
,
794 commandPayload
: SetChargingProfileRequest
795 ): SetChargingProfileResponse
{
797 !OCPP16ServiceUtils
.checkFeatureProfile(
799 OCPP16SupportedFeatureProfiles
.SmartCharging
,
800 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
803 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
805 const { connectorId
, csChargingProfiles
} = commandPayload
806 if (!chargingStation
.hasConnector(connectorId
)) {
808 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
810 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
813 csChargingProfiles
.chargingProfilePurpose
===
814 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
817 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
820 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
824 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
826 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
828 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
830 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
832 connectorStatus
?.transactionStarted
=== false
835 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
837 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
840 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
842 connectorStatus
?.transactionStarted
=== true &&
843 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
846 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
847 csChargingProfiles.transactionId
848 } than the started transaction id ${connectorStatus.transactionId}`
850 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
852 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
854 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
857 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
860 private handleRequestGetCompositeSchedule (
861 chargingStation
: ChargingStation
,
862 commandPayload
: OCPP16GetCompositeScheduleRequest
863 ): OCPP16GetCompositeScheduleResponse
{
865 !OCPP16ServiceUtils
.checkFeatureProfile(
867 OCPP16SupportedFeatureProfiles
.SmartCharging
,
868 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
871 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
873 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
874 if (!chargingStation
.hasConnector(connectorId
)) {
876 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
878 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
880 if (connectorId
=== 0) {
882 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
884 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
886 if (chargingRateUnit
!= null) {
888 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
891 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
893 isEmptyArray(connectorStatus
?.chargingProfiles
) &&
894 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
896 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
898 const currentDate
= new Date()
899 const compositeScheduleInterval
: Interval
= {
901 end
: addSeconds(currentDate
, duration
)
903 // Get charging profiles sorted by connector id then stack level
904 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
908 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
909 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
910 for (const chargingProfile
of chargingProfiles
) {
911 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
913 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
914 chargingProfile.chargingProfileId
915 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
917 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
918 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
920 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
922 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
923 chargingProfile.chargingProfileId
924 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
926 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
927 chargingProfile
.chargingSchedule
.startSchedule
930 if (chargingProfile
.chargingSchedule
.duration
== null) {
932 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
933 chargingProfile.chargingProfileId
934 } has no duration defined and will be set to the maximum time allowed`
936 // OCPP specifies that if duration is not defined, it should be infinite
937 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
939 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
940 chargingProfile
.chargingSchedule
.startSchedule
!
944 !prepareChargingProfileKind(
947 compositeScheduleInterval
.start
,
948 chargingStation
.logPrefix()
954 !canProceedChargingProfile(
956 compositeScheduleInterval
.start
,
957 chargingStation
.logPrefix()
962 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
963 previousCompositeSchedule
,
964 chargingProfile
.chargingSchedule
,
965 compositeScheduleInterval
967 previousCompositeSchedule
= compositeSchedule
969 if (compositeSchedule
!= null) {
971 status: GenericStatus
.Accepted
,
972 scheduleStart
: compositeSchedule
.startSchedule
,
974 chargingSchedule
: compositeSchedule
977 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
980 private handleRequestClearChargingProfile (
981 chargingStation
: ChargingStation
,
982 commandPayload
: OCPP16ClearChargingProfileRequest
983 ): OCPP16ClearChargingProfileResponse
{
985 !OCPP16ServiceUtils
.checkFeatureProfile(
987 OCPP16SupportedFeatureProfiles
.SmartCharging
,
988 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
991 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
993 const { connectorId
} = commandPayload
994 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
995 if (!chargingStation
.hasConnector(connectorId
!)) {
997 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
999 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1001 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1002 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!)
1003 if (connectorId
!= null && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
1004 connectorStatus
.chargingProfiles
= []
1006 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
1008 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1010 if (connectorId
== null) {
1011 let clearedCP
= false
1012 if (chargingStation
.hasEvses
) {
1013 for (const evseStatus
of chargingStation
.evses
.values()) {
1014 for (const status of evseStatus
.connectors
.values()) {
1015 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1018 status.chargingProfiles
1023 for (const id
of chargingStation
.connectors
.keys()) {
1024 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
1027 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
1032 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
1035 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
1038 private async handleRequestChangeAvailability (
1039 chargingStation
: ChargingStation
,
1040 commandPayload
: OCPP16ChangeAvailabilityRequest
1041 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
1042 const { connectorId
, type } = commandPayload
1043 if (!chargingStation
.hasConnector(connectorId
)) {
1045 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
1047 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1049 const chargePointStatus
: OCPP16ChargePointStatus
=
1050 type === OCPP16AvailabilityType
.Operative
1051 ? OCPP16ChargePointStatus
.Available
1052 : OCPP16ChargePointStatus
.Unavailable
1053 if (connectorId
=== 0) {
1054 let response
: OCPP16ChangeAvailabilityResponse
| undefined
1055 if (chargingStation
.hasEvses
) {
1056 for (const evseStatus
of chargingStation
.evses
.values()) {
1057 response
= await OCPP16ServiceUtils
.changeAvailability(
1059 [...evseStatus
.connectors
.keys()],
1065 response
= await OCPP16ServiceUtils
.changeAvailability(
1067 [...chargingStation
.connectors
.keys()],
1072 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1076 (chargingStation
.isChargingStationAvailable() ||
1077 (!chargingStation
.isChargingStationAvailable() &&
1078 type === OCPP16AvailabilityType
.Inoperative
))
1080 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1081 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1082 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1083 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
1085 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1086 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
1087 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1092 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
1094 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
1097 private async handleRequestRemoteStartTransaction (
1098 chargingStation
: ChargingStation
,
1099 commandPayload
: RemoteStartTransactionRequest
1100 ): Promise
<GenericResponse
> {
1101 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
1102 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
1103 return await this.notifyRemoteStartTransactionRejected(
1105 transactionConnectorId
,
1110 !chargingStation
.isChargingStationAvailable() ||
1111 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
1113 return await this.notifyRemoteStartTransactionRejected(
1115 transactionConnectorId
,
1119 // idTag authorization check required
1121 chargingStation
.getAuthorizeRemoteTxRequests() &&
1122 !(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1124 return await this.notifyRemoteStartTransactionRejected(
1126 transactionConnectorId
,
1130 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1132 transactionConnectorId
,
1133 OCPP16ChargePointStatus
.Preparing
1136 chargingProfile
!= null &&
1137 !this.setRemoteStartTransactionChargingProfile(
1139 transactionConnectorId
,
1143 return await this.notifyRemoteStartTransactionRejected(
1145 transactionConnectorId
,
1151 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
1153 transactionConnectorId
,
1157 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1160 private async notifyRemoteStartTransactionRejected (
1161 chargingStation
: ChargingStation
,
1162 connectorId
: number,
1164 ): Promise
<GenericResponse
> {
1165 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1166 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1167 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1170 OCPP16ChargePointStatus
.Available
1174 `${chargingStation.logPrefix()} Remote start transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1176 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1179 private setRemoteStartTransactionChargingProfile (
1180 chargingStation
: ChargingStation
,
1181 connectorId
: number,
1182 chargingProfile
: OCPP16ChargingProfile
1184 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1185 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1187 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1193 `${chargingStation.logPrefix()} Not allowed to set ${
1194 chargingProfile.chargingProfilePurpose
1195 } charging profile(s) at remote start transaction`
1200 private async handleRequestRemoteStopTransaction (
1201 chargingStation
: ChargingStation
,
1202 commandPayload
: RemoteStopTransactionRequest
1203 ): Promise
<GenericResponse
> {
1204 const { transactionId
} = commandPayload
1205 if (chargingStation
.hasEvses
) {
1206 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1208 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1209 if (connectorStatus
.transactionId
=== transactionId
) {
1210 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1216 for (const connectorId
of chargingStation
.connectors
.keys()) {
1219 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1221 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1226 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`
1228 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1231 private handleRequestUpdateFirmware (
1232 chargingStation
: ChargingStation
,
1233 commandPayload
: OCPP16UpdateFirmwareRequest
1234 ): OCPP16UpdateFirmwareResponse
{
1236 !OCPP16ServiceUtils
.checkFeatureProfile(
1238 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1239 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1243 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1245 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1247 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1248 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1249 const { retrieveDate
} = commandPayload
1250 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1252 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1254 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1256 const now
= Date.now()
1257 if (retrieveDate
.getTime() <= now
) {
1258 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1261 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1262 }, retrieveDate
.getTime() - now
)
1264 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1267 private async updateFirmwareSimulation (
1268 chargingStation
: ChargingStation
,
1272 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1275 if (chargingStation
.hasEvses
) {
1276 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1278 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1279 if (connectorStatus
.transactionStarted
=== false) {
1280 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1283 OCPP16ChargePointStatus
.Unavailable
1290 for (const connectorId
of chargingStation
.connectors
.keys()) {
1293 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1295 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1298 OCPP16ChargePointStatus
.Unavailable
1303 await chargingStation
.ocppRequestService
.requestHandler
<
1304 OCPP16FirmwareStatusNotificationRequest
,
1305 OCPP16FirmwareStatusNotificationResponse
1306 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1307 status: OCPP16FirmwareStatus
.Downloading
1309 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1310 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1312 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1313 OCPP16FirmwareStatus
.DownloadFailed
1315 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1316 await chargingStation
.ocppRequestService
.requestHandler
<
1317 OCPP16FirmwareStatusNotificationRequest
,
1318 OCPP16FirmwareStatusNotificationResponse
1319 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1320 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1322 chargingStation
.stationInfo
.firmwareStatus
=
1323 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1326 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1327 await chargingStation
.ocppRequestService
.requestHandler
<
1328 OCPP16FirmwareStatusNotificationRequest
,
1329 OCPP16FirmwareStatusNotificationResponse
1330 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1331 status: OCPP16FirmwareStatus
.Downloaded
1333 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1334 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1335 let wasTransactionsStarted
= false
1336 let transactionsStarted
: boolean
1338 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1339 if (runningTransactions
> 0) {
1340 const waitTime
= secondsToMilliseconds(15)
1342 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1344 )} before continuing firmware update simulation`
1346 await sleep(waitTime
)
1347 transactionsStarted
= true
1348 wasTransactionsStarted
= true
1350 if (chargingStation
.hasEvses
) {
1351 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1353 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1354 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1355 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1358 OCPP16ChargePointStatus
.Unavailable
1365 for (const connectorId
of chargingStation
.connectors
.keys()) {
1368 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1369 OCPP16ChargePointStatus
.Unavailable
1371 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1374 OCPP16ChargePointStatus
.Unavailable
1379 transactionsStarted
= false
1381 } while (transactionsStarted
)
1382 !wasTransactionsStarted
&&
1383 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))))
1384 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1387 await chargingStation
.ocppRequestService
.requestHandler
<
1388 OCPP16FirmwareStatusNotificationRequest
,
1389 OCPP16FirmwareStatusNotificationResponse
1390 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1391 status: OCPP16FirmwareStatus
.Installing
1393 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1394 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1396 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1397 OCPP16FirmwareStatus
.InstallationFailed
1399 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1400 await chargingStation
.ocppRequestService
.requestHandler
<
1401 OCPP16FirmwareStatusNotificationRequest
,
1402 OCPP16FirmwareStatusNotificationResponse
1403 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1404 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1406 chargingStation
.stationInfo
.firmwareStatus
=
1407 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1410 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1411 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1412 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1416 private async handleRequestGetDiagnostics (
1417 chargingStation
: ChargingStation
,
1418 commandPayload
: GetDiagnosticsRequest
1419 ): Promise
<GetDiagnosticsResponse
> {
1421 !OCPP16ServiceUtils
.checkFeatureProfile(
1423 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1424 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1428 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1430 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1432 const { location
} = commandPayload
1433 const uri
= new URL(location
)
1434 if (uri
.protocol
.startsWith('ftp:')) {
1435 let ftpClient
: Client
| undefined
1437 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1438 .filter(file
=> file
.endsWith('.log'))
1439 .map(file
=> join('./', file
))
1440 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1441 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1442 ftpClient
= new Client()
1443 const accessResponse
= await ftpClient
.access({
1445 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1446 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1447 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1449 let uploadResponse
: FTPResponse
| undefined
1450 if (accessResponse
.code
=== 220) {
1451 ftpClient
.trackProgress(info
=> {
1453 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1455 } bytes transferred from diagnostics archive ${info.name}`
1457 chargingStation
.ocppRequestService
1459 OCPP16DiagnosticsStatusNotificationRequest
,
1460 OCPP16DiagnosticsStatusNotificationResponse
1461 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1462 status: OCPP16DiagnosticsStatus
.Uploading
1466 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1467 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1473 uploadResponse
= await ftpClient
.uploadFrom(
1474 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1475 `${uri.pathname}${diagnosticsArchive}`
1477 if (uploadResponse
.code
=== 226) {
1478 await chargingStation
.ocppRequestService
.requestHandler
<
1479 OCPP16DiagnosticsStatusNotificationRequest
,
1480 OCPP16DiagnosticsStatusNotificationResponse
1481 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1482 status: OCPP16DiagnosticsStatus
.Uploaded
1485 return { fileName
: diagnosticsArchive
}
1487 throw new OCPPError(
1488 ErrorType
.GENERIC_ERROR
,
1489 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1490 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1493 throw new OCPPError(
1494 ErrorType
.GENERIC_ERROR
,
1495 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1496 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1499 await chargingStation
.ocppRequestService
.requestHandler
<
1500 OCPP16DiagnosticsStatusNotificationRequest
,
1501 OCPP16DiagnosticsStatusNotificationResponse
1502 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1503 status: OCPP16DiagnosticsStatus
.UploadFailed
1506 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1507 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1509 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1511 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1516 `${chargingStation.logPrefix()} Unsupported protocol ${
1518 } to transfer the diagnostic logs archive`
1520 await chargingStation
.ocppRequestService
.requestHandler
<
1521 OCPP16DiagnosticsStatusNotificationRequest
,
1522 OCPP16DiagnosticsStatusNotificationResponse
1523 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1524 status: OCPP16DiagnosticsStatus
.UploadFailed
1526 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1530 private handleRequestTriggerMessage (
1531 chargingStation
: ChargingStation
,
1532 commandPayload
: OCPP16TriggerMessageRequest
1533 ): OCPP16TriggerMessageResponse
{
1534 const { requestedMessage
, connectorId
} = commandPayload
1536 !OCPP16ServiceUtils
.checkFeatureProfile(
1538 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1539 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1541 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1543 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1546 !OCPP16ServiceUtils
.isConnectorIdValid(
1548 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1549 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1553 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1556 switch (requestedMessage
) {
1557 case OCPP16MessageTrigger
.BootNotification
:
1559 this.emit(`Trigger${OCPP16MessageTrigger.BootNotification}`, chargingStation
)
1561 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1562 case OCPP16MessageTrigger
.Heartbeat
:
1563 nextTick(() => this.emit(`Trigger${OCPP16MessageTrigger.Heartbeat}`, chargingStation
))
1564 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1565 case OCPP16MessageTrigger
.StatusNotification
:
1568 `Trigger${OCPP16MessageTrigger.StatusNotification}`,
1573 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1575 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1578 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1579 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1581 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1583 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}
1588 private handleRequestDataTransfer (
1589 chargingStation
: ChargingStation
,
1590 commandPayload
: OCPP16DataTransferRequest
1591 ): OCPP16DataTransferResponse
{
1592 const { vendorId
} = commandPayload
1594 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1595 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1597 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1599 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1600 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1602 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1604 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1609 private async handleRequestReserveNow (
1610 chargingStation
: ChargingStation
,
1611 commandPayload
: OCPP16ReserveNowRequest
1612 ): Promise
<OCPP16ReserveNowResponse
> {
1614 !OCPP16ServiceUtils
.checkFeatureProfile(
1616 OCPP16SupportedFeatureProfiles
.Reservation
,
1617 OCPP16IncomingRequestCommand
.RESERVE_NOW
1620 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1622 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1623 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1624 const { reservationId
, idTag
, connectorId
} = commandPayload
1625 let response
: OCPP16ReserveNowResponse
1627 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1628 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1630 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1631 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1633 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1634 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1636 await removeExpiredReservations(chargingStation
)
1637 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1638 case OCPP16ChargePointStatus
.Faulted
:
1639 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1641 case OCPP16ChargePointStatus
.Preparing
:
1642 case OCPP16ChargePointStatus
.Charging
:
1643 case OCPP16ChargePointStatus
.SuspendedEV
:
1644 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1645 case OCPP16ChargePointStatus
.Finishing
:
1646 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1648 case OCPP16ChargePointStatus
.Unavailable
:
1649 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1651 case OCPP16ChargePointStatus
.Reserved
:
1652 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1653 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1656 // eslint-disable-next-line no-fallthrough
1658 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1659 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1662 await chargingStation
.addReservation({
1663 id
: commandPayload
.reservationId
,
1666 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1671 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1672 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1673 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1674 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1676 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1678 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1683 private async handleRequestCancelReservation (
1684 chargingStation
: ChargingStation
,
1685 commandPayload
: OCPP16CancelReservationRequest
1686 ): Promise
<GenericResponse
> {
1688 !OCPP16ServiceUtils
.checkFeatureProfile(
1690 OCPP16SupportedFeatureProfiles
.Reservation
,
1691 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1694 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1697 const { reservationId
} = commandPayload
1698 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1699 if (reservation
== null) {
1701 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1703 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1705 await chargingStation
.removeReservation(
1707 ReservationTerminationReason
.RESERVATION_CANCELED
1709 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1711 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1712 return this.handleIncomingRequestError
<GenericResponse
>(
1714 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1716 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}