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