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