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