Apply dependencies update
[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);
2484ac1e 898 template = JSON.parse(fs.readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate;
42a3eee7 899 PerformanceStatistics.endMeasure(measureId, beginId);
5ad8570f 900 } catch (error) {
e7aeea18
JB
901 FileUtils.handleFileException(
902 this.logPrefix(),
a95873d8 903 FileType.ChargingStationTemplate,
2484ac1e 904 this.templateFile,
e7aeea18
JB
905 error as NodeJS.ErrnoException
906 );
5ad8570f 907 }
2484ac1e
JB
908 return template;
909 }
910
911 private createSerialNumber(
912 stationInfo: ChargingStationInfo,
7a3a2ebb
JB
913 existingStationInfo?: ChargingStationInfo,
914 params: { randomSerialNumberUpperCase?: boolean; randomSerialNumber?: boolean } = {
915 randomSerialNumberUpperCase: true,
916 randomSerialNumber: true,
917 }
2484ac1e 918 ): void {
7a3a2ebb
JB
919 params = params ?? {};
920 params.randomSerialNumberUpperCase = params?.randomSerialNumberUpperCase ?? true;
921 params.randomSerialNumber = params?.randomSerialNumber ?? true;
922 if (existingStationInfo) {
923 existingStationInfo?.chargePointSerialNumber &&
924 (stationInfo.chargePointSerialNumber = existingStationInfo.chargePointSerialNumber);
925 existingStationInfo?.chargeBoxSerialNumber &&
926 (stationInfo.chargeBoxSerialNumber = existingStationInfo.chargeBoxSerialNumber);
0b7c34ba
JB
927 existingStationInfo?.meterSerialNumber &&
928 (stationInfo.meterSerialNumber = existingStationInfo.meterSerialNumber);
7a3a2ebb
JB
929 } else {
930 const serialNumberSuffix = params?.randomSerialNumber
931 ? this.getRandomSerialNumberSuffix({ upperCase: params.randomSerialNumberUpperCase })
932 : '';
933 stationInfo.chargePointSerialNumber =
934 stationInfo?.chargePointSerialNumberPrefix &&
935 stationInfo.chargePointSerialNumberPrefix + serialNumberSuffix;
936 stationInfo.chargeBoxSerialNumber =
937 stationInfo?.chargeBoxSerialNumberPrefix &&
938 stationInfo.chargeBoxSerialNumberPrefix + serialNumberSuffix;
0b7c34ba
JB
939 stationInfo.meterSerialNumber =
940 stationInfo?.meterSerialNumberPrefix &&
941 stationInfo.meterSerialNumberPrefix + serialNumberSuffix;
7a3a2ebb
JB
942 }
943 }
944
945 private getStationInfoFromTemplate(): ChargingStationInfo {
946 const stationInfo: ChargingStationInfo =
947 this.getTemplateFromFile() ?? ({} as ChargingStationInfo);
2484ac1e
JB
948 stationInfo.hash = crypto
949 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
7a3a2ebb 950 .update(JSON.stringify(stationInfo))
2484ac1e 951 .digest('hex');
7a3a2ebb 952 const chargingStationId = this.getChargingStationId(stationInfo);
2dcfe98e 953 // Deprecation template keys section
e7aeea18 954 this.warnDeprecatedTemplateKey(
7a3a2ebb 955 stationInfo,
e7aeea18
JB
956 'supervisionUrl',
957 chargingStationId,
958 "Use 'supervisionUrls' instead"
959 );
7a3a2ebb
JB
960 this.convertDeprecatedTemplateKey(stationInfo, 'supervisionUrl', 'supervisionUrls');
961 stationInfo.wsOptions = stationInfo?.wsOptions ?? {};
962 if (!Utils.isEmptyArray(stationInfo.power)) {
963 stationInfo.power = stationInfo.power as number[];
964 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length);
cc6e8ab5 965 stationInfo.maximumPower =
7a3a2ebb
JB
966 stationInfo.powerUnit === PowerUnits.KILO_WATT
967 ? stationInfo.power[powerArrayRandomIndex] * 1000
968 : stationInfo.power[powerArrayRandomIndex];
5ad8570f 969 } else {
7a3a2ebb 970 stationInfo.power = stationInfo.power as number;
cc6e8ab5 971 stationInfo.maximumPower =
7a3a2ebb
JB
972 stationInfo.powerUnit === PowerUnits.KILO_WATT
973 ? stationInfo.power * 1000
974 : stationInfo.power;
5ad8570f 975 }
fd0c36fa
JB
976 delete stationInfo.power;
977 delete stationInfo.powerUnit;
2dcfe98e 978 stationInfo.chargingStationId = chargingStationId;
7a3a2ebb
JB
979 stationInfo.resetTime = stationInfo.resetTime
980 ? stationInfo.resetTime * 1000
e7aeea18 981 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
9ac86a7e 982 return stationInfo;
5ad8570f
JB
983 }
984
2484ac1e
JB
985 private getStationInfoFromFile(): ChargingStationInfo | null {
986 return this.getConfigurationFromFile()?.stationInfo ?? null;
987 }
988
989 private getStationInfo(): ChargingStationInfo {
990 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
7a3a2ebb 991 this.hashId = this.getHashId(stationInfoFromTemplate);
2484ac1e
JB
992 this.configurationFile = path.join(
993 path.resolve(__dirname, '../'),
994 'assets',
995 'configurations',
996 this.hashId + '.json'
997 );
998 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
999 if (stationInfoFromFile?.hash === stationInfoFromTemplate.hash) {
1000 return stationInfoFromFile;
1001 }
7a3a2ebb 1002 this.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile);
2484ac1e
JB
1003 return stationInfoFromTemplate;
1004 }
1005
1006 private saveStationInfo(): void {
1007 this.saveConfiguration(Section.stationInfo);
1008 }
1009
1f5df42a 1010 private getOcppVersion(): OCPPVersion {
c0560973
JB
1011 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
1012 }
1013
e8e865ea
JB
1014 private getOcppPersistentConfiguration(): boolean {
1015 return this.stationInfo.ocppPersistentConfiguration ?? true;
1016 }
1017
c0560973 1018 private handleUnsupportedVersion(version: OCPPVersion) {
e7aeea18 1019 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
2484ac1e 1020 this.templateFile
e7aeea18 1021 }`;
9f2e3130 1022 logger.error(errMsg);
c0560973
JB
1023 throw new Error(errMsg);
1024 }
1025
2484ac1e
JB
1026 private createBootNotificationRequest(stationInfo: ChargingStationInfo): BootNotificationRequest {
1027 return {
1028 chargePointModel: stationInfo.chargePointModel,
1029 chargePointVendor: stationInfo.chargePointVendor,
1030 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && {
1031 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber,
e7aeea18 1032 }),
2484ac1e
JB
1033 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && {
1034 chargePointSerialNumber: stationInfo.chargePointSerialNumber,
43bb4cd9 1035 }),
2484ac1e
JB
1036 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1037 firmwareVersion: stationInfo.firmwareVersion,
e7aeea18 1038 }),
2484ac1e
JB
1039 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1040 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
1041 ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && {
1042 meterSerialNumber: stationInfo.meterSerialNumber,
3f94cab5 1043 }),
2484ac1e
JB
1044 ...(!Utils.isUndefined(stationInfo.meterType) && {
1045 meterType: stationInfo.meterType,
3f94cab5 1046 }),
2e6f5966 1047 };
2484ac1e
JB
1048 }
1049
7a3a2ebb
JB
1050 private getHashId(stationInfo: ChargingStationInfo): string {
1051 const hashBootNotificationRequest = {
1052 chargePointModel: stationInfo.chargePointModel,
1053 chargePointVendor: stationInfo.chargePointVendor,
1054 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumberPrefix) && {
1055 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumberPrefix,
1056 }),
1057 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumberPrefix) && {
1058 chargePointSerialNumber: stationInfo.chargePointSerialNumberPrefix,
1059 }),
1060 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1061 firmwareVersion: stationInfo.firmwareVersion,
1062 }),
1063 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1064 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
0b7c34ba
JB
1065 ...(!Utils.isUndefined(stationInfo.meterSerialNumberPrefix) && {
1066 meterSerialNumber: stationInfo.meterSerialNumberPrefix,
7a3a2ebb
JB
1067 }),
1068 ...(!Utils.isUndefined(stationInfo.meterType) && {
1069 meterType: stationInfo.meterType,
1070 }),
1071 };
2484ac1e 1072 return crypto
3f94cab5 1073 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
7a3a2ebb 1074 .update(JSON.stringify(hashBootNotificationRequest) + stationInfo.chargingStationId)
3f94cab5 1075 .digest('hex');
2484ac1e
JB
1076 }
1077
1078 private initialize(): void {
1079 this.stationInfo = this.getStationInfo();
3f94cab5 1080 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
2484ac1e
JB
1081 this.bootNotificationRequest = this.createBootNotificationRequest(this.stationInfo);
1082 this.ocppConfiguration = this.getOcppConfiguration();
3f94cab5 1083 delete this.stationInfo.Configuration;
0642c3d2
JB
1084 this.wsConfiguredConnectionUrl = new URL(
1085 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
1086 );
0a60c33c 1087 // Build connectors if needed
c0560973 1088 const maxConnectors = this.getMaxNumberOfConnectors();
6ecb15e4 1089 if (maxConnectors <= 0) {
e7aeea18
JB
1090 logger.warn(
1091 `${this.logPrefix()} Charging station template ${
2484ac1e 1092 this.templateFile
e7aeea18
JB
1093 } with ${maxConnectors} connectors`
1094 );
7abfea5f 1095 }
c0560973 1096 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
7abfea5f 1097 if (templateMaxConnectors <= 0) {
e7aeea18
JB
1098 logger.warn(
1099 `${this.logPrefix()} Charging station template ${
2484ac1e 1100 this.templateFile
e7aeea18
JB
1101 } with no connector configuration`
1102 );
593cf3f9 1103 }
ad2f27c3 1104 if (!this.stationInfo.Connectors[0]) {
e7aeea18
JB
1105 logger.warn(
1106 `${this.logPrefix()} Charging station template ${
2484ac1e 1107 this.templateFile
e7aeea18
JB
1108 } with no connector Id 0 configuration`
1109 );
7abfea5f
JB
1110 }
1111 // Sanity check
e7aeea18
JB
1112 if (
1113 maxConnectors >
1114 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
1115 !this.stationInfo.randomConnectors
1116 ) {
1117 logger.warn(
1118 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
2484ac1e 1119 this.templateFile
e7aeea18
JB
1120 }, forcing random connector configurations affectation`
1121 );
ad2f27c3 1122 this.stationInfo.randomConnectors = true;
6ecb15e4 1123 }
e7aeea18 1124 const connectorsConfigHash = crypto
3f94cab5 1125 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
e7aeea18
JB
1126 .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
1127 .digest('hex');
1128 const connectorsConfigChanged =
1129 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
54544ef1 1130 if (this.connectors?.size === 0 || connectorsConfigChanged) {
e7aeea18 1131 connectorsConfigChanged && this.connectors.clear();
ad2f27c3 1132 this.connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 1133 // Add connector Id 0
6af9012e 1134 let lastConnector = '0';
ad2f27c3 1135 for (lastConnector in this.stationInfo.Connectors) {
734d790d 1136 const lastConnectorId = Utils.convertToInt(lastConnector);
e7aeea18
JB
1137 if (
1138 lastConnectorId === 0 &&
1139 this.getUseConnectorId0() &&
1140 this.stationInfo.Connectors[lastConnector]
1141 ) {
1142 this.connectors.set(
1143 lastConnectorId,
1144 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])
1145 );
734d790d
JB
1146 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1147 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1148 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
418106c8 1149 }
0a60c33c
JB
1150 }
1151 }
0a60c33c 1152 // Generate all connectors
e7aeea18
JB
1153 if (
1154 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0
1155 ) {
7abfea5f 1156 for (let index = 1; index <= maxConnectors; index++) {
e7aeea18
JB
1157 const randConnectorId = this.stationInfo.randomConnectors
1158 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1159 : index;
1160 this.connectors.set(
1161 index,
1162 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])
1163 );
734d790d
JB
1164 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1165 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1166 this.getConnectorStatus(index).chargingProfiles = [];
418106c8 1167 }
7abfea5f 1168 }
0a60c33c
JB
1169 }
1170 }
cc6e8ab5
JB
1171 this.stationInfo.maximumAmperage = this.getMaximumAmperage();
1172 this.saveStationInfo();
7a3a2ebb 1173 // Avoid duplication of connectors related information in RAM
ad2f27c3 1174 delete this.stationInfo.Connectors;
0a60c33c 1175 // Initialize transaction attributes on connectors
734d790d
JB
1176 for (const connectorId of this.connectors.keys()) {
1177 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
a2653482 1178 this.initializeConnectorStatus(connectorId);
0a60c33c
JB
1179 }
1180 }
2484ac1e
JB
1181 // OCPP configuration
1182 this.initializeOcppConfiguration();
0642c3d2
JB
1183 if (this.getEnableStatistics()) {
1184 this.performanceStatistics = PerformanceStatistics.getInstance(
1185 this.hashId,
1186 this.stationInfo.chargingStationId,
1187 this.wsConnectionUrl
1188 );
1189 }
1f5df42a 1190 switch (this.getOcppVersion()) {
c0560973 1191 case OCPPVersion.VERSION_16:
e7aeea18
JB
1192 this.ocppIncomingRequestService =
1193 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
1194 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
1195 this,
1196 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
1197 );
c0560973
JB
1198 break;
1199 default:
1f5df42a 1200 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
1201 break;
1202 }
47e22477
JB
1203 if (this.stationInfo.autoRegister) {
1204 this.bootNotificationResponse = {
1205 currentTime: new Date().toISOString(),
1206 interval: this.getHeartbeatInterval() / 1000,
e7aeea18 1207 status: RegistrationStatus.ACCEPTED,
47e22477
JB
1208 };
1209 }
147d0e0f 1210 this.stationInfo.powerDivider = this.getPowerDivider();
147d0e0f
JB
1211 }
1212
2484ac1e 1213 private initializeOcppConfiguration(): void {
e7aeea18
JB
1214 if (
1215 this.getSupervisionUrlOcppConfiguration() &&
a59737e3 1216 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
e7aeea18
JB
1217 ) {
1218 this.addConfigurationKey(
a59737e3 1219 this.getSupervisionUrlOcppKey(),
e7aeea18
JB
1220 this.getConfiguredSupervisionUrl().href,
1221 { reboot: true }
1222 );
e6895390
JB
1223 } else if (
1224 !this.getSupervisionUrlOcppConfiguration() &&
1225 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1226 ) {
1227 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
12fc74d6 1228 }
cc6e8ab5
JB
1229 if (
1230 this.stationInfo.amperageLimitationOcppKey &&
1231 !this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1232 ) {
1233 this.addConfigurationKey(
1234 this.stationInfo.amperageLimitationOcppKey,
1235 (this.stationInfo.maximumAmperage * this.getAmperageLimitationUnitDivider()).toString()
1236 );
1237 }
36f6a92e 1238 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
e7aeea18
JB
1239 this.addConfigurationKey(
1240 StandardParametersKey.SupportedFeatureProfiles,
b22787b4 1241 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
e7aeea18
JB
1242 );
1243 }
1244 this.addConfigurationKey(
1245 StandardParametersKey.NumberOfConnectors,
1246 this.getNumberOfConnectors().toString(),
a95873d8
JB
1247 { readonly: true },
1248 { overwrite: true }
e7aeea18 1249 );
c0560973 1250 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
e7aeea18
JB
1251 this.addConfigurationKey(
1252 StandardParametersKey.MeterValuesSampledData,
1253 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1254 );
7abfea5f 1255 }
7e1dc878
JB
1256 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
1257 const connectorPhaseRotation = [];
734d790d 1258 for (const connectorId of this.connectors.keys()) {
7e1dc878 1259 // AC/DC
734d790d
JB
1260 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1261 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1262 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1263 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
e7aeea18 1264 // AC
734d790d
JB
1265 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1266 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1267 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1268 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
7e1dc878
JB
1269 }
1270 }
e7aeea18
JB
1271 this.addConfigurationKey(
1272 StandardParametersKey.ConnectorPhaseRotation,
1273 connectorPhaseRotation.toString()
1274 );
7e1dc878 1275 }
36f6a92e
JB
1276 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
1277 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
1278 }
e7aeea18
JB
1279 if (
1280 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
68cb8b91 1281 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes(
b22787b4 1282 SupportedFeatureProfiles.LocalAuthListManagement
e7aeea18
JB
1283 )
1284 ) {
36f6a92e
JB
1285 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
1286 }
147d0e0f 1287 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
e7aeea18
JB
1288 this.addConfigurationKey(
1289 StandardParametersKey.ConnectionTimeOut,
1290 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1291 );
8bce55bf 1292 }
2484ac1e 1293 this.saveOcppConfiguration();
073bd098
JB
1294 }
1295
7f7b65ca 1296 private getConfigurationFromFile(): ChargingStationConfiguration | null {
073bd098 1297 let configuration: ChargingStationConfiguration = null;
2484ac1e 1298 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
073bd098 1299 try {
42a3eee7 1300 const measureId = `${FileType.ChargingStationConfiguration} read`;
0642c3d2 1301 const beginId = PerformanceStatistics.beginMeasure(measureId);
073bd098 1302 configuration = JSON.parse(
a95873d8 1303 fs.readFileSync(this.configurationFile, 'utf8')
073bd098 1304 ) as ChargingStationConfiguration;
42a3eee7 1305 PerformanceStatistics.endMeasure(measureId, beginId);
073bd098
JB
1306 } catch (error) {
1307 FileUtils.handleFileException(
1308 this.logPrefix(),
a95873d8 1309 FileType.ChargingStationConfiguration,
073bd098
JB
1310 this.configurationFile,
1311 error as NodeJS.ErrnoException
1312 );
1313 }
1314 }
1315 return configuration;
1316 }
1317
2484ac1e
JB
1318 private saveConfiguration(section?: Section): void {
1319 if (this.configurationFile) {
1320 try {
1321 const configurationData: ChargingStationConfiguration =
1322 this.getConfigurationFromFile() ?? {};
1323 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1324 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
073bd098 1325 }
2484ac1e
JB
1326 switch (section) {
1327 case Section.ocppConfiguration:
1328 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1329 break;
1330 case Section.stationInfo:
1331 configurationData.stationInfo = this.stationInfo;
1332 break;
1333 default:
1334 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1335 configurationData.stationInfo = this.stationInfo;
1336 break;
1337 }
42a3eee7
JB
1338 const measureId = `${FileType.ChargingStationConfiguration} write`;
1339 const beginId = PerformanceStatistics.beginMeasure(measureId);
2484ac1e
JB
1340 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1341 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1342 fs.closeSync(fileDescriptor);
42a3eee7 1343 PerformanceStatistics.endMeasure(measureId, beginId);
2484ac1e
JB
1344 } catch (error) {
1345 FileUtils.handleFileException(
1346 this.logPrefix(),
1347 FileType.ChargingStationConfiguration,
1348 this.configurationFile,
1349 error as NodeJS.ErrnoException
073bd098
JB
1350 );
1351 }
2484ac1e
JB
1352 } else {
1353 logger.error(
1354 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1355 );
073bd098
JB
1356 }
1357 }
1358
2484ac1e
JB
1359 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration {
1360 return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration);
1361 }
1362
1363 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1364 let configuration: ChargingStationConfiguration = null;
1365 if (this.getOcppPersistentConfiguration()) {
7a3a2ebb
JB
1366 const configurationFromFile = this.getConfigurationFromFile();
1367 configuration = configurationFromFile?.configurationKey && configurationFromFile;
073bd098 1368 }
2484ac1e 1369 configuration && delete configuration.stationInfo;
073bd098 1370 return configuration;
7dde0b73
JB
1371 }
1372
2484ac1e
JB
1373 private getOcppConfiguration(): ChargingStationOcppConfiguration {
1374 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1375 if (!ocppConfiguration) {
1376 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1377 }
1378 return ocppConfiguration;
1379 }
1380
1381 private saveOcppConfiguration(): void {
1382 if (this.getOcppPersistentConfiguration()) {
1383 this.saveConfiguration(Section.ocppConfiguration);
1384 }
1385 }
1386
c0560973 1387 private async onOpen(): Promise<void> {
5144f4d1
JB
1388 if (this.isWebSocketConnectionOpened()) {
1389 logger.info(
1390 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1391 );
94bb24d5 1392 if (!this.isRegistered()) {
5144f4d1
JB
1393 // Send BootNotification
1394 let registrationRetryCount = 0;
1395 do {
f7f98c68 1396 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
5144f4d1
JB
1397 BootNotificationRequest,
1398 BootNotificationResponse
1399 >(
f22266fd
JB
1400 RequestCommand.BOOT_NOTIFICATION,
1401 {
1402 chargePointModel: this.bootNotificationRequest.chargePointModel,
1403 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1404 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1405 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1406 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1407 iccid: this.bootNotificationRequest.iccid,
1408 imsi: this.bootNotificationRequest.imsi,
1409 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1410 meterType: this.bootNotificationRequest.meterType,
1411 },
1412 { skipBufferingOnError: true }
1413 );
94bb24d5 1414 if (!this.isRegistered()) {
5144f4d1
JB
1415 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1416 await Utils.sleep(
1417 this.bootNotificationResponse?.interval
1418 ? this.bootNotificationResponse.interval * 1000
1419 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1420 );
1421 }
1422 } while (
94bb24d5 1423 !this.isRegistered() &&
5144f4d1
JB
1424 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1425 this.getRegistrationMaxRetries() === -1)
1426 );
1427 }
94bb24d5
JB
1428 if (this.isRegistered()) {
1429 if (this.isInAcceptedState()) {
1430 await this.startMessageSequence();
1431 this.wsConnectionRestarted && this.flushMessageBuffer();
c0560973 1432 }
5144f4d1
JB
1433 } else {
1434 logger.error(
1435 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1436 );
caad9d6b 1437 }
94bb24d5 1438 this.stopped && (this.stopped = false);
5144f4d1
JB
1439 this.autoReconnectRetryCount = 0;
1440 this.wsConnectionRestarted = false;
2e6f5966 1441 } else {
5144f4d1
JB
1442 logger.warn(
1443 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
e7aeea18 1444 );
2e6f5966 1445 }
2e6f5966
JB
1446 }
1447
6c65a295 1448 private async onClose(code: number, reason: string): Promise<void> {
d09085e9 1449 switch (code) {
6c65a295
JB
1450 // Normal close
1451 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 1452 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18
JB
1453 logger.info(
1454 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1455 code
1456 )}' and reason '${reason}'`
1457 );
c0560973
JB
1458 this.autoReconnectRetryCount = 0;
1459 break;
6c65a295
JB
1460 // Abnormal close
1461 default:
e7aeea18
JB
1462 logger.error(
1463 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1464 code
1465 )}' and reason '${reason}'`
1466 );
d09085e9 1467 await this.reconnect(code);
c0560973
JB
1468 break;
1469 }
2e6f5966
JB
1470 }
1471
16b0d4e7 1472 private async onMessage(data: Data): Promise<void> {
b3ec7bc1
JB
1473 let messageType: number;
1474 let messageId: string;
1475 let commandName: IncomingRequestCommand;
1476 let commandPayload: JsonType;
1477 let errorType: ErrorType;
1478 let errorMessage: string;
1479 let errorDetails: JsonType;
1480 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
9239b49a 1481 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
32b02249 1482 let requestCommandName: RequestCommand | IncomingRequestCommand;
b3ec7bc1 1483 let requestPayload: JsonType;
32b02249 1484 let cachedRequest: CachedRequest;
c0560973
JB
1485 let errMsg: string;
1486 try {
b3ec7bc1 1487 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
47e22477 1488 if (Utils.isIterable(request)) {
9934652c 1489 [messageType, messageId] = request;
b3ec7bc1
JB
1490 // Check the type of message
1491 switch (messageType) {
1492 // Incoming Message
1493 case MessageType.CALL_MESSAGE:
9934652c 1494 [, , commandName, commandPayload] = request as IncomingRequest;
b3ec7bc1
JB
1495 if (this.getEnableStatistics()) {
1496 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1497 }
1498 logger.debug(
1499 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1500 request
1501 )}`
1502 );
1503 // Process the message
1504 await this.ocppIncomingRequestService.incomingRequestHandler(
1505 messageId,
1506 commandName,
1507 commandPayload
1508 );
1509 break;
1510 // Outcome Message
1511 case MessageType.CALL_RESULT_MESSAGE:
9934652c 1512 [, , commandPayload] = request as Response;
b3ec7bc1
JB
1513 // Respond
1514 cachedRequest = this.requests.get(messageId);
1515 if (Utils.isIterable(cachedRequest)) {
1516 [responseCallback, , requestCommandName, requestPayload] = cachedRequest;
1517 } else {
1518 throw new OCPPError(
1519 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1520 `Cached request for message id ${messageId} response is not iterable`,
1521 null,
1522 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1523 );
1524 }
1525 logger.debug(
7ec6c5c9
JB
1526 `${this.logPrefix()} << Command '${
1527 requestCommandName ?? ''
1528 }' received response payload: ${JSON.stringify(request)}`
b3ec7bc1
JB
1529 );
1530 if (!responseCallback) {
1531 // Error
1532 throw new OCPPError(
1533 ErrorType.INTERNAL_ERROR,
c2bc716f
JB
1534 `Response for unknown message id ${messageId}`,
1535 null,
1536 commandPayload
b3ec7bc1
JB
1537 );
1538 }
1539 responseCallback(commandPayload, requestPayload);
1540 break;
1541 // Error Message
1542 case MessageType.CALL_ERROR_MESSAGE:
9934652c 1543 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
b3ec7bc1
JB
1544 cachedRequest = this.requests.get(messageId);
1545 if (Utils.isIterable(cachedRequest)) {
1546 [, rejectCallback, requestCommandName] = cachedRequest;
1547 } else {
1548 throw new OCPPError(
1549 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1550 `Cached request for message id ${messageId} error response is not iterable`,
1551 null,
1552 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1553 );
1554 }
1555 logger.debug(
7ec6c5c9
JB
1556 `${this.logPrefix()} << Command '${
1557 requestCommandName ?? ''
1558 }' received error payload: ${JSON.stringify(request)}`
b3ec7bc1
JB
1559 );
1560 if (!rejectCallback) {
1561 // Error
1562 throw new OCPPError(
1563 ErrorType.INTERNAL_ERROR,
c2bc716f
JB
1564 `Error response for unknown message id ${messageId}`,
1565 null,
1566 { errorType, errorMessage, errorDetails }
b3ec7bc1
JB
1567 );
1568 }
1569 rejectCallback(
1570 new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)
1571 );
1572 break;
1573 // Error
1574 default:
1575 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1576 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1577 logger.error(errMsg);
1578 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1579 }
47e22477 1580 } else {
ac54a9bb
JB
1581 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, {
1582 payload: request,
1583 });
47e22477 1584 }
c0560973
JB
1585 } catch (error) {
1586 // Log
e7aeea18
JB
1587 logger.error(
1588 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1589 this.logPrefix(),
1590 data.toString(),
1591 this.requests.get(messageId),
1592 error
1593 );
c0560973 1594 // Send error
e7aeea18 1595 messageType === MessageType.CALL_MESSAGE &&
b3ec7bc1
JB
1596 (await this.ocppRequestService.sendError(
1597 messageId,
1598 error as OCPPError,
ac54a9bb 1599 Utils.isString(commandName) ? commandName : requestCommandName ?? null
b3ec7bc1 1600 ));
c0560973 1601 }
2328be1e
JB
1602 }
1603
c0560973 1604 private onPing(): void {
9f2e3130 1605 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
c0560973
JB
1606 }
1607
1608 private onPong(): void {
9f2e3130 1609 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
c0560973
JB
1610 }
1611
9534e74e 1612 private onError(error: WSError): void {
9f2e3130 1613 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
c0560973
JB
1614 }
1615
6e0964c8 1616 private getAuthorizationFile(): string | undefined {
e7aeea18
JB
1617 return (
1618 this.stationInfo.authorizationFile &&
1619 path.join(
1620 path.resolve(__dirname, '../'),
1621 'assets',
1622 path.basename(this.stationInfo.authorizationFile)
1623 )
1624 );
c0560973
JB
1625 }
1626
1627 private getAuthorizedTags(): string[] {
1628 let authorizedTags: string[] = [];
1629 const authorizationFile = this.getAuthorizationFile();
1630 if (authorizationFile) {
1631 try {
1632 // Load authorization file
a95873d8 1633 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
c0560973 1634 } catch (error) {
e7aeea18
JB
1635 FileUtils.handleFileException(
1636 this.logPrefix(),
a95873d8 1637 FileType.Authorization,
e7aeea18
JB
1638 authorizationFile,
1639 error as NodeJS.ErrnoException
1640 );
c0560973
JB
1641 }
1642 } else {
e7aeea18 1643 logger.info(
2484ac1e 1644 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
e7aeea18 1645 );
8c4da341 1646 }
c0560973
JB
1647 return authorizedTags;
1648 }
1649
6e0964c8 1650 private getUseConnectorId0(): boolean | undefined {
e7aeea18
JB
1651 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1652 ? this.stationInfo.useConnectorId0
1653 : true;
8bce55bf
JB
1654 }
1655
c0560973 1656 private getNumberOfRunningTransactions(): number {
6ecb15e4 1657 let trxCount = 0;
734d790d
JB
1658 for (const connectorId of this.connectors.keys()) {
1659 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
6ecb15e4
JB
1660 trxCount++;
1661 }
1662 }
1663 return trxCount;
1664 }
1665
1f761b9a 1666 // 0 for disabling
6e0964c8 1667 private getConnectionTimeout(): number | undefined {
291cb255 1668 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
e7aeea18
JB
1669 return (
1670 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1671 Constants.DEFAULT_CONNECTION_TIMEOUT
1672 );
291cb255 1673 }
291cb255 1674 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
1675 }
1676
1f761b9a 1677 // -1 for unlimited, 0 for disabling
6e0964c8 1678 private getAutoReconnectMaxRetries(): number | undefined {
ad2f27c3
JB
1679 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1680 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
1681 }
1682 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1683 return Configuration.getAutoReconnectMaxRetries();
1684 }
1685 return -1;
1686 }
1687
ec977daf 1688 // 0 for disabling
6e0964c8 1689 private getRegistrationMaxRetries(): number | undefined {
ad2f27c3
JB
1690 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1691 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
1692 }
1693 return -1;
1694 }
1695
c0560973
JB
1696 private getPowerDivider(): number {
1697 let powerDivider = this.getNumberOfConnectors();
ad2f27c3 1698 if (this.stationInfo.powerSharedByConnectors) {
c0560973 1699 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
1700 }
1701 return powerDivider;
1702 }
1703
c0560973 1704 private getTemplateMaxNumberOfConnectors(): number {
ad2f27c3 1705 return Object.keys(this.stationInfo.Connectors).length;
7abfea5f
JB
1706 }
1707
c0560973 1708 private getMaxNumberOfConnectors(): number {
e58068fd 1709 let maxConnectors: number;
ad2f27c3
JB
1710 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1711 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
6ecb15e4 1712 // Distribute evenly the number of connectors
ad2f27c3
JB
1713 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1714 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1715 maxConnectors = this.stationInfo.numberOfConnectors as number;
488fd3a7 1716 } else {
e7aeea18
JB
1717 maxConnectors = this.stationInfo.Connectors[0]
1718 ? this.getTemplateMaxNumberOfConnectors() - 1
1719 : this.getTemplateMaxNumberOfConnectors();
5ad8570f
JB
1720 }
1721 return maxConnectors;
2e6f5966
JB
1722 }
1723
0642c3d2
JB
1724 private getMaximumPower(): number {
1725 return (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower;
1726 }
1727
cc6e8ab5 1728 private getMaximumAmperage(): number | undefined {
0642c3d2 1729 const maximumPower = this.getMaximumPower();
cc6e8ab5
JB
1730 switch (this.getCurrentOutType()) {
1731 case CurrentType.AC:
1732 return ACElectricUtils.amperagePerPhaseFromPower(
1733 this.getNumberOfPhases(),
ad8537a7 1734 maximumPower / this.getNumberOfConnectors(),
cc6e8ab5
JB
1735 this.getVoltageOut()
1736 );
1737 case CurrentType.DC:
ad8537a7 1738 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut());
cc6e8ab5
JB
1739 }
1740 }
1741
1742 private getAmperageLimitationUnitDivider(): number {
1743 let unitDivider = 1;
1744 switch (this.stationInfo.amperageLimitationUnit) {
1745 case AmpereUnits.DECI_AMPERE:
1746 unitDivider = 10;
1747 break;
1748 case AmpereUnits.CENTI_AMPERE:
1749 unitDivider = 100;
1750 break;
1751 case AmpereUnits.MILLI_AMPERE:
1752 unitDivider = 1000;
1753 break;
1754 }
1755 return unitDivider;
1756 }
1757
1758 private getAmperageLimitation(): number | undefined {
1759 if (
1760 this.stationInfo.amperageLimitationOcppKey &&
1761 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1762 ) {
1763 return (
1764 Utils.convertToInt(
1765 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey).value
1766 ) / this.getAmperageLimitationUnitDivider()
1767 );
1768 }
1769 }
1770
c0560973 1771 private async startMessageSequence(): Promise<void> {
6114e6f1 1772 if (this.stationInfo.autoRegister) {
f7f98c68 1773 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1774 BootNotificationRequest,
1775 BootNotificationResponse
1776 >(
6a8b180d
JB
1777 RequestCommand.BOOT_NOTIFICATION,
1778 {
1779 chargePointModel: this.bootNotificationRequest.chargePointModel,
1780 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1781 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1782 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
29d1e2e7
JB
1783 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1784 iccid: this.bootNotificationRequest.iccid,
1785 imsi: this.bootNotificationRequest.imsi,
1786 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1787 meterType: this.bootNotificationRequest.meterType,
6a8b180d
JB
1788 },
1789 { skipBufferingOnError: true }
e7aeea18 1790 );
6114e6f1 1791 }
136c90ba 1792 // Start WebSocket ping
c0560973 1793 this.startWebSocketPing();
5ad8570f 1794 // Start heartbeat
c0560973 1795 this.startHeartbeat();
0a60c33c 1796 // Initialize connectors status
734d790d
JB
1797 for (const connectorId of this.connectors.keys()) {
1798 if (connectorId === 0) {
593cf3f9 1799 continue;
e7aeea18
JB
1800 } else if (
1801 !this.stopped &&
1802 !this.getConnectorStatus(connectorId)?.status &&
1803 this.getConnectorStatus(connectorId)?.bootStatus
1804 ) {
136c90ba 1805 // Send status in template at startup
f7f98c68 1806 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1807 StatusNotificationRequest,
1808 StatusNotificationResponse
1809 >(RequestCommand.STATUS_NOTIFICATION, {
1810 connectorId,
1811 status: this.getConnectorStatus(connectorId).bootStatus,
1812 errorCode: ChargePointErrorCode.NO_ERROR,
1813 });
e7aeea18
JB
1814 this.getConnectorStatus(connectorId).status =
1815 this.getConnectorStatus(connectorId).bootStatus;
1816 } else if (
1817 this.stopped &&
1818 this.getConnectorStatus(connectorId)?.status &&
1819 this.getConnectorStatus(connectorId)?.bootStatus
1820 ) {
136c90ba 1821 // Send status in template after reset
f7f98c68 1822 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1823 StatusNotificationRequest,
1824 StatusNotificationResponse
1825 >(RequestCommand.STATUS_NOTIFICATION, {
1826 connectorId,
1827 status: this.getConnectorStatus(connectorId).bootStatus,
1828 errorCode: ChargePointErrorCode.NO_ERROR,
1829 });
e7aeea18
JB
1830 this.getConnectorStatus(connectorId).status =
1831 this.getConnectorStatus(connectorId).bootStatus;
734d790d 1832 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
136c90ba 1833 // Send previous status at template reload
f7f98c68 1834 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1835 StatusNotificationRequest,
1836 StatusNotificationResponse
1837 >(RequestCommand.STATUS_NOTIFICATION, {
1838 connectorId,
1839 status: this.getConnectorStatus(connectorId).status,
1840 errorCode: ChargePointErrorCode.NO_ERROR,
1841 });
5ad8570f 1842 } else {
136c90ba 1843 // Send default status
f7f98c68 1844 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1845 StatusNotificationRequest,
1846 StatusNotificationResponse
1847 >(RequestCommand.STATUS_NOTIFICATION, {
1848 connectorId,
1849 status: ChargePointStatus.AVAILABLE,
1850 errorCode: ChargePointErrorCode.NO_ERROR,
1851 });
734d790d 1852 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
1853 }
1854 }
0a60c33c 1855 // Start the ATG
dd119a6b 1856 this.startAutomaticTransactionGenerator();
dd119a6b
JB
1857 }
1858
1859 private startAutomaticTransactionGenerator() {
ad2f27c3 1860 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
265e4266 1861 if (!this.automaticTransactionGenerator) {
73b9adec 1862 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
5ad8570f 1863 }
265e4266
JB
1864 if (!this.automaticTransactionGenerator.started) {
1865 this.automaticTransactionGenerator.start();
5ad8570f
JB
1866 }
1867 }
5ad8570f
JB
1868 }
1869
e7aeea18
JB
1870 private async stopMessageSequence(
1871 reason: StopTransactionReason = StopTransactionReason.NONE
1872 ): Promise<void> {
136c90ba 1873 // Stop WebSocket ping
c0560973 1874 this.stopWebSocketPing();
79411696 1875 // Stop heartbeat
c0560973 1876 this.stopHeartbeat();
79411696 1877 // Stop the ATG
e7aeea18
JB
1878 if (
1879 this.stationInfo.AutomaticTransactionGenerator.enable &&
1880 this.automaticTransactionGenerator?.started
1881 ) {
0045cef5 1882 this.automaticTransactionGenerator.stop();
79411696 1883 } else {
734d790d
JB
1884 for (const connectorId of this.connectors.keys()) {
1885 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1886 const transactionId = this.getConnectorStatus(connectorId).transactionId;
68c993d5
JB
1887 if (
1888 this.getBeginEndMeterValues() &&
1889 this.getOcppStrictCompliance() &&
1890 !this.getOutOfOrderEndMeterValues()
1891 ) {
1892 // FIXME: Implement OCPP version agnostic helpers
1893 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1894 this,
1895 connectorId,
1896 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1897 );
f7f98c68
JB
1898 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
1899 RequestCommand.METER_VALUES,
1900 {
1901 connectorId,
1902 transactionId,
1903 meterValue: transactionEndMeterValue,
1904 }
1905 );
ef6fa3fb 1906 }
f7f98c68 1907 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1908 StopTransactionRequest,
1909 StopTransactionResponse
1910 >(RequestCommand.STOP_TRANSACTION, {
1911 transactionId,
1912 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1913 idTag: this.getTransactionIdTag(transactionId),
1914 reason,
1915 });
79411696
JB
1916 }
1917 }
1918 }
1919 }
1920
c0560973 1921 private startWebSocketPing(): void {
e7aeea18
JB
1922 const webSocketPingInterval: number = this.getConfigurationKey(
1923 StandardParametersKey.WebSocketPingInterval
1924 )
1925 ? Utils.convertToInt(
1926 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
1927 )
9cd3dfb0 1928 : 0;
ad2f27c3
JB
1929 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1930 this.webSocketPingSetInterval = setInterval(() => {
d5bff457 1931 if (this.isWebSocketConnectionOpened()) {
e7aeea18
JB
1932 this.wsConnection.ping((): void => {
1933 /* This is intentional */
1934 });
136c90ba
JB
1935 }
1936 }, webSocketPingInterval * 1000);
e7aeea18
JB
1937 logger.info(
1938 this.logPrefix() +
1939 ' WebSocket ping started every ' +
1940 Utils.formatDurationSeconds(webSocketPingInterval)
1941 );
ad2f27c3 1942 } else if (this.webSocketPingSetInterval) {
e7aeea18
JB
1943 logger.info(
1944 this.logPrefix() +
1945 ' WebSocket ping every ' +
1946 Utils.formatDurationSeconds(webSocketPingInterval) +
1947 ' already started'
1948 );
136c90ba 1949 } else {
e7aeea18
JB
1950 logger.error(
1951 `${this.logPrefix()} WebSocket ping interval set to ${
1952 webSocketPingInterval
1953 ? Utils.formatDurationSeconds(webSocketPingInterval)
1954 : webSocketPingInterval
1955 }, not starting the WebSocket ping`
1956 );
136c90ba
JB
1957 }
1958 }
1959
c0560973 1960 private stopWebSocketPing(): void {
ad2f27c3
JB
1961 if (this.webSocketPingSetInterval) {
1962 clearInterval(this.webSocketPingSetInterval);
136c90ba
JB
1963 }
1964 }
1965
e7aeea18
JB
1966 private warnDeprecatedTemplateKey(
1967 template: ChargingStationTemplate,
1968 key: string,
1969 chargingStationId: string,
1970 logMsgToAppend = ''
1971 ): void {
2dcfe98e 1972 if (!Utils.isUndefined(template[key])) {
e7aeea18
JB
1973 const logPrefixStr = ` ${chargingStationId} |`;
1974 logger.warn(
1975 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
2484ac1e 1976 this.templateFile
e7aeea18
JB
1977 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1978 );
2dcfe98e
JB
1979 }
1980 }
1981
e7aeea18
JB
1982 private convertDeprecatedTemplateKey(
1983 template: ChargingStationTemplate,
1984 deprecatedKey: string,
1985 key: string
1986 ): void {
2dcfe98e 1987 if (!Utils.isUndefined(template[deprecatedKey])) {
c0f4be74 1988 template[key] = template[deprecatedKey] as unknown;
2dcfe98e
JB
1989 delete template[deprecatedKey];
1990 }
1991 }
1992
1f5df42a 1993 private getConfiguredSupervisionUrl(): URL {
e7aeea18
JB
1994 const supervisionUrls = Utils.cloneObject<string | string[]>(
1995 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1996 );
c0560973 1997 if (!Utils.isEmptyArray(supervisionUrls)) {
2dcfe98e
JB
1998 let urlIndex = 0;
1999 switch (Configuration.getSupervisionUrlDistribution()) {
2000 case SupervisionUrlDistribution.ROUND_ROBIN:
2001 urlIndex = (this.index - 1) % supervisionUrls.length;
2002 break;
2003 case SupervisionUrlDistribution.RANDOM:
2004 // Get a random url
2005 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
2006 break;
2007 case SupervisionUrlDistribution.SEQUENTIAL:
2008 if (this.index <= supervisionUrls.length) {
2009 urlIndex = this.index - 1;
2010 } else {
e7aeea18
JB
2011 logger.warn(
2012 `${this.logPrefix()} No more configured supervision urls available, using the first one`
2013 );
2dcfe98e
JB
2014 }
2015 break;
2016 default:
e7aeea18
JB
2017 logger.error(
2018 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2019 SupervisionUrlDistribution.ROUND_ROBIN
2020 }`
2021 );
2dcfe98e
JB
2022 urlIndex = (this.index - 1) % supervisionUrls.length;
2023 break;
c0560973 2024 }
2dcfe98e 2025 return new URL(supervisionUrls[urlIndex]);
c0560973 2026 }
57939a9d 2027 return new URL(supervisionUrls as string);
136c90ba
JB
2028 }
2029
6e0964c8 2030 private getHeartbeatInterval(): number | undefined {
c0560973
JB
2031 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
2032 if (HeartbeatInterval) {
2033 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
2034 }
2035 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
2036 if (HeartBeatInterval) {
2037 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c 2038 }
e7aeea18
JB
2039 !this.stationInfo.autoRegister &&
2040 logger.warn(
2041 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2042 Constants.DEFAULT_HEARTBEAT_INTERVAL
2043 }`
2044 );
47e22477 2045 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
0a60c33c
JB
2046 }
2047
c0560973 2048 private stopHeartbeat(): void {
ad2f27c3
JB
2049 if (this.heartbeatSetInterval) {
2050 clearInterval(this.heartbeatSetInterval);
7dde0b73 2051 }
5ad8570f
JB
2052 }
2053
e7aeea18 2054 private openWSConnection(
2484ac1e 2055 options: WsOptions = this.stationInfo.wsOptions,
e7aeea18
JB
2056 forceCloseOpened = false
2057 ): void {
37486900 2058 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
e7aeea18
JB
2059 if (
2060 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
2061 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
2062 ) {
15042c5f
JB
2063 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2064 }
d5bff457 2065 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
c0560973
JB
2066 this.wsConnection.close();
2067 }
88184022 2068 let protocol: string;
1f5df42a 2069 switch (this.getOcppVersion()) {
c0560973
JB
2070 case OCPPVersion.VERSION_16:
2071 protocol = 'ocpp' + OCPPVersion.VERSION_16;
2072 break;
2073 default:
1f5df42a 2074 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
2075 break;
2076 }
2077 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
e7aeea18
JB
2078 logger.info(
2079 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
2080 );
136c90ba
JB
2081 }
2082
dd119a6b 2083 private stopMeterValues(connectorId: number) {
734d790d
JB
2084 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
2085 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
dd119a6b
JB
2086 }
2087 }
2088
6e0964c8 2089 private getReconnectExponentialDelay(): boolean | undefined {
e7aeea18
JB
2090 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
2091 ? this.stationInfo.reconnectExponentialDelay
2092 : false;
5ad8570f
JB
2093 }
2094
d09085e9 2095 private async reconnect(code: number): Promise<void> {
7874b0b1
JB
2096 // Stop WebSocket ping
2097 this.stopWebSocketPing();
136c90ba 2098 // Stop heartbeat
c0560973 2099 this.stopHeartbeat();
5ad8570f 2100 // Stop the ATG if needed
e7aeea18
JB
2101 if (
2102 this.stationInfo.AutomaticTransactionGenerator.enable &&
ad2f27c3 2103 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
e7aeea18
JB
2104 this.automaticTransactionGenerator?.started
2105 ) {
0045cef5 2106 this.automaticTransactionGenerator.stop();
ad2f27c3 2107 }
e7aeea18
JB
2108 if (
2109 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
2110 this.getAutoReconnectMaxRetries() === -1
2111 ) {
ad2f27c3 2112 this.autoReconnectRetryCount++;
e7aeea18
JB
2113 const reconnectDelay = this.getReconnectExponentialDelay()
2114 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
2115 : this.getConnectionTimeout() * 1000;
2116 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
2117 logger.error(
2118 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2119 reconnectDelay,
2120 2
2121 )}ms, timeout ${reconnectTimeout}ms`
2122 );
032d6efc 2123 await Utils.sleep(reconnectDelay);
e7aeea18
JB
2124 logger.error(
2125 this.logPrefix() +
2126 ' WebSocket: reconnecting try #' +
2127 this.autoReconnectRetryCount.toString()
2128 );
2129 this.openWSConnection(
2130 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
2131 true
2132 );
265e4266 2133 this.wsConnectionRestarted = true;
c0560973 2134 } else if (this.getAutoReconnectMaxRetries() !== -1) {
e7aeea18 2135 logger.error(
71a77ac2 2136 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
e7aeea18
JB
2137 this.autoReconnectRetryCount
2138 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2139 );
5ad8570f
JB
2140 }
2141 }
2142
a2653482
JB
2143 private initializeConnectorStatus(connectorId: number): void {
2144 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2145 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2146 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d
JB
2147 this.getConnectorStatus(connectorId).transactionStarted = false;
2148 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2149 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
0a60c33c 2150 }
7dde0b73 2151}