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