1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
6 BootNotificationRequest
,
10 IncomingRequestCommand
,
13 StatusNotificationRequest
,
14 } from
'../types/ocpp/Requests';
16 BootNotificationResponse
,
22 StatusNotificationResponse
,
23 } from
'../types/ocpp/Responses';
24 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
25 import ChargingStationConfiguration
, { Section
} from
'../types/ChargingStationConfiguration';
26 import ChargingStationTemplate
, {
31 } from
'../types/ChargingStationTemplate';
33 ConnectorPhaseRotation
,
34 StandardParametersKey
,
35 SupportedFeatureProfiles
,
36 VendorDefaultParametersKey
,
37 } from
'../types/ocpp/Configuration';
38 import { MeterValue
, MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
40 StopTransactionReason
,
41 StopTransactionRequest
,
42 StopTransactionResponse
,
43 } from
'../types/ocpp/Transaction';
44 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
45 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
47 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
48 import BaseError from
'../exception/BaseError';
49 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
50 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
51 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
52 import ChargingStationInfo from
'../types/ChargingStationInfo';
53 import ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
54 import { ChargingStationUtils
} from
'./ChargingStationUtils';
55 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
56 import Configuration from
'../utils/Configuration';
57 import { ConnectorStatus
} from
'../types/ConnectorStatus';
58 import Constants from
'../utils/Constants';
59 import { ErrorType
} from
'../types/ocpp/ErrorType';
60 import { FileType
} from
'../types/FileType';
61 import FileUtils from
'../utils/FileUtils';
62 import { JsonType
} from
'../types/JsonType';
63 import { MessageType
} from
'../types/ocpp/MessageType';
64 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
65 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
66 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
67 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
68 import OCPPError from
'../exception/OCPPError';
69 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
70 import OCPPRequestService from
'./ocpp/OCPPRequestService';
71 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
72 import PerformanceStatistics from
'../performance/PerformanceStatistics';
73 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
74 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
75 import { URL
} from
'url';
76 import Utils from
'../utils/Utils';
77 import crypto from
'crypto';
79 import logger from
'../utils/Logger';
80 import { parentPort
} from
'worker_threads';
81 import path from
'path';
83 export default class ChargingStation
{
84 public hashId
!: string;
85 public readonly templateFile
: string;
86 public authorizedTags
: string[];
87 public stationInfo
!: ChargingStationInfo
;
88 public readonly connectors
: Map
<number, ConnectorStatus
>;
89 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
90 public wsConnection
!: WebSocket
;
91 public readonly requests
: Map
<string, CachedRequest
>;
92 public performanceStatistics
!: PerformanceStatistics
;
93 public heartbeatSetInterval
!: NodeJS
.Timeout
;
94 public ocppRequestService
!: OCPPRequestService
;
95 public bootNotificationResponse
!: BootNotificationResponse
| null;
96 private readonly index
: number;
97 private configurationFile
!: string;
98 private bootNotificationRequest
!: BootNotificationRequest
;
99 private connectorsConfigurationHash
!: string;
100 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
101 private readonly messageBuffer
: Set
<string>;
102 private wsConfiguredConnectionUrl
!: URL
;
103 private wsConnectionRestarted
: boolean;
104 private stopped
: boolean;
105 private autoReconnectRetryCount
: number;
106 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
107 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
109 constructor(index
: number, templateFile
: string) {
111 this.templateFile
= templateFile
;
112 this.stopped
= false;
113 this.wsConnectionRestarted
= false;
114 this.autoReconnectRetryCount
= 0;
115 this.connectors
= new Map
<number, ConnectorStatus
>();
116 this.requests
= new Map
<string, CachedRequest
>();
117 this.messageBuffer
= new Set
<string>();
119 this.authorizedTags
= this.getAuthorizedTags();
122 private get
wsConnectionUrl(): URL
{
123 return this.getSupervisionUrlOcppConfiguration()
125 ChargingStationConfigurationUtils
.getConfigurationKey(
127 this.getSupervisionUrlOcppKey()
130 this.stationInfo
.chargingStationId
132 : this.wsConfiguredConnectionUrl
;
135 public logPrefix(): string {
136 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
139 public getBootNotificationRequest(): BootNotificationRequest
{
140 return this.bootNotificationRequest
;
143 public getRandomIdTag(): string {
144 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
145 return this.authorizedTags
[index
];
148 public hasAuthorizedTags(): boolean {
149 return !Utils
.isEmptyArray(this.authorizedTags
);
152 public getEnableStatistics(): boolean | undefined {
153 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
154 ? this.stationInfo
.enableStatistics
158 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
159 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
162 public getNumberOfPhases(): number | undefined {
163 switch (this.getCurrentOutType()) {
165 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
166 ? this.stationInfo
.numberOfPhases
173 public isWebSocketConnectionOpened(): boolean {
174 return this?.wsConnection
?.readyState
=== OPEN
;
177 public getRegistrationStatus(): RegistrationStatus
{
178 return this?.bootNotificationResponse
?.status;
181 public isInUnknownState(): boolean {
182 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
185 public isInPendingState(): boolean {
186 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
189 public isInAcceptedState(): boolean {
190 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
193 public isInRejectedState(): boolean {
194 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
197 public isRegistered(): boolean {
198 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
201 public isChargingStationAvailable(): boolean {
202 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
205 public isConnectorAvailable(id
: number): boolean {
206 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
209 public getNumberOfConnectors(): number {
210 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
213 public getConnectorStatus(id
: number): ConnectorStatus
{
214 return this.connectors
.get(id
);
217 public getCurrentOutType(): CurrentType
| undefined {
218 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
221 public getOcppStrictCompliance(): boolean {
222 return this.stationInfo
.ocppStrictCompliance
?? false;
225 public getVoltageOut(): number | undefined {
226 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
228 }, cannot define default voltage out`;
229 let defaultVoltageOut
: number;
230 switch (this.getCurrentOutType()) {
232 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
235 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
238 logger
.error(errMsg
);
239 throw new Error(errMsg
);
241 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
242 ? this.stationInfo
.voltageOut
246 public getConnectorMaximumAvailablePower(connectorId
: number): number {
247 let connectorAmperageLimitationPowerLimit
: number;
249 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
250 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
252 connectorAmperageLimitationPowerLimit
=
253 (this.getCurrentOutType() === CurrentType
.AC
254 ? ACElectricUtils
.powerTotal(
255 this.getNumberOfPhases(),
256 this.getVoltageOut(),
257 this.getAmperageLimitation() * this.getNumberOfConnectors()
259 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
260 this.stationInfo
.powerDivider
;
262 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
263 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
265 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
266 isNaN(connectorAmperageLimitationPowerLimit
)
268 : connectorAmperageLimitationPowerLimit
,
269 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
273 public getTransactionIdTag(transactionId
: number): string | undefined {
274 for (const connectorId
of this.connectors
.keys()) {
275 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
276 return this.getConnectorStatus(connectorId
).transactionIdTag
;
281 public getOutOfOrderEndMeterValues(): boolean {
282 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
285 public getBeginEndMeterValues(): boolean {
286 return this.stationInfo
.beginEndMeterValues
?? false;
289 public getMeteringPerTransaction(): boolean {
290 return this.stationInfo
.meteringPerTransaction
?? true;
293 public getTransactionDataMeterValues(): boolean {
294 return this.stationInfo
.transactionDataMeterValues
?? false;
297 public getMainVoltageMeterValues(): boolean {
298 return this.stationInfo
.mainVoltageMeterValues
?? true;
301 public getPhaseLineToLineVoltageMeterValues(): boolean {
302 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
305 public getCustomValueLimitationMeterValues(): boolean {
306 return this.stationInfo
.customValueLimitationMeterValues
?? true;
309 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
310 for (const connectorId
of this.connectors
.keys()) {
313 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
320 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
321 const transactionConnectorStatus
= this.getConnectorStatus(
322 this.getConnectorIdByTransactionId(transactionId
)
324 if (this.getMeteringPerTransaction()) {
325 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
327 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
330 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
331 const connectorStatus
= this.getConnectorStatus(connectorId
);
332 if (this.getMeteringPerTransaction()) {
333 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
335 return connectorStatus
?.energyActiveImportRegisterValue
;
338 public getAuthorizeRemoteTxRequests(): boolean {
339 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
341 StandardParametersKey
.AuthorizeRemoteTxRequests
343 return authorizeRemoteTxRequests
344 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
348 public getLocalAuthListEnabled(): boolean {
349 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
351 StandardParametersKey
.LocalAuthListEnabled
353 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
356 public getSampledValueTemplate(
358 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
359 phase
?: MeterValuePhase
360 ): SampledValueTemplate
| undefined {
361 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
362 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
364 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
369 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
370 !ChargingStationConfigurationUtils
.getConfigurationKey(
372 StandardParametersKey
.MeterValuesSampledData
373 )?.value
.includes(measurand
)
376 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
377 StandardParametersKey.MeterValuesSampledData
382 const sampledValueTemplates
: SampledValueTemplate
[] =
383 this.getConnectorStatus(connectorId
).MeterValues
;
386 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
390 !Constants
.SUPPORTED_MEASURANDS
.includes(
391 sampledValueTemplates
[index
]?.measurand
??
392 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
396 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
400 sampledValueTemplates
[index
]?.phase
=== phase
&&
401 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
402 ChargingStationConfigurationUtils
.getConfigurationKey(
404 StandardParametersKey
.MeterValuesSampledData
405 )?.value
.includes(measurand
)
407 return sampledValueTemplates
[index
];
410 !sampledValueTemplates
[index
].phase
&&
411 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
412 ChargingStationConfigurationUtils
.getConfigurationKey(
414 StandardParametersKey
.MeterValuesSampledData
415 )?.value
.includes(measurand
)
417 return sampledValueTemplates
[index
];
419 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
420 (!sampledValueTemplates
[index
].measurand
||
421 sampledValueTemplates
[index
].measurand
=== measurand
)
423 return sampledValueTemplates
[index
];
426 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
427 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
428 logger
.error(errorMsg
);
429 throw new Error(errorMsg
);
432 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
436 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
437 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
440 public startHeartbeat(): void {
442 this.getHeartbeatInterval() &&
443 this.getHeartbeatInterval() > 0 &&
444 !this.heartbeatSetInterval
446 // eslint-disable-next-line @typescript-eslint/no-misused-promises
447 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
448 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
450 RequestCommand
.HEARTBEAT
452 }, this.getHeartbeatInterval());
455 ' Heartbeat started every ' +
456 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
458 } else if (this.heartbeatSetInterval
) {
461 ' Heartbeat already started every ' +
462 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
466 `${this.logPrefix()} Heartbeat interval set to ${
467 this.getHeartbeatInterval()
468 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
469 : this.getHeartbeatInterval()
470 }, not starting the heartbeat`
475 public restartHeartbeat(): void {
477 this.stopHeartbeat();
479 this.startHeartbeat();
482 public restartWebSocketPing(): void {
483 // Stop WebSocket ping
484 this.stopWebSocketPing();
485 // Start WebSocket ping
486 this.startWebSocketPing();
489 public startMeterValues(connectorId
: number, interval
: number): void {
490 if (connectorId
=== 0) {
492 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
496 if (!this.getConnectorStatus(connectorId
)) {
498 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
502 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
504 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
508 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
509 !this.getConnectorStatus(connectorId
)?.transactionId
512 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
517 // eslint-disable-next-line @typescript-eslint/no-misused-promises
518 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
519 // eslint-disable-next-line @typescript-eslint/no-misused-promises
520 async (): Promise
<void> => {
521 // FIXME: Implement OCPP version agnostic helpers
522 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
525 this.getConnectorStatus(connectorId
).transactionId
,
528 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
530 RequestCommand
.METER_VALUES
,
533 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
534 meterValue
: [meterValue
],
542 `${this.logPrefix()} Charging station ${
543 StandardParametersKey.MeterValueSampleInterval
544 } configuration set to ${
545 interval ? Utils.formatDurationMilliSeconds(interval) : interval
546 }, not sending MeterValues`
551 public start(): void {
552 if (this.getEnableStatistics()) {
553 this.performanceStatistics
.start();
555 this.openWSConnection();
556 // Handle WebSocket message
557 this.wsConnection
.on(
559 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
561 // Handle WebSocket error
562 this.wsConnection
.on(
564 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
566 // Handle WebSocket close
567 this.wsConnection
.on(
569 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
571 // Handle WebSocket open
572 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
573 // Handle WebSocket ping
574 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
575 // Handle WebSocket pong
576 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
577 // Monitor authorization file
578 FileUtils
.watchJsonFile
<string[]>(
580 FileType
.Authorization
,
581 this.getAuthorizationFile(),
584 // Monitor charging station template file
585 FileUtils
.watchJsonFile(
587 FileType
.ChargingStationTemplate
,
590 (event
, filename
): void => {
591 if (filename
&& event
=== 'change') {
594 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
596 } file have changed, reload`
602 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
603 this.automaticTransactionGenerator
605 this.automaticTransactionGenerator
.stop();
607 this.startAutomaticTransactionGenerator();
608 if (this.getEnableStatistics()) {
609 this.performanceStatistics
.restart();
611 this.performanceStatistics
.stop();
613 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
616 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
623 parentPort
.postMessage({
624 id
: ChargingStationWorkerMessageEvents
.STARTED
,
625 data
: { id
: this.stationInfo
.chargingStationId
},
629 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
630 // Stop message sequence
631 await this.stopMessageSequence(reason
);
632 for (const connectorId
of this.connectors
.keys()) {
633 if (connectorId
> 0) {
634 await this.ocppRequestService
.requestHandler
<
635 StatusNotificationRequest
,
636 StatusNotificationResponse
637 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
639 status: ChargePointStatus
.UNAVAILABLE
,
640 errorCode
: ChargePointErrorCode
.NO_ERROR
,
642 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
645 if (this.isWebSocketConnectionOpened()) {
646 this.wsConnection
.close();
648 if (this.getEnableStatistics()) {
649 this.performanceStatistics
.stop();
651 this.bootNotificationResponse
= null;
652 parentPort
.postMessage({
653 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
654 data
: { id
: this.stationInfo
.chargingStationId
},
659 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
660 await this.stop(reason
);
661 await Utils
.sleep(this.stationInfo
.resetTime
);
662 this.stationInfo
= this.getStationInfo();
663 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
667 public saveOcppConfiguration(): void {
668 if (this.getOcppPersistentConfiguration()) {
669 this.saveConfiguration(Section
.ocppConfiguration
);
673 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
674 let limit
: number, matchingChargingProfile
: ChargingProfile
;
675 let chargingProfiles
: ChargingProfile
[] = [];
676 // Get charging profiles for connector and sort by stack level
677 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
678 (a
, b
) => b
.stackLevel
- a
.stackLevel
680 // Get profiles on connector 0
681 if (this.getConnectorStatus(0).chargingProfiles
) {
682 chargingProfiles
.push(
683 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
686 if (!Utils
.isEmptyArray(chargingProfiles
)) {
687 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
691 if (!Utils
.isNullOrUndefined(result
)) {
692 limit
= result
.limit
;
693 matchingChargingProfile
= result
.matchingChargingProfile
;
694 switch (this.getCurrentOutType()) {
697 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
698 ChargingRateUnitType
.WATT
700 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
704 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
705 ChargingRateUnitType
.WATT
707 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
710 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
711 if (limit
> connectorMaximumPower
) {
713 `${this.logPrefix()} Charging profile id ${
714 matchingChargingProfile.chargingProfileId
715 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
716 this.getConnectorStatus(connectorId
).chargingProfiles
718 limit
= connectorMaximumPower
;
725 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
726 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
728 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
730 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
732 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
734 `${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`
736 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
738 let cpReplaced
= false;
739 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
740 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
741 (chargingProfile
: ChargingProfile
, index
: number) => {
743 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
744 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
745 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
747 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
753 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
756 public resetConnectorStatus(connectorId
: number): void {
757 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
758 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
759 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
760 this.getConnectorStatus(connectorId
).transactionStarted
= false;
761 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
762 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
763 delete this.getConnectorStatus(connectorId
).transactionId
;
764 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
765 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
766 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
767 this.stopMeterValues(connectorId
);
770 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
771 return ChargingStationConfigurationUtils
.getConfigurationKey(
773 StandardParametersKey
.SupportedFeatureProfiles
774 )?.value
.includes(featureProfile
);
777 public bufferMessage(message
: string): void {
778 this.messageBuffer
.add(message
);
781 private flushMessageBuffer() {
782 if (this.messageBuffer
.size
> 0) {
783 this.messageBuffer
.forEach((message
) => {
784 // TODO: evaluate the need to track performance
785 this.wsConnection
.send(message
);
786 this.messageBuffer
.delete(message
);
791 private getSupervisionUrlOcppConfiguration(): boolean {
792 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
795 private getSupervisionUrlOcppKey(): string {
796 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
799 private getTemplateFromFile(): ChargingStationTemplate
| null {
800 let template
: ChargingStationTemplate
= null;
802 const measureId
= `${FileType.ChargingStationTemplate} read`;
803 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
805 (JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
) ??
806 ({} as ChargingStationTemplate
);
807 PerformanceStatistics
.endMeasure(measureId
, beginId
);
808 template
.templateHash
= crypto
809 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
810 .update(JSON
.stringify(template
))
813 FileUtils
.handleFileException(
815 FileType
.ChargingStationTemplate
,
817 error
as NodeJS
.ErrnoException
823 private getStationInfoFromTemplate(): ChargingStationInfo
{
824 const stationInfo
: ChargingStationInfo
= this.getTemplateFromFile();
825 if (Utils
.isNullOrUndefined(stationInfo
)) {
826 const logMsg
= 'Failed to read charging station template file';
827 logger
.error(`${this.logPrefix()} ${logMsg}`);
828 throw new BaseError(logMsg
);
830 if (Utils
.isEmptyObject(stationInfo
)) {
832 `${this.logPrefix()} Empty charging station information from template file ${
837 const chargingStationId
= ChargingStationUtils
.getChargingStationId(this.index
, stationInfo
);
838 // Deprecation template keys section
839 ChargingStationUtils
.warnDeprecatedTemplateKey(
844 "Use 'supervisionUrls' instead"
846 ChargingStationUtils
.convertDeprecatedTemplateKey(
851 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
852 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
853 stationInfo
.power
= stationInfo
.power
as number[];
854 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
855 stationInfo
.maximumPower
=
856 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
857 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
858 : stationInfo
.power
[powerArrayRandomIndex
];
860 stationInfo
.power
= stationInfo
.power
as number;
861 stationInfo
.maximumPower
=
862 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
863 ? stationInfo
.power
* 1000
866 delete stationInfo
.power
;
867 delete stationInfo
.powerUnit
;
868 stationInfo
.chargingStationId
= chargingStationId
;
869 stationInfo
.resetTime
= stationInfo
.resetTime
870 ? stationInfo
.resetTime
* 1000
871 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
875 private getStationInfoFromFile(): ChargingStationInfo
{
876 let stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? ({} as ChargingStationInfo
);
877 stationInfo
= ChargingStationUtils
.createStationInfoHash(stationInfo
);
881 private getStationInfo(): ChargingStationInfo
{
882 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
883 this.hashId
= ChargingStationUtils
.getHashId(stationInfoFromTemplate
);
884 this.configurationFile
= path
.join(
885 path
.resolve(__dirname
, '../'),
888 this.hashId
+ '.json'
890 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
891 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
892 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
893 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
894 return this.stationInfo
;
896 return stationInfoFromFile
;
898 ChargingStationUtils
.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
899 return stationInfoFromTemplate
;
902 private saveStationInfo(): void {
903 this.saveConfiguration(Section
.stationInfo
);
906 private getOcppVersion(): OCPPVersion
{
907 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
910 private getOcppPersistentConfiguration(): boolean {
911 return this.stationInfo
.ocppPersistentConfiguration
?? true;
914 private handleUnsupportedVersion(version
: OCPPVersion
) {
915 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
918 logger
.error(errMsg
);
919 throw new Error(errMsg
);
922 private initialize(): void {
923 this.stationInfo
= this.getStationInfo();
924 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
925 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
928 this.ocppConfiguration
= this.getOcppConfiguration();
929 this.stationInfo
?.Configuration
&& delete this.stationInfo
.Configuration
;
930 this.wsConfiguredConnectionUrl
= new URL(
931 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
933 // Build connectors if needed
934 const maxConnectors
= this.getMaxNumberOfConnectors();
935 this.checkMaxConnectors(maxConnectors
);
936 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
937 this.checkTemplateMaxConnectors(templateMaxConnectors
);
940 (this.stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
941 !this.stationInfo
.randomConnectors
944 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
946 }, forcing random connector configurations affectation`
948 this.stationInfo
.randomConnectors
= true;
950 this.initializeConnectors(this.stationInfo
, maxConnectors
, templateMaxConnectors
);
951 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
952 this.stationInfo
= ChargingStationUtils
.createStationInfoHash(this.stationInfo
);
953 this.saveStationInfo();
954 // Avoid duplication of connectors related information in RAM
955 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
956 // OCPP configuration
957 this.initializeOcppConfiguration();
958 if (this.getEnableStatistics()) {
959 this.performanceStatistics
= PerformanceStatistics
.getInstance(
961 this.stationInfo
.chargingStationId
,
965 switch (this.getOcppVersion()) {
966 case OCPPVersion
.VERSION_16
:
967 this.ocppIncomingRequestService
=
968 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
969 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
970 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
974 this.handleUnsupportedVersion(this.getOcppVersion());
977 if (this.stationInfo
.autoRegister
) {
978 this.bootNotificationResponse
= {
979 currentTime
: new Date().toISOString(),
980 interval
: this.getHeartbeatInterval() / 1000,
981 status: RegistrationStatus
.ACCEPTED
,
984 this.stationInfo
.powerDivider
= this.getPowerDivider();
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.getConfiguredSupervisionUrl().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 maxConnectors
: number,
1152 templateMaxConnectors
: number
1154 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1155 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1157 } with no connectors configuration defined`;
1158 logger
.error(logMsg
);
1159 throw new BaseError(logMsg
);
1161 if (!stationInfo
?.Connectors
[0]) {
1163 `${this.logPrefix()} Charging station information from template ${
1165 } with no connector Id 0 configuration`
1168 if (stationInfo
?.Connectors
) {
1169 const connectorsConfigHash
= crypto
1170 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1171 .update(JSON
.stringify(stationInfo
?.Connectors
) + maxConnectors
.toString())
1173 const connectorsConfigChanged
=
1174 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1175 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1176 connectorsConfigChanged
&& this.connectors
.clear();
1177 this.connectorsConfigurationHash
= connectorsConfigHash
;
1178 // Add connector Id 0
1179 let lastConnector
= '0';
1180 for (lastConnector
in stationInfo
?.Connectors
) {
1181 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1183 lastConnectorId
=== 0 &&
1184 this.getUseConnectorId0() &&
1185 stationInfo
?.Connectors
[lastConnector
]
1187 this.connectors
.set(
1189 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1191 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1192 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1193 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1197 // Generate all connectors
1198 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1199 for (let index
= 1; index
<= maxConnectors
; index
++) {
1200 const randConnectorId
= stationInfo
.randomConnectors
1201 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1203 this.connectors
.set(
1205 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1207 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1208 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1209 this.getConnectorStatus(index
).chargingProfiles
= [];
1216 `${this.logPrefix()} Charging station information from template ${
1218 } with no connectors configuration defined, using already defined connectors`
1221 // Initialize transaction attributes on connectors
1222 for (const connectorId
of this.connectors
.keys()) {
1223 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1224 this.initializeConnectorStatus(connectorId
);
1229 private checkMaxConnectors(maxConnectors
: number): void {
1230 if (maxConnectors
<= 0) {
1232 `${this.logPrefix()} Charging station information from template ${
1234 } with ${maxConnectors} connectors`
1239 private checkTemplateMaxConnectors(templateMaxConnectors
: number): void {
1240 if (templateMaxConnectors
=== 0) {
1242 `${this.logPrefix()} Charging station information from template ${
1244 } with empty connectors configuration`
1246 } else if (templateMaxConnectors
< 0) {
1248 `${this.logPrefix()} Charging station information from template ${
1250 } with no connectors configuration defined`
1255 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1256 let configuration
: ChargingStationConfiguration
= null;
1257 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1259 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1260 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1261 configuration
= JSON
.parse(
1262 fs
.readFileSync(this.configurationFile
, 'utf8')
1263 ) as ChargingStationConfiguration
;
1264 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1266 FileUtils
.handleFileException(
1268 FileType
.ChargingStationConfiguration
,
1269 this.configurationFile
,
1270 error
as NodeJS
.ErrnoException
1274 return configuration
;
1277 private saveConfiguration(section
?: Section
): void {
1278 if (this.configurationFile
) {
1280 const configurationData
: ChargingStationConfiguration
=
1281 this.getConfigurationFromFile() ?? {};
1282 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1283 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1286 case Section
.ocppConfiguration
:
1287 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1289 case Section
.stationInfo
:
1290 if (configurationData
?.stationInfo
?.infoHash
=== this.stationInfo
?.infoHash
) {
1292 `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${
1293 this.configurationFile
1298 configurationData
.stationInfo
= this.stationInfo
;
1301 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1302 if (configurationData
?.stationInfo
?.infoHash
!== this.stationInfo
?.infoHash
) {
1303 configurationData
.stationInfo
= this.stationInfo
;
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
);
1314 FileUtils
.handleFileException(
1316 FileType
.ChargingStationConfiguration
,
1317 this.configurationFile
,
1318 error
as NodeJS
.ErrnoException
1323 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1328 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1329 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1332 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1333 let configuration
: ChargingStationConfiguration
= null;
1334 if (this.getOcppPersistentConfiguration()) {
1335 const configurationFromFile
= this.getConfigurationFromFile();
1336 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1338 configuration
&& delete configuration
.stationInfo
;
1339 return configuration
;
1342 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1343 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1344 if (!ocppConfiguration
) {
1345 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1347 return ocppConfiguration
;
1350 private async onOpen(): Promise
<void> {
1351 if (this.isWebSocketConnectionOpened()) {
1353 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1355 if (!this.isRegistered()) {
1356 // Send BootNotification
1357 let registrationRetryCount
= 0;
1359 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1360 BootNotificationRequest
,
1361 BootNotificationResponse
1364 RequestCommand
.BOOT_NOTIFICATION
,
1366 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1367 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1368 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1369 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1370 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1371 iccid
: this.bootNotificationRequest
.iccid
,
1372 imsi
: this.bootNotificationRequest
.imsi
,
1373 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1374 meterType
: this.bootNotificationRequest
.meterType
,
1376 { skipBufferingOnError
: true }
1378 if (!this.isRegistered()) {
1379 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1381 this.bootNotificationResponse
?.interval
1382 ? this.bootNotificationResponse
.interval
* 1000
1383 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1387 !this.isRegistered() &&
1388 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1389 this.getRegistrationMaxRetries() === -1)
1392 if (this.isRegistered()) {
1393 if (this.isInAcceptedState()) {
1394 await this.startMessageSequence();
1395 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1399 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1402 this.stopped
&& (this.stopped
= false);
1403 this.autoReconnectRetryCount
= 0;
1404 this.wsConnectionRestarted
= false;
1407 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1412 private async onClose(code
: number, reason
: string): Promise
<void> {
1415 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1416 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1418 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1420 )}' and reason '${reason}'`
1422 this.autoReconnectRetryCount
= 0;
1427 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1429 )}' and reason '${reason}'`
1431 await this.reconnect(code
);
1436 private async onMessage(data
: Data
): Promise
<void> {
1437 let messageType
: number;
1438 let messageId
: string;
1439 let commandName
: IncomingRequestCommand
;
1440 let commandPayload
: JsonType
;
1441 let errorType
: ErrorType
;
1442 let errorMessage
: string;
1443 let errorDetails
: JsonType
;
1444 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1445 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1446 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1447 let requestPayload
: JsonType
;
1448 let cachedRequest
: CachedRequest
;
1451 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1452 if (Utils
.isIterable(request
)) {
1453 [messageType
, messageId
] = request
;
1454 // Check the type of message
1455 switch (messageType
) {
1457 case MessageType
.CALL_MESSAGE
:
1458 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1459 if (this.getEnableStatistics()) {
1460 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1463 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1467 // Process the message
1468 await this.ocppIncomingRequestService
.incomingRequestHandler(
1476 case MessageType
.CALL_RESULT_MESSAGE
:
1477 [, , commandPayload
] = request
as Response
;
1478 if (!this.requests
.has(messageId
)) {
1480 throw new OCPPError(
1481 ErrorType
.INTERNAL_ERROR
,
1482 `Response for unknown message id ${messageId}`,
1488 cachedRequest
= this.requests
.get(messageId
);
1489 if (Utils
.isIterable(cachedRequest
)) {
1490 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1492 throw new OCPPError(
1493 ErrorType
.PROTOCOL_ERROR
,
1494 `Cached request for message id ${messageId} response is not iterable`,
1496 cachedRequest
as unknown
as JsonType
1500 `${this.logPrefix()} << Command '${
1501 requestCommandName ?? ''
1502 }' received response payload: ${JSON.stringify(request)}`
1504 responseCallback(commandPayload
, requestPayload
);
1507 case MessageType
.CALL_ERROR_MESSAGE
:
1508 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1509 if (!this.requests
.has(messageId
)) {
1511 throw new OCPPError(
1512 ErrorType
.INTERNAL_ERROR
,
1513 `Error response for unknown message id ${messageId}`,
1515 { errorType
, errorMessage
, errorDetails
}
1518 cachedRequest
= this.requests
.get(messageId
);
1519 if (Utils
.isIterable(cachedRequest
)) {
1520 [, errorCallback
, requestCommandName
] = cachedRequest
;
1522 throw new OCPPError(
1523 ErrorType
.PROTOCOL_ERROR
,
1524 `Cached request for message id ${messageId} error response is not iterable`,
1526 cachedRequest
as unknown
as JsonType
1530 `${this.logPrefix()} << Command '${
1531 requestCommandName ?? ''
1532 }' received error payload: ${JSON.stringify(request)}`
1534 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1538 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1539 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1540 logger
.error(errMsg
);
1541 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1544 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1551 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1554 this.requests
.get(messageId
),
1558 messageType
=== MessageType
.CALL_MESSAGE
&&
1559 (await this.ocppRequestService
.sendError(
1563 commandName
?? requestCommandName
?? null
1568 private onPing(): void {
1569 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1572 private onPong(): void {
1573 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1576 private onError(error
: WSError
): void {
1577 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1580 private getAuthorizationFile(): string | undefined {
1582 this.stationInfo
.authorizationFile
&&
1584 path
.resolve(__dirname
, '../'),
1586 path
.basename(this.stationInfo
.authorizationFile
)
1591 private getAuthorizedTags(): string[] {
1592 let authorizedTags
: string[] = [];
1593 const authorizationFile
= this.getAuthorizationFile();
1594 if (authorizationFile
) {
1596 // Load authorization file
1597 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1599 FileUtils
.handleFileException(
1601 FileType
.Authorization
,
1603 error
as NodeJS
.ErrnoException
1608 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1611 return authorizedTags
;
1614 private getUseConnectorId0(): boolean | undefined {
1615 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1616 ? this.stationInfo
.useConnectorId0
1620 private getNumberOfRunningTransactions(): number {
1622 for (const connectorId
of this.connectors
.keys()) {
1623 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1631 private getConnectionTimeout(): number | undefined {
1633 ChargingStationConfigurationUtils
.getConfigurationKey(
1635 StandardParametersKey
.ConnectionTimeOut
1640 ChargingStationConfigurationUtils
.getConfigurationKey(
1642 StandardParametersKey
.ConnectionTimeOut
1644 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1647 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1650 // -1 for unlimited, 0 for disabling
1651 private getAutoReconnectMaxRetries(): number | undefined {
1652 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1653 return this.stationInfo
.autoReconnectMaxRetries
;
1655 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1656 return Configuration
.getAutoReconnectMaxRetries();
1662 private getRegistrationMaxRetries(): number | undefined {
1663 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1664 return this.stationInfo
.registrationMaxRetries
;
1669 private getPowerDivider(): number {
1670 let powerDivider
= this.getNumberOfConnectors();
1671 if (this.stationInfo
.powerSharedByConnectors
) {
1672 powerDivider
= this.getNumberOfRunningTransactions();
1674 return powerDivider
;
1677 private getTemplateMaxNumberOfConnectors(): number {
1678 if (!this.stationInfo
?.Connectors
) {
1681 return Object.keys(this.stationInfo
?.Connectors
).length
;
1684 private getMaxNumberOfConnectors(): number {
1685 let maxConnectors
: number;
1686 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1687 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1688 // Distribute evenly the number of connectors
1689 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1690 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1691 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1693 maxConnectors
= this.stationInfo
?.Connectors
[0]
1694 ? this.getTemplateMaxNumberOfConnectors() - 1
1695 : this.getTemplateMaxNumberOfConnectors();
1697 return maxConnectors
;
1700 private getMaximumPower(): number {
1701 return (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1704 private getMaximumAmperage(): number | undefined {
1705 const maximumPower
= this.getMaximumPower();
1706 switch (this.getCurrentOutType()) {
1707 case CurrentType
.AC
:
1708 return ACElectricUtils
.amperagePerPhaseFromPower(
1709 this.getNumberOfPhases(),
1710 maximumPower
/ this.getNumberOfConnectors(),
1711 this.getVoltageOut()
1713 case CurrentType
.DC
:
1714 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1718 private getAmperageLimitation(): number | undefined {
1720 this.stationInfo
.amperageLimitationOcppKey
&&
1721 ChargingStationConfigurationUtils
.getConfigurationKey(
1723 this.stationInfo
.amperageLimitationOcppKey
1728 ChargingStationConfigurationUtils
.getConfigurationKey(
1730 this.stationInfo
.amperageLimitationOcppKey
1732 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1737 private async startMessageSequence(): Promise
<void> {
1738 if (this.stationInfo
.autoRegister
) {
1739 await this.ocppRequestService
.requestHandler
<
1740 BootNotificationRequest
,
1741 BootNotificationResponse
1744 RequestCommand
.BOOT_NOTIFICATION
,
1746 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1747 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1748 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1749 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1750 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1751 iccid
: this.bootNotificationRequest
.iccid
,
1752 imsi
: this.bootNotificationRequest
.imsi
,
1753 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1754 meterType
: this.bootNotificationRequest
.meterType
,
1756 { skipBufferingOnError
: true }
1759 // Start WebSocket ping
1760 this.startWebSocketPing();
1762 this.startHeartbeat();
1763 // Initialize connectors status
1764 for (const connectorId
of this.connectors
.keys()) {
1765 if (connectorId
=== 0) {
1769 !this.getConnectorStatus(connectorId
)?.status &&
1770 this.getConnectorStatus(connectorId
)?.bootStatus
1772 // Send status in template at startup
1773 await this.ocppRequestService
.requestHandler
<
1774 StatusNotificationRequest
,
1775 StatusNotificationResponse
1776 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1778 status: this.getConnectorStatus(connectorId
).bootStatus
,
1779 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1781 this.getConnectorStatus(connectorId
).status =
1782 this.getConnectorStatus(connectorId
).bootStatus
;
1785 this.getConnectorStatus(connectorId
)?.status &&
1786 this.getConnectorStatus(connectorId
)?.bootStatus
1788 // Send status in template after reset
1789 await this.ocppRequestService
.requestHandler
<
1790 StatusNotificationRequest
,
1791 StatusNotificationResponse
1792 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1794 status: this.getConnectorStatus(connectorId
).bootStatus
,
1795 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1797 this.getConnectorStatus(connectorId
).status =
1798 this.getConnectorStatus(connectorId
).bootStatus
;
1799 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1800 // Send previous status at template reload
1801 await this.ocppRequestService
.requestHandler
<
1802 StatusNotificationRequest
,
1803 StatusNotificationResponse
1804 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1806 status: this.getConnectorStatus(connectorId
).status,
1807 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1810 // Send default status
1811 await this.ocppRequestService
.requestHandler
<
1812 StatusNotificationRequest
,
1813 StatusNotificationResponse
1814 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1816 status: ChargePointStatus
.AVAILABLE
,
1817 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1819 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1823 this.startAutomaticTransactionGenerator();
1826 private startAutomaticTransactionGenerator() {
1827 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1828 if (!this.automaticTransactionGenerator
) {
1829 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1831 if (!this.automaticTransactionGenerator
.started
) {
1832 this.automaticTransactionGenerator
.start();
1837 private async stopMessageSequence(
1838 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1840 // Stop WebSocket ping
1841 this.stopWebSocketPing();
1843 this.stopHeartbeat();
1846 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1847 this.automaticTransactionGenerator
?.started
1849 this.automaticTransactionGenerator
.stop();
1851 for (const connectorId
of this.connectors
.keys()) {
1852 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1853 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1855 this.getBeginEndMeterValues() &&
1856 this.getOcppStrictCompliance() &&
1857 !this.getOutOfOrderEndMeterValues()
1859 // FIXME: Implement OCPP version agnostic helpers
1860 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1863 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1865 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1867 RequestCommand
.METER_VALUES
,
1871 meterValue
: transactionEndMeterValue
,
1875 await this.ocppRequestService
.requestHandler
<
1876 StopTransactionRequest
,
1877 StopTransactionResponse
1878 >(this, RequestCommand
.STOP_TRANSACTION
, {
1880 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1881 idTag
: this.getTransactionIdTag(transactionId
),
1889 private startWebSocketPing(): void {
1890 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1892 StandardParametersKey
.WebSocketPingInterval
1894 ? Utils
.convertToInt(
1895 ChargingStationConfigurationUtils
.getConfigurationKey(
1897 StandardParametersKey
.WebSocketPingInterval
1901 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1902 this.webSocketPingSetInterval
= setInterval(() => {
1903 if (this.isWebSocketConnectionOpened()) {
1904 this.wsConnection
.ping((): void => {
1905 /* This is intentional */
1908 }, webSocketPingInterval
* 1000);
1911 ' WebSocket ping started every ' +
1912 Utils
.formatDurationSeconds(webSocketPingInterval
)
1914 } else if (this.webSocketPingSetInterval
) {
1917 ' WebSocket ping every ' +
1918 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1923 `${this.logPrefix()} WebSocket ping interval set to ${
1924 webSocketPingInterval
1925 ? Utils.formatDurationSeconds(webSocketPingInterval)
1926 : webSocketPingInterval
1927 }, not starting the WebSocket ping`
1932 private stopWebSocketPing(): void {
1933 if (this.webSocketPingSetInterval
) {
1934 clearInterval(this.webSocketPingSetInterval
);
1938 private getConfiguredSupervisionUrl(): URL
{
1939 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1940 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1942 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1944 switch (Configuration
.getSupervisionUrlDistribution()) {
1945 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1946 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1948 case SupervisionUrlDistribution
.RANDOM
:
1950 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1952 case SupervisionUrlDistribution
.SEQUENTIAL
:
1953 if (this.index
<= supervisionUrls
.length
) {
1954 urlIndex
= this.index
- 1;
1957 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1963 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1964 SupervisionUrlDistribution.ROUND_ROBIN
1967 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1970 return new URL(supervisionUrls
[urlIndex
]);
1972 return new URL(supervisionUrls
as string);
1975 private getHeartbeatInterval(): number | undefined {
1976 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1978 StandardParametersKey
.HeartbeatInterval
1980 if (HeartbeatInterval
) {
1981 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1983 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1985 StandardParametersKey
.HeartBeatInterval
1987 if (HeartBeatInterval
) {
1988 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1990 !this.stationInfo
.autoRegister
&&
1992 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1993 Constants.DEFAULT_HEARTBEAT_INTERVAL
1996 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1999 private stopHeartbeat(): void {
2000 if (this.heartbeatSetInterval
) {
2001 clearInterval(this.heartbeatSetInterval
);
2005 private openWSConnection(
2006 options
: WsOptions
= this.stationInfo
.wsOptions
,
2007 forceCloseOpened
= false
2009 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
2011 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
2012 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
2014 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2016 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
2017 this.wsConnection
.close();
2019 let protocol
: string;
2020 switch (this.getOcppVersion()) {
2021 case OCPPVersion
.VERSION_16
:
2022 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
2025 this.handleUnsupportedVersion(this.getOcppVersion());
2028 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
2030 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
2034 private stopMeterValues(connectorId
: number) {
2035 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2036 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2040 private getReconnectExponentialDelay(): boolean | undefined {
2041 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2042 ? this.stationInfo
.reconnectExponentialDelay
2046 private async reconnect(code
: number): Promise
<void> {
2047 // Stop WebSocket ping
2048 this.stopWebSocketPing();
2050 this.stopHeartbeat();
2051 // Stop the ATG if needed
2053 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
2054 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
2055 this.automaticTransactionGenerator
?.started
2057 this.automaticTransactionGenerator
.stop();
2060 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2061 this.getAutoReconnectMaxRetries() === -1
2063 this.autoReconnectRetryCount
++;
2064 const reconnectDelay
= this.getReconnectExponentialDelay()
2065 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2066 : this.getConnectionTimeout() * 1000;
2067 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
2069 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2072 )}ms, timeout ${reconnectTimeout}ms`
2074 await Utils
.sleep(reconnectDelay
);
2077 ' WebSocket: reconnecting try #' +
2078 this.autoReconnectRetryCount
.toString()
2080 this.openWSConnection(
2081 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
2084 this.wsConnectionRestarted
= true;
2085 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2087 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2088 this.autoReconnectRetryCount
2089 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2094 private initializeConnectorStatus(connectorId
: number): void {
2095 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2096 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2097 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2098 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2099 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2100 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;