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