1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import crypto from
'node:crypto';
4 import fs from
'node:fs';
5 import path from
'node:path';
6 import { URL
} from
'node:url';
7 import { parentPort
} from
'worker_threads';
9 import merge from
'just-merge';
10 import WebSocket
, { type RawData
} from
'ws';
12 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
13 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
14 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
15 import { ChargingStationUtils
} from
'./ChargingStationUtils';
16 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
17 import { MessageChannelUtils
} from
'./MessageChannelUtils';
18 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
19 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
20 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
21 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
22 import OCPP20IncomingRequestService from
'./ocpp/2.0/OCPP20IncomingRequestService';
23 import OCPP20RequestService from
'./ocpp/2.0/OCPP20RequestService';
24 import OCPP20ResponseService from
'./ocpp/2.0/OCPP20ResponseService';
25 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
26 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
27 import { OCPPServiceUtils
} from
'./ocpp/OCPPServiceUtils';
28 import SharedLRUCache from
'./SharedLRUCache';
29 import BaseError from
'../exception/BaseError';
30 import OCPPError from
'../exception/OCPPError';
31 import PerformanceStatistics from
'../performance/PerformanceStatistics';
32 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
33 import type { ChargingStationConfiguration
} from
'../types/ChargingStationConfiguration';
34 import type { ChargingStationInfo
} from
'../types/ChargingStationInfo';
35 import type { ChargingStationOcppConfiguration
} from
'../types/ChargingStationOcppConfiguration';
37 type ChargingStationTemplate
,
42 } from
'../types/ChargingStationTemplate';
43 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
44 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
45 import { FileType
} from
'../types/FileType';
46 import type { JsonType
} from
'../types/JsonType';
48 ConnectorPhaseRotation
,
49 StandardParametersKey
,
50 SupportedFeatureProfiles
,
51 VendorDefaultParametersKey
,
52 } from
'../types/ocpp/Configuration';
53 import { ConnectorStatusEnum
} from
'../types/ocpp/ConnectorStatusEnum';
54 import { ErrorType
} from
'../types/ocpp/ErrorType';
55 import { MessageType
} from
'../types/ocpp/MessageType';
56 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
57 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
60 type BootNotificationRequest
,
64 type FirmwareStatusNotificationRequest
,
65 type HeartbeatRequest
,
67 IncomingRequestCommand
,
68 type MeterValuesRequest
,
71 type ResponseCallback
,
72 type StatusNotificationRequest
,
73 } from
'../types/ocpp/Requests';
75 type BootNotificationResponse
,
77 type FirmwareStatusNotificationResponse
,
78 type HeartbeatResponse
,
79 type MeterValuesResponse
,
80 RegistrationStatusEnumType
,
82 type StatusNotificationResponse
,
83 } from
'../types/ocpp/Responses';
85 StopTransactionReason
,
86 type StopTransactionRequest
,
87 type StopTransactionResponse
,
88 } from
'../types/ocpp/Transaction';
89 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
90 import Configuration from
'../utils/Configuration';
91 import Constants from
'../utils/Constants';
92 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
93 import FileUtils from
'../utils/FileUtils';
94 import logger from
'../utils/Logger';
95 import Utils from
'../utils/Utils';
97 export default class ChargingStation
{
98 public readonly index
: number;
99 public readonly templateFile
: string;
100 public stationInfo
!: ChargingStationInfo
;
101 public started
: boolean;
102 public starting
: boolean;
103 public authorizedTagsCache
: AuthorizedTagsCache
;
104 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
105 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
106 public wsConnection
!: WebSocket
| null;
107 public readonly connectors
: Map
<number, ConnectorStatus
>;
108 public readonly requests
: Map
<string, CachedRequest
>;
109 public performanceStatistics
!: PerformanceStatistics
| undefined;
110 public heartbeatSetInterval
!: NodeJS
.Timeout
;
111 public ocppRequestService
!: OCPPRequestService
;
112 public bootNotificationRequest
!: BootNotificationRequest
;
113 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
114 public powerDivider
!: number;
115 private stopping
: boolean;
116 private configurationFile
!: string;
117 private configurationFileHash
!: string;
118 private connectorsConfigurationHash
!: string;
119 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
120 private readonly messageBuffer
: Set
<string>;
121 private configuredSupervisionUrl
!: URL
;
122 private configuredSupervisionUrlIndex
!: number;
123 private wsConnectionRestarted
: boolean;
124 private autoReconnectRetryCount
: number;
125 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
126 private readonly sharedLRUCache
: SharedLRUCache
;
127 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
128 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
130 constructor(index
: number, templateFile
: string) {
131 this.started
= false;
132 this.starting
= false;
133 this.stopping
= false;
134 this.wsConnectionRestarted
= false;
135 this.autoReconnectRetryCount
= 0;
137 this.templateFile
= templateFile
;
138 this.connectors
= new Map
<number, ConnectorStatus
>();
139 this.requests
= new Map
<string, CachedRequest
>();
140 this.messageBuffer
= new Set
<string>();
141 this.sharedLRUCache
= SharedLRUCache
.getInstance();
142 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
143 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
148 private get
wsConnectionUrl(): URL
{
151 this.getSupervisionUrlOcppConfiguration()
152 ? ChargingStationConfigurationUtils.getConfigurationKey(
154 this.getSupervisionUrlOcppKey()
156 : this.configuredSupervisionUrl.href
157 }/${this.stationInfo.chargingStationId}`
161 public logPrefix
= (): string => {
162 return Utils
.logPrefix(
164 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId) &&
165 this?.stationInfo?.chargingStationId) ??
166 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) ??
172 public hasAuthorizedTags(): boolean {
173 return Utils
.isNotEmptyArray(
174 this.authorizedTagsCache
.getAuthorizedTags(
175 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
180 public getEnableStatistics(): boolean {
181 return this.stationInfo
.enableStatistics
?? false;
184 public getMustAuthorizeAtRemoteStart(): boolean {
185 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
188 public getPayloadSchemaValidation(): boolean {
189 return this.stationInfo
.payloadSchemaValidation
?? true;
192 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
193 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
194 switch (this.getCurrentOutType(stationInfo
)) {
196 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
197 ? localStationInfo
.numberOfPhases
204 public isWebSocketConnectionOpened(): boolean {
205 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
208 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
209 return this?.bootNotificationResponse
?.status;
212 public isInUnknownState(): boolean {
213 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
216 public isInPendingState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
220 public isInAcceptedState(): boolean {
221 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
224 public isInRejectedState(): boolean {
225 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
228 public isRegistered(): boolean {
230 this.isInUnknownState() === false &&
231 (this.isInAcceptedState() === true || this.isInPendingState() === true)
235 public isChargingStationAvailable(): boolean {
236 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.OPERATIVE
;
239 public isConnectorAvailable(id
: number): boolean {
240 return id
> 0 && this.getConnectorStatus(id
)?.availability
=== AvailabilityType
.OPERATIVE
;
243 public getNumberOfConnectors(): number {
244 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
247 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
248 return this.connectors
.get(id
);
251 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
252 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
255 public getOcppStrictCompliance(): boolean {
256 return this.stationInfo
?.ocppStrictCompliance
?? false;
259 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
260 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
261 this.getCurrentOutType(stationInfo
),
265 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
266 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
267 ? localStationInfo
.voltageOut
271 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
272 const localStationInfo
= stationInfo
?? this.stationInfo
;
273 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
276 public getConnectorMaximumAvailablePower(connectorId
: number): number {
277 let connectorAmperageLimitationPowerLimit
: number;
279 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
280 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
282 connectorAmperageLimitationPowerLimit
=
283 (this.getCurrentOutType() === CurrentType
.AC
284 ? ACElectricUtils
.powerTotal(
285 this.getNumberOfPhases(),
286 this.getVoltageOut(),
287 this.getAmperageLimitation() * this.getNumberOfConnectors()
289 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
292 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
293 const connectorChargingProfilesPowerLimit
=
294 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
296 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
297 isNaN(connectorAmperageLimitationPowerLimit
)
299 : connectorAmperageLimitationPowerLimit
,
300 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
304 public getTransactionIdTag(transactionId
: number): string | undefined {
305 for (const connectorId
of this.connectors
.keys()) {
308 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
310 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
315 public getOutOfOrderEndMeterValues(): boolean {
316 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
319 public getBeginEndMeterValues(): boolean {
320 return this.stationInfo
?.beginEndMeterValues
?? false;
323 public getMeteringPerTransaction(): boolean {
324 return this.stationInfo
?.meteringPerTransaction
?? true;
327 public getTransactionDataMeterValues(): boolean {
328 return this.stationInfo
?.transactionDataMeterValues
?? false;
331 public getMainVoltageMeterValues(): boolean {
332 return this.stationInfo
?.mainVoltageMeterValues
?? true;
335 public getPhaseLineToLineVoltageMeterValues(): boolean {
336 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
339 public getCustomValueLimitationMeterValues(): boolean {
340 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
343 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
344 for (const connectorId
of this.connectors
.keys()) {
347 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
354 public getEnergyActiveImportRegisterByTransactionId(
355 transactionId
: number,
358 return this.getEnergyActiveImportRegister(
359 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
364 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
365 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
368 public getAuthorizeRemoteTxRequests(): boolean {
369 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
371 StandardParametersKey
.AuthorizeRemoteTxRequests
373 return authorizeRemoteTxRequests
374 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
378 public getLocalAuthListEnabled(): boolean {
379 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
381 StandardParametersKey
.LocalAuthListEnabled
383 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
386 public startHeartbeat(): void {
388 this.getHeartbeatInterval() &&
389 this.getHeartbeatInterval() > 0 &&
390 !this.heartbeatSetInterval
392 this.heartbeatSetInterval
= setInterval(() => {
393 this.ocppRequestService
394 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
397 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
401 }, this.getHeartbeatInterval());
403 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
404 this.getHeartbeatInterval()
407 } else if (this.heartbeatSetInterval
) {
409 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
410 this.getHeartbeatInterval()
415 `${this.logPrefix()} Heartbeat interval set to ${
416 this.getHeartbeatInterval()
417 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
418 : this.getHeartbeatInterval()
419 }, not starting the heartbeat`
424 public restartHeartbeat(): void {
426 this.stopHeartbeat();
428 this.startHeartbeat();
431 public restartWebSocketPing(): void {
432 // Stop WebSocket ping
433 this.stopWebSocketPing();
434 // Start WebSocket ping
435 this.startWebSocketPing();
438 public startMeterValues(connectorId
: number, interval
: number): void {
439 if (connectorId
=== 0) {
441 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
445 if (!this.getConnectorStatus(connectorId
)) {
447 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
451 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
453 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
457 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
458 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
461 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
466 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
467 // FIXME: Implement OCPP version agnostic helpers
468 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
471 this.getConnectorStatus(connectorId
).transactionId
,
474 this.ocppRequestService
475 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
477 RequestCommand
.METER_VALUES
,
480 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
481 meterValue
: [meterValue
],
486 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
493 `${this.logPrefix()} Charging station ${
494 StandardParametersKey.MeterValueSampleInterval
495 } configuration set to ${
496 interval ? Utils.formatDurationMilliSeconds(interval) : interval
497 }, not sending MeterValues`
502 public start(): void {
503 if (this.started
=== false) {
504 if (this.starting
=== false) {
505 this.starting
= true;
506 if (this.getEnableStatistics() === true) {
507 this.performanceStatistics
?.start();
509 this.openWSConnection();
510 // Monitor charging station template file
511 this.templateFileWatcher
= FileUtils
.watchJsonFile(
513 FileType
.ChargingStationTemplate
,
516 (event
, filename
): void => {
517 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
520 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
522 } file have changed, reload`
524 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
528 this.stopAutomaticTransactionGenerator();
530 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
532 this.startAutomaticTransactionGenerator();
534 if (this.getEnableStatistics() === true) {
535 this.performanceStatistics
?.restart();
537 this.performanceStatistics
?.stop();
539 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
542 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
550 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
551 this.starting
= false;
553 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
556 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
560 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
561 if (this.started
=== true) {
562 if (this.stopping
=== false) {
563 this.stopping
= true;
564 await this.stopMessageSequence(reason
);
565 this.closeWSConnection();
566 if (this.getEnableStatistics() === true) {
567 this.performanceStatistics
?.stop();
569 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
570 this.templateFileWatcher
?.close();
571 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
572 this.bootNotificationResponse
= undefined;
573 this.started
= false;
574 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
575 this.stopping
= false;
577 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
580 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
584 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
585 await this.stop(reason
);
586 await Utils
.sleep(this.stationInfo
.resetTime
);
591 public saveOcppConfiguration(): void {
592 if (this.getOcppPersistentConfiguration()) {
593 this.saveConfiguration();
597 public resetConnectorStatus(connectorId
: number): void {
598 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
599 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
600 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
601 this.getConnectorStatus(connectorId
).transactionStarted
= false;
602 delete this.getConnectorStatus(connectorId
)?.localAuthorizeIdTag
;
603 delete this.getConnectorStatus(connectorId
)?.authorizeIdTag
;
604 delete this.getConnectorStatus(connectorId
)?.transactionId
;
605 delete this.getConnectorStatus(connectorId
)?.transactionIdTag
;
606 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
607 delete this.getConnectorStatus(connectorId
)?.transactionBeginMeterValue
;
608 this.stopMeterValues(connectorId
);
609 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
612 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
613 return ChargingStationConfigurationUtils
.getConfigurationKey(
615 StandardParametersKey
.SupportedFeatureProfiles
616 )?.value
?.includes(featureProfile
);
619 public bufferMessage(message
: string): void {
620 this.messageBuffer
.add(message
);
623 public openWSConnection(
624 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
625 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
627 terminateOpened
: false,
630 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
631 params
.closeOpened
= params
?.closeOpened
?? false;
632 params
.terminateOpened
= params
?.terminateOpened
?? false;
633 if (this.started
=== false && this.starting
=== false) {
635 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
640 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
641 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
643 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
645 if (params
?.closeOpened
) {
646 this.closeWSConnection();
648 if (params
?.terminateOpened
) {
649 this.terminateWSConnection();
651 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
652 let protocol
: string;
653 switch (ocppVersion
) {
654 case OCPPVersion
.VERSION_16
:
655 case OCPPVersion
.VERSION_20
:
656 case OCPPVersion
.VERSION_201
:
657 protocol
= `ocpp${ocppVersion}`;
660 this.handleUnsupportedVersion(ocppVersion
);
664 if (this.isWebSocketConnectionOpened() === true) {
666 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
672 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
675 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
677 // Handle WebSocket message
678 this.wsConnection
.on(
680 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
682 // Handle WebSocket error
683 this.wsConnection
.on(
685 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
687 // Handle WebSocket close
688 this.wsConnection
.on(
690 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
692 // Handle WebSocket open
693 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
694 // Handle WebSocket ping
695 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
696 // Handle WebSocket pong
697 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
700 public closeWSConnection(): void {
701 if (this.isWebSocketConnectionOpened() === true) {
702 this.wsConnection
?.close();
703 this.wsConnection
= null;
707 public startAutomaticTransactionGenerator(
708 connectorIds
?: number[],
709 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
711 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
712 automaticTransactionGeneratorConfiguration
??
713 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
716 if (Utils
.isNotEmptyArray(connectorIds
)) {
717 for (const connectorId
of connectorIds
) {
718 this.automaticTransactionGenerator
?.startConnector(connectorId
);
721 this.automaticTransactionGenerator
?.start();
723 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
726 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
727 if (Utils
.isNotEmptyArray(connectorIds
)) {
728 for (const connectorId
of connectorIds
) {
729 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
732 this.automaticTransactionGenerator
?.stop();
734 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
737 public async stopTransactionOnConnector(
739 reason
= StopTransactionReason
.NONE
740 ): Promise
<StopTransactionResponse
> {
741 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
743 this.getBeginEndMeterValues() === true &&
744 this.getOcppStrictCompliance() === true &&
745 this.getOutOfOrderEndMeterValues() === false
747 // FIXME: Implement OCPP version agnostic helpers
748 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
751 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
753 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
755 RequestCommand
.METER_VALUES
,
759 meterValue
: [transactionEndMeterValue
],
763 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
765 RequestCommand
.STOP_TRANSACTION
,
768 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
774 private flushMessageBuffer(): void {
775 if (this.messageBuffer
.size
> 0) {
776 this.messageBuffer
.forEach((message
) => {
778 let commandName
: RequestCommand
;
779 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
780 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
782 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
783 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
785 this.wsConnection
?.send(message
);
786 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
788 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
790 )} payload sent: ${message}`
792 this.messageBuffer
.delete(message
);
797 private getSupervisionUrlOcppConfiguration(): boolean {
798 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
801 private getSupervisionUrlOcppKey(): string {
802 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
805 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
806 let template
: ChargingStationTemplate
;
808 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
809 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
811 const measureId
= `${FileType.ChargingStationTemplate} read`;
812 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
813 template
= JSON
.parse(
814 fs
.readFileSync(this.templateFile
, 'utf8')
815 ) as ChargingStationTemplate
;
816 PerformanceStatistics
.endMeasure(measureId
, beginId
);
817 template
.templateHash
= crypto
818 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
819 .update(JSON
.stringify(template
))
821 this.sharedLRUCache
.setChargingStationTemplate(template
);
824 FileUtils
.handleFileException(
826 FileType
.ChargingStationTemplate
,
827 error
as NodeJS
.ErrnoException
,
834 private getStationInfoFromTemplate(): ChargingStationInfo
{
835 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
836 if (Utils
.isNullOrUndefined(stationTemplate
)) {
837 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
838 logger
.error(`${this.logPrefix()} ${errorMsg}`);
839 throw new BaseError(errorMsg
);
841 if (Utils
.isEmptyObject(stationTemplate
)) {
842 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
843 logger
.error(`${this.logPrefix()} ${errorMsg}`);
844 throw new BaseError(errorMsg
);
846 // Deprecation template keys section
847 ChargingStationUtils
.warnDeprecatedTemplateKey(
852 "Use 'supervisionUrls' instead"
854 ChargingStationUtils
.convertDeprecatedTemplateKey(
859 const stationInfo
: ChargingStationInfo
=
860 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
861 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
862 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
866 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
867 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
868 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
869 stationTemplate
.power
= stationTemplate
.power
as number[];
870 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
871 stationInfo
.maximumPower
=
872 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
873 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
874 : stationTemplate
.power
[powerArrayRandomIndex
];
876 stationTemplate
.power
= stationTemplate
?.power
as number;
877 stationInfo
.maximumPower
=
878 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
879 ? stationTemplate
.power
* 1000
880 : stationTemplate
.power
;
882 stationInfo
.firmwareVersionPattern
=
883 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
885 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
886 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
889 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
891 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
894 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
901 stationTemplate
?.firmwareUpgrade
?? {}
903 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
904 ? stationTemplate
.resetTime
* 1000
905 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
906 const configuredMaxConnectors
=
907 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
908 ChargingStationUtils
.checkConfiguredMaxConnectors(
909 configuredMaxConnectors
,
913 const templateMaxConnectors
=
914 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
915 ChargingStationUtils
.checkTemplateMaxConnectors(
916 templateMaxConnectors
,
921 configuredMaxConnectors
>
922 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
923 !stationTemplate
?.randomConnectors
926 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
928 }, forcing random connector configurations affectation`
930 stationInfo
.randomConnectors
= true;
932 // Build connectors if needed (FIXME: should be factored out)
933 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
934 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
935 ChargingStationUtils
.createStationInfoHash(stationInfo
);
939 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
940 let stationInfo
: ChargingStationInfo
| undefined;
941 this.getStationInfoPersistentConfiguration() &&
942 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
);
943 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
947 private getStationInfo(): ChargingStationInfo
{
948 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
949 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
950 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
951 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
952 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
953 return this.stationInfo
;
955 return stationInfoFromFile
;
957 stationInfoFromFile
&&
958 ChargingStationUtils
.propagateSerialNumber(
959 this.getTemplateFromFile(),
961 stationInfoFromTemplate
963 return stationInfoFromTemplate
;
966 private saveStationInfo(): void {
967 if (this.getStationInfoPersistentConfiguration()) {
968 this.saveConfiguration();
972 private getOcppPersistentConfiguration(): boolean {
973 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
976 private getStationInfoPersistentConfiguration(): boolean {
977 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
980 private handleUnsupportedVersion(version
: OCPPVersion
) {
981 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
982 logger
.error(`${this.logPrefix()} ${errMsg}`);
983 throw new BaseError(errMsg
);
986 private initialize(): void {
987 this.configurationFile
= path
.join(
988 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
989 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
991 this.stationInfo
= this.getStationInfo();
992 this.saveStationInfo();
993 // Avoid duplication of connectors related information in RAM
994 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
995 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
996 if (this.getEnableStatistics() === true) {
997 this.performanceStatistics
= PerformanceStatistics
.getInstance(
998 this.stationInfo
.hashId
,
999 this.stationInfo
.chargingStationId
,
1000 this.configuredSupervisionUrl
1003 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1006 this.powerDivider
= this.getPowerDivider();
1007 // OCPP configuration
1008 this.ocppConfiguration
= this.getOcppConfiguration();
1009 this.initializeOcppConfiguration();
1010 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1011 switch (ocppVersion
) {
1012 case OCPPVersion
.VERSION_16
:
1013 this.ocppIncomingRequestService
=
1014 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1015 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1016 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1019 case OCPPVersion
.VERSION_20
:
1020 case OCPPVersion
.VERSION_201
:
1021 this.ocppIncomingRequestService
=
1022 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1023 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1024 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1028 this.handleUnsupportedVersion(ocppVersion
);
1031 if (this.stationInfo
?.autoRegister
=== true) {
1032 this.bootNotificationResponse
= {
1033 currentTime
: new Date(),
1034 interval
: this.getHeartbeatInterval() / 1000,
1035 status: RegistrationStatusEnumType
.ACCEPTED
,
1039 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1040 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1041 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1043 const patternGroup
: number | undefined =
1044 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1045 this.stationInfo
.firmwareVersion
?.split('.').length
;
1046 const match
= this.stationInfo
?.firmwareVersion
1047 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1048 ?.slice(1, patternGroup
+ 1);
1049 const patchLevelIndex
= match
.length
- 1;
1050 match
[patchLevelIndex
] = (
1051 Utils
.convertToInt(match
[patchLevelIndex
]) +
1052 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1054 this.stationInfo
.firmwareVersion
= match
?.join('.');
1058 private initializeOcppConfiguration(): void {
1060 !ChargingStationConfigurationUtils
.getConfigurationKey(
1062 StandardParametersKey
.HeartbeatInterval
1065 ChargingStationConfigurationUtils
.addConfigurationKey(
1067 StandardParametersKey
.HeartbeatInterval
,
1072 !ChargingStationConfigurationUtils
.getConfigurationKey(
1074 StandardParametersKey
.HeartBeatInterval
1077 ChargingStationConfigurationUtils
.addConfigurationKey(
1079 StandardParametersKey
.HeartBeatInterval
,
1085 this.getSupervisionUrlOcppConfiguration() &&
1086 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1088 ChargingStationConfigurationUtils
.addConfigurationKey(
1090 this.getSupervisionUrlOcppKey(),
1091 this.configuredSupervisionUrl
.href
,
1095 !this.getSupervisionUrlOcppConfiguration() &&
1096 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1098 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1100 this.getSupervisionUrlOcppKey(),
1105 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1106 !ChargingStationConfigurationUtils
.getConfigurationKey(
1108 this.stationInfo
.amperageLimitationOcppKey
1111 ChargingStationConfigurationUtils
.addConfigurationKey(
1113 this.stationInfo
.amperageLimitationOcppKey
,
1115 this.stationInfo
.maximumAmperage
*
1116 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1121 !ChargingStationConfigurationUtils
.getConfigurationKey(
1123 StandardParametersKey
.SupportedFeatureProfiles
1126 ChargingStationConfigurationUtils
.addConfigurationKey(
1128 StandardParametersKey
.SupportedFeatureProfiles
,
1129 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1132 ChargingStationConfigurationUtils
.addConfigurationKey(
1134 StandardParametersKey
.NumberOfConnectors
,
1135 this.getNumberOfConnectors().toString(),
1140 !ChargingStationConfigurationUtils
.getConfigurationKey(
1142 StandardParametersKey
.MeterValuesSampledData
1145 ChargingStationConfigurationUtils
.addConfigurationKey(
1147 StandardParametersKey
.MeterValuesSampledData
,
1148 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1152 !ChargingStationConfigurationUtils
.getConfigurationKey(
1154 StandardParametersKey
.ConnectorPhaseRotation
1157 const connectorPhaseRotation
= [];
1158 for (const connectorId
of this.connectors
.keys()) {
1160 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1161 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1162 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1163 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1165 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1166 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1167 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1168 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1171 ChargingStationConfigurationUtils
.addConfigurationKey(
1173 StandardParametersKey
.ConnectorPhaseRotation
,
1174 connectorPhaseRotation
.toString()
1178 !ChargingStationConfigurationUtils
.getConfigurationKey(
1180 StandardParametersKey
.AuthorizeRemoteTxRequests
1183 ChargingStationConfigurationUtils
.addConfigurationKey(
1185 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1190 !ChargingStationConfigurationUtils
.getConfigurationKey(
1192 StandardParametersKey
.LocalAuthListEnabled
1194 ChargingStationConfigurationUtils
.getConfigurationKey(
1196 StandardParametersKey
.SupportedFeatureProfiles
1197 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1199 ChargingStationConfigurationUtils
.addConfigurationKey(
1201 StandardParametersKey
.LocalAuthListEnabled
,
1206 !ChargingStationConfigurationUtils
.getConfigurationKey(
1208 StandardParametersKey
.ConnectionTimeOut
1211 ChargingStationConfigurationUtils
.addConfigurationKey(
1213 StandardParametersKey
.ConnectionTimeOut
,
1214 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1217 this.saveOcppConfiguration();
1220 private initializeConnectors(
1221 stationInfo
: ChargingStationInfo
,
1222 configuredMaxConnectors
: number,
1223 templateMaxConnectors
: number
1225 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1226 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1227 logger
.error(`${this.logPrefix()} ${logMsg}`);
1228 throw new BaseError(logMsg
);
1230 if (!stationInfo
?.Connectors
[0]) {
1232 `${this.logPrefix()} Charging station information from template ${
1234 } with no connector Id 0 configuration`
1237 if (stationInfo
?.Connectors
) {
1238 const connectorsConfigHash
= crypto
1239 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1240 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1242 const connectorsConfigChanged
=
1243 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1244 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1245 connectorsConfigChanged
&& this.connectors
.clear();
1246 this.connectorsConfigurationHash
= connectorsConfigHash
;
1247 // Add connector Id 0
1248 let lastConnector
= '0';
1249 for (lastConnector
in stationInfo
?.Connectors
) {
1250 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1251 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1253 lastConnectorId
=== 0 &&
1254 this.getUseConnectorId0(stationInfo
) === true &&
1257 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1258 this.connectors
.set(
1260 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1262 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1263 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1264 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1268 // Generate all connectors
1269 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1270 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1271 const randConnectorId
= stationInfo
?.randomConnectors
1272 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1274 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1275 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1276 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1277 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1278 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1279 this.getConnectorStatus(index
).chargingProfiles
= [];
1286 `${this.logPrefix()} Charging station information from template ${
1288 } with no connectors configuration defined, using already defined connectors`
1291 // Initialize transaction attributes on connectors
1292 for (const connectorId
of this.connectors
.keys()) {
1293 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1295 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1296 this.getConnectorStatus(connectorId)?.transactionId
1302 (this.getConnectorStatus(connectorId
)?.transactionStarted
=== undefined ||
1303 this.getConnectorStatus(connectorId
)?.transactionStarted
=== null)
1305 this.initializeConnectorStatus(connectorId
);
1310 private checkStationInfoConnectorStatus(
1311 connectorId
: number,
1312 connectorStatus
: ConnectorStatus
1314 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1316 `${this.logPrefix()} Charging station information from template ${
1318 } with connector ${connectorId} status configuration defined, undefine it`
1320 connectorStatus
.status = undefined;
1324 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1325 let configuration
: ChargingStationConfiguration
| undefined;
1326 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1328 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1329 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1330 this.configurationFileHash
1333 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1334 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1335 configuration
= JSON
.parse(
1336 fs
.readFileSync(this.configurationFile
, 'utf8')
1337 ) as ChargingStationConfiguration
;
1338 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1339 this.configurationFileHash
= configuration
.configurationHash
;
1340 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1343 FileUtils
.handleFileException(
1344 this.configurationFile
,
1345 FileType
.ChargingStationConfiguration
,
1346 error
as NodeJS
.ErrnoException
,
1351 return configuration
;
1354 private saveConfiguration(): void {
1355 if (this.configurationFile
) {
1357 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1358 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1360 const configurationData
: ChargingStationConfiguration
=
1361 this.getConfigurationFromFile() ?? {};
1362 this.ocppConfiguration
?.configurationKey
&&
1363 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1364 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1365 delete configurationData
.configurationHash
;
1366 const configurationHash
= crypto
1367 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1368 .update(JSON
.stringify(configurationData
))
1370 if (this.configurationFileHash
!== configurationHash
) {
1371 configurationData
.configurationHash
= configurationHash
;
1372 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1373 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1374 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1375 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1376 fs
.closeSync(fileDescriptor
);
1377 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1378 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1379 this.configurationFileHash
= configurationHash
;
1380 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1383 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1384 this.configurationFile
1389 FileUtils
.handleFileException(
1390 this.configurationFile
,
1391 FileType
.ChargingStationConfiguration
,
1392 error
as NodeJS
.ErrnoException
,
1398 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1403 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1404 return this.getTemplateFromFile()?.Configuration
;
1407 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1408 let configuration
: ChargingStationConfiguration
| undefined;
1409 if (this.getOcppPersistentConfiguration() === true) {
1410 const configurationFromFile
= this.getConfigurationFromFile();
1411 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1413 configuration
&& delete configuration
.stationInfo
;
1414 return configuration
;
1417 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1418 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1419 this.getOcppConfigurationFromFile();
1420 if (!ocppConfiguration
) {
1421 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1423 return ocppConfiguration
;
1426 private async onOpen(): Promise
<void> {
1427 if (this.isWebSocketConnectionOpened() === true) {
1429 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1431 if (this.isRegistered() === false) {
1432 // Send BootNotification
1433 let registrationRetryCount
= 0;
1435 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1436 BootNotificationRequest
,
1437 BootNotificationResponse
1438 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1439 skipBufferingOnError
: true,
1441 if (this.isRegistered() === false) {
1442 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1444 this?.bootNotificationResponse
?.interval
1445 ? this.bootNotificationResponse
.interval
* 1000
1446 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1450 this.isRegistered() === false &&
1451 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1452 this.getRegistrationMaxRetries() === -1)
1455 if (this.isRegistered() === true) {
1456 if (this.isInAcceptedState() === true) {
1457 await this.startMessageSequence();
1461 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1464 this.wsConnectionRestarted
= false;
1465 this.autoReconnectRetryCount
= 0;
1466 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1469 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1474 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1477 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1478 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1480 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1482 )}' and reason '${reason.toString()}'`
1484 this.autoReconnectRetryCount
= 0;
1489 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1491 )}' and reason '${reason.toString()}'`
1493 this.started
=== true && (await this.reconnect());
1496 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1499 private async onMessage(data
: RawData
): Promise
<void> {
1500 let messageType
: number;
1501 let messageId
: string;
1502 let commandName
: IncomingRequestCommand
;
1503 let commandPayload
: JsonType
;
1504 let errorType
: ErrorType
;
1505 let errorMessage
: string;
1506 let errorDetails
: JsonType
;
1507 let responseCallback
: ResponseCallback
;
1508 let errorCallback
: ErrorCallback
;
1509 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1510 let requestPayload
: JsonType
;
1511 let cachedRequest
: CachedRequest
;
1514 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1515 if (Array.isArray(request
) === true) {
1516 [messageType
, messageId
] = request
;
1517 // Check the type of message
1518 switch (messageType
) {
1520 case MessageType
.CALL_MESSAGE
:
1521 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1522 if (this.getEnableStatistics() === true) {
1523 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1526 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1530 // Process the message
1531 await this.ocppIncomingRequestService
.incomingRequestHandler(
1539 case MessageType
.CALL_RESULT_MESSAGE
:
1540 [, , commandPayload
] = request
as Response
;
1541 if (this.requests
.has(messageId
) === false) {
1543 throw new OCPPError(
1544 ErrorType
.INTERNAL_ERROR
,
1545 `Response for unknown message id ${messageId}`,
1551 cachedRequest
= this.requests
.get(messageId
);
1552 if (Array.isArray(cachedRequest
) === true) {
1553 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1555 throw new OCPPError(
1556 ErrorType
.PROTOCOL_ERROR
,
1557 `Cached request for message id ${messageId} response is not an array`,
1559 cachedRequest
as unknown
as JsonType
1563 `${this.logPrefix()} << Command '${
1564 requestCommandName ?? Constants.UNKNOWN_COMMAND
1565 }' received response payload: ${JSON.stringify(request)}`
1567 responseCallback(commandPayload
, requestPayload
);
1570 case MessageType
.CALL_ERROR_MESSAGE
:
1571 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1572 if (this.requests
.has(messageId
) === false) {
1574 throw new OCPPError(
1575 ErrorType
.INTERNAL_ERROR
,
1576 `Error response for unknown message id ${messageId}`,
1578 { errorType
, errorMessage
, errorDetails
}
1581 cachedRequest
= this.requests
.get(messageId
);
1582 if (Array.isArray(cachedRequest
) === true) {
1583 [, errorCallback
, requestCommandName
] = cachedRequest
;
1585 throw new OCPPError(
1586 ErrorType
.PROTOCOL_ERROR
,
1587 `Cached request for message id ${messageId} error response is not an array`,
1589 cachedRequest
as unknown
as JsonType
1593 `${this.logPrefix()} << Command '${
1594 requestCommandName ?? Constants.UNKNOWN_COMMAND
1595 }' received error response payload: ${JSON.stringify(request)}`
1597 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1601 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1602 errMsg
= `Wrong message type ${messageType}`;
1603 logger
.error(`${this.logPrefix()} ${errMsg}`);
1604 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1606 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1608 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1615 `${this.logPrefix()} Incoming OCPP command '${
1616 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1617 }' message '${data.toString()}'${
1618 messageType !== MessageType.CALL_MESSAGE
1619 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1621 } processing error:`,
1624 if (error
instanceof OCPPError
=== false) {
1626 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1627 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1628 }' message '${data.toString()}' handling is not an OCPPError:`,
1632 switch (messageType
) {
1633 case MessageType
.CALL_MESSAGE
:
1635 await this.ocppRequestService
.sendError(
1639 commandName
?? requestCommandName
?? null
1642 case MessageType
.CALL_RESULT_MESSAGE
:
1643 case MessageType
.CALL_ERROR_MESSAGE
:
1644 if (errorCallback
) {
1645 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1646 errorCallback(error
as OCPPError
, false);
1648 // Remove the request from the cache in case of error at response handling
1649 this.requests
.delete(messageId
);
1656 private onPing(): void {
1657 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1660 private onPong(): void {
1661 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1664 private onError(error
: WSError
): void {
1665 this.closeWSConnection();
1666 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1669 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1670 if (this.getMeteringPerTransaction() === true) {
1673 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1674 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1679 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1680 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1684 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1685 const localStationInfo
= stationInfo
?? this.stationInfo
;
1686 return localStationInfo
?.useConnectorId0
?? true;
1689 private getNumberOfRunningTransactions(): number {
1691 for (const connectorId
of this.connectors
.keys()) {
1692 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1699 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1700 for (const connectorId
of this.connectors
.keys()) {
1701 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1702 await this.stopTransactionOnConnector(connectorId
, reason
);
1708 private getConnectionTimeout(): number {
1710 ChargingStationConfigurationUtils
.getConfigurationKey(
1712 StandardParametersKey
.ConnectionTimeOut
1717 ChargingStationConfigurationUtils
.getConfigurationKey(
1719 StandardParametersKey
.ConnectionTimeOut
1721 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1724 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1727 // -1 for unlimited, 0 for disabling
1728 private getAutoReconnectMaxRetries(): number | undefined {
1729 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1730 return this.stationInfo
.autoReconnectMaxRetries
;
1732 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1733 return Configuration
.getAutoReconnectMaxRetries();
1739 private getRegistrationMaxRetries(): number | undefined {
1740 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1741 return this.stationInfo
.registrationMaxRetries
;
1746 private getPowerDivider(): number {
1747 let powerDivider
= this.getNumberOfConnectors();
1748 if (this.stationInfo
?.powerSharedByConnectors
) {
1749 powerDivider
= this.getNumberOfRunningTransactions();
1751 return powerDivider
;
1754 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1755 const maximumPower
= this.getMaximumPower(stationInfo
);
1756 switch (this.getCurrentOutType(stationInfo
)) {
1757 case CurrentType
.AC
:
1758 return ACElectricUtils
.amperagePerPhaseFromPower(
1759 this.getNumberOfPhases(stationInfo
),
1760 maximumPower
/ this.getNumberOfConnectors(),
1761 this.getVoltageOut(stationInfo
)
1763 case CurrentType
.DC
:
1764 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1768 private getAmperageLimitation(): number | undefined {
1770 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1771 ChargingStationConfigurationUtils
.getConfigurationKey(
1773 this.stationInfo
.amperageLimitationOcppKey
1778 ChargingStationConfigurationUtils
.getConfigurationKey(
1780 this.stationInfo
.amperageLimitationOcppKey
1782 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1787 private async startMessageSequence(): Promise
<void> {
1788 if (this.stationInfo
?.autoRegister
=== true) {
1789 await this.ocppRequestService
.requestHandler
<
1790 BootNotificationRequest
,
1791 BootNotificationResponse
1792 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1793 skipBufferingOnError
: true,
1796 // Start WebSocket ping
1797 this.startWebSocketPing();
1799 this.startHeartbeat();
1800 // Initialize connectors status
1801 for (const connectorId
of this.connectors
.keys()) {
1802 let connectorStatus
: ConnectorStatusEnum
| undefined;
1803 if (connectorId
=== 0) {
1806 !this.getConnectorStatus(connectorId
)?.status &&
1807 (this.isChargingStationAvailable() === false ||
1808 this.isConnectorAvailable(connectorId
) === false)
1810 connectorStatus
= ConnectorStatusEnum
.UNAVAILABLE
;
1812 !this.getConnectorStatus(connectorId
)?.status &&
1813 this.getConnectorStatus(connectorId
)?.bootStatus
1815 // Set boot status in template at startup
1816 connectorStatus
= this.getConnectorStatus(connectorId
)?.bootStatus
;
1817 } else if (this.getConnectorStatus(connectorId
)?.status) {
1818 // Set previous status at startup
1819 connectorStatus
= this.getConnectorStatus(connectorId
)?.status;
1821 // Set default status
1822 connectorStatus
= ConnectorStatusEnum
.AVAILABLE
;
1824 await this.ocppRequestService
.requestHandler
<
1825 StatusNotificationRequest
,
1826 StatusNotificationResponse
1829 RequestCommand
.STATUS_NOTIFICATION
,
1830 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1832 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1834 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1835 await this.ocppRequestService
.requestHandler
<
1836 FirmwareStatusNotificationRequest
,
1837 FirmwareStatusNotificationResponse
1838 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1839 status: FirmwareStatus
.Installed
,
1841 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1845 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1846 this.startAutomaticTransactionGenerator();
1848 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1851 private async stopMessageSequence(
1852 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1854 // Stop WebSocket ping
1855 this.stopWebSocketPing();
1857 this.stopHeartbeat();
1858 // Stop ongoing transactions
1859 if (this.automaticTransactionGenerator
?.started
=== true) {
1860 this.stopAutomaticTransactionGenerator();
1862 await this.stopRunningTransactions(reason
);
1864 for (const connectorId
of this.connectors
.keys()) {
1865 if (connectorId
> 0) {
1866 await this.ocppRequestService
.requestHandler
<
1867 StatusNotificationRequest
,
1868 StatusNotificationResponse
1871 RequestCommand
.STATUS_NOTIFICATION
,
1872 OCPPServiceUtils
.buildStatusNotificationRequest(
1875 ConnectorStatusEnum
.UNAVAILABLE
1878 this.getConnectorStatus(connectorId
).status = undefined;
1883 private startWebSocketPing(): void {
1884 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1886 StandardParametersKey
.WebSocketPingInterval
1888 ? Utils
.convertToInt(
1889 ChargingStationConfigurationUtils
.getConfigurationKey(
1891 StandardParametersKey
.WebSocketPingInterval
1895 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1896 this.webSocketPingSetInterval
= setInterval(() => {
1897 if (this.isWebSocketConnectionOpened() === true) {
1898 this.wsConnection
?.ping();
1900 }, webSocketPingInterval
* 1000);
1902 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
1903 webSocketPingInterval
1906 } else if (this.webSocketPingSetInterval
) {
1908 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
1909 webSocketPingInterval
1914 `${this.logPrefix()} WebSocket ping interval set to ${
1915 webSocketPingInterval
1916 ? Utils.formatDurationSeconds(webSocketPingInterval)
1917 : webSocketPingInterval
1918 }, not starting the WebSocket ping`
1923 private stopWebSocketPing(): void {
1924 if (this.webSocketPingSetInterval
) {
1925 clearInterval(this.webSocketPingSetInterval
);
1929 private getConfiguredSupervisionUrl(): URL
{
1930 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
1931 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
1932 switch (Configuration
.getSupervisionUrlDistribution()) {
1933 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1935 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1937 case SupervisionUrlDistribution
.RANDOM
:
1938 this.configuredSupervisionUrlIndex
= Math.floor(
1939 Utils
.secureRandom() * supervisionUrls
.length
1942 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1943 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1947 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1948 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1951 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1954 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1956 return new URL(supervisionUrls
as string);
1959 private getHeartbeatInterval(): number {
1960 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1962 StandardParametersKey
.HeartbeatInterval
1964 if (HeartbeatInterval
) {
1965 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1967 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1969 StandardParametersKey
.HeartBeatInterval
1971 if (HeartBeatInterval
) {
1972 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1974 this.stationInfo
?.autoRegister
=== false &&
1976 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1977 Constants.DEFAULT_HEARTBEAT_INTERVAL
1980 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1983 private stopHeartbeat(): void {
1984 if (this.heartbeatSetInterval
) {
1985 clearInterval(this.heartbeatSetInterval
);
1989 private terminateWSConnection(): void {
1990 if (this.isWebSocketConnectionOpened() === true) {
1991 this.wsConnection
?.terminate();
1992 this.wsConnection
= null;
1996 private stopMeterValues(connectorId
: number) {
1997 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1998 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
2002 private getReconnectExponentialDelay(): boolean {
2003 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2006 private async reconnect(): Promise
<void> {
2007 // Stop WebSocket ping
2008 this.stopWebSocketPing();
2010 this.stopHeartbeat();
2011 // Stop the ATG if needed
2012 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2013 this.stopAutomaticTransactionGenerator();
2016 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2017 this.getAutoReconnectMaxRetries() === -1
2019 this.autoReconnectRetryCount
++;
2020 const reconnectDelay
= this.getReconnectExponentialDelay()
2021 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2022 : this.getConnectionTimeout() * 1000;
2023 const reconnectDelayWithdraw
= 1000;
2024 const reconnectTimeout
=
2025 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2026 ? reconnectDelay
- reconnectDelayWithdraw
2029 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2032 )}ms, timeout ${reconnectTimeout}ms`
2034 await Utils
.sleep(reconnectDelay
);
2036 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2038 this.openWSConnection(
2039 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2040 { closeOpened
: true }
2042 this.wsConnectionRestarted
= true;
2043 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2045 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2046 this.autoReconnectRetryCount
2047 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2052 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2053 | AutomaticTransactionGeneratorConfiguration
2055 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
2058 private initializeConnectorStatus(connectorId
: number): void {
2059 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2060 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2061 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2062 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2063 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2064 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;