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