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
,
41 hasReservationExpired
,
42 initializeConnectorsMapStatus
,
43 propagateSerialNumber
,
44 stationTemplateToStationInfo
,
45 warnTemplateKeysDeprecation
47 import { IdTagsCache
} from
'./IdTagsCache.js'
49 OCPP16IncomingRequestService
,
51 OCPP16ResponseService
,
52 OCPP20IncomingRequestService
,
54 OCPP20ResponseService
,
55 type OCPPIncomingRequestService
,
56 type OCPPRequestService
,
58 buildStatusNotificationRequest
,
59 buildTransactionEndMeterValue
,
61 sendAndSetConnectorStatus
62 } from
'./ocpp/index.js'
63 import { SharedLRUCache
} from
'./SharedLRUCache.js'
64 import { BaseError
, OCPPError
} from
'../exception/index.js'
65 import { PerformanceStatistics
} from
'../performance/index.js'
67 type AutomaticTransactionGeneratorConfiguration
,
69 type BootNotificationRequest
,
70 type BootNotificationResponse
,
72 type ChargingStationConfiguration
,
73 ChargingStationEvents
,
74 type ChargingStationInfo
,
75 type ChargingStationOcppConfiguration
,
76 type ChargingStationTemplate
,
84 type EvseStatusConfiguration
,
87 type FirmwareStatusNotificationRequest
,
88 type FirmwareStatusNotificationResponse
,
90 type HeartbeatRequest
,
91 type HeartbeatResponse
,
93 type IncomingRequestCommand
,
96 type MeterValuesRequest
,
97 type MeterValuesResponse
,
101 RegistrationStatusEnumType
,
105 ReservationTerminationReason
,
107 StandardParametersKey
,
109 type StatusNotificationRequest
,
110 type StatusNotificationResponse
,
111 type StopTransactionReason
,
112 type StopTransactionRequest
,
113 type StopTransactionResponse
,
114 SupervisionUrlDistribution
,
115 SupportedFeatureProfiles
,
118 WebSocketCloseEventStatusCode
,
120 } from
'../types/index.js'
128 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
129 buildConnectorsStatus
,
138 formatDurationMilliSeconds
,
139 formatDurationSeconds
,
141 getWebSocketCloseEventStatusString
,
155 } from
'../utils/index.js'
157 export class ChargingStation
extends EventEmitter
{
158 public readonly index
: number
159 public readonly templateFile
: string
160 public stationInfo
!: ChargingStationInfo
161 public started
: boolean
162 public starting
: boolean
163 public idTagsCache
: IdTagsCache
164 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined
165 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined
166 public wsConnection
: WebSocket
| null
167 public readonly connectors
: Map
<number, ConnectorStatus
>
168 public readonly evses
: Map
<number, EvseStatus
>
169 public readonly requests
: Map
<string, CachedRequest
>
170 public performanceStatistics
!: PerformanceStatistics
| undefined
171 public heartbeatSetInterval
?: NodeJS
.Timeout
172 public ocppRequestService
!: OCPPRequestService
173 public bootNotificationRequest
!: BootNotificationRequest
174 public bootNotificationResponse
!: BootNotificationResponse
| undefined
175 public powerDivider
!: number
176 private stopping
: boolean
177 private configurationFile
!: string
178 private configurationFileHash
!: string
179 private connectorsConfigurationHash
!: string
180 private evsesConfigurationHash
!: string
181 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
182 private ocppIncomingRequestService
!: OCPPIncomingRequestService
183 private readonly messageBuffer
: Set
<string>
184 private configuredSupervisionUrl
!: URL
185 private autoReconnectRetryCount
: number
186 private templateFileWatcher
!: FSWatcher
| undefined
187 private templateFileHash
!: string
188 private readonly sharedLRUCache
: SharedLRUCache
189 private webSocketPingSetInterval
?: NodeJS
.Timeout
190 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
191 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
193 constructor (index
: number, templateFile
: string) {
196 this.starting
= false
197 this.stopping
= false
198 this.wsConnection
= null
199 this.autoReconnectRetryCount
= 0
201 this.templateFile
= templateFile
202 this.connectors
= new Map
<number, ConnectorStatus
>()
203 this.evses
= new Map
<number, EvseStatus
>()
204 this.requests
= new Map
<string, CachedRequest
>()
205 this.messageBuffer
= new Set
<string>()
206 this.sharedLRUCache
= SharedLRUCache
.getInstance()
207 this.idTagsCache
= IdTagsCache
.getInstance()
208 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this)
210 this.on(ChargingStationEvents
.started
, () => {
211 parentPort
?.postMessage(buildStartedMessage(this))
213 this.on(ChargingStationEvents
.stopped
, () => {
214 parentPort
?.postMessage(buildStoppedMessage(this))
216 this.on(ChargingStationEvents
.updated
, () => {
217 parentPort
?.postMessage(buildUpdatedMessage(this))
223 public get
hasEvses (): boolean {
224 return this.connectors
.size
=== 0 && this.evses
.size
> 0
227 private get
wsConnectionUrl (): URL
{
230 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
231 isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) &&
232 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
233 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)?.value)
234 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
235 getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)!.value
236 : this.configuredSupervisionUrl.href
237 }/${this.stationInfo.chargingStationId}`
241 public logPrefix
= (): string => {
242 if (isNotEmptyString(this?.stationInfo
?.chargingStationId
)) {
243 return logPrefix(` ${this?.stationInfo?.chargingStationId} |`)
245 let stationTemplate
: ChargingStationTemplate
| undefined
247 stationTemplate
= JSON
.parse(
248 readFileSync(this.templateFile
, 'utf8')
249 ) as ChargingStationTemplate
251 stationTemplate
= undefined
253 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`)
256 public hasIdTags (): boolean {
257 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
258 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)!))
261 public getNumberOfPhases (stationInfo
?: ChargingStationInfo
): number {
262 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
263 switch (this.getCurrentOutType(stationInfo
)) {
265 return localStationInfo
.numberOfPhases
?? 3
271 public isWebSocketConnectionOpened (): boolean {
272 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
275 public inUnknownState (): boolean {
276 return isNullOrUndefined(this?.bootNotificationResponse
?.status)
279 public inPendingState (): boolean {
280 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
283 public inAcceptedState (): boolean {
284 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
287 public inRejectedState (): boolean {
288 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
291 public isRegistered (): boolean {
292 return !this.inUnknownState() && (this.inAcceptedState() || this.inPendingState())
295 public isChargingStationAvailable (): boolean {
296 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
299 public hasConnector (connectorId
: number): boolean {
301 for (const evseStatus
of this.evses
.values()) {
302 if (evseStatus
.connectors
.has(connectorId
)) {
308 return this.connectors
.has(connectorId
)
311 public isConnectorAvailable (connectorId
: number): boolean {
314 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
318 public getNumberOfConnectors (): number {
320 let numberOfConnectors
= 0
321 for (const [evseId
, evseStatus
] of this.evses
) {
323 numberOfConnectors
+= evseStatus
.connectors
.size
326 return numberOfConnectors
328 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
331 public getNumberOfEvses (): number {
332 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
335 public getConnectorStatus (connectorId
: number): ConnectorStatus
| undefined {
337 for (const evseStatus
of this.evses
.values()) {
338 if (evseStatus
.connectors
.has(connectorId
)) {
339 return evseStatus
.connectors
.get(connectorId
)
344 return this.connectors
.get(connectorId
)
347 public getConnectorMaximumAvailablePower (connectorId
: number): number {
348 let connectorAmperageLimitationPowerLimit
: number | undefined
350 !isNullOrUndefined(this.getAmperageLimitation()) &&
351 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
352 this.getAmperageLimitation()! < this.stationInfo
.maximumAmperage
!
354 connectorAmperageLimitationPowerLimit
=
355 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
356 ? ACElectricUtils
.powerTotal(
357 this.getNumberOfPhases(),
358 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
359 this.stationInfo
.voltageOut
!,
360 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
361 this.getAmperageLimitation()! *
362 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
364 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
365 DCElectricUtils
.power(this.stationInfo
.voltageOut
!, this.getAmperageLimitation()!)) /
368 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
369 const connectorMaximumPower
= this.stationInfo
.maximumPower
! / this.powerDivider
370 const connectorChargingProfilesPowerLimit
=
371 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
)
373 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
374 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
375 isNaN(connectorAmperageLimitationPowerLimit
!)
377 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
378 connectorAmperageLimitationPowerLimit
!,
379 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
380 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!
384 public getTransactionIdTag (transactionId
: number): string | undefined {
386 for (const evseStatus
of this.evses
.values()) {
387 for (const connectorStatus
of evseStatus
.connectors
.values()) {
388 if (connectorStatus
.transactionId
=== transactionId
) {
389 return connectorStatus
.transactionIdTag
394 for (const connectorId
of this.connectors
.keys()) {
395 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
396 return this.getConnectorStatus(connectorId
)?.transactionIdTag
402 public getNumberOfRunningTransactions (): number {
403 let numberOfRunningTransactions
= 0
405 for (const [evseId
, evseStatus
] of this.evses
) {
409 for (const connectorStatus
of evseStatus
.connectors
.values()) {
410 if (connectorStatus
.transactionStarted
=== true) {
411 ++numberOfRunningTransactions
416 for (const connectorId
of this.connectors
.keys()) {
417 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
418 ++numberOfRunningTransactions
422 return numberOfRunningTransactions
425 public getConnectorIdByTransactionId (transactionId
: number): number | undefined {
427 for (const evseStatus
of this.evses
.values()) {
428 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
429 if (connectorStatus
.transactionId
=== transactionId
) {
435 for (const connectorId
of this.connectors
.keys()) {
436 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
443 public getEnergyActiveImportRegisterByTransactionId (
444 transactionId
: number,
447 return this.getEnergyActiveImportRegister(
448 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
449 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
454 public getEnergyActiveImportRegisterByConnectorId (connectorId
: number, rounded
= false): number {
455 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
456 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
)
459 public getAuthorizeRemoteTxRequests (): boolean {
460 const authorizeRemoteTxRequests
= getConfigurationKey(
462 StandardParametersKey
.AuthorizeRemoteTxRequests
464 return authorizeRemoteTxRequests
!== undefined
465 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
469 public getLocalAuthListEnabled (): boolean {
470 const localAuthListEnabled
= getConfigurationKey(
472 StandardParametersKey
.LocalAuthListEnabled
474 return localAuthListEnabled
!== undefined ? convertToBoolean(localAuthListEnabled
.value
) : false
477 public getHeartbeatInterval (): number {
478 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)
479 if (HeartbeatInterval
!== undefined) {
480 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
))
482 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)
483 if (HeartBeatInterval
!== undefined) {
484 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
))
486 this.stationInfo
?.autoRegister
=== false &&
488 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
489 Constants.DEFAULT_HEARTBEAT_INTERVAL
492 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
495 public setSupervisionUrl (url
: string): void {
497 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
498 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
)
500 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
501 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
!, url
)
503 this.stationInfo
.supervisionUrls
= url
504 this.saveStationInfo()
505 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
509 public startHeartbeat (): void {
510 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
=== undefined) {
511 this.heartbeatSetInterval
= setInterval(() => {
512 this.ocppRequestService
513 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
516 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
520 }, this.getHeartbeatInterval())
522 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
523 this.getHeartbeatInterval()
526 } else if (this.heartbeatSetInterval
!== undefined) {
528 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
529 this.getHeartbeatInterval()
534 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
539 public restartHeartbeat (): void {
543 this.startHeartbeat()
546 public restartWebSocketPing (): void {
547 // Stop WebSocket ping
548 this.stopWebSocketPing()
549 // Start WebSocket ping
550 this.startWebSocketPing()
553 public startMeterValues (connectorId
: number, interval
: number): void {
554 if (connectorId
=== 0) {
555 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`)
558 if (this.getConnectorStatus(connectorId
) == null) {
560 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
565 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
567 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
571 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
572 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
575 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
580 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
581 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
582 const meterValue
= buildMeterValue(
585 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
586 this.getConnectorStatus(connectorId
)!.transactionId
!,
589 this.ocppRequestService
590 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
592 RequestCommand
.METER_VALUES
,
595 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
596 meterValue
: [meterValue
]
601 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
608 `${this.logPrefix()} Charging station ${
609 StandardParametersKey.MeterValueSampleInterval
610 } configuration set to ${interval}, not sending MeterValues`
615 public stopMeterValues (connectorId
: number): void {
616 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
!== undefined) {
617 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
)
621 public start (): void {
623 if (!this.starting
) {
625 if (this.stationInfo
?.enableStatistics
=== true) {
626 this.performanceStatistics
?.start()
628 this.openWSConnection()
629 // Monitor charging station template file
630 this.templateFileWatcher
= watchJsonFile(
632 FileType
.ChargingStationTemplate
,
635 (event
, filename
): void => {
636 if (isNotEmptyString(filename
) && event
=== 'change') {
639 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
641 } file have changed, reload`
643 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
646 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
647 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
)!)
649 this.stopAutomaticTransactionGenerator()
650 delete this.automaticTransactionGeneratorConfiguration
651 if (this.getAutomaticTransactionGeneratorConfiguration().enable
) {
652 this.startAutomaticTransactionGenerator()
654 if (this.stationInfo
?.enableStatistics
=== true) {
655 this.performanceStatistics
?.restart()
657 this.performanceStatistics
?.stop()
659 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
662 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
670 this.emit(ChargingStationEvents
.started
)
671 this.starting
= false
673 logger
.warn(`${this.logPrefix()} Charging station is already starting...`)
676 logger
.warn(`${this.logPrefix()} Charging station is already started...`)
680 public async stop (reason
?: StopTransactionReason
, stopTransactions
?: boolean): Promise
<void> {
682 if (!this.stopping
) {
684 await this.stopMessageSequence(reason
, stopTransactions
)
685 this.closeWSConnection()
686 if (this.stationInfo
?.enableStatistics
=== true) {
687 this.performanceStatistics
?.stop()
689 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
690 this.templateFileWatcher
?.close()
691 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
692 delete this.bootNotificationResponse
694 this.saveConfiguration()
695 this.emit(ChargingStationEvents
.stopped
)
696 this.stopping
= false
698 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`)
701 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`)
705 public async reset (reason
?: StopTransactionReason
): Promise
<void> {
706 await this.stop(reason
)
707 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
708 await sleep(this.stationInfo
.resetTime
!)
713 public saveOcppConfiguration (): void {
714 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
715 this.saveConfiguration()
719 public bufferMessage (message
: string): void {
720 this.messageBuffer
.add(message
)
721 this.setIntervalFlushMessageBuffer()
724 public openWSConnection (
726 params
?: { closeOpened
?: boolean, terminateOpened
?: boolean }
729 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
730 ...this.stationInfo
?.wsOptions
,
733 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
}
734 if (!checkChargingStation(this, this.logPrefix())) {
738 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
739 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
741 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`
743 if (params
?.closeOpened
=== true) {
744 this.closeWSConnection()
746 if (params
?.terminateOpened
=== true) {
747 this.terminateWSConnection()
750 if (this.isWebSocketConnectionOpened()) {
752 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
758 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
761 this.wsConnection
= new WebSocket(
762 this.wsConnectionUrl
,
763 `ocpp${this.stationInfo?.ocppVersion}`,
767 // Handle WebSocket message
768 this.wsConnection
.on(
770 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
772 // Handle WebSocket error
773 this.wsConnection
.on(
775 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
777 // Handle WebSocket close
778 this.wsConnection
.on(
780 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
782 // Handle WebSocket open
783 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void)
784 // Handle WebSocket ping
785 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void)
786 // Handle WebSocket pong
787 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void)
790 public closeWSConnection (): void {
791 if (this.isWebSocketConnectionOpened()) {
792 this.wsConnection
?.close()
793 this.wsConnection
= null
797 public getAutomaticTransactionGeneratorConfiguration (): AutomaticTransactionGeneratorConfiguration
{
798 if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration
)) {
799 let automaticTransactionGeneratorConfiguration
:
800 | AutomaticTransactionGeneratorConfiguration
802 const stationTemplate
= this.getTemplateFromFile()
803 const stationConfiguration
= this.getConfigurationFromFile()
805 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
806 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
807 stationConfiguration
?.automaticTransactionGenerator
!= null
809 automaticTransactionGeneratorConfiguration
=
810 stationConfiguration
?.automaticTransactionGenerator
812 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
814 this.automaticTransactionGeneratorConfiguration
= {
815 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
816 ...automaticTransactionGeneratorConfiguration
819 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
820 return this.automaticTransactionGeneratorConfiguration
!
823 public getAutomaticTransactionGeneratorStatuses (): Status
[] | undefined {
824 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
827 public startAutomaticTransactionGenerator (connectorIds
?: number[]): void {
828 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this)
829 if (isNotEmptyArray(connectorIds
)) {
830 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
831 for (const connectorId
of connectorIds
!) {
832 this.automaticTransactionGenerator
?.startConnector(connectorId
)
835 this.automaticTransactionGenerator
?.start()
837 this.saveAutomaticTransactionGeneratorConfiguration()
838 this.emit(ChargingStationEvents
.updated
)
841 public stopAutomaticTransactionGenerator (connectorIds
?: number[]): void {
842 if (isNotEmptyArray(connectorIds
)) {
843 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
844 for (const connectorId
of connectorIds
!) {
845 this.automaticTransactionGenerator
?.stopConnector(connectorId
)
848 this.automaticTransactionGenerator
?.stop()
850 this.saveAutomaticTransactionGeneratorConfiguration()
851 this.emit(ChargingStationEvents
.updated
)
854 public async stopTransactionOnConnector (
856 reason
?: StopTransactionReason
857 ): Promise
<StopTransactionResponse
> {
858 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
860 this.stationInfo
?.beginEndMeterValues
=== true &&
861 this.stationInfo
?.ocppStrictCompliance
=== true &&
862 this.stationInfo
?.outOfOrderEndMeterValues
=== false
864 const transactionEndMeterValue
= buildTransactionEndMeterValue(
867 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
868 this.getEnergyActiveImportRegisterByTransactionId(transactionId
!)
870 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
872 RequestCommand
.METER_VALUES
,
876 meterValue
: [transactionEndMeterValue
]
880 return await this.ocppRequestService
.requestHandler
<
881 StopTransactionRequest
,
882 StopTransactionResponse
883 >(this, RequestCommand
.STOP_TRANSACTION
, {
885 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
886 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
!, true),
887 ...(isNullOrUndefined(reason
) && { reason
})
891 public getReserveConnectorZeroSupported (): boolean {
892 return convertToBoolean(
893 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
894 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
898 public async addReservation (reservation
: Reservation
): Promise
<void> {
899 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
)
900 if (reservationFound
!== undefined) {
901 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
)
903 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
904 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
905 await sendAndSetConnectorStatus(
907 reservation
.connectorId
,
908 ConnectorStatusEnum
.Reserved
,
910 { send
: reservation
.connectorId
!== 0 }
914 public async removeReservation (
915 reservation
: Reservation
,
916 reason
: ReservationTerminationReason
918 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
919 const connector
= this.getConnectorStatus(reservation
.connectorId
)!
921 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
922 case ReservationTerminationReason
.TRANSACTION_STARTED
:
923 delete connector
.reservation
925 case ReservationTerminationReason
.RESERVATION_CANCELED
:
926 case ReservationTerminationReason
.REPLACE_EXISTING
:
927 case ReservationTerminationReason
.EXPIRED
:
928 await sendAndSetConnectorStatus(
930 reservation
.connectorId
,
931 ConnectorStatusEnum
.Available
,
933 { send
: reservation
.connectorId
!== 0 }
935 delete connector
.reservation
938 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
939 throw new BaseError(`Unknown reservation termination reason '${reason}'`)
943 public getReservationBy (
944 filterKey
: ReservationKey
,
945 value
: number | string
946 ): Reservation
| undefined {
948 for (const evseStatus
of this.evses
.values()) {
949 for (const connectorStatus
of evseStatus
.connectors
.values()) {
950 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
951 return connectorStatus
.reservation
956 for (const connectorStatus
of this.connectors
.values()) {
957 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
958 return connectorStatus
.reservation
964 public isConnectorReservable (
965 reservationId
: number,
969 const reservation
= this.getReservationBy('reservationId', reservationId
)
970 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
971 const reservationExists
= !isUndefined(reservation
) && !hasReservationExpired(reservation
!)
972 if (arguments.length
=== 1) {
973 return !reservationExists
974 } else if (arguments.length
> 1) {
975 const userReservation
= !isUndefined(idTag
)
976 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
977 this.getReservationBy('idTag', idTag
!)
979 const userReservationExists
=
980 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
981 !isUndefined(userReservation
) && !hasReservationExpired(userReservation
!)
982 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
983 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
! > 0
984 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0
986 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
992 private setIntervalFlushMessageBuffer (): void {
993 if (this.flushMessageBufferSetInterval
=== undefined) {
994 this.flushMessageBufferSetInterval
= setInterval(() => {
995 if (this.isWebSocketConnectionOpened() && this.inAcceptedState()) {
996 this.flushMessageBuffer()
998 if (this.messageBuffer
.size
=== 0) {
999 this.clearIntervalFlushMessageBuffer()
1001 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
)
1005 private clearIntervalFlushMessageBuffer (): void {
1006 if (this.flushMessageBufferSetInterval
!== undefined) {
1007 clearInterval(this.flushMessageBufferSetInterval
)
1008 delete this.flushMessageBufferSetInterval
1012 private getNumberOfReservableConnectors (): number {
1013 let numberOfReservableConnectors
= 0
1014 if (this.hasEvses
) {
1015 for (const evseStatus
of this.evses
.values()) {
1016 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
)
1019 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
)
1021 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero()
1024 private getNumberOfReservationsOnConnectorZero (): number {
1026 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
!= null) ||
1027 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
!= null)
1034 private flushMessageBuffer (): void {
1035 if (this.messageBuffer
.size
> 0) {
1036 for (const message
of this.messageBuffer
.values()) {
1037 let beginId
: string | undefined
1038 let commandName
: RequestCommand
| undefined
1039 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
1040 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
1042 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
1043 beginId
= PerformanceStatistics
.beginMeasure(commandName
)
1045 this.wsConnection
?.send(message
, (error
?: Error) => {
1046 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1047 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!)
1048 if (isNullOrUndefined(error
)) {
1050 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1052 )} OCPP message sent '${JSON.stringify(message)}'`
1054 this.messageBuffer
.delete(message
)
1057 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1059 )} OCPP message '${JSON.stringify(message)}' send failed:`,
1068 private getTemplateFromFile (): ChargingStationTemplate
| undefined {
1069 let template
: ChargingStationTemplate
| undefined
1071 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1072 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
)
1074 const measureId
= `${FileType.ChargingStationTemplate} read`
1075 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1076 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
1077 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1078 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1079 .update(JSON
.stringify(template
))
1081 this.sharedLRUCache
.setChargingStationTemplate(template
)
1082 this.templateFileHash
= template
.templateHash
1085 handleFileException(
1087 FileType
.ChargingStationTemplate
,
1088 error
as NodeJS
.ErrnoException
,
1095 private getStationInfoFromTemplate (): ChargingStationInfo
{
1096 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1097 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile()!
1098 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1099 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this)
1100 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
)
1101 if (stationTemplate
?.Connectors
!= null) {
1102 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1104 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
)
1105 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
)
1106 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
)
1107 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
1108 createSerialNumber(stationTemplate
, stationInfo
)
1109 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
)
1110 if (isNotEmptyArray(stationTemplate
?.power
)) {
1111 stationTemplate
.power
= stationTemplate
.power
as number[]
1112 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
)
1113 stationInfo
.maximumPower
=
1114 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1115 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1116 : stationTemplate
.power
[powerArrayRandomIndex
]
1118 stationTemplate
.power
= stationTemplate
?.power
as number
1119 stationInfo
.maximumPower
=
1120 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1121 ? stationTemplate
.power
* 1000
1122 : stationTemplate
.power
1124 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
)
1125 stationInfo
.firmwareVersionPattern
=
1126 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
1128 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1129 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1130 !new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!)
1133 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1135 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1138 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1145 stationTemplate
?.firmwareUpgrade
?? {}
1147 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1148 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1149 secondsToMilliseconds(stationTemplate
.resetTime
!)
1150 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
1154 private getStationInfoFromFile (
1155 stationInfoPersistentConfiguration
= true
1156 ): ChargingStationInfo
| undefined {
1157 let stationInfo
: ChargingStationInfo
| undefined
1158 if (stationInfoPersistentConfiguration
) {
1159 stationInfo
= this.getConfigurationFromFile()?.stationInfo
1160 if (stationInfo
!= null) {
1161 delete stationInfo
?.infoHash
1167 private getStationInfo (): ChargingStationInfo
{
1168 const defaultStationInfo
= Constants
.DEFAULT_STATION_INFO
1169 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate()
1170 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile(
1171 stationInfoFromTemplate
?.stationInfoPersistentConfiguration
1174 // 1. charging station info from template
1175 // 2. charging station info from configuration file
1176 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1177 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1178 return { ...defaultStationInfo
, ...stationInfoFromFile
! }
1180 stationInfoFromFile
!= null &&
1181 propagateSerialNumber(
1182 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
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 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1214 (stationConfiguration
?.connectorsStatus
!= null || stationConfiguration
?.evsesStatus
!= null)
1216 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
)
1217 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
)
1219 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
)
1221 this.stationInfo
= this.getStationInfo()
1223 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1224 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1225 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1227 const patternGroup
: number | undefined =
1228 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1229 this.stationInfo
.firmwareVersion
?.split('.').length
1230 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1231 const match
= new RegExp(this.stationInfo
.firmwareVersionPattern
!)
1232 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1233 .exec(this.stationInfo
.firmwareVersion
!)
1234 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1235 ?.slice(1, patternGroup
! + 1)
1236 if (!isNullOrUndefined(match
)) {
1237 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1238 const patchLevelIndex
= match
!.length
- 1
1240 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1241 match
![patchLevelIndex
] = (convertToInt(match
![patchLevelIndex
]) +
1242 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1243 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!).toString()
1244 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1245 this.stationInfo
.firmwareVersion
= match
!.join('.')
1248 this.saveStationInfo()
1249 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
1250 if (this.stationInfo
?.enableStatistics
=== true) {
1251 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1252 this.stationInfo
.hashId
,
1253 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1254 this.stationInfo
.chargingStationId
!,
1255 this.configuredSupervisionUrl
1258 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
)
1259 this.powerDivider
= this.getPowerDivider()
1260 // OCPP configuration
1261 this.ocppConfiguration
= this.getOcppConfiguration()
1262 this.initializeOcppConfiguration()
1263 this.initializeOcppServices()
1264 this.once(ChargingStationEvents
.accepted
, () => {
1265 this.startMessageSequence().catch((error
) => {
1266 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
)
1269 if (this.stationInfo
?.autoRegister
=== true) {
1270 this.bootNotificationResponse
= {
1271 currentTime
: new Date(),
1272 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1273 status: RegistrationStatusEnumType
.ACCEPTED
1278 private initializeOcppServices (): void {
1279 const ocppVersion
= this.stationInfo
?.ocppVersion
1280 switch (ocppVersion
) {
1281 case OCPPVersion
.VERSION_16
:
1282 this.ocppIncomingRequestService
=
1283 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>()
1284 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1285 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1288 case OCPPVersion
.VERSION_20
:
1289 case OCPPVersion
.VERSION_201
:
1290 this.ocppIncomingRequestService
=
1291 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>()
1292 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1293 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1297 this.handleUnsupportedVersion(ocppVersion
)
1302 private initializeOcppConfiguration (): void {
1303 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
))) {
1304 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0')
1306 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
))) {
1307 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false })
1310 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1311 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
) &&
1312 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1313 isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!))
1315 addConfigurationKey(
1317 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1318 this.stationInfo
.supervisionUrlOcppKey
!,
1319 this.configuredSupervisionUrl
.href
,
1323 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1324 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
) &&
1325 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1326 !isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!))
1328 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1329 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!, { save
: false })
1332 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1333 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1334 isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!))
1336 addConfigurationKey(
1338 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1339 this.stationInfo
.amperageLimitationOcppKey
!,
1341 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1342 (this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)).toString()
1346 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
))
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(),
1362 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
))
1364 addConfigurationKey(
1366 StandardParametersKey
.MeterValuesSampledData
,
1367 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1371 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
))
1373 const connectorsPhaseRotation
: string[] = []
1374 if (this.hasEvses
) {
1375 for (const evseStatus
of this.evses
.values()) {
1376 for (const connectorId
of evseStatus
.connectors
.keys()) {
1377 connectorsPhaseRotation
.push(
1378 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1379 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1384 for (const connectorId
of this.connectors
.keys()) {
1385 connectorsPhaseRotation
.push(
1386 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1387 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1391 addConfigurationKey(
1393 StandardParametersKey
.ConnectorPhaseRotation
,
1394 connectorsPhaseRotation
.toString()
1398 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
))
1400 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true')
1403 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
)) &&
1404 getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)?.value
?.includes(
1405 SupportedFeatureProfiles
.LocalAuthListManagement
1408 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false')
1410 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
))) {
1411 addConfigurationKey(
1413 StandardParametersKey
.ConnectionTimeOut
,
1414 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1417 this.saveOcppConfiguration()
1420 private initializeConnectorsOrEvsesFromFile (configuration
: ChargingStationConfiguration
): void {
1421 if (configuration
?.connectorsStatus
!= null && configuration
?.evsesStatus
== null) {
1422 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1423 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
))
1425 } else if (configuration
?.evsesStatus
!= null && configuration
?.connectorsStatus
== null) {
1426 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1427 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
)
1428 delete evseStatus
.connectorsStatus
1429 this.evses
.set(evseId
, {
1430 ...(evseStatus
as EvseStatus
),
1431 connectors
: new Map
<number, ConnectorStatus
>(
1432 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1433 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1440 } else if (configuration
?.evsesStatus
!= null && configuration
?.connectorsStatus
!= null) {
1441 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1442 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1443 throw new BaseError(errorMsg
)
1445 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`
1446 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1447 throw new BaseError(errorMsg
)
1451 private initializeConnectorsOrEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1452 if (stationTemplate
?.Connectors
!= null && stationTemplate
?.Evses
== null) {
1453 this.initializeConnectorsFromTemplate(stationTemplate
)
1454 } else if (stationTemplate
?.Evses
!= null && stationTemplate
?.Connectors
== null) {
1455 this.initializeEvsesFromTemplate(stationTemplate
)
1456 } else if (stationTemplate
?.Evses
!= null && stationTemplate
?.Connectors
!= null) {
1457 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`
1458 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1459 throw new BaseError(errorMsg
)
1461 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`
1462 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1463 throw new BaseError(errorMsg
)
1467 private initializeConnectorsFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1468 if (stationTemplate
?.Connectors
== null && this.connectors
.size
=== 0) {
1469 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1470 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1471 throw new BaseError(errorMsg
)
1473 if (stationTemplate
?.Connectors
?.[0] == null) {
1475 `${this.logPrefix()} Charging station information from template ${
1477 } with no connector id 0 configuration`
1480 if (stationTemplate
?.Connectors
!= null) {
1481 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1482 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1483 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1485 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1488 const connectorsConfigChanged
=
1489 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
1490 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1491 connectorsConfigChanged
&& this.connectors
.clear()
1492 this.connectorsConfigurationHash
= connectorsConfigHash
1493 if (templateMaxConnectors
> 0) {
1494 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1496 connectorId
=== 0 &&
1497 (stationTemplate
?.Connectors
?.[connectorId
] == null ||
1498 !this.getUseConnectorId0(stationTemplate
))
1502 const templateConnectorId
=
1503 connectorId
> 0 && stationTemplate
?.randomConnectors
=== true
1504 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1506 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
]
1507 checkStationInfoConnectorStatus(
1508 templateConnectorId
,
1513 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
))
1515 initializeConnectorsMapStatus(this.connectors
, this.logPrefix())
1516 this.saveConnectorsStatus()
1519 `${this.logPrefix()} Charging station information from template ${
1521 } with no connectors configuration defined, cannot create connectors`
1527 `${this.logPrefix()} Charging station information from template ${
1529 } with no connectors configuration defined, using already defined connectors`
1534 private initializeEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1535 if (stationTemplate
?.Evses
== null && this.evses
.size
=== 0) {
1536 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1537 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1538 throw new BaseError(errorMsg
)
1540 if (stationTemplate
?.Evses
?.[0] == null) {
1542 `${this.logPrefix()} Charging station information from template ${
1544 } with no evse id 0 configuration`
1547 if (stationTemplate
?.Evses
?.[0]?.Connectors
?.[0] == null) {
1549 `${this.logPrefix()} Charging station information from template ${
1551 } with evse id 0 with no connector id 0 configuration`
1554 if (Object.keys(stationTemplate
?.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1556 `${this.logPrefix()} Charging station information from template ${
1558 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1561 if (stationTemplate
?.Evses
!= null) {
1562 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1563 .update(JSON
.stringify(stationTemplate
?.Evses
))
1565 const evsesConfigChanged
=
1566 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
1567 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1568 evsesConfigChanged
&& this.evses
.clear()
1569 this.evsesConfigurationHash
= evsesConfigHash
1570 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
)
1571 if (templateMaxEvses
> 0) {
1572 for (const evseKey
in stationTemplate
.Evses
) {
1573 const evseId
= convertToInt(evseKey
)
1574 this.evses
.set(evseId
, {
1575 connectors
: buildConnectorsMap(
1576 stationTemplate
?.Evses
[evseKey
]?.Connectors
,
1580 availability
: AvailabilityType
.Operative
1582 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1583 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix())
1585 this.saveEvsesStatus()
1588 `${this.logPrefix()} Charging station information from template ${
1590 } with no evses configuration defined, cannot create evses`
1596 `${this.logPrefix()} Charging station information from template ${
1598 } with no evses configuration defined, using already defined evses`
1603 private getConfigurationFromFile (): ChargingStationConfiguration
| undefined {
1604 let configuration
: ChargingStationConfiguration
| undefined
1605 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1607 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1608 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1609 this.configurationFileHash
1612 const measureId
= `${FileType.ChargingStationConfiguration} read`
1613 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1614 configuration
= JSON
.parse(
1615 readFileSync(this.configurationFile
, 'utf8')
1616 ) as ChargingStationConfiguration
1617 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1618 this.sharedLRUCache
.setChargingStationConfiguration(configuration
)
1619 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1620 this.configurationFileHash
= configuration
.configurationHash
!
1623 handleFileException(
1624 this.configurationFile
,
1625 FileType
.ChargingStationConfiguration
,
1626 error
as NodeJS
.ErrnoException
,
1631 return configuration
1634 private saveAutomaticTransactionGeneratorConfiguration (): void {
1635 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1636 this.saveConfiguration()
1640 private saveConnectorsStatus (): void {
1641 this.saveConfiguration()
1644 private saveEvsesStatus (): void {
1645 this.saveConfiguration()
1648 private saveConfiguration (): void {
1649 if (isNotEmptyString(this.configurationFile
)) {
1651 if (!existsSync(dirname(this.configurationFile
))) {
1652 mkdirSync(dirname(this.configurationFile
), { recursive
: true })
1654 let configurationData
: ChargingStationConfiguration
=
1655 this.getConfigurationFromFile() != null
1656 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1657 cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()!)
1660 this.stationInfo
?.stationInfoPersistentConfiguration
=== true &&
1661 this.stationInfo
!= null
1663 configurationData
.stationInfo
= this.stationInfo
1665 delete configurationData
.stationInfo
1668 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1669 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1671 configurationData
.configurationKey
= this.ocppConfiguration
?.configurationKey
1673 delete configurationData
.configurationKey
1675 configurationData
= merge
<ChargingStationConfiguration
>(
1677 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1680 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== false ||
1681 this.getAutomaticTransactionGeneratorConfiguration() == null
1683 delete configurationData
.automaticTransactionGenerator
1685 if (this.connectors
.size
> 0) {
1686 configurationData
.connectorsStatus
= buildConnectorsStatus(this)
1688 delete configurationData
.connectorsStatus
1690 if (this.evses
.size
> 0) {
1691 configurationData
.evsesStatus
= buildEvsesStatus(this)
1693 delete configurationData
.evsesStatus
1695 delete configurationData
.configurationHash
1696 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1699 stationInfo
: configurationData
.stationInfo
,
1700 configurationKey
: configurationData
.configurationKey
,
1701 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1702 ...(this.connectors
.size
> 0 && {
1703 connectorsStatus
: configurationData
.connectorsStatus
1705 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
})
1706 } satisfies ChargingStationConfiguration
)
1709 if (this.configurationFileHash
!== configurationHash
) {
1710 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1711 configurationData
.configurationHash
= configurationHash
1712 const measureId
= `${FileType.ChargingStationConfiguration} write`
1713 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1715 this.configurationFile
,
1716 JSON
.stringify(configurationData
, undefined, 2),
1719 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1720 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
1721 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
)
1722 this.configurationFileHash
= configurationHash
1723 }).catch((error
) => {
1724 handleFileException(
1725 this.configurationFile
,
1726 FileType
.ChargingStationConfiguration
,
1727 error
as NodeJS
.ErrnoException
,
1733 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1734 this.configurationFile
1739 handleFileException(
1740 this.configurationFile
,
1741 FileType
.ChargingStationConfiguration
,
1742 error
as NodeJS
.ErrnoException
,
1748 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1753 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration
| undefined {
1754 return this.getTemplateFromFile()?.Configuration
1757 private getOcppConfigurationFromFile (): ChargingStationOcppConfiguration
| undefined {
1758 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
1759 if (this.stationInfo
?.ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1760 return { configurationKey
}
1765 private getOcppConfiguration (): ChargingStationOcppConfiguration
| undefined {
1766 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1767 this.getOcppConfigurationFromFile()
1768 if (ocppConfiguration
== null) {
1769 ocppConfiguration
= this.getOcppConfigurationFromTemplate()
1771 return ocppConfiguration
1774 private async onOpen (): Promise
<void> {
1775 if (this.isWebSocketConnectionOpened()) {
1777 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1779 let registrationRetryCount
= 0
1780 if (!this.isRegistered()) {
1781 // Send BootNotification
1783 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1784 BootNotificationRequest
,
1785 BootNotificationResponse
1786 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1787 skipBufferingOnError
: true
1789 if (!this.isRegistered()) {
1790 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
1792 this?.bootNotificationResponse
?.interval
!= null
1793 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1794 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1798 !this.isRegistered() &&
1799 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1800 (registrationRetryCount
<= this.stationInfo
.registrationMaxRetries
! ||
1801 this.stationInfo
?.registrationMaxRetries
=== -1)
1804 if (this.isRegistered()) {
1805 this.emit(ChargingStationEvents
.registered
)
1806 if (this.inAcceptedState()) {
1807 this.emit(ChargingStationEvents
.accepted
)
1811 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${this
1812 .stationInfo?.registrationMaxRetries})`
1815 this.autoReconnectRetryCount
= 0
1816 this.emit(ChargingStationEvents
.updated
)
1819 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1824 private async onClose (code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): Promise
<void> {
1827 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1828 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1830 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1832 )}' and reason '${reason.toString()}'`
1834 this.autoReconnectRetryCount
= 0
1839 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1841 )}' and reason '${reason.toString()}'`
1843 this.started
&& (await this.reconnect())
1846 this.emit(ChargingStationEvents
.updated
)
1849 private getCachedRequest (messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1850 const cachedRequest
= this.requests
.get(messageId
)
1851 if (Array.isArray(cachedRequest
)) {
1852 return cachedRequest
1854 throw new OCPPError(
1855 ErrorType
.PROTOCOL_ERROR
,
1856 `Cached request for message id ${messageId} ${getMessageTypeString(
1858 )} is not an array`,
1864 private async handleIncomingMessage (request
: IncomingRequest
): Promise
<void> {
1865 const [messageType
, messageId
, commandName
, commandPayload
] = request
1866 if (this.stationInfo
?.enableStatistics
=== true) {
1867 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
)
1870 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1874 // Process the message
1875 await this.ocppIncomingRequestService
.incomingRequestHandler(
1881 this.emit(ChargingStationEvents
.updated
)
1884 private handleResponseMessage (response
: Response
): void {
1885 const [messageType
, messageId
, commandPayload
] = response
1886 if (!this.requests
.has(messageId
)) {
1888 throw new OCPPError(
1889 ErrorType
.INTERNAL_ERROR
,
1890 `Response for unknown message id ${messageId}`,
1896 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1897 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1902 `${this.logPrefix()} << Command '${
1903 requestCommandName ?? Constants.UNKNOWN_COMMAND
1904 }' received response payload: ${JSON.stringify(response)}`
1906 responseCallback(commandPayload
, requestPayload
)
1909 private handleErrorMessage (errorResponse
: ErrorResponse
): void {
1910 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
1911 if (!this.requests
.has(messageId
)) {
1913 throw new OCPPError(
1914 ErrorType
.INTERNAL_ERROR
,
1915 `Error response for unknown message id ${messageId}`,
1917 { errorType
, errorMessage
, errorDetails
}
1920 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1921 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1923 `${this.logPrefix()} << Command '${
1924 requestCommandName ?? Constants.UNKNOWN_COMMAND
1925 }' received error response payload: ${JSON.stringify(errorResponse)}`
1927 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
))
1930 private async onMessage (data
: RawData
): Promise
<void> {
1931 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined
1932 let messageType
: MessageType
| undefined
1933 let errorMsg
: string
1935 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1936 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
1937 if (Array.isArray(request
)) {
1938 [messageType
] = request
1939 // Check the type of message
1940 switch (messageType
) {
1942 case MessageType
.CALL_MESSAGE
:
1943 await this.handleIncomingMessage(request
as IncomingRequest
)
1946 case MessageType
.CALL_RESULT_MESSAGE
:
1947 this.handleResponseMessage(request
as Response
)
1950 case MessageType
.CALL_ERROR_MESSAGE
:
1951 this.handleErrorMessage(request
as ErrorResponse
)
1955 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1956 errorMsg
= `Wrong message type ${messageType}`
1957 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1958 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
)
1961 throw new OCPPError(
1962 ErrorType
.PROTOCOL_ERROR
,
1963 'Incoming message is not an array',
1971 let commandName
: IncomingRequestCommand
| undefined
1972 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined
1973 let errorCallback
: ErrorCallback
1974 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1975 const [, messageId
] = request
!
1976 switch (messageType
) {
1977 case MessageType
.CALL_MESSAGE
:
1978 [, , commandName
] = request
as IncomingRequest
1980 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
)
1982 case MessageType
.CALL_RESULT_MESSAGE
:
1983 case MessageType
.CALL_ERROR_MESSAGE
:
1984 if (this.requests
.has(messageId
)) {
1985 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1986 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1987 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1988 errorCallback(error
as OCPPError
, false)
1990 // Remove the request from the cache in case of error at response handling
1991 this.requests
.delete(messageId
)
1995 if (!(error
instanceof OCPPError
)) {
1997 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1998 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1999 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2000 }' message '${data.toString()}' handling is not an OCPPError:`,
2005 `${this.logPrefix()} Incoming OCPP command '${
2006 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2007 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2008 }' message '${data.toString()}'${
2009 messageType !== MessageType.CALL_MESSAGE
2010 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2012 } processing error:`,
2018 private onPing (): void {
2019 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
2022 private onPong (): void {
2023 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
2026 private onError (error
: WSError
): void {
2027 this.closeWSConnection()
2028 logger
.error(`${this.logPrefix()} WebSocket error:`, error
)
2031 private getEnergyActiveImportRegister (connectorStatus
: ConnectorStatus
, rounded
= false): number {
2032 if (this.stationInfo
?.meteringPerTransaction
=== true) {
2035 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2036 Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
2037 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2042 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2043 Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2044 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2048 private getUseConnectorId0 (stationTemplate
?: ChargingStationTemplate
): boolean {
2049 return stationTemplate
?.useConnectorId0
?? true
2052 private async stopRunningTransactions (reason
?: StopTransactionReason
): Promise
<void> {
2053 if (this.hasEvses
) {
2054 for (const [evseId
, evseStatus
] of this.evses
) {
2058 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2059 if (connectorStatus
.transactionStarted
=== true) {
2060 await this.stopTransactionOnConnector(connectorId
, reason
)
2065 for (const connectorId
of this.connectors
.keys()) {
2066 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2067 await this.stopTransactionOnConnector(connectorId
, reason
)
2074 private getConnectionTimeout (): number {
2075 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) !== undefined) {
2076 return convertToInt(
2077 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2078 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)!.value
! ??
2079 Constants
.DEFAULT_CONNECTION_TIMEOUT
2082 return Constants
.DEFAULT_CONNECTION_TIMEOUT
2085 private getPowerDivider (): number {
2086 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()
2087 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2088 powerDivider
= this.getNumberOfRunningTransactions()
2093 private getMaximumAmperage (stationInfo
?: ChargingStationInfo
): number | undefined {
2094 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2095 const maximumPower
= (stationInfo
?? this.stationInfo
).maximumPower
!
2096 switch (this.getCurrentOutType(stationInfo
)) {
2097 case CurrentType
.AC
:
2098 return ACElectricUtils
.amperagePerPhaseFromPower(
2099 this.getNumberOfPhases(stationInfo
),
2100 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2101 this.getVoltageOut(stationInfo
)
2103 case CurrentType
.DC
:
2104 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
))
2108 private getCurrentOutType (stationInfo
?: ChargingStationInfo
): CurrentType
{
2109 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
2112 private getVoltageOut (stationInfo
?: ChargingStationInfo
): Voltage
{
2114 (stationInfo
?? this.stationInfo
).voltageOut
??
2115 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2119 private getAmperageLimitation (): number | undefined {
2121 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2122 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2123 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!) !== undefined
2127 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2128 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)?.value
2129 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2134 private async startMessageSequence (): Promise
<void> {
2135 if (this.stationInfo
?.autoRegister
=== true) {
2136 await this.ocppRequestService
.requestHandler
<
2137 BootNotificationRequest
,
2138 BootNotificationResponse
2139 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2140 skipBufferingOnError
: true
2143 // Start WebSocket ping
2144 this.startWebSocketPing()
2146 this.startHeartbeat()
2147 // Initialize connectors status
2148 if (this.hasEvses
) {
2149 for (const [evseId
, evseStatus
] of this.evses
) {
2151 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2152 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
)
2153 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
, evseId
)
2158 for (const connectorId
of this.connectors
.keys()) {
2159 if (connectorId
> 0) {
2160 const connectorBootStatus
= getBootConnectorStatus(
2163 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2164 this.getConnectorStatus(connectorId
)!
2166 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
)
2170 if (this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
) {
2171 await this.ocppRequestService
.requestHandler
<
2172 FirmwareStatusNotificationRequest
,
2173 FirmwareStatusNotificationResponse
2174 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2175 status: FirmwareStatus
.Installed
2177 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
2181 if (this.getAutomaticTransactionGeneratorConfiguration().enable
) {
2182 this.startAutomaticTransactionGenerator()
2184 this.flushMessageBuffer()
2187 private async stopMessageSequence (
2188 reason
?: StopTransactionReason
,
2189 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
2191 // Stop WebSocket ping
2192 this.stopWebSocketPing()
2194 this.stopHeartbeat()
2196 if (this.automaticTransactionGenerator
?.started
=== true) {
2197 this.stopAutomaticTransactionGenerator()
2199 // Stop ongoing transactions
2200 stopTransactions
=== true && (await this.stopRunningTransactions(reason
))
2201 if (this.hasEvses
) {
2202 for (const [evseId
, evseStatus
] of this.evses
) {
2204 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2205 await this.ocppRequestService
.requestHandler
<
2206 StatusNotificationRequest
,
2207 StatusNotificationResponse
2210 RequestCommand
.STATUS_NOTIFICATION
,
2211 buildStatusNotificationRequest(
2214 ConnectorStatusEnum
.Unavailable
,
2218 delete connectorStatus
?.status
2223 for (const connectorId
of this.connectors
.keys()) {
2224 if (connectorId
> 0) {
2225 await this.ocppRequestService
.requestHandler
<
2226 StatusNotificationRequest
,
2227 StatusNotificationResponse
2230 RequestCommand
.STATUS_NOTIFICATION
,
2231 buildStatusNotificationRequest(this, connectorId
, ConnectorStatusEnum
.Unavailable
)
2233 delete this.getConnectorStatus(connectorId
)?.status
2239 private startWebSocketPing (): void {
2240 const webSocketPingInterval
: number =
2241 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) !== undefined
2243 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
2246 if (webSocketPingInterval
> 0 && this.webSocketPingSetInterval
=== undefined) {
2247 this.webSocketPingSetInterval
= setInterval(() => {
2248 if (this.isWebSocketConnectionOpened()) {
2249 this.wsConnection
?.ping()
2251 }, secondsToMilliseconds(webSocketPingInterval
))
2253 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2254 webSocketPingInterval
2257 } else if (this.webSocketPingSetInterval
!== undefined) {
2259 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2260 webSocketPingInterval
2265 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2270 private stopWebSocketPing (): void {
2271 if (this.webSocketPingSetInterval
!== undefined) {
2272 clearInterval(this.webSocketPingSetInterval
)
2273 delete this.webSocketPingSetInterval
2277 private getConfiguredSupervisionUrl (): URL
{
2278 let configuredSupervisionUrl
: string
2279 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls()
2280 if (isNotEmptyArray(supervisionUrls
)) {
2281 let configuredSupervisionUrlIndex
: number
2282 switch (Configuration
.getSupervisionUrlDistribution()) {
2283 case SupervisionUrlDistribution
.RANDOM
:
2284 configuredSupervisionUrlIndex
= Math.floor(
2285 secureRandom() * (supervisionUrls
as string[]).length
2288 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2289 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2291 !Object.values(SupervisionUrlDistribution
).includes(
2292 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2293 Configuration
.getSupervisionUrlDistribution()!
2296 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2297 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2298 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2301 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
2304 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
]
2306 configuredSupervisionUrl
= supervisionUrls
as string
2308 if (isNotEmptyString(configuredSupervisionUrl
)) {
2309 return new URL(configuredSupervisionUrl
)
2311 const errorMsg
= 'No supervision url(s) configured'
2312 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2313 throw new BaseError(`${errorMsg}`)
2316 private stopHeartbeat (): void {
2317 if (this.heartbeatSetInterval
!== undefined) {
2318 clearInterval(this.heartbeatSetInterval
)
2319 delete this.heartbeatSetInterval
2323 private terminateWSConnection (): void {
2324 if (this.isWebSocketConnectionOpened()) {
2325 this.wsConnection
?.terminate()
2326 this.wsConnection
= null
2330 private async reconnect (): Promise
<void> {
2331 // Stop WebSocket ping
2332 this.stopWebSocketPing()
2334 this.stopHeartbeat()
2335 // Stop the ATG if needed
2336 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
) {
2337 this.stopAutomaticTransactionGenerator()
2340 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2341 this.autoReconnectRetryCount
< this.stationInfo
.autoReconnectMaxRetries
! ||
2342 this.stationInfo
?.autoReconnectMaxRetries
=== -1
2344 ++this.autoReconnectRetryCount
2345 const reconnectDelay
=
2346 this.stationInfo
?.reconnectExponentialDelay
=== true
2347 ? exponentialDelay(this.autoReconnectRetryCount
)
2348 : secondsToMilliseconds(this.getConnectionTimeout())
2349 const reconnectDelayWithdraw
= 1000
2350 const reconnectTimeout
=
2351 reconnectDelay
!= null && reconnectDelay
- reconnectDelayWithdraw
> 0
2352 ? reconnectDelay
- reconnectDelayWithdraw
2355 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2358 )}ms, timeout ${reconnectTimeout}ms`
2360 await sleep(reconnectDelay
)
2362 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2364 this.openWSConnection(
2366 handshakeTimeout
: reconnectTimeout
2368 { closeOpened
: true }
2370 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2372 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2373 this.autoReconnectRetryCount
2374 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`