1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
4 import crypto from
'node:crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import merge from
'just-merge';
10 import WebSocket
, { type RawData
} from
'ws';
12 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
13 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
14 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
15 import { ChargingStationUtils
} from
'./ChargingStationUtils';
16 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
17 import { MessageChannelUtils
} from
'./MessageChannelUtils';
18 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
19 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
20 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
21 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
22 import OCPP20IncomingRequestService from
'./ocpp/2.0/OCPP20IncomingRequestService';
23 import OCPP20RequestService from
'./ocpp/2.0/OCPP20RequestService';
24 import OCPP20ResponseService from
'./ocpp/2.0/OCPP20ResponseService';
25 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
26 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
27 import { OCPPServiceUtils
} from
'./ocpp/OCPPServiceUtils';
28 import SharedLRUCache from
'./SharedLRUCache';
29 import BaseError from
'../exception/BaseError';
30 import OCPPError from
'../exception/OCPPError';
31 import PerformanceStatistics from
'../performance/PerformanceStatistics';
32 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
33 import type { ChargingStationConfiguration
} from
'../types/ChargingStationConfiguration';
34 import type { ChargingStationInfo
} from
'../types/ChargingStationInfo';
35 import type { ChargingStationOcppConfiguration
} from
'../types/ChargingStationOcppConfiguration';
37 type ChargingStationTemplate
,
41 } from
'../types/ChargingStationTemplate';
42 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
43 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
44 import { FileType
} from
'../types/FileType';
45 import type { JsonType
} from
'../types/JsonType';
47 ConnectorPhaseRotation
,
48 StandardParametersKey
,
49 SupportedFeatureProfiles
,
50 VendorDefaultParametersKey
,
51 } from
'../types/ocpp/Configuration';
52 import { ConnectorStatusEnum
} from
'../types/ocpp/ConnectorStatusEnum';
53 import { ErrorType
} from
'../types/ocpp/ErrorType';
54 import { MessageType
} from
'../types/ocpp/MessageType';
55 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
56 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
59 type BootNotificationRequest
,
63 type FirmwareStatusNotificationRequest
,
64 type HeartbeatRequest
,
66 IncomingRequestCommand
,
67 type MeterValuesRequest
,
70 type ResponseCallback
,
71 type StatusNotificationRequest
,
72 } from
'../types/ocpp/Requests';
74 type BootNotificationResponse
,
76 type FirmwareStatusNotificationResponse
,
77 type HeartbeatResponse
,
78 type MeterValuesResponse
,
79 RegistrationStatusEnumType
,
81 type StatusNotificationResponse
,
82 } from
'../types/ocpp/Responses';
84 StopTransactionReason
,
85 type StopTransactionRequest
,
86 type StopTransactionResponse
,
87 } from
'../types/ocpp/Transaction';
88 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
89 import Configuration from
'../utils/Configuration';
90 import Constants from
'../utils/Constants';
91 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
92 import FileUtils from
'../utils/FileUtils';
93 import logger from
'../utils/Logger';
94 import Utils from
'../utils/Utils';
96 export default class ChargingStation
{
97 public readonly index
: number;
98 public readonly templateFile
: string;
99 public stationInfo
!: ChargingStationInfo
;
100 public started
: boolean;
101 public starting
: boolean;
102 public authorizedTagsCache
: AuthorizedTagsCache
;
103 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
104 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
105 public wsConnection
!: WebSocket
| null;
106 public readonly connectors
: Map
<number, ConnectorStatus
>;
107 public readonly requests
: Map
<string, CachedRequest
>;
108 public performanceStatistics
!: PerformanceStatistics
| undefined;
109 public heartbeatSetInterval
!: NodeJS
.Timeout
;
110 public ocppRequestService
!: OCPPRequestService
;
111 public bootNotificationRequest
!: BootNotificationRequest
;
112 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
113 public powerDivider
!: number;
114 private stopping
: boolean;
115 private configurationFile
!: string;
116 private configurationFileHash
!: string;
117 private connectorsConfigurationHash
!: string;
118 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
119 private readonly messageBuffer
: Set
<string>;
120 private configuredSupervisionUrl
!: URL
;
121 private configuredSupervisionUrlIndex
!: number;
122 private wsConnectionRestarted
: boolean;
123 private autoReconnectRetryCount
: number;
124 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
125 private readonly sharedLRUCache
: SharedLRUCache
;
126 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
127 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
129 constructor(index
: number, templateFile
: string) {
130 this.started
= false;
131 this.starting
= false;
132 this.stopping
= false;
133 this.wsConnectionRestarted
= false;
134 this.autoReconnectRetryCount
= 0;
136 this.templateFile
= templateFile
;
137 this.connectors
= new Map
<number, ConnectorStatus
>();
138 this.requests
= new Map
<string, CachedRequest
>();
139 this.messageBuffer
= new Set
<string>();
140 this.sharedLRUCache
= SharedLRUCache
.getInstance();
141 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
142 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
147 private get
wsConnectionUrl(): URL
{
150 this.getSupervisionUrlOcppConfiguration()
151 ? ChargingStationConfigurationUtils.getConfigurationKey(
153 this.getSupervisionUrlOcppKey()
155 : this.configuredSupervisionUrl.href
156 }/${this.stationInfo.chargingStationId}`
160 public logPrefix(): string {
161 return Utils
.logPrefix(
163 this?.stationInfo?.chargingStationId ??
164 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
169 public hasAuthorizedTags(): boolean {
170 return !Utils
.isEmptyArray(
171 this.authorizedTagsCache
.getAuthorizedTags(
172 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
177 public getEnableStatistics(): boolean {
178 return this.stationInfo
.enableStatistics
?? false;
181 public getMustAuthorizeAtRemoteStart(): boolean {
182 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
185 public getPayloadSchemaValidation(): boolean {
186 return this.stationInfo
.payloadSchemaValidation
?? true;
189 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
190 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
191 switch (this.getCurrentOutType(stationInfo
)) {
193 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
194 ? localStationInfo
.numberOfPhases
201 public isWebSocketConnectionOpened(): boolean {
202 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
205 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
206 return this?.bootNotificationResponse
?.status;
209 public isInUnknownState(): boolean {
210 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
213 public isInPendingState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
217 public isInAcceptedState(): boolean {
218 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
221 public isInRejectedState(): boolean {
222 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
225 public isRegistered(): boolean {
227 this.isInUnknownState() === false &&
228 (this.isInAcceptedState() === true || this.isInPendingState() === true)
232 public isChargingStationAvailable(): boolean {
233 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.OPERATIVE
;
236 public isConnectorAvailable(id
: number): boolean {
237 return id
> 0 && this.getConnectorStatus(id
)?.availability
=== AvailabilityType
.OPERATIVE
;
240 public getNumberOfConnectors(): number {
241 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
244 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
245 return this.connectors
.get(id
);
248 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
249 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
252 public getOcppStrictCompliance(): boolean {
253 return this.stationInfo
?.ocppStrictCompliance
?? false;
256 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
257 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
258 this.getCurrentOutType(stationInfo
),
262 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
263 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
264 ? localStationInfo
.voltageOut
268 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
269 const localStationInfo
= stationInfo
?? this.stationInfo
;
270 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
273 public getConnectorMaximumAvailablePower(connectorId
: number): number {
274 let connectorAmperageLimitationPowerLimit
: number;
276 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
277 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
279 connectorAmperageLimitationPowerLimit
=
280 (this.getCurrentOutType() === CurrentType
.AC
281 ? ACElectricUtils
.powerTotal(
282 this.getNumberOfPhases(),
283 this.getVoltageOut(),
284 this.getAmperageLimitation() * this.getNumberOfConnectors()
286 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
289 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
290 const connectorChargingProfilesPowerLimit
=
291 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
293 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
294 isNaN(connectorAmperageLimitationPowerLimit
)
296 : connectorAmperageLimitationPowerLimit
,
297 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
301 public getTransactionIdTag(transactionId
: number): string | undefined {
302 for (const connectorId
of this.connectors
.keys()) {
305 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
307 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
312 public getOutOfOrderEndMeterValues(): boolean {
313 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
316 public getBeginEndMeterValues(): boolean {
317 return this.stationInfo
?.beginEndMeterValues
?? false;
320 public getMeteringPerTransaction(): boolean {
321 return this.stationInfo
?.meteringPerTransaction
?? true;
324 public getTransactionDataMeterValues(): boolean {
325 return this.stationInfo
?.transactionDataMeterValues
?? false;
328 public getMainVoltageMeterValues(): boolean {
329 return this.stationInfo
?.mainVoltageMeterValues
?? true;
332 public getPhaseLineToLineVoltageMeterValues(): boolean {
333 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
336 public getCustomValueLimitationMeterValues(): boolean {
337 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
340 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
341 for (const connectorId
of this.connectors
.keys()) {
344 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
351 public getEnergyActiveImportRegisterByTransactionId(
352 transactionId
: number,
355 return this.getEnergyActiveImportRegister(
356 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
361 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
362 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
365 public getAuthorizeRemoteTxRequests(): boolean {
366 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
368 StandardParametersKey
.AuthorizeRemoteTxRequests
370 return authorizeRemoteTxRequests
371 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
375 public getLocalAuthListEnabled(): boolean {
376 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
378 StandardParametersKey
.LocalAuthListEnabled
380 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
383 public startHeartbeat(): void {
385 this.getHeartbeatInterval() &&
386 this.getHeartbeatInterval() > 0 &&
387 !this.heartbeatSetInterval
389 this.heartbeatSetInterval
= setInterval(() => {
390 this.ocppRequestService
391 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
394 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
398 }, this.getHeartbeatInterval());
400 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
401 this.getHeartbeatInterval()
404 } else if (this.heartbeatSetInterval
) {
406 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
407 this.getHeartbeatInterval()
412 `${this.logPrefix()} Heartbeat interval set to ${
413 this.getHeartbeatInterval()
414 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
415 : this.getHeartbeatInterval()
416 }, not starting the heartbeat`
421 public restartHeartbeat(): void {
423 this.stopHeartbeat();
425 this.startHeartbeat();
428 public restartWebSocketPing(): void {
429 // Stop WebSocket ping
430 this.stopWebSocketPing();
431 // Start WebSocket ping
432 this.startWebSocketPing();
435 public startMeterValues(connectorId
: number, interval
: number): void {
436 if (connectorId
=== 0) {
438 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
442 if (!this.getConnectorStatus(connectorId
)) {
444 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
448 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
450 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
454 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
455 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
458 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
463 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
464 // FIXME: Implement OCPP version agnostic helpers
465 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
468 this.getConnectorStatus(connectorId
).transactionId
,
471 this.ocppRequestService
472 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
474 RequestCommand
.METER_VALUES
,
477 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
478 meterValue
: [meterValue
],
483 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
490 `${this.logPrefix()} Charging station ${
491 StandardParametersKey.MeterValueSampleInterval
492 } configuration set to ${
493 interval ? Utils.formatDurationMilliSeconds(interval) : interval
494 }, not sending MeterValues`
499 public start(): void {
500 if (this.started
=== false) {
501 if (this.starting
=== false) {
502 this.starting
= true;
503 if (this.getEnableStatistics() === true) {
504 this.performanceStatistics
?.start();
506 this.openWSConnection();
507 // Monitor charging station template file
508 this.templateFileWatcher
= FileUtils
.watchJsonFile(
510 FileType
.ChargingStationTemplate
,
513 (event
, filename
): void => {
514 if (filename
&& event
=== 'change') {
517 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
519 } file have changed, reload`
521 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
525 this.stopAutomaticTransactionGenerator();
527 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
529 this.startAutomaticTransactionGenerator();
531 if (this.getEnableStatistics() === true) {
532 this.performanceStatistics
?.restart();
534 this.performanceStatistics
?.stop();
536 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
539 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
547 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
548 this.starting
= false;
550 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
553 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
557 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
558 if (this.started
=== true) {
559 if (this.stopping
=== false) {
560 this.stopping
= true;
561 await this.stopMessageSequence(reason
);
562 this.closeWSConnection();
563 if (this.getEnableStatistics() === true) {
564 this.performanceStatistics
?.stop();
566 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
567 this.templateFileWatcher
?.close();
568 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
569 this.bootNotificationResponse
= undefined;
570 this.started
= false;
571 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
572 this.stopping
= false;
574 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
577 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
581 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
582 await this.stop(reason
);
583 await Utils
.sleep(this.stationInfo
.resetTime
);
588 public saveOcppConfiguration(): void {
589 if (this.getOcppPersistentConfiguration()) {
590 this.saveConfiguration();
594 public resetConnectorStatus(connectorId
: number): void {
595 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
596 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
597 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
598 this.getConnectorStatus(connectorId
).transactionStarted
= false;
599 delete this.getConnectorStatus(connectorId
)?.localAuthorizeIdTag
;
600 delete this.getConnectorStatus(connectorId
)?.authorizeIdTag
;
601 delete this.getConnectorStatus(connectorId
)?.transactionId
;
602 delete this.getConnectorStatus(connectorId
)?.transactionIdTag
;
603 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
604 delete this.getConnectorStatus(connectorId
)?.transactionBeginMeterValue
;
605 this.stopMeterValues(connectorId
);
606 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
609 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
610 return ChargingStationConfigurationUtils
.getConfigurationKey(
612 StandardParametersKey
.SupportedFeatureProfiles
613 )?.value
?.includes(featureProfile
);
616 public bufferMessage(message
: string): void {
617 this.messageBuffer
.add(message
);
620 public openWSConnection(
621 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
622 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
624 terminateOpened
: false,
627 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
628 params
.closeOpened
= params
?.closeOpened
?? false;
629 params
.terminateOpened
= params
?.terminateOpened
?? false;
630 if (this.started
=== false && this.starting
=== false) {
632 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
637 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
638 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
640 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
642 if (params
?.closeOpened
) {
643 this.closeWSConnection();
645 if (params
?.terminateOpened
) {
646 this.terminateWSConnection();
648 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
649 let protocol
: string;
650 switch (ocppVersion
) {
651 case OCPPVersion
.VERSION_16
:
652 case OCPPVersion
.VERSION_20
:
653 case OCPPVersion
.VERSION_201
:
654 protocol
= `ocpp${ocppVersion}`;
657 this.handleUnsupportedVersion(ocppVersion
);
661 if (this.isWebSocketConnectionOpened() === true) {
663 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
669 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
672 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
674 // Handle WebSocket message
675 this.wsConnection
.on(
677 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
679 // Handle WebSocket error
680 this.wsConnection
.on(
682 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
684 // Handle WebSocket close
685 this.wsConnection
.on(
687 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
689 // Handle WebSocket open
690 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
691 // Handle WebSocket ping
692 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
693 // Handle WebSocket pong
694 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
697 public closeWSConnection(): void {
698 if (this.isWebSocketConnectionOpened() === true) {
699 this.wsConnection
?.close();
700 this.wsConnection
= null;
704 public startAutomaticTransactionGenerator(
705 connectorIds
?: number[],
706 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
708 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
709 automaticTransactionGeneratorConfiguration
??
710 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
713 if (!Utils
.isEmptyArray(connectorIds
)) {
714 for (const connectorId
of connectorIds
) {
715 this.automaticTransactionGenerator
?.startConnector(connectorId
);
718 this.automaticTransactionGenerator
?.start();
720 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
723 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
724 if (!Utils
.isEmptyArray(connectorIds
)) {
725 for (const connectorId
of connectorIds
) {
726 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
729 this.automaticTransactionGenerator
?.stop();
731 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
734 public async stopTransactionOnConnector(
736 reason
= StopTransactionReason
.NONE
737 ): Promise
<StopTransactionResponse
> {
738 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
740 this.getBeginEndMeterValues() === true &&
741 this.getOcppStrictCompliance() === true &&
742 this.getOutOfOrderEndMeterValues() === false
744 // FIXME: Implement OCPP version agnostic helpers
745 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
748 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
750 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
752 RequestCommand
.METER_VALUES
,
756 meterValue
: [transactionEndMeterValue
],
760 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
762 RequestCommand
.STOP_TRANSACTION
,
765 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
771 private flushMessageBuffer(): void {
772 if (this.messageBuffer
.size
> 0) {
773 this.messageBuffer
.forEach((message
) => {
775 let commandName
: RequestCommand
;
776 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
777 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
779 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
780 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
782 this.wsConnection
?.send(message
);
783 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
785 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
787 )} payload sent: ${message}`
789 this.messageBuffer
.delete(message
);
794 private getSupervisionUrlOcppConfiguration(): boolean {
795 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
798 private getSupervisionUrlOcppKey(): string {
799 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
802 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
803 let template
: ChargingStationTemplate
;
805 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
806 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
808 const measureId
= `${FileType.ChargingStationTemplate} read`;
809 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
810 template
= JSON
.parse(
811 fs
.readFileSync(this.templateFile
, 'utf8')
812 ) as ChargingStationTemplate
;
813 PerformanceStatistics
.endMeasure(measureId
, beginId
);
814 template
.templateHash
= crypto
815 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
816 .update(JSON
.stringify(template
))
818 this.sharedLRUCache
.setChargingStationTemplate(template
);
821 FileUtils
.handleFileException(
823 FileType
.ChargingStationTemplate
,
825 error
as NodeJS
.ErrnoException
831 private getStationInfoFromTemplate(): ChargingStationInfo
{
832 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
833 if (Utils
.isNullOrUndefined(stationTemplate
)) {
834 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
835 logger
.error(`${this.logPrefix()} ${errorMsg}`);
836 throw new BaseError(errorMsg
);
838 if (Utils
.isEmptyObject(stationTemplate
)) {
839 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
840 logger
.error(`${this.logPrefix()} ${errorMsg}`);
841 throw new BaseError(errorMsg
);
843 // Deprecation template keys section
844 ChargingStationUtils
.warnDeprecatedTemplateKey(
849 "Use 'supervisionUrls' instead"
851 ChargingStationUtils
.convertDeprecatedTemplateKey(
856 const stationInfo
: ChargingStationInfo
=
857 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
858 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
859 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
863 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
864 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
865 if (!Utils
.isEmptyArray(stationTemplate
?.power
)) {
866 stationTemplate
.power
= stationTemplate
.power
as number[];
867 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
868 stationInfo
.maximumPower
=
869 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
870 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
871 : stationTemplate
.power
[powerArrayRandomIndex
];
873 stationTemplate
.power
= stationTemplate
?.power
as number;
874 stationInfo
.maximumPower
=
875 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
876 ? stationTemplate
.power
* 1000
877 : stationTemplate
.power
;
879 stationInfo
.firmwareVersionPattern
=
880 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
882 !Utils
.isEmptyString(stationInfo
.firmwareVersion
) &&
883 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
886 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
888 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
891 stationInfo
.firmwareUpgrade
= merge(
895 stationTemplate
?.firmwareUpgrade
?? {}
897 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
898 ? stationTemplate
.resetTime
* 1000
899 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
900 const configuredMaxConnectors
=
901 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
902 ChargingStationUtils
.checkConfiguredMaxConnectors(
903 configuredMaxConnectors
,
907 const templateMaxConnectors
=
908 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
909 ChargingStationUtils
.checkTemplateMaxConnectors(
910 templateMaxConnectors
,
915 configuredMaxConnectors
>
916 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
917 !stationTemplate
?.randomConnectors
920 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
922 }, forcing random connector configurations affectation`
924 stationInfo
.randomConnectors
= true;
926 // Build connectors if needed (FIXME: should be factored out)
927 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
928 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
929 ChargingStationUtils
.createStationInfoHash(stationInfo
);
933 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
934 let stationInfo
: ChargingStationInfo
| undefined;
935 this.getStationInfoPersistentConfiguration() &&
936 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
);
937 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
941 private getStationInfo(): ChargingStationInfo
{
942 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
943 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
944 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
945 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
946 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
947 return this.stationInfo
;
949 return stationInfoFromFile
;
951 stationInfoFromFile
&&
952 ChargingStationUtils
.propagateSerialNumber(
953 this.getTemplateFromFile(),
955 stationInfoFromTemplate
957 return stationInfoFromTemplate
;
960 private saveStationInfo(): void {
961 if (this.getStationInfoPersistentConfiguration()) {
962 this.saveConfiguration();
966 private getOcppPersistentConfiguration(): boolean {
967 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
970 private getStationInfoPersistentConfiguration(): boolean {
971 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
974 private handleUnsupportedVersion(version
: OCPPVersion
) {
975 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
976 logger
.error(`${this.logPrefix()} ${errMsg}`);
977 throw new BaseError(errMsg
);
980 private initialize(): void {
981 this.configurationFile
= path
.join(
982 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
983 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
985 this.stationInfo
= this.getStationInfo();
986 this.saveStationInfo();
987 // Avoid duplication of connectors related information in RAM
988 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
989 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
990 if (this.getEnableStatistics() === true) {
991 this.performanceStatistics
= PerformanceStatistics
.getInstance(
992 this.stationInfo
.hashId
,
993 this.stationInfo
.chargingStationId
,
994 this.configuredSupervisionUrl
997 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1000 this.powerDivider
= this.getPowerDivider();
1001 // OCPP configuration
1002 this.ocppConfiguration
= this.getOcppConfiguration();
1003 this.initializeOcppConfiguration();
1004 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1005 switch (ocppVersion
) {
1006 case OCPPVersion
.VERSION_16
:
1007 this.ocppIncomingRequestService
=
1008 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1009 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1010 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1013 case OCPPVersion
.VERSION_20
:
1014 case OCPPVersion
.VERSION_201
:
1015 this.ocppIncomingRequestService
=
1016 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1017 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1018 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1022 this.handleUnsupportedVersion(ocppVersion
);
1025 if (this.stationInfo
?.autoRegister
=== true) {
1026 this.bootNotificationResponse
= {
1027 currentTime
: new Date(),
1028 interval
: this.getHeartbeatInterval() / 1000,
1029 status: RegistrationStatusEnumType
.ACCEPTED
,
1033 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1034 !Utils
.isEmptyString(this.stationInfo
.firmwareVersion
) &&
1035 !Utils
.isEmptyString(this.stationInfo
.firmwareVersionPattern
)
1037 const versionStep
= this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
?? 1;
1038 const patternGroup
: number | undefined =
1039 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1040 this.stationInfo
.firmwareVersion
?.split('.').length
;
1041 const match
= this.stationInfo
?.firmwareVersion
1042 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1043 ?.slice(1, patternGroup
+ 1);
1044 const patchLevelIndex
= match
.length
- 1;
1045 match
[patchLevelIndex
] = (
1046 Utils
.convertToInt(match
[patchLevelIndex
]) + versionStep
1048 this.stationInfo
.firmwareVersion
= match
?.join('.');
1052 private initializeOcppConfiguration(): void {
1054 !ChargingStationConfigurationUtils
.getConfigurationKey(
1056 StandardParametersKey
.HeartbeatInterval
1059 ChargingStationConfigurationUtils
.addConfigurationKey(
1061 StandardParametersKey
.HeartbeatInterval
,
1066 !ChargingStationConfigurationUtils
.getConfigurationKey(
1068 StandardParametersKey
.HeartBeatInterval
1071 ChargingStationConfigurationUtils
.addConfigurationKey(
1073 StandardParametersKey
.HeartBeatInterval
,
1079 this.getSupervisionUrlOcppConfiguration() &&
1080 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1082 ChargingStationConfigurationUtils
.addConfigurationKey(
1084 this.getSupervisionUrlOcppKey(),
1085 this.configuredSupervisionUrl
.href
,
1089 !this.getSupervisionUrlOcppConfiguration() &&
1090 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1092 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1094 this.getSupervisionUrlOcppKey(),
1099 !Utils
.isEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1100 !ChargingStationConfigurationUtils
.getConfigurationKey(
1102 this.stationInfo
.amperageLimitationOcppKey
1105 ChargingStationConfigurationUtils
.addConfigurationKey(
1107 this.stationInfo
.amperageLimitationOcppKey
,
1109 this.stationInfo
.maximumAmperage
*
1110 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1115 !ChargingStationConfigurationUtils
.getConfigurationKey(
1117 StandardParametersKey
.SupportedFeatureProfiles
1120 ChargingStationConfigurationUtils
.addConfigurationKey(
1122 StandardParametersKey
.SupportedFeatureProfiles
,
1123 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1126 ChargingStationConfigurationUtils
.addConfigurationKey(
1128 StandardParametersKey
.NumberOfConnectors
,
1129 this.getNumberOfConnectors().toString(),
1134 !ChargingStationConfigurationUtils
.getConfigurationKey(
1136 StandardParametersKey
.MeterValuesSampledData
1139 ChargingStationConfigurationUtils
.addConfigurationKey(
1141 StandardParametersKey
.MeterValuesSampledData
,
1142 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1146 !ChargingStationConfigurationUtils
.getConfigurationKey(
1148 StandardParametersKey
.ConnectorPhaseRotation
1151 const connectorPhaseRotation
= [];
1152 for (const connectorId
of this.connectors
.keys()) {
1154 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1155 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1156 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1157 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1159 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1160 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1161 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1162 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1165 ChargingStationConfigurationUtils
.addConfigurationKey(
1167 StandardParametersKey
.ConnectorPhaseRotation
,
1168 connectorPhaseRotation
.toString()
1172 !ChargingStationConfigurationUtils
.getConfigurationKey(
1174 StandardParametersKey
.AuthorizeRemoteTxRequests
1177 ChargingStationConfigurationUtils
.addConfigurationKey(
1179 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1184 !ChargingStationConfigurationUtils
.getConfigurationKey(
1186 StandardParametersKey
.LocalAuthListEnabled
1188 ChargingStationConfigurationUtils
.getConfigurationKey(
1190 StandardParametersKey
.SupportedFeatureProfiles
1191 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1193 ChargingStationConfigurationUtils
.addConfigurationKey(
1195 StandardParametersKey
.LocalAuthListEnabled
,
1200 !ChargingStationConfigurationUtils
.getConfigurationKey(
1202 StandardParametersKey
.ConnectionTimeOut
1205 ChargingStationConfigurationUtils
.addConfigurationKey(
1207 StandardParametersKey
.ConnectionTimeOut
,
1208 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1211 this.saveOcppConfiguration();
1214 private initializeConnectors(
1215 stationInfo
: ChargingStationInfo
,
1216 configuredMaxConnectors
: number,
1217 templateMaxConnectors
: number
1219 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1220 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1221 logger
.error(`${this.logPrefix()} ${logMsg}`);
1222 throw new BaseError(logMsg
);
1224 if (!stationInfo
?.Connectors
[0]) {
1226 `${this.logPrefix()} Charging station information from template ${
1228 } with no connector Id 0 configuration`
1231 if (stationInfo
?.Connectors
) {
1232 const connectorsConfigHash
= crypto
1233 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1234 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1236 const connectorsConfigChanged
=
1237 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1238 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1239 connectorsConfigChanged
&& this.connectors
.clear();
1240 this.connectorsConfigurationHash
= connectorsConfigHash
;
1241 // Add connector Id 0
1242 let lastConnector
= '0';
1243 for (lastConnector
in stationInfo
?.Connectors
) {
1244 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1245 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1247 lastConnectorId
=== 0 &&
1248 this.getUseConnectorId0(stationInfo
) === true &&
1251 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1252 this.connectors
.set(
1254 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1256 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1257 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1258 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1262 // Generate all connectors
1263 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1264 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1265 const randConnectorId
= stationInfo
?.randomConnectors
1266 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1268 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1269 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1270 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1271 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1272 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1273 this.getConnectorStatus(index
).chargingProfiles
= [];
1280 `${this.logPrefix()} Charging station information from template ${
1282 } with no connectors configuration defined, using already defined connectors`
1285 // Initialize transaction attributes on connectors
1286 for (const connectorId
of this.connectors
.keys()) {
1287 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1289 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1290 this.getConnectorStatus(connectorId)?.transactionId
1296 (this.getConnectorStatus(connectorId
)?.transactionStarted
=== undefined ||
1297 this.getConnectorStatus(connectorId
)?.transactionStarted
=== null)
1299 this.initializeConnectorStatus(connectorId
);
1304 private checkStationInfoConnectorStatus(
1305 connectorId
: number,
1306 connectorStatus
: ConnectorStatus
1308 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1310 `${this.logPrefix()} Charging station information from template ${
1312 } with connector ${connectorId} status configuration defined, undefine it`
1314 connectorStatus
.status = undefined;
1318 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1319 let configuration
: ChargingStationConfiguration
| undefined;
1320 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1322 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1323 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1324 this.configurationFileHash
1327 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1328 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1329 configuration
= JSON
.parse(
1330 fs
.readFileSync(this.configurationFile
, 'utf8')
1331 ) as ChargingStationConfiguration
;
1332 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1333 this.configurationFileHash
= configuration
.configurationHash
;
1334 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1337 FileUtils
.handleFileException(
1339 FileType
.ChargingStationConfiguration
,
1340 this.configurationFile
,
1341 error
as NodeJS
.ErrnoException
1345 return configuration
;
1348 private saveConfiguration(): void {
1349 if (this.configurationFile
) {
1351 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1352 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1354 const configurationData
: ChargingStationConfiguration
=
1355 this.getConfigurationFromFile() ?? {};
1356 this.ocppConfiguration
?.configurationKey
&&
1357 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1358 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1359 delete configurationData
.configurationHash
;
1360 const configurationHash
= crypto
1361 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1362 .update(JSON
.stringify(configurationData
))
1364 if (this.configurationFileHash
!== configurationHash
) {
1365 configurationData
.configurationHash
= configurationHash
;
1366 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1367 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1368 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1369 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1370 fs
.closeSync(fileDescriptor
);
1371 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1372 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1373 this.configurationFileHash
= configurationHash
;
1374 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1377 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1378 this.configurationFile
1383 FileUtils
.handleFileException(
1385 FileType
.ChargingStationConfiguration
,
1386 this.configurationFile
,
1387 error
as NodeJS
.ErrnoException
1392 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1397 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1398 return this.getTemplateFromFile()?.Configuration
;
1401 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1402 let configuration
: ChargingStationConfiguration
| undefined;
1403 if (this.getOcppPersistentConfiguration() === true) {
1404 const configurationFromFile
= this.getConfigurationFromFile();
1405 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1407 configuration
&& delete configuration
.stationInfo
;
1408 return configuration
;
1411 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1412 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1413 this.getOcppConfigurationFromFile();
1414 if (!ocppConfiguration
) {
1415 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1417 return ocppConfiguration
;
1420 private async onOpen(): Promise
<void> {
1421 if (this.isWebSocketConnectionOpened() === true) {
1423 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1425 if (this.isRegistered() === false) {
1426 // Send BootNotification
1427 let registrationRetryCount
= 0;
1429 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1430 BootNotificationRequest
,
1431 BootNotificationResponse
1432 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1433 skipBufferingOnError
: true,
1435 if (this.isRegistered() === false) {
1436 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1438 this?.bootNotificationResponse
?.interval
1439 ? this.bootNotificationResponse
.interval
* 1000
1440 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1444 this.isRegistered() === false &&
1445 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1446 this.getRegistrationMaxRetries() === -1)
1449 if (this.isRegistered() === true) {
1450 if (this.isInAcceptedState() === true) {
1451 await this.startMessageSequence();
1455 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1458 this.wsConnectionRestarted
= false;
1459 this.autoReconnectRetryCount
= 0;
1460 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1463 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1468 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1471 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1472 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1474 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1476 )}' and reason '${reason.toString()}'`
1478 this.autoReconnectRetryCount
= 0;
1483 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1485 )}' and reason '${reason.toString()}'`
1487 this.started
=== true && (await this.reconnect());
1490 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1493 private async onMessage(data
: RawData
): Promise
<void> {
1494 let messageType
: number;
1495 let messageId
: string;
1496 let commandName
: IncomingRequestCommand
;
1497 let commandPayload
: JsonType
;
1498 let errorType
: ErrorType
;
1499 let errorMessage
: string;
1500 let errorDetails
: JsonType
;
1501 let responseCallback
: ResponseCallback
;
1502 let errorCallback
: ErrorCallback
;
1503 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1504 let requestPayload
: JsonType
;
1505 let cachedRequest
: CachedRequest
;
1508 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1509 if (Array.isArray(request
) === true) {
1510 [messageType
, messageId
] = request
;
1511 // Check the type of message
1512 switch (messageType
) {
1514 case MessageType
.CALL_MESSAGE
:
1515 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1516 if (this.getEnableStatistics() === true) {
1517 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1520 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1524 // Process the message
1525 await this.ocppIncomingRequestService
.incomingRequestHandler(
1533 case MessageType
.CALL_RESULT_MESSAGE
:
1534 [, , commandPayload
] = request
as Response
;
1535 if (this.requests
.has(messageId
) === false) {
1537 throw new OCPPError(
1538 ErrorType
.INTERNAL_ERROR
,
1539 `Response for unknown message id ${messageId}`,
1545 cachedRequest
= this.requests
.get(messageId
);
1546 if (Array.isArray(cachedRequest
) === true) {
1547 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1549 throw new OCPPError(
1550 ErrorType
.PROTOCOL_ERROR
,
1551 `Cached request for message id ${messageId} response is not an array`,
1553 cachedRequest
as unknown
as JsonType
1557 `${this.logPrefix()} << Command '${
1558 requestCommandName ?? Constants.UNKNOWN_COMMAND
1559 }' received response payload: ${JSON.stringify(request)}`
1561 responseCallback(commandPayload
, requestPayload
);
1564 case MessageType
.CALL_ERROR_MESSAGE
:
1565 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1566 if (this.requests
.has(messageId
) === false) {
1568 throw new OCPPError(
1569 ErrorType
.INTERNAL_ERROR
,
1570 `Error response for unknown message id ${messageId}`,
1572 { errorType
, errorMessage
, errorDetails
}
1575 cachedRequest
= this.requests
.get(messageId
);
1576 if (Array.isArray(cachedRequest
) === true) {
1577 [, errorCallback
, requestCommandName
] = cachedRequest
;
1579 throw new OCPPError(
1580 ErrorType
.PROTOCOL_ERROR
,
1581 `Cached request for message id ${messageId} error response is not an array`,
1583 cachedRequest
as unknown
as JsonType
1587 `${this.logPrefix()} << Command '${
1588 requestCommandName ?? Constants.UNKNOWN_COMMAND
1589 }' received error response payload: ${JSON.stringify(request)}`
1591 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1595 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1596 errMsg
= `Wrong message type ${messageType}`;
1597 logger
.error(`${this.logPrefix()} ${errMsg}`);
1598 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1600 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1602 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1609 `${this.logPrefix()} Incoming OCPP command '${
1610 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1611 }' message '${data.toString()}'${
1612 messageType !== MessageType.CALL_MESSAGE
1613 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1615 } processing error:`,
1618 if (error
instanceof OCPPError
=== false) {
1620 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1621 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1622 }' message '${data.toString()}' handling is not an OCPPError:`,
1626 switch (messageType
) {
1627 case MessageType
.CALL_MESSAGE
:
1629 await this.ocppRequestService
.sendError(
1633 commandName
?? requestCommandName
?? null
1636 case MessageType
.CALL_RESULT_MESSAGE
:
1637 case MessageType
.CALL_ERROR_MESSAGE
:
1638 if (errorCallback
) {
1639 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1640 errorCallback(error
as OCPPError
, false);
1642 // Remove the request from the cache in case of error at response handling
1643 this.requests
.delete(messageId
);
1650 private onPing(): void {
1651 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1654 private onPong(): void {
1655 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1658 private onError(error
: WSError
): void {
1659 this.closeWSConnection();
1660 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1663 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1664 if (this.getMeteringPerTransaction() === true) {
1667 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1668 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1673 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1674 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1678 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1679 const localStationInfo
= stationInfo
?? this.stationInfo
;
1680 return localStationInfo
?.useConnectorId0
?? true;
1683 private getNumberOfRunningTransactions(): number {
1685 for (const connectorId
of this.connectors
.keys()) {
1686 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1693 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1694 for (const connectorId
of this.connectors
.keys()) {
1695 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1696 await this.stopTransactionOnConnector(connectorId
, reason
);
1702 private getConnectionTimeout(): number {
1704 ChargingStationConfigurationUtils
.getConfigurationKey(
1706 StandardParametersKey
.ConnectionTimeOut
1711 ChargingStationConfigurationUtils
.getConfigurationKey(
1713 StandardParametersKey
.ConnectionTimeOut
1715 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1718 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1721 // -1 for unlimited, 0 for disabling
1722 private getAutoReconnectMaxRetries(): number | undefined {
1723 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1724 return this.stationInfo
.autoReconnectMaxRetries
;
1726 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1727 return Configuration
.getAutoReconnectMaxRetries();
1733 private getRegistrationMaxRetries(): number | undefined {
1734 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1735 return this.stationInfo
.registrationMaxRetries
;
1740 private getPowerDivider(): number {
1741 let powerDivider
= this.getNumberOfConnectors();
1742 if (this.stationInfo
?.powerSharedByConnectors
) {
1743 powerDivider
= this.getNumberOfRunningTransactions();
1745 return powerDivider
;
1748 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1749 const maximumPower
= this.getMaximumPower(stationInfo
);
1750 switch (this.getCurrentOutType(stationInfo
)) {
1751 case CurrentType
.AC
:
1752 return ACElectricUtils
.amperagePerPhaseFromPower(
1753 this.getNumberOfPhases(stationInfo
),
1754 maximumPower
/ this.getNumberOfConnectors(),
1755 this.getVoltageOut(stationInfo
)
1757 case CurrentType
.DC
:
1758 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1762 private getAmperageLimitation(): number | undefined {
1764 !Utils
.isEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1765 ChargingStationConfigurationUtils
.getConfigurationKey(
1767 this.stationInfo
.amperageLimitationOcppKey
1772 ChargingStationConfigurationUtils
.getConfigurationKey(
1774 this.stationInfo
.amperageLimitationOcppKey
1776 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1781 private async startMessageSequence(): Promise
<void> {
1782 if (this.stationInfo
?.autoRegister
=== true) {
1783 await this.ocppRequestService
.requestHandler
<
1784 BootNotificationRequest
,
1785 BootNotificationResponse
1786 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1787 skipBufferingOnError
: true,
1790 // Start WebSocket ping
1791 this.startWebSocketPing();
1793 this.startHeartbeat();
1794 // Initialize connectors status
1795 for (const connectorId
of this.connectors
.keys()) {
1796 let connectorStatus
: ConnectorStatusEnum
| undefined;
1797 if (connectorId
=== 0) {
1800 !this.getConnectorStatus(connectorId
)?.status &&
1801 (this.isChargingStationAvailable() === false ||
1802 this.isConnectorAvailable(connectorId
) === false)
1804 connectorStatus
= ConnectorStatusEnum
.UNAVAILABLE
;
1806 !this.getConnectorStatus(connectorId
)?.status &&
1807 this.getConnectorStatus(connectorId
)?.bootStatus
1809 // Set boot status in template at startup
1810 connectorStatus
= this.getConnectorStatus(connectorId
)?.bootStatus
;
1811 } else if (this.getConnectorStatus(connectorId
)?.status) {
1812 // Set previous status at startup
1813 connectorStatus
= this.getConnectorStatus(connectorId
)?.status;
1815 // Set default status
1816 connectorStatus
= ConnectorStatusEnum
.AVAILABLE
;
1818 await this.ocppRequestService
.requestHandler
<
1819 StatusNotificationRequest
,
1820 StatusNotificationResponse
1823 RequestCommand
.STATUS_NOTIFICATION
,
1824 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1826 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1828 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1829 await this.ocppRequestService
.requestHandler
<
1830 FirmwareStatusNotificationRequest
,
1831 FirmwareStatusNotificationResponse
1832 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1833 status: FirmwareStatus
.Installed
,
1835 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1839 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1840 this.startAutomaticTransactionGenerator();
1842 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1845 private async stopMessageSequence(
1846 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1848 // Stop WebSocket ping
1849 this.stopWebSocketPing();
1851 this.stopHeartbeat();
1852 // Stop ongoing transactions
1853 if (this.automaticTransactionGenerator
?.started
=== true) {
1854 this.stopAutomaticTransactionGenerator();
1856 await this.stopRunningTransactions(reason
);
1858 for (const connectorId
of this.connectors
.keys()) {
1859 if (connectorId
> 0) {
1860 await this.ocppRequestService
.requestHandler
<
1861 StatusNotificationRequest
,
1862 StatusNotificationResponse
1865 RequestCommand
.STATUS_NOTIFICATION
,
1866 OCPPServiceUtils
.buildStatusNotificationRequest(
1869 ConnectorStatusEnum
.UNAVAILABLE
1872 this.getConnectorStatus(connectorId
).status = undefined;
1877 private startWebSocketPing(): void {
1878 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1880 StandardParametersKey
.WebSocketPingInterval
1882 ? Utils
.convertToInt(
1883 ChargingStationConfigurationUtils
.getConfigurationKey(
1885 StandardParametersKey
.WebSocketPingInterval
1889 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1890 this.webSocketPingSetInterval
= setInterval(() => {
1891 if (this.isWebSocketConnectionOpened() === true) {
1892 this.wsConnection
?.ping();
1894 }, webSocketPingInterval
* 1000);
1896 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
1897 webSocketPingInterval
1900 } else if (this.webSocketPingSetInterval
) {
1902 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
1903 webSocketPingInterval
1908 `${this.logPrefix()} WebSocket ping interval set to ${
1909 webSocketPingInterval
1910 ? Utils.formatDurationSeconds(webSocketPingInterval)
1911 : webSocketPingInterval
1912 }, not starting the WebSocket ping`
1917 private stopWebSocketPing(): void {
1918 if (this.webSocketPingSetInterval
) {
1919 clearInterval(this.webSocketPingSetInterval
);
1923 private getConfiguredSupervisionUrl(): URL
{
1924 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
1925 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1926 switch (Configuration
.getSupervisionUrlDistribution()) {
1927 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1929 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1931 case SupervisionUrlDistribution
.RANDOM
:
1932 this.configuredSupervisionUrlIndex
= Math.floor(
1933 Utils
.secureRandom() * supervisionUrls
.length
1936 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1937 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1941 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1942 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1945 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1948 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1950 return new URL(supervisionUrls
as string);
1953 private getHeartbeatInterval(): number {
1954 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1956 StandardParametersKey
.HeartbeatInterval
1958 if (HeartbeatInterval
) {
1959 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1961 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1963 StandardParametersKey
.HeartBeatInterval
1965 if (HeartBeatInterval
) {
1966 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1968 this.stationInfo
?.autoRegister
=== false &&
1970 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1971 Constants.DEFAULT_HEARTBEAT_INTERVAL
1974 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1977 private stopHeartbeat(): void {
1978 if (this.heartbeatSetInterval
) {
1979 clearInterval(this.heartbeatSetInterval
);
1983 private terminateWSConnection(): void {
1984 if (this.isWebSocketConnectionOpened() === true) {
1985 this.wsConnection
?.terminate();
1986 this.wsConnection
= null;
1990 private stopMeterValues(connectorId
: number) {
1991 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1992 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
1996 private getReconnectExponentialDelay(): boolean {
1997 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2000 private async reconnect(): Promise
<void> {
2001 // Stop WebSocket ping
2002 this.stopWebSocketPing();
2004 this.stopHeartbeat();
2005 // Stop the ATG if needed
2006 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2007 this.stopAutomaticTransactionGenerator();
2010 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2011 this.getAutoReconnectMaxRetries() === -1
2013 this.autoReconnectRetryCount
++;
2014 const reconnectDelay
= this.getReconnectExponentialDelay()
2015 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2016 : this.getConnectionTimeout() * 1000;
2017 const reconnectDelayWithdraw
= 1000;
2018 const reconnectTimeout
=
2019 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2020 ? reconnectDelay
- reconnectDelayWithdraw
2023 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2026 )}ms, timeout ${reconnectTimeout}ms`
2028 await Utils
.sleep(reconnectDelay
);
2030 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2032 this.openWSConnection(
2033 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2034 { closeOpened
: true }
2036 this.wsConnectionRestarted
= true;
2037 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2039 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2040 this.autoReconnectRetryCount
2041 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2046 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2047 | AutomaticTransactionGeneratorConfiguration
2049 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
2052 private initializeConnectorStatus(connectorId
: number): void {
2053 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2054 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2055 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2056 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2057 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2058 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;