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