1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import type ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import type ChargingStationInfo from
'../types/ChargingStationInfo';
17 import type ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import type { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public readonly templateFile
: string;
88 public stationInfo
!: ChargingStationInfo
;
89 public started
: boolean;
90 public authorizedTagsCache
: AuthorizedTagsCache
;
91 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
92 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
93 public wsConnection
!: WebSocket
;
94 public readonly connectors
: Map
<number, ConnectorStatus
>;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationRequest
!: BootNotificationRequest
;
100 public bootNotificationResponse
!: BootNotificationResponse
| null;
101 public powerDivider
!: number;
102 private readonly index
: number;
103 private configurationFile
!: string;
104 private configurationFileHash
!: string;
105 private connectorsConfigurationHash
!: string;
106 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
107 private readonly messageBuffer
: Set
<string>;
108 private configuredSupervisionUrl
!: URL
;
109 private wsConnectionRestarted
: boolean;
110 private autoReconnectRetryCount
: number;
111 private templateFileWatcher
!: fs
.FSWatcher
;
112 private readonly sharedLRUCache
: SharedLRUCache
;
113 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
114 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
116 constructor(index
: number, templateFile
: string) {
118 this.templateFile
= templateFile
;
119 this.connectors
= new Map
<number, ConnectorStatus
>();
120 this.requests
= new Map
<string, CachedRequest
>();
121 this.messageBuffer
= new Set
<string>();
122 this.sharedLRUCache
= SharedLRUCache
.getInstance();
123 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
124 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
125 this.started
= false;
126 this.wsConnectionRestarted
= false;
127 this.autoReconnectRetryCount
= 0;
132 private get
wsConnectionUrl(): URL
{
134 (this.getSupervisionUrlOcppConfiguration()
135 ? ChargingStationConfigurationUtils
.getConfigurationKey(
137 this.getSupervisionUrlOcppKey()
139 : this.configuredSupervisionUrl
.href
) +
141 this.stationInfo
.chargingStationId
145 public logPrefix(): string {
146 return Utils
.logPrefix(
148 this?.stationInfo?.chargingStationId ??
149 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
154 public getRandomIdTag(): string {
155 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
156 const index
= Math.floor(
157 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
159 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
162 public hasAuthorizedTags(): boolean {
163 return !Utils
.isEmptyArray(
164 this.authorizedTagsCache
.getAuthorizedTags(
165 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
170 public getEnableStatistics(): boolean | undefined {
171 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
172 ? this.stationInfo
.enableStatistics
176 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
177 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
180 public getPayloadSchemaValidation(): boolean | undefined {
181 return this.stationInfo
.payloadSchemaValidation
?? true;
184 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
185 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
186 switch (this.getCurrentOutType(stationInfo
)) {
188 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
189 ? localStationInfo
.numberOfPhases
196 public isWebSocketConnectionOpened(): boolean {
197 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
200 public getRegistrationStatus(): RegistrationStatus
{
201 return this?.bootNotificationResponse
?.status;
204 public isInUnknownState(): boolean {
205 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
208 public isInPendingState(): boolean {
209 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
212 public isInAcceptedState(): boolean {
213 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
216 public isInRejectedState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
220 public isRegistered(): boolean {
221 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
224 public isChargingStationAvailable(): boolean {
225 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
228 public isConnectorAvailable(id
: number): boolean {
229 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
232 public getNumberOfConnectors(): number {
233 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
236 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
237 return this.connectors
.get(id
);
240 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
241 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
244 public getOcppStrictCompliance(): boolean {
245 return this.stationInfo
?.ocppStrictCompliance
?? false;
248 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
249 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
250 this.getCurrentOutType(stationInfo
),
254 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
255 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
256 ? localStationInfo
.voltageOut
260 public getConnectorMaximumAvailablePower(connectorId
: number): number {
261 let connectorAmperageLimitationPowerLimit
: number;
263 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
264 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
266 connectorAmperageLimitationPowerLimit
=
267 (this.getCurrentOutType() === CurrentType
.AC
268 ? ACElectricUtils
.powerTotal(
269 this.getNumberOfPhases(),
270 this.getVoltageOut(),
271 this.getAmperageLimitation() * this.getNumberOfConnectors()
273 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
276 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
277 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
279 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
280 isNaN(connectorAmperageLimitationPowerLimit
)
282 : connectorAmperageLimitationPowerLimit
,
283 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
287 public getTransactionIdTag(transactionId
: number): string | undefined {
288 for (const connectorId
of this.connectors
.keys()) {
289 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
290 return this.getConnectorStatus(connectorId
).transactionIdTag
;
295 public getOutOfOrderEndMeterValues(): boolean {
296 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
299 public getBeginEndMeterValues(): boolean {
300 return this.stationInfo
?.beginEndMeterValues
?? false;
303 public getMeteringPerTransaction(): boolean {
304 return this.stationInfo
?.meteringPerTransaction
?? true;
307 public getTransactionDataMeterValues(): boolean {
308 return this.stationInfo
?.transactionDataMeterValues
?? false;
311 public getMainVoltageMeterValues(): boolean {
312 return this.stationInfo
?.mainVoltageMeterValues
?? true;
315 public getPhaseLineToLineVoltageMeterValues(): boolean {
316 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
319 public getCustomValueLimitationMeterValues(): boolean {
320 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
323 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
324 for (const connectorId
of this.connectors
.keys()) {
327 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
334 public getEnergyActiveImportRegisterByTransactionId(
335 transactionId
: number,
338 return this.getEnergyActiveImportRegister(
339 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
344 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
345 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
348 public getAuthorizeRemoteTxRequests(): boolean {
349 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
351 StandardParametersKey
.AuthorizeRemoteTxRequests
353 return authorizeRemoteTxRequests
354 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
358 public getLocalAuthListEnabled(): boolean {
359 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
361 StandardParametersKey
.LocalAuthListEnabled
363 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
366 public startHeartbeat(): void {
368 this.getHeartbeatInterval() &&
369 this.getHeartbeatInterval() > 0 &&
370 !this.heartbeatSetInterval
372 // eslint-disable-next-line @typescript-eslint/no-misused-promises
373 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
374 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
376 RequestCommand
.HEARTBEAT
378 }, this.getHeartbeatInterval());
381 ' Heartbeat started every ' +
382 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
384 } else if (this.heartbeatSetInterval
) {
387 ' Heartbeat already started every ' +
388 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
392 `${this.logPrefix()} Heartbeat interval set to ${
393 this.getHeartbeatInterval()
394 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
395 : this.getHeartbeatInterval()
396 }, not starting the heartbeat`
401 public restartHeartbeat(): void {
403 this.stopHeartbeat();
405 this.startHeartbeat();
408 public restartWebSocketPing(): void {
409 // Stop WebSocket ping
410 this.stopWebSocketPing();
411 // Start WebSocket ping
412 this.startWebSocketPing();
415 public startMeterValues(connectorId
: number, interval
: number): void {
416 if (connectorId
=== 0) {
418 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
422 if (!this.getConnectorStatus(connectorId
)) {
424 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
428 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
430 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
434 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
435 !this.getConnectorStatus(connectorId
)?.transactionId
438 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
445 // eslint-disable-next-line @typescript-eslint/no-misused-promises
446 async (): Promise
<void> => {
447 // FIXME: Implement OCPP version agnostic helpers
448 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
451 this.getConnectorStatus(connectorId
).transactionId
,
454 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
456 RequestCommand
.METER_VALUES
,
459 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
460 meterValue
: [meterValue
],
468 `${this.logPrefix()} Charging station ${
469 StandardParametersKey.MeterValueSampleInterval
470 } configuration set to ${
471 interval ? Utils.formatDurationMilliSeconds(interval) : interval
472 }, not sending MeterValues`
477 public start(): void {
478 if (this.getEnableStatistics()) {
479 this.performanceStatistics
.start();
481 this.openWSConnection();
482 // Monitor charging station template file
483 this.templateFileWatcher
= FileUtils
.watchJsonFile(
485 FileType
.ChargingStationTemplate
,
488 (event
, filename
): void => {
489 if (filename
&& event
=== 'change') {
492 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
494 } file have changed, reload`
496 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
500 this.stopAutomaticTransactionGenerator();
501 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
502 this.startAutomaticTransactionGenerator();
504 if (this.getEnableStatistics()) {
505 this.performanceStatistics
.restart();
507 this.performanceStatistics
.stop();
509 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
512 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
519 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
522 public async stop(): Promise
<void> {
523 for (const connectorId
of this.connectors
.keys()) {
524 if (connectorId
> 0) {
525 await this.ocppRequestService
.requestHandler
<
526 StatusNotificationRequest
,
527 StatusNotificationResponse
528 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
530 status: ChargePointStatus
.UNAVAILABLE
,
531 errorCode
: ChargePointErrorCode
.NO_ERROR
,
533 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
536 this.closeWSConnection();
537 if (this.getEnableStatistics()) {
538 this.performanceStatistics
.stop();
540 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
541 this.templateFileWatcher
.close();
542 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
543 this.bootNotificationResponse
= null;
544 this.started
= false;
545 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
548 public async reset(): Promise
<void> {
550 await Utils
.sleep(this.stationInfo
.resetTime
);
555 public saveOcppConfiguration(): void {
556 if (this.getOcppPersistentConfiguration()) {
557 this.saveConfiguration();
561 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
562 let limit
: number, matchingChargingProfile
: ChargingProfile
;
563 let chargingProfiles
: ChargingProfile
[] = [];
564 // Get charging profiles for connector and sort by stack level
565 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
566 (a
, b
) => b
.stackLevel
- a
.stackLevel
568 // Get profiles on connector 0
569 if (this.getConnectorStatus(0).chargingProfiles
) {
570 chargingProfiles
.push(
571 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
574 if (!Utils
.isEmptyArray(chargingProfiles
)) {
575 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
579 if (!Utils
.isNullOrUndefined(result
)) {
580 limit
= result
.limit
;
581 matchingChargingProfile
= result
.matchingChargingProfile
;
582 switch (this.getCurrentOutType()) {
585 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
586 ChargingRateUnitType
.WATT
588 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
592 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
593 ChargingRateUnitType
.WATT
595 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
597 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
598 if (limit
> connectorMaximumPower
) {
600 `${this.logPrefix()} Charging profile id ${
601 matchingChargingProfile.chargingProfileId
602 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
603 this.getConnectorStatus(connectorId
).chargingProfiles
605 limit
= connectorMaximumPower
;
612 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
613 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
615 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
617 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
619 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
621 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`
623 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
625 let cpReplaced
= false;
626 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
627 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
628 (chargingProfile
: ChargingProfile
, index
: number) => {
630 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
631 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
632 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
634 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
640 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
643 public resetConnectorStatus(connectorId
: number): void {
644 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
645 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
646 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
647 this.getConnectorStatus(connectorId
).transactionStarted
= false;
648 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
649 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
650 delete this.getConnectorStatus(connectorId
).transactionId
;
651 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
652 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
653 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
654 this.stopMeterValues(connectorId
);
655 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
658 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
659 return ChargingStationConfigurationUtils
.getConfigurationKey(
661 StandardParametersKey
.SupportedFeatureProfiles
662 )?.value
.includes(featureProfile
);
665 public bufferMessage(message
: string): void {
666 this.messageBuffer
.add(message
);
669 public openWSConnection(
670 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
671 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
673 terminateOpened
: false,
676 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
677 params
.closeOpened
= params
?.closeOpened
?? false;
678 params
.terminateOpened
= params
?.terminateOpened
?? false;
680 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
681 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
683 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
685 if (params
?.closeOpened
) {
686 this.closeWSConnection();
688 if (params
?.terminateOpened
) {
689 this.terminateWSConnection();
691 let protocol
: string;
692 switch (this.getOcppVersion()) {
693 case OCPPVersion
.VERSION_16
:
694 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
697 this.handleUnsupportedVersion(this.getOcppVersion());
701 if (this.isWebSocketConnectionOpened()) {
703 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
709 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
712 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
714 // Handle WebSocket message
715 this.wsConnection
.on(
717 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
719 // Handle WebSocket error
720 this.wsConnection
.on(
722 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
724 // Handle WebSocket close
725 this.wsConnection
.on(
727 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
729 // Handle WebSocket open
730 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
731 // Handle WebSocket ping
732 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
733 // Handle WebSocket pong
734 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
737 public closeWSConnection(): void {
738 if (this.isWebSocketConnectionOpened()) {
739 this.wsConnection
.close();
740 this.wsConnection
= null;
744 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
745 if (!this.automaticTransactionGenerator
) {
746 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
747 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
751 if (!Utils
.isEmptyArray(connectorIds
)) {
752 for (const connectorId
of connectorIds
) {
753 this.automaticTransactionGenerator
.startConnector(connectorId
);
756 this.automaticTransactionGenerator
.start();
760 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
761 if (!Utils
.isEmptyArray(connectorIds
)) {
762 for (const connectorId
of connectorIds
) {
763 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
766 this.automaticTransactionGenerator
?.stop();
767 this.automaticTransactionGenerator
= null;
771 public getNumberOfRunningTransactions(): number {
773 for (const connectorId
of this.connectors
.keys()) {
774 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
781 public async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
782 for (const connectorId
of this.connectors
.keys()) {
783 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
784 await this.stopTransactionOnConnector(connectorId
, reason
);
789 public async stopTransactionOnConnector(
791 reason
= StopTransactionReason
.NONE
792 ): Promise
<StopTransactionResponse
> {
793 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
795 this.getBeginEndMeterValues() &&
796 this.getOcppStrictCompliance() &&
797 !this.getOutOfOrderEndMeterValues()
799 // FIXME: Implement OCPP version agnostic helpers
800 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
803 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
805 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
807 RequestCommand
.METER_VALUES
,
811 meterValue
: [transactionEndMeterValue
],
815 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
817 RequestCommand
.STOP_TRANSACTION
,
820 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
821 idTag
: this.getTransactionIdTag(transactionId
),
827 private flushMessageBuffer(): void {
828 if (this.messageBuffer
.size
> 0) {
829 this.messageBuffer
.forEach((message
) => {
830 // TODO: evaluate the need to track performance
831 this.wsConnection
.send(message
);
832 this.messageBuffer
.delete(message
);
837 private getSupervisionUrlOcppConfiguration(): boolean {
838 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
841 private getSupervisionUrlOcppKey(): string {
842 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
845 private getTemplateFromFile(): ChargingStationTemplate
| null {
846 let template
: ChargingStationTemplate
= null;
848 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
849 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
851 const measureId
= `${FileType.ChargingStationTemplate} read`;
852 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
853 template
= JSON
.parse(
854 fs
.readFileSync(this.templateFile
, 'utf8')
855 ) as ChargingStationTemplate
;
856 PerformanceStatistics
.endMeasure(measureId
, beginId
);
857 template
.templateHash
= crypto
858 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
859 .update(JSON
.stringify(template
))
861 this.sharedLRUCache
.setChargingStationTemplate(template
);
864 FileUtils
.handleFileException(
866 FileType
.ChargingStationTemplate
,
868 error
as NodeJS
.ErrnoException
874 private getStationInfoFromTemplate(): ChargingStationInfo
{
875 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
876 if (Utils
.isNullOrUndefined(stationTemplate
)) {
877 const errorMsg
= 'Failed to read charging station template file';
878 logger
.error(`${this.logPrefix()} ${errorMsg}`);
879 throw new BaseError(errorMsg
);
881 if (Utils
.isEmptyObject(stationTemplate
)) {
882 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
883 logger
.error(`${this.logPrefix()} ${errorMsg}`);
884 throw new BaseError(errorMsg
);
886 // Deprecation template keys section
887 ChargingStationUtils
.warnDeprecatedTemplateKey(
892 "Use 'supervisionUrls' instead"
894 ChargingStationUtils
.convertDeprecatedTemplateKey(
899 const stationInfo
: ChargingStationInfo
=
900 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
901 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
902 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
906 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
907 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
908 stationTemplate
.power
= stationTemplate
.power
as number[];
909 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
910 stationInfo
.maximumPower
=
911 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
912 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
913 : stationTemplate
.power
[powerArrayRandomIndex
];
915 stationTemplate
.power
= stationTemplate
.power
as number;
916 stationInfo
.maximumPower
=
917 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
918 ? stationTemplate
.power
* 1000
919 : stationTemplate
.power
;
921 stationInfo
.resetTime
= stationTemplate
.resetTime
922 ? stationTemplate
.resetTime
* 1000
923 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
924 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
928 ChargingStationUtils
.checkConfiguredMaxConnectors(
929 configuredMaxConnectors
,
933 const templateMaxConnectors
=
934 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
935 ChargingStationUtils
.checkTemplateMaxConnectors(
936 templateMaxConnectors
,
941 configuredMaxConnectors
>
942 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
943 !stationTemplate
?.randomConnectors
946 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
948 }, forcing random connector configurations affectation`
950 stationInfo
.randomConnectors
= true;
952 // Build connectors if needed (FIXME: should be factored out)
953 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
954 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
955 ChargingStationUtils
.createStationInfoHash(stationInfo
);
959 private getStationInfoFromFile(): ChargingStationInfo
| null {
960 let stationInfo
: ChargingStationInfo
= null;
961 this.getStationInfoPersistentConfiguration() &&
962 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
963 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
967 private getStationInfo(): ChargingStationInfo
{
968 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
969 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
970 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
971 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
972 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
973 return this.stationInfo
;
975 return stationInfoFromFile
;
977 stationInfoFromFile
&&
978 ChargingStationUtils
.propagateSerialNumber(
979 this.getTemplateFromFile(),
981 stationInfoFromTemplate
983 return stationInfoFromTemplate
;
986 private saveStationInfo(): void {
987 if (this.getStationInfoPersistentConfiguration()) {
988 this.saveConfiguration();
992 private getOcppVersion(): OCPPVersion
{
993 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
996 private getOcppPersistentConfiguration(): boolean {
997 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1000 private getStationInfoPersistentConfiguration(): boolean {
1001 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1004 private handleUnsupportedVersion(version
: OCPPVersion
) {
1005 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1006 logger
.error(`${this.logPrefix()} ${errMsg}`);
1007 throw new BaseError(errMsg
);
1010 private initialize(): void {
1011 this.configurationFile
= path
.join(
1012 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
1013 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
1015 this.stationInfo
= this.getStationInfo();
1016 this.saveStationInfo();
1017 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
1018 // Avoid duplication of connectors related information in RAM
1019 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
1020 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1021 if (this.getEnableStatistics()) {
1022 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1023 this.stationInfo
.hashId
,
1024 this.stationInfo
.chargingStationId
,
1025 this.configuredSupervisionUrl
1028 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1031 this.powerDivider
= this.getPowerDivider();
1032 // OCPP configuration
1033 this.ocppConfiguration
= this.getOcppConfiguration();
1034 this.initializeOcppConfiguration();
1035 switch (this.getOcppVersion()) {
1036 case OCPPVersion
.VERSION_16
:
1037 this.ocppIncomingRequestService
=
1038 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1039 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1040 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1044 this.handleUnsupportedVersion(this.getOcppVersion());
1047 if (this.stationInfo
?.autoRegister
) {
1048 this.bootNotificationResponse
= {
1049 currentTime
: new Date().toISOString(),
1050 interval
: this.getHeartbeatInterval() / 1000,
1051 status: RegistrationStatus
.ACCEPTED
,
1056 private initializeOcppConfiguration(): void {
1058 !ChargingStationConfigurationUtils
.getConfigurationKey(
1060 StandardParametersKey
.HeartbeatInterval
1063 ChargingStationConfigurationUtils
.addConfigurationKey(
1065 StandardParametersKey
.HeartbeatInterval
,
1070 !ChargingStationConfigurationUtils
.getConfigurationKey(
1072 StandardParametersKey
.HeartBeatInterval
1075 ChargingStationConfigurationUtils
.addConfigurationKey(
1077 StandardParametersKey
.HeartBeatInterval
,
1083 this.getSupervisionUrlOcppConfiguration() &&
1084 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1086 ChargingStationConfigurationUtils
.addConfigurationKey(
1088 this.getSupervisionUrlOcppKey(),
1089 this.configuredSupervisionUrl
.href
,
1093 !this.getSupervisionUrlOcppConfiguration() &&
1094 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1096 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1098 this.getSupervisionUrlOcppKey(),
1103 this.stationInfo
.amperageLimitationOcppKey
&&
1104 !ChargingStationConfigurationUtils
.getConfigurationKey(
1106 this.stationInfo
.amperageLimitationOcppKey
1109 ChargingStationConfigurationUtils
.addConfigurationKey(
1111 this.stationInfo
.amperageLimitationOcppKey
,
1113 this.stationInfo
.maximumAmperage
*
1114 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1119 !ChargingStationConfigurationUtils
.getConfigurationKey(
1121 StandardParametersKey
.SupportedFeatureProfiles
1124 ChargingStationConfigurationUtils
.addConfigurationKey(
1126 StandardParametersKey
.SupportedFeatureProfiles
,
1127 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1130 ChargingStationConfigurationUtils
.addConfigurationKey(
1132 StandardParametersKey
.NumberOfConnectors
,
1133 this.getNumberOfConnectors().toString(),
1138 !ChargingStationConfigurationUtils
.getConfigurationKey(
1140 StandardParametersKey
.MeterValuesSampledData
1143 ChargingStationConfigurationUtils
.addConfigurationKey(
1145 StandardParametersKey
.MeterValuesSampledData
,
1146 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1150 !ChargingStationConfigurationUtils
.getConfigurationKey(
1152 StandardParametersKey
.ConnectorPhaseRotation
1155 const connectorPhaseRotation
= [];
1156 for (const connectorId
of this.connectors
.keys()) {
1158 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1159 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1160 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1161 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1163 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1164 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1165 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1166 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1169 ChargingStationConfigurationUtils
.addConfigurationKey(
1171 StandardParametersKey
.ConnectorPhaseRotation
,
1172 connectorPhaseRotation
.toString()
1176 !ChargingStationConfigurationUtils
.getConfigurationKey(
1178 StandardParametersKey
.AuthorizeRemoteTxRequests
1181 ChargingStationConfigurationUtils
.addConfigurationKey(
1183 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1188 !ChargingStationConfigurationUtils
.getConfigurationKey(
1190 StandardParametersKey
.LocalAuthListEnabled
1192 ChargingStationConfigurationUtils
.getConfigurationKey(
1194 StandardParametersKey
.SupportedFeatureProfiles
1195 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1197 ChargingStationConfigurationUtils
.addConfigurationKey(
1199 StandardParametersKey
.LocalAuthListEnabled
,
1204 !ChargingStationConfigurationUtils
.getConfigurationKey(
1206 StandardParametersKey
.ConnectionTimeOut
1209 ChargingStationConfigurationUtils
.addConfigurationKey(
1211 StandardParametersKey
.ConnectionTimeOut
,
1212 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1215 this.saveOcppConfiguration();
1218 private initializeConnectors(
1219 stationInfo
: ChargingStationInfo
,
1220 configuredMaxConnectors
: number,
1221 templateMaxConnectors
: number
1223 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1224 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1225 logger
.error(`${this.logPrefix()} ${logMsg}`);
1226 throw new BaseError(logMsg
);
1228 if (!stationInfo
?.Connectors
[0]) {
1230 `${this.logPrefix()} Charging station information from template ${
1232 } with no connector Id 0 configuration`
1235 if (stationInfo
?.Connectors
) {
1236 const connectorsConfigHash
= crypto
1237 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1238 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1240 const connectorsConfigChanged
=
1241 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1242 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1243 connectorsConfigChanged
&& this.connectors
.clear();
1244 this.connectorsConfigurationHash
= connectorsConfigHash
;
1245 // Add connector Id 0
1246 let lastConnector
= '0';
1247 for (lastConnector
in stationInfo
?.Connectors
) {
1248 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1250 lastConnectorId
=== 0 &&
1251 this.getUseConnectorId0(stationInfo
) &&
1252 stationInfo
?.Connectors
[lastConnector
]
1254 this.connectors
.set(
1256 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1258 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1259 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1260 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1264 // Generate all connectors
1265 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1266 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1267 const randConnectorId
= stationInfo
?.randomConnectors
1268 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1270 this.connectors
.set(
1272 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1274 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1275 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1276 this.getConnectorStatus(index
).chargingProfiles
= [];
1283 `${this.logPrefix()} Charging station information from template ${
1285 } with no connectors configuration defined, using already defined connectors`
1288 // Initialize transaction attributes on connectors
1289 for (const connectorId
of this.connectors
.keys()) {
1290 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
1291 this.initializeConnectorStatus(connectorId
);
1296 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1297 let configuration
: ChargingStationConfiguration
= null;
1298 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1300 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1301 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1302 this.configurationFileHash
1305 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1306 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1307 configuration
= JSON
.parse(
1308 fs
.readFileSync(this.configurationFile
, 'utf8')
1309 ) as ChargingStationConfiguration
;
1310 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1311 this.configurationFileHash
= configuration
.configurationHash
;
1312 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1315 FileUtils
.handleFileException(
1317 FileType
.ChargingStationConfiguration
,
1318 this.configurationFile
,
1319 error
as NodeJS
.ErrnoException
1323 return configuration
;
1326 private saveConfiguration(): void {
1327 if (this.configurationFile
) {
1329 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1330 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1332 const configurationData
: ChargingStationConfiguration
=
1333 this.getConfigurationFromFile() ?? {};
1334 this.ocppConfiguration
?.configurationKey
&&
1335 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1336 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1337 delete configurationData
.configurationHash
;
1338 const configurationHash
= crypto
1339 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1340 .update(JSON
.stringify(configurationData
))
1342 if (this.configurationFileHash
!== configurationHash
) {
1343 configurationData
.configurationHash
= configurationHash
;
1344 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1345 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1346 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1347 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1348 fs
.closeSync(fileDescriptor
);
1349 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1350 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1351 this.configurationFileHash
= configurationHash
;
1352 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1355 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1356 this.configurationFile
1361 FileUtils
.handleFileException(
1363 FileType
.ChargingStationConfiguration
,
1364 this.configurationFile
,
1365 error
as NodeJS
.ErrnoException
1370 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1375 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1376 return this.getTemplateFromFile()?.Configuration
?? null;
1379 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1380 let configuration
: ChargingStationConfiguration
= null;
1381 if (this.getOcppPersistentConfiguration()) {
1382 const configurationFromFile
= this.getConfigurationFromFile();
1383 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1385 configuration
&& delete configuration
.stationInfo
;
1386 return configuration
;
1389 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1390 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1391 if (!ocppConfiguration
) {
1392 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1394 return ocppConfiguration
;
1397 private async onOpen(): Promise
<void> {
1398 if (this.isWebSocketConnectionOpened()) {
1400 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1402 if (!this.isRegistered()) {
1403 // Send BootNotification
1404 let registrationRetryCount
= 0;
1406 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1407 BootNotificationRequest
,
1408 BootNotificationResponse
1411 RequestCommand
.BOOT_NOTIFICATION
,
1413 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1414 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1415 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1416 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1417 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1418 iccid
: this.bootNotificationRequest
.iccid
,
1419 imsi
: this.bootNotificationRequest
.imsi
,
1420 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1421 meterType
: this.bootNotificationRequest
.meterType
,
1423 { skipBufferingOnError
: true }
1425 if (!this.isRegistered()) {
1426 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1428 this.bootNotificationResponse
?.interval
1429 ? this.bootNotificationResponse
.interval
* 1000
1430 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1434 !this.isRegistered() &&
1435 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1436 this.getRegistrationMaxRetries() === -1)
1439 if (this.isRegistered()) {
1440 if (this.isInAcceptedState()) {
1441 await this.startMessageSequence();
1442 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1446 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1449 this.started
=== false && (this.started
= true);
1450 this.autoReconnectRetryCount
= 0;
1451 this.wsConnectionRestarted
= false;
1452 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1455 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1460 private async onClose(code
: number, reason
: string): Promise
<void> {
1463 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1464 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1466 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1468 )}' and reason '${reason}'`
1470 this.autoReconnectRetryCount
= 0;
1471 await this.stopMessageSequence(StopTransactionReason
.OTHER
);
1476 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1478 )}' and reason '${reason}'`
1480 await this.reconnect(code
);
1483 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1486 private async onMessage(data
: Data
): Promise
<void> {
1487 let messageType
: number;
1488 let messageId
: string;
1489 let commandName
: IncomingRequestCommand
;
1490 let commandPayload
: JsonType
;
1491 let errorType
: ErrorType
;
1492 let errorMessage
: string;
1493 let errorDetails
: JsonType
;
1494 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1495 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1496 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1497 let requestPayload
: JsonType
;
1498 let cachedRequest
: CachedRequest
;
1501 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1502 if (Array.isArray(request
) === true) {
1503 [messageType
, messageId
] = request
;
1504 // Check the type of message
1505 switch (messageType
) {
1507 case MessageType
.CALL_MESSAGE
:
1508 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1509 if (this.getEnableStatistics()) {
1510 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1513 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1517 // Process the message
1518 await this.ocppIncomingRequestService
.incomingRequestHandler(
1526 case MessageType
.CALL_RESULT_MESSAGE
:
1527 [, , commandPayload
] = request
as Response
;
1528 if (!this.requests
.has(messageId
)) {
1530 throw new OCPPError(
1531 ErrorType
.INTERNAL_ERROR
,
1532 `Response for unknown message id ${messageId}`,
1538 cachedRequest
= this.requests
.get(messageId
);
1539 if (Array.isArray(cachedRequest
) === true) {
1540 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1542 throw new OCPPError(
1543 ErrorType
.PROTOCOL_ERROR
,
1544 `Cached request for message id ${messageId} response is not an array`,
1546 cachedRequest
as unknown
as JsonType
1550 `${this.logPrefix()} << Command '${
1551 requestCommandName ?? 'unknown'
1552 }' received response payload: ${JSON.stringify(request)}`
1554 responseCallback(commandPayload
, requestPayload
);
1557 case MessageType
.CALL_ERROR_MESSAGE
:
1558 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1559 if (!this.requests
.has(messageId
)) {
1561 throw new OCPPError(
1562 ErrorType
.INTERNAL_ERROR
,
1563 `Error response for unknown message id ${messageId}`,
1565 { errorType
, errorMessage
, errorDetails
}
1568 cachedRequest
= this.requests
.get(messageId
);
1569 if (Array.isArray(cachedRequest
) === true) {
1570 [, errorCallback
, requestCommandName
] = cachedRequest
;
1572 throw new OCPPError(
1573 ErrorType
.PROTOCOL_ERROR
,
1574 `Cached request for message id ${messageId} error response is not an array`,
1576 cachedRequest
as unknown
as JsonType
1580 `${this.logPrefix()} << Command '${
1581 requestCommandName ?? 'unknown'
1582 }' received error payload: ${JSON.stringify(request)}`
1584 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1588 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1589 errMsg
= `Wrong message type ${messageType}`;
1590 logger
.error(`${this.logPrefix()} ${errMsg}`);
1591 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1593 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1595 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1602 `${this.logPrefix()} Incoming OCPP command '${
1603 commandName ?? requestCommandName ?? null
1604 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1605 this.requests.get(messageId)
1606 )}' processing error:`,
1609 if (!(error
instanceof OCPPError
)) {
1611 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1612 commandName ?? requestCommandName ?? null
1613 }' message '${data.toString()}' handling is not an OCPPError:`,
1618 messageType
=== MessageType
.CALL_MESSAGE
&&
1619 (await this.ocppRequestService
.sendError(
1623 commandName
?? requestCommandName
?? null
1628 private onPing(): void {
1629 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1632 private onPong(): void {
1633 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1636 private onError(error
: WSError
): void {
1637 this.closeWSConnection();
1638 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1641 private getEnergyActiveImportRegister(
1642 connectorStatus
: ConnectorStatus
,
1645 if (this.getMeteringPerTransaction()) {
1648 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1649 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1654 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1655 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1659 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1660 const localStationInfo
= stationInfo
?? this.stationInfo
;
1661 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1662 ? localStationInfo
.useConnectorId0
1667 private getConnectionTimeout(): number | undefined {
1669 ChargingStationConfigurationUtils
.getConfigurationKey(
1671 StandardParametersKey
.ConnectionTimeOut
1676 ChargingStationConfigurationUtils
.getConfigurationKey(
1678 StandardParametersKey
.ConnectionTimeOut
1680 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1683 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1686 // -1 for unlimited, 0 for disabling
1687 private getAutoReconnectMaxRetries(): number | undefined {
1688 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1689 return this.stationInfo
.autoReconnectMaxRetries
;
1691 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1692 return Configuration
.getAutoReconnectMaxRetries();
1698 private getRegistrationMaxRetries(): number | undefined {
1699 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1700 return this.stationInfo
.registrationMaxRetries
;
1705 private getPowerDivider(): number {
1706 let powerDivider
= this.getNumberOfConnectors();
1707 if (this.stationInfo
?.powerSharedByConnectors
) {
1708 powerDivider
= this.getNumberOfRunningTransactions();
1710 return powerDivider
;
1713 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1714 const localStationInfo
= stationInfo
?? this.stationInfo
;
1715 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1718 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1719 const maximumPower
= this.getMaximumPower(stationInfo
);
1720 switch (this.getCurrentOutType(stationInfo
)) {
1721 case CurrentType
.AC
:
1722 return ACElectricUtils
.amperagePerPhaseFromPower(
1723 this.getNumberOfPhases(stationInfo
),
1724 maximumPower
/ this.getNumberOfConnectors(),
1725 this.getVoltageOut(stationInfo
)
1727 case CurrentType
.DC
:
1728 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1732 private getAmperageLimitation(): number | undefined {
1734 this.stationInfo
.amperageLimitationOcppKey
&&
1735 ChargingStationConfigurationUtils
.getConfigurationKey(
1737 this.stationInfo
.amperageLimitationOcppKey
1742 ChargingStationConfigurationUtils
.getConfigurationKey(
1744 this.stationInfo
.amperageLimitationOcppKey
1746 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1751 private async startMessageSequence(): Promise
<void> {
1752 if (this.stationInfo
?.autoRegister
) {
1753 await this.ocppRequestService
.requestHandler
<
1754 BootNotificationRequest
,
1755 BootNotificationResponse
1758 RequestCommand
.BOOT_NOTIFICATION
,
1760 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1761 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1762 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1763 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1764 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1765 iccid
: this.bootNotificationRequest
.iccid
,
1766 imsi
: this.bootNotificationRequest
.imsi
,
1767 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1768 meterType
: this.bootNotificationRequest
.meterType
,
1770 { skipBufferingOnError
: true }
1773 // Start WebSocket ping
1774 this.startWebSocketPing();
1776 this.startHeartbeat();
1777 // Initialize connectors status
1778 for (const connectorId
of this.connectors
.keys()) {
1779 if (connectorId
=== 0) {
1782 this.started
=== true &&
1783 !this.getConnectorStatus(connectorId
)?.status &&
1784 this.getConnectorStatus(connectorId
)?.bootStatus
1786 // Send status in template at startup
1787 await this.ocppRequestService
.requestHandler
<
1788 StatusNotificationRequest
,
1789 StatusNotificationResponse
1790 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1792 status: this.getConnectorStatus(connectorId
).bootStatus
,
1793 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1795 this.getConnectorStatus(connectorId
).status =
1796 this.getConnectorStatus(connectorId
).bootStatus
;
1798 this.started
=== false &&
1799 this.getConnectorStatus(connectorId
)?.status &&
1800 this.getConnectorStatus(connectorId
)?.bootStatus
1802 // Send status in template after reset
1803 await this.ocppRequestService
.requestHandler
<
1804 StatusNotificationRequest
,
1805 StatusNotificationResponse
1806 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1808 status: this.getConnectorStatus(connectorId
).bootStatus
,
1809 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1811 this.getConnectorStatus(connectorId
).status =
1812 this.getConnectorStatus(connectorId
).bootStatus
;
1813 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1814 // Send previous status at template reload
1815 await this.ocppRequestService
.requestHandler
<
1816 StatusNotificationRequest
,
1817 StatusNotificationResponse
1818 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1820 status: this.getConnectorStatus(connectorId
).status,
1821 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1824 // Send default status
1825 await this.ocppRequestService
.requestHandler
<
1826 StatusNotificationRequest
,
1827 StatusNotificationResponse
1828 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1830 status: ChargePointStatus
.AVAILABLE
,
1831 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1833 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1837 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1838 this.startAutomaticTransactionGenerator();
1842 private async stopMessageSequence(
1843 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1845 // Stop WebSocket ping
1846 this.stopWebSocketPing();
1848 this.stopHeartbeat();
1849 // Stop ongoing transactions
1850 if (this.getNumberOfRunningTransactions() > 0) {
1851 if (this.automaticTransactionGenerator
?.started
) {
1852 this.stopAutomaticTransactionGenerator();
1854 await this.stopRunningTransactions(reason
);
1859 private startWebSocketPing(): void {
1860 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1862 StandardParametersKey
.WebSocketPingInterval
1864 ? Utils
.convertToInt(
1865 ChargingStationConfigurationUtils
.getConfigurationKey(
1867 StandardParametersKey
.WebSocketPingInterval
1871 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1872 this.webSocketPingSetInterval
= setInterval(() => {
1873 if (this.isWebSocketConnectionOpened()) {
1874 this.wsConnection
.ping((): void => {
1875 /* This is intentional */
1878 }, webSocketPingInterval
* 1000);
1881 ' WebSocket ping started every ' +
1882 Utils
.formatDurationSeconds(webSocketPingInterval
)
1884 } else if (this.webSocketPingSetInterval
) {
1887 ' WebSocket ping every ' +
1888 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1893 `${this.logPrefix()} WebSocket ping interval set to ${
1894 webSocketPingInterval
1895 ? Utils.formatDurationSeconds(webSocketPingInterval)
1896 : webSocketPingInterval
1897 }, not starting the WebSocket ping`
1902 private stopWebSocketPing(): void {
1903 if (this.webSocketPingSetInterval
) {
1904 clearInterval(this.webSocketPingSetInterval
);
1908 private getConfiguredSupervisionUrl(): URL
{
1909 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1910 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1912 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1914 switch (Configuration
.getSupervisionUrlDistribution()) {
1915 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1916 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1918 case SupervisionUrlDistribution
.RANDOM
:
1920 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1922 case SupervisionUrlDistribution
.SEQUENTIAL
:
1923 if (this.index
<= supervisionUrls
.length
) {
1924 urlIndex
= this.index
- 1;
1927 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1933 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1934 SupervisionUrlDistribution.ROUND_ROBIN
1937 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1940 return new URL(supervisionUrls
[urlIndex
]);
1942 return new URL(supervisionUrls
as string);
1945 private getHeartbeatInterval(): number | undefined {
1946 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1948 StandardParametersKey
.HeartbeatInterval
1950 if (HeartbeatInterval
) {
1951 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1953 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1955 StandardParametersKey
.HeartBeatInterval
1957 if (HeartBeatInterval
) {
1958 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1960 !this.stationInfo
?.autoRegister
&&
1962 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1963 Constants.DEFAULT_HEARTBEAT_INTERVAL
1966 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1969 private stopHeartbeat(): void {
1970 if (this.heartbeatSetInterval
) {
1971 clearInterval(this.heartbeatSetInterval
);
1975 private terminateWSConnection(): void {
1976 if (this.isWebSocketConnectionOpened()) {
1977 this.wsConnection
.terminate();
1978 this.wsConnection
= null;
1982 private stopMeterValues(connectorId
: number) {
1983 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1984 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1988 private getReconnectExponentialDelay(): boolean | undefined {
1989 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1990 ? this.stationInfo
.reconnectExponentialDelay
1994 private async reconnect(code
: number): Promise
<void> {
1995 // Stop WebSocket ping
1996 this.stopWebSocketPing();
1998 this.stopHeartbeat();
1999 // Stop the ATG if needed
2000 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2001 this.stopAutomaticTransactionGenerator();
2004 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2005 this.getAutoReconnectMaxRetries() === -1
2007 this.autoReconnectRetryCount
++;
2008 const reconnectDelay
= this.getReconnectExponentialDelay()
2009 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2010 : this.getConnectionTimeout() * 1000;
2011 const reconnectDelayWithdraw
= 1000;
2012 const reconnectTimeout
=
2013 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2014 ? reconnectDelay
- reconnectDelayWithdraw
2017 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2020 )}ms, timeout ${reconnectTimeout}ms`
2022 await Utils
.sleep(reconnectDelay
);
2025 ' WebSocket: reconnecting try #' +
2026 this.autoReconnectRetryCount
.toString()
2028 this.openWSConnection(
2029 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2030 { closeOpened
: true }
2032 this.wsConnectionRestarted
= true;
2033 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2034 await this.stopMessageSequence(StopTransactionReason
.OTHER
);
2036 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2037 this.autoReconnectRetryCount
2038 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2043 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2044 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2047 private initializeConnectorStatus(connectorId
: number): void {
2048 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2049 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2050 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2051 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2052 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2053 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;