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 templateFile
: string;
89 public stationInfo
!: ChargingStationInfo
;
90 public started
: boolean;
91 public authorizedTagsCache
: AuthorizedTagsCache
;
92 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
93 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
94 public wsConnection
!: WebSocket
;
95 public readonly connectors
: Map
<number, ConnectorStatus
>;
96 public readonly requests
: Map
<string, CachedRequest
>;
97 public performanceStatistics
!: PerformanceStatistics
;
98 public heartbeatSetInterval
!: NodeJS
.Timeout
;
99 public ocppRequestService
!: OCPPRequestService
;
100 public bootNotificationRequest
!: BootNotificationRequest
;
101 public bootNotificationResponse
!: BootNotificationResponse
| null;
102 public powerDivider
!: number;
103 private starting
: boolean;
104 private stopping
: boolean;
105 private readonly index
: number;
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 wsConnectionRestarted
: boolean;
113 private autoReconnectRetryCount
: number;
114 private templateFileWatcher
!: fs
.FSWatcher
;
115 private readonly sharedLRUCache
: SharedLRUCache
;
116 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
117 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
119 constructor(index
: number, templateFile
: string) {
120 this.started
= false;
121 this.starting
= false;
122 this.stopping
= false;
123 this.wsConnectionRestarted
= false;
124 this.autoReconnectRetryCount
= 0;
126 this.templateFile
= templateFile
;
127 this.connectors
= new Map
<number, ConnectorStatus
>();
128 this.requests
= new Map
<string, CachedRequest
>();
129 this.messageBuffer
= new Set
<string>();
130 this.sharedLRUCache
= SharedLRUCache
.getInstance();
131 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
132 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
137 private get
wsConnectionUrl(): URL
{
139 (this.getSupervisionUrlOcppConfiguration()
140 ? ChargingStationConfigurationUtils
.getConfigurationKey(
142 this.getSupervisionUrlOcppKey()
144 : this.configuredSupervisionUrl
.href
) +
146 this.stationInfo
.chargingStationId
150 public logPrefix(): string {
151 return Utils
.logPrefix(
153 this?.stationInfo?.chargingStationId ??
154 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
159 public getRandomIdTag(): string {
160 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
161 const index
= Math.floor(
162 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
164 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
167 public hasAuthorizedTags(): boolean {
168 return !Utils
.isEmptyArray(
169 this.authorizedTagsCache
.getAuthorizedTags(
170 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
175 public getEnableStatistics(): boolean | undefined {
176 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
177 ? this.stationInfo
.enableStatistics
181 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
182 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
185 public getPayloadSchemaValidation(): boolean | undefined {
186 return this.stationInfo
.payloadSchemaValidation
?? true;
189 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
190 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
191 switch (this.getCurrentOutType(stationInfo
)) {
193 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
194 ? localStationInfo
.numberOfPhases
201 public isWebSocketConnectionOpened(): boolean {
202 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
205 public getRegistrationStatus(): RegistrationStatus
{
206 return this?.bootNotificationResponse
?.status;
209 public isInUnknownState(): boolean {
210 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
213 public isInPendingState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
217 public isInAcceptedState(): boolean {
218 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
221 public isInRejectedState(): boolean {
222 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
225 public isRegistered(): boolean {
226 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
229 public isChargingStationAvailable(): boolean {
230 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
233 public isConnectorAvailable(id
: number): boolean {
234 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
237 public getNumberOfConnectors(): number {
238 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
241 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
242 return this.connectors
.get(id
);
245 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
246 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
249 public getOcppStrictCompliance(): boolean {
250 return this.stationInfo
?.ocppStrictCompliance
?? false;
253 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
254 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
255 this.getCurrentOutType(stationInfo
),
259 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
260 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
261 ? localStationInfo
.voltageOut
265 public getConnectorMaximumAvailablePower(connectorId
: number): number {
266 let connectorAmperageLimitationPowerLimit
: number;
268 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
269 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
271 connectorAmperageLimitationPowerLimit
=
272 (this.getCurrentOutType() === CurrentType
.AC
273 ? ACElectricUtils
.powerTotal(
274 this.getNumberOfPhases(),
275 this.getVoltageOut(),
276 this.getAmperageLimitation() * this.getNumberOfConnectors()
278 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
281 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
282 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
284 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
285 isNaN(connectorAmperageLimitationPowerLimit
)
287 : connectorAmperageLimitationPowerLimit
,
288 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
292 public getTransactionIdTag(transactionId
: number): string | undefined {
293 for (const connectorId
of this.connectors
.keys()) {
294 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
295 return this.getConnectorStatus(connectorId
).transactionIdTag
;
300 public getOutOfOrderEndMeterValues(): boolean {
301 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
304 public getBeginEndMeterValues(): boolean {
305 return this.stationInfo
?.beginEndMeterValues
?? false;
308 public getMeteringPerTransaction(): boolean {
309 return this.stationInfo
?.meteringPerTransaction
?? true;
312 public getTransactionDataMeterValues(): boolean {
313 return this.stationInfo
?.transactionDataMeterValues
?? false;
316 public getMainVoltageMeterValues(): boolean {
317 return this.stationInfo
?.mainVoltageMeterValues
?? true;
320 public getPhaseLineToLineVoltageMeterValues(): boolean {
321 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
324 public getCustomValueLimitationMeterValues(): boolean {
325 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
328 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
329 for (const connectorId
of this.connectors
.keys()) {
332 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
339 public getEnergyActiveImportRegisterByTransactionId(
340 transactionId
: number,
343 return this.getEnergyActiveImportRegister(
344 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
349 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
350 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
353 public getAuthorizeRemoteTxRequests(): boolean {
354 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
356 StandardParametersKey
.AuthorizeRemoteTxRequests
358 return authorizeRemoteTxRequests
359 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
363 public getLocalAuthListEnabled(): boolean {
364 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
366 StandardParametersKey
.LocalAuthListEnabled
368 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
371 public startHeartbeat(): void {
373 this.getHeartbeatInterval() &&
374 this.getHeartbeatInterval() > 0 &&
375 !this.heartbeatSetInterval
377 // eslint-disable-next-line @typescript-eslint/no-misused-promises
378 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
379 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
381 RequestCommand
.HEARTBEAT
383 }, this.getHeartbeatInterval());
386 ' Heartbeat started every ' +
387 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
389 } else if (this.heartbeatSetInterval
) {
392 ' Heartbeat already started every ' +
393 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
397 `${this.logPrefix()} Heartbeat interval set to ${
398 this.getHeartbeatInterval()
399 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
400 : this.getHeartbeatInterval()
401 }, not starting the heartbeat`
406 public restartHeartbeat(): void {
408 this.stopHeartbeat();
410 this.startHeartbeat();
413 public restartWebSocketPing(): void {
414 // Stop WebSocket ping
415 this.stopWebSocketPing();
416 // Start WebSocket ping
417 this.startWebSocketPing();
420 public startMeterValues(connectorId
: number, interval
: number): void {
421 if (connectorId
=== 0) {
423 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
427 if (!this.getConnectorStatus(connectorId
)) {
429 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
433 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
435 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
439 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
440 !this.getConnectorStatus(connectorId
)?.transactionId
443 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
448 // eslint-disable-next-line @typescript-eslint/no-misused-promises
449 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
450 // eslint-disable-next-line @typescript-eslint/no-misused-promises
451 async (): Promise
<void> => {
452 // FIXME: Implement OCPP version agnostic helpers
453 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
456 this.getConnectorStatus(connectorId
).transactionId
,
459 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
461 RequestCommand
.METER_VALUES
,
464 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
465 meterValue
: [meterValue
],
473 `${this.logPrefix()} Charging station ${
474 StandardParametersKey.MeterValueSampleInterval
475 } configuration set to ${
476 interval ? Utils.formatDurationMilliSeconds(interval) : interval
477 }, not sending MeterValues`
482 public start(): void {
483 if (this.started
=== false) {
484 if (this.starting
=== false) {
485 this.starting
= true;
486 if (this.getEnableStatistics()) {
487 this.performanceStatistics
.start();
489 this.openWSConnection();
490 // Monitor charging station template file
491 this.templateFileWatcher
= FileUtils
.watchJsonFile(
493 FileType
.ChargingStationTemplate
,
496 (event
, filename
): void => {
497 if (filename
&& event
=== 'change') {
500 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
502 } file have changed, reload`
504 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
508 this.stopAutomaticTransactionGenerator();
510 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
512 this.startAutomaticTransactionGenerator();
514 if (this.getEnableStatistics()) {
515 this.performanceStatistics
.restart();
517 this.performanceStatistics
.stop();
519 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
522 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
529 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
530 this.starting
= false;
532 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
535 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
539 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
540 if (this.started
=== true) {
541 if (this.stopping
=== false) {
542 this.stopping
= true;
543 await this.stopMessageSequence(reason
);
544 for (const connectorId
of this.connectors
.keys()) {
545 if (connectorId
> 0) {
546 await this.ocppRequestService
.requestHandler
<
547 StatusNotificationRequest
,
548 StatusNotificationResponse
549 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
551 status: ChargePointStatus
.UNAVAILABLE
,
552 errorCode
: ChargePointErrorCode
.NO_ERROR
,
554 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
557 this.closeWSConnection();
558 if (this.getEnableStatistics()) {
559 this.performanceStatistics
.stop();
561 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
562 this.templateFileWatcher
.close();
563 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
564 this.bootNotificationResponse
= null;
565 this.started
= false;
566 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
567 this.stopping
= false;
569 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
572 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
576 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
577 await this.stop(reason
);
578 await Utils
.sleep(this.stationInfo
.resetTime
);
583 public saveOcppConfiguration(): void {
584 if (this.getOcppPersistentConfiguration()) {
585 this.saveConfiguration();
589 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
590 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
592 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
594 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
596 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
598 `${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`
600 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
602 let cpReplaced
= false;
603 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
604 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
605 (chargingProfile
: ChargingProfile
, index
: number) => {
607 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
608 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
609 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
611 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
617 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
620 public resetConnectorStatus(connectorId
: number): void {
621 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
622 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
623 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
624 this.getConnectorStatus(connectorId
).transactionStarted
= false;
625 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
626 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
627 delete this.getConnectorStatus(connectorId
).transactionId
;
628 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
629 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
630 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
631 this.stopMeterValues(connectorId
);
632 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
635 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
636 return ChargingStationConfigurationUtils
.getConfigurationKey(
638 StandardParametersKey
.SupportedFeatureProfiles
639 )?.value
.includes(featureProfile
);
642 public bufferMessage(message
: string): void {
643 this.messageBuffer
.add(message
);
646 public openWSConnection(
647 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
648 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
650 terminateOpened
: false,
653 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
654 params
.closeOpened
= params
?.closeOpened
?? false;
655 params
.terminateOpened
= params
?.terminateOpened
?? false;
657 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
658 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
660 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
662 if (params
?.closeOpened
) {
663 this.closeWSConnection();
665 if (params
?.terminateOpened
) {
666 this.terminateWSConnection();
668 let protocol
: string;
669 switch (this.getOcppVersion()) {
670 case OCPPVersion
.VERSION_16
:
671 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
674 this.handleUnsupportedVersion(this.getOcppVersion());
678 if (this.isWebSocketConnectionOpened()) {
680 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
686 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
689 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
691 // Handle WebSocket message
692 this.wsConnection
.on(
694 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
696 // Handle WebSocket error
697 this.wsConnection
.on(
699 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
701 // Handle WebSocket close
702 this.wsConnection
.on(
704 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
706 // Handle WebSocket open
707 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
708 // Handle WebSocket ping
709 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
710 // Handle WebSocket pong
711 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
714 public closeWSConnection(): void {
715 if (this.isWebSocketConnectionOpened()) {
716 this.wsConnection
.close();
717 this.wsConnection
= null;
721 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
722 if (!this.automaticTransactionGenerator
) {
723 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
724 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
728 if (!Utils
.isEmptyArray(connectorIds
)) {
729 for (const connectorId
of connectorIds
) {
730 this.automaticTransactionGenerator
.startConnector(connectorId
);
733 this.automaticTransactionGenerator
.start();
735 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
738 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
739 if (!Utils
.isEmptyArray(connectorIds
)) {
740 for (const connectorId
of connectorIds
) {
741 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
744 this.automaticTransactionGenerator
?.stop();
746 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
749 public async stopTransactionOnConnector(
751 reason
= StopTransactionReason
.NONE
752 ): Promise
<StopTransactionResponse
> {
753 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
755 this.getBeginEndMeterValues() &&
756 this.getOcppStrictCompliance() &&
757 !this.getOutOfOrderEndMeterValues()
759 // FIXME: Implement OCPP version agnostic helpers
760 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
763 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
765 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
767 RequestCommand
.METER_VALUES
,
771 meterValue
: [transactionEndMeterValue
],
775 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
777 RequestCommand
.STOP_TRANSACTION
,
780 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
786 private flushMessageBuffer(): void {
787 if (this.messageBuffer
.size
> 0) {
788 this.messageBuffer
.forEach((message
) => {
789 // TODO: evaluate the need to track performance
790 this.wsConnection
.send(message
);
791 this.messageBuffer
.delete(message
);
796 private getSupervisionUrlOcppConfiguration(): boolean {
797 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
800 private getSupervisionUrlOcppKey(): string {
801 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
804 private getTemplateFromFile(): ChargingStationTemplate
| null {
805 let template
: ChargingStationTemplate
= null;
807 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
808 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
810 const measureId
= `${FileType.ChargingStationTemplate} read`;
811 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
812 template
= JSON
.parse(
813 fs
.readFileSync(this.templateFile
, 'utf8')
814 ) as ChargingStationTemplate
;
815 PerformanceStatistics
.endMeasure(measureId
, beginId
);
816 template
.templateHash
= crypto
817 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
818 .update(JSON
.stringify(template
))
820 this.sharedLRUCache
.setChargingStationTemplate(template
);
823 FileUtils
.handleFileException(
825 FileType
.ChargingStationTemplate
,
827 error
as NodeJS
.ErrnoException
833 private getStationInfoFromTemplate(): ChargingStationInfo
{
834 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
835 if (Utils
.isNullOrUndefined(stationTemplate
)) {
836 const errorMsg
= 'Failed to read charging station template file';
837 logger
.error(`${this.logPrefix()} ${errorMsg}`);
838 throw new BaseError(errorMsg
);
840 if (Utils
.isEmptyObject(stationTemplate
)) {
841 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
842 logger
.error(`${this.logPrefix()} ${errorMsg}`);
843 throw new BaseError(errorMsg
);
845 // Deprecation template keys section
846 ChargingStationUtils
.warnDeprecatedTemplateKey(
851 "Use 'supervisionUrls' instead"
853 ChargingStationUtils
.convertDeprecatedTemplateKey(
858 const stationInfo
: ChargingStationInfo
=
859 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
860 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
861 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
865 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
866 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
867 stationTemplate
.power
= stationTemplate
.power
as number[];
868 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
869 stationInfo
.maximumPower
=
870 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
871 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
872 : stationTemplate
.power
[powerArrayRandomIndex
];
874 stationTemplate
.power
= stationTemplate
.power
as number;
875 stationInfo
.maximumPower
=
876 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
877 ? stationTemplate
.power
* 1000
878 : stationTemplate
.power
;
880 stationInfo
.resetTime
= stationTemplate
.resetTime
881 ? stationTemplate
.resetTime
* 1000
882 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
883 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
887 ChargingStationUtils
.checkConfiguredMaxConnectors(
888 configuredMaxConnectors
,
892 const templateMaxConnectors
=
893 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
894 ChargingStationUtils
.checkTemplateMaxConnectors(
895 templateMaxConnectors
,
900 configuredMaxConnectors
>
901 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
902 !stationTemplate
?.randomConnectors
905 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
907 }, forcing random connector configurations affectation`
909 stationInfo
.randomConnectors
= true;
911 // Build connectors if needed (FIXME: should be factored out)
912 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
913 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
914 ChargingStationUtils
.createStationInfoHash(stationInfo
);
918 private getStationInfoFromFile(): ChargingStationInfo
| null {
919 let stationInfo
: ChargingStationInfo
= null;
920 this.getStationInfoPersistentConfiguration() &&
921 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
922 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
926 private getStationInfo(): ChargingStationInfo
{
927 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
928 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
929 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
930 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
931 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
932 return this.stationInfo
;
934 return stationInfoFromFile
;
936 stationInfoFromFile
&&
937 ChargingStationUtils
.propagateSerialNumber(
938 this.getTemplateFromFile(),
940 stationInfoFromTemplate
942 return stationInfoFromTemplate
;
945 private saveStationInfo(): void {
946 if (this.getStationInfoPersistentConfiguration()) {
947 this.saveConfiguration();
951 private getOcppVersion(): OCPPVersion
{
952 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
955 private getOcppPersistentConfiguration(): boolean {
956 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
959 private getStationInfoPersistentConfiguration(): boolean {
960 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
963 private handleUnsupportedVersion(version
: OCPPVersion
) {
964 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
965 logger
.error(`${this.logPrefix()} ${errMsg}`);
966 throw new BaseError(errMsg
);
969 private initialize(): void {
970 this.configurationFile
= path
.join(
971 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
972 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
974 this.stationInfo
= this.getStationInfo();
975 this.saveStationInfo();
976 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
977 // Avoid duplication of connectors related information in RAM
978 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
979 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
980 if (this.getEnableStatistics()) {
981 this.performanceStatistics
= PerformanceStatistics
.getInstance(
982 this.stationInfo
.hashId
,
983 this.stationInfo
.chargingStationId
,
984 this.configuredSupervisionUrl
987 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
990 this.powerDivider
= this.getPowerDivider();
991 // OCPP configuration
992 this.ocppConfiguration
= this.getOcppConfiguration();
993 this.initializeOcppConfiguration();
994 switch (this.getOcppVersion()) {
995 case OCPPVersion
.VERSION_16
:
996 this.ocppIncomingRequestService
=
997 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
998 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
999 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1003 this.handleUnsupportedVersion(this.getOcppVersion());
1006 if (this.stationInfo
?.autoRegister
) {
1007 this.bootNotificationResponse
= {
1008 currentTime
: new Date().toISOString(),
1009 interval
: this.getHeartbeatInterval() / 1000,
1010 status: RegistrationStatus
.ACCEPTED
,
1015 private initializeOcppConfiguration(): void {
1017 !ChargingStationConfigurationUtils
.getConfigurationKey(
1019 StandardParametersKey
.HeartbeatInterval
1022 ChargingStationConfigurationUtils
.addConfigurationKey(
1024 StandardParametersKey
.HeartbeatInterval
,
1029 !ChargingStationConfigurationUtils
.getConfigurationKey(
1031 StandardParametersKey
.HeartBeatInterval
1034 ChargingStationConfigurationUtils
.addConfigurationKey(
1036 StandardParametersKey
.HeartBeatInterval
,
1042 this.getSupervisionUrlOcppConfiguration() &&
1043 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1045 ChargingStationConfigurationUtils
.addConfigurationKey(
1047 this.getSupervisionUrlOcppKey(),
1048 this.configuredSupervisionUrl
.href
,
1052 !this.getSupervisionUrlOcppConfiguration() &&
1053 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1055 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1057 this.getSupervisionUrlOcppKey(),
1062 this.stationInfo
.amperageLimitationOcppKey
&&
1063 !ChargingStationConfigurationUtils
.getConfigurationKey(
1065 this.stationInfo
.amperageLimitationOcppKey
1068 ChargingStationConfigurationUtils
.addConfigurationKey(
1070 this.stationInfo
.amperageLimitationOcppKey
,
1072 this.stationInfo
.maximumAmperage
*
1073 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1078 !ChargingStationConfigurationUtils
.getConfigurationKey(
1080 StandardParametersKey
.SupportedFeatureProfiles
1083 ChargingStationConfigurationUtils
.addConfigurationKey(
1085 StandardParametersKey
.SupportedFeatureProfiles
,
1086 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1089 ChargingStationConfigurationUtils
.addConfigurationKey(
1091 StandardParametersKey
.NumberOfConnectors
,
1092 this.getNumberOfConnectors().toString(),
1097 !ChargingStationConfigurationUtils
.getConfigurationKey(
1099 StandardParametersKey
.MeterValuesSampledData
1102 ChargingStationConfigurationUtils
.addConfigurationKey(
1104 StandardParametersKey
.MeterValuesSampledData
,
1105 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1109 !ChargingStationConfigurationUtils
.getConfigurationKey(
1111 StandardParametersKey
.ConnectorPhaseRotation
1114 const connectorPhaseRotation
= [];
1115 for (const connectorId
of this.connectors
.keys()) {
1117 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1118 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1119 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1120 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1122 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1123 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1124 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1125 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1128 ChargingStationConfigurationUtils
.addConfigurationKey(
1130 StandardParametersKey
.ConnectorPhaseRotation
,
1131 connectorPhaseRotation
.toString()
1135 !ChargingStationConfigurationUtils
.getConfigurationKey(
1137 StandardParametersKey
.AuthorizeRemoteTxRequests
1140 ChargingStationConfigurationUtils
.addConfigurationKey(
1142 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1147 !ChargingStationConfigurationUtils
.getConfigurationKey(
1149 StandardParametersKey
.LocalAuthListEnabled
1151 ChargingStationConfigurationUtils
.getConfigurationKey(
1153 StandardParametersKey
.SupportedFeatureProfiles
1154 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1156 ChargingStationConfigurationUtils
.addConfigurationKey(
1158 StandardParametersKey
.LocalAuthListEnabled
,
1163 !ChargingStationConfigurationUtils
.getConfigurationKey(
1165 StandardParametersKey
.ConnectionTimeOut
1168 ChargingStationConfigurationUtils
.addConfigurationKey(
1170 StandardParametersKey
.ConnectionTimeOut
,
1171 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1174 this.saveOcppConfiguration();
1177 private initializeConnectors(
1178 stationInfo
: ChargingStationInfo
,
1179 configuredMaxConnectors
: number,
1180 templateMaxConnectors
: number
1182 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1183 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1184 logger
.error(`${this.logPrefix()} ${logMsg}`);
1185 throw new BaseError(logMsg
);
1187 if (!stationInfo
?.Connectors
[0]) {
1189 `${this.logPrefix()} Charging station information from template ${
1191 } with no connector Id 0 configuration`
1194 if (stationInfo
?.Connectors
) {
1195 const connectorsConfigHash
= crypto
1196 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1197 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1199 const connectorsConfigChanged
=
1200 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1201 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1202 connectorsConfigChanged
&& this.connectors
.clear();
1203 this.connectorsConfigurationHash
= connectorsConfigHash
;
1204 // Add connector Id 0
1205 let lastConnector
= '0';
1206 for (lastConnector
in stationInfo
?.Connectors
) {
1207 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1209 lastConnectorId
=== 0 &&
1210 this.getUseConnectorId0(stationInfo
) === true &&
1211 stationInfo
?.Connectors
[lastConnector
]
1213 this.connectors
.set(
1215 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1217 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1218 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1219 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1223 // Generate all connectors
1224 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1225 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1226 const randConnectorId
= stationInfo
?.randomConnectors
1227 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1229 this.connectors
.set(
1231 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1233 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1234 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1235 this.getConnectorStatus(index
).chargingProfiles
= [];
1242 `${this.logPrefix()} Charging station information from template ${
1244 } with no connectors configuration defined, using already defined connectors`
1247 // Initialize transaction attributes on connectors
1248 for (const connectorId
of this.connectors
.keys()) {
1251 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1252 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1254 this.initializeConnectorStatus(connectorId
);
1259 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1260 let configuration
: ChargingStationConfiguration
= null;
1261 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1263 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1264 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1265 this.configurationFileHash
1268 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1269 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1270 configuration
= JSON
.parse(
1271 fs
.readFileSync(this.configurationFile
, 'utf8')
1272 ) as ChargingStationConfiguration
;
1273 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1274 this.configurationFileHash
= configuration
.configurationHash
;
1275 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1278 FileUtils
.handleFileException(
1280 FileType
.ChargingStationConfiguration
,
1281 this.configurationFile
,
1282 error
as NodeJS
.ErrnoException
1286 return configuration
;
1289 private saveConfiguration(): void {
1290 if (this.configurationFile
) {
1292 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1293 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1295 const configurationData
: ChargingStationConfiguration
=
1296 this.getConfigurationFromFile() ?? {};
1297 this.ocppConfiguration
?.configurationKey
&&
1298 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1299 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1300 delete configurationData
.configurationHash
;
1301 const configurationHash
= crypto
1302 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1303 .update(JSON
.stringify(configurationData
))
1305 if (this.configurationFileHash
!== configurationHash
) {
1306 configurationData
.configurationHash
= configurationHash
;
1307 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1308 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1309 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1310 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1311 fs
.closeSync(fileDescriptor
);
1312 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1313 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1314 this.configurationFileHash
= configurationHash
;
1315 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1318 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1319 this.configurationFile
1324 FileUtils
.handleFileException(
1326 FileType
.ChargingStationConfiguration
,
1327 this.configurationFile
,
1328 error
as NodeJS
.ErrnoException
1333 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1338 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1339 return this.getTemplateFromFile()?.Configuration
?? null;
1342 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1343 let configuration
: ChargingStationConfiguration
= null;
1344 if (this.getOcppPersistentConfiguration()) {
1345 const configurationFromFile
= this.getConfigurationFromFile();
1346 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1348 configuration
&& delete configuration
.stationInfo
;
1349 return configuration
;
1352 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1353 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1354 if (!ocppConfiguration
) {
1355 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1357 return ocppConfiguration
;
1360 private async onOpen(): Promise
<void> {
1361 if (this.isWebSocketConnectionOpened()) {
1363 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1365 if (!this.isRegistered()) {
1366 // Send BootNotification
1367 let registrationRetryCount
= 0;
1369 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1370 BootNotificationRequest
,
1371 BootNotificationResponse
1372 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1373 skipBufferingOnError
: true,
1375 if (!this.isRegistered()) {
1376 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1378 this.bootNotificationResponse
?.interval
1379 ? this.bootNotificationResponse
.interval
* 1000
1380 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1384 !this.isRegistered() &&
1385 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1386 this.getRegistrationMaxRetries() === -1)
1389 if (this.isRegistered()) {
1390 if (this.isInAcceptedState()) {
1391 await this.startMessageSequence();
1395 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1398 this.wsConnectionRestarted
= false;
1399 this.autoReconnectRetryCount
= 0;
1400 this.started
= true;
1401 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1404 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1409 private async onClose(code
: number, reason
: string): Promise
<void> {
1412 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1413 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1415 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1417 )}' and reason '${reason}'`
1419 this.autoReconnectRetryCount
= 0;
1424 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1426 )}' and reason '${reason}'`
1428 await this.reconnect();
1431 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1434 private async onMessage(data
: Data
): Promise
<void> {
1435 let messageType
: number;
1436 let messageId
: string;
1437 let commandName
: IncomingRequestCommand
;
1438 let commandPayload
: JsonType
;
1439 let errorType
: ErrorType
;
1440 let errorMessage
: string;
1441 let errorDetails
: JsonType
;
1442 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1443 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1444 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1445 let requestPayload
: JsonType
;
1446 let cachedRequest
: CachedRequest
;
1449 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1450 if (Array.isArray(request
) === true) {
1451 [messageType
, messageId
] = request
;
1452 // Check the type of message
1453 switch (messageType
) {
1455 case MessageType
.CALL_MESSAGE
:
1456 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1457 if (this.getEnableStatistics() === true) {
1458 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1461 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1465 // Process the message
1466 await this.ocppIncomingRequestService
.incomingRequestHandler(
1474 case MessageType
.CALL_RESULT_MESSAGE
:
1475 [, , commandPayload
] = request
as Response
;
1476 if (this.requests
.has(messageId
) === false) {
1478 throw new OCPPError(
1479 ErrorType
.INTERNAL_ERROR
,
1480 `Response for unknown message id ${messageId}`,
1486 cachedRequest
= this.requests
.get(messageId
);
1487 if (Array.isArray(cachedRequest
) === true) {
1488 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1490 throw new OCPPError(
1491 ErrorType
.PROTOCOL_ERROR
,
1492 `Cached request for message id ${messageId} response is not an array`,
1494 cachedRequest
as unknown
as JsonType
1498 `${this.logPrefix()} << Command '${
1499 requestCommandName ?? 'unknown'
1500 }' received response payload: ${JSON.stringify(request)}`
1502 responseCallback(commandPayload
, requestPayload
);
1505 case MessageType
.CALL_ERROR_MESSAGE
:
1506 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1507 if (this.requests
.has(messageId
) === false) {
1509 throw new OCPPError(
1510 ErrorType
.INTERNAL_ERROR
,
1511 `Error response for unknown message id ${messageId}`,
1513 { errorType
, errorMessage
, errorDetails
}
1516 cachedRequest
= this.requests
.get(messageId
);
1517 if (Array.isArray(cachedRequest
) === true) {
1518 [, errorCallback
, requestCommandName
] = cachedRequest
;
1520 throw new OCPPError(
1521 ErrorType
.PROTOCOL_ERROR
,
1522 `Cached request for message id ${messageId} error response is not an array`,
1524 cachedRequest
as unknown
as JsonType
1528 `${this.logPrefix()} << Command '${
1529 requestCommandName ?? 'unknown'
1530 }' received error payload: ${JSON.stringify(request)}`
1532 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1536 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1537 errMsg
= `Wrong message type ${messageType}`;
1538 logger
.error(`${this.logPrefix()} ${errMsg}`);
1539 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1541 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1543 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1550 `${this.logPrefix()} Incoming OCPP command '${
1551 commandName ?? requestCommandName ?? null
1552 }' message '${data.toString()}'${
1553 messageType !== MessageType.CALL_MESSAGE
1554 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1556 } processing error:`,
1559 if (error
instanceof OCPPError
=== false) {
1561 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1562 commandName ?? requestCommandName ?? null
1563 }' message '${data.toString()}' handling is not an OCPPError:`,
1567 switch (messageType
) {
1568 case MessageType
.CALL_MESSAGE
:
1570 await this.ocppRequestService
.sendError(
1574 commandName
?? requestCommandName
?? null
1577 case MessageType
.CALL_RESULT_MESSAGE
:
1578 case MessageType
.CALL_ERROR_MESSAGE
:
1579 if (errorCallback
) {
1580 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1581 errorCallback(error
as OCPPError
, false);
1583 // Remove the request from the cache in case of error at response handling
1584 this.requests
.delete(messageId
);
1591 private onPing(): void {
1592 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1595 private onPong(): void {
1596 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1599 private onError(error
: WSError
): void {
1600 this.closeWSConnection();
1601 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1604 private getEnergyActiveImportRegister(
1605 connectorStatus
: ConnectorStatus
,
1608 if (this.getMeteringPerTransaction() === true) {
1611 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1612 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1617 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1618 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1622 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1623 const localStationInfo
= stationInfo
?? this.stationInfo
;
1624 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1625 ? localStationInfo
.useConnectorId0
1629 private getNumberOfRunningTransactions(): number {
1631 for (const connectorId
of this.connectors
.keys()) {
1632 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1639 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1640 for (const connectorId
of this.connectors
.keys()) {
1641 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1642 await this.stopTransactionOnConnector(connectorId
, reason
);
1648 private getConnectionTimeout(): number | undefined {
1650 ChargingStationConfigurationUtils
.getConfigurationKey(
1652 StandardParametersKey
.ConnectionTimeOut
1657 ChargingStationConfigurationUtils
.getConfigurationKey(
1659 StandardParametersKey
.ConnectionTimeOut
1661 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1664 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1667 // -1 for unlimited, 0 for disabling
1668 private getAutoReconnectMaxRetries(): number | undefined {
1669 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1670 return this.stationInfo
.autoReconnectMaxRetries
;
1672 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1673 return Configuration
.getAutoReconnectMaxRetries();
1679 private getRegistrationMaxRetries(): number | undefined {
1680 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1681 return this.stationInfo
.registrationMaxRetries
;
1686 private getPowerDivider(): number {
1687 let powerDivider
= this.getNumberOfConnectors();
1688 if (this.stationInfo
?.powerSharedByConnectors
) {
1689 powerDivider
= this.getNumberOfRunningTransactions();
1691 return powerDivider
;
1694 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1695 const localStationInfo
= stationInfo
?? this.stationInfo
;
1696 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1699 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1700 const maximumPower
= this.getMaximumPower(stationInfo
);
1701 switch (this.getCurrentOutType(stationInfo
)) {
1702 case CurrentType
.AC
:
1703 return ACElectricUtils
.amperagePerPhaseFromPower(
1704 this.getNumberOfPhases(stationInfo
),
1705 maximumPower
/ this.getNumberOfConnectors(),
1706 this.getVoltageOut(stationInfo
)
1708 case CurrentType
.DC
:
1709 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1713 private getAmperageLimitation(): number | undefined {
1715 this.stationInfo
.amperageLimitationOcppKey
&&
1716 ChargingStationConfigurationUtils
.getConfigurationKey(
1718 this.stationInfo
.amperageLimitationOcppKey
1723 ChargingStationConfigurationUtils
.getConfigurationKey(
1725 this.stationInfo
.amperageLimitationOcppKey
1727 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1732 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1733 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1734 let chargingProfiles
: ChargingProfile
[] = [];
1735 // Get charging profiles for connector and sort by stack level
1736 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1737 (a
, b
) => b
.stackLevel
- a
.stackLevel
1739 // Get profiles on connector 0
1740 if (this.getConnectorStatus(0).chargingProfiles
) {
1741 chargingProfiles
.push(
1742 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1745 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1746 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1750 if (!Utils
.isNullOrUndefined(result
)) {
1751 limit
= result
.limit
;
1752 matchingChargingProfile
= result
.matchingChargingProfile
;
1753 switch (this.getCurrentOutType()) {
1754 case CurrentType
.AC
:
1756 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1757 ChargingRateUnitType
.WATT
1759 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1761 case CurrentType
.DC
:
1763 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1764 ChargingRateUnitType
.WATT
1766 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1768 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1769 if (limit
> connectorMaximumPower
) {
1771 `${this.logPrefix()} Charging profile id ${
1772 matchingChargingProfile.chargingProfileId
1773 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1774 this.getConnectorStatus(connectorId
).chargingProfiles
1776 limit
= connectorMaximumPower
;
1783 private async startMessageSequence(): Promise
<void> {
1784 if (this.stationInfo
?.autoRegister
) {
1785 await this.ocppRequestService
.requestHandler
<
1786 BootNotificationRequest
,
1787 BootNotificationResponse
1788 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1789 skipBufferingOnError
: true,
1792 // Start WebSocket ping
1793 this.startWebSocketPing();
1795 this.startHeartbeat();
1796 // Initialize connectors status
1797 for (const connectorId
of this.connectors
.keys()) {
1798 if (connectorId
=== 0) {
1801 this.started
=== true &&
1802 !this.getConnectorStatus(connectorId
)?.status &&
1803 this.getConnectorStatus(connectorId
)?.bootStatus
1805 // Send status in template at startup
1806 await this.ocppRequestService
.requestHandler
<
1807 StatusNotificationRequest
,
1808 StatusNotificationResponse
1809 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1811 status: this.getConnectorStatus(connectorId
).bootStatus
,
1812 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1814 this.getConnectorStatus(connectorId
).status =
1815 this.getConnectorStatus(connectorId
).bootStatus
;
1817 this.started
=== false &&
1818 this.getConnectorStatus(connectorId
)?.status &&
1819 this.getConnectorStatus(connectorId
)?.bootStatus
1821 // Send status in template after reset
1822 await this.ocppRequestService
.requestHandler
<
1823 StatusNotificationRequest
,
1824 StatusNotificationResponse
1825 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1827 status: this.getConnectorStatus(connectorId
).bootStatus
,
1828 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1830 this.getConnectorStatus(connectorId
).status =
1831 this.getConnectorStatus(connectorId
).bootStatus
;
1832 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1833 // Send previous status at template reload
1834 await this.ocppRequestService
.requestHandler
<
1835 StatusNotificationRequest
,
1836 StatusNotificationResponse
1837 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1839 status: this.getConnectorStatus(connectorId
).status,
1840 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1843 // Send default status
1844 await this.ocppRequestService
.requestHandler
<
1845 StatusNotificationRequest
,
1846 StatusNotificationResponse
1847 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1849 status: ChargePointStatus
.AVAILABLE
,
1850 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1852 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1856 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1857 this.startAutomaticTransactionGenerator();
1859 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1862 private async stopMessageSequence(
1863 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1865 // Stop WebSocket ping
1866 this.stopWebSocketPing();
1868 this.stopHeartbeat();
1869 // Stop ongoing transactions
1870 if (this.automaticTransactionGenerator
?.started
=== true) {
1871 this.stopAutomaticTransactionGenerator();
1873 await this.stopRunningTransactions(reason
);
1877 private startWebSocketPing(): void {
1878 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1880 StandardParametersKey
.WebSocketPingInterval
1882 ? Utils
.convertToInt(
1883 ChargingStationConfigurationUtils
.getConfigurationKey(
1885 StandardParametersKey
.WebSocketPingInterval
1889 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1890 this.webSocketPingSetInterval
= setInterval(() => {
1891 if (this.isWebSocketConnectionOpened()) {
1892 this.wsConnection
.ping((): void => {
1893 /* This is intentional */
1896 }, webSocketPingInterval
* 1000);
1899 ' WebSocket ping started every ' +
1900 Utils
.formatDurationSeconds(webSocketPingInterval
)
1902 } else if (this.webSocketPingSetInterval
) {
1905 ' WebSocket ping every ' +
1906 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1911 `${this.logPrefix()} WebSocket ping interval set to ${
1912 webSocketPingInterval
1913 ? Utils.formatDurationSeconds(webSocketPingInterval)
1914 : webSocketPingInterval
1915 }, not starting the WebSocket ping`
1920 private stopWebSocketPing(): void {
1921 if (this.webSocketPingSetInterval
) {
1922 clearInterval(this.webSocketPingSetInterval
);
1926 private getConfiguredSupervisionUrl(): URL
{
1927 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1928 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1930 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1932 switch (Configuration
.getSupervisionUrlDistribution()) {
1933 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1934 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1936 case SupervisionUrlDistribution
.RANDOM
:
1938 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1940 case SupervisionUrlDistribution
.SEQUENTIAL
:
1941 if (this.index
<= supervisionUrls
.length
) {
1942 urlIndex
= this.index
- 1;
1945 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1951 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1952 SupervisionUrlDistribution.ROUND_ROBIN
1955 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1958 return new URL(supervisionUrls
[urlIndex
]);
1960 return new URL(supervisionUrls
as string);
1963 private getHeartbeatInterval(): number | undefined {
1964 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1966 StandardParametersKey
.HeartbeatInterval
1968 if (HeartbeatInterval
) {
1969 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1971 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1973 StandardParametersKey
.HeartBeatInterval
1975 if (HeartBeatInterval
) {
1976 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1978 !this.stationInfo
?.autoRegister
&&
1980 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1981 Constants.DEFAULT_HEARTBEAT_INTERVAL
1984 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1987 private stopHeartbeat(): void {
1988 if (this.heartbeatSetInterval
) {
1989 clearInterval(this.heartbeatSetInterval
);
1993 private terminateWSConnection(): void {
1994 if (this.isWebSocketConnectionOpened()) {
1995 this.wsConnection
.terminate();
1996 this.wsConnection
= null;
2000 private stopMeterValues(connectorId
: number) {
2001 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2002 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2006 private getReconnectExponentialDelay(): boolean | undefined {
2007 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2008 ? this.stationInfo
.reconnectExponentialDelay
2012 private async reconnect(): Promise
<void> {
2013 // Stop WebSocket ping
2014 this.stopWebSocketPing();
2016 this.stopHeartbeat();
2017 // Stop the ATG if needed
2018 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2019 this.stopAutomaticTransactionGenerator();
2022 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2023 this.getAutoReconnectMaxRetries() === -1
2025 this.autoReconnectRetryCount
++;
2026 const reconnectDelay
= this.getReconnectExponentialDelay()
2027 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2028 : this.getConnectionTimeout() * 1000;
2029 const reconnectDelayWithdraw
= 1000;
2030 const reconnectTimeout
=
2031 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2032 ? reconnectDelay
- reconnectDelayWithdraw
2035 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2038 )}ms, timeout ${reconnectTimeout}ms`
2040 await Utils
.sleep(reconnectDelay
);
2043 ' WebSocket: reconnecting try #' +
2044 this.autoReconnectRetryCount
.toString()
2046 this.openWSConnection(
2047 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2048 { closeOpened
: true }
2050 this.wsConnectionRestarted
= true;
2051 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2053 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2054 this.autoReconnectRetryCount
2055 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2060 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2061 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2064 private initializeConnectorStatus(connectorId
: number): void {
2065 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2066 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2067 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2068 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2069 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2070 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;