refactor: move template firmware defaults to constants
[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 {
66a7748d 289 stationTemplate = undefined
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 )
6b90dcca
JB
1230 // Priority:
1231 // 1. charging station info from template
1232 // 2. charging station info from configuration file
2466918c
JB
1233 if (
1234 stationInfoFromFile != null &&
1235 stationInfoFromFile.templateHash === stationInfoFromTemplate.templateHash
1236 ) {
36b73d95 1237 return setChargingStationOptions(
56f94590 1238 mergeDeepRight(Constants.DEFAULT_STATION_INFO, stationInfoFromFile),
36b73d95
JB
1239 options
1240 )
f765beaa 1241 }
66a7748d 1242 stationInfoFromFile != null &&
fba11dc6 1243 propagateSerialNumber(
5199f9fd 1244 this.getTemplateFromFile(),
fec4d204 1245 stationInfoFromFile,
66a7748d
JB
1246 stationInfoFromTemplate
1247 )
36b73d95 1248 return setChargingStationOptions(
56f94590 1249 mergeDeepRight(Constants.DEFAULT_STATION_INFO, stationInfoFromTemplate),
36b73d95
JB
1250 options
1251 )
2484ac1e
JB
1252 }
1253
66a7748d 1254 private saveStationInfo (): void {
5398cecf 1255 if (this.stationInfo?.stationInfoPersistentConfiguration === true) {
66a7748d 1256 this.saveConfiguration()
ccb1d6e9 1257 }
2484ac1e
JB
1258 }
1259
66a7748d
JB
1260 private handleUnsupportedVersion (version: OCPPVersion | undefined): void {
1261 const errorMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`
1262 logger.error(`${this.logPrefix()} ${errorMsg}`)
1263 throw new BaseError(errorMsg)
c0560973
JB
1264 }
1265
52c58949 1266 private initialize (options?: ChargingStationOptions): void {
66a7748d
JB
1267 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1268 const stationTemplate = this.getTemplateFromFile()!
1269 checkTemplate(stationTemplate, this.logPrefix(), this.templateFile)
d972af76
JB
1270 this.configurationFile = join(
1271 dirname(this.templateFile.replace('station-templates', 'configurations')),
66a7748d
JB
1272 `${getHashId(this.index, stationTemplate)}.json`
1273 )
1274 const stationConfiguration = this.getConfigurationFromFile()
a4f7c75f 1275 if (
5199f9fd 1276 stationConfiguration?.stationInfo?.templateHash === stationTemplate.templateHash &&
66a7748d 1277 (stationConfiguration?.connectorsStatus != null || stationConfiguration?.evsesStatus != null)
a4f7c75f 1278 ) {
66a7748d
JB
1279 checkConfiguration(stationConfiguration, this.logPrefix(), this.configurationFile)
1280 this.initializeConnectorsOrEvsesFromFile(stationConfiguration)
a4f7c75f 1281 } else {
66a7748d 1282 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate)
a4f7c75f 1283 }
36b73d95 1284 this.stationInfo = this.getStationInfo(options)
3637ca2c
JB
1285 if (
1286 this.stationInfo.firmwareStatus === FirmwareStatus.Installing &&
1feac591
JB
1287 isNotEmptyString(this.stationInfo.firmwareVersionPattern) &&
1288 isNotEmptyString(this.stationInfo.firmwareVersion)
3637ca2c 1289 ) {
2466918c 1290 const patternGroup =
15748260 1291 this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ??
5dc7c990
JB
1292 this.stationInfo.firmwareVersion.split('.').length
1293 const match = new RegExp(this.stationInfo.firmwareVersionPattern)
1294 .exec(this.stationInfo.firmwareVersion)
1295 ?.slice(1, patternGroup + 1)
aa63c9b7
JB
1296 if (match != null) {
1297 const patchLevelIndex = match.length - 1
1298 match[patchLevelIndex] = (
1299 convertToInt(match[patchLevelIndex]) +
1300 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1301 this.stationInfo.firmwareUpgrade!.versionUpgrade!.step!
1302 ).toString()
1303 this.stationInfo.firmwareVersion = match.join('.')
77807350 1304 }
3637ca2c 1305 }
66a7748d
JB
1306 this.saveStationInfo()
1307 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl()
5199f9fd 1308 if (this.stationInfo.enableStatistics === true) {
6bccfcbc
JB
1309 this.performanceStatistics = PerformanceStatistics.getInstance(
1310 this.stationInfo.hashId,
2466918c 1311 this.stationInfo.chargingStationId,
66a7748d
JB
1312 this.configuredSupervisionUrl
1313 )
6bccfcbc 1314 }
2466918c
JB
1315 const bootNotificationRequest = createBootNotificationRequest(this.stationInfo)
1316 if (bootNotificationRequest == null) {
1317 const errorMsg = 'Error while creating boot notification request'
1318 logger.error(`${this.logPrefix()} ${errorMsg}`)
1319 throw new BaseError(errorMsg)
1320 }
1321 this.bootNotificationRequest = bootNotificationRequest
66a7748d 1322 this.powerDivider = this.getPowerDivider()
692f2f64 1323 // OCPP configuration
52c58949 1324 this.ocppConfiguration = this.getOcppConfiguration(options?.persistentConfiguration)
66a7748d
JB
1325 this.initializeOcppConfiguration()
1326 this.initializeOcppServices()
5199f9fd 1327 if (this.stationInfo.autoRegister === true) {
692f2f64
JB
1328 this.bootNotificationResponse = {
1329 currentTime: new Date(),
be4c6702 1330 interval: millisecondsToSeconds(this.getHeartbeatInterval()),
66a7748d
JB
1331 status: RegistrationStatusEnumType.ACCEPTED
1332 }
692f2f64 1333 }
147d0e0f
JB
1334 }
1335
66a7748d
JB
1336 private initializeOcppServices (): void {
1337 const ocppVersion = this.stationInfo?.ocppVersion
feff11ec
JB
1338 switch (ocppVersion) {
1339 case OCPPVersion.VERSION_16:
1340 this.ocppIncomingRequestService =
66a7748d 1341 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>()
feff11ec 1342 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
66a7748d
JB
1343 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
1344 )
1345 break
feff11ec
JB
1346 case OCPPVersion.VERSION_20:
1347 case OCPPVersion.VERSION_201:
1348 this.ocppIncomingRequestService =
66a7748d 1349 OCPP20IncomingRequestService.getInstance<OCPP20IncomingRequestService>()
feff11ec 1350 this.ocppRequestService = OCPP20RequestService.getInstance<OCPP20RequestService>(
66a7748d
JB
1351 OCPP20ResponseService.getInstance<OCPP20ResponseService>()
1352 )
1353 break
feff11ec 1354 default:
66a7748d
JB
1355 this.handleUnsupportedVersion(ocppVersion)
1356 break
feff11ec
JB
1357 }
1358 }
1359
66a7748d 1360 private initializeOcppConfiguration (): void {
aa63c9b7 1361 if (getConfigurationKey(this, StandardParametersKey.HeartbeatInterval) == null) {
66a7748d 1362 addConfigurationKey(this, StandardParametersKey.HeartbeatInterval, '0')
f0f65a62 1363 }
aa63c9b7 1364 if (getConfigurationKey(this, StandardParametersKey.HeartBeatInterval) == null) {
66a7748d 1365 addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', { visible: false })
f0f65a62 1366 }
e7aeea18 1367 if (
4e3b1d6b 1368 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
5199f9fd 1369 isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
5dc7c990 1370 getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey) == null
e7aeea18 1371 ) {
f2d5e3d9 1372 addConfigurationKey(
17ac262c 1373 this,
5dc7c990 1374 this.stationInfo.supervisionUrlOcppKey,
fa7bccf4 1375 this.configuredSupervisionUrl.href,
66a7748d
JB
1376 { reboot: true }
1377 )
e6895390 1378 } else if (
4e3b1d6b 1379 this.stationInfo?.supervisionUrlOcppConfiguration === false &&
5199f9fd 1380 isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
5dc7c990 1381 getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey) != null
e6895390 1382 ) {
5dc7c990 1383 deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey, { save: false })
12fc74d6 1384 }
cc6e8ab5 1385 if (
9bf0ef23 1386 isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
5dc7c990 1387 getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey) == null
cc6e8ab5 1388 ) {
f2d5e3d9 1389 addConfigurationKey(
17ac262c 1390 this,
5dc7c990 1391 this.stationInfo.amperageLimitationOcppKey,
66a7748d
JB
1392 // prettier-ignore
1393 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
5dc7c990 1394 (this.stationInfo.maximumAmperage! * getAmperageLimitationUnitDivider(this.stationInfo)).toString()
66a7748d 1395 )
cc6e8ab5 1396 }
aa63c9b7 1397 if (getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles) == null) {
f2d5e3d9 1398 addConfigurationKey(
17ac262c 1399 this,
e7aeea18 1400 StandardParametersKey.SupportedFeatureProfiles,
66a7748d
JB
1401 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1402 )
e7aeea18 1403 }
f2d5e3d9 1404 addConfigurationKey(
17ac262c 1405 this,
e7aeea18
JB
1406 StandardParametersKey.NumberOfConnectors,
1407 this.getNumberOfConnectors().toString(),
a95873d8 1408 { readonly: true },
66a7748d
JB
1409 { overwrite: true }
1410 )
aa63c9b7 1411 if (getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData) == null) {
f2d5e3d9 1412 addConfigurationKey(
17ac262c 1413 this,
e7aeea18 1414 StandardParametersKey.MeterValuesSampledData,
66a7748d
JB
1415 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1416 )
7abfea5f 1417 }
aa63c9b7 1418 if (getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation) == null) {
66a7748d 1419 const connectorsPhaseRotation: string[] = []
28e78158
JB
1420 if (this.hasEvses) {
1421 for (const evseStatus of this.evses.values()) {
1422 for (const connectorId of evseStatus.connectors.keys()) {
dd08d43d 1423 connectorsPhaseRotation.push(
66a7748d
JB
1424 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1425 getPhaseRotationValue(connectorId, this.getNumberOfPhases())!
1426 )
28e78158
JB
1427 }
1428 }
1429 } else {
1430 for (const connectorId of this.connectors.keys()) {
dd08d43d 1431 connectorsPhaseRotation.push(
66a7748d
JB
1432 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1433 getPhaseRotationValue(connectorId, this.getNumberOfPhases())!
1434 )
7e1dc878
JB
1435 }
1436 }
f2d5e3d9 1437 addConfigurationKey(
17ac262c 1438 this,
e7aeea18 1439 StandardParametersKey.ConnectorPhaseRotation,
66a7748d
JB
1440 connectorsPhaseRotation.toString()
1441 )
7e1dc878 1442 }
aa63c9b7 1443 if (getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests) == null) {
66a7748d 1444 addConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests, 'true')
36f6a92e 1445 }
17ac262c 1446 if (
aa63c9b7 1447 getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled) == null &&
a807045b 1448 hasFeatureProfile(this, SupportedFeatureProfiles.LocalAuthListManagement) === true
17ac262c 1449 ) {
66a7748d 1450 addConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled, 'false')
f2d5e3d9 1451 }
aa63c9b7 1452 if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut) == null) {
f2d5e3d9 1453 addConfigurationKey(
17ac262c 1454 this,
e7aeea18 1455 StandardParametersKey.ConnectionTimeOut,
66a7748d
JB
1456 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1457 )
8bce55bf 1458 }
66a7748d 1459 this.saveOcppConfiguration()
073bd098
JB
1460 }
1461
66a7748d 1462 private initializeConnectorsOrEvsesFromFile (configuration: ChargingStationConfiguration): void {
5199f9fd 1463 if (configuration.connectorsStatus != null && configuration.evsesStatus == null) {
8df5ae48 1464 for (const [connectorId, connectorStatus] of configuration.connectorsStatus.entries()) {
40615072 1465 this.connectors.set(connectorId, clone<ConnectorStatus>(connectorStatus))
8df5ae48 1466 }
5199f9fd 1467 } else if (configuration.evsesStatus != null && configuration.connectorsStatus == null) {
a4f7c75f 1468 for (const [evseId, evseStatusConfiguration] of configuration.evsesStatus.entries()) {
40615072 1469 const evseStatus = clone<EvseStatusConfiguration>(evseStatusConfiguration)
66a7748d 1470 delete evseStatus.connectorsStatus
a4f7c75f 1471 this.evses.set(evseId, {
8df5ae48 1472 ...(evseStatus as EvseStatus),
a4f7c75f 1473 connectors: new Map<number, ConnectorStatus>(
66a7748d 1474 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
e1d9a0f4 1475 evseStatusConfiguration.connectorsStatus!.map((connectorStatus, connectorId) => [
a4f7c75f 1476 connectorId,
66a7748d
JB
1477 connectorStatus
1478 ])
1479 )
1480 })
a4f7c75f 1481 }
5199f9fd 1482 } else if (configuration.evsesStatus != null && configuration.connectorsStatus != null) {
66a7748d
JB
1483 const errorMsg = `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1484 logger.error(`${this.logPrefix()} ${errorMsg}`)
1485 throw new BaseError(errorMsg)
a4f7c75f 1486 } else {
66a7748d
JB
1487 const errorMsg = `No connectors or evses defined in configuration file ${this.configurationFile}`
1488 logger.error(`${this.logPrefix()} ${errorMsg}`)
1489 throw new BaseError(errorMsg)
a4f7c75f
JB
1490 }
1491 }
1492
66a7748d 1493 private initializeConnectorsOrEvsesFromTemplate (stationTemplate: ChargingStationTemplate): void {
5199f9fd 1494 if (stationTemplate.Connectors != null && stationTemplate.Evses == null) {
66a7748d 1495 this.initializeConnectorsFromTemplate(stationTemplate)
5199f9fd 1496 } else if (stationTemplate.Evses != null && stationTemplate.Connectors == null) {
66a7748d 1497 this.initializeEvsesFromTemplate(stationTemplate)
5199f9fd 1498 } else if (stationTemplate.Evses != null && stationTemplate.Connectors != null) {
66a7748d
JB
1499 const errorMsg = `Connectors and evses defined at the same time in template file ${this.templateFile}`
1500 logger.error(`${this.logPrefix()} ${errorMsg}`)
1501 throw new BaseError(errorMsg)
ae25f265 1502 } else {
66a7748d
JB
1503 const errorMsg = `No connectors or evses defined in template file ${this.templateFile}`
1504 logger.error(`${this.logPrefix()} ${errorMsg}`)
1505 throw new BaseError(errorMsg)
ae25f265
JB
1506 }
1507 }
1508
66a7748d 1509 private initializeConnectorsFromTemplate (stationTemplate: ChargingStationTemplate): void {
5199f9fd 1510 if (stationTemplate.Connectors == null && this.connectors.size === 0) {
66a7748d
JB
1511 const errorMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1512 logger.error(`${this.logPrefix()} ${errorMsg}`)
1513 throw new BaseError(errorMsg)
3d25cc86 1514 }
5199f9fd 1515 if (stationTemplate.Connectors?.[0] == null) {
3d25cc86
JB
1516 logger.warn(
1517 `${this.logPrefix()} Charging station information from template ${
1518 this.templateFile
66a7748d
JB
1519 } with no connector id 0 configuration`
1520 )
3d25cc86 1521 }
5199f9fd 1522 if (stationTemplate.Connectors != null) {
cda5d0fb 1523 const { configuredMaxConnectors, templateMaxConnectors, templateMaxAvailableConnectors } =
66a7748d 1524 checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile)
d972af76 1525 const connectorsConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM)
cda5d0fb 1526 .update(
5199f9fd 1527 `${JSON.stringify(stationTemplate.Connectors)}${configuredMaxConnectors.toString()}`
cda5d0fb 1528 )
66a7748d 1529 .digest('hex')
3d25cc86 1530 const connectorsConfigChanged =
5199f9fd
JB
1531 this.connectors.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash
1532 if (this.connectors.size === 0 || connectorsConfigChanged) {
66a7748d
JB
1533 connectorsConfigChanged && this.connectors.clear()
1534 this.connectorsConfigurationHash = connectorsConfigHash
269196a8
JB
1535 if (templateMaxConnectors > 0) {
1536 for (let connectorId = 0; connectorId <= configuredMaxConnectors; connectorId++) {
1537 if (
1538 connectorId === 0 &&
5199f9fd
JB
1539 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1540 (stationTemplate.Connectors[connectorId] == null ||
66a7748d 1541 !this.getUseConnectorId0(stationTemplate))
269196a8 1542 ) {
66a7748d 1543 continue
269196a8
JB
1544 }
1545 const templateConnectorId =
5199f9fd 1546 connectorId > 0 && stationTemplate.randomConnectors === true
fcda9151 1547 ? randomInt(1, templateMaxAvailableConnectors)
66a7748d 1548 : connectorId
5199f9fd 1549 const connectorStatus = stationTemplate.Connectors[templateConnectorId]
fba11dc6 1550 checkStationInfoConnectorStatus(
ae25f265 1551 templateConnectorId,
04b1261c
JB
1552 connectorStatus,
1553 this.logPrefix(),
66a7748d
JB
1554 this.templateFile
1555 )
40615072 1556 this.connectors.set(connectorId, clone<ConnectorStatus>(connectorStatus))
3d25cc86 1557 }
66a7748d
JB
1558 initializeConnectorsMapStatus(this.connectors, this.logPrefix())
1559 this.saveConnectorsStatus()
ae25f265
JB
1560 } else {
1561 logger.warn(
1562 `${this.logPrefix()} Charging station information from template ${
1563 this.templateFile
66a7748d
JB
1564 } with no connectors configuration defined, cannot create connectors`
1565 )
3d25cc86
JB
1566 }
1567 }
1568 } else {
1569 logger.warn(
1570 `${this.logPrefix()} Charging station information from template ${
1571 this.templateFile
66a7748d
JB
1572 } with no connectors configuration defined, using already defined connectors`
1573 )
3d25cc86 1574 }
3d25cc86
JB
1575 }
1576
66a7748d 1577 private initializeEvsesFromTemplate (stationTemplate: ChargingStationTemplate): void {
5199f9fd 1578 if (stationTemplate.Evses == null && this.evses.size === 0) {
66a7748d
JB
1579 const errorMsg = `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1580 logger.error(`${this.logPrefix()} ${errorMsg}`)
1581 throw new BaseError(errorMsg)
2585c6e9 1582 }
5199f9fd 1583 if (stationTemplate.Evses?.[0] == null) {
2585c6e9
JB
1584 logger.warn(
1585 `${this.logPrefix()} Charging station information from template ${
1586 this.templateFile
66a7748d
JB
1587 } with no evse id 0 configuration`
1588 )
2585c6e9 1589 }
5199f9fd 1590 if (stationTemplate.Evses?.[0]?.Connectors[0] == null) {
59a0f26d
JB
1591 logger.warn(
1592 `${this.logPrefix()} Charging station information from template ${
1593 this.templateFile
66a7748d
JB
1594 } with evse id 0 with no connector id 0 configuration`
1595 )
59a0f26d 1596 }
5199f9fd 1597 if (Object.keys(stationTemplate.Evses?.[0]?.Connectors as object).length > 1) {
491dad29
JB
1598 logger.warn(
1599 `${this.logPrefix()} Charging station information from template ${
1600 this.templateFile
66a7748d
JB
1601 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1602 )
491dad29 1603 }
5199f9fd 1604 if (stationTemplate.Evses != null) {
d972af76 1605 const evsesConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM)
5199f9fd 1606 .update(JSON.stringify(stationTemplate.Evses))
66a7748d 1607 .digest('hex')
2585c6e9 1608 const evsesConfigChanged =
5199f9fd
JB
1609 this.evses.size !== 0 && this.evsesConfigurationHash !== evsesConfigHash
1610 if (this.evses.size === 0 || evsesConfigChanged) {
66a7748d
JB
1611 evsesConfigChanged && this.evses.clear()
1612 this.evsesConfigurationHash = evsesConfigHash
5199f9fd 1613 const templateMaxEvses = getMaxNumberOfEvses(stationTemplate.Evses)
ae25f265 1614 if (templateMaxEvses > 0) {
eb979012 1615 for (const evseKey in stationTemplate.Evses) {
66a7748d 1616 const evseId = convertToInt(evseKey)
52952bf8 1617 this.evses.set(evseId, {
fba11dc6 1618 connectors: buildConnectorsMap(
5199f9fd 1619 stationTemplate.Evses[evseKey].Connectors,
ae25f265 1620 this.logPrefix(),
66a7748d 1621 this.templateFile
ae25f265 1622 ),
66a7748d
JB
1623 availability: AvailabilityType.Operative
1624 })
1625 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1626 initializeConnectorsMapStatus(this.evses.get(evseId)!.connectors, this.logPrefix())
ae25f265 1627 }
66a7748d 1628 this.saveEvsesStatus()
ae25f265
JB
1629 } else {
1630 logger.warn(
1631 `${this.logPrefix()} Charging station information from template ${
04b1261c 1632 this.templateFile
66a7748d
JB
1633 } with no evses configuration defined, cannot create evses`
1634 )
2585c6e9
JB
1635 }
1636 }
513db108
JB
1637 } else {
1638 logger.warn(
1639 `${this.logPrefix()} Charging station information from template ${
1640 this.templateFile
66a7748d
JB
1641 } with no evses configuration defined, using already defined evses`
1642 )
2585c6e9
JB
1643 }
1644 }
1645
66a7748d
JB
1646 private getConfigurationFromFile (): ChargingStationConfiguration | undefined {
1647 let configuration: ChargingStationConfiguration | undefined
9bf0ef23 1648 if (isNotEmptyString(this.configurationFile) && existsSync(this.configurationFile)) {
073bd098 1649 try {
57adbebc
JB
1650 if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
1651 configuration = this.sharedLRUCache.getChargingStationConfiguration(
66a7748d
JB
1652 this.configurationFileHash
1653 )
7c72977b 1654 } else {
66a7748d
JB
1655 const measureId = `${FileType.ChargingStationConfiguration} read`
1656 const beginId = PerformanceStatistics.beginMeasure(measureId)
7c72977b 1657 configuration = JSON.parse(
66a7748d
JB
1658 readFileSync(this.configurationFile, 'utf8')
1659 ) as ChargingStationConfiguration
1660 PerformanceStatistics.endMeasure(measureId, beginId)
1661 this.sharedLRUCache.setChargingStationConfiguration(configuration)
1662 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1663 this.configurationFileHash = configuration.configurationHash!
7c72977b 1664 }
073bd098 1665 } catch (error) {
fa5995d6 1666 handleFileException(
073bd098 1667 this.configurationFile,
7164966d
JB
1668 FileType.ChargingStationConfiguration,
1669 error as NodeJS.ErrnoException,
66a7748d
JB
1670 this.logPrefix()
1671 )
073bd098
JB
1672 }
1673 }
66a7748d 1674 return configuration
073bd098
JB
1675 }
1676
66a7748d 1677 private saveAutomaticTransactionGeneratorConfiguration (): void {
5398cecf 1678 if (this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration === true) {
66a7748d 1679 this.saveConfiguration()
5ced7e80 1680 }
ac7f79af
JB
1681 }
1682
66a7748d
JB
1683 private saveConnectorsStatus (): void {
1684 this.saveConfiguration()
52952bf8
JB
1685 }
1686
66a7748d
JB
1687 private saveEvsesStatus (): void {
1688 this.saveConfiguration()
52952bf8
JB
1689 }
1690
66a7748d 1691 private saveConfiguration (): void {
9bf0ef23 1692 if (isNotEmptyString(this.configurationFile)) {
2484ac1e 1693 try {
d972af76 1694 if (!existsSync(dirname(this.configurationFile))) {
66a7748d 1695 mkdirSync(dirname(this.configurationFile), { recursive: true })
073bd098 1696 }
2466918c 1697 const configurationFromFile = this.getConfigurationFromFile()
66a7748d 1698 let configurationData: ChargingStationConfiguration =
2466918c 1699 configurationFromFile != null
40615072 1700 ? clone<ChargingStationConfiguration>(configurationFromFile)
66a7748d 1701 : {}
5199f9fd 1702 if (this.stationInfo?.stationInfoPersistentConfiguration === true) {
66a7748d 1703 configurationData.stationInfo = this.stationInfo
5ced7e80 1704 } else {
66a7748d 1705 delete configurationData.stationInfo
52952bf8 1706 }
5398cecf
JB
1707 if (
1708 this.stationInfo?.ocppPersistentConfiguration === true &&
755a76d5 1709 Array.isArray(this.ocppConfiguration?.configurationKey)
5398cecf 1710 ) {
5199f9fd 1711 configurationData.configurationKey = this.ocppConfiguration.configurationKey
5ced7e80 1712 } else {
66a7748d 1713 delete configurationData.configurationKey
52952bf8 1714 }
b4c82e73 1715 configurationData = mergeDeepRight(
179ed367 1716 configurationData,
66a7748d
JB
1717 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1718 )
a97d2d6c 1719 if (this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration !== true) {
66a7748d 1720 delete configurationData.automaticTransactionGenerator
5ced7e80 1721 }
b1bbdae5 1722 if (this.connectors.size > 0) {
66a7748d 1723 configurationData.connectorsStatus = buildConnectorsStatus(this)
5ced7e80 1724 } else {
66a7748d 1725 delete configurationData.connectorsStatus
52952bf8 1726 }
b1bbdae5 1727 if (this.evses.size > 0) {
66a7748d 1728 configurationData.evsesStatus = buildEvsesStatus(this)
5ced7e80 1729 } else {
66a7748d 1730 delete configurationData.evsesStatus
52952bf8 1731 }
66a7748d 1732 delete configurationData.configurationHash
d972af76 1733 const configurationHash = createHash(Constants.DEFAULT_HASH_ALGORITHM)
5ced7e80
JB
1734 .update(
1735 JSON.stringify({
1736 stationInfo: configurationData.stationInfo,
1737 configurationKey: configurationData.configurationKey,
1738 automaticTransactionGenerator: configurationData.automaticTransactionGenerator,
8ab96efb 1739 ...(this.connectors.size > 0 && {
66a7748d 1740 connectorsStatus: configurationData.connectorsStatus
8ab96efb 1741 }),
66a7748d
JB
1742 ...(this.evses.size > 0 && { evsesStatus: configurationData.evsesStatus })
1743 } satisfies ChargingStationConfiguration)
5ced7e80 1744 )
66a7748d 1745 .digest('hex')
7c72977b 1746 if (this.configurationFileHash !== configurationHash) {
0ebf7c2e 1747 AsyncLock.runExclusive(AsyncLockType.configuration, () => {
66a7748d
JB
1748 configurationData.configurationHash = configurationHash
1749 const measureId = `${FileType.ChargingStationConfiguration} write`
1750 const beginId = PerformanceStatistics.beginMeasure(measureId)
0ebf7c2e
JB
1751 writeFileSync(
1752 this.configurationFile,
4ed03b6e 1753 JSON.stringify(configurationData, undefined, 2),
66a7748d
JB
1754 'utf8'
1755 )
1756 PerformanceStatistics.endMeasure(measureId, beginId)
1757 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash)
1758 this.sharedLRUCache.setChargingStationConfiguration(configurationData)
1759 this.configurationFileHash = configurationHash
ea32ea05 1760 }).catch((error: unknown) => {
0ebf7c2e
JB
1761 handleFileException(
1762 this.configurationFile,
1763 FileType.ChargingStationConfiguration,
1764 error as NodeJS.ErrnoException,
66a7748d
JB
1765 this.logPrefix()
1766 )
1767 })
7c72977b
JB
1768 } else {
1769 logger.debug(
1770 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1771 this.configurationFile
66a7748d
JB
1772 }`
1773 )
2484ac1e 1774 }
2484ac1e 1775 } catch (error) {
fa5995d6 1776 handleFileException(
2484ac1e 1777 this.configurationFile,
7164966d
JB
1778 FileType.ChargingStationConfiguration,
1779 error as NodeJS.ErrnoException,
66a7748d
JB
1780 this.logPrefix()
1781 )
073bd098 1782 }
2484ac1e
JB
1783 } else {
1784 logger.error(
66a7748d
JB
1785 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1786 )
073bd098
JB
1787 }
1788 }
1789
66a7748d
JB
1790 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration | undefined {
1791 return this.getTemplateFromFile()?.Configuration
2484ac1e
JB
1792 }
1793
52c58949
JB
1794 private getOcppConfigurationFromFile (
1795 ocppPersistentConfiguration?: boolean
1796 ): ChargingStationOcppConfiguration | undefined {
66a7748d 1797 const configurationKey = this.getConfigurationFromFile()?.configurationKey
52c58949 1798 if (ocppPersistentConfiguration === true && Array.isArray(configurationKey)) {
66a7748d 1799 return { configurationKey }
648512ce 1800 }
66a7748d 1801 return undefined
7dde0b73
JB
1802 }
1803
52c58949 1804 private getOcppConfiguration (
1feac591 1805 ocppPersistentConfiguration: boolean | undefined = this.stationInfo?.ocppPersistentConfiguration
52c58949 1806 ): ChargingStationOcppConfiguration | undefined {
551e477c 1807 let ocppConfiguration: ChargingStationOcppConfiguration | undefined =
52c58949 1808 this.getOcppConfigurationFromFile(ocppPersistentConfiguration)
66a7748d
JB
1809 if (ocppConfiguration == null) {
1810 ocppConfiguration = this.getOcppConfigurationFromTemplate()
2484ac1e 1811 }
66a7748d 1812 return ocppConfiguration
2484ac1e
JB
1813 }
1814
66a7748d
JB
1815 private async onOpen (): Promise<void> {
1816 if (this.isWebSocketConnectionOpened()) {
5c0e9352 1817 this.emit(ChargingStationEvents.updated)
5144f4d1 1818 logger.info(
1d41bc6b 1819 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} succeeded`
66a7748d
JB
1820 )
1821 let registrationRetryCount = 0
1822 if (!this.isRegistered()) {
5144f4d1 1823 // Send BootNotification
5144f4d1 1824 do {
f7f98c68 1825 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
66a7748d
JB
1826 BootNotificationRequest,
1827 BootNotificationResponse
8bfbc743 1828 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
66a7748d
JB
1829 skipBufferingOnError: true
1830 })
01d2a2c7
JB
1831 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1832 if (this.bootNotificationResponse?.currentTime != null) {
1833 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1834 this.bootNotificationResponse.currentTime = convertToDate(
1835 this.bootNotificationResponse.currentTime
1836 )!
1837 }
66a7748d
JB
1838 if (!this.isRegistered()) {
1839 this.stationInfo?.registrationMaxRetries !== -1 && ++registrationRetryCount
9bf0ef23 1840 await sleep(
5199f9fd 1841 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
73b78a1f 1842 this.bootNotificationResponse?.interval != null
be4c6702 1843 ? secondsToMilliseconds(this.bootNotificationResponse.interval)
66a7748d
JB
1844 : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1845 )
5144f4d1
JB
1846 }
1847 } while (
66a7748d
JB
1848 !this.isRegistered() &&
1849 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
5199f9fd 1850 (registrationRetryCount <= this.stationInfo!.registrationMaxRetries! ||
9a77cc07 1851 this.stationInfo?.registrationMaxRetries === -1)
66a7748d 1852 )
5144f4d1 1853 }
66a7748d
JB
1854 if (this.isRegistered()) {
1855 this.emit(ChargingStationEvents.registered)
1856 if (this.inAcceptedState()) {
1857 this.emit(ChargingStationEvents.accepted)
c0560973 1858 }
5144f4d1 1859 } else {
e054fc1c
JB
1860 if (this.inRejectedState()) {
1861 this.emit(ChargingStationEvents.rejected)
1862 }
5144f4d1 1863 logger.error(
a223d9be
JB
1864 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${
1865 this.stationInfo?.registrationMaxRetries
1866 })`
66a7748d 1867 )
caad9d6b 1868 }
2960841f 1869 this.wsConnectionRetryCount = 0
66a7748d 1870 this.emit(ChargingStationEvents.updated)
2e6f5966 1871 } else {
5144f4d1 1872 logger.warn(
1d41bc6b 1873 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} failed`
66a7748d 1874 )
2e6f5966 1875 }
2e6f5966
JB
1876 }
1877
ba9a56a6 1878 private onClose (code: WebSocketCloseEventStatusCode, reason: Buffer): void {
e054fc1c 1879 this.emit(ChargingStationEvents.disconnected)
5c0e9352 1880 this.emit(ChargingStationEvents.updated)
d09085e9 1881 switch (code) {
6c65a295
JB
1882 // Normal close
1883 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 1884 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18 1885 logger.info(
9bf0ef23 1886 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
66a7748d
JB
1887 code
1888 )}' and reason '${reason.toString()}'`
1889 )
2960841f 1890 this.wsConnectionRetryCount = 0
66a7748d 1891 break
6c65a295
JB
1892 // Abnormal close
1893 default:
e7aeea18 1894 logger.error(
9bf0ef23 1895 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
66a7748d
JB
1896 code
1897 )}' and reason '${reason.toString()}'`
1898 )
7c974155 1899 this.started &&
5c0e9352
JB
1900 this.reconnect()
1901 .then(() => {
1902 this.emit(ChargingStationEvents.updated)
1903 })
ea32ea05
JB
1904 .catch((error: unknown) =>
1905 logger.error(`${this.logPrefix()} Error while reconnecting:`, error)
1906 )
66a7748d 1907 break
c0560973 1908 }
2e6f5966
JB
1909 }
1910
c510c989
JB
1911 private getCachedRequest (
1912 messageType: MessageType | undefined,
1913 messageId: string
1914 ): CachedRequest | undefined {
66a7748d
JB
1915 const cachedRequest = this.requests.get(messageId)
1916 if (Array.isArray(cachedRequest)) {
1917 return cachedRequest
56d09fd7
JB
1918 }
1919 throw new OCPPError(
1920 ErrorType.PROTOCOL_ERROR,
041365be 1921 `Cached request for message id ${messageId} ${getMessageTypeString(
66a7748d 1922 messageType
56d09fd7
JB
1923 )} is not an array`,
1924 undefined,
66a7748d
JB
1925 cachedRequest
1926 )
56d09fd7
JB
1927 }
1928
66a7748d
JB
1929 private async handleIncomingMessage (request: IncomingRequest): Promise<void> {
1930 const [messageType, messageId, commandName, commandPayload] = request
9a77cc07 1931 if (this.stationInfo?.enableStatistics === true) {
66a7748d 1932 this.performanceStatistics?.addRequestStatistic(commandName, messageType)
56d09fd7
JB
1933 }
1934 logger.debug(
1935 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
66a7748d
JB
1936 request
1937 )}`
1938 )
56d09fd7
JB
1939 // Process the message
1940 await this.ocppIncomingRequestService.incomingRequestHandler(
1941 this,
1942 messageId,
1943 commandName,
66a7748d
JB
1944 commandPayload
1945 )
1946 this.emit(ChargingStationEvents.updated)
56d09fd7
JB
1947 }
1948
66a7748d
JB
1949 private handleResponseMessage (response: Response): void {
1950 const [messageType, messageId, commandPayload] = response
1951 if (!this.requests.has(messageId)) {
56d09fd7
JB
1952 // Error
1953 throw new OCPPError(
1954 ErrorType.INTERNAL_ERROR,
1955 `Response for unknown message id ${messageId}`,
1956 undefined,
66a7748d
JB
1957 commandPayload
1958 )
56d09fd7
JB
1959 }
1960 // Respond
66a7748d 1961 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
56d09fd7
JB
1962 const [responseCallback, , requestCommandName, requestPayload] = this.getCachedRequest(
1963 messageType,
66a7748d
JB
1964 messageId
1965 )!
56d09fd7 1966 logger.debug(
5199f9fd
JB
1967 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1968 response
1969 )}`
66a7748d
JB
1970 )
1971 responseCallback(commandPayload, requestPayload)
56d09fd7
JB
1972 }
1973
66a7748d
JB
1974 private handleErrorMessage (errorResponse: ErrorResponse): void {
1975 const [messageType, messageId, errorType, errorMessage, errorDetails] = errorResponse
1976 if (!this.requests.has(messageId)) {
56d09fd7
JB
1977 // Error
1978 throw new OCPPError(
1979 ErrorType.INTERNAL_ERROR,
1980 `Error response for unknown message id ${messageId}`,
1981 undefined,
66a7748d
JB
1982 { errorType, errorMessage, errorDetails }
1983 )
56d09fd7 1984 }
66a7748d
JB
1985 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1986 const [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!
56d09fd7 1987 logger.debug(
5199f9fd
JB
1988 `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify(
1989 errorResponse
1990 )}`
66a7748d
JB
1991 )
1992 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails))
56d09fd7
JB
1993 }
1994
66a7748d
JB
1995 private async onMessage (data: RawData): Promise<void> {
1996 let request: IncomingRequest | Response | ErrorResponse | undefined
1997 let messageType: MessageType | undefined
1998 let errorMsg: string
c0560973 1999 try {
e1d9a0f4 2000 // eslint-disable-next-line @typescript-eslint/no-base-to-string
66a7748d
JB
2001 request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse
2002 if (Array.isArray(request)) {
2003 [messageType] = request
b3ec7bc1
JB
2004 // Check the type of message
2005 switch (messageType) {
2006 // Incoming Message
2007 case MessageType.CALL_MESSAGE:
66a7748d
JB
2008 await this.handleIncomingMessage(request as IncomingRequest)
2009 break
56d09fd7 2010 // Response Message
b3ec7bc1 2011 case MessageType.CALL_RESULT_MESSAGE:
66a7748d
JB
2012 this.handleResponseMessage(request as Response)
2013 break
a2d1c0f1
JB
2014 // Error Message
2015 case MessageType.CALL_ERROR_MESSAGE:
66a7748d
JB
2016 this.handleErrorMessage(request as ErrorResponse)
2017 break
56d09fd7 2018 // Unknown Message
b3ec7bc1
JB
2019 default:
2020 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
66a7748d
JB
2021 errorMsg = `Wrong message type ${messageType}`
2022 logger.error(`${this.logPrefix()} ${errorMsg}`)
2023 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errorMsg)
b3ec7bc1 2024 }
47e22477 2025 } else {
e1d9a0f4
JB
2026 throw new OCPPError(
2027 ErrorType.PROTOCOL_ERROR,
2028 'Incoming message is not an array',
2029 undefined,
2030 {
66a7748d
JB
2031 request
2032 }
2033 )
47e22477 2034 }
c0560973 2035 } catch (error) {
c3c8ae3f
JB
2036 if (!Array.isArray(request)) {
2037 logger.error(`${this.logPrefix()} Incoming message '${request}' parsing error:`, error)
2038 return
2039 }
66a7748d
JB
2040 let commandName: IncomingRequestCommand | undefined
2041 let requestCommandName: RequestCommand | IncomingRequestCommand | undefined
2042 let errorCallback: ErrorCallback
c3c8ae3f 2043 const [, messageId] = request
13701f69
JB
2044 switch (messageType) {
2045 case MessageType.CALL_MESSAGE:
66a7748d 2046 [, , commandName] = request as IncomingRequest
13701f69 2047 // Send error
66a7748d
JB
2048 await this.ocppRequestService.sendError(this, messageId, error as OCPPError, commandName)
2049 break
13701f69
JB
2050 case MessageType.CALL_RESULT_MESSAGE:
2051 case MessageType.CALL_ERROR_MESSAGE:
66a7748d
JB
2052 if (this.requests.has(messageId)) {
2053 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2054 [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!
13701f69 2055 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
66a7748d 2056 errorCallback(error as OCPPError, false)
13701f69
JB
2057 } else {
2058 // Remove the request from the cache in case of error at response handling
66a7748d 2059 this.requests.delete(messageId)
13701f69 2060 }
66a7748d 2061 break
ba7965c4 2062 }
66a7748d 2063 if (!(error instanceof OCPPError)) {
56d09fd7
JB
2064 logger.warn(
2065 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1feac591 2066 commandName ?? requestCommandName ?? Constants.UNKNOWN_OCPP_COMMAND
e1d9a0f4 2067 // eslint-disable-next-line @typescript-eslint/no-base-to-string
56d09fd7 2068 }' message '${data.toString()}' handling is not an OCPPError:`,
66a7748d
JB
2069 error
2070 )
56d09fd7
JB
2071 }
2072 logger.error(
2073 `${this.logPrefix()} Incoming OCPP command '${
1feac591 2074 commandName ?? requestCommandName ?? Constants.UNKNOWN_OCPP_COMMAND
e1d9a0f4 2075 // eslint-disable-next-line @typescript-eslint/no-base-to-string
56d09fd7 2076 }' message '${data.toString()}'${
c510c989
JB
2077 this.requests.has(messageId)
2078 ? ` matching cached request '${JSON.stringify(this.getCachedRequest(messageType, messageId))}'`
56d09fd7
JB
2079 : ''
2080 } processing error:`,
66a7748d
JB
2081 error
2082 )
c0560973 2083 }
2328be1e
JB
2084 }
2085
66a7748d
JB
2086 private onPing (): void {
2087 logger.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
c0560973
JB
2088 }
2089
66a7748d
JB
2090 private onPong (): void {
2091 logger.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
c0560973
JB
2092 }
2093
66a7748d
JB
2094 private onError (error: WSError): void {
2095 this.closeWSConnection()
2096 logger.error(`${this.logPrefix()} WebSocket error:`, error)
c0560973
JB
2097 }
2098
f938317f
JB
2099 private getEnergyActiveImportRegister (
2100 connectorStatus: ConnectorStatus | undefined,
2101 rounded = false
2102 ): number {
5398cecf 2103 if (this.stationInfo?.meteringPerTransaction === true) {
07989fad 2104 return (
66a7748d 2105 (rounded
f938317f
JB
2106 ? connectorStatus?.transactionEnergyActiveImportRegisterValue != null
2107 ? Math.round(connectorStatus.transactionEnergyActiveImportRegisterValue)
2108 : undefined
2109 : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0
66a7748d 2110 )
07989fad
JB
2111 }
2112 return (
66a7748d 2113 (rounded
f938317f
JB
2114 ? connectorStatus?.energyActiveImportRegisterValue != null
2115 ? Math.round(connectorStatus.energyActiveImportRegisterValue)
2116 : undefined
2117 : connectorStatus?.energyActiveImportRegisterValue) ?? 0
66a7748d 2118 )
07989fad
JB
2119 }
2120
66a7748d 2121 private getUseConnectorId0 (stationTemplate?: ChargingStationTemplate): boolean {
1feac591
JB
2122 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2123 return stationTemplate?.useConnectorId0 ?? Constants.DEFAULT_STATION_INFO.useConnectorId0!
8bce55bf
JB
2124 }
2125
66a7748d 2126 private async stopRunningTransactions (reason?: StopTransactionReason): Promise<void> {
28e78158 2127 if (this.hasEvses) {
3fa7f799
JB
2128 for (const [evseId, evseStatus] of this.evses) {
2129 if (evseId === 0) {
66a7748d 2130 continue
3fa7f799 2131 }
28e78158
JB
2132 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
2133 if (connectorStatus.transactionStarted === true) {
66a7748d 2134 await this.stopTransactionOnConnector(connectorId, reason)
28e78158
JB
2135 }
2136 }
2137 }
2138 } else {
2139 for (const connectorId of this.connectors.keys()) {
2140 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
66a7748d 2141 await this.stopTransactionOnConnector(connectorId, reason)
28e78158 2142 }
60ddad53
JB
2143 }
2144 }
2145 }
2146
1f761b9a 2147 // 0 for disabling
66a7748d 2148 private getConnectionTimeout (): number {
a807045b 2149 if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut) != null) {
4e3b1d6b 2150 return convertToInt(
5199f9fd 2151 getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)?.value ??
66a7748d
JB
2152 Constants.DEFAULT_CONNECTION_TIMEOUT
2153 )
291cb255 2154 }
66a7748d 2155 return Constants.DEFAULT_CONNECTION_TIMEOUT
3574dfd3
JB
2156 }
2157
66a7748d
JB
2158 private getPowerDivider (): number {
2159 let powerDivider = this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()
be1e907c 2160 if (this.stationInfo?.powerSharedByConnectors === true) {
66a7748d 2161 powerDivider = this.getNumberOfRunningTransactions()
6ecb15e4 2162 }
66a7748d 2163 return powerDivider
6ecb15e4
JB
2164 }
2165
66a7748d
JB
2166 private getMaximumAmperage (stationInfo?: ChargingStationInfo): number | undefined {
2167 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
5199f9fd 2168 const maximumPower = (stationInfo ?? this.stationInfo!).maximumPower!
fa7bccf4 2169 switch (this.getCurrentOutType(stationInfo)) {
cc6e8ab5
JB
2170 case CurrentType.AC:
2171 return ACElectricUtils.amperagePerPhaseFromPower(
fa7bccf4 2172 this.getNumberOfPhases(stationInfo),
b1bbdae5 2173 maximumPower / (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()),
66a7748d
JB
2174 this.getVoltageOut(stationInfo)
2175 )
cc6e8ab5 2176 case CurrentType.DC:
66a7748d 2177 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo))
cc6e8ab5
JB
2178 }
2179 }
2180
66a7748d 2181 private getCurrentOutType (stationInfo?: ChargingStationInfo): CurrentType {
1feac591
JB
2182 return (
2183 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2184 (stationInfo ?? this.stationInfo!).currentOutType ??
2185 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2186 Constants.DEFAULT_STATION_INFO.currentOutType!
2187 )
5398cecf
JB
2188 }
2189
66a7748d 2190 private getVoltageOut (stationInfo?: ChargingStationInfo): Voltage {
74ed61d9 2191 return (
5199f9fd
JB
2192 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2193 (stationInfo ?? this.stationInfo!).voltageOut ??
74ed61d9 2194 getDefaultVoltageOut(this.getCurrentOutType(stationInfo), this.logPrefix(), this.templateFile)
66a7748d 2195 )
5398cecf
JB
2196 }
2197
66a7748d 2198 private getAmperageLimitation (): number | undefined {
cc6e8ab5 2199 if (
9bf0ef23 2200 isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
5dc7c990 2201 getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey) != null
cc6e8ab5
JB
2202 ) {
2203 return (
5dc7c990
JB
2204 convertToInt(getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey)?.value) /
2205 getAmperageLimitationUnitDivider(this.stationInfo)
66a7748d 2206 )
cc6e8ab5
JB
2207 }
2208 }
2209
e054fc1c 2210 private async startMessageSequence (ATGStopAbsoluteDuration?: boolean): Promise<void> {
b7f9e41d 2211 if (this.stationInfo?.autoRegister === true) {
f7f98c68 2212 await this.ocppRequestService.requestHandler<
66a7748d
JB
2213 BootNotificationRequest,
2214 BootNotificationResponse
8bfbc743 2215 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
66a7748d
JB
2216 skipBufferingOnError: true
2217 })
6114e6f1 2218 }
136c90ba 2219 // Start WebSocket ping
66a7748d 2220 this.startWebSocketPing()
5ad8570f 2221 // Start heartbeat
66a7748d 2222 this.startHeartbeat()
0a60c33c 2223 // Initialize connectors status
c3b83130
JB
2224 if (this.hasEvses) {
2225 for (const [evseId, evseStatus] of this.evses) {
4334db72
JB
2226 if (evseId > 0) {
2227 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
66a7748d
JB
2228 const connectorBootStatus = getBootConnectorStatus(this, connectorId, connectorStatus)
2229 await sendAndSetConnectorStatus(this, connectorId, connectorBootStatus, evseId)
4334db72 2230 }
c3b83130 2231 }
4334db72
JB
2232 }
2233 } else {
2234 for (const connectorId of this.connectors.keys()) {
2235 if (connectorId > 0) {
fba11dc6 2236 const connectorBootStatus = getBootConnectorStatus(
c3b83130
JB
2237 this,
2238 connectorId,
66a7748d
JB
2239 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2240 this.getConnectorStatus(connectorId)!
2241 )
2242 await sendAndSetConnectorStatus(this, connectorId, connectorBootStatus)
c3b83130
JB
2243 }
2244 }
5ad8570f 2245 }
5199f9fd 2246 if (this.stationInfo?.firmwareStatus === FirmwareStatus.Installing) {
c9a4f9ea 2247 await this.ocppRequestService.requestHandler<
66a7748d
JB
2248 FirmwareStatusNotificationRequest,
2249 FirmwareStatusNotificationResponse
c9a4f9ea 2250 >(this, RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
66a7748d
JB
2251 status: FirmwareStatus.Installed
2252 })
2253 this.stationInfo.firmwareStatus = FirmwareStatus.Installed
c9a4f9ea 2254 }
3637ca2c 2255
0a60c33c 2256 // Start the ATG
5199f9fd 2257 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable === true) {
e054fc1c 2258 this.startAutomaticTransactionGenerator(undefined, ATGStopAbsoluteDuration)
fa7bccf4 2259 }
66a7748d 2260 this.flushMessageBuffer()
fa7bccf4
JB
2261 }
2262
e054fc1c 2263 private internalStopMessageSequence (): void {
136c90ba 2264 // Stop WebSocket ping
66a7748d 2265 this.stopWebSocketPing()
79411696 2266 // Stop heartbeat
66a7748d 2267 this.stopHeartbeat()
9ff486f4 2268 // Stop the ATG
b20eb107 2269 if (this.automaticTransactionGenerator?.started === true) {
66a7748d 2270 this.stopAutomaticTransactionGenerator()
79411696 2271 }
e054fc1c
JB
2272 }
2273
2274 private async stopMessageSequence (
2275 reason?: StopTransactionReason,
7e3bde4f 2276 stopTransactions?: boolean
e054fc1c
JB
2277 ): Promise<void> {
2278 this.internalStopMessageSequence()
3e888c65 2279 // Stop ongoing transactions
66a7748d 2280 stopTransactions === true && (await this.stopRunningTransactions(reason))
039211f9
JB
2281 if (this.hasEvses) {
2282 for (const [evseId, evseStatus] of this.evses) {
2283 if (evseId > 0) {
2284 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
e054fc1c 2285 await sendAndSetConnectorStatus(
039211f9 2286 this,
e054fc1c
JB
2287 connectorId,
2288 ConnectorStatusEnum.Unavailable,
2289 evseId
66a7748d 2290 )
5199f9fd 2291 delete connectorStatus.status
039211f9
JB
2292 }
2293 }
2294 }
2295 } else {
2296 for (const connectorId of this.connectors.keys()) {
2297 if (connectorId > 0) {
e054fc1c 2298 await sendAndSetConnectorStatus(this, connectorId, ConnectorStatusEnum.Unavailable)
66a7748d 2299 delete this.getConnectorStatus(connectorId)?.status
039211f9 2300 }
45c0ae82
JB
2301 }
2302 }
79411696
JB
2303 }
2304
66a7748d 2305 private startWebSocketPing (): void {
97608fbd 2306 const webSocketPingInterval =
a807045b 2307 getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval) != null
4e3b1d6b 2308 ? convertToInt(
66a7748d
JB
2309 getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value
2310 )
2311 : 0
2960841f
JB
2312 if (webSocketPingInterval > 0 && this.wsPingSetInterval == null) {
2313 this.wsPingSetInterval = setInterval(() => {
66a7748d
JB
2314 if (this.isWebSocketConnectionOpened()) {
2315 this.wsConnection?.ping()
136c90ba 2316 }
66a7748d 2317 }, secondsToMilliseconds(webSocketPingInterval))
e7aeea18 2318 logger.info(
9bf0ef23 2319 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
66a7748d
JB
2320 webSocketPingInterval
2321 )}`
2322 )
2960841f 2323 } else if (this.wsPingSetInterval != null) {
e7aeea18 2324 logger.info(
9bf0ef23 2325 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
66a7748d
JB
2326 webSocketPingInterval
2327 )}`
2328 )
136c90ba 2329 } else {
e7aeea18 2330 logger.error(
66a7748d
JB
2331 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2332 )
136c90ba
JB
2333 }
2334 }
2335
66a7748d 2336 private stopWebSocketPing (): void {
2960841f
JB
2337 if (this.wsPingSetInterval != null) {
2338 clearInterval(this.wsPingSetInterval)
2339 delete this.wsPingSetInterval
136c90ba
JB
2340 }
2341 }
2342
66a7748d
JB
2343 private getConfiguredSupervisionUrl (): URL {
2344 let configuredSupervisionUrl: string
2345 const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls()
9bf0ef23 2346 if (isNotEmptyArray(supervisionUrls)) {
66a7748d 2347 let configuredSupervisionUrlIndex: number
2dcfe98e 2348 switch (Configuration.getSupervisionUrlDistribution()) {
2dcfe98e 2349 case SupervisionUrlDistribution.RANDOM:
5dc7c990 2350 configuredSupervisionUrlIndex = Math.floor(secureRandom() * supervisionUrls.length)
66a7748d 2351 break
a52a6446 2352 case SupervisionUrlDistribution.ROUND_ROBIN:
c72f6634 2353 case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY:
2dcfe98e 2354 default:
66a7748d
JB
2355 !Object.values(SupervisionUrlDistribution).includes(
2356 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2357 Configuration.getSupervisionUrlDistribution()!
2358 ) &&
ae61fa2f 2359 logger.warn(
e1d9a0f4 2360 // eslint-disable-next-line @typescript-eslint/no-base-to-string
81c74884 2361 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' in configuration from values '${SupervisionUrlDistribution.toString()}', defaulting to '${
a52a6446 2362 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
81c74884 2363 }'`
66a7748d 2364 )
5dc7c990 2365 configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length
66a7748d 2366 break
c0560973 2367 }
5dc7c990 2368 configuredSupervisionUrl = supervisionUrls[configuredSupervisionUrlIndex]
d5c3df49 2369 } else {
5dc7c990
JB
2370 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2371 configuredSupervisionUrl = supervisionUrls!
d5c3df49 2372 }
9bf0ef23 2373 if (isNotEmptyString(configuredSupervisionUrl)) {
66a7748d 2374 return new URL(configuredSupervisionUrl)
c0560973 2375 }
66a7748d
JB
2376 const errorMsg = 'No supervision url(s) configured'
2377 logger.error(`${this.logPrefix()} ${errorMsg}`)
5199f9fd 2378 throw new BaseError(errorMsg)
136c90ba
JB
2379 }
2380
66a7748d 2381 private stopHeartbeat (): void {
a807045b 2382 if (this.heartbeatSetInterval != null) {
66a7748d
JB
2383 clearInterval(this.heartbeatSetInterval)
2384 delete this.heartbeatSetInterval
7dde0b73 2385 }
5ad8570f
JB
2386 }
2387
66a7748d
JB
2388 private terminateWSConnection (): void {
2389 if (this.isWebSocketConnectionOpened()) {
2390 this.wsConnection?.terminate()
2391 this.wsConnection = null
55516218
JB
2392 }
2393 }
2394
66a7748d 2395 private async reconnect (): Promise<void> {
e7aeea18 2396 if (
66a7748d 2397 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2960841f 2398 this.wsConnectionRetryCount < this.stationInfo!.autoReconnectMaxRetries! ||
5398cecf 2399 this.stationInfo?.autoReconnectMaxRetries === -1
e7aeea18 2400 ) {
2960841f
JB
2401 this.wsConnectionRetried = true
2402 ++this.wsConnectionRetryCount
5398cecf
JB
2403 const reconnectDelay =
2404 this.stationInfo?.reconnectExponentialDelay === true
2960841f 2405 ? exponentialDelay(this.wsConnectionRetryCount)
66a7748d
JB
2406 : secondsToMilliseconds(this.getConnectionTimeout())
2407 const reconnectDelayWithdraw = 1000
1e080116 2408 const reconnectTimeout =
5199f9fd 2409 reconnectDelay - reconnectDelayWithdraw > 0 ? reconnectDelay - reconnectDelayWithdraw : 0
e7aeea18 2410 logger.error(
9bf0ef23 2411 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
e7aeea18 2412 reconnectDelay,
66a7748d
JB
2413 2
2414 )}ms, timeout ${reconnectTimeout}ms`
2415 )
2416 await sleep(reconnectDelay)
e7aeea18 2417 logger.error(
2960841f 2418 `${this.logPrefix()} WebSocket connection retry #${this.wsConnectionRetryCount.toString()}`
66a7748d 2419 )
e7aeea18 2420 this.openWSConnection(
59b6ed8d 2421 {
66a7748d 2422 handshakeTimeout: reconnectTimeout
59b6ed8d 2423 },
66a7748d
JB
2424 { closeOpened: true }
2425 )
5398cecf 2426 } else if (this.stationInfo?.autoReconnectMaxRetries !== -1) {
e7aeea18 2427 logger.error(
d56ea27c 2428 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2960841f 2429 this.wsConnectionRetryCount
66a7748d
JB
2430 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`
2431 )
5ad8570f
JB
2432 }
2433 }
7dde0b73 2434}