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