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