refactor: cleanup log messages
[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(
04c32a95 595 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`,
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
04c32a95 602 ${connectorId}`,
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;
42371a2e 1028 if (interval > 0) {
04c32a95
JB
1029 logger.info(
1030 `${this.logPrefix()} Reservation expiration date checks started every ${formatDurationMilliSeconds(
1031 interval,
1032 )}`,
1033 );
37aa4e56 1034 this.reservationExpirationSetInterval = setInterval((): void => {
354c3fbe 1035 const currentDate = new Date();
42371a2e
JB
1036 if (this.hasEvses) {
1037 for (const evseStatus of this.evses.values()) {
1038 for (const connectorStatus of evseStatus.connectors.values()) {
354c3fbe
JB
1039 if (
1040 connectorStatus.reservation &&
1041 connectorStatus.reservation.expiryDate < currentDate
1042 ) {
37aa4e56 1043 this.removeReservation(
8cc482a9 1044 connectorStatus.reservation,
42371a2e 1045 ReservationTerminationReason.EXPIRED,
37aa4e56 1046 ).catch(Constants.EMPTY_FUNCTION);
42371a2e
JB
1047 }
1048 }
1049 }
1050 } else {
1051 for (const connectorStatus of this.connectors.values()) {
354c3fbe
JB
1052 if (
1053 connectorStatus.reservation &&
1054 connectorStatus.reservation.expiryDate < currentDate
1055 ) {
37aa4e56 1056 this.removeReservation(
8cc482a9 1057 connectorStatus.reservation,
5edd8ba0 1058 ReservationTerminationReason.EXPIRED,
37aa4e56 1059 ).catch(Constants.EMPTY_FUNCTION);
66dd3447
JB
1060 }
1061 }
1062 }
42371a2e
JB
1063 }, interval);
1064 }
d193a949
JB
1065 }
1066
1067 public restartReservationExpiryDateSetInterval(): void {
178956d8
JB
1068 this.stopReservationExpirationSetInterval();
1069 this.startReservationExpirationSetInterval();
d193a949
JB
1070 }
1071
1072 public validateIncomingRequestWithReservation(connectorId: number, idTag: string): boolean {
3fa7f799 1073 return this.getReservationBy(ReservationFilterKey.CONNECTOR_ID, connectorId)?.idTag === idTag;
d193a949
JB
1074 }
1075
1076 public isConnectorReservable(
1077 reservationId: number,
66dd3447 1078 idTag?: string,
5edd8ba0 1079 connectorId?: number,
d193a949 1080 ): boolean {
ea5d5eef 1081 const [alreadyExists] = this.doesReservationExists({ id: reservationId });
d193a949
JB
1082 if (alreadyExists) {
1083 return alreadyExists;
24578c31 1084 }
9bf0ef23 1085 const userReservedAlready = isUndefined(
e1d9a0f4 1086 this.getReservationBy(ReservationFilterKey.ID_TAG, idTag!),
66dd3447
JB
1087 )
1088 ? false
1089 : true;
e1d9a0f4 1090 const notConnectorZero = isUndefined(connectorId) ? true : connectorId! > 0;
d193a949
JB
1091 const freeConnectorsAvailable = this.getNumberOfReservableConnectors() > 0;
1092 return !alreadyExists && !userReservedAlready && notConnectorZero && freeConnectorsAvailable;
1093 }
1094
1095 private getNumberOfReservableConnectors(): number {
1096 let reservableConnectors = 0;
66dd3447 1097 if (this.hasEvses) {
3fa7f799 1098 for (const evseStatus of this.evses.values()) {
fba11dc6 1099 reservableConnectors += countReservableConnectors(evseStatus.connectors);
66dd3447
JB
1100 }
1101 } else {
fba11dc6 1102 reservableConnectors = countReservableConnectors(this.connectors);
66dd3447
JB
1103 }
1104 return reservableConnectors - this.getNumberOfReservationsOnConnectorZero();
1105 }
1106
d193a949 1107 private getNumberOfReservationsOnConnectorZero(): number {
66dd3447 1108 let numberOfReservations = 0;
3fa7f799
JB
1109 if (this.hasEvses && this.evses.get(0)?.connectors.get(0)?.reservation) {
1110 ++numberOfReservations;
66dd3447
JB
1111 } else if (this.connectors.get(0)?.reservation) {
1112 ++numberOfReservations;
1113 }
1114 return numberOfReservations;
24578c31
JB
1115 }
1116
f90c1757 1117 private flushMessageBuffer(): void {
8e242273 1118 if (this.messageBuffer.size > 0) {
7d3b0f64 1119 for (const message of this.messageBuffer.values()) {
e1d9a0f4
JB
1120 let beginId: string | undefined;
1121 let commandName: RequestCommand | undefined;
8ca6874c 1122 const [messageType] = JSON.parse(message) as OutgoingRequest | Response | ErrorResponse;
1431af78
JB
1123 const isRequest = messageType === MessageType.CALL_MESSAGE;
1124 if (isRequest) {
1125 [, , commandName] = JSON.parse(message) as OutgoingRequest;
1126 beginId = PerformanceStatistics.beginMeasure(commandName);
1127 }
72092cfc 1128 this.wsConnection?.send(message);
e1d9a0f4 1129 isRequest && PerformanceStatistics.endMeasure(commandName!, beginId!);
8ca6874c
JB
1130 logger.debug(
1131 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
5edd8ba0
JB
1132 messageType,
1133 )} payload sent: ${message}`,
8ca6874c 1134 );
8e242273 1135 this.messageBuffer.delete(message);
7d3b0f64 1136 }
77f00f84
JB
1137 }
1138 }
1139
1f5df42a
JB
1140 private getSupervisionUrlOcppConfiguration(): boolean {
1141 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
12fc74d6
JB
1142 }
1143
178956d8
JB
1144 private stopReservationExpirationSetInterval(): void {
1145 if (this.reservationExpirationSetInterval) {
1146 clearInterval(this.reservationExpirationSetInterval);
d193a949 1147 }
24578c31
JB
1148 }
1149
e8e865ea 1150 private getSupervisionUrlOcppKey(): string {
6dad8e21 1151 return this.stationInfo.supervisionUrlOcppKey ?? VendorParametersKey.ConnectionUrl;
e8e865ea
JB
1152 }
1153
72092cfc 1154 private getTemplateFromFile(): ChargingStationTemplate | undefined {
e1d9a0f4 1155 let template: ChargingStationTemplate | undefined;
5ad8570f 1156 try {
cda5d0fb
JB
1157 if (this.sharedLRUCache.hasChargingStationTemplate(this.templateFileHash)) {
1158 template = this.sharedLRUCache.getChargingStationTemplate(this.templateFileHash);
7c72977b
JB
1159 } else {
1160 const measureId = `${FileType.ChargingStationTemplate} read`;
1161 const beginId = PerformanceStatistics.beginMeasure(measureId);
d972af76 1162 template = JSON.parse(readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate;
7c72977b 1163 PerformanceStatistics.endMeasure(measureId, beginId);
d972af76 1164 template.templateHash = createHash(Constants.DEFAULT_HASH_ALGORITHM)
7c72977b
JB
1165 .update(JSON.stringify(template))
1166 .digest('hex');
57adbebc 1167 this.sharedLRUCache.setChargingStationTemplate(template);
cda5d0fb 1168 this.templateFileHash = template.templateHash;
7c72977b 1169 }
5ad8570f 1170 } catch (error) {
fa5995d6 1171 handleFileException(
2484ac1e 1172 this.templateFile,
7164966d
JB
1173 FileType.ChargingStationTemplate,
1174 error as NodeJS.ErrnoException,
5edd8ba0 1175 this.logPrefix(),
e7aeea18 1176 );
5ad8570f 1177 }
2484ac1e
JB
1178 return template;
1179 }
1180
7a3a2ebb 1181 private getStationInfoFromTemplate(): ChargingStationInfo {
e1d9a0f4 1182 const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile()!;
fba11dc6
JB
1183 checkTemplate(stationTemplate, this.logPrefix(), this.templateFile);
1184 warnTemplateKeysDeprecation(stationTemplate, this.logPrefix(), this.templateFile);
8a133cc8 1185 if (stationTemplate?.Connectors) {
fba11dc6 1186 checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile);
8a133cc8 1187 }
fba11dc6
JB
1188 const stationInfo: ChargingStationInfo = stationTemplateToStationInfo(stationTemplate);
1189 stationInfo.hashId = getHashId(this.index, stationTemplate);
1190 stationInfo.chargingStationId = getChargingStationId(this.index, stationTemplate);
72092cfc 1191 stationInfo.ocppVersion = stationTemplate?.ocppVersion ?? OCPPVersion.VERSION_16;
fba11dc6 1192 createSerialNumber(stationTemplate, stationInfo);
9bf0ef23 1193 if (isNotEmptyArray(stationTemplate?.power)) {
551e477c 1194 stationTemplate.power = stationTemplate.power as number[];
9bf0ef23 1195 const powerArrayRandomIndex = Math.floor(secureRandom() * stationTemplate.power.length);
cc6e8ab5 1196 stationInfo.maximumPower =
72092cfc 1197 stationTemplate?.powerUnit === PowerUnits.KILO_WATT
fa7bccf4
JB
1198 ? stationTemplate.power[powerArrayRandomIndex] * 1000
1199 : stationTemplate.power[powerArrayRandomIndex];
5ad8570f 1200 } else {
551e477c 1201 stationTemplate.power = stationTemplate?.power as number;
cc6e8ab5 1202 stationInfo.maximumPower =
72092cfc 1203 stationTemplate?.powerUnit === PowerUnits.KILO_WATT
fa7bccf4
JB
1204 ? stationTemplate.power * 1000
1205 : stationTemplate.power;
1206 }
3637ca2c 1207 stationInfo.firmwareVersionPattern =
72092cfc 1208 stationTemplate?.firmwareVersionPattern ?? Constants.SEMVER_PATTERN;
3637ca2c 1209 if (
9bf0ef23 1210 isNotEmptyString(stationInfo.firmwareVersion) &&
e1d9a0f4 1211 new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion!) === false
3637ca2c
JB
1212 ) {
1213 logger.warn(
1214 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1215 this.templateFile
5edd8ba0 1216 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`,
3637ca2c
JB
1217 );
1218 }
598c886d 1219 stationInfo.firmwareUpgrade = merge<FirmwareUpgrade>(
15748260 1220 {
598c886d
JB
1221 versionUpgrade: {
1222 step: 1,
1223 },
15748260
JB
1224 reset: true,
1225 },
5edd8ba0 1226 stationTemplate?.firmwareUpgrade ?? {},
15748260 1227 );
9bf0ef23 1228 stationInfo.resetTime = !isNullOrUndefined(stationTemplate?.resetTime)
e1d9a0f4 1229 ? stationTemplate.resetTime! * 1000
e7aeea18 1230 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
fa7bccf4 1231 stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo);
9ac86a7e 1232 return stationInfo;
5ad8570f
JB
1233 }
1234
551e477c
JB
1235 private getStationInfoFromFile(): ChargingStationInfo | undefined {
1236 let stationInfo: ChargingStationInfo | undefined;
f832e5df
JB
1237 if (this.getStationInfoPersistentConfiguration()) {
1238 stationInfo = this.getConfigurationFromFile()?.stationInfo;
1239 if (stationInfo) {
1240 delete stationInfo?.infoHash;
1241 }
1242 }
f765beaa 1243 return stationInfo;
2484ac1e
JB
1244 }
1245
1246 private getStationInfo(): ChargingStationInfo {
1247 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
551e477c 1248 const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile();
6b90dcca
JB
1249 // Priority:
1250 // 1. charging station info from template
1251 // 2. charging station info from configuration file
f765beaa 1252 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
e1d9a0f4 1253 return stationInfoFromFile!;
f765beaa 1254 }
fec4d204 1255 stationInfoFromFile &&
fba11dc6 1256 propagateSerialNumber(
e1d9a0f4 1257 this.getTemplateFromFile()!,
fec4d204 1258 stationInfoFromFile,
5edd8ba0 1259 stationInfoFromTemplate,
fec4d204 1260 );
01efc60a 1261 return stationInfoFromTemplate;
2484ac1e
JB
1262 }
1263
1264 private saveStationInfo(): void {
ccb1d6e9 1265 if (this.getStationInfoPersistentConfiguration()) {
b1bbdae5 1266 this.saveConfiguration();
ccb1d6e9 1267 }
2484ac1e
JB
1268 }
1269
e8e865ea 1270 private getOcppPersistentConfiguration(): boolean {
ccb1d6e9
JB
1271 return this.stationInfo?.ocppPersistentConfiguration ?? true;
1272 }
1273
1274 private getStationInfoPersistentConfiguration(): boolean {
1275 return this.stationInfo?.stationInfoPersistentConfiguration ?? true;
e8e865ea
JB
1276 }
1277
5ced7e80
JB
1278 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1279 return this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration ?? true;
1280 }
1281
c0560973 1282 private handleUnsupportedVersion(version: OCPPVersion) {
66dd3447
JB
1283 const errorMsg = `Unsupported protocol version '${version}' configured
1284 in template file ${this.templateFile}`;
ded57f02
JB
1285 logger.error(`${this.logPrefix()} ${errorMsg}`);
1286 throw new BaseError(errorMsg);
c0560973
JB
1287 }
1288
2484ac1e 1289 private initialize(): void {
e1d9a0f4 1290 const stationTemplate = this.getTemplateFromFile()!;
fba11dc6 1291 checkTemplate(stationTemplate, this.logPrefix(), this.templateFile);
d972af76
JB
1292 this.configurationFile = join(
1293 dirname(this.templateFile.replace('station-templates', 'configurations')),
5edd8ba0 1294 `${getHashId(this.index, stationTemplate)}.json`,
0642c3d2 1295 );
a4f7c75f 1296 const chargingStationConfiguration = this.getConfigurationFromFile();
a4f7c75f 1297 if (
ba01a213 1298 chargingStationConfiguration?.stationInfo?.templateHash === stationTemplate?.templateHash &&
e1d9a0f4 1299 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
a4f7c75f
JB
1300 (chargingStationConfiguration?.connectorsStatus || chargingStationConfiguration?.evsesStatus)
1301 ) {
1302 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration);
1303 } else {
1304 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate);
1305 }
b44b779a 1306 this.stationInfo = this.getStationInfo();
3637ca2c
JB
1307 if (
1308 this.stationInfo.firmwareStatus === FirmwareStatus.Installing &&
9bf0ef23
JB
1309 isNotEmptyString(this.stationInfo.firmwareVersion) &&
1310 isNotEmptyString(this.stationInfo.firmwareVersionPattern)
3637ca2c 1311 ) {
d812bdcb 1312 const patternGroup: number | undefined =
15748260 1313 this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ??
d812bdcb 1314 this.stationInfo.firmwareVersion?.split('.').length;
e1d9a0f4
JB
1315 const match = this.stationInfo
1316 .firmwareVersion!.match(new RegExp(this.stationInfo.firmwareVersionPattern!))!
1317 .slice(1, patternGroup! + 1);
3637ca2c 1318 const patchLevelIndex = match.length - 1;
5d280aae 1319 match[patchLevelIndex] = (
9bf0ef23 1320 convertToInt(match[patchLevelIndex]) +
e1d9a0f4 1321 this.stationInfo.firmwareUpgrade!.versionUpgrade!.step!
5d280aae 1322 ).toString();
72092cfc 1323 this.stationInfo.firmwareVersion = match?.join('.');
3637ca2c 1324 }
6bccfcbc 1325 this.saveStationInfo();
6bccfcbc
JB
1326 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
1327 if (this.getEnableStatistics() === true) {
1328 this.performanceStatistics = PerformanceStatistics.getInstance(
1329 this.stationInfo.hashId,
e1d9a0f4 1330 this.stationInfo.chargingStationId!,
5edd8ba0 1331 this.configuredSupervisionUrl,
6bccfcbc
JB
1332 );
1333 }
fba11dc6 1334 this.bootNotificationRequest = createBootNotificationRequest(this.stationInfo);
692f2f64
JB
1335 this.powerDivider = this.getPowerDivider();
1336 // OCPP configuration
1337 this.ocppConfiguration = this.getOcppConfiguration();
1338 this.initializeOcppConfiguration();
1339 this.initializeOcppServices();
1340 if (this.stationInfo?.autoRegister === true) {
1341 this.bootNotificationResponse = {
1342 currentTime: new Date(),
1343 interval: this.getHeartbeatInterval() / 1000,
1344 status: RegistrationStatusEnumType.ACCEPTED,
1345 };
1346 }
147d0e0f
JB
1347 }
1348
feff11ec
JB
1349 private initializeOcppServices(): void {
1350 const ocppVersion = this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
1351 switch (ocppVersion) {
1352 case OCPPVersion.VERSION_16:
1353 this.ocppIncomingRequestService =
1354 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
1355 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
5edd8ba0 1356 OCPP16ResponseService.getInstance<OCPP16ResponseService>(),
feff11ec
JB
1357 );
1358 break;
1359 case OCPPVersion.VERSION_20:
1360 case OCPPVersion.VERSION_201:
1361 this.ocppIncomingRequestService =
1362 OCPP20IncomingRequestService.getInstance<OCPP20IncomingRequestService>();
1363 this.ocppRequestService = OCPP20RequestService.getInstance<OCPP20RequestService>(
5edd8ba0 1364 OCPP20ResponseService.getInstance<OCPP20ResponseService>(),
feff11ec
JB
1365 );
1366 break;
1367 default:
1368 this.handleUnsupportedVersion(ocppVersion);
1369 break;
1370 }
1371 }
1372
2484ac1e 1373 private initializeOcppConfiguration(): void {
f2d5e3d9
JB
1374 if (!getConfigurationKey(this, StandardParametersKey.HeartbeatInterval)) {
1375 addConfigurationKey(this, StandardParametersKey.HeartbeatInterval, '0');
f0f65a62 1376 }
f2d5e3d9
JB
1377 if (!getConfigurationKey(this, StandardParametersKey.HeartBeatInterval)) {
1378 addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', { visible: false });
f0f65a62 1379 }
e7aeea18
JB
1380 if (
1381 this.getSupervisionUrlOcppConfiguration() &&
9bf0ef23 1382 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
f2d5e3d9 1383 !getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e7aeea18 1384 ) {
f2d5e3d9 1385 addConfigurationKey(
17ac262c 1386 this,
a59737e3 1387 this.getSupervisionUrlOcppKey(),
fa7bccf4 1388 this.configuredSupervisionUrl.href,
5edd8ba0 1389 { reboot: true },
e7aeea18 1390 );
e6895390
JB
1391 } else if (
1392 !this.getSupervisionUrlOcppConfiguration() &&
9bf0ef23 1393 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
f2d5e3d9 1394 getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e6895390 1395 ) {
f2d5e3d9 1396 deleteConfigurationKey(this, this.getSupervisionUrlOcppKey(), { save: false });
12fc74d6 1397 }
cc6e8ab5 1398 if (
9bf0ef23 1399 isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
f2d5e3d9 1400 !getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)
cc6e8ab5 1401 ) {
f2d5e3d9 1402 addConfigurationKey(
17ac262c 1403 this,
e1d9a0f4 1404 this.stationInfo.amperageLimitationOcppKey!,
17ac262c 1405 (
e1d9a0f4 1406 this.stationInfo.maximumAmperage! * getAmperageLimitationUnitDivider(this.stationInfo)
5edd8ba0 1407 ).toString(),
cc6e8ab5
JB
1408 );
1409 }
f2d5e3d9
JB
1410 if (!getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)) {
1411 addConfigurationKey(
17ac262c 1412 this,
e7aeea18 1413 StandardParametersKey.SupportedFeatureProfiles,
5edd8ba0 1414 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`,
e7aeea18
JB
1415 );
1416 }
f2d5e3d9 1417 addConfigurationKey(
17ac262c 1418 this,
e7aeea18
JB
1419 StandardParametersKey.NumberOfConnectors,
1420 this.getNumberOfConnectors().toString(),
a95873d8 1421 { readonly: true },
5edd8ba0 1422 { overwrite: true },
e7aeea18 1423 );
f2d5e3d9
JB
1424 if (!getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData)) {
1425 addConfigurationKey(
17ac262c 1426 this,
e7aeea18 1427 StandardParametersKey.MeterValuesSampledData,
5edd8ba0 1428 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
e7aeea18 1429 );
7abfea5f 1430 }
f2d5e3d9 1431 if (!getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation)) {
dd08d43d 1432 const connectorsPhaseRotation: string[] = [];
28e78158
JB
1433 if (this.hasEvses) {
1434 for (const evseStatus of this.evses.values()) {
1435 for (const connectorId of evseStatus.connectors.keys()) {
dd08d43d 1436 connectorsPhaseRotation.push(
e1d9a0f4 1437 getPhaseRotationValue(connectorId, this.getNumberOfPhases())!,
dd08d43d 1438 );
28e78158
JB
1439 }
1440 }
1441 } else {
1442 for (const connectorId of this.connectors.keys()) {
dd08d43d 1443 connectorsPhaseRotation.push(
e1d9a0f4 1444 getPhaseRotationValue(connectorId, this.getNumberOfPhases())!,
dd08d43d 1445 );
7e1dc878
JB
1446 }
1447 }
f2d5e3d9 1448 addConfigurationKey(
17ac262c 1449 this,
e7aeea18 1450 StandardParametersKey.ConnectorPhaseRotation,
5edd8ba0 1451 connectorsPhaseRotation.toString(),
e7aeea18 1452 );
7e1dc878 1453 }
f2d5e3d9
JB
1454 if (!getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests)) {
1455 addConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
36f6a92e 1456 }
17ac262c 1457 if (
f2d5e3d9
JB
1458 !getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled) &&
1459 getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)?.value?.includes(
1460 SupportedFeatureProfiles.LocalAuthListManagement,
17ac262c
JB
1461 )
1462 ) {
f2d5e3d9
JB
1463 addConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled, 'false');
1464 }
1465 if (!getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) {
1466 addConfigurationKey(
17ac262c 1467 this,
e7aeea18 1468 StandardParametersKey.ConnectionTimeOut,
5edd8ba0 1469 Constants.DEFAULT_CONNECTION_TIMEOUT.toString(),
e7aeea18 1470 );
8bce55bf 1471 }
2484ac1e 1472 this.saveOcppConfiguration();
073bd098
JB
1473 }
1474
a4f7c75f
JB
1475 private initializeConnectorsOrEvsesFromFile(configuration: ChargingStationConfiguration): void {
1476 if (configuration?.connectorsStatus && !configuration?.evsesStatus) {
8df5ae48 1477 for (const [connectorId, connectorStatus] of configuration.connectorsStatus.entries()) {
9bf0ef23 1478 this.connectors.set(connectorId, cloneObject<ConnectorStatus>(connectorStatus));
8df5ae48 1479 }
a4f7c75f
JB
1480 } else if (configuration?.evsesStatus && !configuration?.connectorsStatus) {
1481 for (const [evseId, evseStatusConfiguration] of configuration.evsesStatus.entries()) {
9bf0ef23 1482 const evseStatus = cloneObject<EvseStatusConfiguration>(evseStatusConfiguration);
a4f7c75f
JB
1483 delete evseStatus.connectorsStatus;
1484 this.evses.set(evseId, {
8df5ae48 1485 ...(evseStatus as EvseStatus),
a4f7c75f 1486 connectors: new Map<number, ConnectorStatus>(
e1d9a0f4 1487 evseStatusConfiguration.connectorsStatus!.map((connectorStatus, connectorId) => [
a4f7c75f
JB
1488 connectorId,
1489 connectorStatus,
5edd8ba0 1490 ]),
a4f7c75f
JB
1491 ),
1492 });
1493 }
1494 } else if (configuration?.evsesStatus && configuration?.connectorsStatus) {
1495 const errorMsg = `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1496 logger.error(`${this.logPrefix()} ${errorMsg}`);
1497 throw new BaseError(errorMsg);
1498 } else {
1499 const errorMsg = `No connectors or evses defined in configuration file ${this.configurationFile}`;
1500 logger.error(`${this.logPrefix()} ${errorMsg}`);
1501 throw new BaseError(errorMsg);
1502 }
1503 }
1504
34eeb1fb 1505 private initializeConnectorsOrEvsesFromTemplate(stationTemplate: ChargingStationTemplate) {
cda5d0fb 1506 if (stationTemplate?.Connectors && !stationTemplate?.Evses) {
34eeb1fb 1507 this.initializeConnectorsFromTemplate(stationTemplate);
cda5d0fb 1508 } else if (stationTemplate?.Evses && !stationTemplate?.Connectors) {
34eeb1fb 1509 this.initializeEvsesFromTemplate(stationTemplate);
cda5d0fb 1510 } else if (stationTemplate?.Evses && stationTemplate?.Connectors) {
ae25f265
JB
1511 const errorMsg = `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1512 logger.error(`${this.logPrefix()} ${errorMsg}`);
1513 throw new BaseError(errorMsg);
1514 } else {
1515 const errorMsg = `No connectors or evses defined in template file ${this.templateFile}`;
1516 logger.error(`${this.logPrefix()} ${errorMsg}`);
1517 throw new BaseError(errorMsg);
1518 }
1519 }
1520
34eeb1fb 1521 private initializeConnectorsFromTemplate(stationTemplate: ChargingStationTemplate): void {
cda5d0fb 1522 if (!stationTemplate?.Connectors && this.connectors.size === 0) {
ded57f02
JB
1523 const errorMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1524 logger.error(`${this.logPrefix()} ${errorMsg}`);
1525 throw new BaseError(errorMsg);
3d25cc86 1526 }
e1d9a0f4 1527 if (!stationTemplate?.Connectors?.[0]) {
3d25cc86
JB
1528 logger.warn(
1529 `${this.logPrefix()} Charging station information from template ${
1530 this.templateFile
5edd8ba0 1531 } with no connector id 0 configuration`,
3d25cc86
JB
1532 );
1533 }
cda5d0fb
JB
1534 if (stationTemplate?.Connectors) {
1535 const { configuredMaxConnectors, templateMaxConnectors, templateMaxAvailableConnectors } =
fba11dc6 1536 checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile);
d972af76 1537 const connectorsConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM)
cda5d0fb 1538 .update(
5edd8ba0 1539 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`,
cda5d0fb 1540 )
3d25cc86
JB
1541 .digest('hex');
1542 const connectorsConfigChanged =
1543 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1544 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1545 connectorsConfigChanged && this.connectors.clear();
1546 this.connectorsConfigurationHash = connectorsConfigHash;
269196a8
JB
1547 if (templateMaxConnectors > 0) {
1548 for (let connectorId = 0; connectorId <= configuredMaxConnectors; connectorId++) {
1549 if (
1550 connectorId === 0 &&
cda5d0fb
JB
1551 (!stationTemplate?.Connectors[connectorId] ||
1552 this.getUseConnectorId0(stationTemplate) === false)
269196a8
JB
1553 ) {
1554 continue;
1555 }
1556 const templateConnectorId =
cda5d0fb 1557 connectorId > 0 && stationTemplate?.randomConnectors
9bf0ef23 1558 ? getRandomInteger(templateMaxAvailableConnectors, 1)
269196a8 1559 : connectorId;
cda5d0fb 1560 const connectorStatus = stationTemplate?.Connectors[templateConnectorId];
fba11dc6 1561 checkStationInfoConnectorStatus(
ae25f265 1562 templateConnectorId,
04b1261c
JB
1563 connectorStatus,
1564 this.logPrefix(),
5edd8ba0 1565 this.templateFile,
04b1261c 1566 );
9bf0ef23 1567 this.connectors.set(connectorId, cloneObject<ConnectorStatus>(connectorStatus));
3d25cc86 1568 }
fba11dc6 1569 initializeConnectorsMapStatus(this.connectors, this.logPrefix());
52952bf8 1570 this.saveConnectorsStatus();
ae25f265
JB
1571 } else {
1572 logger.warn(
1573 `${this.logPrefix()} Charging station information from template ${
1574 this.templateFile
5edd8ba0 1575 } with no connectors configuration defined, cannot create connectors`,
ae25f265 1576 );
3d25cc86
JB
1577 }
1578 }
1579 } else {
1580 logger.warn(
1581 `${this.logPrefix()} Charging station information from template ${
1582 this.templateFile
5edd8ba0 1583 } with no connectors configuration defined, using already defined connectors`,
3d25cc86
JB
1584 );
1585 }
3d25cc86
JB
1586 }
1587
34eeb1fb 1588 private initializeEvsesFromTemplate(stationTemplate: ChargingStationTemplate): void {
cda5d0fb 1589 if (!stationTemplate?.Evses && this.evses.size === 0) {
ded57f02
JB
1590 const errorMsg = `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1591 logger.error(`${this.logPrefix()} ${errorMsg}`);
1592 throw new BaseError(errorMsg);
2585c6e9 1593 }
e1d9a0f4 1594 if (!stationTemplate?.Evses?.[0]) {
2585c6e9
JB
1595 logger.warn(
1596 `${this.logPrefix()} Charging station information from template ${
1597 this.templateFile
5edd8ba0 1598 } with no evse id 0 configuration`,
2585c6e9
JB
1599 );
1600 }
e1d9a0f4 1601 if (!stationTemplate?.Evses?.[0]?.Connectors?.[0]) {
59a0f26d
JB
1602 logger.warn(
1603 `${this.logPrefix()} Charging station information from template ${
1604 this.templateFile
5edd8ba0 1605 } with evse id 0 with no connector id 0 configuration`,
59a0f26d
JB
1606 );
1607 }
cda5d0fb 1608 if (stationTemplate?.Evses) {
d972af76 1609 const evsesConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM)
ba01a213 1610 .update(JSON.stringify(stationTemplate?.Evses))
2585c6e9
JB
1611 .digest('hex');
1612 const evsesConfigChanged =
1613 this.evses?.size !== 0 && this.evsesConfigurationHash !== evsesConfigHash;
1614 if (this.evses?.size === 0 || evsesConfigChanged) {
1615 evsesConfigChanged && this.evses.clear();
1616 this.evsesConfigurationHash = evsesConfigHash;
fba11dc6 1617 const templateMaxEvses = getMaxNumberOfEvses(stationTemplate?.Evses);
ae25f265 1618 if (templateMaxEvses > 0) {
cda5d0fb 1619 for (const evse in stationTemplate.Evses) {
9bf0ef23 1620 const evseId = convertToInt(evse);
52952bf8 1621 this.evses.set(evseId, {
fba11dc6 1622 connectors: buildConnectorsMap(
cda5d0fb 1623 stationTemplate?.Evses[evse]?.Connectors,
ae25f265 1624 this.logPrefix(),
5edd8ba0 1625 this.templateFile,
ae25f265
JB
1626 ),
1627 availability: AvailabilityType.Operative,
1628 });
e1d9a0f4 1629 initializeConnectorsMapStatus(this.evses.get(evseId)!.connectors, this.logPrefix());
ae25f265 1630 }
52952bf8 1631 this.saveEvsesStatus();
ae25f265
JB
1632 } else {
1633 logger.warn(
1634 `${this.logPrefix()} Charging station information from template ${
04b1261c 1635 this.templateFile
5edd8ba0 1636 } with no evses configuration defined, cannot create evses`,
04b1261c 1637 );
2585c6e9
JB
1638 }
1639 }
513db108
JB
1640 } else {
1641 logger.warn(
1642 `${this.logPrefix()} Charging station information from template ${
1643 this.templateFile
5edd8ba0 1644 } with no evses configuration defined, using already defined evses`,
513db108 1645 );
2585c6e9
JB
1646 }
1647 }
1648
551e477c
JB
1649 private getConfigurationFromFile(): ChargingStationConfiguration | undefined {
1650 let configuration: ChargingStationConfiguration | undefined;
9bf0ef23 1651 if (isNotEmptyString(this.configurationFile) && existsSync(this.configurationFile)) {
073bd098 1652 try {
57adbebc
JB
1653 if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
1654 configuration = this.sharedLRUCache.getChargingStationConfiguration(
5edd8ba0 1655 this.configurationFileHash,
57adbebc 1656 );
7c72977b
JB
1657 } else {
1658 const measureId = `${FileType.ChargingStationConfiguration} read`;
1659 const beginId = PerformanceStatistics.beginMeasure(measureId);
1660 configuration = JSON.parse(
5edd8ba0 1661 readFileSync(this.configurationFile, 'utf8'),
7c72977b
JB
1662 ) as ChargingStationConfiguration;
1663 PerformanceStatistics.endMeasure(measureId, beginId);
57adbebc 1664 this.sharedLRUCache.setChargingStationConfiguration(configuration);
e1d9a0f4 1665 this.configurationFileHash = configuration.configurationHash!;
7c72977b 1666 }
073bd098 1667 } catch (error) {
fa5995d6 1668 handleFileException(
073bd098 1669 this.configurationFile,
7164966d
JB
1670 FileType.ChargingStationConfiguration,
1671 error as NodeJS.ErrnoException,
5edd8ba0 1672 this.logPrefix(),
073bd098
JB
1673 );
1674 }
1675 }
1676 return configuration;
1677 }
1678
cb60061f 1679 private saveAutomaticTransactionGeneratorConfiguration(): void {
5ced7e80
JB
1680 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1681 this.saveConfiguration();
1682 }
ac7f79af
JB
1683 }
1684
52952bf8 1685 private saveConnectorsStatus() {
7446de3b 1686 this.saveConfiguration();
52952bf8
JB
1687 }
1688
1689 private saveEvsesStatus() {
7446de3b 1690 this.saveConfiguration();
52952bf8
JB
1691 }
1692
179ed367 1693 private saveConfiguration(): void {
9bf0ef23 1694 if (isNotEmptyString(this.configurationFile)) {
2484ac1e 1695 try {
d972af76
JB
1696 if (!existsSync(dirname(this.configurationFile))) {
1697 mkdirSync(dirname(this.configurationFile), { recursive: true });
073bd098 1698 }
ae8ceef3
JB
1699 let configurationData: ChargingStationConfiguration = this.getConfigurationFromFile()
1700 ? cloneObject<ChargingStationConfiguration>(this.getConfigurationFromFile()!)
1701 : {};
34eeb1fb 1702 if (this.getStationInfoPersistentConfiguration() && this.stationInfo) {
52952bf8 1703 configurationData.stationInfo = this.stationInfo;
5ced7e80
JB
1704 } else {
1705 delete configurationData.stationInfo;
52952bf8 1706 }
34eeb1fb 1707 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration?.configurationKey) {
52952bf8 1708 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
5ced7e80
JB
1709 } else {
1710 delete configurationData.configurationKey;
52952bf8 1711 }
179ed367
JB
1712 configurationData = merge<ChargingStationConfiguration>(
1713 configurationData,
5edd8ba0 1714 buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
179ed367 1715 );
5ced7e80
JB
1716 if (
1717 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1718 !this.getAutomaticTransactionGeneratorConfiguration()
1719 ) {
1720 delete configurationData.automaticTransactionGenerator;
1721 }
b1bbdae5 1722 if (this.connectors.size > 0) {
179ed367 1723 configurationData.connectorsStatus = buildConnectorsStatus(this);
5ced7e80
JB
1724 } else {
1725 delete configurationData.connectorsStatus;
52952bf8 1726 }
b1bbdae5 1727 if (this.evses.size > 0) {
179ed367 1728 configurationData.evsesStatus = buildEvsesStatus(this);
5ced7e80
JB
1729 } else {
1730 delete configurationData.evsesStatus;
52952bf8 1731 }
7c72977b 1732 delete configurationData.configurationHash;
d972af76 1733 const configurationHash = createHash(Constants.DEFAULT_HASH_ALGORITHM)
5ced7e80
JB
1734 .update(
1735 JSON.stringify({
1736 stationInfo: configurationData.stationInfo,
1737 configurationKey: configurationData.configurationKey,
1738 automaticTransactionGenerator: configurationData.automaticTransactionGenerator,
5edd8ba0 1739 } as ChargingStationConfiguration),
5ced7e80 1740 )
7c72977b
JB
1741 .digest('hex');
1742 if (this.configurationFileHash !== configurationHash) {
dd485b56 1743 AsyncLock.acquire(AsyncLockType.configuration)
1227a6f1
JB
1744 .then(() => {
1745 configurationData.configurationHash = configurationHash;
1746 const measureId = `${FileType.ChargingStationConfiguration} write`;
1747 const beginId = PerformanceStatistics.beginMeasure(measureId);
d972af76
JB
1748 const fileDescriptor = openSync(this.configurationFile, 'w');
1749 writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1750 closeSync(fileDescriptor);
1227a6f1
JB
1751 PerformanceStatistics.endMeasure(measureId, beginId);
1752 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
1753 this.sharedLRUCache.setChargingStationConfiguration(configurationData);
1754 this.configurationFileHash = configurationHash;
1755 })
1756 .catch((error) => {
fa5995d6 1757 handleFileException(
1227a6f1
JB
1758 this.configurationFile,
1759 FileType.ChargingStationConfiguration,
1760 error as NodeJS.ErrnoException,
5edd8ba0 1761 this.logPrefix(),
1227a6f1
JB
1762 );
1763 })
1764 .finally(() => {
dd485b56 1765 AsyncLock.release(AsyncLockType.configuration).catch(Constants.EMPTY_FUNCTION);
1227a6f1 1766 });
7c72977b
JB
1767 } else {
1768 logger.debug(
1769 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1770 this.configurationFile
5edd8ba0 1771 }`,
7c72977b 1772 );
2484ac1e 1773 }
2484ac1e 1774 } catch (error) {
fa5995d6 1775 handleFileException(
2484ac1e 1776 this.configurationFile,
7164966d
JB
1777 FileType.ChargingStationConfiguration,
1778 error as NodeJS.ErrnoException,
5edd8ba0 1779 this.logPrefix(),
073bd098
JB
1780 );
1781 }
2484ac1e
JB
1782 } else {
1783 logger.error(
5edd8ba0 1784 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`,
2484ac1e 1785 );
073bd098
JB
1786 }
1787 }
1788
551e477c
JB
1789 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | undefined {
1790 return this.getTemplateFromFile()?.Configuration;
2484ac1e
JB
1791 }
1792
551e477c 1793 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | undefined {
60655b26
JB
1794 const configurationKey = this.getConfigurationFromFile()?.configurationKey;
1795 if (this.getOcppPersistentConfiguration() === true && configurationKey) {
1796 return { configurationKey };
648512ce 1797 }
60655b26 1798 return undefined;
7dde0b73
JB
1799 }
1800
551e477c
JB
1801 private getOcppConfiguration(): ChargingStationOcppConfiguration | undefined {
1802 let ocppConfiguration: ChargingStationOcppConfiguration | undefined =
72092cfc 1803 this.getOcppConfigurationFromFile();
2484ac1e
JB
1804 if (!ocppConfiguration) {
1805 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1806 }
1807 return ocppConfiguration;
1808 }
1809
c0560973 1810 private async onOpen(): Promise<void> {
56eb297e 1811 if (this.isWebSocketConnectionOpened() === true) {
5144f4d1 1812 logger.info(
5edd8ba0 1813 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`,
5144f4d1 1814 );
ed6cfcff 1815 if (this.isRegistered() === false) {
5144f4d1
JB
1816 // Send BootNotification
1817 let registrationRetryCount = 0;
1818 do {
f7f98c68 1819 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
5144f4d1
JB
1820 BootNotificationRequest,
1821 BootNotificationResponse
8bfbc743
JB
1822 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
1823 skipBufferingOnError: true,
1824 });
ed6cfcff 1825 if (this.isRegistered() === false) {
1fe0632a 1826 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount;
9bf0ef23 1827 await sleep(
1895299d 1828 this?.bootNotificationResponse?.interval
5144f4d1 1829 ? this.bootNotificationResponse.interval * 1000
5edd8ba0 1830 : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL,
5144f4d1
JB
1831 );
1832 }
1833 } while (
ed6cfcff 1834 this.isRegistered() === false &&
e1d9a0f4 1835 (registrationRetryCount <= this.getRegistrationMaxRetries()! ||
5144f4d1
JB
1836 this.getRegistrationMaxRetries() === -1)
1837 );
1838 }
ed6cfcff 1839 if (this.isRegistered() === true) {
f7c2994d 1840 if (this.inAcceptedState() === true) {
94bb24d5 1841 await this.startMessageSequence();
c0560973 1842 }
5144f4d1
JB
1843 } else {
1844 logger.error(
5edd8ba0 1845 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`,
5144f4d1 1846 );
caad9d6b 1847 }
5144f4d1 1848 this.wsConnectionRestarted = false;
aa428a31 1849 this.autoReconnectRetryCount = 0;
c8faabc8 1850 parentPort?.postMessage(buildUpdatedMessage(this));
2e6f5966 1851 } else {
5144f4d1 1852 logger.warn(
5edd8ba0 1853 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`,
e7aeea18 1854 );
2e6f5966 1855 }
2e6f5966
JB
1856 }
1857
ef7d8c21 1858 private async onClose(code: number, reason: Buffer): Promise<void> {
d09085e9 1859 switch (code) {
6c65a295
JB
1860 // Normal close
1861 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 1862 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18 1863 logger.info(
9bf0ef23 1864 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
5edd8ba0
JB
1865 code,
1866 )}' and reason '${reason.toString()}'`,
e7aeea18 1867 );
c0560973
JB
1868 this.autoReconnectRetryCount = 0;
1869 break;
6c65a295
JB
1870 // Abnormal close
1871 default:
e7aeea18 1872 logger.error(
9bf0ef23 1873 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
5edd8ba0
JB
1874 code,
1875 )}' and reason '${reason.toString()}'`,
e7aeea18 1876 );
56eb297e 1877 this.started === true && (await this.reconnect());
c0560973
JB
1878 break;
1879 }
c8faabc8 1880 parentPort?.postMessage(buildUpdatedMessage(this));
2e6f5966
JB
1881 }
1882
56d09fd7
JB
1883 private getCachedRequest(messageType: MessageType, messageId: string): CachedRequest | undefined {
1884 const cachedRequest = this.requests.get(messageId);
1885 if (Array.isArray(cachedRequest) === true) {
1886 return cachedRequest;
1887 }
1888 throw new OCPPError(
1889 ErrorType.PROTOCOL_ERROR,
1890 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
5edd8ba0 1891 messageType,
56d09fd7
JB
1892 )} is not an array`,
1893 undefined,
5edd8ba0 1894 cachedRequest as JsonType,
56d09fd7
JB
1895 );
1896 }
1897
1898 private async handleIncomingMessage(request: IncomingRequest): Promise<void> {
1899 const [messageType, messageId, commandName, commandPayload] = request;
1900 if (this.getEnableStatistics() === true) {
1901 this.performanceStatistics?.addRequestStatistic(commandName, messageType);
1902 }
1903 logger.debug(
1904 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
5edd8ba0
JB
1905 request,
1906 )}`,
56d09fd7
JB
1907 );
1908 // Process the message
1909 await this.ocppIncomingRequestService.incomingRequestHandler(
1910 this,
1911 messageId,
1912 commandName,
5edd8ba0 1913 commandPayload,
56d09fd7
JB
1914 );
1915 }
1916
1917 private handleResponseMessage(response: Response): void {
1918 const [messageType, messageId, commandPayload] = response;
1919 if (this.requests.has(messageId) === false) {
1920 // Error
1921 throw new OCPPError(
1922 ErrorType.INTERNAL_ERROR,
1923 `Response for unknown message id ${messageId}`,
1924 undefined,
5edd8ba0 1925 commandPayload,
56d09fd7
JB
1926 );
1927 }
1928 // Respond
1929 const [responseCallback, , requestCommandName, requestPayload] = this.getCachedRequest(
1930 messageType,
5edd8ba0 1931 messageId,
e1d9a0f4 1932 )!;
56d09fd7
JB
1933 logger.debug(
1934 `${this.logPrefix()} << Command '${
1935 requestCommandName ?? Constants.UNKNOWN_COMMAND
5edd8ba0 1936 }' received response payload: ${JSON.stringify(response)}`,
56d09fd7
JB
1937 );
1938 responseCallback(commandPayload, requestPayload);
1939 }
1940
1941 private handleErrorMessage(errorResponse: ErrorResponse): void {
1942 const [messageType, messageId, errorType, errorMessage, errorDetails] = errorResponse;
1943 if (this.requests.has(messageId) === false) {
1944 // Error
1945 throw new OCPPError(
1946 ErrorType.INTERNAL_ERROR,
1947 `Error response for unknown message id ${messageId}`,
1948 undefined,
5edd8ba0 1949 { errorType, errorMessage, errorDetails },
56d09fd7
JB
1950 );
1951 }
e1d9a0f4 1952 const [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!;
56d09fd7
JB
1953 logger.debug(
1954 `${this.logPrefix()} << Command '${
1955 requestCommandName ?? Constants.UNKNOWN_COMMAND
5edd8ba0 1956 }' received error response payload: ${JSON.stringify(errorResponse)}`,
56d09fd7
JB
1957 );
1958 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
1959 }
1960
ef7d8c21 1961 private async onMessage(data: RawData): Promise<void> {
e1d9a0f4
JB
1962 let request: IncomingRequest | Response | ErrorResponse | undefined;
1963 let messageType: number | undefined;
ded57f02 1964 let errorMsg: string;
c0560973 1965 try {
e1d9a0f4 1966 // eslint-disable-next-line @typescript-eslint/no-base-to-string
56d09fd7 1967 request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
53e5fd67 1968 if (Array.isArray(request) === true) {
56d09fd7 1969 [messageType] = request;
b3ec7bc1
JB
1970 // Check the type of message
1971 switch (messageType) {
1972 // Incoming Message
1973 case MessageType.CALL_MESSAGE:
56d09fd7 1974 await this.handleIncomingMessage(request as IncomingRequest);
b3ec7bc1 1975 break;
56d09fd7 1976 // Response Message
b3ec7bc1 1977 case MessageType.CALL_RESULT_MESSAGE:
56d09fd7 1978 this.handleResponseMessage(request as Response);
a2d1c0f1
JB
1979 break;
1980 // Error Message
1981 case MessageType.CALL_ERROR_MESSAGE:
56d09fd7 1982 this.handleErrorMessage(request as ErrorResponse);
b3ec7bc1 1983 break;
56d09fd7 1984 // Unknown Message
b3ec7bc1
JB
1985 default:
1986 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
ded57f02
JB
1987 errorMsg = `Wrong message type ${messageType}`;
1988 logger.error(`${this.logPrefix()} ${errorMsg}`);
1989 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errorMsg);
b3ec7bc1 1990 }
c8faabc8 1991 parentPort?.postMessage(buildUpdatedMessage(this));
47e22477 1992 } else {
e1d9a0f4
JB
1993 throw new OCPPError(
1994 ErrorType.PROTOCOL_ERROR,
1995 'Incoming message is not an array',
1996 undefined,
1997 {
1998 request,
1999 },
2000 );
47e22477 2001 }
c0560973 2002 } catch (error) {
e1d9a0f4
JB
2003 let commandName: IncomingRequestCommand | undefined;
2004 let requestCommandName: RequestCommand | IncomingRequestCommand | undefined;
56d09fd7 2005 let errorCallback: ErrorCallback;
e1d9a0f4 2006 const [, messageId] = request!;
13701f69
JB
2007 switch (messageType) {
2008 case MessageType.CALL_MESSAGE:
56d09fd7 2009 [, , commandName] = request as IncomingRequest;
13701f69 2010 // Send error
56d09fd7 2011 await this.ocppRequestService.sendError(this, messageId, error as OCPPError, commandName);
13701f69
JB
2012 break;
2013 case MessageType.CALL_RESULT_MESSAGE:
2014 case MessageType.CALL_ERROR_MESSAGE:
56d09fd7 2015 if (this.requests.has(messageId) === true) {
e1d9a0f4 2016 [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!;
13701f69
JB
2017 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2018 errorCallback(error as OCPPError, false);
2019 } else {
2020 // Remove the request from the cache in case of error at response handling
2021 this.requests.delete(messageId);
2022 }
de4cb8b6 2023 break;
ba7965c4 2024 }
56d09fd7
JB
2025 if (error instanceof OCPPError === false) {
2026 logger.warn(
2027 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2028 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
e1d9a0f4 2029 // eslint-disable-next-line @typescript-eslint/no-base-to-string
56d09fd7 2030 }' message '${data.toString()}' handling is not an OCPPError:`,
5edd8ba0 2031 error,
56d09fd7
JB
2032 );
2033 }
2034 logger.error(
2035 `${this.logPrefix()} Incoming OCPP command '${
2036 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
e1d9a0f4 2037 // eslint-disable-next-line @typescript-eslint/no-base-to-string
56d09fd7
JB
2038 }' message '${data.toString()}'${
2039 messageType !== MessageType.CALL_MESSAGE
2040 ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'`
2041 : ''
2042 } processing error:`,
5edd8ba0 2043 error,
56d09fd7 2044 );
c0560973 2045 }
2328be1e
JB
2046 }
2047
c0560973 2048 private onPing(): void {
44eb6026 2049 logger.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
c0560973
JB
2050 }
2051
2052 private onPong(): void {
44eb6026 2053 logger.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
c0560973
JB
2054 }
2055
9534e74e 2056 private onError(error: WSError): void {
bcc9c3c0 2057 this.closeWSConnection();
44eb6026 2058 logger.error(`${this.logPrefix()} WebSocket error:`, error);
c0560973
JB
2059 }
2060
18bf8274 2061 private getEnergyActiveImportRegister(connectorStatus: ConnectorStatus, rounded = false): number {
95bdbf12 2062 if (this.getMeteringPerTransaction() === true) {
07989fad 2063 return (
18bf8274 2064 (rounded === true
e1d9a0f4 2065 ? Math.round(connectorStatus.transactionEnergyActiveImportRegisterValue!)
07989fad
JB
2066 : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0
2067 );
2068 }
2069 return (
18bf8274 2070 (rounded === true
e1d9a0f4 2071 ? Math.round(connectorStatus.energyActiveImportRegisterValue!)
07989fad
JB
2072 : connectorStatus?.energyActiveImportRegisterValue) ?? 0
2073 );
2074 }
2075
cda5d0fb
JB
2076 private getUseConnectorId0(stationTemplate?: ChargingStationTemplate): boolean {
2077 return stationTemplate?.useConnectorId0 ?? true;
8bce55bf
JB
2078 }
2079
60ddad53 2080 private async stopRunningTransactions(reason = StopTransactionReason.NONE): Promise<void> {
28e78158 2081 if (this.hasEvses) {
3fa7f799
JB
2082 for (const [evseId, evseStatus] of this.evses) {
2083 if (evseId === 0) {
2084 continue;
2085 }
28e78158
JB
2086 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
2087 if (connectorStatus.transactionStarted === true) {
2088 await this.stopTransactionOnConnector(connectorId, reason);
2089 }
2090 }
2091 }
2092 } else {
2093 for (const connectorId of this.connectors.keys()) {
2094 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
2095 await this.stopTransactionOnConnector(connectorId, reason);
2096 }
60ddad53
JB
2097 }
2098 }
2099 }
2100
1f761b9a 2101 // 0 for disabling
c72f6634 2102 private getConnectionTimeout(): number {
f2d5e3d9 2103 if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) {
e7aeea18 2104 return (
f2d5e3d9
JB
2105 parseInt(getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)!.value!) ??
2106 Constants.DEFAULT_CONNECTION_TIMEOUT
e7aeea18 2107 );
291cb255 2108 }
291cb255 2109 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
2110 }
2111
1f761b9a 2112 // -1 for unlimited, 0 for disabling
72092cfc 2113 private getAutoReconnectMaxRetries(): number | undefined {
b1bbdae5
JB
2114 return (
2115 this.stationInfo.autoReconnectMaxRetries ?? Configuration.getAutoReconnectMaxRetries() ?? -1
2116 );
3574dfd3
JB
2117 }
2118
ec977daf 2119 // 0 for disabling
72092cfc 2120 private getRegistrationMaxRetries(): number | undefined {
b1bbdae5 2121 return this.stationInfo.registrationMaxRetries ?? -1;
32a1eb7a
JB
2122 }
2123
c0560973 2124 private getPowerDivider(): number {
b1bbdae5 2125 let powerDivider = this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors();
fa7bccf4 2126 if (this.stationInfo?.powerSharedByConnectors) {
c0560973 2127 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
2128 }
2129 return powerDivider;
2130 }
2131
fa7bccf4
JB
2132 private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
2133 const maximumPower = this.getMaximumPower(stationInfo);
2134 switch (this.getCurrentOutType(stationInfo)) {
cc6e8ab5
JB
2135 case CurrentType.AC:
2136 return ACElectricUtils.amperagePerPhaseFromPower(
fa7bccf4 2137 this.getNumberOfPhases(stationInfo),
b1bbdae5 2138 maximumPower / (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()),
5edd8ba0 2139 this.getVoltageOut(stationInfo),
cc6e8ab5
JB
2140 );
2141 case CurrentType.DC:
fa7bccf4 2142 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo));
cc6e8ab5
JB
2143 }
2144 }
2145
cc6e8ab5
JB
2146 private getAmperageLimitation(): number | undefined {
2147 if (
9bf0ef23 2148 isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
f2d5e3d9 2149 getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)
cc6e8ab5
JB
2150 ) {
2151 return (
9bf0ef23 2152 convertToInt(
f2d5e3d9 2153 getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)?.value,
fba11dc6 2154 ) / getAmperageLimitationUnitDivider(this.stationInfo)
cc6e8ab5
JB
2155 );
2156 }
2157 }
2158
c0560973 2159 private async startMessageSequence(): Promise<void> {
b7f9e41d 2160 if (this.stationInfo?.autoRegister === true) {
f7f98c68 2161 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
2162 BootNotificationRequest,
2163 BootNotificationResponse
8bfbc743
JB
2164 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
2165 skipBufferingOnError: true,
2166 });
6114e6f1 2167 }
136c90ba 2168 // Start WebSocket ping
c0560973 2169 this.startWebSocketPing();
5ad8570f 2170 // Start heartbeat
c0560973 2171 this.startHeartbeat();
0a60c33c 2172 // Initialize connectors status
c3b83130
JB
2173 if (this.hasEvses) {
2174 for (const [evseId, evseStatus] of this.evses) {
4334db72
JB
2175 if (evseId > 0) {
2176 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
fba11dc6 2177 const connectorBootStatus = getBootConnectorStatus(this, connectorId, connectorStatus);
4334db72
JB
2178 await OCPPServiceUtils.sendAndSetConnectorStatus(
2179 this,
2180 connectorId,
12f26d4a 2181 connectorBootStatus,
5edd8ba0 2182 evseId,
4334db72
JB
2183 );
2184 }
c3b83130 2185 }
4334db72
JB
2186 }
2187 } else {
2188 for (const connectorId of this.connectors.keys()) {
2189 if (connectorId > 0) {
fba11dc6 2190 const connectorBootStatus = getBootConnectorStatus(
c3b83130
JB
2191 this,
2192 connectorId,
e1d9a0f4 2193 this.getConnectorStatus(connectorId)!,
c3b83130
JB
2194 );
2195 await OCPPServiceUtils.sendAndSetConnectorStatus(this, connectorId, connectorBootStatus);
2196 }
2197 }
5ad8570f 2198 }
c9a4f9ea
JB
2199 if (this.stationInfo?.firmwareStatus === FirmwareStatus.Installing) {
2200 await this.ocppRequestService.requestHandler<
2201 FirmwareStatusNotificationRequest,
2202 FirmwareStatusNotificationResponse
2203 >(this, RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
2204 status: FirmwareStatus.Installed,
2205 });
2206 this.stationInfo.firmwareStatus = FirmwareStatus.Installed;
c9a4f9ea 2207 }
3637ca2c 2208
0a60c33c 2209 // Start the ATG
ac7f79af 2210 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable === true) {
4f69be04 2211 this.startAutomaticTransactionGenerator();
fa7bccf4 2212 }
aa428a31 2213 this.wsConnectionRestarted === true && this.flushMessageBuffer();
fa7bccf4
JB
2214 }
2215
e7aeea18 2216 private async stopMessageSequence(
5edd8ba0 2217 reason: StopTransactionReason = StopTransactionReason.NONE,
e7aeea18 2218 ): Promise<void> {
136c90ba 2219 // Stop WebSocket ping
c0560973 2220 this.stopWebSocketPing();
79411696 2221 // Stop heartbeat
c0560973 2222 this.stopHeartbeat();
fa7bccf4 2223 // Stop ongoing transactions
b20eb107 2224 if (this.automaticTransactionGenerator?.started === true) {
60ddad53
JB
2225 this.stopAutomaticTransactionGenerator();
2226 } else {
2227 await this.stopRunningTransactions(reason);
79411696 2228 }
039211f9
JB
2229 if (this.hasEvses) {
2230 for (const [evseId, evseStatus] of this.evses) {
2231 if (evseId > 0) {
2232 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
2233 await this.ocppRequestService.requestHandler<
2234 StatusNotificationRequest,
2235 StatusNotificationResponse
2236 >(
2237 this,
2238 RequestCommand.STATUS_NOTIFICATION,
2239 OCPPServiceUtils.buildStatusNotificationRequest(
2240 this,
2241 connectorId,
12f26d4a 2242 ConnectorStatusEnum.Unavailable,
5edd8ba0
JB
2243 evseId,
2244 ),
039211f9
JB
2245 );
2246 delete connectorStatus?.status;
2247 }
2248 }
2249 }
2250 } else {
2251 for (const connectorId of this.connectors.keys()) {
2252 if (connectorId > 0) {
2253 await this.ocppRequestService.requestHandler<
2254 StatusNotificationRequest,
2255 StatusNotificationResponse
2256 >(
6e939d9e 2257 this,
039211f9
JB
2258 RequestCommand.STATUS_NOTIFICATION,
2259 OCPPServiceUtils.buildStatusNotificationRequest(
2260 this,
2261 connectorId,
5edd8ba0
JB
2262 ConnectorStatusEnum.Unavailable,
2263 ),
039211f9
JB
2264 );
2265 delete this.getConnectorStatus(connectorId)?.status;
2266 }
45c0ae82
JB
2267 }
2268 }
79411696
JB
2269 }
2270
c0560973 2271 private startWebSocketPing(): void {
f2d5e3d9 2272 const webSocketPingInterval: number = getConfigurationKey(
17ac262c 2273 this,
5edd8ba0 2274 StandardParametersKey.WebSocketPingInterval,
e7aeea18 2275 )
f2d5e3d9 2276 ? convertToInt(getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value)
9cd3dfb0 2277 : 0;
ad2f27c3
JB
2278 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
2279 this.webSocketPingSetInterval = setInterval(() => {
56eb297e 2280 if (this.isWebSocketConnectionOpened() === true) {
72092cfc 2281 this.wsConnection?.ping();
136c90ba
JB
2282 }
2283 }, webSocketPingInterval * 1000);
e7aeea18 2284 logger.info(
9bf0ef23 2285 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
5edd8ba0
JB
2286 webSocketPingInterval,
2287 )}`,
e7aeea18 2288 );
ad2f27c3 2289 } else if (this.webSocketPingSetInterval) {
e7aeea18 2290 logger.info(
9bf0ef23 2291 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
5edd8ba0
JB
2292 webSocketPingInterval,
2293 )}`,
e7aeea18 2294 );
136c90ba 2295 } else {
e7aeea18 2296 logger.error(
5edd8ba0 2297 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`,
e7aeea18 2298 );
136c90ba
JB
2299 }
2300 }
2301
c0560973 2302 private stopWebSocketPing(): void {
ad2f27c3
JB
2303 if (this.webSocketPingSetInterval) {
2304 clearInterval(this.webSocketPingSetInterval);
dfe81c8f 2305 delete this.webSocketPingSetInterval;
136c90ba
JB
2306 }
2307 }
2308
1f5df42a 2309 private getConfiguredSupervisionUrl(): URL {
d5c3df49 2310 let configuredSupervisionUrl: string;
72092cfc 2311 const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls();
9bf0ef23 2312 if (isNotEmptyArray(supervisionUrls)) {
269de583 2313 let configuredSupervisionUrlIndex: number;
2dcfe98e 2314 switch (Configuration.getSupervisionUrlDistribution()) {
2dcfe98e 2315 case SupervisionUrlDistribution.RANDOM:
e1d9a0f4
JB
2316 configuredSupervisionUrlIndex = Math.floor(
2317 secureRandom() * (supervisionUrls as string[]).length,
2318 );
2dcfe98e 2319 break;
a52a6446 2320 case SupervisionUrlDistribution.ROUND_ROBIN:
c72f6634 2321 case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY:
2dcfe98e 2322 default:
a52a6446 2323 Object.values(SupervisionUrlDistribution).includes(
e1d9a0f4 2324 Configuration.getSupervisionUrlDistribution()!,
a52a6446
JB
2325 ) === false &&
2326 logger.error(
e1d9a0f4 2327 // eslint-disable-next-line @typescript-eslint/no-base-to-string
a52a6446
JB
2328 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2329 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
5edd8ba0 2330 }`,
a52a6446 2331 );
e1d9a0f4 2332 configuredSupervisionUrlIndex = (this.index - 1) % (supervisionUrls as string[]).length;
2dcfe98e 2333 break;
c0560973 2334 }
e1d9a0f4 2335 configuredSupervisionUrl = (supervisionUrls as string[])[configuredSupervisionUrlIndex];
d5c3df49
JB
2336 } else {
2337 configuredSupervisionUrl = supervisionUrls as string;
2338 }
9bf0ef23 2339 if (isNotEmptyString(configuredSupervisionUrl)) {
d5c3df49 2340 return new URL(configuredSupervisionUrl);
c0560973 2341 }
49c508b0 2342 const errorMsg = 'No supervision url(s) configured';
7f77d16f
JB
2343 logger.error(`${this.logPrefix()} ${errorMsg}`);
2344 throw new BaseError(`${errorMsg}`);
136c90ba
JB
2345 }
2346
c0560973 2347 private stopHeartbeat(): void {
ad2f27c3
JB
2348 if (this.heartbeatSetInterval) {
2349 clearInterval(this.heartbeatSetInterval);
dfe81c8f 2350 delete this.heartbeatSetInterval;
7dde0b73 2351 }
5ad8570f
JB
2352 }
2353
55516218 2354 private terminateWSConnection(): void {
56eb297e 2355 if (this.isWebSocketConnectionOpened() === true) {
72092cfc 2356 this.wsConnection?.terminate();
55516218
JB
2357 this.wsConnection = null;
2358 }
2359 }
2360
c72f6634 2361 private getReconnectExponentialDelay(): boolean {
a14885a3 2362 return this.stationInfo?.reconnectExponentialDelay ?? false;
5ad8570f
JB
2363 }
2364
aa428a31 2365 private async reconnect(): Promise<void> {
7874b0b1
JB
2366 // Stop WebSocket ping
2367 this.stopWebSocketPing();
136c90ba 2368 // Stop heartbeat
c0560973 2369 this.stopHeartbeat();
5ad8570f 2370 // Stop the ATG if needed
ac7f79af 2371 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure === true) {
fa7bccf4 2372 this.stopAutomaticTransactionGenerator();
ad2f27c3 2373 }
e7aeea18 2374 if (
e1d9a0f4 2375 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries()! ||
e7aeea18
JB
2376 this.getAutoReconnectMaxRetries() === -1
2377 ) {
1fe0632a 2378 ++this.autoReconnectRetryCount;
e7aeea18 2379 const reconnectDelay = this.getReconnectExponentialDelay()
9bf0ef23 2380 ? exponentialDelay(this.autoReconnectRetryCount)
e7aeea18 2381 : this.getConnectionTimeout() * 1000;
1e080116
JB
2382 const reconnectDelayWithdraw = 1000;
2383 const reconnectTimeout =
2384 reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0
2385 ? reconnectDelay - reconnectDelayWithdraw
2386 : 0;
e7aeea18 2387 logger.error(
9bf0ef23 2388 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
e7aeea18 2389 reconnectDelay,
5edd8ba0
JB
2390 2,
2391 )}ms, timeout ${reconnectTimeout}ms`,
e7aeea18 2392 );
9bf0ef23 2393 await sleep(reconnectDelay);
e7aeea18 2394 logger.error(
5edd8ba0 2395 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`,
e7aeea18
JB
2396 );
2397 this.openWSConnection(
59b6ed8d 2398 {
abe9e9dd 2399 ...(this.stationInfo?.wsOptions ?? {}),
59b6ed8d
JB
2400 handshakeTimeout: reconnectTimeout,
2401 },
5edd8ba0 2402 { closeOpened: true },
e7aeea18 2403 );
265e4266 2404 this.wsConnectionRestarted = true;
c0560973 2405 } else if (this.getAutoReconnectMaxRetries() !== -1) {
e7aeea18 2406 logger.error(
d56ea27c 2407 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
e7aeea18 2408 this.autoReconnectRetryCount
5edd8ba0 2409 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`,
e7aeea18 2410 );
5ad8570f
JB
2411 }
2412 }
7dde0b73 2413}