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