1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import type ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import type ChargingStationInfo from
'../types/ChargingStationInfo';
17 import type ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import type { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public readonly templateFile
: string;
88 public stationInfo
!: ChargingStationInfo
;
89 public started
: boolean;
90 public authorizedTagsCache
: AuthorizedTagsCache
;
91 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
92 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
93 public wsConnection
!: WebSocket
;
94 public readonly connectors
: Map
<number, ConnectorStatus
>;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationRequest
!: BootNotificationRequest
;
100 public bootNotificationResponse
!: BootNotificationResponse
| null;
101 public powerDivider
!: number;
102 private readonly index
: number;
103 private configurationFile
!: string;
104 private configurationFileHash
!: string;
105 private connectorsConfigurationHash
!: string;
106 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
107 private readonly messageBuffer
: Set
<string>;
108 private configuredSupervisionUrl
!: URL
;
109 private wsConnectionRestarted
: boolean;
110 private autoReconnectRetryCount
: number;
111 private templateFileWatcher
!: fs
.FSWatcher
;
112 private readonly sharedLRUCache
: SharedLRUCache
;
113 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
114 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
116 constructor(index
: number, templateFile
: string) {
118 this.templateFile
= templateFile
;
119 this.connectors
= new Map
<number, ConnectorStatus
>();
120 this.requests
= new Map
<string, CachedRequest
>();
121 this.messageBuffer
= new Set
<string>();
122 this.sharedLRUCache
= SharedLRUCache
.getInstance();
123 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
124 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
125 this.started
= false;
126 this.wsConnectionRestarted
= false;
127 this.autoReconnectRetryCount
= 0;
132 private get
wsConnectionUrl(): URL
{
134 (this.getSupervisionUrlOcppConfiguration()
135 ? ChargingStationConfigurationUtils
.getConfigurationKey(
137 this.getSupervisionUrlOcppKey()
139 : this.configuredSupervisionUrl
.href
) +
141 this.stationInfo
.chargingStationId
145 public logPrefix(): string {
146 return Utils
.logPrefix(
148 this?.stationInfo?.chargingStationId ??
149 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
154 public getRandomIdTag(): string {
155 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
156 const index
= Math.floor(
157 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
159 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
162 public hasAuthorizedTags(): boolean {
163 return !Utils
.isEmptyArray(
164 this.authorizedTagsCache
.getAuthorizedTags(
165 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
170 public getEnableStatistics(): boolean | undefined {
171 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
172 ? this.stationInfo
.enableStatistics
176 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
177 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
180 public getPayloadSchemaValidation(): boolean | undefined {
181 return this.stationInfo
.payloadSchemaValidation
?? true;
184 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
185 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
186 switch (this.getCurrentOutType(stationInfo
)) {
188 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
189 ? localStationInfo
.numberOfPhases
196 public isWebSocketConnectionOpened(): boolean {
197 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
200 public getRegistrationStatus(): RegistrationStatus
{
201 return this?.bootNotificationResponse
?.status;
204 public isInUnknownState(): boolean {
205 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
208 public isInPendingState(): boolean {
209 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
212 public isInAcceptedState(): boolean {
213 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
216 public isInRejectedState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
220 public isRegistered(): boolean {
221 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
224 public isChargingStationAvailable(): boolean {
225 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
228 public isConnectorAvailable(id
: number): boolean {
229 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
232 public getNumberOfConnectors(): number {
233 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
236 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
237 return this.connectors
.get(id
);
240 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
241 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
244 public getOcppStrictCompliance(): boolean {
245 return this.stationInfo
?.ocppStrictCompliance
?? false;
248 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
249 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
250 this.getCurrentOutType(stationInfo
),
254 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
255 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
256 ? localStationInfo
.voltageOut
260 public getConnectorMaximumAvailablePower(connectorId
: number): number {
261 let connectorAmperageLimitationPowerLimit
: number;
263 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
264 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
266 connectorAmperageLimitationPowerLimit
=
267 (this.getCurrentOutType() === CurrentType
.AC
268 ? ACElectricUtils
.powerTotal(
269 this.getNumberOfPhases(),
270 this.getVoltageOut(),
271 this.getAmperageLimitation() * this.getNumberOfConnectors()
273 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
276 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
277 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
279 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
280 isNaN(connectorAmperageLimitationPowerLimit
)
282 : connectorAmperageLimitationPowerLimit
,
283 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
287 public getTransactionIdTag(transactionId
: number): string | undefined {
288 for (const connectorId
of this.connectors
.keys()) {
289 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
290 return this.getConnectorStatus(connectorId
).transactionIdTag
;
295 public getOutOfOrderEndMeterValues(): boolean {
296 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
299 public getBeginEndMeterValues(): boolean {
300 return this.stationInfo
?.beginEndMeterValues
?? false;
303 public getMeteringPerTransaction(): boolean {
304 return this.stationInfo
?.meteringPerTransaction
?? true;
307 public getTransactionDataMeterValues(): boolean {
308 return this.stationInfo
?.transactionDataMeterValues
?? false;
311 public getMainVoltageMeterValues(): boolean {
312 return this.stationInfo
?.mainVoltageMeterValues
?? true;
315 public getPhaseLineToLineVoltageMeterValues(): boolean {
316 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
319 public getCustomValueLimitationMeterValues(): boolean {
320 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
323 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
324 for (const connectorId
of this.connectors
.keys()) {
327 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
334 public getEnergyActiveImportRegisterByTransactionId(
335 transactionId
: number,
338 return this.getEnergyActiveImportRegister(
339 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
344 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
345 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
348 public getAuthorizeRemoteTxRequests(): boolean {
349 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
351 StandardParametersKey
.AuthorizeRemoteTxRequests
353 return authorizeRemoteTxRequests
354 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
358 public getLocalAuthListEnabled(): boolean {
359 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
361 StandardParametersKey
.LocalAuthListEnabled
363 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
366 public startHeartbeat(): void {
368 this.getHeartbeatInterval() &&
369 this.getHeartbeatInterval() > 0 &&
370 !this.heartbeatSetInterval
372 // eslint-disable-next-line @typescript-eslint/no-misused-promises
373 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
374 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
376 RequestCommand
.HEARTBEAT
378 }, this.getHeartbeatInterval());
381 ' Heartbeat started every ' +
382 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
384 } else if (this.heartbeatSetInterval
) {
387 ' Heartbeat already started every ' +
388 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
392 `${this.logPrefix()} Heartbeat interval set to ${
393 this.getHeartbeatInterval()
394 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
395 : this.getHeartbeatInterval()
396 }, not starting the heartbeat`
401 public restartHeartbeat(): void {
403 this.stopHeartbeat();
405 this.startHeartbeat();
408 public restartWebSocketPing(): void {
409 // Stop WebSocket ping
410 this.stopWebSocketPing();
411 // Start WebSocket ping
412 this.startWebSocketPing();
415 public startMeterValues(connectorId
: number, interval
: number): void {
416 if (connectorId
=== 0) {
418 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
422 if (!this.getConnectorStatus(connectorId
)) {
424 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
428 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
430 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
434 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
435 !this.getConnectorStatus(connectorId
)?.transactionId
438 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
445 // eslint-disable-next-line @typescript-eslint/no-misused-promises
446 async (): Promise
<void> => {
447 // FIXME: Implement OCPP version agnostic helpers
448 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
451 this.getConnectorStatus(connectorId
).transactionId
,
454 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
456 RequestCommand
.METER_VALUES
,
459 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
460 meterValue
: [meterValue
],
468 `${this.logPrefix()} Charging station ${
469 StandardParametersKey.MeterValueSampleInterval
470 } configuration set to ${
471 interval ? Utils.formatDurationMilliSeconds(interval) : interval
472 }, not sending MeterValues`
477 public start(): void {
478 if (this.getEnableStatistics()) {
479 this.performanceStatistics
.start();
481 this.openWSConnection();
482 // Monitor charging station template file
483 this.templateFileWatcher
= FileUtils
.watchJsonFile(
485 FileType
.ChargingStationTemplate
,
488 (event
, filename
): void => {
489 if (filename
&& event
=== 'change') {
492 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
494 } file have changed, reload`
496 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
500 this.stopAutomaticTransactionGenerator();
501 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
502 this.startAutomaticTransactionGenerator();
504 if (this.getEnableStatistics()) {
505 this.performanceStatistics
.restart();
507 this.performanceStatistics
.stop();
509 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
512 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
519 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
522 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
523 await this.stopMessageSequence(reason
);
524 for (const connectorId
of this.connectors
.keys()) {
525 if (connectorId
> 0) {
526 await this.ocppRequestService
.requestHandler
<
527 StatusNotificationRequest
,
528 StatusNotificationResponse
529 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
531 status: ChargePointStatus
.UNAVAILABLE
,
532 errorCode
: ChargePointErrorCode
.NO_ERROR
,
534 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
537 this.closeWSConnection();
538 if (this.getEnableStatistics()) {
539 this.performanceStatistics
.stop();
541 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
542 this.templateFileWatcher
.close();
543 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
544 this.bootNotificationResponse
= null;
545 this.started
= false;
546 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
549 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
550 await this.stop(reason
);
551 await Utils
.sleep(this.stationInfo
.resetTime
);
556 public saveOcppConfiguration(): void {
557 if (this.getOcppPersistentConfiguration()) {
558 this.saveConfiguration();
562 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
563 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
565 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
567 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
569 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
571 `${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`
573 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
575 let cpReplaced
= false;
576 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
577 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
578 (chargingProfile
: ChargingProfile
, index
: number) => {
580 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
581 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
582 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
584 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
590 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
593 public resetConnectorStatus(connectorId
: number): void {
594 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
595 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
596 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
597 this.getConnectorStatus(connectorId
).transactionStarted
= false;
598 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
599 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
600 delete this.getConnectorStatus(connectorId
).transactionId
;
601 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
602 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
603 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
604 this.stopMeterValues(connectorId
);
605 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
608 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
609 return ChargingStationConfigurationUtils
.getConfigurationKey(
611 StandardParametersKey
.SupportedFeatureProfiles
612 )?.value
.includes(featureProfile
);
615 public bufferMessage(message
: string): void {
616 this.messageBuffer
.add(message
);
619 public openWSConnection(
620 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
621 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
623 terminateOpened
: false,
626 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
627 params
.closeOpened
= params
?.closeOpened
?? false;
628 params
.terminateOpened
= params
?.terminateOpened
?? false;
630 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
631 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
633 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
635 if (params
?.closeOpened
) {
636 this.closeWSConnection();
638 if (params
?.terminateOpened
) {
639 this.terminateWSConnection();
641 let protocol
: string;
642 switch (this.getOcppVersion()) {
643 case OCPPVersion
.VERSION_16
:
644 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
647 this.handleUnsupportedVersion(this.getOcppVersion());
651 if (this.isWebSocketConnectionOpened()) {
653 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
659 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
662 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
664 // Handle WebSocket message
665 this.wsConnection
.on(
667 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
669 // Handle WebSocket error
670 this.wsConnection
.on(
672 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
674 // Handle WebSocket close
675 this.wsConnection
.on(
677 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
679 // Handle WebSocket open
680 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
681 // Handle WebSocket ping
682 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
683 // Handle WebSocket pong
684 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
687 public closeWSConnection(): void {
688 if (this.isWebSocketConnectionOpened()) {
689 this.wsConnection
.close();
690 this.wsConnection
= null;
694 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
695 if (!this.automaticTransactionGenerator
) {
696 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
697 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
701 if (!Utils
.isEmptyArray(connectorIds
)) {
702 for (const connectorId
of connectorIds
) {
703 this.automaticTransactionGenerator
.startConnector(connectorId
);
706 this.automaticTransactionGenerator
.start();
710 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
711 if (!Utils
.isEmptyArray(connectorIds
)) {
712 for (const connectorId
of connectorIds
) {
713 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
716 this.automaticTransactionGenerator
?.stop();
717 this.automaticTransactionGenerator
= null;
721 public async stopTransactionOnConnector(
723 reason
= StopTransactionReason
.NONE
724 ): Promise
<StopTransactionResponse
> {
725 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
727 this.getBeginEndMeterValues() &&
728 this.getOcppStrictCompliance() &&
729 !this.getOutOfOrderEndMeterValues()
731 // FIXME: Implement OCPP version agnostic helpers
732 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
735 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
737 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
739 RequestCommand
.METER_VALUES
,
743 meterValue
: [transactionEndMeterValue
],
747 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
749 RequestCommand
.STOP_TRANSACTION
,
752 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
758 private flushMessageBuffer(): void {
759 if (this.messageBuffer
.size
> 0) {
760 this.messageBuffer
.forEach((message
) => {
761 // TODO: evaluate the need to track performance
762 this.wsConnection
.send(message
);
763 this.messageBuffer
.delete(message
);
768 private getSupervisionUrlOcppConfiguration(): boolean {
769 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
772 private getSupervisionUrlOcppKey(): string {
773 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
776 private getTemplateFromFile(): ChargingStationTemplate
| null {
777 let template
: ChargingStationTemplate
= null;
779 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
780 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
782 const measureId
= `${FileType.ChargingStationTemplate} read`;
783 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
784 template
= JSON
.parse(
785 fs
.readFileSync(this.templateFile
, 'utf8')
786 ) as ChargingStationTemplate
;
787 PerformanceStatistics
.endMeasure(measureId
, beginId
);
788 template
.templateHash
= crypto
789 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
790 .update(JSON
.stringify(template
))
792 this.sharedLRUCache
.setChargingStationTemplate(template
);
795 FileUtils
.handleFileException(
797 FileType
.ChargingStationTemplate
,
799 error
as NodeJS
.ErrnoException
805 private getStationInfoFromTemplate(): ChargingStationInfo
{
806 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
807 if (Utils
.isNullOrUndefined(stationTemplate
)) {
808 const errorMsg
= 'Failed to read charging station template file';
809 logger
.error(`${this.logPrefix()} ${errorMsg}`);
810 throw new BaseError(errorMsg
);
812 if (Utils
.isEmptyObject(stationTemplate
)) {
813 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
814 logger
.error(`${this.logPrefix()} ${errorMsg}`);
815 throw new BaseError(errorMsg
);
817 // Deprecation template keys section
818 ChargingStationUtils
.warnDeprecatedTemplateKey(
823 "Use 'supervisionUrls' instead"
825 ChargingStationUtils
.convertDeprecatedTemplateKey(
830 const stationInfo
: ChargingStationInfo
=
831 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
832 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
833 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
837 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
838 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
839 stationTemplate
.power
= stationTemplate
.power
as number[];
840 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
841 stationInfo
.maximumPower
=
842 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
843 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
844 : stationTemplate
.power
[powerArrayRandomIndex
];
846 stationTemplate
.power
= stationTemplate
.power
as number;
847 stationInfo
.maximumPower
=
848 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
849 ? stationTemplate
.power
* 1000
850 : stationTemplate
.power
;
852 stationInfo
.resetTime
= stationTemplate
.resetTime
853 ? stationTemplate
.resetTime
* 1000
854 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
855 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
859 ChargingStationUtils
.checkConfiguredMaxConnectors(
860 configuredMaxConnectors
,
864 const templateMaxConnectors
=
865 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
866 ChargingStationUtils
.checkTemplateMaxConnectors(
867 templateMaxConnectors
,
872 configuredMaxConnectors
>
873 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
874 !stationTemplate
?.randomConnectors
877 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
879 }, forcing random connector configurations affectation`
881 stationInfo
.randomConnectors
= true;
883 // Build connectors if needed (FIXME: should be factored out)
884 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
885 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
886 ChargingStationUtils
.createStationInfoHash(stationInfo
);
890 private getStationInfoFromFile(): ChargingStationInfo
| null {
891 let stationInfo
: ChargingStationInfo
= null;
892 this.getStationInfoPersistentConfiguration() &&
893 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
894 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
898 private getStationInfo(): ChargingStationInfo
{
899 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
900 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
901 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
902 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
903 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
904 return this.stationInfo
;
906 return stationInfoFromFile
;
908 stationInfoFromFile
&&
909 ChargingStationUtils
.propagateSerialNumber(
910 this.getTemplateFromFile(),
912 stationInfoFromTemplate
914 return stationInfoFromTemplate
;
917 private saveStationInfo(): void {
918 if (this.getStationInfoPersistentConfiguration()) {
919 this.saveConfiguration();
923 private getOcppVersion(): OCPPVersion
{
924 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
927 private getOcppPersistentConfiguration(): boolean {
928 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
931 private getStationInfoPersistentConfiguration(): boolean {
932 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
935 private handleUnsupportedVersion(version
: OCPPVersion
) {
936 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
937 logger
.error(`${this.logPrefix()} ${errMsg}`);
938 throw new BaseError(errMsg
);
941 private initialize(): void {
942 this.configurationFile
= path
.join(
943 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
944 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
946 this.stationInfo
= this.getStationInfo();
947 this.saveStationInfo();
948 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
949 // Avoid duplication of connectors related information in RAM
950 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
951 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
952 if (this.getEnableStatistics()) {
953 this.performanceStatistics
= PerformanceStatistics
.getInstance(
954 this.stationInfo
.hashId
,
955 this.stationInfo
.chargingStationId
,
956 this.configuredSupervisionUrl
959 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
962 this.powerDivider
= this.getPowerDivider();
963 // OCPP configuration
964 this.ocppConfiguration
= this.getOcppConfiguration();
965 this.initializeOcppConfiguration();
966 switch (this.getOcppVersion()) {
967 case OCPPVersion
.VERSION_16
:
968 this.ocppIncomingRequestService
=
969 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
970 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
971 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
975 this.handleUnsupportedVersion(this.getOcppVersion());
978 if (this.stationInfo
?.autoRegister
) {
979 this.bootNotificationResponse
= {
980 currentTime
: new Date().toISOString(),
981 interval
: this.getHeartbeatInterval() / 1000,
982 status: RegistrationStatus
.ACCEPTED
,
987 private initializeOcppConfiguration(): void {
989 !ChargingStationConfigurationUtils
.getConfigurationKey(
991 StandardParametersKey
.HeartbeatInterval
994 ChargingStationConfigurationUtils
.addConfigurationKey(
996 StandardParametersKey
.HeartbeatInterval
,
1001 !ChargingStationConfigurationUtils
.getConfigurationKey(
1003 StandardParametersKey
.HeartBeatInterval
1006 ChargingStationConfigurationUtils
.addConfigurationKey(
1008 StandardParametersKey
.HeartBeatInterval
,
1014 this.getSupervisionUrlOcppConfiguration() &&
1015 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1017 ChargingStationConfigurationUtils
.addConfigurationKey(
1019 this.getSupervisionUrlOcppKey(),
1020 this.configuredSupervisionUrl
.href
,
1024 !this.getSupervisionUrlOcppConfiguration() &&
1025 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1027 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1029 this.getSupervisionUrlOcppKey(),
1034 this.stationInfo
.amperageLimitationOcppKey
&&
1035 !ChargingStationConfigurationUtils
.getConfigurationKey(
1037 this.stationInfo
.amperageLimitationOcppKey
1040 ChargingStationConfigurationUtils
.addConfigurationKey(
1042 this.stationInfo
.amperageLimitationOcppKey
,
1044 this.stationInfo
.maximumAmperage
*
1045 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1050 !ChargingStationConfigurationUtils
.getConfigurationKey(
1052 StandardParametersKey
.SupportedFeatureProfiles
1055 ChargingStationConfigurationUtils
.addConfigurationKey(
1057 StandardParametersKey
.SupportedFeatureProfiles
,
1058 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1061 ChargingStationConfigurationUtils
.addConfigurationKey(
1063 StandardParametersKey
.NumberOfConnectors
,
1064 this.getNumberOfConnectors().toString(),
1069 !ChargingStationConfigurationUtils
.getConfigurationKey(
1071 StandardParametersKey
.MeterValuesSampledData
1074 ChargingStationConfigurationUtils
.addConfigurationKey(
1076 StandardParametersKey
.MeterValuesSampledData
,
1077 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1081 !ChargingStationConfigurationUtils
.getConfigurationKey(
1083 StandardParametersKey
.ConnectorPhaseRotation
1086 const connectorPhaseRotation
= [];
1087 for (const connectorId
of this.connectors
.keys()) {
1089 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1090 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1091 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1092 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1094 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1095 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1096 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1097 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1100 ChargingStationConfigurationUtils
.addConfigurationKey(
1102 StandardParametersKey
.ConnectorPhaseRotation
,
1103 connectorPhaseRotation
.toString()
1107 !ChargingStationConfigurationUtils
.getConfigurationKey(
1109 StandardParametersKey
.AuthorizeRemoteTxRequests
1112 ChargingStationConfigurationUtils
.addConfigurationKey(
1114 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1119 !ChargingStationConfigurationUtils
.getConfigurationKey(
1121 StandardParametersKey
.LocalAuthListEnabled
1123 ChargingStationConfigurationUtils
.getConfigurationKey(
1125 StandardParametersKey
.SupportedFeatureProfiles
1126 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1128 ChargingStationConfigurationUtils
.addConfigurationKey(
1130 StandardParametersKey
.LocalAuthListEnabled
,
1135 !ChargingStationConfigurationUtils
.getConfigurationKey(
1137 StandardParametersKey
.ConnectionTimeOut
1140 ChargingStationConfigurationUtils
.addConfigurationKey(
1142 StandardParametersKey
.ConnectionTimeOut
,
1143 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1146 this.saveOcppConfiguration();
1149 private initializeConnectors(
1150 stationInfo
: ChargingStationInfo
,
1151 configuredMaxConnectors
: number,
1152 templateMaxConnectors
: number
1154 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1155 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1156 logger
.error(`${this.logPrefix()} ${logMsg}`);
1157 throw new BaseError(logMsg
);
1159 if (!stationInfo
?.Connectors
[0]) {
1161 `${this.logPrefix()} Charging station information from template ${
1163 } with no connector Id 0 configuration`
1166 if (stationInfo
?.Connectors
) {
1167 const connectorsConfigHash
= crypto
1168 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1169 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1171 const connectorsConfigChanged
=
1172 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1173 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1174 connectorsConfigChanged
&& this.connectors
.clear();
1175 this.connectorsConfigurationHash
= connectorsConfigHash
;
1176 // Add connector Id 0
1177 let lastConnector
= '0';
1178 for (lastConnector
in stationInfo
?.Connectors
) {
1179 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1181 lastConnectorId
=== 0 &&
1182 this.getUseConnectorId0(stationInfo
) &&
1183 stationInfo
?.Connectors
[lastConnector
]
1185 this.connectors
.set(
1187 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1189 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1190 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1191 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1195 // Generate all connectors
1196 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1197 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1198 const randConnectorId
= stationInfo
?.randomConnectors
1199 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1201 this.connectors
.set(
1203 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1205 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1206 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1207 this.getConnectorStatus(index
).chargingProfiles
= [];
1214 `${this.logPrefix()} Charging station information from template ${
1216 } with no connectors configuration defined, using already defined connectors`
1219 // Initialize transaction attributes on connectors
1220 for (const connectorId
of this.connectors
.keys()) {
1223 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1224 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1226 this.initializeConnectorStatus(connectorId
);
1231 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1232 let configuration
: ChargingStationConfiguration
= null;
1233 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1235 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1236 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1237 this.configurationFileHash
1240 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1241 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1242 configuration
= JSON
.parse(
1243 fs
.readFileSync(this.configurationFile
, 'utf8')
1244 ) as ChargingStationConfiguration
;
1245 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1246 this.configurationFileHash
= configuration
.configurationHash
;
1247 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1250 FileUtils
.handleFileException(
1252 FileType
.ChargingStationConfiguration
,
1253 this.configurationFile
,
1254 error
as NodeJS
.ErrnoException
1258 return configuration
;
1261 private saveConfiguration(): void {
1262 if (this.configurationFile
) {
1264 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1265 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1267 const configurationData
: ChargingStationConfiguration
=
1268 this.getConfigurationFromFile() ?? {};
1269 this.ocppConfiguration
?.configurationKey
&&
1270 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1271 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1272 delete configurationData
.configurationHash
;
1273 const configurationHash
= crypto
1274 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1275 .update(JSON
.stringify(configurationData
))
1277 if (this.configurationFileHash
!== configurationHash
) {
1278 configurationData
.configurationHash
= configurationHash
;
1279 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1280 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1281 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1282 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1283 fs
.closeSync(fileDescriptor
);
1284 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1285 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1286 this.configurationFileHash
= configurationHash
;
1287 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1290 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1291 this.configurationFile
1296 FileUtils
.handleFileException(
1298 FileType
.ChargingStationConfiguration
,
1299 this.configurationFile
,
1300 error
as NodeJS
.ErrnoException
1305 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1310 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1311 return this.getTemplateFromFile()?.Configuration
?? null;
1314 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1315 let configuration
: ChargingStationConfiguration
= null;
1316 if (this.getOcppPersistentConfiguration()) {
1317 const configurationFromFile
= this.getConfigurationFromFile();
1318 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1320 configuration
&& delete configuration
.stationInfo
;
1321 return configuration
;
1324 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1325 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1326 if (!ocppConfiguration
) {
1327 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1329 return ocppConfiguration
;
1332 private async onOpen(): Promise
<void> {
1333 if (this.isWebSocketConnectionOpened()) {
1335 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1337 if (!this.isRegistered()) {
1338 // Send BootNotification
1339 let registrationRetryCount
= 0;
1341 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1342 BootNotificationRequest
,
1343 BootNotificationResponse
1346 RequestCommand
.BOOT_NOTIFICATION
,
1348 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1349 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1350 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1351 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1352 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1353 iccid
: this.bootNotificationRequest
.iccid
,
1354 imsi
: this.bootNotificationRequest
.imsi
,
1355 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1356 meterType
: this.bootNotificationRequest
.meterType
,
1358 { skipBufferingOnError
: true }
1360 if (!this.isRegistered()) {
1361 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1363 this.bootNotificationResponse
?.interval
1364 ? this.bootNotificationResponse
.interval
* 1000
1365 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1369 !this.isRegistered() &&
1370 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1371 this.getRegistrationMaxRetries() === -1)
1374 if (this.isRegistered()) {
1375 if (this.isInAcceptedState()) {
1376 await this.startMessageSequence();
1377 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1381 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1384 this.started
=== false && (this.started
= true);
1385 this.autoReconnectRetryCount
= 0;
1386 this.wsConnectionRestarted
= false;
1387 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1390 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1395 private async onClose(code
: number, reason
: string): Promise
<void> {
1398 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1399 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1401 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1403 )}' and reason '${reason}'`
1405 this.autoReconnectRetryCount
= 0;
1410 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1412 )}' and reason '${reason}'`
1414 await this.reconnect(code
);
1417 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1420 private async onMessage(data
: Data
): Promise
<void> {
1421 let messageType
: number;
1422 let messageId
: string;
1423 let commandName
: IncomingRequestCommand
;
1424 let commandPayload
: JsonType
;
1425 let errorType
: ErrorType
;
1426 let errorMessage
: string;
1427 let errorDetails
: JsonType
;
1428 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1429 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1430 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1431 let requestPayload
: JsonType
;
1432 let cachedRequest
: CachedRequest
;
1435 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1436 if (Array.isArray(request
) === true) {
1437 [messageType
, messageId
] = request
;
1438 // Check the type of message
1439 switch (messageType
) {
1441 case MessageType
.CALL_MESSAGE
:
1442 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1443 if (this.getEnableStatistics()) {
1444 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1447 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1451 // Process the message
1452 await this.ocppIncomingRequestService
.incomingRequestHandler(
1460 case MessageType
.CALL_RESULT_MESSAGE
:
1461 [, , commandPayload
] = request
as Response
;
1462 if (!this.requests
.has(messageId
)) {
1464 throw new OCPPError(
1465 ErrorType
.INTERNAL_ERROR
,
1466 `Response for unknown message id ${messageId}`,
1472 cachedRequest
= this.requests
.get(messageId
);
1473 if (Array.isArray(cachedRequest
) === true) {
1474 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1476 throw new OCPPError(
1477 ErrorType
.PROTOCOL_ERROR
,
1478 `Cached request for message id ${messageId} response is not an array`,
1480 cachedRequest
as unknown
as JsonType
1484 `${this.logPrefix()} << Command '${
1485 requestCommandName ?? 'unknown'
1486 }' received response payload: ${JSON.stringify(request)}`
1488 responseCallback(commandPayload
, requestPayload
);
1491 case MessageType
.CALL_ERROR_MESSAGE
:
1492 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1493 if (!this.requests
.has(messageId
)) {
1495 throw new OCPPError(
1496 ErrorType
.INTERNAL_ERROR
,
1497 `Error response for unknown message id ${messageId}`,
1499 { errorType
, errorMessage
, errorDetails
}
1502 cachedRequest
= this.requests
.get(messageId
);
1503 if (Array.isArray(cachedRequest
) === true) {
1504 [, errorCallback
, requestCommandName
] = cachedRequest
;
1506 throw new OCPPError(
1507 ErrorType
.PROTOCOL_ERROR
,
1508 `Cached request for message id ${messageId} error response is not an array`,
1510 cachedRequest
as unknown
as JsonType
1514 `${this.logPrefix()} << Command '${
1515 requestCommandName ?? 'unknown'
1516 }' received error payload: ${JSON.stringify(request)}`
1518 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1522 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1523 errMsg
= `Wrong message type ${messageType}`;
1524 logger
.error(`${this.logPrefix()} ${errMsg}`);
1525 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1527 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1529 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1536 `${this.logPrefix()} Incoming OCPP command '${
1537 commandName ?? requestCommandName ?? null
1538 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1539 this.requests.get(messageId)
1540 )}' processing error:`,
1543 if (!(error
instanceof OCPPError
)) {
1545 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1546 commandName ?? requestCommandName ?? null
1547 }' message '${data.toString()}' handling is not an OCPPError:`,
1552 messageType
=== MessageType
.CALL_MESSAGE
&&
1553 (await this.ocppRequestService
.sendError(
1557 commandName
?? requestCommandName
?? null
1562 private onPing(): void {
1563 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1566 private onPong(): void {
1567 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1570 private onError(error
: WSError
): void {
1571 this.closeWSConnection();
1572 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1575 private getEnergyActiveImportRegister(
1576 connectorStatus
: ConnectorStatus
,
1579 if (this.getMeteringPerTransaction()) {
1582 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1583 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1588 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1589 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1593 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1594 const localStationInfo
= stationInfo
?? this.stationInfo
;
1595 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1596 ? localStationInfo
.useConnectorId0
1600 private getNumberOfRunningTransactions(): number {
1602 for (const connectorId
of this.connectors
.keys()) {
1603 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1610 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1611 for (const connectorId
of this.connectors
.keys()) {
1612 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1613 await this.stopTransactionOnConnector(connectorId
, reason
);
1619 private getConnectionTimeout(): number | undefined {
1621 ChargingStationConfigurationUtils
.getConfigurationKey(
1623 StandardParametersKey
.ConnectionTimeOut
1628 ChargingStationConfigurationUtils
.getConfigurationKey(
1630 StandardParametersKey
.ConnectionTimeOut
1632 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1635 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1638 // -1 for unlimited, 0 for disabling
1639 private getAutoReconnectMaxRetries(): number | undefined {
1640 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1641 return this.stationInfo
.autoReconnectMaxRetries
;
1643 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1644 return Configuration
.getAutoReconnectMaxRetries();
1650 private getRegistrationMaxRetries(): number | undefined {
1651 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1652 return this.stationInfo
.registrationMaxRetries
;
1657 private getPowerDivider(): number {
1658 let powerDivider
= this.getNumberOfConnectors();
1659 if (this.stationInfo
?.powerSharedByConnectors
) {
1660 powerDivider
= this.getNumberOfRunningTransactions();
1662 return powerDivider
;
1665 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1666 const localStationInfo
= stationInfo
?? this.stationInfo
;
1667 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1670 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1671 const maximumPower
= this.getMaximumPower(stationInfo
);
1672 switch (this.getCurrentOutType(stationInfo
)) {
1673 case CurrentType
.AC
:
1674 return ACElectricUtils
.amperagePerPhaseFromPower(
1675 this.getNumberOfPhases(stationInfo
),
1676 maximumPower
/ this.getNumberOfConnectors(),
1677 this.getVoltageOut(stationInfo
)
1679 case CurrentType
.DC
:
1680 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1684 private getAmperageLimitation(): number | undefined {
1686 this.stationInfo
.amperageLimitationOcppKey
&&
1687 ChargingStationConfigurationUtils
.getConfigurationKey(
1689 this.stationInfo
.amperageLimitationOcppKey
1694 ChargingStationConfigurationUtils
.getConfigurationKey(
1696 this.stationInfo
.amperageLimitationOcppKey
1698 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1703 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1704 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1705 let chargingProfiles
: ChargingProfile
[] = [];
1706 // Get charging profiles for connector and sort by stack level
1707 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1708 (a
, b
) => b
.stackLevel
- a
.stackLevel
1710 // Get profiles on connector 0
1711 if (this.getConnectorStatus(0).chargingProfiles
) {
1712 chargingProfiles
.push(
1713 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1716 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1717 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1721 if (!Utils
.isNullOrUndefined(result
)) {
1722 limit
= result
.limit
;
1723 matchingChargingProfile
= result
.matchingChargingProfile
;
1724 switch (this.getCurrentOutType()) {
1725 case CurrentType
.AC
:
1727 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1728 ChargingRateUnitType
.WATT
1730 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1732 case CurrentType
.DC
:
1734 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1735 ChargingRateUnitType
.WATT
1737 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1739 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1740 if (limit
> connectorMaximumPower
) {
1742 `${this.logPrefix()} Charging profile id ${
1743 matchingChargingProfile.chargingProfileId
1744 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1745 this.getConnectorStatus(connectorId
).chargingProfiles
1747 limit
= connectorMaximumPower
;
1754 private async startMessageSequence(): Promise
<void> {
1755 if (this.stationInfo
?.autoRegister
) {
1756 await this.ocppRequestService
.requestHandler
<
1757 BootNotificationRequest
,
1758 BootNotificationResponse
1761 RequestCommand
.BOOT_NOTIFICATION
,
1763 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1764 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1765 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1766 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1767 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1768 iccid
: this.bootNotificationRequest
.iccid
,
1769 imsi
: this.bootNotificationRequest
.imsi
,
1770 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1771 meterType
: this.bootNotificationRequest
.meterType
,
1773 { skipBufferingOnError
: true }
1776 // Start WebSocket ping
1777 this.startWebSocketPing();
1779 this.startHeartbeat();
1780 // Initialize connectors status
1781 for (const connectorId
of this.connectors
.keys()) {
1782 if (connectorId
=== 0) {
1785 this.started
=== true &&
1786 !this.getConnectorStatus(connectorId
)?.status &&
1787 this.getConnectorStatus(connectorId
)?.bootStatus
1789 // Send status in template at startup
1790 await this.ocppRequestService
.requestHandler
<
1791 StatusNotificationRequest
,
1792 StatusNotificationResponse
1793 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1795 status: this.getConnectorStatus(connectorId
).bootStatus
,
1796 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1798 this.getConnectorStatus(connectorId
).status =
1799 this.getConnectorStatus(connectorId
).bootStatus
;
1801 this.started
=== false &&
1802 this.getConnectorStatus(connectorId
)?.status &&
1803 this.getConnectorStatus(connectorId
)?.bootStatus
1805 // Send status in template after reset
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
;
1816 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1817 // Send previous status at template reload
1818 await this.ocppRequestService
.requestHandler
<
1819 StatusNotificationRequest
,
1820 StatusNotificationResponse
1821 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1823 status: this.getConnectorStatus(connectorId
).status,
1824 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1827 // Send default status
1828 await this.ocppRequestService
.requestHandler
<
1829 StatusNotificationRequest
,
1830 StatusNotificationResponse
1831 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1833 status: ChargePointStatus
.AVAILABLE
,
1834 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1836 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1840 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1841 this.startAutomaticTransactionGenerator();
1845 private async stopMessageSequence(
1846 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1848 // Stop WebSocket ping
1849 this.stopWebSocketPing();
1851 this.stopHeartbeat();
1852 // Stop ongoing transactions
1853 if (this.automaticTransactionGenerator
?.started
=== true) {
1854 this.stopAutomaticTransactionGenerator();
1856 await this.stopRunningTransactions(reason
);
1860 private startWebSocketPing(): void {
1861 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1863 StandardParametersKey
.WebSocketPingInterval
1865 ? Utils
.convertToInt(
1866 ChargingStationConfigurationUtils
.getConfigurationKey(
1868 StandardParametersKey
.WebSocketPingInterval
1872 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1873 this.webSocketPingSetInterval
= setInterval(() => {
1874 if (this.isWebSocketConnectionOpened()) {
1875 this.wsConnection
.ping((): void => {
1876 /* This is intentional */
1879 }, webSocketPingInterval
* 1000);
1882 ' WebSocket ping started every ' +
1883 Utils
.formatDurationSeconds(webSocketPingInterval
)
1885 } else if (this.webSocketPingSetInterval
) {
1888 ' WebSocket ping every ' +
1889 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1894 `${this.logPrefix()} WebSocket ping interval set to ${
1895 webSocketPingInterval
1896 ? Utils.formatDurationSeconds(webSocketPingInterval)
1897 : webSocketPingInterval
1898 }, not starting the WebSocket ping`
1903 private stopWebSocketPing(): void {
1904 if (this.webSocketPingSetInterval
) {
1905 clearInterval(this.webSocketPingSetInterval
);
1909 private getConfiguredSupervisionUrl(): URL
{
1910 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1911 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1913 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1915 switch (Configuration
.getSupervisionUrlDistribution()) {
1916 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1917 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1919 case SupervisionUrlDistribution
.RANDOM
:
1921 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1923 case SupervisionUrlDistribution
.SEQUENTIAL
:
1924 if (this.index
<= supervisionUrls
.length
) {
1925 urlIndex
= this.index
- 1;
1928 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1934 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1935 SupervisionUrlDistribution.ROUND_ROBIN
1938 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1941 return new URL(supervisionUrls
[urlIndex
]);
1943 return new URL(supervisionUrls
as string);
1946 private getHeartbeatInterval(): number | undefined {
1947 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1949 StandardParametersKey
.HeartbeatInterval
1951 if (HeartbeatInterval
) {
1952 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1954 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1956 StandardParametersKey
.HeartBeatInterval
1958 if (HeartBeatInterval
) {
1959 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1961 !this.stationInfo
?.autoRegister
&&
1963 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1964 Constants.DEFAULT_HEARTBEAT_INTERVAL
1967 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1970 private stopHeartbeat(): void {
1971 if (this.heartbeatSetInterval
) {
1972 clearInterval(this.heartbeatSetInterval
);
1976 private terminateWSConnection(): void {
1977 if (this.isWebSocketConnectionOpened()) {
1978 this.wsConnection
.terminate();
1979 this.wsConnection
= null;
1983 private stopMeterValues(connectorId
: number) {
1984 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1985 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1989 private getReconnectExponentialDelay(): boolean | undefined {
1990 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1991 ? this.stationInfo
.reconnectExponentialDelay
1995 private async reconnect(code
: number): Promise
<void> {
1996 // Stop WebSocket ping
1997 this.stopWebSocketPing();
1999 this.stopHeartbeat();
2000 // Stop the ATG if needed
2001 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2002 this.stopAutomaticTransactionGenerator();
2005 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2006 this.getAutoReconnectMaxRetries() === -1
2008 this.autoReconnectRetryCount
++;
2009 const reconnectDelay
= this.getReconnectExponentialDelay()
2010 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2011 : this.getConnectionTimeout() * 1000;
2012 const reconnectDelayWithdraw
= 1000;
2013 const reconnectTimeout
=
2014 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2015 ? reconnectDelay
- reconnectDelayWithdraw
2018 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2021 )}ms, timeout ${reconnectTimeout}ms`
2023 await Utils
.sleep(reconnectDelay
);
2026 ' WebSocket: reconnecting try #' +
2027 this.autoReconnectRetryCount
.toString()
2029 this.openWSConnection(
2030 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2031 { closeOpened
: true }
2033 this.wsConnectionRestarted
= true;
2034 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2036 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2037 this.autoReconnectRetryCount
2038 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2043 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2044 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2047 private initializeConnectorStatus(connectorId
: number): void {
2048 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2049 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2050 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2051 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2052 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2053 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;