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 readonly sharedLRUCache
: SharedLRUCache
;
132 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
133 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
135 constructor(index
: number, templateFile
: string) {
136 this.started
= false;
137 this.starting
= false;
138 this.stopping
= false;
139 this.wsConnectionRestarted
= false;
140 this.autoReconnectRetryCount
= 0;
142 this.templateFile
= templateFile
;
143 this.connectors
= new Map
<number, ConnectorStatus
>();
144 this.evses
= new Map
<number, EvseStatus
>();
145 this.requests
= new Map
<string, CachedRequest
>();
146 this.messageBuffer
= new Set
<string>();
147 this.sharedLRUCache
= SharedLRUCache
.getInstance();
148 this.idTagsCache
= IdTagsCache
.getInstance();
149 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
154 public get
hasEvses(): boolean {
155 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
158 private get
wsConnectionUrl(): URL
{
161 this.getSupervisionUrlOcppConfiguration() &&
162 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey())
163 ? ChargingStationConfigurationUtils.getConfigurationKey(
165 this.getSupervisionUrlOcppKey()
167 : this.configuredSupervisionUrl.href
168 }/${this.stationInfo.chargingStationId}`
172 public logPrefix
= (): string => {
173 return Utils
.logPrefix(
175 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId)
176 ? this?.stationInfo?.chargingStationId
177 : ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())) ??
178 'Error at building log prefix'
183 public hasIdTags(): boolean {
184 const idTagsFile
= ChargingStationUtils
.getIdTagsFile(this.stationInfo
);
185 return Utils
.isNotEmptyArray(this.idTagsCache
.getIdTags(idTagsFile
));
188 public getEnableStatistics(): boolean {
189 return this.stationInfo
.enableStatistics
?? false;
192 public getMustAuthorizeAtRemoteStart(): boolean {
193 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
196 public getPayloadSchemaValidation(): boolean {
197 return this.stationInfo
.payloadSchemaValidation
?? true;
200 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
201 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
202 switch (this.getCurrentOutType(stationInfo
)) {
204 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
205 ? localStationInfo
.numberOfPhases
212 public isWebSocketConnectionOpened(): boolean {
213 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
216 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
217 return this?.bootNotificationResponse
?.status;
220 public isInUnknownState(): boolean {
221 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
224 public isInPendingState(): boolean {
225 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
228 public isInAcceptedState(): boolean {
229 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
232 public isInRejectedState(): boolean {
233 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
236 public isRegistered(): boolean {
238 this.isInUnknownState() === false &&
239 (this.isInAcceptedState() === true || this.isInPendingState() === true)
243 public isChargingStationAvailable(): boolean {
244 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
247 public hasConnector(connectorId
: number): boolean {
249 for (const evseStatus
of this.evses
.values()) {
250 if (evseStatus
.connectors
.has(connectorId
)) {
256 return this.connectors
.has(connectorId
);
259 public isConnectorAvailable(connectorId
: number): boolean {
262 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
266 public getNumberOfConnectors(): number {
268 let numberOfConnectors
= 0;
269 for (const [evseId
, evseStatus
] of this.evses
) {
271 numberOfConnectors
+= evseStatus
.connectors
.size
;
274 return numberOfConnectors
;
276 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
279 public getNumberOfEvses(): number {
280 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
283 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
285 for (const evseStatus
of this.evses
.values()) {
286 if (evseStatus
.connectors
.has(connectorId
)) {
287 return evseStatus
.connectors
.get(connectorId
);
292 return this.connectors
.get(connectorId
);
295 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
296 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
299 public getOcppStrictCompliance(): boolean {
300 return this.stationInfo
?.ocppStrictCompliance
?? false;
303 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
304 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
305 this.getCurrentOutType(stationInfo
),
309 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
310 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
311 ? localStationInfo
.voltageOut
315 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
316 const localStationInfo
= stationInfo
?? this.stationInfo
;
317 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
320 public getConnectorMaximumAvailablePower(connectorId
: number): number {
321 let connectorAmperageLimitationPowerLimit
: number;
323 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
324 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
326 connectorAmperageLimitationPowerLimit
=
327 (this.getCurrentOutType() === CurrentType
.AC
328 ? ACElectricUtils
.powerTotal(
329 this.getNumberOfPhases(),
330 this.getVoltageOut(),
331 this.getAmperageLimitation() *
332 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
334 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
337 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
338 const connectorChargingProfilesPowerLimit
=
339 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
341 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
342 isNaN(connectorAmperageLimitationPowerLimit
)
344 : connectorAmperageLimitationPowerLimit
,
345 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
349 public getTransactionIdTag(transactionId
: number): string | undefined {
351 for (const evseStatus
of this.evses
.values()) {
352 for (const connectorStatus
of evseStatus
.connectors
.values()) {
353 if (connectorStatus
.transactionId
=== transactionId
) {
354 return connectorStatus
.transactionIdTag
;
359 for (const connectorId
of this.connectors
.keys()) {
362 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
364 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
370 public getNumberOfRunningTransactions(): number {
373 for (const evseStatus
of this.evses
.values()) {
374 for (const connectorStatus
of evseStatus
.connectors
.values()) {
375 if (connectorStatus
.transactionStarted
=== true) {
381 for (const connectorId
of this.connectors
.keys()) {
382 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
390 public getOutOfOrderEndMeterValues(): boolean {
391 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
394 public getBeginEndMeterValues(): boolean {
395 return this.stationInfo
?.beginEndMeterValues
?? false;
398 public getMeteringPerTransaction(): boolean {
399 return this.stationInfo
?.meteringPerTransaction
?? true;
402 public getTransactionDataMeterValues(): boolean {
403 return this.stationInfo
?.transactionDataMeterValues
?? false;
406 public getMainVoltageMeterValues(): boolean {
407 return this.stationInfo
?.mainVoltageMeterValues
?? true;
410 public getPhaseLineToLineVoltageMeterValues(): boolean {
411 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
414 public getCustomValueLimitationMeterValues(): boolean {
415 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
418 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
420 for (const evseStatus
of this.evses
.values()) {
421 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
422 if (connectorStatus
.transactionId
=== transactionId
) {
428 for (const connectorId
of this.connectors
.keys()) {
431 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
439 public getEnergyActiveImportRegisterByTransactionId(
440 transactionId
: number,
443 return this.getEnergyActiveImportRegister(
444 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
449 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
450 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
453 public getAuthorizeRemoteTxRequests(): boolean {
454 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
456 StandardParametersKey
.AuthorizeRemoteTxRequests
458 return authorizeRemoteTxRequests
459 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
463 public getLocalAuthListEnabled(): boolean {
464 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
466 StandardParametersKey
.LocalAuthListEnabled
468 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
471 public getHeartbeatInterval(): number {
472 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
474 StandardParametersKey
.HeartbeatInterval
476 if (HeartbeatInterval
) {
477 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
479 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
481 StandardParametersKey
.HeartBeatInterval
483 if (HeartBeatInterval
) {
484 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
486 this.stationInfo
?.autoRegister
=== false &&
488 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
489 Constants.DEFAULT_HEARTBEAT_INTERVAL
492 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
495 public setSupervisionUrl(url
: string): void {
497 this.getSupervisionUrlOcppConfiguration() &&
498 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey())
500 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
502 this.getSupervisionUrlOcppKey(),
506 this.stationInfo
.supervisionUrls
= url
;
507 this.saveStationInfo();
508 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
512 public startHeartbeat(): void {
513 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
514 this.heartbeatSetInterval
= setInterval(() => {
515 this.ocppRequestService
516 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
519 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
523 }, this.getHeartbeatInterval());
525 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
526 this.getHeartbeatInterval()
529 } else if (this.heartbeatSetInterval
) {
531 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
532 this.getHeartbeatInterval()
537 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
542 public restartHeartbeat(): void {
544 this.stopHeartbeat();
546 this.startHeartbeat();
549 public restartWebSocketPing(): void {
550 // Stop WebSocket ping
551 this.stopWebSocketPing();
552 // Start WebSocket ping
553 this.startWebSocketPing();
556 public startMeterValues(connectorId
: number, interval
: number): void {
557 if (connectorId
=== 0) {
559 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
563 if (!this.getConnectorStatus(connectorId
)) {
565 `${this.logPrefix()} Trying to start MeterValues on non existing connector id ${connectorId.toString()}`
569 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
571 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
575 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
576 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
579 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
584 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
585 // FIXME: Implement OCPP version agnostic helpers
586 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
589 this.getConnectorStatus(connectorId
).transactionId
,
592 this.ocppRequestService
593 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
595 RequestCommand
.METER_VALUES
,
598 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
599 meterValue
: [meterValue
],
604 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
611 `${this.logPrefix()} Charging station ${
612 StandardParametersKey.MeterValueSampleInterval
613 } configuration set to ${interval}, not sending MeterValues`
618 public stopMeterValues(connectorId
: number) {
619 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
620 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
624 public start(): void {
625 if (this.started
=== false) {
626 if (this.starting
=== false) {
627 this.starting
= true;
628 if (this.getEnableStatistics() === true) {
629 this.performanceStatistics
?.start();
631 this.openWSConnection();
632 // Monitor charging station template file
633 this.templateFileWatcher
= FileUtils
.watchJsonFile(
635 FileType
.ChargingStationTemplate
,
638 (event
, filename
): void => {
639 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
642 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
644 } file have changed, reload`
646 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
650 this.stopAutomaticTransactionGenerator();
652 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
654 this.startAutomaticTransactionGenerator();
656 if (this.getEnableStatistics() === true) {
657 this.performanceStatistics
?.restart();
659 this.performanceStatistics
?.stop();
661 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
664 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
672 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
673 this.starting
= false;
675 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
678 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
682 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
683 if (this.started
=== true) {
684 if (this.stopping
=== false) {
685 this.stopping
= true;
686 await this.stopMessageSequence(reason
);
687 this.closeWSConnection();
688 if (this.getEnableStatistics() === true) {
689 this.performanceStatistics
?.stop();
691 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
692 this.templateFileWatcher
?.close();
693 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
694 delete this.bootNotificationResponse
;
695 this.started
= false;
696 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
697 this.stopping
= false;
699 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
702 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
706 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
707 await this.stop(reason
);
708 await Utils
.sleep(this.stationInfo
.resetTime
);
713 public saveOcppConfiguration(): void {
714 if (this.getOcppPersistentConfiguration()) {
715 this.saveConfiguration();
719 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
720 return ChargingStationConfigurationUtils
.getConfigurationKey(
722 StandardParametersKey
.SupportedFeatureProfiles
723 )?.value
?.includes(featureProfile
);
726 public bufferMessage(message
: string): void {
727 this.messageBuffer
.add(message
);
730 public openWSConnection(
731 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
732 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
734 terminateOpened
: false,
737 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
738 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
739 if (this.started
=== false && this.starting
=== false) {
741 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
746 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
747 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
749 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
751 if (params
?.closeOpened
) {
752 this.closeWSConnection();
754 if (params
?.terminateOpened
) {
755 this.terminateWSConnection();
758 if (this.isWebSocketConnectionOpened() === true) {
760 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
766 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
769 this.wsConnection
= new WebSocket(
770 this.wsConnectionUrl
,
771 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
775 // Handle WebSocket message
776 this.wsConnection
.on(
778 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
780 // Handle WebSocket error
781 this.wsConnection
.on(
783 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
785 // Handle WebSocket close
786 this.wsConnection
.on(
788 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
790 // Handle WebSocket open
791 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
792 // Handle WebSocket ping
793 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
794 // Handle WebSocket pong
795 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
798 public closeWSConnection(): void {
799 if (this.isWebSocketConnectionOpened() === true) {
800 this.wsConnection
?.close();
801 this.wsConnection
= null;
805 public startAutomaticTransactionGenerator(
806 connectorIds
?: number[],
807 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
809 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
810 automaticTransactionGeneratorConfiguration
??
811 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
814 if (Utils
.isNotEmptyArray(connectorIds
)) {
815 for (const connectorId
of connectorIds
) {
816 this.automaticTransactionGenerator
?.startConnector(connectorId
);
819 this.automaticTransactionGenerator
?.start();
821 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
824 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
825 if (Utils
.isNotEmptyArray(connectorIds
)) {
826 for (const connectorId
of connectorIds
) {
827 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
830 this.automaticTransactionGenerator
?.stop();
832 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
835 public async stopTransactionOnConnector(
837 reason
= StopTransactionReason
.NONE
838 ): Promise
<StopTransactionResponse
> {
839 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
841 this.getBeginEndMeterValues() === true &&
842 this.getOcppStrictCompliance() === true &&
843 this.getOutOfOrderEndMeterValues() === false
845 // FIXME: Implement OCPP version agnostic helpers
846 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
849 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
851 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
853 RequestCommand
.METER_VALUES
,
857 meterValue
: [transactionEndMeterValue
],
861 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
863 RequestCommand
.STOP_TRANSACTION
,
866 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
872 private flushMessageBuffer(): void {
873 if (this.messageBuffer
.size
> 0) {
874 for (const message
of this.messageBuffer
.values()) {
876 let commandName
: RequestCommand
;
877 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
878 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
880 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
881 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
883 this.wsConnection
?.send(message
);
884 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
886 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
888 )} payload sent: ${message}`
890 this.messageBuffer
.delete(message
);
895 private getSupervisionUrlOcppConfiguration(): boolean {
896 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
899 private getSupervisionUrlOcppKey(): string {
900 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
903 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
904 let template
: ChargingStationTemplate
;
906 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
907 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
909 const measureId
= `${FileType.ChargingStationTemplate} read`;
910 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
911 template
= JSON
.parse(
912 fs
.readFileSync(this.templateFile
, 'utf8')
913 ) as ChargingStationTemplate
;
914 PerformanceStatistics
.endMeasure(measureId
, beginId
);
915 template
.templateHash
= crypto
916 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
917 .update(JSON
.stringify(template
))
919 this.sharedLRUCache
.setChargingStationTemplate(template
);
922 FileUtils
.handleFileException(
924 FileType
.ChargingStationTemplate
,
925 error
as NodeJS
.ErrnoException
,
932 private getStationInfoFromTemplate(): ChargingStationInfo
{
933 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
934 if (Utils
.isNullOrUndefined(stationTemplate
)) {
935 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
936 logger
.error(`${this.logPrefix()} ${errorMsg}`);
937 throw new BaseError(errorMsg
);
939 if (Utils
.isEmptyObject(stationTemplate
)) {
940 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
941 logger
.error(`${this.logPrefix()} ${errorMsg}`);
942 throw new BaseError(errorMsg
);
944 ChargingStationUtils
.warnTemplateKeysDeprecation(
949 const stationInfo
: ChargingStationInfo
=
950 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
951 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
952 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
956 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
957 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
958 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
959 stationTemplate
.power
= stationTemplate
.power
as number[];
960 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
961 stationInfo
.maximumPower
=
962 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
963 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
964 : stationTemplate
.power
[powerArrayRandomIndex
];
966 stationTemplate
.power
= stationTemplate
?.power
as number;
967 stationInfo
.maximumPower
=
968 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
969 ? stationTemplate
.power
* 1000
970 : stationTemplate
.power
;
972 stationInfo
.firmwareVersionPattern
=
973 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
975 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
976 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
979 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
981 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
984 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
991 stationTemplate
?.firmwareUpgrade
?? {}
993 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
994 ? stationTemplate
.resetTime
* 1000
995 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
996 // Initialize evses or connectors if needed (FIXME: should be factored out)
997 this.initializeConnectorsOrEvses(stationInfo
);
998 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
999 ChargingStationUtils
.createStationInfoHash(stationInfo
);
1003 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1004 let stationInfo
: ChargingStationInfo
| undefined;
1005 this.getStationInfoPersistentConfiguration() &&
1006 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
);
1007 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
1011 private getStationInfo(): ChargingStationInfo
{
1012 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1013 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1015 // 1. charging station info from template
1016 // 2. charging station info from configuration file
1017 // 3. charging station info attribute
1018 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1019 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
1020 return this.stationInfo
;
1022 return stationInfoFromFile
;
1024 stationInfoFromFile
&&
1025 ChargingStationUtils
.propagateSerialNumber(
1026 this.getTemplateFromFile(),
1027 stationInfoFromFile
,
1028 stationInfoFromTemplate
1030 return stationInfoFromTemplate
;
1033 private saveStationInfo(): void {
1034 if (this.getStationInfoPersistentConfiguration()) {
1035 this.saveConfiguration();
1039 private getOcppPersistentConfiguration(): boolean {
1040 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1043 private getStationInfoPersistentConfiguration(): boolean {
1044 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1047 private handleUnsupportedVersion(version
: OCPPVersion
) {
1048 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1049 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1050 throw new BaseError(errorMsg
);
1053 private initialize(): void {
1054 this.configurationFile
= path
.join(
1055 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
1056 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
1058 this.stationInfo
= this.getStationInfo();
1060 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1061 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1062 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1064 const patternGroup
: number | undefined =
1065 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1066 this.stationInfo
.firmwareVersion
?.split('.').length
;
1067 const match
= this.stationInfo
?.firmwareVersion
1068 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1069 ?.slice(1, patternGroup
+ 1);
1070 const patchLevelIndex
= match
.length
- 1;
1071 match
[patchLevelIndex
] = (
1072 Utils
.convertToInt(match
[patchLevelIndex
]) +
1073 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1075 this.stationInfo
.firmwareVersion
= match
?.join('.');
1077 this.saveStationInfo();
1078 // Avoid duplication of connectors or evses related information in RAM
1079 delete this.stationInfo
?.Connectors
;
1080 delete this.stationInfo
?.Evses
;
1081 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1082 if (this.getEnableStatistics() === true) {
1083 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1084 this.stationInfo
.hashId
,
1085 this.stationInfo
.chargingStationId
,
1086 this.configuredSupervisionUrl
1089 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1092 this.powerDivider
= this.getPowerDivider();
1093 // OCPP configuration
1094 this.ocppConfiguration
= this.getOcppConfiguration();
1095 this.initializeOcppConfiguration();
1096 this.initializeOcppServices();
1097 if (this.stationInfo
?.autoRegister
=== true) {
1098 this.bootNotificationResponse
= {
1099 currentTime
: new Date(),
1100 interval
: this.getHeartbeatInterval() / 1000,
1101 status: RegistrationStatusEnumType
.ACCEPTED
,
1106 private initializeOcppServices(): void {
1107 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1108 switch (ocppVersion
) {
1109 case OCPPVersion
.VERSION_16
:
1110 this.ocppIncomingRequestService
=
1111 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1112 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1113 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1116 case OCPPVersion
.VERSION_20
:
1117 case OCPPVersion
.VERSION_201
:
1118 this.ocppIncomingRequestService
=
1119 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1120 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1121 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1125 this.handleUnsupportedVersion(ocppVersion
);
1130 private initializeOcppConfiguration(): void {
1132 !ChargingStationConfigurationUtils
.getConfigurationKey(
1134 StandardParametersKey
.HeartbeatInterval
1137 ChargingStationConfigurationUtils
.addConfigurationKey(
1139 StandardParametersKey
.HeartbeatInterval
,
1144 !ChargingStationConfigurationUtils
.getConfigurationKey(
1146 StandardParametersKey
.HeartBeatInterval
1149 ChargingStationConfigurationUtils
.addConfigurationKey(
1151 StandardParametersKey
.HeartBeatInterval
,
1157 this.getSupervisionUrlOcppConfiguration() &&
1158 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1159 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1161 ChargingStationConfigurationUtils
.addConfigurationKey(
1163 this.getSupervisionUrlOcppKey(),
1164 this.configuredSupervisionUrl
.href
,
1168 !this.getSupervisionUrlOcppConfiguration() &&
1169 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1170 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1172 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1174 this.getSupervisionUrlOcppKey(),
1179 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1180 !ChargingStationConfigurationUtils
.getConfigurationKey(
1182 this.stationInfo
.amperageLimitationOcppKey
1185 ChargingStationConfigurationUtils
.addConfigurationKey(
1187 this.stationInfo
.amperageLimitationOcppKey
,
1189 this.stationInfo
.maximumAmperage
*
1190 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1195 !ChargingStationConfigurationUtils
.getConfigurationKey(
1197 StandardParametersKey
.SupportedFeatureProfiles
1200 ChargingStationConfigurationUtils
.addConfigurationKey(
1202 StandardParametersKey
.SupportedFeatureProfiles
,
1203 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1206 ChargingStationConfigurationUtils
.addConfigurationKey(
1208 StandardParametersKey
.NumberOfConnectors
,
1209 this.getNumberOfConnectors().toString(),
1214 !ChargingStationConfigurationUtils
.getConfigurationKey(
1216 StandardParametersKey
.MeterValuesSampledData
1219 ChargingStationConfigurationUtils
.addConfigurationKey(
1221 StandardParametersKey
.MeterValuesSampledData
,
1222 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1226 !ChargingStationConfigurationUtils
.getConfigurationKey(
1228 StandardParametersKey
.ConnectorPhaseRotation
1231 const connectorsPhaseRotation
: string[] = [];
1232 if (this.hasEvses
) {
1233 for (const evseStatus
of this.evses
.values()) {
1234 for (const connectorId
of evseStatus
.connectors
.keys()) {
1235 connectorsPhaseRotation
.push(
1236 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1241 for (const connectorId
of this.connectors
.keys()) {
1242 connectorsPhaseRotation
.push(
1243 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1247 ChargingStationConfigurationUtils
.addConfigurationKey(
1249 StandardParametersKey
.ConnectorPhaseRotation
,
1250 connectorsPhaseRotation
.toString()
1254 !ChargingStationConfigurationUtils
.getConfigurationKey(
1256 StandardParametersKey
.AuthorizeRemoteTxRequests
1259 ChargingStationConfigurationUtils
.addConfigurationKey(
1261 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1266 !ChargingStationConfigurationUtils
.getConfigurationKey(
1268 StandardParametersKey
.LocalAuthListEnabled
1270 ChargingStationConfigurationUtils
.getConfigurationKey(
1272 StandardParametersKey
.SupportedFeatureProfiles
1273 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1275 ChargingStationConfigurationUtils
.addConfigurationKey(
1277 StandardParametersKey
.LocalAuthListEnabled
,
1282 !ChargingStationConfigurationUtils
.getConfigurationKey(
1284 StandardParametersKey
.ConnectionTimeOut
1287 ChargingStationConfigurationUtils
.addConfigurationKey(
1289 StandardParametersKey
.ConnectionTimeOut
,
1290 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1293 this.saveOcppConfiguration();
1296 private initializeConnectorsOrEvses(stationInfo
: ChargingStationInfo
) {
1297 if (stationInfo
?.Connectors
&& !stationInfo
?.Evses
) {
1298 this.initializeConnectors(stationInfo
);
1299 } else if (stationInfo
?.Evses
&& !stationInfo
?.Connectors
) {
1300 this.initializeEvses(stationInfo
);
1301 } else if (stationInfo
?.Evses
&& stationInfo
?.Connectors
) {
1302 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1303 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1304 throw new BaseError(errorMsg
);
1306 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1307 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1308 throw new BaseError(errorMsg
);
1312 private initializeConnectors(stationInfo
: ChargingStationInfo
): void {
1313 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1314 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1315 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1316 throw new BaseError(errorMsg
);
1318 if (!stationInfo
?.Connectors
[0]) {
1320 `${this.logPrefix()} Charging station information from template ${
1322 } with no connector id 0 configuration`
1325 if (stationInfo
?.Connectors
) {
1326 const configuredMaxConnectors
=
1327 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationInfo
);
1328 ChargingStationUtils
.checkConfiguredMaxConnectors(
1329 configuredMaxConnectors
,
1333 const connectorsConfigHash
= crypto
1334 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1335 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1337 const connectorsConfigChanged
=
1338 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1339 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1340 connectorsConfigChanged
&& this.connectors
.clear();
1341 this.connectorsConfigurationHash
= connectorsConfigHash
;
1342 const templateMaxConnectors
= ChargingStationUtils
.getMaxNumberOfConnectors(
1343 stationInfo
.Connectors
1345 ChargingStationUtils
.checkTemplateMaxConnectors(
1346 templateMaxConnectors
,
1350 const templateMaxAvailableConnectors
= stationInfo
?.Connectors
[0]
1351 ? templateMaxConnectors
- 1
1352 : templateMaxConnectors
;
1354 configuredMaxConnectors
> templateMaxAvailableConnectors
&&
1355 !stationInfo
?.randomConnectors
1358 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1360 }, forcing random connector configurations affectation`
1362 stationInfo
.randomConnectors
= true;
1364 if (templateMaxConnectors
> 0) {
1365 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1367 connectorId
=== 0 &&
1368 (!stationInfo
?.Connectors
[connectorId
] ||
1369 this.getUseConnectorId0(stationInfo
) === false)
1373 const templateConnectorId
=
1374 connectorId
> 0 && stationInfo
?.randomConnectors
1375 ? Utils
.getRandomInteger(templateMaxAvailableConnectors
, 1)
1377 const connectorStatus
= stationInfo
?.Connectors
[templateConnectorId
];
1378 ChargingStationUtils
.checkStationInfoConnectorStatus(
1379 templateConnectorId
,
1384 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1386 ChargingStationUtils
.initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1387 this.saveConnectorsStatus();
1390 `${this.logPrefix()} Charging station information from template ${
1392 } with no connectors configuration defined, cannot create connectors`
1398 `${this.logPrefix()} Charging station information from template ${
1400 } with no connectors configuration defined, using already defined connectors`
1405 private initializeEvses(stationInfo
: ChargingStationInfo
): void {
1406 if (!stationInfo
?.Evses
&& this.evses
.size
=== 0) {
1407 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1408 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1409 throw new BaseError(errorMsg
);
1411 if (!stationInfo
?.Evses
[0]) {
1413 `${this.logPrefix()} Charging station information from template ${
1415 } with no evse id 0 configuration`
1418 if (!stationInfo
?.Evses
[0]?.Connectors
[0]) {
1420 `${this.logPrefix()} Charging station information from template ${
1422 } with evse id 0 with no connector id 0 configuration`
1425 if (stationInfo
?.Evses
) {
1426 const evsesConfigHash
= crypto
1427 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1428 .update(`${JSON.stringify(stationInfo?.Evses)}`)
1430 const evsesConfigChanged
=
1431 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1432 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1433 evsesConfigChanged
&& this.evses
.clear();
1434 this.evsesConfigurationHash
= evsesConfigHash
;
1435 const templateMaxEvses
= ChargingStationUtils
.getMaxNumberOfEvses(stationInfo
?.Evses
);
1436 if (templateMaxEvses
> 0) {
1437 for (const evse
in stationInfo
.Evses
) {
1438 const evseId
= Utils
.convertToInt(evse
);
1439 this.evses
.set(evseId
, {
1440 connectors
: ChargingStationUtils
.buildConnectorsMap(
1441 stationInfo
?.Evses
[evse
]?.Connectors
,
1445 availability
: AvailabilityType
.Operative
,
1447 ChargingStationUtils
.initializeConnectorsMapStatus(
1448 this.evses
.get(evseId
)?.connectors
,
1452 this.saveEvsesStatus();
1455 `${this.logPrefix()} Charging station information from template ${
1457 } with no evses configuration defined, cannot create evses`
1463 `${this.logPrefix()} Charging station information from template ${
1465 } with no evses configuration defined, using already defined evses`
1470 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1471 let configuration
: ChargingStationConfiguration
| undefined;
1472 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1474 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1475 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1476 this.configurationFileHash
1479 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1480 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1481 configuration
= JSON
.parse(
1482 fs
.readFileSync(this.configurationFile
, 'utf8')
1483 ) as ChargingStationConfiguration
;
1484 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1485 this.configurationFileHash
= configuration
.configurationHash
;
1486 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1489 FileUtils
.handleFileException(
1490 this.configurationFile
,
1491 FileType
.ChargingStationConfiguration
,
1492 error
as NodeJS
.ErrnoException
,
1497 return configuration
;
1500 private saveConnectorsStatus() {
1501 if (this.getOcppPersistentConfiguration()) {
1502 this.saveConfiguration();
1506 private saveEvsesStatus() {
1507 if (this.getOcppPersistentConfiguration()) {
1508 this.saveConfiguration();
1512 private saveConfiguration(): void {
1513 if (this.configurationFile
) {
1515 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1516 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1518 const configurationData
: ChargingStationConfiguration
=
1519 Utils
.cloneObject(this.getConfigurationFromFile()) ?? {};
1520 if (this.stationInfo
) {
1521 configurationData
.stationInfo
= this.stationInfo
;
1523 if (this.ocppConfiguration
?.configurationKey
) {
1524 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1526 if (this.connectors
.size
> 0) {
1527 configurationData
.connectorsStatus
= [...this.connectors
.values()].map(
1528 // eslint-disable-next-line @typescript-eslint/no-unused-vars
1529 ({ transactionSetInterval
, ...connectorStatusRest
}) => connectorStatusRest
1532 if (this.evses
.size
> 0) {
1533 configurationData
.evsesStatus
= [...this.evses
.values()].map((evseStatus
) => {
1536 connectorsStatus
: [...evseStatus
.connectors
.values()].map(
1537 // eslint-disable-next-line @typescript-eslint/no-unused-vars
1538 ({ transactionSetInterval
, ...connectorStatusRest
}) => connectorStatusRest
1541 delete status.connectors
;
1542 return status as EvseStatusConfiguration
;
1545 delete configurationData
.configurationHash
;
1546 const configurationHash
= crypto
1547 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1548 .update(JSON
.stringify(configurationData
))
1550 if (this.configurationFileHash
!== configurationHash
) {
1551 configurationData
.configurationHash
= configurationHash
;
1552 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1553 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1554 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1555 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1556 fs
.closeSync(fileDescriptor
);
1557 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1558 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1559 this.configurationFileHash
= configurationHash
;
1560 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1563 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1564 this.configurationFile
1569 FileUtils
.handleFileException(
1570 this.configurationFile
,
1571 FileType
.ChargingStationConfiguration
,
1572 error
as NodeJS
.ErrnoException
,
1578 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1583 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1584 return this.getTemplateFromFile()?.Configuration
;
1587 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1588 let configuration
: ChargingStationConfiguration
| undefined;
1589 if (this.getOcppPersistentConfiguration() === true) {
1590 const configurationFromFile
= this.getConfigurationFromFile();
1591 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1593 if (!Utils
.isNullOrUndefined(configuration
)) {
1594 delete configuration
.stationInfo
;
1595 delete configuration
.configurationHash
;
1597 return configuration
;
1600 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1601 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1602 this.getOcppConfigurationFromFile();
1603 if (!ocppConfiguration
) {
1604 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1606 return ocppConfiguration
;
1609 private async onOpen(): Promise
<void> {
1610 if (this.isWebSocketConnectionOpened() === true) {
1612 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1614 if (this.isRegistered() === false) {
1615 // Send BootNotification
1616 let registrationRetryCount
= 0;
1618 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1619 BootNotificationRequest
,
1620 BootNotificationResponse
1621 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1622 skipBufferingOnError
: true,
1624 if (this.isRegistered() === false) {
1625 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1627 this?.bootNotificationResponse
?.interval
1628 ? this.bootNotificationResponse
.interval
* 1000
1629 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1633 this.isRegistered() === false &&
1634 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1635 this.getRegistrationMaxRetries() === -1)
1638 if (this.isRegistered() === true) {
1639 if (this.isInAcceptedState() === true) {
1640 await this.startMessageSequence();
1644 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1647 this.wsConnectionRestarted
= false;
1648 this.autoReconnectRetryCount
= 0;
1649 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1652 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1657 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1660 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1661 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1663 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1665 )}' and reason '${reason.toString()}'`
1667 this.autoReconnectRetryCount
= 0;
1672 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1674 )}' and reason '${reason.toString()}'`
1676 this.started
=== true && (await this.reconnect());
1679 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1682 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1683 const cachedRequest
= this.requests
.get(messageId
);
1684 if (Array.isArray(cachedRequest
) === true) {
1685 return cachedRequest
;
1687 throw new OCPPError(
1688 ErrorType
.PROTOCOL_ERROR
,
1689 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1691 )} is not an array`,
1693 cachedRequest
as JsonType
1697 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1698 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1699 if (this.getEnableStatistics() === true) {
1700 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1703 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1707 // Process the message
1708 await this.ocppIncomingRequestService
.incomingRequestHandler(
1716 private handleResponseMessage(response
: Response
): void {
1717 const [messageType
, messageId
, commandPayload
] = response
;
1718 if (this.requests
.has(messageId
) === false) {
1720 throw new OCPPError(
1721 ErrorType
.INTERNAL_ERROR
,
1722 `Response for unknown message id ${messageId}`,
1728 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1733 `${this.logPrefix()} << Command '${
1734 requestCommandName ?? Constants.UNKNOWN_COMMAND
1735 }' received response payload: ${JSON.stringify(response)}`
1737 responseCallback(commandPayload
, requestPayload
);
1740 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1741 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1742 if (this.requests
.has(messageId
) === false) {
1744 throw new OCPPError(
1745 ErrorType
.INTERNAL_ERROR
,
1746 `Error response for unknown message id ${messageId}`,
1748 { errorType
, errorMessage
, errorDetails
}
1751 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1753 `${this.logPrefix()} << Command '${
1754 requestCommandName ?? Constants.UNKNOWN_COMMAND
1755 }' received error response payload: ${JSON.stringify(errorResponse)}`
1757 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1760 private async onMessage(data
: RawData
): Promise
<void> {
1761 let request
: IncomingRequest
| Response
| ErrorResponse
;
1762 let messageType
: number;
1763 let errorMsg
: string;
1765 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1766 if (Array.isArray(request
) === true) {
1767 [messageType
] = request
;
1768 // Check the type of message
1769 switch (messageType
) {
1771 case MessageType
.CALL_MESSAGE
:
1772 await this.handleIncomingMessage(request
as IncomingRequest
);
1775 case MessageType
.CALL_RESULT_MESSAGE
:
1776 this.handleResponseMessage(request
as Response
);
1779 case MessageType
.CALL_ERROR_MESSAGE
:
1780 this.handleErrorMessage(request
as ErrorResponse
);
1784 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1785 errorMsg
= `Wrong message type ${messageType}`;
1786 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1787 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1789 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1791 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1796 let commandName
: IncomingRequestCommand
;
1797 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1798 let errorCallback
: ErrorCallback
;
1799 const [, messageId
] = request
;
1800 switch (messageType
) {
1801 case MessageType
.CALL_MESSAGE
:
1802 [, , commandName
] = request
as IncomingRequest
;
1804 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1806 case MessageType
.CALL_RESULT_MESSAGE
:
1807 case MessageType
.CALL_ERROR_MESSAGE
:
1808 if (this.requests
.has(messageId
) === true) {
1809 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1810 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1811 errorCallback(error
as OCPPError
, false);
1813 // Remove the request from the cache in case of error at response handling
1814 this.requests
.delete(messageId
);
1818 if (error
instanceof OCPPError
=== false) {
1820 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1821 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1822 }' message '${data.toString()}' handling is not an OCPPError:`,
1827 `${this.logPrefix()} Incoming OCPP command '${
1828 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1829 }' message '${data.toString()}'${
1830 messageType !== MessageType.CALL_MESSAGE
1831 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1833 } processing error:`,
1839 private onPing(): void {
1840 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1843 private onPong(): void {
1844 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1847 private onError(error
: WSError
): void {
1848 this.closeWSConnection();
1849 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1852 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1853 if (this.getMeteringPerTransaction() === true) {
1856 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1857 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1862 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1863 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1867 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1868 return (stationInfo
?? this.stationInfo
)?.useConnectorId0
?? true;
1871 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1872 if (this.hasEvses
) {
1873 for (const evseStatus
of this.evses
.values()) {
1874 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1875 if (connectorStatus
.transactionStarted
=== true) {
1876 await this.stopTransactionOnConnector(connectorId
, reason
);
1881 for (const connectorId
of this.connectors
.keys()) {
1882 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1883 await this.stopTransactionOnConnector(connectorId
, reason
);
1890 private getConnectionTimeout(): number {
1892 ChargingStationConfigurationUtils
.getConfigurationKey(
1894 StandardParametersKey
.ConnectionTimeOut
1899 ChargingStationConfigurationUtils
.getConfigurationKey(
1901 StandardParametersKey
.ConnectionTimeOut
1903 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1906 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1909 // -1 for unlimited, 0 for disabling
1910 private getAutoReconnectMaxRetries(): number | undefined {
1912 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
1917 private getRegistrationMaxRetries(): number | undefined {
1918 return this.stationInfo
.registrationMaxRetries
?? -1;
1921 private getPowerDivider(): number {
1922 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
1923 if (this.stationInfo
?.powerSharedByConnectors
) {
1924 powerDivider
= this.getNumberOfRunningTransactions();
1926 return powerDivider
;
1929 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1930 const maximumPower
= this.getMaximumPower(stationInfo
);
1931 switch (this.getCurrentOutType(stationInfo
)) {
1932 case CurrentType
.AC
:
1933 return ACElectricUtils
.amperagePerPhaseFromPower(
1934 this.getNumberOfPhases(stationInfo
),
1935 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
1936 this.getVoltageOut(stationInfo
)
1938 case CurrentType
.DC
:
1939 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1943 private getAmperageLimitation(): number | undefined {
1945 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1946 ChargingStationConfigurationUtils
.getConfigurationKey(
1948 this.stationInfo
.amperageLimitationOcppKey
1953 ChargingStationConfigurationUtils
.getConfigurationKey(
1955 this.stationInfo
.amperageLimitationOcppKey
1957 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1962 private async startMessageSequence(): Promise
<void> {
1963 if (this.stationInfo
?.autoRegister
=== true) {
1964 await this.ocppRequestService
.requestHandler
<
1965 BootNotificationRequest
,
1966 BootNotificationResponse
1967 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1968 skipBufferingOnError
: true,
1971 // Start WebSocket ping
1972 this.startWebSocketPing();
1974 this.startHeartbeat();
1975 // Initialize connectors status
1976 if (this.hasEvses
) {
1977 for (const [evseId
, evseStatus
] of this.evses
) {
1979 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1980 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
1985 await OCPPServiceUtils
.sendAndSetConnectorStatus(
1994 for (const connectorId
of this.connectors
.keys()) {
1995 if (connectorId
> 0) {
1996 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
1999 this.getConnectorStatus(connectorId
)
2001 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2005 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2006 await this.ocppRequestService
.requestHandler
<
2007 FirmwareStatusNotificationRequest
,
2008 FirmwareStatusNotificationResponse
2009 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2010 status: FirmwareStatus
.Installed
,
2012 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2016 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
2017 this.startAutomaticTransactionGenerator();
2019 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2022 private async stopMessageSequence(
2023 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2025 // Stop WebSocket ping
2026 this.stopWebSocketPing();
2028 this.stopHeartbeat();
2029 // Stop ongoing transactions
2030 if (this.automaticTransactionGenerator
?.started
=== true) {
2031 this.stopAutomaticTransactionGenerator();
2033 await this.stopRunningTransactions(reason
);
2035 if (this.hasEvses
) {
2036 for (const [evseId
, evseStatus
] of this.evses
) {
2038 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2039 await this.ocppRequestService
.requestHandler
<
2040 StatusNotificationRequest
,
2041 StatusNotificationResponse
2044 RequestCommand
.STATUS_NOTIFICATION
,
2045 OCPPServiceUtils
.buildStatusNotificationRequest(
2048 ConnectorStatusEnum
.Unavailable
2051 delete connectorStatus
?.status;
2056 for (const connectorId
of this.connectors
.keys()) {
2057 if (connectorId
> 0) {
2058 await this.ocppRequestService
.requestHandler
<
2059 StatusNotificationRequest
,
2060 StatusNotificationResponse
2063 RequestCommand
.STATUS_NOTIFICATION
,
2064 OCPPServiceUtils
.buildStatusNotificationRequest(
2067 ConnectorStatusEnum
.Unavailable
2070 delete this.getConnectorStatus(connectorId
)?.status;
2076 private startWebSocketPing(): void {
2077 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2079 StandardParametersKey
.WebSocketPingInterval
2081 ? Utils
.convertToInt(
2082 ChargingStationConfigurationUtils
.getConfigurationKey(
2084 StandardParametersKey
.WebSocketPingInterval
2088 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2089 this.webSocketPingSetInterval
= setInterval(() => {
2090 if (this.isWebSocketConnectionOpened() === true) {
2091 this.wsConnection
?.ping();
2093 }, webSocketPingInterval
* 1000);
2095 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
2096 webSocketPingInterval
2099 } else if (this.webSocketPingSetInterval
) {
2101 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
2102 webSocketPingInterval
2107 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2112 private stopWebSocketPing(): void {
2113 if (this.webSocketPingSetInterval
) {
2114 clearInterval(this.webSocketPingSetInterval
);
2115 delete this.webSocketPingSetInterval
;
2119 private getConfiguredSupervisionUrl(): URL
{
2120 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2121 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
2122 let configuredSupervisionUrlIndex
: number;
2123 switch (Configuration
.getSupervisionUrlDistribution()) {
2124 case SupervisionUrlDistribution
.RANDOM
:
2125 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2127 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2128 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2130 Object.values(SupervisionUrlDistribution
).includes(
2131 Configuration
.getSupervisionUrlDistribution()
2134 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2135 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2138 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2141 return new URL(supervisionUrls
[configuredSupervisionUrlIndex
]);
2143 return new URL(supervisionUrls
as string);
2146 private stopHeartbeat(): void {
2147 if (this.heartbeatSetInterval
) {
2148 clearInterval(this.heartbeatSetInterval
);
2149 delete this.heartbeatSetInterval
;
2153 private terminateWSConnection(): void {
2154 if (this.isWebSocketConnectionOpened() === true) {
2155 this.wsConnection
?.terminate();
2156 this.wsConnection
= null;
2160 private getReconnectExponentialDelay(): boolean {
2161 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2164 private async reconnect(): Promise
<void> {
2165 // Stop WebSocket ping
2166 this.stopWebSocketPing();
2168 this.stopHeartbeat();
2169 // Stop the ATG if needed
2170 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2171 this.stopAutomaticTransactionGenerator();
2174 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2175 this.getAutoReconnectMaxRetries() === -1
2177 this.autoReconnectRetryCount
++;
2178 const reconnectDelay
= this.getReconnectExponentialDelay()
2179 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2180 : this.getConnectionTimeout() * 1000;
2181 const reconnectDelayWithdraw
= 1000;
2182 const reconnectTimeout
=
2183 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2184 ? reconnectDelay
- reconnectDelayWithdraw
2187 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2190 )}ms, timeout ${reconnectTimeout}ms`
2192 await Utils
.sleep(reconnectDelay
);
2194 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2196 this.openWSConnection(
2198 ...(this.stationInfo
?.wsOptions
?? {}),
2199 handshakeTimeout
: reconnectTimeout
,
2201 { closeOpened
: true }
2203 this.wsConnectionRestarted
= true;
2204 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2206 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2207 this.autoReconnectRetryCount
2208 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2213 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2214 | AutomaticTransactionGeneratorConfiguration
2216 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;