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';
19 type ChargingStationTemplate
,
23 } from
'../types/ChargingStationTemplate';
24 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
25 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
26 import { FileType
} from
'../types/FileType';
27 import type { JsonType
} from
'../types/JsonType';
28 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
29 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
30 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
32 ConnectorPhaseRotation
,
33 StandardParametersKey
,
34 SupportedFeatureProfiles
,
35 VendorDefaultParametersKey
,
36 } from
'../types/ocpp/Configuration';
37 import { ErrorType
} from
'../types/ocpp/ErrorType';
38 import { MessageType
} from
'../types/ocpp/MessageType';
39 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
40 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
43 BootNotificationRequest
,
47 IncomingRequestCommand
,
50 StatusNotificationRequest
,
51 } from
'../types/ocpp/Requests';
53 BootNotificationResponse
,
59 StatusNotificationResponse
,
60 } from
'../types/ocpp/Responses';
62 StopTransactionReason
,
63 StopTransactionRequest
,
64 StopTransactionResponse
,
65 } from
'../types/ocpp/Transaction';
66 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
67 import Configuration from
'../utils/Configuration';
68 import Constants from
'../utils/Constants';
69 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
70 import FileUtils from
'../utils/FileUtils';
71 import logger from
'../utils/Logger';
72 import Utils from
'../utils/Utils';
73 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
74 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
75 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
76 import { ChargingStationUtils
} from
'./ChargingStationUtils';
77 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
78 import { MessageChannelUtils
} from
'./MessageChannelUtils';
79 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
80 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
81 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
82 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
83 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
84 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
85 import SharedLRUCache from
'./SharedLRUCache';
87 export default class ChargingStation
{
88 public readonly index
: number;
89 public readonly templateFile
: string;
90 public stationInfo
!: ChargingStationInfo
;
91 public started
: boolean;
92 public authorizedTagsCache
: AuthorizedTagsCache
;
93 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
94 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
95 public wsConnection
!: WebSocket
;
96 public readonly connectors
: Map
<number, ConnectorStatus
>;
97 public readonly requests
: Map
<string, CachedRequest
>;
98 public performanceStatistics
!: PerformanceStatistics
;
99 public heartbeatSetInterval
!: NodeJS
.Timeout
;
100 public ocppRequestService
!: OCPPRequestService
;
101 public bootNotificationRequest
!: BootNotificationRequest
;
102 public bootNotificationResponse
!: BootNotificationResponse
| null;
103 public powerDivider
!: number;
104 private starting
: boolean;
105 private stopping
: boolean;
106 private configurationFile
!: string;
107 private configurationFileHash
!: string;
108 private connectorsConfigurationHash
!: string;
109 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
110 private readonly messageBuffer
: Set
<string>;
111 private configuredSupervisionUrl
!: URL
;
112 private configuredSupervisionUrlIndex
!: number;
113 private wsConnectionRestarted
: boolean;
114 private autoReconnectRetryCount
: number;
115 private templateFileWatcher
!: fs
.FSWatcher
;
116 private readonly sharedLRUCache
: SharedLRUCache
;
117 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
118 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
120 constructor(index
: number, templateFile
: string) {
121 this.started
= false;
122 this.starting
= false;
123 this.stopping
= false;
124 this.wsConnectionRestarted
= false;
125 this.autoReconnectRetryCount
= 0;
127 this.templateFile
= templateFile
;
128 this.connectors
= new Map
<number, ConnectorStatus
>();
129 this.requests
= new Map
<string, CachedRequest
>();
130 this.messageBuffer
= new Set
<string>();
131 this.sharedLRUCache
= SharedLRUCache
.getInstance();
132 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
133 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
138 private get
wsConnectionUrl(): URL
{
140 (this.getSupervisionUrlOcppConfiguration()
141 ? ChargingStationConfigurationUtils
.getConfigurationKey(
143 this.getSupervisionUrlOcppKey()
145 : this.configuredSupervisionUrl
.href
) +
147 this.stationInfo
.chargingStationId
151 public logPrefix(): string {
152 return Utils
.logPrefix(
154 this?.stationInfo?.chargingStationId ??
155 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
160 public hasAuthorizedTags(): boolean {
161 return !Utils
.isEmptyArray(
162 this.authorizedTagsCache
.getAuthorizedTags(
163 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
168 public getEnableStatistics(): boolean | undefined {
169 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
170 ? this.stationInfo
.enableStatistics
174 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
175 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
178 public getPayloadSchemaValidation(): boolean | undefined {
179 return this.stationInfo
.payloadSchemaValidation
?? true;
182 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
183 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
184 switch (this.getCurrentOutType(stationInfo
)) {
186 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
187 ? localStationInfo
.numberOfPhases
194 public isWebSocketConnectionOpened(): boolean {
195 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
198 public getRegistrationStatus(): RegistrationStatus
{
199 return this?.bootNotificationResponse
?.status;
202 public isInUnknownState(): boolean {
203 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
206 public isInPendingState(): boolean {
207 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
210 public isInAcceptedState(): boolean {
211 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
214 public isInRejectedState(): boolean {
215 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
218 public isRegistered(): boolean {
219 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
222 public isChargingStationAvailable(): boolean {
223 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
226 public isConnectorAvailable(id
: number): boolean {
227 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
230 public getNumberOfConnectors(): number {
231 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
234 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
235 return this.connectors
.get(id
);
238 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
239 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
242 public getOcppStrictCompliance(): boolean {
243 return this.stationInfo
?.ocppStrictCompliance
?? false;
246 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
247 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
248 this.getCurrentOutType(stationInfo
),
252 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
253 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
254 ? localStationInfo
.voltageOut
258 public getConnectorMaximumAvailablePower(connectorId
: number): number {
259 let connectorAmperageLimitationPowerLimit
: number;
261 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
262 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
264 connectorAmperageLimitationPowerLimit
=
265 (this.getCurrentOutType() === CurrentType
.AC
266 ? ACElectricUtils
.powerTotal(
267 this.getNumberOfPhases(),
268 this.getVoltageOut(),
269 this.getAmperageLimitation() * this.getNumberOfConnectors()
271 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
274 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
275 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
277 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
278 isNaN(connectorAmperageLimitationPowerLimit
)
280 : connectorAmperageLimitationPowerLimit
,
281 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
285 public getTransactionIdTag(transactionId
: number): string | undefined {
286 for (const connectorId
of this.connectors
.keys()) {
287 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
288 return this.getConnectorStatus(connectorId
).transactionIdTag
;
293 public getOutOfOrderEndMeterValues(): boolean {
294 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
297 public getBeginEndMeterValues(): boolean {
298 return this.stationInfo
?.beginEndMeterValues
?? false;
301 public getMeteringPerTransaction(): boolean {
302 return this.stationInfo
?.meteringPerTransaction
?? true;
305 public getTransactionDataMeterValues(): boolean {
306 return this.stationInfo
?.transactionDataMeterValues
?? false;
309 public getMainVoltageMeterValues(): boolean {
310 return this.stationInfo
?.mainVoltageMeterValues
?? true;
313 public getPhaseLineToLineVoltageMeterValues(): boolean {
314 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
317 public getCustomValueLimitationMeterValues(): boolean {
318 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
321 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
322 for (const connectorId
of this.connectors
.keys()) {
325 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
332 public getEnergyActiveImportRegisterByTransactionId(
333 transactionId
: number,
336 return this.getEnergyActiveImportRegister(
337 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
342 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
343 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
346 public getAuthorizeRemoteTxRequests(): boolean {
347 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
349 StandardParametersKey
.AuthorizeRemoteTxRequests
351 return authorizeRemoteTxRequests
352 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
356 public getLocalAuthListEnabled(): boolean {
357 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
359 StandardParametersKey
.LocalAuthListEnabled
361 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
364 public startHeartbeat(): void {
366 this.getHeartbeatInterval() &&
367 this.getHeartbeatInterval() > 0 &&
368 !this.heartbeatSetInterval
370 // eslint-disable-next-line @typescript-eslint/no-misused-promises
371 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
372 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
374 RequestCommand
.HEARTBEAT
376 }, this.getHeartbeatInterval());
379 ' Heartbeat started every ' +
380 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
382 } else if (this.heartbeatSetInterval
) {
385 ' Heartbeat already started every ' +
386 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
390 `${this.logPrefix()} Heartbeat interval set to ${
391 this.getHeartbeatInterval()
392 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
393 : this.getHeartbeatInterval()
394 }, not starting the heartbeat`
399 public restartHeartbeat(): void {
401 this.stopHeartbeat();
403 this.startHeartbeat();
406 public restartWebSocketPing(): void {
407 // Stop WebSocket ping
408 this.stopWebSocketPing();
409 // Start WebSocket ping
410 this.startWebSocketPing();
413 public startMeterValues(connectorId
: number, interval
: number): void {
414 if (connectorId
=== 0) {
416 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
420 if (!this.getConnectorStatus(connectorId
)) {
422 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
426 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
428 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
432 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
433 !this.getConnectorStatus(connectorId
)?.transactionId
436 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
441 // eslint-disable-next-line @typescript-eslint/no-misused-promises
442 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 async (): Promise
<void> => {
445 // FIXME: Implement OCPP version agnostic helpers
446 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
449 this.getConnectorStatus(connectorId
).transactionId
,
452 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
454 RequestCommand
.METER_VALUES
,
457 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
458 meterValue
: [meterValue
],
466 `${this.logPrefix()} Charging station ${
467 StandardParametersKey.MeterValueSampleInterval
468 } configuration set to ${
469 interval ? Utils.formatDurationMilliSeconds(interval) : interval
470 }, not sending MeterValues`
475 public start(): void {
476 if (this.started
=== false) {
477 if (this.starting
=== false) {
478 this.starting
= true;
479 if (this.getEnableStatistics()) {
480 this.performanceStatistics
.start();
482 this.openWSConnection();
483 // Monitor charging station template file
484 this.templateFileWatcher
= FileUtils
.watchJsonFile(
486 FileType
.ChargingStationTemplate
,
489 (event
, filename
): void => {
490 if (filename
&& event
=== 'change') {
493 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
495 } file have changed, reload`
497 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
501 this.stopAutomaticTransactionGenerator();
503 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
505 this.startAutomaticTransactionGenerator();
507 if (this.getEnableStatistics()) {
508 this.performanceStatistics
.restart();
510 this.performanceStatistics
.stop();
512 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
515 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
522 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
523 this.starting
= false;
525 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
528 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
532 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
533 if (this.started
=== true) {
534 if (this.stopping
=== false) {
535 this.stopping
= true;
536 await this.stopMessageSequence(reason
);
537 for (const connectorId
of this.connectors
.keys()) {
538 if (connectorId
> 0) {
539 await this.ocppRequestService
.requestHandler
<
540 StatusNotificationRequest
,
541 StatusNotificationResponse
542 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
544 status: ChargePointStatus
.UNAVAILABLE
,
545 errorCode
: ChargePointErrorCode
.NO_ERROR
,
547 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
550 this.closeWSConnection();
551 if (this.getEnableStatistics()) {
552 this.performanceStatistics
.stop();
554 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
555 this.templateFileWatcher
.close();
556 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
557 this.bootNotificationResponse
= null;
558 this.started
= false;
559 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
560 this.stopping
= false;
562 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
565 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
569 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
570 await this.stop(reason
);
571 await Utils
.sleep(this.stationInfo
.resetTime
);
576 public saveOcppConfiguration(): void {
577 if (this.getOcppPersistentConfiguration()) {
578 this.saveConfiguration();
582 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
583 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
585 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
587 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
589 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
591 `${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`
593 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
595 let cpReplaced
= false;
596 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
597 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
598 (chargingProfile
: ChargingProfile
, index
: number) => {
600 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
601 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
602 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
604 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
610 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
613 public resetConnectorStatus(connectorId
: number): void {
614 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
615 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
616 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
617 this.getConnectorStatus(connectorId
).transactionStarted
= false;
618 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
619 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
620 delete this.getConnectorStatus(connectorId
).transactionId
;
621 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
622 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
623 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
624 this.stopMeterValues(connectorId
);
625 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
628 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
629 return ChargingStationConfigurationUtils
.getConfigurationKey(
631 StandardParametersKey
.SupportedFeatureProfiles
632 )?.value
.includes(featureProfile
);
635 public bufferMessage(message
: string): void {
636 this.messageBuffer
.add(message
);
639 public openWSConnection(
640 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
641 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
643 terminateOpened
: false,
646 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
647 params
.closeOpened
= params
?.closeOpened
?? false;
648 params
.terminateOpened
= params
?.terminateOpened
?? false;
650 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
651 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
653 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
655 if (params
?.closeOpened
) {
656 this.closeWSConnection();
658 if (params
?.terminateOpened
) {
659 this.terminateWSConnection();
661 let protocol
: string;
662 switch (this.getOcppVersion()) {
663 case OCPPVersion
.VERSION_16
:
664 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
667 this.handleUnsupportedVersion(this.getOcppVersion());
671 if (this.isWebSocketConnectionOpened()) {
673 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
679 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
682 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
684 // Handle WebSocket message
685 this.wsConnection
.on(
687 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
689 // Handle WebSocket error
690 this.wsConnection
.on(
692 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
694 // Handle WebSocket close
695 this.wsConnection
.on(
697 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
699 // Handle WebSocket open
700 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
701 // Handle WebSocket ping
702 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
703 // Handle WebSocket pong
704 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
707 public closeWSConnection(): void {
708 if (this.isWebSocketConnectionOpened()) {
709 this.wsConnection
.close();
710 this.wsConnection
= null;
714 public startAutomaticTransactionGenerator(
715 connectorIds
?: number[],
716 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
718 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
719 automaticTransactionGeneratorConfiguration
??
720 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
723 if (!Utils
.isEmptyArray(connectorIds
)) {
724 for (const connectorId
of connectorIds
) {
725 this.automaticTransactionGenerator
.startConnector(connectorId
);
728 this.automaticTransactionGenerator
.start();
730 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
733 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
734 if (!Utils
.isEmptyArray(connectorIds
)) {
735 for (const connectorId
of connectorIds
) {
736 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
739 this.automaticTransactionGenerator
?.stop();
741 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
744 public async stopTransactionOnConnector(
746 reason
= StopTransactionReason
.NONE
747 ): Promise
<StopTransactionResponse
> {
748 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
750 this.getBeginEndMeterValues() &&
751 this.getOcppStrictCompliance() &&
752 !this.getOutOfOrderEndMeterValues()
754 // FIXME: Implement OCPP version agnostic helpers
755 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
758 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
760 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
762 RequestCommand
.METER_VALUES
,
766 meterValue
: [transactionEndMeterValue
],
770 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
772 RequestCommand
.STOP_TRANSACTION
,
775 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
781 private flushMessageBuffer(): void {
782 if (this.messageBuffer
.size
> 0) {
783 this.messageBuffer
.forEach((message
) => {
784 // TODO: evaluate the need to track performance
785 this.wsConnection
.send(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';
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 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
861 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
862 stationTemplate
.power
= stationTemplate
.power
as number[];
863 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
864 stationInfo
.maximumPower
=
865 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
866 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
867 : stationTemplate
.power
[powerArrayRandomIndex
];
869 stationTemplate
.power
= stationTemplate
.power
as number;
870 stationInfo
.maximumPower
=
871 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
872 ? stationTemplate
.power
* 1000
873 : stationTemplate
.power
;
875 stationInfo
.resetTime
= stationTemplate
.resetTime
876 ? stationTemplate
.resetTime
* 1000
877 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
878 const configuredMaxConnectors
=
879 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
880 ChargingStationUtils
.checkConfiguredMaxConnectors(
881 configuredMaxConnectors
,
885 const templateMaxConnectors
=
886 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
887 ChargingStationUtils
.checkTemplateMaxConnectors(
888 templateMaxConnectors
,
893 configuredMaxConnectors
>
894 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
895 !stationTemplate
?.randomConnectors
898 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
900 }, forcing random connector configurations affectation`
902 stationInfo
.randomConnectors
= true;
904 // Build connectors if needed (FIXME: should be factored out)
905 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
906 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
907 ChargingStationUtils
.createStationInfoHash(stationInfo
);
911 private getStationInfoFromFile(): ChargingStationInfo
| null {
912 let stationInfo
: ChargingStationInfo
= null;
913 this.getStationInfoPersistentConfiguration() &&
914 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
915 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
919 private getStationInfo(): ChargingStationInfo
{
920 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
921 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
922 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
923 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
924 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
925 return this.stationInfo
;
927 return stationInfoFromFile
;
929 stationInfoFromFile
&&
930 ChargingStationUtils
.propagateSerialNumber(
931 this.getTemplateFromFile(),
933 stationInfoFromTemplate
935 return stationInfoFromTemplate
;
938 private saveStationInfo(): void {
939 if (this.getStationInfoPersistentConfiguration()) {
940 this.saveConfiguration();
944 private getOcppVersion(): OCPPVersion
{
945 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
948 private getOcppPersistentConfiguration(): boolean {
949 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
952 private getStationInfoPersistentConfiguration(): boolean {
953 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
956 private handleUnsupportedVersion(version
: OCPPVersion
) {
957 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
958 logger
.error(`${this.logPrefix()} ${errMsg}`);
959 throw new BaseError(errMsg
);
962 private initialize(): void {
963 this.configurationFile
= path
.join(
964 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
965 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
967 this.stationInfo
= this.getStationInfo();
968 this.saveStationInfo();
969 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
970 // Avoid duplication of connectors related information in RAM
971 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
972 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
973 if (this.getEnableStatistics()) {
974 this.performanceStatistics
= PerformanceStatistics
.getInstance(
975 this.stationInfo
.hashId
,
976 this.stationInfo
.chargingStationId
,
977 this.configuredSupervisionUrl
980 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
983 this.powerDivider
= this.getPowerDivider();
984 // OCPP configuration
985 this.ocppConfiguration
= this.getOcppConfiguration();
986 this.initializeOcppConfiguration();
987 switch (this.getOcppVersion()) {
988 case OCPPVersion
.VERSION_16
:
989 this.ocppIncomingRequestService
=
990 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
991 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
992 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
996 this.handleUnsupportedVersion(this.getOcppVersion());
999 if (this.stationInfo
?.autoRegister
) {
1000 this.bootNotificationResponse
= {
1001 currentTime
: new Date().toISOString(),
1002 interval
: this.getHeartbeatInterval() / 1000,
1003 status: RegistrationStatus
.ACCEPTED
,
1008 private initializeOcppConfiguration(): void {
1010 !ChargingStationConfigurationUtils
.getConfigurationKey(
1012 StandardParametersKey
.HeartbeatInterval
1015 ChargingStationConfigurationUtils
.addConfigurationKey(
1017 StandardParametersKey
.HeartbeatInterval
,
1022 !ChargingStationConfigurationUtils
.getConfigurationKey(
1024 StandardParametersKey
.HeartBeatInterval
1027 ChargingStationConfigurationUtils
.addConfigurationKey(
1029 StandardParametersKey
.HeartBeatInterval
,
1035 this.getSupervisionUrlOcppConfiguration() &&
1036 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1038 ChargingStationConfigurationUtils
.addConfigurationKey(
1040 this.getSupervisionUrlOcppKey(),
1041 this.configuredSupervisionUrl
.href
,
1045 !this.getSupervisionUrlOcppConfiguration() &&
1046 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1048 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1050 this.getSupervisionUrlOcppKey(),
1055 this.stationInfo
.amperageLimitationOcppKey
&&
1056 !ChargingStationConfigurationUtils
.getConfigurationKey(
1058 this.stationInfo
.amperageLimitationOcppKey
1061 ChargingStationConfigurationUtils
.addConfigurationKey(
1063 this.stationInfo
.amperageLimitationOcppKey
,
1065 this.stationInfo
.maximumAmperage
*
1066 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1071 !ChargingStationConfigurationUtils
.getConfigurationKey(
1073 StandardParametersKey
.SupportedFeatureProfiles
1076 ChargingStationConfigurationUtils
.addConfigurationKey(
1078 StandardParametersKey
.SupportedFeatureProfiles
,
1079 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1082 ChargingStationConfigurationUtils
.addConfigurationKey(
1084 StandardParametersKey
.NumberOfConnectors
,
1085 this.getNumberOfConnectors().toString(),
1090 !ChargingStationConfigurationUtils
.getConfigurationKey(
1092 StandardParametersKey
.MeterValuesSampledData
1095 ChargingStationConfigurationUtils
.addConfigurationKey(
1097 StandardParametersKey
.MeterValuesSampledData
,
1098 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1102 !ChargingStationConfigurationUtils
.getConfigurationKey(
1104 StandardParametersKey
.ConnectorPhaseRotation
1107 const connectorPhaseRotation
= [];
1108 for (const connectorId
of this.connectors
.keys()) {
1110 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1111 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1112 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1113 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1115 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1116 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1117 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1118 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1121 ChargingStationConfigurationUtils
.addConfigurationKey(
1123 StandardParametersKey
.ConnectorPhaseRotation
,
1124 connectorPhaseRotation
.toString()
1128 !ChargingStationConfigurationUtils
.getConfigurationKey(
1130 StandardParametersKey
.AuthorizeRemoteTxRequests
1133 ChargingStationConfigurationUtils
.addConfigurationKey(
1135 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1140 !ChargingStationConfigurationUtils
.getConfigurationKey(
1142 StandardParametersKey
.LocalAuthListEnabled
1144 ChargingStationConfigurationUtils
.getConfigurationKey(
1146 StandardParametersKey
.SupportedFeatureProfiles
1147 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1149 ChargingStationConfigurationUtils
.addConfigurationKey(
1151 StandardParametersKey
.LocalAuthListEnabled
,
1156 !ChargingStationConfigurationUtils
.getConfigurationKey(
1158 StandardParametersKey
.ConnectionTimeOut
1161 ChargingStationConfigurationUtils
.addConfigurationKey(
1163 StandardParametersKey
.ConnectionTimeOut
,
1164 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1167 this.saveOcppConfiguration();
1170 private initializeConnectors(
1171 stationInfo
: ChargingStationInfo
,
1172 configuredMaxConnectors
: number,
1173 templateMaxConnectors
: number
1175 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1176 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1177 logger
.error(`${this.logPrefix()} ${logMsg}`);
1178 throw new BaseError(logMsg
);
1180 if (!stationInfo
?.Connectors
[0]) {
1182 `${this.logPrefix()} Charging station information from template ${
1184 } with no connector Id 0 configuration`
1187 if (stationInfo
?.Connectors
) {
1188 const connectorsConfigHash
= crypto
1189 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1190 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1192 const connectorsConfigChanged
=
1193 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1194 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1195 connectorsConfigChanged
&& this.connectors
.clear();
1196 this.connectorsConfigurationHash
= connectorsConfigHash
;
1197 // Add connector Id 0
1198 let lastConnector
= '0';
1199 for (lastConnector
in stationInfo
?.Connectors
) {
1200 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1202 lastConnectorId
=== 0 &&
1203 this.getUseConnectorId0(stationInfo
) === true &&
1204 stationInfo
?.Connectors
[lastConnector
]
1206 this.connectors
.set(
1208 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1210 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1211 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1212 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1216 // Generate all connectors
1217 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1218 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1219 const randConnectorId
= stationInfo
?.randomConnectors
1220 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1222 this.connectors
.set(
1224 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1226 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1227 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1228 this.getConnectorStatus(index
).chargingProfiles
= [];
1235 `${this.logPrefix()} Charging station information from template ${
1237 } with no connectors configuration defined, using already defined connectors`
1240 // Initialize transaction attributes on connectors
1241 for (const connectorId
of this.connectors
.keys()) {
1244 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1245 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1247 this.initializeConnectorStatus(connectorId
);
1252 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1253 let configuration
: ChargingStationConfiguration
= null;
1254 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1256 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1257 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1258 this.configurationFileHash
1261 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1262 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1263 configuration
= JSON
.parse(
1264 fs
.readFileSync(this.configurationFile
, 'utf8')
1265 ) as ChargingStationConfiguration
;
1266 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1267 this.configurationFileHash
= configuration
.configurationHash
;
1268 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1271 FileUtils
.handleFileException(
1273 FileType
.ChargingStationConfiguration
,
1274 this.configurationFile
,
1275 error
as NodeJS
.ErrnoException
1279 return configuration
;
1282 private saveConfiguration(): void {
1283 if (this.configurationFile
) {
1285 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1286 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1288 const configurationData
: ChargingStationConfiguration
=
1289 this.getConfigurationFromFile() ?? {};
1290 this.ocppConfiguration
?.configurationKey
&&
1291 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1292 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1293 delete configurationData
.configurationHash
;
1294 const configurationHash
= crypto
1295 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1296 .update(JSON
.stringify(configurationData
))
1298 if (this.configurationFileHash
!== configurationHash
) {
1299 configurationData
.configurationHash
= configurationHash
;
1300 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1301 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1302 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1303 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1304 fs
.closeSync(fileDescriptor
);
1305 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1306 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1307 this.configurationFileHash
= configurationHash
;
1308 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1311 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1312 this.configurationFile
1317 FileUtils
.handleFileException(
1319 FileType
.ChargingStationConfiguration
,
1320 this.configurationFile
,
1321 error
as NodeJS
.ErrnoException
1326 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1331 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1332 return this.getTemplateFromFile()?.Configuration
?? null;
1335 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1336 let configuration
: ChargingStationConfiguration
= null;
1337 if (this.getOcppPersistentConfiguration()) {
1338 const configurationFromFile
= this.getConfigurationFromFile();
1339 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1341 configuration
&& delete configuration
.stationInfo
;
1342 return configuration
;
1345 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1346 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1347 if (!ocppConfiguration
) {
1348 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1350 return ocppConfiguration
;
1353 private async onOpen(): Promise
<void> {
1354 if (this.isWebSocketConnectionOpened()) {
1356 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1358 if (!this.isRegistered()) {
1359 // Send BootNotification
1360 let registrationRetryCount
= 0;
1362 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1363 BootNotificationRequest
,
1364 BootNotificationResponse
1365 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1366 skipBufferingOnError
: true,
1368 if (!this.isRegistered()) {
1369 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1371 this.bootNotificationResponse
?.interval
1372 ? this.bootNotificationResponse
.interval
* 1000
1373 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1377 !this.isRegistered() &&
1378 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1379 this.getRegistrationMaxRetries() === -1)
1382 if (this.isRegistered()) {
1383 if (this.isInAcceptedState()) {
1384 await this.startMessageSequence();
1388 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1391 this.wsConnectionRestarted
= false;
1392 this.autoReconnectRetryCount
= 0;
1393 this.started
= true;
1394 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1397 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1402 private async onClose(code
: number, reason
: string): Promise
<void> {
1405 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1406 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1408 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1410 )}' and reason '${reason}'`
1412 this.autoReconnectRetryCount
= 0;
1417 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1419 )}' and reason '${reason}'`
1421 await this.reconnect();
1424 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1427 private async onMessage(data
: Data
): Promise
<void> {
1428 let messageType
: number;
1429 let messageId
: string;
1430 let commandName
: IncomingRequestCommand
;
1431 let commandPayload
: JsonType
;
1432 let errorType
: ErrorType
;
1433 let errorMessage
: string;
1434 let errorDetails
: JsonType
;
1435 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1436 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1437 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1438 let requestPayload
: JsonType
;
1439 let cachedRequest
: CachedRequest
;
1442 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1443 if (Array.isArray(request
) === true) {
1444 [messageType
, messageId
] = request
;
1445 // Check the type of message
1446 switch (messageType
) {
1448 case MessageType
.CALL_MESSAGE
:
1449 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1450 if (this.getEnableStatistics() === true) {
1451 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1454 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1458 // Process the message
1459 await this.ocppIncomingRequestService
.incomingRequestHandler(
1467 case MessageType
.CALL_RESULT_MESSAGE
:
1468 [, , commandPayload
] = request
as Response
;
1469 if (this.requests
.has(messageId
) === false) {
1471 throw new OCPPError(
1472 ErrorType
.INTERNAL_ERROR
,
1473 `Response for unknown message id ${messageId}`,
1479 cachedRequest
= this.requests
.get(messageId
);
1480 if (Array.isArray(cachedRequest
) === true) {
1481 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1483 throw new OCPPError(
1484 ErrorType
.PROTOCOL_ERROR
,
1485 `Cached request for message id ${messageId} response is not an array`,
1487 cachedRequest
as unknown
as JsonType
1491 `${this.logPrefix()} << Command '${
1492 requestCommandName ?? 'unknown'
1493 }' received response payload: ${JSON.stringify(request)}`
1495 responseCallback(commandPayload
, requestPayload
);
1498 case MessageType
.CALL_ERROR_MESSAGE
:
1499 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1500 if (this.requests
.has(messageId
) === false) {
1502 throw new OCPPError(
1503 ErrorType
.INTERNAL_ERROR
,
1504 `Error response for unknown message id ${messageId}`,
1506 { errorType
, errorMessage
, errorDetails
}
1509 cachedRequest
= this.requests
.get(messageId
);
1510 if (Array.isArray(cachedRequest
) === true) {
1511 [, errorCallback
, requestCommandName
] = cachedRequest
;
1513 throw new OCPPError(
1514 ErrorType
.PROTOCOL_ERROR
,
1515 `Cached request for message id ${messageId} error response is not an array`,
1517 cachedRequest
as unknown
as JsonType
1521 `${this.logPrefix()} << Command '${
1522 requestCommandName ?? 'unknown'
1523 }' received error payload: ${JSON.stringify(request)}`
1525 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1529 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1530 errMsg
= `Wrong message type ${messageType}`;
1531 logger
.error(`${this.logPrefix()} ${errMsg}`);
1532 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1534 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1536 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1543 `${this.logPrefix()} Incoming OCPP command '${
1544 commandName ?? requestCommandName ?? null
1545 }' message '${data.toString()}'${
1546 messageType !== MessageType.CALL_MESSAGE
1547 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1549 } processing error:`,
1552 if (error
instanceof OCPPError
=== false) {
1554 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1555 commandName ?? requestCommandName ?? null
1556 }' message '${data.toString()}' handling is not an OCPPError:`,
1560 switch (messageType
) {
1561 case MessageType
.CALL_MESSAGE
:
1563 await this.ocppRequestService
.sendError(
1567 commandName
?? requestCommandName
?? null
1570 case MessageType
.CALL_RESULT_MESSAGE
:
1571 case MessageType
.CALL_ERROR_MESSAGE
:
1572 if (errorCallback
) {
1573 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1574 errorCallback(error
as OCPPError
, false);
1576 // Remove the request from the cache in case of error at response handling
1577 this.requests
.delete(messageId
);
1584 private onPing(): void {
1585 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1588 private onPong(): void {
1589 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1592 private onError(error
: WSError
): void {
1593 this.closeWSConnection();
1594 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1597 private getEnergyActiveImportRegister(
1598 connectorStatus
: ConnectorStatus
,
1601 if (this.getMeteringPerTransaction() === true) {
1604 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1605 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1610 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1611 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1615 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1616 const localStationInfo
= stationInfo
?? this.stationInfo
;
1617 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1618 ? localStationInfo
.useConnectorId0
1622 private getNumberOfRunningTransactions(): number {
1624 for (const connectorId
of this.connectors
.keys()) {
1625 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1632 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1633 for (const connectorId
of this.connectors
.keys()) {
1634 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1635 await this.stopTransactionOnConnector(connectorId
, reason
);
1641 private getConnectionTimeout(): number {
1643 ChargingStationConfigurationUtils
.getConfigurationKey(
1645 StandardParametersKey
.ConnectionTimeOut
1650 ChargingStationConfigurationUtils
.getConfigurationKey(
1652 StandardParametersKey
.ConnectionTimeOut
1654 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1657 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1660 // -1 for unlimited, 0 for disabling
1661 private getAutoReconnectMaxRetries(): number {
1662 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1663 return this.stationInfo
.autoReconnectMaxRetries
;
1665 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1666 return Configuration
.getAutoReconnectMaxRetries();
1672 private getRegistrationMaxRetries(): number {
1673 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1674 return this.stationInfo
.registrationMaxRetries
;
1679 private getPowerDivider(): number {
1680 let powerDivider
= this.getNumberOfConnectors();
1681 if (this.stationInfo
?.powerSharedByConnectors
) {
1682 powerDivider
= this.getNumberOfRunningTransactions();
1684 return powerDivider
;
1687 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1688 const localStationInfo
= stationInfo
?? this.stationInfo
;
1689 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1692 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1693 const maximumPower
= this.getMaximumPower(stationInfo
);
1694 switch (this.getCurrentOutType(stationInfo
)) {
1695 case CurrentType
.AC
:
1696 return ACElectricUtils
.amperagePerPhaseFromPower(
1697 this.getNumberOfPhases(stationInfo
),
1698 maximumPower
/ this.getNumberOfConnectors(),
1699 this.getVoltageOut(stationInfo
)
1701 case CurrentType
.DC
:
1702 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1706 private getAmperageLimitation(): number | undefined {
1708 this.stationInfo
.amperageLimitationOcppKey
&&
1709 ChargingStationConfigurationUtils
.getConfigurationKey(
1711 this.stationInfo
.amperageLimitationOcppKey
1716 ChargingStationConfigurationUtils
.getConfigurationKey(
1718 this.stationInfo
.amperageLimitationOcppKey
1720 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1725 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1726 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1727 let chargingProfiles
: ChargingProfile
[] = [];
1728 // Get charging profiles for connector and sort by stack level
1729 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1730 (a
, b
) => b
.stackLevel
- a
.stackLevel
1732 // Get profiles on connector 0
1733 if (this.getConnectorStatus(0).chargingProfiles
) {
1734 chargingProfiles
.push(
1735 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1738 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1739 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1743 if (!Utils
.isNullOrUndefined(result
)) {
1744 limit
= result
.limit
;
1745 matchingChargingProfile
= result
.matchingChargingProfile
;
1746 switch (this.getCurrentOutType()) {
1747 case CurrentType
.AC
:
1749 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1750 ChargingRateUnitType
.WATT
1752 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1754 case CurrentType
.DC
:
1756 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1757 ChargingRateUnitType
.WATT
1759 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1761 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1762 if (limit
> connectorMaximumPower
) {
1764 `${this.logPrefix()} Charging profile id ${
1765 matchingChargingProfile.chargingProfileId
1766 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1767 this.getConnectorStatus(connectorId
).chargingProfiles
1769 limit
= connectorMaximumPower
;
1776 private async startMessageSequence(): Promise
<void> {
1777 if (this.stationInfo
?.autoRegister
) {
1778 await this.ocppRequestService
.requestHandler
<
1779 BootNotificationRequest
,
1780 BootNotificationResponse
1781 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1782 skipBufferingOnError
: true,
1785 // Start WebSocket ping
1786 this.startWebSocketPing();
1788 this.startHeartbeat();
1789 // Initialize connectors status
1790 for (const connectorId
of this.connectors
.keys()) {
1791 if (connectorId
=== 0) {
1794 this.started
=== true &&
1795 !this.getConnectorStatus(connectorId
)?.status &&
1796 this.getConnectorStatus(connectorId
)?.bootStatus
1798 // Send status in template at startup
1799 await this.ocppRequestService
.requestHandler
<
1800 StatusNotificationRequest
,
1801 StatusNotificationResponse
1802 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1804 status: this.getConnectorStatus(connectorId
).bootStatus
,
1805 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1807 this.getConnectorStatus(connectorId
).status =
1808 this.getConnectorStatus(connectorId
).bootStatus
;
1810 this.started
=== false &&
1811 this.getConnectorStatus(connectorId
)?.status &&
1812 this.getConnectorStatus(connectorId
)?.bootStatus
1814 // Send status in template after reset
1815 await this.ocppRequestService
.requestHandler
<
1816 StatusNotificationRequest
,
1817 StatusNotificationResponse
1818 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1820 status: this.getConnectorStatus(connectorId
).bootStatus
,
1821 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1823 this.getConnectorStatus(connectorId
).status =
1824 this.getConnectorStatus(connectorId
).bootStatus
;
1825 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1826 // Send previous status at template reload
1827 await this.ocppRequestService
.requestHandler
<
1828 StatusNotificationRequest
,
1829 StatusNotificationResponse
1830 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1832 status: this.getConnectorStatus(connectorId
).status,
1833 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1836 // Send default status
1837 await this.ocppRequestService
.requestHandler
<
1838 StatusNotificationRequest
,
1839 StatusNotificationResponse
1840 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1842 status: ChargePointStatus
.AVAILABLE
,
1843 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1845 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1849 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1850 this.startAutomaticTransactionGenerator();
1852 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1855 private async stopMessageSequence(
1856 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1858 // Stop WebSocket ping
1859 this.stopWebSocketPing();
1861 this.stopHeartbeat();
1862 // Stop ongoing transactions
1863 if (this.automaticTransactionGenerator
?.started
=== true) {
1864 this.stopAutomaticTransactionGenerator();
1866 await this.stopRunningTransactions(reason
);
1870 private startWebSocketPing(): void {
1871 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1873 StandardParametersKey
.WebSocketPingInterval
1875 ? Utils
.convertToInt(
1876 ChargingStationConfigurationUtils
.getConfigurationKey(
1878 StandardParametersKey
.WebSocketPingInterval
1882 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1883 this.webSocketPingSetInterval
= setInterval(() => {
1884 if (this.isWebSocketConnectionOpened()) {
1885 this.wsConnection
.ping((): void => {
1886 /* This is intentional */
1889 }, webSocketPingInterval
* 1000);
1892 ' WebSocket ping started every ' +
1893 Utils
.formatDurationSeconds(webSocketPingInterval
)
1895 } else if (this.webSocketPingSetInterval
) {
1898 ' WebSocket ping every ' +
1899 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1904 `${this.logPrefix()} WebSocket ping interval set to ${
1905 webSocketPingInterval
1906 ? Utils.formatDurationSeconds(webSocketPingInterval)
1907 : webSocketPingInterval
1908 }, not starting the WebSocket ping`
1913 private stopWebSocketPing(): void {
1914 if (this.webSocketPingSetInterval
) {
1915 clearInterval(this.webSocketPingSetInterval
);
1919 private getConfiguredSupervisionUrl(): URL
{
1920 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1921 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
&&
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()) {
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
);
2031 ' WebSocket: reconnecting try #' +
2032 this.autoReconnectRetryCount
.toString()
2034 this.openWSConnection(
2035 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2036 { closeOpened
: true }
2038 this.wsConnectionRestarted
= true;
2039 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2041 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2042 this.autoReconnectRetryCount
2043 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2048 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2049 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2052 private initializeConnectorStatus(connectorId
: number): void {
2053 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2054 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2055 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2056 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2057 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2058 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;