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