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