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';
13 AutomaticTransactionGenerator
,
14 ChargingStationConfigurationUtils
,
16 ChargingStationWorkerBroadcastChannel
,
22 // OCPP16IncomingRequestService,
24 // OCPP16ResponseService,
26 OCPP20IncomingRequestService
,
28 // OCPP20ResponseService,
29 type OCPPIncomingRequestService
,
30 type OCPPRequestService
,
33 import { OCPP16IncomingRequestService
} from
'./ocpp/1.6/OCPP16IncomingRequestService';
34 import { OCPP16ResponseService
} from
'./ocpp/1.6/OCPP16ResponseService';
35 import { OCPP20ResponseService
} from
'./ocpp/2.0/OCPP20ResponseService';
36 import { OCPPServiceUtils
} from
'./ocpp/OCPPServiceUtils';
37 import { BaseError
, OCPPError
} from
'../exception';
38 import { PerformanceStatistics
} from
'../performance';
40 type AutomaticTransactionGeneratorConfiguration
,
42 type BootNotificationRequest
,
43 type BootNotificationResponse
,
45 type ChargingStationConfiguration
,
46 type ChargingStationInfo
,
47 type ChargingStationOcppConfiguration
,
48 type ChargingStationTemplate
,
56 type EvseStatusConfiguration
,
59 type FirmwareStatusNotificationRequest
,
60 type FirmwareStatusNotificationResponse
,
62 type HeartbeatRequest
,
63 type HeartbeatResponse
,
65 type IncomingRequestCommand
,
70 type MeterValuesRequest
,
71 type MeterValuesResponse
,
75 RegistrationStatusEnumType
,
78 StandardParametersKey
,
79 type StatusNotificationRequest
,
80 type StatusNotificationResponse
,
81 StopTransactionReason
,
82 type StopTransactionRequest
,
83 type StopTransactionResponse
,
84 SupervisionUrlDistribution
,
85 SupportedFeatureProfiles
,
88 WebSocketCloseEventStatusCode
,
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 ? ChargingStationConfigurationUtils.getConfigurationKey(
166 this.getSupervisionUrlOcppKey()
168 : this.configuredSupervisionUrl.href
169 }/${this.stationInfo.chargingStationId}`
173 public logPrefix
= (): string => {
174 return Utils
.logPrefix(
176 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId)
177 ? this?.stationInfo?.chargingStationId
178 : ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())) ??
179 'Error at building log prefix'
184 public hasIdTags(): boolean {
185 const idTagsFile
= ChargingStationUtils
.getIdTagsFile(this.stationInfo
);
186 return Utils
.isNotEmptyArray(this.idTagsCache
.getIdTags(idTagsFile
));
189 public getEnableStatistics(): boolean {
190 return this.stationInfo
.enableStatistics
?? false;
193 public getMustAuthorizeAtRemoteStart(): boolean {
194 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
197 public getPayloadSchemaValidation(): boolean {
198 return this.stationInfo
.payloadSchemaValidation
?? true;
201 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
202 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
203 switch (this.getCurrentOutType(stationInfo
)) {
205 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
206 ? localStationInfo
.numberOfPhases
213 public isWebSocketConnectionOpened(): boolean {
214 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
217 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
218 return this?.bootNotificationResponse
?.status;
221 public isInUnknownState(): boolean {
222 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
225 public isInPendingState(): boolean {
226 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
229 public isInAcceptedState(): boolean {
230 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
233 public isInRejectedState(): boolean {
234 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
237 public isRegistered(): boolean {
239 this.isInUnknownState() === false &&
240 (this.isInAcceptedState() === true || this.isInPendingState() === true)
244 public isChargingStationAvailable(): boolean {
245 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
248 public hasConnector(connectorId
: number): boolean {
250 for (const evseStatus
of this.evses
.values()) {
251 if (evseStatus
.connectors
.has(connectorId
)) {
257 return this.connectors
.has(connectorId
);
260 public isConnectorAvailable(connectorId
: number): boolean {
263 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
267 public getNumberOfConnectors(): number {
269 if (this.evses
.size
=== 0) {
270 throw new BaseError('Evses not initialized, cannot get number of connectors');
272 let numberOfConnectors
= 0;
273 for (const [evseId
, evseStatus
] of this.evses
) {
275 numberOfConnectors
+= evseStatus
.connectors
.size
;
278 return numberOfConnectors
;
280 if (this.connectors
.size
=== 0) {
281 throw new BaseError('Connectors not initialized, cannot get number of connectors');
283 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
286 public getNumberOfEvses(): number {
287 if (this.evses
.size
=== 0) {
288 throw new BaseError('Evses not initialized, cannot get number of evses');
290 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
293 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
295 for (const evseStatus
of this.evses
.values()) {
296 if (evseStatus
.connectors
.has(connectorId
)) {
297 return evseStatus
.connectors
.get(connectorId
);
302 return this.connectors
.get(connectorId
);
305 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
306 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
309 public getOcppStrictCompliance(): boolean {
310 return this.stationInfo
?.ocppStrictCompliance
?? false;
313 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
314 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
315 this.getCurrentOutType(stationInfo
),
319 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
320 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
321 ? localStationInfo
.voltageOut
325 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
326 const localStationInfo
= stationInfo
?? this.stationInfo
;
327 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
330 public getConnectorMaximumAvailablePower(connectorId
: number): number {
331 let connectorAmperageLimitationPowerLimit
: number;
333 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
334 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
336 connectorAmperageLimitationPowerLimit
=
337 (this.getCurrentOutType() === CurrentType
.AC
338 ? ACElectricUtils
.powerTotal(
339 this.getNumberOfPhases(),
340 this.getVoltageOut(),
341 this.getAmperageLimitation() *
342 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
344 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
347 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
348 const connectorChargingProfilesPowerLimit
=
349 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
351 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
352 isNaN(connectorAmperageLimitationPowerLimit
)
354 : connectorAmperageLimitationPowerLimit
,
355 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
359 public getTransactionIdTag(transactionId
: number): string | undefined {
361 for (const evseStatus
of this.evses
.values()) {
362 for (const connectorStatus
of evseStatus
.connectors
.values()) {
363 if (connectorStatus
.transactionId
=== transactionId
) {
364 return connectorStatus
.transactionIdTag
;
369 for (const connectorId
of this.connectors
.keys()) {
372 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
374 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
380 public getNumberOfRunningTransactions(): number {
383 for (const evseStatus
of this.evses
.values()) {
384 for (const connectorStatus
of evseStatus
.connectors
.values()) {
385 if (connectorStatus
.transactionStarted
=== true) {
391 for (const connectorId
of this.connectors
.keys()) {
392 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
400 public getOutOfOrderEndMeterValues(): boolean {
401 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
404 public getBeginEndMeterValues(): boolean {
405 return this.stationInfo
?.beginEndMeterValues
?? false;
408 public getMeteringPerTransaction(): boolean {
409 return this.stationInfo
?.meteringPerTransaction
?? true;
412 public getTransactionDataMeterValues(): boolean {
413 return this.stationInfo
?.transactionDataMeterValues
?? false;
416 public getMainVoltageMeterValues(): boolean {
417 return this.stationInfo
?.mainVoltageMeterValues
?? true;
420 public getPhaseLineToLineVoltageMeterValues(): boolean {
421 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
424 public getCustomValueLimitationMeterValues(): boolean {
425 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
428 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
430 for (const evseStatus
of this.evses
.values()) {
431 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
432 if (connectorStatus
.transactionId
=== transactionId
) {
438 for (const connectorId
of this.connectors
.keys()) {
441 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
449 public getEnergyActiveImportRegisterByTransactionId(
450 transactionId
: number,
453 return this.getEnergyActiveImportRegister(
454 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
459 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
460 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
463 public getAuthorizeRemoteTxRequests(): boolean {
464 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
466 StandardParametersKey
.AuthorizeRemoteTxRequests
468 return authorizeRemoteTxRequests
469 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
473 public getLocalAuthListEnabled(): boolean {
474 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
476 StandardParametersKey
.LocalAuthListEnabled
478 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
481 public getHeartbeatInterval(): number {
482 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
484 StandardParametersKey
.HeartbeatInterval
486 if (HeartbeatInterval
) {
487 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
489 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
491 StandardParametersKey
.HeartBeatInterval
493 if (HeartBeatInterval
) {
494 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
496 this.stationInfo
?.autoRegister
=== false &&
498 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
499 Constants.DEFAULT_HEARTBEAT_INTERVAL
502 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
505 public setSupervisionUrl(url
: string): void {
507 this.getSupervisionUrlOcppConfiguration() &&
508 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey())
510 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
512 this.getSupervisionUrlOcppKey(),
516 this.stationInfo
.supervisionUrls
= url
;
517 this.saveStationInfo();
518 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
522 public startHeartbeat(): void {
523 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
524 this.heartbeatSetInterval
= setInterval(() => {
525 this.ocppRequestService
526 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
529 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
533 }, this.getHeartbeatInterval());
535 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
536 this.getHeartbeatInterval()
539 } else if (this.heartbeatSetInterval
) {
541 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
542 this.getHeartbeatInterval()
547 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
552 public restartHeartbeat(): void {
554 this.stopHeartbeat();
556 this.startHeartbeat();
559 public restartWebSocketPing(): void {
560 // Stop WebSocket ping
561 this.stopWebSocketPing();
562 // Start WebSocket ping
563 this.startWebSocketPing();
566 public startMeterValues(connectorId
: number, interval
: number): void {
567 if (connectorId
=== 0) {
569 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
573 if (!this.getConnectorStatus(connectorId
)) {
575 `${this.logPrefix()} Trying to start MeterValues on non existing connector id ${connectorId.toString()}`
579 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
581 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
585 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
586 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
589 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
594 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
595 // FIXME: Implement OCPP version agnostic helpers
596 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
599 this.getConnectorStatus(connectorId
).transactionId
,
602 this.ocppRequestService
603 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
605 RequestCommand
.METER_VALUES
,
608 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
609 meterValue
: [meterValue
],
614 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
621 `${this.logPrefix()} Charging station ${
622 StandardParametersKey.MeterValueSampleInterval
623 } configuration set to ${interval}, not sending MeterValues`
628 public stopMeterValues(connectorId
: number) {
629 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
630 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
634 public start(): void {
635 if (this.started
=== false) {
636 if (this.starting
=== false) {
637 this.starting
= true;
638 if (this.getEnableStatistics() === true) {
639 this.performanceStatistics
?.start();
641 this.openWSConnection();
642 // Monitor charging station template file
643 this.templateFileWatcher
= FileUtils
.watchJsonFile(
645 FileType
.ChargingStationTemplate
,
648 (event
, filename
): void => {
649 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
652 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
654 } file have changed, reload`
656 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
660 this.stopAutomaticTransactionGenerator();
662 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
664 this.startAutomaticTransactionGenerator();
666 if (this.getEnableStatistics() === true) {
667 this.performanceStatistics
?.restart();
669 this.performanceStatistics
?.stop();
671 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
674 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
682 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
683 this.starting
= false;
685 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
688 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
692 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
693 if (this.started
=== true) {
694 if (this.stopping
=== false) {
695 this.stopping
= true;
696 await this.stopMessageSequence(reason
);
697 this.closeWSConnection();
698 if (this.getEnableStatistics() === true) {
699 this.performanceStatistics
?.stop();
701 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
702 this.templateFileWatcher
?.close();
703 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
704 delete this.bootNotificationResponse
;
705 this.started
= false;
706 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
707 this.stopping
= false;
709 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
712 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
716 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
717 await this.stop(reason
);
718 await Utils
.sleep(this.stationInfo
.resetTime
);
723 public saveOcppConfiguration(): void {
724 if (this.getOcppPersistentConfiguration()) {
725 this.saveConfiguration();
729 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
730 return ChargingStationConfigurationUtils
.getConfigurationKey(
732 StandardParametersKey
.SupportedFeatureProfiles
733 )?.value
?.includes(featureProfile
);
736 public bufferMessage(message
: string): void {
737 this.messageBuffer
.add(message
);
740 public openWSConnection(
741 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
742 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
744 terminateOpened
: false,
747 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
748 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
749 if (this.started
=== false && this.starting
=== false) {
751 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
756 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
757 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
759 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
761 if (params
?.closeOpened
) {
762 this.closeWSConnection();
764 if (params
?.terminateOpened
) {
765 this.terminateWSConnection();
768 if (this.isWebSocketConnectionOpened() === true) {
770 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
776 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
779 this.wsConnection
= new WebSocket(
780 this.wsConnectionUrl
,
781 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
785 // Handle WebSocket message
786 this.wsConnection
.on(
788 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
790 // Handle WebSocket error
791 this.wsConnection
.on(
793 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
795 // Handle WebSocket close
796 this.wsConnection
.on(
798 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
800 // Handle WebSocket open
801 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
802 // Handle WebSocket ping
803 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
804 // Handle WebSocket pong
805 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
808 public closeWSConnection(): void {
809 if (this.isWebSocketConnectionOpened() === true) {
810 this.wsConnection
?.close();
811 this.wsConnection
= null;
815 public startAutomaticTransactionGenerator(
816 connectorIds
?: number[],
817 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
819 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
820 automaticTransactionGeneratorConfiguration
??
821 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
824 if (Utils
.isNotEmptyArray(connectorIds
)) {
825 for (const connectorId
of connectorIds
) {
826 this.automaticTransactionGenerator
?.startConnector(connectorId
);
829 this.automaticTransactionGenerator
?.start();
831 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
834 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
835 if (Utils
.isNotEmptyArray(connectorIds
)) {
836 for (const connectorId
of connectorIds
) {
837 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
840 this.automaticTransactionGenerator
?.stop();
842 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
845 public async stopTransactionOnConnector(
847 reason
= StopTransactionReason
.NONE
848 ): Promise
<StopTransactionResponse
> {
849 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
851 this.getBeginEndMeterValues() === true &&
852 this.getOcppStrictCompliance() === true &&
853 this.getOutOfOrderEndMeterValues() === false
855 // FIXME: Implement OCPP version agnostic helpers
856 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
859 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
861 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
863 RequestCommand
.METER_VALUES
,
867 meterValue
: [transactionEndMeterValue
],
871 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
873 RequestCommand
.STOP_TRANSACTION
,
876 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
882 private flushMessageBuffer(): void {
883 if (this.messageBuffer
.size
> 0) {
884 for (const message
of this.messageBuffer
.values()) {
886 let commandName
: RequestCommand
;
887 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
888 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
890 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
891 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
893 this.wsConnection
?.send(message
);
894 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
896 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
898 )} payload sent: ${message}`
900 this.messageBuffer
.delete(message
);
905 private getSupervisionUrlOcppConfiguration(): boolean {
906 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
909 private getSupervisionUrlOcppKey(): string {
910 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
913 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
914 let template
: ChargingStationTemplate
;
916 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
917 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
919 const measureId
= `${FileType.ChargingStationTemplate} read`;
920 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
921 template
= JSON
.parse(
922 fs
.readFileSync(this.templateFile
, 'utf8')
923 ) as ChargingStationTemplate
;
924 PerformanceStatistics
.endMeasure(measureId
, beginId
);
925 template
.templateHash
= crypto
926 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
927 .update(JSON
.stringify(template
))
929 this.sharedLRUCache
.setChargingStationTemplate(template
);
930 this.templateFileHash
= template
.templateHash
;
933 FileUtils
.handleFileException(
935 FileType
.ChargingStationTemplate
,
936 error
as NodeJS
.ErrnoException
,
943 private getStationInfoFromTemplate(): ChargingStationInfo
{
944 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
945 ChargingStationUtils
.checkTemplateFile(stationTemplate
, this.logPrefix(), this.templateFile
);
946 ChargingStationUtils
.warnTemplateKeysDeprecation(
951 if (stationTemplate
?.Connectors
) {
952 ChargingStationUtils
.checkConnectorsConfiguration(
958 const stationInfo
: ChargingStationInfo
=
959 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
960 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
961 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
965 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
966 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
967 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
968 stationTemplate
.power
= stationTemplate
.power
as number[];
969 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
970 stationInfo
.maximumPower
=
971 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
972 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
973 : stationTemplate
.power
[powerArrayRandomIndex
];
975 stationTemplate
.power
= stationTemplate
?.power
as number;
976 stationInfo
.maximumPower
=
977 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
978 ? stationTemplate
.power
* 1000
979 : stationTemplate
.power
;
981 stationInfo
.firmwareVersionPattern
=
982 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
984 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
985 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
988 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
990 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
993 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1000 stationTemplate
?.firmwareUpgrade
?? {}
1002 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
1003 ? stationTemplate
.resetTime
* 1000
1004 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1005 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1009 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1010 let stationInfo
: ChargingStationInfo
| undefined;
1011 if (this.getStationInfoPersistentConfiguration()) {
1012 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1014 delete stationInfo
?.infoHash
;
1020 private getStationInfo(): ChargingStationInfo
{
1021 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1022 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1024 // 1. charging station info from template
1025 // 2. charging station info from configuration file
1026 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1027 return stationInfoFromFile
;
1029 stationInfoFromFile
&&
1030 ChargingStationUtils
.propagateSerialNumber(
1031 this.getTemplateFromFile(),
1032 stationInfoFromFile
,
1033 stationInfoFromTemplate
1035 return stationInfoFromTemplate
;
1038 private saveStationInfo(): void {
1039 if (this.getStationInfoPersistentConfiguration()) {
1040 this.saveConfiguration();
1044 private getOcppPersistentConfiguration(): boolean {
1045 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1048 private getStationInfoPersistentConfiguration(): boolean {
1049 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1052 private handleUnsupportedVersion(version
: OCPPVersion
) {
1053 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1054 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1055 throw new BaseError(errorMsg
);
1058 private initialize(): void {
1059 const stationTemplate
= this.getTemplateFromFile();
1060 ChargingStationUtils
.checkTemplateFile(stationTemplate
, this.logPrefix(), this.templateFile
);
1061 this.configurationFile
= path
.join(
1062 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
1063 `${ChargingStationUtils.getHashId(this.index, stationTemplate)}.json`
1065 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1066 this.stationInfo
= this.getStationInfo();
1068 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1069 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1070 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1072 const patternGroup
: number | undefined =
1073 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1074 this.stationInfo
.firmwareVersion
?.split('.').length
;
1075 const match
= this.stationInfo
?.firmwareVersion
1076 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1077 ?.slice(1, patternGroup
+ 1);
1078 const patchLevelIndex
= match
.length
- 1;
1079 match
[patchLevelIndex
] = (
1080 Utils
.convertToInt(match
[patchLevelIndex
]) +
1081 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1083 this.stationInfo
.firmwareVersion
= match
?.join('.');
1085 this.saveStationInfo();
1086 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1087 if (this.getEnableStatistics() === true) {
1088 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1089 this.stationInfo
.hashId
,
1090 this.stationInfo
.chargingStationId
,
1091 this.configuredSupervisionUrl
1094 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1097 this.powerDivider
= this.getPowerDivider();
1098 // OCPP configuration
1099 this.ocppConfiguration
= this.getOcppConfiguration();
1100 this.initializeOcppConfiguration();
1101 this.initializeOcppServices();
1102 if (this.stationInfo
?.autoRegister
=== true) {
1103 this.bootNotificationResponse
= {
1104 currentTime
: new Date(),
1105 interval
: this.getHeartbeatInterval() / 1000,
1106 status: RegistrationStatusEnumType
.ACCEPTED
,
1111 private initializeOcppServices(): void {
1112 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1113 switch (ocppVersion
) {
1114 case OCPPVersion
.VERSION_16
:
1115 this.ocppIncomingRequestService
=
1116 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1117 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1118 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1121 case OCPPVersion
.VERSION_20
:
1122 case OCPPVersion
.VERSION_201
:
1123 this.ocppIncomingRequestService
=
1124 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1125 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1126 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1130 this.handleUnsupportedVersion(ocppVersion
);
1135 private initializeOcppConfiguration(): void {
1137 !ChargingStationConfigurationUtils
.getConfigurationKey(
1139 StandardParametersKey
.HeartbeatInterval
1142 ChargingStationConfigurationUtils
.addConfigurationKey(
1144 StandardParametersKey
.HeartbeatInterval
,
1149 !ChargingStationConfigurationUtils
.getConfigurationKey(
1151 StandardParametersKey
.HeartBeatInterval
1154 ChargingStationConfigurationUtils
.addConfigurationKey(
1156 StandardParametersKey
.HeartBeatInterval
,
1162 this.getSupervisionUrlOcppConfiguration() &&
1163 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1164 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1166 ChargingStationConfigurationUtils
.addConfigurationKey(
1168 this.getSupervisionUrlOcppKey(),
1169 this.configuredSupervisionUrl
.href
,
1173 !this.getSupervisionUrlOcppConfiguration() &&
1174 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1175 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1177 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1179 this.getSupervisionUrlOcppKey(),
1184 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1185 !ChargingStationConfigurationUtils
.getConfigurationKey(
1187 this.stationInfo
.amperageLimitationOcppKey
1190 ChargingStationConfigurationUtils
.addConfigurationKey(
1192 this.stationInfo
.amperageLimitationOcppKey
,
1194 this.stationInfo
.maximumAmperage
*
1195 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1200 !ChargingStationConfigurationUtils
.getConfigurationKey(
1202 StandardParametersKey
.SupportedFeatureProfiles
1205 ChargingStationConfigurationUtils
.addConfigurationKey(
1207 StandardParametersKey
.SupportedFeatureProfiles
,
1208 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1211 ChargingStationConfigurationUtils
.addConfigurationKey(
1213 StandardParametersKey
.NumberOfConnectors
,
1214 this.getNumberOfConnectors().toString(),
1219 !ChargingStationConfigurationUtils
.getConfigurationKey(
1221 StandardParametersKey
.MeterValuesSampledData
1224 ChargingStationConfigurationUtils
.addConfigurationKey(
1226 StandardParametersKey
.MeterValuesSampledData
,
1227 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1231 !ChargingStationConfigurationUtils
.getConfigurationKey(
1233 StandardParametersKey
.ConnectorPhaseRotation
1236 const connectorsPhaseRotation
: string[] = [];
1237 if (this.hasEvses
) {
1238 for (const evseStatus
of this.evses
.values()) {
1239 for (const connectorId
of evseStatus
.connectors
.keys()) {
1240 connectorsPhaseRotation
.push(
1241 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1246 for (const connectorId
of this.connectors
.keys()) {
1247 connectorsPhaseRotation
.push(
1248 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1252 ChargingStationConfigurationUtils
.addConfigurationKey(
1254 StandardParametersKey
.ConnectorPhaseRotation
,
1255 connectorsPhaseRotation
.toString()
1259 !ChargingStationConfigurationUtils
.getConfigurationKey(
1261 StandardParametersKey
.AuthorizeRemoteTxRequests
1264 ChargingStationConfigurationUtils
.addConfigurationKey(
1266 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1271 !ChargingStationConfigurationUtils
.getConfigurationKey(
1273 StandardParametersKey
.LocalAuthListEnabled
1275 ChargingStationConfigurationUtils
.getConfigurationKey(
1277 StandardParametersKey
.SupportedFeatureProfiles
1278 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1280 ChargingStationConfigurationUtils
.addConfigurationKey(
1282 StandardParametersKey
.LocalAuthListEnabled
,
1287 !ChargingStationConfigurationUtils
.getConfigurationKey(
1289 StandardParametersKey
.ConnectionTimeOut
1292 ChargingStationConfigurationUtils
.addConfigurationKey(
1294 StandardParametersKey
.ConnectionTimeOut
,
1295 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1298 this.saveOcppConfiguration();
1301 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1302 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1303 this.initializeConnectorsFromTemplate(stationTemplate
);
1304 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1305 this.initializeEvsesFromTemplate(stationTemplate
);
1306 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1307 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1308 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1309 throw new BaseError(errorMsg
);
1311 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1312 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1313 throw new BaseError(errorMsg
);
1317 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1318 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1319 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1320 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1321 throw new BaseError(errorMsg
);
1323 if (!stationTemplate
?.Connectors
[0]) {
1325 `${this.logPrefix()} Charging station information from template ${
1327 } with no connector id 0 configuration`
1330 if (stationTemplate
?.Connectors
) {
1331 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1332 ChargingStationUtils
.checkConnectorsConfiguration(
1337 const connectorsConfigHash
= crypto
1338 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1340 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1343 const connectorsConfigChanged
=
1344 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1345 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1346 connectorsConfigChanged
&& this.connectors
.clear();
1347 this.connectorsConfigurationHash
= connectorsConfigHash
;
1348 if (templateMaxConnectors
> 0) {
1349 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1351 connectorId
=== 0 &&
1352 (!stationTemplate
?.Connectors
[connectorId
] ||
1353 this.getUseConnectorId0(stationTemplate
) === false)
1357 const templateConnectorId
=
1358 connectorId
> 0 && stationTemplate
?.randomConnectors
1359 ? Utils
.getRandomInteger(templateMaxAvailableConnectors
, 1)
1361 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1362 ChargingStationUtils
.checkStationInfoConnectorStatus(
1363 templateConnectorId
,
1368 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1370 ChargingStationUtils
.initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1371 this.saveConnectorsStatus();
1374 `${this.logPrefix()} Charging station information from template ${
1376 } with no connectors configuration defined, cannot create connectors`
1382 `${this.logPrefix()} Charging station information from template ${
1384 } with no connectors configuration defined, using already defined connectors`
1389 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1390 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1391 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1392 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1393 throw new BaseError(errorMsg
);
1395 if (!stationTemplate
?.Evses
[0]) {
1397 `${this.logPrefix()} Charging station information from template ${
1399 } with no evse id 0 configuration`
1402 if (!stationTemplate
?.Evses
[0]?.Connectors
[0]) {
1404 `${this.logPrefix()} Charging station information from template ${
1406 } with evse id 0 with no connector id 0 configuration`
1409 if (stationTemplate
?.Evses
) {
1410 const evsesConfigHash
= crypto
1411 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1412 .update(`${JSON.stringify(stationTemplate?.Evses)}`)
1414 const evsesConfigChanged
=
1415 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1416 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1417 evsesConfigChanged
&& this.evses
.clear();
1418 this.evsesConfigurationHash
= evsesConfigHash
;
1419 const templateMaxEvses
= ChargingStationUtils
.getMaxNumberOfEvses(stationTemplate
?.Evses
);
1420 if (templateMaxEvses
> 0) {
1421 for (const evse
in stationTemplate
.Evses
) {
1422 const evseId
= Utils
.convertToInt(evse
);
1423 this.evses
.set(evseId
, {
1424 connectors
: ChargingStationUtils
.buildConnectorsMap(
1425 stationTemplate
?.Evses
[evse
]?.Connectors
,
1429 availability
: AvailabilityType
.Operative
,
1431 ChargingStationUtils
.initializeConnectorsMapStatus(
1432 this.evses
.get(evseId
)?.connectors
,
1436 this.saveEvsesStatus();
1439 `${this.logPrefix()} Charging station information from template ${
1441 } with no evses configuration defined, cannot create evses`
1447 `${this.logPrefix()} Charging station information from template ${
1449 } with no evses configuration defined, using already defined evses`
1454 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1455 let configuration
: ChargingStationConfiguration
| undefined;
1456 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1458 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1459 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1460 this.configurationFileHash
1463 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1464 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1465 configuration
= JSON
.parse(
1466 fs
.readFileSync(this.configurationFile
, 'utf8')
1467 ) as ChargingStationConfiguration
;
1468 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1469 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1470 this.configurationFileHash
= configuration
.configurationHash
;
1473 FileUtils
.handleFileException(
1474 this.configurationFile
,
1475 FileType
.ChargingStationConfiguration
,
1476 error
as NodeJS
.ErrnoException
,
1481 return configuration
;
1484 private saveConnectorsStatus() {
1485 this.saveConfiguration();
1488 private saveEvsesStatus() {
1489 this.saveConfiguration();
1492 private saveConfiguration(): void {
1493 if (this.configurationFile
) {
1495 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1496 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1498 const configurationData
: ChargingStationConfiguration
=
1499 Utils
.cloneObject(this.getConfigurationFromFile()) ?? {};
1500 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1501 configurationData
.stationInfo
= this.stationInfo
;
1503 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1504 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1506 if (this.connectors
.size
> 0) {
1507 configurationData
.connectorsStatus
= [...this.connectors
.values()].map(
1508 // eslint-disable-next-line @typescript-eslint/no-unused-vars
1509 ({ transactionSetInterval
, ...connectorStatusRest
}) => connectorStatusRest
1512 if (this.evses
.size
> 0) {
1513 configurationData
.evsesStatus
= [...this.evses
.values()].map((evseStatus
) => {
1516 connectorsStatus
: [...evseStatus
.connectors
.values()].map(
1517 // eslint-disable-next-line @typescript-eslint/no-unused-vars
1518 ({ transactionSetInterval
, ...connectorStatusRest
}) => connectorStatusRest
1521 delete status.connectors
;
1522 return status as EvseStatusConfiguration
;
1525 delete configurationData
.configurationHash
;
1526 const configurationHash
= crypto
1527 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1528 .update(JSON
.stringify(configurationData
))
1530 if (this.configurationFileHash
!== configurationHash
) {
1531 configurationData
.configurationHash
= configurationHash
;
1532 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1533 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1534 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1535 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1536 fs
.closeSync(fileDescriptor
);
1537 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1538 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1539 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1540 this.configurationFileHash
= configurationHash
;
1543 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1544 this.configurationFile
1549 FileUtils
.handleFileException(
1550 this.configurationFile
,
1551 FileType
.ChargingStationConfiguration
,
1552 error
as NodeJS
.ErrnoException
,
1558 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1563 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1564 return this.getTemplateFromFile()?.Configuration
;
1567 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1568 let configuration
: ChargingStationConfiguration
| undefined;
1569 if (this.getOcppPersistentConfiguration() === true) {
1570 const configurationFromFile
= this.getConfigurationFromFile();
1571 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1573 if (!Utils
.isNullOrUndefined(configuration
)) {
1574 delete configuration
.stationInfo
;
1575 delete configuration
.configurationHash
;
1577 return configuration
;
1580 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1581 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1582 this.getOcppConfigurationFromFile();
1583 if (!ocppConfiguration
) {
1584 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1586 return ocppConfiguration
;
1589 private async onOpen(): Promise
<void> {
1590 if (this.isWebSocketConnectionOpened() === true) {
1592 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1594 if (this.isRegistered() === false) {
1595 // Send BootNotification
1596 let registrationRetryCount
= 0;
1598 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1599 BootNotificationRequest
,
1600 BootNotificationResponse
1601 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1602 skipBufferingOnError
: true,
1604 if (this.isRegistered() === false) {
1605 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1607 this?.bootNotificationResponse
?.interval
1608 ? this.bootNotificationResponse
.interval
* 1000
1609 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1613 this.isRegistered() === false &&
1614 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1615 this.getRegistrationMaxRetries() === -1)
1618 if (this.isRegistered() === true) {
1619 if (this.isInAcceptedState() === true) {
1620 await this.startMessageSequence();
1624 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1627 this.wsConnectionRestarted
= false;
1628 this.autoReconnectRetryCount
= 0;
1629 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1632 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1637 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1640 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1641 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1643 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1645 )}' and reason '${reason.toString()}'`
1647 this.autoReconnectRetryCount
= 0;
1652 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1654 )}' and reason '${reason.toString()}'`
1656 this.started
=== true && (await this.reconnect());
1659 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1662 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1663 const cachedRequest
= this.requests
.get(messageId
);
1664 if (Array.isArray(cachedRequest
) === true) {
1665 return cachedRequest
;
1667 throw new OCPPError(
1668 ErrorType
.PROTOCOL_ERROR
,
1669 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1671 )} is not an array`,
1673 cachedRequest
as JsonType
1677 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1678 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1679 if (this.getEnableStatistics() === true) {
1680 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1683 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1687 // Process the message
1688 await this.ocppIncomingRequestService
.incomingRequestHandler(
1696 private handleResponseMessage(response
: Response
): void {
1697 const [messageType
, messageId
, commandPayload
] = response
;
1698 if (this.requests
.has(messageId
) === false) {
1700 throw new OCPPError(
1701 ErrorType
.INTERNAL_ERROR
,
1702 `Response for unknown message id ${messageId}`,
1708 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1713 `${this.logPrefix()} << Command '${
1714 requestCommandName ?? Constants.UNKNOWN_COMMAND
1715 }' received response payload: ${JSON.stringify(response)}`
1717 responseCallback(commandPayload
, requestPayload
);
1720 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1721 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1722 if (this.requests
.has(messageId
) === false) {
1724 throw new OCPPError(
1725 ErrorType
.INTERNAL_ERROR
,
1726 `Error response for unknown message id ${messageId}`,
1728 { errorType
, errorMessage
, errorDetails
}
1731 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1733 `${this.logPrefix()} << Command '${
1734 requestCommandName ?? Constants.UNKNOWN_COMMAND
1735 }' received error response payload: ${JSON.stringify(errorResponse)}`
1737 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1740 private async onMessage(data
: RawData
): Promise
<void> {
1741 let request
: IncomingRequest
| Response
| ErrorResponse
;
1742 let messageType
: number;
1743 let errorMsg
: string;
1745 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1746 if (Array.isArray(request
) === true) {
1747 [messageType
] = request
;
1748 // Check the type of message
1749 switch (messageType
) {
1751 case MessageType
.CALL_MESSAGE
:
1752 await this.handleIncomingMessage(request
as IncomingRequest
);
1755 case MessageType
.CALL_RESULT_MESSAGE
:
1756 this.handleResponseMessage(request
as Response
);
1759 case MessageType
.CALL_ERROR_MESSAGE
:
1760 this.handleErrorMessage(request
as ErrorResponse
);
1764 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1765 errorMsg
= `Wrong message type ${messageType}`;
1766 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1767 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1769 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1771 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1776 let commandName
: IncomingRequestCommand
;
1777 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1778 let errorCallback
: ErrorCallback
;
1779 const [, messageId
] = request
;
1780 switch (messageType
) {
1781 case MessageType
.CALL_MESSAGE
:
1782 [, , commandName
] = request
as IncomingRequest
;
1784 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1786 case MessageType
.CALL_RESULT_MESSAGE
:
1787 case MessageType
.CALL_ERROR_MESSAGE
:
1788 if (this.requests
.has(messageId
) === true) {
1789 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1790 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1791 errorCallback(error
as OCPPError
, false);
1793 // Remove the request from the cache in case of error at response handling
1794 this.requests
.delete(messageId
);
1798 if (error
instanceof OCPPError
=== false) {
1800 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1801 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1802 }' message '${data.toString()}' handling is not an OCPPError:`,
1807 `${this.logPrefix()} Incoming OCPP command '${
1808 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1809 }' message '${data.toString()}'${
1810 messageType !== MessageType.CALL_MESSAGE
1811 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1813 } processing error:`,
1819 private onPing(): void {
1820 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1823 private onPong(): void {
1824 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1827 private onError(error
: WSError
): void {
1828 this.closeWSConnection();
1829 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1832 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1833 if (this.getMeteringPerTransaction() === true) {
1836 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1837 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1842 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1843 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1847 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
1848 return stationTemplate
?.useConnectorId0
?? true;
1851 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1852 if (this.hasEvses
) {
1853 for (const evseStatus
of this.evses
.values()) {
1854 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1855 if (connectorStatus
.transactionStarted
=== true) {
1856 await this.stopTransactionOnConnector(connectorId
, reason
);
1861 for (const connectorId
of this.connectors
.keys()) {
1862 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1863 await this.stopTransactionOnConnector(connectorId
, reason
);
1870 private getConnectionTimeout(): number {
1872 ChargingStationConfigurationUtils
.getConfigurationKey(
1874 StandardParametersKey
.ConnectionTimeOut
1879 ChargingStationConfigurationUtils
.getConfigurationKey(
1881 StandardParametersKey
.ConnectionTimeOut
1883 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1886 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1889 // -1 for unlimited, 0 for disabling
1890 private getAutoReconnectMaxRetries(): number | undefined {
1892 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
1897 private getRegistrationMaxRetries(): number | undefined {
1898 return this.stationInfo
.registrationMaxRetries
?? -1;
1901 private getPowerDivider(): number {
1902 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
1903 if (this.stationInfo
?.powerSharedByConnectors
) {
1904 powerDivider
= this.getNumberOfRunningTransactions();
1906 return powerDivider
;
1909 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1910 const maximumPower
= this.getMaximumPower(stationInfo
);
1911 switch (this.getCurrentOutType(stationInfo
)) {
1912 case CurrentType
.AC
:
1913 return ACElectricUtils
.amperagePerPhaseFromPower(
1914 this.getNumberOfPhases(stationInfo
),
1915 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
1916 this.getVoltageOut(stationInfo
)
1918 case CurrentType
.DC
:
1919 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1923 private getAmperageLimitation(): number | undefined {
1925 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1926 ChargingStationConfigurationUtils
.getConfigurationKey(
1928 this.stationInfo
.amperageLimitationOcppKey
1933 ChargingStationConfigurationUtils
.getConfigurationKey(
1935 this.stationInfo
.amperageLimitationOcppKey
1937 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1942 private async startMessageSequence(): Promise
<void> {
1943 if (this.stationInfo
?.autoRegister
=== true) {
1944 await this.ocppRequestService
.requestHandler
<
1945 BootNotificationRequest
,
1946 BootNotificationResponse
1947 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1948 skipBufferingOnError
: true,
1951 // Start WebSocket ping
1952 this.startWebSocketPing();
1954 this.startHeartbeat();
1955 // Initialize connectors status
1956 if (this.hasEvses
) {
1957 for (const [evseId
, evseStatus
] of this.evses
) {
1959 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1960 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
1965 await OCPPServiceUtils
.sendAndSetConnectorStatus(
1974 for (const connectorId
of this.connectors
.keys()) {
1975 if (connectorId
> 0) {
1976 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
1979 this.getConnectorStatus(connectorId
)
1981 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
1985 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1986 await this.ocppRequestService
.requestHandler
<
1987 FirmwareStatusNotificationRequest
,
1988 FirmwareStatusNotificationResponse
1989 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1990 status: FirmwareStatus
.Installed
,
1992 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1996 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1997 this.startAutomaticTransactionGenerator();
1999 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2002 private async stopMessageSequence(
2003 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2005 // Stop WebSocket ping
2006 this.stopWebSocketPing();
2008 this.stopHeartbeat();
2009 // Stop ongoing transactions
2010 if (this.automaticTransactionGenerator
?.started
=== true) {
2011 this.stopAutomaticTransactionGenerator();
2013 await this.stopRunningTransactions(reason
);
2015 if (this.hasEvses
) {
2016 for (const [evseId
, evseStatus
] of this.evses
) {
2018 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2019 await this.ocppRequestService
.requestHandler
<
2020 StatusNotificationRequest
,
2021 StatusNotificationResponse
2024 RequestCommand
.STATUS_NOTIFICATION
,
2025 OCPPServiceUtils
.buildStatusNotificationRequest(
2028 ConnectorStatusEnum
.Unavailable
2031 delete connectorStatus
?.status;
2036 for (const connectorId
of this.connectors
.keys()) {
2037 if (connectorId
> 0) {
2038 await this.ocppRequestService
.requestHandler
<
2039 StatusNotificationRequest
,
2040 StatusNotificationResponse
2043 RequestCommand
.STATUS_NOTIFICATION
,
2044 OCPPServiceUtils
.buildStatusNotificationRequest(
2047 ConnectorStatusEnum
.Unavailable
2050 delete this.getConnectorStatus(connectorId
)?.status;
2056 private startWebSocketPing(): void {
2057 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2059 StandardParametersKey
.WebSocketPingInterval
2061 ? Utils
.convertToInt(
2062 ChargingStationConfigurationUtils
.getConfigurationKey(
2064 StandardParametersKey
.WebSocketPingInterval
2068 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2069 this.webSocketPingSetInterval
= setInterval(() => {
2070 if (this.isWebSocketConnectionOpened() === true) {
2071 this.wsConnection
?.ping();
2073 }, webSocketPingInterval
* 1000);
2075 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
2076 webSocketPingInterval
2079 } else if (this.webSocketPingSetInterval
) {
2081 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
2082 webSocketPingInterval
2087 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2092 private stopWebSocketPing(): void {
2093 if (this.webSocketPingSetInterval
) {
2094 clearInterval(this.webSocketPingSetInterval
);
2095 delete this.webSocketPingSetInterval
;
2099 private getConfiguredSupervisionUrl(): URL
{
2100 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2101 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
2102 let configuredSupervisionUrlIndex
: number;
2103 switch (Configuration
.getSupervisionUrlDistribution()) {
2104 case SupervisionUrlDistribution
.RANDOM
:
2105 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2107 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2108 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2110 Object.values(SupervisionUrlDistribution
).includes(
2111 Configuration
.getSupervisionUrlDistribution()
2114 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2115 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2118 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2121 return new URL(supervisionUrls
[configuredSupervisionUrlIndex
]);
2123 return new URL(supervisionUrls
as string);
2126 private stopHeartbeat(): void {
2127 if (this.heartbeatSetInterval
) {
2128 clearInterval(this.heartbeatSetInterval
);
2129 delete this.heartbeatSetInterval
;
2133 private terminateWSConnection(): void {
2134 if (this.isWebSocketConnectionOpened() === true) {
2135 this.wsConnection
?.terminate();
2136 this.wsConnection
= null;
2140 private getReconnectExponentialDelay(): boolean {
2141 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2144 private async reconnect(): Promise
<void> {
2145 // Stop WebSocket ping
2146 this.stopWebSocketPing();
2148 this.stopHeartbeat();
2149 // Stop the ATG if needed
2150 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2151 this.stopAutomaticTransactionGenerator();
2154 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2155 this.getAutoReconnectMaxRetries() === -1
2157 this.autoReconnectRetryCount
++;
2158 const reconnectDelay
= this.getReconnectExponentialDelay()
2159 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2160 : this.getConnectionTimeout() * 1000;
2161 const reconnectDelayWithdraw
= 1000;
2162 const reconnectTimeout
=
2163 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2164 ? reconnectDelay
- reconnectDelayWithdraw
2167 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2170 )}ms, timeout ${reconnectTimeout}ms`
2172 await Utils
.sleep(reconnectDelay
);
2174 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2176 this.openWSConnection(
2178 ...(this.stationInfo
?.wsOptions
?? {}),
2179 handshakeTimeout
: reconnectTimeout
,
2181 { closeOpened
: true }
2183 this.wsConnectionRestarted
= true;
2184 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2186 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2187 this.autoReconnectRetryCount
2188 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2193 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2194 | AutomaticTransactionGeneratorConfiguration
2196 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;