Set connector status at start given its availability first
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import crypto from 'crypto';
4 import fs from 'fs';
5 import path from 'path';
6 import { URL } from 'url';
7 import { parentPort } from 'worker_threads';
8
9 import WebSocket, { Data, RawData } from 'ws';
10
11 import BaseError from '../exception/BaseError';
12 import OCPPError from '../exception/OCPPError';
13 import PerformanceStatistics from '../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration } from '../types/AutomaticTransactionGenerator';
15 import type { ChargingStationConfiguration } from '../types/ChargingStationConfiguration';
16 import type { ChargingStationInfo } from '../types/ChargingStationInfo';
17 import type { ChargingStationOcppConfiguration } from '../types/ChargingStationOcppConfiguration';
18 import {
19 type ChargingStationTemplate,
20 CurrentType,
21 PowerUnits,
22 type WsOptions,
23 } from '../types/ChargingStationTemplate';
24 import { SupervisionUrlDistribution } from '../types/ConfigurationData';
25 import type { ConnectorStatus } from '../types/ConnectorStatus';
26 import { FileType } from '../types/FileType';
27 import type { JsonType } from '../types/JsonType';
28 import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
29 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
30 import { ChargingProfile, ChargingRateUnitType } from '../types/ocpp/ChargingProfile';
31 import {
32 ConnectorPhaseRotation,
33 StandardParametersKey,
34 SupportedFeatureProfiles,
35 VendorDefaultParametersKey,
36 } from '../types/ocpp/Configuration';
37 import { ErrorType } from '../types/ocpp/ErrorType';
38 import { MessageType } from '../types/ocpp/MessageType';
39 import { MeterValue, MeterValueMeasurand } from '../types/ocpp/MeterValues';
40 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
41 import {
42 AvailabilityType,
43 BootNotificationRequest,
44 CachedRequest,
45 HeartbeatRequest,
46 IncomingRequest,
47 IncomingRequestCommand,
48 MeterValuesRequest,
49 RequestCommand,
50 StatusNotificationRequest,
51 } from '../types/ocpp/Requests';
52 import {
53 BootNotificationResponse,
54 ErrorResponse,
55 HeartbeatResponse,
56 MeterValuesResponse,
57 RegistrationStatus,
58 Response,
59 StatusNotificationResponse,
60 } from '../types/ocpp/Responses';
61 import {
62 StopTransactionReason,
63 StopTransactionRequest,
64 StopTransactionResponse,
65 } from '../types/ocpp/Transaction';
66 import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
67 import Configuration from '../utils/Configuration';
68 import Constants from '../utils/Constants';
69 import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils';
70 import FileUtils from '../utils/FileUtils';
71 import logger from '../utils/Logger';
72 import Utils from '../utils/Utils';
73 import AuthorizedTagsCache from './AuthorizedTagsCache';
74 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
75 import { ChargingStationConfigurationUtils } from './ChargingStationConfigurationUtils';
76 import { ChargingStationUtils } from './ChargingStationUtils';
77 import ChargingStationWorkerBroadcastChannel from './ChargingStationWorkerBroadcastChannel';
78 import { MessageChannelUtils } from './MessageChannelUtils';
79 import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
80 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
81 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
82 import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
83 import type OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
84 import type OCPPRequestService from './ocpp/OCPPRequestService';
85 import SharedLRUCache from './SharedLRUCache';
86
87 export default class ChargingStation {
88 public readonly index: number;
89 public readonly templateFile: string;
90 public stationInfo!: ChargingStationInfo;
91 public started: boolean;
92 public authorizedTagsCache: AuthorizedTagsCache;
93 public automaticTransactionGenerator!: AutomaticTransactionGenerator;
94 public ocppConfiguration!: ChargingStationOcppConfiguration;
95 public wsConnection!: WebSocket;
96 public readonly connectors: Map<number, ConnectorStatus>;
97 public readonly requests: Map<string, CachedRequest>;
98 public performanceStatistics!: PerformanceStatistics;
99 public heartbeatSetInterval!: NodeJS.Timeout;
100 public ocppRequestService!: OCPPRequestService;
101 public bootNotificationRequest!: BootNotificationRequest;
102 public bootNotificationResponse!: BootNotificationResponse | null;
103 public powerDivider!: number;
104 private starting: boolean;
105 private stopping: boolean;
106 private configurationFile!: string;
107 private configurationFileHash!: string;
108 private connectorsConfigurationHash!: string;
109 private ocppIncomingRequestService!: OCPPIncomingRequestService;
110 private readonly messageBuffer: Set<string>;
111 private configuredSupervisionUrl!: URL;
112 private configuredSupervisionUrlIndex!: number;
113 private wsConnectionRestarted: boolean;
114 private autoReconnectRetryCount: number;
115 private templateFileWatcher!: fs.FSWatcher;
116 private readonly sharedLRUCache: SharedLRUCache;
117 private webSocketPingSetInterval!: NodeJS.Timeout;
118 private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel;
119
120 constructor(index: number, templateFile: string) {
121 this.started = false;
122 this.starting = false;
123 this.stopping = false;
124 this.wsConnectionRestarted = false;
125 this.autoReconnectRetryCount = 0;
126 this.index = index;
127 this.templateFile = templateFile;
128 this.connectors = new Map<number, ConnectorStatus>();
129 this.requests = new Map<string, CachedRequest>();
130 this.messageBuffer = new Set<string>();
131 this.sharedLRUCache = SharedLRUCache.getInstance();
132 this.authorizedTagsCache = AuthorizedTagsCache.getInstance();
133 this.chargingStationWorkerBroadcastChannel = new ChargingStationWorkerBroadcastChannel(this);
134
135 this.initialize();
136 }
137
138 private get wsConnectionUrl(): URL {
139 return new URL(
140 (this.getSupervisionUrlOcppConfiguration()
141 ? ChargingStationConfigurationUtils.getConfigurationKey(
142 this,
143 this.getSupervisionUrlOcppKey()
144 ).value
145 : this.configuredSupervisionUrl.href) +
146 '/' +
147 this.stationInfo.chargingStationId
148 );
149 }
150
151 public logPrefix(): string {
152 return Utils.logPrefix(
153 ` ${
154 this?.stationInfo?.chargingStationId ??
155 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
156 } |`
157 );
158 }
159
160 public hasAuthorizedTags(): boolean {
161 return !Utils.isEmptyArray(
162 this.authorizedTagsCache.getAuthorizedTags(
163 ChargingStationUtils.getAuthorizationFile(this.stationInfo)
164 )
165 );
166 }
167
168 public getEnableStatistics(): boolean | undefined {
169 return !Utils.isUndefined(this.stationInfo.enableStatistics)
170 ? this.stationInfo.enableStatistics
171 : true;
172 }
173
174 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
175 return this.stationInfo.mustAuthorizeAtRemoteStart ?? true;
176 }
177
178 public getPayloadSchemaValidation(): boolean | undefined {
179 return this.stationInfo.payloadSchemaValidation ?? true;
180 }
181
182 public getNumberOfPhases(stationInfo?: ChargingStationInfo): number | undefined {
183 const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
184 switch (this.getCurrentOutType(stationInfo)) {
185 case CurrentType.AC:
186 return !Utils.isUndefined(localStationInfo.numberOfPhases)
187 ? localStationInfo.numberOfPhases
188 : 3;
189 case CurrentType.DC:
190 return 0;
191 }
192 }
193
194 public isWebSocketConnectionOpened(): boolean {
195 return this?.wsConnection?.readyState === WebSocket.OPEN;
196 }
197
198 public getRegistrationStatus(): RegistrationStatus {
199 return this?.bootNotificationResponse?.status;
200 }
201
202 public isInUnknownState(): boolean {
203 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
204 }
205
206 public isInPendingState(): boolean {
207 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
208 }
209
210 public isInAcceptedState(): boolean {
211 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
212 }
213
214 public isInRejectedState(): boolean {
215 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
216 }
217
218 public isRegistered(): boolean {
219 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
220 }
221
222 public isChargingStationAvailable(): boolean {
223 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
224 }
225
226 public isConnectorAvailable(id: number): boolean {
227 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
228 }
229
230 public getNumberOfConnectors(): number {
231 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
232 }
233
234 public getConnectorStatus(id: number): ConnectorStatus | undefined {
235 return this.connectors.get(id);
236 }
237
238 public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType {
239 return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC;
240 }
241
242 public getOcppStrictCompliance(): boolean {
243 return this.stationInfo?.ocppStrictCompliance ?? false;
244 }
245
246 public getVoltageOut(stationInfo?: ChargingStationInfo): number | undefined {
247 const defaultVoltageOut = ChargingStationUtils.getDefaultVoltageOut(
248 this.getCurrentOutType(stationInfo),
249 this.templateFile,
250 this.logPrefix()
251 );
252 const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
253 return !Utils.isUndefined(localStationInfo.voltageOut)
254 ? localStationInfo.voltageOut
255 : defaultVoltageOut;
256 }
257
258 public getConnectorMaximumAvailablePower(connectorId: number): number {
259 let connectorAmperageLimitationPowerLimit: number;
260 if (
261 !Utils.isNullOrUndefined(this.getAmperageLimitation()) &&
262 this.getAmperageLimitation() < this.stationInfo.maximumAmperage
263 ) {
264 connectorAmperageLimitationPowerLimit =
265 (this.getCurrentOutType() === CurrentType.AC
266 ? ACElectricUtils.powerTotal(
267 this.getNumberOfPhases(),
268 this.getVoltageOut(),
269 this.getAmperageLimitation() * this.getNumberOfConnectors()
270 )
271 : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) /
272 this.powerDivider;
273 }
274 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
275 const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId);
276 return Math.min(
277 isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower,
278 isNaN(connectorAmperageLimitationPowerLimit)
279 ? Infinity
280 : connectorAmperageLimitationPowerLimit,
281 isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit
282 );
283 }
284
285 public getTransactionIdTag(transactionId: number): string | undefined {
286 for (const connectorId of this.connectors.keys()) {
287 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
288 return this.getConnectorStatus(connectorId).transactionIdTag;
289 }
290 }
291 }
292
293 public getOutOfOrderEndMeterValues(): boolean {
294 return this.stationInfo?.outOfOrderEndMeterValues ?? false;
295 }
296
297 public getBeginEndMeterValues(): boolean {
298 return this.stationInfo?.beginEndMeterValues ?? false;
299 }
300
301 public getMeteringPerTransaction(): boolean {
302 return this.stationInfo?.meteringPerTransaction ?? true;
303 }
304
305 public getTransactionDataMeterValues(): boolean {
306 return this.stationInfo?.transactionDataMeterValues ?? false;
307 }
308
309 public getMainVoltageMeterValues(): boolean {
310 return this.stationInfo?.mainVoltageMeterValues ?? true;
311 }
312
313 public getPhaseLineToLineVoltageMeterValues(): boolean {
314 return this.stationInfo?.phaseLineToLineVoltageMeterValues ?? false;
315 }
316
317 public getCustomValueLimitationMeterValues(): boolean {
318 return this.stationInfo?.customValueLimitationMeterValues ?? true;
319 }
320
321 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
322 for (const connectorId of this.connectors.keys()) {
323 if (
324 connectorId > 0 &&
325 this.getConnectorStatus(connectorId)?.transactionId === transactionId
326 ) {
327 return connectorId;
328 }
329 }
330 }
331
332 public getEnergyActiveImportRegisterByTransactionId(
333 transactionId: number,
334 meterStop = false
335 ): number {
336 return this.getEnergyActiveImportRegister(
337 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId)),
338 meterStop
339 );
340 }
341
342 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number {
343 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId));
344 }
345
346 public getAuthorizeRemoteTxRequests(): boolean {
347 const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey(
348 this,
349 StandardParametersKey.AuthorizeRemoteTxRequests
350 );
351 return authorizeRemoteTxRequests
352 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
353 : false;
354 }
355
356 public getLocalAuthListEnabled(): boolean {
357 const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey(
358 this,
359 StandardParametersKey.LocalAuthListEnabled
360 );
361 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
362 }
363
364 public startHeartbeat(): void {
365 if (
366 this.getHeartbeatInterval() &&
367 this.getHeartbeatInterval() > 0 &&
368 !this.heartbeatSetInterval
369 ) {
370 // eslint-disable-next-line @typescript-eslint/no-misused-promises
371 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
372 await this.ocppRequestService.requestHandler<HeartbeatRequest, HeartbeatResponse>(
373 this,
374 RequestCommand.HEARTBEAT
375 );
376 }, this.getHeartbeatInterval());
377 logger.info(
378 this.logPrefix() +
379 ' Heartbeat started every ' +
380 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
381 );
382 } else if (this.heartbeatSetInterval) {
383 logger.info(
384 this.logPrefix() +
385 ' Heartbeat already started every ' +
386 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
387 );
388 } else {
389 logger.error(
390 `${this.logPrefix()} Heartbeat interval set to ${
391 this.getHeartbeatInterval()
392 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
393 : this.getHeartbeatInterval()
394 }, not starting the heartbeat`
395 );
396 }
397 }
398
399 public restartHeartbeat(): void {
400 // Stop heartbeat
401 this.stopHeartbeat();
402 // Start heartbeat
403 this.startHeartbeat();
404 }
405
406 public restartWebSocketPing(): void {
407 // Stop WebSocket ping
408 this.stopWebSocketPing();
409 // Start WebSocket ping
410 this.startWebSocketPing();
411 }
412
413 public startMeterValues(connectorId: number, interval: number): void {
414 if (connectorId === 0) {
415 logger.error(
416 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
417 );
418 return;
419 }
420 if (!this.getConnectorStatus(connectorId)) {
421 logger.error(
422 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
423 );
424 return;
425 }
426 if (this.getConnectorStatus(connectorId)?.transactionStarted === false) {
427 logger.error(
428 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
429 );
430 return;
431 } else if (
432 this.getConnectorStatus(connectorId)?.transactionStarted === true &&
433 !this.getConnectorStatus(connectorId)?.transactionId
434 ) {
435 logger.error(
436 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
437 );
438 return;
439 }
440 if (interval > 0) {
441 // eslint-disable-next-line @typescript-eslint/no-misused-promises
442 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 async (): Promise<void> => {
445 // FIXME: Implement OCPP version agnostic helpers
446 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
447 this,
448 connectorId,
449 this.getConnectorStatus(connectorId).transactionId,
450 interval
451 );
452 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
453 this,
454 RequestCommand.METER_VALUES,
455 {
456 connectorId,
457 transactionId: this.getConnectorStatus(connectorId).transactionId,
458 meterValue: [meterValue],
459 }
460 );
461 },
462 interval
463 );
464 } else {
465 logger.error(
466 `${this.logPrefix()} Charging station ${
467 StandardParametersKey.MeterValueSampleInterval
468 } configuration set to ${
469 interval ? Utils.formatDurationMilliSeconds(interval) : interval
470 }, not sending MeterValues`
471 );
472 }
473 }
474
475 public start(): void {
476 if (this.started === false) {
477 if (this.starting === false) {
478 this.starting = true;
479 if (this.getEnableStatistics()) {
480 this.performanceStatistics.start();
481 }
482 this.openWSConnection();
483 // Monitor charging station template file
484 this.templateFileWatcher = FileUtils.watchJsonFile(
485 this.logPrefix(),
486 FileType.ChargingStationTemplate,
487 this.templateFile,
488 null,
489 (event, filename): void => {
490 if (filename && event === 'change') {
491 try {
492 logger.debug(
493 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
494 this.templateFile
495 } file have changed, reload`
496 );
497 this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
498 // Initialize
499 this.initialize();
500 // Restart the ATG
501 this.stopAutomaticTransactionGenerator();
502 if (
503 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable === true
504 ) {
505 this.startAutomaticTransactionGenerator();
506 }
507 if (this.getEnableStatistics()) {
508 this.performanceStatistics.restart();
509 } else {
510 this.performanceStatistics.stop();
511 }
512 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
513 } catch (error) {
514 logger.error(
515 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
516 error
517 );
518 }
519 }
520 }
521 );
522 this.started = true;
523 parentPort.postMessage(MessageChannelUtils.buildStartedMessage(this));
524 this.starting = false;
525 } else {
526 logger.warn(`${this.logPrefix()} Charging station is already starting...`);
527 }
528 } else {
529 logger.warn(`${this.logPrefix()} Charging station is already started...`);
530 }
531 }
532
533 public async stop(reason?: StopTransactionReason): Promise<void> {
534 if (this.started === true) {
535 if (this.stopping === false) {
536 this.stopping = true;
537 await this.stopMessageSequence(reason);
538 this.closeWSConnection();
539 this.wsConnectionRestarted = false;
540 if (this.getEnableStatistics()) {
541 this.performanceStatistics.stop();
542 }
543 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
544 this.templateFileWatcher.close();
545 this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
546 this.bootNotificationResponse = null;
547 this.started = false;
548 parentPort.postMessage(MessageChannelUtils.buildStoppedMessage(this));
549 this.stopping = false;
550 } else {
551 logger.warn(`${this.logPrefix()} Charging station is already stopping...`);
552 }
553 } else {
554 logger.warn(`${this.logPrefix()} Charging station is already stopped...`);
555 }
556 }
557
558 public async reset(reason?: StopTransactionReason): Promise<void> {
559 await this.stop(reason);
560 await Utils.sleep(this.stationInfo.resetTime);
561 this.initialize();
562 this.start();
563 }
564
565 public saveOcppConfiguration(): void {
566 if (this.getOcppPersistentConfiguration()) {
567 this.saveConfiguration();
568 }
569 }
570
571 public resetConnectorStatus(connectorId: number): void {
572 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
573 this.getConnectorStatus(connectorId).idTagAuthorized = false;
574 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
575 this.getConnectorStatus(connectorId).transactionStarted = false;
576 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
577 delete this.getConnectorStatus(connectorId).authorizeIdTag;
578 delete this.getConnectorStatus(connectorId).transactionId;
579 delete this.getConnectorStatus(connectorId).transactionIdTag;
580 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
581 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
582 this.stopMeterValues(connectorId);
583 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
584 }
585
586 public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean {
587 return ChargingStationConfigurationUtils.getConfigurationKey(
588 this,
589 StandardParametersKey.SupportedFeatureProfiles
590 )?.value.includes(featureProfile);
591 }
592
593 public bufferMessage(message: string): void {
594 this.messageBuffer.add(message);
595 }
596
597 public openWSConnection(
598 options: WsOptions = this.stationInfo?.wsOptions ?? {},
599 params: { closeOpened?: boolean; terminateOpened?: boolean } = {
600 closeOpened: false,
601 terminateOpened: false,
602 }
603 ): void {
604 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
605 params.closeOpened = params?.closeOpened ?? false;
606 params.terminateOpened = params?.terminateOpened ?? false;
607 if (
608 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
609 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
610 ) {
611 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
612 }
613 if (params?.closeOpened) {
614 this.closeWSConnection();
615 }
616 if (params?.terminateOpened) {
617 this.terminateWSConnection();
618 }
619 let protocol: string;
620 switch (this.getOcppVersion()) {
621 case OCPPVersion.VERSION_16:
622 protocol = 'ocpp' + OCPPVersion.VERSION_16;
623 break;
624 default:
625 this.handleUnsupportedVersion(this.getOcppVersion());
626 break;
627 }
628
629 if (this.isWebSocketConnectionOpened() === true) {
630 logger.warn(
631 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
632 );
633 return;
634 }
635
636 logger.info(
637 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
638 );
639
640 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
641
642 // Handle WebSocket message
643 this.wsConnection.on(
644 'message',
645 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
646 );
647 // Handle WebSocket error
648 this.wsConnection.on(
649 'error',
650 this.onError.bind(this) as (this: WebSocket, error: Error) => void
651 );
652 // Handle WebSocket close
653 this.wsConnection.on(
654 'close',
655 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
656 );
657 // Handle WebSocket open
658 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
659 // Handle WebSocket ping
660 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
661 // Handle WebSocket pong
662 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
663 }
664
665 public closeWSConnection(): void {
666 if (this.isWebSocketConnectionOpened() === true) {
667 this.wsConnection.close();
668 this.wsConnection = null;
669 }
670 }
671
672 public startAutomaticTransactionGenerator(
673 connectorIds?: number[],
674 automaticTransactionGeneratorConfiguration?: AutomaticTransactionGeneratorConfiguration
675 ): void {
676 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(
677 automaticTransactionGeneratorConfiguration ??
678 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
679 this
680 );
681 if (!Utils.isEmptyArray(connectorIds)) {
682 for (const connectorId of connectorIds) {
683 this.automaticTransactionGenerator.startConnector(connectorId);
684 }
685 } else {
686 this.automaticTransactionGenerator.start();
687 }
688 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
689 }
690
691 public stopAutomaticTransactionGenerator(connectorIds?: number[]): void {
692 if (!Utils.isEmptyArray(connectorIds)) {
693 for (const connectorId of connectorIds) {
694 this.automaticTransactionGenerator?.stopConnector(connectorId);
695 }
696 } else {
697 this.automaticTransactionGenerator?.stop();
698 }
699 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
700 }
701
702 public async stopTransactionOnConnector(
703 connectorId: number,
704 reason = StopTransactionReason.NONE
705 ): Promise<StopTransactionResponse> {
706 const transactionId = this.getConnectorStatus(connectorId).transactionId;
707 if (
708 this.getBeginEndMeterValues() &&
709 this.getOcppStrictCompliance() &&
710 !this.getOutOfOrderEndMeterValues()
711 ) {
712 // FIXME: Implement OCPP version agnostic helpers
713 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
714 this,
715 connectorId,
716 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
717 );
718 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
719 this,
720 RequestCommand.METER_VALUES,
721 {
722 connectorId,
723 transactionId,
724 meterValue: [transactionEndMeterValue],
725 }
726 );
727 }
728 return this.ocppRequestService.requestHandler<StopTransactionRequest, StopTransactionResponse>(
729 this,
730 RequestCommand.STOP_TRANSACTION,
731 {
732 transactionId,
733 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true),
734 reason,
735 }
736 );
737 }
738
739 private flushMessageBuffer(): void {
740 if (this.messageBuffer.size > 0) {
741 this.messageBuffer.forEach((message) => {
742 // TODO: evaluate the need to track performance
743 this.wsConnection.send(message);
744 this.messageBuffer.delete(message);
745 });
746 }
747 }
748
749 private getSupervisionUrlOcppConfiguration(): boolean {
750 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
751 }
752
753 private getSupervisionUrlOcppKey(): string {
754 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
755 }
756
757 private getTemplateFromFile(): ChargingStationTemplate | null {
758 let template: ChargingStationTemplate = null;
759 try {
760 if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) {
761 template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash);
762 } else {
763 const measureId = `${FileType.ChargingStationTemplate} read`;
764 const beginId = PerformanceStatistics.beginMeasure(measureId);
765 template = JSON.parse(
766 fs.readFileSync(this.templateFile, 'utf8')
767 ) as ChargingStationTemplate;
768 PerformanceStatistics.endMeasure(measureId, beginId);
769 template.templateHash = crypto
770 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
771 .update(JSON.stringify(template))
772 .digest('hex');
773 this.sharedLRUCache.setChargingStationTemplate(template);
774 }
775 } catch (error) {
776 FileUtils.handleFileException(
777 this.logPrefix(),
778 FileType.ChargingStationTemplate,
779 this.templateFile,
780 error as NodeJS.ErrnoException
781 );
782 }
783 return template;
784 }
785
786 private getStationInfoFromTemplate(): ChargingStationInfo {
787 const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile();
788 if (Utils.isNullOrUndefined(stationTemplate)) {
789 const errorMsg = 'Failed to read charging station template file';
790 logger.error(`${this.logPrefix()} ${errorMsg}`);
791 throw new BaseError(errorMsg);
792 }
793 if (Utils.isEmptyObject(stationTemplate)) {
794 const errorMsg = `Empty charging station information from template file ${this.templateFile}`;
795 logger.error(`${this.logPrefix()} ${errorMsg}`);
796 throw new BaseError(errorMsg);
797 }
798 // Deprecation template keys section
799 ChargingStationUtils.warnDeprecatedTemplateKey(
800 stationTemplate,
801 'supervisionUrl',
802 this.templateFile,
803 this.logPrefix(),
804 "Use 'supervisionUrls' instead"
805 );
806 ChargingStationUtils.convertDeprecatedTemplateKey(
807 stationTemplate,
808 'supervisionUrl',
809 'supervisionUrls'
810 );
811 const stationInfo: ChargingStationInfo =
812 ChargingStationUtils.stationTemplateToStationInfo(stationTemplate);
813 stationInfo.hashId = ChargingStationUtils.getHashId(this.index, stationTemplate);
814 stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId(
815 this.index,
816 stationTemplate
817 );
818 ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
819 if (!Utils.isEmptyArray(stationTemplate.power)) {
820 stationTemplate.power = stationTemplate.power as number[];
821 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
822 stationInfo.maximumPower =
823 stationTemplate.powerUnit === PowerUnits.KILO_WATT
824 ? stationTemplate.power[powerArrayRandomIndex] * 1000
825 : stationTemplate.power[powerArrayRandomIndex];
826 } else {
827 stationTemplate.power = stationTemplate.power as number;
828 stationInfo.maximumPower =
829 stationTemplate.powerUnit === PowerUnits.KILO_WATT
830 ? stationTemplate.power * 1000
831 : stationTemplate.power;
832 }
833 stationInfo.resetTime = stationTemplate.resetTime
834 ? stationTemplate.resetTime * 1000
835 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
836 const configuredMaxConnectors =
837 ChargingStationUtils.getConfiguredNumberOfConnectors(stationTemplate);
838 ChargingStationUtils.checkConfiguredMaxConnectors(
839 configuredMaxConnectors,
840 this.templateFile,
841 this.logPrefix()
842 );
843 const templateMaxConnectors =
844 ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate);
845 ChargingStationUtils.checkTemplateMaxConnectors(
846 templateMaxConnectors,
847 this.templateFile,
848 this.logPrefix()
849 );
850 if (
851 configuredMaxConnectors >
852 (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
853 !stationTemplate?.randomConnectors
854 ) {
855 logger.warn(
856 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
857 this.templateFile
858 }, forcing random connector configurations affectation`
859 );
860 stationInfo.randomConnectors = true;
861 }
862 // Build connectors if needed (FIXME: should be factored out)
863 this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors);
864 stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo);
865 ChargingStationUtils.createStationInfoHash(stationInfo);
866 return stationInfo;
867 }
868
869 private getStationInfoFromFile(): ChargingStationInfo | null {
870 let stationInfo: ChargingStationInfo = null;
871 this.getStationInfoPersistentConfiguration() &&
872 (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null);
873 stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo);
874 return stationInfo;
875 }
876
877 private getStationInfo(): ChargingStationInfo {
878 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
879 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
880 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
881 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
882 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
883 return this.stationInfo;
884 }
885 return stationInfoFromFile;
886 }
887 stationInfoFromFile &&
888 ChargingStationUtils.propagateSerialNumber(
889 this.getTemplateFromFile(),
890 stationInfoFromFile,
891 stationInfoFromTemplate
892 );
893 return stationInfoFromTemplate;
894 }
895
896 private saveStationInfo(): void {
897 if (this.getStationInfoPersistentConfiguration()) {
898 this.saveConfiguration();
899 }
900 }
901
902 private getOcppVersion(): OCPPVersion {
903 return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
904 }
905
906 private getOcppPersistentConfiguration(): boolean {
907 return this.stationInfo?.ocppPersistentConfiguration ?? true;
908 }
909
910 private getStationInfoPersistentConfiguration(): boolean {
911 return this.stationInfo?.stationInfoPersistentConfiguration ?? true;
912 }
913
914 private handleUnsupportedVersion(version: OCPPVersion) {
915 const errMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
916 logger.error(`${this.logPrefix()} ${errMsg}`);
917 throw new BaseError(errMsg);
918 }
919
920 private initialize(): void {
921 this.configurationFile = path.join(
922 path.dirname(this.templateFile.replace('station-templates', 'configurations')),
923 ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile()) + '.json'
924 );
925 this.stationInfo = this.getStationInfo();
926 this.saveStationInfo();
927 // Avoid duplication of connectors related information in RAM
928 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
929 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
930 if (this.getEnableStatistics()) {
931 this.performanceStatistics = PerformanceStatistics.getInstance(
932 this.stationInfo.hashId,
933 this.stationInfo.chargingStationId,
934 this.configuredSupervisionUrl
935 );
936 }
937 this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest(
938 this.stationInfo
939 );
940 this.powerDivider = this.getPowerDivider();
941 // OCPP configuration
942 this.ocppConfiguration = this.getOcppConfiguration();
943 this.initializeOcppConfiguration();
944 switch (this.getOcppVersion()) {
945 case OCPPVersion.VERSION_16:
946 this.ocppIncomingRequestService =
947 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
948 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
949 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
950 );
951 break;
952 default:
953 this.handleUnsupportedVersion(this.getOcppVersion());
954 break;
955 }
956 if (this.stationInfo?.autoRegister) {
957 this.bootNotificationResponse = {
958 currentTime: new Date().toISOString(),
959 interval: this.getHeartbeatInterval() / 1000,
960 status: RegistrationStatus.ACCEPTED,
961 };
962 }
963 }
964
965 private initializeOcppConfiguration(): void {
966 if (
967 !ChargingStationConfigurationUtils.getConfigurationKey(
968 this,
969 StandardParametersKey.HeartbeatInterval
970 )
971 ) {
972 ChargingStationConfigurationUtils.addConfigurationKey(
973 this,
974 StandardParametersKey.HeartbeatInterval,
975 '0'
976 );
977 }
978 if (
979 !ChargingStationConfigurationUtils.getConfigurationKey(
980 this,
981 StandardParametersKey.HeartBeatInterval
982 )
983 ) {
984 ChargingStationConfigurationUtils.addConfigurationKey(
985 this,
986 StandardParametersKey.HeartBeatInterval,
987 '0',
988 { visible: false }
989 );
990 }
991 if (
992 this.getSupervisionUrlOcppConfiguration() &&
993 !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
994 ) {
995 ChargingStationConfigurationUtils.addConfigurationKey(
996 this,
997 this.getSupervisionUrlOcppKey(),
998 this.configuredSupervisionUrl.href,
999 { reboot: true }
1000 );
1001 } else if (
1002 !this.getSupervisionUrlOcppConfiguration() &&
1003 ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1004 ) {
1005 ChargingStationConfigurationUtils.deleteConfigurationKey(
1006 this,
1007 this.getSupervisionUrlOcppKey(),
1008 { save: false }
1009 );
1010 }
1011 if (
1012 this.stationInfo.amperageLimitationOcppKey &&
1013 !ChargingStationConfigurationUtils.getConfigurationKey(
1014 this,
1015 this.stationInfo.amperageLimitationOcppKey
1016 )
1017 ) {
1018 ChargingStationConfigurationUtils.addConfigurationKey(
1019 this,
1020 this.stationInfo.amperageLimitationOcppKey,
1021 (
1022 this.stationInfo.maximumAmperage *
1023 ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1024 ).toString()
1025 );
1026 }
1027 if (
1028 !ChargingStationConfigurationUtils.getConfigurationKey(
1029 this,
1030 StandardParametersKey.SupportedFeatureProfiles
1031 )
1032 ) {
1033 ChargingStationConfigurationUtils.addConfigurationKey(
1034 this,
1035 StandardParametersKey.SupportedFeatureProfiles,
1036 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1037 );
1038 }
1039 ChargingStationConfigurationUtils.addConfigurationKey(
1040 this,
1041 StandardParametersKey.NumberOfConnectors,
1042 this.getNumberOfConnectors().toString(),
1043 { readonly: true },
1044 { overwrite: true }
1045 );
1046 if (
1047 !ChargingStationConfigurationUtils.getConfigurationKey(
1048 this,
1049 StandardParametersKey.MeterValuesSampledData
1050 )
1051 ) {
1052 ChargingStationConfigurationUtils.addConfigurationKey(
1053 this,
1054 StandardParametersKey.MeterValuesSampledData,
1055 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1056 );
1057 }
1058 if (
1059 !ChargingStationConfigurationUtils.getConfigurationKey(
1060 this,
1061 StandardParametersKey.ConnectorPhaseRotation
1062 )
1063 ) {
1064 const connectorPhaseRotation = [];
1065 for (const connectorId of this.connectors.keys()) {
1066 // AC/DC
1067 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1068 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1069 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1070 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1071 // AC
1072 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1073 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1074 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1075 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1076 }
1077 }
1078 ChargingStationConfigurationUtils.addConfigurationKey(
1079 this,
1080 StandardParametersKey.ConnectorPhaseRotation,
1081 connectorPhaseRotation.toString()
1082 );
1083 }
1084 if (
1085 !ChargingStationConfigurationUtils.getConfigurationKey(
1086 this,
1087 StandardParametersKey.AuthorizeRemoteTxRequests
1088 )
1089 ) {
1090 ChargingStationConfigurationUtils.addConfigurationKey(
1091 this,
1092 StandardParametersKey.AuthorizeRemoteTxRequests,
1093 'true'
1094 );
1095 }
1096 if (
1097 !ChargingStationConfigurationUtils.getConfigurationKey(
1098 this,
1099 StandardParametersKey.LocalAuthListEnabled
1100 ) &&
1101 ChargingStationConfigurationUtils.getConfigurationKey(
1102 this,
1103 StandardParametersKey.SupportedFeatureProfiles
1104 )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement)
1105 ) {
1106 ChargingStationConfigurationUtils.addConfigurationKey(
1107 this,
1108 StandardParametersKey.LocalAuthListEnabled,
1109 'false'
1110 );
1111 }
1112 if (
1113 !ChargingStationConfigurationUtils.getConfigurationKey(
1114 this,
1115 StandardParametersKey.ConnectionTimeOut
1116 )
1117 ) {
1118 ChargingStationConfigurationUtils.addConfigurationKey(
1119 this,
1120 StandardParametersKey.ConnectionTimeOut,
1121 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1122 );
1123 }
1124 this.saveOcppConfiguration();
1125 }
1126
1127 private initializeConnectors(
1128 stationInfo: ChargingStationInfo,
1129 configuredMaxConnectors: number,
1130 templateMaxConnectors: number
1131 ): void {
1132 if (!stationInfo?.Connectors && this.connectors.size === 0) {
1133 const logMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1134 logger.error(`${this.logPrefix()} ${logMsg}`);
1135 throw new BaseError(logMsg);
1136 }
1137 if (!stationInfo?.Connectors[0]) {
1138 logger.warn(
1139 `${this.logPrefix()} Charging station information from template ${
1140 this.templateFile
1141 } with no connector Id 0 configuration`
1142 );
1143 }
1144 if (stationInfo?.Connectors) {
1145 const connectorsConfigHash = crypto
1146 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1147 .update(JSON.stringify(stationInfo?.Connectors) + configuredMaxConnectors.toString())
1148 .digest('hex');
1149 const connectorsConfigChanged =
1150 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1151 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1152 connectorsConfigChanged && this.connectors.clear();
1153 this.connectorsConfigurationHash = connectorsConfigHash;
1154 // Add connector Id 0
1155 let lastConnector = '0';
1156 for (lastConnector in stationInfo?.Connectors) {
1157 const connectorStatus = stationInfo?.Connectors[lastConnector];
1158 const lastConnectorId = Utils.convertToInt(lastConnector);
1159 if (
1160 lastConnectorId === 0 &&
1161 this.getUseConnectorId0(stationInfo) === true &&
1162 connectorStatus
1163 ) {
1164 this.checkStationInfoConnectorStatus(lastConnectorId, connectorStatus);
1165 this.connectors.set(
1166 lastConnectorId,
1167 Utils.cloneObject<ConnectorStatus>(connectorStatus)
1168 );
1169 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1170 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1171 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1172 }
1173 }
1174 }
1175 // Generate all connectors
1176 if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
1177 for (let index = 1; index <= configuredMaxConnectors; index++) {
1178 const randConnectorId = stationInfo?.randomConnectors
1179 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1180 : index;
1181 const connectorStatus = stationInfo?.Connectors[randConnectorId.toString()];
1182 this.checkStationInfoConnectorStatus(randConnectorId, connectorStatus);
1183 this.connectors.set(index, Utils.cloneObject<ConnectorStatus>(connectorStatus));
1184 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1185 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1186 this.getConnectorStatus(index).chargingProfiles = [];
1187 }
1188 }
1189 }
1190 }
1191 } else {
1192 logger.warn(
1193 `${this.logPrefix()} Charging station information from template ${
1194 this.templateFile
1195 } with no connectors configuration defined, using already defined connectors`
1196 );
1197 }
1198 // Initialize transaction attributes on connectors
1199 for (const connectorId of this.connectors.keys()) {
1200 if (
1201 connectorId > 0 &&
1202 (this.getConnectorStatus(connectorId).transactionStarted === undefined ||
1203 this.getConnectorStatus(connectorId).transactionStarted === false)
1204 ) {
1205 this.initializeConnectorStatus(connectorId);
1206 }
1207 }
1208 }
1209
1210 private checkStationInfoConnectorStatus(
1211 connectorId: number,
1212 connectorStatus: ConnectorStatus
1213 ): void {
1214 if (!Utils.isNullOrUndefined(connectorStatus?.status)) {
1215 logger.warn(
1216 `${this.logPrefix()} Charging station information from template ${
1217 this.templateFile
1218 } with connector ${connectorId} status configuration defined, undefine it`
1219 );
1220 connectorStatus.status = undefined;
1221 }
1222 }
1223
1224 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1225 let configuration: ChargingStationConfiguration = null;
1226 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
1227 try {
1228 if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
1229 configuration = this.sharedLRUCache.getChargingStationConfiguration(
1230 this.configurationFileHash
1231 );
1232 } else {
1233 const measureId = `${FileType.ChargingStationConfiguration} read`;
1234 const beginId = PerformanceStatistics.beginMeasure(measureId);
1235 configuration = JSON.parse(
1236 fs.readFileSync(this.configurationFile, 'utf8')
1237 ) as ChargingStationConfiguration;
1238 PerformanceStatistics.endMeasure(measureId, beginId);
1239 this.configurationFileHash = configuration.configurationHash;
1240 this.sharedLRUCache.setChargingStationConfiguration(configuration);
1241 }
1242 } catch (error) {
1243 FileUtils.handleFileException(
1244 this.logPrefix(),
1245 FileType.ChargingStationConfiguration,
1246 this.configurationFile,
1247 error as NodeJS.ErrnoException
1248 );
1249 }
1250 }
1251 return configuration;
1252 }
1253
1254 private saveConfiguration(): void {
1255 if (this.configurationFile) {
1256 try {
1257 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1258 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1259 }
1260 const configurationData: ChargingStationConfiguration =
1261 this.getConfigurationFromFile() ?? {};
1262 this.ocppConfiguration?.configurationKey &&
1263 (configurationData.configurationKey = this.ocppConfiguration.configurationKey);
1264 this.stationInfo && (configurationData.stationInfo = this.stationInfo);
1265 delete configurationData.configurationHash;
1266 const configurationHash = crypto
1267 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1268 .update(JSON.stringify(configurationData))
1269 .digest('hex');
1270 if (this.configurationFileHash !== configurationHash) {
1271 configurationData.configurationHash = configurationHash;
1272 const measureId = `${FileType.ChargingStationConfiguration} write`;
1273 const beginId = PerformanceStatistics.beginMeasure(measureId);
1274 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1275 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1276 fs.closeSync(fileDescriptor);
1277 PerformanceStatistics.endMeasure(measureId, beginId);
1278 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
1279 this.configurationFileHash = configurationHash;
1280 this.sharedLRUCache.setChargingStationConfiguration(configurationData);
1281 } else {
1282 logger.debug(
1283 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1284 this.configurationFile
1285 }`
1286 );
1287 }
1288 } catch (error) {
1289 FileUtils.handleFileException(
1290 this.logPrefix(),
1291 FileType.ChargingStationConfiguration,
1292 this.configurationFile,
1293 error as NodeJS.ErrnoException
1294 );
1295 }
1296 } else {
1297 logger.error(
1298 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1299 );
1300 }
1301 }
1302
1303 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null {
1304 return this.getTemplateFromFile()?.Configuration ?? null;
1305 }
1306
1307 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1308 let configuration: ChargingStationConfiguration = null;
1309 if (this.getOcppPersistentConfiguration()) {
1310 const configurationFromFile = this.getConfigurationFromFile();
1311 configuration = configurationFromFile?.configurationKey && configurationFromFile;
1312 }
1313 configuration && delete configuration.stationInfo;
1314 return configuration;
1315 }
1316
1317 private getOcppConfiguration(): ChargingStationOcppConfiguration | null {
1318 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1319 if (!ocppConfiguration) {
1320 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1321 }
1322 return ocppConfiguration;
1323 }
1324
1325 private async onOpen(): Promise<void> {
1326 if (this.isWebSocketConnectionOpened() === true) {
1327 logger.info(
1328 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1329 );
1330 if (!this.isRegistered()) {
1331 // Send BootNotification
1332 let registrationRetryCount = 0;
1333 do {
1334 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
1335 BootNotificationRequest,
1336 BootNotificationResponse
1337 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
1338 skipBufferingOnError: true,
1339 });
1340 if (!this.isRegistered()) {
1341 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1342 await Utils.sleep(
1343 this.bootNotificationResponse?.interval
1344 ? this.bootNotificationResponse.interval * 1000
1345 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1346 );
1347 }
1348 } while (
1349 !this.isRegistered() &&
1350 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1351 this.getRegistrationMaxRetries() === -1)
1352 );
1353 }
1354 if (this.isRegistered()) {
1355 if (this.isInAcceptedState()) {
1356 await this.startMessageSequence();
1357 }
1358 } else {
1359 logger.error(
1360 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1361 );
1362 }
1363 this.wsConnectionRestarted = false;
1364 this.autoReconnectRetryCount = 0;
1365 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
1366 } else {
1367 logger.warn(
1368 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1369 );
1370 }
1371 }
1372
1373 private async onClose(code: number, reason: string): Promise<void> {
1374 switch (code) {
1375 // Normal close
1376 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1377 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1378 logger.info(
1379 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1380 code
1381 )}' and reason '${reason}'`
1382 );
1383 this.autoReconnectRetryCount = 0;
1384 break;
1385 // Abnormal close
1386 default:
1387 logger.error(
1388 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1389 code
1390 )}' and reason '${reason}'`
1391 );
1392 this.started === true && (await this.reconnect());
1393 break;
1394 }
1395 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
1396 }
1397
1398 private async onMessage(data: Data): Promise<void> {
1399 let messageType: number;
1400 let messageId: string;
1401 let commandName: IncomingRequestCommand;
1402 let commandPayload: JsonType;
1403 let errorType: ErrorType;
1404 let errorMessage: string;
1405 let errorDetails: JsonType;
1406 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
1407 let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1408 let requestCommandName: RequestCommand | IncomingRequestCommand;
1409 let requestPayload: JsonType;
1410 let cachedRequest: CachedRequest;
1411 let errMsg: string;
1412 try {
1413 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
1414 if (Array.isArray(request) === true) {
1415 [messageType, messageId] = request;
1416 // Check the type of message
1417 switch (messageType) {
1418 // Incoming Message
1419 case MessageType.CALL_MESSAGE:
1420 [, , commandName, commandPayload] = request as IncomingRequest;
1421 if (this.getEnableStatistics() === true) {
1422 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1423 }
1424 logger.debug(
1425 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1426 request
1427 )}`
1428 );
1429 // Process the message
1430 await this.ocppIncomingRequestService.incomingRequestHandler(
1431 this,
1432 messageId,
1433 commandName,
1434 commandPayload
1435 );
1436 break;
1437 // Outcome Message
1438 case MessageType.CALL_RESULT_MESSAGE:
1439 [, , commandPayload] = request as Response;
1440 if (this.requests.has(messageId) === false) {
1441 // Error
1442 throw new OCPPError(
1443 ErrorType.INTERNAL_ERROR,
1444 `Response for unknown message id ${messageId}`,
1445 null,
1446 commandPayload
1447 );
1448 }
1449 // Respond
1450 cachedRequest = this.requests.get(messageId);
1451 if (Array.isArray(cachedRequest) === true) {
1452 [responseCallback, errorCallback, requestCommandName, requestPayload] = cachedRequest;
1453 } else {
1454 throw new OCPPError(
1455 ErrorType.PROTOCOL_ERROR,
1456 `Cached request for message id ${messageId} response is not an array`,
1457 null,
1458 cachedRequest as unknown as JsonType
1459 );
1460 }
1461 logger.debug(
1462 `${this.logPrefix()} << Command '${
1463 requestCommandName ?? Constants.UNKNOWN_COMMAND
1464 }' received response payload: ${JSON.stringify(request)}`
1465 );
1466 responseCallback(commandPayload, requestPayload);
1467 break;
1468 // Error Message
1469 case MessageType.CALL_ERROR_MESSAGE:
1470 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
1471 if (this.requests.has(messageId) === false) {
1472 // Error
1473 throw new OCPPError(
1474 ErrorType.INTERNAL_ERROR,
1475 `Error response for unknown message id ${messageId}`,
1476 null,
1477 { errorType, errorMessage, errorDetails }
1478 );
1479 }
1480 cachedRequest = this.requests.get(messageId);
1481 if (Array.isArray(cachedRequest) === true) {
1482 [, errorCallback, requestCommandName] = cachedRequest;
1483 } else {
1484 throw new OCPPError(
1485 ErrorType.PROTOCOL_ERROR,
1486 `Cached request for message id ${messageId} error response is not an array`,
1487 null,
1488 cachedRequest as unknown as JsonType
1489 );
1490 }
1491 logger.debug(
1492 `${this.logPrefix()} << Command '${
1493 requestCommandName ?? Constants.UNKNOWN_COMMAND
1494 }' received error payload: ${JSON.stringify(request)}`
1495 );
1496 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
1497 break;
1498 // Error
1499 default:
1500 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1501 errMsg = `Wrong message type ${messageType}`;
1502 logger.error(`${this.logPrefix()} ${errMsg}`);
1503 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1504 }
1505 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
1506 } else {
1507 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, {
1508 request,
1509 });
1510 }
1511 } catch (error) {
1512 // Log
1513 logger.error(
1514 `${this.logPrefix()} Incoming OCPP command '${
1515 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1516 }' message '${data.toString()}'${
1517 messageType !== MessageType.CALL_MESSAGE
1518 ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'`
1519 : ''
1520 } processing error:`,
1521 error
1522 );
1523 if (error instanceof OCPPError === false) {
1524 logger.warn(
1525 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1526 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1527 }' message '${data.toString()}' handling is not an OCPPError:`,
1528 error
1529 );
1530 }
1531 switch (messageType) {
1532 case MessageType.CALL_MESSAGE:
1533 // Send error
1534 await this.ocppRequestService.sendError(
1535 this,
1536 messageId,
1537 error as OCPPError,
1538 commandName ?? requestCommandName ?? null
1539 );
1540 break;
1541 case MessageType.CALL_RESULT_MESSAGE:
1542 case MessageType.CALL_ERROR_MESSAGE:
1543 if (errorCallback) {
1544 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1545 errorCallback(error as OCPPError, false);
1546 } else {
1547 // Remove the request from the cache in case of error at response handling
1548 this.requests.delete(messageId);
1549 }
1550 break;
1551 }
1552 }
1553 }
1554
1555 private onPing(): void {
1556 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1557 }
1558
1559 private onPong(): void {
1560 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1561 }
1562
1563 private onError(error: WSError): void {
1564 this.closeWSConnection();
1565 logger.error(this.logPrefix() + ' WebSocket error:', error);
1566 }
1567
1568 private getEnergyActiveImportRegister(
1569 connectorStatus: ConnectorStatus,
1570 meterStop = false
1571 ): number {
1572 if (this.getMeteringPerTransaction() === true) {
1573 return (
1574 (meterStop === true
1575 ? Math.round(connectorStatus?.transactionEnergyActiveImportRegisterValue)
1576 : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0
1577 );
1578 }
1579 return (
1580 (meterStop === true
1581 ? Math.round(connectorStatus?.energyActiveImportRegisterValue)
1582 : connectorStatus?.energyActiveImportRegisterValue) ?? 0
1583 );
1584 }
1585
1586 private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean {
1587 const localStationInfo = stationInfo ?? this.stationInfo;
1588 return !Utils.isUndefined(localStationInfo.useConnectorId0)
1589 ? localStationInfo.useConnectorId0
1590 : true;
1591 }
1592
1593 private getNumberOfRunningTransactions(): number {
1594 let trxCount = 0;
1595 for (const connectorId of this.connectors.keys()) {
1596 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
1597 trxCount++;
1598 }
1599 }
1600 return trxCount;
1601 }
1602
1603 private async stopRunningTransactions(reason = StopTransactionReason.NONE): Promise<void> {
1604 for (const connectorId of this.connectors.keys()) {
1605 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
1606 await this.stopTransactionOnConnector(connectorId, reason);
1607 }
1608 }
1609 }
1610
1611 // 0 for disabling
1612 private getConnectionTimeout(): number {
1613 if (
1614 ChargingStationConfigurationUtils.getConfigurationKey(
1615 this,
1616 StandardParametersKey.ConnectionTimeOut
1617 )
1618 ) {
1619 return (
1620 parseInt(
1621 ChargingStationConfigurationUtils.getConfigurationKey(
1622 this,
1623 StandardParametersKey.ConnectionTimeOut
1624 ).value
1625 ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
1626 );
1627 }
1628 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1629 }
1630
1631 // -1 for unlimited, 0 for disabling
1632 private getAutoReconnectMaxRetries(): number {
1633 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1634 return this.stationInfo.autoReconnectMaxRetries;
1635 }
1636 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1637 return Configuration.getAutoReconnectMaxRetries();
1638 }
1639 return -1;
1640 }
1641
1642 // 0 for disabling
1643 private getRegistrationMaxRetries(): number {
1644 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1645 return this.stationInfo.registrationMaxRetries;
1646 }
1647 return -1;
1648 }
1649
1650 private getPowerDivider(): number {
1651 let powerDivider = this.getNumberOfConnectors();
1652 if (this.stationInfo?.powerSharedByConnectors) {
1653 powerDivider = this.getNumberOfRunningTransactions();
1654 }
1655 return powerDivider;
1656 }
1657
1658 private getMaximumPower(stationInfo?: ChargingStationInfo): number {
1659 const localStationInfo = stationInfo ?? this.stationInfo;
1660 return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower;
1661 }
1662
1663 private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
1664 const maximumPower = this.getMaximumPower(stationInfo);
1665 switch (this.getCurrentOutType(stationInfo)) {
1666 case CurrentType.AC:
1667 return ACElectricUtils.amperagePerPhaseFromPower(
1668 this.getNumberOfPhases(stationInfo),
1669 maximumPower / this.getNumberOfConnectors(),
1670 this.getVoltageOut(stationInfo)
1671 );
1672 case CurrentType.DC:
1673 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo));
1674 }
1675 }
1676
1677 private getAmperageLimitation(): number | undefined {
1678 if (
1679 this.stationInfo.amperageLimitationOcppKey &&
1680 ChargingStationConfigurationUtils.getConfigurationKey(
1681 this,
1682 this.stationInfo.amperageLimitationOcppKey
1683 )
1684 ) {
1685 return (
1686 Utils.convertToInt(
1687 ChargingStationConfigurationUtils.getConfigurationKey(
1688 this,
1689 this.stationInfo.amperageLimitationOcppKey
1690 ).value
1691 ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1692 );
1693 }
1694 }
1695
1696 private getChargingProfilePowerLimit(connectorId: number): number | undefined {
1697 let limit: number, matchingChargingProfile: ChargingProfile;
1698 let chargingProfiles: ChargingProfile[] = [];
1699 // Get charging profiles for connector and sort by stack level
1700 chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort(
1701 (a, b) => b.stackLevel - a.stackLevel
1702 );
1703 // Get profiles on connector 0
1704 if (this.getConnectorStatus(0).chargingProfiles) {
1705 chargingProfiles.push(
1706 ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel)
1707 );
1708 }
1709 if (!Utils.isEmptyArray(chargingProfiles)) {
1710 const result = ChargingStationUtils.getLimitFromChargingProfiles(
1711 chargingProfiles,
1712 this.logPrefix()
1713 );
1714 if (!Utils.isNullOrUndefined(result)) {
1715 limit = result.limit;
1716 matchingChargingProfile = result.matchingChargingProfile;
1717 switch (this.getCurrentOutType()) {
1718 case CurrentType.AC:
1719 limit =
1720 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
1721 ChargingRateUnitType.WATT
1722 ? limit
1723 : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit);
1724 break;
1725 case CurrentType.DC:
1726 limit =
1727 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
1728 ChargingRateUnitType.WATT
1729 ? limit
1730 : DCElectricUtils.power(this.getVoltageOut(), limit);
1731 }
1732 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
1733 if (limit > connectorMaximumPower) {
1734 logger.error(
1735 `${this.logPrefix()} Charging profile id ${
1736 matchingChargingProfile.chargingProfileId
1737 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1738 this.getConnectorStatus(connectorId).chargingProfiles
1739 );
1740 limit = connectorMaximumPower;
1741 }
1742 }
1743 }
1744 return limit;
1745 }
1746
1747 private async startMessageSequence(): Promise<void> {
1748 if (this.stationInfo?.autoRegister) {
1749 await this.ocppRequestService.requestHandler<
1750 BootNotificationRequest,
1751 BootNotificationResponse
1752 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
1753 skipBufferingOnError: true,
1754 });
1755 }
1756 // Start WebSocket ping
1757 this.startWebSocketPing();
1758 // Start heartbeat
1759 this.startHeartbeat();
1760 // Initialize connectors status
1761 for (const connectorId of this.connectors.keys()) {
1762 let chargePointStatus: ChargePointStatus;
1763 if (connectorId === 0) {
1764 continue;
1765 } else if (
1766 !this.getConnectorStatus(connectorId)?.status &&
1767 (this.isChargingStationAvailable() === false ||
1768 (this.isChargingStationAvailable() === true &&
1769 this.isConnectorAvailable(connectorId) === false))
1770 ) {
1771 chargePointStatus = ChargePointStatus.UNAVAILABLE;
1772 } else if (
1773 !this.getConnectorStatus(connectorId)?.status &&
1774 this.getConnectorStatus(connectorId)?.bootStatus
1775 ) {
1776 // Set boot status in template at startup
1777 chargePointStatus = this.getConnectorStatus(connectorId).bootStatus;
1778 } else if (this.getConnectorStatus(connectorId)?.status) {
1779 // Set previous status at startup
1780 chargePointStatus = this.getConnectorStatus(connectorId).status;
1781 } else {
1782 // Set default status
1783 chargePointStatus = ChargePointStatus.AVAILABLE;
1784 }
1785 await this.ocppRequestService.requestHandler<
1786 StatusNotificationRequest,
1787 StatusNotificationResponse
1788 >(this, RequestCommand.STATUS_NOTIFICATION, {
1789 connectorId,
1790 status: chargePointStatus,
1791 errorCode: ChargePointErrorCode.NO_ERROR,
1792 });
1793 this.getConnectorStatus(connectorId).status = chargePointStatus;
1794 }
1795 // Start the ATG
1796 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable === true) {
1797 this.startAutomaticTransactionGenerator();
1798 }
1799 this.wsConnectionRestarted === true && this.flushMessageBuffer();
1800 }
1801
1802 private async stopMessageSequence(
1803 reason: StopTransactionReason = StopTransactionReason.NONE
1804 ): Promise<void> {
1805 // Stop WebSocket ping
1806 this.stopWebSocketPing();
1807 // Stop heartbeat
1808 this.stopHeartbeat();
1809 // Stop ongoing transactions
1810 if (this.automaticTransactionGenerator?.started === true) {
1811 this.stopAutomaticTransactionGenerator();
1812 } else {
1813 await this.stopRunningTransactions(reason);
1814 }
1815 for (const connectorId of this.connectors.keys()) {
1816 if (connectorId > 0) {
1817 await this.ocppRequestService.requestHandler<
1818 StatusNotificationRequest,
1819 StatusNotificationResponse
1820 >(this, RequestCommand.STATUS_NOTIFICATION, {
1821 connectorId,
1822 status: ChargePointStatus.UNAVAILABLE,
1823 errorCode: ChargePointErrorCode.NO_ERROR,
1824 });
1825 this.getConnectorStatus(connectorId).status = null;
1826 }
1827 }
1828 }
1829
1830 private startWebSocketPing(): void {
1831 const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey(
1832 this,
1833 StandardParametersKey.WebSocketPingInterval
1834 )
1835 ? Utils.convertToInt(
1836 ChargingStationConfigurationUtils.getConfigurationKey(
1837 this,
1838 StandardParametersKey.WebSocketPingInterval
1839 ).value
1840 )
1841 : 0;
1842 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1843 this.webSocketPingSetInterval = setInterval(() => {
1844 if (this.isWebSocketConnectionOpened() === true) {
1845 this.wsConnection.ping((): void => {
1846 /* This is intentional */
1847 });
1848 }
1849 }, webSocketPingInterval * 1000);
1850 logger.info(
1851 this.logPrefix() +
1852 ' WebSocket ping started every ' +
1853 Utils.formatDurationSeconds(webSocketPingInterval)
1854 );
1855 } else if (this.webSocketPingSetInterval) {
1856 logger.info(
1857 this.logPrefix() +
1858 ' WebSocket ping every ' +
1859 Utils.formatDurationSeconds(webSocketPingInterval) +
1860 ' already started'
1861 );
1862 } else {
1863 logger.error(
1864 `${this.logPrefix()} WebSocket ping interval set to ${
1865 webSocketPingInterval
1866 ? Utils.formatDurationSeconds(webSocketPingInterval)
1867 : webSocketPingInterval
1868 }, not starting the WebSocket ping`
1869 );
1870 }
1871 }
1872
1873 private stopWebSocketPing(): void {
1874 if (this.webSocketPingSetInterval) {
1875 clearInterval(this.webSocketPingSetInterval);
1876 }
1877 }
1878
1879 private getConfiguredSupervisionUrl(): URL {
1880 const supervisionUrls = Utils.cloneObject<string | string[]>(
1881 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1882 );
1883 if (!Utils.isEmptyArray(supervisionUrls)) {
1884 switch (Configuration.getSupervisionUrlDistribution()) {
1885 case SupervisionUrlDistribution.ROUND_ROBIN:
1886 // FIXME
1887 this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
1888 break;
1889 case SupervisionUrlDistribution.RANDOM:
1890 this.configuredSupervisionUrlIndex = Math.floor(
1891 Utils.secureRandom() * supervisionUrls.length
1892 );
1893 break;
1894 case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY:
1895 this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
1896 break;
1897 default:
1898 logger.error(
1899 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1900 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1901 }`
1902 );
1903 this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
1904 break;
1905 }
1906 return new URL(supervisionUrls[this.configuredSupervisionUrlIndex]);
1907 }
1908 return new URL(supervisionUrls as string);
1909 }
1910
1911 private getHeartbeatInterval(): number {
1912 const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1913 this,
1914 StandardParametersKey.HeartbeatInterval
1915 );
1916 if (HeartbeatInterval) {
1917 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1918 }
1919 const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1920 this,
1921 StandardParametersKey.HeartBeatInterval
1922 );
1923 if (HeartBeatInterval) {
1924 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1925 }
1926 !this.stationInfo?.autoRegister &&
1927 logger.warn(
1928 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1929 Constants.DEFAULT_HEARTBEAT_INTERVAL
1930 }`
1931 );
1932 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1933 }
1934
1935 private stopHeartbeat(): void {
1936 if (this.heartbeatSetInterval) {
1937 clearInterval(this.heartbeatSetInterval);
1938 }
1939 }
1940
1941 private terminateWSConnection(): void {
1942 if (this.isWebSocketConnectionOpened() === true) {
1943 this.wsConnection.terminate();
1944 this.wsConnection = null;
1945 }
1946 }
1947
1948 private stopMeterValues(connectorId: number) {
1949 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1950 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1951 }
1952 }
1953
1954 private getReconnectExponentialDelay(): boolean {
1955 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1956 ? this.stationInfo.reconnectExponentialDelay
1957 : false;
1958 }
1959
1960 private async reconnect(): Promise<void> {
1961 // Stop WebSocket ping
1962 this.stopWebSocketPing();
1963 // Stop heartbeat
1964 this.stopHeartbeat();
1965 // Stop the ATG if needed
1966 if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure === true) {
1967 this.stopAutomaticTransactionGenerator();
1968 }
1969 if (
1970 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1971 this.getAutoReconnectMaxRetries() === -1
1972 ) {
1973 this.autoReconnectRetryCount++;
1974 const reconnectDelay = this.getReconnectExponentialDelay()
1975 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1976 : this.getConnectionTimeout() * 1000;
1977 const reconnectDelayWithdraw = 1000;
1978 const reconnectTimeout =
1979 reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0
1980 ? reconnectDelay - reconnectDelayWithdraw
1981 : 0;
1982 logger.error(
1983 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1984 reconnectDelay,
1985 2
1986 )}ms, timeout ${reconnectTimeout}ms`
1987 );
1988 await Utils.sleep(reconnectDelay);
1989 logger.error(
1990 this.logPrefix() +
1991 ' WebSocket: reconnecting try #' +
1992 this.autoReconnectRetryCount.toString()
1993 );
1994 this.openWSConnection(
1995 { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout },
1996 { closeOpened: true }
1997 );
1998 this.wsConnectionRestarted = true;
1999 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2000 logger.error(
2001 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2002 this.autoReconnectRetryCount
2003 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2004 );
2005 }
2006 }
2007
2008 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null {
2009 return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null;
2010 }
2011
2012 private initializeConnectorStatus(connectorId: number): void {
2013 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2014 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2015 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
2016 this.getConnectorStatus(connectorId).transactionStarted = false;
2017 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2018 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
2019 }
2020 }