build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
b4d34251 2
43ee4373 3import crypto from 'node:crypto';
130783a7
JB
4import fs from 'node:fs';
5import path from 'node:path';
6import { URL } from 'node:url';
01f4001e 7import { parentPort } from 'node:worker_threads';
8114d10e 8
5d280aae 9import merge from 'just-merge';
ef7d8c21 10import WebSocket, { type RawData } from 'ws';
8114d10e 11
4c3c0d59 12import { AutomaticTransactionGenerator } from './AutomaticTransactionGenerator';
7671fa0b 13import { ChargingStationWorkerBroadcastChannel } from './broadcast-channel/ChargingStationWorkerBroadcastChannel';
4c3c0d59
JB
14import { ChargingStationConfigurationUtils } from './ChargingStationConfigurationUtils';
15import { ChargingStationUtils } from './ChargingStationUtils';
4c3c0d59 16import { IdTagsCache } from './IdTagsCache';
368a6eda 17import {
4c3c0d59 18 OCPP16IncomingRequestService,
368a6eda 19 OCPP16RequestService,
4c3c0d59 20 OCPP16ResponseService,
368a6eda
JB
21 OCPP16ServiceUtils,
22 OCPP20IncomingRequestService,
23 OCPP20RequestService,
4c3c0d59 24 OCPP20ResponseService,
368a6eda
JB
25 type OCPPIncomingRequestService,
26 type OCPPRequestService,
4c3c0d59 27 OCPPServiceUtils,
368a6eda 28} from './ocpp';
4c3c0d59 29import { SharedLRUCache } from './SharedLRUCache';
268a74bb 30import { BaseError, OCPPError } from '../exception';
b84bca85 31import { PerformanceStatistics } from '../performance';
e7aeea18 32import {
268a74bb 33 type AutomaticTransactionGeneratorConfiguration,
e7aeea18 34 AvailabilityType,
e0b0ee21 35 type BootNotificationRequest,
268a74bb 36 type BootNotificationResponse,
e0b0ee21 37 type CachedRequest,
268a74bb
JB
38 type ChargingStationConfiguration,
39 type ChargingStationInfo,
40 type ChargingStationOcppConfiguration,
41 type ChargingStationTemplate,
c8aafe0d 42 type ConnectorStatus,
268a74bb
JB
43 ConnectorStatusEnum,
44 CurrentType,
e0b0ee21 45 type ErrorCallback,
268a74bb
JB
46 type ErrorResponse,
47 ErrorType,
2585c6e9 48 type EvseStatus,
52952bf8 49 type EvseStatusConfiguration,
268a74bb 50 FileType,
c9a4f9ea
JB
51 FirmwareStatus,
52 type FirmwareStatusNotificationRequest,
268a74bb
JB
53 type FirmwareStatusNotificationResponse,
54 type FirmwareUpgrade,
e0b0ee21 55 type HeartbeatRequest,
268a74bb 56 type HeartbeatResponse,
e0b0ee21 57 type IncomingRequest,
268a74bb
JB
58 type IncomingRequestCommand,
59 type JsonType,
60 MessageType,
61 type MeterValue,
62 MeterValueMeasurand,
e0b0ee21 63 type MeterValuesRequest,
268a74bb
JB
64 type MeterValuesResponse,
65 OCPPVersion,
8ca6874c 66 type OutgoingRequest,
268a74bb
JB
67 PowerUnits,
68 RegistrationStatusEnumType,
e7aeea18 69 RequestCommand,
268a74bb 70 type Response,
268a74bb 71 StandardParametersKey,
5ced7e80 72 type Status,
e0b0ee21 73 type StatusNotificationRequest,
e0b0ee21 74 type StatusNotificationResponse,
ef6fa3fb 75 StopTransactionReason,
e0b0ee21
JB
76 type StopTransactionRequest,
77 type StopTransactionResponse,
268a74bb
JB
78 SupervisionUrlDistribution,
79 SupportedFeatureProfiles,
6dad8e21 80 VendorParametersKey,
268a74bb
JB
81 type WSError,
82 WebSocketCloseEventStatusCode,
83 type WsOptions,
84} from '../types';
60a74391
JB
85import {
86 ACElectricUtils,
1227a6f1
JB
87 AsyncLock,
88 AsyncLockType,
60a74391
JB
89 Configuration,
90 Constants,
91 DCElectricUtils,
51022aa0 92 ErrorUtils,
60a74391 93 FileUtils,
7671fa0b 94 MessageChannelUtils,
60a74391 95 Utils,
179ed367
JB
96 buildChargingStationAutomaticTransactionGeneratorConfiguration,
97 buildConnectorsStatus,
98 buildEvsesStatus,
60a74391
JB
99 logger,
100} from '../utils';
3f40bc9c 101
268a74bb 102export class ChargingStation {
c72f6634 103 public readonly index: number;
2484ac1e 104 public readonly templateFile: string;
6e0964c8 105 public stationInfo!: ChargingStationInfo;
452a82ca 106 public started: boolean;
cbf9b878 107 public starting: boolean;
f911a4af 108 public idTagsCache: IdTagsCache;
551e477c
JB
109 public automaticTransactionGenerator!: AutomaticTransactionGenerator | undefined;
110 public ocppConfiguration!: ChargingStationOcppConfiguration | undefined;
72092cfc 111 public wsConnection!: WebSocket | null;
8df5ae48 112 public readonly connectors: Map<number, ConnectorStatus>;
2585c6e9 113 public readonly evses: Map<number, EvseStatus>;
9e23580d 114 public readonly requests: Map<string, CachedRequest>;
551e477c 115 public performanceStatistics!: PerformanceStatistics | undefined;
6e0964c8 116 public heartbeatSetInterval!: NodeJS.Timeout;
6e0964c8 117 public ocppRequestService!: OCPPRequestService;
0a03f36c 118 public bootNotificationRequest!: BootNotificationRequest;
1895299d 119 public bootNotificationResponse!: BootNotificationResponse | undefined;
fa7bccf4 120 public powerDivider!: number;
950b1349 121 private stopping: boolean;
073bd098 122 private configurationFile!: string;
7c72977b 123 private configurationFileHash!: string;
6e0964c8 124 private connectorsConfigurationHash!: string;
2585c6e9 125 private evsesConfigurationHash!: string;
a472cf2b 126 private ocppIncomingRequestService!: OCPPIncomingRequestService;
8e242273 127 private readonly messageBuffer: Set<string>;
fa7bccf4 128 private configuredSupervisionUrl!: URL;
265e4266 129 private wsConnectionRestarted: boolean;
ad2f27c3 130 private autoReconnectRetryCount: number;
72092cfc 131 private templateFileWatcher!: fs.FSWatcher | undefined;
cda5d0fb 132 private templateFileHash!: string;
57adbebc 133 private readonly sharedLRUCache: SharedLRUCache;
6e0964c8 134 private webSocketPingSetInterval!: NodeJS.Timeout;
89b7a234 135 private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel;
6af9012e 136
2484ac1e 137 constructor(index: number, templateFile: string) {
aa428a31 138 this.started = false;
950b1349
JB
139 this.starting = false;
140 this.stopping = false;
aa428a31
JB
141 this.wsConnectionRestarted = false;
142 this.autoReconnectRetryCount = 0;
ad2f27c3 143 this.index = index;
2484ac1e 144 this.templateFile = templateFile;
9f2e3130 145 this.connectors = new Map<number, ConnectorStatus>();
2585c6e9 146 this.evses = new Map<number, EvseStatus>();
32b02249 147 this.requests = new Map<string, CachedRequest>();
8e242273 148 this.messageBuffer = new Set<string>();
b44b779a 149 this.sharedLRUCache = SharedLRUCache.getInstance();
f911a4af 150 this.idTagsCache = IdTagsCache.getInstance();
89b7a234 151 this.chargingStationWorkerBroadcastChannel = new ChargingStationWorkerBroadcastChannel(this);
32de5a57 152
9f2e3130 153 this.initialize();
c0560973
JB
154 }
155
a14022a2
JB
156 public get hasEvses(): boolean {
157 return this.connectors.size === 0 && this.evses.size > 0;
158 }
159
25f5a959 160 private get wsConnectionUrl(): URL {
fa7bccf4 161 return new URL(
44eb6026 162 `${
269de583 163 this.getSupervisionUrlOcppConfiguration() &&
d5c3df49
JB
164 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
165 Utils.isNotEmptyString(
166 ChargingStationConfigurationUtils.getConfigurationKey(
167 this,
168 this.getSupervisionUrlOcppKey()
169 )?.value
170 )
44eb6026
JB
171 ? ChargingStationConfigurationUtils.getConfigurationKey(
172 this,
173 this.getSupervisionUrlOcppKey()
d5c3df49 174 ).value
44eb6026
JB
175 : this.configuredSupervisionUrl.href
176 }/${this.stationInfo.chargingStationId}`
fa7bccf4 177 );
12fc74d6
JB
178 }
179
8b7072dc 180 public logPrefix = (): string => {
ccb1d6e9
JB
181 return Utils.logPrefix(
182 ` ${
e302df1d
JB
183 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId)
184 ? this?.stationInfo?.chargingStationId
185 : ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())) ??
186 'Error at building log prefix'
ccb1d6e9
JB
187 } |`
188 );
8b7072dc 189 };
c0560973 190
f911a4af 191 public hasIdTags(): boolean {
453bea86
JB
192 return Utils.isNotEmptyArray(
193 this.idTagsCache.getIdTags(ChargingStationUtils.getIdTagsFile(this.stationInfo))
194 );
c0560973
JB
195 }
196
ad774cec
JB
197 public getEnableStatistics(): boolean {
198 return this.stationInfo.enableStatistics ?? false;
c0560973
JB
199 }
200
ad774cec 201 public getMustAuthorizeAtRemoteStart(): boolean {
03ebf4c1 202 return this.stationInfo.mustAuthorizeAtRemoteStart ?? true;
a7fc8211
JB
203 }
204
ad774cec 205 public getPayloadSchemaValidation(): boolean {
e3018bc4
JB
206 return this.stationInfo.payloadSchemaValidation ?? true;
207 }
208
fa7bccf4
JB
209 public getNumberOfPhases(stationInfo?: ChargingStationInfo): number | undefined {
210 const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
211 switch (this.getCurrentOutType(stationInfo)) {
4c2b4904 212 case CurrentType.AC:
fa7bccf4
JB
213 return !Utils.isUndefined(localStationInfo.numberOfPhases)
214 ? localStationInfo.numberOfPhases
e7aeea18 215 : 3;
4c2b4904 216 case CurrentType.DC:
c0560973
JB
217 return 0;
218 }
219 }
220
d5bff457 221 public isWebSocketConnectionOpened(): boolean {
0d8140bd 222 return this?.wsConnection?.readyState === WebSocket.OPEN;
c0560973
JB
223 }
224
1895299d 225 public getRegistrationStatus(): RegistrationStatusEnumType | undefined {
672fed6e
JB
226 return this?.bootNotificationResponse?.status;
227 }
228
f7c2994d 229 public inUnknownState(): boolean {
73c4266d
JB
230 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
231 }
232
f7c2994d 233 public inPendingState(): boolean {
d270cc87 234 return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.PENDING;
16cd35ad
JB
235 }
236
f7c2994d 237 public inAcceptedState(): boolean {
d270cc87 238 return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.ACCEPTED;
c0560973
JB
239 }
240
f7c2994d 241 public inRejectedState(): boolean {
d270cc87 242 return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.REJECTED;
16cd35ad
JB
243 }
244
245 public isRegistered(): boolean {
ed6cfcff 246 return (
f7c2994d
JB
247 this.inUnknownState() === false &&
248 (this.inAcceptedState() === true || this.inPendingState() === true)
ed6cfcff 249 );
16cd35ad
JB
250 }
251
c0560973 252 public isChargingStationAvailable(): boolean {
0d6f335f 253 return this.getConnectorStatus(0)?.availability === AvailabilityType.Operative;
c0560973
JB
254 }
255
a14022a2
JB
256 public hasConnector(connectorId: number): boolean {
257 if (this.hasEvses) {
258 for (const evseStatus of this.evses.values()) {
259 if (evseStatus.connectors.has(connectorId)) {
260 return true;
261 }
262 }
263 return false;
264 }
265 return this.connectors.has(connectorId);
266 }
267
28e78158
JB
268 public isConnectorAvailable(connectorId: number): boolean {
269 return (
270 connectorId > 0 &&
271 this.getConnectorStatus(connectorId)?.availability === AvailabilityType.Operative
272 );
c0560973
JB
273 }
274
54544ef1 275 public getNumberOfConnectors(): number {
28e78158 276 if (this.hasEvses) {
cda5d0fb
JB
277 if (this.evses.size === 0) {
278 throw new BaseError('Evses not initialized, cannot get number of connectors');
279 }
28e78158
JB
280 let numberOfConnectors = 0;
281 for (const [evseId, evseStatus] of this.evses) {
4334db72
JB
282 if (evseId > 0) {
283 numberOfConnectors += evseStatus.connectors.size;
28e78158 284 }
28e78158
JB
285 }
286 return numberOfConnectors;
287 }
cda5d0fb
JB
288 if (this.connectors.size === 0) {
289 throw new BaseError('Connectors not initialized, cannot get number of connectors');
290 }
007b5bde 291 return this.connectors.has(0) ? this.connectors.size - 1 : this.connectors.size;
54544ef1
JB
292 }
293
28e78158 294 public getNumberOfEvses(): number {
cda5d0fb
JB
295 if (this.evses.size === 0) {
296 throw new BaseError('Evses not initialized, cannot get number of evses');
297 }
007b5bde 298 return this.evses.has(0) ? this.evses.size - 1 : this.evses.size;
28e78158
JB
299 }
300
301 public getConnectorStatus(connectorId: number): ConnectorStatus | undefined {
302 if (this.hasEvses) {
303 for (const evseStatus of this.evses.values()) {
304 if (evseStatus.connectors.has(connectorId)) {
305 return evseStatus.connectors.get(connectorId);
306 }
307 }
5e128725 308 return undefined;
28e78158
JB
309 }
310 return this.connectors.get(connectorId);
c0560973
JB
311 }
312
fa7bccf4 313 public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType {
72092cfc 314 return (stationInfo ?? this.stationInfo)?.currentOutType ?? CurrentType.AC;
c0560973
JB
315 }
316
672fed6e 317 public getOcppStrictCompliance(): boolean {
ccb1d6e9 318 return this.stationInfo?.ocppStrictCompliance ?? false;
672fed6e
JB
319 }
320
fa7bccf4 321 public getVoltageOut(stationInfo?: ChargingStationInfo): number | undefined {
492cf6ab 322 const defaultVoltageOut = ChargingStationUtils.getDefaultVoltageOut(
fa7bccf4 323 this.getCurrentOutType(stationInfo),
8a133cc8
JB
324 this.logPrefix(),
325 this.templateFile
492cf6ab 326 );
ac7f79af 327 return (stationInfo ?? this.stationInfo).voltageOut ?? defaultVoltageOut;
c0560973
JB
328 }
329
15068be9
JB
330 public getMaximumPower(stationInfo?: ChargingStationInfo): number {
331 const localStationInfo = stationInfo ?? this.stationInfo;
332 return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower;
333 }
334
ad8537a7 335 public getConnectorMaximumAvailablePower(connectorId: number): number {
d20f43b5 336 let connectorAmperageLimitationPowerLimit: number;
b47d68d7
JB
337 if (
338 !Utils.isNullOrUndefined(this.getAmperageLimitation()) &&
72092cfc 339 this.getAmperageLimitation() < this.stationInfo?.maximumAmperage
b47d68d7 340 ) {
4160ae28
JB
341 connectorAmperageLimitationPowerLimit =
342 (this.getCurrentOutType() === CurrentType.AC
cc6e8ab5
JB
343 ? ACElectricUtils.powerTotal(
344 this.getNumberOfPhases(),
345 this.getVoltageOut(),
b1bbdae5
JB
346 this.getAmperageLimitation() *
347 (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors())
cc6e8ab5 348 )
4160ae28 349 : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) /
fa7bccf4 350 this.powerDivider;
cc6e8ab5 351 }
fa7bccf4 352 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
15068be9
JB
353 const connectorChargingProfilesPowerLimit =
354 ChargingStationUtils.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId);
ad8537a7
JB
355 return Math.min(
356 isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower,
357 isNaN(connectorAmperageLimitationPowerLimit)
358 ? Infinity
359 : connectorAmperageLimitationPowerLimit,
15068be9 360 isNaN(connectorChargingProfilesPowerLimit) ? Infinity : connectorChargingProfilesPowerLimit
ad8537a7 361 );
cc6e8ab5
JB
362 }
363
6e0964c8 364 public getTransactionIdTag(transactionId: number): string | undefined {
28e78158
JB
365 if (this.hasEvses) {
366 for (const evseStatus of this.evses.values()) {
367 for (const connectorStatus of evseStatus.connectors.values()) {
368 if (connectorStatus.transactionId === transactionId) {
369 return connectorStatus.transactionIdTag;
370 }
371 }
372 }
373 } else {
374 for (const connectorId of this.connectors.keys()) {
375 if (
376 connectorId > 0 &&
377 this.getConnectorStatus(connectorId)?.transactionId === transactionId
378 ) {
379 return this.getConnectorStatus(connectorId)?.transactionIdTag;
380 }
c0560973
JB
381 }
382 }
383 }
384
ded57f02
JB
385 public getNumberOfRunningTransactions(): number {
386 let trxCount = 0;
387 if (this.hasEvses) {
388 for (const evseStatus of this.evses.values()) {
389 for (const connectorStatus of evseStatus.connectors.values()) {
390 if (connectorStatus.transactionStarted === true) {
391 ++trxCount;
392 }
393 }
394 }
395 } else {
396 for (const connectorId of this.connectors.keys()) {
397 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
398 ++trxCount;
399 }
400 }
401 }
402 return trxCount;
403 }
404
6ed92bc1 405 public getOutOfOrderEndMeterValues(): boolean {
ccb1d6e9 406 return this.stationInfo?.outOfOrderEndMeterValues ?? false;
6ed92bc1
JB
407 }
408
409 public getBeginEndMeterValues(): boolean {
ccb1d6e9 410 return this.stationInfo?.beginEndMeterValues ?? false;
6ed92bc1
JB
411 }
412
413 public getMeteringPerTransaction(): boolean {
ccb1d6e9 414 return this.stationInfo?.meteringPerTransaction ?? true;
6ed92bc1
JB
415 }
416
fd0c36fa 417 public getTransactionDataMeterValues(): boolean {
ccb1d6e9 418 return this.stationInfo?.transactionDataMeterValues ?? false;
fd0c36fa
JB
419 }
420
9ccca265 421 public getMainVoltageMeterValues(): boolean {
ccb1d6e9 422 return this.stationInfo?.mainVoltageMeterValues ?? true;
9ccca265
JB
423 }
424
6b10669b 425 public getPhaseLineToLineVoltageMeterValues(): boolean {
ccb1d6e9 426 return this.stationInfo?.phaseLineToLineVoltageMeterValues ?? false;
9bd87386
JB
427 }
428
7bc31f9c 429 public getCustomValueLimitationMeterValues(): boolean {
ccb1d6e9 430 return this.stationInfo?.customValueLimitationMeterValues ?? true;
7bc31f9c
JB
431 }
432
f479a792 433 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
28e78158
JB
434 if (this.hasEvses) {
435 for (const evseStatus of this.evses.values()) {
436 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
437 if (connectorStatus.transactionId === transactionId) {
438 return connectorId;
439 }
440 }
441 }
442 } else {
443 for (const connectorId of this.connectors.keys()) {
444 if (
445 connectorId > 0 &&
446 this.getConnectorStatus(connectorId)?.transactionId === transactionId
447 ) {
448 return connectorId;
449 }
c0560973
JB
450 }
451 }
452 }
453
07989fad
JB
454 public getEnergyActiveImportRegisterByTransactionId(
455 transactionId: number,
18bf8274 456 rounded = false
07989fad
JB
457 ): number {
458 return this.getEnergyActiveImportRegister(
459 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId)),
18bf8274 460 rounded
cbad1217 461 );
cbad1217
JB
462 }
463
18bf8274
JB
464 public getEnergyActiveImportRegisterByConnectorId(connectorId: number, rounded = false): number {
465 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId), rounded);
6ed92bc1
JB
466 }
467
c0560973 468 public getAuthorizeRemoteTxRequests(): boolean {
17ac262c
JB
469 const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey(
470 this,
e7aeea18
JB
471 StandardParametersKey.AuthorizeRemoteTxRequests
472 );
473 return authorizeRemoteTxRequests
474 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
475 : false;
c0560973
JB
476 }
477
478 public getLocalAuthListEnabled(): boolean {
17ac262c
JB
479 const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey(
480 this,
e7aeea18
JB
481 StandardParametersKey.LocalAuthListEnabled
482 );
c0560973
JB
483 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
484 }
485
8f953431
JB
486 public getHeartbeatInterval(): number {
487 const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
488 this,
489 StandardParametersKey.HeartbeatInterval
490 );
491 if (HeartbeatInterval) {
492 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
493 }
494 const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
495 this,
496 StandardParametersKey.HeartBeatInterval
497 );
498 if (HeartBeatInterval) {
499 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
500 }
501 this.stationInfo?.autoRegister === false &&
502 logger.warn(
503 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
504 Constants.DEFAULT_HEARTBEAT_INTERVAL
505 }`
506 );
507 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
508 }
509
269de583
JB
510 public setSupervisionUrl(url: string): void {
511 if (
512 this.getSupervisionUrlOcppConfiguration() &&
513 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey())
514 ) {
515 ChargingStationConfigurationUtils.setConfigurationKeyValue(
516 this,
517 this.getSupervisionUrlOcppKey(),
518 url
519 );
520 } else {
521 this.stationInfo.supervisionUrls = url;
522 this.saveStationInfo();
523 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
524 }
525 }
526
c0560973 527 public startHeartbeat(): void {
5b43123f 528 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
6a8329b4
JB
529 this.heartbeatSetInterval = setInterval(() => {
530 this.ocppRequestService
531 .requestHandler<HeartbeatRequest, HeartbeatResponse>(this, RequestCommand.HEARTBEAT)
72092cfc 532 .catch((error) => {
6a8329b4
JB
533 logger.error(
534 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
535 error
536 );
537 });
c0560973 538 }, this.getHeartbeatInterval());
e7aeea18 539 logger.info(
44eb6026
JB
540 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
541 this.getHeartbeatInterval()
542 )}`
e7aeea18 543 );
c0560973 544 } else if (this.heartbeatSetInterval) {
e7aeea18 545 logger.info(
44eb6026
JB
546 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
547 this.getHeartbeatInterval()
548 )}`
e7aeea18 549 );
c0560973 550 } else {
e7aeea18 551 logger.error(
8f953431 552 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
e7aeea18 553 );
c0560973
JB
554 }
555 }
556
557 public restartHeartbeat(): void {
558 // Stop heartbeat
559 this.stopHeartbeat();
560 // Start heartbeat
561 this.startHeartbeat();
562 }
563
17ac262c
JB
564 public restartWebSocketPing(): void {
565 // Stop WebSocket ping
566 this.stopWebSocketPing();
567 // Start WebSocket ping
568 this.startWebSocketPing();
569 }
570
c0560973
JB
571 public startMeterValues(connectorId: number, interval: number): void {
572 if (connectorId === 0) {
e7aeea18 573 logger.error(
2585c6e9 574 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
e7aeea18 575 );
c0560973
JB
576 return;
577 }
734d790d 578 if (!this.getConnectorStatus(connectorId)) {
e7aeea18 579 logger.error(
2585c6e9 580 `${this.logPrefix()} Trying to start MeterValues on non existing connector id ${connectorId.toString()}`
e7aeea18 581 );
c0560973
JB
582 return;
583 }
5e3cb728 584 if (this.getConnectorStatus(connectorId)?.transactionStarted === false) {
e7aeea18 585 logger.error(
2585c6e9 586 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
e7aeea18 587 );
c0560973 588 return;
e7aeea18 589 } else if (
5e3cb728 590 this.getConnectorStatus(connectorId)?.transactionStarted === true &&
d812bdcb 591 Utils.isNullOrUndefined(this.getConnectorStatus(connectorId)?.transactionId)
e7aeea18
JB
592 ) {
593 logger.error(
2585c6e9 594 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
e7aeea18 595 );
c0560973
JB
596 return;
597 }
598 if (interval > 0) {
6a8329b4
JB
599 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(() => {
600 // FIXME: Implement OCPP version agnostic helpers
601 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
602 this,
603 connectorId,
604 this.getConnectorStatus(connectorId).transactionId,
605 interval
606 );
607 this.ocppRequestService
608 .requestHandler<MeterValuesRequest, MeterValuesResponse>(
08f130a0 609 this,
f22266fd
JB
610 RequestCommand.METER_VALUES,
611 {
612 connectorId,
72092cfc 613 transactionId: this.getConnectorStatus(connectorId)?.transactionId,
f22266fd
JB
614 meterValue: [meterValue],
615 }
6a8329b4 616 )
72092cfc 617 .catch((error) => {
6a8329b4
JB
618 logger.error(
619 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
620 error
621 );
622 });
623 }, interval);
c0560973 624 } else {
e7aeea18
JB
625 logger.error(
626 `${this.logPrefix()} Charging station ${
627 StandardParametersKey.MeterValueSampleInterval
910c3f0c 628 } configuration set to ${interval}, not sending MeterValues`
e7aeea18 629 );
c0560973
JB
630 }
631 }
632
04b1261c
JB
633 public stopMeterValues(connectorId: number) {
634 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
635 clearInterval(this.getConnectorStatus(connectorId)?.transactionSetInterval);
636 }
637 }
638
c0560973 639 public start(): void {
0d8852a5
JB
640 if (this.started === false) {
641 if (this.starting === false) {
642 this.starting = true;
ad774cec 643 if (this.getEnableStatistics() === true) {
551e477c 644 this.performanceStatistics?.start();
0d8852a5
JB
645 }
646 this.openWSConnection();
647 // Monitor charging station template file
648 this.templateFileWatcher = FileUtils.watchJsonFile(
0d8852a5 649 this.templateFile,
7164966d
JB
650 FileType.ChargingStationTemplate,
651 this.logPrefix(),
652 undefined,
0d8852a5 653 (event, filename): void => {
5a2a53cf 654 if (Utils.isNotEmptyString(filename) && event === 'change') {
0d8852a5
JB
655 try {
656 logger.debug(
657 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
658 this.templateFile
659 } file have changed, reload`
660 );
cda5d0fb 661 this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash);
0d8852a5
JB
662 // Initialize
663 this.initialize();
664 // Restart the ATG
665 this.stopAutomaticTransactionGenerator();
ac7f79af 666 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable === true) {
0d8852a5
JB
667 this.startAutomaticTransactionGenerator();
668 }
ad774cec 669 if (this.getEnableStatistics() === true) {
551e477c 670 this.performanceStatistics?.restart();
0d8852a5 671 } else {
551e477c 672 this.performanceStatistics?.stop();
0d8852a5
JB
673 }
674 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
675 } catch (error) {
676 logger.error(
677 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
678 error
679 );
950b1349 680 }
a95873d8 681 }
a95873d8 682 }
0d8852a5 683 );
56eb297e 684 this.started = true;
1895299d 685 parentPort?.postMessage(MessageChannelUtils.buildStartedMessage(this));
0d8852a5
JB
686 this.starting = false;
687 } else {
688 logger.warn(`${this.logPrefix()} Charging station is already starting...`);
689 }
950b1349 690 } else {
0d8852a5 691 logger.warn(`${this.logPrefix()} Charging station is already started...`);
950b1349 692 }
c0560973
JB
693 }
694
60ddad53 695 public async stop(reason?: StopTransactionReason): Promise<void> {
0d8852a5
JB
696 if (this.started === true) {
697 if (this.stopping === false) {
698 this.stopping = true;
699 await this.stopMessageSequence(reason);
0d8852a5 700 this.closeWSConnection();
ad774cec 701 if (this.getEnableStatistics() === true) {
551e477c 702 this.performanceStatistics?.stop();
0d8852a5
JB
703 }
704 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
72092cfc 705 this.templateFileWatcher?.close();
cda5d0fb 706 this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash);
cdde2cfe 707 delete this.bootNotificationResponse;
0d8852a5 708 this.started = false;
ac7f79af 709 this.saveConfiguration();
1895299d 710 parentPort?.postMessage(MessageChannelUtils.buildStoppedMessage(this));
0d8852a5
JB
711 this.stopping = false;
712 } else {
713 logger.warn(`${this.logPrefix()} Charging station is already stopping...`);
c0560973 714 }
950b1349 715 } else {
0d8852a5 716 logger.warn(`${this.logPrefix()} Charging station is already stopped...`);
c0560973 717 }
c0560973
JB
718 }
719
60ddad53
JB
720 public async reset(reason?: StopTransactionReason): Promise<void> {
721 await this.stop(reason);
94ec7e96 722 await Utils.sleep(this.stationInfo.resetTime);
fa7bccf4 723 this.initialize();
94ec7e96
JB
724 this.start();
725 }
726
17ac262c
JB
727 public saveOcppConfiguration(): void {
728 if (this.getOcppPersistentConfiguration()) {
b1bbdae5 729 this.saveConfiguration();
e6895390
JB
730 }
731 }
732
72092cfc 733 public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean | undefined {
17ac262c
JB
734 return ChargingStationConfigurationUtils.getConfigurationKey(
735 this,
736 StandardParametersKey.SupportedFeatureProfiles
72092cfc 737 )?.value?.includes(featureProfile);
68cb8b91
JB
738 }
739
8e242273
JB
740 public bufferMessage(message: string): void {
741 this.messageBuffer.add(message);
3ba2381e
JB
742 }
743
db2336d9 744 public openWSConnection(
abe9e9dd 745 options: WsOptions = this.stationInfo?.wsOptions ?? {},
db2336d9
JB
746 params: { closeOpened?: boolean; terminateOpened?: boolean } = {
747 closeOpened: false,
748 terminateOpened: false,
749 }
750 ): void {
20f0b76c 751 options = { handshakeTimeout: this.getConnectionTimeout() * 1000, ...options };
b1bbdae5 752 params = { ...{ closeOpened: false, terminateOpened: false }, ...params };
cbf9b878 753 if (this.started === false && this.starting === false) {
d1c6c833
JB
754 logger.warn(
755 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
756 );
757 return;
758 }
db2336d9
JB
759 if (
760 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
761 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
762 ) {
763 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
764 }
765 if (params?.closeOpened) {
766 this.closeWSConnection();
767 }
768 if (params?.terminateOpened) {
769 this.terminateWSConnection();
770 }
db2336d9 771
56eb297e 772 if (this.isWebSocketConnectionOpened() === true) {
0a03f36c
JB
773 logger.warn(
774 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
775 );
776 return;
777 }
778
db2336d9 779 logger.info(
0a03f36c 780 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
db2336d9
JB
781 );
782
feff11ec
JB
783 this.wsConnection = new WebSocket(
784 this.wsConnectionUrl,
785 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
786 options
787 );
db2336d9
JB
788
789 // Handle WebSocket message
790 this.wsConnection.on(
791 'message',
792 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
793 );
794 // Handle WebSocket error
795 this.wsConnection.on(
796 'error',
797 this.onError.bind(this) as (this: WebSocket, error: Error) => void
798 );
799 // Handle WebSocket close
800 this.wsConnection.on(
801 'close',
802 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
803 );
804 // Handle WebSocket open
805 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
806 // Handle WebSocket ping
807 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
808 // Handle WebSocket pong
809 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
810 }
811
812 public closeWSConnection(): void {
56eb297e 813 if (this.isWebSocketConnectionOpened() === true) {
72092cfc 814 this.wsConnection?.close();
db2336d9
JB
815 this.wsConnection = null;
816 }
817 }
818
ac7f79af
JB
819 public getAutomaticTransactionGeneratorConfiguration():
820 | AutomaticTransactionGeneratorConfiguration
821 | undefined {
86b46b49
JB
822 let automaticTransactionGeneratorConfiguration:
823 | AutomaticTransactionGeneratorConfiguration
824 | undefined;
ac7f79af
JB
825 const automaticTransactionGeneratorConfigurationFromFile =
826 this.getConfigurationFromFile()?.automaticTransactionGenerator;
5ced7e80
JB
827 if (
828 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
829 automaticTransactionGeneratorConfigurationFromFile
830 ) {
86b46b49
JB
831 automaticTransactionGeneratorConfiguration =
832 automaticTransactionGeneratorConfigurationFromFile;
833 } else {
834 automaticTransactionGeneratorConfiguration =
835 this.getTemplateFromFile()?.AutomaticTransactionGenerator;
ac7f79af 836 }
86b46b49 837 return {
86b46b49 838 ...Constants.DEFAULT_ATG_CONFIGURATION,
ba056436 839 ...automaticTransactionGeneratorConfiguration,
86b46b49 840 };
ac7f79af
JB
841 }
842
5ced7e80
JB
843 public getAutomaticTransactionGeneratorStatuses(): Status[] | undefined {
844 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses;
845 }
846
ac7f79af
JB
847 public startAutomaticTransactionGenerator(connectorIds?: number[]): void {
848 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
53ac516c 849 if (Utils.isNotEmptyArray(connectorIds)) {
a5e9befc 850 for (const connectorId of connectorIds) {
551e477c 851 this.automaticTransactionGenerator?.startConnector(connectorId);
a5e9befc
JB
852 }
853 } else {
551e477c 854 this.automaticTransactionGenerator?.start();
4f69be04 855 }
cb60061f 856 this.saveAutomaticTransactionGeneratorConfiguration();
1895299d 857 parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
4f69be04
JB
858 }
859
a5e9befc 860 public stopAutomaticTransactionGenerator(connectorIds?: number[]): void {
53ac516c 861 if (Utils.isNotEmptyArray(connectorIds)) {
a5e9befc
JB
862 for (const connectorId of connectorIds) {
863 this.automaticTransactionGenerator?.stopConnector(connectorId);
864 }
865 } else {
866 this.automaticTransactionGenerator?.stop();
4f69be04 867 }
cb60061f 868 this.saveAutomaticTransactionGeneratorConfiguration();
1895299d 869 parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
4f69be04
JB
870 }
871
5e3cb728
JB
872 public async stopTransactionOnConnector(
873 connectorId: number,
874 reason = StopTransactionReason.NONE
875 ): Promise<StopTransactionResponse> {
72092cfc 876 const transactionId = this.getConnectorStatus(connectorId)?.transactionId;
5e3cb728 877 if (
c7e8e0a2
JB
878 this.getBeginEndMeterValues() === true &&
879 this.getOcppStrictCompliance() === true &&
880 this.getOutOfOrderEndMeterValues() === false
5e3cb728
JB
881 ) {
882 // FIXME: Implement OCPP version agnostic helpers
883 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
884 this,
885 connectorId,
886 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
887 );
888 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
889 this,
890 RequestCommand.METER_VALUES,
891 {
892 connectorId,
893 transactionId,
894 meterValue: [transactionEndMeterValue],
895 }
896 );
897 }
898 return this.ocppRequestService.requestHandler<StopTransactionRequest, StopTransactionResponse>(
899 this,
900 RequestCommand.STOP_TRANSACTION,
901 {
902 transactionId,
903 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true),
5e3cb728
JB
904 reason,
905 }
906 );
907 }
908
f90c1757 909 private flushMessageBuffer(): void {
8e242273 910 if (this.messageBuffer.size > 0) {
7d3b0f64 911 for (const message of this.messageBuffer.values()) {
1431af78
JB
912 let beginId: string;
913 let commandName: RequestCommand;
8ca6874c 914 const [messageType] = JSON.parse(message) as OutgoingRequest | Response | ErrorResponse;
1431af78
JB
915 const isRequest = messageType === MessageType.CALL_MESSAGE;
916 if (isRequest) {
917 [, , commandName] = JSON.parse(message) as OutgoingRequest;
918 beginId = PerformanceStatistics.beginMeasure(commandName);
919 }
72092cfc 920 this.wsConnection?.send(message);
1431af78 921 isRequest && PerformanceStatistics.endMeasure(commandName, beginId);
8ca6874c
JB
922 logger.debug(
923 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
924 messageType
925 )} payload sent: ${message}`
926 );
8e242273 927 this.messageBuffer.delete(message);
7d3b0f64 928 }
77f00f84
JB
929 }
930 }
931
1f5df42a
JB
932 private getSupervisionUrlOcppConfiguration(): boolean {
933 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
12fc74d6
JB
934 }
935
e8e865ea 936 private getSupervisionUrlOcppKey(): string {
6dad8e21 937 return this.stationInfo.supervisionUrlOcppKey ?? VendorParametersKey.ConnectionUrl;
e8e865ea
JB
938 }
939
72092cfc
JB
940 private getTemplateFromFile(): ChargingStationTemplate | undefined {
941 let template: ChargingStationTemplate;
5ad8570f 942 try {
cda5d0fb
JB
943 if (this.sharedLRUCache.hasChargingStationTemplate(this.templateFileHash)) {
944 template = this.sharedLRUCache.getChargingStationTemplate(this.templateFileHash);
7c72977b
JB
945 } else {
946 const measureId = `${FileType.ChargingStationTemplate} read`;
947 const beginId = PerformanceStatistics.beginMeasure(measureId);
948 template = JSON.parse(
949 fs.readFileSync(this.templateFile, 'utf8')
950 ) as ChargingStationTemplate;
951 PerformanceStatistics.endMeasure(measureId, beginId);
952 template.templateHash = crypto
953 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
954 .update(JSON.stringify(template))
955 .digest('hex');
57adbebc 956 this.sharedLRUCache.setChargingStationTemplate(template);
cda5d0fb 957 this.templateFileHash = template.templateHash;
7c72977b 958 }
5ad8570f 959 } catch (error) {
51022aa0 960 ErrorUtils.handleFileException(
2484ac1e 961 this.templateFile,
7164966d
JB
962 FileType.ChargingStationTemplate,
963 error as NodeJS.ErrnoException,
964 this.logPrefix()
e7aeea18 965 );
5ad8570f 966 }
2484ac1e
JB
967 return template;
968 }
969
7a3a2ebb 970 private getStationInfoFromTemplate(): ChargingStationInfo {
72092cfc 971 const stationTemplate: ChargingStationTemplate | undefined = this.getTemplateFromFile();
e1893686 972 ChargingStationUtils.checkTemplate(stationTemplate, this.logPrefix(), this.templateFile);
ae5020a3 973 ChargingStationUtils.warnTemplateKeysDeprecation(
ae5020a3 974 stationTemplate,
8a133cc8
JB
975 this.logPrefix(),
976 this.templateFile
ae5020a3 977 );
8a133cc8
JB
978 if (stationTemplate?.Connectors) {
979 ChargingStationUtils.checkConnectorsConfiguration(
980 stationTemplate,
981 this.logPrefix(),
982 this.templateFile
983 );
984 }
fa7bccf4
JB
985 const stationInfo: ChargingStationInfo =
986 ChargingStationUtils.stationTemplateToStationInfo(stationTemplate);
51c83d6f 987 stationInfo.hashId = ChargingStationUtils.getHashId(this.index, stationTemplate);
fa7bccf4
JB
988 stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId(
989 this.index,
990 stationTemplate
991 );
72092cfc 992 stationInfo.ocppVersion = stationTemplate?.ocppVersion ?? OCPPVersion.VERSION_16;
fa7bccf4 993 ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
53ac516c 994 if (Utils.isNotEmptyArray(stationTemplate?.power)) {
551e477c 995 stationTemplate.power = stationTemplate.power as number[];
fa7bccf4 996 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
cc6e8ab5 997 stationInfo.maximumPower =
72092cfc 998 stationTemplate?.powerUnit === PowerUnits.KILO_WATT
fa7bccf4
JB
999 ? stationTemplate.power[powerArrayRandomIndex] * 1000
1000 : stationTemplate.power[powerArrayRandomIndex];
5ad8570f 1001 } else {
551e477c 1002 stationTemplate.power = stationTemplate?.power as number;
cc6e8ab5 1003 stationInfo.maximumPower =
72092cfc 1004 stationTemplate?.powerUnit === PowerUnits.KILO_WATT
fa7bccf4
JB
1005 ? stationTemplate.power * 1000
1006 : stationTemplate.power;
1007 }
3637ca2c 1008 stationInfo.firmwareVersionPattern =
72092cfc 1009 stationTemplate?.firmwareVersionPattern ?? Constants.SEMVER_PATTERN;
3637ca2c 1010 if (
5a2a53cf 1011 Utils.isNotEmptyString(stationInfo.firmwareVersion) &&
3637ca2c
JB
1012 new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion) === false
1013 ) {
1014 logger.warn(
1015 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1016 this.templateFile
1017 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1018 );
1019 }
598c886d 1020 stationInfo.firmwareUpgrade = merge<FirmwareUpgrade>(
15748260 1021 {
598c886d
JB
1022 versionUpgrade: {
1023 step: 1,
1024 },
15748260
JB
1025 reset: true,
1026 },
abe9e9dd 1027 stationTemplate?.firmwareUpgrade ?? {}
15748260 1028 );
d812bdcb 1029 stationInfo.resetTime = !Utils.isNullOrUndefined(stationTemplate?.resetTime)
fa7bccf4 1030 ? stationTemplate.resetTime * 1000
e7aeea18 1031 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
fa7bccf4 1032 stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo);
9ac86a7e 1033 return stationInfo;
5ad8570f
JB
1034 }
1035
551e477c
JB
1036 private getStationInfoFromFile(): ChargingStationInfo | undefined {
1037 let stationInfo: ChargingStationInfo | undefined;
f832e5df
JB
1038 if (this.getStationInfoPersistentConfiguration()) {
1039 stationInfo = this.getConfigurationFromFile()?.stationInfo;
1040 if (stationInfo) {
1041 delete stationInfo?.infoHash;
1042 }
1043 }
f765beaa 1044 return stationInfo;
2484ac1e
JB
1045 }
1046
1047 private getStationInfo(): ChargingStationInfo {
1048 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
551e477c 1049 const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile();
6b90dcca
JB
1050 // Priority:
1051 // 1. charging station info from template
1052 // 2. charging station info from configuration file
f765beaa 1053 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
2484ac1e 1054 return stationInfoFromFile;
f765beaa 1055 }
fec4d204
JB
1056 stationInfoFromFile &&
1057 ChargingStationUtils.propagateSerialNumber(
1058 this.getTemplateFromFile(),
1059 stationInfoFromFile,
1060 stationInfoFromTemplate
1061 );
01efc60a 1062 return stationInfoFromTemplate;
2484ac1e
JB
1063 }
1064
1065 private saveStationInfo(): void {
ccb1d6e9 1066 if (this.getStationInfoPersistentConfiguration()) {
b1bbdae5 1067 this.saveConfiguration();
ccb1d6e9 1068 }
2484ac1e
JB
1069 }
1070
e8e865ea 1071 private getOcppPersistentConfiguration(): boolean {
ccb1d6e9
JB
1072 return this.stationInfo?.ocppPersistentConfiguration ?? true;
1073 }
1074
1075 private getStationInfoPersistentConfiguration(): boolean {
1076 return this.stationInfo?.stationInfoPersistentConfiguration ?? true;
e8e865ea
JB
1077 }
1078
5ced7e80
JB
1079 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1080 return this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration ?? true;
1081 }
1082
c0560973 1083 private handleUnsupportedVersion(version: OCPPVersion) {
ded57f02
JB
1084 const errorMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1085 logger.error(`${this.logPrefix()} ${errorMsg}`);
1086 throw new BaseError(errorMsg);
c0560973
JB
1087 }
1088
2484ac1e 1089 private initialize(): void {
cda5d0fb 1090 const stationTemplate = this.getTemplateFromFile();
e1893686 1091 ChargingStationUtils.checkTemplate(stationTemplate, this.logPrefix(), this.templateFile);
fa7bccf4 1092 this.configurationFile = path.join(
ee5f26a2 1093 path.dirname(this.templateFile.replace('station-templates', 'configurations')),
cda5d0fb 1094 `${ChargingStationUtils.getHashId(this.index, stationTemplate)}.json`
0642c3d2 1095 );
a4f7c75f 1096 const chargingStationConfiguration = this.getConfigurationFromFile();
a4f7c75f 1097 if (
ba01a213
JB
1098 chargingStationConfiguration?.stationInfo?.templateHash === stationTemplate?.templateHash &&
1099 (chargingStationConfiguration?.connectorsStatus || chargingStationConfiguration?.evsesStatus)
a4f7c75f
JB
1100 ) {
1101 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration);
1102 } else {
1103 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate);
1104 }
b44b779a 1105 this.stationInfo = this.getStationInfo();
3637ca2c
JB
1106 if (
1107 this.stationInfo.firmwareStatus === FirmwareStatus.Installing &&
5a2a53cf
JB
1108 Utils.isNotEmptyString(this.stationInfo.firmwareVersion) &&
1109 Utils.isNotEmptyString(this.stationInfo.firmwareVersionPattern)
3637ca2c 1110 ) {
d812bdcb 1111 const patternGroup: number | undefined =
15748260 1112 this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ??
d812bdcb 1113 this.stationInfo.firmwareVersion?.split('.').length;
72092cfc
JB
1114 const match = this.stationInfo?.firmwareVersion
1115 ?.match(new RegExp(this.stationInfo.firmwareVersionPattern))
1116 ?.slice(1, patternGroup + 1);
3637ca2c 1117 const patchLevelIndex = match.length - 1;
5d280aae 1118 match[patchLevelIndex] = (
07c52a72
JB
1119 Utils.convertToInt(match[patchLevelIndex]) +
1120 this.stationInfo.firmwareUpgrade?.versionUpgrade?.step
5d280aae 1121 ).toString();
72092cfc 1122 this.stationInfo.firmwareVersion = match?.join('.');
3637ca2c 1123 }
6bccfcbc 1124 this.saveStationInfo();
6bccfcbc
JB
1125 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
1126 if (this.getEnableStatistics() === true) {
1127 this.performanceStatistics = PerformanceStatistics.getInstance(
1128 this.stationInfo.hashId,
1129 this.stationInfo.chargingStationId,
1130 this.configuredSupervisionUrl
1131 );
1132 }
692f2f64
JB
1133 this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest(
1134 this.stationInfo
1135 );
1136 this.powerDivider = this.getPowerDivider();
1137 // OCPP configuration
1138 this.ocppConfiguration = this.getOcppConfiguration();
1139 this.initializeOcppConfiguration();
1140 this.initializeOcppServices();
1141 if (this.stationInfo?.autoRegister === true) {
1142 this.bootNotificationResponse = {
1143 currentTime: new Date(),
1144 interval: this.getHeartbeatInterval() / 1000,
1145 status: RegistrationStatusEnumType.ACCEPTED,
1146 };
1147 }
147d0e0f
JB
1148 }
1149
feff11ec
JB
1150 private initializeOcppServices(): void {
1151 const ocppVersion = this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
1152 switch (ocppVersion) {
1153 case OCPPVersion.VERSION_16:
1154 this.ocppIncomingRequestService =
1155 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
1156 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
1157 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
1158 );
1159 break;
1160 case OCPPVersion.VERSION_20:
1161 case OCPPVersion.VERSION_201:
1162 this.ocppIncomingRequestService =
1163 OCPP20IncomingRequestService.getInstance<OCPP20IncomingRequestService>();
1164 this.ocppRequestService = OCPP20RequestService.getInstance<OCPP20RequestService>(
1165 OCPP20ResponseService.getInstance<OCPP20ResponseService>()
1166 );
1167 break;
1168 default:
1169 this.handleUnsupportedVersion(ocppVersion);
1170 break;
1171 }
1172 }
1173
2484ac1e 1174 private initializeOcppConfiguration(): void {
17ac262c
JB
1175 if (
1176 !ChargingStationConfigurationUtils.getConfigurationKey(
1177 this,
1178 StandardParametersKey.HeartbeatInterval
1179 )
1180 ) {
1181 ChargingStationConfigurationUtils.addConfigurationKey(
1182 this,
1183 StandardParametersKey.HeartbeatInterval,
1184 '0'
1185 );
f0f65a62 1186 }
17ac262c
JB
1187 if (
1188 !ChargingStationConfigurationUtils.getConfigurationKey(
1189 this,
1190 StandardParametersKey.HeartBeatInterval
1191 )
1192 ) {
1193 ChargingStationConfigurationUtils.addConfigurationKey(
1194 this,
1195 StandardParametersKey.HeartBeatInterval,
1196 '0',
1197 { visible: false }
1198 );
f0f65a62 1199 }
e7aeea18
JB
1200 if (
1201 this.getSupervisionUrlOcppConfiguration() &&
269de583 1202 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
17ac262c 1203 !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e7aeea18 1204 ) {
17ac262c
JB
1205 ChargingStationConfigurationUtils.addConfigurationKey(
1206 this,
a59737e3 1207 this.getSupervisionUrlOcppKey(),
fa7bccf4 1208 this.configuredSupervisionUrl.href,
e7aeea18
JB
1209 { reboot: true }
1210 );
e6895390
JB
1211 } else if (
1212 !this.getSupervisionUrlOcppConfiguration() &&
269de583 1213 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
17ac262c 1214 ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e6895390 1215 ) {
17ac262c
JB
1216 ChargingStationConfigurationUtils.deleteConfigurationKey(
1217 this,
1218 this.getSupervisionUrlOcppKey(),
1219 { save: false }
1220 );
12fc74d6 1221 }
cc6e8ab5 1222 if (
5a2a53cf 1223 Utils.isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
17ac262c
JB
1224 !ChargingStationConfigurationUtils.getConfigurationKey(
1225 this,
1226 this.stationInfo.amperageLimitationOcppKey
1227 )
cc6e8ab5 1228 ) {
17ac262c
JB
1229 ChargingStationConfigurationUtils.addConfigurationKey(
1230 this,
cc6e8ab5 1231 this.stationInfo.amperageLimitationOcppKey,
17ac262c
JB
1232 (
1233 this.stationInfo.maximumAmperage *
1234 ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1235 ).toString()
cc6e8ab5
JB
1236 );
1237 }
17ac262c
JB
1238 if (
1239 !ChargingStationConfigurationUtils.getConfigurationKey(
1240 this,
1241 StandardParametersKey.SupportedFeatureProfiles
1242 )
1243 ) {
1244 ChargingStationConfigurationUtils.addConfigurationKey(
1245 this,
e7aeea18 1246 StandardParametersKey.SupportedFeatureProfiles,
b22787b4 1247 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
e7aeea18
JB
1248 );
1249 }
17ac262c
JB
1250 ChargingStationConfigurationUtils.addConfigurationKey(
1251 this,
e7aeea18
JB
1252 StandardParametersKey.NumberOfConnectors,
1253 this.getNumberOfConnectors().toString(),
a95873d8
JB
1254 { readonly: true },
1255 { overwrite: true }
e7aeea18 1256 );
17ac262c
JB
1257 if (
1258 !ChargingStationConfigurationUtils.getConfigurationKey(
1259 this,
1260 StandardParametersKey.MeterValuesSampledData
1261 )
1262 ) {
1263 ChargingStationConfigurationUtils.addConfigurationKey(
1264 this,
e7aeea18
JB
1265 StandardParametersKey.MeterValuesSampledData,
1266 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1267 );
7abfea5f 1268 }
17ac262c
JB
1269 if (
1270 !ChargingStationConfigurationUtils.getConfigurationKey(
1271 this,
1272 StandardParametersKey.ConnectorPhaseRotation
1273 )
1274 ) {
dd08d43d 1275 const connectorsPhaseRotation: string[] = [];
28e78158
JB
1276 if (this.hasEvses) {
1277 for (const evseStatus of this.evses.values()) {
1278 for (const connectorId of evseStatus.connectors.keys()) {
dd08d43d
JB
1279 connectorsPhaseRotation.push(
1280 ChargingStationUtils.getPhaseRotationValue(connectorId, this.getNumberOfPhases())
1281 );
28e78158
JB
1282 }
1283 }
1284 } else {
1285 for (const connectorId of this.connectors.keys()) {
dd08d43d
JB
1286 connectorsPhaseRotation.push(
1287 ChargingStationUtils.getPhaseRotationValue(connectorId, this.getNumberOfPhases())
1288 );
7e1dc878
JB
1289 }
1290 }
17ac262c
JB
1291 ChargingStationConfigurationUtils.addConfigurationKey(
1292 this,
e7aeea18 1293 StandardParametersKey.ConnectorPhaseRotation,
dd08d43d 1294 connectorsPhaseRotation.toString()
e7aeea18 1295 );
7e1dc878 1296 }
e7aeea18 1297 if (
17ac262c
JB
1298 !ChargingStationConfigurationUtils.getConfigurationKey(
1299 this,
1300 StandardParametersKey.AuthorizeRemoteTxRequests
e7aeea18
JB
1301 )
1302 ) {
17ac262c
JB
1303 ChargingStationConfigurationUtils.addConfigurationKey(
1304 this,
1305 StandardParametersKey.AuthorizeRemoteTxRequests,
1306 'true'
1307 );
36f6a92e 1308 }
17ac262c
JB
1309 if (
1310 !ChargingStationConfigurationUtils.getConfigurationKey(
1311 this,
1312 StandardParametersKey.LocalAuthListEnabled
1313 ) &&
1314 ChargingStationConfigurationUtils.getConfigurationKey(
1315 this,
1316 StandardParametersKey.SupportedFeatureProfiles
72092cfc 1317 )?.value?.includes(SupportedFeatureProfiles.LocalAuthListManagement)
17ac262c
JB
1318 ) {
1319 ChargingStationConfigurationUtils.addConfigurationKey(
1320 this,
1321 StandardParametersKey.LocalAuthListEnabled,
1322 'false'
1323 );
1324 }
1325 if (
1326 !ChargingStationConfigurationUtils.getConfigurationKey(
1327 this,
1328 StandardParametersKey.ConnectionTimeOut
1329 )
1330 ) {
1331 ChargingStationConfigurationUtils.addConfigurationKey(
1332 this,
e7aeea18
JB
1333 StandardParametersKey.ConnectionTimeOut,
1334 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1335 );
8bce55bf 1336 }
2484ac1e 1337 this.saveOcppConfiguration();
073bd098
JB
1338 }
1339
a4f7c75f
JB
1340 private initializeConnectorsOrEvsesFromFile(configuration: ChargingStationConfiguration): void {
1341 if (configuration?.connectorsStatus && !configuration?.evsesStatus) {
8df5ae48
JB
1342 for (const [connectorId, connectorStatus] of configuration.connectorsStatus.entries()) {
1343 this.connectors.set(connectorId, Utils.cloneObject<ConnectorStatus>(connectorStatus));
1344 }
a4f7c75f
JB
1345 } else if (configuration?.evsesStatus && !configuration?.connectorsStatus) {
1346 for (const [evseId, evseStatusConfiguration] of configuration.evsesStatus.entries()) {
8df5ae48 1347 const evseStatus = Utils.cloneObject<EvseStatusConfiguration>(evseStatusConfiguration);
a4f7c75f
JB
1348 delete evseStatus.connectorsStatus;
1349 this.evses.set(evseId, {
8df5ae48 1350 ...(evseStatus as EvseStatus),
a4f7c75f
JB
1351 connectors: new Map<number, ConnectorStatus>(
1352 evseStatusConfiguration.connectorsStatus.map((connectorStatus, connectorId) => [
1353 connectorId,
1354 connectorStatus,
1355 ])
1356 ),
1357 });
1358 }
1359 } else if (configuration?.evsesStatus && configuration?.connectorsStatus) {
1360 const errorMsg = `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1361 logger.error(`${this.logPrefix()} ${errorMsg}`);
1362 throw new BaseError(errorMsg);
1363 } else {
1364 const errorMsg = `No connectors or evses defined in configuration file ${this.configurationFile}`;
1365 logger.error(`${this.logPrefix()} ${errorMsg}`);
1366 throw new BaseError(errorMsg);
1367 }
1368 }
1369
34eeb1fb 1370 private initializeConnectorsOrEvsesFromTemplate(stationTemplate: ChargingStationTemplate) {
cda5d0fb 1371 if (stationTemplate?.Connectors && !stationTemplate?.Evses) {
34eeb1fb 1372 this.initializeConnectorsFromTemplate(stationTemplate);
cda5d0fb 1373 } else if (stationTemplate?.Evses && !stationTemplate?.Connectors) {
34eeb1fb 1374 this.initializeEvsesFromTemplate(stationTemplate);
cda5d0fb 1375 } else if (stationTemplate?.Evses && stationTemplate?.Connectors) {
ae25f265
JB
1376 const errorMsg = `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1377 logger.error(`${this.logPrefix()} ${errorMsg}`);
1378 throw new BaseError(errorMsg);
1379 } else {
1380 const errorMsg = `No connectors or evses defined in template file ${this.templateFile}`;
1381 logger.error(`${this.logPrefix()} ${errorMsg}`);
1382 throw new BaseError(errorMsg);
1383 }
1384 }
1385
34eeb1fb 1386 private initializeConnectorsFromTemplate(stationTemplate: ChargingStationTemplate): void {
cda5d0fb 1387 if (!stationTemplate?.Connectors && this.connectors.size === 0) {
ded57f02
JB
1388 const errorMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1389 logger.error(`${this.logPrefix()} ${errorMsg}`);
1390 throw new BaseError(errorMsg);
3d25cc86 1391 }
cda5d0fb 1392 if (!stationTemplate?.Connectors[0]) {
3d25cc86
JB
1393 logger.warn(
1394 `${this.logPrefix()} Charging station information from template ${
1395 this.templateFile
2585c6e9 1396 } with no connector id 0 configuration`
3d25cc86
JB
1397 );
1398 }
cda5d0fb
JB
1399 if (stationTemplate?.Connectors) {
1400 const { configuredMaxConnectors, templateMaxConnectors, templateMaxAvailableConnectors } =
1401 ChargingStationUtils.checkConnectorsConfiguration(
1402 stationTemplate,
8a133cc8
JB
1403 this.logPrefix(),
1404 this.templateFile
cda5d0fb 1405 );
3d25cc86
JB
1406 const connectorsConfigHash = crypto
1407 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
cda5d0fb
JB
1408 .update(
1409 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1410 )
3d25cc86
JB
1411 .digest('hex');
1412 const connectorsConfigChanged =
1413 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1414 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1415 connectorsConfigChanged && this.connectors.clear();
1416 this.connectorsConfigurationHash = connectorsConfigHash;
269196a8
JB
1417 if (templateMaxConnectors > 0) {
1418 for (let connectorId = 0; connectorId <= configuredMaxConnectors; connectorId++) {
1419 if (
1420 connectorId === 0 &&
cda5d0fb
JB
1421 (!stationTemplate?.Connectors[connectorId] ||
1422 this.getUseConnectorId0(stationTemplate) === false)
269196a8
JB
1423 ) {
1424 continue;
1425 }
1426 const templateConnectorId =
cda5d0fb 1427 connectorId > 0 && stationTemplate?.randomConnectors
269196a8
JB
1428 ? Utils.getRandomInteger(templateMaxAvailableConnectors, 1)
1429 : connectorId;
cda5d0fb 1430 const connectorStatus = stationTemplate?.Connectors[templateConnectorId];
04b1261c 1431 ChargingStationUtils.checkStationInfoConnectorStatus(
ae25f265 1432 templateConnectorId,
04b1261c
JB
1433 connectorStatus,
1434 this.logPrefix(),
1435 this.templateFile
1436 );
ae25f265 1437 this.connectors.set(connectorId, Utils.cloneObject<ConnectorStatus>(connectorStatus));
3d25cc86 1438 }
52952bf8
JB
1439 ChargingStationUtils.initializeConnectorsMapStatus(this.connectors, this.logPrefix());
1440 this.saveConnectorsStatus();
ae25f265
JB
1441 } else {
1442 logger.warn(
1443 `${this.logPrefix()} Charging station information from template ${
1444 this.templateFile
1445 } with no connectors configuration defined, cannot create connectors`
1446 );
3d25cc86
JB
1447 }
1448 }
1449 } else {
1450 logger.warn(
1451 `${this.logPrefix()} Charging station information from template ${
1452 this.templateFile
1453 } with no connectors configuration defined, using already defined connectors`
1454 );
1455 }
3d25cc86
JB
1456 }
1457
34eeb1fb 1458 private initializeEvsesFromTemplate(stationTemplate: ChargingStationTemplate): void {
cda5d0fb 1459 if (!stationTemplate?.Evses && this.evses.size === 0) {
ded57f02
JB
1460 const errorMsg = `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1461 logger.error(`${this.logPrefix()} ${errorMsg}`);
1462 throw new BaseError(errorMsg);
2585c6e9 1463 }
cda5d0fb 1464 if (!stationTemplate?.Evses[0]) {
2585c6e9
JB
1465 logger.warn(
1466 `${this.logPrefix()} Charging station information from template ${
1467 this.templateFile
1468 } with no evse id 0 configuration`
1469 );
1470 }
cda5d0fb 1471 if (!stationTemplate?.Evses[0]?.Connectors[0]) {
59a0f26d
JB
1472 logger.warn(
1473 `${this.logPrefix()} Charging station information from template ${
1474 this.templateFile
1475 } with evse id 0 with no connector id 0 configuration`
1476 );
1477 }
cda5d0fb 1478 if (stationTemplate?.Evses) {
2585c6e9
JB
1479 const evsesConfigHash = crypto
1480 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
ba01a213 1481 .update(JSON.stringify(stationTemplate?.Evses))
2585c6e9
JB
1482 .digest('hex');
1483 const evsesConfigChanged =
1484 this.evses?.size !== 0 && this.evsesConfigurationHash !== evsesConfigHash;
1485 if (this.evses?.size === 0 || evsesConfigChanged) {
1486 evsesConfigChanged && this.evses.clear();
1487 this.evsesConfigurationHash = evsesConfigHash;
cda5d0fb 1488 const templateMaxEvses = ChargingStationUtils.getMaxNumberOfEvses(stationTemplate?.Evses);
ae25f265 1489 if (templateMaxEvses > 0) {
cda5d0fb 1490 for (const evse in stationTemplate.Evses) {
52952bf8
JB
1491 const evseId = Utils.convertToInt(evse);
1492 this.evses.set(evseId, {
ae25f265 1493 connectors: ChargingStationUtils.buildConnectorsMap(
cda5d0fb 1494 stationTemplate?.Evses[evse]?.Connectors,
ae25f265
JB
1495 this.logPrefix(),
1496 this.templateFile
1497 ),
1498 availability: AvailabilityType.Operative,
1499 });
1500 ChargingStationUtils.initializeConnectorsMapStatus(
52952bf8 1501 this.evses.get(evseId)?.connectors,
ae25f265
JB
1502 this.logPrefix()
1503 );
1504 }
52952bf8 1505 this.saveEvsesStatus();
ae25f265
JB
1506 } else {
1507 logger.warn(
1508 `${this.logPrefix()} Charging station information from template ${
04b1261c 1509 this.templateFile
ae25f265 1510 } with no evses configuration defined, cannot create evses`
04b1261c 1511 );
2585c6e9
JB
1512 }
1513 }
513db108
JB
1514 } else {
1515 logger.warn(
1516 `${this.logPrefix()} Charging station information from template ${
1517 this.templateFile
1518 } with no evses configuration defined, using already defined evses`
1519 );
2585c6e9
JB
1520 }
1521 }
1522
551e477c
JB
1523 private getConfigurationFromFile(): ChargingStationConfiguration | undefined {
1524 let configuration: ChargingStationConfiguration | undefined;
7b5dbe91 1525 if (Utils.isNotEmptyString(this.configurationFile) && fs.existsSync(this.configurationFile)) {
073bd098 1526 try {
57adbebc
JB
1527 if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
1528 configuration = this.sharedLRUCache.getChargingStationConfiguration(
1529 this.configurationFileHash
1530 );
7c72977b
JB
1531 } else {
1532 const measureId = `${FileType.ChargingStationConfiguration} read`;
1533 const beginId = PerformanceStatistics.beginMeasure(measureId);
1534 configuration = JSON.parse(
1535 fs.readFileSync(this.configurationFile, 'utf8')
1536 ) as ChargingStationConfiguration;
1537 PerformanceStatistics.endMeasure(measureId, beginId);
57adbebc 1538 this.sharedLRUCache.setChargingStationConfiguration(configuration);
cda5d0fb 1539 this.configurationFileHash = configuration.configurationHash;
7c72977b 1540 }
073bd098 1541 } catch (error) {
51022aa0 1542 ErrorUtils.handleFileException(
073bd098 1543 this.configurationFile,
7164966d
JB
1544 FileType.ChargingStationConfiguration,
1545 error as NodeJS.ErrnoException,
1546 this.logPrefix()
073bd098
JB
1547 );
1548 }
1549 }
1550 return configuration;
1551 }
1552
cb60061f 1553 private saveAutomaticTransactionGeneratorConfiguration(): void {
5ced7e80
JB
1554 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1555 this.saveConfiguration();
1556 }
ac7f79af
JB
1557 }
1558
52952bf8 1559 private saveConnectorsStatus() {
7446de3b 1560 this.saveConfiguration();
52952bf8
JB
1561 }
1562
1563 private saveEvsesStatus() {
7446de3b 1564 this.saveConfiguration();
52952bf8
JB
1565 }
1566
179ed367 1567 private saveConfiguration(): void {
7b5dbe91 1568 if (Utils.isNotEmptyString(this.configurationFile)) {
2484ac1e 1569 try {
2484ac1e
JB
1570 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1571 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
073bd098 1572 }
ac7f79af 1573 let configurationData: ChargingStationConfiguration =
8df5ae48 1574 Utils.cloneObject<ChargingStationConfiguration>(this.getConfigurationFromFile()) ?? {};
34eeb1fb 1575 if (this.getStationInfoPersistentConfiguration() && this.stationInfo) {
52952bf8 1576 configurationData.stationInfo = this.stationInfo;
5ced7e80
JB
1577 } else {
1578 delete configurationData.stationInfo;
52952bf8 1579 }
34eeb1fb 1580 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration?.configurationKey) {
52952bf8 1581 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
5ced7e80
JB
1582 } else {
1583 delete configurationData.configurationKey;
52952bf8 1584 }
179ed367
JB
1585 configurationData = merge<ChargingStationConfiguration>(
1586 configurationData,
1587 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1588 );
5ced7e80
JB
1589 if (
1590 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1591 !this.getAutomaticTransactionGeneratorConfiguration()
1592 ) {
1593 delete configurationData.automaticTransactionGenerator;
1594 }
b1bbdae5 1595 if (this.connectors.size > 0) {
179ed367 1596 configurationData.connectorsStatus = buildConnectorsStatus(this);
5ced7e80
JB
1597 } else {
1598 delete configurationData.connectorsStatus;
52952bf8 1599 }
b1bbdae5 1600 if (this.evses.size > 0) {
179ed367 1601 configurationData.evsesStatus = buildEvsesStatus(this);
5ced7e80
JB
1602 } else {
1603 delete configurationData.evsesStatus;
52952bf8 1604 }
7c72977b
JB
1605 delete configurationData.configurationHash;
1606 const configurationHash = crypto
1607 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
5ced7e80
JB
1608 .update(
1609 JSON.stringify({
1610 stationInfo: configurationData.stationInfo,
1611 configurationKey: configurationData.configurationKey,
1612 automaticTransactionGenerator: configurationData.automaticTransactionGenerator,
1613 } as ChargingStationConfiguration)
1614 )
7c72977b
JB
1615 .digest('hex');
1616 if (this.configurationFileHash !== configurationHash) {
dd485b56 1617 AsyncLock.acquire(AsyncLockType.configuration)
1227a6f1
JB
1618 .then(() => {
1619 configurationData.configurationHash = configurationHash;
1620 const measureId = `${FileType.ChargingStationConfiguration} write`;
1621 const beginId = PerformanceStatistics.beginMeasure(measureId);
1622 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1623 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1624 fs.closeSync(fileDescriptor);
1625 PerformanceStatistics.endMeasure(measureId, beginId);
1626 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
1627 this.sharedLRUCache.setChargingStationConfiguration(configurationData);
1628 this.configurationFileHash = configurationHash;
1629 })
1630 .catch((error) => {
51022aa0 1631 ErrorUtils.handleFileException(
1227a6f1
JB
1632 this.configurationFile,
1633 FileType.ChargingStationConfiguration,
1634 error as NodeJS.ErrnoException,
1635 this.logPrefix()
1636 );
1637 })
1638 .finally(() => {
dd485b56 1639 AsyncLock.release(AsyncLockType.configuration).catch(Constants.EMPTY_FUNCTION);
1227a6f1 1640 });
7c72977b
JB
1641 } else {
1642 logger.debug(
1643 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1644 this.configurationFile
1645 }`
1646 );
2484ac1e 1647 }
2484ac1e 1648 } catch (error) {
51022aa0 1649 ErrorUtils.handleFileException(
2484ac1e 1650 this.configurationFile,
7164966d
JB
1651 FileType.ChargingStationConfiguration,
1652 error as NodeJS.ErrnoException,
1653 this.logPrefix()
073bd098
JB
1654 );
1655 }
2484ac1e
JB
1656 } else {
1657 logger.error(
01efc60a 1658 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
2484ac1e 1659 );
073bd098
JB
1660 }
1661 }
1662
551e477c
JB
1663 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | undefined {
1664 return this.getTemplateFromFile()?.Configuration;
2484ac1e
JB
1665 }
1666
551e477c 1667 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | undefined {
60655b26
JB
1668 const configurationKey = this.getConfigurationFromFile()?.configurationKey;
1669 if (this.getOcppPersistentConfiguration() === true && configurationKey) {
1670 return { configurationKey };
648512ce 1671 }
60655b26 1672 return undefined;
7dde0b73
JB
1673 }
1674
551e477c
JB
1675 private getOcppConfiguration(): ChargingStationOcppConfiguration | undefined {
1676 let ocppConfiguration: ChargingStationOcppConfiguration | undefined =
72092cfc 1677 this.getOcppConfigurationFromFile();
2484ac1e
JB
1678 if (!ocppConfiguration) {
1679 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1680 }
1681 return ocppConfiguration;
1682 }
1683
c0560973 1684 private async onOpen(): Promise<void> {
56eb297e 1685 if (this.isWebSocketConnectionOpened() === true) {
5144f4d1
JB
1686 logger.info(
1687 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1688 );
ed6cfcff 1689 if (this.isRegistered() === false) {
5144f4d1
JB
1690 // Send BootNotification
1691 let registrationRetryCount = 0;
1692 do {
f7f98c68 1693 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
5144f4d1
JB
1694 BootNotificationRequest,
1695 BootNotificationResponse
8bfbc743
JB
1696 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
1697 skipBufferingOnError: true,
1698 });
ed6cfcff 1699 if (this.isRegistered() === false) {
1fe0632a 1700 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount;
5144f4d1 1701 await Utils.sleep(
1895299d 1702 this?.bootNotificationResponse?.interval
5144f4d1 1703 ? this.bootNotificationResponse.interval * 1000
7d34a2f4 1704 : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL
5144f4d1
JB
1705 );
1706 }
1707 } while (
ed6cfcff 1708 this.isRegistered() === false &&
5144f4d1
JB
1709 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1710 this.getRegistrationMaxRetries() === -1)
1711 );
1712 }
ed6cfcff 1713 if (this.isRegistered() === true) {
f7c2994d 1714 if (this.inAcceptedState() === true) {
94bb24d5 1715 await this.startMessageSequence();
c0560973 1716 }
5144f4d1
JB
1717 } else {
1718 logger.error(
1719 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1720 );
caad9d6b 1721 }
5144f4d1 1722 this.wsConnectionRestarted = false;
aa428a31 1723 this.autoReconnectRetryCount = 0;
1895299d 1724 parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
2e6f5966 1725 } else {
5144f4d1
JB
1726 logger.warn(
1727 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
e7aeea18 1728 );
2e6f5966 1729 }
2e6f5966
JB
1730 }
1731
ef7d8c21 1732 private async onClose(code: number, reason: Buffer): Promise<void> {
d09085e9 1733 switch (code) {
6c65a295
JB
1734 // Normal close
1735 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 1736 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18 1737 logger.info(
5e3cb728 1738 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
e7aeea18 1739 code
ef7d8c21 1740 )}' and reason '${reason.toString()}'`
e7aeea18 1741 );
c0560973
JB
1742 this.autoReconnectRetryCount = 0;
1743 break;
6c65a295
JB
1744 // Abnormal close
1745 default:
e7aeea18 1746 logger.error(
5e3cb728 1747 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
e7aeea18 1748 code
ef7d8c21 1749 )}' and reason '${reason.toString()}'`
e7aeea18 1750 );
56eb297e 1751 this.started === true && (await this.reconnect());
c0560973
JB
1752 break;
1753 }
1895299d 1754 parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
2e6f5966
JB
1755 }
1756
56d09fd7
JB
1757 private getCachedRequest(messageType: MessageType, messageId: string): CachedRequest | undefined {
1758 const cachedRequest = this.requests.get(messageId);
1759 if (Array.isArray(cachedRequest) === true) {
1760 return cachedRequest;
1761 }
1762 throw new OCPPError(
1763 ErrorType.PROTOCOL_ERROR,
1764 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1765 messageType
1766 )} is not an array`,
1767 undefined,
617cad0c 1768 cachedRequest as JsonType
56d09fd7
JB
1769 );
1770 }
1771
1772 private async handleIncomingMessage(request: IncomingRequest): Promise<void> {
1773 const [messageType, messageId, commandName, commandPayload] = request;
1774 if (this.getEnableStatistics() === true) {
1775 this.performanceStatistics?.addRequestStatistic(commandName, messageType);
1776 }
1777 logger.debug(
1778 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1779 request
1780 )}`
1781 );
1782 // Process the message
1783 await this.ocppIncomingRequestService.incomingRequestHandler(
1784 this,
1785 messageId,
1786 commandName,
1787 commandPayload
1788 );
1789 }
1790
1791 private handleResponseMessage(response: Response): void {
1792 const [messageType, messageId, commandPayload] = response;
1793 if (this.requests.has(messageId) === false) {
1794 // Error
1795 throw new OCPPError(
1796 ErrorType.INTERNAL_ERROR,
1797 `Response for unknown message id ${messageId}`,
1798 undefined,
1799 commandPayload
1800 );
1801 }
1802 // Respond
1803 const [responseCallback, , requestCommandName, requestPayload] = this.getCachedRequest(
1804 messageType,
1805 messageId
1806 );
1807 logger.debug(
1808 `${this.logPrefix()} << Command '${
1809 requestCommandName ?? Constants.UNKNOWN_COMMAND
1810 }' received response payload: ${JSON.stringify(response)}`
1811 );
1812 responseCallback(commandPayload, requestPayload);
1813 }
1814
1815 private handleErrorMessage(errorResponse: ErrorResponse): void {
1816 const [messageType, messageId, errorType, errorMessage, errorDetails] = errorResponse;
1817 if (this.requests.has(messageId) === false) {
1818 // Error
1819 throw new OCPPError(
1820 ErrorType.INTERNAL_ERROR,
1821 `Error response for unknown message id ${messageId}`,
1822 undefined,
1823 { errorType, errorMessage, errorDetails }
1824 );
1825 }
1826 const [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId);
1827 logger.debug(
1828 `${this.logPrefix()} << Command '${
1829 requestCommandName ?? Constants.UNKNOWN_COMMAND
1830 }' received error response payload: ${JSON.stringify(errorResponse)}`
1831 );
1832 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
1833 }
1834
ef7d8c21 1835 private async onMessage(data: RawData): Promise<void> {
56d09fd7 1836 let request: IncomingRequest | Response | ErrorResponse;
b3ec7bc1 1837 let messageType: number;
ded57f02 1838 let errorMsg: string;
c0560973 1839 try {
56d09fd7 1840 request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
53e5fd67 1841 if (Array.isArray(request) === true) {
56d09fd7 1842 [messageType] = request;
b3ec7bc1
JB
1843 // Check the type of message
1844 switch (messageType) {
1845 // Incoming Message
1846 case MessageType.CALL_MESSAGE:
56d09fd7 1847 await this.handleIncomingMessage(request as IncomingRequest);
b3ec7bc1 1848 break;
56d09fd7 1849 // Response Message
b3ec7bc1 1850 case MessageType.CALL_RESULT_MESSAGE:
56d09fd7 1851 this.handleResponseMessage(request as Response);
a2d1c0f1
JB
1852 break;
1853 // Error Message
1854 case MessageType.CALL_ERROR_MESSAGE:
56d09fd7 1855 this.handleErrorMessage(request as ErrorResponse);
b3ec7bc1 1856 break;
56d09fd7 1857 // Unknown Message
b3ec7bc1
JB
1858 default:
1859 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
ded57f02
JB
1860 errorMsg = `Wrong message type ${messageType}`;
1861 logger.error(`${this.logPrefix()} ${errorMsg}`);
1862 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errorMsg);
b3ec7bc1 1863 }
1895299d 1864 parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
47e22477 1865 } else {
53e5fd67 1866 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, {
ba7965c4 1867 request,
ac54a9bb 1868 });
47e22477 1869 }
c0560973 1870 } catch (error) {
56d09fd7
JB
1871 let commandName: IncomingRequestCommand;
1872 let requestCommandName: RequestCommand | IncomingRequestCommand;
1873 let errorCallback: ErrorCallback;
1874 const [, messageId] = request;
13701f69
JB
1875 switch (messageType) {
1876 case MessageType.CALL_MESSAGE:
56d09fd7 1877 [, , commandName] = request as IncomingRequest;
13701f69 1878 // Send error
56d09fd7 1879 await this.ocppRequestService.sendError(this, messageId, error as OCPPError, commandName);
13701f69
JB
1880 break;
1881 case MessageType.CALL_RESULT_MESSAGE:
1882 case MessageType.CALL_ERROR_MESSAGE:
56d09fd7
JB
1883 if (this.requests.has(messageId) === true) {
1884 [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId);
13701f69
JB
1885 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1886 errorCallback(error as OCPPError, false);
1887 } else {
1888 // Remove the request from the cache in case of error at response handling
1889 this.requests.delete(messageId);
1890 }
de4cb8b6 1891 break;
ba7965c4 1892 }
56d09fd7
JB
1893 if (error instanceof OCPPError === false) {
1894 logger.warn(
1895 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1896 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1897 }' message '${data.toString()}' handling is not an OCPPError:`,
1898 error
1899 );
1900 }
1901 logger.error(
1902 `${this.logPrefix()} Incoming OCPP command '${
1903 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1904 }' message '${data.toString()}'${
1905 messageType !== MessageType.CALL_MESSAGE
1906 ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'`
1907 : ''
1908 } processing error:`,
1909 error
1910 );
c0560973 1911 }
2328be1e
JB
1912 }
1913
c0560973 1914 private onPing(): void {
44eb6026 1915 logger.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
c0560973
JB
1916 }
1917
1918 private onPong(): void {
44eb6026 1919 logger.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
c0560973
JB
1920 }
1921
9534e74e 1922 private onError(error: WSError): void {
bcc9c3c0 1923 this.closeWSConnection();
44eb6026 1924 logger.error(`${this.logPrefix()} WebSocket error:`, error);
c0560973
JB
1925 }
1926
18bf8274 1927 private getEnergyActiveImportRegister(connectorStatus: ConnectorStatus, rounded = false): number {
95bdbf12 1928 if (this.getMeteringPerTransaction() === true) {
07989fad 1929 return (
18bf8274 1930 (rounded === true
07989fad
JB
1931 ? Math.round(connectorStatus?.transactionEnergyActiveImportRegisterValue)
1932 : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0
1933 );
1934 }
1935 return (
18bf8274 1936 (rounded === true
07989fad
JB
1937 ? Math.round(connectorStatus?.energyActiveImportRegisterValue)
1938 : connectorStatus?.energyActiveImportRegisterValue) ?? 0
1939 );
1940 }
1941
cda5d0fb
JB
1942 private getUseConnectorId0(stationTemplate?: ChargingStationTemplate): boolean {
1943 return stationTemplate?.useConnectorId0 ?? true;
8bce55bf
JB
1944 }
1945
60ddad53 1946 private async stopRunningTransactions(reason = StopTransactionReason.NONE): Promise<void> {
28e78158
JB
1947 if (this.hasEvses) {
1948 for (const evseStatus of this.evses.values()) {
1949 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
1950 if (connectorStatus.transactionStarted === true) {
1951 await this.stopTransactionOnConnector(connectorId, reason);
1952 }
1953 }
1954 }
1955 } else {
1956 for (const connectorId of this.connectors.keys()) {
1957 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
1958 await this.stopTransactionOnConnector(connectorId, reason);
1959 }
60ddad53
JB
1960 }
1961 }
1962 }
1963
1f761b9a 1964 // 0 for disabling
c72f6634 1965 private getConnectionTimeout(): number {
17ac262c
JB
1966 if (
1967 ChargingStationConfigurationUtils.getConfigurationKey(
1968 this,
1969 StandardParametersKey.ConnectionTimeOut
1970 )
1971 ) {
e7aeea18 1972 return (
17ac262c
JB
1973 parseInt(
1974 ChargingStationConfigurationUtils.getConfigurationKey(
1975 this,
1976 StandardParametersKey.ConnectionTimeOut
1977 ).value
1978 ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
e7aeea18 1979 );
291cb255 1980 }
291cb255 1981 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
1982 }
1983
1f761b9a 1984 // -1 for unlimited, 0 for disabling
72092cfc 1985 private getAutoReconnectMaxRetries(): number | undefined {
b1bbdae5
JB
1986 return (
1987 this.stationInfo.autoReconnectMaxRetries ?? Configuration.getAutoReconnectMaxRetries() ?? -1
1988 );
3574dfd3
JB
1989 }
1990
ec977daf 1991 // 0 for disabling
72092cfc 1992 private getRegistrationMaxRetries(): number | undefined {
b1bbdae5 1993 return this.stationInfo.registrationMaxRetries ?? -1;
32a1eb7a
JB
1994 }
1995
c0560973 1996 private getPowerDivider(): number {
b1bbdae5 1997 let powerDivider = this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors();
fa7bccf4 1998 if (this.stationInfo?.powerSharedByConnectors) {
c0560973 1999 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
2000 }
2001 return powerDivider;
2002 }
2003
fa7bccf4
JB
2004 private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
2005 const maximumPower = this.getMaximumPower(stationInfo);
2006 switch (this.getCurrentOutType(stationInfo)) {
cc6e8ab5
JB
2007 case CurrentType.AC:
2008 return ACElectricUtils.amperagePerPhaseFromPower(
fa7bccf4 2009 this.getNumberOfPhases(stationInfo),
b1bbdae5 2010 maximumPower / (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()),
fa7bccf4 2011 this.getVoltageOut(stationInfo)
cc6e8ab5
JB
2012 );
2013 case CurrentType.DC:
fa7bccf4 2014 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo));
cc6e8ab5
JB
2015 }
2016 }
2017
cc6e8ab5
JB
2018 private getAmperageLimitation(): number | undefined {
2019 if (
5a2a53cf 2020 Utils.isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
17ac262c
JB
2021 ChargingStationConfigurationUtils.getConfigurationKey(
2022 this,
2023 this.stationInfo.amperageLimitationOcppKey
2024 )
cc6e8ab5
JB
2025 ) {
2026 return (
2027 Utils.convertToInt(
17ac262c
JB
2028 ChargingStationConfigurationUtils.getConfigurationKey(
2029 this,
2030 this.stationInfo.amperageLimitationOcppKey
72092cfc 2031 )?.value
17ac262c 2032 ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
cc6e8ab5
JB
2033 );
2034 }
2035 }
2036
c0560973 2037 private async startMessageSequence(): Promise<void> {
b7f9e41d 2038 if (this.stationInfo?.autoRegister === true) {
f7f98c68 2039 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
2040 BootNotificationRequest,
2041 BootNotificationResponse
8bfbc743
JB
2042 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
2043 skipBufferingOnError: true,
2044 });
6114e6f1 2045 }
136c90ba 2046 // Start WebSocket ping
c0560973 2047 this.startWebSocketPing();
5ad8570f 2048 // Start heartbeat
c0560973 2049 this.startHeartbeat();
0a60c33c 2050 // Initialize connectors status
c3b83130
JB
2051 if (this.hasEvses) {
2052 for (const [evseId, evseStatus] of this.evses) {
4334db72
JB
2053 if (evseId > 0) {
2054 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
2055 const connectorBootStatus = ChargingStationUtils.getBootConnectorStatus(
2056 this,
2057 connectorId,
2058 connectorStatus
2059 );
2060 await OCPPServiceUtils.sendAndSetConnectorStatus(
2061 this,
2062 connectorId,
12f26d4a
JB
2063 connectorBootStatus,
2064 evseId
4334db72
JB
2065 );
2066 }
c3b83130 2067 }
4334db72
JB
2068 }
2069 } else {
2070 for (const connectorId of this.connectors.keys()) {
2071 if (connectorId > 0) {
c3b83130
JB
2072 const connectorBootStatus = ChargingStationUtils.getBootConnectorStatus(
2073 this,
2074 connectorId,
4334db72 2075 this.getConnectorStatus(connectorId)
c3b83130
JB
2076 );
2077 await OCPPServiceUtils.sendAndSetConnectorStatus(this, connectorId, connectorBootStatus);
2078 }
2079 }
5ad8570f 2080 }
c9a4f9ea
JB
2081 if (this.stationInfo?.firmwareStatus === FirmwareStatus.Installing) {
2082 await this.ocppRequestService.requestHandler<
2083 FirmwareStatusNotificationRequest,
2084 FirmwareStatusNotificationResponse
2085 >(this, RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
2086 status: FirmwareStatus.Installed,
2087 });
2088 this.stationInfo.firmwareStatus = FirmwareStatus.Installed;
c9a4f9ea 2089 }
3637ca2c 2090
0a60c33c 2091 // Start the ATG
ac7f79af 2092 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable === true) {
4f69be04 2093 this.startAutomaticTransactionGenerator();
fa7bccf4 2094 }
aa428a31 2095 this.wsConnectionRestarted === true && this.flushMessageBuffer();
fa7bccf4
JB
2096 }
2097
e7aeea18
JB
2098 private async stopMessageSequence(
2099 reason: StopTransactionReason = StopTransactionReason.NONE
2100 ): Promise<void> {
136c90ba 2101 // Stop WebSocket ping
c0560973 2102 this.stopWebSocketPing();
79411696 2103 // Stop heartbeat
c0560973 2104 this.stopHeartbeat();
fa7bccf4 2105 // Stop ongoing transactions
b20eb107 2106 if (this.automaticTransactionGenerator?.started === true) {
60ddad53
JB
2107 this.stopAutomaticTransactionGenerator();
2108 } else {
2109 await this.stopRunningTransactions(reason);
79411696 2110 }
039211f9
JB
2111 if (this.hasEvses) {
2112 for (const [evseId, evseStatus] of this.evses) {
2113 if (evseId > 0) {
2114 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
2115 await this.ocppRequestService.requestHandler<
2116 StatusNotificationRequest,
2117 StatusNotificationResponse
2118 >(
2119 this,
2120 RequestCommand.STATUS_NOTIFICATION,
2121 OCPPServiceUtils.buildStatusNotificationRequest(
2122 this,
2123 connectorId,
12f26d4a
JB
2124 ConnectorStatusEnum.Unavailable,
2125 evseId
039211f9
JB
2126 )
2127 );
2128 delete connectorStatus?.status;
2129 }
2130 }
2131 }
2132 } else {
2133 for (const connectorId of this.connectors.keys()) {
2134 if (connectorId > 0) {
2135 await this.ocppRequestService.requestHandler<
2136 StatusNotificationRequest,
2137 StatusNotificationResponse
2138 >(
6e939d9e 2139 this,
039211f9
JB
2140 RequestCommand.STATUS_NOTIFICATION,
2141 OCPPServiceUtils.buildStatusNotificationRequest(
2142 this,
2143 connectorId,
2144 ConnectorStatusEnum.Unavailable
2145 )
2146 );
2147 delete this.getConnectorStatus(connectorId)?.status;
2148 }
45c0ae82
JB
2149 }
2150 }
79411696
JB
2151 }
2152
c0560973 2153 private startWebSocketPing(): void {
17ac262c
JB
2154 const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey(
2155 this,
e7aeea18
JB
2156 StandardParametersKey.WebSocketPingInterval
2157 )
2158 ? Utils.convertToInt(
17ac262c
JB
2159 ChargingStationConfigurationUtils.getConfigurationKey(
2160 this,
2161 StandardParametersKey.WebSocketPingInterval
72092cfc 2162 )?.value
e7aeea18 2163 )
9cd3dfb0 2164 : 0;
ad2f27c3
JB
2165 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
2166 this.webSocketPingSetInterval = setInterval(() => {
56eb297e 2167 if (this.isWebSocketConnectionOpened() === true) {
72092cfc 2168 this.wsConnection?.ping();
136c90ba
JB
2169 }
2170 }, webSocketPingInterval * 1000);
e7aeea18 2171 logger.info(
44eb6026
JB
2172 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
2173 webSocketPingInterval
2174 )}`
e7aeea18 2175 );
ad2f27c3 2176 } else if (this.webSocketPingSetInterval) {
e7aeea18 2177 logger.info(
44eb6026
JB
2178 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
2179 webSocketPingInterval
2180 )}`
e7aeea18 2181 );
136c90ba 2182 } else {
e7aeea18 2183 logger.error(
8f953431 2184 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
e7aeea18 2185 );
136c90ba
JB
2186 }
2187 }
2188
c0560973 2189 private stopWebSocketPing(): void {
ad2f27c3
JB
2190 if (this.webSocketPingSetInterval) {
2191 clearInterval(this.webSocketPingSetInterval);
dfe81c8f 2192 delete this.webSocketPingSetInterval;
136c90ba
JB
2193 }
2194 }
2195
1f5df42a 2196 private getConfiguredSupervisionUrl(): URL {
d5c3df49 2197 let configuredSupervisionUrl: string;
72092cfc 2198 const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls();
53ac516c 2199 if (Utils.isNotEmptyArray(supervisionUrls)) {
269de583 2200 let configuredSupervisionUrlIndex: number;
2dcfe98e 2201 switch (Configuration.getSupervisionUrlDistribution()) {
2dcfe98e 2202 case SupervisionUrlDistribution.RANDOM:
269de583 2203 configuredSupervisionUrlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
2dcfe98e 2204 break;
a52a6446 2205 case SupervisionUrlDistribution.ROUND_ROBIN:
c72f6634 2206 case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY:
2dcfe98e 2207 default:
a52a6446
JB
2208 Object.values(SupervisionUrlDistribution).includes(
2209 Configuration.getSupervisionUrlDistribution()
2210 ) === false &&
2211 logger.error(
2212 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2213 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2214 }`
2215 );
269de583 2216 configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
2dcfe98e 2217 break;
c0560973 2218 }
d5c3df49
JB
2219 configuredSupervisionUrl = supervisionUrls[configuredSupervisionUrlIndex];
2220 } else {
2221 configuredSupervisionUrl = supervisionUrls as string;
2222 }
2223 if (Utils.isNotEmptyString(configuredSupervisionUrl)) {
2224 return new URL(configuredSupervisionUrl);
c0560973 2225 }
49c508b0 2226 const errorMsg = 'No supervision url(s) configured';
7f77d16f
JB
2227 logger.error(`${this.logPrefix()} ${errorMsg}`);
2228 throw new BaseError(`${errorMsg}`);
136c90ba
JB
2229 }
2230
c0560973 2231 private stopHeartbeat(): void {
ad2f27c3
JB
2232 if (this.heartbeatSetInterval) {
2233 clearInterval(this.heartbeatSetInterval);
dfe81c8f 2234 delete this.heartbeatSetInterval;
7dde0b73 2235 }
5ad8570f
JB
2236 }
2237
55516218 2238 private terminateWSConnection(): void {
56eb297e 2239 if (this.isWebSocketConnectionOpened() === true) {
72092cfc 2240 this.wsConnection?.terminate();
55516218
JB
2241 this.wsConnection = null;
2242 }
2243 }
2244
c72f6634 2245 private getReconnectExponentialDelay(): boolean {
a14885a3 2246 return this.stationInfo?.reconnectExponentialDelay ?? false;
5ad8570f
JB
2247 }
2248
aa428a31 2249 private async reconnect(): Promise<void> {
7874b0b1
JB
2250 // Stop WebSocket ping
2251 this.stopWebSocketPing();
136c90ba 2252 // Stop heartbeat
c0560973 2253 this.stopHeartbeat();
5ad8570f 2254 // Stop the ATG if needed
ac7f79af 2255 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure === true) {
fa7bccf4 2256 this.stopAutomaticTransactionGenerator();
ad2f27c3 2257 }
e7aeea18
JB
2258 if (
2259 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
2260 this.getAutoReconnectMaxRetries() === -1
2261 ) {
1fe0632a 2262 ++this.autoReconnectRetryCount;
e7aeea18
JB
2263 const reconnectDelay = this.getReconnectExponentialDelay()
2264 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
2265 : this.getConnectionTimeout() * 1000;
1e080116
JB
2266 const reconnectDelayWithdraw = 1000;
2267 const reconnectTimeout =
2268 reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0
2269 ? reconnectDelay - reconnectDelayWithdraw
2270 : 0;
e7aeea18 2271 logger.error(
d56ea27c 2272 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
e7aeea18
JB
2273 reconnectDelay,
2274 2
2275 )}ms, timeout ${reconnectTimeout}ms`
2276 );
032d6efc 2277 await Utils.sleep(reconnectDelay);
e7aeea18 2278 logger.error(
44eb6026 2279 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
e7aeea18
JB
2280 );
2281 this.openWSConnection(
59b6ed8d 2282 {
abe9e9dd 2283 ...(this.stationInfo?.wsOptions ?? {}),
59b6ed8d
JB
2284 handshakeTimeout: reconnectTimeout,
2285 },
1e080116 2286 { closeOpened: true }
e7aeea18 2287 );
265e4266 2288 this.wsConnectionRestarted = true;
c0560973 2289 } else if (this.getAutoReconnectMaxRetries() !== -1) {
e7aeea18 2290 logger.error(
d56ea27c 2291 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
e7aeea18 2292 this.autoReconnectRetryCount
d56ea27c 2293 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
e7aeea18 2294 );
5ad8570f
JB
2295 }
2296 }
7dde0b73 2297}