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
, parse
} 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 ChargingStationOptions
,
77 type ChargingStationTemplate
,
85 type EvseStatusConfiguration
,
88 type FirmwareStatusNotificationRequest
,
89 type FirmwareStatusNotificationResponse
,
91 type HeartbeatRequest
,
92 type HeartbeatResponse
,
94 type IncomingRequestCommand
,
97 type MeterValuesRequest
,
98 type MeterValuesResponse
,
100 type OutgoingRequest
,
102 RegistrationStatusEnumType
,
106 ReservationTerminationReason
,
108 StandardParametersKey
,
110 type StopTransactionReason
,
111 type StopTransactionRequest
,
112 type StopTransactionResponse
,
113 SupervisionUrlDistribution
,
114 SupportedFeatureProfiles
,
117 WebSocketCloseEventStatusCode
,
119 } from
'../types/index.js'
128 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
129 buildConnectorsStatus
,
139 formatDurationMilliSeconds
,
140 formatDurationSeconds
,
142 getWebSocketCloseEventStatusString
,
154 } from
'../utils/index.js'
156 export class ChargingStation
extends EventEmitter
{
157 public readonly index
: number
158 public readonly templateFile
: string
159 public stationInfo
?: ChargingStationInfo
160 public started
: boolean
161 public starting
: boolean
162 public idTagsCache
: IdTagsCache
163 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined
164 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined
165 public wsConnection
: WebSocket
| null
166 public readonly connectors
: Map
<number, ConnectorStatus
>
167 public readonly evses
: Map
<number, EvseStatus
>
168 public readonly requests
: Map
<string, CachedRequest
>
169 public performanceStatistics
!: PerformanceStatistics
| undefined
170 public heartbeatSetInterval
?: NodeJS
.Timeout
171 public ocppRequestService
!: OCPPRequestService
172 public bootNotificationRequest
?: BootNotificationRequest
173 public bootNotificationResponse
?: BootNotificationResponse
174 public powerDivider
?: number
175 private stopping
: boolean
176 private configurationFile
!: string
177 private configurationFileHash
!: string
178 private connectorsConfigurationHash
!: string
179 private evsesConfigurationHash
!: string
180 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
181 private ocppIncomingRequestService
!: OCPPIncomingRequestService
182 private readonly messageBuffer
: Set
<string>
183 private configuredSupervisionUrl
!: URL
184 private wsConnectionRetried
: boolean
185 private wsConnectionRetryCount
: number
186 private templateFileWatcher
!: FSWatcher
| undefined
187 private templateFileHash
!: string
188 private readonly sharedLRUCache
: SharedLRUCache
189 private wsPingSetInterval
?: NodeJS
.Timeout
190 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
191 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
193 constructor (index
: number, templateFile
: string, options
?: ChargingStationOptions
) {
196 this.starting
= false
197 this.stopping
= false
198 this.wsConnection
= null
199 this.wsConnectionRetried
= false
200 this.wsConnectionRetryCount
= 0
202 this.templateFile
= templateFile
203 this.connectors
= new Map
<number, ConnectorStatus
>()
204 this.evses
= new Map
<number, EvseStatus
>()
205 this.requests
= new Map
<string, CachedRequest
>()
206 this.messageBuffer
= new Set
<string>()
207 this.sharedLRUCache
= SharedLRUCache
.getInstance()
208 this.idTagsCache
= IdTagsCache
.getInstance()
209 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this)
211 this.on(ChargingStationEvents
.added
, () => {
212 parentPort
?.postMessage(buildAddedMessage(this))
214 this.on(ChargingStationEvents
.started
, () => {
215 parentPort
?.postMessage(buildStartedMessage(this))
217 this.on(ChargingStationEvents
.stopped
, () => {
218 parentPort
?.postMessage(buildStoppedMessage(this))
220 this.on(ChargingStationEvents
.updated
, () => {
221 parentPort
?.postMessage(buildUpdatedMessage(this))
223 this.on(ChargingStationEvents
.accepted
, () => {
224 this.startMessageSequence(
225 this.wsConnectionRetried
227 : this.getAutomaticTransactionGeneratorConfiguration()?.stopAbsoluteDuration
229 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
)
231 this.wsConnectionRetried
= false
233 this.on(ChargingStationEvents
.rejected
, () => {
234 this.wsConnectionRetried
= false
236 this.on(ChargingStationEvents
.disconnected
, () => {
238 this.internalStopMessageSequence()
241 `${this.logPrefix()} Error while stopping the internal message sequence:`,
252 options
?.autoStart
=== true ||
253 (options
?.autoStart
!== false && this.stationInfo
?.autoStart
=== true)
259 public get
hasEvses (): boolean {
260 return this.connectors
.size
=== 0 && this.evses
.size
> 0
263 public get
wsConnectionUrl (): URL
{
266 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
267 isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
268 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value)
269 ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value
270 : this.configuredSupervisionUrl.href
271 }/${this.stationInfo?.chargingStationId}`
275 public logPrefix
= (): string => {
277 this instanceof ChargingStation
&&
278 this.stationInfo
!= null &&
279 isNotEmptyString(this.stationInfo
.chargingStationId
)
281 return logPrefix(` ${this.stationInfo.chargingStationId} |`)
283 let stationTemplate
: ChargingStationTemplate
| undefined
285 stationTemplate
= JSON
.parse(
286 readFileSync(this.templateFile
, 'utf8')
287 ) as ChargingStationTemplate
289 stationTemplate
= undefined
291 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`)
294 public hasIdTags (): boolean {
295 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
296 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
!)!))
299 public getNumberOfPhases (stationInfo
?: ChargingStationInfo
): number {
300 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
301 const localStationInfo
= stationInfo
?? this.stationInfo
!
302 switch (this.getCurrentOutType(stationInfo
)) {
304 return localStationInfo
.numberOfPhases
?? 3
310 public isWebSocketConnectionOpened (): boolean {
311 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
314 public inUnknownState (): boolean {
315 return this.bootNotificationResponse
?.status == null
318 public inPendingState (): boolean {
319 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
322 public inAcceptedState (): boolean {
323 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
326 public inRejectedState (): boolean {
327 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
330 public isRegistered (): boolean {
331 return !this.inUnknownState() && (this.inAcceptedState() || this.inPendingState())
334 public isChargingStationAvailable (): boolean {
335 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
338 public hasConnector (connectorId
: number): boolean {
340 for (const evseStatus
of this.evses
.values()) {
341 if (evseStatus
.connectors
.has(connectorId
)) {
347 return this.connectors
.has(connectorId
)
350 public isConnectorAvailable (connectorId
: number): boolean {
353 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
357 public getNumberOfConnectors (): number {
359 let numberOfConnectors
= 0
360 for (const [evseId
, evseStatus
] of this.evses
) {
362 numberOfConnectors
+= evseStatus
.connectors
.size
365 return numberOfConnectors
367 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
370 public getNumberOfEvses (): number {
371 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
374 public getConnectorStatus (connectorId
: number): ConnectorStatus
| undefined {
376 for (const evseStatus
of this.evses
.values()) {
377 if (evseStatus
.connectors
.has(connectorId
)) {
378 return evseStatus
.connectors
.get(connectorId
)
383 return this.connectors
.get(connectorId
)
386 public getConnectorMaximumAvailablePower (connectorId
: number): number {
387 let connectorAmperageLimitationPowerLimit
: number | undefined
388 const amperageLimitation
= this.getAmperageLimitation()
390 amperageLimitation
!= null &&
391 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
392 amperageLimitation
< this.stationInfo
!.maximumAmperage
!
394 connectorAmperageLimitationPowerLimit
=
395 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
396 ? ACElectricUtils
.powerTotal(
397 this.getNumberOfPhases(),
398 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
399 this.stationInfo
.voltageOut
!,
401 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
403 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
404 DCElectricUtils
.power(this.stationInfo
!.voltageOut
!, amperageLimitation
)) /
405 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
408 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
409 const connectorMaximumPower
= this.stationInfo
!.maximumPower
! / this.powerDivider
!
410 const connectorChargingProfilesPowerLimit
=
411 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
)
413 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
414 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
415 isNaN(connectorAmperageLimitationPowerLimit
!)
417 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
418 connectorAmperageLimitationPowerLimit
!,
419 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
420 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!
424 public getTransactionIdTag (transactionId
: number): string | undefined {
426 for (const evseStatus
of this.evses
.values()) {
427 for (const connectorStatus
of evseStatus
.connectors
.values()) {
428 if (connectorStatus
.transactionId
=== transactionId
) {
429 return connectorStatus
.transactionIdTag
434 for (const connectorId
of this.connectors
.keys()) {
435 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
436 return this.getConnectorStatus(connectorId
)?.transactionIdTag
442 public getNumberOfRunningTransactions (): number {
443 let numberOfRunningTransactions
= 0
445 for (const [evseId
, evseStatus
] of this.evses
) {
449 for (const connectorStatus
of evseStatus
.connectors
.values()) {
450 if (connectorStatus
.transactionStarted
=== true) {
451 ++numberOfRunningTransactions
456 for (const connectorId
of this.connectors
.keys()) {
457 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
458 ++numberOfRunningTransactions
462 return numberOfRunningTransactions
465 public getConnectorIdByTransactionId (transactionId
: number | undefined): number | undefined {
466 if (transactionId
== null) {
468 } else if (this.hasEvses
) {
469 for (const evseStatus
of this.evses
.values()) {
470 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
471 if (connectorStatus
.transactionId
=== transactionId
) {
477 for (const connectorId
of this.connectors
.keys()) {
478 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
485 public getEnergyActiveImportRegisterByTransactionId (
486 transactionId
: number | undefined,
489 return this.getEnergyActiveImportRegister(
490 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
491 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!),
496 public getEnergyActiveImportRegisterByConnectorId (connectorId
: number, rounded
= false): number {
497 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
)
500 public getAuthorizeRemoteTxRequests (): boolean {
501 const authorizeRemoteTxRequests
= getConfigurationKey(
503 StandardParametersKey
.AuthorizeRemoteTxRequests
505 return authorizeRemoteTxRequests
!= null
506 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
510 public getLocalAuthListEnabled (): boolean {
511 const localAuthListEnabled
= getConfigurationKey(
513 StandardParametersKey
.LocalAuthListEnabled
515 return localAuthListEnabled
!= null ? convertToBoolean(localAuthListEnabled
.value
) : false
518 public getHeartbeatInterval (): number {
519 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)
520 if (HeartbeatInterval
!= null) {
521 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
))
523 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)
524 if (HeartBeatInterval
!= null) {
525 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
))
527 this.stationInfo
?.autoRegister
=== false &&
529 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
530 Constants.DEFAULT_HEARTBEAT_INTERVAL
533 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
536 public setSupervisionUrl (url
: string): void {
538 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
539 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
)
541 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
, url
)
543 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
544 this.stationInfo
!.supervisionUrls
= url
545 this.saveStationInfo()
546 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
550 public startHeartbeat (): void {
551 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
== null) {
552 this.heartbeatSetInterval
= setInterval(() => {
553 this.ocppRequestService
554 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
557 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
561 }, this.getHeartbeatInterval())
563 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
564 this.getHeartbeatInterval()
567 } else if (this.heartbeatSetInterval
!= null) {
569 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
570 this.getHeartbeatInterval()
575 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
580 public restartHeartbeat (): void {
584 this.startHeartbeat()
587 public restartWebSocketPing (): void {
588 // Stop WebSocket ping
589 this.stopWebSocketPing()
590 // Start WebSocket ping
591 this.startWebSocketPing()
594 public startMeterValues (connectorId
: number, interval
: number): void {
595 if (connectorId
=== 0) {
596 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`)
599 const connectorStatus
= this.getConnectorStatus(connectorId
)
600 if (connectorStatus
== null) {
602 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
607 if (connectorStatus
.transactionStarted
=== false) {
609 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
613 connectorStatus
.transactionStarted
=== true &&
614 connectorStatus
.transactionId
== null
617 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
622 connectorStatus
.transactionSetInterval
= setInterval(() => {
623 const meterValue
= buildMeterValue(
626 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
627 connectorStatus
.transactionId
!,
630 this.ocppRequestService
631 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
633 RequestCommand
.METER_VALUES
,
636 transactionId
: connectorStatus
.transactionId
,
637 meterValue
: [meterValue
]
642 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
649 `${this.logPrefix()} Charging station ${
650 StandardParametersKey.MeterValueSampleInterval
651 } configuration set to ${interval}, not sending MeterValues`
656 public stopMeterValues (connectorId
: number): void {
657 const connectorStatus
= this.getConnectorStatus(connectorId
)
658 if (connectorStatus
?.transactionSetInterval
!= null) {
659 clearInterval(connectorStatus
.transactionSetInterval
)
663 private add (): void {
664 this.emit(ChargingStationEvents
.added
)
667 public start (): void {
669 if (!this.starting
) {
671 if (this.stationInfo
?.enableStatistics
=== true) {
672 this.performanceStatistics
?.start()
674 this.openWSConnection()
675 // Monitor charging station template file
676 this.templateFileWatcher
= watchJsonFile(
678 FileType
.ChargingStationTemplate
,
681 (event
, filename
): void => {
682 if (isNotEmptyString(filename
) && event
=== 'change') {
685 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
687 } file have changed, reload`
689 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
692 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
693 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
!)!)
695 const ATGStarted
= this.automaticTransactionGenerator
?.started
696 if (ATGStarted
=== true) {
697 this.stopAutomaticTransactionGenerator()
699 delete this.automaticTransactionGeneratorConfiguration
701 this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true &&
704 this.startAutomaticTransactionGenerator(undefined, true)
706 if (this.stationInfo
?.enableStatistics
=== true) {
707 this.performanceStatistics
?.restart()
709 this.performanceStatistics
?.stop()
711 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
714 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
722 this.emit(ChargingStationEvents
.started
)
723 this.starting
= false
725 logger
.warn(`${this.logPrefix()} Charging station is already starting...`)
728 logger
.warn(`${this.logPrefix()} Charging station is already started...`)
733 reason
?: StopTransactionReason
,
734 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
737 if (!this.stopping
) {
739 await this.stopMessageSequence(reason
, stopTransactions
)
740 this.closeWSConnection()
741 if (this.stationInfo
?.enableStatistics
=== true) {
742 this.performanceStatistics
?.stop()
744 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
745 this.templateFileWatcher
?.close()
746 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
747 delete this.bootNotificationResponse
749 this.saveConfiguration()
750 this.emit(ChargingStationEvents
.stopped
)
751 this.stopping
= false
753 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`)
756 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`)
760 public async reset (reason
?: StopTransactionReason
): Promise
<void> {
761 await this.stop(reason
)
762 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
763 await sleep(this.stationInfo
!.resetTime
!)
768 public saveOcppConfiguration (): void {
769 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
770 this.saveConfiguration()
774 public bufferMessage (message
: string): void {
775 this.messageBuffer
.add(message
)
776 this.setIntervalFlushMessageBuffer()
779 public openWSConnection (
781 params
?: { closeOpened
?: boolean, terminateOpened
?: boolean }
784 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
785 ...this.stationInfo
?.wsOptions
,
788 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
}
789 if (!checkChargingStation(this, this.logPrefix())) {
792 if (this.stationInfo
?.supervisionUser
!= null && this.stationInfo
.supervisionPassword
!= null) {
793 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`
795 if (params
.closeOpened
=== true) {
796 this.closeWSConnection()
798 if (params
.terminateOpened
=== true) {
799 this.terminateWSConnection()
802 if (this.isWebSocketConnectionOpened()) {
804 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.href} is already opened`
809 logger
.info(`${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.href}`)
811 this.wsConnection
= new WebSocket(
812 this.wsConnectionUrl
,
813 `ocpp${this.stationInfo?.ocppVersion}`,
817 // Handle WebSocket message
818 this.wsConnection
.on('message', data
=> {
819 this.onMessage(data
).catch(Constants
.EMPTY_FUNCTION
)
821 // Handle WebSocket error
822 this.wsConnection
.on('error', this.onError
.bind(this))
823 // Handle WebSocket close
824 this.wsConnection
.on('close', this.onClose
.bind(this))
825 // Handle WebSocket open
826 this.wsConnection
.on('open', () => {
827 this.onOpen().catch(error
=>
828 logger
.error(`${this.logPrefix()} Error while opening WebSocket connection:`, error
)
831 // Handle WebSocket ping
832 this.wsConnection
.on('ping', this.onPing
.bind(this))
833 // Handle WebSocket pong
834 this.wsConnection
.on('pong', this.onPong
.bind(this))
837 public closeWSConnection (): void {
838 if (this.isWebSocketConnectionOpened()) {
839 this.wsConnection
?.close()
840 this.wsConnection
= null
844 public getAutomaticTransactionGeneratorConfiguration ():
845 | AutomaticTransactionGeneratorConfiguration
847 if (this.automaticTransactionGeneratorConfiguration
== null) {
848 let automaticTransactionGeneratorConfiguration
:
849 | AutomaticTransactionGeneratorConfiguration
851 const stationTemplate
= this.getTemplateFromFile()
852 const stationConfiguration
= this.getConfigurationFromFile()
854 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
855 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
856 stationConfiguration
?.automaticTransactionGenerator
!= null
858 automaticTransactionGeneratorConfiguration
=
859 stationConfiguration
.automaticTransactionGenerator
861 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
863 this.automaticTransactionGeneratorConfiguration
= {
864 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
865 ...automaticTransactionGeneratorConfiguration
868 return this.automaticTransactionGeneratorConfiguration
871 public getAutomaticTransactionGeneratorStatuses (): Status
[] | undefined {
872 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
875 public startAutomaticTransactionGenerator (
876 connectorIds
?: number[],
877 stopAbsoluteDuration
?: boolean
879 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this)
880 if (isNotEmptyArray(connectorIds
)) {
881 for (const connectorId
of connectorIds
) {
882 this.automaticTransactionGenerator
?.startConnector(connectorId
, stopAbsoluteDuration
)
885 this.automaticTransactionGenerator
?.start(stopAbsoluteDuration
)
887 this.saveAutomaticTransactionGeneratorConfiguration()
888 this.emit(ChargingStationEvents
.updated
)
891 public stopAutomaticTransactionGenerator (connectorIds
?: number[]): void {
892 if (isNotEmptyArray(connectorIds
)) {
893 for (const connectorId
of connectorIds
) {
894 this.automaticTransactionGenerator
?.stopConnector(connectorId
)
897 this.automaticTransactionGenerator
?.stop()
899 this.saveAutomaticTransactionGeneratorConfiguration()
900 this.emit(ChargingStationEvents
.updated
)
903 public async stopTransactionOnConnector (
905 reason
?: StopTransactionReason
906 ): Promise
<StopTransactionResponse
> {
907 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
909 this.stationInfo
?.beginEndMeterValues
=== true &&
910 this.stationInfo
.ocppStrictCompliance
=== true &&
911 this.stationInfo
.outOfOrderEndMeterValues
=== false
913 const transactionEndMeterValue
= buildTransactionEndMeterValue(
916 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
918 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
920 RequestCommand
.METER_VALUES
,
924 meterValue
: [transactionEndMeterValue
]
928 return await this.ocppRequestService
.requestHandler
<
929 StopTransactionRequest
,
930 StopTransactionResponse
931 >(this, RequestCommand
.STOP_TRANSACTION
, {
933 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
934 ...(reason
!= null && { reason
})
938 public getReserveConnectorZeroSupported (): boolean {
939 return convertToBoolean(
940 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
941 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
945 public async addReservation (reservation
: Reservation
): Promise
<void> {
946 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
)
947 if (reservationFound
!= null) {
948 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
)
950 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
951 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
952 await sendAndSetConnectorStatus(
954 reservation
.connectorId
,
955 ConnectorStatusEnum
.Reserved
,
957 { send
: reservation
.connectorId
!== 0 }
961 public async removeReservation (
962 reservation
: Reservation
,
963 reason
: ReservationTerminationReason
965 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
966 const connector
= this.getConnectorStatus(reservation
.connectorId
)!
968 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
969 case ReservationTerminationReason
.TRANSACTION_STARTED
:
970 delete connector
.reservation
972 case ReservationTerminationReason
.RESERVATION_CANCELED
:
973 case ReservationTerminationReason
.REPLACE_EXISTING
:
974 case ReservationTerminationReason
.EXPIRED
:
975 await sendAndSetConnectorStatus(
977 reservation
.connectorId
,
978 ConnectorStatusEnum
.Available
,
980 { send
: reservation
.connectorId
!== 0 }
982 delete connector
.reservation
985 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
986 throw new BaseError(`Unknown reservation termination reason '${reason}'`)
990 public getReservationBy (
991 filterKey
: ReservationKey
,
992 value
: number | string
993 ): Reservation
| undefined {
995 for (const evseStatus
of this.evses
.values()) {
996 for (const connectorStatus
of evseStatus
.connectors
.values()) {
997 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
998 return connectorStatus
.reservation
1003 for (const connectorStatus
of this.connectors
.values()) {
1004 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
1005 return connectorStatus
.reservation
1011 public isConnectorReservable (
1012 reservationId
: number,
1014 connectorId
?: number
1016 const reservation
= this.getReservationBy('reservationId', reservationId
)
1017 const reservationExists
= reservation
!== undefined && !hasReservationExpired(reservation
)
1018 if (arguments.length
=== 1) {
1019 return !reservationExists
1020 } else if (arguments.length
> 1) {
1021 const userReservation
=
1022 idTag
!== undefined ? this.getReservationBy('idTag', idTag
) : undefined
1023 const userReservationExists
=
1024 userReservation
!== undefined && !hasReservationExpired(userReservation
)
1025 const notConnectorZero
= connectorId
=== undefined ? true : connectorId
> 0
1026 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0
1028 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
1034 private setIntervalFlushMessageBuffer (): void {
1035 if (this.flushMessageBufferSetInterval
== null) {
1036 this.flushMessageBufferSetInterval
= setInterval(() => {
1037 if (this.isWebSocketConnectionOpened() && this.inAcceptedState()) {
1038 this.flushMessageBuffer()
1040 if (this.messageBuffer
.size
=== 0) {
1041 this.clearIntervalFlushMessageBuffer()
1043 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
)
1047 private clearIntervalFlushMessageBuffer (): void {
1048 if (this.flushMessageBufferSetInterval
!= null) {
1049 clearInterval(this.flushMessageBufferSetInterval
)
1050 delete this.flushMessageBufferSetInterval
1054 private getNumberOfReservableConnectors (): number {
1055 let numberOfReservableConnectors
= 0
1056 if (this.hasEvses
) {
1057 for (const evseStatus
of this.evses
.values()) {
1058 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
)
1061 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
)
1063 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero()
1066 private getNumberOfReservationsOnConnectorZero (): number {
1068 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
!= null) ||
1069 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
!= null)
1076 private flushMessageBuffer (): void {
1077 if (this.messageBuffer
.size
> 0) {
1078 for (const message
of this.messageBuffer
.values()) {
1079 let beginId
: string | undefined
1080 let commandName
: RequestCommand
| undefined
1081 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
1082 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
1084 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
1085 beginId
= PerformanceStatistics
.beginMeasure(commandName
)
1087 this.wsConnection
?.send(message
, (error
?: Error) => {
1088 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1089 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!)
1090 if (error
== null) {
1092 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1094 )} OCPP message sent '${JSON.stringify(message)}'`
1096 this.messageBuffer
.delete(message
)
1099 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1101 )} OCPP message '${JSON.stringify(message)}' send failed:`,
1110 private getTemplateFromFile (): ChargingStationTemplate
| undefined {
1111 let template
: ChargingStationTemplate
| undefined
1113 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1114 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
)
1116 const measureId
= `${FileType.ChargingStationTemplate} read`
1117 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1118 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
1119 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1120 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1121 .update(JSON
.stringify(template
))
1123 this.sharedLRUCache
.setChargingStationTemplate(template
)
1124 this.templateFileHash
= template
.templateHash
1127 handleFileException(
1129 FileType
.ChargingStationTemplate
,
1130 error
as NodeJS
.ErrnoException
,
1137 private getStationInfoFromTemplate (): ChargingStationInfo
{
1138 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1139 const stationTemplate
= this.getTemplateFromFile()!
1140 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1141 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this)
1142 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
)
1143 if (stationTemplate
.Connectors
!= null) {
1144 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1146 const stationInfo
= stationTemplateToStationInfo(stationTemplate
)
1147 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
)
1148 stationInfo
.autoStart
= stationTemplate
.autoStart
?? true
1149 stationInfo
.templateName
= parse(this.templateFile
).name
1150 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
)
1151 stationInfo
.ocppVersion
= stationTemplate
.ocppVersion
?? OCPPVersion
.VERSION_16
1152 createSerialNumber(stationTemplate
, stationInfo
)
1153 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
)
1154 if (isNotEmptyArray(stationTemplate
.power
)) {
1155 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
)
1156 stationInfo
.maximumPower
=
1157 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1158 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1159 : stationTemplate
.power
[powerArrayRandomIndex
]
1161 stationInfo
.maximumPower
=
1162 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1163 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1164 stationTemplate
.power
! * 1000
1165 : stationTemplate
.power
1167 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
)
1168 stationInfo
.firmwareVersionPattern
=
1169 stationTemplate
.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
1171 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1172 !new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
)
1175 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1177 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1180 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1187 stationTemplate
.firmwareUpgrade
?? {}
1189 stationInfo
.resetTime
=
1190 stationTemplate
.resetTime
!= null
1191 ? secondsToMilliseconds(stationTemplate
.resetTime
)
1192 : Constants
.DEFAULT_CHARGING_STATION_RESET_TIME
1196 private getStationInfoFromFile (
1197 stationInfoPersistentConfiguration
= true
1198 ): ChargingStationInfo
| undefined {
1199 let stationInfo
: ChargingStationInfo
| undefined
1200 if (stationInfoPersistentConfiguration
) {
1201 stationInfo
= this.getConfigurationFromFile()?.stationInfo
1202 if (stationInfo
!= null) {
1203 delete stationInfo
.infoHash
1204 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1205 if (stationInfo
.templateName
== null) {
1206 stationInfo
.templateName
= parse(this.templateFile
).name
1208 if (stationInfo
.autoStart
== null) {
1209 stationInfo
.autoStart
= true
1216 private getStationInfo (): ChargingStationInfo
{
1217 const defaultStationInfo
= Constants
.DEFAULT_STATION_INFO
1218 const stationInfoFromTemplate
= this.getStationInfoFromTemplate()
1219 const stationInfoFromFile
= this.getStationInfoFromFile(
1220 stationInfoFromTemplate
.stationInfoPersistentConfiguration
1223 // 1. charging station info from template
1224 // 2. charging station info from configuration file
1226 stationInfoFromFile
!= null &&
1227 stationInfoFromFile
.templateHash
=== stationInfoFromTemplate
.templateHash
1229 return { ...defaultStationInfo
, ...stationInfoFromFile
}
1231 stationInfoFromFile
!= null &&
1232 propagateSerialNumber(
1233 this.getTemplateFromFile(),
1234 stationInfoFromFile
,
1235 stationInfoFromTemplate
1237 return { ...defaultStationInfo
, ...stationInfoFromTemplate
}
1240 private saveStationInfo (): void {
1241 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1242 this.saveConfiguration()
1246 private handleUnsupportedVersion (version
: OCPPVersion
| undefined): void {
1247 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`
1248 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1249 throw new BaseError(errorMsg
)
1252 private initialize (): void {
1253 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1254 const stationTemplate
= this.getTemplateFromFile()!
1255 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1256 this.configurationFile
= join(
1257 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1258 `${getHashId(this.index, stationTemplate)}.json`
1260 const stationConfiguration
= this.getConfigurationFromFile()
1262 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
.templateHash
&&
1263 (stationConfiguration
?.connectorsStatus
!= null || stationConfiguration
?.evsesStatus
!= null)
1265 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
)
1266 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
)
1268 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
)
1270 this.stationInfo
= this.getStationInfo()
1272 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1273 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1274 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1276 const patternGroup
=
1277 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1278 this.stationInfo
.firmwareVersion
.split('.').length
1279 const match
= new RegExp(this.stationInfo
.firmwareVersionPattern
)
1280 .exec(this.stationInfo
.firmwareVersion
)
1281 ?.slice(1, patternGroup
+ 1)
1282 if (match
!= null) {
1283 const patchLevelIndex
= match
.length
- 1
1284 match
[patchLevelIndex
] = (
1285 convertToInt(match
[patchLevelIndex
]) +
1286 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1287 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1289 this.stationInfo
.firmwareVersion
= match
.join('.')
1292 this.saveStationInfo()
1293 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
1294 if (this.stationInfo
.enableStatistics
=== true) {
1295 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1296 this.stationInfo
.hashId
,
1297 this.stationInfo
.chargingStationId
,
1298 this.configuredSupervisionUrl
1301 const bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
)
1302 if (bootNotificationRequest
== null) {
1303 const errorMsg
= 'Error while creating boot notification request'
1304 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1305 throw new BaseError(errorMsg
)
1307 this.bootNotificationRequest
= bootNotificationRequest
1308 this.powerDivider
= this.getPowerDivider()
1309 // OCPP configuration
1310 this.ocppConfiguration
= this.getOcppConfiguration()
1311 this.initializeOcppConfiguration()
1312 this.initializeOcppServices()
1313 if (this.stationInfo
.autoRegister
=== true) {
1314 this.bootNotificationResponse
= {
1315 currentTime
: new Date(),
1316 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1317 status: RegistrationStatusEnumType
.ACCEPTED
1322 private initializeOcppServices (): void {
1323 const ocppVersion
= this.stationInfo
?.ocppVersion
1324 switch (ocppVersion
) {
1325 case OCPPVersion
.VERSION_16
:
1326 this.ocppIncomingRequestService
=
1327 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>()
1328 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1329 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1332 case OCPPVersion
.VERSION_20
:
1333 case OCPPVersion
.VERSION_201
:
1334 this.ocppIncomingRequestService
=
1335 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>()
1336 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1337 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1341 this.handleUnsupportedVersion(ocppVersion
)
1346 private initializeOcppConfiguration (): void {
1347 if (getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
) == null) {
1348 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0')
1350 if (getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
) == null) {
1351 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false })
1354 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1355 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1356 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) == null
1358 addConfigurationKey(
1360 this.stationInfo
.supervisionUrlOcppKey
,
1361 this.configuredSupervisionUrl
.href
,
1365 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1366 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1367 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) != null
1369 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
, { save
: false })
1372 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1373 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) == null
1375 addConfigurationKey(
1377 this.stationInfo
.amperageLimitationOcppKey
,
1379 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1380 (this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)).toString()
1383 if (getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
) == null) {
1384 addConfigurationKey(
1386 StandardParametersKey
.SupportedFeatureProfiles
,
1387 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1390 addConfigurationKey(
1392 StandardParametersKey
.NumberOfConnectors
,
1393 this.getNumberOfConnectors().toString(),
1397 if (getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
) == null) {
1398 addConfigurationKey(
1400 StandardParametersKey
.MeterValuesSampledData
,
1401 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1404 if (getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
) == null) {
1405 const connectorsPhaseRotation
: string[] = []
1406 if (this.hasEvses
) {
1407 for (const evseStatus
of this.evses
.values()) {
1408 for (const connectorId
of evseStatus
.connectors
.keys()) {
1409 connectorsPhaseRotation
.push(
1410 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1411 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1416 for (const connectorId
of this.connectors
.keys()) {
1417 connectorsPhaseRotation
.push(
1418 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1419 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1423 addConfigurationKey(
1425 StandardParametersKey
.ConnectorPhaseRotation
,
1426 connectorsPhaseRotation
.toString()
1429 if (getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
) == null) {
1430 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true')
1433 getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) == null &&
1434 hasFeatureProfile(this, SupportedFeatureProfiles
.LocalAuthListManagement
) === true
1436 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false')
1438 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) == null) {
1439 addConfigurationKey(
1441 StandardParametersKey
.ConnectionTimeOut
,
1442 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1445 this.saveOcppConfiguration()
1448 private initializeConnectorsOrEvsesFromFile (configuration
: ChargingStationConfiguration
): void {
1449 if (configuration
.connectorsStatus
!= null && configuration
.evsesStatus
== null) {
1450 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1451 this.connectors
.set(connectorId
, clone
<ConnectorStatus
>(connectorStatus
))
1453 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
== null) {
1454 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1455 const evseStatus
= clone
<EvseStatusConfiguration
>(evseStatusConfiguration
)
1456 delete evseStatus
.connectorsStatus
1457 this.evses
.set(evseId
, {
1458 ...(evseStatus
as EvseStatus
),
1459 connectors
: new Map
<number, ConnectorStatus
>(
1460 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1461 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1468 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
!= null) {
1469 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1470 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1471 throw new BaseError(errorMsg
)
1473 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`
1474 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1475 throw new BaseError(errorMsg
)
1479 private initializeConnectorsOrEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1480 if (stationTemplate
.Connectors
!= null && stationTemplate
.Evses
== null) {
1481 this.initializeConnectorsFromTemplate(stationTemplate
)
1482 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
== null) {
1483 this.initializeEvsesFromTemplate(stationTemplate
)
1484 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
!= null) {
1485 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`
1486 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1487 throw new BaseError(errorMsg
)
1489 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`
1490 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1491 throw new BaseError(errorMsg
)
1495 private initializeConnectorsFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1496 if (stationTemplate
.Connectors
== null && this.connectors
.size
=== 0) {
1497 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1498 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1499 throw new BaseError(errorMsg
)
1501 if (stationTemplate
.Connectors
?.[0] == null) {
1503 `${this.logPrefix()} Charging station information from template ${
1505 } with no connector id 0 configuration`
1508 if (stationTemplate
.Connectors
!= null) {
1509 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1510 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1511 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1513 `${JSON.stringify(stationTemplate.Connectors)}${configuredMaxConnectors.toString()}`
1516 const connectorsConfigChanged
=
1517 this.connectors
.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
1518 if (this.connectors
.size
=== 0 || connectorsConfigChanged
) {
1519 connectorsConfigChanged
&& this.connectors
.clear()
1520 this.connectorsConfigurationHash
= connectorsConfigHash
1521 if (templateMaxConnectors
> 0) {
1522 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1524 connectorId
=== 0 &&
1525 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1526 (stationTemplate
.Connectors
[connectorId
] == null ||
1527 !this.getUseConnectorId0(stationTemplate
))
1531 const templateConnectorId
=
1532 connectorId
> 0 && stationTemplate
.randomConnectors
=== true
1533 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1535 const connectorStatus
= stationTemplate
.Connectors
[templateConnectorId
]
1536 checkStationInfoConnectorStatus(
1537 templateConnectorId
,
1542 this.connectors
.set(connectorId
, clone
<ConnectorStatus
>(connectorStatus
))
1544 initializeConnectorsMapStatus(this.connectors
, this.logPrefix())
1545 this.saveConnectorsStatus()
1548 `${this.logPrefix()} Charging station information from template ${
1550 } with no connectors configuration defined, cannot create connectors`
1556 `${this.logPrefix()} Charging station information from template ${
1558 } with no connectors configuration defined, using already defined connectors`
1563 private initializeEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1564 if (stationTemplate
.Evses
== null && this.evses
.size
=== 0) {
1565 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1566 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1567 throw new BaseError(errorMsg
)
1569 if (stationTemplate
.Evses
?.[0] == null) {
1571 `${this.logPrefix()} Charging station information from template ${
1573 } with no evse id 0 configuration`
1576 if (stationTemplate
.Evses
?.[0]?.Connectors
[0] == null) {
1578 `${this.logPrefix()} Charging station information from template ${
1580 } with evse id 0 with no connector id 0 configuration`
1583 if (Object.keys(stationTemplate
.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1585 `${this.logPrefix()} Charging station information from template ${
1587 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1590 if (stationTemplate
.Evses
!= null) {
1591 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1592 .update(JSON
.stringify(stationTemplate
.Evses
))
1594 const evsesConfigChanged
=
1595 this.evses
.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
1596 if (this.evses
.size
=== 0 || evsesConfigChanged
) {
1597 evsesConfigChanged
&& this.evses
.clear()
1598 this.evsesConfigurationHash
= evsesConfigHash
1599 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
.Evses
)
1600 if (templateMaxEvses
> 0) {
1601 for (const evseKey
in stationTemplate
.Evses
) {
1602 const evseId
= convertToInt(evseKey
)
1603 this.evses
.set(evseId
, {
1604 connectors
: buildConnectorsMap(
1605 stationTemplate
.Evses
[evseKey
].Connectors
,
1609 availability
: AvailabilityType
.Operative
1611 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1612 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix())
1614 this.saveEvsesStatus()
1617 `${this.logPrefix()} Charging station information from template ${
1619 } with no evses configuration defined, cannot create evses`
1625 `${this.logPrefix()} Charging station information from template ${
1627 } with no evses configuration defined, using already defined evses`
1632 private getConfigurationFromFile (): ChargingStationConfiguration
| undefined {
1633 let configuration
: ChargingStationConfiguration
| undefined
1634 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1636 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1637 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1638 this.configurationFileHash
1641 const measureId
= `${FileType.ChargingStationConfiguration} read`
1642 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1643 configuration
= JSON
.parse(
1644 readFileSync(this.configurationFile
, 'utf8')
1645 ) as ChargingStationConfiguration
1646 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1647 this.sharedLRUCache
.setChargingStationConfiguration(configuration
)
1648 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1649 this.configurationFileHash
= configuration
.configurationHash
!
1652 handleFileException(
1653 this.configurationFile
,
1654 FileType
.ChargingStationConfiguration
,
1655 error
as NodeJS
.ErrnoException
,
1660 return configuration
1663 private saveAutomaticTransactionGeneratorConfiguration (): void {
1664 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1665 this.saveConfiguration()
1669 private saveConnectorsStatus (): void {
1670 this.saveConfiguration()
1673 private saveEvsesStatus (): void {
1674 this.saveConfiguration()
1677 private saveConfiguration (): void {
1678 if (isNotEmptyString(this.configurationFile
)) {
1680 if (!existsSync(dirname(this.configurationFile
))) {
1681 mkdirSync(dirname(this.configurationFile
), { recursive
: true })
1683 const configurationFromFile
= this.getConfigurationFromFile()
1684 let configurationData
: ChargingStationConfiguration
=
1685 configurationFromFile
!= null
1686 ? clone
<ChargingStationConfiguration
>(configurationFromFile
)
1688 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1689 configurationData
.stationInfo
= this.stationInfo
1691 delete configurationData
.stationInfo
1694 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1695 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1697 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
1699 delete configurationData
.configurationKey
1701 configurationData
= merge
<ChargingStationConfiguration
>(
1703 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1706 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== false ||
1707 this.getAutomaticTransactionGeneratorConfiguration() == null
1709 delete configurationData
.automaticTransactionGenerator
1711 if (this.connectors
.size
> 0) {
1712 configurationData
.connectorsStatus
= buildConnectorsStatus(this)
1714 delete configurationData
.connectorsStatus
1716 if (this.evses
.size
> 0) {
1717 configurationData
.evsesStatus
= buildEvsesStatus(this)
1719 delete configurationData
.evsesStatus
1721 delete configurationData
.configurationHash
1722 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1725 stationInfo
: configurationData
.stationInfo
,
1726 configurationKey
: configurationData
.configurationKey
,
1727 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1728 ...(this.connectors
.size
> 0 && {
1729 connectorsStatus
: configurationData
.connectorsStatus
1731 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
})
1732 } satisfies ChargingStationConfiguration
)
1735 if (this.configurationFileHash
!== configurationHash
) {
1736 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1737 configurationData
.configurationHash
= configurationHash
1738 const measureId
= `${FileType.ChargingStationConfiguration} write`
1739 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1741 this.configurationFile
,
1742 JSON
.stringify(configurationData
, undefined, 2),
1745 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1746 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
1747 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
)
1748 this.configurationFileHash
= configurationHash
1750 handleFileException(
1751 this.configurationFile
,
1752 FileType
.ChargingStationConfiguration
,
1753 error
as NodeJS
.ErrnoException
,
1759 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1760 this.configurationFile
1765 handleFileException(
1766 this.configurationFile
,
1767 FileType
.ChargingStationConfiguration
,
1768 error
as NodeJS
.ErrnoException
,
1774 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1779 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration
| undefined {
1780 return this.getTemplateFromFile()?.Configuration
1783 private getOcppConfigurationFromFile (): ChargingStationOcppConfiguration
| undefined {
1784 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
1785 if (this.stationInfo
?.ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1786 return { configurationKey
}
1791 private getOcppConfiguration (): ChargingStationOcppConfiguration
| undefined {
1792 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1793 this.getOcppConfigurationFromFile()
1794 if (ocppConfiguration
== null) {
1795 ocppConfiguration
= this.getOcppConfigurationFromTemplate()
1797 return ocppConfiguration
1800 private async onOpen (): Promise
<void> {
1801 if (this.isWebSocketConnectionOpened()) {
1803 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} succeeded`
1805 let registrationRetryCount
= 0
1806 if (!this.isRegistered()) {
1807 // Send BootNotification
1809 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1810 BootNotificationRequest
,
1811 BootNotificationResponse
1812 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1813 skipBufferingOnError
: true
1815 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1816 if (this.bootNotificationResponse
?.currentTime
!= null) {
1817 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1818 this.bootNotificationResponse
.currentTime
= convertToDate(
1819 this.bootNotificationResponse
.currentTime
1822 if (!this.isRegistered()) {
1823 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
1825 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1826 this.bootNotificationResponse
?.interval
!= null
1827 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1828 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1832 !this.isRegistered() &&
1833 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1834 (registrationRetryCount
<= this.stationInfo
!.registrationMaxRetries
! ||
1835 this.stationInfo
?.registrationMaxRetries
=== -1)
1838 if (this.isRegistered()) {
1839 this.emit(ChargingStationEvents
.registered
)
1840 if (this.inAcceptedState()) {
1841 this.emit(ChargingStationEvents
.accepted
)
1844 if (this.inRejectedState()) {
1845 this.emit(ChargingStationEvents
.rejected
)
1848 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${
1849 this.stationInfo?.registrationMaxRetries
1853 this.wsConnectionRetryCount
= 0
1854 this.emit(ChargingStationEvents
.updated
)
1857 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} failed`
1862 private onClose (code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): void {
1863 this.emit(ChargingStationEvents
.disconnected
)
1866 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1867 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1869 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1871 )}' and reason '${reason.toString()}'`
1873 this.wsConnectionRetryCount
= 0
1878 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1880 )}' and reason '${reason.toString()}'`
1883 this.reconnect().catch(error
=>
1884 logger
.error(`${this.logPrefix()} Error while reconnecting:`, error
)
1888 this.emit(ChargingStationEvents
.updated
)
1891 private getCachedRequest (
1892 messageType
: MessageType
| undefined,
1894 ): CachedRequest
| undefined {
1895 const cachedRequest
= this.requests
.get(messageId
)
1896 if (Array.isArray(cachedRequest
)) {
1897 return cachedRequest
1899 throw new OCPPError(
1900 ErrorType
.PROTOCOL_ERROR
,
1901 `Cached request for message id ${messageId} ${getMessageTypeString(
1903 )} is not an array`,
1909 private async handleIncomingMessage (request
: IncomingRequest
): Promise
<void> {
1910 const [messageType
, messageId
, commandName
, commandPayload
] = request
1911 if (this.stationInfo
?.enableStatistics
=== true) {
1912 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
)
1915 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1919 // Process the message
1920 await this.ocppIncomingRequestService
.incomingRequestHandler(
1926 this.emit(ChargingStationEvents
.updated
)
1929 private handleResponseMessage (response
: Response
): void {
1930 const [messageType
, messageId
, commandPayload
] = response
1931 if (!this.requests
.has(messageId
)) {
1933 throw new OCPPError(
1934 ErrorType
.INTERNAL_ERROR
,
1935 `Response for unknown message id ${messageId}`,
1941 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1942 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1947 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1951 responseCallback(commandPayload
, requestPayload
)
1954 private handleErrorMessage (errorResponse
: ErrorResponse
): void {
1955 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
1956 if (!this.requests
.has(messageId
)) {
1958 throw new OCPPError(
1959 ErrorType
.INTERNAL_ERROR
,
1960 `Error response for unknown message id ${messageId}`,
1962 { errorType
, errorMessage
, errorDetails
}
1965 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1966 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1968 `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify(
1972 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
))
1975 private async onMessage (data
: RawData
): Promise
<void> {
1976 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined
1977 let messageType
: MessageType
| undefined
1978 let errorMsg
: string
1980 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1981 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
1982 if (Array.isArray(request
)) {
1983 [messageType
] = request
1984 // Check the type of message
1985 switch (messageType
) {
1987 case MessageType
.CALL_MESSAGE
:
1988 await this.handleIncomingMessage(request
as IncomingRequest
)
1991 case MessageType
.CALL_RESULT_MESSAGE
:
1992 this.handleResponseMessage(request
as Response
)
1995 case MessageType
.CALL_ERROR_MESSAGE
:
1996 this.handleErrorMessage(request
as ErrorResponse
)
2000 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2001 errorMsg
= `Wrong message type ${messageType}`
2002 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2003 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
)
2006 throw new OCPPError(
2007 ErrorType
.PROTOCOL_ERROR
,
2008 'Incoming message is not an array',
2016 if (!Array.isArray(request
)) {
2017 logger
.error(`${this.logPrefix()} Incoming message '${request}' parsing error:`, error
)
2020 let commandName
: IncomingRequestCommand
| undefined
2021 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined
2022 let errorCallback
: ErrorCallback
2023 const [, messageId
] = request
2024 switch (messageType
) {
2025 case MessageType
.CALL_MESSAGE
:
2026 [, , commandName
] = request
as IncomingRequest
2028 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
)
2030 case MessageType
.CALL_RESULT_MESSAGE
:
2031 case MessageType
.CALL_ERROR_MESSAGE
:
2032 if (this.requests
.has(messageId
)) {
2033 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2034 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
2035 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2036 errorCallback(error
as OCPPError
, false)
2038 // Remove the request from the cache in case of error at response handling
2039 this.requests
.delete(messageId
)
2043 if (!(error
instanceof OCPPError
)) {
2045 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2046 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2047 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2048 }' message '${data.toString()}' handling is not an OCPPError:`,
2053 `${this.logPrefix()} Incoming OCPP command '${
2054 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2055 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2056 }' message '${data.toString()}'${
2057 this.requests.has(messageId)
2058 ? ` matching cached request
'${JSON.stringify(this.getCachedRequest(messageType, messageId))}'`
2060 } processing error:`,
2066 private onPing (): void {
2067 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
2070 private onPong (): void {
2071 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
2074 private onError (error
: WSError
): void {
2075 this.closeWSConnection()
2076 logger
.error(`${this.logPrefix()} WebSocket error:`, error
)
2079 private getEnergyActiveImportRegister (
2080 connectorStatus
: ConnectorStatus
| undefined,
2083 if (this.stationInfo
?.meteringPerTransaction
=== true) {
2086 ? connectorStatus
?.transactionEnergyActiveImportRegisterValue
!= null
2087 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
)
2089 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2094 ? connectorStatus
?.energyActiveImportRegisterValue
!= null
2095 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
)
2097 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2101 private getUseConnectorId0 (stationTemplate
?: ChargingStationTemplate
): boolean {
2102 return stationTemplate
?.useConnectorId0
?? true
2105 private async stopRunningTransactions (reason
?: StopTransactionReason
): Promise
<void> {
2106 if (this.hasEvses
) {
2107 for (const [evseId
, evseStatus
] of this.evses
) {
2111 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2112 if (connectorStatus
.transactionStarted
=== true) {
2113 await this.stopTransactionOnConnector(connectorId
, reason
)
2118 for (const connectorId
of this.connectors
.keys()) {
2119 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2120 await this.stopTransactionOnConnector(connectorId
, reason
)
2127 private getConnectionTimeout (): number {
2128 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) != null) {
2129 return convertToInt(
2130 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)?.value
??
2131 Constants
.DEFAULT_CONNECTION_TIMEOUT
2134 return Constants
.DEFAULT_CONNECTION_TIMEOUT
2137 private getPowerDivider (): number {
2138 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()
2139 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2140 powerDivider
= this.getNumberOfRunningTransactions()
2145 private getMaximumAmperage (stationInfo
?: ChargingStationInfo
): number | undefined {
2146 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2147 const maximumPower
= (stationInfo
?? this.stationInfo
!).maximumPower
!
2148 switch (this.getCurrentOutType(stationInfo
)) {
2149 case CurrentType
.AC
:
2150 return ACElectricUtils
.amperagePerPhaseFromPower(
2151 this.getNumberOfPhases(stationInfo
),
2152 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2153 this.getVoltageOut(stationInfo
)
2155 case CurrentType
.DC
:
2156 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
))
2160 private getCurrentOutType (stationInfo
?: ChargingStationInfo
): CurrentType
{
2161 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2162 return (stationInfo
?? this.stationInfo
!).currentOutType
?? CurrentType
.AC
2165 private getVoltageOut (stationInfo
?: ChargingStationInfo
): Voltage
{
2167 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2168 (stationInfo
?? this.stationInfo
!).voltageOut
??
2169 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2173 private getAmperageLimitation (): number | undefined {
2175 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2176 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) != null
2179 convertToInt(getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
)?.value
) /
2180 getAmperageLimitationUnitDivider(this.stationInfo
)
2185 private async startMessageSequence (ATGStopAbsoluteDuration
?: boolean): Promise
<void> {
2186 if (this.stationInfo
?.autoRegister
=== true) {
2187 await this.ocppRequestService
.requestHandler
<
2188 BootNotificationRequest
,
2189 BootNotificationResponse
2190 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2191 skipBufferingOnError
: true
2194 // Start WebSocket ping
2195 this.startWebSocketPing()
2197 this.startHeartbeat()
2198 // Initialize connectors status
2199 if (this.hasEvses
) {
2200 for (const [evseId
, evseStatus
] of this.evses
) {
2202 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2203 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
)
2204 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
, evseId
)
2209 for (const connectorId
of this.connectors
.keys()) {
2210 if (connectorId
> 0) {
2211 const connectorBootStatus
= getBootConnectorStatus(
2214 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2215 this.getConnectorStatus(connectorId
)!
2217 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
)
2221 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2222 await this.ocppRequestService
.requestHandler
<
2223 FirmwareStatusNotificationRequest
,
2224 FirmwareStatusNotificationResponse
2225 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2226 status: FirmwareStatus
.Installed
2228 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
2232 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2233 this.startAutomaticTransactionGenerator(undefined, ATGStopAbsoluteDuration
)
2235 this.flushMessageBuffer()
2238 private internalStopMessageSequence (): void {
2239 // Stop WebSocket ping
2240 this.stopWebSocketPing()
2242 this.stopHeartbeat()
2244 if (this.automaticTransactionGenerator
?.started
=== true) {
2245 this.stopAutomaticTransactionGenerator()
2249 private async stopMessageSequence (
2250 reason
?: StopTransactionReason
,
2251 stopTransactions
?: boolean
2253 this.internalStopMessageSequence()
2254 // Stop ongoing transactions
2255 stopTransactions
=== true && (await this.stopRunningTransactions(reason
))
2256 if (this.hasEvses
) {
2257 for (const [evseId
, evseStatus
] of this.evses
) {
2259 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2260 await sendAndSetConnectorStatus(
2263 ConnectorStatusEnum
.Unavailable
,
2266 delete connectorStatus
.status
2271 for (const connectorId
of this.connectors
.keys()) {
2272 if (connectorId
> 0) {
2273 await sendAndSetConnectorStatus(this, connectorId
, ConnectorStatusEnum
.Unavailable
)
2274 delete this.getConnectorStatus(connectorId
)?.status
2280 private startWebSocketPing (): void {
2281 const webSocketPingInterval
=
2282 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) != null
2284 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
2287 if (webSocketPingInterval
> 0 && this.wsPingSetInterval
== null) {
2288 this.wsPingSetInterval
= setInterval(() => {
2289 if (this.isWebSocketConnectionOpened()) {
2290 this.wsConnection
?.ping()
2292 }, secondsToMilliseconds(webSocketPingInterval
))
2294 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2295 webSocketPingInterval
2298 } else if (this.wsPingSetInterval
!= null) {
2300 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2301 webSocketPingInterval
2306 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2311 private stopWebSocketPing (): void {
2312 if (this.wsPingSetInterval
!= null) {
2313 clearInterval(this.wsPingSetInterval
)
2314 delete this.wsPingSetInterval
2318 private getConfiguredSupervisionUrl (): URL
{
2319 let configuredSupervisionUrl
: string
2320 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls()
2321 if (isNotEmptyArray(supervisionUrls
)) {
2322 let configuredSupervisionUrlIndex
: number
2323 switch (Configuration
.getSupervisionUrlDistribution()) {
2324 case SupervisionUrlDistribution
.RANDOM
:
2325 configuredSupervisionUrlIndex
= Math.floor(secureRandom() * supervisionUrls
.length
)
2327 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2328 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2330 !Object.values(SupervisionUrlDistribution
).includes(
2331 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2332 Configuration
.getSupervisionUrlDistribution()!
2335 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2336 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2337 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2340 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
2343 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
]
2345 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2346 configuredSupervisionUrl
= supervisionUrls
!
2348 if (isNotEmptyString(configuredSupervisionUrl
)) {
2349 return new URL(configuredSupervisionUrl
)
2351 const errorMsg
= 'No supervision url(s) configured'
2352 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2353 throw new BaseError(errorMsg
)
2356 private stopHeartbeat (): void {
2357 if (this.heartbeatSetInterval
!= null) {
2358 clearInterval(this.heartbeatSetInterval
)
2359 delete this.heartbeatSetInterval
2363 private terminateWSConnection (): void {
2364 if (this.isWebSocketConnectionOpened()) {
2365 this.wsConnection
?.terminate()
2366 this.wsConnection
= null
2370 private async reconnect (): Promise
<void> {
2372 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2373 this.wsConnectionRetryCount
< this.stationInfo
!.autoReconnectMaxRetries
! ||
2374 this.stationInfo
?.autoReconnectMaxRetries
=== -1
2376 this.wsConnectionRetried
= true
2377 ++this.wsConnectionRetryCount
2378 const reconnectDelay
=
2379 this.stationInfo
?.reconnectExponentialDelay
=== true
2380 ? exponentialDelay(this.wsConnectionRetryCount
)
2381 : secondsToMilliseconds(this.getConnectionTimeout())
2382 const reconnectDelayWithdraw
= 1000
2383 const reconnectTimeout
=
2384 reconnectDelay
- reconnectDelayWithdraw
> 0 ? reconnectDelay
- reconnectDelayWithdraw
: 0
2386 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2389 )}ms, timeout ${reconnectTimeout}ms`
2391 await sleep(reconnectDelay
)
2393 `${this.logPrefix()} WebSocket connection retry #${this.wsConnectionRetryCount.toString()}`
2395 this.openWSConnection(
2397 handshakeTimeout
: reconnectTimeout
2399 { closeOpened
: true }
2401 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2403 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2404 this.wsConnectionRetryCount
2405 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`