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
'node:worker_threads';
9 import merge from
'just-merge';
10 import WebSocket
, { type RawData
} from
'ws';
12 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
13 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
14 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
15 import { ChargingStationUtils
} from
'./ChargingStationUtils';
16 import { IdTagsCache
} from
'./IdTagsCache';
18 OCPP16IncomingRequestService
,
20 OCPP16ResponseService
,
22 OCPP20IncomingRequestService
,
24 OCPP20ResponseService
,
25 type OCPPIncomingRequestService
,
26 type OCPPRequestService
,
29 import { SharedLRUCache
} from
'./SharedLRUCache';
30 import { BaseError
, OCPPError
} from
'../exception';
31 import { PerformanceStatistics
} from
'../performance';
33 type AutomaticTransactionGeneratorConfiguration
,
35 type BootNotificationRequest
,
36 type BootNotificationResponse
,
38 type ChargingStationConfiguration
,
39 type ChargingStationInfo
,
40 type ChargingStationOcppConfiguration
,
41 type ChargingStationTemplate
,
49 type EvseStatusConfiguration
,
52 type FirmwareStatusNotificationRequest
,
53 type FirmwareStatusNotificationResponse
,
55 type HeartbeatRequest
,
56 type HeartbeatResponse
,
58 type IncomingRequestCommand
,
63 type MeterValuesRequest
,
64 type MeterValuesResponse
,
68 RegistrationStatusEnumType
,
71 StandardParametersKey
,
73 type StatusNotificationRequest
,
74 type StatusNotificationResponse
,
75 StopTransactionReason
,
76 type StopTransactionRequest
,
77 type StopTransactionResponse
,
78 SupervisionUrlDistribution
,
79 SupportedFeatureProfiles
,
82 WebSocketCloseEventStatusCode
,
96 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
97 buildConnectorsStatus
,
102 export class ChargingStation
{
103 public readonly index
: number;
104 public readonly templateFile
: string;
105 public stationInfo
!: ChargingStationInfo
;
106 public started
: boolean;
107 public starting
: boolean;
108 public idTagsCache
: IdTagsCache
;
109 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
110 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
111 public wsConnection
!: WebSocket
| null;
112 public readonly connectors
: Map
<number, ConnectorStatus
>;
113 public readonly evses
: Map
<number, EvseStatus
>;
114 public readonly requests
: Map
<string, CachedRequest
>;
115 public performanceStatistics
!: PerformanceStatistics
| undefined;
116 public heartbeatSetInterval
!: NodeJS
.Timeout
;
117 public ocppRequestService
!: OCPPRequestService
;
118 public bootNotificationRequest
!: BootNotificationRequest
;
119 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
120 public powerDivider
!: number;
121 private stopping
: boolean;
122 private configurationFile
!: string;
123 private configurationFileHash
!: string;
124 private connectorsConfigurationHash
!: string;
125 private evsesConfigurationHash
!: string;
126 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
127 private readonly messageBuffer
: Set
<string>;
128 private configuredSupervisionUrl
!: URL
;
129 private wsConnectionRestarted
: boolean;
130 private autoReconnectRetryCount
: number;
131 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
132 private templateFileHash
!: string;
133 private readonly sharedLRUCache
: SharedLRUCache
;
134 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
135 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
137 constructor(index
: number, templateFile
: string) {
138 this.started
= false;
139 this.starting
= false;
140 this.stopping
= false;
141 this.wsConnectionRestarted
= false;
142 this.autoReconnectRetryCount
= 0;
144 this.templateFile
= templateFile
;
145 this.connectors
= new Map
<number, ConnectorStatus
>();
146 this.evses
= new Map
<number, EvseStatus
>();
147 this.requests
= new Map
<string, CachedRequest
>();
148 this.messageBuffer
= new Set
<string>();
149 this.sharedLRUCache
= SharedLRUCache
.getInstance();
150 this.idTagsCache
= IdTagsCache
.getInstance();
151 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
156 public get
hasEvses(): boolean {
157 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
160 private get
wsConnectionUrl(): URL
{
163 this.getSupervisionUrlOcppConfiguration() &&
164 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
165 Utils.isNotEmptyString(
166 ChargingStationConfigurationUtils.getConfigurationKey(
168 this.getSupervisionUrlOcppKey()
171 ? ChargingStationConfigurationUtils.getConfigurationKey(
173 this.getSupervisionUrlOcppKey()
175 : this.configuredSupervisionUrl.href
176 }/${this.stationInfo.chargingStationId}`
180 public logPrefix
= (): string => {
181 return Utils
.logPrefix(
183 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId)
184 ? this?.stationInfo?.chargingStationId
185 : ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())) ??
186 'Error at building log prefix'
191 public hasIdTags(): boolean {
192 return Utils
.isNotEmptyArray(
193 this.idTagsCache
.getIdTags(ChargingStationUtils
.getIdTagsFile(this.stationInfo
))
197 public getEnableStatistics(): boolean {
198 return this.stationInfo
.enableStatistics
?? false;
201 public getMustAuthorizeAtRemoteStart(): boolean {
202 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
205 public getPayloadSchemaValidation(): boolean {
206 return this.stationInfo
.payloadSchemaValidation
?? true;
209 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
210 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
211 switch (this.getCurrentOutType(stationInfo
)) {
213 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
214 ? localStationInfo
.numberOfPhases
221 public isWebSocketConnectionOpened(): boolean {
222 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
225 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
226 return this?.bootNotificationResponse
?.status;
229 public inUnknownState(): boolean {
230 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
233 public inPendingState(): boolean {
234 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
237 public inAcceptedState(): boolean {
238 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
241 public inRejectedState(): boolean {
242 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
245 public isRegistered(): boolean {
247 this.inUnknownState() === false &&
248 (this.inAcceptedState() === true || this.inPendingState() === true)
252 public isChargingStationAvailable(): boolean {
253 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
256 public hasConnector(connectorId
: number): boolean {
258 for (const evseStatus
of this.evses
.values()) {
259 if (evseStatus
.connectors
.has(connectorId
)) {
265 return this.connectors
.has(connectorId
);
268 public isConnectorAvailable(connectorId
: number): boolean {
271 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
275 public getNumberOfConnectors(): number {
277 if (this.evses
.size
=== 0) {
278 throw new BaseError('Evses not initialized, cannot get number of connectors');
280 let numberOfConnectors
= 0;
281 for (const [evseId
, evseStatus
] of this.evses
) {
283 numberOfConnectors
+= evseStatus
.connectors
.size
;
286 return numberOfConnectors
;
288 if (this.connectors
.size
=== 0) {
289 throw new BaseError('Connectors not initialized, cannot get number of connectors');
291 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
294 public getNumberOfEvses(): number {
295 if (this.evses
.size
=== 0) {
296 throw new BaseError('Evses not initialized, cannot get number of evses');
298 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
301 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
303 for (const evseStatus
of this.evses
.values()) {
304 if (evseStatus
.connectors
.has(connectorId
)) {
305 return evseStatus
.connectors
.get(connectorId
);
310 return this.connectors
.get(connectorId
);
313 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
314 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
317 public getOcppStrictCompliance(): boolean {
318 return this.stationInfo
?.ocppStrictCompliance
?? false;
321 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
322 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
323 this.getCurrentOutType(stationInfo
),
327 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
330 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
331 const localStationInfo
= stationInfo
?? this.stationInfo
;
332 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
335 public getConnectorMaximumAvailablePower(connectorId
: number): number {
336 let connectorAmperageLimitationPowerLimit
: number;
338 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
339 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
341 connectorAmperageLimitationPowerLimit
=
342 (this.getCurrentOutType() === CurrentType
.AC
343 ? ACElectricUtils
.powerTotal(
344 this.getNumberOfPhases(),
345 this.getVoltageOut(),
346 this.getAmperageLimitation() *
347 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
349 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
352 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
353 const connectorChargingProfilesPowerLimit
=
354 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
356 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
357 isNaN(connectorAmperageLimitationPowerLimit
)
359 : connectorAmperageLimitationPowerLimit
,
360 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
364 public getTransactionIdTag(transactionId
: number): string | undefined {
366 for (const evseStatus
of this.evses
.values()) {
367 for (const connectorStatus
of evseStatus
.connectors
.values()) {
368 if (connectorStatus
.transactionId
=== transactionId
) {
369 return connectorStatus
.transactionIdTag
;
374 for (const connectorId
of this.connectors
.keys()) {
377 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
379 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
385 public getNumberOfRunningTransactions(): number {
388 for (const evseStatus
of this.evses
.values()) {
389 for (const connectorStatus
of evseStatus
.connectors
.values()) {
390 if (connectorStatus
.transactionStarted
=== true) {
396 for (const connectorId
of this.connectors
.keys()) {
397 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
405 public getOutOfOrderEndMeterValues(): boolean {
406 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
409 public getBeginEndMeterValues(): boolean {
410 return this.stationInfo
?.beginEndMeterValues
?? false;
413 public getMeteringPerTransaction(): boolean {
414 return this.stationInfo
?.meteringPerTransaction
?? true;
417 public getTransactionDataMeterValues(): boolean {
418 return this.stationInfo
?.transactionDataMeterValues
?? false;
421 public getMainVoltageMeterValues(): boolean {
422 return this.stationInfo
?.mainVoltageMeterValues
?? true;
425 public getPhaseLineToLineVoltageMeterValues(): boolean {
426 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
429 public getCustomValueLimitationMeterValues(): boolean {
430 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
433 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
435 for (const evseStatus
of this.evses
.values()) {
436 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
437 if (connectorStatus
.transactionId
=== transactionId
) {
443 for (const connectorId
of this.connectors
.keys()) {
446 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
454 public getEnergyActiveImportRegisterByTransactionId(
455 transactionId
: number,
458 return this.getEnergyActiveImportRegister(
459 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
464 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
465 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
468 public getAuthorizeRemoteTxRequests(): boolean {
469 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
471 StandardParametersKey
.AuthorizeRemoteTxRequests
473 return authorizeRemoteTxRequests
474 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
478 public getLocalAuthListEnabled(): boolean {
479 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
481 StandardParametersKey
.LocalAuthListEnabled
483 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
486 public getHeartbeatInterval(): number {
487 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
489 StandardParametersKey
.HeartbeatInterval
491 if (HeartbeatInterval
) {
492 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
494 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
496 StandardParametersKey
.HeartBeatInterval
498 if (HeartBeatInterval
) {
499 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
501 this.stationInfo
?.autoRegister
=== false &&
503 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
504 Constants.DEFAULT_HEARTBEAT_INTERVAL
507 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
510 public setSupervisionUrl(url
: string): void {
512 this.getSupervisionUrlOcppConfiguration() &&
513 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey())
515 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
517 this.getSupervisionUrlOcppKey(),
521 this.stationInfo
.supervisionUrls
= url
;
522 this.saveStationInfo();
523 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
527 public startHeartbeat(): void {
528 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
529 this.heartbeatSetInterval
= setInterval(() => {
530 this.ocppRequestService
531 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
534 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
538 }, this.getHeartbeatInterval());
540 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
541 this.getHeartbeatInterval()
544 } else if (this.heartbeatSetInterval
) {
546 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
547 this.getHeartbeatInterval()
552 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
557 public restartHeartbeat(): void {
559 this.stopHeartbeat();
561 this.startHeartbeat();
564 public restartWebSocketPing(): void {
565 // Stop WebSocket ping
566 this.stopWebSocketPing();
567 // Start WebSocket ping
568 this.startWebSocketPing();
571 public startMeterValues(connectorId
: number, interval
: number): void {
572 if (connectorId
=== 0) {
574 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
578 if (!this.getConnectorStatus(connectorId
)) {
580 `${this.logPrefix()} Trying to start MeterValues on non existing connector id ${connectorId.toString()}`
584 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
586 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
590 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
591 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
594 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
599 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
600 // FIXME: Implement OCPP version agnostic helpers
601 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
604 this.getConnectorStatus(connectorId
).transactionId
,
607 this.ocppRequestService
608 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
610 RequestCommand
.METER_VALUES
,
613 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
614 meterValue
: [meterValue
],
619 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
626 `${this.logPrefix()} Charging station ${
627 StandardParametersKey.MeterValueSampleInterval
628 } configuration set to ${interval}, not sending MeterValues`
633 public stopMeterValues(connectorId
: number) {
634 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
635 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
639 public start(): void {
640 if (this.started
=== false) {
641 if (this.starting
=== false) {
642 this.starting
= true;
643 if (this.getEnableStatistics() === true) {
644 this.performanceStatistics
?.start();
646 this.openWSConnection();
647 // Monitor charging station template file
648 this.templateFileWatcher
= FileUtils
.watchJsonFile(
650 FileType
.ChargingStationTemplate
,
653 (event
, filename
): void => {
654 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
657 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
659 } file have changed, reload`
661 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
665 this.stopAutomaticTransactionGenerator();
666 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
667 this.startAutomaticTransactionGenerator();
669 if (this.getEnableStatistics() === true) {
670 this.performanceStatistics
?.restart();
672 this.performanceStatistics
?.stop();
674 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
677 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
685 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
686 this.starting
= false;
688 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
691 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
695 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
696 if (this.started
=== true) {
697 if (this.stopping
=== false) {
698 this.stopping
= true;
699 await this.stopMessageSequence(reason
);
700 this.closeWSConnection();
701 if (this.getEnableStatistics() === true) {
702 this.performanceStatistics
?.stop();
704 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
705 this.templateFileWatcher
?.close();
706 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
707 delete this.bootNotificationResponse
;
708 this.started
= false;
709 this.saveConfiguration();
710 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
711 this.stopping
= false;
713 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
716 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
720 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
721 await this.stop(reason
);
722 await Utils
.sleep(this.stationInfo
.resetTime
);
727 public saveOcppConfiguration(): void {
728 if (this.getOcppPersistentConfiguration()) {
729 this.saveConfiguration();
733 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
734 return ChargingStationConfigurationUtils
.getConfigurationKey(
736 StandardParametersKey
.SupportedFeatureProfiles
737 )?.value
?.includes(featureProfile
);
740 public bufferMessage(message
: string): void {
741 this.messageBuffer
.add(message
);
744 public openWSConnection(
745 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
746 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
748 terminateOpened
: false,
751 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
752 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
753 if (this.started
=== false && this.starting
=== false) {
755 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
760 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
761 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
763 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
765 if (params
?.closeOpened
) {
766 this.closeWSConnection();
768 if (params
?.terminateOpened
) {
769 this.terminateWSConnection();
772 if (this.isWebSocketConnectionOpened() === true) {
774 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
780 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
783 this.wsConnection
= new WebSocket(
784 this.wsConnectionUrl
,
785 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
789 // Handle WebSocket message
790 this.wsConnection
.on(
792 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
794 // Handle WebSocket error
795 this.wsConnection
.on(
797 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
799 // Handle WebSocket close
800 this.wsConnection
.on(
802 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
804 // Handle WebSocket open
805 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
806 // Handle WebSocket ping
807 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
808 // Handle WebSocket pong
809 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
812 public closeWSConnection(): void {
813 if (this.isWebSocketConnectionOpened() === true) {
814 this.wsConnection
?.close();
815 this.wsConnection
= null;
819 public getAutomaticTransactionGeneratorConfiguration():
820 | AutomaticTransactionGeneratorConfiguration
822 let automaticTransactionGeneratorConfiguration
:
823 | AutomaticTransactionGeneratorConfiguration
825 const automaticTransactionGeneratorConfigurationFromFile
=
826 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
828 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
829 automaticTransactionGeneratorConfigurationFromFile
831 automaticTransactionGeneratorConfiguration
=
832 automaticTransactionGeneratorConfigurationFromFile
;
834 automaticTransactionGeneratorConfiguration
=
835 this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
838 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
839 ...automaticTransactionGeneratorConfiguration
,
843 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
844 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
847 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
848 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
849 if (Utils
.isNotEmptyArray(connectorIds
)) {
850 for (const connectorId
of connectorIds
) {
851 this.automaticTransactionGenerator
?.startConnector(connectorId
);
854 this.automaticTransactionGenerator
?.start();
856 this.saveChargingStationAutomaticTransactionGeneratorConfiguration();
857 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
860 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
861 if (Utils
.isNotEmptyArray(connectorIds
)) {
862 for (const connectorId
of connectorIds
) {
863 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
866 this.automaticTransactionGenerator
?.stop();
868 this.saveChargingStationAutomaticTransactionGeneratorConfiguration();
869 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
872 public async stopTransactionOnConnector(
874 reason
= StopTransactionReason
.NONE
875 ): Promise
<StopTransactionResponse
> {
876 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
878 this.getBeginEndMeterValues() === true &&
879 this.getOcppStrictCompliance() === true &&
880 this.getOutOfOrderEndMeterValues() === false
882 // FIXME: Implement OCPP version agnostic helpers
883 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
886 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
888 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
890 RequestCommand
.METER_VALUES
,
894 meterValue
: [transactionEndMeterValue
],
898 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
900 RequestCommand
.STOP_TRANSACTION
,
903 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
909 private flushMessageBuffer(): void {
910 if (this.messageBuffer
.size
> 0) {
911 for (const message
of this.messageBuffer
.values()) {
913 let commandName
: RequestCommand
;
914 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
915 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
917 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
918 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
920 this.wsConnection
?.send(message
);
921 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
923 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
925 )} payload sent: ${message}`
927 this.messageBuffer
.delete(message
);
932 private getSupervisionUrlOcppConfiguration(): boolean {
933 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
936 private getSupervisionUrlOcppKey(): string {
937 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
940 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
941 let template
: ChargingStationTemplate
;
943 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
944 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
946 const measureId
= `${FileType.ChargingStationTemplate} read`;
947 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
948 template
= JSON
.parse(
949 fs
.readFileSync(this.templateFile
, 'utf8')
950 ) as ChargingStationTemplate
;
951 PerformanceStatistics
.endMeasure(measureId
, beginId
);
952 template
.templateHash
= crypto
953 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
954 .update(JSON
.stringify(template
))
956 this.sharedLRUCache
.setChargingStationTemplate(template
);
957 this.templateFileHash
= template
.templateHash
;
960 ErrorUtils
.handleFileException(
962 FileType
.ChargingStationTemplate
,
963 error
as NodeJS
.ErrnoException
,
970 private getStationInfoFromTemplate(): ChargingStationInfo
{
971 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
972 ChargingStationUtils
.checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
973 ChargingStationUtils
.warnTemplateKeysDeprecation(
978 if (stationTemplate
?.Connectors
) {
979 ChargingStationUtils
.checkConnectorsConfiguration(
985 const stationInfo
: ChargingStationInfo
=
986 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
987 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
988 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
992 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
993 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
994 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
995 stationTemplate
.power
= stationTemplate
.power
as number[];
996 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
997 stationInfo
.maximumPower
=
998 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
999 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1000 : stationTemplate
.power
[powerArrayRandomIndex
];
1002 stationTemplate
.power
= stationTemplate
?.power
as number;
1003 stationInfo
.maximumPower
=
1004 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1005 ? stationTemplate
.power
* 1000
1006 : stationTemplate
.power
;
1008 stationInfo
.firmwareVersionPattern
=
1009 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1011 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
1012 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
1015 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1017 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1020 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1027 stationTemplate
?.firmwareUpgrade
?? {}
1029 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
1030 ? stationTemplate
.resetTime
* 1000
1031 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1032 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1036 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1037 let stationInfo
: ChargingStationInfo
| undefined;
1038 if (this.getStationInfoPersistentConfiguration()) {
1039 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1041 delete stationInfo
?.infoHash
;
1047 private getStationInfo(): ChargingStationInfo
{
1048 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1049 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1051 // 1. charging station info from template
1052 // 2. charging station info from configuration file
1053 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1054 return stationInfoFromFile
;
1056 stationInfoFromFile
&&
1057 ChargingStationUtils
.propagateSerialNumber(
1058 this.getTemplateFromFile(),
1059 stationInfoFromFile
,
1060 stationInfoFromTemplate
1062 return stationInfoFromTemplate
;
1065 private saveStationInfo(): void {
1066 if (this.getStationInfoPersistentConfiguration()) {
1067 this.saveConfiguration();
1071 private getOcppPersistentConfiguration(): boolean {
1072 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1075 private getStationInfoPersistentConfiguration(): boolean {
1076 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1079 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1080 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1083 private handleUnsupportedVersion(version
: OCPPVersion
) {
1084 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1085 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1086 throw new BaseError(errorMsg
);
1089 private initialize(): void {
1090 const stationTemplate
= this.getTemplateFromFile();
1091 ChargingStationUtils
.checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1092 this.configurationFile
= path
.join(
1093 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
1094 `${ChargingStationUtils.getHashId(this.index, stationTemplate)}.json`
1096 const chargingStationConfiguration
= this.getConfigurationFromFile();
1097 // FIXME: template changes to evses or connectors are not taken into account
1099 chargingStationConfiguration
?.connectorsStatus
||
1100 chargingStationConfiguration
?.evsesStatus
1102 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1104 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1106 this.stationInfo
= this.getStationInfo();
1108 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1109 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1110 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1112 const patternGroup
: number | undefined =
1113 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1114 this.stationInfo
.firmwareVersion
?.split('.').length
;
1115 const match
= this.stationInfo
?.firmwareVersion
1116 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1117 ?.slice(1, patternGroup
+ 1);
1118 const patchLevelIndex
= match
.length
- 1;
1119 match
[patchLevelIndex
] = (
1120 Utils
.convertToInt(match
[patchLevelIndex
]) +
1121 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1123 this.stationInfo
.firmwareVersion
= match
?.join('.');
1125 this.saveStationInfo();
1126 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1127 if (this.getEnableStatistics() === true) {
1128 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1129 this.stationInfo
.hashId
,
1130 this.stationInfo
.chargingStationId
,
1131 this.configuredSupervisionUrl
1134 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1137 this.powerDivider
= this.getPowerDivider();
1138 // OCPP configuration
1139 this.ocppConfiguration
= this.getOcppConfiguration();
1140 this.initializeOcppConfiguration();
1141 this.initializeOcppServices();
1142 if (this.stationInfo
?.autoRegister
=== true) {
1143 this.bootNotificationResponse
= {
1144 currentTime
: new Date(),
1145 interval
: this.getHeartbeatInterval() / 1000,
1146 status: RegistrationStatusEnumType
.ACCEPTED
,
1151 private initializeOcppServices(): void {
1152 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1153 switch (ocppVersion
) {
1154 case OCPPVersion
.VERSION_16
:
1155 this.ocppIncomingRequestService
=
1156 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1157 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1158 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1161 case OCPPVersion
.VERSION_20
:
1162 case OCPPVersion
.VERSION_201
:
1163 this.ocppIncomingRequestService
=
1164 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1165 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1166 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1170 this.handleUnsupportedVersion(ocppVersion
);
1175 private initializeOcppConfiguration(): void {
1177 !ChargingStationConfigurationUtils
.getConfigurationKey(
1179 StandardParametersKey
.HeartbeatInterval
1182 ChargingStationConfigurationUtils
.addConfigurationKey(
1184 StandardParametersKey
.HeartbeatInterval
,
1189 !ChargingStationConfigurationUtils
.getConfigurationKey(
1191 StandardParametersKey
.HeartBeatInterval
1194 ChargingStationConfigurationUtils
.addConfigurationKey(
1196 StandardParametersKey
.HeartBeatInterval
,
1202 this.getSupervisionUrlOcppConfiguration() &&
1203 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1204 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1206 ChargingStationConfigurationUtils
.addConfigurationKey(
1208 this.getSupervisionUrlOcppKey(),
1209 this.configuredSupervisionUrl
.href
,
1213 !this.getSupervisionUrlOcppConfiguration() &&
1214 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1215 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1217 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1219 this.getSupervisionUrlOcppKey(),
1224 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1225 !ChargingStationConfigurationUtils
.getConfigurationKey(
1227 this.stationInfo
.amperageLimitationOcppKey
1230 ChargingStationConfigurationUtils
.addConfigurationKey(
1232 this.stationInfo
.amperageLimitationOcppKey
,
1234 this.stationInfo
.maximumAmperage
*
1235 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1240 !ChargingStationConfigurationUtils
.getConfigurationKey(
1242 StandardParametersKey
.SupportedFeatureProfiles
1245 ChargingStationConfigurationUtils
.addConfigurationKey(
1247 StandardParametersKey
.SupportedFeatureProfiles
,
1248 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1251 ChargingStationConfigurationUtils
.addConfigurationKey(
1253 StandardParametersKey
.NumberOfConnectors
,
1254 this.getNumberOfConnectors().toString(),
1259 !ChargingStationConfigurationUtils
.getConfigurationKey(
1261 StandardParametersKey
.MeterValuesSampledData
1264 ChargingStationConfigurationUtils
.addConfigurationKey(
1266 StandardParametersKey
.MeterValuesSampledData
,
1267 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1271 !ChargingStationConfigurationUtils
.getConfigurationKey(
1273 StandardParametersKey
.ConnectorPhaseRotation
1276 const connectorsPhaseRotation
: string[] = [];
1277 if (this.hasEvses
) {
1278 for (const evseStatus
of this.evses
.values()) {
1279 for (const connectorId
of evseStatus
.connectors
.keys()) {
1280 connectorsPhaseRotation
.push(
1281 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1286 for (const connectorId
of this.connectors
.keys()) {
1287 connectorsPhaseRotation
.push(
1288 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1292 ChargingStationConfigurationUtils
.addConfigurationKey(
1294 StandardParametersKey
.ConnectorPhaseRotation
,
1295 connectorsPhaseRotation
.toString()
1299 !ChargingStationConfigurationUtils
.getConfigurationKey(
1301 StandardParametersKey
.AuthorizeRemoteTxRequests
1304 ChargingStationConfigurationUtils
.addConfigurationKey(
1306 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1311 !ChargingStationConfigurationUtils
.getConfigurationKey(
1313 StandardParametersKey
.LocalAuthListEnabled
1315 ChargingStationConfigurationUtils
.getConfigurationKey(
1317 StandardParametersKey
.SupportedFeatureProfiles
1318 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1320 ChargingStationConfigurationUtils
.addConfigurationKey(
1322 StandardParametersKey
.LocalAuthListEnabled
,
1327 !ChargingStationConfigurationUtils
.getConfigurationKey(
1329 StandardParametersKey
.ConnectionTimeOut
1332 ChargingStationConfigurationUtils
.addConfigurationKey(
1334 StandardParametersKey
.ConnectionTimeOut
,
1335 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1338 this.saveOcppConfiguration();
1341 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1342 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1343 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1344 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1346 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1347 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1348 const evseStatus
= Utils
.cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1349 delete evseStatus
.connectorsStatus
;
1350 this.evses
.set(evseId
, {
1351 ...(evseStatus
as EvseStatus
),
1352 connectors
: new Map
<number, ConnectorStatus
>(
1353 evseStatusConfiguration
.connectorsStatus
.map((connectorStatus
, connectorId
) => [
1360 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1361 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1362 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1363 throw new BaseError(errorMsg
);
1365 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1366 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1367 throw new BaseError(errorMsg
);
1371 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1372 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1373 this.initializeConnectorsFromTemplate(stationTemplate
);
1374 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1375 this.initializeEvsesFromTemplate(stationTemplate
);
1376 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1377 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1378 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1379 throw new BaseError(errorMsg
);
1381 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1382 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1383 throw new BaseError(errorMsg
);
1387 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1388 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1389 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1390 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1391 throw new BaseError(errorMsg
);
1393 if (!stationTemplate
?.Connectors
[0]) {
1395 `${this.logPrefix()} Charging station information from template ${
1397 } with no connector id 0 configuration`
1400 if (stationTemplate
?.Connectors
) {
1401 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1402 ChargingStationUtils
.checkConnectorsConfiguration(
1407 const connectorsConfigHash
= crypto
1408 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1410 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1413 const connectorsConfigChanged
=
1414 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1415 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1416 connectorsConfigChanged
&& this.connectors
.clear();
1417 this.connectorsConfigurationHash
= connectorsConfigHash
;
1418 if (templateMaxConnectors
> 0) {
1419 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1421 connectorId
=== 0 &&
1422 (!stationTemplate
?.Connectors
[connectorId
] ||
1423 this.getUseConnectorId0(stationTemplate
) === false)
1427 const templateConnectorId
=
1428 connectorId
> 0 && stationTemplate
?.randomConnectors
1429 ? Utils
.getRandomInteger(templateMaxAvailableConnectors
, 1)
1431 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1432 ChargingStationUtils
.checkStationInfoConnectorStatus(
1433 templateConnectorId
,
1438 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1440 ChargingStationUtils
.initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1441 this.saveConnectorsStatus();
1444 `${this.logPrefix()} Charging station information from template ${
1446 } with no connectors configuration defined, cannot create connectors`
1452 `${this.logPrefix()} Charging station information from template ${
1454 } with no connectors configuration defined, using already defined connectors`
1459 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1460 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1461 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1462 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1463 throw new BaseError(errorMsg
);
1465 if (!stationTemplate
?.Evses
[0]) {
1467 `${this.logPrefix()} Charging station information from template ${
1469 } with no evse id 0 configuration`
1472 if (!stationTemplate
?.Evses
[0]?.Connectors
[0]) {
1474 `${this.logPrefix()} Charging station information from template ${
1476 } with evse id 0 with no connector id 0 configuration`
1479 if (stationTemplate
?.Evses
) {
1480 const evsesConfigHash
= crypto
1481 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1482 .update(`${JSON.stringify(stationTemplate?.Evses)}`)
1484 const evsesConfigChanged
=
1485 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1486 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1487 evsesConfigChanged
&& this.evses
.clear();
1488 this.evsesConfigurationHash
= evsesConfigHash
;
1489 const templateMaxEvses
= ChargingStationUtils
.getMaxNumberOfEvses(stationTemplate
?.Evses
);
1490 if (templateMaxEvses
> 0) {
1491 for (const evse
in stationTemplate
.Evses
) {
1492 const evseId
= Utils
.convertToInt(evse
);
1493 this.evses
.set(evseId
, {
1494 connectors
: ChargingStationUtils
.buildConnectorsMap(
1495 stationTemplate
?.Evses
[evse
]?.Connectors
,
1499 availability
: AvailabilityType
.Operative
,
1501 ChargingStationUtils
.initializeConnectorsMapStatus(
1502 this.evses
.get(evseId
)?.connectors
,
1506 this.saveEvsesStatus();
1509 `${this.logPrefix()} Charging station information from template ${
1511 } with no evses configuration defined, cannot create evses`
1517 `${this.logPrefix()} Charging station information from template ${
1519 } with no evses configuration defined, using already defined evses`
1524 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1525 let configuration
: ChargingStationConfiguration
| undefined;
1526 if (Utils
.isNotEmptyString(this.configurationFile
) && fs
.existsSync(this.configurationFile
)) {
1528 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1529 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1530 this.configurationFileHash
1533 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1534 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1535 configuration
= JSON
.parse(
1536 fs
.readFileSync(this.configurationFile
, 'utf8')
1537 ) as ChargingStationConfiguration
;
1538 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1539 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1540 this.configurationFileHash
= configuration
.configurationHash
;
1543 ErrorUtils
.handleFileException(
1544 this.configurationFile
,
1545 FileType
.ChargingStationConfiguration
,
1546 error
as NodeJS
.ErrnoException
,
1551 return configuration
;
1554 private saveChargingStationAutomaticTransactionGeneratorConfiguration(): void {
1555 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1556 this.saveConfiguration();
1560 private saveConnectorsStatus() {
1561 this.saveConfiguration();
1564 private saveEvsesStatus() {
1565 this.saveConfiguration();
1568 private saveConfiguration(): void {
1569 if (Utils
.isNotEmptyString(this.configurationFile
)) {
1571 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1572 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1574 let configurationData
: ChargingStationConfiguration
=
1575 Utils
.cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()) ?? {};
1576 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1577 configurationData
.stationInfo
= this.stationInfo
;
1579 delete configurationData
.stationInfo
;
1581 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1582 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1584 delete configurationData
.configurationKey
;
1586 configurationData
= merge
<ChargingStationConfiguration
>(
1588 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1591 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1592 !this.getAutomaticTransactionGeneratorConfiguration()
1594 delete configurationData
.automaticTransactionGenerator
;
1596 if (this.connectors
.size
> 0) {
1597 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1599 delete configurationData
.connectorsStatus
;
1601 if (this.evses
.size
> 0) {
1602 configurationData
.evsesStatus
= buildEvsesStatus(this);
1604 delete configurationData
.evsesStatus
;
1606 delete configurationData
.configurationHash
;
1607 const configurationHash
= crypto
1608 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1611 stationInfo
: configurationData
.stationInfo
,
1612 configurationKey
: configurationData
.configurationKey
,
1613 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1614 } as ChargingStationConfiguration
)
1617 if (this.configurationFileHash
!== configurationHash
) {
1618 AsyncLock
.acquire(AsyncLockType
.configuration
)
1620 configurationData
.configurationHash
= configurationHash
;
1621 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1622 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1623 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1624 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1625 fs
.closeSync(fileDescriptor
);
1626 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1627 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1628 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1629 this.configurationFileHash
= configurationHash
;
1632 ErrorUtils
.handleFileException(
1633 this.configurationFile
,
1634 FileType
.ChargingStationConfiguration
,
1635 error
as NodeJS
.ErrnoException
,
1640 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1644 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1645 this.configurationFile
1650 ErrorUtils
.handleFileException(
1651 this.configurationFile
,
1652 FileType
.ChargingStationConfiguration
,
1653 error
as NodeJS
.ErrnoException
,
1659 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1664 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1665 return this.getTemplateFromFile()?.Configuration
;
1668 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1669 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1670 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1671 return { configurationKey
};
1676 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1677 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1678 this.getOcppConfigurationFromFile();
1679 if (!ocppConfiguration
) {
1680 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1682 return ocppConfiguration
;
1685 private async onOpen(): Promise
<void> {
1686 if (this.isWebSocketConnectionOpened() === true) {
1688 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1690 if (this.isRegistered() === false) {
1691 // Send BootNotification
1692 let registrationRetryCount
= 0;
1694 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1695 BootNotificationRequest
,
1696 BootNotificationResponse
1697 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1698 skipBufferingOnError
: true,
1700 if (this.isRegistered() === false) {
1701 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1703 this?.bootNotificationResponse
?.interval
1704 ? this.bootNotificationResponse
.interval
* 1000
1705 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1709 this.isRegistered() === false &&
1710 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1711 this.getRegistrationMaxRetries() === -1)
1714 if (this.isRegistered() === true) {
1715 if (this.inAcceptedState() === true) {
1716 await this.startMessageSequence();
1720 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1723 this.wsConnectionRestarted
= false;
1724 this.autoReconnectRetryCount
= 0;
1725 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1728 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1733 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1736 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1737 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1739 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1741 )}' and reason '${reason.toString()}'`
1743 this.autoReconnectRetryCount
= 0;
1748 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1750 )}' and reason '${reason.toString()}'`
1752 this.started
=== true && (await this.reconnect());
1755 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1758 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1759 const cachedRequest
= this.requests
.get(messageId
);
1760 if (Array.isArray(cachedRequest
) === true) {
1761 return cachedRequest
;
1763 throw new OCPPError(
1764 ErrorType
.PROTOCOL_ERROR
,
1765 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1767 )} is not an array`,
1769 cachedRequest
as JsonType
1773 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1774 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1775 if (this.getEnableStatistics() === true) {
1776 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1779 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1783 // Process the message
1784 await this.ocppIncomingRequestService
.incomingRequestHandler(
1792 private handleResponseMessage(response
: Response
): void {
1793 const [messageType
, messageId
, commandPayload
] = response
;
1794 if (this.requests
.has(messageId
) === false) {
1796 throw new OCPPError(
1797 ErrorType
.INTERNAL_ERROR
,
1798 `Response for unknown message id ${messageId}`,
1804 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1809 `${this.logPrefix()} << Command '${
1810 requestCommandName ?? Constants.UNKNOWN_COMMAND
1811 }' received response payload: ${JSON.stringify(response)}`
1813 responseCallback(commandPayload
, requestPayload
);
1816 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1817 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1818 if (this.requests
.has(messageId
) === false) {
1820 throw new OCPPError(
1821 ErrorType
.INTERNAL_ERROR
,
1822 `Error response for unknown message id ${messageId}`,
1824 { errorType
, errorMessage
, errorDetails
}
1827 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1829 `${this.logPrefix()} << Command '${
1830 requestCommandName ?? Constants.UNKNOWN_COMMAND
1831 }' received error response payload: ${JSON.stringify(errorResponse)}`
1833 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1836 private async onMessage(data
: RawData
): Promise
<void> {
1837 let request
: IncomingRequest
| Response
| ErrorResponse
;
1838 let messageType
: number;
1839 let errorMsg
: string;
1841 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1842 if (Array.isArray(request
) === true) {
1843 [messageType
] = request
;
1844 // Check the type of message
1845 switch (messageType
) {
1847 case MessageType
.CALL_MESSAGE
:
1848 await this.handleIncomingMessage(request
as IncomingRequest
);
1851 case MessageType
.CALL_RESULT_MESSAGE
:
1852 this.handleResponseMessage(request
as Response
);
1855 case MessageType
.CALL_ERROR_MESSAGE
:
1856 this.handleErrorMessage(request
as ErrorResponse
);
1860 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1861 errorMsg
= `Wrong message type ${messageType}`;
1862 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1863 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1865 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1867 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1872 let commandName
: IncomingRequestCommand
;
1873 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1874 let errorCallback
: ErrorCallback
;
1875 const [, messageId
] = request
;
1876 switch (messageType
) {
1877 case MessageType
.CALL_MESSAGE
:
1878 [, , commandName
] = request
as IncomingRequest
;
1880 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1882 case MessageType
.CALL_RESULT_MESSAGE
:
1883 case MessageType
.CALL_ERROR_MESSAGE
:
1884 if (this.requests
.has(messageId
) === true) {
1885 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1886 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1887 errorCallback(error
as OCPPError
, false);
1889 // Remove the request from the cache in case of error at response handling
1890 this.requests
.delete(messageId
);
1894 if (error
instanceof OCPPError
=== false) {
1896 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1897 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1898 }' message '${data.toString()}' handling is not an OCPPError:`,
1903 `${this.logPrefix()} Incoming OCPP command '${
1904 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1905 }' message '${data.toString()}'${
1906 messageType !== MessageType.CALL_MESSAGE
1907 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1909 } processing error:`,
1915 private onPing(): void {
1916 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1919 private onPong(): void {
1920 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1923 private onError(error
: WSError
): void {
1924 this.closeWSConnection();
1925 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1928 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1929 if (this.getMeteringPerTransaction() === true) {
1932 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1933 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1938 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1939 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1943 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
1944 return stationTemplate
?.useConnectorId0
?? true;
1947 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1948 if (this.hasEvses
) {
1949 for (const evseStatus
of this.evses
.values()) {
1950 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1951 if (connectorStatus
.transactionStarted
=== true) {
1952 await this.stopTransactionOnConnector(connectorId
, reason
);
1957 for (const connectorId
of this.connectors
.keys()) {
1958 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1959 await this.stopTransactionOnConnector(connectorId
, reason
);
1966 private getConnectionTimeout(): number {
1968 ChargingStationConfigurationUtils
.getConfigurationKey(
1970 StandardParametersKey
.ConnectionTimeOut
1975 ChargingStationConfigurationUtils
.getConfigurationKey(
1977 StandardParametersKey
.ConnectionTimeOut
1979 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1982 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1985 // -1 for unlimited, 0 for disabling
1986 private getAutoReconnectMaxRetries(): number | undefined {
1988 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
1993 private getRegistrationMaxRetries(): number | undefined {
1994 return this.stationInfo
.registrationMaxRetries
?? -1;
1997 private getPowerDivider(): number {
1998 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
1999 if (this.stationInfo
?.powerSharedByConnectors
) {
2000 powerDivider
= this.getNumberOfRunningTransactions();
2002 return powerDivider
;
2005 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2006 const maximumPower
= this.getMaximumPower(stationInfo
);
2007 switch (this.getCurrentOutType(stationInfo
)) {
2008 case CurrentType
.AC
:
2009 return ACElectricUtils
.amperagePerPhaseFromPower(
2010 this.getNumberOfPhases(stationInfo
),
2011 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2012 this.getVoltageOut(stationInfo
)
2014 case CurrentType
.DC
:
2015 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2019 private getAmperageLimitation(): number | undefined {
2021 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2022 ChargingStationConfigurationUtils
.getConfigurationKey(
2024 this.stationInfo
.amperageLimitationOcppKey
2029 ChargingStationConfigurationUtils
.getConfigurationKey(
2031 this.stationInfo
.amperageLimitationOcppKey
2033 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
2038 private async startMessageSequence(): Promise
<void> {
2039 if (this.stationInfo
?.autoRegister
=== true) {
2040 await this.ocppRequestService
.requestHandler
<
2041 BootNotificationRequest
,
2042 BootNotificationResponse
2043 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2044 skipBufferingOnError
: true,
2047 // Start WebSocket ping
2048 this.startWebSocketPing();
2050 this.startHeartbeat();
2051 // Initialize connectors status
2052 if (this.hasEvses
) {
2053 for (const [evseId
, evseStatus
] of this.evses
) {
2055 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2056 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2061 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2064 connectorBootStatus
,
2071 for (const connectorId
of this.connectors
.keys()) {
2072 if (connectorId
> 0) {
2073 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2076 this.getConnectorStatus(connectorId
)
2078 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2082 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2083 await this.ocppRequestService
.requestHandler
<
2084 FirmwareStatusNotificationRequest
,
2085 FirmwareStatusNotificationResponse
2086 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2087 status: FirmwareStatus
.Installed
,
2089 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2093 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2094 this.startAutomaticTransactionGenerator();
2096 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2099 private async stopMessageSequence(
2100 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2102 // Stop WebSocket ping
2103 this.stopWebSocketPing();
2105 this.stopHeartbeat();
2106 // Stop ongoing transactions
2107 if (this.automaticTransactionGenerator
?.started
=== true) {
2108 this.stopAutomaticTransactionGenerator();
2110 await this.stopRunningTransactions(reason
);
2112 if (this.hasEvses
) {
2113 for (const [evseId
, evseStatus
] of this.evses
) {
2115 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2116 await this.ocppRequestService
.requestHandler
<
2117 StatusNotificationRequest
,
2118 StatusNotificationResponse
2121 RequestCommand
.STATUS_NOTIFICATION
,
2122 OCPPServiceUtils
.buildStatusNotificationRequest(
2125 ConnectorStatusEnum
.Unavailable
,
2129 delete connectorStatus
?.status;
2134 for (const connectorId
of this.connectors
.keys()) {
2135 if (connectorId
> 0) {
2136 await this.ocppRequestService
.requestHandler
<
2137 StatusNotificationRequest
,
2138 StatusNotificationResponse
2141 RequestCommand
.STATUS_NOTIFICATION
,
2142 OCPPServiceUtils
.buildStatusNotificationRequest(
2145 ConnectorStatusEnum
.Unavailable
2148 delete this.getConnectorStatus(connectorId
)?.status;
2154 private startWebSocketPing(): void {
2155 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2157 StandardParametersKey
.WebSocketPingInterval
2159 ? Utils
.convertToInt(
2160 ChargingStationConfigurationUtils
.getConfigurationKey(
2162 StandardParametersKey
.WebSocketPingInterval
2166 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2167 this.webSocketPingSetInterval
= setInterval(() => {
2168 if (this.isWebSocketConnectionOpened() === true) {
2169 this.wsConnection
?.ping();
2171 }, webSocketPingInterval
* 1000);
2173 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
2174 webSocketPingInterval
2177 } else if (this.webSocketPingSetInterval
) {
2179 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
2180 webSocketPingInterval
2185 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2190 private stopWebSocketPing(): void {
2191 if (this.webSocketPingSetInterval
) {
2192 clearInterval(this.webSocketPingSetInterval
);
2193 delete this.webSocketPingSetInterval
;
2197 private getConfiguredSupervisionUrl(): URL
{
2198 let configuredSupervisionUrl
: string;
2199 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2200 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
2201 let configuredSupervisionUrlIndex
: number;
2202 switch (Configuration
.getSupervisionUrlDistribution()) {
2203 case SupervisionUrlDistribution
.RANDOM
:
2204 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2206 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2207 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2209 Object.values(SupervisionUrlDistribution
).includes(
2210 Configuration
.getSupervisionUrlDistribution()
2213 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2214 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2217 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2220 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
];
2222 configuredSupervisionUrl
= supervisionUrls
as string;
2224 if (Utils
.isNotEmptyString(configuredSupervisionUrl
)) {
2225 return new URL(configuredSupervisionUrl
);
2227 const errorMsg
= 'No supervision url(s) configured';
2228 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2229 throw new BaseError(`${errorMsg}`);
2232 private stopHeartbeat(): void {
2233 if (this.heartbeatSetInterval
) {
2234 clearInterval(this.heartbeatSetInterval
);
2235 delete this.heartbeatSetInterval
;
2239 private terminateWSConnection(): void {
2240 if (this.isWebSocketConnectionOpened() === true) {
2241 this.wsConnection
?.terminate();
2242 this.wsConnection
= null;
2246 private getReconnectExponentialDelay(): boolean {
2247 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2250 private async reconnect(): Promise
<void> {
2251 // Stop WebSocket ping
2252 this.stopWebSocketPing();
2254 this.stopHeartbeat();
2255 // Stop the ATG if needed
2256 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2257 this.stopAutomaticTransactionGenerator();
2260 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2261 this.getAutoReconnectMaxRetries() === -1
2263 ++this.autoReconnectRetryCount
;
2264 const reconnectDelay
= this.getReconnectExponentialDelay()
2265 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2266 : this.getConnectionTimeout() * 1000;
2267 const reconnectDelayWithdraw
= 1000;
2268 const reconnectTimeout
=
2269 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2270 ? reconnectDelay
- reconnectDelayWithdraw
2273 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2276 )}ms, timeout ${reconnectTimeout}ms`
2278 await Utils
.sleep(reconnectDelay
);
2280 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2282 this.openWSConnection(
2284 ...(this.stationInfo
?.wsOptions
?? {}),
2285 handshakeTimeout
: reconnectTimeout
,
2287 { closeOpened
: true }
2289 this.wsConnectionRestarted
= true;
2290 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2292 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2293 this.autoReconnectRetryCount
2294 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`