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 | undefined): number | undefined {
431 if (transactionId
== null) {
433 } else if (this.hasEvses
) {
434 for (const evseStatus
of this.evses
.values()) {
435 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
436 if (connectorStatus
.transactionId
=== transactionId
) {
442 for (const connectorId
of this.connectors
.keys()) {
443 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
450 public getEnergyActiveImportRegisterByTransactionId (
451 transactionId
: number | undefined,
454 return this.getEnergyActiveImportRegister(
455 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
456 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!),
461 public getEnergyActiveImportRegisterByConnectorId (connectorId
: number, rounded
= false): number {
462 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
)
465 public getAuthorizeRemoteTxRequests (): boolean {
466 const authorizeRemoteTxRequests
= getConfigurationKey(
468 StandardParametersKey
.AuthorizeRemoteTxRequests
470 return authorizeRemoteTxRequests
!= null
471 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
475 public getLocalAuthListEnabled (): boolean {
476 const localAuthListEnabled
= getConfigurationKey(
478 StandardParametersKey
.LocalAuthListEnabled
480 return localAuthListEnabled
!= null ? convertToBoolean(localAuthListEnabled
.value
) : false
483 public getHeartbeatInterval (): number {
484 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)
485 if (HeartbeatInterval
!= null) {
486 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
))
488 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)
489 if (HeartBeatInterval
!= null) {
490 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
))
492 this.stationInfo
?.autoRegister
=== false &&
494 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
495 Constants.DEFAULT_HEARTBEAT_INTERVAL
498 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
501 public setSupervisionUrl (url
: string): void {
503 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
504 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
)
506 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
507 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
!, url
)
509 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
510 this.stationInfo
!.supervisionUrls
= url
511 this.saveStationInfo()
512 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
516 public startHeartbeat (): void {
517 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
== null) {
518 this.heartbeatSetInterval
= setInterval(() => {
519 this.ocppRequestService
520 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
523 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
527 }, this.getHeartbeatInterval())
529 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
530 this.getHeartbeatInterval()
533 } else if (this.heartbeatSetInterval
!= null) {
535 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
536 this.getHeartbeatInterval()
541 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
546 public restartHeartbeat (): void {
550 this.startHeartbeat()
553 public restartWebSocketPing (): void {
554 // Stop WebSocket ping
555 this.stopWebSocketPing()
556 // Start WebSocket ping
557 this.startWebSocketPing()
560 public startMeterValues (connectorId
: number, interval
: number): void {
561 if (connectorId
=== 0) {
562 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`)
565 const connectorStatus
= this.getConnectorStatus(connectorId
)
566 if (connectorStatus
== null) {
568 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
573 if (connectorStatus
.transactionStarted
=== false) {
575 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
579 connectorStatus
.transactionStarted
=== true &&
580 connectorStatus
.transactionId
== null
583 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
588 connectorStatus
.transactionSetInterval
= setInterval(() => {
589 const meterValue
= buildMeterValue(
592 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
593 connectorStatus
.transactionId
!,
596 this.ocppRequestService
597 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
599 RequestCommand
.METER_VALUES
,
602 transactionId
: connectorStatus
.transactionId
,
603 meterValue
: [meterValue
]
608 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
615 `${this.logPrefix()} Charging station ${
616 StandardParametersKey.MeterValueSampleInterval
617 } configuration set to ${interval}, not sending MeterValues`
622 public stopMeterValues (connectorId
: number): void {
623 const connectorStatus
= this.getConnectorStatus(connectorId
)
624 if (connectorStatus
?.transactionSetInterval
!= null) {
625 clearInterval(connectorStatus
.transactionSetInterval
)
629 public start (): void {
631 if (!this.starting
) {
633 if (this.stationInfo
?.enableStatistics
=== true) {
634 this.performanceStatistics
?.start()
636 this.openWSConnection()
637 // Monitor charging station template file
638 this.templateFileWatcher
= watchJsonFile(
640 FileType
.ChargingStationTemplate
,
643 (event
, filename
): void => {
644 if (isNotEmptyString(filename
) && event
=== 'change') {
647 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
649 } file have changed, reload`
651 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
654 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
655 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
!)!)
657 this.stopAutomaticTransactionGenerator()
658 delete this.automaticTransactionGeneratorConfiguration
659 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
660 this.startAutomaticTransactionGenerator()
662 if (this.stationInfo
?.enableStatistics
=== true) {
663 this.performanceStatistics
?.restart()
665 this.performanceStatistics
?.stop()
667 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
670 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
678 this.emit(ChargingStationEvents
.started
)
679 this.starting
= false
681 logger
.warn(`${this.logPrefix()} Charging station is already starting...`)
684 logger
.warn(`${this.logPrefix()} Charging station is already started...`)
688 public async stop (reason
?: StopTransactionReason
, stopTransactions
?: boolean): Promise
<void> {
690 if (!this.stopping
) {
692 await this.stopMessageSequence(reason
, stopTransactions
)
693 this.closeWSConnection()
694 if (this.stationInfo
?.enableStatistics
=== true) {
695 this.performanceStatistics
?.stop()
697 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
698 this.templateFileWatcher
?.close()
699 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
700 delete this.bootNotificationResponse
702 this.saveConfiguration()
703 this.emit(ChargingStationEvents
.stopped
)
704 this.stopping
= false
706 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`)
709 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`)
713 public async reset (reason
?: StopTransactionReason
): Promise
<void> {
714 await this.stop(reason
)
715 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
716 await sleep(this.stationInfo
!.resetTime
!)
721 public saveOcppConfiguration (): void {
722 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
723 this.saveConfiguration()
727 public bufferMessage (message
: string): void {
728 this.messageBuffer
.add(message
)
729 this.setIntervalFlushMessageBuffer()
732 public openWSConnection (
734 params
?: { closeOpened
?: boolean, terminateOpened
?: boolean }
737 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
738 ...this.stationInfo
?.wsOptions
,
741 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
}
742 if (!checkChargingStation(this, this.logPrefix())) {
745 if (this.stationInfo
?.supervisionUser
!= null && this.stationInfo
.supervisionPassword
!= null) {
746 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`
748 if (params
.closeOpened
=== true) {
749 this.closeWSConnection()
751 if (params
.terminateOpened
=== true) {
752 this.terminateWSConnection()
755 if (this.isWebSocketConnectionOpened()) {
757 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
763 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
766 this.wsConnection
= new WebSocket(
767 this.wsConnectionUrl
,
768 `ocpp${this.stationInfo?.ocppVersion}`,
772 // Handle WebSocket message
773 this.wsConnection
.on(
775 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
777 // Handle WebSocket error
778 this.wsConnection
.on(
780 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
782 // Handle WebSocket close
783 this.wsConnection
.on(
785 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
787 // Handle WebSocket open
788 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void)
789 // Handle WebSocket ping
790 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void)
791 // Handle WebSocket pong
792 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void)
795 public closeWSConnection (): void {
796 if (this.isWebSocketConnectionOpened()) {
797 this.wsConnection
?.close()
798 this.wsConnection
= null
802 public getAutomaticTransactionGeneratorConfiguration ():
803 | AutomaticTransactionGeneratorConfiguration
805 if (this.automaticTransactionGeneratorConfiguration
== null) {
806 let automaticTransactionGeneratorConfiguration
:
807 | AutomaticTransactionGeneratorConfiguration
809 const stationTemplate
= this.getTemplateFromFile()
810 const stationConfiguration
= this.getConfigurationFromFile()
812 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
813 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
814 stationConfiguration
?.automaticTransactionGenerator
!= null
816 automaticTransactionGeneratorConfiguration
=
817 stationConfiguration
.automaticTransactionGenerator
819 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
821 this.automaticTransactionGeneratorConfiguration
= {
822 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
823 ...automaticTransactionGeneratorConfiguration
826 return this.automaticTransactionGeneratorConfiguration
829 public getAutomaticTransactionGeneratorStatuses (): Status
[] | undefined {
830 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
833 public startAutomaticTransactionGenerator (connectorIds
?: number[]): void {
834 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this)
835 if (isNotEmptyArray(connectorIds
)) {
836 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
837 for (const connectorId
of connectorIds
!) {
838 this.automaticTransactionGenerator
?.startConnector(connectorId
)
841 this.automaticTransactionGenerator
?.start()
843 this.saveAutomaticTransactionGeneratorConfiguration()
844 this.emit(ChargingStationEvents
.updated
)
847 public stopAutomaticTransactionGenerator (connectorIds
?: number[]): void {
848 if (isNotEmptyArray(connectorIds
)) {
849 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
850 for (const connectorId
of connectorIds
!) {
851 this.automaticTransactionGenerator
?.stopConnector(connectorId
)
854 this.automaticTransactionGenerator
?.stop()
856 this.saveAutomaticTransactionGeneratorConfiguration()
857 this.emit(ChargingStationEvents
.updated
)
860 public async stopTransactionOnConnector (
862 reason
?: StopTransactionReason
863 ): Promise
<StopTransactionResponse
> {
864 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
866 this.stationInfo
?.beginEndMeterValues
=== true &&
867 this.stationInfo
.ocppStrictCompliance
=== true &&
868 this.stationInfo
.outOfOrderEndMeterValues
=== false
870 const transactionEndMeterValue
= buildTransactionEndMeterValue(
873 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
875 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
877 RequestCommand
.METER_VALUES
,
881 meterValue
: [transactionEndMeterValue
]
885 return await this.ocppRequestService
.requestHandler
<
886 StopTransactionRequest
,
887 StopTransactionResponse
888 >(this, RequestCommand
.STOP_TRANSACTION
, {
890 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
891 ...(reason
!= null && { reason
})
895 public getReserveConnectorZeroSupported (): boolean {
896 return convertToBoolean(
897 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
898 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
902 public async addReservation (reservation
: Reservation
): Promise
<void> {
903 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
)
904 if (reservationFound
!= null) {
905 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
)
907 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
908 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
909 await sendAndSetConnectorStatus(
911 reservation
.connectorId
,
912 ConnectorStatusEnum
.Reserved
,
914 { send
: reservation
.connectorId
!== 0 }
918 public async removeReservation (
919 reservation
: Reservation
,
920 reason
: ReservationTerminationReason
922 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
923 const connector
= this.getConnectorStatus(reservation
.connectorId
)!
925 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
926 case ReservationTerminationReason
.TRANSACTION_STARTED
:
927 delete connector
.reservation
929 case ReservationTerminationReason
.RESERVATION_CANCELED
:
930 case ReservationTerminationReason
.REPLACE_EXISTING
:
931 case ReservationTerminationReason
.EXPIRED
:
932 await sendAndSetConnectorStatus(
934 reservation
.connectorId
,
935 ConnectorStatusEnum
.Available
,
937 { send
: reservation
.connectorId
!== 0 }
939 delete connector
.reservation
942 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
943 throw new BaseError(`Unknown reservation termination reason '${reason}'`)
947 public getReservationBy (
948 filterKey
: ReservationKey
,
949 value
: number | string
950 ): Reservation
| undefined {
952 for (const evseStatus
of this.evses
.values()) {
953 for (const connectorStatus
of evseStatus
.connectors
.values()) {
954 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
955 return connectorStatus
.reservation
960 for (const connectorStatus
of this.connectors
.values()) {
961 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
962 return connectorStatus
.reservation
968 public isConnectorReservable (
969 reservationId
: number,
973 const reservation
= this.getReservationBy('reservationId', reservationId
)
974 const reservationExists
= reservation
!== undefined && !hasReservationExpired(reservation
)
975 if (arguments.length
=== 1) {
976 return !reservationExists
977 } else if (arguments.length
> 1) {
978 const userReservation
=
979 idTag
!== undefined ? this.getReservationBy('idTag', idTag
) : undefined
980 const userReservationExists
=
981 userReservation
!== undefined && !hasReservationExpired(userReservation
)
982 const notConnectorZero
= connectorId
=== undefined ? true : connectorId
> 0
983 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0
985 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
991 private setIntervalFlushMessageBuffer (): void {
992 if (this.flushMessageBufferSetInterval
== null) {
993 this.flushMessageBufferSetInterval
= setInterval(() => {
994 if (this.isWebSocketConnectionOpened() && this.inAcceptedState()) {
995 this.flushMessageBuffer()
997 if (this.messageBuffer
.size
=== 0) {
998 this.clearIntervalFlushMessageBuffer()
1000 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
)
1004 private clearIntervalFlushMessageBuffer (): void {
1005 if (this.flushMessageBufferSetInterval
!= null) {
1006 clearInterval(this.flushMessageBufferSetInterval
)
1007 delete this.flushMessageBufferSetInterval
1011 private getNumberOfReservableConnectors (): number {
1012 let numberOfReservableConnectors
= 0
1013 if (this.hasEvses
) {
1014 for (const evseStatus
of this.evses
.values()) {
1015 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
)
1018 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
)
1020 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero()
1023 private getNumberOfReservationsOnConnectorZero (): number {
1025 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
!= null) ||
1026 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
!= null)
1033 private flushMessageBuffer (): void {
1034 if (this.messageBuffer
.size
> 0) {
1035 for (const message
of this.messageBuffer
.values()) {
1036 let beginId
: string | undefined
1037 let commandName
: RequestCommand
| undefined
1038 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
1039 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
1041 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
1042 beginId
= PerformanceStatistics
.beginMeasure(commandName
)
1044 this.wsConnection
?.send(message
, (error
?: Error) => {
1045 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1046 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!)
1047 if (error
== null) {
1049 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1051 )} OCPP message sent '${JSON.stringify(message)}'`
1053 this.messageBuffer
.delete(message
)
1056 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1058 )} OCPP message '${JSON.stringify(message)}' send failed:`,
1067 private getTemplateFromFile (): ChargingStationTemplate
| undefined {
1068 let template
: ChargingStationTemplate
| undefined
1070 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1071 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
)
1073 const measureId
= `${FileType.ChargingStationTemplate} read`
1074 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1075 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
1076 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1077 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1078 .update(JSON
.stringify(template
))
1080 this.sharedLRUCache
.setChargingStationTemplate(template
)
1081 this.templateFileHash
= template
.templateHash
1084 handleFileException(
1086 FileType
.ChargingStationTemplate
,
1087 error
as NodeJS
.ErrnoException
,
1094 private getStationInfoFromTemplate (): ChargingStationInfo
{
1095 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1096 const stationTemplate
= this.getTemplateFromFile()!
1097 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1098 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this)
1099 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
)
1100 if (stationTemplate
.Connectors
!= null) {
1101 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1103 const stationInfo
= stationTemplateToStationInfo(stationTemplate
)
1104 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
)
1105 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
)
1106 stationInfo
.ocppVersion
= stationTemplate
.ocppVersion
?? OCPPVersion
.VERSION_16
1107 createSerialNumber(stationTemplate
, stationInfo
)
1108 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
)
1109 if (isNotEmptyArray(stationTemplate
.power
)) {
1110 stationTemplate
.power
= stationTemplate
.power
as number[]
1111 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
)
1112 stationInfo
.maximumPower
=
1113 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1114 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1115 : stationTemplate
.power
[powerArrayRandomIndex
]
1117 stationTemplate
.power
= stationTemplate
.power
as number
1118 stationInfo
.maximumPower
=
1119 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1120 ? stationTemplate
.power
* 1000
1121 : stationTemplate
.power
1123 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
)
1124 stationInfo
.firmwareVersionPattern
=
1125 stationTemplate
.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
1127 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1128 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1129 !new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!)
1132 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1134 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1137 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1144 stationTemplate
.firmwareUpgrade
?? {}
1146 stationInfo
.resetTime
=
1147 stationTemplate
.resetTime
!= null
1148 ? secondsToMilliseconds(stationTemplate
.resetTime
)
1149 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
1153 private getStationInfoFromFile (
1154 stationInfoPersistentConfiguration
= true
1155 ): ChargingStationInfo
| undefined {
1156 let stationInfo
: ChargingStationInfo
| undefined
1157 if (stationInfoPersistentConfiguration
) {
1158 stationInfo
= this.getConfigurationFromFile()?.stationInfo
1159 if (stationInfo
!= null) {
1160 delete stationInfo
.infoHash
1166 private getStationInfo (): ChargingStationInfo
{
1167 const defaultStationInfo
= Constants
.DEFAULT_STATION_INFO
1168 const stationInfoFromTemplate
= this.getStationInfoFromTemplate()
1169 const stationInfoFromFile
= this.getStationInfoFromFile(
1170 stationInfoFromTemplate
.stationInfoPersistentConfiguration
1173 // 1. charging station info from template
1174 // 2. charging station info from configuration file
1176 stationInfoFromFile
!= null &&
1177 stationInfoFromFile
.templateHash
=== stationInfoFromTemplate
.templateHash
1179 return { ...defaultStationInfo
, ...stationInfoFromFile
}
1181 stationInfoFromFile
!= null &&
1182 propagateSerialNumber(
1183 this.getTemplateFromFile(),
1184 stationInfoFromFile
,
1185 stationInfoFromTemplate
1187 return { ...defaultStationInfo
, ...stationInfoFromTemplate
}
1190 private saveStationInfo (): void {
1191 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1192 this.saveConfiguration()
1196 private handleUnsupportedVersion (version
: OCPPVersion
| undefined): void {
1197 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`
1198 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1199 throw new BaseError(errorMsg
)
1202 private initialize (): void {
1203 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1204 const stationTemplate
= this.getTemplateFromFile()!
1205 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1206 this.configurationFile
= join(
1207 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1208 `${getHashId(this.index, stationTemplate)}.json`
1210 const stationConfiguration
= this.getConfigurationFromFile()
1212 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
.templateHash
&&
1213 (stationConfiguration
?.connectorsStatus
!= null || stationConfiguration
?.evsesStatus
!= null)
1215 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
)
1216 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
)
1218 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
)
1220 this.stationInfo
= this.getStationInfo()
1222 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1223 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1224 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1226 const patternGroup
=
1227 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1228 this.stationInfo
.firmwareVersion
?.split('.').length
1229 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1230 const match
= new RegExp(this.stationInfo
.firmwareVersionPattern
!)
1231 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1232 .exec(this.stationInfo
.firmwareVersion
!)
1233 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1234 ?.slice(1, patternGroup
! + 1)
1235 if (match
!= null) {
1236 const patchLevelIndex
= match
.length
- 1
1237 match
[patchLevelIndex
] = (
1238 convertToInt(match
[patchLevelIndex
]) +
1239 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1240 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1242 this.stationInfo
.firmwareVersion
= match
.join('.')
1245 this.saveStationInfo()
1246 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
1247 if (this.stationInfo
.enableStatistics
=== true) {
1248 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1249 this.stationInfo
.hashId
,
1250 this.stationInfo
.chargingStationId
,
1251 this.configuredSupervisionUrl
1254 const bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
)
1255 if (bootNotificationRequest
== null) {
1256 const errorMsg
= 'Error while creating boot notification request'
1257 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1258 throw new BaseError(errorMsg
)
1260 this.bootNotificationRequest
= bootNotificationRequest
1261 this.powerDivider
= this.getPowerDivider()
1262 // OCPP configuration
1263 this.ocppConfiguration
= this.getOcppConfiguration()
1264 this.initializeOcppConfiguration()
1265 this.initializeOcppServices()
1266 this.once(ChargingStationEvents
.accepted
, () => {
1267 this.startMessageSequence().catch(error
=> {
1268 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
)
1271 if (this.stationInfo
.autoRegister
=== true) {
1272 this.bootNotificationResponse
= {
1273 currentTime
: new Date(),
1274 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1275 status: RegistrationStatusEnumType
.ACCEPTED
1280 private initializeOcppServices (): void {
1281 const ocppVersion
= this.stationInfo
?.ocppVersion
1282 switch (ocppVersion
) {
1283 case OCPPVersion
.VERSION_16
:
1284 this.ocppIncomingRequestService
=
1285 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>()
1286 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1287 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1290 case OCPPVersion
.VERSION_20
:
1291 case OCPPVersion
.VERSION_201
:
1292 this.ocppIncomingRequestService
=
1293 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>()
1294 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1295 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1299 this.handleUnsupportedVersion(ocppVersion
)
1304 private initializeOcppConfiguration (): void {
1305 if (getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
) == null) {
1306 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0')
1308 if (getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
) == null) {
1309 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false })
1312 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1313 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1314 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1315 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!) == null
1317 addConfigurationKey(
1319 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1320 this.stationInfo
.supervisionUrlOcppKey
!,
1321 this.configuredSupervisionUrl
.href
,
1325 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1326 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1327 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1328 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!) != null
1330 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1331 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!, { save
: false })
1334 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1335 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1336 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!) == null
1338 addConfigurationKey(
1340 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1341 this.stationInfo
!.amperageLimitationOcppKey
!,
1343 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1344 (this.stationInfo
!.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)).toString()
1347 if (getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
) == null) {
1348 addConfigurationKey(
1350 StandardParametersKey
.SupportedFeatureProfiles
,
1351 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1354 addConfigurationKey(
1356 StandardParametersKey
.NumberOfConnectors
,
1357 this.getNumberOfConnectors().toString(),
1361 if (getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
) == null) {
1362 addConfigurationKey(
1364 StandardParametersKey
.MeterValuesSampledData
,
1365 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1368 if (getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
) == null) {
1369 const connectorsPhaseRotation
: string[] = []
1370 if (this.hasEvses
) {
1371 for (const evseStatus
of this.evses
.values()) {
1372 for (const connectorId
of evseStatus
.connectors
.keys()) {
1373 connectorsPhaseRotation
.push(
1374 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1375 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1380 for (const connectorId
of this.connectors
.keys()) {
1381 connectorsPhaseRotation
.push(
1382 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1383 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1387 addConfigurationKey(
1389 StandardParametersKey
.ConnectorPhaseRotation
,
1390 connectorsPhaseRotation
.toString()
1393 if (getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
) == null) {
1394 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true')
1397 getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) == null &&
1398 hasFeatureProfile(this, SupportedFeatureProfiles
.LocalAuthListManagement
) === true
1400 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false')
1402 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) == null) {
1403 addConfigurationKey(
1405 StandardParametersKey
.ConnectionTimeOut
,
1406 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1409 this.saveOcppConfiguration()
1412 private initializeConnectorsOrEvsesFromFile (configuration
: ChargingStationConfiguration
): void {
1413 if (configuration
.connectorsStatus
!= null && configuration
.evsesStatus
== null) {
1414 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1415 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
))
1417 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
== null) {
1418 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1419 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
)
1420 delete evseStatus
.connectorsStatus
1421 this.evses
.set(evseId
, {
1422 ...(evseStatus
as EvseStatus
),
1423 connectors
: new Map
<number, ConnectorStatus
>(
1424 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1425 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1432 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
!= null) {
1433 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1434 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1435 throw new BaseError(errorMsg
)
1437 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`
1438 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1439 throw new BaseError(errorMsg
)
1443 private initializeConnectorsOrEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1444 if (stationTemplate
.Connectors
!= null && stationTemplate
.Evses
== null) {
1445 this.initializeConnectorsFromTemplate(stationTemplate
)
1446 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
== null) {
1447 this.initializeEvsesFromTemplate(stationTemplate
)
1448 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
!= null) {
1449 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`
1450 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1451 throw new BaseError(errorMsg
)
1453 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`
1454 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1455 throw new BaseError(errorMsg
)
1459 private initializeConnectorsFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1460 if (stationTemplate
.Connectors
== null && this.connectors
.size
=== 0) {
1461 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1462 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1463 throw new BaseError(errorMsg
)
1465 if (stationTemplate
.Connectors
?.[0] == null) {
1467 `${this.logPrefix()} Charging station information from template ${
1469 } with no connector id 0 configuration`
1472 if (stationTemplate
.Connectors
!= null) {
1473 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1474 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1475 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1477 `${JSON.stringify(stationTemplate.Connectors)}${configuredMaxConnectors.toString()}`
1480 const connectorsConfigChanged
=
1481 this.connectors
.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
1482 if (this.connectors
.size
=== 0 || connectorsConfigChanged
) {
1483 connectorsConfigChanged
&& this.connectors
.clear()
1484 this.connectorsConfigurationHash
= connectorsConfigHash
1485 if (templateMaxConnectors
> 0) {
1486 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1488 connectorId
=== 0 &&
1489 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1490 (stationTemplate
.Connectors
[connectorId
] == null ||
1491 !this.getUseConnectorId0(stationTemplate
))
1495 const templateConnectorId
=
1496 connectorId
> 0 && stationTemplate
.randomConnectors
=== true
1497 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1499 const connectorStatus
= stationTemplate
.Connectors
[templateConnectorId
]
1500 checkStationInfoConnectorStatus(
1501 templateConnectorId
,
1506 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
))
1508 initializeConnectorsMapStatus(this.connectors
, this.logPrefix())
1509 this.saveConnectorsStatus()
1512 `${this.logPrefix()} Charging station information from template ${
1514 } with no connectors configuration defined, cannot create connectors`
1520 `${this.logPrefix()} Charging station information from template ${
1522 } with no connectors configuration defined, using already defined connectors`
1527 private initializeEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1528 if (stationTemplate
.Evses
== null && this.evses
.size
=== 0) {
1529 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1530 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1531 throw new BaseError(errorMsg
)
1533 if (stationTemplate
.Evses
?.[0] == null) {
1535 `${this.logPrefix()} Charging station information from template ${
1537 } with no evse id 0 configuration`
1540 if (stationTemplate
.Evses
?.[0]?.Connectors
[0] == null) {
1542 `${this.logPrefix()} Charging station information from template ${
1544 } with evse id 0 with no connector id 0 configuration`
1547 if (Object.keys(stationTemplate
.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1549 `${this.logPrefix()} Charging station information from template ${
1551 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1554 if (stationTemplate
.Evses
!= null) {
1555 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1556 .update(JSON
.stringify(stationTemplate
.Evses
))
1558 const evsesConfigChanged
=
1559 this.evses
.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
1560 if (this.evses
.size
=== 0 || evsesConfigChanged
) {
1561 evsesConfigChanged
&& this.evses
.clear()
1562 this.evsesConfigurationHash
= evsesConfigHash
1563 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
.Evses
)
1564 if (templateMaxEvses
> 0) {
1565 for (const evseKey
in stationTemplate
.Evses
) {
1566 const evseId
= convertToInt(evseKey
)
1567 this.evses
.set(evseId
, {
1568 connectors
: buildConnectorsMap(
1569 stationTemplate
.Evses
[evseKey
].Connectors
,
1573 availability
: AvailabilityType
.Operative
1575 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1576 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix())
1578 this.saveEvsesStatus()
1581 `${this.logPrefix()} Charging station information from template ${
1583 } with no evses configuration defined, cannot create evses`
1589 `${this.logPrefix()} Charging station information from template ${
1591 } with no evses configuration defined, using already defined evses`
1596 private getConfigurationFromFile (): ChargingStationConfiguration
| undefined {
1597 let configuration
: ChargingStationConfiguration
| undefined
1598 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1600 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1601 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1602 this.configurationFileHash
1605 const measureId
= `${FileType.ChargingStationConfiguration} read`
1606 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1607 configuration
= JSON
.parse(
1608 readFileSync(this.configurationFile
, 'utf8')
1609 ) as ChargingStationConfiguration
1610 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1611 this.sharedLRUCache
.setChargingStationConfiguration(configuration
)
1612 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1613 this.configurationFileHash
= configuration
.configurationHash
!
1616 handleFileException(
1617 this.configurationFile
,
1618 FileType
.ChargingStationConfiguration
,
1619 error
as NodeJS
.ErrnoException
,
1624 return configuration
1627 private saveAutomaticTransactionGeneratorConfiguration (): void {
1628 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1629 this.saveConfiguration()
1633 private saveConnectorsStatus (): void {
1634 this.saveConfiguration()
1637 private saveEvsesStatus (): void {
1638 this.saveConfiguration()
1641 private saveConfiguration (): void {
1642 if (isNotEmptyString(this.configurationFile
)) {
1644 if (!existsSync(dirname(this.configurationFile
))) {
1645 mkdirSync(dirname(this.configurationFile
), { recursive
: true })
1647 const configurationFromFile
= this.getConfigurationFromFile()
1648 let configurationData
: ChargingStationConfiguration
=
1649 configurationFromFile
!= null
1650 ? cloneObject
<ChargingStationConfiguration
>(configurationFromFile
)
1652 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1653 configurationData
.stationInfo
= this.stationInfo
1655 delete configurationData
.stationInfo
1658 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1659 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1661 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
1663 delete configurationData
.configurationKey
1665 configurationData
= merge
<ChargingStationConfiguration
>(
1667 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1670 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== false ||
1671 this.getAutomaticTransactionGeneratorConfiguration() == null
1673 delete configurationData
.automaticTransactionGenerator
1675 if (this.connectors
.size
> 0) {
1676 configurationData
.connectorsStatus
= buildConnectorsStatus(this)
1678 delete configurationData
.connectorsStatus
1680 if (this.evses
.size
> 0) {
1681 configurationData
.evsesStatus
= buildEvsesStatus(this)
1683 delete configurationData
.evsesStatus
1685 delete configurationData
.configurationHash
1686 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1689 stationInfo
: configurationData
.stationInfo
,
1690 configurationKey
: configurationData
.configurationKey
,
1691 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1692 ...(this.connectors
.size
> 0 && {
1693 connectorsStatus
: configurationData
.connectorsStatus
1695 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
})
1696 } satisfies ChargingStationConfiguration
)
1699 if (this.configurationFileHash
!== configurationHash
) {
1700 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1701 configurationData
.configurationHash
= configurationHash
1702 const measureId
= `${FileType.ChargingStationConfiguration} write`
1703 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1705 this.configurationFile
,
1706 JSON
.stringify(configurationData
, undefined, 2),
1709 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1710 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
1711 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
)
1712 this.configurationFileHash
= configurationHash
1714 handleFileException(
1715 this.configurationFile
,
1716 FileType
.ChargingStationConfiguration
,
1717 error
as NodeJS
.ErrnoException
,
1723 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1724 this.configurationFile
1729 handleFileException(
1730 this.configurationFile
,
1731 FileType
.ChargingStationConfiguration
,
1732 error
as NodeJS
.ErrnoException
,
1738 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1743 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration
| undefined {
1744 return this.getTemplateFromFile()?.Configuration
1747 private getOcppConfigurationFromFile (): ChargingStationOcppConfiguration
| undefined {
1748 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
1749 if (this.stationInfo
?.ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1750 return { configurationKey
}
1755 private getOcppConfiguration (): ChargingStationOcppConfiguration
| undefined {
1756 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1757 this.getOcppConfigurationFromFile()
1758 if (ocppConfiguration
== null) {
1759 ocppConfiguration
= this.getOcppConfigurationFromTemplate()
1761 return ocppConfiguration
1764 private async onOpen (): Promise
<void> {
1765 if (this.isWebSocketConnectionOpened()) {
1767 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1769 let registrationRetryCount
= 0
1770 if (!this.isRegistered()) {
1771 // Send BootNotification
1773 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1774 BootNotificationRequest
,
1775 BootNotificationResponse
1776 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1777 skipBufferingOnError
: true
1779 if (!this.isRegistered()) {
1780 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
1782 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1783 this.bootNotificationResponse
?.interval
!= null
1784 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1785 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1789 !this.isRegistered() &&
1790 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1791 (registrationRetryCount
<= this.stationInfo
!.registrationMaxRetries
! ||
1792 this.stationInfo
?.registrationMaxRetries
=== -1)
1795 if (this.isRegistered()) {
1796 this.emit(ChargingStationEvents
.registered
)
1797 if (this.inAcceptedState()) {
1798 this.emit(ChargingStationEvents
.accepted
)
1802 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${
1803 this.stationInfo?.registrationMaxRetries
1807 this.autoReconnectRetryCount
= 0
1808 this.emit(ChargingStationEvents
.updated
)
1811 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1816 private async onClose (code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): Promise
<void> {
1819 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1820 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1822 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1824 )}' and reason '${reason.toString()}'`
1826 this.autoReconnectRetryCount
= 0
1831 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1833 )}' and reason '${reason.toString()}'`
1835 this.started
&& (await this.reconnect())
1838 this.emit(ChargingStationEvents
.updated
)
1841 private getCachedRequest (messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1842 const cachedRequest
= this.requests
.get(messageId
)
1843 if (Array.isArray(cachedRequest
)) {
1844 return cachedRequest
1846 throw new OCPPError(
1847 ErrorType
.PROTOCOL_ERROR
,
1848 `Cached request for message id ${messageId} ${getMessageTypeString(
1850 )} is not an array`,
1856 private async handleIncomingMessage (request
: IncomingRequest
): Promise
<void> {
1857 const [messageType
, messageId
, commandName
, commandPayload
] = request
1858 if (this.stationInfo
?.enableStatistics
=== true) {
1859 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
)
1862 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1866 // Process the message
1867 await this.ocppIncomingRequestService
.incomingRequestHandler(
1873 this.emit(ChargingStationEvents
.updated
)
1876 private handleResponseMessage (response
: Response
): void {
1877 const [messageType
, messageId
, commandPayload
] = response
1878 if (!this.requests
.has(messageId
)) {
1880 throw new OCPPError(
1881 ErrorType
.INTERNAL_ERROR
,
1882 `Response for unknown message id ${messageId}`,
1888 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1889 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1894 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1898 responseCallback(commandPayload
, requestPayload
)
1901 private handleErrorMessage (errorResponse
: ErrorResponse
): void {
1902 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
1903 if (!this.requests
.has(messageId
)) {
1905 throw new OCPPError(
1906 ErrorType
.INTERNAL_ERROR
,
1907 `Error response for unknown message id ${messageId}`,
1909 { errorType
, errorMessage
, errorDetails
}
1912 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1913 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1915 `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify(
1919 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
))
1922 private async onMessage (data
: RawData
): Promise
<void> {
1923 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined
1924 let messageType
: MessageType
| undefined
1925 let errorMsg
: string
1927 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1928 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
1929 if (Array.isArray(request
)) {
1930 [messageType
] = request
1931 // Check the type of message
1932 switch (messageType
) {
1934 case MessageType
.CALL_MESSAGE
:
1935 await this.handleIncomingMessage(request
as IncomingRequest
)
1938 case MessageType
.CALL_RESULT_MESSAGE
:
1939 this.handleResponseMessage(request
as Response
)
1942 case MessageType
.CALL_ERROR_MESSAGE
:
1943 this.handleErrorMessage(request
as ErrorResponse
)
1947 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1948 errorMsg
= `Wrong message type ${messageType}`
1949 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1950 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
)
1953 throw new OCPPError(
1954 ErrorType
.PROTOCOL_ERROR
,
1955 'Incoming message is not an array',
1963 let commandName
: IncomingRequestCommand
| undefined
1964 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined
1965 let errorCallback
: ErrorCallback
1966 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1967 const [, messageId
] = request
!
1968 switch (messageType
) {
1969 case MessageType
.CALL_MESSAGE
:
1970 [, , commandName
] = request
as IncomingRequest
1972 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
)
1974 case MessageType
.CALL_RESULT_MESSAGE
:
1975 case MessageType
.CALL_ERROR_MESSAGE
:
1976 if (this.requests
.has(messageId
)) {
1977 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1978 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1979 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1980 errorCallback(error
as OCPPError
, false)
1982 // Remove the request from the cache in case of error at response handling
1983 this.requests
.delete(messageId
)
1987 if (!(error
instanceof OCPPError
)) {
1989 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1990 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1991 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1992 }' message '${data.toString()}' handling is not an OCPPError:`,
1997 `${this.logPrefix()} Incoming OCPP command '${
1998 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1999 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2000 }' message '${data.toString()}'${
2001 messageType !== MessageType.CALL_MESSAGE
2002 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2004 } processing error:`,
2010 private onPing (): void {
2011 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
2014 private onPong (): void {
2015 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
2018 private onError (error
: WSError
): void {
2019 this.closeWSConnection()
2020 logger
.error(`${this.logPrefix()} WebSocket error:`, error
)
2023 private getEnergyActiveImportRegister (
2024 connectorStatus
: ConnectorStatus
| undefined,
2027 if (this.stationInfo
?.meteringPerTransaction
=== true) {
2030 ? connectorStatus
?.transactionEnergyActiveImportRegisterValue
!= null
2031 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
)
2033 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2038 ? connectorStatus
?.energyActiveImportRegisterValue
!= null
2039 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
)
2041 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2045 private getUseConnectorId0 (stationTemplate
?: ChargingStationTemplate
): boolean {
2046 return stationTemplate
?.useConnectorId0
?? true
2049 private async stopRunningTransactions (reason
?: StopTransactionReason
): Promise
<void> {
2050 if (this.hasEvses
) {
2051 for (const [evseId
, evseStatus
] of this.evses
) {
2055 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2056 if (connectorStatus
.transactionStarted
=== true) {
2057 await this.stopTransactionOnConnector(connectorId
, reason
)
2062 for (const connectorId
of this.connectors
.keys()) {
2063 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2064 await this.stopTransactionOnConnector(connectorId
, reason
)
2071 private getConnectionTimeout (): number {
2072 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) != null) {
2073 return convertToInt(
2074 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)?.value
??
2075 Constants
.DEFAULT_CONNECTION_TIMEOUT
2078 return Constants
.DEFAULT_CONNECTION_TIMEOUT
2081 private getPowerDivider (): number {
2082 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()
2083 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2084 powerDivider
= this.getNumberOfRunningTransactions()
2089 private getMaximumAmperage (stationInfo
?: ChargingStationInfo
): number | undefined {
2090 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2091 const maximumPower
= (stationInfo
?? this.stationInfo
!).maximumPower
!
2092 switch (this.getCurrentOutType(stationInfo
)) {
2093 case CurrentType
.AC
:
2094 return ACElectricUtils
.amperagePerPhaseFromPower(
2095 this.getNumberOfPhases(stationInfo
),
2096 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2097 this.getVoltageOut(stationInfo
)
2099 case CurrentType
.DC
:
2100 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
))
2104 private getCurrentOutType (stationInfo
?: ChargingStationInfo
): CurrentType
{
2105 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2106 return (stationInfo
?? this.stationInfo
!).currentOutType
?? CurrentType
.AC
2109 private getVoltageOut (stationInfo
?: ChargingStationInfo
): Voltage
{
2111 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2112 (stationInfo
?? this.stationInfo
!).voltageOut
??
2113 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2117 private getAmperageLimitation (): number | undefined {
2119 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2120 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2121 getConfigurationKey(this, this.stationInfo
!.amperageLimitationOcppKey
!) != null
2125 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2126 getConfigurationKey(this, this.stationInfo
!.amperageLimitationOcppKey
!)!.value
2127 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2128 ) / getAmperageLimitationUnitDivider(this.stationInfo
!)
2133 private async startMessageSequence (): Promise
<void> {
2134 if (this.stationInfo
?.autoRegister
=== true) {
2135 await this.ocppRequestService
.requestHandler
<
2136 BootNotificationRequest
,
2137 BootNotificationResponse
2138 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2139 skipBufferingOnError
: true
2142 // Start WebSocket ping
2143 this.startWebSocketPing()
2145 this.startHeartbeat()
2146 // Initialize connectors status
2147 if (this.hasEvses
) {
2148 for (const [evseId
, evseStatus
] of this.evses
) {
2150 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2151 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
)
2152 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
, evseId
)
2157 for (const connectorId
of this.connectors
.keys()) {
2158 if (connectorId
> 0) {
2159 const connectorBootStatus
= getBootConnectorStatus(
2162 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2163 this.getConnectorStatus(connectorId
)!
2165 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
)
2169 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2170 await this.ocppRequestService
.requestHandler
<
2171 FirmwareStatusNotificationRequest
,
2172 FirmwareStatusNotificationResponse
2173 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2174 status: FirmwareStatus
.Installed
2176 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
2180 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2181 this.startAutomaticTransactionGenerator()
2183 this.flushMessageBuffer()
2186 private async stopMessageSequence (
2187 reason
?: StopTransactionReason
,
2188 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
2190 // Stop WebSocket ping
2191 this.stopWebSocketPing()
2193 this.stopHeartbeat()
2195 if (this.automaticTransactionGenerator
?.started
=== true) {
2196 this.stopAutomaticTransactionGenerator()
2198 // Stop ongoing transactions
2199 stopTransactions
=== true && (await this.stopRunningTransactions(reason
))
2200 if (this.hasEvses
) {
2201 for (const [evseId
, evseStatus
] of this.evses
) {
2203 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2204 await this.ocppRequestService
.requestHandler
<
2205 StatusNotificationRequest
,
2206 StatusNotificationResponse
2209 RequestCommand
.STATUS_NOTIFICATION
,
2210 buildStatusNotificationRequest(
2213 ConnectorStatusEnum
.Unavailable
,
2217 delete connectorStatus
.status
2222 for (const connectorId
of this.connectors
.keys()) {
2223 if (connectorId
> 0) {
2224 await this.ocppRequestService
.requestHandler
<
2225 StatusNotificationRequest
,
2226 StatusNotificationResponse
2229 RequestCommand
.STATUS_NOTIFICATION
,
2230 buildStatusNotificationRequest(this, connectorId
, ConnectorStatusEnum
.Unavailable
)
2232 delete this.getConnectorStatus(connectorId
)?.status
2238 private startWebSocketPing (): void {
2239 const webSocketPingInterval
=
2240 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) != null
2242 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
2245 if (webSocketPingInterval
> 0 && this.webSocketPingSetInterval
== null) {
2246 this.webSocketPingSetInterval
= setInterval(() => {
2247 if (this.isWebSocketConnectionOpened()) {
2248 this.wsConnection
?.ping()
2250 }, secondsToMilliseconds(webSocketPingInterval
))
2252 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2253 webSocketPingInterval
2256 } else if (this.webSocketPingSetInterval
!= null) {
2258 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2259 webSocketPingInterval
2264 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2269 private stopWebSocketPing (): void {
2270 if (this.webSocketPingSetInterval
!= null) {
2271 clearInterval(this.webSocketPingSetInterval
)
2272 delete this.webSocketPingSetInterval
2276 private getConfiguredSupervisionUrl (): URL
{
2277 let configuredSupervisionUrl
: string
2278 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls()
2279 if (isNotEmptyArray(supervisionUrls
)) {
2280 let configuredSupervisionUrlIndex
: number
2281 switch (Configuration
.getSupervisionUrlDistribution()) {
2282 case SupervisionUrlDistribution
.RANDOM
:
2283 configuredSupervisionUrlIndex
= Math.floor(
2284 secureRandom() * (supervisionUrls
as string[]).length
2287 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2288 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2290 !Object.values(SupervisionUrlDistribution
).includes(
2291 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2292 Configuration
.getSupervisionUrlDistribution()!
2295 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2296 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2297 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2300 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
2303 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
]
2305 configuredSupervisionUrl
= supervisionUrls
as string
2307 if (isNotEmptyString(configuredSupervisionUrl
)) {
2308 return new URL(configuredSupervisionUrl
)
2310 const errorMsg
= 'No supervision url(s) configured'
2311 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2312 throw new BaseError(errorMsg
)
2315 private stopHeartbeat (): void {
2316 if (this.heartbeatSetInterval
!= null) {
2317 clearInterval(this.heartbeatSetInterval
)
2318 delete this.heartbeatSetInterval
2322 private terminateWSConnection (): void {
2323 if (this.isWebSocketConnectionOpened()) {
2324 this.wsConnection
?.terminate()
2325 this.wsConnection
= null
2329 private async reconnect (): Promise
<void> {
2330 // Stop WebSocket ping
2331 this.stopWebSocketPing()
2333 this.stopHeartbeat()
2334 // Stop the ATG if needed
2335 if (this.getAutomaticTransactionGeneratorConfiguration()?.stopOnConnectionFailure
=== true) {
2336 this.stopAutomaticTransactionGenerator()
2339 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2340 this.autoReconnectRetryCount
< this.stationInfo
!.autoReconnectMaxRetries
! ||
2341 this.stationInfo
?.autoReconnectMaxRetries
=== -1
2343 ++this.autoReconnectRetryCount
2344 const reconnectDelay
=
2345 this.stationInfo
?.reconnectExponentialDelay
=== true
2346 ? exponentialDelay(this.autoReconnectRetryCount
)
2347 : secondsToMilliseconds(this.getConnectionTimeout())
2348 const reconnectDelayWithdraw
= 1000
2349 const reconnectTimeout
=
2350 reconnectDelay
- reconnectDelayWithdraw
> 0 ? reconnectDelay
- reconnectDelayWithdraw
: 0
2352 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2355 )}ms, timeout ${reconnectTimeout}ms`
2357 await sleep(reconnectDelay
)
2359 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2361 this.openWSConnection(
2363 handshakeTimeout
: reconnectTimeout
2365 { closeOpened
: true }
2367 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2369 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2370 this.autoReconnectRetryCount
2371 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`