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