1 // Partial Copyright Jerome Benoit. 2021-2023. 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 buildStatusNotificationRequest
,
60 buildTransactionEndMeterValue
,
62 sendAndSetConnectorStatus
63 } from
'./ocpp/index.js'
64 import { SharedLRUCache
} from
'./SharedLRUCache.js'
65 import { BaseError
, OCPPError
} from
'../exception/index.js'
66 import { PerformanceStatistics
} from
'../performance/index.js'
68 type AutomaticTransactionGeneratorConfiguration
,
70 type BootNotificationRequest
,
71 type BootNotificationResponse
,
73 type ChargingStationConfiguration
,
74 ChargingStationEvents
,
75 type ChargingStationInfo
,
76 type ChargingStationOcppConfiguration
,
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 StatusNotificationRequest
,
111 type StatusNotificationResponse
,
112 type StopTransactionReason
,
113 type StopTransactionRequest
,
114 type StopTransactionResponse
,
115 SupervisionUrlDistribution
,
116 SupportedFeatureProfiles
,
119 WebSocketCloseEventStatusCode
,
121 } from
'../types/index.js'
129 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
130 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 autoReconnectRetryCount
: number
185 private templateFileWatcher
!: FSWatcher
| undefined
186 private templateFileHash
!: string
187 private readonly sharedLRUCache
: SharedLRUCache
188 private webSocketPingSetInterval
?: NodeJS
.Timeout
189 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
190 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
192 constructor (index
: number, templateFile
: string) {
195 this.starting
= false
196 this.stopping
= false
197 this.wsConnection
= null
198 this.autoReconnectRetryCount
= 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))
222 public get
hasEvses (): boolean {
223 return this.connectors
.size
=== 0 && this.evses
.size
> 0
226 private get
wsConnectionUrl (): URL
{
229 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
230 isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
231 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
232 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)?.value)
233 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
234 getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)!.value
235 : this.configuredSupervisionUrl.href
236 }/${this.stationInfo?.chargingStationId}`
240 public logPrefix
= (): string => {
242 this instanceof ChargingStation
&&
243 this.stationInfo
!= null &&
244 isNotEmptyString(this.stationInfo
.chargingStationId
)
246 return logPrefix(` ${this.stationInfo.chargingStationId} |`)
248 let stationTemplate
: ChargingStationTemplate
| undefined
250 stationTemplate
= JSON
.parse(
251 readFileSync(this.templateFile
, 'utf8')
252 ) as ChargingStationTemplate
254 stationTemplate
= undefined
256 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`)
259 public hasIdTags (): boolean {
260 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
261 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
!)!))
264 public getNumberOfPhases (stationInfo
?: ChargingStationInfo
): number {
265 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
266 const localStationInfo
= stationInfo
?? this.stationInfo
!
267 switch (this.getCurrentOutType(stationInfo
)) {
269 return localStationInfo
.numberOfPhases
?? 3
275 public isWebSocketConnectionOpened (): boolean {
276 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
279 public inUnknownState (): boolean {
280 return this.bootNotificationResponse
?.status == null
283 public inPendingState (): boolean {
284 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
287 public inAcceptedState (): boolean {
288 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
291 public inRejectedState (): boolean {
292 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
295 public isRegistered (): boolean {
296 return !this.inUnknownState() && (this.inAcceptedState() || this.inPendingState())
299 public isChargingStationAvailable (): boolean {
300 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
303 public hasConnector (connectorId
: number): boolean {
305 for (const evseStatus
of this.evses
.values()) {
306 if (evseStatus
.connectors
.has(connectorId
)) {
312 return this.connectors
.has(connectorId
)
315 public isConnectorAvailable (connectorId
: number): boolean {
318 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
322 public getNumberOfConnectors (): number {
324 let numberOfConnectors
= 0
325 for (const [evseId
, evseStatus
] of this.evses
) {
327 numberOfConnectors
+= evseStatus
.connectors
.size
330 return numberOfConnectors
332 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
335 public getNumberOfEvses (): number {
336 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
339 public getConnectorStatus (connectorId
: number): ConnectorStatus
| undefined {
341 for (const evseStatus
of this.evses
.values()) {
342 if (evseStatus
.connectors
.has(connectorId
)) {
343 return evseStatus
.connectors
.get(connectorId
)
348 return this.connectors
.get(connectorId
)
351 public getConnectorMaximumAvailablePower (connectorId
: number): number {
352 let connectorAmperageLimitationPowerLimit
: number | undefined
353 const amperageLimitation
= this.getAmperageLimitation()
355 amperageLimitation
!= null &&
356 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
357 amperageLimitation
< this.stationInfo
!.maximumAmperage
!
359 connectorAmperageLimitationPowerLimit
=
360 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
361 ? ACElectricUtils
.powerTotal(
362 this.getNumberOfPhases(),
363 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
364 this.stationInfo
.voltageOut
!,
366 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
368 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
369 DCElectricUtils
.power(this.stationInfo
!.voltageOut
!, amperageLimitation
)) /
370 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
373 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
374 const connectorMaximumPower
= this.stationInfo
!.maximumPower
! / this.powerDivider
!
375 const connectorChargingProfilesPowerLimit
=
376 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
)
378 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
379 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
380 isNaN(connectorAmperageLimitationPowerLimit
!)
382 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
383 connectorAmperageLimitationPowerLimit
!,
384 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
385 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!
389 public getTransactionIdTag (transactionId
: number): string | undefined {
391 for (const evseStatus
of this.evses
.values()) {
392 for (const connectorStatus
of evseStatus
.connectors
.values()) {
393 if (connectorStatus
.transactionId
=== transactionId
) {
394 return connectorStatus
.transactionIdTag
399 for (const connectorId
of this.connectors
.keys()) {
400 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
401 return this.getConnectorStatus(connectorId
)?.transactionIdTag
407 public getNumberOfRunningTransactions (): number {
408 let numberOfRunningTransactions
= 0
410 for (const [evseId
, evseStatus
] of this.evses
) {
414 for (const connectorStatus
of evseStatus
.connectors
.values()) {
415 if (connectorStatus
.transactionStarted
=== true) {
416 ++numberOfRunningTransactions
421 for (const connectorId
of this.connectors
.keys()) {
422 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
423 ++numberOfRunningTransactions
427 return numberOfRunningTransactions
430 public getConnectorIdByTransactionId (transactionId
: number): number | undefined {
432 for (const evseStatus
of this.evses
.values()) {
433 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
434 if (connectorStatus
.transactionId
=== transactionId
) {
440 for (const connectorId
of this.connectors
.keys()) {
441 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
448 public getEnergyActiveImportRegisterByTransactionId (
449 transactionId
: number,
452 return this.getEnergyActiveImportRegister(
453 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
454 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
459 public getEnergyActiveImportRegisterByConnectorId (connectorId
: number, rounded
= false): number {
460 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
461 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
)
464 public getAuthorizeRemoteTxRequests (): boolean {
465 const authorizeRemoteTxRequests
= getConfigurationKey(
467 StandardParametersKey
.AuthorizeRemoteTxRequests
469 return authorizeRemoteTxRequests
!= null
470 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
474 public getLocalAuthListEnabled (): boolean {
475 const localAuthListEnabled
= getConfigurationKey(
477 StandardParametersKey
.LocalAuthListEnabled
479 return localAuthListEnabled
!= null ? convertToBoolean(localAuthListEnabled
.value
) : false
482 public getHeartbeatInterval (): number {
483 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)
484 if (HeartbeatInterval
!= null) {
485 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
))
487 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)
488 if (HeartBeatInterval
!= null) {
489 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
))
491 this.stationInfo
?.autoRegister
=== false &&
493 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
494 Constants.DEFAULT_HEARTBEAT_INTERVAL
497 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
500 public setSupervisionUrl (url
: string): void {
502 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
503 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
)
505 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
506 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
!, url
)
508 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
509 this.stationInfo
!.supervisionUrls
= url
510 this.saveStationInfo()
511 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
515 public startHeartbeat (): void {
516 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
== null) {
517 this.heartbeatSetInterval
= setInterval(() => {
518 this.ocppRequestService
519 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
522 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
526 }, this.getHeartbeatInterval())
528 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
529 this.getHeartbeatInterval()
532 } else if (this.heartbeatSetInterval
!= null) {
534 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
535 this.getHeartbeatInterval()
540 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
545 public restartHeartbeat (): void {
549 this.startHeartbeat()
552 public restartWebSocketPing (): void {
553 // Stop WebSocket ping
554 this.stopWebSocketPing()
555 // Start WebSocket ping
556 this.startWebSocketPing()
559 public startMeterValues (connectorId
: number, interval
: number): void {
560 if (connectorId
=== 0) {
561 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`)
564 if (this.getConnectorStatus(connectorId
) == null) {
566 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
571 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
573 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
577 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
578 this.getConnectorStatus(connectorId
)?.transactionId
== null
581 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
586 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
587 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
588 const meterValue
= buildMeterValue(
591 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
592 this.getConnectorStatus(connectorId
)!.transactionId
!,
595 this.ocppRequestService
596 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
598 RequestCommand
.METER_VALUES
,
601 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
602 meterValue
: [meterValue
]
607 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
614 `${this.logPrefix()} Charging station ${
615 StandardParametersKey.MeterValueSampleInterval
616 } configuration set to ${interval}, not sending MeterValues`
621 public stopMeterValues (connectorId
: number): void {
622 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
!= null) {
623 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
)
627 public start (): void {
629 if (!this.starting
) {
631 if (this.stationInfo
?.enableStatistics
=== true) {
632 this.performanceStatistics
?.start()
634 this.openWSConnection()
635 // Monitor charging station template file
636 this.templateFileWatcher
= watchJsonFile(
638 FileType
.ChargingStationTemplate
,
641 (event
, filename
): void => {
642 if (isNotEmptyString(filename
) && event
=== 'change') {
645 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
647 } file have changed, reload`
649 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
652 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
653 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
!)!)
655 this.stopAutomaticTransactionGenerator()
656 delete this.automaticTransactionGeneratorConfiguration
657 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
658 this.startAutomaticTransactionGenerator()
660 if (this.stationInfo
?.enableStatistics
=== true) {
661 this.performanceStatistics
?.restart()
663 this.performanceStatistics
?.stop()
665 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
668 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
676 this.emit(ChargingStationEvents
.started
)
677 this.starting
= false
679 logger
.warn(`${this.logPrefix()} Charging station is already starting...`)
682 logger
.warn(`${this.logPrefix()} Charging station is already started...`)
686 public async stop (reason
?: StopTransactionReason
, stopTransactions
?: boolean): Promise
<void> {
688 if (!this.stopping
) {
690 await this.stopMessageSequence(reason
, stopTransactions
)
691 this.closeWSConnection()
692 if (this.stationInfo
?.enableStatistics
=== true) {
693 this.performanceStatistics
?.stop()
695 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
696 this.templateFileWatcher
?.close()
697 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
698 delete this.bootNotificationResponse
700 this.saveConfiguration()
701 this.emit(ChargingStationEvents
.stopped
)
702 this.stopping
= false
704 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`)
707 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`)
711 public async reset (reason
?: StopTransactionReason
): Promise
<void> {
712 await this.stop(reason
)
713 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
714 await sleep(this.stationInfo
!.resetTime
!)
719 public saveOcppConfiguration (): void {
720 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
721 this.saveConfiguration()
725 public bufferMessage (message
: string): void {
726 this.messageBuffer
.add(message
)
727 this.setIntervalFlushMessageBuffer()
730 public openWSConnection (
732 params
?: { closeOpened
?: boolean, terminateOpened
?: boolean }
735 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
736 ...this.stationInfo
?.wsOptions
,
739 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
}
740 if (!checkChargingStation(this, this.logPrefix())) {
743 if (this.stationInfo
?.supervisionUser
!= null && this.stationInfo
.supervisionPassword
!= null) {
744 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`
746 if (params
.closeOpened
=== true) {
747 this.closeWSConnection()
749 if (params
.terminateOpened
=== true) {
750 this.terminateWSConnection()
753 if (this.isWebSocketConnectionOpened()) {
755 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
761 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
764 this.wsConnection
= new WebSocket(
765 this.wsConnectionUrl
,
766 `ocpp${this.stationInfo?.ocppVersion}`,
770 // Handle WebSocket message
771 this.wsConnection
.on(
773 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
775 // Handle WebSocket error
776 this.wsConnection
.on(
778 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
780 // Handle WebSocket close
781 this.wsConnection
.on(
783 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
785 // Handle WebSocket open
786 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void)
787 // Handle WebSocket ping
788 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void)
789 // Handle WebSocket pong
790 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void)
793 public closeWSConnection (): void {
794 if (this.isWebSocketConnectionOpened()) {
795 this.wsConnection
?.close()
796 this.wsConnection
= null
800 public getAutomaticTransactionGeneratorConfiguration ():
801 | AutomaticTransactionGeneratorConfiguration
803 if (this.automaticTransactionGeneratorConfiguration
== null) {
804 let automaticTransactionGeneratorConfiguration
:
805 | AutomaticTransactionGeneratorConfiguration
807 const stationTemplate
= this.getTemplateFromFile()
808 const stationConfiguration
= this.getConfigurationFromFile()
810 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
811 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
812 stationConfiguration
?.automaticTransactionGenerator
!= null
814 automaticTransactionGeneratorConfiguration
=
815 stationConfiguration
.automaticTransactionGenerator
817 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
819 this.automaticTransactionGeneratorConfiguration
= {
820 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
821 ...automaticTransactionGeneratorConfiguration
824 return this.automaticTransactionGeneratorConfiguration
827 public getAutomaticTransactionGeneratorStatuses (): Status
[] | undefined {
828 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
831 public startAutomaticTransactionGenerator (connectorIds
?: number[]): void {
832 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this)
833 if (isNotEmptyArray(connectorIds
)) {
834 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
835 for (const connectorId
of connectorIds
!) {
836 this.automaticTransactionGenerator
?.startConnector(connectorId
)
839 this.automaticTransactionGenerator
?.start()
841 this.saveAutomaticTransactionGeneratorConfiguration()
842 this.emit(ChargingStationEvents
.updated
)
845 public stopAutomaticTransactionGenerator (connectorIds
?: number[]): void {
846 if (isNotEmptyArray(connectorIds
)) {
847 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
848 for (const connectorId
of connectorIds
!) {
849 this.automaticTransactionGenerator
?.stopConnector(connectorId
)
852 this.automaticTransactionGenerator
?.stop()
854 this.saveAutomaticTransactionGeneratorConfiguration()
855 this.emit(ChargingStationEvents
.updated
)
858 public async stopTransactionOnConnector (
860 reason
?: StopTransactionReason
861 ): Promise
<StopTransactionResponse
> {
862 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
863 const transactionId
= this.getConnectorStatus(connectorId
)!.transactionId
!
865 this.stationInfo
?.beginEndMeterValues
=== true &&
866 this.stationInfo
.ocppStrictCompliance
=== true &&
867 this.stationInfo
.outOfOrderEndMeterValues
=== false
869 const transactionEndMeterValue
= buildTransactionEndMeterValue(
872 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
874 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
876 RequestCommand
.METER_VALUES
,
880 meterValue
: [transactionEndMeterValue
]
884 return await this.ocppRequestService
.requestHandler
<
885 StopTransactionRequest
,
886 StopTransactionResponse
887 >(this, RequestCommand
.STOP_TRANSACTION
, {
889 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
890 ...(reason
!= null && { reason
})
894 public getReserveConnectorZeroSupported (): boolean {
895 return convertToBoolean(
896 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
897 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
901 public async addReservation (reservation
: Reservation
): Promise
<void> {
902 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
)
903 if (reservationFound
!= null) {
904 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
)
906 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
907 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
908 await sendAndSetConnectorStatus(
910 reservation
.connectorId
,
911 ConnectorStatusEnum
.Reserved
,
913 { send
: reservation
.connectorId
!== 0 }
917 public async removeReservation (
918 reservation
: Reservation
,
919 reason
: ReservationTerminationReason
921 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
922 const connector
= this.getConnectorStatus(reservation
.connectorId
)!
924 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
925 case ReservationTerminationReason
.TRANSACTION_STARTED
:
926 delete connector
.reservation
928 case ReservationTerminationReason
.RESERVATION_CANCELED
:
929 case ReservationTerminationReason
.REPLACE_EXISTING
:
930 case ReservationTerminationReason
.EXPIRED
:
931 await sendAndSetConnectorStatus(
933 reservation
.connectorId
,
934 ConnectorStatusEnum
.Available
,
936 { send
: reservation
.connectorId
!== 0 }
938 delete connector
.reservation
941 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
942 throw new BaseError(`Unknown reservation termination reason '${reason}'`)
946 public getReservationBy (
947 filterKey
: ReservationKey
,
948 value
: number | string
949 ): Reservation
| undefined {
951 for (const evseStatus
of this.evses
.values()) {
952 for (const connectorStatus
of evseStatus
.connectors
.values()) {
953 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
954 return connectorStatus
.reservation
959 for (const connectorStatus
of this.connectors
.values()) {
960 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
961 return connectorStatus
.reservation
967 public isConnectorReservable (
968 reservationId
: number,
972 const reservation
= this.getReservationBy('reservationId', reservationId
)
973 const reservationExists
= reservation
!== undefined && !hasReservationExpired(reservation
)
974 if (arguments.length
=== 1) {
975 return !reservationExists
976 } else if (arguments.length
> 1) {
977 const userReservation
=
978 idTag
!== undefined ? this.getReservationBy('idTag', idTag
) : undefined
979 const userReservationExists
=
980 userReservation
!== undefined && !hasReservationExpired(userReservation
)
981 const notConnectorZero
= connectorId
=== undefined ? true : connectorId
> 0
982 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0
984 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
990 private setIntervalFlushMessageBuffer (): void {
991 if (this.flushMessageBufferSetInterval
== null) {
992 this.flushMessageBufferSetInterval
= setInterval(() => {
993 if (this.isWebSocketConnectionOpened() && this.inAcceptedState()) {
994 this.flushMessageBuffer()
996 if (this.messageBuffer
.size
=== 0) {
997 this.clearIntervalFlushMessageBuffer()
999 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
)
1003 private clearIntervalFlushMessageBuffer (): void {
1004 if (this.flushMessageBufferSetInterval
!= null) {
1005 clearInterval(this.flushMessageBufferSetInterval
)
1006 delete this.flushMessageBufferSetInterval
1010 private getNumberOfReservableConnectors (): number {
1011 let numberOfReservableConnectors
= 0
1012 if (this.hasEvses
) {
1013 for (const evseStatus
of this.evses
.values()) {
1014 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
)
1017 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
)
1019 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero()
1022 private getNumberOfReservationsOnConnectorZero (): number {
1024 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
!= null) ||
1025 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
!= null)
1032 private flushMessageBuffer (): void {
1033 if (this.messageBuffer
.size
> 0) {
1034 for (const message
of this.messageBuffer
.values()) {
1035 let beginId
: string | undefined
1036 let commandName
: RequestCommand
| undefined
1037 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
1038 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
1040 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
1041 beginId
= PerformanceStatistics
.beginMeasure(commandName
)
1043 this.wsConnection
?.send(message
, (error
?: Error) => {
1044 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1045 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!)
1046 if (error
== null) {
1048 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1050 )} OCPP message sent '${JSON.stringify(message)}'`
1052 this.messageBuffer
.delete(message
)
1055 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1057 )} OCPP message '${JSON.stringify(message)}' send failed:`,
1066 private getTemplateFromFile (): ChargingStationTemplate
| undefined {
1067 let template
: ChargingStationTemplate
| undefined
1069 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1070 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
)
1072 const measureId
= `${FileType.ChargingStationTemplate} read`
1073 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1074 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
1075 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1076 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1077 .update(JSON
.stringify(template
))
1079 this.sharedLRUCache
.setChargingStationTemplate(template
)
1080 this.templateFileHash
= template
.templateHash
1083 handleFileException(
1085 FileType
.ChargingStationTemplate
,
1086 error
as NodeJS
.ErrnoException
,
1093 private getStationInfoFromTemplate (): ChargingStationInfo
{
1094 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1095 const stationTemplate
= this.getTemplateFromFile()!
1096 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1097 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this)
1098 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
)
1099 if (stationTemplate
.Connectors
!= null) {
1100 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1102 const stationInfo
= stationTemplateToStationInfo(stationTemplate
)
1103 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
)
1104 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
)
1105 stationInfo
.ocppVersion
= stationTemplate
.ocppVersion
?? OCPPVersion
.VERSION_16
1106 createSerialNumber(stationTemplate
, stationInfo
)
1107 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
)
1108 if (isNotEmptyArray(stationTemplate
.power
)) {
1109 stationTemplate
.power
= stationTemplate
.power
as number[]
1110 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
)
1111 stationInfo
.maximumPower
=
1112 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1113 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1114 : stationTemplate
.power
[powerArrayRandomIndex
]
1116 stationTemplate
.power
= stationTemplate
.power
as number
1117 stationInfo
.maximumPower
=
1118 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1119 ? stationTemplate
.power
* 1000
1120 : stationTemplate
.power
1122 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
)
1123 stationInfo
.firmwareVersionPattern
=
1124 stationTemplate
.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
1126 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1127 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1128 !new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!)
1131 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1133 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1136 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1143 stationTemplate
.firmwareUpgrade
?? {}
1145 stationInfo
.resetTime
=
1146 stationTemplate
.resetTime
!= null
1147 ? secondsToMilliseconds(stationTemplate
.resetTime
)
1148 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
1152 private getStationInfoFromFile (
1153 stationInfoPersistentConfiguration
= true
1154 ): ChargingStationInfo
| undefined {
1155 let stationInfo
: ChargingStationInfo
| undefined
1156 if (stationInfoPersistentConfiguration
) {
1157 stationInfo
= this.getConfigurationFromFile()?.stationInfo
1158 if (stationInfo
!= null) {
1159 delete stationInfo
.infoHash
1165 private getStationInfo (): ChargingStationInfo
{
1166 const defaultStationInfo
= Constants
.DEFAULT_STATION_INFO
1167 const stationInfoFromTemplate
= this.getStationInfoFromTemplate()
1168 const stationInfoFromFile
= this.getStationInfoFromFile(
1169 stationInfoFromTemplate
.stationInfoPersistentConfiguration
1172 // 1. charging station info from template
1173 // 2. charging station info from configuration file
1175 stationInfoFromFile
!= null &&
1176 stationInfoFromFile
.templateHash
=== stationInfoFromTemplate
.templateHash
1178 return { ...defaultStationInfo
, ...stationInfoFromFile
}
1180 stationInfoFromFile
!= null &&
1181 propagateSerialNumber(
1182 this.getTemplateFromFile(),
1183 stationInfoFromFile
,
1184 stationInfoFromTemplate
1186 return { ...defaultStationInfo
, ...stationInfoFromTemplate
}
1189 private saveStationInfo (): void {
1190 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1191 this.saveConfiguration()
1195 private handleUnsupportedVersion (version
: OCPPVersion
| undefined): void {
1196 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`
1197 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1198 throw new BaseError(errorMsg
)
1201 private initialize (): void {
1202 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1203 const stationTemplate
= this.getTemplateFromFile()!
1204 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1205 this.configurationFile
= join(
1206 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1207 `${getHashId(this.index, stationTemplate)}.json`
1209 const stationConfiguration
= this.getConfigurationFromFile()
1211 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
.templateHash
&&
1212 (stationConfiguration
?.connectorsStatus
!= null || stationConfiguration
?.evsesStatus
!= null)
1214 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
)
1215 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
)
1217 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
)
1219 this.stationInfo
= this.getStationInfo()
1221 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1222 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1223 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1225 const patternGroup
=
1226 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1227 this.stationInfo
.firmwareVersion
?.split('.').length
1228 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1229 const match
= new RegExp(this.stationInfo
.firmwareVersionPattern
!)
1230 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1231 .exec(this.stationInfo
.firmwareVersion
!)
1232 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1233 ?.slice(1, patternGroup
! + 1)
1234 if (match
!= null) {
1235 const patchLevelIndex
= match
.length
- 1
1236 match
[patchLevelIndex
] = (
1237 convertToInt(match
[patchLevelIndex
]) +
1238 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1239 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1241 this.stationInfo
.firmwareVersion
= match
.join('.')
1244 this.saveStationInfo()
1245 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
1246 if (this.stationInfo
.enableStatistics
=== true) {
1247 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1248 this.stationInfo
.hashId
,
1249 this.stationInfo
.chargingStationId
,
1250 this.configuredSupervisionUrl
1253 const bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
)
1254 if (bootNotificationRequest
== null) {
1255 const errorMsg
= 'Error while creating boot notification request'
1256 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1257 throw new BaseError(errorMsg
)
1259 this.bootNotificationRequest
= bootNotificationRequest
1260 this.powerDivider
= this.getPowerDivider()
1261 // OCPP configuration
1262 this.ocppConfiguration
= this.getOcppConfiguration()
1263 this.initializeOcppConfiguration()
1264 this.initializeOcppServices()
1265 this.once(ChargingStationEvents
.accepted
, () => {
1266 this.startMessageSequence().catch((error
) => {
1267 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
)
1270 if (this.stationInfo
.autoRegister
=== true) {
1271 this.bootNotificationResponse
= {
1272 currentTime
: new Date(),
1273 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1274 status: RegistrationStatusEnumType
.ACCEPTED
1279 private initializeOcppServices (): void {
1280 const ocppVersion
= this.stationInfo
?.ocppVersion
1281 switch (ocppVersion
) {
1282 case OCPPVersion
.VERSION_16
:
1283 this.ocppIncomingRequestService
=
1284 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>()
1285 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1286 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1289 case OCPPVersion
.VERSION_20
:
1290 case OCPPVersion
.VERSION_201
:
1291 this.ocppIncomingRequestService
=
1292 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>()
1293 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1294 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1298 this.handleUnsupportedVersion(ocppVersion
)
1303 private initializeOcppConfiguration (): void {
1304 if (getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
) == null) {
1305 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0')
1307 if (getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
) == null) {
1308 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false })
1311 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1312 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1313 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1314 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!) == null
1316 addConfigurationKey(
1318 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1319 this.stationInfo
.supervisionUrlOcppKey
!,
1320 this.configuredSupervisionUrl
.href
,
1324 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1325 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1326 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1327 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!) != null
1329 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1330 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!, { save
: false })
1333 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1334 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1335 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!) == null
1337 addConfigurationKey(
1339 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1340 this.stationInfo
!.amperageLimitationOcppKey
!,
1342 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1343 (this.stationInfo
!.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)).toString()
1346 if (getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
) == null) {
1347 addConfigurationKey(
1349 StandardParametersKey
.SupportedFeatureProfiles
,
1350 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1353 addConfigurationKey(
1355 StandardParametersKey
.NumberOfConnectors
,
1356 this.getNumberOfConnectors().toString(),
1360 if (getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
) == null) {
1361 addConfigurationKey(
1363 StandardParametersKey
.MeterValuesSampledData
,
1364 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1367 if (getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
) == null) {
1368 const connectorsPhaseRotation
: string[] = []
1369 if (this.hasEvses
) {
1370 for (const evseStatus
of this.evses
.values()) {
1371 for (const connectorId
of evseStatus
.connectors
.keys()) {
1372 connectorsPhaseRotation
.push(
1373 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1374 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1379 for (const connectorId
of this.connectors
.keys()) {
1380 connectorsPhaseRotation
.push(
1381 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1382 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1386 addConfigurationKey(
1388 StandardParametersKey
.ConnectorPhaseRotation
,
1389 connectorsPhaseRotation
.toString()
1392 if (getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
) == null) {
1393 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true')
1396 getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) == null &&
1397 hasFeatureProfile(this, SupportedFeatureProfiles
.LocalAuthListManagement
) === true
1399 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false')
1401 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) == null) {
1402 addConfigurationKey(
1404 StandardParametersKey
.ConnectionTimeOut
,
1405 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1408 this.saveOcppConfiguration()
1411 private initializeConnectorsOrEvsesFromFile (configuration
: ChargingStationConfiguration
): void {
1412 if (configuration
.connectorsStatus
!= null && configuration
.evsesStatus
== null) {
1413 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1414 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
))
1416 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
== null) {
1417 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1418 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
)
1419 delete evseStatus
.connectorsStatus
1420 this.evses
.set(evseId
, {
1421 ...(evseStatus
as EvseStatus
),
1422 connectors
: new Map
<number, ConnectorStatus
>(
1423 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1424 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1431 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
!= null) {
1432 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1433 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1434 throw new BaseError(errorMsg
)
1436 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`
1437 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1438 throw new BaseError(errorMsg
)
1442 private initializeConnectorsOrEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1443 if (stationTemplate
.Connectors
!= null && stationTemplate
.Evses
== null) {
1444 this.initializeConnectorsFromTemplate(stationTemplate
)
1445 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
== null) {
1446 this.initializeEvsesFromTemplate(stationTemplate
)
1447 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
!= null) {
1448 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`
1449 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1450 throw new BaseError(errorMsg
)
1452 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`
1453 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1454 throw new BaseError(errorMsg
)
1458 private initializeConnectorsFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1459 if (stationTemplate
.Connectors
== null && this.connectors
.size
=== 0) {
1460 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1461 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1462 throw new BaseError(errorMsg
)
1464 if (stationTemplate
.Connectors
?.[0] == null) {
1466 `${this.logPrefix()} Charging station information from template ${
1468 } with no connector id 0 configuration`
1471 if (stationTemplate
.Connectors
!= null) {
1472 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1473 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1474 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1476 `${JSON.stringify(stationTemplate.Connectors)}${configuredMaxConnectors.toString()}`
1479 const connectorsConfigChanged
=
1480 this.connectors
.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
1481 if (this.connectors
.size
=== 0 || connectorsConfigChanged
) {
1482 connectorsConfigChanged
&& this.connectors
.clear()
1483 this.connectorsConfigurationHash
= connectorsConfigHash
1484 if (templateMaxConnectors
> 0) {
1485 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1487 connectorId
=== 0 &&
1488 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1489 (stationTemplate
.Connectors
[connectorId
] == null ||
1490 !this.getUseConnectorId0(stationTemplate
))
1494 const templateConnectorId
=
1495 connectorId
> 0 && stationTemplate
.randomConnectors
=== true
1496 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1498 const connectorStatus
= stationTemplate
.Connectors
[templateConnectorId
]
1499 checkStationInfoConnectorStatus(
1500 templateConnectorId
,
1505 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
))
1507 initializeConnectorsMapStatus(this.connectors
, this.logPrefix())
1508 this.saveConnectorsStatus()
1511 `${this.logPrefix()} Charging station information from template ${
1513 } with no connectors configuration defined, cannot create connectors`
1519 `${this.logPrefix()} Charging station information from template ${
1521 } with no connectors configuration defined, using already defined connectors`
1526 private initializeEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1527 if (stationTemplate
.Evses
== null && this.evses
.size
=== 0) {
1528 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1529 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1530 throw new BaseError(errorMsg
)
1532 if (stationTemplate
.Evses
?.[0] == null) {
1534 `${this.logPrefix()} Charging station information from template ${
1536 } with no evse id 0 configuration`
1539 if (stationTemplate
.Evses
?.[0]?.Connectors
[0] == null) {
1541 `${this.logPrefix()} Charging station information from template ${
1543 } with evse id 0 with no connector id 0 configuration`
1546 if (Object.keys(stationTemplate
.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1548 `${this.logPrefix()} Charging station information from template ${
1550 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1553 if (stationTemplate
.Evses
!= null) {
1554 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1555 .update(JSON
.stringify(stationTemplate
.Evses
))
1557 const evsesConfigChanged
=
1558 this.evses
.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
1559 if (this.evses
.size
=== 0 || evsesConfigChanged
) {
1560 evsesConfigChanged
&& this.evses
.clear()
1561 this.evsesConfigurationHash
= evsesConfigHash
1562 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
.Evses
)
1563 if (templateMaxEvses
> 0) {
1564 for (const evseKey
in stationTemplate
.Evses
) {
1565 const evseId
= convertToInt(evseKey
)
1566 this.evses
.set(evseId
, {
1567 connectors
: buildConnectorsMap(
1568 stationTemplate
.Evses
[evseKey
].Connectors
,
1572 availability
: AvailabilityType
.Operative
1574 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1575 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix())
1577 this.saveEvsesStatus()
1580 `${this.logPrefix()} Charging station information from template ${
1582 } with no evses configuration defined, cannot create evses`
1588 `${this.logPrefix()} Charging station information from template ${
1590 } with no evses configuration defined, using already defined evses`
1595 private getConfigurationFromFile (): ChargingStationConfiguration
| undefined {
1596 let configuration
: ChargingStationConfiguration
| undefined
1597 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1599 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1600 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1601 this.configurationFileHash
1604 const measureId
= `${FileType.ChargingStationConfiguration} read`
1605 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1606 configuration
= JSON
.parse(
1607 readFileSync(this.configurationFile
, 'utf8')
1608 ) as ChargingStationConfiguration
1609 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1610 this.sharedLRUCache
.setChargingStationConfiguration(configuration
)
1611 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1612 this.configurationFileHash
= configuration
.configurationHash
!
1615 handleFileException(
1616 this.configurationFile
,
1617 FileType
.ChargingStationConfiguration
,
1618 error
as NodeJS
.ErrnoException
,
1623 return configuration
1626 private saveAutomaticTransactionGeneratorConfiguration (): void {
1627 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1628 this.saveConfiguration()
1632 private saveConnectorsStatus (): void {
1633 this.saveConfiguration()
1636 private saveEvsesStatus (): void {
1637 this.saveConfiguration()
1640 private saveConfiguration (): void {
1641 if (isNotEmptyString(this.configurationFile
)) {
1643 if (!existsSync(dirname(this.configurationFile
))) {
1644 mkdirSync(dirname(this.configurationFile
), { recursive
: true })
1646 const configurationFromFile
= this.getConfigurationFromFile()
1647 let configurationData
: ChargingStationConfiguration
=
1648 configurationFromFile
!= null
1649 ? cloneObject
<ChargingStationConfiguration
>(configurationFromFile
)
1651 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1652 configurationData
.stationInfo
= this.stationInfo
1654 delete configurationData
.stationInfo
1657 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1658 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1660 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
1662 delete configurationData
.configurationKey
1664 configurationData
= merge
<ChargingStationConfiguration
>(
1666 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1669 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== false ||
1670 this.getAutomaticTransactionGeneratorConfiguration() == null
1672 delete configurationData
.automaticTransactionGenerator
1674 if (this.connectors
.size
> 0) {
1675 configurationData
.connectorsStatus
= buildConnectorsStatus(this)
1677 delete configurationData
.connectorsStatus
1679 if (this.evses
.size
> 0) {
1680 configurationData
.evsesStatus
= buildEvsesStatus(this)
1682 delete configurationData
.evsesStatus
1684 delete configurationData
.configurationHash
1685 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1688 stationInfo
: configurationData
.stationInfo
,
1689 configurationKey
: configurationData
.configurationKey
,
1690 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1691 ...(this.connectors
.size
> 0 && {
1692 connectorsStatus
: configurationData
.connectorsStatus
1694 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
})
1695 } satisfies ChargingStationConfiguration
)
1698 if (this.configurationFileHash
!== configurationHash
) {
1699 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1700 configurationData
.configurationHash
= configurationHash
1701 const measureId
= `${FileType.ChargingStationConfiguration} write`
1702 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1704 this.configurationFile
,
1705 JSON
.stringify(configurationData
, undefined, 2),
1708 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1709 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
1710 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
)
1711 this.configurationFileHash
= configurationHash
1712 }).catch((error
) => {
1713 handleFileException(
1714 this.configurationFile
,
1715 FileType
.ChargingStationConfiguration
,
1716 error
as NodeJS
.ErrnoException
,
1722 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1723 this.configurationFile
1728 handleFileException(
1729 this.configurationFile
,
1730 FileType
.ChargingStationConfiguration
,
1731 error
as NodeJS
.ErrnoException
,
1737 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1742 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration
| undefined {
1743 return this.getTemplateFromFile()?.Configuration
1746 private getOcppConfigurationFromFile (): ChargingStationOcppConfiguration
| undefined {
1747 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
1748 if (this.stationInfo
?.ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1749 return { configurationKey
}
1754 private getOcppConfiguration (): ChargingStationOcppConfiguration
| undefined {
1755 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1756 this.getOcppConfigurationFromFile()
1757 if (ocppConfiguration
== null) {
1758 ocppConfiguration
= this.getOcppConfigurationFromTemplate()
1760 return ocppConfiguration
1763 private async onOpen (): Promise
<void> {
1764 if (this.isWebSocketConnectionOpened()) {
1766 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1768 let registrationRetryCount
= 0
1769 if (!this.isRegistered()) {
1770 // Send BootNotification
1772 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1773 BootNotificationRequest
,
1774 BootNotificationResponse
1775 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1776 skipBufferingOnError
: true
1778 if (!this.isRegistered()) {
1779 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
1781 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1782 this.bootNotificationResponse
?.interval
!= null
1783 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1784 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1788 !this.isRegistered() &&
1789 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1790 (registrationRetryCount
<= this.stationInfo
!.registrationMaxRetries
! ||
1791 this.stationInfo
?.registrationMaxRetries
=== -1)
1794 if (this.isRegistered()) {
1795 this.emit(ChargingStationEvents
.registered
)
1796 if (this.inAcceptedState()) {
1797 this.emit(ChargingStationEvents
.accepted
)
1801 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${this
1802 .stationInfo?.registrationMaxRetries})`
1805 this.autoReconnectRetryCount
= 0
1806 this.emit(ChargingStationEvents
.updated
)
1809 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1814 private async onClose (code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): Promise
<void> {
1817 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1818 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1820 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1822 )}' and reason '${reason.toString()}'`
1824 this.autoReconnectRetryCount
= 0
1829 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1831 )}' and reason '${reason.toString()}'`
1833 this.started
&& (await this.reconnect())
1836 this.emit(ChargingStationEvents
.updated
)
1839 private getCachedRequest (messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1840 const cachedRequest
= this.requests
.get(messageId
)
1841 if (Array.isArray(cachedRequest
)) {
1842 return cachedRequest
1844 throw new OCPPError(
1845 ErrorType
.PROTOCOL_ERROR
,
1846 `Cached request for message id ${messageId} ${getMessageTypeString(
1848 )} is not an array`,
1854 private async handleIncomingMessage (request
: IncomingRequest
): Promise
<void> {
1855 const [messageType
, messageId
, commandName
, commandPayload
] = request
1856 if (this.stationInfo
?.enableStatistics
=== true) {
1857 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
)
1860 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1864 // Process the message
1865 await this.ocppIncomingRequestService
.incomingRequestHandler(
1871 this.emit(ChargingStationEvents
.updated
)
1874 private handleResponseMessage (response
: Response
): void {
1875 const [messageType
, messageId
, commandPayload
] = response
1876 if (!this.requests
.has(messageId
)) {
1878 throw new OCPPError(
1879 ErrorType
.INTERNAL_ERROR
,
1880 `Response for unknown message id ${messageId}`,
1886 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1887 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1892 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1896 responseCallback(commandPayload
, requestPayload
)
1899 private handleErrorMessage (errorResponse
: ErrorResponse
): void {
1900 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
1901 if (!this.requests
.has(messageId
)) {
1903 throw new OCPPError(
1904 ErrorType
.INTERNAL_ERROR
,
1905 `Error response for unknown message id ${messageId}`,
1907 { errorType
, errorMessage
, errorDetails
}
1910 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1911 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1913 `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify(
1917 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
))
1920 private async onMessage (data
: RawData
): Promise
<void> {
1921 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined
1922 let messageType
: MessageType
| undefined
1923 let errorMsg
: string
1925 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1926 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
1927 if (Array.isArray(request
)) {
1928 [messageType
] = request
1929 // Check the type of message
1930 switch (messageType
) {
1932 case MessageType
.CALL_MESSAGE
:
1933 await this.handleIncomingMessage(request
as IncomingRequest
)
1936 case MessageType
.CALL_RESULT_MESSAGE
:
1937 this.handleResponseMessage(request
as Response
)
1940 case MessageType
.CALL_ERROR_MESSAGE
:
1941 this.handleErrorMessage(request
as ErrorResponse
)
1945 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1946 errorMsg
= `Wrong message type ${messageType}`
1947 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1948 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
)
1951 throw new OCPPError(
1952 ErrorType
.PROTOCOL_ERROR
,
1953 'Incoming message is not an array',
1961 let commandName
: IncomingRequestCommand
| undefined
1962 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined
1963 let errorCallback
: ErrorCallback
1964 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1965 const [, messageId
] = request
!
1966 switch (messageType
) {
1967 case MessageType
.CALL_MESSAGE
:
1968 [, , commandName
] = request
as IncomingRequest
1970 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
)
1972 case MessageType
.CALL_RESULT_MESSAGE
:
1973 case MessageType
.CALL_ERROR_MESSAGE
:
1974 if (this.requests
.has(messageId
)) {
1975 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1976 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1977 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1978 errorCallback(error
as OCPPError
, false)
1980 // Remove the request from the cache in case of error at response handling
1981 this.requests
.delete(messageId
)
1985 if (!(error
instanceof OCPPError
)) {
1987 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1988 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1989 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1990 }' message '${data.toString()}' handling is not an OCPPError:`,
1995 `${this.logPrefix()} Incoming OCPP command '${
1996 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1997 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1998 }' message '${data.toString()}'${
1999 messageType !== MessageType.CALL_MESSAGE
2000 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2002 } processing error:`,
2008 private onPing (): void {
2009 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
2012 private onPong (): void {
2013 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
2016 private onError (error
: WSError
): void {
2017 this.closeWSConnection()
2018 logger
.error(`${this.logPrefix()} WebSocket error:`, error
)
2021 private getEnergyActiveImportRegister (connectorStatus
: ConnectorStatus
, rounded
= false): number {
2022 if (this.stationInfo
?.meteringPerTransaction
=== true) {
2025 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2026 Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
2027 : connectorStatus
.transactionEnergyActiveImportRegisterValue
) ?? 0
2032 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2033 Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2034 : connectorStatus
.energyActiveImportRegisterValue
) ?? 0
2038 private getUseConnectorId0 (stationTemplate
?: ChargingStationTemplate
): boolean {
2039 return stationTemplate
?.useConnectorId0
?? true
2042 private async stopRunningTransactions (reason
?: StopTransactionReason
): Promise
<void> {
2043 if (this.hasEvses
) {
2044 for (const [evseId
, evseStatus
] of this.evses
) {
2048 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2049 if (connectorStatus
.transactionStarted
=== true) {
2050 await this.stopTransactionOnConnector(connectorId
, reason
)
2055 for (const connectorId
of this.connectors
.keys()) {
2056 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2057 await this.stopTransactionOnConnector(connectorId
, reason
)
2064 private getConnectionTimeout (): number {
2065 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) != null) {
2066 return convertToInt(
2067 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)?.value
??
2068 Constants
.DEFAULT_CONNECTION_TIMEOUT
2071 return Constants
.DEFAULT_CONNECTION_TIMEOUT
2074 private getPowerDivider (): number {
2075 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()
2076 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2077 powerDivider
= this.getNumberOfRunningTransactions()
2082 private getMaximumAmperage (stationInfo
?: ChargingStationInfo
): number | undefined {
2083 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2084 const maximumPower
= (stationInfo
?? this.stationInfo
!).maximumPower
!
2085 switch (this.getCurrentOutType(stationInfo
)) {
2086 case CurrentType
.AC
:
2087 return ACElectricUtils
.amperagePerPhaseFromPower(
2088 this.getNumberOfPhases(stationInfo
),
2089 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2090 this.getVoltageOut(stationInfo
)
2092 case CurrentType
.DC
:
2093 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
))
2097 private getCurrentOutType (stationInfo
?: ChargingStationInfo
): CurrentType
{
2098 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2099 return (stationInfo
?? this.stationInfo
!).currentOutType
?? CurrentType
.AC
2102 private getVoltageOut (stationInfo
?: ChargingStationInfo
): Voltage
{
2104 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2105 (stationInfo
?? this.stationInfo
!).voltageOut
??
2106 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2110 private getAmperageLimitation (): number | undefined {
2112 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2113 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2114 getConfigurationKey(this, this.stationInfo
!.amperageLimitationOcppKey
!) != null
2118 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2119 getConfigurationKey(this, this.stationInfo
!.amperageLimitationOcppKey
!)!.value
2120 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2121 ) / getAmperageLimitationUnitDivider(this.stationInfo
!)
2126 private async startMessageSequence (): Promise
<void> {
2127 if (this.stationInfo
?.autoRegister
=== true) {
2128 await this.ocppRequestService
.requestHandler
<
2129 BootNotificationRequest
,
2130 BootNotificationResponse
2131 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2132 skipBufferingOnError
: true
2135 // Start WebSocket ping
2136 this.startWebSocketPing()
2138 this.startHeartbeat()
2139 // Initialize connectors status
2140 if (this.hasEvses
) {
2141 for (const [evseId
, evseStatus
] of this.evses
) {
2143 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2144 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
)
2145 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
, evseId
)
2150 for (const connectorId
of this.connectors
.keys()) {
2151 if (connectorId
> 0) {
2152 const connectorBootStatus
= getBootConnectorStatus(
2155 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2156 this.getConnectorStatus(connectorId
)!
2158 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
)
2162 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2163 await this.ocppRequestService
.requestHandler
<
2164 FirmwareStatusNotificationRequest
,
2165 FirmwareStatusNotificationResponse
2166 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2167 status: FirmwareStatus
.Installed
2169 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
2173 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2174 this.startAutomaticTransactionGenerator()
2176 this.flushMessageBuffer()
2179 private async stopMessageSequence (
2180 reason
?: StopTransactionReason
,
2181 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
2183 // Stop WebSocket ping
2184 this.stopWebSocketPing()
2186 this.stopHeartbeat()
2188 if (this.automaticTransactionGenerator
?.started
=== true) {
2189 this.stopAutomaticTransactionGenerator()
2191 // Stop ongoing transactions
2192 stopTransactions
=== true && (await this.stopRunningTransactions(reason
))
2193 if (this.hasEvses
) {
2194 for (const [evseId
, evseStatus
] of this.evses
) {
2196 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2197 await this.ocppRequestService
.requestHandler
<
2198 StatusNotificationRequest
,
2199 StatusNotificationResponse
2202 RequestCommand
.STATUS_NOTIFICATION
,
2203 buildStatusNotificationRequest(
2206 ConnectorStatusEnum
.Unavailable
,
2210 delete connectorStatus
.status
2215 for (const connectorId
of this.connectors
.keys()) {
2216 if (connectorId
> 0) {
2217 await this.ocppRequestService
.requestHandler
<
2218 StatusNotificationRequest
,
2219 StatusNotificationResponse
2222 RequestCommand
.STATUS_NOTIFICATION
,
2223 buildStatusNotificationRequest(this, connectorId
, ConnectorStatusEnum
.Unavailable
)
2225 delete this.getConnectorStatus(connectorId
)?.status
2231 private startWebSocketPing (): void {
2232 const webSocketPingInterval
=
2233 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) != null
2235 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
2238 if (webSocketPingInterval
> 0 && this.webSocketPingSetInterval
== null) {
2239 this.webSocketPingSetInterval
= setInterval(() => {
2240 if (this.isWebSocketConnectionOpened()) {
2241 this.wsConnection
?.ping()
2243 }, secondsToMilliseconds(webSocketPingInterval
))
2245 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2246 webSocketPingInterval
2249 } else if (this.webSocketPingSetInterval
!= null) {
2251 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2252 webSocketPingInterval
2257 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2262 private stopWebSocketPing (): void {
2263 if (this.webSocketPingSetInterval
!= null) {
2264 clearInterval(this.webSocketPingSetInterval
)
2265 delete this.webSocketPingSetInterval
2269 private getConfiguredSupervisionUrl (): URL
{
2270 let configuredSupervisionUrl
: string
2271 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls()
2272 if (isNotEmptyArray(supervisionUrls
)) {
2273 let configuredSupervisionUrlIndex
: number
2274 switch (Configuration
.getSupervisionUrlDistribution()) {
2275 case SupervisionUrlDistribution
.RANDOM
:
2276 configuredSupervisionUrlIndex
= Math.floor(
2277 secureRandom() * (supervisionUrls
as string[]).length
2280 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2281 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2283 !Object.values(SupervisionUrlDistribution
).includes(
2284 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2285 Configuration
.getSupervisionUrlDistribution()!
2288 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2289 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2290 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2293 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
2296 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
]
2298 configuredSupervisionUrl
= supervisionUrls
as string
2300 if (isNotEmptyString(configuredSupervisionUrl
)) {
2301 return new URL(configuredSupervisionUrl
)
2303 const errorMsg
= 'No supervision url(s) configured'
2304 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2305 throw new BaseError(errorMsg
)
2308 private stopHeartbeat (): void {
2309 if (this.heartbeatSetInterval
!= null) {
2310 clearInterval(this.heartbeatSetInterval
)
2311 delete this.heartbeatSetInterval
2315 private terminateWSConnection (): void {
2316 if (this.isWebSocketConnectionOpened()) {
2317 this.wsConnection
?.terminate()
2318 this.wsConnection
= null
2322 private async reconnect (): Promise
<void> {
2323 // Stop WebSocket ping
2324 this.stopWebSocketPing()
2326 this.stopHeartbeat()
2327 // Stop the ATG if needed
2328 if (this.getAutomaticTransactionGeneratorConfiguration()?.stopOnConnectionFailure
=== true) {
2329 this.stopAutomaticTransactionGenerator()
2332 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2333 this.autoReconnectRetryCount
< this.stationInfo
!.autoReconnectMaxRetries
! ||
2334 this.stationInfo
?.autoReconnectMaxRetries
=== -1
2336 ++this.autoReconnectRetryCount
2337 const reconnectDelay
=
2338 this.stationInfo
?.reconnectExponentialDelay
=== true
2339 ? exponentialDelay(this.autoReconnectRetryCount
)
2340 : secondsToMilliseconds(this.getConnectionTimeout())
2341 const reconnectDelayWithdraw
= 1000
2342 const reconnectTimeout
=
2343 reconnectDelay
- reconnectDelayWithdraw
> 0 ? reconnectDelay
- reconnectDelayWithdraw
: 0
2345 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2348 )}ms, timeout ${reconnectTimeout}ms`
2350 await sleep(reconnectDelay
)
2352 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2354 this.openWSConnection(
2356 handshakeTimeout
: reconnectTimeout
2358 { closeOpened
: true }
2360 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2362 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2363 this.autoReconnectRetryCount
2364 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`