1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import 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
,
41 } from
'../types/ChargingStationTemplate';
42 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
43 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
44 import { FileType
} from
'../types/FileType';
45 import type { JsonType
} from
'../types/JsonType';
46 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
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
,
70 type ResponseCallback
,
71 type StatusNotificationRequest
,
72 } from
'../types/ocpp/Requests';
74 type BootNotificationResponse
,
76 type FirmwareStatusNotificationResponse
,
77 type HeartbeatResponse
,
78 type MeterValuesResponse
,
79 RegistrationStatusEnumType
,
81 type StatusNotificationResponse
,
82 } from
'../types/ocpp/Responses';
84 StopTransactionReason
,
85 type StopTransactionRequest
,
86 type StopTransactionResponse
,
87 } from
'../types/ocpp/Transaction';
88 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
89 import Configuration from
'../utils/Configuration';
90 import Constants from
'../utils/Constants';
91 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
92 import FileUtils from
'../utils/FileUtils';
93 import logger from
'../utils/Logger';
94 import Utils from
'../utils/Utils';
96 export default class ChargingStation
{
97 public readonly index
: number;
98 public readonly templateFile
: string;
99 public stationInfo
!: ChargingStationInfo
;
100 public started
: boolean;
101 public starting
: boolean;
102 public authorizedTagsCache
: AuthorizedTagsCache
;
103 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
104 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
105 public wsConnection
!: WebSocket
;
106 public readonly connectors
: Map
<number, ConnectorStatus
>;
107 public readonly requests
: Map
<string, CachedRequest
>;
108 public performanceStatistics
!: PerformanceStatistics
;
109 public heartbeatSetInterval
!: NodeJS
.Timeout
;
110 public ocppRequestService
!: OCPPRequestService
;
111 public bootNotificationRequest
!: BootNotificationRequest
;
112 public bootNotificationResponse
!: BootNotificationResponse
| null;
113 public powerDivider
!: number;
114 private stopping
: boolean;
115 private configurationFile
!: string;
116 private configurationFileHash
!: string;
117 private connectorsConfigurationHash
!: string;
118 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
119 private readonly messageBuffer
: Set
<string>;
120 private configuredSupervisionUrl
!: URL
;
121 private configuredSupervisionUrlIndex
!: number;
122 private wsConnectionRestarted
: boolean;
123 private autoReconnectRetryCount
: number;
124 private templateFileWatcher
!: fs
.FSWatcher
;
125 private readonly sharedLRUCache
: SharedLRUCache
;
126 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
127 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
129 constructor(index
: number, templateFile
: string) {
130 this.started
= false;
131 this.starting
= false;
132 this.stopping
= false;
133 this.wsConnectionRestarted
= false;
134 this.autoReconnectRetryCount
= 0;
136 this.templateFile
= templateFile
;
137 this.connectors
= new Map
<number, ConnectorStatus
>();
138 this.requests
= new Map
<string, CachedRequest
>();
139 this.messageBuffer
= new Set
<string>();
140 this.sharedLRUCache
= SharedLRUCache
.getInstance();
141 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
142 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
147 private get
wsConnectionUrl(): URL
{
149 (this.getSupervisionUrlOcppConfiguration()
150 ? ChargingStationConfigurationUtils
.getConfigurationKey(
152 this.getSupervisionUrlOcppKey()
154 : this.configuredSupervisionUrl
.href
) +
156 this.stationInfo
.chargingStationId
160 public logPrefix(): string {
161 return Utils
.logPrefix(
163 this?.stationInfo?.chargingStationId ??
164 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
169 public hasAuthorizedTags(): boolean {
170 return !Utils
.isEmptyArray(
171 this.authorizedTagsCache
.getAuthorizedTags(
172 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
177 public getEnableStatistics(): boolean {
178 return this.stationInfo
.enableStatistics
?? false;
181 public getMustAuthorizeAtRemoteStart(): boolean {
182 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
185 public getPayloadSchemaValidation(): boolean {
186 return this.stationInfo
.payloadSchemaValidation
?? true;
189 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
190 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
191 switch (this.getCurrentOutType(stationInfo
)) {
193 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
194 ? localStationInfo
.numberOfPhases
201 public isWebSocketConnectionOpened(): boolean {
202 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
205 public getRegistrationStatus(): RegistrationStatusEnumType
{
206 return this?.bootNotificationResponse
?.status;
209 public isInUnknownState(): boolean {
210 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
213 public isInPendingState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
217 public isInAcceptedState(): boolean {
218 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
221 public isInRejectedState(): boolean {
222 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
225 public isRegistered(): boolean {
227 this.isInUnknownState() === false &&
228 (this.isInAcceptedState() === true || this.isInPendingState() === true)
232 public isChargingStationAvailable(): boolean {
233 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
236 public isConnectorAvailable(id
: number): boolean {
237 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
240 public getNumberOfConnectors(): number {
241 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
244 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
245 return this.connectors
.get(id
);
248 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
249 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
252 public getOcppStrictCompliance(): boolean {
253 return this.stationInfo
?.ocppStrictCompliance
?? false;
256 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
257 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
258 this.getCurrentOutType(stationInfo
),
262 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
263 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
264 ? localStationInfo
.voltageOut
268 public getConnectorMaximumAvailablePower(connectorId
: number): number {
269 let connectorAmperageLimitationPowerLimit
: number;
271 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
272 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
274 connectorAmperageLimitationPowerLimit
=
275 (this.getCurrentOutType() === CurrentType
.AC
276 ? ACElectricUtils
.powerTotal(
277 this.getNumberOfPhases(),
278 this.getVoltageOut(),
279 this.getAmperageLimitation() * this.getNumberOfConnectors()
281 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
284 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
285 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
287 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
288 isNaN(connectorAmperageLimitationPowerLimit
)
290 : connectorAmperageLimitationPowerLimit
,
291 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
295 public getTransactionIdTag(transactionId
: number): string | undefined {
296 for (const connectorId
of this.connectors
.keys()) {
297 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
298 return this.getConnectorStatus(connectorId
).transactionIdTag
;
303 public getOutOfOrderEndMeterValues(): boolean {
304 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
307 public getBeginEndMeterValues(): boolean {
308 return this.stationInfo
?.beginEndMeterValues
?? false;
311 public getMeteringPerTransaction(): boolean {
312 return this.stationInfo
?.meteringPerTransaction
?? true;
315 public getTransactionDataMeterValues(): boolean {
316 return this.stationInfo
?.transactionDataMeterValues
?? false;
319 public getMainVoltageMeterValues(): boolean {
320 return this.stationInfo
?.mainVoltageMeterValues
?? true;
323 public getPhaseLineToLineVoltageMeterValues(): boolean {
324 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
327 public getCustomValueLimitationMeterValues(): boolean {
328 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
331 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
332 for (const connectorId
of this.connectors
.keys()) {
335 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
342 public getEnergyActiveImportRegisterByTransactionId(
343 transactionId
: number,
346 return this.getEnergyActiveImportRegister(
347 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
352 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
353 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
356 public getAuthorizeRemoteTxRequests(): boolean {
357 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
359 StandardParametersKey
.AuthorizeRemoteTxRequests
361 return authorizeRemoteTxRequests
362 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
366 public getLocalAuthListEnabled(): boolean {
367 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
369 StandardParametersKey
.LocalAuthListEnabled
371 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
374 public startHeartbeat(): void {
376 this.getHeartbeatInterval() &&
377 this.getHeartbeatInterval() > 0 &&
378 !this.heartbeatSetInterval
380 this.heartbeatSetInterval
= setInterval(() => {
381 this.ocppRequestService
382 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
385 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
389 }, this.getHeartbeatInterval());
392 ' Heartbeat started every ' +
393 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
395 } else if (this.heartbeatSetInterval
) {
398 ' Heartbeat already started every ' +
399 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
403 `${this.logPrefix()} Heartbeat interval set to ${
404 this.getHeartbeatInterval()
405 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
406 : this.getHeartbeatInterval()
407 }, not starting the heartbeat`
412 public restartHeartbeat(): void {
414 this.stopHeartbeat();
416 this.startHeartbeat();
419 public restartWebSocketPing(): void {
420 // Stop WebSocket ping
421 this.stopWebSocketPing();
422 // Start WebSocket ping
423 this.startWebSocketPing();
426 public startMeterValues(connectorId
: number, interval
: number): void {
427 if (connectorId
=== 0) {
429 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
433 if (!this.getConnectorStatus(connectorId
)) {
435 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
439 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
441 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
445 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
446 !this.getConnectorStatus(connectorId
)?.transactionId
449 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
454 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
455 // FIXME: Implement OCPP version agnostic helpers
456 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
459 this.getConnectorStatus(connectorId
).transactionId
,
462 this.ocppRequestService
463 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
465 RequestCommand
.METER_VALUES
,
468 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
469 meterValue
: [meterValue
],
474 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
481 `${this.logPrefix()} Charging station ${
482 StandardParametersKey.MeterValueSampleInterval
483 } configuration set to ${
484 interval ? Utils.formatDurationMilliSeconds(interval) : interval
485 }, not sending MeterValues`
490 public start(): void {
491 if (this.started
=== false) {
492 if (this.starting
=== false) {
493 this.starting
= true;
494 if (this.getEnableStatistics() === true) {
495 this.performanceStatistics
.start();
497 this.openWSConnection();
498 // Monitor charging station template file
499 this.templateFileWatcher
= FileUtils
.watchJsonFile(
501 FileType
.ChargingStationTemplate
,
504 (event
, filename
): void => {
505 if (filename
&& event
=== 'change') {
508 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
510 } file have changed, reload`
512 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
516 this.stopAutomaticTransactionGenerator();
518 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
520 this.startAutomaticTransactionGenerator();
522 if (this.getEnableStatistics() === true) {
523 this.performanceStatistics
.restart();
525 this.performanceStatistics
.stop();
527 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
530 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
538 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
539 this.starting
= false;
541 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
544 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
548 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
549 if (this.started
=== true) {
550 if (this.stopping
=== false) {
551 this.stopping
= true;
552 await this.stopMessageSequence(reason
);
553 this.closeWSConnection();
554 if (this.getEnableStatistics() === true) {
555 this.performanceStatistics
.stop();
557 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
558 this.templateFileWatcher
.close();
559 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
560 this.bootNotificationResponse
= null;
561 this.started
= false;
562 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
563 this.stopping
= false;
565 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
568 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
572 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
573 await this.stop(reason
);
574 await Utils
.sleep(this.stationInfo
.resetTime
);
579 public saveOcppConfiguration(): void {
580 if (this.getOcppPersistentConfiguration()) {
581 this.saveConfiguration();
585 public resetConnectorStatus(connectorId
: number): void {
586 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
587 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
588 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
589 this.getConnectorStatus(connectorId
).transactionStarted
= false;
590 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
591 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
592 delete this.getConnectorStatus(connectorId
).transactionId
;
593 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
594 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
595 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
596 this.stopMeterValues(connectorId
);
597 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
600 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
601 return ChargingStationConfigurationUtils
.getConfigurationKey(
603 StandardParametersKey
.SupportedFeatureProfiles
604 )?.value
.includes(featureProfile
);
607 public bufferMessage(message
: string): void {
608 this.messageBuffer
.add(message
);
611 public openWSConnection(
612 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
613 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
615 terminateOpened
: false,
618 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
619 params
.closeOpened
= params
?.closeOpened
?? false;
620 params
.terminateOpened
= params
?.terminateOpened
?? false;
621 if (this.started
=== false && this.starting
=== false) {
623 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
628 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
629 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
631 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
633 if (params
?.closeOpened
) {
634 this.closeWSConnection();
636 if (params
?.terminateOpened
) {
637 this.terminateWSConnection();
639 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
640 let protocol
: string;
641 switch (ocppVersion
) {
642 case OCPPVersion
.VERSION_16
:
643 case OCPPVersion
.VERSION_20
:
644 case OCPPVersion
.VERSION_201
:
645 protocol
= 'ocpp' + ocppVersion
;
648 this.handleUnsupportedVersion(ocppVersion
);
652 if (this.isWebSocketConnectionOpened() === true) {
654 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
660 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
663 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
665 // Handle WebSocket message
666 this.wsConnection
.on(
668 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
670 // Handle WebSocket error
671 this.wsConnection
.on(
673 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
675 // Handle WebSocket close
676 this.wsConnection
.on(
678 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
680 // Handle WebSocket open
681 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
682 // Handle WebSocket ping
683 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
684 // Handle WebSocket pong
685 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
688 public closeWSConnection(): void {
689 if (this.isWebSocketConnectionOpened() === true) {
690 this.wsConnection
.close();
691 this.wsConnection
= null;
695 public startAutomaticTransactionGenerator(
696 connectorIds
?: number[],
697 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
699 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
700 automaticTransactionGeneratorConfiguration
??
701 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
704 if (!Utils
.isEmptyArray(connectorIds
)) {
705 for (const connectorId
of connectorIds
) {
706 this.automaticTransactionGenerator
.startConnector(connectorId
);
709 this.automaticTransactionGenerator
.start();
711 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
714 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
715 if (!Utils
.isEmptyArray(connectorIds
)) {
716 for (const connectorId
of connectorIds
) {
717 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
720 this.automaticTransactionGenerator
?.stop();
722 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
725 public async stopTransactionOnConnector(
727 reason
= StopTransactionReason
.NONE
728 ): Promise
<StopTransactionResponse
> {
729 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
731 this.getBeginEndMeterValues() === true &&
732 this.getOcppStrictCompliance() === true &&
733 this.getOutOfOrderEndMeterValues() === false
735 // FIXME: Implement OCPP version agnostic helpers
736 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
739 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
741 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
743 RequestCommand
.METER_VALUES
,
747 meterValue
: [transactionEndMeterValue
],
751 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
753 RequestCommand
.STOP_TRANSACTION
,
756 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
762 private flushMessageBuffer(): void {
763 if (this.messageBuffer
.size
> 0) {
764 this.messageBuffer
.forEach((message
) => {
765 // TODO: evaluate the need to track performance
766 this.wsConnection
.send(message
);
767 this.messageBuffer
.delete(message
);
772 private getSupervisionUrlOcppConfiguration(): boolean {
773 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
776 private getSupervisionUrlOcppKey(): string {
777 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
780 private getTemplateFromFile(): ChargingStationTemplate
| null {
781 let template
: ChargingStationTemplate
= null;
783 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
784 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
786 const measureId
= `${FileType.ChargingStationTemplate} read`;
787 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
788 template
= JSON
.parse(
789 fs
.readFileSync(this.templateFile
, 'utf8')
790 ) as ChargingStationTemplate
;
791 PerformanceStatistics
.endMeasure(measureId
, beginId
);
792 template
.templateHash
= crypto
793 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
794 .update(JSON
.stringify(template
))
796 this.sharedLRUCache
.setChargingStationTemplate(template
);
799 FileUtils
.handleFileException(
801 FileType
.ChargingStationTemplate
,
803 error
as NodeJS
.ErrnoException
809 private getStationInfoFromTemplate(): ChargingStationInfo
{
810 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
811 if (Utils
.isNullOrUndefined(stationTemplate
)) {
812 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
813 logger
.error(`${this.logPrefix()} ${errorMsg}`);
814 throw new BaseError(errorMsg
);
816 if (Utils
.isEmptyObject(stationTemplate
)) {
817 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
818 logger
.error(`${this.logPrefix()} ${errorMsg}`);
819 throw new BaseError(errorMsg
);
821 // Deprecation template keys section
822 ChargingStationUtils
.warnDeprecatedTemplateKey(
827 "Use 'supervisionUrls' instead"
829 ChargingStationUtils
.convertDeprecatedTemplateKey(
834 const stationInfo
: ChargingStationInfo
=
835 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
836 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
837 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
841 stationInfo
.ocppVersion
= stationTemplate
.ocppVersion
?? OCPPVersion
.VERSION_16
;
842 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
843 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
844 stationTemplate
.power
= stationTemplate
.power
as number[];
845 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
846 stationInfo
.maximumPower
=
847 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
848 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
849 : stationTemplate
.power
[powerArrayRandomIndex
];
851 stationTemplate
.power
= stationTemplate
.power
as number;
852 stationInfo
.maximumPower
=
853 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
854 ? stationTemplate
.power
* 1000
855 : stationTemplate
.power
;
857 stationInfo
.firmwareVersionPattern
=
858 stationTemplate
.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
860 stationInfo
.firmwareVersion
&&
861 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
864 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
866 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
869 stationInfo
.firmwareUpgrade
= merge(
873 stationTemplate
.firmwareUpgrade
?? {}
875 stationInfo
.resetTime
= stationTemplate
.resetTime
876 ? stationTemplate
.resetTime
* 1000
877 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
878 const configuredMaxConnectors
=
879 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
880 ChargingStationUtils
.checkConfiguredMaxConnectors(
881 configuredMaxConnectors
,
885 const templateMaxConnectors
=
886 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
887 ChargingStationUtils
.checkTemplateMaxConnectors(
888 templateMaxConnectors
,
893 configuredMaxConnectors
>
894 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
895 !stationTemplate
?.randomConnectors
898 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
900 }, forcing random connector configurations affectation`
902 stationInfo
.randomConnectors
= true;
904 // Build connectors if needed (FIXME: should be factored out)
905 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
906 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
907 ChargingStationUtils
.createStationInfoHash(stationInfo
);
911 private getStationInfoFromFile(): ChargingStationInfo
| null {
912 let stationInfo
: ChargingStationInfo
= null;
913 this.getStationInfoPersistentConfiguration() &&
914 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
915 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
919 private getStationInfo(): ChargingStationInfo
{
920 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
921 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
922 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
923 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
924 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
925 return this.stationInfo
;
927 return stationInfoFromFile
;
929 stationInfoFromFile
&&
930 ChargingStationUtils
.propagateSerialNumber(
931 this.getTemplateFromFile(),
933 stationInfoFromTemplate
935 return stationInfoFromTemplate
;
938 private saveStationInfo(): void {
939 if (this.getStationInfoPersistentConfiguration()) {
940 this.saveConfiguration();
944 private getOcppPersistentConfiguration(): boolean {
945 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
948 private getStationInfoPersistentConfiguration(): boolean {
949 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
952 private handleUnsupportedVersion(version
: OCPPVersion
) {
953 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
954 logger
.error(`${this.logPrefix()} ${errMsg}`);
955 throw new BaseError(errMsg
);
958 private initialize(): void {
959 this.configurationFile
= path
.join(
960 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
961 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
963 this.stationInfo
= this.getStationInfo();
964 this.saveStationInfo();
965 // Avoid duplication of connectors related information in RAM
966 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
967 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
968 if (this.getEnableStatistics() === true) {
969 this.performanceStatistics
= PerformanceStatistics
.getInstance(
970 this.stationInfo
.hashId
,
971 this.stationInfo
.chargingStationId
,
972 this.configuredSupervisionUrl
975 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
978 this.powerDivider
= this.getPowerDivider();
979 // OCPP configuration
980 this.ocppConfiguration
= this.getOcppConfiguration();
981 this.initializeOcppConfiguration();
982 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
983 switch (ocppVersion
) {
984 case OCPPVersion
.VERSION_16
:
985 this.ocppIncomingRequestService
=
986 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
987 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
988 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
991 case OCPPVersion
.VERSION_20
:
992 case OCPPVersion
.VERSION_201
:
993 this.ocppIncomingRequestService
=
994 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
995 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
996 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1000 this.handleUnsupportedVersion(ocppVersion
);
1003 if (this.stationInfo
?.autoRegister
=== true) {
1004 this.bootNotificationResponse
= {
1005 currentTime
: new Date(),
1006 interval
: this.getHeartbeatInterval() / 1000,
1007 status: RegistrationStatusEnumType
.ACCEPTED
,
1011 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1012 this.stationInfo
.firmwareVersion
&&
1013 this.stationInfo
.firmwareVersionPattern
1015 const versionStep
= this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
?? 1;
1016 const patternGroup
: number =
1017 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1018 this.stationInfo
.firmwareVersion
.split('.').length
;
1019 const match
= this.stationInfo
.firmwareVersion
1020 .match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1021 .slice(1, patternGroup
+ 1);
1022 const patchLevelIndex
= match
.length
- 1;
1023 match
[patchLevelIndex
] = (
1024 Utils
.convertToInt(match
[patchLevelIndex
]) + versionStep
1026 this.stationInfo
.firmwareVersion
= match
.join('.');
1030 private initializeOcppConfiguration(): void {
1032 !ChargingStationConfigurationUtils
.getConfigurationKey(
1034 StandardParametersKey
.HeartbeatInterval
1037 ChargingStationConfigurationUtils
.addConfigurationKey(
1039 StandardParametersKey
.HeartbeatInterval
,
1044 !ChargingStationConfigurationUtils
.getConfigurationKey(
1046 StandardParametersKey
.HeartBeatInterval
1049 ChargingStationConfigurationUtils
.addConfigurationKey(
1051 StandardParametersKey
.HeartBeatInterval
,
1057 this.getSupervisionUrlOcppConfiguration() &&
1058 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1060 ChargingStationConfigurationUtils
.addConfigurationKey(
1062 this.getSupervisionUrlOcppKey(),
1063 this.configuredSupervisionUrl
.href
,
1067 !this.getSupervisionUrlOcppConfiguration() &&
1068 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1070 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1072 this.getSupervisionUrlOcppKey(),
1077 this.stationInfo
.amperageLimitationOcppKey
&&
1078 !ChargingStationConfigurationUtils
.getConfigurationKey(
1080 this.stationInfo
.amperageLimitationOcppKey
1083 ChargingStationConfigurationUtils
.addConfigurationKey(
1085 this.stationInfo
.amperageLimitationOcppKey
,
1087 this.stationInfo
.maximumAmperage
*
1088 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1093 !ChargingStationConfigurationUtils
.getConfigurationKey(
1095 StandardParametersKey
.SupportedFeatureProfiles
1098 ChargingStationConfigurationUtils
.addConfigurationKey(
1100 StandardParametersKey
.SupportedFeatureProfiles
,
1101 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1104 ChargingStationConfigurationUtils
.addConfigurationKey(
1106 StandardParametersKey
.NumberOfConnectors
,
1107 this.getNumberOfConnectors().toString(),
1112 !ChargingStationConfigurationUtils
.getConfigurationKey(
1114 StandardParametersKey
.MeterValuesSampledData
1117 ChargingStationConfigurationUtils
.addConfigurationKey(
1119 StandardParametersKey
.MeterValuesSampledData
,
1120 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1124 !ChargingStationConfigurationUtils
.getConfigurationKey(
1126 StandardParametersKey
.ConnectorPhaseRotation
1129 const connectorPhaseRotation
= [];
1130 for (const connectorId
of this.connectors
.keys()) {
1132 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1133 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1134 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1135 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1137 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1138 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1139 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1140 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1143 ChargingStationConfigurationUtils
.addConfigurationKey(
1145 StandardParametersKey
.ConnectorPhaseRotation
,
1146 connectorPhaseRotation
.toString()
1150 !ChargingStationConfigurationUtils
.getConfigurationKey(
1152 StandardParametersKey
.AuthorizeRemoteTxRequests
1155 ChargingStationConfigurationUtils
.addConfigurationKey(
1157 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1162 !ChargingStationConfigurationUtils
.getConfigurationKey(
1164 StandardParametersKey
.LocalAuthListEnabled
1166 ChargingStationConfigurationUtils
.getConfigurationKey(
1168 StandardParametersKey
.SupportedFeatureProfiles
1169 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1171 ChargingStationConfigurationUtils
.addConfigurationKey(
1173 StandardParametersKey
.LocalAuthListEnabled
,
1178 !ChargingStationConfigurationUtils
.getConfigurationKey(
1180 StandardParametersKey
.ConnectionTimeOut
1183 ChargingStationConfigurationUtils
.addConfigurationKey(
1185 StandardParametersKey
.ConnectionTimeOut
,
1186 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1189 this.saveOcppConfiguration();
1192 private initializeConnectors(
1193 stationInfo
: ChargingStationInfo
,
1194 configuredMaxConnectors
: number,
1195 templateMaxConnectors
: number
1197 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1198 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1199 logger
.error(`${this.logPrefix()} ${logMsg}`);
1200 throw new BaseError(logMsg
);
1202 if (!stationInfo
?.Connectors
[0]) {
1204 `${this.logPrefix()} Charging station information from template ${
1206 } with no connector Id 0 configuration`
1209 if (stationInfo
?.Connectors
) {
1210 const connectorsConfigHash
= crypto
1211 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1212 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1214 const connectorsConfigChanged
=
1215 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1216 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1217 connectorsConfigChanged
&& this.connectors
.clear();
1218 this.connectorsConfigurationHash
= connectorsConfigHash
;
1219 // Add connector Id 0
1220 let lastConnector
= '0';
1221 for (lastConnector
in stationInfo
?.Connectors
) {
1222 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1223 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1225 lastConnectorId
=== 0 &&
1226 this.getUseConnectorId0(stationInfo
) === true &&
1229 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1230 this.connectors
.set(
1232 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1234 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1235 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1236 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1240 // Generate all connectors
1241 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1242 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1243 const randConnectorId
= stationInfo
?.randomConnectors
1244 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1246 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1247 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1248 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1249 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1250 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1251 this.getConnectorStatus(index
).chargingProfiles
= [];
1258 `${this.logPrefix()} Charging station information from template ${
1260 } with no connectors configuration defined, using already defined connectors`
1263 // Initialize transaction attributes on connectors
1264 for (const connectorId
of this.connectors
.keys()) {
1265 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionStarted
=== true) {
1267 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1268 this.getConnectorStatus(connectorId).transactionId
1274 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1275 this.getConnectorStatus(connectorId
).transactionStarted
=== null)
1277 this.initializeConnectorStatus(connectorId
);
1282 private checkStationInfoConnectorStatus(
1283 connectorId
: number,
1284 connectorStatus
: ConnectorStatus
1286 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1288 `${this.logPrefix()} Charging station information from template ${
1290 } with connector ${connectorId} status configuration defined, undefine it`
1292 connectorStatus
.status = undefined;
1296 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1297 let configuration
: ChargingStationConfiguration
= null;
1298 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1300 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1301 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1302 this.configurationFileHash
1305 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1306 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1307 configuration
= JSON
.parse(
1308 fs
.readFileSync(this.configurationFile
, 'utf8')
1309 ) as ChargingStationConfiguration
;
1310 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1311 this.configurationFileHash
= configuration
.configurationHash
;
1312 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1315 FileUtils
.handleFileException(
1317 FileType
.ChargingStationConfiguration
,
1318 this.configurationFile
,
1319 error
as NodeJS
.ErrnoException
1323 return configuration
;
1326 private saveConfiguration(): void {
1327 if (this.configurationFile
) {
1329 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1330 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1332 const configurationData
: ChargingStationConfiguration
=
1333 this.getConfigurationFromFile() ?? {};
1334 this.ocppConfiguration
?.configurationKey
&&
1335 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1336 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1337 delete configurationData
.configurationHash
;
1338 const configurationHash
= crypto
1339 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1340 .update(JSON
.stringify(configurationData
))
1342 if (this.configurationFileHash
!== configurationHash
) {
1343 configurationData
.configurationHash
= configurationHash
;
1344 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1345 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1346 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1347 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1348 fs
.closeSync(fileDescriptor
);
1349 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1350 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1351 this.configurationFileHash
= configurationHash
;
1352 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1355 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1356 this.configurationFile
1361 FileUtils
.handleFileException(
1363 FileType
.ChargingStationConfiguration
,
1364 this.configurationFile
,
1365 error
as NodeJS
.ErrnoException
1370 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1375 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1376 return this.getTemplateFromFile()?.Configuration
?? null;
1379 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1380 let configuration
: ChargingStationConfiguration
= null;
1381 if (this.getOcppPersistentConfiguration() === true) {
1382 const configurationFromFile
= this.getConfigurationFromFile();
1383 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1385 configuration
&& delete configuration
.stationInfo
;
1386 return configuration
;
1389 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1390 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1391 if (!ocppConfiguration
) {
1392 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1394 return ocppConfiguration
;
1397 private async onOpen(): Promise
<void> {
1398 if (this.isWebSocketConnectionOpened() === true) {
1400 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1402 if (this.isRegistered() === false) {
1403 // Send BootNotification
1404 let registrationRetryCount
= 0;
1406 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1407 BootNotificationRequest
,
1408 BootNotificationResponse
1409 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1410 skipBufferingOnError
: true,
1412 if (this.isRegistered() === false) {
1413 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1415 this.bootNotificationResponse
?.interval
1416 ? this.bootNotificationResponse
.interval
* 1000
1417 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1421 this.isRegistered() === false &&
1422 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1423 this.getRegistrationMaxRetries() === -1)
1426 if (this.isRegistered() === true) {
1427 if (this.isInAcceptedState() === true) {
1428 await this.startMessageSequence();
1432 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1435 this.wsConnectionRestarted
= false;
1436 this.autoReconnectRetryCount
= 0;
1437 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1440 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1445 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1448 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1449 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1451 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1453 )}' and reason '${reason.toString()}'`
1455 this.autoReconnectRetryCount
= 0;
1460 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1462 )}' and reason '${reason.toString()}'`
1464 this.started
=== true && (await this.reconnect());
1467 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1470 private async onMessage(data
: RawData
): Promise
<void> {
1471 let messageType
: number;
1472 let messageId
: string;
1473 let commandName
: IncomingRequestCommand
;
1474 let commandPayload
: JsonType
;
1475 let errorType
: ErrorType
;
1476 let errorMessage
: string;
1477 let errorDetails
: JsonType
;
1478 let responseCallback
: ResponseCallback
;
1479 let errorCallback
: ErrorCallback
;
1480 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1481 let requestPayload
: JsonType
;
1482 let cachedRequest
: CachedRequest
;
1485 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1486 if (Array.isArray(request
) === true) {
1487 [messageType
, messageId
] = request
;
1488 // Check the type of message
1489 switch (messageType
) {
1491 case MessageType
.CALL_MESSAGE
:
1492 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1493 if (this.getEnableStatistics() === true) {
1494 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1497 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1501 // Process the message
1502 await this.ocppIncomingRequestService
.incomingRequestHandler(
1510 case MessageType
.CALL_RESULT_MESSAGE
:
1511 [, , commandPayload
] = request
as Response
;
1512 if (this.requests
.has(messageId
) === false) {
1514 throw new OCPPError(
1515 ErrorType
.INTERNAL_ERROR
,
1516 `Response for unknown message id ${messageId}`,
1522 cachedRequest
= this.requests
.get(messageId
);
1523 if (Array.isArray(cachedRequest
) === true) {
1524 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1526 throw new OCPPError(
1527 ErrorType
.PROTOCOL_ERROR
,
1528 `Cached request for message id ${messageId} response is not an array`,
1530 cachedRequest
as unknown
as JsonType
1534 `${this.logPrefix()} << Command '${
1535 requestCommandName ?? Constants.UNKNOWN_COMMAND
1536 }' received response payload: ${JSON.stringify(request)}`
1538 responseCallback(commandPayload
, requestPayload
);
1541 case MessageType
.CALL_ERROR_MESSAGE
:
1542 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1543 if (this.requests
.has(messageId
) === false) {
1545 throw new OCPPError(
1546 ErrorType
.INTERNAL_ERROR
,
1547 `Error response for unknown message id ${messageId}`,
1549 { errorType
, errorMessage
, errorDetails
}
1552 cachedRequest
= this.requests
.get(messageId
);
1553 if (Array.isArray(cachedRequest
) === true) {
1554 [, errorCallback
, requestCommandName
] = cachedRequest
;
1556 throw new OCPPError(
1557 ErrorType
.PROTOCOL_ERROR
,
1558 `Cached request for message id ${messageId} error response is not an array`,
1560 cachedRequest
as unknown
as JsonType
1564 `${this.logPrefix()} << Command '${
1565 requestCommandName ?? Constants.UNKNOWN_COMMAND
1566 }' received error payload: ${JSON.stringify(request)}`
1568 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1572 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1573 errMsg
= `Wrong message type ${messageType}`;
1574 logger
.error(`${this.logPrefix()} ${errMsg}`);
1575 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1577 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1579 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1586 `${this.logPrefix()} Incoming OCPP command '${
1587 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1588 }' message '${data.toString()}'${
1589 messageType !== MessageType.CALL_MESSAGE
1590 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1592 } processing error:`,
1595 if (error
instanceof OCPPError
=== false) {
1597 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1598 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1599 }' message '${data.toString()}' handling is not an OCPPError:`,
1603 switch (messageType
) {
1604 case MessageType
.CALL_MESSAGE
:
1606 await this.ocppRequestService
.sendError(
1610 commandName
?? requestCommandName
?? null
1613 case MessageType
.CALL_RESULT_MESSAGE
:
1614 case MessageType
.CALL_ERROR_MESSAGE
:
1615 if (errorCallback
) {
1616 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1617 errorCallback(error
as OCPPError
, false);
1619 // Remove the request from the cache in case of error at response handling
1620 this.requests
.delete(messageId
);
1627 private onPing(): void {
1628 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1631 private onPong(): void {
1632 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1635 private onError(error
: WSError
): void {
1636 this.closeWSConnection();
1637 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1640 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1641 if (this.getMeteringPerTransaction() === true) {
1644 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1645 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1650 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1651 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1655 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1656 const localStationInfo
= stationInfo
?? this.stationInfo
;
1657 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1658 ? localStationInfo
.useConnectorId0
1662 private getNumberOfRunningTransactions(): number {
1664 for (const connectorId
of this.connectors
.keys()) {
1665 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1672 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1673 for (const connectorId
of this.connectors
.keys()) {
1674 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1675 await this.stopTransactionOnConnector(connectorId
, reason
);
1681 private getConnectionTimeout(): number {
1683 ChargingStationConfigurationUtils
.getConfigurationKey(
1685 StandardParametersKey
.ConnectionTimeOut
1690 ChargingStationConfigurationUtils
.getConfigurationKey(
1692 StandardParametersKey
.ConnectionTimeOut
1694 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1697 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1700 // -1 for unlimited, 0 for disabling
1701 private getAutoReconnectMaxRetries(): number {
1702 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1703 return this.stationInfo
.autoReconnectMaxRetries
;
1705 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1706 return Configuration
.getAutoReconnectMaxRetries();
1712 private getRegistrationMaxRetries(): number {
1713 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1714 return this.stationInfo
.registrationMaxRetries
;
1719 private getPowerDivider(): number {
1720 let powerDivider
= this.getNumberOfConnectors();
1721 if (this.stationInfo
?.powerSharedByConnectors
) {
1722 powerDivider
= this.getNumberOfRunningTransactions();
1724 return powerDivider
;
1727 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1728 const localStationInfo
= stationInfo
?? this.stationInfo
;
1729 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1732 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1733 const maximumPower
= this.getMaximumPower(stationInfo
);
1734 switch (this.getCurrentOutType(stationInfo
)) {
1735 case CurrentType
.AC
:
1736 return ACElectricUtils
.amperagePerPhaseFromPower(
1737 this.getNumberOfPhases(stationInfo
),
1738 maximumPower
/ this.getNumberOfConnectors(),
1739 this.getVoltageOut(stationInfo
)
1741 case CurrentType
.DC
:
1742 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1746 private getAmperageLimitation(): number | undefined {
1748 this.stationInfo
.amperageLimitationOcppKey
&&
1749 ChargingStationConfigurationUtils
.getConfigurationKey(
1751 this.stationInfo
.amperageLimitationOcppKey
1756 ChargingStationConfigurationUtils
.getConfigurationKey(
1758 this.stationInfo
.amperageLimitationOcppKey
1760 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1765 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1766 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1767 let chargingProfiles
: ChargingProfile
[] = [];
1768 // Get charging profiles for connector and sort by stack level
1769 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1770 (a
, b
) => b
.stackLevel
- a
.stackLevel
1772 // Get profiles on connector 0
1773 if (this.getConnectorStatus(0).chargingProfiles
) {
1774 chargingProfiles
.push(
1775 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1778 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1779 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1783 if (!Utils
.isNullOrUndefined(result
)) {
1784 limit
= result
.limit
;
1785 matchingChargingProfile
= result
.matchingChargingProfile
;
1786 switch (this.getCurrentOutType()) {
1787 case CurrentType
.AC
:
1789 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1790 ChargingRateUnitType
.WATT
1792 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1794 case CurrentType
.DC
:
1796 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1797 ChargingRateUnitType
.WATT
1799 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1801 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1802 if (limit
> connectorMaximumPower
) {
1804 `${this.logPrefix()} Charging profile id ${
1805 matchingChargingProfile.chargingProfileId
1806 } limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
1809 limit
= connectorMaximumPower
;
1816 private async startMessageSequence(): Promise
<void> {
1817 if (this.stationInfo
?.autoRegister
=== true) {
1818 await this.ocppRequestService
.requestHandler
<
1819 BootNotificationRequest
,
1820 BootNotificationResponse
1821 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1822 skipBufferingOnError
: true,
1825 // Start WebSocket ping
1826 this.startWebSocketPing();
1828 this.startHeartbeat();
1829 // Initialize connectors status
1830 for (const connectorId
of this.connectors
.keys()) {
1831 let connectorStatus
: ConnectorStatusEnum
;
1832 if (connectorId
=== 0) {
1835 !this.getConnectorStatus(connectorId
)?.status &&
1836 (this.isChargingStationAvailable() === false ||
1837 this.isConnectorAvailable(connectorId
) === false)
1839 connectorStatus
= ConnectorStatusEnum
.UNAVAILABLE
;
1841 !this.getConnectorStatus(connectorId
)?.status &&
1842 this.getConnectorStatus(connectorId
)?.bootStatus
1844 // Set boot status in template at startup
1845 connectorStatus
= this.getConnectorStatus(connectorId
).bootStatus
;
1846 } else if (this.getConnectorStatus(connectorId
)?.status) {
1847 // Set previous status at startup
1848 connectorStatus
= this.getConnectorStatus(connectorId
).status;
1850 // Set default status
1851 connectorStatus
= ConnectorStatusEnum
.AVAILABLE
;
1853 await this.ocppRequestService
.requestHandler
<
1854 StatusNotificationRequest
,
1855 StatusNotificationResponse
1858 RequestCommand
.STATUS_NOTIFICATION
,
1859 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1861 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1863 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1864 await this.ocppRequestService
.requestHandler
<
1865 FirmwareStatusNotificationRequest
,
1866 FirmwareStatusNotificationResponse
1867 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1868 status: FirmwareStatus
.Installed
,
1870 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1874 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1875 this.startAutomaticTransactionGenerator();
1877 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1880 private async stopMessageSequence(
1881 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1883 // Stop WebSocket ping
1884 this.stopWebSocketPing();
1886 this.stopHeartbeat();
1887 // Stop ongoing transactions
1888 if (this.automaticTransactionGenerator
?.started
=== true) {
1889 this.stopAutomaticTransactionGenerator();
1891 await this.stopRunningTransactions(reason
);
1893 for (const connectorId
of this.connectors
.keys()) {
1894 if (connectorId
> 0) {
1895 await this.ocppRequestService
.requestHandler
<
1896 StatusNotificationRequest
,
1897 StatusNotificationResponse
1900 RequestCommand
.STATUS_NOTIFICATION
,
1901 OCPPServiceUtils
.buildStatusNotificationRequest(
1904 ConnectorStatusEnum
.UNAVAILABLE
1907 this.getConnectorStatus(connectorId
).status = null;
1912 private startWebSocketPing(): void {
1913 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1915 StandardParametersKey
.WebSocketPingInterval
1917 ? Utils
.convertToInt(
1918 ChargingStationConfigurationUtils
.getConfigurationKey(
1920 StandardParametersKey
.WebSocketPingInterval
1924 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1925 this.webSocketPingSetInterval
= setInterval(() => {
1926 if (this.isWebSocketConnectionOpened() === true) {
1927 this.wsConnection
.ping();
1929 }, webSocketPingInterval
* 1000);
1932 ' WebSocket ping started every ' +
1933 Utils
.formatDurationSeconds(webSocketPingInterval
)
1935 } else if (this.webSocketPingSetInterval
) {
1938 ' WebSocket ping already started every ' +
1939 Utils
.formatDurationSeconds(webSocketPingInterval
)
1943 `${this.logPrefix()} WebSocket ping interval set to ${
1944 webSocketPingInterval
1945 ? Utils.formatDurationSeconds(webSocketPingInterval)
1946 : webSocketPingInterval
1947 }, not starting the WebSocket ping`
1952 private stopWebSocketPing(): void {
1953 if (this.webSocketPingSetInterval
) {
1954 clearInterval(this.webSocketPingSetInterval
);
1958 private getConfiguredSupervisionUrl(): URL
{
1959 const supervisionUrls
= this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls();
1960 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1961 switch (Configuration
.getSupervisionUrlDistribution()) {
1962 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1964 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1966 case SupervisionUrlDistribution
.RANDOM
:
1967 this.configuredSupervisionUrlIndex
= Math.floor(
1968 Utils
.secureRandom() * supervisionUrls
.length
1971 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1972 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1976 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1977 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1980 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1983 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1985 return new URL(supervisionUrls
as string);
1988 private getHeartbeatInterval(): number {
1989 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1991 StandardParametersKey
.HeartbeatInterval
1993 if (HeartbeatInterval
) {
1994 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1996 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1998 StandardParametersKey
.HeartBeatInterval
2000 if (HeartBeatInterval
) {
2001 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
2003 this.stationInfo
?.autoRegister
=== false &&
2005 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2006 Constants.DEFAULT_HEARTBEAT_INTERVAL
2009 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
2012 private stopHeartbeat(): void {
2013 if (this.heartbeatSetInterval
) {
2014 clearInterval(this.heartbeatSetInterval
);
2018 private terminateWSConnection(): void {
2019 if (this.isWebSocketConnectionOpened() === true) {
2020 this.wsConnection
.terminate();
2021 this.wsConnection
= null;
2025 private stopMeterValues(connectorId
: number) {
2026 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2027 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2031 private getReconnectExponentialDelay(): boolean {
2032 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2033 ? this.stationInfo
.reconnectExponentialDelay
2037 private async reconnect(): Promise
<void> {
2038 // Stop WebSocket ping
2039 this.stopWebSocketPing();
2041 this.stopHeartbeat();
2042 // Stop the ATG if needed
2043 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2044 this.stopAutomaticTransactionGenerator();
2047 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2048 this.getAutoReconnectMaxRetries() === -1
2050 this.autoReconnectRetryCount
++;
2051 const reconnectDelay
= this.getReconnectExponentialDelay()
2052 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2053 : this.getConnectionTimeout() * 1000;
2054 const reconnectDelayWithdraw
= 1000;
2055 const reconnectTimeout
=
2056 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2057 ? reconnectDelay
- reconnectDelayWithdraw
2060 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2063 )}ms, timeout ${reconnectTimeout}ms`
2065 await Utils
.sleep(reconnectDelay
);
2067 this.logPrefix() + ' WebSocket connection retry #' + this.autoReconnectRetryCount
.toString()
2069 this.openWSConnection(
2070 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2071 { closeOpened
: true }
2073 this.wsConnectionRestarted
= true;
2074 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2076 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2077 this.autoReconnectRetryCount
2078 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2083 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2084 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2087 private initializeConnectorStatus(connectorId
: number): void {
2088 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2089 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2090 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2091 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2092 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2093 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;