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