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';
19 secondsToMilliseconds
,
21 import { create
} from
'tar';
23 import { OCPP16Constants
} from
'./OCPP16Constants';
24 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
27 canProceedChargingProfile
,
30 prepareChargingProfileKind
,
31 removeExpiredReservations
,
32 setConfigurationKeyValue
,
33 } from
'../../../charging-station';
34 import { OCPPError
} from
'../../../exception';
36 type ChangeConfigurationRequest
,
37 type ChangeConfigurationResponse
,
38 type ClearChargingProfileRequest
,
39 type ClearChargingProfileResponse
,
43 type GetConfigurationRequest
,
44 type GetConfigurationResponse
,
45 type GetDiagnosticsRequest
,
46 type GetDiagnosticsResponse
,
47 type IncomingRequestHandler
,
50 OCPP16AuthorizationStatus
,
51 OCPP16AvailabilityType
,
52 type OCPP16BootNotificationRequest
,
53 type OCPP16BootNotificationResponse
,
54 type OCPP16CancelReservationRequest
,
55 type OCPP16ChangeAvailabilityRequest
,
56 type OCPP16ChangeAvailabilityResponse
,
57 OCPP16ChargePointErrorCode
,
58 OCPP16ChargePointStatus
,
59 type OCPP16ChargingProfile
,
60 OCPP16ChargingProfilePurposeType
,
61 OCPP16ChargingRateUnitType
,
62 type OCPP16ChargingSchedule
,
63 type OCPP16ChargingSchedulePeriod
,
64 type OCPP16ClearCacheRequest
,
65 type OCPP16DataTransferRequest
,
66 type OCPP16DataTransferResponse
,
67 OCPP16DataTransferVendorId
,
68 OCPP16DiagnosticsStatus
,
69 type OCPP16DiagnosticsStatusNotificationRequest
,
70 type OCPP16DiagnosticsStatusNotificationResponse
,
72 type OCPP16FirmwareStatusNotificationRequest
,
73 type OCPP16FirmwareStatusNotificationResponse
,
74 type OCPP16GetCompositeScheduleRequest
,
75 type OCPP16GetCompositeScheduleResponse
,
76 type OCPP16HeartbeatRequest
,
77 type OCPP16HeartbeatResponse
,
78 OCPP16IncomingRequestCommand
,
81 type OCPP16ReserveNowRequest
,
82 type OCPP16ReserveNowResponse
,
83 OCPP16StandardParametersKey
,
84 type OCPP16StartTransactionRequest
,
85 type OCPP16StartTransactionResponse
,
86 type OCPP16StatusNotificationRequest
,
87 type OCPP16StatusNotificationResponse
,
88 OCPP16StopTransactionReason
,
89 OCPP16SupportedFeatureProfiles
,
90 type OCPP16TriggerMessageRequest
,
91 type OCPP16TriggerMessageResponse
,
92 type OCPP16UpdateFirmwareRequest
,
93 type OCPP16UpdateFirmwareResponse
,
94 type OCPPConfigurationKey
,
96 type RemoteStartTransactionRequest
,
97 type RemoteStopTransactionRequest
,
98 ReservationTerminationReason
,
100 type SetChargingProfileRequest
,
101 type SetChargingProfileResponse
,
102 type UnlockConnectorRequest
,
103 type UnlockConnectorResponse
,
104 } from
'../../../types';
110 formatDurationMilliSeconds
,
120 } from
'../../../utils';
121 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService';
123 const moduleName
= 'OCPP16IncomingRequestService';
125 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
126 protected jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
127 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
129 public constructor() {
130 // if (new.target?.name === moduleName) {
131 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
133 super(OCPPVersion
.VERSION_16
);
134 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
136 OCPP16IncomingRequestCommand
.RESET
,
137 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
,
140 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
141 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
,
144 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
145 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
,
148 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
149 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
,
152 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
153 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
,
156 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
157 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
,
160 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
161 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
,
164 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
165 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
,
168 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
169 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
,
172 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
173 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
176 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
177 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
180 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
181 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
,
184 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
185 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
,
188 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
189 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
,
192 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
193 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
,
196 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
197 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
,
200 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
201 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
,
204 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
206 OCPP16IncomingRequestCommand
.RESET
,
207 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
208 'assets/json-schemas/ocpp/1.6/Reset.json',
214 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
215 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
216 'assets/json-schemas/ocpp/1.6/ClearCache.json',
222 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
223 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
224 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
230 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
231 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
232 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
238 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
239 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
240 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
246 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
247 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
248 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
254 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
255 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
256 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
262 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
263 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
264 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
270 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
271 OCPP16ServiceUtils
.parseJsonSchemaFile
<ClearChargingProfileRequest
>(
272 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
278 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
279 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
280 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
286 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
287 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
288 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
294 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
295 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
296 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
302 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
303 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
304 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
310 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
311 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
312 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
318 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
319 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
320 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
326 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
327 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
328 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
334 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
335 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
336 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
342 this.validatePayload
= this.validatePayload
.bind(this) as (
343 chargingStation
: ChargingStation
,
344 commandName
: OCPP16IncomingRequestCommand
,
345 commandPayload
: JsonType
,
349 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
350 chargingStation
: ChargingStation
,
352 commandName
: OCPP16IncomingRequestCommand
,
353 commandPayload
: ReqType
,
355 let response
: ResType
;
357 chargingStation
.getOcppStrictCompliance() === true &&
358 chargingStation
.inPendingState() === true &&
359 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
360 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
363 ErrorType
.SECURITY_ERROR
,
364 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
368 )} while the charging station is in pending state on the central server`,
374 chargingStation
.isRegistered() === true ||
375 (chargingStation
.getOcppStrictCompliance() === false &&
376 chargingStation
.inUnknownState() === true)
379 this.incomingRequestHandlers
.has(commandName
) === true &&
380 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
383 this.validatePayload(chargingStation
, commandName
, commandPayload
);
384 // Call the method to build the response
385 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
392 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler:
393 Handle incoming request error:`,
401 ErrorType
.NOT_IMPLEMENTED
,
402 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
413 ErrorType
.SECURITY_ERROR
,
414 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
418 )} while the charging station is not registered on the central server.`,
423 // Send the built response
424 await chargingStation
.ocppRequestService
.sendResponse(
432 private validatePayload(
433 chargingStation
: ChargingStation
,
434 commandName
: OCPP16IncomingRequestCommand
,
435 commandPayload
: JsonType
,
437 if (this.jsonSchemas
.has(commandName
) === true) {
438 return this.validateIncomingRequestPayload(
441 this.jsonSchemas
.get(commandName
)!,
446 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found
447 for command '${commandName}' PDU validation`,
452 // Simulate charging station restart
453 private handleRequestReset(
454 chargingStation
: ChargingStation
,
455 commandPayload
: ResetRequest
,
457 const { type } = commandPayload
;
458 this.runInAsyncScope(
459 chargingStation
.reset
.bind(chargingStation
) as (
460 this: ChargingStation
,
464 `${type}Reset` as OCPP16StopTransactionReason
,
465 ).catch(Constants
.EMPTY_FUNCTION
);
467 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be
468 back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime!)}`,
470 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
473 private async handleRequestUnlockConnector(
474 chargingStation
: ChargingStation
,
475 commandPayload
: UnlockConnectorRequest
,
476 ): Promise
<UnlockConnectorResponse
> {
477 const { connectorId
} = commandPayload
;
478 if (chargingStation
.hasConnector(connectorId
) === false) {
480 `${chargingStation.logPrefix()} Trying to unlock a non existing
481 connector id ${connectorId.toString()}`,
483 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
485 if (connectorId
=== 0) {
487 `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}`,
489 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
491 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
492 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
494 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
496 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
497 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
499 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
501 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
504 OCPP16ChargePointStatus
.Available
,
506 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
509 private handleRequestGetConfiguration(
510 chargingStation
: ChargingStation
,
511 commandPayload
: GetConfigurationRequest
,
512 ): GetConfigurationResponse
{
513 const { key
} = commandPayload
;
514 const configurationKey
: OCPPConfigurationKey
[] = [];
515 const unknownKey
: string[] = [];
516 if (isUndefined(key
) === true) {
517 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
518 if (isUndefined(configuration
.visible
) === true) {
519 configuration
.visible
= true;
521 if (configuration
.visible
=== false) {
524 configurationKey
.push({
525 key
: configuration
.key
,
526 readonly: configuration
.readonly,
527 value
: configuration
.value
,
530 } else if (isNotEmptyArray(key
) === true) {
531 for (const k
of key
!) {
532 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
534 if (isUndefined(keyFound
.visible
) === true) {
535 keyFound
.visible
= true;
537 if (keyFound
.visible
=== false) {
540 configurationKey
.push({
542 readonly: keyFound
.readonly,
543 value
: keyFound
.value
,
556 private handleRequestChangeConfiguration(
557 chargingStation
: ChargingStation
,
558 commandPayload
: ChangeConfigurationRequest
,
559 ): ChangeConfigurationResponse
{
560 const { key
, value
} = commandPayload
;
561 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
562 if (keyToChange
?.readonly === true) {
563 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
564 } else if (keyToChange
?.readonly === false) {
565 let valueChanged
= false;
566 if (keyToChange
.value
!== value
) {
567 setConfigurationKeyValue(chargingStation
, key
, value
, true);
570 let triggerHeartbeatRestart
= false;
572 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
573 OCPP16StandardParametersKey
.HeartBeatInterval
&&
576 setConfigurationKeyValue(
578 OCPP16StandardParametersKey
.HeartbeatInterval
,
581 triggerHeartbeatRestart
= true;
584 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
585 OCPP16StandardParametersKey
.HeartbeatInterval
&&
588 setConfigurationKeyValue(
590 OCPP16StandardParametersKey
.HeartBeatInterval
,
593 triggerHeartbeatRestart
= true;
595 if (triggerHeartbeatRestart
) {
596 chargingStation
.restartHeartbeat();
599 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
600 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
603 chargingStation
.restartWebSocketPing();
605 if (keyToChange
.reboot
) {
606 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
608 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
610 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
613 private handleRequestSetChargingProfile(
614 chargingStation
: ChargingStation
,
615 commandPayload
: SetChargingProfileRequest
,
616 ): SetChargingProfileResponse
{
618 OCPP16ServiceUtils
.checkFeatureProfile(
620 OCPP16SupportedFeatureProfiles
.SmartCharging
,
621 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
624 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
626 const { connectorId
, csChargingProfiles
} = commandPayload
;
627 if (chargingStation
.hasConnector(connectorId
) === false) {
629 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a
630 non existing connector id ${connectorId}`,
632 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
635 csChargingProfiles
.chargingProfilePurpose
===
636 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
639 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
642 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
643 (connectorId
=== 0 ||
644 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false)
647 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
648 on connector ${connectorId} without a started transaction`,
650 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
652 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
654 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
657 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
660 private handleRequestGetCompositeSchedule(
661 chargingStation
: ChargingStation
,
662 commandPayload
: OCPP16GetCompositeScheduleRequest
,
663 ): OCPP16GetCompositeScheduleResponse
{
665 OCPP16ServiceUtils
.checkFeatureProfile(
667 OCPP16SupportedFeatureProfiles
.SmartCharging
,
668 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
671 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
673 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
674 if (chargingStation
.hasConnector(connectorId
) === false) {
676 `${chargingStation.logPrefix()} Trying to get composite schedule to a
677 non existing connector id ${connectorId}`,
679 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
681 if (connectorId
=== 0) {
683 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
685 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
687 if (chargingRateUnit
) {
689 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`,
692 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
695 connectorStatus
?.chargingProfiles
&&
696 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
699 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
701 const currentDate
= new Date();
702 const interval
: Interval
= {
704 end
: addSeconds(currentDate
, duration
),
706 const storedChargingProfiles
: OCPP16ChargingProfile
[] = cloneObject
<OCPP16ChargingProfile
[]>(
707 (connectorStatus
?.chargingProfiles
?? []).concat(
708 chargingStation
.getConnectorStatus(0)?.chargingProfiles
?? [],
710 ).sort((a
, b
) => b
.stackLevel
- a
.stackLevel
);
711 const chargingProfiles
: OCPP16ChargingProfile
[] = [];
712 for (const storedChargingProfile
of storedChargingProfiles
) {
714 connectorStatus
?.transactionStarted
&&
715 isNullOrUndefined(storedChargingProfile
.chargingSchedule
?.startSchedule
)
718 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
719 storedChargingProfile.chargingProfileId
720 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
722 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
723 storedChargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
725 if (!isDate(storedChargingProfile
.chargingSchedule
?.startSchedule
)) {
727 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
728 storedChargingProfile.chargingProfileId
729 } startSchedule property is not a Date object. Trying to convert it to a Date object`,
731 storedChargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
732 storedChargingProfile
.chargingSchedule
?.startSchedule
,
736 !prepareChargingProfileKind(
738 storedChargingProfile
,
739 interval
.start
as Date,
740 chargingStation
.logPrefix(),
746 !canProceedChargingProfile(
747 storedChargingProfile
,
748 interval
.start
as Date,
749 chargingStation
.logPrefix(),
754 // Add active charging profiles into chargingProfiles array
756 isValidTime(storedChargingProfile
.chargingSchedule
?.startSchedule
) &&
757 isWithinInterval(storedChargingProfile
.chargingSchedule
.startSchedule
!, interval
) &&
758 (isEmptyArray(chargingProfiles
) ||
759 (isNotEmptyArray(chargingProfiles
) &&
761 storedChargingProfile
.chargingSchedule
.startSchedule
!,
763 chargingProfiles
.map(
764 (chargingProfile
) => chargingProfile
.chargingSchedule
.startSchedule
?? maxTime
,
769 storedChargingProfile
.chargingSchedule
.startSchedule
!,
771 chargingProfiles
.map(
774 chargingProfile
.chargingSchedule
.startSchedule
!,
775 chargingProfile
.chargingSchedule
.duration
!,
781 chargingProfiles
.push(storedChargingProfile
);
784 const compositeScheduleStart
: Date = min(
785 chargingProfiles
.map(
786 (chargingProfile
) => chargingProfile
.chargingSchedule
.startSchedule
?? maxTime
,
789 const compositeScheduleDuration
: number = Math.max(
790 ...chargingProfiles
.map(
791 (chargingProfile
) => chargingProfile
.chargingSchedule
.duration
?? -Infinity,
794 // FIXME: remove overlapping charging schedule periods
795 const compositeSchedulePeriods
: OCPP16ChargingSchedulePeriod
[] = chargingProfiles
796 .map((chargingProfile
) => chargingProfile
.chargingSchedule
.chargingSchedulePeriod
)
798 (accumulator
, value
) =>
799 accumulator
.concat(value
).sort((a
, b
) => a
.startPeriod
- b
.startPeriod
),
802 const compositeSchedule
: OCPP16ChargingSchedule
= {
803 startSchedule
: compositeScheduleStart
,
804 duration
: compositeScheduleDuration
,
805 chargingRateUnit
: chargingProfiles
.every(
807 chargingProfile
.chargingSchedule
.chargingRateUnit
=== OCPP16ChargingRateUnitType
.AMPERE
,
809 ? OCPP16ChargingRateUnitType
.AMPERE
810 : chargingProfiles
.every(
812 chargingProfile
.chargingSchedule
.chargingRateUnit
=== OCPP16ChargingRateUnitType
.WATT
,
814 ? OCPP16ChargingRateUnitType
.WATT
815 : OCPP16ChargingRateUnitType
.AMPERE
,
816 chargingSchedulePeriod
: compositeSchedulePeriods
,
817 minChargeRate
: Math.min(
818 ...chargingProfiles
.map(
819 (chargingProfile
) => chargingProfile
.chargingSchedule
.minChargeRate
?? Infinity,
824 status: GenericStatus
.Accepted
,
825 scheduleStart
: compositeSchedule
.startSchedule
!,
827 chargingSchedule
: compositeSchedule
,
831 private handleRequestClearChargingProfile(
832 chargingStation
: ChargingStation
,
833 commandPayload
: ClearChargingProfileRequest
,
834 ): ClearChargingProfileResponse
{
836 OCPP16ServiceUtils
.checkFeatureProfile(
838 OCPP16SupportedFeatureProfiles
.SmartCharging
,
839 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
842 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
844 const { connectorId
} = commandPayload
;
845 if (chargingStation
.hasConnector(connectorId
!) === false) {
847 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to
848 a non existing connector id ${connectorId}`,
850 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
853 !isNullOrUndefined(connectorId
) &&
854 isNotEmptyArray(chargingStation
.getConnectorStatus(connectorId
!)?.chargingProfiles
)
856 chargingStation
.getConnectorStatus(connectorId
!)!.chargingProfiles
= [];
858 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
860 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
862 if (isNullOrUndefined(connectorId
)) {
863 let clearedCP
= false;
864 if (chargingStation
.hasEvses
) {
865 for (const evseStatus
of chargingStation
.evses
.values()) {
866 for (const connectorStatus
of evseStatus
.connectors
.values()) {
867 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
870 connectorStatus
.chargingProfiles
,
875 for (const id
of chargingStation
.connectors
.keys()) {
876 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
879 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
884 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
887 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
890 private async handleRequestChangeAvailability(
891 chargingStation
: ChargingStation
,
892 commandPayload
: OCPP16ChangeAvailabilityRequest
,
893 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
894 const { connectorId
, type } = commandPayload
;
895 if (chargingStation
.hasConnector(connectorId
) === false) {
897 `${chargingStation.logPrefix()} Trying to change the availability of a
898 non existing connector id ${connectorId.toString()}`,
900 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
902 const chargePointStatus
: OCPP16ChargePointStatus
=
903 type === OCPP16AvailabilityType
.Operative
904 ? OCPP16ChargePointStatus
.Available
905 : OCPP16ChargePointStatus
.Unavailable
;
906 if (connectorId
=== 0) {
907 let response
: OCPP16ChangeAvailabilityResponse
;
908 if (chargingStation
.hasEvses
) {
909 for (const evseStatus
of chargingStation
.evses
.values()) {
910 response
= await OCPP16ServiceUtils
.changeAvailability(
912 [...evseStatus
.connectors
.keys()],
918 response
= await OCPP16ServiceUtils
.changeAvailability(
920 [...chargingStation
.connectors
.keys()],
928 (chargingStation
.isChargingStationAvailable() === true ||
929 (chargingStation
.isChargingStationAvailable() === false &&
930 type === OCPP16AvailabilityType
.Inoperative
))
932 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
933 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
934 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
936 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
937 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
942 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
944 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
947 private async handleRequestRemoteStartTransaction(
948 chargingStation
: ChargingStation
,
949 commandPayload
: RemoteStartTransactionRequest
,
950 ): Promise
<GenericResponse
> {
951 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
952 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
953 return this.notifyRemoteStartTransactionRejected(
955 transactionConnectorId
,
960 !chargingStation
.isChargingStationAvailable() ||
961 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
963 return this.notifyRemoteStartTransactionRejected(
965 transactionConnectorId
,
969 const remoteStartTransactionLogMsg
= `
970 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
971 chargingStation.stationInfo.chargingStationId
972 }#${transactionConnectorId.toString()} for idTag '${idTag}'`;
973 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
975 transactionConnectorId
,
976 OCPP16ChargePointStatus
.Preparing
,
978 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
979 // Authorization check required
981 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
982 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
984 // Authorization successful, start transaction
986 this.setRemoteStartTransactionChargingProfile(
988 transactionConnectorId
,
992 connectorStatus
.transactionRemoteStarted
= true;
995 await chargingStation
.ocppRequestService
.requestHandler
<
996 OCPP16StartTransactionRequest
,
997 OCPP16StartTransactionResponse
998 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
999 connectorId
: transactionConnectorId
,
1002 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1004 logger
.debug(remoteStartTransactionLogMsg
);
1005 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1007 return this.notifyRemoteStartTransactionRejected(
1009 transactionConnectorId
,
1013 return this.notifyRemoteStartTransactionRejected(
1015 transactionConnectorId
,
1019 // No authorization check required, start transaction
1021 this.setRemoteStartTransactionChargingProfile(
1023 transactionConnectorId
,
1027 connectorStatus
.transactionRemoteStarted
= true;
1030 await chargingStation
.ocppRequestService
.requestHandler
<
1031 OCPP16StartTransactionRequest
,
1032 OCPP16StartTransactionResponse
1033 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
1034 connectorId
: transactionConnectorId
,
1037 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1039 logger
.debug(remoteStartTransactionLogMsg
);
1040 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1042 return this.notifyRemoteStartTransactionRejected(
1044 transactionConnectorId
,
1048 return this.notifyRemoteStartTransactionRejected(
1050 transactionConnectorId
,
1055 private async notifyRemoteStartTransactionRejected(
1056 chargingStation
: ChargingStation
,
1057 connectorId
: number,
1059 ): Promise
<GenericResponse
> {
1061 chargingStation
.getConnectorStatus(connectorId
)?.status !== OCPP16ChargePointStatus
.Available
1063 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1066 OCPP16ChargePointStatus
.Available
,
1070 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id
1071 ${connectorId.toString()}, idTag '${idTag}', availability '${chargingStation.getConnectorStatus(
1073 )?.availability}', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`,
1075 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1078 private setRemoteStartTransactionChargingProfile(
1079 chargingStation
: ChargingStation
,
1080 connectorId
: number,
1081 chargingProfile
: OCPP16ChargingProfile
,
1085 chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1087 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1089 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction
1090 on connector id ${connectorId}: %j`,
1096 chargingProfile
.chargingProfilePurpose
!== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1099 `${chargingStation.logPrefix()} Not allowed to set ${
1100 chargingProfile.chargingProfilePurpose
1101 } charging profile(s) at remote start transaction`,
1108 private async handleRequestRemoteStopTransaction(
1109 chargingStation
: ChargingStation
,
1110 commandPayload
: RemoteStopTransactionRequest
,
1111 ): Promise
<GenericResponse
> {
1112 const { transactionId
} = commandPayload
;
1113 if (chargingStation
.hasEvses
) {
1114 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1116 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1117 if (connectorStatus
.transactionId
=== transactionId
) {
1118 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1124 for (const connectorId
of chargingStation
.connectors
.keys()) {
1127 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1129 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1134 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id
1135 ${transactionId.toString()}`,
1137 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1140 private handleRequestUpdateFirmware(
1141 chargingStation
: ChargingStation
,
1142 commandPayload
: OCPP16UpdateFirmwareRequest
,
1143 ): OCPP16UpdateFirmwareResponse
{
1145 OCPP16ServiceUtils
.checkFeatureProfile(
1147 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1148 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1152 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1153 Cannot simulate firmware update: feature profile not supported`,
1155 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1157 let { retrieveDate
} = commandPayload
;
1159 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1160 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1163 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1164 Cannot simulate firmware update: firmware update is already in progress`,
1166 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1168 retrieveDate
= convertToDate(retrieveDate
)!;
1169 const now
= Date.now();
1170 if (retrieveDate
?.getTime() <= now
) {
1171 this.runInAsyncScope(
1172 this.updateFirmwareSimulation
.bind(this) as (
1173 this: OCPP16IncomingRequestService
,
1178 ).catch(Constants
.EMPTY_FUNCTION
);
1182 this.runInAsyncScope(
1183 this.updateFirmwareSimulation
.bind(this) as (
1184 this: OCPP16IncomingRequestService
,
1189 ).catch(Constants
.EMPTY_FUNCTION
);
1191 retrieveDate
?.getTime() - now
,
1194 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1197 private async updateFirmwareSimulation(
1198 chargingStation
: ChargingStation
,
1202 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1205 if (chargingStation
.hasEvses
) {
1206 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1208 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1209 if (connectorStatus
?.transactionStarted
=== false) {
1210 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1213 OCPP16ChargePointStatus
.Unavailable
,
1220 for (const connectorId
of chargingStation
.connectors
.keys()) {
1223 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1225 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1228 OCPP16ChargePointStatus
.Unavailable
,
1233 await chargingStation
.ocppRequestService
.requestHandler
<
1234 OCPP16FirmwareStatusNotificationRequest
,
1235 OCPP16FirmwareStatusNotificationResponse
1236 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1237 status: OCPP16FirmwareStatus
.Downloading
,
1239 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1241 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1242 OCPP16FirmwareStatus
.DownloadFailed
1244 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1245 await chargingStation
.ocppRequestService
.requestHandler
<
1246 OCPP16FirmwareStatusNotificationRequest
,
1247 OCPP16FirmwareStatusNotificationResponse
1248 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1249 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1251 chargingStation
.stationInfo
.firmwareStatus
=
1252 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1255 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1256 await chargingStation
.ocppRequestService
.requestHandler
<
1257 OCPP16FirmwareStatusNotificationRequest
,
1258 OCPP16FirmwareStatusNotificationResponse
1259 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1260 status: OCPP16FirmwareStatus
.Downloaded
,
1262 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1263 let wasTransactionsStarted
= false;
1264 let transactionsStarted
: boolean;
1266 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1267 if (runningTransactions
> 0) {
1268 const waitTime
= secondsToMilliseconds(15);
1270 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation:
1271 ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1273 )} before continuing firmware update simulation`,
1275 await sleep(waitTime
);
1276 transactionsStarted
= true;
1277 wasTransactionsStarted
= true;
1279 if (chargingStation
.hasEvses
) {
1280 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1282 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1283 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1284 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1287 OCPP16ChargePointStatus
.Unavailable
,
1294 for (const connectorId
of chargingStation
.connectors
.keys()) {
1297 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1298 OCPP16ChargePointStatus
.Unavailable
1300 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1303 OCPP16ChargePointStatus
.Unavailable
,
1308 transactionsStarted
= false;
1310 } while (transactionsStarted
);
1311 !wasTransactionsStarted
&&
1312 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1313 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1316 await chargingStation
.ocppRequestService
.requestHandler
<
1317 OCPP16FirmwareStatusNotificationRequest
,
1318 OCPP16FirmwareStatusNotificationResponse
1319 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1320 status: OCPP16FirmwareStatus
.Installing
,
1322 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1324 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1325 OCPP16FirmwareStatus
.InstallationFailed
1327 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1328 await chargingStation
.ocppRequestService
.requestHandler
<
1329 OCPP16FirmwareStatusNotificationRequest
,
1330 OCPP16FirmwareStatusNotificationResponse
1331 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1332 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1334 chargingStation
.stationInfo
.firmwareStatus
=
1335 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1338 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1339 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1340 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1344 private async handleRequestGetDiagnostics(
1345 chargingStation
: ChargingStation
,
1346 commandPayload
: GetDiagnosticsRequest
,
1347 ): Promise
<GetDiagnosticsResponse
> {
1349 OCPP16ServiceUtils
.checkFeatureProfile(
1351 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1352 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1356 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1357 Cannot get diagnostics: feature profile not supported`,
1359 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1361 const { location
} = commandPayload
;
1362 const uri
= new URL(location
);
1363 if (uri
.protocol
.startsWith('ftp:')) {
1364 let ftpClient
: Client
| undefined;
1366 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1367 .filter((file
) => file
.endsWith('.log'))
1368 .map((file
) => join('./', file
));
1369 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1370 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1371 ftpClient
= new Client();
1372 const accessResponse
= await ftpClient
.access({
1374 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1375 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1376 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1378 let uploadResponse
: FTPResponse
| undefined;
1379 if (accessResponse
.code
=== 220) {
1380 ftpClient
.trackProgress((info
) => {
1382 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1384 } bytes transferred from diagnostics archive ${info.name}`,
1386 chargingStation
.ocppRequestService
1388 OCPP16DiagnosticsStatusNotificationRequest
,
1389 OCPP16DiagnosticsStatusNotificationResponse
1390 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1391 status: OCPP16DiagnosticsStatus
.Uploading
,
1395 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1396 Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`,
1401 uploadResponse
= await ftpClient
.uploadFrom(
1402 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1403 `${uri.pathname}${diagnosticsArchive}`,
1405 if (uploadResponse
.code
=== 226) {
1406 await chargingStation
.ocppRequestService
.requestHandler
<
1407 OCPP16DiagnosticsStatusNotificationRequest
,
1408 OCPP16DiagnosticsStatusNotificationResponse
1409 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1410 status: OCPP16DiagnosticsStatus
.Uploaded
,
1415 return { fileName
: diagnosticsArchive
};
1417 throw new OCPPError(
1418 ErrorType
.GENERIC_ERROR
,
1419 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1420 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1422 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1425 throw new OCPPError(
1426 ErrorType
.GENERIC_ERROR
,
1427 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1428 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1430 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1433 await chargingStation
.ocppRequestService
.requestHandler
<
1434 OCPP16DiagnosticsStatusNotificationRequest
,
1435 OCPP16DiagnosticsStatusNotificationResponse
1436 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1437 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1442 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1444 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1446 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1451 `${chargingStation.logPrefix()} Unsupported protocol ${
1453 } to transfer the diagnostic logs archive`,
1455 await chargingStation
.ocppRequestService
.requestHandler
<
1456 OCPP16DiagnosticsStatusNotificationRequest
,
1457 OCPP16DiagnosticsStatusNotificationResponse
1458 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1459 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1461 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1465 private handleRequestTriggerMessage(
1466 chargingStation
: ChargingStation
,
1467 commandPayload
: OCPP16TriggerMessageRequest
,
1468 ): OCPP16TriggerMessageResponse
{
1469 const { requestedMessage
, connectorId
} = commandPayload
;
1471 !OCPP16ServiceUtils
.checkFeatureProfile(
1473 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1474 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1476 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1478 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1481 !OCPP16ServiceUtils
.isConnectorIdValid(
1483 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1487 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1490 switch (requestedMessage
) {
1491 case OCPP16MessageTrigger
.BootNotification
:
1493 chargingStation
.ocppRequestService
1494 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1496 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1497 chargingStation
.bootNotificationRequest
,
1498 { skipBufferingOnError
: true, triggerMessage
: true },
1500 .then((response
) => {
1501 chargingStation
.bootNotificationResponse
= response
;
1503 .catch(Constants
.EMPTY_FUNCTION
);
1504 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1505 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1506 case OCPP16MessageTrigger
.Heartbeat
:
1508 chargingStation
.ocppRequestService
1509 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1511 OCPP16RequestCommand
.HEARTBEAT
,
1514 triggerMessage
: true,
1517 .catch(Constants
.EMPTY_FUNCTION
);
1518 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1519 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1520 case OCPP16MessageTrigger
.StatusNotification
:
1522 if (!isNullOrUndefined(connectorId
)) {
1523 chargingStation
.ocppRequestService
1524 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1526 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1529 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1530 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1533 triggerMessage
: true,
1536 .catch(Constants
.EMPTY_FUNCTION
);
1538 // eslint-disable-next-line no-lonely-if
1539 if (chargingStation
.hasEvses
) {
1540 for (const evseStatus
of chargingStation
.evses
.values()) {
1541 for (const [id
, connectorStatus
] of evseStatus
.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
);
1562 for (const id
of chargingStation
.connectors
.keys()) {
1563 chargingStation
.ocppRequestService
1565 OCPP16StatusNotificationRequest
,
1566 OCPP16StatusNotificationResponse
1569 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1572 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1573 status: chargingStation
.getConnectorStatus(id
)?.status,
1576 triggerMessage
: true,
1579 .catch(Constants
.EMPTY_FUNCTION
);
1583 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1584 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1586 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1589 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1591 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1593 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1598 private handleRequestDataTransfer(
1599 chargingStation
: ChargingStation
,
1600 commandPayload
: OCPP16DataTransferRequest
,
1601 ): OCPP16DataTransferResponse
{
1602 const { vendorId
} = commandPayload
;
1604 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1605 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1607 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1609 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1611 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1613 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1618 private async handleRequestReserveNow(
1619 chargingStation
: ChargingStation
,
1620 commandPayload
: OCPP16ReserveNowRequest
,
1621 ): Promise
<OCPP16ReserveNowResponse
> {
1623 !OCPP16ServiceUtils
.checkFeatureProfile(
1625 OCPP16SupportedFeatureProfiles
.Reservation
,
1626 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1629 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1631 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1632 let response
: OCPP16ReserveNowResponse
;
1634 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1635 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1637 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1638 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1640 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1641 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1643 await removeExpiredReservations(chargingStation
);
1644 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1645 case OCPP16ChargePointStatus
.Faulted
:
1646 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1648 case OCPP16ChargePointStatus
.Preparing
:
1649 case OCPP16ChargePointStatus
.Charging
:
1650 case OCPP16ChargePointStatus
.SuspendedEV
:
1651 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1652 case OCPP16ChargePointStatus
.Finishing
:
1653 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1655 case OCPP16ChargePointStatus
.Unavailable
:
1656 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1658 case OCPP16ChargePointStatus
.Reserved
:
1659 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1660 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1663 // eslint-disable-next-line no-fallthrough
1665 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1666 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1669 await chargingStation
.addReservation({
1670 id
: commandPayload
.reservationId
,
1673 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1678 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1679 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1681 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1683 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1688 private async handleRequestCancelReservation(
1689 chargingStation
: ChargingStation
,
1690 commandPayload
: OCPP16CancelReservationRequest
,
1691 ): Promise
<GenericResponse
> {
1693 !OCPP16ServiceUtils
.checkFeatureProfile(
1695 OCPP16SupportedFeatureProfiles
.Reservation
,
1696 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1699 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1702 const { reservationId
} = commandPayload
;
1703 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1704 if (isUndefined(reservation
)) {
1706 `${chargingStation.logPrefix()} Reservation with id ${reservationId}
1707 does not exist on charging station`,
1709 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1711 await chargingStation
.removeReservation(
1713 ReservationTerminationReason
.RESERVATION_CANCELED
,
1715 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1717 return this.handleIncomingRequestError
<GenericResponse
>(
1719 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1721 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},