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