1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { createHash
} from
'node:crypto'
4 import { EventEmitter
} from
'node:events'
5 import { type FSWatcher
, existsSync
, mkdirSync
, readFileSync
, writeFileSync
} from
'node:fs'
6 import { dirname
, join
} from
'node:path'
7 import { URL
} from
'node:url'
8 import { parentPort
} from
'node:worker_threads'
10 import { millisecondsToSeconds
, secondsToMilliseconds
} from
'date-fns'
11 import merge from
'just-merge'
12 import { type RawData
, WebSocket
} from
'ws'
14 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator.js'
15 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel.js'
18 deleteConfigurationKey
,
20 setConfigurationKeyValue
21 } from
'./ConfigurationKeyUtils.js'
26 checkConnectorsConfiguration
,
27 checkStationInfoConnectorStatus
,
29 createBootNotificationRequest
,
31 getAmperageLimitationUnitDivider
,
32 getBootConnectorStatus
,
33 getChargingStationConnectorChargingProfilesPowerLimit
,
39 getNumberOfReservableConnectors
,
40 getPhaseRotationValue
,
42 hasReservationExpired
,
43 initializeConnectorsMapStatus
,
44 propagateSerialNumber
,
45 stationTemplateToStationInfo
,
46 warnTemplateKeysDeprecation
48 import { IdTagsCache
} from
'./IdTagsCache.js'
50 OCPP16IncomingRequestService
,
52 OCPP16ResponseService
,
53 OCPP20IncomingRequestService
,
55 OCPP20ResponseService
,
56 type OCPPIncomingRequestService
,
57 type OCPPRequestService
,
59 buildTransactionEndMeterValue
,
61 sendAndSetConnectorStatus
62 } from
'./ocpp/index.js'
63 import { SharedLRUCache
} from
'./SharedLRUCache.js'
64 import { BaseError
, OCPPError
} from
'../exception/index.js'
65 import { PerformanceStatistics
} from
'../performance/index.js'
67 type AutomaticTransactionGeneratorConfiguration
,
69 type BootNotificationRequest
,
70 type BootNotificationResponse
,
72 type ChargingStationConfiguration
,
73 ChargingStationEvents
,
74 type ChargingStationInfo
,
75 type ChargingStationOcppConfiguration
,
76 type ChargingStationTemplate
,
84 type EvseStatusConfiguration
,
87 type FirmwareStatusNotificationRequest
,
88 type FirmwareStatusNotificationResponse
,
90 type HeartbeatRequest
,
91 type HeartbeatResponse
,
93 type IncomingRequestCommand
,
96 type MeterValuesRequest
,
97 type MeterValuesResponse
,
101 RegistrationStatusEnumType
,
105 ReservationTerminationReason
,
107 StandardParametersKey
,
109 type StopTransactionReason
,
110 type StopTransactionRequest
,
111 type StopTransactionResponse
,
112 SupervisionUrlDistribution
,
113 SupportedFeatureProfiles
,
116 WebSocketCloseEventStatusCode
,
118 } from
'../types/index.js'
126 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
127 buildConnectorsStatus
,
137 formatDurationMilliSeconds
,
138 formatDurationSeconds
,
140 getWebSocketCloseEventStatusString
,
152 } from
'../utils/index.js'
154 export class ChargingStation
extends EventEmitter
{
155 public readonly index
: number
156 public readonly templateFile
: string
157 public stationInfo
?: ChargingStationInfo
158 public started
: boolean
159 public starting
: boolean
160 public idTagsCache
: IdTagsCache
161 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined
162 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined
163 public wsConnection
: WebSocket
| null
164 public readonly connectors
: Map
<number, ConnectorStatus
>
165 public readonly evses
: Map
<number, EvseStatus
>
166 public readonly requests
: Map
<string, CachedRequest
>
167 public performanceStatistics
!: PerformanceStatistics
| undefined
168 public heartbeatSetInterval
?: NodeJS
.Timeout
169 public ocppRequestService
!: OCPPRequestService
170 public bootNotificationRequest
?: BootNotificationRequest
171 public bootNotificationResponse
?: BootNotificationResponse
172 public powerDivider
?: number
173 private stopping
: boolean
174 private configurationFile
!: string
175 private configurationFileHash
!: string
176 private connectorsConfigurationHash
!: string
177 private evsesConfigurationHash
!: string
178 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
179 private ocppIncomingRequestService
!: OCPPIncomingRequestService
180 private readonly messageBuffer
: Set
<string>
181 private configuredSupervisionUrl
!: URL
182 private wsConnectionRetried
: boolean
183 private wsConnectionRetryCount
: number
184 private templateFileWatcher
!: FSWatcher
| undefined
185 private templateFileHash
!: string
186 private readonly sharedLRUCache
: SharedLRUCache
187 private wsPingSetInterval
?: NodeJS
.Timeout
188 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
189 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
191 constructor (index
: number, templateFile
: string) {
194 this.starting
= false
195 this.stopping
= false
196 this.wsConnection
= null
197 this.wsConnectionRetried
= false
198 this.wsConnectionRetryCount
= 0
200 this.templateFile
= templateFile
201 this.connectors
= new Map
<number, ConnectorStatus
>()
202 this.evses
= new Map
<number, EvseStatus
>()
203 this.requests
= new Map
<string, CachedRequest
>()
204 this.messageBuffer
= new Set
<string>()
205 this.sharedLRUCache
= SharedLRUCache
.getInstance()
206 this.idTagsCache
= IdTagsCache
.getInstance()
207 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this)
209 this.on(ChargingStationEvents
.started
, () => {
210 parentPort
?.postMessage(buildStartedMessage(this))
212 this.on(ChargingStationEvents
.stopped
, () => {
213 parentPort
?.postMessage(buildStoppedMessage(this))
215 this.on(ChargingStationEvents
.updated
, () => {
216 parentPort
?.postMessage(buildUpdatedMessage(this))
218 this.on(ChargingStationEvents
.accepted
, () => {
219 this.startMessageSequence(
220 this.wsConnectionRetried
222 : this.getAutomaticTransactionGeneratorConfiguration()?.stopAbsoluteDuration
224 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
)
226 this.wsConnectionRetried
= false
228 this.on(ChargingStationEvents
.disconnected
, () => {
230 this.internalStopMessageSequence()
233 `${this.logPrefix()} Error while stopping the internal message sequence:`,
242 public get
hasEvses (): boolean {
243 return this.connectors
.size
=== 0 && this.evses
.size
> 0
246 private get
wsConnectionUrl (): URL
{
249 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
250 isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
251 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value)
252 ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value
253 : this.configuredSupervisionUrl.href
254 }/${this.stationInfo?.chargingStationId}`
258 public logPrefix
= (): string => {
260 this instanceof ChargingStation
&&
261 this.stationInfo
!= null &&
262 isNotEmptyString(this.stationInfo
.chargingStationId
)
264 return logPrefix(` ${this.stationInfo.chargingStationId} |`)
266 let stationTemplate
: ChargingStationTemplate
| undefined
268 stationTemplate
= JSON
.parse(
269 readFileSync(this.templateFile
, 'utf8')
270 ) as ChargingStationTemplate
272 stationTemplate
= undefined
274 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`)
277 public hasIdTags (): boolean {
278 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
279 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
!)!))
282 public getNumberOfPhases (stationInfo
?: ChargingStationInfo
): number {
283 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
284 const localStationInfo
= stationInfo
?? this.stationInfo
!
285 switch (this.getCurrentOutType(stationInfo
)) {
287 return localStationInfo
.numberOfPhases
?? 3
293 public isWebSocketConnectionOpened (): boolean {
294 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
297 public inUnknownState (): boolean {
298 return this.bootNotificationResponse
?.status == null
301 public inPendingState (): boolean {
302 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
305 public inAcceptedState (): boolean {
306 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
309 public inRejectedState (): boolean {
310 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
313 public isRegistered (): boolean {
314 return !this.inUnknownState() && (this.inAcceptedState() || this.inPendingState())
317 public isChargingStationAvailable (): boolean {
318 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
321 public hasConnector (connectorId
: number): boolean {
323 for (const evseStatus
of this.evses
.values()) {
324 if (evseStatus
.connectors
.has(connectorId
)) {
330 return this.connectors
.has(connectorId
)
333 public isConnectorAvailable (connectorId
: number): boolean {
336 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
340 public getNumberOfConnectors (): number {
342 let numberOfConnectors
= 0
343 for (const [evseId
, evseStatus
] of this.evses
) {
345 numberOfConnectors
+= evseStatus
.connectors
.size
348 return numberOfConnectors
350 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
353 public getNumberOfEvses (): number {
354 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
357 public getConnectorStatus (connectorId
: number): ConnectorStatus
| undefined {
359 for (const evseStatus
of this.evses
.values()) {
360 if (evseStatus
.connectors
.has(connectorId
)) {
361 return evseStatus
.connectors
.get(connectorId
)
366 return this.connectors
.get(connectorId
)
369 public getConnectorMaximumAvailablePower (connectorId
: number): number {
370 let connectorAmperageLimitationPowerLimit
: number | undefined
371 const amperageLimitation
= this.getAmperageLimitation()
373 amperageLimitation
!= null &&
374 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
375 amperageLimitation
< this.stationInfo
!.maximumAmperage
!
377 connectorAmperageLimitationPowerLimit
=
378 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
379 ? ACElectricUtils
.powerTotal(
380 this.getNumberOfPhases(),
381 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
382 this.stationInfo
.voltageOut
!,
384 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
386 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
387 DCElectricUtils
.power(this.stationInfo
!.voltageOut
!, amperageLimitation
)) /
388 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
391 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
392 const connectorMaximumPower
= this.stationInfo
!.maximumPower
! / this.powerDivider
!
393 const connectorChargingProfilesPowerLimit
=
394 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
)
396 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
397 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
398 isNaN(connectorAmperageLimitationPowerLimit
!)
400 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
401 connectorAmperageLimitationPowerLimit
!,
402 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
403 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!
407 public getTransactionIdTag (transactionId
: number): string | undefined {
409 for (const evseStatus
of this.evses
.values()) {
410 for (const connectorStatus
of evseStatus
.connectors
.values()) {
411 if (connectorStatus
.transactionId
=== transactionId
) {
412 return connectorStatus
.transactionIdTag
417 for (const connectorId
of this.connectors
.keys()) {
418 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
419 return this.getConnectorStatus(connectorId
)?.transactionIdTag
425 public getNumberOfRunningTransactions (): number {
426 let numberOfRunningTransactions
= 0
428 for (const [evseId
, evseStatus
] of this.evses
) {
432 for (const connectorStatus
of evseStatus
.connectors
.values()) {
433 if (connectorStatus
.transactionStarted
=== true) {
434 ++numberOfRunningTransactions
439 for (const connectorId
of this.connectors
.keys()) {
440 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
441 ++numberOfRunningTransactions
445 return numberOfRunningTransactions
448 public getConnectorIdByTransactionId (transactionId
: number | undefined): number | undefined {
449 if (transactionId
== null) {
451 } else if (this.hasEvses
) {
452 for (const evseStatus
of this.evses
.values()) {
453 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
454 if (connectorStatus
.transactionId
=== transactionId
) {
460 for (const connectorId
of this.connectors
.keys()) {
461 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
468 public getEnergyActiveImportRegisterByTransactionId (
469 transactionId
: number | undefined,
472 return this.getEnergyActiveImportRegister(
473 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
474 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!),
479 public getEnergyActiveImportRegisterByConnectorId (connectorId
: number, rounded
= false): number {
480 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
)
483 public getAuthorizeRemoteTxRequests (): boolean {
484 const authorizeRemoteTxRequests
= getConfigurationKey(
486 StandardParametersKey
.AuthorizeRemoteTxRequests
488 return authorizeRemoteTxRequests
!= null
489 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
493 public getLocalAuthListEnabled (): boolean {
494 const localAuthListEnabled
= getConfigurationKey(
496 StandardParametersKey
.LocalAuthListEnabled
498 return localAuthListEnabled
!= null ? convertToBoolean(localAuthListEnabled
.value
) : false
501 public getHeartbeatInterval (): number {
502 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)
503 if (HeartbeatInterval
!= null) {
504 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
))
506 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)
507 if (HeartBeatInterval
!= null) {
508 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
))
510 this.stationInfo
?.autoRegister
=== false &&
512 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
513 Constants.DEFAULT_HEARTBEAT_INTERVAL
516 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
519 public setSupervisionUrl (url
: string): void {
521 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
522 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
)
524 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
, url
)
526 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
527 this.stationInfo
!.supervisionUrls
= url
528 this.saveStationInfo()
529 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
533 public startHeartbeat (): void {
534 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
== null) {
535 this.heartbeatSetInterval
= setInterval(() => {
536 this.ocppRequestService
537 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
540 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
544 }, this.getHeartbeatInterval())
546 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
547 this.getHeartbeatInterval()
550 } else if (this.heartbeatSetInterval
!= null) {
552 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
553 this.getHeartbeatInterval()
558 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
563 public restartHeartbeat (): void {
567 this.startHeartbeat()
570 public restartWebSocketPing (): void {
571 // Stop WebSocket ping
572 this.stopWebSocketPing()
573 // Start WebSocket ping
574 this.startWebSocketPing()
577 public startMeterValues (connectorId
: number, interval
: number): void {
578 if (connectorId
=== 0) {
579 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`)
582 const connectorStatus
= this.getConnectorStatus(connectorId
)
583 if (connectorStatus
== null) {
585 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
590 if (connectorStatus
.transactionStarted
=== false) {
592 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
596 connectorStatus
.transactionStarted
=== true &&
597 connectorStatus
.transactionId
== null
600 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
605 connectorStatus
.transactionSetInterval
= setInterval(() => {
606 const meterValue
= buildMeterValue(
609 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
610 connectorStatus
.transactionId
!,
613 this.ocppRequestService
614 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
616 RequestCommand
.METER_VALUES
,
619 transactionId
: connectorStatus
.transactionId
,
620 meterValue
: [meterValue
]
625 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
632 `${this.logPrefix()} Charging station ${
633 StandardParametersKey.MeterValueSampleInterval
634 } configuration set to ${interval}, not sending MeterValues`
639 public stopMeterValues (connectorId
: number): void {
640 const connectorStatus
= this.getConnectorStatus(connectorId
)
641 if (connectorStatus
?.transactionSetInterval
!= null) {
642 clearInterval(connectorStatus
.transactionSetInterval
)
646 public start (): void {
648 if (!this.starting
) {
650 if (this.stationInfo
?.enableStatistics
=== true) {
651 this.performanceStatistics
?.start()
653 this.openWSConnection()
654 // Monitor charging station template file
655 this.templateFileWatcher
= watchJsonFile(
657 FileType
.ChargingStationTemplate
,
660 (event
, filename
): void => {
661 if (isNotEmptyString(filename
) && event
=== 'change') {
664 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
666 } file have changed, reload`
668 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
671 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
672 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
!)!)
674 const ATGStarted
= this.automaticTransactionGenerator
?.started
675 if (ATGStarted
=== true) {
676 this.stopAutomaticTransactionGenerator()
678 delete this.automaticTransactionGeneratorConfiguration
680 this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true &&
683 this.startAutomaticTransactionGenerator(undefined, true)
685 if (this.stationInfo
?.enableStatistics
=== true) {
686 this.performanceStatistics
?.restart()
688 this.performanceStatistics
?.stop()
690 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
693 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
701 this.emit(ChargingStationEvents
.started
)
702 this.starting
= false
704 logger
.warn(`${this.logPrefix()} Charging station is already starting...`)
707 logger
.warn(`${this.logPrefix()} Charging station is already started...`)
711 public async stop (reason
?: StopTransactionReason
, stopTransactions
?: boolean): Promise
<void> {
713 if (!this.stopping
) {
715 await this.stopMessageSequence(reason
, stopTransactions
)
716 this.closeWSConnection()
717 if (this.stationInfo
?.enableStatistics
=== true) {
718 this.performanceStatistics
?.stop()
720 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
721 this.templateFileWatcher
?.close()
722 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
723 delete this.bootNotificationResponse
725 this.saveConfiguration()
726 this.emit(ChargingStationEvents
.stopped
)
727 this.stopping
= false
729 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`)
732 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`)
736 public async reset (reason
?: StopTransactionReason
): Promise
<void> {
737 await this.stop(reason
)
738 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
739 await sleep(this.stationInfo
!.resetTime
!)
744 public saveOcppConfiguration (): void {
745 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
746 this.saveConfiguration()
750 public bufferMessage (message
: string): void {
751 this.messageBuffer
.add(message
)
752 this.setIntervalFlushMessageBuffer()
755 public openWSConnection (
757 params
?: { closeOpened
?: boolean, terminateOpened
?: boolean }
760 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
761 ...this.stationInfo
?.wsOptions
,
764 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
}
765 if (!checkChargingStation(this, this.logPrefix())) {
768 if (this.stationInfo
?.supervisionUser
!= null && this.stationInfo
.supervisionPassword
!= null) {
769 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`
771 if (params
.closeOpened
=== true) {
772 this.closeWSConnection()
774 if (params
.terminateOpened
=== true) {
775 this.terminateWSConnection()
778 if (this.isWebSocketConnectionOpened()) {
780 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
786 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
789 this.wsConnection
= new WebSocket(
790 this.wsConnectionUrl
,
791 `ocpp${this.stationInfo?.ocppVersion}`,
795 // Handle WebSocket message
796 this.wsConnection
.on('message', data
=> {
797 this.onMessage(data
).catch(Constants
.EMPTY_FUNCTION
)
799 // Handle WebSocket error
800 this.wsConnection
.on('error', this.onError
.bind(this))
801 // Handle WebSocket close
802 this.wsConnection
.on('close', this.onClose
.bind(this))
803 // Handle WebSocket open
804 this.wsConnection
.on('open', () => {
805 this.onOpen().catch(error
=>
806 logger
.error(`${this.logPrefix()} Error while opening WebSocket connection:`, error
)
809 // Handle WebSocket ping
810 this.wsConnection
.on('ping', this.onPing
.bind(this))
811 // Handle WebSocket pong
812 this.wsConnection
.on('pong', this.onPong
.bind(this))
815 public closeWSConnection (): void {
816 if (this.isWebSocketConnectionOpened()) {
817 this.wsConnection
?.close()
818 this.wsConnection
= null
822 public getAutomaticTransactionGeneratorConfiguration ():
823 | AutomaticTransactionGeneratorConfiguration
825 if (this.automaticTransactionGeneratorConfiguration
== null) {
826 let automaticTransactionGeneratorConfiguration
:
827 | AutomaticTransactionGeneratorConfiguration
829 const stationTemplate
= this.getTemplateFromFile()
830 const stationConfiguration
= this.getConfigurationFromFile()
832 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
833 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
834 stationConfiguration
?.automaticTransactionGenerator
!= null
836 automaticTransactionGeneratorConfiguration
=
837 stationConfiguration
.automaticTransactionGenerator
839 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
841 this.automaticTransactionGeneratorConfiguration
= {
842 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
843 ...automaticTransactionGeneratorConfiguration
846 return this.automaticTransactionGeneratorConfiguration
849 public getAutomaticTransactionGeneratorStatuses (): Status
[] | undefined {
850 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
853 public startAutomaticTransactionGenerator (
854 connectorIds
?: number[],
855 stopAbsoluteDuration
?: boolean
857 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this)
858 if (isNotEmptyArray(connectorIds
)) {
859 for (const connectorId
of connectorIds
) {
860 this.automaticTransactionGenerator
?.startConnector(connectorId
, stopAbsoluteDuration
)
863 this.automaticTransactionGenerator
?.start(stopAbsoluteDuration
)
865 this.saveAutomaticTransactionGeneratorConfiguration()
866 this.emit(ChargingStationEvents
.updated
)
869 public stopAutomaticTransactionGenerator (connectorIds
?: number[]): void {
870 if (isNotEmptyArray(connectorIds
)) {
871 for (const connectorId
of connectorIds
) {
872 this.automaticTransactionGenerator
?.stopConnector(connectorId
)
875 this.automaticTransactionGenerator
?.stop()
877 this.saveAutomaticTransactionGeneratorConfiguration()
878 this.emit(ChargingStationEvents
.updated
)
881 public async stopTransactionOnConnector (
883 reason
?: StopTransactionReason
884 ): Promise
<StopTransactionResponse
> {
885 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
887 this.stationInfo
?.beginEndMeterValues
=== true &&
888 this.stationInfo
.ocppStrictCompliance
=== true &&
889 this.stationInfo
.outOfOrderEndMeterValues
=== false
891 const transactionEndMeterValue
= buildTransactionEndMeterValue(
894 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
896 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
898 RequestCommand
.METER_VALUES
,
902 meterValue
: [transactionEndMeterValue
]
906 return await this.ocppRequestService
.requestHandler
<
907 StopTransactionRequest
,
908 StopTransactionResponse
909 >(this, RequestCommand
.STOP_TRANSACTION
, {
911 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
912 ...(reason
!= null && { reason
})
916 public getReserveConnectorZeroSupported (): boolean {
917 return convertToBoolean(
918 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
919 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
923 public async addReservation (reservation
: Reservation
): Promise
<void> {
924 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
)
925 if (reservationFound
!= null) {
926 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
)
928 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
929 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
930 await sendAndSetConnectorStatus(
932 reservation
.connectorId
,
933 ConnectorStatusEnum
.Reserved
,
935 { send
: reservation
.connectorId
!== 0 }
939 public async removeReservation (
940 reservation
: Reservation
,
941 reason
: ReservationTerminationReason
943 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
944 const connector
= this.getConnectorStatus(reservation
.connectorId
)!
946 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
947 case ReservationTerminationReason
.TRANSACTION_STARTED
:
948 delete connector
.reservation
950 case ReservationTerminationReason
.RESERVATION_CANCELED
:
951 case ReservationTerminationReason
.REPLACE_EXISTING
:
952 case ReservationTerminationReason
.EXPIRED
:
953 await sendAndSetConnectorStatus(
955 reservation
.connectorId
,
956 ConnectorStatusEnum
.Available
,
958 { send
: reservation
.connectorId
!== 0 }
960 delete connector
.reservation
963 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
964 throw new BaseError(`Unknown reservation termination reason '${reason}'`)
968 public getReservationBy (
969 filterKey
: ReservationKey
,
970 value
: number | string
971 ): Reservation
| undefined {
973 for (const evseStatus
of this.evses
.values()) {
974 for (const connectorStatus
of evseStatus
.connectors
.values()) {
975 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
976 return connectorStatus
.reservation
981 for (const connectorStatus
of this.connectors
.values()) {
982 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
983 return connectorStatus
.reservation
989 public isConnectorReservable (
990 reservationId
: number,
994 const reservation
= this.getReservationBy('reservationId', reservationId
)
995 const reservationExists
= reservation
!== undefined && !hasReservationExpired(reservation
)
996 if (arguments.length
=== 1) {
997 return !reservationExists
998 } else if (arguments.length
> 1) {
999 const userReservation
=
1000 idTag
!== undefined ? this.getReservationBy('idTag', idTag
) : undefined
1001 const userReservationExists
=
1002 userReservation
!== undefined && !hasReservationExpired(userReservation
)
1003 const notConnectorZero
= connectorId
=== undefined ? true : connectorId
> 0
1004 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0
1006 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
1012 private setIntervalFlushMessageBuffer (): void {
1013 if (this.flushMessageBufferSetInterval
== null) {
1014 this.flushMessageBufferSetInterval
= setInterval(() => {
1015 if (this.isWebSocketConnectionOpened() && this.inAcceptedState()) {
1016 this.flushMessageBuffer()
1018 if (this.messageBuffer
.size
=== 0) {
1019 this.clearIntervalFlushMessageBuffer()
1021 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
)
1025 private clearIntervalFlushMessageBuffer (): void {
1026 if (this.flushMessageBufferSetInterval
!= null) {
1027 clearInterval(this.flushMessageBufferSetInterval
)
1028 delete this.flushMessageBufferSetInterval
1032 private getNumberOfReservableConnectors (): number {
1033 let numberOfReservableConnectors
= 0
1034 if (this.hasEvses
) {
1035 for (const evseStatus
of this.evses
.values()) {
1036 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
)
1039 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
)
1041 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero()
1044 private getNumberOfReservationsOnConnectorZero (): number {
1046 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
!= null) ||
1047 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
!= null)
1054 private flushMessageBuffer (): void {
1055 if (this.messageBuffer
.size
> 0) {
1056 for (const message
of this.messageBuffer
.values()) {
1057 let beginId
: string | undefined
1058 let commandName
: RequestCommand
| undefined
1059 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
1060 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
1062 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
1063 beginId
= PerformanceStatistics
.beginMeasure(commandName
)
1065 this.wsConnection
?.send(message
, (error
?: Error) => {
1066 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1067 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!)
1068 if (error
== null) {
1070 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1072 )} OCPP message sent '${JSON.stringify(message)}'`
1074 this.messageBuffer
.delete(message
)
1077 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1079 )} OCPP message '${JSON.stringify(message)}' send failed:`,
1088 private getTemplateFromFile (): ChargingStationTemplate
| undefined {
1089 let template
: ChargingStationTemplate
| undefined
1091 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1092 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
)
1094 const measureId
= `${FileType.ChargingStationTemplate} read`
1095 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1096 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
1097 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1098 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1099 .update(JSON
.stringify(template
))
1101 this.sharedLRUCache
.setChargingStationTemplate(template
)
1102 this.templateFileHash
= template
.templateHash
1105 handleFileException(
1107 FileType
.ChargingStationTemplate
,
1108 error
as NodeJS
.ErrnoException
,
1115 private getStationInfoFromTemplate (): ChargingStationInfo
{
1116 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1117 const stationTemplate
= this.getTemplateFromFile()!
1118 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1119 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this)
1120 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
)
1121 if (stationTemplate
.Connectors
!= null) {
1122 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1124 const stationInfo
= stationTemplateToStationInfo(stationTemplate
)
1125 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
)
1126 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
)
1127 stationInfo
.ocppVersion
= stationTemplate
.ocppVersion
?? OCPPVersion
.VERSION_16
1128 createSerialNumber(stationTemplate
, stationInfo
)
1129 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
)
1130 if (isNotEmptyArray(stationTemplate
.power
)) {
1131 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
)
1132 stationInfo
.maximumPower
=
1133 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1134 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1135 : stationTemplate
.power
[powerArrayRandomIndex
]
1137 stationInfo
.maximumPower
=
1138 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1139 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1140 stationTemplate
.power
! * 1000
1141 : stationTemplate
.power
1143 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
)
1144 stationInfo
.firmwareVersionPattern
=
1145 stationTemplate
.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
1147 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1148 !new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
)
1151 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1153 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1156 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1163 stationTemplate
.firmwareUpgrade
?? {}
1165 stationInfo
.resetTime
=
1166 stationTemplate
.resetTime
!= null
1167 ? secondsToMilliseconds(stationTemplate
.resetTime
)
1168 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
1172 private getStationInfoFromFile (
1173 stationInfoPersistentConfiguration
= true
1174 ): ChargingStationInfo
| undefined {
1175 let stationInfo
: ChargingStationInfo
| undefined
1176 if (stationInfoPersistentConfiguration
) {
1177 stationInfo
= this.getConfigurationFromFile()?.stationInfo
1178 if (stationInfo
!= null) {
1179 delete stationInfo
.infoHash
1185 private getStationInfo (): ChargingStationInfo
{
1186 const defaultStationInfo
= Constants
.DEFAULT_STATION_INFO
1187 const stationInfoFromTemplate
= this.getStationInfoFromTemplate()
1188 const stationInfoFromFile
= this.getStationInfoFromFile(
1189 stationInfoFromTemplate
.stationInfoPersistentConfiguration
1192 // 1. charging station info from template
1193 // 2. charging station info from configuration file
1195 stationInfoFromFile
!= null &&
1196 stationInfoFromFile
.templateHash
=== stationInfoFromTemplate
.templateHash
1198 return { ...defaultStationInfo
, ...stationInfoFromFile
}
1200 stationInfoFromFile
!= null &&
1201 propagateSerialNumber(
1202 this.getTemplateFromFile(),
1203 stationInfoFromFile
,
1204 stationInfoFromTemplate
1206 return { ...defaultStationInfo
, ...stationInfoFromTemplate
}
1209 private saveStationInfo (): void {
1210 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1211 this.saveConfiguration()
1215 private handleUnsupportedVersion (version
: OCPPVersion
| undefined): void {
1216 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`
1217 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1218 throw new BaseError(errorMsg
)
1221 private initialize (): void {
1222 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1223 const stationTemplate
= this.getTemplateFromFile()!
1224 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1225 this.configurationFile
= join(
1226 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1227 `${getHashId(this.index, stationTemplate)}.json`
1229 const stationConfiguration
= this.getConfigurationFromFile()
1231 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
.templateHash
&&
1232 (stationConfiguration
?.connectorsStatus
!= null || stationConfiguration
?.evsesStatus
!= null)
1234 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
)
1235 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
)
1237 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
)
1239 this.stationInfo
= this.getStationInfo()
1241 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1242 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1243 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1245 const patternGroup
=
1246 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1247 this.stationInfo
.firmwareVersion
.split('.').length
1248 const match
= new RegExp(this.stationInfo
.firmwareVersionPattern
)
1249 .exec(this.stationInfo
.firmwareVersion
)
1250 ?.slice(1, patternGroup
+ 1)
1251 if (match
!= null) {
1252 const patchLevelIndex
= match
.length
- 1
1253 match
[patchLevelIndex
] = (
1254 convertToInt(match
[patchLevelIndex
]) +
1255 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1256 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1258 this.stationInfo
.firmwareVersion
= match
.join('.')
1261 this.saveStationInfo()
1262 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
1263 if (this.stationInfo
.enableStatistics
=== true) {
1264 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1265 this.stationInfo
.hashId
,
1266 this.stationInfo
.chargingStationId
,
1267 this.configuredSupervisionUrl
1270 const bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
)
1271 if (bootNotificationRequest
== null) {
1272 const errorMsg
= 'Error while creating boot notification request'
1273 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1274 throw new BaseError(errorMsg
)
1276 this.bootNotificationRequest
= bootNotificationRequest
1277 this.powerDivider
= this.getPowerDivider()
1278 // OCPP configuration
1279 this.ocppConfiguration
= this.getOcppConfiguration()
1280 this.initializeOcppConfiguration()
1281 this.initializeOcppServices()
1282 if (this.stationInfo
.autoRegister
=== true) {
1283 this.bootNotificationResponse
= {
1284 currentTime
: new Date(),
1285 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1286 status: RegistrationStatusEnumType
.ACCEPTED
1291 private initializeOcppServices (): void {
1292 const ocppVersion
= this.stationInfo
?.ocppVersion
1293 switch (ocppVersion
) {
1294 case OCPPVersion
.VERSION_16
:
1295 this.ocppIncomingRequestService
=
1296 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>()
1297 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1298 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1301 case OCPPVersion
.VERSION_20
:
1302 case OCPPVersion
.VERSION_201
:
1303 this.ocppIncomingRequestService
=
1304 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>()
1305 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1306 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1310 this.handleUnsupportedVersion(ocppVersion
)
1315 private initializeOcppConfiguration (): void {
1316 if (getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
) == null) {
1317 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0')
1319 if (getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
) == null) {
1320 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false })
1323 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1324 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1325 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) == null
1327 addConfigurationKey(
1329 this.stationInfo
.supervisionUrlOcppKey
,
1330 this.configuredSupervisionUrl
.href
,
1334 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1335 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1336 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) != null
1338 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
, { save
: false })
1341 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1342 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) == null
1344 addConfigurationKey(
1346 this.stationInfo
.amperageLimitationOcppKey
,
1348 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1349 (this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)).toString()
1352 if (getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
) == null) {
1353 addConfigurationKey(
1355 StandardParametersKey
.SupportedFeatureProfiles
,
1356 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1359 addConfigurationKey(
1361 StandardParametersKey
.NumberOfConnectors
,
1362 this.getNumberOfConnectors().toString(),
1366 if (getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
) == null) {
1367 addConfigurationKey(
1369 StandardParametersKey
.MeterValuesSampledData
,
1370 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1373 if (getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
) == null) {
1374 const connectorsPhaseRotation
: string[] = []
1375 if (this.hasEvses
) {
1376 for (const evseStatus
of this.evses
.values()) {
1377 for (const connectorId
of evseStatus
.connectors
.keys()) {
1378 connectorsPhaseRotation
.push(
1379 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1380 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1385 for (const connectorId
of this.connectors
.keys()) {
1386 connectorsPhaseRotation
.push(
1387 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1388 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1392 addConfigurationKey(
1394 StandardParametersKey
.ConnectorPhaseRotation
,
1395 connectorsPhaseRotation
.toString()
1398 if (getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
) == null) {
1399 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true')
1402 getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) == null &&
1403 hasFeatureProfile(this, SupportedFeatureProfiles
.LocalAuthListManagement
) === true
1405 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false')
1407 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) == null) {
1408 addConfigurationKey(
1410 StandardParametersKey
.ConnectionTimeOut
,
1411 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1414 this.saveOcppConfiguration()
1417 private initializeConnectorsOrEvsesFromFile (configuration
: ChargingStationConfiguration
): void {
1418 if (configuration
.connectorsStatus
!= null && configuration
.evsesStatus
== null) {
1419 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1420 this.connectors
.set(connectorId
, clone
<ConnectorStatus
>(connectorStatus
))
1422 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
== null) {
1423 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1424 const evseStatus
= clone
<EvseStatusConfiguration
>(evseStatusConfiguration
)
1425 delete evseStatus
.connectorsStatus
1426 this.evses
.set(evseId
, {
1427 ...(evseStatus
as EvseStatus
),
1428 connectors
: new Map
<number, ConnectorStatus
>(
1429 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1430 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1437 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
!= null) {
1438 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1439 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1440 throw new BaseError(errorMsg
)
1442 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`
1443 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1444 throw new BaseError(errorMsg
)
1448 private initializeConnectorsOrEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1449 if (stationTemplate
.Connectors
!= null && stationTemplate
.Evses
== null) {
1450 this.initializeConnectorsFromTemplate(stationTemplate
)
1451 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
== null) {
1452 this.initializeEvsesFromTemplate(stationTemplate
)
1453 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
!= null) {
1454 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`
1455 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1456 throw new BaseError(errorMsg
)
1458 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`
1459 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1460 throw new BaseError(errorMsg
)
1464 private initializeConnectorsFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1465 if (stationTemplate
.Connectors
== null && this.connectors
.size
=== 0) {
1466 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1467 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1468 throw new BaseError(errorMsg
)
1470 if (stationTemplate
.Connectors
?.[0] == null) {
1472 `${this.logPrefix()} Charging station information from template ${
1474 } with no connector id 0 configuration`
1477 if (stationTemplate
.Connectors
!= null) {
1478 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1479 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1480 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1482 `${JSON.stringify(stationTemplate.Connectors)}${configuredMaxConnectors.toString()}`
1485 const connectorsConfigChanged
=
1486 this.connectors
.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
1487 if (this.connectors
.size
=== 0 || connectorsConfigChanged
) {
1488 connectorsConfigChanged
&& this.connectors
.clear()
1489 this.connectorsConfigurationHash
= connectorsConfigHash
1490 if (templateMaxConnectors
> 0) {
1491 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1493 connectorId
=== 0 &&
1494 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1495 (stationTemplate
.Connectors
[connectorId
] == null ||
1496 !this.getUseConnectorId0(stationTemplate
))
1500 const templateConnectorId
=
1501 connectorId
> 0 && stationTemplate
.randomConnectors
=== true
1502 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1504 const connectorStatus
= stationTemplate
.Connectors
[templateConnectorId
]
1505 checkStationInfoConnectorStatus(
1506 templateConnectorId
,
1511 this.connectors
.set(connectorId
, clone
<ConnectorStatus
>(connectorStatus
))
1513 initializeConnectorsMapStatus(this.connectors
, this.logPrefix())
1514 this.saveConnectorsStatus()
1517 `${this.logPrefix()} Charging station information from template ${
1519 } with no connectors configuration defined, cannot create connectors`
1525 `${this.logPrefix()} Charging station information from template ${
1527 } with no connectors configuration defined, using already defined connectors`
1532 private initializeEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1533 if (stationTemplate
.Evses
== null && this.evses
.size
=== 0) {
1534 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1535 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1536 throw new BaseError(errorMsg
)
1538 if (stationTemplate
.Evses
?.[0] == null) {
1540 `${this.logPrefix()} Charging station information from template ${
1542 } with no evse id 0 configuration`
1545 if (stationTemplate
.Evses
?.[0]?.Connectors
[0] == null) {
1547 `${this.logPrefix()} Charging station information from template ${
1549 } with evse id 0 with no connector id 0 configuration`
1552 if (Object.keys(stationTemplate
.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1554 `${this.logPrefix()} Charging station information from template ${
1556 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1559 if (stationTemplate
.Evses
!= null) {
1560 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1561 .update(JSON
.stringify(stationTemplate
.Evses
))
1563 const evsesConfigChanged
=
1564 this.evses
.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
1565 if (this.evses
.size
=== 0 || evsesConfigChanged
) {
1566 evsesConfigChanged
&& this.evses
.clear()
1567 this.evsesConfigurationHash
= evsesConfigHash
1568 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
.Evses
)
1569 if (templateMaxEvses
> 0) {
1570 for (const evseKey
in stationTemplate
.Evses
) {
1571 const evseId
= convertToInt(evseKey
)
1572 this.evses
.set(evseId
, {
1573 connectors
: buildConnectorsMap(
1574 stationTemplate
.Evses
[evseKey
].Connectors
,
1578 availability
: AvailabilityType
.Operative
1580 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1581 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix())
1583 this.saveEvsesStatus()
1586 `${this.logPrefix()} Charging station information from template ${
1588 } with no evses configuration defined, cannot create evses`
1594 `${this.logPrefix()} Charging station information from template ${
1596 } with no evses configuration defined, using already defined evses`
1601 private getConfigurationFromFile (): ChargingStationConfiguration
| undefined {
1602 let configuration
: ChargingStationConfiguration
| undefined
1603 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1605 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1606 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1607 this.configurationFileHash
1610 const measureId
= `${FileType.ChargingStationConfiguration} read`
1611 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1612 configuration
= JSON
.parse(
1613 readFileSync(this.configurationFile
, 'utf8')
1614 ) as ChargingStationConfiguration
1615 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1616 this.sharedLRUCache
.setChargingStationConfiguration(configuration
)
1617 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1618 this.configurationFileHash
= configuration
.configurationHash
!
1621 handleFileException(
1622 this.configurationFile
,
1623 FileType
.ChargingStationConfiguration
,
1624 error
as NodeJS
.ErrnoException
,
1629 return configuration
1632 private saveAutomaticTransactionGeneratorConfiguration (): void {
1633 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1634 this.saveConfiguration()
1638 private saveConnectorsStatus (): void {
1639 this.saveConfiguration()
1642 private saveEvsesStatus (): void {
1643 this.saveConfiguration()
1646 private saveConfiguration (): void {
1647 if (isNotEmptyString(this.configurationFile
)) {
1649 if (!existsSync(dirname(this.configurationFile
))) {
1650 mkdirSync(dirname(this.configurationFile
), { recursive
: true })
1652 const configurationFromFile
= this.getConfigurationFromFile()
1653 let configurationData
: ChargingStationConfiguration
=
1654 configurationFromFile
!= null
1655 ? clone
<ChargingStationConfiguration
>(configurationFromFile
)
1657 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1658 configurationData
.stationInfo
= this.stationInfo
1660 delete configurationData
.stationInfo
1663 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1664 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1666 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
1668 delete configurationData
.configurationKey
1670 configurationData
= merge
<ChargingStationConfiguration
>(
1672 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1675 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== false ||
1676 this.getAutomaticTransactionGeneratorConfiguration() == null
1678 delete configurationData
.automaticTransactionGenerator
1680 if (this.connectors
.size
> 0) {
1681 configurationData
.connectorsStatus
= buildConnectorsStatus(this)
1683 delete configurationData
.connectorsStatus
1685 if (this.evses
.size
> 0) {
1686 configurationData
.evsesStatus
= buildEvsesStatus(this)
1688 delete configurationData
.evsesStatus
1690 delete configurationData
.configurationHash
1691 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1694 stationInfo
: configurationData
.stationInfo
,
1695 configurationKey
: configurationData
.configurationKey
,
1696 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1697 ...(this.connectors
.size
> 0 && {
1698 connectorsStatus
: configurationData
.connectorsStatus
1700 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
})
1701 } satisfies ChargingStationConfiguration
)
1704 if (this.configurationFileHash
!== configurationHash
) {
1705 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1706 configurationData
.configurationHash
= configurationHash
1707 const measureId
= `${FileType.ChargingStationConfiguration} write`
1708 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1710 this.configurationFile
,
1711 JSON
.stringify(configurationData
, undefined, 2),
1714 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1715 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
1716 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
)
1717 this.configurationFileHash
= configurationHash
1719 handleFileException(
1720 this.configurationFile
,
1721 FileType
.ChargingStationConfiguration
,
1722 error
as NodeJS
.ErrnoException
,
1728 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1729 this.configurationFile
1734 handleFileException(
1735 this.configurationFile
,
1736 FileType
.ChargingStationConfiguration
,
1737 error
as NodeJS
.ErrnoException
,
1743 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1748 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration
| undefined {
1749 return this.getTemplateFromFile()?.Configuration
1752 private getOcppConfigurationFromFile (): ChargingStationOcppConfiguration
| undefined {
1753 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
1754 if (this.stationInfo
?.ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1755 return { configurationKey
}
1760 private getOcppConfiguration (): ChargingStationOcppConfiguration
| undefined {
1761 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1762 this.getOcppConfigurationFromFile()
1763 if (ocppConfiguration
== null) {
1764 ocppConfiguration
= this.getOcppConfigurationFromTemplate()
1766 return ocppConfiguration
1769 private async onOpen (): Promise
<void> {
1770 if (this.isWebSocketConnectionOpened()) {
1772 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1774 let registrationRetryCount
= 0
1775 if (!this.isRegistered()) {
1776 // Send BootNotification
1778 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1779 BootNotificationRequest
,
1780 BootNotificationResponse
1781 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1782 skipBufferingOnError
: true
1784 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1785 if (this.bootNotificationResponse
?.currentTime
!= null) {
1786 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1787 this.bootNotificationResponse
.currentTime
= convertToDate(
1788 this.bootNotificationResponse
.currentTime
1791 if (!this.isRegistered()) {
1792 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
1794 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1795 this.bootNotificationResponse
?.interval
!= null
1796 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1797 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1801 !this.isRegistered() &&
1802 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1803 (registrationRetryCount
<= this.stationInfo
!.registrationMaxRetries
! ||
1804 this.stationInfo
?.registrationMaxRetries
=== -1)
1807 if (this.isRegistered()) {
1808 this.emit(ChargingStationEvents
.registered
)
1809 if (this.inAcceptedState()) {
1810 this.emit(ChargingStationEvents
.accepted
)
1813 if (this.inRejectedState()) {
1814 this.emit(ChargingStationEvents
.rejected
)
1817 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${
1818 this.stationInfo?.registrationMaxRetries
1822 this.wsConnectionRetryCount
= 0
1823 this.emit(ChargingStationEvents
.updated
)
1826 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1831 private onClose (code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): void {
1832 this.emit(ChargingStationEvents
.disconnected
)
1835 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1836 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1838 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1840 )}' and reason '${reason.toString()}'`
1842 this.wsConnectionRetryCount
= 0
1847 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1849 )}' and reason '${reason.toString()}'`
1852 this.reconnect().catch(error
=>
1853 logger
.error(`${this.logPrefix()} Error while reconnecting:`, error
)
1857 this.emit(ChargingStationEvents
.updated
)
1860 private getCachedRequest (messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1861 const cachedRequest
= this.requests
.get(messageId
)
1862 if (Array.isArray(cachedRequest
)) {
1863 return cachedRequest
1865 throw new OCPPError(
1866 ErrorType
.PROTOCOL_ERROR
,
1867 `Cached request for message id ${messageId} ${getMessageTypeString(
1869 )} is not an array`,
1875 private async handleIncomingMessage (request
: IncomingRequest
): Promise
<void> {
1876 const [messageType
, messageId
, commandName
, commandPayload
] = request
1877 if (this.stationInfo
?.enableStatistics
=== true) {
1878 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
)
1881 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1885 // Process the message
1886 await this.ocppIncomingRequestService
.incomingRequestHandler(
1892 this.emit(ChargingStationEvents
.updated
)
1895 private handleResponseMessage (response
: Response
): void {
1896 const [messageType
, messageId
, commandPayload
] = response
1897 if (!this.requests
.has(messageId
)) {
1899 throw new OCPPError(
1900 ErrorType
.INTERNAL_ERROR
,
1901 `Response for unknown message id ${messageId}`,
1907 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1908 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1913 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1917 responseCallback(commandPayload
, requestPayload
)
1920 private handleErrorMessage (errorResponse
: ErrorResponse
): void {
1921 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
1922 if (!this.requests
.has(messageId
)) {
1924 throw new OCPPError(
1925 ErrorType
.INTERNAL_ERROR
,
1926 `Error response for unknown message id ${messageId}`,
1928 { errorType
, errorMessage
, errorDetails
}
1931 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1932 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1934 `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify(
1938 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
))
1941 private async onMessage (data
: RawData
): Promise
<void> {
1942 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined
1943 let messageType
: MessageType
| undefined
1944 let errorMsg
: string
1946 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1947 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
1948 if (Array.isArray(request
)) {
1949 [messageType
] = request
1950 // Check the type of message
1951 switch (messageType
) {
1953 case MessageType
.CALL_MESSAGE
:
1954 await this.handleIncomingMessage(request
as IncomingRequest
)
1957 case MessageType
.CALL_RESULT_MESSAGE
:
1958 this.handleResponseMessage(request
as Response
)
1961 case MessageType
.CALL_ERROR_MESSAGE
:
1962 this.handleErrorMessage(request
as ErrorResponse
)
1966 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1967 errorMsg
= `Wrong message type ${messageType}`
1968 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1969 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
)
1972 throw new OCPPError(
1973 ErrorType
.PROTOCOL_ERROR
,
1974 'Incoming message is not an array',
1982 if (!Array.isArray(request
)) {
1983 logger
.error(`${this.logPrefix()} Incoming message '${request}' parsing error:`, error
)
1986 let commandName
: IncomingRequestCommand
| undefined
1987 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined
1988 let errorCallback
: ErrorCallback
1989 const [, messageId
] = request
1990 switch (messageType
) {
1991 case MessageType
.CALL_MESSAGE
:
1992 [, , commandName
] = request
as IncomingRequest
1994 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
)
1996 case MessageType
.CALL_RESULT_MESSAGE
:
1997 case MessageType
.CALL_ERROR_MESSAGE
:
1998 if (this.requests
.has(messageId
)) {
1999 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2000 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
2001 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2002 errorCallback(error
as OCPPError
, false)
2004 // Remove the request from the cache in case of error at response handling
2005 this.requests
.delete(messageId
)
2009 if (!(error
instanceof OCPPError
)) {
2011 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2012 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2013 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2014 }' message '${data.toString()}' handling is not an OCPPError:`,
2019 `${this.logPrefix()} Incoming OCPP command '${
2020 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2021 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2022 }' message '${data.toString()}'${
2023 messageType !== MessageType.CALL_MESSAGE
2024 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2026 } processing error:`,
2032 private onPing (): void {
2033 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
2036 private onPong (): void {
2037 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
2040 private onError (error
: WSError
): void {
2041 this.closeWSConnection()
2042 logger
.error(`${this.logPrefix()} WebSocket error:`, error
)
2045 private getEnergyActiveImportRegister (
2046 connectorStatus
: ConnectorStatus
| undefined,
2049 if (this.stationInfo
?.meteringPerTransaction
=== true) {
2052 ? connectorStatus
?.transactionEnergyActiveImportRegisterValue
!= null
2053 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
)
2055 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2060 ? connectorStatus
?.energyActiveImportRegisterValue
!= null
2061 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
)
2063 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2067 private getUseConnectorId0 (stationTemplate
?: ChargingStationTemplate
): boolean {
2068 return stationTemplate
?.useConnectorId0
?? true
2071 private async stopRunningTransactions (reason
?: StopTransactionReason
): Promise
<void> {
2072 if (this.hasEvses
) {
2073 for (const [evseId
, evseStatus
] of this.evses
) {
2077 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2078 if (connectorStatus
.transactionStarted
=== true) {
2079 await this.stopTransactionOnConnector(connectorId
, reason
)
2084 for (const connectorId
of this.connectors
.keys()) {
2085 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2086 await this.stopTransactionOnConnector(connectorId
, reason
)
2093 private getConnectionTimeout (): number {
2094 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) != null) {
2095 return convertToInt(
2096 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)?.value
??
2097 Constants
.DEFAULT_CONNECTION_TIMEOUT
2100 return Constants
.DEFAULT_CONNECTION_TIMEOUT
2103 private getPowerDivider (): number {
2104 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()
2105 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2106 powerDivider
= this.getNumberOfRunningTransactions()
2111 private getMaximumAmperage (stationInfo
?: ChargingStationInfo
): number | undefined {
2112 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2113 const maximumPower
= (stationInfo
?? this.stationInfo
!).maximumPower
!
2114 switch (this.getCurrentOutType(stationInfo
)) {
2115 case CurrentType
.AC
:
2116 return ACElectricUtils
.amperagePerPhaseFromPower(
2117 this.getNumberOfPhases(stationInfo
),
2118 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2119 this.getVoltageOut(stationInfo
)
2121 case CurrentType
.DC
:
2122 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
))
2126 private getCurrentOutType (stationInfo
?: ChargingStationInfo
): CurrentType
{
2127 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2128 return (stationInfo
?? this.stationInfo
!).currentOutType
?? CurrentType
.AC
2131 private getVoltageOut (stationInfo
?: ChargingStationInfo
): Voltage
{
2133 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2134 (stationInfo
?? this.stationInfo
!).voltageOut
??
2135 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2139 private getAmperageLimitation (): number | undefined {
2141 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2142 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) != null
2145 convertToInt(getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
)?.value
) /
2146 getAmperageLimitationUnitDivider(this.stationInfo
)
2151 private async startMessageSequence (ATGStopAbsoluteDuration
?: boolean): Promise
<void> {
2152 if (this.stationInfo
?.autoRegister
=== true) {
2153 await this.ocppRequestService
.requestHandler
<
2154 BootNotificationRequest
,
2155 BootNotificationResponse
2156 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2157 skipBufferingOnError
: true
2160 // Start WebSocket ping
2161 this.startWebSocketPing()
2163 this.startHeartbeat()
2164 // Initialize connectors status
2165 if (this.hasEvses
) {
2166 for (const [evseId
, evseStatus
] of this.evses
) {
2168 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2169 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
)
2170 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
, evseId
)
2175 for (const connectorId
of this.connectors
.keys()) {
2176 if (connectorId
> 0) {
2177 const connectorBootStatus
= getBootConnectorStatus(
2180 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2181 this.getConnectorStatus(connectorId
)!
2183 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
)
2187 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2188 await this.ocppRequestService
.requestHandler
<
2189 FirmwareStatusNotificationRequest
,
2190 FirmwareStatusNotificationResponse
2191 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2192 status: FirmwareStatus
.Installed
2194 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
2198 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2199 this.startAutomaticTransactionGenerator(undefined, ATGStopAbsoluteDuration
)
2201 this.flushMessageBuffer()
2204 private internalStopMessageSequence (): void {
2205 // Stop WebSocket ping
2206 this.stopWebSocketPing()
2208 this.stopHeartbeat()
2210 if (this.automaticTransactionGenerator
?.started
=== true) {
2211 this.stopAutomaticTransactionGenerator()
2215 private async stopMessageSequence (
2216 reason
?: StopTransactionReason
,
2217 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
2219 this.internalStopMessageSequence()
2220 // Stop ongoing transactions
2221 stopTransactions
=== true && (await this.stopRunningTransactions(reason
))
2222 if (this.hasEvses
) {
2223 for (const [evseId
, evseStatus
] of this.evses
) {
2225 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2226 await sendAndSetConnectorStatus(
2229 ConnectorStatusEnum
.Unavailable
,
2232 delete connectorStatus
.status
2237 for (const connectorId
of this.connectors
.keys()) {
2238 if (connectorId
> 0) {
2239 await sendAndSetConnectorStatus(this, connectorId
, ConnectorStatusEnum
.Unavailable
)
2240 delete this.getConnectorStatus(connectorId
)?.status
2246 private startWebSocketPing (): void {
2247 const webSocketPingInterval
=
2248 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) != null
2250 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
2253 if (webSocketPingInterval
> 0 && this.wsPingSetInterval
== null) {
2254 this.wsPingSetInterval
= setInterval(() => {
2255 if (this.isWebSocketConnectionOpened()) {
2256 this.wsConnection
?.ping()
2258 }, secondsToMilliseconds(webSocketPingInterval
))
2260 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2261 webSocketPingInterval
2264 } else if (this.wsPingSetInterval
!= null) {
2266 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2267 webSocketPingInterval
2272 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2277 private stopWebSocketPing (): void {
2278 if (this.wsPingSetInterval
!= null) {
2279 clearInterval(this.wsPingSetInterval
)
2280 delete this.wsPingSetInterval
2284 private getConfiguredSupervisionUrl (): URL
{
2285 let configuredSupervisionUrl
: string
2286 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls()
2287 if (isNotEmptyArray(supervisionUrls
)) {
2288 let configuredSupervisionUrlIndex
: number
2289 switch (Configuration
.getSupervisionUrlDistribution()) {
2290 case SupervisionUrlDistribution
.RANDOM
:
2291 configuredSupervisionUrlIndex
= Math.floor(secureRandom() * supervisionUrls
.length
)
2293 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2294 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2296 !Object.values(SupervisionUrlDistribution
).includes(
2297 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2298 Configuration
.getSupervisionUrlDistribution()!
2301 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2302 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2303 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2306 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
2309 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
]
2311 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2312 configuredSupervisionUrl
= supervisionUrls
!
2314 if (isNotEmptyString(configuredSupervisionUrl
)) {
2315 return new URL(configuredSupervisionUrl
)
2317 const errorMsg
= 'No supervision url(s) configured'
2318 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2319 throw new BaseError(errorMsg
)
2322 private stopHeartbeat (): void {
2323 if (this.heartbeatSetInterval
!= null) {
2324 clearInterval(this.heartbeatSetInterval
)
2325 delete this.heartbeatSetInterval
2329 private terminateWSConnection (): void {
2330 if (this.isWebSocketConnectionOpened()) {
2331 this.wsConnection
?.terminate()
2332 this.wsConnection
= null
2336 private async reconnect (): Promise
<void> {
2338 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2339 this.wsConnectionRetryCount
< this.stationInfo
!.autoReconnectMaxRetries
! ||
2340 this.stationInfo
?.autoReconnectMaxRetries
=== -1
2342 this.wsConnectionRetried
= true
2343 ++this.wsConnectionRetryCount
2344 const reconnectDelay
=
2345 this.stationInfo
?.reconnectExponentialDelay
=== true
2346 ? exponentialDelay(this.wsConnectionRetryCount
)
2347 : secondsToMilliseconds(this.getConnectionTimeout())
2348 const reconnectDelayWithdraw
= 1000
2349 const reconnectTimeout
=
2350 reconnectDelay
- reconnectDelayWithdraw
> 0 ? reconnectDelay
- reconnectDelayWithdraw
: 0
2352 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2355 )}ms, timeout ${reconnectTimeout}ms`
2357 await sleep(reconnectDelay
)
2359 `${this.logPrefix()} WebSocket connection retry #${this.wsConnectionRetryCount.toString()}`
2361 this.openWSConnection(
2363 handshakeTimeout
: reconnectTimeout
2365 { closeOpened
: true }
2367 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2369 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2370 this.wsConnectionRetryCount
2371 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`