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