1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { createWriteStream
, readdirSync
} from
'node:fs'
4 import { dirname
, join
, resolve
} from
'node:path'
5 import { URL
, fileURLToPath
} from
'node:url'
7 import type { ValidateFunction
} from
'ajv'
8 import { Client
, type FTPResponse
} from
'basic-ftp'
16 import { maxTime
} from
'date-fns/constants'
17 import { create
} from
'tar'
19 import { OCPP16Constants
} from
'./OCPP16Constants.js'
20 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils.js'
23 canProceedChargingProfile
,
26 getConnectorChargingProfiles
,
27 prepareChargingProfileKind
,
28 removeExpiredReservations
,
29 setConfigurationKeyValue
30 } from
'../../../charging-station/index.js'
31 import { OCPPError
} from
'../../../exception/index.js'
33 type ChangeConfigurationRequest
,
34 type ChangeConfigurationResponse
,
38 type GetConfigurationRequest
,
39 type GetConfigurationResponse
,
40 type GetDiagnosticsRequest
,
41 type GetDiagnosticsResponse
,
42 type IncomingRequestHandler
,
44 OCPP16AuthorizationStatus
,
45 OCPP16AvailabilityType
,
46 type OCPP16BootNotificationRequest
,
47 type OCPP16BootNotificationResponse
,
48 type OCPP16CancelReservationRequest
,
49 type OCPP16ChangeAvailabilityRequest
,
50 type OCPP16ChangeAvailabilityResponse
,
51 OCPP16ChargePointErrorCode
,
52 OCPP16ChargePointStatus
,
53 type OCPP16ChargingProfile
,
54 OCPP16ChargingProfilePurposeType
,
55 type OCPP16ChargingSchedule
,
56 type OCPP16ClearCacheRequest
,
57 type OCPP16ClearChargingProfileRequest
,
58 type OCPP16ClearChargingProfileResponse
,
59 type OCPP16DataTransferRequest
,
60 type OCPP16DataTransferResponse
,
61 OCPP16DataTransferVendorId
,
62 OCPP16DiagnosticsStatus
,
63 type OCPP16DiagnosticsStatusNotificationRequest
,
64 type OCPP16DiagnosticsStatusNotificationResponse
,
66 type OCPP16FirmwareStatusNotificationRequest
,
67 type OCPP16FirmwareStatusNotificationResponse
,
68 type OCPP16GetCompositeScheduleRequest
,
69 type OCPP16GetCompositeScheduleResponse
,
70 type OCPP16HeartbeatRequest
,
71 type OCPP16HeartbeatResponse
,
72 OCPP16IncomingRequestCommand
,
75 type OCPP16ReserveNowRequest
,
76 type OCPP16ReserveNowResponse
,
77 OCPP16StandardParametersKey
,
78 type OCPP16StartTransactionRequest
,
79 type OCPP16StartTransactionResponse
,
80 type OCPP16StatusNotificationRequest
,
81 type OCPP16StatusNotificationResponse
,
82 OCPP16StopTransactionReason
,
83 OCPP16SupportedFeatureProfiles
,
84 type OCPP16TriggerMessageRequest
,
85 type OCPP16TriggerMessageResponse
,
86 type OCPP16UpdateFirmwareRequest
,
87 type OCPP16UpdateFirmwareResponse
,
88 type OCPPConfigurationKey
,
90 type RemoteStartTransactionRequest
,
91 type RemoteStopTransactionRequest
,
92 ReservationTerminationReason
,
94 type SetChargingProfileRequest
,
95 type SetChargingProfileResponse
,
96 type UnlockConnectorRequest
,
97 type UnlockConnectorResponse
98 } from
'../../../types/index.js'
103 formatDurationMilliSeconds
,
110 } from
'../../../utils/index.js'
111 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService.js'
113 const moduleName
= 'OCPP16IncomingRequestService'
115 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
116 protected payloadValidateFunctions
: Map
<OCPP16IncomingRequestCommand
, ValidateFunction
<JsonType
>>
118 private readonly incomingRequestHandlers
: Map
<
119 OCPP16IncomingRequestCommand
,
120 IncomingRequestHandler
123 public constructor () {
124 // if (new.target.name === moduleName) {
125 // throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
127 super(OCPPVersion
.VERSION_16
)
128 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
130 OCPP16IncomingRequestCommand
.RESET
,
131 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
134 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
135 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
138 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
139 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
142 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
143 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
146 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
147 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
150 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
151 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
154 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
155 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
158 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
159 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
162 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
163 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
166 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
167 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
170 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
171 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
174 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
175 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
178 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
179 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
182 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
183 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
186 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
187 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
190 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
191 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
194 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
195 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
198 this.payloadValidateFunctions
= new Map
<
199 OCPP16IncomingRequestCommand
,
200 ValidateFunction
<JsonType
>
203 OCPP16IncomingRequestCommand
.RESET
,
206 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
207 'assets/json-schemas/ocpp/1.6/Reset.json',
215 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
218 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
219 'assets/json-schemas/ocpp/1.6/ClearCache.json',
227 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
230 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
231 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
239 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
242 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
243 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
251 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
254 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
255 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
263 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
266 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
267 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
275 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
278 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
279 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
287 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
290 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
291 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
299 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
302 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearChargingProfileRequest
>(
303 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
311 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
314 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
315 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
323 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
326 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
327 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
335 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
338 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
339 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
347 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
350 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
351 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
359 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
362 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
363 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
371 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
374 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
375 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
383 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
386 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
387 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
395 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
398 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
399 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
407 this.validatePayload
= this.validatePayload
.bind(this)
410 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
411 chargingStation
: ChargingStation
,
413 commandName
: OCPP16IncomingRequestCommand
,
414 commandPayload
: ReqType
416 let response
: ResType
418 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
419 chargingStation
.inPendingState() &&
420 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
421 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
424 ErrorType
.SECURITY_ERROR
,
425 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
429 )} while the charging station is in pending state on the central server`,
435 chargingStation
.isRegistered() ||
436 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
437 chargingStation
.inUnknownState())
440 this.incomingRequestHandlers
.has(commandName
) &&
441 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
444 this.validatePayload(chargingStation
, commandName
, commandPayload
)
445 // Call the method to build the response
446 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
447 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
454 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
462 ErrorType
.NOT_IMPLEMENTED
,
463 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
474 ErrorType
.SECURITY_ERROR
,
475 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
479 )} while the charging station is not registered on the central server.`,
484 // Send the built response
485 await chargingStation
.ocppRequestService
.sendResponse(
493 private validatePayload (
494 chargingStation
: ChargingStation
,
495 commandName
: OCPP16IncomingRequestCommand
,
496 commandPayload
: JsonType
498 if (this.payloadValidateFunctions
.has(commandName
)) {
499 return this.validateIncomingRequestPayload(chargingStation
, commandName
, commandPayload
)
502 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
507 // Simulate charging station restart
508 private handleRequestReset (
509 chargingStation
: ChargingStation
,
510 commandPayload
: ResetRequest
512 const { type } = commandPayload
514 .reset(`${type}Reset` as OCPP16StopTransactionReason
)
515 .catch(Constants
.EMPTY_FUNCTION
)
517 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
518 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
519 chargingStation.stationInfo!.resetTime!
522 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
525 private async handleRequestUnlockConnector (
526 chargingStation
: ChargingStation
,
527 commandPayload
: UnlockConnectorRequest
528 ): Promise
<UnlockConnectorResponse
> {
529 const { connectorId
} = commandPayload
530 if (!chargingStation
.hasConnector(connectorId
)) {
532 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`
534 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
536 if (connectorId
=== 0) {
537 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`)
538 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
540 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
541 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
543 OCPP16StopTransactionReason
.UNLOCK_COMMAND
545 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
546 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
548 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
550 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
553 OCPP16ChargePointStatus
.Available
555 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
558 private handleRequestGetConfiguration (
559 chargingStation
: ChargingStation
,
560 commandPayload
: GetConfigurationRequest
561 ): GetConfigurationResponse
{
562 const { key
} = commandPayload
563 const configurationKey
: OCPPConfigurationKey
[] = []
564 const unknownKey
: string[] = []
566 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
567 for (const configKey
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
568 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(configKey
)) {
571 configurationKey
.push({
573 readonly: configKey
.readonly,
574 value
: configKey
.value
577 } else if (isNotEmptyArray(key
)) {
578 for (const k
of key
) {
579 const keyFound
= getConfigurationKey(chargingStation
, k
, true)
580 if (keyFound
!= null) {
581 if (!OCPP16ServiceUtils
.isConfigurationKeyVisible(keyFound
)) {
584 configurationKey
.push({
586 readonly: keyFound
.readonly,
587 value
: keyFound
.value
600 private handleRequestChangeConfiguration (
601 chargingStation
: ChargingStation
,
602 commandPayload
: ChangeConfigurationRequest
603 ): ChangeConfigurationResponse
{
604 const { key
, value
} = commandPayload
605 const keyToChange
= getConfigurationKey(chargingStation
, key
, true)
606 if (keyToChange
?.readonly === true) {
607 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
608 } else if (keyToChange
?.readonly === false) {
609 let valueChanged
= false
610 if (keyToChange
.value
!== value
) {
611 setConfigurationKeyValue(chargingStation
, key
, value
, true)
614 let triggerHeartbeatRestart
= false
616 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
617 OCPP16StandardParametersKey
.HeartBeatInterval
&&
620 setConfigurationKeyValue(
622 OCPP16StandardParametersKey
.HeartbeatInterval
,
625 triggerHeartbeatRestart
= true
628 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
629 OCPP16StandardParametersKey
.HeartbeatInterval
&&
632 setConfigurationKeyValue(
634 OCPP16StandardParametersKey
.HeartBeatInterval
,
637 triggerHeartbeatRestart
= true
639 if (triggerHeartbeatRestart
) {
640 chargingStation
.restartHeartbeat()
643 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
644 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
647 chargingStation
.restartWebSocketPing()
649 if (keyToChange
.reboot
=== true) {
650 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
652 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
654 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
657 private handleRequestSetChargingProfile (
658 chargingStation
: ChargingStation
,
659 commandPayload
: SetChargingProfileRequest
660 ): SetChargingProfileResponse
{
662 !OCPP16ServiceUtils
.checkFeatureProfile(
664 OCPP16SupportedFeatureProfiles
.SmartCharging
,
665 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
668 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
670 const { connectorId
, csChargingProfiles
} = commandPayload
671 if (!chargingStation
.hasConnector(connectorId
)) {
673 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`
675 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
678 csChargingProfiles
.chargingProfilePurpose
===
679 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
682 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
685 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
689 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`
691 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
693 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
695 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
697 connectorStatus
?.transactionStarted
=== false
700 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`
702 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
705 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
707 connectorStatus
?.transactionStarted
=== true &&
708 csChargingProfiles
.transactionId
!== connectorStatus
.transactionId
711 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
712 csChargingProfiles.transactionId
713 } than the started transaction id ${connectorStatus.transactionId}`
715 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
717 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
)
719 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
722 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
725 private handleRequestGetCompositeSchedule (
726 chargingStation
: ChargingStation
,
727 commandPayload
: OCPP16GetCompositeScheduleRequest
728 ): OCPP16GetCompositeScheduleResponse
{
730 !OCPP16ServiceUtils
.checkFeatureProfile(
732 OCPP16SupportedFeatureProfiles
.SmartCharging
,
733 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
736 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
738 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
739 if (!chargingStation
.hasConnector(connectorId
)) {
741 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`
743 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
745 if (connectorId
=== 0) {
747 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`
749 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
751 if (chargingRateUnit
!= null) {
753 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`
756 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
758 isEmptyArray(connectorStatus
?.chargingProfiles
) &&
759 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
)
761 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
763 const currentDate
= new Date()
764 const compositeScheduleInterval
: Interval
= {
766 end
: addSeconds(currentDate
, duration
)
768 // Get charging profiles sorted by connector id then stack level
769 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
773 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined
774 let compositeSchedule
: OCPP16ChargingSchedule
| undefined
775 for (const chargingProfile
of chargingProfiles
) {
776 if (chargingProfile
.chargingSchedule
.startSchedule
== null) {
778 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
779 chargingProfile.chargingProfileId
780 } has no startSchedule defined. Trying to set it to the connector current transaction start date`
782 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
783 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
785 if (!isDate(chargingProfile
.chargingSchedule
.startSchedule
)) {
787 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
788 chargingProfile.chargingProfileId
789 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`
791 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
792 chargingProfile
.chargingSchedule
.startSchedule
795 if (chargingProfile
.chargingSchedule
.duration
== null) {
797 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
798 chargingProfile.chargingProfileId
799 } has no duration defined and will be set to the maximum time allowed`
801 // OCPP specifies that if duration is not defined, it should be infinite
802 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
804 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
805 chargingProfile
.chargingSchedule
.startSchedule
!
809 !prepareChargingProfileKind(
812 compositeScheduleInterval
.start
,
813 chargingStation
.logPrefix()
819 !canProceedChargingProfile(
821 compositeScheduleInterval
.start
,
822 chargingStation
.logPrefix()
827 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
828 previousCompositeSchedule
,
829 chargingProfile
.chargingSchedule
,
830 compositeScheduleInterval
832 previousCompositeSchedule
= compositeSchedule
834 if (compositeSchedule
!= null) {
836 status: GenericStatus
.Accepted
,
837 scheduleStart
: compositeSchedule
.startSchedule
,
839 chargingSchedule
: compositeSchedule
842 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
845 private handleRequestClearChargingProfile (
846 chargingStation
: ChargingStation
,
847 commandPayload
: OCPP16ClearChargingProfileRequest
848 ): OCPP16ClearChargingProfileResponse
{
850 !OCPP16ServiceUtils
.checkFeatureProfile(
852 OCPP16SupportedFeatureProfiles
.SmartCharging
,
853 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
856 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
858 const { connectorId
} = commandPayload
859 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
860 if (!chargingStation
.hasConnector(connectorId
!)) {
862 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`
864 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
866 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
867 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!)
868 if (connectorId
!= null && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
869 connectorStatus
.chargingProfiles
= []
871 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`
873 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
875 if (connectorId
== null) {
876 let clearedCP
= false
877 if (chargingStation
.hasEvses
) {
878 for (const evseStatus
of chargingStation
.evses
.values()) {
879 for (const status of evseStatus
.connectors
.values()) {
880 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
883 status.chargingProfiles
888 for (const id
of chargingStation
.connectors
.keys()) {
889 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
892 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
897 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
900 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
903 private async handleRequestChangeAvailability (
904 chargingStation
: ChargingStation
,
905 commandPayload
: OCPP16ChangeAvailabilityRequest
906 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
907 const { connectorId
, type } = commandPayload
908 if (!chargingStation
.hasConnector(connectorId
)) {
910 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`
912 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
914 const chargePointStatus
: OCPP16ChargePointStatus
=
915 type === OCPP16AvailabilityType
.Operative
916 ? OCPP16ChargePointStatus
.Available
917 : OCPP16ChargePointStatus
.Unavailable
918 if (connectorId
=== 0) {
919 let response
: OCPP16ChangeAvailabilityResponse
| undefined
920 if (chargingStation
.hasEvses
) {
921 for (const evseStatus
of chargingStation
.evses
.values()) {
922 response
= await OCPP16ServiceUtils
.changeAvailability(
924 [...evseStatus
.connectors
.keys()],
930 response
= await OCPP16ServiceUtils
.changeAvailability(
932 [...chargingStation
.connectors
.keys()],
937 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
941 (chargingStation
.isChargingStationAvailable() ||
942 (!chargingStation
.isChargingStationAvailable() &&
943 type === OCPP16AvailabilityType
.Inoperative
))
945 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
946 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
947 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
948 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
950 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
951 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type
952 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
957 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
959 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
962 private async handleRequestRemoteStartTransaction (
963 chargingStation
: ChargingStation
,
964 commandPayload
: RemoteStartTransactionRequest
965 ): Promise
<GenericResponse
> {
966 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
967 if (!chargingStation
.hasConnector(transactionConnectorId
)) {
968 return await this.notifyRemoteStartTransactionRejected(
970 transactionConnectorId
,
975 !chargingStation
.isChargingStationAvailable() ||
976 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
978 return await this.notifyRemoteStartTransactionRejected(
980 transactionConnectorId
,
984 const remoteStartTransactionLogMsg
= `
985 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
986 chargingStation.stationInfo?.chargingStationId
987 }#${transactionConnectorId} for idTag '${idTag}'`
988 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
990 transactionConnectorId
,
991 OCPP16ChargePointStatus
.Preparing
993 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
994 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!
995 // Authorization check required
997 chargingStation
.getAuthorizeRemoteTxRequests() &&
998 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
1000 // Authorization successful, start transaction
1002 (chargingProfile
!= null &&
1003 this.setRemoteStartTransactionChargingProfile(
1005 transactionConnectorId
,
1008 chargingProfile
== null
1010 connectorStatus
.transactionRemoteStarted
= true
1013 await chargingStation
.ocppRequestService
.requestHandler
<
1014 OCPP16StartTransactionRequest
,
1015 OCPP16StartTransactionResponse
1016 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
1017 connectorId
: transactionConnectorId
,
1020 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1022 logger
.debug(remoteStartTransactionLogMsg
)
1023 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1025 return await this.notifyRemoteStartTransactionRejected(
1027 transactionConnectorId
,
1031 return await this.notifyRemoteStartTransactionRejected(
1033 transactionConnectorId
,
1037 // No authorization check required, start transaction
1039 (chargingProfile
!= null &&
1040 this.setRemoteStartTransactionChargingProfile(
1042 transactionConnectorId
,
1045 chargingProfile
== null
1047 connectorStatus
.transactionRemoteStarted
= true
1050 await chargingStation
.ocppRequestService
.requestHandler
<
1051 OCPP16StartTransactionRequest
,
1052 OCPP16StartTransactionResponse
1053 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
1054 connectorId
: transactionConnectorId
,
1057 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1059 logger
.debug(remoteStartTransactionLogMsg
)
1060 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
1062 return await this.notifyRemoteStartTransactionRejected(
1064 transactionConnectorId
,
1068 return await this.notifyRemoteStartTransactionRejected(
1070 transactionConnectorId
,
1075 private async notifyRemoteStartTransactionRejected (
1076 chargingStation
: ChargingStation
,
1077 connectorId
: number,
1079 ): Promise
<GenericResponse
> {
1080 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)
1081 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1082 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1085 OCPP16ChargePointStatus
.Available
1089 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`
1091 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1094 private setRemoteStartTransactionChargingProfile (
1095 chargingStation
: ChargingStation
,
1096 connectorId
: number,
1097 chargingProfile
: OCPP16ChargingProfile
1099 if (chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1100 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
)
1102 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1108 `${chargingStation.logPrefix()} Not allowed to set ${
1109 chargingProfile.chargingProfilePurpose
1110 } charging profile(s) at remote start transaction`
1115 private async handleRequestRemoteStopTransaction (
1116 chargingStation
: ChargingStation
,
1117 commandPayload
: RemoteStopTransactionRequest
1118 ): Promise
<GenericResponse
> {
1119 const { transactionId
} = commandPayload
1120 if (chargingStation
.hasEvses
) {
1121 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1123 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1124 if (connectorStatus
.transactionId
=== transactionId
) {
1125 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1131 for (const connectorId
of chargingStation
.connectors
.keys()) {
1134 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1136 return await OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
)
1141 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`
1143 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
1146 private handleRequestUpdateFirmware (
1147 chargingStation
: ChargingStation
,
1148 commandPayload
: OCPP16UpdateFirmwareRequest
1149 ): OCPP16UpdateFirmwareResponse
{
1151 !OCPP16ServiceUtils
.checkFeatureProfile(
1153 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1154 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1158 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`
1160 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1162 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1163 commandPayload
.retrieveDate
= convertToDate(commandPayload
.retrieveDate
)!
1164 const { retrieveDate
} = commandPayload
1165 if (chargingStation
.stationInfo
?.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1167 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`
1169 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1171 const now
= Date.now()
1172 if (retrieveDate
.getTime() <= now
) {
1173 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1176 this.updateFirmwareSimulation(chargingStation
).catch(Constants
.EMPTY_FUNCTION
)
1177 }, retrieveDate
.getTime() - now
)
1179 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1182 private async updateFirmwareSimulation (
1183 chargingStation
: ChargingStation
,
1187 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1190 if (chargingStation
.hasEvses
) {
1191 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1193 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1194 if (connectorStatus
.transactionStarted
=== false) {
1195 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1198 OCPP16ChargePointStatus
.Unavailable
1205 for (const connectorId
of chargingStation
.connectors
.keys()) {
1208 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1210 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1213 OCPP16ChargePointStatus
.Unavailable
1218 await chargingStation
.ocppRequestService
.requestHandler
<
1219 OCPP16FirmwareStatusNotificationRequest
,
1220 OCPP16FirmwareStatusNotificationResponse
1221 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1222 status: OCPP16FirmwareStatus
.Downloading
1224 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1225 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
1227 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1228 OCPP16FirmwareStatus
.DownloadFailed
1230 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1231 await chargingStation
.ocppRequestService
.requestHandler
<
1232 OCPP16FirmwareStatusNotificationRequest
,
1233 OCPP16FirmwareStatusNotificationResponse
1234 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1235 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1237 chargingStation
.stationInfo
.firmwareStatus
=
1238 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1241 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1242 await chargingStation
.ocppRequestService
.requestHandler
<
1243 OCPP16FirmwareStatusNotificationRequest
,
1244 OCPP16FirmwareStatusNotificationResponse
1245 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1246 status: OCPP16FirmwareStatus
.Downloaded
1248 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1249 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
1250 let wasTransactionsStarted
= false
1251 let transactionsStarted
: boolean
1253 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions()
1254 if (runningTransactions
> 0) {
1255 const waitTime
= secondsToMilliseconds(15)
1257 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1259 )} before continuing firmware update simulation`
1261 await sleep(waitTime
)
1262 transactionsStarted
= true
1263 wasTransactionsStarted
= true
1265 if (chargingStation
.hasEvses
) {
1266 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1268 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1269 if (connectorStatus
.status !== OCPP16ChargePointStatus
.Unavailable
) {
1270 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1273 OCPP16ChargePointStatus
.Unavailable
1280 for (const connectorId
of chargingStation
.connectors
.keys()) {
1283 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1284 OCPP16ChargePointStatus
.Unavailable
1286 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1289 OCPP16ChargePointStatus
.Unavailable
1294 transactionsStarted
= false
1296 } while (transactionsStarted
)
1297 !wasTransactionsStarted
&&
1298 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))))
1299 if (!checkChargingStation(chargingStation
, chargingStation
.logPrefix())) {
1302 await chargingStation
.ocppRequestService
.requestHandler
<
1303 OCPP16FirmwareStatusNotificationRequest
,
1304 OCPP16FirmwareStatusNotificationResponse
1305 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1306 status: OCPP16FirmwareStatus
.Installing
1308 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1309 chargingStation
.stationInfo
!.firmwareStatus
= OCPP16FirmwareStatus
.Installing
1311 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1312 OCPP16FirmwareStatus
.InstallationFailed
1314 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1315 await chargingStation
.ocppRequestService
.requestHandler
<
1316 OCPP16FirmwareStatusNotificationRequest
,
1317 OCPP16FirmwareStatusNotificationResponse
1318 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1319 status: chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1321 chargingStation
.stationInfo
.firmwareStatus
=
1322 chargingStation
.stationInfo
.firmwareUpgrade
.failureStatus
1325 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1326 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)))
1327 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
)
1331 private async handleRequestGetDiagnostics (
1332 chargingStation
: ChargingStation
,
1333 commandPayload
: GetDiagnosticsRequest
1334 ): Promise
<GetDiagnosticsResponse
> {
1336 !OCPP16ServiceUtils
.checkFeatureProfile(
1338 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1339 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1343 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`
1345 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1347 const { location
} = commandPayload
1348 const uri
= new URL(location
)
1349 if (uri
.protocol
.startsWith('ftp:')) {
1350 let ftpClient
: Client
| undefined
1352 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1353 .filter(file
=> file
.endsWith('.log'))
1354 .map(file
=> join('./', file
))
1355 const diagnosticsArchive
= `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz`
1356 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
))
1357 ftpClient
= new Client()
1358 const accessResponse
= await ftpClient
.access({
1360 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1361 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1362 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
})
1364 let uploadResponse
: FTPResponse
| undefined
1365 if (accessResponse
.code
=== 220) {
1366 ftpClient
.trackProgress(info
=> {
1368 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1370 } bytes transferred from diagnostics archive ${info.name}`
1372 chargingStation
.ocppRequestService
1374 OCPP16DiagnosticsStatusNotificationRequest
,
1375 OCPP16DiagnosticsStatusNotificationResponse
1376 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1377 status: OCPP16DiagnosticsStatus
.Uploading
1381 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1382 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1388 uploadResponse
= await ftpClient
.uploadFrom(
1389 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1390 `${uri.pathname}${diagnosticsArchive}`
1392 if (uploadResponse
.code
=== 226) {
1393 await chargingStation
.ocppRequestService
.requestHandler
<
1394 OCPP16DiagnosticsStatusNotificationRequest
,
1395 OCPP16DiagnosticsStatusNotificationResponse
1396 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1397 status: OCPP16DiagnosticsStatus
.Uploaded
1400 return { fileName
: diagnosticsArchive
}
1402 throw new OCPPError(
1403 ErrorType
.GENERIC_ERROR
,
1404 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse.code}`,
1405 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1408 throw new OCPPError(
1409 ErrorType
.GENERIC_ERROR
,
1410 `Diagnostics transfer failed with error code ${accessResponse.code}|${uploadResponse?.code}`,
1411 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1414 await chargingStation
.ocppRequestService
.requestHandler
<
1415 OCPP16DiagnosticsStatusNotificationRequest
,
1416 OCPP16DiagnosticsStatusNotificationResponse
1417 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1418 status: OCPP16DiagnosticsStatus
.UploadFailed
1421 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1422 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1424 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1426 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
}
1431 `${chargingStation.logPrefix()} Unsupported protocol ${
1433 } to transfer the diagnostic logs archive`
1435 await chargingStation
.ocppRequestService
.requestHandler
<
1436 OCPP16DiagnosticsStatusNotificationRequest
,
1437 OCPP16DiagnosticsStatusNotificationResponse
1438 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1439 status: OCPP16DiagnosticsStatus
.UploadFailed
1441 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
1445 private handleRequestTriggerMessage (
1446 chargingStation
: ChargingStation
,
1447 commandPayload
: OCPP16TriggerMessageRequest
1448 ): OCPP16TriggerMessageResponse
{
1449 const { requestedMessage
, connectorId
} = commandPayload
1451 !OCPP16ServiceUtils
.checkFeatureProfile(
1453 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1454 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1456 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1458 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1461 !OCPP16ServiceUtils
.isConnectorIdValid(
1463 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1464 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1468 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
1471 switch (requestedMessage
) {
1472 case OCPP16MessageTrigger
.BootNotification
:
1474 chargingStation
.ocppRequestService
1475 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1477 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1478 chargingStation
.bootNotificationRequest
,
1479 { skipBufferingOnError
: true, triggerMessage
: true }
1482 chargingStation
.bootNotificationResponse
= response
1484 .catch(Constants
.EMPTY_FUNCTION
)
1485 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
)
1486 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1487 case OCPP16MessageTrigger
.Heartbeat
:
1489 chargingStation
.ocppRequestService
1490 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1492 OCPP16RequestCommand
.HEARTBEAT
,
1495 triggerMessage
: true
1498 .catch(Constants
.EMPTY_FUNCTION
)
1499 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
)
1500 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1501 case OCPP16MessageTrigger
.StatusNotification
:
1503 if (connectorId
!= null) {
1504 chargingStation
.ocppRequestService
1505 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1507 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1510 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1511 status: chargingStation
.getConnectorStatus(connectorId
)?.status
1514 triggerMessage
: true
1517 .catch(Constants
.EMPTY_FUNCTION
)
1518 } else if (chargingStation
.hasEvses
) {
1519 for (const evseStatus
of chargingStation
.evses
.values()) {
1520 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1521 chargingStation
.ocppRequestService
1523 OCPP16StatusNotificationRequest
,
1524 OCPP16StatusNotificationResponse
1527 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1530 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1531 status: connectorStatus
.status
1534 triggerMessage
: true
1537 .catch(Constants
.EMPTY_FUNCTION
)
1541 for (const [id
, connectorStatus
] of chargingStation
.connectors
) {
1542 chargingStation
.ocppRequestService
1544 OCPP16StatusNotificationRequest
,
1545 OCPP16StatusNotificationResponse
1548 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1551 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1552 status: connectorStatus
.status
1555 triggerMessage
: true
1558 .catch(Constants
.EMPTY_FUNCTION
)
1561 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
)
1562 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
1564 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
1567 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1568 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1570 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1572 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}
1577 private handleRequestDataTransfer (
1578 chargingStation
: ChargingStation
,
1579 commandPayload
: OCPP16DataTransferRequest
1580 ): OCPP16DataTransferResponse
{
1581 const { vendorId
} = commandPayload
1583 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1584 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
1586 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
1588 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1589 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1591 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1593 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}
1598 private async handleRequestReserveNow (
1599 chargingStation
: ChargingStation
,
1600 commandPayload
: OCPP16ReserveNowRequest
1601 ): Promise
<OCPP16ReserveNowResponse
> {
1603 !OCPP16ServiceUtils
.checkFeatureProfile(
1605 OCPP16SupportedFeatureProfiles
.Reservation
,
1606 OCPP16IncomingRequestCommand
.RESERVE_NOW
1609 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1611 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1612 commandPayload
.expiryDate
= convertToDate(commandPayload
.expiryDate
)!
1613 const { reservationId
, idTag
, connectorId
} = commandPayload
1614 let response
: OCPP16ReserveNowResponse
1616 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1617 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1619 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1620 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1622 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1623 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
1625 await removeExpiredReservations(chargingStation
)
1626 switch (chargingStation
.getConnectorStatus(connectorId
)?.status) {
1627 case OCPP16ChargePointStatus
.Faulted
:
1628 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
1630 case OCPP16ChargePointStatus
.Preparing
:
1631 case OCPP16ChargePointStatus
.Charging
:
1632 case OCPP16ChargePointStatus
.SuspendedEV
:
1633 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1634 case OCPP16ChargePointStatus
.Finishing
:
1635 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1637 case OCPP16ChargePointStatus
.Unavailable
:
1638 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
1640 case OCPP16ChargePointStatus
.Reserved
:
1641 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1642 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1645 // eslint-disable-next-line no-fallthrough
1647 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1648 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
1651 await chargingStation
.addReservation({
1652 id
: commandPayload
.reservationId
,
1655 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
1660 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1661 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
1662 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1663 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1665 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1667 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
}
1672 private async handleRequestCancelReservation (
1673 chargingStation
: ChargingStation
,
1674 commandPayload
: OCPP16CancelReservationRequest
1675 ): Promise
<GenericResponse
> {
1677 !OCPP16ServiceUtils
.checkFeatureProfile(
1679 OCPP16SupportedFeatureProfiles
.Reservation
,
1680 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
1683 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1686 const { reservationId
} = commandPayload
1687 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
)
1688 if (reservation
== null) {
1690 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`
1692 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
1694 await chargingStation
.removeReservation(
1696 ReservationTerminationReason
.RESERVATION_CANCELED
1698 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
1700 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1701 return this.handleIncomingRequestError
<GenericResponse
>(
1703 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1705 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
}