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