1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { createHash
} from
'node:crypto';
13 import { dirname
, join
} from
'node:path';
14 import { URL
} from
'node:url';
15 import { parentPort
} from
'node:worker_threads';
17 import merge from
'just-merge';
18 import { type RawData
, WebSocket
} from
'ws';
20 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
21 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
22 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
25 checkConnectorsConfiguration
,
26 checkStationInfoConnectorStatus
,
28 countReservableConnectors
,
29 createBootNotificationRequest
,
31 getAmperageLimitationUnitDivider
,
32 getBootConnectorStatus
,
33 getChargingStationConnectorChargingProfilesPowerLimit
,
39 getPhaseRotationValue
,
40 initializeConnectorsMapStatus
,
41 propagateSerialNumber
,
42 stationTemplateToStationInfo
,
43 warnTemplateKeysDeprecation
,
44 } from
'./ChargingStationUtils';
45 import { IdTagsCache
} from
'./IdTagsCache';
47 OCPP16IncomingRequestService
,
49 OCPP16ResponseService
,
51 OCPP20IncomingRequestService
,
53 OCPP20ResponseService
,
54 type OCPPIncomingRequestService
,
55 type OCPPRequestService
,
58 import { SharedLRUCache
} from
'./SharedLRUCache';
59 import { BaseError
, OCPPError
} from
'../exception';
60 import { PerformanceStatistics
} from
'../performance';
62 type AutomaticTransactionGeneratorConfiguration
,
64 type BootNotificationRequest
,
65 type BootNotificationResponse
,
67 type ChargingStationConfiguration
,
68 type ChargingStationInfo
,
69 type ChargingStationOcppConfiguration
,
70 type ChargingStationTemplate
,
78 type EvseStatusConfiguration
,
81 type FirmwareStatusNotificationRequest
,
82 type FirmwareStatusNotificationResponse
,
84 type HeartbeatRequest
,
85 type HeartbeatResponse
,
87 type IncomingRequestCommand
,
92 type MeterValuesRequest
,
93 type MeterValuesResponse
,
97 RegistrationStatusEnumType
,
100 ReservationFilterKey
,
101 ReservationTerminationReason
,
103 StandardParametersKey
,
105 type StatusNotificationRequest
,
106 type StatusNotificationResponse
,
107 StopTransactionReason
,
108 type StopTransactionRequest
,
109 type StopTransactionResponse
,
110 SupervisionUrlDistribution
,
111 SupportedFeatureProfiles
,
114 WebSocketCloseEventStatusCode
,
124 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
125 buildConnectorsStatus
,
134 formatDurationMilliSeconds
,
135 formatDurationSeconds
,
137 getWebSocketCloseEventStatusString
,
151 export class ChargingStation
{
152 public readonly index
: number;
153 public readonly templateFile
: string;
154 public stationInfo
!: ChargingStationInfo
;
155 public started
: boolean;
156 public starting
: boolean;
157 public idTagsCache
: IdTagsCache
;
158 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
159 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
160 public wsConnection
!: WebSocket
| null;
161 public readonly connectors
: Map
<number, ConnectorStatus
>;
162 public readonly evses
: Map
<number, EvseStatus
>;
163 public readonly requests
: Map
<string, CachedRequest
>;
164 public performanceStatistics
!: PerformanceStatistics
| undefined;
165 public heartbeatSetInterval
?: NodeJS
.Timeout
;
166 public ocppRequestService
!: OCPPRequestService
;
167 public bootNotificationRequest
!: BootNotificationRequest
;
168 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
169 public powerDivider
!: number;
170 private stopping
: boolean;
171 private configurationFile
!: string;
172 private configurationFileHash
!: string;
173 private connectorsConfigurationHash
!: string;
174 private evsesConfigurationHash
!: string;
175 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
176 private readonly messageBuffer
: Set
<string>;
177 private configuredSupervisionUrl
!: URL
;
178 private wsConnectionRestarted
: boolean;
179 private autoReconnectRetryCount
: number;
180 private templateFileWatcher
!: FSWatcher
| undefined;
181 private templateFileHash
!: string;
182 private readonly sharedLRUCache
: SharedLRUCache
;
183 private webSocketPingSetInterval
?: NodeJS
.Timeout
;
184 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
185 private reservationExpirationSetInterval
?: NodeJS
.Timeout
;
187 constructor(index
: number, templateFile
: string) {
188 this.started
= false;
189 this.starting
= false;
190 this.stopping
= false;
191 this.wsConnectionRestarted
= false;
192 this.autoReconnectRetryCount
= 0;
194 this.templateFile
= templateFile
;
195 this.connectors
= new Map
<number, ConnectorStatus
>();
196 this.evses
= new Map
<number, EvseStatus
>();
197 this.requests
= new Map
<string, CachedRequest
>();
198 this.messageBuffer
= new Set
<string>();
199 this.sharedLRUCache
= SharedLRUCache
.getInstance();
200 this.idTagsCache
= IdTagsCache
.getInstance();
201 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
206 public get
hasEvses(): boolean {
207 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
210 private get
wsConnectionUrl(): URL
{
213 this.getSupervisionUrlOcppConfiguration() &&
214 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
216 ChargingStationConfigurationUtils.getConfigurationKey(
218 this.getSupervisionUrlOcppKey(),
221 ? ChargingStationConfigurationUtils.getConfigurationKey(
223 this.getSupervisionUrlOcppKey(),
225 : this.configuredSupervisionUrl.href
226 }/${this.stationInfo.chargingStationId}`,
230 public logPrefix
= (): string => {
233 (isNotEmptyString(this?.stationInfo?.chargingStationId)
234 ? this?.stationInfo?.chargingStationId
235 : getChargingStationId(this.index, this.getTemplateFromFile()!)) ??
236 'Error at building log prefix'
241 public hasIdTags(): boolean {
242 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)!));
245 public getEnableStatistics(): boolean {
246 return this.stationInfo
.enableStatistics
?? false;
249 public getMustAuthorizeAtRemoteStart(): boolean {
250 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
253 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number {
254 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
255 switch (this.getCurrentOutType(stationInfo
)) {
257 return !isUndefined(localStationInfo
.numberOfPhases
) ? localStationInfo
.numberOfPhases
! : 3;
263 public isWebSocketConnectionOpened(): boolean {
264 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
267 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
268 return this?.bootNotificationResponse
?.status;
271 public inUnknownState(): boolean {
272 return isNullOrUndefined(this?.bootNotificationResponse
?.status);
275 public inPendingState(): boolean {
276 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
279 public inAcceptedState(): boolean {
280 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
283 public inRejectedState(): boolean {
284 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
287 public isRegistered(): boolean {
289 this.inUnknownState() === false &&
290 (this.inAcceptedState() === true || this.inPendingState() === true)
294 public isChargingStationAvailable(): boolean {
295 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
298 public hasConnector(connectorId
: number): boolean {
300 for (const evseStatus
of this.evses
.values()) {
301 if (evseStatus
.connectors
.has(connectorId
)) {
307 return this.connectors
.has(connectorId
);
310 public isConnectorAvailable(connectorId
: number): boolean {
313 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
317 public getNumberOfConnectors(): number {
319 let numberOfConnectors
= 0;
320 for (const [evseId
, evseStatus
] of this.evses
) {
322 numberOfConnectors
+= evseStatus
.connectors
.size
;
325 return numberOfConnectors
;
327 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
330 public getNumberOfEvses(): number {
331 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
334 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
336 for (const evseStatus
of this.evses
.values()) {
337 if (evseStatus
.connectors
.has(connectorId
)) {
338 return evseStatus
.connectors
.get(connectorId
);
343 return this.connectors
.get(connectorId
);
346 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
347 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
350 public getOcppStrictCompliance(): boolean {
351 return this.stationInfo
?.ocppStrictCompliance
?? true;
354 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number {
355 const defaultVoltageOut
= getDefaultVoltageOut(
356 this.getCurrentOutType(stationInfo
),
360 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
363 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
364 const localStationInfo
= stationInfo
?? this.stationInfo
;
365 // eslint-disable-next-line @typescript-eslint/dot-notation
366 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
369 public getConnectorMaximumAvailablePower(connectorId
: number): number {
370 let connectorAmperageLimitationPowerLimit
: number | undefined;
372 !isNullOrUndefined(this.getAmperageLimitation()) &&
373 this.getAmperageLimitation()! < this.stationInfo
.maximumAmperage
!
375 connectorAmperageLimitationPowerLimit
=
376 (this.getCurrentOutType() === CurrentType
.AC
377 ? ACElectricUtils
.powerTotal(
378 this.getNumberOfPhases(),
379 this.getVoltageOut(),
380 this.getAmperageLimitation()! *
381 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
383 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation()!)) /
386 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
387 const connectorChargingProfilesPowerLimit
=
388 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
390 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
391 isNaN(connectorAmperageLimitationPowerLimit
!)
393 : connectorAmperageLimitationPowerLimit
!,
394 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!,
398 public getTransactionIdTag(transactionId
: number): string | undefined {
400 for (const evseStatus
of this.evses
.values()) {
401 for (const connectorStatus
of evseStatus
.connectors
.values()) {
402 if (connectorStatus
.transactionId
=== transactionId
) {
403 return connectorStatus
.transactionIdTag
;
408 for (const connectorId
of this.connectors
.keys()) {
409 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
410 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
416 public getNumberOfRunningTransactions(): number {
419 for (const [evseId
, evseStatus
] of this.evses
) {
423 for (const connectorStatus
of evseStatus
.connectors
.values()) {
424 if (connectorStatus
.transactionStarted
=== true) {
430 for (const connectorId
of this.connectors
.keys()) {
431 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
439 public getOutOfOrderEndMeterValues(): boolean {
440 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
443 public getBeginEndMeterValues(): boolean {
444 return this.stationInfo
?.beginEndMeterValues
?? false;
447 public getMeteringPerTransaction(): boolean {
448 return this.stationInfo
?.meteringPerTransaction
?? true;
451 public getTransactionDataMeterValues(): boolean {
452 return this.stationInfo
?.transactionDataMeterValues
?? false;
455 public getMainVoltageMeterValues(): boolean {
456 return this.stationInfo
?.mainVoltageMeterValues
?? true;
459 public getPhaseLineToLineVoltageMeterValues(): boolean {
460 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
463 public getCustomValueLimitationMeterValues(): boolean {
464 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
467 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
469 for (const evseStatus
of this.evses
.values()) {
470 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
471 if (connectorStatus
.transactionId
=== transactionId
) {
477 for (const connectorId
of this.connectors
.keys()) {
478 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
485 public getEnergyActiveImportRegisterByTransactionId(
486 transactionId
: number,
489 return this.getEnergyActiveImportRegister(
490 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
495 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
496 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
);
499 public getAuthorizeRemoteTxRequests(): boolean {
500 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
502 StandardParametersKey
.AuthorizeRemoteTxRequests
,
504 return authorizeRemoteTxRequests
? convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
507 public getLocalAuthListEnabled(): boolean {
508 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
510 StandardParametersKey
.LocalAuthListEnabled
,
512 return localAuthListEnabled
? convertToBoolean(localAuthListEnabled
.value
) : false;
515 public getHeartbeatInterval(): number {
516 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
518 StandardParametersKey
.HeartbeatInterval
,
520 if (HeartbeatInterval
) {
521 return convertToInt(HeartbeatInterval
.value
) * 1000;
523 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
525 StandardParametersKey
.HeartBeatInterval
,
527 if (HeartBeatInterval
) {
528 return convertToInt(HeartBeatInterval
.value
) * 1000;
530 this.stationInfo
?.autoRegister
=== false &&
532 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
533 Constants.DEFAULT_HEARTBEAT_INTERVAL
536 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
539 public setSupervisionUrl(url
: string): void {
541 this.getSupervisionUrlOcppConfiguration() &&
542 isNotEmptyString(this.getSupervisionUrlOcppKey())
544 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
546 this.getSupervisionUrlOcppKey(),
550 this.stationInfo
.supervisionUrls
= url
;
551 this.saveStationInfo();
552 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
556 public startHeartbeat(): void {
557 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
558 this.heartbeatSetInterval
= setInterval(() => {
559 this.ocppRequestService
560 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
563 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
567 }, this.getHeartbeatInterval());
569 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
570 this.getHeartbeatInterval(),
573 } else if (this.heartbeatSetInterval
) {
575 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
576 this.getHeartbeatInterval(),
581 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()},
582 not starting the heartbeat`,
587 public restartHeartbeat(): void {
589 this.stopHeartbeat();
591 this.startHeartbeat();
594 public restartWebSocketPing(): void {
595 // Stop WebSocket ping
596 this.stopWebSocketPing();
597 // Start WebSocket ping
598 this.startWebSocketPing();
601 public startMeterValues(connectorId
: number, interval
: number): void {
602 if (connectorId
=== 0) {
604 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`,
608 if (!this.getConnectorStatus(connectorId
)) {
610 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
611 ${connectorId.toString()}`,
615 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
617 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
618 with no transaction started`,
622 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
623 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
626 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
627 with no transaction id`,
632 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
633 // FIXME: Implement OCPP version agnostic helpers
634 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
637 this.getConnectorStatus(connectorId
)!.transactionId
!,
640 this.ocppRequestService
641 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
643 RequestCommand
.METER_VALUES
,
646 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
647 meterValue
: [meterValue
],
652 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
659 `${this.logPrefix()} Charging station ${
660 StandardParametersKey.MeterValueSampleInterval
661 } configuration set to ${interval}, not sending MeterValues`,
666 public stopMeterValues(connectorId
: number) {
667 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
668 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
672 public start(): void {
673 if (this.started
=== false) {
674 if (this.starting
=== false) {
675 this.starting
= true;
676 if (this.getEnableStatistics() === true) {
677 this.performanceStatistics
?.start();
679 if (this.hasFeatureProfile(SupportedFeatureProfiles
.Reservation
)) {
680 this.startReservationExpirationSetInterval();
682 this.openWSConnection();
683 // Monitor charging station template file
684 this.templateFileWatcher
= watchJsonFile(
686 FileType
.ChargingStationTemplate
,
689 (event
, filename
): void => {
690 if (isNotEmptyString(filename
) && event
=== 'change') {
693 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
695 } file have changed, reload`,
697 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
700 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
)!);
702 this.stopAutomaticTransactionGenerator();
703 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
704 this.startAutomaticTransactionGenerator();
706 if (this.getEnableStatistics() === true) {
707 this.performanceStatistics
?.restart();
709 this.performanceStatistics
?.stop();
711 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
714 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
722 parentPort
?.postMessage(buildStartedMessage(this));
723 this.starting
= false;
725 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
728 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
732 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
733 if (this.started
=== true) {
734 if (this.stopping
=== false) {
735 this.stopping
= true;
736 await this.stopMessageSequence(reason
);
737 this.closeWSConnection();
738 if (this.getEnableStatistics() === true) {
739 this.performanceStatistics
?.stop();
741 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
742 this.templateFileWatcher
?.close();
743 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
744 delete this.bootNotificationResponse
;
745 this.started
= false;
746 this.saveConfiguration();
747 parentPort
?.postMessage(buildStoppedMessage(this));
748 this.stopping
= false;
750 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
753 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
757 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
758 await this.stop(reason
);
759 await sleep(this.stationInfo
.resetTime
!);
764 public saveOcppConfiguration(): void {
765 if (this.getOcppPersistentConfiguration()) {
766 this.saveConfiguration();
770 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
771 return ChargingStationConfigurationUtils
.getConfigurationKey(
773 StandardParametersKey
.SupportedFeatureProfiles
,
774 )?.value
?.includes(featureProfile
);
777 public bufferMessage(message
: string): void {
778 this.messageBuffer
.add(message
);
781 public openWSConnection(
782 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
783 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
785 terminateOpened
: false,
788 options
= { handshakeTimeout
: this.getConnectionTimeout() * 1000, ...options
};
789 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
790 if (this.started
=== false && this.starting
=== false) {
792 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()}
793 on stopped charging station`,
798 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
799 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
801 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
803 if (params
?.closeOpened
) {
804 this.closeWSConnection();
806 if (params
?.terminateOpened
) {
807 this.terminateWSConnection();
810 if (this.isWebSocketConnectionOpened() === true) {
812 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()}
819 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`,
822 this.wsConnection
= new WebSocket(
823 this.wsConnectionUrl
,
824 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
828 // Handle WebSocket message
829 this.wsConnection
.on(
831 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void,
833 // Handle WebSocket error
834 this.wsConnection
.on(
836 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void,
838 // Handle WebSocket close
839 this.wsConnection
.on(
841 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void,
843 // Handle WebSocket open
844 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
845 // Handle WebSocket ping
846 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
847 // Handle WebSocket pong
848 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
851 public closeWSConnection(): void {
852 if (this.isWebSocketConnectionOpened() === true) {
853 this.wsConnection
?.close();
854 this.wsConnection
= null;
858 public getAutomaticTransactionGeneratorConfiguration(): AutomaticTransactionGeneratorConfiguration
{
859 let automaticTransactionGeneratorConfiguration
:
860 | AutomaticTransactionGeneratorConfiguration
862 const automaticTransactionGeneratorConfigurationFromFile
=
863 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
865 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
866 automaticTransactionGeneratorConfigurationFromFile
868 automaticTransactionGeneratorConfiguration
=
869 automaticTransactionGeneratorConfigurationFromFile
;
871 automaticTransactionGeneratorConfiguration
=
872 this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
875 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
876 ...automaticTransactionGeneratorConfiguration
,
880 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
881 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
884 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
885 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
886 if (isNotEmptyArray(connectorIds
)) {
887 for (const connectorId
of connectorIds
!) {
888 this.automaticTransactionGenerator
?.startConnector(connectorId
);
891 this.automaticTransactionGenerator
?.start();
893 this.saveAutomaticTransactionGeneratorConfiguration();
894 parentPort
?.postMessage(buildUpdatedMessage(this));
897 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
898 if (isNotEmptyArray(connectorIds
)) {
899 for (const connectorId
of connectorIds
!) {
900 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
903 this.automaticTransactionGenerator
?.stop();
905 this.saveAutomaticTransactionGeneratorConfiguration();
906 parentPort
?.postMessage(buildUpdatedMessage(this));
909 public async stopTransactionOnConnector(
911 reason
= StopTransactionReason
.NONE
,
912 ): Promise
<StopTransactionResponse
> {
913 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
915 this.getBeginEndMeterValues() === true &&
916 this.getOcppStrictCompliance() === true &&
917 this.getOutOfOrderEndMeterValues() === false
919 // FIXME: Implement OCPP version agnostic helpers
920 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
923 this.getEnergyActiveImportRegisterByTransactionId(transactionId
!),
925 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
927 RequestCommand
.METER_VALUES
,
931 meterValue
: [transactionEndMeterValue
],
935 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
937 RequestCommand
.STOP_TRANSACTION
,
940 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
!, true),
946 public getReservationOnConnectorId0Enabled(): boolean {
947 return convertToBoolean(
948 ChargingStationConfigurationUtils
.getConfigurationKey(
950 StandardParametersKey
.ReserveConnectorZeroSupported
,
955 public async addReservation(reservation
: Reservation
): Promise
<void> {
956 const [exists
, reservationFound
] = this.doesReservationExists(reservation
);
958 await this.removeReservation(
960 ReservationTerminationReason
.REPLACE_EXISTING
,
963 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
;
964 await OCPPServiceUtils
.sendAndSetConnectorStatus(
966 reservation
.connectorId
,
967 ConnectorStatusEnum
.Reserved
,
969 { send
: reservation
.connectorId
!== 0 },
973 public async removeReservation(
974 reservation
: Reservation
,
975 reason
?: ReservationTerminationReason
,
977 const connector
= this.getConnectorStatus(reservation
.connectorId
)!;
979 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
980 delete connector
.reservation
;
982 case ReservationTerminationReason
.TRANSACTION_STARTED
:
983 delete connector
.reservation
;
985 case ReservationTerminationReason
.RESERVATION_CANCELED
:
986 case ReservationTerminationReason
.REPLACE_EXISTING
:
987 case ReservationTerminationReason
.EXPIRED
:
988 await OCPPServiceUtils
.sendAndSetConnectorStatus(
990 reservation
.connectorId
,
991 ConnectorStatusEnum
.Available
,
993 { send
: reservation
.connectorId
!== 0 },
995 delete connector
.reservation
;
1002 public getReservationBy(
1003 filterKey
: ReservationFilterKey
,
1004 value
: number | string,
1005 ): Reservation
| undefined {
1006 if (this.hasEvses
) {
1007 for (const evseStatus
of this.evses
.values()) {
1008 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1009 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1010 return connectorStatus
.reservation
;
1015 for (const connectorStatus
of this.connectors
.values()) {
1016 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1017 return connectorStatus
.reservation
;
1023 public doesReservationExists(
1024 reservation
: Partial
<Reservation
>,
1025 ): [boolean, Reservation
| undefined] {
1026 const foundReservation
= this.getReservationBy(
1027 ReservationFilterKey
.RESERVATION_ID
,
1030 return isUndefined(foundReservation
) ? [false, undefined] : [true, foundReservation
];
1033 public startReservationExpirationSetInterval(customInterval
?: number): void {
1035 customInterval
?? Constants
.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL
;
1037 `${this.logPrefix()} Reservation expiration date interval is set to ${interval}
1038 and starts on charging station now`,
1040 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1041 this.reservationExpirationSetInterval
= setInterval(async (): Promise
<void> => {
1042 const now
= new Date();
1043 if (this.hasEvses
) {
1044 for (const evseStatus
of this.evses
.values()) {
1045 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1046 if (connectorStatus
.reservation
!.expiryDate
< now
) {
1047 await this.removeReservation(
1048 connectorStatus
.reservation
!,
1049 ReservationTerminationReason
.EXPIRED
,
1055 for (const connectorStatus
of this.connectors
.values()) {
1056 if (connectorStatus
.reservation
!.expiryDate
< now
) {
1057 await this.removeReservation(
1058 connectorStatus
.reservation
!,
1059 ReservationTerminationReason
.EXPIRED
,
1067 public restartReservationExpiryDateSetInterval(): void {
1068 this.stopReservationExpirationSetInterval();
1069 this.startReservationExpirationSetInterval();
1072 public validateIncomingRequestWithReservation(connectorId
: number, idTag
: string): boolean {
1073 return this.getReservationBy(ReservationFilterKey
.CONNECTOR_ID
, connectorId
)?.idTag
=== idTag
;
1076 public isConnectorReservable(
1077 reservationId
: number,
1079 connectorId
?: number,
1081 const [alreadyExists
] = this.doesReservationExists({ id
: reservationId
});
1082 if (alreadyExists
) {
1083 return alreadyExists
;
1085 const userReservedAlready
= isUndefined(
1086 this.getReservationBy(ReservationFilterKey
.ID_TAG
, idTag
!),
1090 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
! > 0;
1091 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
1092 return !alreadyExists
&& !userReservedAlready
&& notConnectorZero
&& freeConnectorsAvailable
;
1095 private getNumberOfReservableConnectors(): number {
1096 let reservableConnectors
= 0;
1097 if (this.hasEvses
) {
1098 for (const evseStatus
of this.evses
.values()) {
1099 reservableConnectors
+= countReservableConnectors(evseStatus
.connectors
);
1102 reservableConnectors
= countReservableConnectors(this.connectors
);
1104 return reservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1107 private getNumberOfReservationsOnConnectorZero(): number {
1108 let numberOfReservations
= 0;
1109 if (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) {
1110 ++numberOfReservations
;
1111 } else if (this.connectors
.get(0)?.reservation
) {
1112 ++numberOfReservations
;
1114 return numberOfReservations
;
1117 private flushMessageBuffer(): void {
1118 if (this.messageBuffer
.size
> 0) {
1119 for (const message
of this.messageBuffer
.values()) {
1120 let beginId
: string | undefined;
1121 let commandName
: RequestCommand
| undefined;
1122 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1123 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1125 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1126 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1128 this.wsConnection
?.send(message
);
1129 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!);
1131 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1133 )} payload sent: ${message}`,
1135 this.messageBuffer
.delete(message
);
1140 private getSupervisionUrlOcppConfiguration(): boolean {
1141 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
1144 private stopReservationExpirationSetInterval(): void {
1145 if (this.reservationExpirationSetInterval
) {
1146 clearInterval(this.reservationExpirationSetInterval
);
1150 private getSupervisionUrlOcppKey(): string {
1151 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
1154 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1155 let template
: ChargingStationTemplate
| undefined;
1157 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1158 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1160 const measureId
= `${FileType.ChargingStationTemplate} read`;
1161 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1162 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1163 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1164 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1165 .update(JSON
.stringify(template
))
1167 this.sharedLRUCache
.setChargingStationTemplate(template
);
1168 this.templateFileHash
= template
.templateHash
;
1171 handleFileException(
1173 FileType
.ChargingStationTemplate
,
1174 error
as NodeJS
.ErrnoException
,
1181 private getStationInfoFromTemplate(): ChargingStationInfo
{
1182 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile()!;
1183 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1184 warnTemplateKeysDeprecation(stationTemplate
, this.logPrefix(), this.templateFile
);
1185 if (stationTemplate
?.Connectors
) {
1186 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1188 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1189 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1190 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1191 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1192 createSerialNumber(stationTemplate
, stationInfo
);
1193 if (isNotEmptyArray(stationTemplate
?.power
)) {
1194 stationTemplate
.power
= stationTemplate
.power
as number[];
1195 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1196 stationInfo
.maximumPower
=
1197 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1198 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1199 : stationTemplate
.power
[powerArrayRandomIndex
];
1201 stationTemplate
.power
= stationTemplate
?.power
as number;
1202 stationInfo
.maximumPower
=
1203 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1204 ? stationTemplate
.power
* 1000
1205 : stationTemplate
.power
;
1207 stationInfo
.firmwareVersionPattern
=
1208 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1210 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1211 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!) === false
1214 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1216 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`,
1219 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1226 stationTemplate
?.firmwareUpgrade
?? {},
1228 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1229 ? stationTemplate
.resetTime
! * 1000
1230 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1231 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1235 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1236 let stationInfo
: ChargingStationInfo
| undefined;
1237 if (this.getStationInfoPersistentConfiguration()) {
1238 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1240 delete stationInfo
?.infoHash
;
1246 private getStationInfo(): ChargingStationInfo
{
1247 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1248 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1250 // 1. charging station info from template
1251 // 2. charging station info from configuration file
1252 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1253 return stationInfoFromFile
!;
1255 stationInfoFromFile
&&
1256 propagateSerialNumber(
1257 this.getTemplateFromFile()!,
1258 stationInfoFromFile
,
1259 stationInfoFromTemplate
,
1261 return stationInfoFromTemplate
;
1264 private saveStationInfo(): void {
1265 if (this.getStationInfoPersistentConfiguration()) {
1266 this.saveConfiguration();
1270 private getOcppPersistentConfiguration(): boolean {
1271 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1274 private getStationInfoPersistentConfiguration(): boolean {
1275 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1278 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1279 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1282 private handleUnsupportedVersion(version
: OCPPVersion
) {
1283 const errorMsg
= `Unsupported protocol version '${version}' configured
1284 in template file ${this.templateFile}`;
1285 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1286 throw new BaseError(errorMsg
);
1289 private initialize(): void {
1290 const stationTemplate
= this.getTemplateFromFile()!;
1291 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1292 this.configurationFile
= join(
1293 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1294 `${getHashId(this.index, stationTemplate)}.json`,
1296 const chargingStationConfiguration
= this.getConfigurationFromFile();
1298 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1299 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1300 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1302 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1304 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1306 this.stationInfo
= this.getStationInfo();
1308 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1309 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1310 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1312 const patternGroup
: number | undefined =
1313 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1314 this.stationInfo
.firmwareVersion
?.split('.').length
;
1315 const match
= this.stationInfo
1316 .firmwareVersion
!.match(new RegExp(this.stationInfo
.firmwareVersionPattern
!))!
1317 .slice(1, patternGroup
! + 1);
1318 const patchLevelIndex
= match
.length
- 1;
1319 match
[patchLevelIndex
] = (
1320 convertToInt(match
[patchLevelIndex
]) +
1321 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1323 this.stationInfo
.firmwareVersion
= match
?.join('.');
1325 this.saveStationInfo();
1326 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1327 if (this.getEnableStatistics() === true) {
1328 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1329 this.stationInfo
.hashId
,
1330 this.stationInfo
.chargingStationId
!,
1331 this.configuredSupervisionUrl
,
1334 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
);
1335 this.powerDivider
= this.getPowerDivider();
1336 // OCPP configuration
1337 this.ocppConfiguration
= this.getOcppConfiguration();
1338 this.initializeOcppConfiguration();
1339 this.initializeOcppServices();
1340 if (this.stationInfo
?.autoRegister
=== true) {
1341 this.bootNotificationResponse
= {
1342 currentTime
: new Date(),
1343 interval
: this.getHeartbeatInterval() / 1000,
1344 status: RegistrationStatusEnumType
.ACCEPTED
,
1349 private initializeOcppServices(): void {
1350 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1351 switch (ocppVersion
) {
1352 case OCPPVersion
.VERSION_16
:
1353 this.ocppIncomingRequestService
=
1354 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1355 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1356 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(),
1359 case OCPPVersion
.VERSION_20
:
1360 case OCPPVersion
.VERSION_201
:
1361 this.ocppIncomingRequestService
=
1362 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1363 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1364 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>(),
1368 this.handleUnsupportedVersion(ocppVersion
);
1373 private initializeOcppConfiguration(): void {
1375 !ChargingStationConfigurationUtils
.getConfigurationKey(
1377 StandardParametersKey
.HeartbeatInterval
,
1380 ChargingStationConfigurationUtils
.addConfigurationKey(
1382 StandardParametersKey
.HeartbeatInterval
,
1387 !ChargingStationConfigurationUtils
.getConfigurationKey(
1389 StandardParametersKey
.HeartBeatInterval
,
1392 ChargingStationConfigurationUtils
.addConfigurationKey(
1394 StandardParametersKey
.HeartBeatInterval
,
1400 this.getSupervisionUrlOcppConfiguration() &&
1401 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1402 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1404 ChargingStationConfigurationUtils
.addConfigurationKey(
1406 this.getSupervisionUrlOcppKey(),
1407 this.configuredSupervisionUrl
.href
,
1411 !this.getSupervisionUrlOcppConfiguration() &&
1412 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1413 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1415 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1417 this.getSupervisionUrlOcppKey(),
1422 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1423 !ChargingStationConfigurationUtils
.getConfigurationKey(
1425 this.stationInfo
.amperageLimitationOcppKey
!,
1428 ChargingStationConfigurationUtils
.addConfigurationKey(
1430 this.stationInfo
.amperageLimitationOcppKey
!,
1432 this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)
1437 !ChargingStationConfigurationUtils
.getConfigurationKey(
1439 StandardParametersKey
.SupportedFeatureProfiles
,
1442 ChargingStationConfigurationUtils
.addConfigurationKey(
1444 StandardParametersKey
.SupportedFeatureProfiles
,
1445 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`,
1448 ChargingStationConfigurationUtils
.addConfigurationKey(
1450 StandardParametersKey
.NumberOfConnectors
,
1451 this.getNumberOfConnectors().toString(),
1453 { overwrite
: true },
1456 !ChargingStationConfigurationUtils
.getConfigurationKey(
1458 StandardParametersKey
.MeterValuesSampledData
,
1461 ChargingStationConfigurationUtils
.addConfigurationKey(
1463 StandardParametersKey
.MeterValuesSampledData
,
1464 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
1468 !ChargingStationConfigurationUtils
.getConfigurationKey(
1470 StandardParametersKey
.ConnectorPhaseRotation
,
1473 const connectorsPhaseRotation
: string[] = [];
1474 if (this.hasEvses
) {
1475 for (const evseStatus
of this.evses
.values()) {
1476 for (const connectorId
of evseStatus
.connectors
.keys()) {
1477 connectorsPhaseRotation
.push(
1478 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1483 for (const connectorId
of this.connectors
.keys()) {
1484 connectorsPhaseRotation
.push(
1485 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1489 ChargingStationConfigurationUtils
.addConfigurationKey(
1491 StandardParametersKey
.ConnectorPhaseRotation
,
1492 connectorsPhaseRotation
.toString(),
1496 !ChargingStationConfigurationUtils
.getConfigurationKey(
1498 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1501 ChargingStationConfigurationUtils
.addConfigurationKey(
1503 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1508 !ChargingStationConfigurationUtils
.getConfigurationKey(
1510 StandardParametersKey
.LocalAuthListEnabled
,
1512 ChargingStationConfigurationUtils
.getConfigurationKey(
1514 StandardParametersKey
.SupportedFeatureProfiles
,
1515 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1517 ChargingStationConfigurationUtils
.addConfigurationKey(
1519 StandardParametersKey
.LocalAuthListEnabled
,
1524 !ChargingStationConfigurationUtils
.getConfigurationKey(
1526 StandardParametersKey
.ConnectionTimeOut
,
1529 ChargingStationConfigurationUtils
.addConfigurationKey(
1531 StandardParametersKey
.ConnectionTimeOut
,
1532 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString(),
1535 this.saveOcppConfiguration();
1538 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1539 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1540 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1541 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1543 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1544 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1545 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1546 delete evseStatus
.connectorsStatus
;
1547 this.evses
.set(evseId
, {
1548 ...(evseStatus
as EvseStatus
),
1549 connectors
: new Map
<number, ConnectorStatus
>(
1550 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1557 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1558 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1559 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1560 throw new BaseError(errorMsg
);
1562 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1563 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1564 throw new BaseError(errorMsg
);
1568 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1569 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1570 this.initializeConnectorsFromTemplate(stationTemplate
);
1571 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1572 this.initializeEvsesFromTemplate(stationTemplate
);
1573 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1574 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1575 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1576 throw new BaseError(errorMsg
);
1578 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1579 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1580 throw new BaseError(errorMsg
);
1584 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1585 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1586 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1587 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1588 throw new BaseError(errorMsg
);
1590 if (!stationTemplate
?.Connectors
?.[0]) {
1592 `${this.logPrefix()} Charging station information from template ${
1594 } with no connector id 0 configuration`,
1597 if (stationTemplate
?.Connectors
) {
1598 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1599 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1600 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1602 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`,
1605 const connectorsConfigChanged
=
1606 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1607 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1608 connectorsConfigChanged
&& this.connectors
.clear();
1609 this.connectorsConfigurationHash
= connectorsConfigHash
;
1610 if (templateMaxConnectors
> 0) {
1611 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1613 connectorId
=== 0 &&
1614 (!stationTemplate
?.Connectors
[connectorId
] ||
1615 this.getUseConnectorId0(stationTemplate
) === false)
1619 const templateConnectorId
=
1620 connectorId
> 0 && stationTemplate
?.randomConnectors
1621 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1623 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1624 checkStationInfoConnectorStatus(
1625 templateConnectorId
,
1630 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1632 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1633 this.saveConnectorsStatus();
1636 `${this.logPrefix()} Charging station information from template ${
1638 } with no connectors configuration defined, cannot create connectors`,
1644 `${this.logPrefix()} Charging station information from template ${
1646 } with no connectors configuration defined, using already defined connectors`,
1651 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1652 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1653 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1654 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1655 throw new BaseError(errorMsg
);
1657 if (!stationTemplate
?.Evses
?.[0]) {
1659 `${this.logPrefix()} Charging station information from template ${
1661 } with no evse id 0 configuration`,
1664 if (!stationTemplate
?.Evses
?.[0]?.Connectors
?.[0]) {
1666 `${this.logPrefix()} Charging station information from template ${
1668 } with evse id 0 with no connector id 0 configuration`,
1671 if (stationTemplate
?.Evses
) {
1672 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1673 .update(JSON
.stringify(stationTemplate
?.Evses
))
1675 const evsesConfigChanged
=
1676 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1677 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1678 evsesConfigChanged
&& this.evses
.clear();
1679 this.evsesConfigurationHash
= evsesConfigHash
;
1680 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1681 if (templateMaxEvses
> 0) {
1682 for (const evse
in stationTemplate
.Evses
) {
1683 const evseId
= convertToInt(evse
);
1684 this.evses
.set(evseId
, {
1685 connectors
: buildConnectorsMap(
1686 stationTemplate
?.Evses
[evse
]?.Connectors
,
1690 availability
: AvailabilityType
.Operative
,
1692 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix());
1694 this.saveEvsesStatus();
1697 `${this.logPrefix()} Charging station information from template ${
1699 } with no evses configuration defined, cannot create evses`,
1705 `${this.logPrefix()} Charging station information from template ${
1707 } with no evses configuration defined, using already defined evses`,
1712 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1713 let configuration
: ChargingStationConfiguration
| undefined;
1714 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1716 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1717 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1718 this.configurationFileHash
,
1721 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1722 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1723 configuration
= JSON
.parse(
1724 readFileSync(this.configurationFile
, 'utf8'),
1725 ) as ChargingStationConfiguration
;
1726 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1727 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1728 this.configurationFileHash
= configuration
.configurationHash
!;
1731 handleFileException(
1732 this.configurationFile
,
1733 FileType
.ChargingStationConfiguration
,
1734 error
as NodeJS
.ErrnoException
,
1739 return configuration
;
1742 private saveAutomaticTransactionGeneratorConfiguration(): void {
1743 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1744 this.saveConfiguration();
1748 private saveConnectorsStatus() {
1749 this.saveConfiguration();
1752 private saveEvsesStatus() {
1753 this.saveConfiguration();
1756 private saveConfiguration(): void {
1757 if (isNotEmptyString(this.configurationFile
)) {
1759 if (!existsSync(dirname(this.configurationFile
))) {
1760 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1762 let configurationData
: ChargingStationConfiguration
=
1763 cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()!) ?? {};
1764 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1765 configurationData
.stationInfo
= this.stationInfo
;
1767 delete configurationData
.stationInfo
;
1769 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1770 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1772 delete configurationData
.configurationKey
;
1774 configurationData
= merge
<ChargingStationConfiguration
>(
1776 buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
1779 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1780 !this.getAutomaticTransactionGeneratorConfiguration()
1782 delete configurationData
.automaticTransactionGenerator
;
1784 if (this.connectors
.size
> 0) {
1785 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1787 delete configurationData
.connectorsStatus
;
1789 if (this.evses
.size
> 0) {
1790 configurationData
.evsesStatus
= buildEvsesStatus(this);
1792 delete configurationData
.evsesStatus
;
1794 delete configurationData
.configurationHash
;
1795 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1798 stationInfo
: configurationData
.stationInfo
,
1799 configurationKey
: configurationData
.configurationKey
,
1800 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1801 } as ChargingStationConfiguration
),
1804 if (this.configurationFileHash
!== configurationHash
) {
1805 AsyncLock
.acquire(AsyncLockType
.configuration
)
1807 configurationData
.configurationHash
= configurationHash
;
1808 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1809 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1810 const fileDescriptor
= openSync(this.configurationFile
, 'w');
1811 writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1812 closeSync(fileDescriptor
);
1813 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1814 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1815 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1816 this.configurationFileHash
= configurationHash
;
1819 handleFileException(
1820 this.configurationFile
,
1821 FileType
.ChargingStationConfiguration
,
1822 error
as NodeJS
.ErrnoException
,
1827 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1831 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1832 this.configurationFile
1837 handleFileException(
1838 this.configurationFile
,
1839 FileType
.ChargingStationConfiguration
,
1840 error
as NodeJS
.ErrnoException
,
1846 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`,
1851 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1852 return this.getTemplateFromFile()?.Configuration
;
1855 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1856 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1857 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1858 return { configurationKey
};
1863 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1864 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1865 this.getOcppConfigurationFromFile();
1866 if (!ocppConfiguration
) {
1867 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1869 return ocppConfiguration
;
1872 private async onOpen(): Promise
<void> {
1873 if (this.isWebSocketConnectionOpened() === true) {
1875 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`,
1877 if (this.isRegistered() === false) {
1878 // Send BootNotification
1879 let registrationRetryCount
= 0;
1881 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1882 BootNotificationRequest
,
1883 BootNotificationResponse
1884 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1885 skipBufferingOnError
: true,
1887 if (this.isRegistered() === false) {
1888 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1890 this?.bootNotificationResponse
?.interval
1891 ? this.bootNotificationResponse
.interval
* 1000
1892 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
,
1896 this.isRegistered() === false &&
1897 (registrationRetryCount
<= this.getRegistrationMaxRetries()! ||
1898 this.getRegistrationMaxRetries() === -1)
1901 if (this.isRegistered() === true) {
1902 if (this.inAcceptedState() === true) {
1903 await this.startMessageSequence();
1907 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`,
1910 this.wsConnectionRestarted
= false;
1911 this.autoReconnectRetryCount
= 0;
1912 parentPort
?.postMessage(buildUpdatedMessage(this));
1915 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`,
1920 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1923 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1924 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1926 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1928 )}' and reason '${reason.toString()}'`,
1930 this.autoReconnectRetryCount
= 0;
1935 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1937 )}' and reason '${reason.toString()}'`,
1939 this.started
=== true && (await this.reconnect());
1942 parentPort
?.postMessage(buildUpdatedMessage(this));
1945 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1946 const cachedRequest
= this.requests
.get(messageId
);
1947 if (Array.isArray(cachedRequest
) === true) {
1948 return cachedRequest
;
1950 throw new OCPPError(
1951 ErrorType
.PROTOCOL_ERROR
,
1952 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1954 )} is not an array`,
1956 cachedRequest
as JsonType
,
1960 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1961 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1962 if (this.getEnableStatistics() === true) {
1963 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1966 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1970 // Process the message
1971 await this.ocppIncomingRequestService
.incomingRequestHandler(
1979 private handleResponseMessage(response
: Response
): void {
1980 const [messageType
, messageId
, commandPayload
] = response
;
1981 if (this.requests
.has(messageId
) === false) {
1983 throw new OCPPError(
1984 ErrorType
.INTERNAL_ERROR
,
1985 `Response for unknown message id ${messageId}`,
1991 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1996 `${this.logPrefix()} << Command '${
1997 requestCommandName ?? Constants.UNKNOWN_COMMAND
1998 }' received response payload: ${JSON.stringify(response)}`,
2000 responseCallback(commandPayload
, requestPayload
);
2003 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
2004 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
2005 if (this.requests
.has(messageId
) === false) {
2007 throw new OCPPError(
2008 ErrorType
.INTERNAL_ERROR
,
2009 `Error response for unknown message id ${messageId}`,
2011 { errorType
, errorMessage
, errorDetails
},
2014 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
2016 `${this.logPrefix()} << Command '${
2017 requestCommandName ?? Constants.UNKNOWN_COMMAND
2018 }' received error response payload: ${JSON.stringify(errorResponse)}`,
2020 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
2023 private async onMessage(data
: RawData
): Promise
<void> {
2024 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined;
2025 let messageType
: number | undefined;
2026 let errorMsg
: string;
2028 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2029 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
2030 if (Array.isArray(request
) === true) {
2031 [messageType
] = request
;
2032 // Check the type of message
2033 switch (messageType
) {
2035 case MessageType
.CALL_MESSAGE
:
2036 await this.handleIncomingMessage(request
as IncomingRequest
);
2039 case MessageType
.CALL_RESULT_MESSAGE
:
2040 this.handleResponseMessage(request
as Response
);
2043 case MessageType
.CALL_ERROR_MESSAGE
:
2044 this.handleErrorMessage(request
as ErrorResponse
);
2048 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2049 errorMsg
= `Wrong message type ${messageType}`;
2050 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2051 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
2053 parentPort
?.postMessage(buildUpdatedMessage(this));
2055 throw new OCPPError(
2056 ErrorType
.PROTOCOL_ERROR
,
2057 'Incoming message is not an array',
2065 let commandName
: IncomingRequestCommand
| undefined;
2066 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined;
2067 let errorCallback
: ErrorCallback
;
2068 const [, messageId
] = request
!;
2069 switch (messageType
) {
2070 case MessageType
.CALL_MESSAGE
:
2071 [, , commandName
] = request
as IncomingRequest
;
2073 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
2075 case MessageType
.CALL_RESULT_MESSAGE
:
2076 case MessageType
.CALL_ERROR_MESSAGE
:
2077 if (this.requests
.has(messageId
) === true) {
2078 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
2079 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2080 errorCallback(error
as OCPPError
, false);
2082 // Remove the request from the cache in case of error at response handling
2083 this.requests
.delete(messageId
);
2087 if (error
instanceof OCPPError
=== false) {
2089 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2090 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2091 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2092 }' message '${data.toString()}' handling is not an OCPPError:`,
2097 `${this.logPrefix()} Incoming OCPP command '${
2098 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2099 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2100 }' message '${data.toString()}'${
2101 messageType !== MessageType.CALL_MESSAGE
2102 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2104 } processing error:`,
2110 private onPing(): void {
2111 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
2114 private onPong(): void {
2115 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
2118 private onError(error
: WSError
): void {
2119 this.closeWSConnection();
2120 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
2123 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2124 if (this.getMeteringPerTransaction() === true) {
2127 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
2128 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2133 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2134 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2138 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2139 return stationTemplate
?.useConnectorId0
?? true;
2142 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
2143 if (this.hasEvses
) {
2144 for (const [evseId
, evseStatus
] of this.evses
) {
2148 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2149 if (connectorStatus
.transactionStarted
=== true) {
2150 await this.stopTransactionOnConnector(connectorId
, reason
);
2155 for (const connectorId
of this.connectors
.keys()) {
2156 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2157 await this.stopTransactionOnConnector(connectorId
, reason
);
2164 private getConnectionTimeout(): number {
2166 ChargingStationConfigurationUtils
.getConfigurationKey(
2168 StandardParametersKey
.ConnectionTimeOut
,
2173 ChargingStationConfigurationUtils
.getConfigurationKey(
2175 StandardParametersKey
.ConnectionTimeOut
,
2177 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
2180 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2183 // -1 for unlimited, 0 for disabling
2184 private getAutoReconnectMaxRetries(): number | undefined {
2186 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
2191 private getRegistrationMaxRetries(): number | undefined {
2192 return this.stationInfo
.registrationMaxRetries
?? -1;
2195 private getPowerDivider(): number {
2196 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2197 if (this.stationInfo
?.powerSharedByConnectors
) {
2198 powerDivider
= this.getNumberOfRunningTransactions();
2200 return powerDivider
;
2203 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2204 const maximumPower
= this.getMaximumPower(stationInfo
);
2205 switch (this.getCurrentOutType(stationInfo
)) {
2206 case CurrentType
.AC
:
2207 return ACElectricUtils
.amperagePerPhaseFromPower(
2208 this.getNumberOfPhases(stationInfo
),
2209 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2210 this.getVoltageOut(stationInfo
),
2212 case CurrentType
.DC
:
2213 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2217 private getAmperageLimitation(): number | undefined {
2219 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2220 ChargingStationConfigurationUtils
.getConfigurationKey(
2222 this.stationInfo
.amperageLimitationOcppKey
!,
2227 ChargingStationConfigurationUtils
.getConfigurationKey(
2229 this.stationInfo
.amperageLimitationOcppKey
!,
2231 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2236 private async startMessageSequence(): Promise
<void> {
2237 if (this.stationInfo
?.autoRegister
=== true) {
2238 await this.ocppRequestService
.requestHandler
<
2239 BootNotificationRequest
,
2240 BootNotificationResponse
2241 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2242 skipBufferingOnError
: true,
2245 // Start WebSocket ping
2246 this.startWebSocketPing();
2248 this.startHeartbeat();
2249 // Initialize connectors status
2250 if (this.hasEvses
) {
2251 for (const [evseId
, evseStatus
] of this.evses
) {
2253 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2254 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2255 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2258 connectorBootStatus
,
2265 for (const connectorId
of this.connectors
.keys()) {
2266 if (connectorId
> 0) {
2267 const connectorBootStatus
= getBootConnectorStatus(
2270 this.getConnectorStatus(connectorId
)!,
2272 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2276 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2277 await this.ocppRequestService
.requestHandler
<
2278 FirmwareStatusNotificationRequest
,
2279 FirmwareStatusNotificationResponse
2280 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2281 status: FirmwareStatus
.Installed
,
2283 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2287 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2288 this.startAutomaticTransactionGenerator();
2290 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2293 private async stopMessageSequence(
2294 reason
: StopTransactionReason
= StopTransactionReason
.NONE
,
2296 // Stop WebSocket ping
2297 this.stopWebSocketPing();
2299 this.stopHeartbeat();
2300 // Stop ongoing transactions
2301 if (this.automaticTransactionGenerator
?.started
=== true) {
2302 this.stopAutomaticTransactionGenerator();
2304 await this.stopRunningTransactions(reason
);
2306 if (this.hasEvses
) {
2307 for (const [evseId
, evseStatus
] of this.evses
) {
2309 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2310 await this.ocppRequestService
.requestHandler
<
2311 StatusNotificationRequest
,
2312 StatusNotificationResponse
2315 RequestCommand
.STATUS_NOTIFICATION
,
2316 OCPPServiceUtils
.buildStatusNotificationRequest(
2319 ConnectorStatusEnum
.Unavailable
,
2323 delete connectorStatus
?.status;
2328 for (const connectorId
of this.connectors
.keys()) {
2329 if (connectorId
> 0) {
2330 await this.ocppRequestService
.requestHandler
<
2331 StatusNotificationRequest
,
2332 StatusNotificationResponse
2335 RequestCommand
.STATUS_NOTIFICATION
,
2336 OCPPServiceUtils
.buildStatusNotificationRequest(
2339 ConnectorStatusEnum
.Unavailable
,
2342 delete this.getConnectorStatus(connectorId
)?.status;
2348 private startWebSocketPing(): void {
2349 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2351 StandardParametersKey
.WebSocketPingInterval
,
2354 ChargingStationConfigurationUtils
.getConfigurationKey(
2356 StandardParametersKey
.WebSocketPingInterval
,
2360 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2361 this.webSocketPingSetInterval
= setInterval(() => {
2362 if (this.isWebSocketConnectionOpened() === true) {
2363 this.wsConnection
?.ping();
2365 }, webSocketPingInterval
* 1000);
2367 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2368 webSocketPingInterval,
2371 } else if (this.webSocketPingSetInterval
) {
2373 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2374 webSocketPingInterval,
2379 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`,
2384 private stopWebSocketPing(): void {
2385 if (this.webSocketPingSetInterval
) {
2386 clearInterval(this.webSocketPingSetInterval
);
2387 delete this.webSocketPingSetInterval
;
2391 private getConfiguredSupervisionUrl(): URL
{
2392 let configuredSupervisionUrl
: string;
2393 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2394 if (isNotEmptyArray(supervisionUrls
)) {
2395 let configuredSupervisionUrlIndex
: number;
2396 switch (Configuration
.getSupervisionUrlDistribution()) {
2397 case SupervisionUrlDistribution
.RANDOM
:
2398 configuredSupervisionUrlIndex
= Math.floor(
2399 secureRandom() * (supervisionUrls
as string[]).length
,
2402 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2403 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2405 Object.values(SupervisionUrlDistribution
).includes(
2406 Configuration
.getSupervisionUrlDistribution()!,
2409 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2410 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2411 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2414 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
;
2417 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
];
2419 configuredSupervisionUrl
= supervisionUrls
as string;
2421 if (isNotEmptyString(configuredSupervisionUrl
)) {
2422 return new URL(configuredSupervisionUrl
);
2424 const errorMsg
= 'No supervision url(s) configured';
2425 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2426 throw new BaseError(`${errorMsg}`);
2429 private stopHeartbeat(): void {
2430 if (this.heartbeatSetInterval
) {
2431 clearInterval(this.heartbeatSetInterval
);
2432 delete this.heartbeatSetInterval
;
2436 private terminateWSConnection(): void {
2437 if (this.isWebSocketConnectionOpened() === true) {
2438 this.wsConnection
?.terminate();
2439 this.wsConnection
= null;
2443 private getReconnectExponentialDelay(): boolean {
2444 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2447 private async reconnect(): Promise
<void> {
2448 // Stop WebSocket ping
2449 this.stopWebSocketPing();
2451 this.stopHeartbeat();
2452 // Stop the ATG if needed
2453 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2454 this.stopAutomaticTransactionGenerator();
2457 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries()! ||
2458 this.getAutoReconnectMaxRetries() === -1
2460 ++this.autoReconnectRetryCount
;
2461 const reconnectDelay
= this.getReconnectExponentialDelay()
2462 ? exponentialDelay(this.autoReconnectRetryCount
)
2463 : this.getConnectionTimeout() * 1000;
2464 const reconnectDelayWithdraw
= 1000;
2465 const reconnectTimeout
=
2466 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2467 ? reconnectDelay
- reconnectDelayWithdraw
2470 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2473 )}ms, timeout ${reconnectTimeout}ms`,
2475 await sleep(reconnectDelay
);
2477 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`,
2479 this.openWSConnection(
2481 ...(this.stationInfo
?.wsOptions
?? {}),
2482 handshakeTimeout
: reconnectTimeout
,
2484 { closeOpened
: true },
2486 this.wsConnectionRestarted
= true;
2487 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2489 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2490 this.autoReconnectRetryCount
2491 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`,