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