Cleanup files and files name.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
4 import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
5 import ChargingStationTemplate, { CurrentType, PowerUnits, Voltage } from '../types/ChargingStationTemplate';
6 import { ConnectorPhaseRotation, StandardParametersKey, SupportedFeatureProfiles } from '../types/ocpp/Configuration';
7 import Connectors, { Connector, SampledValueTemplate } from '../types/Connectors';
8 import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
9 import Requests, { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand } from '../types/ocpp/Requests';
10 import WebSocket, { ClientOptions, MessageEvent } from 'ws';
11
12 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
13 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
14 import { ChargingProfile } from '../types/ocpp/ChargingProfile';
15 import ChargingStationInfo from '../types/ChargingStationInfo';
16 import { ClientRequestArgs } from 'http';
17 import Configuration from '../utils/Configuration';
18 import Constants from '../utils/Constants';
19 import { ErrorType } from '../types/ocpp/ErrorType';
20 import FileUtils from '../utils/FileUtils';
21 import { MessageType } from '../types/ocpp/MessageType';
22 import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
23 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
24 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
25 import OCPPError from './ocpp/OCPPError';
26 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
27 import OCPPRequestService from './ocpp/OCPPRequestService';
28 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
29 import PerformanceStatistics from '../performance/PerformanceStatistics';
30 import { StopTransactionReason } from '../types/ocpp/Transaction';
31 import { URL } from 'url';
32 import Utils from '../utils/Utils';
33 import { WebSocketCloseEventStatusCode } from '../types/WebSocket';
34 import crypto from 'crypto';
35 import fs from 'fs';
36 import logger from '../utils/Logger';
37 import path from 'path';
38
39 export default class ChargingStation {
40 public stationTemplateFile: string;
41 public authorizedTags: string[];
42 public stationInfo!: ChargingStationInfo;
43 public connectors: Connectors;
44 public configuration!: ChargingStationConfiguration;
45 public hasStopped: boolean;
46 public wsConnection!: WebSocket;
47 public requests: Requests;
48 public messageQueue: string[];
49 public performanceStatistics!: PerformanceStatistics;
50 public heartbeatSetInterval!: NodeJS.Timeout;
51 public ocppIncomingRequestService!: OCPPIncomingRequestService;
52 public ocppRequestService!: OCPPRequestService;
53 private index: number;
54 private bootNotificationRequest!: BootNotificationRequest;
55 private bootNotificationResponse!: BootNotificationResponse | null;
56 private connectorsConfigurationHash!: string;
57 private wsConnectionUrl!: URL;
58 private hasSocketRestarted: boolean;
59 private autoReconnectRetryCount: number;
60 private automaticTransactionGeneration!: AutomaticTransactionGenerator;
61 private webSocketPingSetInterval!: NodeJS.Timeout;
62
63 constructor(index: number, stationTemplateFile: string) {
64 this.index = index;
65 this.stationTemplateFile = stationTemplateFile;
66 this.connectors = {} as Connectors;
67 this.initialize();
68
69 this.hasStopped = false;
70 this.hasSocketRestarted = false;
71 this.autoReconnectRetryCount = 0;
72
73 this.requests = {} as Requests;
74 this.messageQueue = [] as string[];
75
76 this.authorizedTags = this.getAuthorizedTags();
77 }
78
79 public logPrefix(): string {
80 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
81 }
82
83 public getBootNotificationRequest(): BootNotificationRequest {
84 return this.bootNotificationRequest;
85 }
86
87 public getRandomTagId(): string {
88 const index = Math.floor(Math.random() * this.authorizedTags.length);
89 return this.authorizedTags[index];
90 }
91
92 public hasAuthorizedTags(): boolean {
93 return !Utils.isEmptyArray(this.authorizedTags);
94 }
95
96 public getEnableStatistics(): boolean | undefined {
97 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
98 }
99
100 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
101 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
102 }
103
104 public getNumberOfPhases(): number | undefined {
105 switch (this.getCurrentOutType()) {
106 case CurrentType.AC:
107 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
108 case CurrentType.DC:
109 return 0;
110 }
111 }
112
113 public isWebSocketConnectionOpened(): boolean {
114 return this.wsConnection?.readyState === WebSocket.OPEN;
115 }
116
117 public isRegistered(): boolean {
118 return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
119 }
120
121 public isChargingStationAvailable(): boolean {
122 return this.getConnector(0).availability === AvailabilityType.OPERATIVE;
123 }
124
125 public isConnectorAvailable(id: number): boolean {
126 return this.getConnector(id).availability === AvailabilityType.OPERATIVE;
127 }
128
129 public getConnector(id: number): Connector {
130 return this.connectors[id];
131 }
132
133 public getCurrentOutType(): CurrentType | undefined {
134 return this.stationInfo.currentOutType ?? CurrentType.AC;
135 }
136
137 public getVoltageOut(): number | undefined {
138 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
139 let defaultVoltageOut: number;
140 switch (this.getCurrentOutType()) {
141 case CurrentType.AC:
142 defaultVoltageOut = Voltage.VOLTAGE_230;
143 break;
144 case CurrentType.DC:
145 defaultVoltageOut = Voltage.VOLTAGE_400;
146 break;
147 default:
148 logger.error(errMsg);
149 throw new Error(errMsg);
150 }
151 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
152 }
153
154 public getTransactionIdTag(transactionId: number): string | undefined {
155 for (const connector in this.connectors) {
156 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
157 return this.getConnector(Utils.convertToInt(connector)).transactionIdTag;
158 }
159 }
160 }
161
162 public getOutOfOrderEndMeterValues(): boolean {
163 return this.stationInfo.outOfOrderEndMeterValues ?? false;
164 }
165
166 public getBeginEndMeterValues(): boolean {
167 return this.stationInfo.beginEndMeterValues ?? false;
168 }
169
170 public getMeteringPerTransaction(): boolean {
171 return this.stationInfo.meteringPerTransaction ?? true;
172 }
173
174 public getTransactionDataMeterValues(): boolean {
175 return this.stationInfo.transactionDataMeterValues ?? false;
176 }
177
178 public getMainVoltageMeterValues(): boolean {
179 return this.stationInfo.mainVoltageMeterValues ?? true;
180 }
181
182 public getPhaseLineToLineVoltageMeterValues(): boolean {
183 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
184 }
185
186 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
187 if (this.getMeteringPerTransaction()) {
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)).transactionEnergyActiveImportRegisterValue;
191 }
192 }
193 }
194 for (const connector in this.connectors) {
195 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
196 return this.getConnector(Utils.convertToInt(connector)).energyActiveImportRegisterValue;
197 }
198 }
199 }
200
201 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
202 if (this.getMeteringPerTransaction()) {
203 return this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue;
204 }
205 return this.getConnector(connectorId).energyActiveImportRegisterValue;
206 }
207
208 public getAuthorizeRemoteTxRequests(): boolean {
209 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
210 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
211 }
212
213 public getLocalAuthListEnabled(): boolean {
214 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
215 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
216 }
217
218 public restartWebSocketPing(): void {
219 // Stop WebSocket ping
220 this.stopWebSocketPing();
221 // Start WebSocket ping
222 this.startWebSocketPing();
223 }
224
225 public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
226 phase?: MeterValuePhase): SampledValueTemplate | undefined {
227 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
228 logger.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
229 return;
230 }
231 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
232 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`);
233 return;
234 }
235 const sampledValueTemplates: SampledValueTemplate[] = this.getConnector(connectorId).MeterValues;
236 for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) {
237 if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) {
238 logger.warn(`${this.logPrefix()} Unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
239 continue;
240 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
241 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
242 return sampledValueTemplates[index];
243 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
244 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
245 return sampledValueTemplates[index];
246 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
247 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
248 return sampledValueTemplates[index];
249 }
250 }
251 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
252 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand ${measurand} in template on connectorId ${connectorId}`;
253 logger.error(errorMsg);
254 throw new Error(errorMsg);
255 }
256 logger.debug(`${this.logPrefix()} No MeterValues for measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
257 }
258
259 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
260 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
261 }
262
263 public startHeartbeat(): void {
264 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
265 // eslint-disable-next-line @typescript-eslint/no-misused-promises
266 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
267 await this.ocppRequestService.sendHeartbeat();
268 }, this.getHeartbeatInterval());
269 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
270 } else if (this.heartbeatSetInterval) {
271 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
272 } else {
273 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
274 }
275 }
276
277 public restartHeartbeat(): void {
278 // Stop heartbeat
279 this.stopHeartbeat();
280 // Start heartbeat
281 this.startHeartbeat();
282 }
283
284 public startMeterValues(connectorId: number, interval: number): void {
285 if (connectorId === 0) {
286 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
287 return;
288 }
289 if (!this.getConnector(connectorId)) {
290 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
291 return;
292 }
293 if (!this.getConnector(connectorId)?.transactionStarted) {
294 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
295 return;
296 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
297 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
298 return;
299 }
300 if (interval > 0) {
301 // eslint-disable-next-line @typescript-eslint/no-misused-promises
302 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
303 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval);
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 if (this.getEnableStatistics()) {
312 this.performanceStatistics.start();
313 }
314 this.openWSConnection();
315 // Monitor authorization file
316 this.startAuthorizationFileMonitoring();
317 // Monitor station template file
318 this.startStationTemplateFileMonitoring();
319 // Handle Socket incoming messages
320 this.wsConnection.on('message', this.onMessage.bind(this));
321 // Handle Socket error
322 this.wsConnection.on('error', this.onError.bind(this));
323 // Handle Socket close
324 this.wsConnection.on('close', this.onClose.bind(this));
325 // Handle Socket opening connection
326 this.wsConnection.on('open', this.onOpen.bind(this));
327 // Handle Socket ping
328 this.wsConnection.on('ping', this.onPing.bind(this));
329 // Handle Socket pong
330 this.wsConnection.on('pong', this.onPong.bind(this));
331 }
332
333 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
334 // Stop message sequence
335 await this.stopMessageSequence(reason);
336 for (const connector in this.connectors) {
337 if (Utils.convertToInt(connector) > 0) {
338 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
339 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
340 }
341 }
342 if (this.isWebSocketConnectionOpened()) {
343 this.wsConnection.close();
344 }
345 if (this.getEnableStatistics()) {
346 this.performanceStatistics.stop();
347 }
348 this.bootNotificationResponse = null;
349 this.hasStopped = true;
350 }
351
352 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
353 return this.configuration.configurationKey.find((configElement) => {
354 if (caseInsensitive) {
355 return configElement.key.toLowerCase() === key.toLowerCase();
356 }
357 return configElement.key === key;
358 });
359 }
360
361 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
362 const keyFound = this.getConfigurationKey(key);
363 if (!keyFound) {
364 this.configuration.configurationKey.push({
365 key,
366 readonly,
367 value,
368 visible,
369 reboot,
370 });
371 } else {
372 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
373 }
374 }
375
376 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
377 const keyFound = this.getConfigurationKey(key);
378 if (keyFound) {
379 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
380 this.configuration.configurationKey[keyIndex].value = value;
381 } else {
382 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
383 }
384 }
385
386 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
387 let cpReplaced = false;
388 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
389 this.getConnector(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
390 if (chargingProfile.chargingProfileId === cp.chargingProfileId
391 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
392 this.getConnector(connectorId).chargingProfiles[index] = cp;
393 cpReplaced = true;
394 }
395 });
396 }
397 !cpReplaced && this.getConnector(connectorId).chargingProfiles?.push(cp);
398 }
399
400 public resetTransactionOnConnector(connectorId: number): void {
401 this.getConnector(connectorId).authorized = false;
402 this.getConnector(connectorId).transactionStarted = false;
403 delete this.getConnector(connectorId).authorizeIdTag;
404 delete this.getConnector(connectorId).transactionId;
405 delete this.getConnector(connectorId).transactionIdTag;
406 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
407 delete this.getConnector(connectorId).transactionBeginMeterValue;
408 this.stopMeterValues(connectorId);
409 }
410
411 public addToMessageQueue(message: string): void {
412 let dups = false;
413 // Handle dups in message queue
414 for (const bufferedMessage of this.messageQueue) {
415 // Message already in the queue
416 if (message === bufferedMessage) {
417 dups = true;
418 break;
419 }
420 }
421 if (!dups) {
422 // Queue message
423 this.messageQueue.push(message);
424 }
425 }
426
427 private flushMessageQueue() {
428 if (!Utils.isEmptyArray(this.messageQueue)) {
429 this.messageQueue.forEach((message, index) => {
430 this.messageQueue.splice(index, 1);
431 // TODO: evaluate the need to track performance
432 this.wsConnection.send(message);
433 });
434 }
435 }
436
437 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
438 // In case of multiple instances: add instance index to charging station id
439 let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
440 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
441 const idSuffix = stationTemplate.nameSuffix ?? '';
442 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
443 }
444
445 private buildStationInfo(): ChargingStationInfo {
446 let stationTemplateFromFile: ChargingStationTemplate;
447 try {
448 // Load template file
449 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
450 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
451 fs.closeSync(fileDescriptor);
452 } catch (error) {
453 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
454 }
455 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
456 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
457 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
458 const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length);
459 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
460 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
461 : stationTemplateFromFile.power[powerArrayRandomIndex];
462 } else {
463 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
464 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
465 ? stationTemplateFromFile.power * 1000
466 : stationTemplateFromFile.power;
467 }
468 delete stationInfo.power;
469 delete stationInfo.powerUnit;
470 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
471 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
472 return stationInfo;
473 }
474
475 private getOCPPVersion(): OCPPVersion {
476 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
477 }
478
479 private handleUnsupportedVersion(version: OCPPVersion) {
480 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
481 logger.error(errMsg);
482 throw new Error(errMsg);
483 }
484
485 private initialize(): void {
486 this.stationInfo = this.buildStationInfo();
487 this.bootNotificationRequest = {
488 chargePointModel: this.stationInfo.chargePointModel,
489 chargePointVendor: this.stationInfo.chargePointVendor,
490 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
491 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
492 };
493 this.configuration = this.getTemplateChargingStationConfiguration();
494 this.wsConnectionUrl = new URL(this.getSupervisionURL().href + '/' + this.stationInfo.chargingStationId);
495 // Build connectors if needed
496 const maxConnectors = this.getMaxNumberOfConnectors();
497 if (maxConnectors <= 0) {
498 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
499 }
500 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
501 if (templateMaxConnectors <= 0) {
502 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
503 }
504 if (!this.stationInfo.Connectors[0]) {
505 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
506 }
507 // Sanity check
508 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
509 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
510 this.stationInfo.randomConnectors = true;
511 }
512 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
513 // FIXME: Handle shrinking the number of connectors
514 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
515 this.connectorsConfigurationHash = connectorsConfigHash;
516 // Add connector Id 0
517 let lastConnector = '0';
518 for (lastConnector in this.stationInfo.Connectors) {
519 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
520 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
521 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
522 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
523 this.connectors[lastConnector].chargingProfiles = [];
524 }
525 }
526 }
527 // Generate all connectors
528 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
529 for (let index = 1; index <= maxConnectors; index++) {
530 const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
531 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorId]);
532 this.connectors[index].availability = AvailabilityType.OPERATIVE;
533 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
534 this.connectors[index].chargingProfiles = [];
535 }
536 }
537 }
538 }
539 // Avoid duplication of connectors related information
540 delete this.stationInfo.Connectors;
541 // Initialize transaction attributes on connectors
542 for (const connector in this.connectors) {
543 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
544 this.initTransactionAttributesOnConnector(Utils.convertToInt(connector));
545 }
546 }
547 switch (this.getOCPPVersion()) {
548 case OCPPVersion.VERSION_16:
549 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
550 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
551 break;
552 default:
553 this.handleUnsupportedVersion(this.getOCPPVersion());
554 break;
555 }
556 // OCPP parameters
557 this.initOCPPParameters();
558 if (this.stationInfo.autoRegister) {
559 this.bootNotificationResponse = {
560 currentTime: new Date().toISOString(),
561 interval: this.getHeartbeatInterval() / 1000,
562 status: RegistrationStatus.ACCEPTED
563 };
564 }
565 this.stationInfo.powerDivider = this.getPowerDivider();
566 if (this.getEnableStatistics()) {
567 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId, this.wsConnectionUrl);
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()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
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.isWebSocketConnectionOpened()) {
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 OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming request is not iterable', commandName);
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.addRequestStatistic(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 OCPPError(ErrorType.PROTOCOL_ERROR, `Response request for message id ${messageId} is not iterable`, commandName);
680 }
681 if (!responseCallback) {
682 // Error
683 throw new OCPPError(ErrorType.INTERNAL_ERROR, `Response request for unknown message id ${messageId}`, commandName);
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 OCPPError(ErrorType.INTERNAL_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 OCPPError(ErrorType.PROTOCOL_ERROR, `Error request for message id ${messageId} is not iterable`);
698 }
699 delete this.requests[messageId];
700 rejectCallback(new OCPPError(commandName, commandPayload.toString(), null, errorDetails));
701 break;
702 // Error
703 default:
704 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
705 logger.error(errMsg);
706 throw new OCPPError(ErrorType.PROTOCOL_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() + ' Received a WS ping (rfc6455) from the server');
718 }
719
720 private onPong(): void {
721 logger.debug(this.logPrefix() + ' 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 ?? {} 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 }
859
860 private startAutomaticTransactionGenerator() {
861 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
862 if (!this.automaticTransactionGeneration) {
863 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
864 }
865 if (this.automaticTransactionGeneration.timeToStop) {
866 // The ATG might sleep
867 void this.automaticTransactionGeneration.start();
868 }
869 }
870 }
871
872 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
873 // Stop WebSocket ping
874 this.stopWebSocketPing();
875 // Stop heartbeat
876 this.stopHeartbeat();
877 // Stop the ATG
878 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
879 this.automaticTransactionGeneration &&
880 !this.automaticTransactionGeneration.timeToStop) {
881 await this.automaticTransactionGeneration.stop(reason);
882 } else {
883 for (const connector in this.connectors) {
884 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
885 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
886 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
887 this.getTransactionIdTag(transactionId), reason);
888 }
889 }
890 }
891 }
892
893 private startWebSocketPing(): void {
894 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
895 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
896 : 0;
897 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
898 this.webSocketPingSetInterval = setInterval(() => {
899 if (this.isWebSocketConnectionOpened()) {
900 this.wsConnection.ping((): void => { });
901 }
902 }, webSocketPingInterval * 1000);
903 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
904 } else if (this.webSocketPingSetInterval) {
905 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
906 } else {
907 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
908 }
909 }
910
911 private stopWebSocketPing(): void {
912 if (this.webSocketPingSetInterval) {
913 clearInterval(this.webSocketPingSetInterval);
914 }
915 }
916
917 private getSupervisionURL(): URL {
918 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
919 let indexUrl = 0;
920 if (!Utils.isEmptyArray(supervisionUrls)) {
921 if (Configuration.getDistributeStationsToTenantsEqually()) {
922 indexUrl = this.index % supervisionUrls.length;
923 } else {
924 // Get a random url
925 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
926 }
927 return new URL(supervisionUrls[indexUrl]);
928 }
929 return new URL(supervisionUrls as string);
930 }
931
932 private getHeartbeatInterval(): number | undefined {
933 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
934 if (HeartbeatInterval) {
935 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
936 }
937 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
938 if (HeartBeatInterval) {
939 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
940 }
941 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
942 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
943 }
944
945 private stopHeartbeat(): void {
946 if (this.heartbeatSetInterval) {
947 clearInterval(this.heartbeatSetInterval);
948 }
949 }
950
951 private openWSConnection(options?: ClientOptions & ClientRequestArgs, forceCloseOpened = false): void {
952 options = options ?? {};
953 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
954 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
955 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
956 }
957 if (this.isWebSocketConnectionOpened() && 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() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
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 // Restart the ATG
1009 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1010 this.automaticTransactionGeneration) {
1011 await this.automaticTransactionGeneration.stop();
1012 }
1013 this.startAutomaticTransactionGenerator();
1014 if (this.getEnableStatistics()) {
1015 this.performanceStatistics.restart();
1016 } else {
1017 this.performanceStatistics.stop();
1018 }
1019 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1020 } catch (error) {
1021 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1022 }
1023 });
1024 } catch (error) {
1025 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
1026 }
1027 }
1028
1029 private getReconnectExponentialDelay(): boolean | undefined {
1030 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1031 }
1032
1033 private async reconnect(error: unknown): Promise<void> {
1034 // Stop WebSocket ping
1035 this.stopWebSocketPing();
1036 // Stop heartbeat
1037 this.stopHeartbeat();
1038 // Stop the ATG if needed
1039 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1040 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1041 this.automaticTransactionGeneration &&
1042 !this.automaticTransactionGeneration.timeToStop) {
1043 await this.automaticTransactionGeneration.stop();
1044 }
1045 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1046 this.autoReconnectRetryCount++;
1047 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1048 logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
1049 await Utils.sleep(reconnectDelay);
1050 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1051 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
1052 this.hasSocketRestarted = true;
1053 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1054 logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1055 }
1056 }
1057
1058 private initTransactionAttributesOnConnector(connectorId: number): void {
1059 this.getConnector(connectorId).authorized = false;
1060 this.getConnector(connectorId).transactionStarted = false;
1061 this.getConnector(connectorId).energyActiveImportRegisterValue = 0;
1062 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
1063 }
1064 }
1065