Consistent variables naming.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
2 import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
3 import ChargingStationTemplate, { CurrentOutType, PowerUnits, VoltageOut } from '../types/ChargingStationTemplate';
4 import { ConnectorPhaseRotation, StandardParametersKey, SupportedFeatureProfiles } from '../types/ocpp/Configuration';
5 import Connectors, { Connector, SampledValueTemplate } from '../types/Connectors';
6 import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
7 import { PerformanceObserver, performance } from 'perf_hooks';
8 import Requests, { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand } from '../types/ocpp/Requests';
9 import WebSocket, { MessageEvent } from 'ws';
10
11 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
12 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
13 import { ChargingProfile } from '../types/ocpp/ChargingProfile';
14 import ChargingStationInfo from '../types/ChargingStationInfo';
15 import Configuration from '../utils/Configuration';
16 import Constants from '../utils/Constants';
17 import FileUtils from '../utils/FileUtils';
18 import { MessageType } from '../types/ocpp/MessageType';
19 import OCPP16IncomingRequestService from './ocpp/1.6/OCCP16IncomingRequestService';
20 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
21 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
22 import OCPPError from './OcppError';
23 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
24 import OCPPRequestService from './ocpp/OCPPRequestService';
25 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
26 import PerformanceStatistics from '../utils/PerformanceStatistics';
27 import { StopTransactionReason } from '../types/ocpp/Transaction';
28 import Utils from '../utils/Utils';
29 import { WebSocketCloseEventStatusCode } from '../types/WebSocket';
30 import crypto from 'crypto';
31 import fs from 'fs';
32 import logger from '../utils/Logger';
33 import path from 'path';
34
35 export default class ChargingStation {
36 public stationTemplateFile: string;
37 public authorizedTags: string[];
38 public stationInfo!: ChargingStationInfo;
39 public connectors: Connectors;
40 public configuration!: ChargingStationConfiguration;
41 public hasStopped: boolean;
42 public wsConnection!: WebSocket;
43 public requests: Requests;
44 public messageQueue: string[];
45 public performanceStatistics!: PerformanceStatistics;
46 public heartbeatSetInterval!: NodeJS.Timeout;
47 public ocppIncomingRequestService!: OCPPIncomingRequestService;
48 public ocppRequestService!: OCPPRequestService;
49 private index: number;
50 private bootNotificationRequest!: BootNotificationRequest;
51 private bootNotificationResponse!: BootNotificationResponse | null;
52 private connectorsConfigurationHash!: string;
53 private supervisionUrl!: string;
54 private wsConnectionUrl!: string;
55 private hasSocketRestarted: boolean;
56 private autoReconnectRetryCount: number;
57 private automaticTransactionGeneration!: AutomaticTransactionGenerator;
58 private performanceObserver!: PerformanceObserver;
59 private webSocketPingSetInterval!: NodeJS.Timeout;
60
61 constructor(index: number, stationTemplateFile: string) {
62 this.index = index;
63 this.stationTemplateFile = stationTemplateFile;
64 this.connectors = {} as Connectors;
65 this.initialize();
66
67 this.hasStopped = false;
68 this.hasSocketRestarted = false;
69 this.autoReconnectRetryCount = 0;
70
71 this.requests = {} as Requests;
72 this.messageQueue = [] as string[];
73
74 this.authorizedTags = this.getAuthorizedTags();
75 }
76
77 public logPrefix(): string {
78 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
79 }
80
81 public getRandomTagId(): string {
82 const index = Math.floor(Math.random() * this.authorizedTags.length);
83 return this.authorizedTags[index];
84 }
85
86 public hasAuthorizedTags(): boolean {
87 return !Utils.isEmptyArray(this.authorizedTags);
88 }
89
90 public getEnableStatistics(): boolean | undefined {
91 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
92 }
93
94 public getNumberOfPhases(): number | undefined {
95 switch (this.getCurrentOutType()) {
96 case CurrentOutType.AC:
97 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
98 case CurrentOutType.DC:
99 return 0;
100 }
101 }
102
103 public isWebSocketOpen(): boolean {
104 return this.wsConnection?.readyState === WebSocket.OPEN;
105 }
106
107 public isRegistered(): boolean {
108 return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
109 }
110
111 public isChargingStationAvailable(): boolean {
112 return this.getConnector(0).availability === AvailabilityType.OPERATIVE;
113 }
114
115 public isConnectorAvailable(id: number): boolean {
116 return this.getConnector(id).availability === AvailabilityType.OPERATIVE;
117 }
118
119 public getConnector(id: number): Connector {
120 return this.connectors[id];
121 }
122
123 public getCurrentOutType(): CurrentOutType | undefined {
124 return this.stationInfo.currentOutType ?? CurrentOutType.AC;
125 }
126
127 public getVoltageOut(): number | undefined {
128 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
129 let defaultVoltageOut: number;
130 switch (this.getCurrentOutType()) {
131 case CurrentOutType.AC:
132 defaultVoltageOut = VoltageOut.VOLTAGE_230;
133 break;
134 case CurrentOutType.DC:
135 defaultVoltageOut = VoltageOut.VOLTAGE_400;
136 break;
137 default:
138 logger.error(errMsg);
139 throw Error(errMsg);
140 }
141 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
142 }
143
144 public getTransactionIdTag(transactionId: number): string | undefined {
145 for (const connector in this.connectors) {
146 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
147 return this.getConnector(Utils.convertToInt(connector)).transactionIdTag;
148 }
149 }
150 }
151
152 public getOutOfOrderEndMeterValues(): boolean {
153 return this.stationInfo.outOfOrderEndMeterValues ?? false;
154 }
155
156 public getBeginEndMeterValues(): boolean {
157 return this.stationInfo.beginEndMeterValues ?? false;
158 }
159
160 public getMeteringPerTransaction(): boolean {
161 return this.stationInfo.meteringPerTransaction ?? true;
162 }
163
164 public getTransactionDataMeterValues(): boolean {
165 return this.stationInfo.transactionDataMeterValues ?? false;
166 }
167
168 public getMainVoltageMeterValues(): boolean {
169 return this.stationInfo.mainVoltageMeterValues ?? true;
170 }
171
172 public getPhaseLineToLineVoltageMeterValues(): boolean {
173 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
174 }
175
176 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
177 if (this.getMeteringPerTransaction()) {
178 for (const connector in this.connectors) {
179 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
180 return this.getConnector(Utils.convertToInt(connector)).transactionEnergyActiveImportRegisterValue;
181 }
182 }
183 }
184 for (const connector in this.connectors) {
185 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
186 return this.getConnector(Utils.convertToInt(connector)).energyActiveImportRegisterValue;
187 }
188 }
189 }
190
191 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
192 if (this.getMeteringPerTransaction()) {
193 return this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue;
194 }
195 return this.getConnector(connectorId).energyActiveImportRegisterValue;
196 }
197
198 public getAuthorizeRemoteTxRequests(): boolean {
199 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
200 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
201 }
202
203 public getLocalAuthListEnabled(): boolean {
204 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
205 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
206 }
207
208 public restartWebSocketPing(): void {
209 // Stop WebSocket ping
210 this.stopWebSocketPing();
211 // Start WebSocket ping
212 this.startWebSocketPing();
213 }
214
215 public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
216 phase?: MeterValuePhase): SampledValueTemplate | undefined {
217 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
218 logger.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
219 return;
220 }
221 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
222 logger.debug(`${this.logPrefix()} Trying to get MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`);
223 return;
224 }
225 const sampledValueTemplates: SampledValueTemplate[] = this.getConnector(connectorId).MeterValues;
226 for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) {
227 if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
228 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
229 return sampledValueTemplates[index];
230 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
231 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
232 return sampledValueTemplates[index];
233 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
234 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
235 return sampledValueTemplates[index];
236 }
237 }
238 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
239 logger.error(`${this.logPrefix()} Missing MeterValues for default measurand ${measurand} in template on connectorId ${connectorId}`);
240 }
241 logger.debug(`${this.logPrefix()} No MeterValues for measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
242 }
243
244 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
245 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
246 }
247
248 public startHeartbeat(): void {
249 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
250 // eslint-disable-next-line @typescript-eslint/no-misused-promises
251 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
252 await this.ocppRequestService.sendHeartbeat();
253 }, this.getHeartbeatInterval());
254 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
255 } else if (this.heartbeatSetInterval) {
256 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
257 } else {
258 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
259 }
260 }
261
262 public restartHeartbeat(): void {
263 // Stop heartbeat
264 this.stopHeartbeat();
265 // Start heartbeat
266 this.startHeartbeat();
267 }
268
269 public startMeterValues(connectorId: number, interval: number): void {
270 if (connectorId === 0) {
271 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
272 return;
273 }
274 if (!this.getConnector(connectorId)) {
275 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
276 return;
277 }
278 if (!this.getConnector(connectorId)?.transactionStarted) {
279 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
280 return;
281 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
282 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
283 return;
284 }
285 if (interval > 0) {
286 // eslint-disable-next-line @typescript-eslint/no-misused-promises
287 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
288 if (this.getEnableStatistics()) {
289 const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
290 this.performanceObserver.observe({
291 entryTypes: ['function'],
292 });
293 await sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
294 } else {
295 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
296 }
297 }, interval);
298 } else {
299 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
300 }
301 }
302
303 public start(): void {
304 this.openWSConnection();
305 // Monitor authorization file
306 this.startAuthorizationFileMonitoring();
307 // Monitor station template file
308 this.startStationTemplateFileMonitoring();
309 // Handle Socket incoming messages
310 this.wsConnection.on('message', this.onMessage.bind(this));
311 // Handle Socket error
312 this.wsConnection.on('error', this.onError.bind(this));
313 // Handle Socket close
314 this.wsConnection.on('close', this.onClose.bind(this));
315 // Handle Socket opening connection
316 this.wsConnection.on('open', this.onOpen.bind(this));
317 // Handle Socket ping
318 this.wsConnection.on('ping', this.onPing.bind(this));
319 // Handle Socket pong
320 this.wsConnection.on('pong', this.onPong.bind(this));
321 }
322
323 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
324 // Stop message sequence
325 await this.stopMessageSequence(reason);
326 for (const connector in this.connectors) {
327 if (Utils.convertToInt(connector) > 0) {
328 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
329 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
330 }
331 }
332 if (this.isWebSocketOpen()) {
333 this.wsConnection.close();
334 }
335 this.bootNotificationResponse = null;
336 this.hasStopped = true;
337 }
338
339 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
340 const configurationKey: ConfigurationKey | undefined = this.configuration.configurationKey.find((configElement) => {
341 if (caseInsensitive) {
342 return configElement.key.toLowerCase() === key.toLowerCase();
343 }
344 return configElement.key === key;
345 });
346 return configurationKey;
347 }
348
349 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
350 const keyFound = this.getConfigurationKey(key);
351 if (!keyFound) {
352 this.configuration.configurationKey.push({
353 key,
354 readonly,
355 value,
356 visible,
357 reboot,
358 });
359 } else {
360 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
361 }
362 }
363
364 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
365 const keyFound = this.getConfigurationKey(key);
366 if (keyFound) {
367 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
368 this.configuration.configurationKey[keyIndex].value = value;
369 } else {
370 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
371 }
372 }
373
374 public setChargingProfile(connectorId: number, cp: ChargingProfile): boolean {
375 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
376 this.getConnector(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
377 if (chargingProfile.chargingProfileId === cp.chargingProfileId
378 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
379 this.getConnector(connectorId).chargingProfiles[index] = cp;
380 return true;
381 }
382 });
383 }
384 this.getConnector(connectorId).chargingProfiles?.push(cp);
385 return true;
386 }
387
388 public resetTransactionOnConnector(connectorId: number): void {
389 this.getConnector(connectorId).authorized = false;
390 this.getConnector(connectorId).transactionStarted = false;
391 delete this.getConnector(connectorId).authorizeIdTag;
392 delete this.getConnector(connectorId).transactionId;
393 delete this.getConnector(connectorId).transactionIdTag;
394 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
395 delete this.getConnector(connectorId).transactionBeginMeterValue;
396 this.stopMeterValues(connectorId);
397 }
398
399 public addToMessageQueue(message: string): void {
400 let dups = false;
401 // Handle dups in message queue
402 for (const bufferedMessage of this.messageQueue) {
403 // Message already in the queue
404 if (message === bufferedMessage) {
405 dups = true;
406 break;
407 }
408 }
409 if (!dups) {
410 // Queue message
411 this.messageQueue.push(message);
412 }
413 }
414
415 private flushMessageQueue() {
416 if (!Utils.isEmptyArray(this.messageQueue)) {
417 this.messageQueue.forEach((message, index) => {
418 this.messageQueue.splice(index, 1);
419 this.wsConnection.send(message);
420 });
421 }
422 }
423
424 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
425 // In case of multiple instances: add instance index to charging station id
426 let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
427 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
428 const idSuffix = stationTemplate.nameSuffix ?? '';
429 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
430 }
431
432 private buildStationInfo(): ChargingStationInfo {
433 let stationTemplateFromFile: ChargingStationTemplate;
434 try {
435 // Load template file
436 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
437 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
438 fs.closeSync(fileDescriptor);
439 } catch (error) {
440 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
441 }
442 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
443 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
444 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
445 const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length);
446 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
447 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
448 : stationTemplateFromFile.power[powerArrayRandomIndex];
449 } else {
450 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
451 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
452 ? stationTemplateFromFile.power * 1000
453 : stationTemplateFromFile.power;
454 }
455 delete stationInfo.power;
456 delete stationInfo.powerUnit;
457 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
458 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
459 return stationInfo;
460 }
461
462 private getOCPPVersion(): OCPPVersion {
463 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
464 }
465
466 private handleUnsupportedVersion(version: OCPPVersion) {
467 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
468 logger.error(errMsg);
469 throw new Error(errMsg);
470 }
471
472 private initialize(): void {
473 this.stationInfo = this.buildStationInfo();
474 this.bootNotificationRequest = {
475 chargePointModel: this.stationInfo.chargePointModel,
476 chargePointVendor: this.stationInfo.chargePointVendor,
477 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
478 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
479 };
480 this.configuration = this.getTemplateChargingStationConfiguration();
481 this.supervisionUrl = this.getSupervisionURL();
482 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
483 // Build connectors if needed
484 const maxConnectors = this.getMaxNumberOfConnectors();
485 if (maxConnectors <= 0) {
486 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
487 }
488 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
489 if (templateMaxConnectors <= 0) {
490 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
491 }
492 if (!this.stationInfo.Connectors[0]) {
493 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
494 }
495 // Sanity check
496 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
497 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
498 this.stationInfo.randomConnectors = true;
499 }
500 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
501 // FIXME: Handle shrinking the number of connectors
502 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
503 this.connectorsConfigurationHash = connectorsConfigHash;
504 // Add connector Id 0
505 let lastConnector = '0';
506 for (lastConnector in this.stationInfo.Connectors) {
507 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
508 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
509 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
510 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
511 this.connectors[lastConnector].chargingProfiles = [];
512 }
513 }
514 }
515 // Generate all connectors
516 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
517 for (let index = 1; index <= maxConnectors; index++) {
518 const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
519 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorId]);
520 this.connectors[index].availability = AvailabilityType.OPERATIVE;
521 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
522 this.connectors[index].chargingProfiles = [];
523 }
524 }
525 }
526 }
527 // Avoid duplication of connectors related information
528 delete this.stationInfo.Connectors;
529 // Initialize transaction attributes on connectors
530 for (const connector in this.connectors) {
531 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
532 this.initTransactionAttributesOnConnector(Utils.convertToInt(connector));
533 }
534 }
535 switch (this.getOCPPVersion()) {
536 case OCPPVersion.VERSION_16:
537 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
538 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
539 break;
540 default:
541 this.handleUnsupportedVersion(this.getOCPPVersion());
542 break;
543 }
544 // OCPP parameters
545 this.initOCPPParameters();
546 this.stationInfo.powerDivider = this.getPowerDivider();
547 if (this.getEnableStatistics()) {
548 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId);
549 this.performanceObserver = new PerformanceObserver((list) => {
550 const entry = list.getEntries()[0];
551 this.performanceStatistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
552 this.performanceObserver.disconnect();
553 });
554 }
555 }
556
557 private initOCPPParameters(): void {
558 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
559 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
560 }
561 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
562 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
563 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
564 }
565 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
566 const connectorPhaseRotation = [];
567 for (const connector in this.connectors) {
568 // AC/DC
569 if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) {
570 connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`);
571 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) {
572 connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
573 // AC
574 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) {
575 connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
576 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) {
577 connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`);
578 }
579 }
580 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
581 }
582 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
583 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
584 }
585 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
586 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
587 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
588 }
589 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
590 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
591 }
592 }
593
594 private async onOpen(): Promise<void> {
595 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
596 if (!this.isRegistered()) {
597 // Send BootNotification
598 let registrationRetryCount = 0;
599 do {
600 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
601 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
602 if (!this.isRegistered()) {
603 registrationRetryCount++;
604 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
605 }
606 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
607 }
608 if (this.isRegistered()) {
609 await this.startMessageSequence();
610 this.hasStopped && (this.hasStopped = false);
611 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
612 this.flushMessageQueue();
613 }
614 } else {
615 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
616 }
617 this.autoReconnectRetryCount = 0;
618 this.hasSocketRestarted = false;
619 }
620
621 private async onClose(closeEvent: any): Promise<void> {
622 switch (closeEvent) {
623 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
624 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
625 logger.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
626 this.autoReconnectRetryCount = 0;
627 break;
628 default: // Abnormal close
629 logger.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
630 await this.reconnect(closeEvent);
631 break;
632 }
633 }
634
635 private async onMessage(messageEvent: MessageEvent): Promise<void> {
636 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
637 let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
638 let rejectCallback: (error: OCPPError) => void;
639 let requestPayload: Record<string, unknown>;
640 let errMsg: string;
641 try {
642 // Parse the message
643 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
644 // Check the Type of message
645 switch (messageType) {
646 // Incoming Message
647 case MessageType.CALL_MESSAGE:
648 if (this.getEnableStatistics()) {
649 this.performanceStatistics.addMessage(commandName, messageType);
650 }
651 // Process the call
652 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
653 break;
654 // Outcome Message
655 case MessageType.CALL_RESULT_MESSAGE:
656 // Respond
657 if (Utils.isIterable(this.requests[messageId])) {
658 [responseCallback, , requestPayload] = this.requests[messageId];
659 } else {
660 throw new Error(`Response request for message id ${messageId} is not iterable`);
661 }
662 if (!responseCallback) {
663 // Error
664 throw new Error(`Response request for unknown message id ${messageId}`);
665 }
666 delete this.requests[messageId];
667 responseCallback(commandName, requestPayload);
668 break;
669 // Error Message
670 case MessageType.CALL_ERROR_MESSAGE:
671 if (!this.requests[messageId]) {
672 // Error
673 throw new Error(`Error request for unknown message id ${messageId}`);
674 }
675 if (Utils.isIterable(this.requests[messageId])) {
676 [, rejectCallback] = this.requests[messageId];
677 } else {
678 throw new Error(`Error request for message id ${messageId} is not iterable`);
679 }
680 delete this.requests[messageId];
681 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
682 break;
683 // Error
684 default:
685 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
686 logger.error(errMsg);
687 throw new Error(errMsg);
688 }
689 } catch (error) {
690 // Log
691 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
692 // Send error
693 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
694 }
695 }
696
697 private onPing(): void {
698 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
699 }
700
701 private onPong(): void {
702 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
703 }
704
705 private async onError(errorEvent: any): Promise<void> {
706 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
707 // switch (errorEvent.code) {
708 // case 'ECONNREFUSED':
709 // await this._reconnect(errorEvent);
710 // break;
711 // }
712 }
713
714 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
715 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
716 }
717
718 private getAuthorizationFile(): string | undefined {
719 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
720 }
721
722 private getAuthorizedTags(): string[] {
723 let authorizedTags: string[] = [];
724 const authorizationFile = this.getAuthorizationFile();
725 if (authorizationFile) {
726 try {
727 // Load authorization file
728 const fileDescriptor = fs.openSync(authorizationFile, 'r');
729 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
730 fs.closeSync(fileDescriptor);
731 } catch (error) {
732 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
733 }
734 } else {
735 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
736 }
737 return authorizedTags;
738 }
739
740 private getUseConnectorId0(): boolean | undefined {
741 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
742 }
743
744 private getNumberOfRunningTransactions(): number {
745 let trxCount = 0;
746 for (const connector in this.connectors) {
747 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
748 trxCount++;
749 }
750 }
751 return trxCount;
752 }
753
754 // 0 for disabling
755 private getConnectionTimeout(): number | undefined {
756 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
757 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
758 }
759 return Constants.DEFAULT_CONNECTION_TIMEOUT;
760 }
761
762 // -1 for unlimited, 0 for disabling
763 private getAutoReconnectMaxRetries(): number | undefined {
764 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
765 return this.stationInfo.autoReconnectMaxRetries;
766 }
767 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
768 return Configuration.getAutoReconnectMaxRetries();
769 }
770 return -1;
771 }
772
773 // 0 for disabling
774 private getRegistrationMaxRetries(): number | undefined {
775 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
776 return this.stationInfo.registrationMaxRetries;
777 }
778 return -1;
779 }
780
781 private getPowerDivider(): number {
782 let powerDivider = this.getNumberOfConnectors();
783 if (this.stationInfo.powerSharedByConnectors) {
784 powerDivider = this.getNumberOfRunningTransactions();
785 }
786 return powerDivider;
787 }
788
789 private getTemplateMaxNumberOfConnectors(): number {
790 return Object.keys(this.stationInfo.Connectors).length;
791 }
792
793 private getMaxNumberOfConnectors(): number {
794 let maxConnectors = 0;
795 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
796 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
797 // Distribute evenly the number of connectors
798 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
799 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
800 maxConnectors = this.stationInfo.numberOfConnectors as number;
801 } else {
802 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
803 }
804 return maxConnectors;
805 }
806
807 private getNumberOfConnectors(): number {
808 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
809 }
810
811 private async startMessageSequence(): Promise<void> {
812 // Start WebSocket ping
813 this.startWebSocketPing();
814 // Start heartbeat
815 this.startHeartbeat();
816 // Initialize connectors status
817 for (const connector in this.connectors) {
818 if (Utils.convertToInt(connector) === 0) {
819 continue;
820 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
821 // Send status in template at startup
822 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
823 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
824 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
825 // Send status in template after reset
826 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
827 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
828 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
829 // Send previous status at template reload
830 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
831 } else {
832 // Send default status
833 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
834 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
835 }
836 }
837 // Start the ATG
838 this.startAutomaticTransactionGenerator();
839 if (this.getEnableStatistics()) {
840 this.performanceStatistics.start();
841 }
842 }
843
844 private startAutomaticTransactionGenerator() {
845 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
846 if (!this.automaticTransactionGeneration) {
847 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
848 }
849 if (this.automaticTransactionGeneration.timeToStop) {
850 // The ATG might sleep
851 void this.automaticTransactionGeneration.start();
852 }
853 }
854 }
855
856 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
857 // Stop WebSocket ping
858 this.stopWebSocketPing();
859 // Stop heartbeat
860 this.stopHeartbeat();
861 // Stop the ATG
862 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
863 this.automaticTransactionGeneration &&
864 !this.automaticTransactionGeneration.timeToStop) {
865 await this.automaticTransactionGeneration.stop(reason);
866 } else {
867 for (const connector in this.connectors) {
868 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
869 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
870 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
871 this.getTransactionIdTag(transactionId), reason);
872 }
873 }
874 }
875 }
876
877 private startWebSocketPing(): void {
878 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
879 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
880 : 0;
881 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
882 this.webSocketPingSetInterval = setInterval(() => {
883 if (this.isWebSocketOpen()) {
884 this.wsConnection.ping((): void => { });
885 }
886 }, webSocketPingInterval * 1000);
887 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
888 } else if (this.webSocketPingSetInterval) {
889 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
890 } else {
891 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
892 }
893 }
894
895 private stopWebSocketPing(): void {
896 if (this.webSocketPingSetInterval) {
897 clearInterval(this.webSocketPingSetInterval);
898 }
899 }
900
901 private getSupervisionURL(): string {
902 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
903 let indexUrl = 0;
904 if (!Utils.isEmptyArray(supervisionUrls)) {
905 if (Configuration.getDistributeStationsToTenantsEqually()) {
906 indexUrl = this.index % supervisionUrls.length;
907 } else {
908 // Get a random url
909 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
910 }
911 return supervisionUrls[indexUrl];
912 }
913 return supervisionUrls as string;
914 }
915
916 private getHeartbeatInterval(): number | undefined {
917 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
918 if (HeartbeatInterval) {
919 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
920 }
921 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
922 if (HeartBeatInterval) {
923 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
924 }
925 }
926
927 private stopHeartbeat(): void {
928 if (this.heartbeatSetInterval) {
929 clearInterval(this.heartbeatSetInterval);
930 }
931 }
932
933 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
934 options ?? {} as WebSocket.ClientOptions;
935 options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
936 if (this.isWebSocketOpen() && forceCloseOpened) {
937 this.wsConnection.close();
938 }
939 let protocol;
940 switch (this.getOCPPVersion()) {
941 case OCPPVersion.VERSION_16:
942 protocol = 'ocpp' + OCPPVersion.VERSION_16;
943 break;
944 default:
945 this.handleUnsupportedVersion(this.getOCPPVersion());
946 break;
947 }
948 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
949 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
950 }
951
952 private stopMeterValues(connectorId: number) {
953 if (this.getConnector(connectorId)?.transactionSetInterval) {
954 clearInterval(this.getConnector(connectorId).transactionSetInterval);
955 }
956 }
957
958 private startAuthorizationFileMonitoring(): void {
959 const authorizationFile = this.getAuthorizationFile();
960 if (authorizationFile) {
961 try {
962 fs.watch(authorizationFile).on('change', () => {
963 try {
964 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
965 // Initialize authorizedTags
966 this.authorizedTags = this.getAuthorizedTags();
967 } catch (error) {
968 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
969 }
970 });
971 } catch (error) {
972 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
973 }
974 } else {
975 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
976 }
977 }
978
979 private startStationTemplateFileMonitoring(): void {
980 try {
981 // eslint-disable-next-line @typescript-eslint/no-misused-promises
982 fs.watch(this.stationTemplateFile).on('change', async (): Promise<void> => {
983 try {
984 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
985 // Initialize
986 this.initialize();
987 // Stop the ATG
988 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
989 this.automaticTransactionGeneration) {
990 await this.automaticTransactionGeneration.stop();
991 }
992 // Start the ATG
993 this.startAutomaticTransactionGenerator();
994 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
995 } catch (error) {
996 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
997 }
998 });
999 } catch (error) {
1000 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
1001 }
1002 }
1003
1004 private getReconnectExponentialDelay(): boolean | undefined {
1005 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1006 }
1007
1008 private async reconnect(error: any): Promise<void> {
1009 // Stop heartbeat
1010 this.stopHeartbeat();
1011 // Stop the ATG if needed
1012 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1013 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1014 this.automaticTransactionGeneration &&
1015 !this.automaticTransactionGeneration.timeToStop) {
1016 await this.automaticTransactionGeneration.stop();
1017 }
1018 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1019 this.autoReconnectRetryCount++;
1020 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1021 logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
1022 await Utils.sleep(reconnectDelay);
1023 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1024 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
1025 this.hasSocketRestarted = true;
1026 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1027 logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1028 }
1029 }
1030
1031 private initTransactionAttributesOnConnector(connectorId: number): void {
1032 this.getConnector(connectorId).authorized = false;
1033 this.getConnector(connectorId).transactionStarted = false;
1034 this.getConnector(connectorId).energyActiveImportRegisterValue = 0;
1035 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
1036 }
1037 }
1038