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
;
104 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
105 public wsConnection
!: WebSocket
;
106 public readonly connectors
: Map
<number, ConnectorStatus
>;
107 public readonly requests
: Map
<string, CachedRequest
>;
108 public performanceStatistics
!: PerformanceStatistics
;
109 public heartbeatSetInterval
!: NodeJS
.Timeout
;
110 public ocppRequestService
!: OCPPRequestService
;
111 public bootNotificationRequest
!: BootNotificationRequest
;
112 public bootNotificationResponse
!: BootNotificationResponse
| null;
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
;
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
{
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()) {
303 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
304 return this.getConnectorStatus(connectorId
).transactionIdTag
;
309 public getOutOfOrderEndMeterValues(): boolean {
310 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
313 public getBeginEndMeterValues(): boolean {
314 return this.stationInfo
?.beginEndMeterValues
?? false;
317 public getMeteringPerTransaction(): boolean {
318 return this.stationInfo
?.meteringPerTransaction
?? true;
321 public getTransactionDataMeterValues(): boolean {
322 return this.stationInfo
?.transactionDataMeterValues
?? false;
325 public getMainVoltageMeterValues(): boolean {
326 return this.stationInfo
?.mainVoltageMeterValues
?? true;
329 public getPhaseLineToLineVoltageMeterValues(): boolean {
330 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
333 public getCustomValueLimitationMeterValues(): boolean {
334 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
337 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
338 for (const connectorId
of this.connectors
.keys()) {
341 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
348 public getEnergyActiveImportRegisterByTransactionId(
349 transactionId
: number,
352 return this.getEnergyActiveImportRegister(
353 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
358 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
359 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
362 public getAuthorizeRemoteTxRequests(): boolean {
363 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
365 StandardParametersKey
.AuthorizeRemoteTxRequests
367 return authorizeRemoteTxRequests
368 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
372 public getLocalAuthListEnabled(): boolean {
373 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
375 StandardParametersKey
.LocalAuthListEnabled
377 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
380 public startHeartbeat(): void {
382 this.getHeartbeatInterval() &&
383 this.getHeartbeatInterval() > 0 &&
384 !this.heartbeatSetInterval
386 this.heartbeatSetInterval
= setInterval(() => {
387 this.ocppRequestService
388 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
391 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
395 }, this.getHeartbeatInterval());
397 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
398 this.getHeartbeatInterval()
401 } else if (this.heartbeatSetInterval
) {
403 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
404 this.getHeartbeatInterval()
409 `${this.logPrefix()} Heartbeat interval set to ${
410 this.getHeartbeatInterval()
411 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
412 : this.getHeartbeatInterval()
413 }, not starting the heartbeat`
418 public restartHeartbeat(): void {
420 this.stopHeartbeat();
422 this.startHeartbeat();
425 public restartWebSocketPing(): void {
426 // Stop WebSocket ping
427 this.stopWebSocketPing();
428 // Start WebSocket ping
429 this.startWebSocketPing();
432 public startMeterValues(connectorId
: number, interval
: number): void {
433 if (connectorId
=== 0) {
435 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
439 if (!this.getConnectorStatus(connectorId
)) {
441 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
445 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
447 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
451 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
452 !this.getConnectorStatus(connectorId
)?.transactionId
455 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
460 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
461 // FIXME: Implement OCPP version agnostic helpers
462 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
465 this.getConnectorStatus(connectorId
).transactionId
,
468 this.ocppRequestService
469 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
471 RequestCommand
.METER_VALUES
,
474 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
475 meterValue
: [meterValue
],
480 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
487 `${this.logPrefix()} Charging station ${
488 StandardParametersKey.MeterValueSampleInterval
489 } configuration set to ${
490 interval ? Utils.formatDurationMilliSeconds(interval) : interval
491 }, not sending MeterValues`
496 public start(): void {
497 if (this.started
=== false) {
498 if (this.starting
=== false) {
499 this.starting
= true;
500 if (this.getEnableStatistics() === true) {
501 this.performanceStatistics
.start();
503 this.openWSConnection();
504 // Monitor charging station template file
505 this.templateFileWatcher
= FileUtils
.watchJsonFile(
507 FileType
.ChargingStationTemplate
,
510 (event
, filename
): void => {
511 if (filename
&& event
=== 'change') {
514 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
516 } file have changed, reload`
518 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
522 this.stopAutomaticTransactionGenerator();
524 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
526 this.startAutomaticTransactionGenerator();
528 if (this.getEnableStatistics() === true) {
529 this.performanceStatistics
.restart();
531 this.performanceStatistics
.stop();
533 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
536 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
544 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
545 this.starting
= false;
547 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
550 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
554 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
555 if (this.started
=== true) {
556 if (this.stopping
=== false) {
557 this.stopping
= true;
558 await this.stopMessageSequence(reason
);
559 this.closeWSConnection();
560 if (this.getEnableStatistics() === true) {
561 this.performanceStatistics
.stop();
563 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
564 this.templateFileWatcher
.close();
565 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
566 this.bootNotificationResponse
= null;
567 this.started
= false;
568 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
569 this.stopping
= false;
571 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
574 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
578 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
579 await this.stop(reason
);
580 await Utils
.sleep(this.stationInfo
.resetTime
);
585 public saveOcppConfiguration(): void {
586 if (this.getOcppPersistentConfiguration()) {
587 this.saveConfiguration();
591 public resetConnectorStatus(connectorId
: number): void {
592 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
593 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
594 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
595 this.getConnectorStatus(connectorId
).transactionStarted
= false;
596 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
597 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
598 delete this.getConnectorStatus(connectorId
).transactionId
;
599 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
600 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
601 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
602 this.stopMeterValues(connectorId
);
603 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
606 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
607 return ChargingStationConfigurationUtils
.getConfigurationKey(
609 StandardParametersKey
.SupportedFeatureProfiles
610 )?.value
.includes(featureProfile
);
613 public bufferMessage(message
: string): void {
614 this.messageBuffer
.add(message
);
617 public openWSConnection(
618 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
619 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
621 terminateOpened
: false,
624 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
625 params
.closeOpened
= params
?.closeOpened
?? false;
626 params
.terminateOpened
= params
?.terminateOpened
?? false;
627 if (this.started
=== false && this.starting
=== false) {
629 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
634 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
635 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
637 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
639 if (params
?.closeOpened
) {
640 this.closeWSConnection();
642 if (params
?.terminateOpened
) {
643 this.terminateWSConnection();
645 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
646 let protocol
: string;
647 switch (ocppVersion
) {
648 case OCPPVersion
.VERSION_16
:
649 case OCPPVersion
.VERSION_20
:
650 case OCPPVersion
.VERSION_201
:
651 protocol
= `ocpp${ocppVersion}`;
654 this.handleUnsupportedVersion(ocppVersion
);
658 if (this.isWebSocketConnectionOpened() === true) {
660 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
666 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
669 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
671 // Handle WebSocket message
672 this.wsConnection
.on(
674 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
676 // Handle WebSocket error
677 this.wsConnection
.on(
679 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
681 // Handle WebSocket close
682 this.wsConnection
.on(
684 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
686 // Handle WebSocket open
687 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
688 // Handle WebSocket ping
689 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
690 // Handle WebSocket pong
691 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
694 public closeWSConnection(): void {
695 if (this.isWebSocketConnectionOpened() === true) {
696 this.wsConnection
.close();
697 this.wsConnection
= null;
701 public startAutomaticTransactionGenerator(
702 connectorIds
?: number[],
703 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
705 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
706 automaticTransactionGeneratorConfiguration
??
707 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
710 if (!Utils
.isEmptyArray(connectorIds
)) {
711 for (const connectorId
of connectorIds
) {
712 this.automaticTransactionGenerator
.startConnector(connectorId
);
715 this.automaticTransactionGenerator
.start();
717 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
720 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
721 if (!Utils
.isEmptyArray(connectorIds
)) {
722 for (const connectorId
of connectorIds
) {
723 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
726 this.automaticTransactionGenerator
?.stop();
728 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
731 public async stopTransactionOnConnector(
733 reason
= StopTransactionReason
.NONE
734 ): Promise
<StopTransactionResponse
> {
735 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
737 this.getBeginEndMeterValues() === true &&
738 this.getOcppStrictCompliance() === true &&
739 this.getOutOfOrderEndMeterValues() === false
741 // FIXME: Implement OCPP version agnostic helpers
742 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
745 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
747 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
749 RequestCommand
.METER_VALUES
,
753 meterValue
: [transactionEndMeterValue
],
757 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
759 RequestCommand
.STOP_TRANSACTION
,
762 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
768 private flushMessageBuffer(): void {
769 if (this.messageBuffer
.size
> 0) {
770 this.messageBuffer
.forEach((message
) => {
772 let commandName
: RequestCommand
;
773 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
774 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
776 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
777 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
779 this.wsConnection
.send(message
);
780 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
782 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
784 )} payload sent: ${message}`
786 this.messageBuffer
.delete(message
);
791 private getSupervisionUrlOcppConfiguration(): boolean {
792 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
795 private getSupervisionUrlOcppKey(): string {
796 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
799 private getTemplateFromFile(): ChargingStationTemplate
| null {
800 let template
: ChargingStationTemplate
= null;
802 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
803 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
805 const measureId
= `${FileType.ChargingStationTemplate} read`;
806 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
807 template
= JSON
.parse(
808 fs
.readFileSync(this.templateFile
, 'utf8')
809 ) as ChargingStationTemplate
;
810 PerformanceStatistics
.endMeasure(measureId
, beginId
);
811 template
.templateHash
= crypto
812 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
813 .update(JSON
.stringify(template
))
815 this.sharedLRUCache
.setChargingStationTemplate(template
);
818 FileUtils
.handleFileException(
820 FileType
.ChargingStationTemplate
,
822 error
as NodeJS
.ErrnoException
828 private getStationInfoFromTemplate(): ChargingStationInfo
{
829 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
830 if (Utils
.isNullOrUndefined(stationTemplate
)) {
831 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
832 logger
.error(`${this.logPrefix()} ${errorMsg}`);
833 throw new BaseError(errorMsg
);
835 if (Utils
.isEmptyObject(stationTemplate
)) {
836 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
837 logger
.error(`${this.logPrefix()} ${errorMsg}`);
838 throw new BaseError(errorMsg
);
840 // Deprecation template keys section
841 ChargingStationUtils
.warnDeprecatedTemplateKey(
846 "Use 'supervisionUrls' instead"
848 ChargingStationUtils
.convertDeprecatedTemplateKey(
853 const stationInfo
: ChargingStationInfo
=
854 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
855 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
856 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
860 stationInfo
.ocppVersion
= stationTemplate
.ocppVersion
?? OCPPVersion
.VERSION_16
;
861 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
862 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
863 stationTemplate
.power
= stationTemplate
.power
as number[];
864 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
865 stationInfo
.maximumPower
=
866 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
867 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
868 : stationTemplate
.power
[powerArrayRandomIndex
];
870 stationTemplate
.power
= stationTemplate
.power
as number;
871 stationInfo
.maximumPower
=
872 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
873 ? stationTemplate
.power
* 1000
874 : stationTemplate
.power
;
876 stationInfo
.firmwareVersionPattern
=
877 stationTemplate
.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
879 stationInfo
.firmwareVersion
&&
880 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
883 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
885 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
888 stationInfo
.firmwareUpgrade
= merge(
892 stationTemplate
.firmwareUpgrade
?? {}
894 stationInfo
.resetTime
= stationTemplate
.resetTime
895 ? stationTemplate
.resetTime
* 1000
896 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
897 const configuredMaxConnectors
=
898 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
899 ChargingStationUtils
.checkConfiguredMaxConnectors(
900 configuredMaxConnectors
,
904 const templateMaxConnectors
=
905 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
906 ChargingStationUtils
.checkTemplateMaxConnectors(
907 templateMaxConnectors
,
912 configuredMaxConnectors
>
913 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
914 !stationTemplate
?.randomConnectors
917 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
919 }, forcing random connector configurations affectation`
921 stationInfo
.randomConnectors
= true;
923 // Build connectors if needed (FIXME: should be factored out)
924 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
925 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
926 ChargingStationUtils
.createStationInfoHash(stationInfo
);
930 private getStationInfoFromFile(): ChargingStationInfo
| null {
931 let stationInfo
: ChargingStationInfo
= null;
932 this.getStationInfoPersistentConfiguration() &&
933 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
934 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
938 private getStationInfo(): ChargingStationInfo
{
939 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
940 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
941 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
942 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
943 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
944 return this.stationInfo
;
946 return stationInfoFromFile
;
948 stationInfoFromFile
&&
949 ChargingStationUtils
.propagateSerialNumber(
950 this.getTemplateFromFile(),
952 stationInfoFromTemplate
954 return stationInfoFromTemplate
;
957 private saveStationInfo(): void {
958 if (this.getStationInfoPersistentConfiguration()) {
959 this.saveConfiguration();
963 private getOcppPersistentConfiguration(): boolean {
964 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
967 private getStationInfoPersistentConfiguration(): boolean {
968 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
971 private handleUnsupportedVersion(version
: OCPPVersion
) {
972 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
973 logger
.error(`${this.logPrefix()} ${errMsg}`);
974 throw new BaseError(errMsg
);
977 private initialize(): void {
978 this.configurationFile
= path
.join(
979 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
980 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
982 this.stationInfo
= this.getStationInfo();
983 this.saveStationInfo();
984 // Avoid duplication of connectors related information in RAM
985 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
986 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
987 if (this.getEnableStatistics() === true) {
988 this.performanceStatistics
= PerformanceStatistics
.getInstance(
989 this.stationInfo
.hashId
,
990 this.stationInfo
.chargingStationId
,
991 this.configuredSupervisionUrl
994 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
997 this.powerDivider
= this.getPowerDivider();
998 // OCPP configuration
999 this.ocppConfiguration
= this.getOcppConfiguration();
1000 this.initializeOcppConfiguration();
1001 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1002 switch (ocppVersion
) {
1003 case OCPPVersion
.VERSION_16
:
1004 this.ocppIncomingRequestService
=
1005 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1006 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1007 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1010 case OCPPVersion
.VERSION_20
:
1011 case OCPPVersion
.VERSION_201
:
1012 this.ocppIncomingRequestService
=
1013 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1014 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1015 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1019 this.handleUnsupportedVersion(ocppVersion
);
1022 if (this.stationInfo
?.autoRegister
=== true) {
1023 this.bootNotificationResponse
= {
1024 currentTime
: new Date(),
1025 interval
: this.getHeartbeatInterval() / 1000,
1026 status: RegistrationStatusEnumType
.ACCEPTED
,
1030 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1031 this.stationInfo
.firmwareVersion
&&
1032 this.stationInfo
.firmwareVersionPattern
1034 const versionStep
= this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
?? 1;
1035 const patternGroup
: number =
1036 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1037 this.stationInfo
.firmwareVersion
.split('.').length
;
1038 const match
= this.stationInfo
.firmwareVersion
1039 .match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1040 .slice(1, patternGroup
+ 1);
1041 const patchLevelIndex
= match
.length
- 1;
1042 match
[patchLevelIndex
] = (
1043 Utils
.convertToInt(match
[patchLevelIndex
]) + versionStep
1045 this.stationInfo
.firmwareVersion
= match
.join('.');
1049 private initializeOcppConfiguration(): void {
1051 !ChargingStationConfigurationUtils
.getConfigurationKey(
1053 StandardParametersKey
.HeartbeatInterval
1056 ChargingStationConfigurationUtils
.addConfigurationKey(
1058 StandardParametersKey
.HeartbeatInterval
,
1063 !ChargingStationConfigurationUtils
.getConfigurationKey(
1065 StandardParametersKey
.HeartBeatInterval
1068 ChargingStationConfigurationUtils
.addConfigurationKey(
1070 StandardParametersKey
.HeartBeatInterval
,
1076 this.getSupervisionUrlOcppConfiguration() &&
1077 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1079 ChargingStationConfigurationUtils
.addConfigurationKey(
1081 this.getSupervisionUrlOcppKey(),
1082 this.configuredSupervisionUrl
.href
,
1086 !this.getSupervisionUrlOcppConfiguration() &&
1087 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1089 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1091 this.getSupervisionUrlOcppKey(),
1096 this.stationInfo
.amperageLimitationOcppKey
&&
1097 !ChargingStationConfigurationUtils
.getConfigurationKey(
1099 this.stationInfo
.amperageLimitationOcppKey
1102 ChargingStationConfigurationUtils
.addConfigurationKey(
1104 this.stationInfo
.amperageLimitationOcppKey
,
1106 this.stationInfo
.maximumAmperage
*
1107 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1112 !ChargingStationConfigurationUtils
.getConfigurationKey(
1114 StandardParametersKey
.SupportedFeatureProfiles
1117 ChargingStationConfigurationUtils
.addConfigurationKey(
1119 StandardParametersKey
.SupportedFeatureProfiles
,
1120 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1123 ChargingStationConfigurationUtils
.addConfigurationKey(
1125 StandardParametersKey
.NumberOfConnectors
,
1126 this.getNumberOfConnectors().toString(),
1131 !ChargingStationConfigurationUtils
.getConfigurationKey(
1133 StandardParametersKey
.MeterValuesSampledData
1136 ChargingStationConfigurationUtils
.addConfigurationKey(
1138 StandardParametersKey
.MeterValuesSampledData
,
1139 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1143 !ChargingStationConfigurationUtils
.getConfigurationKey(
1145 StandardParametersKey
.ConnectorPhaseRotation
1148 const connectorPhaseRotation
= [];
1149 for (const connectorId
of this.connectors
.keys()) {
1151 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1152 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1153 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1154 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1156 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1157 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1158 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1159 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1162 ChargingStationConfigurationUtils
.addConfigurationKey(
1164 StandardParametersKey
.ConnectorPhaseRotation
,
1165 connectorPhaseRotation
.toString()
1169 !ChargingStationConfigurationUtils
.getConfigurationKey(
1171 StandardParametersKey
.AuthorizeRemoteTxRequests
1174 ChargingStationConfigurationUtils
.addConfigurationKey(
1176 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1181 !ChargingStationConfigurationUtils
.getConfigurationKey(
1183 StandardParametersKey
.LocalAuthListEnabled
1185 ChargingStationConfigurationUtils
.getConfigurationKey(
1187 StandardParametersKey
.SupportedFeatureProfiles
1188 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1190 ChargingStationConfigurationUtils
.addConfigurationKey(
1192 StandardParametersKey
.LocalAuthListEnabled
,
1197 !ChargingStationConfigurationUtils
.getConfigurationKey(
1199 StandardParametersKey
.ConnectionTimeOut
1202 ChargingStationConfigurationUtils
.addConfigurationKey(
1204 StandardParametersKey
.ConnectionTimeOut
,
1205 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1208 this.saveOcppConfiguration();
1211 private initializeConnectors(
1212 stationInfo
: ChargingStationInfo
,
1213 configuredMaxConnectors
: number,
1214 templateMaxConnectors
: number
1216 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1217 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1218 logger
.error(`${this.logPrefix()} ${logMsg}`);
1219 throw new BaseError(logMsg
);
1221 if (!stationInfo
?.Connectors
[0]) {
1223 `${this.logPrefix()} Charging station information from template ${
1225 } with no connector Id 0 configuration`
1228 if (stationInfo
?.Connectors
) {
1229 const connectorsConfigHash
= crypto
1230 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1231 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1233 const connectorsConfigChanged
=
1234 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1235 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1236 connectorsConfigChanged
&& this.connectors
.clear();
1237 this.connectorsConfigurationHash
= connectorsConfigHash
;
1238 // Add connector Id 0
1239 let lastConnector
= '0';
1240 for (lastConnector
in stationInfo
?.Connectors
) {
1241 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1242 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1244 lastConnectorId
=== 0 &&
1245 this.getUseConnectorId0(stationInfo
) === true &&
1248 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1249 this.connectors
.set(
1251 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1253 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1254 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1255 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1259 // Generate all connectors
1260 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1261 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1262 const randConnectorId
= stationInfo
?.randomConnectors
1263 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1265 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1266 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1267 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1268 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1269 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1270 this.getConnectorStatus(index
).chargingProfiles
= [];
1277 `${this.logPrefix()} Charging station information from template ${
1279 } with no connectors configuration defined, using already defined connectors`
1282 // Initialize transaction attributes on connectors
1283 for (const connectorId
of this.connectors
.keys()) {
1284 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionStarted
=== true) {
1286 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1287 this.getConnectorStatus(connectorId).transactionId
1293 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1294 this.getConnectorStatus(connectorId
).transactionStarted
=== null)
1296 this.initializeConnectorStatus(connectorId
);
1301 private checkStationInfoConnectorStatus(
1302 connectorId
: number,
1303 connectorStatus
: ConnectorStatus
1305 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1307 `${this.logPrefix()} Charging station information from template ${
1309 } with connector ${connectorId} status configuration defined, undefine it`
1311 connectorStatus
.status = undefined;
1315 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1316 let configuration
: ChargingStationConfiguration
= null;
1317 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1319 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1320 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1321 this.configurationFileHash
1324 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1325 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1326 configuration
= JSON
.parse(
1327 fs
.readFileSync(this.configurationFile
, 'utf8')
1328 ) as ChargingStationConfiguration
;
1329 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1330 this.configurationFileHash
= configuration
.configurationHash
;
1331 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1334 FileUtils
.handleFileException(
1336 FileType
.ChargingStationConfiguration
,
1337 this.configurationFile
,
1338 error
as NodeJS
.ErrnoException
1342 return configuration
;
1345 private saveConfiguration(): void {
1346 if (this.configurationFile
) {
1348 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1349 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1351 const configurationData
: ChargingStationConfiguration
=
1352 this.getConfigurationFromFile() ?? {};
1353 this.ocppConfiguration
?.configurationKey
&&
1354 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1355 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1356 delete configurationData
.configurationHash
;
1357 const configurationHash
= crypto
1358 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1359 .update(JSON
.stringify(configurationData
))
1361 if (this.configurationFileHash
!== configurationHash
) {
1362 configurationData
.configurationHash
= configurationHash
;
1363 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1364 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1365 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1366 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1367 fs
.closeSync(fileDescriptor
);
1368 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1369 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1370 this.configurationFileHash
= configurationHash
;
1371 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1374 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1375 this.configurationFile
1380 FileUtils
.handleFileException(
1382 FileType
.ChargingStationConfiguration
,
1383 this.configurationFile
,
1384 error
as NodeJS
.ErrnoException
1389 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1394 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1395 return this.getTemplateFromFile()?.Configuration
?? null;
1398 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1399 let configuration
: ChargingStationConfiguration
= null;
1400 if (this.getOcppPersistentConfiguration() === true) {
1401 const configurationFromFile
= this.getConfigurationFromFile();
1402 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1404 configuration
&& delete configuration
.stationInfo
;
1405 return configuration
;
1408 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1409 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1410 if (!ocppConfiguration
) {
1411 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1413 return ocppConfiguration
;
1416 private async onOpen(): Promise
<void> {
1417 if (this.isWebSocketConnectionOpened() === true) {
1419 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1421 if (this.isRegistered() === false) {
1422 // Send BootNotification
1423 let registrationRetryCount
= 0;
1425 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1426 BootNotificationRequest
,
1427 BootNotificationResponse
1428 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1429 skipBufferingOnError
: true,
1431 if (this.isRegistered() === false) {
1432 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1434 this.bootNotificationResponse
?.interval
1435 ? this.bootNotificationResponse
.interval
* 1000
1436 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1440 this.isRegistered() === false &&
1441 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1442 this.getRegistrationMaxRetries() === -1)
1445 if (this.isRegistered() === true) {
1446 if (this.isInAcceptedState() === true) {
1447 await this.startMessageSequence();
1451 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1454 this.wsConnectionRestarted
= false;
1455 this.autoReconnectRetryCount
= 0;
1456 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1459 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1464 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1467 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1468 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1470 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1472 )}' and reason '${reason.toString()}'`
1474 this.autoReconnectRetryCount
= 0;
1479 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1481 )}' and reason '${reason.toString()}'`
1483 this.started
=== true && (await this.reconnect());
1486 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1489 private async onMessage(data
: RawData
): Promise
<void> {
1490 let messageType
: number;
1491 let messageId
: string;
1492 let commandName
: IncomingRequestCommand
;
1493 let commandPayload
: JsonType
;
1494 let errorType
: ErrorType
;
1495 let errorMessage
: string;
1496 let errorDetails
: JsonType
;
1497 let responseCallback
: ResponseCallback
;
1498 let errorCallback
: ErrorCallback
;
1499 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1500 let requestPayload
: JsonType
;
1501 let cachedRequest
: CachedRequest
;
1504 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1505 if (Array.isArray(request
) === true) {
1506 [messageType
, messageId
] = request
;
1507 // Check the type of message
1508 switch (messageType
) {
1510 case MessageType
.CALL_MESSAGE
:
1511 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1512 if (this.getEnableStatistics() === true) {
1513 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1516 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1520 // Process the message
1521 await this.ocppIncomingRequestService
.incomingRequestHandler(
1529 case MessageType
.CALL_RESULT_MESSAGE
:
1530 [, , commandPayload
] = request
as Response
;
1531 if (this.requests
.has(messageId
) === false) {
1533 throw new OCPPError(
1534 ErrorType
.INTERNAL_ERROR
,
1535 `Response for unknown message id ${messageId}`,
1541 cachedRequest
= this.requests
.get(messageId
);
1542 if (Array.isArray(cachedRequest
) === true) {
1543 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1545 throw new OCPPError(
1546 ErrorType
.PROTOCOL_ERROR
,
1547 `Cached request for message id ${messageId} response is not an array`,
1549 cachedRequest
as unknown
as JsonType
1553 `${this.logPrefix()} << Command '${
1554 requestCommandName ?? Constants.UNKNOWN_COMMAND
1555 }' received response payload: ${JSON.stringify(request)}`
1557 responseCallback(commandPayload
, requestPayload
);
1560 case MessageType
.CALL_ERROR_MESSAGE
:
1561 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1562 if (this.requests
.has(messageId
) === false) {
1564 throw new OCPPError(
1565 ErrorType
.INTERNAL_ERROR
,
1566 `Error response for unknown message id ${messageId}`,
1568 { errorType
, errorMessage
, errorDetails
}
1571 cachedRequest
= this.requests
.get(messageId
);
1572 if (Array.isArray(cachedRequest
) === true) {
1573 [, errorCallback
, requestCommandName
] = cachedRequest
;
1575 throw new OCPPError(
1576 ErrorType
.PROTOCOL_ERROR
,
1577 `Cached request for message id ${messageId} error response is not an array`,
1579 cachedRequest
as unknown
as JsonType
1583 `${this.logPrefix()} << Command '${
1584 requestCommandName ?? Constants.UNKNOWN_COMMAND
1585 }' received error response payload: ${JSON.stringify(request)}`
1587 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1591 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1592 errMsg
= `Wrong message type ${messageType}`;
1593 logger
.error(`${this.logPrefix()} ${errMsg}`);
1594 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1596 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1598 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1605 `${this.logPrefix()} Incoming OCPP command '${
1606 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1607 }' message '${data.toString()}'${
1608 messageType !== MessageType.CALL_MESSAGE
1609 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1611 } processing error:`,
1614 if (error
instanceof OCPPError
=== false) {
1616 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1617 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1618 }' message '${data.toString()}' handling is not an OCPPError:`,
1622 switch (messageType
) {
1623 case MessageType
.CALL_MESSAGE
:
1625 await this.ocppRequestService
.sendError(
1629 commandName
?? requestCommandName
?? null
1632 case MessageType
.CALL_RESULT_MESSAGE
:
1633 case MessageType
.CALL_ERROR_MESSAGE
:
1634 if (errorCallback
) {
1635 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1636 errorCallback(error
as OCPPError
, false);
1638 // Remove the request from the cache in case of error at response handling
1639 this.requests
.delete(messageId
);
1646 private onPing(): void {
1647 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1650 private onPong(): void {
1651 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1654 private onError(error
: WSError
): void {
1655 this.closeWSConnection();
1656 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1659 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1660 if (this.getMeteringPerTransaction() === true) {
1663 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1664 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1669 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1670 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1674 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1675 const localStationInfo
= stationInfo
?? this.stationInfo
;
1676 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1677 ? localStationInfo
.useConnectorId0
1681 private getNumberOfRunningTransactions(): number {
1683 for (const connectorId
of this.connectors
.keys()) {
1684 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1691 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1692 for (const connectorId
of this.connectors
.keys()) {
1693 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1694 await this.stopTransactionOnConnector(connectorId
, reason
);
1700 private getConnectionTimeout(): number {
1702 ChargingStationConfigurationUtils
.getConfigurationKey(
1704 StandardParametersKey
.ConnectionTimeOut
1709 ChargingStationConfigurationUtils
.getConfigurationKey(
1711 StandardParametersKey
.ConnectionTimeOut
1713 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1716 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1719 // -1 for unlimited, 0 for disabling
1720 private getAutoReconnectMaxRetries(): number {
1721 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1722 return this.stationInfo
.autoReconnectMaxRetries
;
1724 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1725 return Configuration
.getAutoReconnectMaxRetries();
1731 private getRegistrationMaxRetries(): number {
1732 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1733 return this.stationInfo
.registrationMaxRetries
;
1738 private getPowerDivider(): number {
1739 let powerDivider
= this.getNumberOfConnectors();
1740 if (this.stationInfo
?.powerSharedByConnectors
) {
1741 powerDivider
= this.getNumberOfRunningTransactions();
1743 return powerDivider
;
1746 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1747 const maximumPower
= this.getMaximumPower(stationInfo
);
1748 switch (this.getCurrentOutType(stationInfo
)) {
1749 case CurrentType
.AC
:
1750 return ACElectricUtils
.amperagePerPhaseFromPower(
1751 this.getNumberOfPhases(stationInfo
),
1752 maximumPower
/ this.getNumberOfConnectors(),
1753 this.getVoltageOut(stationInfo
)
1755 case CurrentType
.DC
:
1756 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1760 private getAmperageLimitation(): number | undefined {
1762 this.stationInfo
.amperageLimitationOcppKey
&&
1763 ChargingStationConfigurationUtils
.getConfigurationKey(
1765 this.stationInfo
.amperageLimitationOcppKey
1770 ChargingStationConfigurationUtils
.getConfigurationKey(
1772 this.stationInfo
.amperageLimitationOcppKey
1774 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1779 private async startMessageSequence(): Promise
<void> {
1780 if (this.stationInfo
?.autoRegister
=== true) {
1781 await this.ocppRequestService
.requestHandler
<
1782 BootNotificationRequest
,
1783 BootNotificationResponse
1784 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1785 skipBufferingOnError
: true,
1788 // Start WebSocket ping
1789 this.startWebSocketPing();
1791 this.startHeartbeat();
1792 // Initialize connectors status
1793 for (const connectorId
of this.connectors
.keys()) {
1794 let connectorStatus
: ConnectorStatusEnum
;
1795 if (connectorId
=== 0) {
1798 !this.getConnectorStatus(connectorId
)?.status &&
1799 (this.isChargingStationAvailable() === false ||
1800 this.isConnectorAvailable(connectorId
) === false)
1802 connectorStatus
= ConnectorStatusEnum
.UNAVAILABLE
;
1804 !this.getConnectorStatus(connectorId
)?.status &&
1805 this.getConnectorStatus(connectorId
)?.bootStatus
1807 // Set boot status in template at startup
1808 connectorStatus
= this.getConnectorStatus(connectorId
).bootStatus
;
1809 } else if (this.getConnectorStatus(connectorId
)?.status) {
1810 // Set previous status at startup
1811 connectorStatus
= this.getConnectorStatus(connectorId
).status;
1813 // Set default status
1814 connectorStatus
= ConnectorStatusEnum
.AVAILABLE
;
1816 await this.ocppRequestService
.requestHandler
<
1817 StatusNotificationRequest
,
1818 StatusNotificationResponse
1821 RequestCommand
.STATUS_NOTIFICATION
,
1822 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1824 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1826 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1827 await this.ocppRequestService
.requestHandler
<
1828 FirmwareStatusNotificationRequest
,
1829 FirmwareStatusNotificationResponse
1830 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1831 status: FirmwareStatus
.Installed
,
1833 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1837 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1838 this.startAutomaticTransactionGenerator();
1840 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1843 private async stopMessageSequence(
1844 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1846 // Stop WebSocket ping
1847 this.stopWebSocketPing();
1849 this.stopHeartbeat();
1850 // Stop ongoing transactions
1851 if (this.automaticTransactionGenerator
?.started
=== true) {
1852 this.stopAutomaticTransactionGenerator();
1854 await this.stopRunningTransactions(reason
);
1856 for (const connectorId
of this.connectors
.keys()) {
1857 if (connectorId
> 0) {
1858 await this.ocppRequestService
.requestHandler
<
1859 StatusNotificationRequest
,
1860 StatusNotificationResponse
1863 RequestCommand
.STATUS_NOTIFICATION
,
1864 OCPPServiceUtils
.buildStatusNotificationRequest(
1867 ConnectorStatusEnum
.UNAVAILABLE
1870 this.getConnectorStatus(connectorId
).status = null;
1875 private startWebSocketPing(): void {
1876 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1878 StandardParametersKey
.WebSocketPingInterval
1880 ? Utils
.convertToInt(
1881 ChargingStationConfigurationUtils
.getConfigurationKey(
1883 StandardParametersKey
.WebSocketPingInterval
1887 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1888 this.webSocketPingSetInterval
= setInterval(() => {
1889 if (this.isWebSocketConnectionOpened() === true) {
1890 this.wsConnection
.ping();
1892 }, webSocketPingInterval
* 1000);
1894 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
1895 webSocketPingInterval
1898 } else if (this.webSocketPingSetInterval
) {
1900 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
1901 webSocketPingInterval
1906 `${this.logPrefix()} WebSocket ping interval set to ${
1907 webSocketPingInterval
1908 ? Utils.formatDurationSeconds(webSocketPingInterval)
1909 : webSocketPingInterval
1910 }, not starting the WebSocket ping`
1915 private stopWebSocketPing(): void {
1916 if (this.webSocketPingSetInterval
) {
1917 clearInterval(this.webSocketPingSetInterval
);
1921 private getConfiguredSupervisionUrl(): URL
{
1922 const supervisionUrls
= this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls();
1923 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1924 switch (Configuration
.getSupervisionUrlDistribution()) {
1925 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1927 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1929 case SupervisionUrlDistribution
.RANDOM
:
1930 this.configuredSupervisionUrlIndex
= Math.floor(
1931 Utils
.secureRandom() * supervisionUrls
.length
1934 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1935 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1939 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1940 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1943 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1946 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1948 return new URL(supervisionUrls
as string);
1951 private getHeartbeatInterval(): number {
1952 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1954 StandardParametersKey
.HeartbeatInterval
1956 if (HeartbeatInterval
) {
1957 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1959 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1961 StandardParametersKey
.HeartBeatInterval
1963 if (HeartBeatInterval
) {
1964 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1966 this.stationInfo
?.autoRegister
=== false &&
1968 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1969 Constants.DEFAULT_HEARTBEAT_INTERVAL
1972 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1975 private stopHeartbeat(): void {
1976 if (this.heartbeatSetInterval
) {
1977 clearInterval(this.heartbeatSetInterval
);
1981 private terminateWSConnection(): void {
1982 if (this.isWebSocketConnectionOpened() === true) {
1983 this.wsConnection
.terminate();
1984 this.wsConnection
= null;
1988 private stopMeterValues(connectorId
: number) {
1989 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1990 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1994 private getReconnectExponentialDelay(): boolean {
1995 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1996 ? this.stationInfo
.reconnectExponentialDelay
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(): AutomaticTransactionGeneratorConfiguration
| null {
2047 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2050 private initializeConnectorStatus(connectorId
: number): void {
2051 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2052 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2053 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2054 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2055 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2056 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;