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