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