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