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