1 // Partial Copyright Jerome Benoit. 2021-2023. 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 { JSONSchemaType
} from
'ajv';
8 import { Client
, type FTPResponse
} from
'basic-ftp';
9 import { addSeconds
, isWithinInterval
, max
, secondsToMilliseconds
} from
'date-fns';
10 import { create
} from
'tar';
12 import { OCPP16Constants
} from
'./OCPP16Constants';
13 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
18 removeExpiredReservations
,
19 setConfigurationKeyValue
,
20 } from
'../../../charging-station';
21 import { OCPPError
} from
'../../../exception';
23 type ChangeConfigurationRequest
,
24 type ChangeConfigurationResponse
,
25 type ClearChargingProfileRequest
,
26 type ClearChargingProfileResponse
,
30 type GetConfigurationRequest
,
31 type GetConfigurationResponse
,
32 type GetDiagnosticsRequest
,
33 type GetDiagnosticsResponse
,
34 type IncomingRequestHandler
,
37 OCPP16AuthorizationStatus
,
38 OCPP16AvailabilityType
,
39 type OCPP16BootNotificationRequest
,
40 type OCPP16BootNotificationResponse
,
41 type OCPP16CancelReservationRequest
,
42 type OCPP16ChangeAvailabilityRequest
,
43 type OCPP16ChangeAvailabilityResponse
,
44 OCPP16ChargePointErrorCode
,
45 OCPP16ChargePointStatus
,
46 type OCPP16ChargingProfile
,
47 OCPP16ChargingProfilePurposeType
,
48 type OCPP16ChargingSchedule
,
49 type OCPP16ClearCacheRequest
,
50 type OCPP16DataTransferRequest
,
51 type OCPP16DataTransferResponse
,
52 OCPP16DataTransferVendorId
,
53 OCPP16DiagnosticsStatus
,
54 type OCPP16DiagnosticsStatusNotificationRequest
,
55 type OCPP16DiagnosticsStatusNotificationResponse
,
57 type OCPP16FirmwareStatusNotificationRequest
,
58 type OCPP16FirmwareStatusNotificationResponse
,
59 type OCPP16GetCompositeScheduleRequest
,
60 type OCPP16GetCompositeScheduleResponse
,
61 type OCPP16HeartbeatRequest
,
62 type OCPP16HeartbeatResponse
,
63 OCPP16IncomingRequestCommand
,
66 type OCPP16ReserveNowRequest
,
67 type OCPP16ReserveNowResponse
,
68 OCPP16StandardParametersKey
,
69 type OCPP16StartTransactionRequest
,
70 type OCPP16StartTransactionResponse
,
71 type OCPP16StatusNotificationRequest
,
72 type OCPP16StatusNotificationResponse
,
73 OCPP16StopTransactionReason
,
74 OCPP16SupportedFeatureProfiles
,
75 type OCPP16TriggerMessageRequest
,
76 type OCPP16TriggerMessageResponse
,
77 type OCPP16UpdateFirmwareRequest
,
78 type OCPP16UpdateFirmwareResponse
,
79 type OCPPConfigurationKey
,
81 type RemoteStartTransactionRequest
,
82 type RemoteStopTransactionRequest
,
83 ReservationTerminationReason
,
85 type SetChargingProfileRequest
,
86 type SetChargingProfileResponse
,
87 type UnlockConnectorRequest
,
88 type UnlockConnectorResponse
,
89 } from
'../../../types';
94 formatDurationMilliSeconds
,
103 } from
'../../../utils';
104 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService';
106 const moduleName
= 'OCPP16IncomingRequestService';
108 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
109 protected jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
110 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
112 public constructor() {
113 // if (new.target?.name === moduleName) {
114 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
116 super(OCPPVersion
.VERSION_16
);
117 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
119 OCPP16IncomingRequestCommand
.RESET
,
120 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
,
123 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
124 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
,
127 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
128 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
,
131 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
132 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
,
135 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
136 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
,
139 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
140 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
,
143 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
144 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
,
147 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
148 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
,
151 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
152 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
,
155 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
156 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
159 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
160 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
163 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
164 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
,
167 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
168 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
,
171 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
172 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
,
175 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
176 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
,
179 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
180 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
,
183 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
184 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
,
187 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
189 OCPP16IncomingRequestCommand
.RESET
,
190 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
191 'assets/json-schemas/ocpp/1.6/Reset.json',
197 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
198 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
199 'assets/json-schemas/ocpp/1.6/ClearCache.json',
205 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
206 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
207 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
213 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
214 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
215 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
221 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
222 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
223 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
229 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
230 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
231 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
237 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
238 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
239 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
245 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
246 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
247 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
253 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
254 OCPP16ServiceUtils
.parseJsonSchemaFile
<ClearChargingProfileRequest
>(
255 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
261 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
262 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
263 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
269 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
270 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
271 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
277 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
278 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
279 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
285 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
286 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
287 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
293 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
294 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
295 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
301 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
302 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
303 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
309 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
310 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
311 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
317 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
318 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
319 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
325 this.validatePayload
= this.validatePayload
.bind(this) as (
326 chargingStation
: ChargingStation
,
327 commandName
: OCPP16IncomingRequestCommand
,
328 commandPayload
: JsonType
,
332 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
333 chargingStation
: ChargingStation
,
335 commandName
: OCPP16IncomingRequestCommand
,
336 commandPayload
: ReqType
,
338 let response
: ResType
;
340 chargingStation
.getOcppStrictCompliance() === true &&
341 chargingStation
.inPendingState() === true &&
342 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
343 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
346 ErrorType
.SECURITY_ERROR
,
347 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
351 )} while the charging station is in pending state on the central server`,
357 chargingStation
.isRegistered() === true ||
358 (chargingStation
.getOcppStrictCompliance() === false &&
359 chargingStation
.inUnknownState() === true)
362 this.incomingRequestHandlers
.has(commandName
) === true &&
363 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
366 this.validatePayload(chargingStation
, commandName
, commandPayload
);
367 // Call the method to build the response
368 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
375 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler:
376 Handle incoming request error:`,
384 ErrorType
.NOT_IMPLEMENTED
,
385 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
396 ErrorType
.SECURITY_ERROR
,
397 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
401 )} while the charging station is not registered on the central server.`,
406 // Send the built response
407 await chargingStation
.ocppRequestService
.sendResponse(
415 private validatePayload(
416 chargingStation
: ChargingStation
,
417 commandName
: OCPP16IncomingRequestCommand
,
418 commandPayload
: JsonType
,
420 if (this.jsonSchemas
.has(commandName
) === true) {
421 return this.validateIncomingRequestPayload(
424 this.jsonSchemas
.get(commandName
)!,
429 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found
430 for command '${commandName}' PDU validation`,
435 // Simulate charging station restart
436 private handleRequestReset(
437 chargingStation
: ChargingStation
,
438 commandPayload
: ResetRequest
,
440 const { type } = commandPayload
;
441 this.runInAsyncScope(
442 chargingStation
.reset
.bind(chargingStation
) as (
443 this: ChargingStation
,
447 `${type}Reset` as OCPP16StopTransactionReason
,
448 ).catch(Constants
.EMPTY_FUNCTION
);
450 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be
451 back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime!)}`,
453 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
456 private async handleRequestUnlockConnector(
457 chargingStation
: ChargingStation
,
458 commandPayload
: UnlockConnectorRequest
,
459 ): Promise
<UnlockConnectorResponse
> {
460 const { connectorId
} = commandPayload
;
461 if (chargingStation
.hasConnector(connectorId
) === false) {
463 `${chargingStation.logPrefix()} Trying to unlock a non existing
464 connector id ${connectorId.toString()}`,
466 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
468 if (connectorId
=== 0) {
470 `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}`,
472 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
474 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
475 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
477 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
479 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
480 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
482 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
484 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
487 OCPP16ChargePointStatus
.Available
,
489 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
492 private handleRequestGetConfiguration(
493 chargingStation
: ChargingStation
,
494 commandPayload
: GetConfigurationRequest
,
495 ): GetConfigurationResponse
{
496 const { key
} = commandPayload
;
497 const configurationKey
: OCPPConfigurationKey
[] = [];
498 const unknownKey
: string[] = [];
499 if (isUndefined(key
) === true) {
500 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
501 if (isUndefined(configuration
.visible
) === true) {
502 configuration
.visible
= true;
504 if (configuration
.visible
=== false) {
507 configurationKey
.push({
508 key
: configuration
.key
,
509 readonly: configuration
.readonly,
510 value
: configuration
.value
,
513 } else if (isNotEmptyArray(key
) === true) {
514 for (const k
of key
!) {
515 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
517 if (isUndefined(keyFound
.visible
) === true) {
518 keyFound
.visible
= true;
520 if (keyFound
.visible
=== false) {
523 configurationKey
.push({
525 readonly: keyFound
.readonly,
526 value
: keyFound
.value
,
539 private handleRequestChangeConfiguration(
540 chargingStation
: ChargingStation
,
541 commandPayload
: ChangeConfigurationRequest
,
542 ): ChangeConfigurationResponse
{
543 const { key
, value
} = commandPayload
;
544 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
545 if (keyToChange
?.readonly === true) {
546 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
547 } else if (keyToChange
?.readonly === false) {
548 let valueChanged
= false;
549 if (keyToChange
.value
!== value
) {
550 setConfigurationKeyValue(chargingStation
, key
, value
, true);
553 let triggerHeartbeatRestart
= false;
555 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
556 OCPP16StandardParametersKey
.HeartBeatInterval
&&
559 setConfigurationKeyValue(
561 OCPP16StandardParametersKey
.HeartbeatInterval
,
564 triggerHeartbeatRestart
= true;
567 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
568 OCPP16StandardParametersKey
.HeartbeatInterval
&&
571 setConfigurationKeyValue(
573 OCPP16StandardParametersKey
.HeartBeatInterval
,
576 triggerHeartbeatRestart
= true;
578 if (triggerHeartbeatRestart
) {
579 chargingStation
.restartHeartbeat();
582 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
583 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
586 chargingStation
.restartWebSocketPing();
588 if (keyToChange
.reboot
) {
589 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
591 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
593 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
596 private handleRequestSetChargingProfile(
597 chargingStation
: ChargingStation
,
598 commandPayload
: SetChargingProfileRequest
,
599 ): SetChargingProfileResponse
{
601 OCPP16ServiceUtils
.checkFeatureProfile(
603 OCPP16SupportedFeatureProfiles
.SmartCharging
,
604 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
607 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
609 const { connectorId
, csChargingProfiles
} = commandPayload
;
610 if (chargingStation
.hasConnector(connectorId
) === false) {
612 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a
613 non existing connector id ${connectorId}`,
615 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
618 csChargingProfiles
.chargingProfilePurpose
===
619 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
622 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
625 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
626 (connectorId
=== 0 ||
627 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false)
630 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
631 on connector ${connectorId} without a started transaction`,
633 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
635 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
637 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
640 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
643 private handleRequestGetCompositeSchedule(
644 chargingStation
: ChargingStation
,
645 commandPayload
: OCPP16GetCompositeScheduleRequest
,
646 ): OCPP16GetCompositeScheduleResponse
{
648 OCPP16ServiceUtils
.checkFeatureProfile(
650 OCPP16SupportedFeatureProfiles
.SmartCharging
,
651 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
654 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
656 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
657 if (chargingStation
.hasConnector(connectorId
) === false) {
659 `${chargingStation.logPrefix()} Trying to get composite schedule to a
660 non existing connector id ${connectorId}`,
662 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
664 if (connectorId
=== 0) {
666 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
668 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
670 if (chargingRateUnit
) {
672 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported`,
674 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
676 if (isEmptyArray(chargingStation
.getConnectorStatus(connectorId
)?.chargingProfiles
)) {
677 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
679 const startDate
= new Date();
680 const interval
: Interval
= {
682 end
: addSeconds(startDate
, duration
),
684 let compositeSchedule
: OCPP16ChargingSchedule
| undefined;
685 for (const chargingProfile
of chargingStation
.getConnectorStatus(connectorId
)!
686 .chargingProfiles
!) {
688 compositeSchedule
?.chargingRateUnit
&&
689 compositeSchedule
.chargingRateUnit
!== chargingProfile
.chargingSchedule
.chargingRateUnit
692 `${chargingStation.logPrefix()} Building composite schedule with different charging rate units is not yet supported, skipping charging profile id ${
693 chargingProfile.chargingProfileId
699 isWithinInterval(chargingProfile
.chargingSchedule
.startSchedule
!, interval
) &&
702 chargingProfile
.chargingSchedule
.startSchedule
!,
703 chargingProfile
.chargingSchedule
.duration
!,
708 compositeSchedule
= {
710 compositeSchedule
?.startSchedule
?? interval
.start
,
711 chargingProfile
.chargingSchedule
.startSchedule
!,
714 compositeSchedule
?.duration
?? -Infinity,
715 chargingProfile
.chargingSchedule
.duration
!,
717 chargingRateUnit
: chargingProfile
.chargingSchedule
.chargingRateUnit
,
718 ...(compositeSchedule
?.chargingSchedulePeriod
=== undefined
719 ? { chargingSchedulePeriod
: [] }
721 chargingSchedulePeriod
: compositeSchedule
.chargingSchedulePeriod
.concat(
722 ...chargingProfile
.chargingSchedule
.chargingSchedulePeriod
,
725 ...(chargingProfile
.chargingSchedule
.minChargeRate
&& {
726 minChargeRate
: Math.min(
727 compositeSchedule
?.minChargeRate
?? Infinity,
728 chargingProfile
.chargingSchedule
.minChargeRate
,
735 status: GenericStatus
.Accepted
,
736 scheduleStart
: compositeSchedule
?.startSchedule
,
738 chargingSchedule
: compositeSchedule
,
742 private handleRequestClearChargingProfile(
743 chargingStation
: ChargingStation
,
744 commandPayload
: ClearChargingProfileRequest
,
745 ): ClearChargingProfileResponse
{
747 OCPP16ServiceUtils
.checkFeatureProfile(
749 OCPP16SupportedFeatureProfiles
.SmartCharging
,
750 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
753 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
755 const { connectorId
} = commandPayload
;
756 if (chargingStation
.hasConnector(connectorId
!) === false) {
758 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to
759 a non existing connector id ${connectorId}`,
761 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
764 !isNullOrUndefined(connectorId
) &&
765 isNotEmptyArray(chargingStation
.getConnectorStatus(connectorId
!)?.chargingProfiles
)
767 chargingStation
.getConnectorStatus(connectorId
!)!.chargingProfiles
= [];
769 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
771 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
773 if (isNullOrUndefined(connectorId
)) {
774 let clearedCP
= false;
775 if (chargingStation
.hasEvses
) {
776 for (const evseStatus
of chargingStation
.evses
.values()) {
777 for (const connectorStatus
of evseStatus
.connectors
.values()) {
778 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
781 connectorStatus
.chargingProfiles
,
786 for (const id
of chargingStation
.connectors
.keys()) {
787 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
790 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
795 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
798 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
801 private async handleRequestChangeAvailability(
802 chargingStation
: ChargingStation
,
803 commandPayload
: OCPP16ChangeAvailabilityRequest
,
804 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
805 const { connectorId
, type } = commandPayload
;
806 if (chargingStation
.hasConnector(connectorId
) === false) {
808 `${chargingStation.logPrefix()} Trying to change the availability of a
809 non existing connector id ${connectorId.toString()}`,
811 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
813 const chargePointStatus
: OCPP16ChargePointStatus
=
814 type === OCPP16AvailabilityType
.Operative
815 ? OCPP16ChargePointStatus
.Available
816 : OCPP16ChargePointStatus
.Unavailable
;
817 if (connectorId
=== 0) {
818 let response
: OCPP16ChangeAvailabilityResponse
;
819 if (chargingStation
.hasEvses
) {
820 for (const evseStatus
of chargingStation
.evses
.values()) {
821 response
= await OCPP16ServiceUtils
.changeAvailability(
823 [...evseStatus
.connectors
.keys()],
829 response
= await OCPP16ServiceUtils
.changeAvailability(
831 [...chargingStation
.connectors
.keys()],
839 (chargingStation
.isChargingStationAvailable() === true ||
840 (chargingStation
.isChargingStationAvailable() === false &&
841 type === OCPP16AvailabilityType
.Inoperative
))
843 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
844 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
845 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
847 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
848 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
853 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
855 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
858 private async handleRequestRemoteStartTransaction(
859 chargingStation
: ChargingStation
,
860 commandPayload
: RemoteStartTransactionRequest
,
861 ): Promise
<GenericResponse
> {
862 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
863 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
864 return this.notifyRemoteStartTransactionRejected(
866 transactionConnectorId
,
871 !chargingStation
.isChargingStationAvailable() ||
872 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
874 return this.notifyRemoteStartTransactionRejected(
876 transactionConnectorId
,
880 const remoteStartTransactionLogMsg
= `
881 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
882 chargingStation.stationInfo.chargingStationId
883 }#${transactionConnectorId.toString()} for idTag '${idTag}'`;
884 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
886 transactionConnectorId
,
887 OCPP16ChargePointStatus
.Preparing
,
889 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
890 // Authorization check required
892 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
893 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
895 // Authorization successful, start transaction
897 this.setRemoteStartTransactionChargingProfile(
899 transactionConnectorId
,
903 connectorStatus
.transactionRemoteStarted
= true;
906 await chargingStation
.ocppRequestService
.requestHandler
<
907 OCPP16StartTransactionRequest
,
908 OCPP16StartTransactionResponse
909 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
910 connectorId
: transactionConnectorId
,
913 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
915 logger
.debug(remoteStartTransactionLogMsg
);
916 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
918 return this.notifyRemoteStartTransactionRejected(
920 transactionConnectorId
,
924 return this.notifyRemoteStartTransactionRejected(
926 transactionConnectorId
,
930 // No authorization check required, start transaction
932 this.setRemoteStartTransactionChargingProfile(
934 transactionConnectorId
,
938 connectorStatus
.transactionRemoteStarted
= true;
941 await chargingStation
.ocppRequestService
.requestHandler
<
942 OCPP16StartTransactionRequest
,
943 OCPP16StartTransactionResponse
944 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
945 connectorId
: transactionConnectorId
,
948 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
950 logger
.debug(remoteStartTransactionLogMsg
);
951 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
953 return this.notifyRemoteStartTransactionRejected(
955 transactionConnectorId
,
959 return this.notifyRemoteStartTransactionRejected(
961 transactionConnectorId
,
966 private async notifyRemoteStartTransactionRejected(
967 chargingStation
: ChargingStation
,
970 ): Promise
<GenericResponse
> {
972 chargingStation
.getConnectorStatus(connectorId
)?.status !== OCPP16ChargePointStatus
.Available
974 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
977 OCPP16ChargePointStatus
.Available
,
981 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id
982 ${connectorId.toString()}, idTag '${idTag}', availability '${chargingStation.getConnectorStatus(
984 )?.availability}', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`,
986 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
989 private setRemoteStartTransactionChargingProfile(
990 chargingStation
: ChargingStation
,
992 chargingProfile
: OCPP16ChargingProfile
,
996 chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
998 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1000 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction
1001 on connector id ${connectorId}: %j`,
1007 chargingProfile
.chargingProfilePurpose
!== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1010 `${chargingStation.logPrefix()} Not allowed to set ${
1011 chargingProfile.chargingProfilePurpose
1012 } charging profile(s) at remote start transaction`,
1019 private async handleRequestRemoteStopTransaction(
1020 chargingStation
: ChargingStation
,
1021 commandPayload
: RemoteStopTransactionRequest
,
1022 ): Promise
<GenericResponse
> {
1023 const { transactionId
} = commandPayload
;
1024 if (chargingStation
.hasEvses
) {
1025 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1027 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1028 if (connectorStatus
.transactionId
=== transactionId
) {
1029 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1035 for (const connectorId
of chargingStation
.connectors
.keys()) {
1038 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1040 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1045 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id
1046 ${transactionId.toString()}`,
1048 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1051 private handleRequestUpdateFirmware(
1052 chargingStation
: ChargingStation
,
1053 commandPayload
: OCPP16UpdateFirmwareRequest
,
1054 ): OCPP16UpdateFirmwareResponse
{
1056 OCPP16ServiceUtils
.checkFeatureProfile(
1058 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1059 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1063 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1064 Cannot simulate firmware update: feature profile not supported`,
1066 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1068 let { retrieveDate
} = commandPayload
;
1070 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1071 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1074 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1075 Cannot simulate firmware update: firmware update is already in progress`,
1077 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1079 retrieveDate
= convertToDate(retrieveDate
)!;
1080 const now
= Date.now();
1081 if (retrieveDate
?.getTime() <= now
) {
1082 this.runInAsyncScope(
1083 this.updateFirmwareSimulation
.bind(this) as (
1084 this: OCPP16IncomingRequestService
,
1089 ).catch(Constants
.EMPTY_FUNCTION
);
1093 this.runInAsyncScope(
1094 this.updateFirmwareSimulation
.bind(this) as (
1095 this: OCPP16IncomingRequestService
,
1100 ).catch(Constants
.EMPTY_FUNCTION
);
1102 retrieveDate
?.getTime() - now
,
1105 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1108 private async updateFirmwareSimulation(
1109 chargingStation
: ChargingStation
,
1113 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1116 if (chargingStation
.hasEvses
) {
1117 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1119 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1120 if (connectorStatus
?.transactionStarted
=== false) {
1121 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1124 OCPP16ChargePointStatus
.Unavailable
,
1131 for (const connectorId
of chargingStation
.connectors
.keys()) {
1134 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1136 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1139 OCPP16ChargePointStatus
.Unavailable
,
1144 await chargingStation
.ocppRequestService
.requestHandler
<
1145 OCPP16FirmwareStatusNotificationRequest
,
1146 OCPP16FirmwareStatusNotificationResponse
1147 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1148 status: OCPP16FirmwareStatus
.Downloading
,
1150 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1152 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1153 OCPP16FirmwareStatus
.DownloadFailed
1155 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1156 await chargingStation
.ocppRequestService
.requestHandler
<
1157 OCPP16FirmwareStatusNotificationRequest
,
1158 OCPP16FirmwareStatusNotificationResponse
1159 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1160 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1162 chargingStation
.stationInfo
.firmwareStatus
=
1163 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1166 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1167 await chargingStation
.ocppRequestService
.requestHandler
<
1168 OCPP16FirmwareStatusNotificationRequest
,
1169 OCPP16FirmwareStatusNotificationResponse
1170 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1171 status: OCPP16FirmwareStatus
.Downloaded
,
1173 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1174 let wasTransactionsStarted
= false;
1175 let transactionsStarted
: boolean;
1177 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1178 if (runningTransactions
> 0) {
1179 const waitTime
= secondsToMilliseconds(15);
1181 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation:
1182 ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1184 )} before continuing firmware update simulation`,
1186 await sleep(waitTime
);
1187 transactionsStarted
= true;
1188 wasTransactionsStarted
= true;
1190 if (chargingStation
.hasEvses
) {
1191 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1193 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1194 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1195 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1198 OCPP16ChargePointStatus
.Unavailable
,
1205 for (const connectorId
of chargingStation
.connectors
.keys()) {
1208 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1209 OCPP16ChargePointStatus
.Unavailable
1211 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1214 OCPP16ChargePointStatus
.Unavailable
,
1219 transactionsStarted
= false;
1221 } while (transactionsStarted
);
1222 !wasTransactionsStarted
&&
1223 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1224 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1227 await chargingStation
.ocppRequestService
.requestHandler
<
1228 OCPP16FirmwareStatusNotificationRequest
,
1229 OCPP16FirmwareStatusNotificationResponse
1230 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1231 status: OCPP16FirmwareStatus
.Installing
,
1233 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1235 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1236 OCPP16FirmwareStatus
.InstallationFailed
1238 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1239 await chargingStation
.ocppRequestService
.requestHandler
<
1240 OCPP16FirmwareStatusNotificationRequest
,
1241 OCPP16FirmwareStatusNotificationResponse
1242 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1243 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1245 chargingStation
.stationInfo
.firmwareStatus
=
1246 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1249 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1250 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1251 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1255 private async handleRequestGetDiagnostics(
1256 chargingStation
: ChargingStation
,
1257 commandPayload
: GetDiagnosticsRequest
,
1258 ): Promise
<GetDiagnosticsResponse
> {
1260 OCPP16ServiceUtils
.checkFeatureProfile(
1262 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1263 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1267 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1268 Cannot get diagnostics: feature profile not supported`,
1270 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1272 const { location
} = commandPayload
;
1273 const uri
= new URL(location
);
1274 if (uri
.protocol
.startsWith('ftp:')) {
1275 let ftpClient
: Client
| undefined;
1277 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1278 .filter((file
) => file
.endsWith('.log'))
1279 .map((file
) => join('./', file
));
1280 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1281 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1282 ftpClient
= new Client();
1283 const accessResponse
= await ftpClient
.access({
1285 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1286 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1287 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1289 let uploadResponse
: FTPResponse
| undefined;
1290 if (accessResponse
.code
=== 220) {
1291 ftpClient
.trackProgress((info
) => {
1293 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1295 } bytes transferred from diagnostics archive ${info.name}`,
1297 chargingStation
.ocppRequestService
1299 OCPP16DiagnosticsStatusNotificationRequest
,
1300 OCPP16DiagnosticsStatusNotificationResponse
1301 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1302 status: OCPP16DiagnosticsStatus
.Uploading
,
1306 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1307 Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`,
1312 uploadResponse
= await ftpClient
.uploadFrom(
1313 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1314 `${uri.pathname}${diagnosticsArchive}`,
1316 if (uploadResponse
.code
=== 226) {
1317 await chargingStation
.ocppRequestService
.requestHandler
<
1318 OCPP16DiagnosticsStatusNotificationRequest
,
1319 OCPP16DiagnosticsStatusNotificationResponse
1320 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1321 status: OCPP16DiagnosticsStatus
.Uploaded
,
1326 return { fileName
: diagnosticsArchive
};
1328 throw new OCPPError(
1329 ErrorType
.GENERIC_ERROR
,
1330 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1331 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1333 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1336 throw new OCPPError(
1337 ErrorType
.GENERIC_ERROR
,
1338 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1339 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1341 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1344 await chargingStation
.ocppRequestService
.requestHandler
<
1345 OCPP16DiagnosticsStatusNotificationRequest
,
1346 OCPP16DiagnosticsStatusNotificationResponse
1347 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1348 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1353 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1355 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1357 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1362 `${chargingStation.logPrefix()} Unsupported protocol ${
1364 } to transfer the diagnostic logs archive`,
1366 await chargingStation
.ocppRequestService
.requestHandler
<
1367 OCPP16DiagnosticsStatusNotificationRequest
,
1368 OCPP16DiagnosticsStatusNotificationResponse
1369 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1370 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1372 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1376 private handleRequestTriggerMessage(
1377 chargingStation
: ChargingStation
,
1378 commandPayload
: OCPP16TriggerMessageRequest
,
1379 ): OCPP16TriggerMessageResponse
{
1380 const { requestedMessage
, connectorId
} = commandPayload
;
1382 !OCPP16ServiceUtils
.checkFeatureProfile(
1384 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1385 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1387 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1389 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1392 !OCPP16ServiceUtils
.isConnectorIdValid(
1394 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1398 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1401 switch (requestedMessage
) {
1402 case OCPP16MessageTrigger
.BootNotification
:
1404 chargingStation
.ocppRequestService
1405 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1407 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1408 chargingStation
.bootNotificationRequest
,
1409 { skipBufferingOnError
: true, triggerMessage
: true },
1411 .then((response
) => {
1412 chargingStation
.bootNotificationResponse
= response
;
1414 .catch(Constants
.EMPTY_FUNCTION
);
1415 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1416 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1417 case OCPP16MessageTrigger
.Heartbeat
:
1419 chargingStation
.ocppRequestService
1420 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1422 OCPP16RequestCommand
.HEARTBEAT
,
1425 triggerMessage
: true,
1428 .catch(Constants
.EMPTY_FUNCTION
);
1429 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1430 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1431 case OCPP16MessageTrigger
.StatusNotification
:
1433 if (!isNullOrUndefined(connectorId
)) {
1434 chargingStation
.ocppRequestService
1435 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1437 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1440 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1441 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1444 triggerMessage
: true,
1447 .catch(Constants
.EMPTY_FUNCTION
);
1449 // eslint-disable-next-line no-lonely-if
1450 if (chargingStation
.hasEvses
) {
1451 for (const evseStatus
of chargingStation
.evses
.values()) {
1452 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1453 chargingStation
.ocppRequestService
1455 OCPP16StatusNotificationRequest
,
1456 OCPP16StatusNotificationResponse
1459 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1462 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1463 status: connectorStatus
.status,
1466 triggerMessage
: true,
1469 .catch(Constants
.EMPTY_FUNCTION
);
1473 for (const id
of chargingStation
.connectors
.keys()) {
1474 chargingStation
.ocppRequestService
1476 OCPP16StatusNotificationRequest
,
1477 OCPP16StatusNotificationResponse
1480 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1483 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1484 status: chargingStation
.getConnectorStatus(id
)?.status,
1487 triggerMessage
: true,
1490 .catch(Constants
.EMPTY_FUNCTION
);
1494 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1495 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1497 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1500 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1502 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1504 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1509 private handleRequestDataTransfer(
1510 chargingStation
: ChargingStation
,
1511 commandPayload
: OCPP16DataTransferRequest
,
1512 ): OCPP16DataTransferResponse
{
1513 const { vendorId
} = commandPayload
;
1515 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1516 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1518 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1520 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1522 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1524 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1529 private async handleRequestReserveNow(
1530 chargingStation
: ChargingStation
,
1531 commandPayload
: OCPP16ReserveNowRequest
,
1532 ): Promise
<OCPP16ReserveNowResponse
> {
1534 !OCPP16ServiceUtils
.checkFeatureProfile(
1536 OCPP16SupportedFeatureProfiles
.Reservation
,
1537 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1540 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1542 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1543 let response
: OCPP16ReserveNowResponse
;
1545 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1546 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1548 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1549 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1551 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1552 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1554 await removeExpiredReservations(chargingStation
);
1555 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1556 case OCPP16ChargePointStatus
.Faulted
:
1557 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1559 case OCPP16ChargePointStatus
.Preparing
:
1560 case OCPP16ChargePointStatus
.Charging
:
1561 case OCPP16ChargePointStatus
.SuspendedEV
:
1562 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1563 case OCPP16ChargePointStatus
.Finishing
:
1564 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1566 case OCPP16ChargePointStatus
.Unavailable
:
1567 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1569 case OCPP16ChargePointStatus
.Reserved
:
1570 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1571 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1574 // eslint-disable-next-line no-fallthrough
1576 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1577 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1580 await chargingStation
.addReservation({
1581 id
: commandPayload
.reservationId
,
1584 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1589 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1590 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1592 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1594 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1599 private async handleRequestCancelReservation(
1600 chargingStation
: ChargingStation
,
1601 commandPayload
: OCPP16CancelReservationRequest
,
1602 ): Promise
<GenericResponse
> {
1604 !OCPP16ServiceUtils
.checkFeatureProfile(
1606 OCPP16SupportedFeatureProfiles
.Reservation
,
1607 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1610 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1613 const { reservationId
} = commandPayload
;
1614 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1615 if (isUndefined(reservation
)) {
1617 `${chargingStation.logPrefix()} Reservation with id ${reservationId}
1618 does not exist on charging station`,
1620 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1622 await chargingStation
.removeReservation(
1624 ReservationTerminationReason
.RESERVATION_CANCELED
,
1626 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1628 return this.handleIncomingRequestError
<GenericResponse
>(
1630 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1632 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},