Initial code cleanups for the future OCPP requests code optimization
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
e7aeea18
JB
3import {
4 AvailabilityType,
5 BootNotificationRequest,
6 CachedRequest,
7 IncomingRequest,
8 IncomingRequestCommand,
9 RequestCommand,
10} from '../types/ocpp/Requests';
efa43e52 11import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
e7aeea18
JB
12import ChargingStationConfiguration, {
13 ConfigurationKey,
14} from '../types/ChargingStationConfiguration';
15import ChargingStationTemplate, {
16 CurrentType,
17 PowerUnits,
18 Voltage,
19} from '../types/ChargingStationTemplate';
20import {
21 ConnectorPhaseRotation,
22 StandardParametersKey,
23 SupportedFeatureProfiles,
24 VendorDefaultParametersKey,
25} from '../types/ocpp/Configuration';
9ccca265 26import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
16b0d4e7 27import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
9534e74e 28import WebSocket, { ClientOptions, Data, OPEN, RawData } from 'ws';
3f40bc9c 29
6af9012e 30import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
c0560973
JB
31import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
32import { ChargingProfile } from '../types/ocpp/ChargingProfile';
9ac86a7e 33import ChargingStationInfo from '../types/ChargingStationInfo';
ee0f106b 34import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
15042c5f 35import { ClientRequestArgs } from 'http';
6af9012e 36import Configuration from '../utils/Configuration';
057e2042 37import { ConnectorStatus } from '../types/ConnectorStatus';
63b48f77 38import Constants from '../utils/Constants';
14763b46 39import { ErrorType } from '../types/ocpp/ErrorType';
23132a44 40import FileUtils from '../utils/FileUtils';
d1888640 41import { JsonType } from '../types/JsonType';
d2a64eb5 42import { MessageType } from '../types/ocpp/MessageType';
e7171280 43import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
c0560973
JB
44import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
45import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
e58068fd 46import OCPPError from '../exception/OCPPError';
c0560973
JB
47import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
48import OCPPRequestService from './ocpp/OCPPRequestService';
49import { OCPPVersion } from '../types/ocpp/OCPPVersion';
a6b3c6c3 50import PerformanceStatistics from '../performance/PerformanceStatistics';
057e2042 51import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
c0560973 52import { StopTransactionReason } from '../types/ocpp/Transaction';
2dcfe98e 53import { SupervisionUrlDistribution } from '../types/ConfigurationData';
57939a9d 54import { URL } from 'url';
6af9012e 55import Utils from '../utils/Utils';
3f40bc9c
JB
56import crypto from 'crypto';
57import fs from 'fs';
9f2e3130 58import logger from '../utils/Logger';
ee0f106b 59import { parentPort } from 'worker_threads';
bf1866b2 60import path from 'path';
3f40bc9c
JB
61
62export default class ChargingStation {
9f2e3130 63 public readonly id: string;
9e23580d 64 public readonly stationTemplateFile: string;
c0560973 65 public authorizedTags: string[];
6e0964c8 66 public stationInfo!: ChargingStationInfo;
9e23580d 67 public readonly connectors: Map<number, ConnectorStatus>;
6e0964c8 68 public configuration!: ChargingStationConfiguration;
6e0964c8 69 public wsConnection!: WebSocket;
9e23580d 70 public readonly requests: Map<string, CachedRequest>;
6e0964c8
JB
71 public performanceStatistics!: PerformanceStatistics;
72 public heartbeatSetInterval!: NodeJS.Timeout;
6e0964c8 73 public ocppRequestService!: OCPPRequestService;
9e23580d 74 private readonly index: number;
6e0964c8
JB
75 private bootNotificationRequest!: BootNotificationRequest;
76 private bootNotificationResponse!: BootNotificationResponse | null;
77 private connectorsConfigurationHash!: string;
a472cf2b 78 private ocppIncomingRequestService!: OCPPIncomingRequestService;
8e242273 79 private readonly messageBuffer: Set<string>;
12fc74d6 80 private wsConfiguredConnectionUrl!: URL;
265e4266 81 private wsConnectionRestarted: boolean;
a472cf2b 82 private stopped: boolean;
ad2f27c3 83 private autoReconnectRetryCount: number;
265e4266 84 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
6e0964c8 85 private webSocketPingSetInterval!: NodeJS.Timeout;
6af9012e
JB
86
87 constructor(index: number, stationTemplateFile: string) {
1629a152 88 this.id = Utils.generateUUID();
ad2f27c3
JB
89 this.index = index;
90 this.stationTemplateFile = stationTemplateFile;
265e4266
JB
91 this.stopped = false;
92 this.wsConnectionRestarted = false;
ad2f27c3 93 this.autoReconnectRetryCount = 0;
9f2e3130 94 this.connectors = new Map<number, ConnectorStatus>();
32b02249 95 this.requests = new Map<string, CachedRequest>();
8e242273 96 this.messageBuffer = new Set<string>();
9f2e3130 97 this.initialize();
c0560973
JB
98 this.authorizedTags = this.getAuthorizedTags();
99 }
100
12fc74d6 101 get wsConnectionUrl(): URL {
e7aeea18
JB
102 return this.getSupervisionUrlOcppConfiguration()
103 ? new URL(
104 this.getConfigurationKey(
105 this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl
106 ).value +
107 '/' +
108 this.stationInfo.chargingStationId
109 )
110 : this.wsConfiguredConnectionUrl;
12fc74d6
JB
111 }
112
c0560973 113 public logPrefix(): string {
54b1efe0 114 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
c0560973
JB
115 }
116
802cfa13
JB
117 public getBootNotificationRequest(): BootNotificationRequest {
118 return this.bootNotificationRequest;
119 }
120
f4bf2abd 121 public getRandomIdTag(): string {
c37528f1 122 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
c0560973
JB
123 return this.authorizedTags[index];
124 }
125
126 public hasAuthorizedTags(): boolean {
127 return !Utils.isEmptyArray(this.authorizedTags);
128 }
129
6e0964c8 130 public getEnableStatistics(): boolean | undefined {
e7aeea18
JB
131 return !Utils.isUndefined(this.stationInfo.enableStatistics)
132 ? this.stationInfo.enableStatistics
133 : true;
c0560973
JB
134 }
135
a7fc8211
JB
136 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
137 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
138 }
139
6e0964c8 140 public getNumberOfPhases(): number | undefined {
7decf1b6 141 switch (this.getCurrentOutType()) {
4c2b4904 142 case CurrentType.AC:
e7aeea18
JB
143 return !Utils.isUndefined(this.stationInfo.numberOfPhases)
144 ? this.stationInfo.numberOfPhases
145 : 3;
4c2b4904 146 case CurrentType.DC:
c0560973
JB
147 return 0;
148 }
149 }
150
d5bff457 151 public isWebSocketConnectionOpened(): boolean {
e58068fd 152 return this?.wsConnection?.readyState === OPEN;
c0560973
JB
153 }
154
672fed6e
JB
155 public getRegistrationStatus(): RegistrationStatus {
156 return this?.bootNotificationResponse?.status;
157 }
158
73c4266d
JB
159 public isInUnknownState(): boolean {
160 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
161 }
162
16cd35ad
JB
163 public isInPendingState(): boolean {
164 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
165 }
166
167 public isInAcceptedState(): boolean {
e58068fd 168 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
c0560973
JB
169 }
170
16cd35ad
JB
171 public isInRejectedState(): boolean {
172 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
173 }
174
175 public isRegistered(): boolean {
73c4266d 176 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
16cd35ad
JB
177 }
178
c0560973 179 public isChargingStationAvailable(): boolean {
734d790d 180 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
c0560973
JB
181 }
182
183 public isConnectorAvailable(id: number): boolean {
9f2e3130 184 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
c0560973
JB
185 }
186
54544ef1
JB
187 public getNumberOfConnectors(): number {
188 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
189 }
190
734d790d
JB
191 public getConnectorStatus(id: number): ConnectorStatus {
192 return this.connectors.get(id);
c0560973
JB
193 }
194
4c2b4904
JB
195 public getCurrentOutType(): CurrentType | undefined {
196 return this.stationInfo.currentOutType ?? CurrentType.AC;
c0560973
JB
197 }
198
672fed6e
JB
199 public getOcppStrictCompliance(): boolean {
200 return this.stationInfo.ocppStrictCompliance ?? false;
201 }
202
6e0964c8 203 public getVoltageOut(): number | undefined {
e7aeea18
JB
204 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
205 this.stationTemplateFile
206 }, cannot define default voltage out`;
c0560973 207 let defaultVoltageOut: number;
7decf1b6 208 switch (this.getCurrentOutType()) {
4c2b4904
JB
209 case CurrentType.AC:
210 defaultVoltageOut = Voltage.VOLTAGE_230;
c0560973 211 break;
4c2b4904
JB
212 case CurrentType.DC:
213 defaultVoltageOut = Voltage.VOLTAGE_400;
c0560973
JB
214 break;
215 default:
9f2e3130 216 logger.error(errMsg);
290d006c 217 throw new Error(errMsg);
c0560973 218 }
e7aeea18
JB
219 return !Utils.isUndefined(this.stationInfo.voltageOut)
220 ? this.stationInfo.voltageOut
221 : defaultVoltageOut;
c0560973
JB
222 }
223
6e0964c8 224 public getTransactionIdTag(transactionId: number): string | undefined {
734d790d
JB
225 for (const connectorId of this.connectors.keys()) {
226 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
227 return this.getConnectorStatus(connectorId).transactionIdTag;
c0560973
JB
228 }
229 }
230 }
231
6ed92bc1
JB
232 public getOutOfOrderEndMeterValues(): boolean {
233 return this.stationInfo.outOfOrderEndMeterValues ?? false;
234 }
235
236 public getBeginEndMeterValues(): boolean {
237 return this.stationInfo.beginEndMeterValues ?? false;
238 }
239
240 public getMeteringPerTransaction(): boolean {
241 return this.stationInfo.meteringPerTransaction ?? true;
242 }
243
fd0c36fa
JB
244 public getTransactionDataMeterValues(): boolean {
245 return this.stationInfo.transactionDataMeterValues ?? false;
246 }
247
9ccca265
JB
248 public getMainVoltageMeterValues(): boolean {
249 return this.stationInfo.mainVoltageMeterValues ?? true;
250 }
251
6b10669b
JB
252 public getPhaseLineToLineVoltageMeterValues(): boolean {
253 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
9bd87386
JB
254 }
255
6ed92bc1
JB
256 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
257 if (this.getMeteringPerTransaction()) {
734d790d 258 for (const connectorId of this.connectors.keys()) {
e7aeea18
JB
259 if (
260 connectorId > 0 &&
261 this.getConnectorStatus(connectorId).transactionId === transactionId
262 ) {
734d790d 263 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
6ed92bc1
JB
264 }
265 }
266 }
734d790d
JB
267 for (const connectorId of this.connectors.keys()) {
268 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
269 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
c0560973
JB
270 }
271 }
272 }
273
6ed92bc1
JB
274 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
275 if (this.getMeteringPerTransaction()) {
734d790d 276 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
6ed92bc1 277 }
734d790d 278 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
6ed92bc1
JB
279 }
280
c0560973 281 public getAuthorizeRemoteTxRequests(): boolean {
e7aeea18
JB
282 const authorizeRemoteTxRequests = this.getConfigurationKey(
283 StandardParametersKey.AuthorizeRemoteTxRequests
284 );
285 return authorizeRemoteTxRequests
286 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
287 : false;
c0560973
JB
288 }
289
290 public getLocalAuthListEnabled(): boolean {
e7aeea18
JB
291 const localAuthListEnabled = this.getConfigurationKey(
292 StandardParametersKey.LocalAuthListEnabled
293 );
c0560973
JB
294 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
295 }
296
297 public restartWebSocketPing(): void {
298 // Stop WebSocket ping
299 this.stopWebSocketPing();
300 // Start WebSocket ping
301 this.startWebSocketPing();
302 }
303
e7aeea18
JB
304 public getSampledValueTemplate(
305 connectorId: number,
306 measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
307 phase?: MeterValuePhase
308 ): SampledValueTemplate | undefined {
9ed69c71 309 const onPhaseStr = phase ? `on phase ${phase} ` : '';
9ccca265 310 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
e7aeea18
JB
311 logger.warn(
312 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
313 );
9bd87386
JB
314 return;
315 }
e7aeea18
JB
316 if (
317 measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
318 !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
319 measurand
320 )
321 ) {
322 logger.debug(
323 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
324 StandardParametersKey.MeterValuesSampledData
325 }' OCPP parameter`
326 );
9ccca265
JB
327 return;
328 }
e7aeea18
JB
329 const sampledValueTemplates: SampledValueTemplate[] =
330 this.getConnectorStatus(connectorId).MeterValues;
331 for (
332 let index = 0;
333 !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length;
334 index++
335 ) {
336 if (
337 !Constants.SUPPORTED_MEASURANDS.includes(
338 sampledValueTemplates[index]?.measurand ??
339 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
340 )
341 ) {
342 logger.warn(
343 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
344 );
345 } else if (
346 phase &&
347 sampledValueTemplates[index]?.phase === phase &&
348 sampledValueTemplates[index]?.measurand === measurand &&
349 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
350 measurand
351 )
352 ) {
9ccca265 353 return sampledValueTemplates[index];
e7aeea18
JB
354 } else if (
355 !phase &&
356 !sampledValueTemplates[index].phase &&
357 sampledValueTemplates[index]?.measurand === measurand &&
358 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
359 measurand
360 )
361 ) {
9ccca265 362 return sampledValueTemplates[index];
e7aeea18
JB
363 } else if (
364 measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
365 (!sampledValueTemplates[index].measurand ||
366 sampledValueTemplates[index].measurand === measurand)
367 ) {
9ccca265
JB
368 return sampledValueTemplates[index];
369 }
370 }
9bd87386 371 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
7d75bee1 372 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
9f2e3130 373 logger.error(errorMsg);
de96acad 374 throw new Error(errorMsg);
9ccca265 375 }
e7aeea18
JB
376 logger.debug(
377 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
378 );
9ccca265
JB
379 }
380
e644918b
JB
381 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
382 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
383 }
384
c0560973 385 public startHeartbeat(): void {
e7aeea18
JB
386 if (
387 this.getHeartbeatInterval() &&
388 this.getHeartbeatInterval() > 0 &&
389 !this.heartbeatSetInterval
390 ) {
71623267
JB
391 // eslint-disable-next-line @typescript-eslint/no-misused-promises
392 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
c0560973
JB
393 await this.ocppRequestService.sendHeartbeat();
394 }, this.getHeartbeatInterval());
e7aeea18
JB
395 logger.info(
396 this.logPrefix() +
397 ' Heartbeat started every ' +
398 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
399 );
c0560973 400 } else if (this.heartbeatSetInterval) {
e7aeea18
JB
401 logger.info(
402 this.logPrefix() +
403 ' Heartbeat already started every ' +
404 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
405 );
c0560973 406 } else {
e7aeea18
JB
407 logger.error(
408 `${this.logPrefix()} Heartbeat interval set to ${
409 this.getHeartbeatInterval()
410 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
411 : this.getHeartbeatInterval()
412 }, not starting the heartbeat`
413 );
c0560973
JB
414 }
415 }
416
417 public restartHeartbeat(): void {
418 // Stop heartbeat
419 this.stopHeartbeat();
420 // Start heartbeat
421 this.startHeartbeat();
422 }
423
424 public startMeterValues(connectorId: number, interval: number): void {
425 if (connectorId === 0) {
e7aeea18
JB
426 logger.error(
427 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
428 );
c0560973
JB
429 return;
430 }
734d790d 431 if (!this.getConnectorStatus(connectorId)) {
e7aeea18
JB
432 logger.error(
433 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
434 );
c0560973
JB
435 return;
436 }
734d790d 437 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
e7aeea18
JB
438 logger.error(
439 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
440 );
c0560973 441 return;
e7aeea18
JB
442 } else if (
443 this.getConnectorStatus(connectorId)?.transactionStarted &&
444 !this.getConnectorStatus(connectorId)?.transactionId
445 ) {
446 logger.error(
447 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
448 );
c0560973
JB
449 return;
450 }
451 if (interval > 0) {
71623267 452 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e7aeea18 453 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
9534e74e 454 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e7aeea18
JB
455 async (): Promise<void> => {
456 await this.ocppRequestService.sendMeterValues(
457 connectorId,
458 this.getConnectorStatus(connectorId).transactionId,
459 interval
460 );
461 },
462 interval
463 );
c0560973 464 } else {
e7aeea18
JB
465 logger.error(
466 `${this.logPrefix()} Charging station ${
467 StandardParametersKey.MeterValueSampleInterval
468 } configuration set to ${
469 interval ? Utils.formatDurationMilliSeconds(interval) : interval
470 }, not sending MeterValues`
471 );
c0560973
JB
472 }
473 }
474
475 public start(): void {
7874b0b1
JB
476 if (this.getEnableStatistics()) {
477 this.performanceStatistics.start();
478 }
c0560973
JB
479 this.openWSConnection();
480 // Monitor authorization file
481 this.startAuthorizationFileMonitoring();
482 // Monitor station template file
483 this.startStationTemplateFileMonitoring();
8bf88613 484 // Handle WebSocket message
9534e74e
JB
485 this.wsConnection.on(
486 'message',
487 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
488 );
5dc8b1b5 489 // Handle WebSocket error
9534e74e
JB
490 this.wsConnection.on(
491 'error',
492 this.onError.bind(this) as (this: WebSocket, error: Error) => void
493 );
5dc8b1b5 494 // Handle WebSocket close
9534e74e
JB
495 this.wsConnection.on(
496 'close',
497 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
498 );
8bf88613 499 // Handle WebSocket open
9534e74e 500 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
5dc8b1b5 501 // Handle WebSocket ping
9534e74e 502 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
5dc8b1b5 503 // Handle WebSocket pong
9534e74e 504 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
e7aeea18
JB
505 parentPort.postMessage({
506 id: ChargingStationWorkerMessageEvents.STARTED,
507 data: { id: this.stationInfo.chargingStationId },
508 });
c0560973
JB
509 }
510
511 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
512 // Stop message sequence
513 await this.stopMessageSequence(reason);
734d790d
JB
514 for (const connectorId of this.connectors.keys()) {
515 if (connectorId > 0) {
e7aeea18
JB
516 await this.ocppRequestService.sendStatusNotification(
517 connectorId,
518 ChargePointStatus.UNAVAILABLE
519 );
734d790d 520 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
c0560973
JB
521 }
522 }
d5bff457 523 if (this.isWebSocketConnectionOpened()) {
c0560973
JB
524 this.wsConnection.close();
525 }
7874b0b1
JB
526 if (this.getEnableStatistics()) {
527 this.performanceStatistics.stop();
528 }
c0560973 529 this.bootNotificationResponse = null;
e7aeea18
JB
530 parentPort.postMessage({
531 id: ChargingStationWorkerMessageEvents.STOPPED,
532 data: { id: this.stationInfo.chargingStationId },
533 });
265e4266 534 this.stopped = true;
c0560973
JB
535 }
536
e7aeea18
JB
537 public getConfigurationKey(
538 key: string | StandardParametersKey,
539 caseInsensitive = false
540 ): ConfigurationKey | undefined {
7874b0b1 541 return this.configuration.configurationKey.find((configElement) => {
c0560973
JB
542 if (caseInsensitive) {
543 return configElement.key.toLowerCase() === key.toLowerCase();
544 }
545 return configElement.key === key;
546 });
c0560973
JB
547 }
548
e7aeea18
JB
549 public addConfigurationKey(
550 key: string | StandardParametersKey,
551 value: string,
552 options: { readonly?: boolean; visible?: boolean; reboot?: boolean } = {
553 readonly: false,
554 visible: true,
555 reboot: false,
556 }
557 ): void {
c0560973 558 const keyFound = this.getConfigurationKey(key);
12fc74d6
JB
559 const readonly = options.readonly;
560 const visible = options.visible;
561 const reboot = options.reboot;
c0560973
JB
562 if (!keyFound) {
563 this.configuration.configurationKey.push({
564 key,
565 readonly,
566 value,
567 visible,
568 reboot,
569 });
570 } else {
e7aeea18
JB
571 logger.error(
572 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
573 keyFound
574 );
c0560973
JB
575 }
576 }
577
578 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
579 const keyFound = this.getConfigurationKey(key);
580 if (keyFound) {
581 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
582 this.configuration.configurationKey[keyIndex].value = value;
583 } else {
e7aeea18
JB
584 logger.error(
585 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
586 { key, value }
587 );
c0560973
JB
588 }
589 }
590
a7fc8211
JB
591 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
592 let cpReplaced = false;
734d790d 593 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
e7aeea18
JB
594 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
595 (chargingProfile: ChargingProfile, index: number) => {
596 if (
597 chargingProfile.chargingProfileId === cp.chargingProfileId ||
598 (chargingProfile.stackLevel === cp.stackLevel &&
599 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
600 ) {
601 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
602 cpReplaced = true;
603 }
c0560973 604 }
e7aeea18 605 );
c0560973 606 }
734d790d 607 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
c0560973
JB
608 }
609
a2653482
JB
610 public resetConnectorStatus(connectorId: number): void {
611 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
612 this.getConnectorStatus(connectorId).idTagAuthorized = false;
613 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d 614 this.getConnectorStatus(connectorId).transactionStarted = false;
a2653482 615 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
734d790d
JB
616 delete this.getConnectorStatus(connectorId).authorizeIdTag;
617 delete this.getConnectorStatus(connectorId).transactionId;
618 delete this.getConnectorStatus(connectorId).transactionIdTag;
619 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
620 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
dd119a6b 621 this.stopMeterValues(connectorId);
2e6f5966
JB
622 }
623
8e242273
JB
624 public bufferMessage(message: string): void {
625 this.messageBuffer.add(message);
3ba2381e
JB
626 }
627
8e242273
JB
628 private flushMessageBuffer() {
629 if (this.messageBuffer.size > 0) {
630 this.messageBuffer.forEach((message) => {
aef1b33a 631 // TODO: evaluate the need to track performance
77f00f84 632 this.wsConnection.send(message);
8e242273 633 this.messageBuffer.delete(message);
77f00f84
JB
634 });
635 }
636 }
637
1f5df42a
JB
638 private getSupervisionUrlOcppConfiguration(): boolean {
639 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
12fc74d6
JB
640 }
641
c0560973 642 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
ef6076c1 643 // In case of multiple instances: add instance index to charging station id
203bc097 644 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
9ccca265 645 const idSuffix = stationTemplate.nameSuffix ?? '';
e7aeea18
JB
646 return stationTemplate.fixedName
647 ? stationTemplate.baseName
648 : stationTemplate.baseName +
649 '-' +
650 instanceIndex.toString() +
651 ('000000000' + this.index.toString()).substr(
652 ('000000000' + this.index.toString()).length - 4
653 ) +
654 idSuffix;
5ad8570f
JB
655 }
656
c0560973 657 private buildStationInfo(): ChargingStationInfo {
9ac86a7e 658 let stationTemplateFromFile: ChargingStationTemplate;
5ad8570f
JB
659 try {
660 // Load template file
ad2f27c3 661 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
e7aeea18
JB
662 stationTemplateFromFile = JSON.parse(
663 fs.readFileSync(fileDescriptor, 'utf8')
664 ) as ChargingStationTemplate;
5ad8570f
JB
665 fs.closeSync(fileDescriptor);
666 } catch (error) {
e7aeea18
JB
667 FileUtils.handleFileException(
668 this.logPrefix(),
669 'Template',
670 this.stationTemplateFile,
671 error as NodeJS.ErrnoException
672 );
5ad8570f 673 }
2dcfe98e
JB
674 const chargingStationId = this.getChargingStationId(stationTemplateFromFile);
675 // Deprecation template keys section
e7aeea18
JB
676 this.warnDeprecatedTemplateKey(
677 stationTemplateFromFile,
678 'supervisionUrl',
679 chargingStationId,
680 "Use 'supervisionUrls' instead"
681 );
2dcfe98e 682 this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls');
e7aeea18 683 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? ({} as ChargingStationInfo);
cd8dd457 684 stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
0a60c33c 685 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
9ac86a7e 686 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
e7aeea18
JB
687 const powerArrayRandomIndex = Math.floor(
688 Utils.secureRandom() * stationTemplateFromFile.power.length
689 );
690 stationInfo.maxPower =
691 stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
692 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
693 : stationTemplateFromFile.power[powerArrayRandomIndex];
5ad8570f 694 } else {
510f0fa5 695 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
e7aeea18
JB
696 stationInfo.maxPower =
697 stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
698 ? stationTemplateFromFile.power * 1000
699 : stationTemplateFromFile.power;
5ad8570f 700 }
fd0c36fa
JB
701 delete stationInfo.power;
702 delete stationInfo.powerUnit;
2dcfe98e 703 stationInfo.chargingStationId = chargingStationId;
e7aeea18
JB
704 stationInfo.resetTime = stationTemplateFromFile.resetTime
705 ? stationTemplateFromFile.resetTime * 1000
706 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
9ac86a7e 707 return stationInfo;
5ad8570f
JB
708 }
709
1f5df42a 710 private getOcppVersion(): OCPPVersion {
c0560973
JB
711 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
712 }
713
714 private handleUnsupportedVersion(version: OCPPVersion) {
e7aeea18
JB
715 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
716 this.stationTemplateFile
717 }`;
9f2e3130 718 logger.error(errMsg);
c0560973
JB
719 throw new Error(errMsg);
720 }
721
722 private initialize(): void {
723 this.stationInfo = this.buildStationInfo();
37486900 724 this.configuration = this.getTemplateChargingStationConfiguration();
798010fa 725 delete this.stationInfo.Configuration;
ad2f27c3
JB
726 this.bootNotificationRequest = {
727 chargePointModel: this.stationInfo.chargePointModel,
728 chargePointVendor: this.stationInfo.chargePointVendor,
e7aeea18
JB
729 ...(!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && {
730 chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix,
731 }),
732 ...(!Utils.isUndefined(this.stationInfo.firmwareVersion) && {
733 firmwareVersion: this.stationInfo.firmwareVersion,
734 }),
2e6f5966 735 };
0a60c33c 736 // Build connectors if needed
c0560973 737 const maxConnectors = this.getMaxNumberOfConnectors();
6ecb15e4 738 if (maxConnectors <= 0) {
e7aeea18
JB
739 logger.warn(
740 `${this.logPrefix()} Charging station template ${
741 this.stationTemplateFile
742 } with ${maxConnectors} connectors`
743 );
7abfea5f 744 }
c0560973 745 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
7abfea5f 746 if (templateMaxConnectors <= 0) {
e7aeea18
JB
747 logger.warn(
748 `${this.logPrefix()} Charging station template ${
749 this.stationTemplateFile
750 } with no connector configuration`
751 );
593cf3f9 752 }
ad2f27c3 753 if (!this.stationInfo.Connectors[0]) {
e7aeea18
JB
754 logger.warn(
755 `${this.logPrefix()} Charging station template ${
756 this.stationTemplateFile
757 } with no connector Id 0 configuration`
758 );
7abfea5f
JB
759 }
760 // Sanity check
e7aeea18
JB
761 if (
762 maxConnectors >
763 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
764 !this.stationInfo.randomConnectors
765 ) {
766 logger.warn(
767 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
768 this.stationTemplateFile
769 }, forcing random connector configurations affectation`
770 );
ad2f27c3 771 this.stationInfo.randomConnectors = true;
6ecb15e4 772 }
e7aeea18
JB
773 const connectorsConfigHash = crypto
774 .createHash('sha256')
775 .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
776 .digest('hex');
777 const connectorsConfigChanged =
778 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
54544ef1 779 if (this.connectors?.size === 0 || connectorsConfigChanged) {
e7aeea18 780 connectorsConfigChanged && this.connectors.clear();
ad2f27c3 781 this.connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 782 // Add connector Id 0
6af9012e 783 let lastConnector = '0';
ad2f27c3 784 for (lastConnector in this.stationInfo.Connectors) {
734d790d 785 const lastConnectorId = Utils.convertToInt(lastConnector);
e7aeea18
JB
786 if (
787 lastConnectorId === 0 &&
788 this.getUseConnectorId0() &&
789 this.stationInfo.Connectors[lastConnector]
790 ) {
791 this.connectors.set(
792 lastConnectorId,
793 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])
794 );
734d790d
JB
795 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
796 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
797 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
418106c8 798 }
0a60c33c
JB
799 }
800 }
0a60c33c 801 // Generate all connectors
e7aeea18
JB
802 if (
803 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0
804 ) {
7abfea5f 805 for (let index = 1; index <= maxConnectors; index++) {
e7aeea18
JB
806 const randConnectorId = this.stationInfo.randomConnectors
807 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
808 : index;
809 this.connectors.set(
810 index,
811 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])
812 );
734d790d
JB
813 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
814 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
815 this.getConnectorStatus(index).chargingProfiles = [];
418106c8 816 }
7abfea5f 817 }
0a60c33c
JB
818 }
819 }
d4a73fb7 820 // Avoid duplication of connectors related information
ad2f27c3 821 delete this.stationInfo.Connectors;
0a60c33c 822 // Initialize transaction attributes on connectors
734d790d
JB
823 for (const connectorId of this.connectors.keys()) {
824 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
a2653482 825 this.initializeConnectorStatus(connectorId);
0a60c33c
JB
826 }
827 }
e7aeea18
JB
828 this.wsConfiguredConnectionUrl = new URL(
829 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
830 );
1f5df42a 831 switch (this.getOcppVersion()) {
c0560973 832 case OCPPVersion.VERSION_16:
e7aeea18
JB
833 this.ocppIncomingRequestService =
834 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
835 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
836 this,
837 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
838 );
c0560973
JB
839 break;
840 default:
1f5df42a 841 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
842 break;
843 }
7abfea5f 844 // OCPP parameters
1f5df42a 845 this.initOcppParameters();
47e22477
JB
846 if (this.stationInfo.autoRegister) {
847 this.bootNotificationResponse = {
848 currentTime: new Date().toISOString(),
849 interval: this.getHeartbeatInterval() / 1000,
e7aeea18 850 status: RegistrationStatus.ACCEPTED,
47e22477
JB
851 };
852 }
147d0e0f
JB
853 this.stationInfo.powerDivider = this.getPowerDivider();
854 if (this.getEnableStatistics()) {
e7aeea18
JB
855 this.performanceStatistics = PerformanceStatistics.getInstance(
856 this.id,
857 this.stationInfo.chargingStationId,
858 this.wsConnectionUrl
859 );
147d0e0f
JB
860 }
861 }
862
1f5df42a 863 private initOcppParameters(): void {
e7aeea18
JB
864 if (
865 this.getSupervisionUrlOcppConfiguration() &&
866 !this.getConfigurationKey(
867 this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl
868 )
869 ) {
870 this.addConfigurationKey(
871 VendorDefaultParametersKey.ConnectionUrl,
872 this.getConfiguredSupervisionUrl().href,
873 { reboot: true }
874 );
12fc74d6 875 }
36f6a92e 876 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
e7aeea18
JB
877 this.addConfigurationKey(
878 StandardParametersKey.SupportedFeatureProfiles,
879 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
880 );
881 }
882 this.addConfigurationKey(
883 StandardParametersKey.NumberOfConnectors,
884 this.getNumberOfConnectors().toString(),
885 { readonly: true }
886 );
c0560973 887 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
e7aeea18
JB
888 this.addConfigurationKey(
889 StandardParametersKey.MeterValuesSampledData,
890 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
891 );
7abfea5f 892 }
7e1dc878
JB
893 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
894 const connectorPhaseRotation = [];
734d790d 895 for (const connectorId of this.connectors.keys()) {
7e1dc878 896 // AC/DC
734d790d
JB
897 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
898 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
899 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
900 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
e7aeea18 901 // AC
734d790d
JB
902 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
903 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
904 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
905 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
7e1dc878
JB
906 }
907 }
e7aeea18
JB
908 this.addConfigurationKey(
909 StandardParametersKey.ConnectorPhaseRotation,
910 connectorPhaseRotation.toString()
911 );
7e1dc878 912 }
36f6a92e
JB
913 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
914 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
915 }
e7aeea18
JB
916 if (
917 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
918 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(
919 SupportedFeatureProfiles.Local_Auth_List_Management
920 )
921 ) {
36f6a92e
JB
922 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
923 }
147d0e0f 924 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
e7aeea18
JB
925 this.addConfigurationKey(
926 StandardParametersKey.ConnectionTimeOut,
927 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
928 );
8bce55bf 929 }
7dde0b73
JB
930 }
931
c0560973 932 private async onOpen(): Promise<void> {
e7aeea18
JB
933 logger.info(
934 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
935 );
672fed6e 936 if (!this.isInAcceptedState()) {
c0560973
JB
937 // Send BootNotification
938 let registrationRetryCount = 0;
939 do {
e7aeea18
JB
940 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(
941 this.bootNotificationRequest.chargePointModel,
942 this.bootNotificationRequest.chargePointVendor,
943 this.bootNotificationRequest.chargeBoxSerialNumber,
944 this.bootNotificationRequest.firmwareVersion
945 );
672fed6e
JB
946 if (!this.isInAcceptedState()) {
947 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
e7aeea18
JB
948 await Utils.sleep(
949 this.bootNotificationResponse?.interval
950 ? this.bootNotificationResponse.interval * 1000
951 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
952 );
c0560973 953 }
e7aeea18
JB
954 } while (
955 !this.isInAcceptedState() &&
956 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
957 this.getRegistrationMaxRetries() === -1)
958 );
c7db4718 959 }
16cd35ad 960 if (this.isInAcceptedState()) {
c0560973 961 await this.startMessageSequence();
265e4266
JB
962 this.stopped && (this.stopped = false);
963 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
caad9d6b
JB
964 this.flushMessageBuffer();
965 }
2e6f5966 966 } else {
e7aeea18
JB
967 logger.error(
968 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
969 );
2e6f5966 970 }
c0560973 971 this.autoReconnectRetryCount = 0;
265e4266 972 this.wsConnectionRestarted = false;
2e6f5966
JB
973 }
974
6c65a295 975 private async onClose(code: number, reason: string): Promise<void> {
d09085e9 976 switch (code) {
6c65a295
JB
977 // Normal close
978 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 979 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18
JB
980 logger.info(
981 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
982 code
983 )}' and reason '${reason}'`
984 );
c0560973
JB
985 this.autoReconnectRetryCount = 0;
986 break;
6c65a295
JB
987 // Abnormal close
988 default:
e7aeea18
JB
989 logger.error(
990 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
991 code
992 )}' and reason '${reason}'`
993 );
d09085e9 994 await this.reconnect(code);
c0560973
JB
995 break;
996 }
2e6f5966
JB
997 }
998
16b0d4e7 999 private async onMessage(data: Data): Promise<void> {
e7aeea18
JB
1000 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [
1001 0,
1002 '',
1003 '' as IncomingRequestCommand,
1004 {},
1005 {},
1006 ];
1007 let responseCallback: (
1008 payload: JsonType | string,
1009 requestPayload: JsonType | OCPPError
1010 ) => void;
9239b49a 1011 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
32b02249 1012 let requestCommandName: RequestCommand | IncomingRequestCommand;
d1888640 1013 let requestPayload: JsonType | OCPPError;
32b02249 1014 let cachedRequest: CachedRequest;
c0560973
JB
1015 let errMsg: string;
1016 try {
16b0d4e7 1017 const request = JSON.parse(data.toString()) as IncomingRequest;
47e22477
JB
1018 if (Utils.isIterable(request)) {
1019 // Parse the message
1020 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
1021 } else {
e7aeea18
JB
1022 throw new OCPPError(
1023 ErrorType.PROTOCOL_ERROR,
1024 'Incoming request is not iterable',
1025 commandName
1026 );
47e22477 1027 }
c0560973
JB
1028 // Check the Type of message
1029 switch (messageType) {
1030 // Incoming Message
1031 case MessageType.CALL_MESSAGE:
1032 if (this.getEnableStatistics()) {
aef1b33a 1033 this.performanceStatistics.addRequestStatistic(commandName, messageType);
c0560973
JB
1034 }
1035 // Process the call
e7aeea18
JB
1036 await this.ocppIncomingRequestService.handleRequest(
1037 messageId,
1038 commandName,
1039 commandPayload
1040 );
c0560973
JB
1041 break;
1042 // Outcome Message
1043 case MessageType.CALL_RESULT_MESSAGE:
1044 // Respond
16b0d4e7
JB
1045 cachedRequest = this.requests.get(messageId);
1046 if (Utils.isIterable(cachedRequest)) {
32b02249 1047 [responseCallback, , , requestPayload] = cachedRequest;
c0560973 1048 } else {
e7aeea18
JB
1049 throw new OCPPError(
1050 ErrorType.PROTOCOL_ERROR,
1051 `Cached request for message id ${messageId} response is not iterable`,
1052 commandName
1053 );
c0560973
JB
1054 }
1055 if (!responseCallback) {
1056 // Error
e7aeea18
JB
1057 throw new OCPPError(
1058 ErrorType.INTERNAL_ERROR,
1059 `Response for unknown message id ${messageId}`,
1060 commandName
1061 );
c0560973 1062 }
c0560973
JB
1063 responseCallback(commandName, requestPayload);
1064 break;
1065 // Error Message
1066 case MessageType.CALL_ERROR_MESSAGE:
16b0d4e7 1067 cachedRequest = this.requests.get(messageId);
16b0d4e7 1068 if (Utils.isIterable(cachedRequest)) {
32b02249 1069 [, rejectCallback, requestCommandName] = cachedRequest;
c0560973 1070 } else {
e7aeea18
JB
1071 throw new OCPPError(
1072 ErrorType.PROTOCOL_ERROR,
1073 `Cached request for message id ${messageId} error response is not iterable`
1074 );
c0560973 1075 }
32b02249
JB
1076 if (!rejectCallback) {
1077 // Error
e7aeea18
JB
1078 throw new OCPPError(
1079 ErrorType.INTERNAL_ERROR,
1080 `Error response for unknown message id ${messageId}`,
1081 requestCommandName
1082 );
32b02249 1083 }
e7aeea18
JB
1084 rejectCallback(
1085 new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails)
1086 );
c0560973
JB
1087 break;
1088 // Error
1089 default:
9534e74e 1090 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
c0560973 1091 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
9f2e3130 1092 logger.error(errMsg);
14763b46 1093 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
c0560973
JB
1094 }
1095 } catch (error) {
1096 // Log
e7aeea18
JB
1097 logger.error(
1098 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1099 this.logPrefix(),
1100 data.toString(),
1101 this.requests.get(messageId),
1102 error
1103 );
c0560973 1104 // Send error
e7aeea18
JB
1105 messageType === MessageType.CALL_MESSAGE &&
1106 (await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName));
c0560973 1107 }
2328be1e
JB
1108 }
1109
c0560973 1110 private onPing(): void {
9f2e3130 1111 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
c0560973
JB
1112 }
1113
1114 private onPong(): void {
9f2e3130 1115 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
c0560973
JB
1116 }
1117
9534e74e 1118 private onError(error: WSError): void {
9f2e3130 1119 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
c0560973
JB
1120 }
1121
1122 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
e7aeea18 1123 return this.stationInfo.Configuration ?? ({} as ChargingStationConfiguration);
c0560973
JB
1124 }
1125
6e0964c8 1126 private getAuthorizationFile(): string | undefined {
e7aeea18
JB
1127 return (
1128 this.stationInfo.authorizationFile &&
1129 path.join(
1130 path.resolve(__dirname, '../'),
1131 'assets',
1132 path.basename(this.stationInfo.authorizationFile)
1133 )
1134 );
c0560973
JB
1135 }
1136
1137 private getAuthorizedTags(): string[] {
1138 let authorizedTags: string[] = [];
1139 const authorizationFile = this.getAuthorizationFile();
1140 if (authorizationFile) {
1141 try {
1142 // Load authorization file
1143 const fileDescriptor = fs.openSync(authorizationFile, 'r');
1144 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
1145 fs.closeSync(fileDescriptor);
1146 } catch (error) {
e7aeea18
JB
1147 FileUtils.handleFileException(
1148 this.logPrefix(),
1149 'Authorization',
1150 authorizationFile,
1151 error as NodeJS.ErrnoException
1152 );
c0560973
JB
1153 }
1154 } else {
e7aeea18
JB
1155 logger.info(
1156 this.logPrefix() +
1157 ' No authorization file given in template file ' +
1158 this.stationTemplateFile
1159 );
8c4da341 1160 }
c0560973
JB
1161 return authorizedTags;
1162 }
1163
6e0964c8 1164 private getUseConnectorId0(): boolean | undefined {
e7aeea18
JB
1165 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1166 ? this.stationInfo.useConnectorId0
1167 : true;
8bce55bf
JB
1168 }
1169
c0560973 1170 private getNumberOfRunningTransactions(): number {
6ecb15e4 1171 let trxCount = 0;
734d790d
JB
1172 for (const connectorId of this.connectors.keys()) {
1173 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
6ecb15e4
JB
1174 trxCount++;
1175 }
1176 }
1177 return trxCount;
1178 }
1179
1f761b9a 1180 // 0 for disabling
6e0964c8 1181 private getConnectionTimeout(): number | undefined {
291cb255 1182 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
e7aeea18
JB
1183 return (
1184 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1185 Constants.DEFAULT_CONNECTION_TIMEOUT
1186 );
291cb255 1187 }
291cb255 1188 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
1189 }
1190
1f761b9a 1191 // -1 for unlimited, 0 for disabling
6e0964c8 1192 private getAutoReconnectMaxRetries(): number | undefined {
ad2f27c3
JB
1193 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1194 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
1195 }
1196 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1197 return Configuration.getAutoReconnectMaxRetries();
1198 }
1199 return -1;
1200 }
1201
ec977daf 1202 // 0 for disabling
6e0964c8 1203 private getRegistrationMaxRetries(): number | undefined {
ad2f27c3
JB
1204 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1205 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
1206 }
1207 return -1;
1208 }
1209
c0560973
JB
1210 private getPowerDivider(): number {
1211 let powerDivider = this.getNumberOfConnectors();
ad2f27c3 1212 if (this.stationInfo.powerSharedByConnectors) {
c0560973 1213 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
1214 }
1215 return powerDivider;
1216 }
1217
c0560973 1218 private getTemplateMaxNumberOfConnectors(): number {
ad2f27c3 1219 return Object.keys(this.stationInfo.Connectors).length;
7abfea5f
JB
1220 }
1221
c0560973 1222 private getMaxNumberOfConnectors(): number {
e58068fd 1223 let maxConnectors: number;
ad2f27c3
JB
1224 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1225 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
6ecb15e4 1226 // Distribute evenly the number of connectors
ad2f27c3
JB
1227 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1228 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1229 maxConnectors = this.stationInfo.numberOfConnectors as number;
488fd3a7 1230 } else {
e7aeea18
JB
1231 maxConnectors = this.stationInfo.Connectors[0]
1232 ? this.getTemplateMaxNumberOfConnectors() - 1
1233 : this.getTemplateMaxNumberOfConnectors();
5ad8570f
JB
1234 }
1235 return maxConnectors;
2e6f5966
JB
1236 }
1237
c0560973 1238 private async startMessageSequence(): Promise<void> {
6114e6f1 1239 if (this.stationInfo.autoRegister) {
e7aeea18
JB
1240 await this.ocppRequestService.sendBootNotification(
1241 this.bootNotificationRequest.chargePointModel,
1242 this.bootNotificationRequest.chargePointVendor,
1243 this.bootNotificationRequest.chargeBoxSerialNumber,
1244 this.bootNotificationRequest.firmwareVersion
1245 );
6114e6f1 1246 }
136c90ba 1247 // Start WebSocket ping
c0560973 1248 this.startWebSocketPing();
5ad8570f 1249 // Start heartbeat
c0560973 1250 this.startHeartbeat();
0a60c33c 1251 // Initialize connectors status
734d790d
JB
1252 for (const connectorId of this.connectors.keys()) {
1253 if (connectorId === 0) {
593cf3f9 1254 continue;
e7aeea18
JB
1255 } else if (
1256 !this.stopped &&
1257 !this.getConnectorStatus(connectorId)?.status &&
1258 this.getConnectorStatus(connectorId)?.bootStatus
1259 ) {
136c90ba 1260 // Send status in template at startup
e7aeea18
JB
1261 await this.ocppRequestService.sendStatusNotification(
1262 connectorId,
1263 this.getConnectorStatus(connectorId).bootStatus
1264 );
1265 this.getConnectorStatus(connectorId).status =
1266 this.getConnectorStatus(connectorId).bootStatus;
1267 } else if (
1268 this.stopped &&
1269 this.getConnectorStatus(connectorId)?.status &&
1270 this.getConnectorStatus(connectorId)?.bootStatus
1271 ) {
136c90ba 1272 // Send status in template after reset
e7aeea18
JB
1273 await this.ocppRequestService.sendStatusNotification(
1274 connectorId,
1275 this.getConnectorStatus(connectorId).bootStatus
1276 );
1277 this.getConnectorStatus(connectorId).status =
1278 this.getConnectorStatus(connectorId).bootStatus;
734d790d 1279 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
136c90ba 1280 // Send previous status at template reload
e7aeea18
JB
1281 await this.ocppRequestService.sendStatusNotification(
1282 connectorId,
1283 this.getConnectorStatus(connectorId).status
1284 );
5ad8570f 1285 } else {
136c90ba 1286 // Send default status
e7aeea18
JB
1287 await this.ocppRequestService.sendStatusNotification(
1288 connectorId,
1289 ChargePointStatus.AVAILABLE
1290 );
734d790d 1291 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
1292 }
1293 }
0a60c33c 1294 // Start the ATG
dd119a6b 1295 this.startAutomaticTransactionGenerator();
dd119a6b
JB
1296 }
1297
1298 private startAutomaticTransactionGenerator() {
ad2f27c3 1299 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
265e4266 1300 if (!this.automaticTransactionGenerator) {
73b9adec 1301 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
5ad8570f 1302 }
265e4266
JB
1303 if (!this.automaticTransactionGenerator.started) {
1304 this.automaticTransactionGenerator.start();
5ad8570f
JB
1305 }
1306 }
5ad8570f
JB
1307 }
1308
e7aeea18
JB
1309 private async stopMessageSequence(
1310 reason: StopTransactionReason = StopTransactionReason.NONE
1311 ): Promise<void> {
136c90ba 1312 // Stop WebSocket ping
c0560973 1313 this.stopWebSocketPing();
79411696 1314 // Stop heartbeat
c0560973 1315 this.stopHeartbeat();
79411696 1316 // Stop the ATG
e7aeea18
JB
1317 if (
1318 this.stationInfo.AutomaticTransactionGenerator.enable &&
1319 this.automaticTransactionGenerator?.started
1320 ) {
0045cef5 1321 this.automaticTransactionGenerator.stop();
79411696 1322 } else {
734d790d
JB
1323 for (const connectorId of this.connectors.keys()) {
1324 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1325 const transactionId = this.getConnectorStatus(connectorId).transactionId;
e7aeea18
JB
1326 await this.ocppRequestService.sendStopTransaction(
1327 transactionId,
1328 this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1329 this.getTransactionIdTag(transactionId),
1330 reason
1331 );
79411696
JB
1332 }
1333 }
1334 }
1335 }
1336
c0560973 1337 private startWebSocketPing(): void {
e7aeea18
JB
1338 const webSocketPingInterval: number = this.getConfigurationKey(
1339 StandardParametersKey.WebSocketPingInterval
1340 )
1341 ? Utils.convertToInt(
1342 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
1343 )
9cd3dfb0 1344 : 0;
ad2f27c3
JB
1345 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1346 this.webSocketPingSetInterval = setInterval(() => {
d5bff457 1347 if (this.isWebSocketConnectionOpened()) {
e7aeea18
JB
1348 this.wsConnection.ping((): void => {
1349 /* This is intentional */
1350 });
136c90ba
JB
1351 }
1352 }, webSocketPingInterval * 1000);
e7aeea18
JB
1353 logger.info(
1354 this.logPrefix() +
1355 ' WebSocket ping started every ' +
1356 Utils.formatDurationSeconds(webSocketPingInterval)
1357 );
ad2f27c3 1358 } else if (this.webSocketPingSetInterval) {
e7aeea18
JB
1359 logger.info(
1360 this.logPrefix() +
1361 ' WebSocket ping every ' +
1362 Utils.formatDurationSeconds(webSocketPingInterval) +
1363 ' already started'
1364 );
136c90ba 1365 } else {
e7aeea18
JB
1366 logger.error(
1367 `${this.logPrefix()} WebSocket ping interval set to ${
1368 webSocketPingInterval
1369 ? Utils.formatDurationSeconds(webSocketPingInterval)
1370 : webSocketPingInterval
1371 }, not starting the WebSocket ping`
1372 );
136c90ba
JB
1373 }
1374 }
1375
c0560973 1376 private stopWebSocketPing(): void {
ad2f27c3
JB
1377 if (this.webSocketPingSetInterval) {
1378 clearInterval(this.webSocketPingSetInterval);
136c90ba
JB
1379 }
1380 }
1381
e7aeea18
JB
1382 private warnDeprecatedTemplateKey(
1383 template: ChargingStationTemplate,
1384 key: string,
1385 chargingStationId: string,
1386 logMsgToAppend = ''
1387 ): void {
2dcfe98e 1388 if (!Utils.isUndefined(template[key])) {
e7aeea18
JB
1389 const logPrefixStr = ` ${chargingStationId} |`;
1390 logger.warn(
1391 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1392 this.stationTemplateFile
1393 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1394 );
2dcfe98e
JB
1395 }
1396 }
1397
e7aeea18
JB
1398 private convertDeprecatedTemplateKey(
1399 template: ChargingStationTemplate,
1400 deprecatedKey: string,
1401 key: string
1402 ): void {
2dcfe98e 1403 if (!Utils.isUndefined(template[deprecatedKey])) {
c0f4be74 1404 template[key] = template[deprecatedKey] as unknown;
2dcfe98e
JB
1405 delete template[deprecatedKey];
1406 }
1407 }
1408
1f5df42a 1409 private getConfiguredSupervisionUrl(): URL {
e7aeea18
JB
1410 const supervisionUrls = Utils.cloneObject<string | string[]>(
1411 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1412 );
c0560973 1413 if (!Utils.isEmptyArray(supervisionUrls)) {
2dcfe98e
JB
1414 let urlIndex = 0;
1415 switch (Configuration.getSupervisionUrlDistribution()) {
1416 case SupervisionUrlDistribution.ROUND_ROBIN:
1417 urlIndex = (this.index - 1) % supervisionUrls.length;
1418 break;
1419 case SupervisionUrlDistribution.RANDOM:
1420 // Get a random url
1421 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1422 break;
1423 case SupervisionUrlDistribution.SEQUENTIAL:
1424 if (this.index <= supervisionUrls.length) {
1425 urlIndex = this.index - 1;
1426 } else {
e7aeea18
JB
1427 logger.warn(
1428 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1429 );
2dcfe98e
JB
1430 }
1431 break;
1432 default:
e7aeea18
JB
1433 logger.error(
1434 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1435 SupervisionUrlDistribution.ROUND_ROBIN
1436 }`
1437 );
2dcfe98e
JB
1438 urlIndex = (this.index - 1) % supervisionUrls.length;
1439 break;
c0560973 1440 }
2dcfe98e 1441 return new URL(supervisionUrls[urlIndex]);
c0560973 1442 }
57939a9d 1443 return new URL(supervisionUrls as string);
136c90ba
JB
1444 }
1445
6e0964c8 1446 private getHeartbeatInterval(): number | undefined {
c0560973
JB
1447 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1448 if (HeartbeatInterval) {
1449 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1450 }
1451 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1452 if (HeartBeatInterval) {
1453 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c 1454 }
e7aeea18
JB
1455 !this.stationInfo.autoRegister &&
1456 logger.warn(
1457 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1458 Constants.DEFAULT_HEARTBEAT_INTERVAL
1459 }`
1460 );
47e22477 1461 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
0a60c33c
JB
1462 }
1463
c0560973 1464 private stopHeartbeat(): void {
ad2f27c3
JB
1465 if (this.heartbeatSetInterval) {
1466 clearInterval(this.heartbeatSetInterval);
7dde0b73 1467 }
5ad8570f
JB
1468 }
1469
e7aeea18
JB
1470 private openWSConnection(
1471 options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions,
1472 forceCloseOpened = false
1473 ): void {
37486900 1474 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
e7aeea18
JB
1475 if (
1476 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
1477 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
1478 ) {
15042c5f
JB
1479 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1480 }
d5bff457 1481 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
c0560973
JB
1482 this.wsConnection.close();
1483 }
88184022 1484 let protocol: string;
1f5df42a 1485 switch (this.getOcppVersion()) {
c0560973
JB
1486 case OCPPVersion.VERSION_16:
1487 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1488 break;
1489 default:
1f5df42a 1490 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
1491 break;
1492 }
1493 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
e7aeea18
JB
1494 logger.info(
1495 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
1496 );
136c90ba
JB
1497 }
1498
dd119a6b 1499 private stopMeterValues(connectorId: number) {
734d790d
JB
1500 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1501 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
dd119a6b
JB
1502 }
1503 }
1504
c0560973 1505 private startAuthorizationFileMonitoring(): void {
23132a44
JB
1506 const authorizationFile = this.getAuthorizationFile();
1507 if (authorizationFile) {
5ad8570f 1508 try {
3ec10737
JB
1509 fs.watch(authorizationFile, (event, filename) => {
1510 if (filename && event === 'change') {
1511 try {
e7aeea18
JB
1512 logger.debug(
1513 this.logPrefix() +
1514 ' Authorization file ' +
1515 authorizationFile +
1516 ' have changed, reload'
1517 );
3ec10737
JB
1518 // Initialize authorizedTags
1519 this.authorizedTags = this.getAuthorizedTags();
1520 } catch (error) {
9f2e3130 1521 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
3ec10737 1522 }
23132a44
JB
1523 }
1524 });
5ad8570f 1525 } catch (error) {
e7aeea18
JB
1526 FileUtils.handleFileException(
1527 this.logPrefix(),
1528 'Authorization',
1529 authorizationFile,
1530 error as NodeJS.ErrnoException
1531 );
5ad8570f 1532 }
23132a44 1533 } else {
e7aeea18
JB
1534 logger.info(
1535 this.logPrefix() +
1536 ' No authorization file given in template file ' +
1537 this.stationTemplateFile +
1538 '. Not monitoring changes'
1539 );
23132a44 1540 }
5ad8570f
JB
1541 }
1542
c0560973 1543 private startStationTemplateFileMonitoring(): void {
23132a44 1544 try {
b809adf1 1545 fs.watch(this.stationTemplateFile, (event, filename): void => {
3ec10737
JB
1546 if (filename && event === 'change') {
1547 try {
e7aeea18
JB
1548 logger.debug(
1549 this.logPrefix() +
1550 ' Template file ' +
1551 this.stationTemplateFile +
1552 ' have changed, reload'
1553 );
3ec10737
JB
1554 // Initialize
1555 this.initialize();
1556 // Restart the ATG
e7aeea18
JB
1557 if (
1558 !this.stationInfo.AutomaticTransactionGenerator.enable &&
1559 this.automaticTransactionGenerator
1560 ) {
0045cef5 1561 this.automaticTransactionGenerator.stop();
3ec10737
JB
1562 }
1563 this.startAutomaticTransactionGenerator();
1564 if (this.getEnableStatistics()) {
1565 this.performanceStatistics.restart();
1566 } else {
1567 this.performanceStatistics.stop();
1568 }
1569 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1570 } catch (error) {
e7aeea18
JB
1571 logger.error(
1572 this.logPrefix() + ' Charging station template file monitoring error: %j',
1573 error
1574 );
087a502d 1575 }
79411696 1576 }
23132a44
JB
1577 });
1578 } catch (error) {
e7aeea18
JB
1579 FileUtils.handleFileException(
1580 this.logPrefix(),
1581 'Template',
1582 this.stationTemplateFile,
1583 error as NodeJS.ErrnoException
1584 );
23132a44 1585 }
5ad8570f
JB
1586 }
1587
6e0964c8 1588 private getReconnectExponentialDelay(): boolean | undefined {
e7aeea18
JB
1589 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1590 ? this.stationInfo.reconnectExponentialDelay
1591 : false;
5ad8570f
JB
1592 }
1593
d09085e9 1594 private async reconnect(code: number): Promise<void> {
7874b0b1
JB
1595 // Stop WebSocket ping
1596 this.stopWebSocketPing();
136c90ba 1597 // Stop heartbeat
c0560973 1598 this.stopHeartbeat();
5ad8570f 1599 // Stop the ATG if needed
e7aeea18
JB
1600 if (
1601 this.stationInfo.AutomaticTransactionGenerator.enable &&
ad2f27c3 1602 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
e7aeea18
JB
1603 this.automaticTransactionGenerator?.started
1604 ) {
0045cef5 1605 this.automaticTransactionGenerator.stop();
ad2f27c3 1606 }
e7aeea18
JB
1607 if (
1608 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1609 this.getAutoReconnectMaxRetries() === -1
1610 ) {
ad2f27c3 1611 this.autoReconnectRetryCount++;
e7aeea18
JB
1612 const reconnectDelay = this.getReconnectExponentialDelay()
1613 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1614 : this.getConnectionTimeout() * 1000;
1615 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
1616 logger.error(
1617 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1618 reconnectDelay,
1619 2
1620 )}ms, timeout ${reconnectTimeout}ms`
1621 );
032d6efc 1622 await Utils.sleep(reconnectDelay);
e7aeea18
JB
1623 logger.error(
1624 this.logPrefix() +
1625 ' WebSocket: reconnecting try #' +
1626 this.autoReconnectRetryCount.toString()
1627 );
1628 this.openWSConnection(
1629 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
1630 true
1631 );
265e4266 1632 this.wsConnectionRestarted = true;
c0560973 1633 } else if (this.getAutoReconnectMaxRetries() !== -1) {
e7aeea18
JB
1634 logger.error(
1635 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1636 this.autoReconnectRetryCount
1637 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1638 );
5ad8570f
JB
1639 }
1640 }
1641
a2653482
JB
1642 private initializeConnectorStatus(connectorId: number): void {
1643 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1644 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1645 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d
JB
1646 this.getConnectorStatus(connectorId).transactionStarted = false;
1647 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1648 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
0a60c33c 1649 }
7dde0b73 1650}