1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import crypto from
'node:crypto';
4 import fs from
'node:fs';
5 import path from
'node:path';
6 import { URL
} from
'node:url';
7 import { parentPort
} from
'node:worker_threads';
9 import merge from
'just-merge';
10 import WebSocket
, { type RawData
} from
'ws';
12 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
13 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
14 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
15 import { ChargingStationUtils
} from
'./ChargingStationUtils';
16 import { IdTagsCache
} from
'./IdTagsCache';
18 OCPP16IncomingRequestService
,
20 OCPP16ResponseService
,
22 OCPP20IncomingRequestService
,
24 OCPP20ResponseService
,
25 type OCPPIncomingRequestService
,
26 type OCPPRequestService
,
29 import { SharedLRUCache
} from
'./SharedLRUCache';
30 import { BaseError
, OCPPError
} from
'../exception';
31 import { PerformanceStatistics
} from
'../performance';
33 type AutomaticTransactionGeneratorConfiguration
,
35 type BootNotificationRequest
,
36 type BootNotificationResponse
,
38 type ChargingStationConfiguration
,
39 type ChargingStationInfo
,
40 type ChargingStationOcppConfiguration
,
41 type ChargingStationTemplate
,
49 type EvseStatusConfiguration
,
52 type FirmwareStatusNotificationRequest
,
53 type FirmwareStatusNotificationResponse
,
55 type HeartbeatRequest
,
56 type HeartbeatResponse
,
58 type IncomingRequestCommand
,
63 type MeterValuesRequest
,
64 type MeterValuesResponse
,
68 RegistrationStatusEnumType
,
71 StandardParametersKey
,
72 type StatusNotificationRequest
,
73 type StatusNotificationResponse
,
74 StopTransactionReason
,
75 type StopTransactionRequest
,
76 type StopTransactionResponse
,
77 SupervisionUrlDistribution
,
78 SupportedFeatureProfiles
,
81 WebSocketCloseEventStatusCode
,
95 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
96 buildConnectorsStatus
,
101 export class ChargingStation
{
102 public readonly index
: number;
103 public readonly templateFile
: string;
104 public stationInfo
!: ChargingStationInfo
;
105 public started
: boolean;
106 public starting
: boolean;
107 public idTagsCache
: IdTagsCache
;
108 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
109 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
110 public wsConnection
!: WebSocket
| null;
111 public readonly connectors
: Map
<number, ConnectorStatus
>;
112 public readonly evses
: Map
<number, EvseStatus
>;
113 public readonly requests
: Map
<string, CachedRequest
>;
114 public performanceStatistics
!: PerformanceStatistics
| undefined;
115 public heartbeatSetInterval
!: NodeJS
.Timeout
;
116 public ocppRequestService
!: OCPPRequestService
;
117 public bootNotificationRequest
!: BootNotificationRequest
;
118 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
119 public powerDivider
!: number;
120 private stopping
: boolean;
121 private configurationFile
!: string;
122 private configurationFileHash
!: string;
123 private connectorsConfigurationHash
!: string;
124 private evsesConfigurationHash
!: string;
125 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
126 private readonly messageBuffer
: Set
<string>;
127 private configuredSupervisionUrl
!: URL
;
128 private wsConnectionRestarted
: boolean;
129 private autoReconnectRetryCount
: number;
130 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
131 private templateFileHash
!: string;
132 private readonly sharedLRUCache
: SharedLRUCache
;
133 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
134 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
136 constructor(index
: number, templateFile
: string) {
137 this.started
= false;
138 this.starting
= false;
139 this.stopping
= false;
140 this.wsConnectionRestarted
= false;
141 this.autoReconnectRetryCount
= 0;
143 this.templateFile
= templateFile
;
144 this.connectors
= new Map
<number, ConnectorStatus
>();
145 this.evses
= new Map
<number, EvseStatus
>();
146 this.requests
= new Map
<string, CachedRequest
>();
147 this.messageBuffer
= new Set
<string>();
148 this.sharedLRUCache
= SharedLRUCache
.getInstance();
149 this.idTagsCache
= IdTagsCache
.getInstance();
150 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
155 public get
hasEvses(): boolean {
156 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
159 private get
wsConnectionUrl(): URL
{
162 this.getSupervisionUrlOcppConfiguration() &&
163 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
164 Utils.isNotEmptyString(
165 ChargingStationConfigurationUtils.getConfigurationKey(
167 this.getSupervisionUrlOcppKey()
170 ? ChargingStationConfigurationUtils.getConfigurationKey(
172 this.getSupervisionUrlOcppKey()
174 : this.configuredSupervisionUrl.href
175 }/${this.stationInfo.chargingStationId}`
179 public logPrefix
= (): string => {
180 return Utils
.logPrefix(
182 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId)
183 ? this?.stationInfo?.chargingStationId
184 : ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())) ??
185 'Error at building log prefix'
190 public hasIdTags(): boolean {
191 return Utils
.isNotEmptyArray(
192 this.idTagsCache
.getIdTags(ChargingStationUtils
.getIdTagsFile(this.stationInfo
))
196 public getEnableStatistics(): boolean {
197 return this.stationInfo
.enableStatistics
?? false;
200 public getMustAuthorizeAtRemoteStart(): boolean {
201 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
204 public getPayloadSchemaValidation(): boolean {
205 return this.stationInfo
.payloadSchemaValidation
?? true;
208 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
209 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
210 switch (this.getCurrentOutType(stationInfo
)) {
212 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
213 ? localStationInfo
.numberOfPhases
220 public isWebSocketConnectionOpened(): boolean {
221 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
224 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
225 return this?.bootNotificationResponse
?.status;
228 public inUnknownState(): boolean {
229 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
232 public inPendingState(): boolean {
233 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
236 public inAcceptedState(): boolean {
237 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
240 public inRejectedState(): boolean {
241 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
244 public isRegistered(): boolean {
246 this.inUnknownState() === false &&
247 (this.inAcceptedState() === true || this.inPendingState() === true)
251 public isChargingStationAvailable(): boolean {
252 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
255 public hasConnector(connectorId
: number): boolean {
257 for (const evseStatus
of this.evses
.values()) {
258 if (evseStatus
.connectors
.has(connectorId
)) {
264 return this.connectors
.has(connectorId
);
267 public isConnectorAvailable(connectorId
: number): boolean {
270 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
274 public getNumberOfConnectors(): number {
276 if (this.evses
.size
=== 0) {
277 throw new BaseError('Evses not initialized, cannot get number of connectors');
279 let numberOfConnectors
= 0;
280 for (const [evseId
, evseStatus
] of this.evses
) {
282 numberOfConnectors
+= evseStatus
.connectors
.size
;
285 return numberOfConnectors
;
287 if (this.connectors
.size
=== 0) {
288 throw new BaseError('Connectors not initialized, cannot get number of connectors');
290 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
293 public getNumberOfEvses(): number {
294 if (this.evses
.size
=== 0) {
295 throw new BaseError('Evses not initialized, cannot get number of evses');
297 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
300 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
302 for (const evseStatus
of this.evses
.values()) {
303 if (evseStatus
.connectors
.has(connectorId
)) {
304 return evseStatus
.connectors
.get(connectorId
);
309 return this.connectors
.get(connectorId
);
312 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
313 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
316 public getOcppStrictCompliance(): boolean {
317 return this.stationInfo
?.ocppStrictCompliance
?? false;
320 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
321 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
322 this.getCurrentOutType(stationInfo
),
326 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
329 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
330 const localStationInfo
= stationInfo
?? this.stationInfo
;
331 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
334 public getConnectorMaximumAvailablePower(connectorId
: number): number {
335 let connectorAmperageLimitationPowerLimit
: number;
337 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
338 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
340 connectorAmperageLimitationPowerLimit
=
341 (this.getCurrentOutType() === CurrentType
.AC
342 ? ACElectricUtils
.powerTotal(
343 this.getNumberOfPhases(),
344 this.getVoltageOut(),
345 this.getAmperageLimitation() *
346 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
348 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
351 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
352 const connectorChargingProfilesPowerLimit
=
353 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
355 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
356 isNaN(connectorAmperageLimitationPowerLimit
)
358 : connectorAmperageLimitationPowerLimit
,
359 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
363 public getTransactionIdTag(transactionId
: number): string | undefined {
365 for (const evseStatus
of this.evses
.values()) {
366 for (const connectorStatus
of evseStatus
.connectors
.values()) {
367 if (connectorStatus
.transactionId
=== transactionId
) {
368 return connectorStatus
.transactionIdTag
;
373 for (const connectorId
of this.connectors
.keys()) {
376 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
378 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
384 public getNumberOfRunningTransactions(): number {
387 for (const evseStatus
of this.evses
.values()) {
388 for (const connectorStatus
of evseStatus
.connectors
.values()) {
389 if (connectorStatus
.transactionStarted
=== true) {
395 for (const connectorId
of this.connectors
.keys()) {
396 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
404 public getOutOfOrderEndMeterValues(): boolean {
405 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
408 public getBeginEndMeterValues(): boolean {
409 return this.stationInfo
?.beginEndMeterValues
?? false;
412 public getMeteringPerTransaction(): boolean {
413 return this.stationInfo
?.meteringPerTransaction
?? true;
416 public getTransactionDataMeterValues(): boolean {
417 return this.stationInfo
?.transactionDataMeterValues
?? false;
420 public getMainVoltageMeterValues(): boolean {
421 return this.stationInfo
?.mainVoltageMeterValues
?? true;
424 public getPhaseLineToLineVoltageMeterValues(): boolean {
425 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
428 public getCustomValueLimitationMeterValues(): boolean {
429 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
432 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
434 for (const evseStatus
of this.evses
.values()) {
435 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
436 if (connectorStatus
.transactionId
=== transactionId
) {
442 for (const connectorId
of this.connectors
.keys()) {
445 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
453 public getEnergyActiveImportRegisterByTransactionId(
454 transactionId
: number,
457 return this.getEnergyActiveImportRegister(
458 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
463 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
464 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
467 public getAuthorizeRemoteTxRequests(): boolean {
468 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
470 StandardParametersKey
.AuthorizeRemoteTxRequests
472 return authorizeRemoteTxRequests
473 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
477 public getLocalAuthListEnabled(): boolean {
478 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
480 StandardParametersKey
.LocalAuthListEnabled
482 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
485 public getHeartbeatInterval(): number {
486 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
488 StandardParametersKey
.HeartbeatInterval
490 if (HeartbeatInterval
) {
491 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
493 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
495 StandardParametersKey
.HeartBeatInterval
497 if (HeartBeatInterval
) {
498 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
500 this.stationInfo
?.autoRegister
=== false &&
502 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
503 Constants.DEFAULT_HEARTBEAT_INTERVAL
506 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
509 public setSupervisionUrl(url
: string): void {
511 this.getSupervisionUrlOcppConfiguration() &&
512 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey())
514 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
516 this.getSupervisionUrlOcppKey(),
520 this.stationInfo
.supervisionUrls
= url
;
521 this.saveStationInfo();
522 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
526 public startHeartbeat(): void {
527 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
528 this.heartbeatSetInterval
= setInterval(() => {
529 this.ocppRequestService
530 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
533 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
537 }, this.getHeartbeatInterval());
539 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
540 this.getHeartbeatInterval()
543 } else if (this.heartbeatSetInterval
) {
545 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
546 this.getHeartbeatInterval()
551 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
556 public restartHeartbeat(): void {
558 this.stopHeartbeat();
560 this.startHeartbeat();
563 public restartWebSocketPing(): void {
564 // Stop WebSocket ping
565 this.stopWebSocketPing();
566 // Start WebSocket ping
567 this.startWebSocketPing();
570 public startMeterValues(connectorId
: number, interval
: number): void {
571 if (connectorId
=== 0) {
573 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
577 if (!this.getConnectorStatus(connectorId
)) {
579 `${this.logPrefix()} Trying to start MeterValues on non existing connector id ${connectorId.toString()}`
583 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
585 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
589 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
590 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
593 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
598 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
599 // FIXME: Implement OCPP version agnostic helpers
600 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
603 this.getConnectorStatus(connectorId
).transactionId
,
606 this.ocppRequestService
607 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
609 RequestCommand
.METER_VALUES
,
612 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
613 meterValue
: [meterValue
],
618 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
625 `${this.logPrefix()} Charging station ${
626 StandardParametersKey.MeterValueSampleInterval
627 } configuration set to ${interval}, not sending MeterValues`
632 public stopMeterValues(connectorId
: number) {
633 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
634 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
638 public start(): void {
639 if (this.started
=== false) {
640 if (this.starting
=== false) {
641 this.starting
= true;
642 if (this.getEnableStatistics() === true) {
643 this.performanceStatistics
?.start();
645 this.openWSConnection();
646 // Monitor charging station template file
647 this.templateFileWatcher
= FileUtils
.watchJsonFile(
649 FileType
.ChargingStationTemplate
,
652 (event
, filename
): void => {
653 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
656 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
658 } file have changed, reload`
660 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
664 this.stopAutomaticTransactionGenerator();
665 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
666 this.startAutomaticTransactionGenerator();
668 if (this.getEnableStatistics() === true) {
669 this.performanceStatistics
?.restart();
671 this.performanceStatistics
?.stop();
673 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
676 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
684 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
685 this.starting
= false;
687 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
690 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
694 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
695 if (this.started
=== true) {
696 if (this.stopping
=== false) {
697 this.stopping
= true;
698 await this.stopMessageSequence(reason
);
699 this.closeWSConnection();
700 if (this.getEnableStatistics() === true) {
701 this.performanceStatistics
?.stop();
703 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
704 this.templateFileWatcher
?.close();
705 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
706 delete this.bootNotificationResponse
;
707 this.started
= false;
708 this.saveConfiguration();
709 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
710 this.stopping
= false;
712 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
715 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
719 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
720 await this.stop(reason
);
721 await Utils
.sleep(this.stationInfo
.resetTime
);
726 public saveOcppConfiguration(): void {
727 if (this.getOcppPersistentConfiguration()) {
728 this.saveConfiguration();
732 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
733 return ChargingStationConfigurationUtils
.getConfigurationKey(
735 StandardParametersKey
.SupportedFeatureProfiles
736 )?.value
?.includes(featureProfile
);
739 public bufferMessage(message
: string): void {
740 this.messageBuffer
.add(message
);
743 public openWSConnection(
744 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
745 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
747 terminateOpened
: false,
750 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
751 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
752 if (this.started
=== false && this.starting
=== false) {
754 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
759 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
760 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
762 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
764 if (params
?.closeOpened
) {
765 this.closeWSConnection();
767 if (params
?.terminateOpened
) {
768 this.terminateWSConnection();
771 if (this.isWebSocketConnectionOpened() === true) {
773 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
779 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
782 this.wsConnection
= new WebSocket(
783 this.wsConnectionUrl
,
784 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
788 // Handle WebSocket message
789 this.wsConnection
.on(
791 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
793 // Handle WebSocket error
794 this.wsConnection
.on(
796 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
798 // Handle WebSocket close
799 this.wsConnection
.on(
801 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
803 // Handle WebSocket open
804 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
805 // Handle WebSocket ping
806 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
807 // Handle WebSocket pong
808 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
811 public closeWSConnection(): void {
812 if (this.isWebSocketConnectionOpened() === true) {
813 this.wsConnection
?.close();
814 this.wsConnection
= null;
818 public getAutomaticTransactionGeneratorConfiguration():
819 | AutomaticTransactionGeneratorConfiguration
821 const automaticTransactionGeneratorConfigurationFromFile
=
822 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
823 if (automaticTransactionGeneratorConfigurationFromFile
) {
824 return automaticTransactionGeneratorConfigurationFromFile
;
826 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
829 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
830 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
831 if (Utils
.isNotEmptyArray(connectorIds
)) {
832 for (const connectorId
of connectorIds
) {
833 this.automaticTransactionGenerator
?.startConnector(connectorId
);
836 this.automaticTransactionGenerator
?.start();
838 this.saveChargingStationAutomaticTransactionGeneratorConfiguration();
839 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
842 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
843 if (Utils
.isNotEmptyArray(connectorIds
)) {
844 for (const connectorId
of connectorIds
) {
845 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
848 this.automaticTransactionGenerator
?.stop();
850 this.saveChargingStationAutomaticTransactionGeneratorConfiguration();
851 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
854 public async stopTransactionOnConnector(
856 reason
= StopTransactionReason
.NONE
857 ): Promise
<StopTransactionResponse
> {
858 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
860 this.getBeginEndMeterValues() === true &&
861 this.getOcppStrictCompliance() === true &&
862 this.getOutOfOrderEndMeterValues() === false
864 // FIXME: Implement OCPP version agnostic helpers
865 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
868 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
870 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
872 RequestCommand
.METER_VALUES
,
876 meterValue
: [transactionEndMeterValue
],
880 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
882 RequestCommand
.STOP_TRANSACTION
,
885 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
891 private flushMessageBuffer(): void {
892 if (this.messageBuffer
.size
> 0) {
893 for (const message
of this.messageBuffer
.values()) {
895 let commandName
: RequestCommand
;
896 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
897 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
899 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
900 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
902 this.wsConnection
?.send(message
);
903 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
905 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
907 )} payload sent: ${message}`
909 this.messageBuffer
.delete(message
);
914 private getSupervisionUrlOcppConfiguration(): boolean {
915 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
918 private getSupervisionUrlOcppKey(): string {
919 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
922 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
923 let template
: ChargingStationTemplate
;
925 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
926 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
928 const measureId
= `${FileType.ChargingStationTemplate} read`;
929 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
930 template
= JSON
.parse(
931 fs
.readFileSync(this.templateFile
, 'utf8')
932 ) as ChargingStationTemplate
;
933 PerformanceStatistics
.endMeasure(measureId
, beginId
);
934 template
.templateHash
= crypto
935 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
936 .update(JSON
.stringify(template
))
938 this.sharedLRUCache
.setChargingStationTemplate(template
);
939 this.templateFileHash
= template
.templateHash
;
942 ErrorUtils
.handleFileException(
944 FileType
.ChargingStationTemplate
,
945 error
as NodeJS
.ErrnoException
,
952 private getStationInfoFromTemplate(): ChargingStationInfo
{
953 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
954 ChargingStationUtils
.checkTemplateFile(stationTemplate
, this.logPrefix(), this.templateFile
);
955 ChargingStationUtils
.warnTemplateKeysDeprecation(
960 if (stationTemplate
?.Connectors
) {
961 ChargingStationUtils
.checkConnectorsConfiguration(
967 const stationInfo
: ChargingStationInfo
=
968 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
969 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
970 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
974 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
975 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
976 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
977 stationTemplate
.power
= stationTemplate
.power
as number[];
978 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
979 stationInfo
.maximumPower
=
980 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
981 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
982 : stationTemplate
.power
[powerArrayRandomIndex
];
984 stationTemplate
.power
= stationTemplate
?.power
as number;
985 stationInfo
.maximumPower
=
986 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
987 ? stationTemplate
.power
* 1000
988 : stationTemplate
.power
;
990 stationInfo
.firmwareVersionPattern
=
991 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
993 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
994 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
997 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
999 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1002 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1009 stationTemplate
?.firmwareUpgrade
?? {}
1011 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
1012 ? stationTemplate
.resetTime
* 1000
1013 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1014 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1018 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1019 let stationInfo
: ChargingStationInfo
| undefined;
1020 if (this.getStationInfoPersistentConfiguration()) {
1021 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1023 delete stationInfo
?.infoHash
;
1029 private getStationInfo(): ChargingStationInfo
{
1030 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1031 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1033 // 1. charging station info from template
1034 // 2. charging station info from configuration file
1035 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1036 return stationInfoFromFile
;
1038 stationInfoFromFile
&&
1039 ChargingStationUtils
.propagateSerialNumber(
1040 this.getTemplateFromFile(),
1041 stationInfoFromFile
,
1042 stationInfoFromTemplate
1044 return stationInfoFromTemplate
;
1047 private saveStationInfo(): void {
1048 if (this.getStationInfoPersistentConfiguration()) {
1049 this.saveConfiguration();
1053 private getOcppPersistentConfiguration(): boolean {
1054 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1057 private getStationInfoPersistentConfiguration(): boolean {
1058 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1061 private handleUnsupportedVersion(version
: OCPPVersion
) {
1062 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1063 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1064 throw new BaseError(errorMsg
);
1067 private initialize(): void {
1068 const stationTemplate
= this.getTemplateFromFile();
1069 ChargingStationUtils
.checkTemplateFile(stationTemplate
, this.logPrefix(), this.templateFile
);
1070 this.configurationFile
= path
.join(
1071 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
1072 `${ChargingStationUtils.getHashId(this.index, stationTemplate)}.json`
1074 const chargingStationConfiguration
= this.getConfigurationFromFile();
1075 const featureFlag
= false;
1078 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1080 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1082 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1084 this.stationInfo
= this.getStationInfo();
1086 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1087 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1088 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1090 const patternGroup
: number | undefined =
1091 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1092 this.stationInfo
.firmwareVersion
?.split('.').length
;
1093 const match
= this.stationInfo
?.firmwareVersion
1094 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1095 ?.slice(1, patternGroup
+ 1);
1096 const patchLevelIndex
= match
.length
- 1;
1097 match
[patchLevelIndex
] = (
1098 Utils
.convertToInt(match
[patchLevelIndex
]) +
1099 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1101 this.stationInfo
.firmwareVersion
= match
?.join('.');
1103 this.saveStationInfo();
1104 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1105 if (this.getEnableStatistics() === true) {
1106 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1107 this.stationInfo
.hashId
,
1108 this.stationInfo
.chargingStationId
,
1109 this.configuredSupervisionUrl
1112 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1115 this.powerDivider
= this.getPowerDivider();
1116 // OCPP configuration
1117 this.ocppConfiguration
= this.getOcppConfiguration();
1118 this.initializeOcppConfiguration();
1119 this.initializeOcppServices();
1120 if (this.stationInfo
?.autoRegister
=== true) {
1121 this.bootNotificationResponse
= {
1122 currentTime
: new Date(),
1123 interval
: this.getHeartbeatInterval() / 1000,
1124 status: RegistrationStatusEnumType
.ACCEPTED
,
1129 private initializeOcppServices(): void {
1130 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1131 switch (ocppVersion
) {
1132 case OCPPVersion
.VERSION_16
:
1133 this.ocppIncomingRequestService
=
1134 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1135 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1136 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1139 case OCPPVersion
.VERSION_20
:
1140 case OCPPVersion
.VERSION_201
:
1141 this.ocppIncomingRequestService
=
1142 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1143 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1144 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1148 this.handleUnsupportedVersion(ocppVersion
);
1153 private initializeOcppConfiguration(): void {
1155 !ChargingStationConfigurationUtils
.getConfigurationKey(
1157 StandardParametersKey
.HeartbeatInterval
1160 ChargingStationConfigurationUtils
.addConfigurationKey(
1162 StandardParametersKey
.HeartbeatInterval
,
1167 !ChargingStationConfigurationUtils
.getConfigurationKey(
1169 StandardParametersKey
.HeartBeatInterval
1172 ChargingStationConfigurationUtils
.addConfigurationKey(
1174 StandardParametersKey
.HeartBeatInterval
,
1180 this.getSupervisionUrlOcppConfiguration() &&
1181 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1182 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1184 ChargingStationConfigurationUtils
.addConfigurationKey(
1186 this.getSupervisionUrlOcppKey(),
1187 this.configuredSupervisionUrl
.href
,
1191 !this.getSupervisionUrlOcppConfiguration() &&
1192 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1193 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1195 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1197 this.getSupervisionUrlOcppKey(),
1202 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1203 !ChargingStationConfigurationUtils
.getConfigurationKey(
1205 this.stationInfo
.amperageLimitationOcppKey
1208 ChargingStationConfigurationUtils
.addConfigurationKey(
1210 this.stationInfo
.amperageLimitationOcppKey
,
1212 this.stationInfo
.maximumAmperage
*
1213 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1218 !ChargingStationConfigurationUtils
.getConfigurationKey(
1220 StandardParametersKey
.SupportedFeatureProfiles
1223 ChargingStationConfigurationUtils
.addConfigurationKey(
1225 StandardParametersKey
.SupportedFeatureProfiles
,
1226 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1229 ChargingStationConfigurationUtils
.addConfigurationKey(
1231 StandardParametersKey
.NumberOfConnectors
,
1232 this.getNumberOfConnectors().toString(),
1237 !ChargingStationConfigurationUtils
.getConfigurationKey(
1239 StandardParametersKey
.MeterValuesSampledData
1242 ChargingStationConfigurationUtils
.addConfigurationKey(
1244 StandardParametersKey
.MeterValuesSampledData
,
1245 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1249 !ChargingStationConfigurationUtils
.getConfigurationKey(
1251 StandardParametersKey
.ConnectorPhaseRotation
1254 const connectorsPhaseRotation
: string[] = [];
1255 if (this.hasEvses
) {
1256 for (const evseStatus
of this.evses
.values()) {
1257 for (const connectorId
of evseStatus
.connectors
.keys()) {
1258 connectorsPhaseRotation
.push(
1259 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1264 for (const connectorId
of this.connectors
.keys()) {
1265 connectorsPhaseRotation
.push(
1266 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1270 ChargingStationConfigurationUtils
.addConfigurationKey(
1272 StandardParametersKey
.ConnectorPhaseRotation
,
1273 connectorsPhaseRotation
.toString()
1277 !ChargingStationConfigurationUtils
.getConfigurationKey(
1279 StandardParametersKey
.AuthorizeRemoteTxRequests
1282 ChargingStationConfigurationUtils
.addConfigurationKey(
1284 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1289 !ChargingStationConfigurationUtils
.getConfigurationKey(
1291 StandardParametersKey
.LocalAuthListEnabled
1293 ChargingStationConfigurationUtils
.getConfigurationKey(
1295 StandardParametersKey
.SupportedFeatureProfiles
1296 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1298 ChargingStationConfigurationUtils
.addConfigurationKey(
1300 StandardParametersKey
.LocalAuthListEnabled
,
1305 !ChargingStationConfigurationUtils
.getConfigurationKey(
1307 StandardParametersKey
.ConnectionTimeOut
1310 ChargingStationConfigurationUtils
.addConfigurationKey(
1312 StandardParametersKey
.ConnectionTimeOut
,
1313 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1316 this.saveOcppConfiguration();
1319 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1320 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1321 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1322 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1324 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1325 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1326 const evseStatus
= Utils
.cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1327 delete evseStatus
.connectorsStatus
;
1328 this.evses
.set(evseId
, {
1329 ...(evseStatus
as EvseStatus
),
1330 connectors
: new Map
<number, ConnectorStatus
>(
1331 evseStatusConfiguration
.connectorsStatus
.map((connectorStatus
, connectorId
) => [
1338 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1339 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1340 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1341 throw new BaseError(errorMsg
);
1343 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1344 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1345 throw new BaseError(errorMsg
);
1349 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1350 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1351 this.initializeConnectorsFromTemplate(stationTemplate
);
1352 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1353 this.initializeEvsesFromTemplate(stationTemplate
);
1354 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1355 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1356 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1357 throw new BaseError(errorMsg
);
1359 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1360 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1361 throw new BaseError(errorMsg
);
1365 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1366 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1367 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1368 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1369 throw new BaseError(errorMsg
);
1371 if (!stationTemplate
?.Connectors
[0]) {
1373 `${this.logPrefix()} Charging station information from template ${
1375 } with no connector id 0 configuration`
1378 if (stationTemplate
?.Connectors
) {
1379 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1380 ChargingStationUtils
.checkConnectorsConfiguration(
1385 const connectorsConfigHash
= crypto
1386 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1388 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1391 const connectorsConfigChanged
=
1392 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1393 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1394 connectorsConfigChanged
&& this.connectors
.clear();
1395 this.connectorsConfigurationHash
= connectorsConfigHash
;
1396 if (templateMaxConnectors
> 0) {
1397 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1399 connectorId
=== 0 &&
1400 (!stationTemplate
?.Connectors
[connectorId
] ||
1401 this.getUseConnectorId0(stationTemplate
) === false)
1405 const templateConnectorId
=
1406 connectorId
> 0 && stationTemplate
?.randomConnectors
1407 ? Utils
.getRandomInteger(templateMaxAvailableConnectors
, 1)
1409 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1410 ChargingStationUtils
.checkStationInfoConnectorStatus(
1411 templateConnectorId
,
1416 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1418 ChargingStationUtils
.initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1419 this.saveConnectorsStatus();
1422 `${this.logPrefix()} Charging station information from template ${
1424 } with no connectors configuration defined, cannot create connectors`
1430 `${this.logPrefix()} Charging station information from template ${
1432 } with no connectors configuration defined, using already defined connectors`
1437 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1438 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1439 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1440 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1441 throw new BaseError(errorMsg
);
1443 if (!stationTemplate
?.Evses
[0]) {
1445 `${this.logPrefix()} Charging station information from template ${
1447 } with no evse id 0 configuration`
1450 if (!stationTemplate
?.Evses
[0]?.Connectors
[0]) {
1452 `${this.logPrefix()} Charging station information from template ${
1454 } with evse id 0 with no connector id 0 configuration`
1457 if (stationTemplate
?.Evses
) {
1458 const evsesConfigHash
= crypto
1459 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1460 .update(`${JSON.stringify(stationTemplate?.Evses)}`)
1462 const evsesConfigChanged
=
1463 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1464 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1465 evsesConfigChanged
&& this.evses
.clear();
1466 this.evsesConfigurationHash
= evsesConfigHash
;
1467 const templateMaxEvses
= ChargingStationUtils
.getMaxNumberOfEvses(stationTemplate
?.Evses
);
1468 if (templateMaxEvses
> 0) {
1469 for (const evse
in stationTemplate
.Evses
) {
1470 const evseId
= Utils
.convertToInt(evse
);
1471 this.evses
.set(evseId
, {
1472 connectors
: ChargingStationUtils
.buildConnectorsMap(
1473 stationTemplate
?.Evses
[evse
]?.Connectors
,
1477 availability
: AvailabilityType
.Operative
,
1479 ChargingStationUtils
.initializeConnectorsMapStatus(
1480 this.evses
.get(evseId
)?.connectors
,
1484 this.saveEvsesStatus();
1487 `${this.logPrefix()} Charging station information from template ${
1489 } with no evses configuration defined, cannot create evses`
1495 `${this.logPrefix()} Charging station information from template ${
1497 } with no evses configuration defined, using already defined evses`
1502 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1503 let configuration
: ChargingStationConfiguration
| undefined;
1504 if (Utils
.isNotEmptyString(this.configurationFile
) && fs
.existsSync(this.configurationFile
)) {
1506 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1507 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1508 this.configurationFileHash
1511 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1512 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1513 configuration
= JSON
.parse(
1514 fs
.readFileSync(this.configurationFile
, 'utf8')
1515 ) as ChargingStationConfiguration
;
1516 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1517 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1518 this.configurationFileHash
= configuration
.configurationHash
;
1521 ErrorUtils
.handleFileException(
1522 this.configurationFile
,
1523 FileType
.ChargingStationConfiguration
,
1524 error
as NodeJS
.ErrnoException
,
1529 return configuration
;
1532 private saveChargingStationAutomaticTransactionGeneratorConfiguration(): void {
1533 this.saveConfiguration();
1536 private saveConnectorsStatus() {
1537 this.saveConfiguration();
1540 private saveEvsesStatus() {
1541 this.saveConfiguration();
1544 private saveConfiguration(): void {
1545 if (Utils
.isNotEmptyString(this.configurationFile
)) {
1547 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1548 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1550 let configurationData
: ChargingStationConfiguration
=
1551 Utils
.cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()) ?? {};
1552 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1553 configurationData
.stationInfo
= this.stationInfo
;
1555 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1556 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1558 configurationData
= merge
<ChargingStationConfiguration
>(
1560 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1562 if (this.connectors
.size
> 0) {
1563 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1565 if (this.evses
.size
> 0) {
1566 configurationData
.evsesStatus
= buildEvsesStatus(this);
1568 delete configurationData
.configurationHash
;
1569 const configurationHash
= crypto
1570 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1571 .update(JSON
.stringify(configurationData
))
1573 if (this.configurationFileHash
!== configurationHash
) {
1574 AsyncLock
.acquire(AsyncLockType
.configuration
)
1576 configurationData
.configurationHash
= configurationHash
;
1577 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1578 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1579 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1580 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1581 fs
.closeSync(fileDescriptor
);
1582 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1583 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1584 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1585 this.configurationFileHash
= configurationHash
;
1588 ErrorUtils
.handleFileException(
1589 this.configurationFile
,
1590 FileType
.ChargingStationConfiguration
,
1591 error
as NodeJS
.ErrnoException
,
1596 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1600 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1601 this.configurationFile
1606 ErrorUtils
.handleFileException(
1607 this.configurationFile
,
1608 FileType
.ChargingStationConfiguration
,
1609 error
as NodeJS
.ErrnoException
,
1615 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1620 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1621 return this.getTemplateFromFile()?.Configuration
;
1624 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1625 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1626 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1627 return { configurationKey
};
1632 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1633 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1634 this.getOcppConfigurationFromFile();
1635 if (!ocppConfiguration
) {
1636 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1638 return ocppConfiguration
;
1641 private async onOpen(): Promise
<void> {
1642 if (this.isWebSocketConnectionOpened() === true) {
1644 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1646 if (this.isRegistered() === false) {
1647 // Send BootNotification
1648 let registrationRetryCount
= 0;
1650 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1651 BootNotificationRequest
,
1652 BootNotificationResponse
1653 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1654 skipBufferingOnError
: true,
1656 if (this.isRegistered() === false) {
1657 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1659 this?.bootNotificationResponse
?.interval
1660 ? this.bootNotificationResponse
.interval
* 1000
1661 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1665 this.isRegistered() === false &&
1666 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1667 this.getRegistrationMaxRetries() === -1)
1670 if (this.isRegistered() === true) {
1671 if (this.inAcceptedState() === true) {
1672 await this.startMessageSequence();
1676 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1679 this.wsConnectionRestarted
= false;
1680 this.autoReconnectRetryCount
= 0;
1681 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1684 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1689 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1692 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1693 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1695 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1697 )}' and reason '${reason.toString()}'`
1699 this.autoReconnectRetryCount
= 0;
1704 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1706 )}' and reason '${reason.toString()}'`
1708 this.started
=== true && (await this.reconnect());
1711 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1714 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1715 const cachedRequest
= this.requests
.get(messageId
);
1716 if (Array.isArray(cachedRequest
) === true) {
1717 return cachedRequest
;
1719 throw new OCPPError(
1720 ErrorType
.PROTOCOL_ERROR
,
1721 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1723 )} is not an array`,
1725 cachedRequest
as JsonType
1729 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1730 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1731 if (this.getEnableStatistics() === true) {
1732 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1735 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1739 // Process the message
1740 await this.ocppIncomingRequestService
.incomingRequestHandler(
1748 private handleResponseMessage(response
: Response
): void {
1749 const [messageType
, messageId
, commandPayload
] = response
;
1750 if (this.requests
.has(messageId
) === false) {
1752 throw new OCPPError(
1753 ErrorType
.INTERNAL_ERROR
,
1754 `Response for unknown message id ${messageId}`,
1760 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1765 `${this.logPrefix()} << Command '${
1766 requestCommandName ?? Constants.UNKNOWN_COMMAND
1767 }' received response payload: ${JSON.stringify(response)}`
1769 responseCallback(commandPayload
, requestPayload
);
1772 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1773 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1774 if (this.requests
.has(messageId
) === false) {
1776 throw new OCPPError(
1777 ErrorType
.INTERNAL_ERROR
,
1778 `Error response for unknown message id ${messageId}`,
1780 { errorType
, errorMessage
, errorDetails
}
1783 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1785 `${this.logPrefix()} << Command '${
1786 requestCommandName ?? Constants.UNKNOWN_COMMAND
1787 }' received error response payload: ${JSON.stringify(errorResponse)}`
1789 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1792 private async onMessage(data
: RawData
): Promise
<void> {
1793 let request
: IncomingRequest
| Response
| ErrorResponse
;
1794 let messageType
: number;
1795 let errorMsg
: string;
1797 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1798 if (Array.isArray(request
) === true) {
1799 [messageType
] = request
;
1800 // Check the type of message
1801 switch (messageType
) {
1803 case MessageType
.CALL_MESSAGE
:
1804 await this.handleIncomingMessage(request
as IncomingRequest
);
1807 case MessageType
.CALL_RESULT_MESSAGE
:
1808 this.handleResponseMessage(request
as Response
);
1811 case MessageType
.CALL_ERROR_MESSAGE
:
1812 this.handleErrorMessage(request
as ErrorResponse
);
1816 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1817 errorMsg
= `Wrong message type ${messageType}`;
1818 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1819 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1821 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1823 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1828 let commandName
: IncomingRequestCommand
;
1829 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1830 let errorCallback
: ErrorCallback
;
1831 const [, messageId
] = request
;
1832 switch (messageType
) {
1833 case MessageType
.CALL_MESSAGE
:
1834 [, , commandName
] = request
as IncomingRequest
;
1836 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1838 case MessageType
.CALL_RESULT_MESSAGE
:
1839 case MessageType
.CALL_ERROR_MESSAGE
:
1840 if (this.requests
.has(messageId
) === true) {
1841 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1842 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1843 errorCallback(error
as OCPPError
, false);
1845 // Remove the request from the cache in case of error at response handling
1846 this.requests
.delete(messageId
);
1850 if (error
instanceof OCPPError
=== false) {
1852 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1853 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1854 }' message '${data.toString()}' handling is not an OCPPError:`,
1859 `${this.logPrefix()} Incoming OCPP command '${
1860 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1861 }' message '${data.toString()}'${
1862 messageType !== MessageType.CALL_MESSAGE
1863 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1865 } processing error:`,
1871 private onPing(): void {
1872 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1875 private onPong(): void {
1876 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1879 private onError(error
: WSError
): void {
1880 this.closeWSConnection();
1881 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1884 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1885 if (this.getMeteringPerTransaction() === true) {
1888 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1889 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1894 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1895 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1899 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
1900 return stationTemplate
?.useConnectorId0
?? true;
1903 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1904 if (this.hasEvses
) {
1905 for (const evseStatus
of this.evses
.values()) {
1906 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1907 if (connectorStatus
.transactionStarted
=== true) {
1908 await this.stopTransactionOnConnector(connectorId
, reason
);
1913 for (const connectorId
of this.connectors
.keys()) {
1914 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1915 await this.stopTransactionOnConnector(connectorId
, reason
);
1922 private getConnectionTimeout(): number {
1924 ChargingStationConfigurationUtils
.getConfigurationKey(
1926 StandardParametersKey
.ConnectionTimeOut
1931 ChargingStationConfigurationUtils
.getConfigurationKey(
1933 StandardParametersKey
.ConnectionTimeOut
1935 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1938 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1941 // -1 for unlimited, 0 for disabling
1942 private getAutoReconnectMaxRetries(): number | undefined {
1944 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
1949 private getRegistrationMaxRetries(): number | undefined {
1950 return this.stationInfo
.registrationMaxRetries
?? -1;
1953 private getPowerDivider(): number {
1954 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
1955 if (this.stationInfo
?.powerSharedByConnectors
) {
1956 powerDivider
= this.getNumberOfRunningTransactions();
1958 return powerDivider
;
1961 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1962 const maximumPower
= this.getMaximumPower(stationInfo
);
1963 switch (this.getCurrentOutType(stationInfo
)) {
1964 case CurrentType
.AC
:
1965 return ACElectricUtils
.amperagePerPhaseFromPower(
1966 this.getNumberOfPhases(stationInfo
),
1967 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
1968 this.getVoltageOut(stationInfo
)
1970 case CurrentType
.DC
:
1971 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1975 private getAmperageLimitation(): number | undefined {
1977 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1978 ChargingStationConfigurationUtils
.getConfigurationKey(
1980 this.stationInfo
.amperageLimitationOcppKey
1985 ChargingStationConfigurationUtils
.getConfigurationKey(
1987 this.stationInfo
.amperageLimitationOcppKey
1989 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1994 private async startMessageSequence(): Promise
<void> {
1995 if (this.stationInfo
?.autoRegister
=== true) {
1996 await this.ocppRequestService
.requestHandler
<
1997 BootNotificationRequest
,
1998 BootNotificationResponse
1999 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2000 skipBufferingOnError
: true,
2003 // Start WebSocket ping
2004 this.startWebSocketPing();
2006 this.startHeartbeat();
2007 // Initialize connectors status
2008 if (this.hasEvses
) {
2009 for (const [evseId
, evseStatus
] of this.evses
) {
2011 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2012 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2017 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2020 connectorBootStatus
,
2027 for (const connectorId
of this.connectors
.keys()) {
2028 if (connectorId
> 0) {
2029 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2032 this.getConnectorStatus(connectorId
)
2034 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2038 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2039 await this.ocppRequestService
.requestHandler
<
2040 FirmwareStatusNotificationRequest
,
2041 FirmwareStatusNotificationResponse
2042 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2043 status: FirmwareStatus
.Installed
,
2045 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2049 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2050 this.startAutomaticTransactionGenerator();
2052 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2055 private async stopMessageSequence(
2056 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2058 // Stop WebSocket ping
2059 this.stopWebSocketPing();
2061 this.stopHeartbeat();
2062 // Stop ongoing transactions
2063 if (this.automaticTransactionGenerator
?.started
=== true) {
2064 this.stopAutomaticTransactionGenerator();
2066 await this.stopRunningTransactions(reason
);
2068 if (this.hasEvses
) {
2069 for (const [evseId
, evseStatus
] of this.evses
) {
2071 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2072 await this.ocppRequestService
.requestHandler
<
2073 StatusNotificationRequest
,
2074 StatusNotificationResponse
2077 RequestCommand
.STATUS_NOTIFICATION
,
2078 OCPPServiceUtils
.buildStatusNotificationRequest(
2081 ConnectorStatusEnum
.Unavailable
,
2085 delete connectorStatus
?.status;
2090 for (const connectorId
of this.connectors
.keys()) {
2091 if (connectorId
> 0) {
2092 await this.ocppRequestService
.requestHandler
<
2093 StatusNotificationRequest
,
2094 StatusNotificationResponse
2097 RequestCommand
.STATUS_NOTIFICATION
,
2098 OCPPServiceUtils
.buildStatusNotificationRequest(
2101 ConnectorStatusEnum
.Unavailable
2104 delete this.getConnectorStatus(connectorId
)?.status;
2110 private startWebSocketPing(): void {
2111 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2113 StandardParametersKey
.WebSocketPingInterval
2115 ? Utils
.convertToInt(
2116 ChargingStationConfigurationUtils
.getConfigurationKey(
2118 StandardParametersKey
.WebSocketPingInterval
2122 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2123 this.webSocketPingSetInterval
= setInterval(() => {
2124 if (this.isWebSocketConnectionOpened() === true) {
2125 this.wsConnection
?.ping();
2127 }, webSocketPingInterval
* 1000);
2129 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
2130 webSocketPingInterval
2133 } else if (this.webSocketPingSetInterval
) {
2135 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
2136 webSocketPingInterval
2141 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2146 private stopWebSocketPing(): void {
2147 if (this.webSocketPingSetInterval
) {
2148 clearInterval(this.webSocketPingSetInterval
);
2149 delete this.webSocketPingSetInterval
;
2153 private getConfiguredSupervisionUrl(): URL
{
2154 let configuredSupervisionUrl
: string;
2155 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2156 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
2157 let configuredSupervisionUrlIndex
: number;
2158 switch (Configuration
.getSupervisionUrlDistribution()) {
2159 case SupervisionUrlDistribution
.RANDOM
:
2160 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2162 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2163 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2165 Object.values(SupervisionUrlDistribution
).includes(
2166 Configuration
.getSupervisionUrlDistribution()
2169 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2170 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2173 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2176 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
];
2178 configuredSupervisionUrl
= supervisionUrls
as string;
2180 if (Utils
.isNotEmptyString(configuredSupervisionUrl
)) {
2181 return new URL(configuredSupervisionUrl
);
2183 const errorMsg
= 'No supervision url(s) configured';
2184 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2185 throw new BaseError(`${errorMsg}`);
2188 private stopHeartbeat(): void {
2189 if (this.heartbeatSetInterval
) {
2190 clearInterval(this.heartbeatSetInterval
);
2191 delete this.heartbeatSetInterval
;
2195 private terminateWSConnection(): void {
2196 if (this.isWebSocketConnectionOpened() === true) {
2197 this.wsConnection
?.terminate();
2198 this.wsConnection
= null;
2202 private getReconnectExponentialDelay(): boolean {
2203 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2206 private async reconnect(): Promise
<void> {
2207 // Stop WebSocket ping
2208 this.stopWebSocketPing();
2210 this.stopHeartbeat();
2211 // Stop the ATG if needed
2212 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2213 this.stopAutomaticTransactionGenerator();
2216 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2217 this.getAutoReconnectMaxRetries() === -1
2219 this.autoReconnectRetryCount
++;
2220 const reconnectDelay
= this.getReconnectExponentialDelay()
2221 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2222 : this.getConnectionTimeout() * 1000;
2223 const reconnectDelayWithdraw
= 1000;
2224 const reconnectTimeout
=
2225 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2226 ? reconnectDelay
- reconnectDelayWithdraw
2229 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2232 )}ms, timeout ${reconnectTimeout}ms`
2234 await Utils
.sleep(reconnectDelay
);
2236 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2238 this.openWSConnection(
2240 ...(this.stationInfo
?.wsOptions
?? {}),
2241 handshakeTimeout
: reconnectTimeout
,
2243 { closeOpened
: true }
2245 this.wsConnectionRestarted
= true;
2246 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2248 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2249 this.autoReconnectRetryCount
2250 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`