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.saveAutomaticTransactionGeneratorConfiguration();
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.saveAutomaticTransactionGeneratorConfiguration();
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();
1098 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1099 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1101 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1103 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1105 this.stationInfo
= this.getStationInfo();
1107 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1108 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1109 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1111 const patternGroup
: number | undefined =
1112 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1113 this.stationInfo
.firmwareVersion
?.split('.').length
;
1114 const match
= this.stationInfo
?.firmwareVersion
1115 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1116 ?.slice(1, patternGroup
+ 1);
1117 const patchLevelIndex
= match
.length
- 1;
1118 match
[patchLevelIndex
] = (
1119 Utils
.convertToInt(match
[patchLevelIndex
]) +
1120 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1122 this.stationInfo
.firmwareVersion
= match
?.join('.');
1124 this.saveStationInfo();
1125 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1126 if (this.getEnableStatistics() === true) {
1127 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1128 this.stationInfo
.hashId
,
1129 this.stationInfo
.chargingStationId
,
1130 this.configuredSupervisionUrl
1133 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1136 this.powerDivider
= this.getPowerDivider();
1137 // OCPP configuration
1138 this.ocppConfiguration
= this.getOcppConfiguration();
1139 this.initializeOcppConfiguration();
1140 this.initializeOcppServices();
1141 if (this.stationInfo
?.autoRegister
=== true) {
1142 this.bootNotificationResponse
= {
1143 currentTime
: new Date(),
1144 interval
: this.getHeartbeatInterval() / 1000,
1145 status: RegistrationStatusEnumType
.ACCEPTED
,
1150 private initializeOcppServices(): void {
1151 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1152 switch (ocppVersion
) {
1153 case OCPPVersion
.VERSION_16
:
1154 this.ocppIncomingRequestService
=
1155 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1156 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1157 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1160 case OCPPVersion
.VERSION_20
:
1161 case OCPPVersion
.VERSION_201
:
1162 this.ocppIncomingRequestService
=
1163 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1164 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1165 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1169 this.handleUnsupportedVersion(ocppVersion
);
1174 private initializeOcppConfiguration(): void {
1176 !ChargingStationConfigurationUtils
.getConfigurationKey(
1178 StandardParametersKey
.HeartbeatInterval
1181 ChargingStationConfigurationUtils
.addConfigurationKey(
1183 StandardParametersKey
.HeartbeatInterval
,
1188 !ChargingStationConfigurationUtils
.getConfigurationKey(
1190 StandardParametersKey
.HeartBeatInterval
1193 ChargingStationConfigurationUtils
.addConfigurationKey(
1195 StandardParametersKey
.HeartBeatInterval
,
1201 this.getSupervisionUrlOcppConfiguration() &&
1202 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1203 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1205 ChargingStationConfigurationUtils
.addConfigurationKey(
1207 this.getSupervisionUrlOcppKey(),
1208 this.configuredSupervisionUrl
.href
,
1212 !this.getSupervisionUrlOcppConfiguration() &&
1213 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1214 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1216 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1218 this.getSupervisionUrlOcppKey(),
1223 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1224 !ChargingStationConfigurationUtils
.getConfigurationKey(
1226 this.stationInfo
.amperageLimitationOcppKey
1229 ChargingStationConfigurationUtils
.addConfigurationKey(
1231 this.stationInfo
.amperageLimitationOcppKey
,
1233 this.stationInfo
.maximumAmperage
*
1234 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1239 !ChargingStationConfigurationUtils
.getConfigurationKey(
1241 StandardParametersKey
.SupportedFeatureProfiles
1244 ChargingStationConfigurationUtils
.addConfigurationKey(
1246 StandardParametersKey
.SupportedFeatureProfiles
,
1247 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1250 ChargingStationConfigurationUtils
.addConfigurationKey(
1252 StandardParametersKey
.NumberOfConnectors
,
1253 this.getNumberOfConnectors().toString(),
1258 !ChargingStationConfigurationUtils
.getConfigurationKey(
1260 StandardParametersKey
.MeterValuesSampledData
1263 ChargingStationConfigurationUtils
.addConfigurationKey(
1265 StandardParametersKey
.MeterValuesSampledData
,
1266 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1270 !ChargingStationConfigurationUtils
.getConfigurationKey(
1272 StandardParametersKey
.ConnectorPhaseRotation
1275 const connectorsPhaseRotation
: string[] = [];
1276 if (this.hasEvses
) {
1277 for (const evseStatus
of this.evses
.values()) {
1278 for (const connectorId
of evseStatus
.connectors
.keys()) {
1279 connectorsPhaseRotation
.push(
1280 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1285 for (const connectorId
of this.connectors
.keys()) {
1286 connectorsPhaseRotation
.push(
1287 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1291 ChargingStationConfigurationUtils
.addConfigurationKey(
1293 StandardParametersKey
.ConnectorPhaseRotation
,
1294 connectorsPhaseRotation
.toString()
1298 !ChargingStationConfigurationUtils
.getConfigurationKey(
1300 StandardParametersKey
.AuthorizeRemoteTxRequests
1303 ChargingStationConfigurationUtils
.addConfigurationKey(
1305 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1310 !ChargingStationConfigurationUtils
.getConfigurationKey(
1312 StandardParametersKey
.LocalAuthListEnabled
1314 ChargingStationConfigurationUtils
.getConfigurationKey(
1316 StandardParametersKey
.SupportedFeatureProfiles
1317 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1319 ChargingStationConfigurationUtils
.addConfigurationKey(
1321 StandardParametersKey
.LocalAuthListEnabled
,
1326 !ChargingStationConfigurationUtils
.getConfigurationKey(
1328 StandardParametersKey
.ConnectionTimeOut
1331 ChargingStationConfigurationUtils
.addConfigurationKey(
1333 StandardParametersKey
.ConnectionTimeOut
,
1334 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1337 this.saveOcppConfiguration();
1340 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1341 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1342 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1343 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1345 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1346 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1347 const evseStatus
= Utils
.cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1348 delete evseStatus
.connectorsStatus
;
1349 this.evses
.set(evseId
, {
1350 ...(evseStatus
as EvseStatus
),
1351 connectors
: new Map
<number, ConnectorStatus
>(
1352 evseStatusConfiguration
.connectorsStatus
.map((connectorStatus
, connectorId
) => [
1359 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1360 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1361 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1362 throw new BaseError(errorMsg
);
1364 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1365 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1366 throw new BaseError(errorMsg
);
1370 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1371 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1372 this.initializeConnectorsFromTemplate(stationTemplate
);
1373 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1374 this.initializeEvsesFromTemplate(stationTemplate
);
1375 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1376 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1377 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1378 throw new BaseError(errorMsg
);
1380 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1381 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1382 throw new BaseError(errorMsg
);
1386 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1387 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1388 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1389 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1390 throw new BaseError(errorMsg
);
1392 if (!stationTemplate
?.Connectors
[0]) {
1394 `${this.logPrefix()} Charging station information from template ${
1396 } with no connector id 0 configuration`
1399 if (stationTemplate
?.Connectors
) {
1400 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1401 ChargingStationUtils
.checkConnectorsConfiguration(
1406 const connectorsConfigHash
= crypto
1407 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1409 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1412 const connectorsConfigChanged
=
1413 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1414 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1415 connectorsConfigChanged
&& this.connectors
.clear();
1416 this.connectorsConfigurationHash
= connectorsConfigHash
;
1417 if (templateMaxConnectors
> 0) {
1418 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1420 connectorId
=== 0 &&
1421 (!stationTemplate
?.Connectors
[connectorId
] ||
1422 this.getUseConnectorId0(stationTemplate
) === false)
1426 const templateConnectorId
=
1427 connectorId
> 0 && stationTemplate
?.randomConnectors
1428 ? Utils
.getRandomInteger(templateMaxAvailableConnectors
, 1)
1430 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1431 ChargingStationUtils
.checkStationInfoConnectorStatus(
1432 templateConnectorId
,
1437 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1439 ChargingStationUtils
.initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1440 this.saveConnectorsStatus();
1443 `${this.logPrefix()} Charging station information from template ${
1445 } with no connectors configuration defined, cannot create connectors`
1451 `${this.logPrefix()} Charging station information from template ${
1453 } with no connectors configuration defined, using already defined connectors`
1458 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1459 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1460 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1461 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1462 throw new BaseError(errorMsg
);
1464 if (!stationTemplate
?.Evses
[0]) {
1466 `${this.logPrefix()} Charging station information from template ${
1468 } with no evse id 0 configuration`
1471 if (!stationTemplate
?.Evses
[0]?.Connectors
[0]) {
1473 `${this.logPrefix()} Charging station information from template ${
1475 } with evse id 0 with no connector id 0 configuration`
1478 if (stationTemplate
?.Evses
) {
1479 const evsesConfigHash
= crypto
1480 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1481 .update(JSON
.stringify(stationTemplate
?.Evses
))
1483 const evsesConfigChanged
=
1484 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1485 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1486 evsesConfigChanged
&& this.evses
.clear();
1487 this.evsesConfigurationHash
= evsesConfigHash
;
1488 const templateMaxEvses
= ChargingStationUtils
.getMaxNumberOfEvses(stationTemplate
?.Evses
);
1489 if (templateMaxEvses
> 0) {
1490 for (const evse
in stationTemplate
.Evses
) {
1491 const evseId
= Utils
.convertToInt(evse
);
1492 this.evses
.set(evseId
, {
1493 connectors
: ChargingStationUtils
.buildConnectorsMap(
1494 stationTemplate
?.Evses
[evse
]?.Connectors
,
1498 availability
: AvailabilityType
.Operative
,
1500 ChargingStationUtils
.initializeConnectorsMapStatus(
1501 this.evses
.get(evseId
)?.connectors
,
1505 this.saveEvsesStatus();
1508 `${this.logPrefix()} Charging station information from template ${
1510 } with no evses configuration defined, cannot create evses`
1516 `${this.logPrefix()} Charging station information from template ${
1518 } with no evses configuration defined, using already defined evses`
1523 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1524 let configuration
: ChargingStationConfiguration
| undefined;
1525 if (Utils
.isNotEmptyString(this.configurationFile
) && fs
.existsSync(this.configurationFile
)) {
1527 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1528 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1529 this.configurationFileHash
1532 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1533 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1534 configuration
= JSON
.parse(
1535 fs
.readFileSync(this.configurationFile
, 'utf8')
1536 ) as ChargingStationConfiguration
;
1537 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1538 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1539 this.configurationFileHash
= configuration
.configurationHash
;
1542 ErrorUtils
.handleFileException(
1543 this.configurationFile
,
1544 FileType
.ChargingStationConfiguration
,
1545 error
as NodeJS
.ErrnoException
,
1550 return configuration
;
1553 private saveAutomaticTransactionGeneratorConfiguration(): void {
1554 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1555 this.saveConfiguration();
1559 private saveConnectorsStatus() {
1560 this.saveConfiguration();
1563 private saveEvsesStatus() {
1564 this.saveConfiguration();
1567 private saveConfiguration(): void {
1568 if (Utils
.isNotEmptyString(this.configurationFile
)) {
1570 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1571 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1573 let configurationData
: ChargingStationConfiguration
=
1574 Utils
.cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()) ?? {};
1575 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1576 configurationData
.stationInfo
= this.stationInfo
;
1578 delete configurationData
.stationInfo
;
1580 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1581 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1583 delete configurationData
.configurationKey
;
1585 configurationData
= merge
<ChargingStationConfiguration
>(
1587 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1590 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1591 !this.getAutomaticTransactionGeneratorConfiguration()
1593 delete configurationData
.automaticTransactionGenerator
;
1595 if (this.connectors
.size
> 0) {
1596 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1598 delete configurationData
.connectorsStatus
;
1600 if (this.evses
.size
> 0) {
1601 configurationData
.evsesStatus
= buildEvsesStatus(this);
1603 delete configurationData
.evsesStatus
;
1605 delete configurationData
.configurationHash
;
1606 const configurationHash
= crypto
1607 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1610 stationInfo
: configurationData
.stationInfo
,
1611 configurationKey
: configurationData
.configurationKey
,
1612 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1613 } as ChargingStationConfiguration
)
1616 if (this.configurationFileHash
!== configurationHash
) {
1617 AsyncLock
.acquire(AsyncLockType
.configuration
)
1619 configurationData
.configurationHash
= configurationHash
;
1620 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1621 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1622 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1623 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1624 fs
.closeSync(fileDescriptor
);
1625 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1626 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1627 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1628 this.configurationFileHash
= configurationHash
;
1631 ErrorUtils
.handleFileException(
1632 this.configurationFile
,
1633 FileType
.ChargingStationConfiguration
,
1634 error
as NodeJS
.ErrnoException
,
1639 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1643 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1644 this.configurationFile
1649 ErrorUtils
.handleFileException(
1650 this.configurationFile
,
1651 FileType
.ChargingStationConfiguration
,
1652 error
as NodeJS
.ErrnoException
,
1658 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1663 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1664 return this.getTemplateFromFile()?.Configuration
;
1667 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1668 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1669 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1670 return { configurationKey
};
1675 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1676 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1677 this.getOcppConfigurationFromFile();
1678 if (!ocppConfiguration
) {
1679 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1681 return ocppConfiguration
;
1684 private async onOpen(): Promise
<void> {
1685 if (this.isWebSocketConnectionOpened() === true) {
1687 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1689 if (this.isRegistered() === false) {
1690 // Send BootNotification
1691 let registrationRetryCount
= 0;
1693 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1694 BootNotificationRequest
,
1695 BootNotificationResponse
1696 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1697 skipBufferingOnError
: true,
1699 if (this.isRegistered() === false) {
1700 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1702 this?.bootNotificationResponse
?.interval
1703 ? this.bootNotificationResponse
.interval
* 1000
1704 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1708 this.isRegistered() === false &&
1709 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1710 this.getRegistrationMaxRetries() === -1)
1713 if (this.isRegistered() === true) {
1714 if (this.inAcceptedState() === true) {
1715 await this.startMessageSequence();
1719 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1722 this.wsConnectionRestarted
= false;
1723 this.autoReconnectRetryCount
= 0;
1724 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1727 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1732 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1735 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1736 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1738 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1740 )}' and reason '${reason.toString()}'`
1742 this.autoReconnectRetryCount
= 0;
1747 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1749 )}' and reason '${reason.toString()}'`
1751 this.started
=== true && (await this.reconnect());
1754 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1757 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1758 const cachedRequest
= this.requests
.get(messageId
);
1759 if (Array.isArray(cachedRequest
) === true) {
1760 return cachedRequest
;
1762 throw new OCPPError(
1763 ErrorType
.PROTOCOL_ERROR
,
1764 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1766 )} is not an array`,
1768 cachedRequest
as JsonType
1772 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1773 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1774 if (this.getEnableStatistics() === true) {
1775 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1778 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1782 // Process the message
1783 await this.ocppIncomingRequestService
.incomingRequestHandler(
1791 private handleResponseMessage(response
: Response
): void {
1792 const [messageType
, messageId
, commandPayload
] = response
;
1793 if (this.requests
.has(messageId
) === false) {
1795 throw new OCPPError(
1796 ErrorType
.INTERNAL_ERROR
,
1797 `Response for unknown message id ${messageId}`,
1803 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1808 `${this.logPrefix()} << Command '${
1809 requestCommandName ?? Constants.UNKNOWN_COMMAND
1810 }' received response payload: ${JSON.stringify(response)}`
1812 responseCallback(commandPayload
, requestPayload
);
1815 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1816 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1817 if (this.requests
.has(messageId
) === false) {
1819 throw new OCPPError(
1820 ErrorType
.INTERNAL_ERROR
,
1821 `Error response for unknown message id ${messageId}`,
1823 { errorType
, errorMessage
, errorDetails
}
1826 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1828 `${this.logPrefix()} << Command '${
1829 requestCommandName ?? Constants.UNKNOWN_COMMAND
1830 }' received error response payload: ${JSON.stringify(errorResponse)}`
1832 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1835 private async onMessage(data
: RawData
): Promise
<void> {
1836 let request
: IncomingRequest
| Response
| ErrorResponse
;
1837 let messageType
: number;
1838 let errorMsg
: string;
1840 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1841 if (Array.isArray(request
) === true) {
1842 [messageType
] = request
;
1843 // Check the type of message
1844 switch (messageType
) {
1846 case MessageType
.CALL_MESSAGE
:
1847 await this.handleIncomingMessage(request
as IncomingRequest
);
1850 case MessageType
.CALL_RESULT_MESSAGE
:
1851 this.handleResponseMessage(request
as Response
);
1854 case MessageType
.CALL_ERROR_MESSAGE
:
1855 this.handleErrorMessage(request
as ErrorResponse
);
1859 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1860 errorMsg
= `Wrong message type ${messageType}`;
1861 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1862 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1864 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1866 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1871 let commandName
: IncomingRequestCommand
;
1872 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1873 let errorCallback
: ErrorCallback
;
1874 const [, messageId
] = request
;
1875 switch (messageType
) {
1876 case MessageType
.CALL_MESSAGE
:
1877 [, , commandName
] = request
as IncomingRequest
;
1879 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1881 case MessageType
.CALL_RESULT_MESSAGE
:
1882 case MessageType
.CALL_ERROR_MESSAGE
:
1883 if (this.requests
.has(messageId
) === true) {
1884 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1885 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1886 errorCallback(error
as OCPPError
, false);
1888 // Remove the request from the cache in case of error at response handling
1889 this.requests
.delete(messageId
);
1893 if (error
instanceof OCPPError
=== false) {
1895 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1896 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1897 }' message '${data.toString()}' handling is not an OCPPError:`,
1902 `${this.logPrefix()} Incoming OCPP command '${
1903 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1904 }' message '${data.toString()}'${
1905 messageType !== MessageType.CALL_MESSAGE
1906 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1908 } processing error:`,
1914 private onPing(): void {
1915 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1918 private onPong(): void {
1919 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1922 private onError(error
: WSError
): void {
1923 this.closeWSConnection();
1924 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1927 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1928 if (this.getMeteringPerTransaction() === true) {
1931 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1932 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1937 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1938 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1942 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
1943 return stationTemplate
?.useConnectorId0
?? true;
1946 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1947 if (this.hasEvses
) {
1948 for (const evseStatus
of this.evses
.values()) {
1949 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1950 if (connectorStatus
.transactionStarted
=== true) {
1951 await this.stopTransactionOnConnector(connectorId
, reason
);
1956 for (const connectorId
of this.connectors
.keys()) {
1957 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1958 await this.stopTransactionOnConnector(connectorId
, reason
);
1965 private getConnectionTimeout(): number {
1967 ChargingStationConfigurationUtils
.getConfigurationKey(
1969 StandardParametersKey
.ConnectionTimeOut
1974 ChargingStationConfigurationUtils
.getConfigurationKey(
1976 StandardParametersKey
.ConnectionTimeOut
1978 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1981 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1984 // -1 for unlimited, 0 for disabling
1985 private getAutoReconnectMaxRetries(): number | undefined {
1987 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
1992 private getRegistrationMaxRetries(): number | undefined {
1993 return this.stationInfo
.registrationMaxRetries
?? -1;
1996 private getPowerDivider(): number {
1997 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
1998 if (this.stationInfo
?.powerSharedByConnectors
) {
1999 powerDivider
= this.getNumberOfRunningTransactions();
2001 return powerDivider
;
2004 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2005 const maximumPower
= this.getMaximumPower(stationInfo
);
2006 switch (this.getCurrentOutType(stationInfo
)) {
2007 case CurrentType
.AC
:
2008 return ACElectricUtils
.amperagePerPhaseFromPower(
2009 this.getNumberOfPhases(stationInfo
),
2010 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2011 this.getVoltageOut(stationInfo
)
2013 case CurrentType
.DC
:
2014 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2018 private getAmperageLimitation(): number | undefined {
2020 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2021 ChargingStationConfigurationUtils
.getConfigurationKey(
2023 this.stationInfo
.amperageLimitationOcppKey
2028 ChargingStationConfigurationUtils
.getConfigurationKey(
2030 this.stationInfo
.amperageLimitationOcppKey
2032 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
2037 private async startMessageSequence(): Promise
<void> {
2038 if (this.stationInfo
?.autoRegister
=== true) {
2039 await this.ocppRequestService
.requestHandler
<
2040 BootNotificationRequest
,
2041 BootNotificationResponse
2042 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2043 skipBufferingOnError
: true,
2046 // Start WebSocket ping
2047 this.startWebSocketPing();
2049 this.startHeartbeat();
2050 // Initialize connectors status
2051 if (this.hasEvses
) {
2052 for (const [evseId
, evseStatus
] of this.evses
) {
2054 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2055 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2060 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2063 connectorBootStatus
,
2070 for (const connectorId
of this.connectors
.keys()) {
2071 if (connectorId
> 0) {
2072 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2075 this.getConnectorStatus(connectorId
)
2077 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2081 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2082 await this.ocppRequestService
.requestHandler
<
2083 FirmwareStatusNotificationRequest
,
2084 FirmwareStatusNotificationResponse
2085 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2086 status: FirmwareStatus
.Installed
,
2088 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2092 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2093 this.startAutomaticTransactionGenerator();
2095 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2098 private async stopMessageSequence(
2099 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2101 // Stop WebSocket ping
2102 this.stopWebSocketPing();
2104 this.stopHeartbeat();
2105 // Stop ongoing transactions
2106 if (this.automaticTransactionGenerator
?.started
=== true) {
2107 this.stopAutomaticTransactionGenerator();
2109 await this.stopRunningTransactions(reason
);
2111 if (this.hasEvses
) {
2112 for (const [evseId
, evseStatus
] of this.evses
) {
2114 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2115 await this.ocppRequestService
.requestHandler
<
2116 StatusNotificationRequest
,
2117 StatusNotificationResponse
2120 RequestCommand
.STATUS_NOTIFICATION
,
2121 OCPPServiceUtils
.buildStatusNotificationRequest(
2124 ConnectorStatusEnum
.Unavailable
,
2128 delete connectorStatus
?.status;
2133 for (const connectorId
of this.connectors
.keys()) {
2134 if (connectorId
> 0) {
2135 await this.ocppRequestService
.requestHandler
<
2136 StatusNotificationRequest
,
2137 StatusNotificationResponse
2140 RequestCommand
.STATUS_NOTIFICATION
,
2141 OCPPServiceUtils
.buildStatusNotificationRequest(
2144 ConnectorStatusEnum
.Unavailable
2147 delete this.getConnectorStatus(connectorId
)?.status;
2153 private startWebSocketPing(): void {
2154 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2156 StandardParametersKey
.WebSocketPingInterval
2158 ? Utils
.convertToInt(
2159 ChargingStationConfigurationUtils
.getConfigurationKey(
2161 StandardParametersKey
.WebSocketPingInterval
2165 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2166 this.webSocketPingSetInterval
= setInterval(() => {
2167 if (this.isWebSocketConnectionOpened() === true) {
2168 this.wsConnection
?.ping();
2170 }, webSocketPingInterval
* 1000);
2172 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
2173 webSocketPingInterval
2176 } else if (this.webSocketPingSetInterval
) {
2178 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
2179 webSocketPingInterval
2184 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2189 private stopWebSocketPing(): void {
2190 if (this.webSocketPingSetInterval
) {
2191 clearInterval(this.webSocketPingSetInterval
);
2192 delete this.webSocketPingSetInterval
;
2196 private getConfiguredSupervisionUrl(): URL
{
2197 let configuredSupervisionUrl
: string;
2198 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2199 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
2200 let configuredSupervisionUrlIndex
: number;
2201 switch (Configuration
.getSupervisionUrlDistribution()) {
2202 case SupervisionUrlDistribution
.RANDOM
:
2203 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2205 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2206 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2208 Object.values(SupervisionUrlDistribution
).includes(
2209 Configuration
.getSupervisionUrlDistribution()
2212 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2213 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2216 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2219 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
];
2221 configuredSupervisionUrl
= supervisionUrls
as string;
2223 if (Utils
.isNotEmptyString(configuredSupervisionUrl
)) {
2224 return new URL(configuredSupervisionUrl
);
2226 const errorMsg
= 'No supervision url(s) configured';
2227 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2228 throw new BaseError(`${errorMsg}`);
2231 private stopHeartbeat(): void {
2232 if (this.heartbeatSetInterval
) {
2233 clearInterval(this.heartbeatSetInterval
);
2234 delete this.heartbeatSetInterval
;
2238 private terminateWSConnection(): void {
2239 if (this.isWebSocketConnectionOpened() === true) {
2240 this.wsConnection
?.terminate();
2241 this.wsConnection
= null;
2245 private getReconnectExponentialDelay(): boolean {
2246 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2249 private async reconnect(): Promise
<void> {
2250 // Stop WebSocket ping
2251 this.stopWebSocketPing();
2253 this.stopHeartbeat();
2254 // Stop the ATG if needed
2255 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2256 this.stopAutomaticTransactionGenerator();
2259 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2260 this.getAutoReconnectMaxRetries() === -1
2262 ++this.autoReconnectRetryCount
;
2263 const reconnectDelay
= this.getReconnectExponentialDelay()
2264 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2265 : this.getConnectionTimeout() * 1000;
2266 const reconnectDelayWithdraw
= 1000;
2267 const reconnectTimeout
=
2268 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2269 ? reconnectDelay
- reconnectDelayWithdraw
2272 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2275 )}ms, timeout ${reconnectTimeout}ms`
2277 await Utils
.sleep(reconnectDelay
);
2279 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2281 this.openWSConnection(
2283 ...(this.stationInfo
?.wsOptions
?? {}),
2284 handshakeTimeout
: reconnectTimeout
,
2286 { closeOpened
: true }
2288 this.wsConnectionRestarted
= true;
2289 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2291 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2292 this.autoReconnectRetryCount
2293 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`