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