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