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