1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { millisecondsToSeconds
, secondsToMilliseconds
} from
'date-fns'
4 import { hash
, randomInt
} from
'node:crypto'
5 import { EventEmitter
} from
'node:events'
6 import { existsSync
, type FSWatcher
, mkdirSync
, readFileSync
, rmSync
, writeFileSync
} from
'node:fs'
7 import { dirname
, join
} from
'node:path'
8 import { URL
} from
'node:url'
9 import { parentPort
} from
'node:worker_threads'
10 import { type RawData
, WebSocket
} from
'ws'
12 import { BaseError
, OCPPError
} from
'../exception/index.js'
13 import { PerformanceStatistics
} from
'../performance/index.js'
15 type AutomaticTransactionGeneratorConfiguration
,
17 type BootNotificationRequest
,
18 type BootNotificationResponse
,
20 type ChargingStationConfiguration
,
21 ChargingStationEvents
,
22 type ChargingStationInfo
,
23 type ChargingStationOcppConfiguration
,
24 type ChargingStationOptions
,
25 type ChargingStationTemplate
,
33 type EvseStatusConfiguration
,
36 type FirmwareStatusNotificationRequest
,
37 type FirmwareStatusNotificationResponse
,
38 type HeartbeatRequest
,
39 type HeartbeatResponse
,
41 type IncomingRequestCommand
,
44 type MeterValuesRequest
,
45 type MeterValuesResponse
,
49 RegistrationStatusEnumType
,
53 ReservationTerminationReason
,
55 StandardParametersKey
,
57 type StopTransactionReason
,
58 type StopTransactionRequest
,
59 type StopTransactionResponse
,
60 SupervisionUrlDistribution
,
61 SupportedFeatureProfiles
,
63 WebSocketCloseEventStatusCode
,
66 } from
'../types/index.js'
72 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
73 buildConnectorsStatus
,
87 formatDurationMilliSeconds
,
88 formatDurationSeconds
,
89 getWebSocketCloseEventStatusString
,
102 } from
'../utils/index.js'
103 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator.js'
104 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel.js'
107 deleteConfigurationKey
,
109 setConfigurationKeyValue
,
110 } from
'./ConfigurationKeyUtils.js'
114 checkChargingStationState
,
116 checkConnectorsConfiguration
,
117 checkStationInfoConnectorStatus
,
119 createBootNotificationRequest
,
121 getAmperageLimitationUnitDivider
,
122 getBootConnectorStatus
,
123 getChargingStationChargingProfilesLimit
,
124 getChargingStationId
,
125 getConnectorChargingProfilesLimit
,
126 getDefaultVoltageOut
,
130 getNumberOfReservableConnectors
,
131 getPhaseRotationValue
,
133 hasReservationExpired
,
134 initializeConnectorsMapStatus
,
135 prepareConnectorStatus
,
136 propagateSerialNumber
,
137 setChargingStationOptions
,
138 stationTemplateToStationInfo
,
140 warnTemplateKeysDeprecation
,
141 } from
'./Helpers.js'
142 import { IdTagsCache
} from
'./IdTagsCache.js'
145 buildTransactionEndMeterValue
,
146 getMessageTypeString
,
147 OCPP16IncomingRequestService
,
148 OCPP16RequestService
,
149 OCPP16ResponseService
,
150 OCPP20IncomingRequestService
,
151 OCPP20RequestService
,
152 OCPP20ResponseService
,
153 type OCPPIncomingRequestService
,
154 type OCPPRequestService
,
155 sendAndSetConnectorStatus
,
156 } from
'./ocpp/index.js'
157 import { SharedLRUCache
} from
'./SharedLRUCache.js'
159 export class ChargingStation
extends EventEmitter
{
160 public automaticTransactionGenerator
?: AutomaticTransactionGenerator
161 public bootNotificationRequest
?: BootNotificationRequest
162 public bootNotificationResponse
?: BootNotificationResponse
163 public readonly connectors
: Map
<number, ConnectorStatus
>
164 public readonly evses
: Map
<number, EvseStatus
>
165 public heartbeatSetInterval
?: NodeJS
.Timeout
166 public idTagsCache
: IdTagsCache
167 public readonly index
: number
168 public ocppConfiguration
?: ChargingStationOcppConfiguration
169 public ocppRequestService
!: OCPPRequestService
170 public performanceStatistics
?: PerformanceStatistics
171 public powerDivider
?: number
172 public readonly requests
: Map
<string, CachedRequest
>
173 public started
: boolean
174 public starting
: boolean
175 public stationInfo
?: ChargingStationInfo
176 public readonly templateFile
: string
177 public wsConnection
: null | WebSocket
179 public get
hasEvses (): boolean {
180 return this.connectors
.size
=== 0 && this.evses
.size
> 0
183 public get
wsConnectionUrl (): URL
{
184 const wsConnectionBaseUrlStr
= `${
185 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
186 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
187 isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
188 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value)
189 ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value
190 : this.configuredSupervisionUrl.href
193 `${wsConnectionBaseUrlStr}${
194 !wsConnectionBaseUrlStr.endsWith('/') ? '/' : ''
195 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
196 }${this.stationInfo?.chargingStationId}`
200 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
201 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
202 private configurationFile
!: string
203 private configurationFileHash
!: string
204 private configuredSupervisionUrl
!: URL
205 private connectorsConfigurationHash
!: string
206 private evsesConfigurationHash
!: string
207 private flushingMessageBuffer
: boolean
208 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
209 private readonly messageQueue
: string[]
210 private ocppIncomingRequestService
!: OCPPIncomingRequestService
211 private readonly sharedLRUCache
: SharedLRUCache
212 private stopping
: boolean
213 private templateFileHash
!: string
214 private templateFileWatcher
?: FSWatcher
215 private wsConnectionRetryCount
: number
216 private wsPingSetInterval
?: NodeJS
.Timeout
218 constructor (index
: number, templateFile
: string, options
?: ChargingStationOptions
) {
221 this.starting
= false
222 this.stopping
= false
223 this.wsConnection
= null
224 this.wsConnectionRetryCount
= 0
226 this.templateFile
= templateFile
227 this.connectors
= new Map
<number, ConnectorStatus
>()
228 this.evses
= new Map
<number, EvseStatus
>()
229 this.requests
= new Map
<string, CachedRequest
>()
230 this.flushingMessageBuffer
= false
231 this.messageQueue
= new Array<string>()
232 this.sharedLRUCache
= SharedLRUCache
.getInstance()
233 this.idTagsCache
= IdTagsCache
.getInstance()
234 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this)
236 this.on(ChargingStationEvents
.added
, () => {
237 parentPort
?.postMessage(buildAddedMessage(this))
239 this.on(ChargingStationEvents
.deleted
, () => {
240 parentPort
?.postMessage(buildDeletedMessage(this))
242 this.on(ChargingStationEvents
.started
, () => {
243 parentPort
?.postMessage(buildStartedMessage(this))
245 this.on(ChargingStationEvents
.stopped
, () => {
246 parentPort
?.postMessage(buildStoppedMessage(this))
248 this.on(ChargingStationEvents
.updated
, () => {
249 parentPort
?.postMessage(buildUpdatedMessage(this))
251 this.on(ChargingStationEvents
.accepted
, () => {
252 this.startMessageSequence(
253 this.wsConnectionRetryCount
> 0
255 : this.getAutomaticTransactionGeneratorConfiguration()?.stopAbsoluteDuration
256 ).catch((error
: unknown
) => {
257 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
)
259 this.wsConnectionRetryCount
= 0
261 this.on(ChargingStationEvents
.rejected
, () => {
262 this.wsConnectionRetryCount
= 0
264 this.on(ChargingStationEvents
.connected
, () => {
265 if (this.wsPingSetInterval
== null) {
266 this.startWebSocketPing()
269 this.on(ChargingStationEvents
.disconnected
, () => {
271 this.internalStopMessageSequence()
274 `${this.logPrefix()} Error while stopping the internal message sequence:`,
280 this.initialize(options
)
284 if (this.stationInfo
?.autoStart
=== true) {
289 public async addReservation (reservation
: Reservation
): Promise
<void> {
290 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
)
291 if (reservationFound
!= null) {
292 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
)
294 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
295 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
296 await sendAndSetConnectorStatus(
298 reservation
.connectorId
,
299 ConnectorStatusEnum
.Reserved
,
301 { send
: reservation
.connectorId
!== 0 }
305 public bufferMessage (message
: string): void {
306 this.messageQueue
.push(message
)
307 this.setIntervalFlushMessageBuffer()
310 public closeWSConnection (): void {
311 if (this.isWebSocketConnectionOpened()) {
312 this.wsConnection
?.close()
313 this.wsConnection
= null
317 public async delete (deleteConfiguration
= true): Promise
<void> {
321 AutomaticTransactionGenerator
.deleteInstance(this)
322 PerformanceStatistics
.deleteInstance(this.stationInfo
?.hashId
)
323 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
324 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
!)!)
325 this.requests
.clear()
326 this.connectors
.clear()
328 this.templateFileWatcher
?.unref()
329 deleteConfiguration
&& rmSync(this.configurationFile
, { force
: true })
330 this.chargingStationWorkerBroadcastChannel
.unref()
331 this.emit(ChargingStationEvents
.deleted
)
332 this.removeAllListeners()
335 public getAuthorizeRemoteTxRequests (): boolean {
336 const authorizeRemoteTxRequests
= getConfigurationKey(
338 StandardParametersKey
.AuthorizeRemoteTxRequests
340 return authorizeRemoteTxRequests
!= null
341 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
345 public getAutomaticTransactionGeneratorConfiguration ():
346 | AutomaticTransactionGeneratorConfiguration
348 if (this.automaticTransactionGeneratorConfiguration
== null) {
349 let automaticTransactionGeneratorConfiguration
:
350 | AutomaticTransactionGeneratorConfiguration
352 const stationTemplate
= this.getTemplateFromFile()
353 const stationConfiguration
= this.getConfigurationFromFile()
355 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
356 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
357 stationConfiguration
?.automaticTransactionGenerator
!= null
359 automaticTransactionGeneratorConfiguration
=
360 stationConfiguration
.automaticTransactionGenerator
362 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
364 this.automaticTransactionGeneratorConfiguration
= {
365 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
366 ...automaticTransactionGeneratorConfiguration
,
369 return this.automaticTransactionGeneratorConfiguration
372 public getAutomaticTransactionGeneratorStatuses (): Status
[] | undefined {
373 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
376 public getConnectorIdByTransactionId (transactionId
: number | undefined): number | undefined {
377 if (transactionId
== null) {
379 } else if (this.hasEvses
) {
380 for (const evseStatus
of this.evses
.values()) {
381 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
382 if (connectorStatus
.transactionId
=== transactionId
) {
388 for (const connectorId
of this.connectors
.keys()) {
389 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
396 public getConnectorMaximumAvailablePower (connectorId
: number): number {
397 let connectorAmperageLimitationLimit
: number | undefined
398 const amperageLimitation
= this.getAmperageLimitation()
400 amperageLimitation
!= null &&
401 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
402 amperageLimitation
< this.stationInfo
!.maximumAmperage
!
404 connectorAmperageLimitationLimit
=
405 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
406 ? ACElectricUtils
.powerTotal(
407 this.getNumberOfPhases(),
408 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
409 this.stationInfo
.voltageOut
!,
411 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
413 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
414 DCElectricUtils
.power(this.stationInfo
!.voltageOut
!, amperageLimitation
)) /
415 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
418 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
419 const connectorMaximumPower
= this.stationInfo
!.maximumPower
! / this.powerDivider
!
420 const chargingStationChargingProfilesLimit
=
421 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
422 getChargingStationChargingProfilesLimit(this)! / this.powerDivider
!
423 const connectorChargingProfilesLimit
= getConnectorChargingProfilesLimit(this, connectorId
)
425 Number.isNaN(connectorMaximumPower
) ? Number.POSITIVE_INFINITY
: connectorMaximumPower
,
426 connectorAmperageLimitationLimit
== null || Number.isNaN(connectorAmperageLimitationLimit
)
427 ? Number.POSITIVE_INFINITY
428 : connectorAmperageLimitationLimit
,
429 Number.isNaN(chargingStationChargingProfilesLimit
)
430 ? Number.POSITIVE_INFINITY
431 : chargingStationChargingProfilesLimit
,
432 connectorChargingProfilesLimit
== null || Number.isNaN(connectorChargingProfilesLimit
)
433 ? Number.POSITIVE_INFINITY
434 : connectorChargingProfilesLimit
438 public getConnectorStatus (connectorId
: number): ConnectorStatus
| undefined {
440 for (const evseStatus
of this.evses
.values()) {
441 if (evseStatus
.connectors
.has(connectorId
)) {
442 return evseStatus
.connectors
.get(connectorId
)
447 return this.connectors
.get(connectorId
)
450 public getEnergyActiveImportRegisterByConnectorId (connectorId
: number, rounded
= false): number {
451 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
)
454 public getEnergyActiveImportRegisterByTransactionId (
455 transactionId
: number | undefined,
458 return this.getEnergyActiveImportRegister(
459 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
460 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!),
465 public getHeartbeatInterval (): number {
466 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)
467 if (HeartbeatInterval
!= null) {
468 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
))
470 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)
471 if (HeartBeatInterval
!= null) {
472 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
))
474 this.stationInfo
?.autoRegister
=== false &&
476 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL.toString()}`
478 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
481 public getLocalAuthListEnabled (): boolean {
482 const localAuthListEnabled
= getConfigurationKey(
484 StandardParametersKey
.LocalAuthListEnabled
486 return localAuthListEnabled
!= null ? convertToBoolean(localAuthListEnabled
.value
) : false
489 public getNumberOfConnectors (): number {
491 let numberOfConnectors
= 0
492 for (const [evseId
, evseStatus
] of this.evses
) {
494 numberOfConnectors
+= evseStatus
.connectors
.size
497 return numberOfConnectors
499 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
502 public getNumberOfEvses (): number {
503 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
506 public getNumberOfPhases (stationInfo
?: ChargingStationInfo
): number {
507 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
508 const localStationInfo
= stationInfo
?? this.stationInfo
!
509 switch (this.getCurrentOutType(stationInfo
)) {
511 return localStationInfo
.numberOfPhases
?? 3
517 public getNumberOfRunningTransactions (): number {
518 let numberOfRunningTransactions
= 0
520 for (const [evseId
, evseStatus
] of this.evses
) {
524 for (const connectorStatus
of evseStatus
.connectors
.values()) {
525 if (connectorStatus
.transactionStarted
=== true) {
526 ++numberOfRunningTransactions
531 for (const connectorId
of this.connectors
.keys()) {
532 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
533 ++numberOfRunningTransactions
537 return numberOfRunningTransactions
540 public getReservationBy (
541 filterKey
: ReservationKey
,
542 value
: number | string
543 ): Reservation
| undefined {
545 for (const evseStatus
of this.evses
.values()) {
546 for (const connectorStatus
of evseStatus
.connectors
.values()) {
547 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
548 return connectorStatus
.reservation
553 for (const connectorStatus
of this.connectors
.values()) {
554 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
555 return connectorStatus
.reservation
561 public getReserveConnectorZeroSupported (): boolean {
562 return convertToBoolean(
563 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
564 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
568 public getTransactionIdTag (transactionId
: number): string | undefined {
570 for (const evseStatus
of this.evses
.values()) {
571 for (const connectorStatus
of evseStatus
.connectors
.values()) {
572 if (connectorStatus
.transactionId
=== transactionId
) {
573 return connectorStatus
.transactionIdTag
578 for (const connectorId
of this.connectors
.keys()) {
579 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
580 return this.getConnectorStatus(connectorId
)?.transactionIdTag
586 public hasConnector (connectorId
: number): boolean {
588 for (const evseStatus
of this.evses
.values()) {
589 if (evseStatus
.connectors
.has(connectorId
)) {
595 return this.connectors
.has(connectorId
)
598 public hasIdTags (): boolean {
599 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
600 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
!)!))
603 public inAcceptedState (): boolean {
604 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
607 public inPendingState (): boolean {
608 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
611 public inRejectedState (): boolean {
612 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
615 public inUnknownState (): boolean {
616 return this.bootNotificationResponse
?.status == null
619 public isChargingStationAvailable (): boolean {
620 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
623 public isConnectorAvailable (connectorId
: number): boolean {
626 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
630 public isConnectorReservable (
631 reservationId
: number,
635 const reservation
= this.getReservationBy('reservationId', reservationId
)
636 const reservationExists
= reservation
!= null && !hasReservationExpired(reservation
)
637 if (arguments.length
=== 1) {
638 return !reservationExists
639 } else if (arguments.length
> 1) {
640 const userReservation
= idTag
!= null ? this.getReservationBy('idTag', idTag
) : undefined
641 const userReservationExists
=
642 userReservation
!= null && !hasReservationExpired(userReservation
)
643 const notConnectorZero
= connectorId
== null ? true : connectorId
> 0
644 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0
646 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
652 public isWebSocketConnectionOpened (): boolean {
653 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
656 public logPrefix
= (): string => {
658 this instanceof ChargingStation
&&
659 this.stationInfo
!= null &&
660 isNotEmptyString(this.stationInfo
.chargingStationId
)
662 return logPrefix(` ${this.stationInfo.chargingStationId} |`)
664 let stationTemplate
: ChargingStationTemplate
| undefined
666 stationTemplate
= JSON
.parse(
667 readFileSync(this.templateFile
, 'utf8')
668 ) as ChargingStationTemplate
672 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`)
675 public openWSConnection (
677 params
?: { closeOpened
?: boolean; terminateOpened
?: boolean }
680 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
681 ...this.stationInfo
?.wsOptions
,
684 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
}
685 if (!checkChargingStationState(this, this.logPrefix())) {
688 if (this.stationInfo
?.supervisionUser
!= null && this.stationInfo
.supervisionPassword
!= null) {
689 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`
691 if (params
.closeOpened
) {
692 this.closeWSConnection()
694 if (params
.terminateOpened
) {
695 this.terminateWSConnection()
698 if (this.isWebSocketConnectionOpened()) {
700 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.href} is already opened`
705 logger
.info(`${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.href}`)
707 this.wsConnection
= new WebSocket(
708 this.wsConnectionUrl
,
709 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
710 `ocpp${this.stationInfo?.ocppVersion}`,
714 // Handle WebSocket message
715 this.wsConnection
.on('message', data
=> {
716 this.onMessage(data
).catch(Constants
.EMPTY_FUNCTION
)
718 // Handle WebSocket error
719 this.wsConnection
.on('error', this.onError
.bind(this))
720 // Handle WebSocket close
721 this.wsConnection
.on('close', this.onClose
.bind(this))
722 // Handle WebSocket open
723 this.wsConnection
.on('open', () => {
724 this.onOpen().catch((error
: unknown
) =>
725 logger
.error(`${this.logPrefix()} Error while opening WebSocket connection:`, error
)
728 // Handle WebSocket ping
729 this.wsConnection
.on('ping', this.onPing
.bind(this))
730 // Handle WebSocket pong
731 this.wsConnection
.on('pong', this.onPong
.bind(this))
734 public async removeReservation (
735 reservation
: Reservation
,
736 reason
: ReservationTerminationReason
738 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
739 const connector
= this.getConnectorStatus(reservation
.connectorId
)!
741 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
742 case ReservationTerminationReason
.TRANSACTION_STARTED
:
743 delete connector
.reservation
745 case ReservationTerminationReason
.EXPIRED
:
746 case ReservationTerminationReason
.REPLACE_EXISTING
:
747 case ReservationTerminationReason
.RESERVATION_CANCELED
:
748 await sendAndSetConnectorStatus(
750 reservation
.connectorId
,
751 ConnectorStatusEnum
.Available
,
753 { send
: reservation
.connectorId
!== 0 }
755 delete connector
.reservation
758 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
759 throw new BaseError(`Unknown reservation termination reason '${reason}'`)
763 public async reset (reason
?: StopTransactionReason
): Promise
<void> {
764 await this.stop(reason
)
765 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
766 await sleep(this.stationInfo
!.resetTime
!)
771 public restartHeartbeat (): void {
775 this.startHeartbeat()
778 public restartMeterValues (connectorId
: number, interval
: number): void {
779 this.stopMeterValues(connectorId
)
780 this.startMeterValues(connectorId
, interval
)
783 public restartWebSocketPing (): void {
784 // Stop WebSocket ping
785 this.stopWebSocketPing()
786 // Start WebSocket ping
787 this.startWebSocketPing()
790 public saveOcppConfiguration (): void {
791 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
792 this.saveConfiguration()
796 public setSupervisionUrl (url
: string): void {
798 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
799 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
)
801 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
, url
)
803 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
804 this.stationInfo
!.supervisionUrls
= url
805 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
806 this.saveStationInfo()
810 public start (): void {
812 if (!this.starting
) {
814 if (this.stationInfo
?.enableStatistics
=== true) {
815 this.performanceStatistics
?.start()
817 this.openWSConnection()
818 // Monitor charging station template file
819 this.templateFileWatcher
= watchJsonFile(
821 FileType
.ChargingStationTemplate
,
824 (event
, filename
): void => {
825 if (isNotEmptyString(filename
) && event
=== 'change') {
828 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
830 } file have changed, reload`
832 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
833 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
834 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
!)!)
838 const ATGStarted
= this.automaticTransactionGenerator
?.started
839 if (ATGStarted
=== true) {
840 this.stopAutomaticTransactionGenerator()
842 delete this.automaticTransactionGeneratorConfiguration
844 this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true &&
847 this.startAutomaticTransactionGenerator(undefined, true)
849 if (this.stationInfo
?.enableStatistics
=== true) {
850 this.performanceStatistics
?.restart()
852 this.performanceStatistics
?.stop()
854 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
857 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
865 this.emit(ChargingStationEvents
.started
)
866 this.starting
= false
868 logger
.warn(`${this.logPrefix()} Charging station is already starting...`)
871 logger
.warn(`${this.logPrefix()} Charging station is already started...`)
875 public startAutomaticTransactionGenerator (
876 connectorIds
?: number[],
877 stopAbsoluteDuration
?: boolean
879 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this)
880 if (isNotEmptyArray(connectorIds
)) {
881 for (const connectorId
of connectorIds
) {
882 this.automaticTransactionGenerator
?.startConnector(connectorId
, stopAbsoluteDuration
)
885 this.automaticTransactionGenerator
?.start(stopAbsoluteDuration
)
887 this.saveAutomaticTransactionGeneratorConfiguration()
888 this.emit(ChargingStationEvents
.updated
)
891 public startHeartbeat (): void {
892 const heartbeatInterval
= this.getHeartbeatInterval()
893 if (heartbeatInterval
> 0 && this.heartbeatSetInterval
== null) {
894 this.heartbeatSetInterval
= setInterval(() => {
895 this.ocppRequestService
896 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
897 .catch((error
: unknown
) => {
899 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
903 }, heartbeatInterval
)
905 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
909 } else if (this.heartbeatSetInterval
!= null) {
911 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
917 `${this.logPrefix()} Heartbeat interval set to ${heartbeatInterval.toString()}, not starting the heartbeat`
922 public startMeterValues (connectorId
: number, interval
: number): void {
923 if (connectorId
=== 0) {
925 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
929 const connectorStatus
= this.getConnectorStatus(connectorId
)
930 if (connectorStatus
== null) {
932 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
933 ${connectorId.toString()}`
937 if (connectorStatus
.transactionStarted
=== false) {
939 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()} with no transaction started`
943 connectorStatus
.transactionStarted
=== true &&
944 connectorStatus
.transactionId
== null
947 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()} with no transaction id`
952 connectorStatus
.transactionSetInterval
= setInterval(() => {
953 const meterValue
= buildMeterValue(
956 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
957 connectorStatus
.transactionId
!,
960 this.ocppRequestService
961 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
963 RequestCommand
.METER_VALUES
,
966 meterValue
: [meterValue
],
967 transactionId
: connectorStatus
.transactionId
,
970 .catch((error
: unknown
) => {
972 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
979 `${this.logPrefix()} Charging station ${
980 StandardParametersKey.MeterValueSampleInterval
981 } configuration set to ${interval.toString()}, not sending MeterValues`
987 reason
?: StopTransactionReason
,
988 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
991 if (!this.stopping
) {
993 await this.stopMessageSequence(reason
, stopTransactions
)
994 this.closeWSConnection()
995 if (this.stationInfo
?.enableStatistics
=== true) {
996 this.performanceStatistics
?.stop()
998 this.templateFileWatcher
?.close()
999 delete this.bootNotificationResponse
1000 this.started
= false
1001 this.saveConfiguration()
1002 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
1003 this.emit(ChargingStationEvents
.stopped
)
1004 this.stopping
= false
1006 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`)
1009 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`)
1013 public stopAutomaticTransactionGenerator (connectorIds
?: number[]): void {
1014 if (isNotEmptyArray(connectorIds
)) {
1015 for (const connectorId
of connectorIds
) {
1016 this.automaticTransactionGenerator
?.stopConnector(connectorId
)
1019 this.automaticTransactionGenerator
?.stop()
1021 this.saveAutomaticTransactionGeneratorConfiguration()
1022 this.emit(ChargingStationEvents
.updated
)
1025 public stopMeterValues (connectorId
: number): void {
1026 const connectorStatus
= this.getConnectorStatus(connectorId
)
1027 if (connectorStatus
?.transactionSetInterval
!= null) {
1028 clearInterval(connectorStatus
.transactionSetInterval
)
1032 public async stopTransactionOnConnector (
1033 connectorId
: number,
1034 reason
?: StopTransactionReason
1035 ): Promise
<StopTransactionResponse
> {
1036 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
1038 this.stationInfo
?.beginEndMeterValues
=== true &&
1039 this.stationInfo
.ocppStrictCompliance
=== true &&
1040 this.stationInfo
.outOfOrderEndMeterValues
=== false
1042 const transactionEndMeterValue
= buildTransactionEndMeterValue(
1045 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1047 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1049 RequestCommand
.METER_VALUES
,
1052 meterValue
: [transactionEndMeterValue
],
1057 return await this.ocppRequestService
.requestHandler
<
1058 Partial
<StopTransactionRequest
>,
1059 StopTransactionResponse
1060 >(this, RequestCommand
.STOP_TRANSACTION
, {
1061 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
1063 ...(reason
!= null && { reason
}),
1067 private add (): void {
1068 this.emit(ChargingStationEvents
.added
)
1071 private clearIntervalFlushMessageBuffer (): void {
1072 if (this.flushMessageBufferSetInterval
!= null) {
1073 clearInterval(this.flushMessageBufferSetInterval
)
1074 delete this.flushMessageBufferSetInterval
1078 private flushMessageBuffer (): void {
1079 if (!this.flushingMessageBuffer
&& this.messageQueue
.length
> 0) {
1080 this.flushingMessageBuffer
= true
1081 this.sendMessageBuffer(() => {
1082 this.flushingMessageBuffer
= false
1087 private getAmperageLimitation (): number | undefined {
1089 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1090 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) != null
1093 convertToInt(getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
)?.value
) /
1094 getAmperageLimitationUnitDivider(this.stationInfo
)
1099 private getCachedRequest (
1100 messageType
: MessageType
| undefined,
1102 ): CachedRequest
| undefined {
1103 const cachedRequest
= this.requests
.get(messageId
)
1104 if (Array.isArray(cachedRequest
)) {
1105 return cachedRequest
1107 throw new OCPPError(
1108 ErrorType
.PROTOCOL_ERROR
,
1109 `Cached request for message id '${messageId}' ${getMessageTypeString(
1111 )} is not an array`,
1117 private getConfigurationFromFile (): ChargingStationConfiguration
| undefined {
1118 let configuration
: ChargingStationConfiguration
| undefined
1119 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1121 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1122 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1123 this.configurationFileHash
1126 const measureId
= `${FileType.ChargingStationConfiguration} read`
1127 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1128 configuration
= JSON
.parse(
1129 readFileSync(this.configurationFile
, 'utf8')
1130 ) as ChargingStationConfiguration
1131 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1132 this.sharedLRUCache
.setChargingStationConfiguration(configuration
)
1133 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1134 this.configurationFileHash
= configuration
.configurationHash
!
1137 handleFileException(
1138 this.configurationFile
,
1139 FileType
.ChargingStationConfiguration
,
1140 error
as NodeJS
.ErrnoException
,
1145 return configuration
1148 private getConfiguredSupervisionUrl (): URL
{
1149 let configuredSupervisionUrl
: string | undefined
1150 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls()
1151 if (isNotEmptyArray(supervisionUrls
)) {
1152 let configuredSupervisionUrlIndex
: number
1153 switch (Configuration
.getSupervisionUrlDistribution()) {
1154 case SupervisionUrlDistribution
.RANDOM
:
1155 configuredSupervisionUrlIndex
= Math.floor(secureRandom() * supervisionUrls
.length
)
1157 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1158 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1160 !Object.values(SupervisionUrlDistribution
).includes(
1161 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1162 Configuration
.getSupervisionUrlDistribution()!
1165 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string
1166 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' in configuration from values '${SupervisionUrlDistribution.toString()}', defaulting to '${
1167 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1170 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
1173 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
]
1174 } else if (typeof supervisionUrls
=== 'string') {
1175 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1176 configuredSupervisionUrl
= supervisionUrls
!
1178 if (isNotEmptyString(configuredSupervisionUrl
)) {
1179 return new URL(configuredSupervisionUrl
)
1181 const errorMsg
= 'No supervision url(s) configured'
1182 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1183 throw new BaseError(errorMsg
)
1187 private getConnectionTimeout (): number {
1188 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) != null) {
1189 return convertToInt(
1190 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)?.value
??
1191 Constants
.DEFAULT_CONNECTION_TIMEOUT
1194 return Constants
.DEFAULT_CONNECTION_TIMEOUT
1197 private getCurrentOutType (stationInfo
?: ChargingStationInfo
): CurrentType
{
1199 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1200 (stationInfo
?? this.stationInfo
!).currentOutType
??
1201 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1202 Constants
.DEFAULT_STATION_INFO
.currentOutType
!
1206 private getEnergyActiveImportRegister (
1207 connectorStatus
: ConnectorStatus
| undefined,
1210 if (this.stationInfo
?.meteringPerTransaction
=== true) {
1213 ? connectorStatus
?.transactionEnergyActiveImportRegisterValue
!= null
1214 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
)
1216 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1221 ? connectorStatus
?.energyActiveImportRegisterValue
!= null
1222 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
)
1224 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1228 private getMaximumAmperage (stationInfo
?: ChargingStationInfo
): number | undefined {
1229 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1230 const maximumPower
= (stationInfo
?? this.stationInfo
!).maximumPower
!
1231 switch (this.getCurrentOutType(stationInfo
)) {
1232 case CurrentType
.AC
:
1233 return ACElectricUtils
.amperagePerPhaseFromPower(
1234 this.getNumberOfPhases(stationInfo
),
1235 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
1236 this.getVoltageOut(stationInfo
)
1238 case CurrentType
.DC
:
1239 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
))
1243 private getNumberOfReservableConnectors (): number {
1244 let numberOfReservableConnectors
= 0
1245 if (this.hasEvses
) {
1246 for (const evseStatus
of this.evses
.values()) {
1247 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
)
1250 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
)
1252 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero()
1255 private getNumberOfReservationsOnConnectorZero (): number {
1257 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
!= null) ||
1258 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
!= null)
1265 private getOcppConfiguration (
1266 ocppPersistentConfiguration
: boolean | undefined = this.stationInfo
?.ocppPersistentConfiguration
1267 ): ChargingStationOcppConfiguration
| undefined {
1268 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1269 this.getOcppConfigurationFromFile(ocppPersistentConfiguration
)
1270 ocppConfiguration
??= this.getOcppConfigurationFromTemplate()
1271 return ocppConfiguration
1274 private getOcppConfigurationFromFile (
1275 ocppPersistentConfiguration
?: boolean
1276 ): ChargingStationOcppConfiguration
| undefined {
1277 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
1278 if (ocppPersistentConfiguration
&& Array.isArray(configurationKey
)) {
1279 return { configurationKey
}
1284 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration
| undefined {
1285 return this.getTemplateFromFile()?.Configuration
1288 private getPowerDivider (): number {
1289 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()
1290 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
1291 powerDivider
= this.getNumberOfRunningTransactions()
1296 private getStationInfo (options
?: ChargingStationOptions
): ChargingStationInfo
{
1297 const stationInfoFromTemplate
= this.getStationInfoFromTemplate()
1298 options
?.persistentConfiguration
!= null &&
1299 (stationInfoFromTemplate
.stationInfoPersistentConfiguration
= options
.persistentConfiguration
)
1300 const stationInfoFromFile
= this.getStationInfoFromFile(
1301 stationInfoFromTemplate
.stationInfoPersistentConfiguration
1303 let stationInfo
: ChargingStationInfo
1305 // 1. charging station info from template
1306 // 2. charging station info from configuration file
1308 stationInfoFromFile
!= null &&
1309 stationInfoFromFile
.templateHash
=== stationInfoFromTemplate
.templateHash
1311 stationInfo
= stationInfoFromFile
1313 stationInfo
= stationInfoFromTemplate
1314 stationInfoFromFile
!= null &&
1315 propagateSerialNumber(this.getTemplateFromFile(), stationInfoFromFile
, stationInfo
)
1317 return setChargingStationOptions(
1318 mergeDeepRight(Constants
.DEFAULT_STATION_INFO
, stationInfo
),
1323 private getStationInfoFromFile (
1324 stationInfoPersistentConfiguration
: boolean | undefined = Constants
.DEFAULT_STATION_INFO
1325 .stationInfoPersistentConfiguration
1326 ): ChargingStationInfo
| undefined {
1327 let stationInfo
: ChargingStationInfo
| undefined
1328 if (stationInfoPersistentConfiguration
) {
1329 stationInfo
= this.getConfigurationFromFile()?.stationInfo
1330 if (stationInfo
!= null) {
1331 // eslint-disable-next-line @typescript-eslint/no-deprecated
1332 delete stationInfo
.infoHash
1333 delete (stationInfo
as ChargingStationTemplate
).numberOfConnectors
1334 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1335 stationInfo
.templateIndex
??= this.index
1336 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1337 stationInfo
.templateName
??= buildTemplateName(this.templateFile
)
1343 private getStationInfoFromTemplate (): ChargingStationInfo
{
1344 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1345 const stationTemplate
= this.getTemplateFromFile()!
1346 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1347 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
)
1348 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
)
1349 if (stationTemplate
.Connectors
!= null) {
1350 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1352 const stationInfo
= stationTemplateToStationInfo(stationTemplate
)
1353 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
)
1354 stationInfo
.templateIndex
= this.index
1355 stationInfo
.templateName
= buildTemplateName(this.templateFile
)
1356 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
)
1357 createSerialNumber(stationTemplate
, stationInfo
)
1358 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
)
1359 if (isNotEmptyArray
<number>(stationTemplate
.power
)) {
1360 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
)
1361 stationInfo
.maximumPower
=
1362 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1363 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1364 : stationTemplate
.power
[powerArrayRandomIndex
]
1365 } else if (typeof stationTemplate
.power
=== 'number') {
1366 stationInfo
.maximumPower
=
1367 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1368 ? stationTemplate
.power
* 1000
1369 : stationTemplate
.power
1371 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
)
1373 isNotEmptyString(stationInfo
.firmwareVersionPattern
) &&
1374 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1375 !new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
)
1378 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1380 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1383 if (stationTemplate
.resetTime
!= null) {
1384 stationInfo
.resetTime
= secondsToMilliseconds(stationTemplate
.resetTime
)
1389 private getTemplateFromFile (): ChargingStationTemplate
| undefined {
1390 let template
: ChargingStationTemplate
| undefined
1392 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1393 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
)
1395 const measureId
= `${FileType.ChargingStationTemplate} read`
1396 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1397 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
1398 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1399 template
.templateHash
= hash(
1400 Constants
.DEFAULT_HASH_ALGORITHM
,
1401 JSON
.stringify(template
),
1404 this.sharedLRUCache
.setChargingStationTemplate(template
)
1405 this.templateFileHash
= template
.templateHash
1408 handleFileException(
1410 FileType
.ChargingStationTemplate
,
1411 error
as NodeJS
.ErrnoException
,
1418 private getUseConnectorId0 (stationTemplate
?: ChargingStationTemplate
): boolean {
1419 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1420 return stationTemplate
?.useConnectorId0
?? Constants
.DEFAULT_STATION_INFO
.useConnectorId0
!
1423 private getVoltageOut (stationInfo
?: ChargingStationInfo
): Voltage
{
1425 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1426 (stationInfo
?? this.stationInfo
!).voltageOut
??
1427 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
1431 private getWebSocketPingInterval (): number {
1432 return getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) != null
1433 ? convertToInt(getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
)
1437 private handleErrorMessage (errorResponse
: ErrorResponse
): void {
1438 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
1439 if (!this.requests
.has(messageId
)) {
1441 throw new OCPPError(
1442 ErrorType
.INTERNAL_ERROR
,
1443 `Error response for unknown message id '${messageId}'`,
1445 { errorDetails
, errorMessage
, errorType
}
1448 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1449 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1451 `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify(
1455 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
))
1458 private async handleIncomingMessage (request
: IncomingRequest
): Promise
<void> {
1459 const [messageType
, messageId
, commandName
, commandPayload
] = request
1460 if (this.requests
.has(messageId
)) {
1461 throw new OCPPError(
1462 ErrorType
.SECURITY_ERROR
,
1463 `Received message with duplicate message id '${messageId}'`,
1468 if (this.stationInfo
?.enableStatistics
=== true) {
1469 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
)
1472 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1476 // Process the message
1477 await this.ocppIncomingRequestService
.incomingRequestHandler(
1483 this.emit(ChargingStationEvents
.updated
)
1486 private handleResponseMessage (response
: Response
): void {
1487 const [messageType
, messageId
, commandPayload
] = response
1488 if (!this.requests
.has(messageId
)) {
1490 throw new OCPPError(
1491 ErrorType
.INTERNAL_ERROR
,
1492 `Response for unknown message id '${messageId}'`,
1498 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1499 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1504 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1508 responseCallback(commandPayload
, requestPayload
)
1511 private handleUnsupportedVersion (version
: OCPPVersion
| undefined): void {
1512 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1513 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`
1514 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1515 throw new BaseError(errorMsg
)
1518 private initialize (options
?: ChargingStationOptions
): void {
1519 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1520 const stationTemplate
= this.getTemplateFromFile()!
1521 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1522 this.configurationFile
= join(
1523 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1524 `${getHashId(this.index, stationTemplate)}.json`
1526 const stationConfiguration
= this.getConfigurationFromFile()
1528 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
.templateHash
&&
1529 (stationConfiguration
?.connectorsStatus
!= null || stationConfiguration
?.evsesStatus
!= null)
1531 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
)
1532 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
)
1534 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
)
1536 this.stationInfo
= this.getStationInfo(options
)
1537 validateStationInfo(this)
1539 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1540 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
) &&
1541 isNotEmptyString(this.stationInfo
.firmwareVersion
)
1543 const patternGroup
=
1544 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1545 this.stationInfo
.firmwareVersion
.split('.').length
1546 const match
= new RegExp(this.stationInfo
.firmwareVersionPattern
)
1547 .exec(this.stationInfo
.firmwareVersion
)
1548 ?.slice(1, patternGroup
+ 1)
1549 if (match
!= null) {
1550 const patchLevelIndex
= match
.length
- 1
1551 match
[patchLevelIndex
] = (
1552 convertToInt(match
[patchLevelIndex
]) +
1553 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1554 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1556 this.stationInfo
.firmwareVersion
= match
.join('.')
1559 this.saveStationInfo()
1560 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
1561 if (this.stationInfo
.enableStatistics
=== true) {
1562 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1563 this.stationInfo
.hashId
,
1564 this.stationInfo
.chargingStationId
,
1565 this.configuredSupervisionUrl
1568 const bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
)
1569 if (bootNotificationRequest
== null) {
1570 const errorMsg
= 'Error while creating boot notification request'
1571 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1572 throw new BaseError(errorMsg
)
1574 this.bootNotificationRequest
= bootNotificationRequest
1575 this.powerDivider
= this.getPowerDivider()
1576 // OCPP configuration
1577 this.ocppConfiguration
= this.getOcppConfiguration(options
?.persistentConfiguration
)
1578 this.initializeOcppConfiguration()
1579 this.initializeOcppServices()
1580 if (this.stationInfo
.autoRegister
=== true) {
1581 this.bootNotificationResponse
= {
1582 currentTime
: new Date(),
1583 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1584 status: RegistrationStatusEnumType
.ACCEPTED
,
1589 private initializeConnectorsFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1590 if (stationTemplate
.Connectors
== null && this.connectors
.size
=== 0) {
1591 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1592 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1593 throw new BaseError(errorMsg
)
1595 if (stationTemplate
.Connectors
?.[0] == null) {
1597 `${this.logPrefix()} Charging station information from template ${
1599 } with no connector id 0 configuration`
1602 if (stationTemplate
.Connectors
!= null) {
1603 const { configuredMaxConnectors
, templateMaxAvailableConnectors
, templateMaxConnectors
} =
1604 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1605 const connectorsConfigHash
= hash(
1606 Constants
.DEFAULT_HASH_ALGORITHM
,
1607 `${JSON.stringify(stationTemplate.Connectors)}${configuredMaxConnectors.toString()}`,
1610 const connectorsConfigChanged
=
1611 this.connectors
.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
1612 if (this.connectors
.size
=== 0 || connectorsConfigChanged
) {
1613 connectorsConfigChanged
&& this.connectors
.clear()
1614 this.connectorsConfigurationHash
= connectorsConfigHash
1615 if (templateMaxConnectors
> 0) {
1616 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1618 connectorId
=== 0 &&
1619 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1620 (stationTemplate
.Connectors
[connectorId
] == null ||
1621 !this.getUseConnectorId0(stationTemplate
))
1625 const templateConnectorId
=
1626 connectorId
> 0 && stationTemplate
.randomConnectors
=== true
1627 ? randomInt(1, templateMaxAvailableConnectors
)
1629 const connectorStatus
= stationTemplate
.Connectors
[templateConnectorId
]
1630 checkStationInfoConnectorStatus(
1631 templateConnectorId
,
1636 this.connectors
.set(connectorId
, clone
<ConnectorStatus
>(connectorStatus
))
1638 initializeConnectorsMapStatus(this.connectors
, this.logPrefix())
1639 this.saveConnectorsStatus()
1642 `${this.logPrefix()} Charging station information from template ${
1644 } with no connectors configuration defined, cannot create connectors`
1650 `${this.logPrefix()} Charging station information from template ${
1652 } with no connectors configuration defined, using already defined connectors`
1657 private initializeConnectorsOrEvsesFromFile (configuration
: ChargingStationConfiguration
): void {
1658 if (configuration
.connectorsStatus
!= null && configuration
.evsesStatus
== null) {
1659 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1660 this.connectors
.set(
1662 prepareConnectorStatus(clone
<ConnectorStatus
>(connectorStatus
))
1665 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
== null) {
1666 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1667 const evseStatus
= clone
<EvseStatusConfiguration
>(evseStatusConfiguration
)
1668 delete evseStatus
.connectorsStatus
1669 this.evses
.set(evseId
, {
1670 ...(evseStatus
as EvseStatus
),
1671 connectors
: new Map
<number, ConnectorStatus
>(
1672 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1673 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1675 prepareConnectorStatus(connectorStatus
),
1680 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
!= null) {
1681 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1682 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1683 throw new BaseError(errorMsg
)
1685 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`
1686 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1687 throw new BaseError(errorMsg
)
1691 private initializeConnectorsOrEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1692 if (stationTemplate
.Connectors
!= null && stationTemplate
.Evses
== null) {
1693 this.initializeConnectorsFromTemplate(stationTemplate
)
1694 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
== null) {
1695 this.initializeEvsesFromTemplate(stationTemplate
)
1696 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
!= null) {
1697 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`
1698 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1699 throw new BaseError(errorMsg
)
1701 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`
1702 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1703 throw new BaseError(errorMsg
)
1707 private initializeEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1708 if (stationTemplate
.Evses
== null && this.evses
.size
=== 0) {
1709 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1710 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1711 throw new BaseError(errorMsg
)
1713 if (stationTemplate
.Evses
?.[0] == null) {
1715 `${this.logPrefix()} Charging station information from template ${
1717 } with no evse id 0 configuration`
1720 if (stationTemplate
.Evses
?.[0]?.Connectors
[0] == null) {
1722 `${this.logPrefix()} Charging station information from template ${
1724 } with evse id 0 with no connector id 0 configuration`
1727 if (Object.keys(stationTemplate
.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1729 `${this.logPrefix()} Charging station information from template ${
1731 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1734 if (stationTemplate
.Evses
!= null) {
1735 const evsesConfigHash
= hash(
1736 Constants
.DEFAULT_HASH_ALGORITHM
,
1737 JSON
.stringify(stationTemplate
.Evses
),
1740 const evsesConfigChanged
=
1741 this.evses
.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
1742 if (this.evses
.size
=== 0 || evsesConfigChanged
) {
1743 evsesConfigChanged
&& this.evses
.clear()
1744 this.evsesConfigurationHash
= evsesConfigHash
1745 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
.Evses
)
1746 if (templateMaxEvses
> 0) {
1747 for (const evseKey
in stationTemplate
.Evses
) {
1748 const evseId
= convertToInt(evseKey
)
1749 this.evses
.set(evseId
, {
1750 availability
: AvailabilityType
.Operative
,
1751 connectors
: buildConnectorsMap(
1752 stationTemplate
.Evses
[evseKey
].Connectors
,
1757 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1758 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix())
1760 this.saveEvsesStatus()
1763 `${this.logPrefix()} Charging station information from template ${
1765 } with no evses configuration defined, cannot create evses`
1771 `${this.logPrefix()} Charging station information from template ${
1773 } with no evses configuration defined, using already defined evses`
1778 private initializeOcppConfiguration (): void {
1779 if (getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
) == null) {
1780 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0')
1782 if (getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
) == null) {
1783 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', {
1788 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1789 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1790 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) == null
1792 addConfigurationKey(
1794 this.stationInfo
.supervisionUrlOcppKey
,
1795 this.configuredSupervisionUrl
.href
,
1799 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1800 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1801 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) != null
1803 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
, {
1808 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1809 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) == null
1811 addConfigurationKey(
1813 this.stationInfo
.amperageLimitationOcppKey
,
1816 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1817 this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)
1821 if (getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
) == null) {
1822 addConfigurationKey(
1824 StandardParametersKey
.SupportedFeatureProfiles
,
1825 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1828 addConfigurationKey(
1830 StandardParametersKey
.NumberOfConnectors
,
1831 this.getNumberOfConnectors().toString(),
1835 if (getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
) == null) {
1836 addConfigurationKey(
1838 StandardParametersKey
.MeterValuesSampledData
,
1839 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1842 if (getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
) == null) {
1843 const connectorsPhaseRotation
: string[] = []
1844 if (this.hasEvses
) {
1845 for (const evseStatus
of this.evses
.values()) {
1846 for (const connectorId
of evseStatus
.connectors
.keys()) {
1847 connectorsPhaseRotation
.push(
1848 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1849 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1854 for (const connectorId
of this.connectors
.keys()) {
1855 connectorsPhaseRotation
.push(
1856 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1857 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1861 addConfigurationKey(
1863 StandardParametersKey
.ConnectorPhaseRotation
,
1864 connectorsPhaseRotation
.toString()
1867 if (getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
) == null) {
1868 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true')
1871 getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) == null &&
1872 hasFeatureProfile(this, SupportedFeatureProfiles
.LocalAuthListManagement
) === true
1874 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false')
1876 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) == null) {
1877 addConfigurationKey(
1879 StandardParametersKey
.ConnectionTimeOut
,
1880 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1883 this.saveOcppConfiguration()
1886 private initializeOcppServices (): void {
1887 const ocppVersion
= this.stationInfo
?.ocppVersion
1888 switch (ocppVersion
) {
1889 case OCPPVersion
.VERSION_16
:
1890 this.ocppIncomingRequestService
=
1891 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>()
1892 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1893 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1896 case OCPPVersion
.VERSION_20
:
1897 case OCPPVersion
.VERSION_201
:
1898 this.ocppIncomingRequestService
=
1899 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>()
1900 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1901 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1905 this.handleUnsupportedVersion(ocppVersion
)
1910 private internalStopMessageSequence (): void {
1911 // Stop WebSocket ping
1912 this.stopWebSocketPing()
1914 this.stopHeartbeat()
1916 if (this.automaticTransactionGenerator
?.started
=== true) {
1917 this.stopAutomaticTransactionGenerator()
1921 private onClose (code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): void {
1922 this.emit(ChargingStationEvents
.disconnected
)
1923 this.emit(ChargingStationEvents
.updated
)
1926 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1927 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1929 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1931 )}' and reason '${reason.toString()}'`
1933 this.wsConnectionRetryCount
= 0
1938 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1940 )}' and reason '${reason.toString()}'`
1945 this.emit(ChargingStationEvents
.updated
)
1948 .catch((error
: unknown
) =>
1949 logger
.error(`${this.logPrefix()} Error while reconnecting:`, error
)
1955 private onError (error
: WSError
): void {
1956 this.closeWSConnection()
1957 logger
.error(`${this.logPrefix()} WebSocket error:`, error
)
1960 private async onMessage (data
: RawData
): Promise
<void> {
1961 let request
: ErrorResponse
| IncomingRequest
| Response
| undefined
1962 let messageType
: MessageType
| undefined
1963 let errorMsg
: string
1965 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1966 request
= JSON
.parse(data
.toString()) as ErrorResponse
| IncomingRequest
| Response
1967 if (Array.isArray(request
)) {
1968 ;[messageType
] = request
1969 // Check the type of message
1970 switch (messageType
) {
1972 case MessageType
.CALL_ERROR_MESSAGE
:
1973 this.handleErrorMessage(request
as ErrorResponse
)
1976 case MessageType
.CALL_MESSAGE
:
1977 await this.handleIncomingMessage(request
as IncomingRequest
)
1980 case MessageType
.CALL_RESULT_MESSAGE
:
1981 this.handleResponseMessage(request
as Response
)
1985 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1986 errorMsg
= `Wrong message type ${messageType}`
1987 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1988 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
)
1991 throw new OCPPError(
1992 ErrorType
.PROTOCOL_ERROR
,
1993 'Incoming message is not an array',
2001 if (!Array.isArray(request
)) {
2002 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2003 logger
.error(`${this.logPrefix()} Incoming message '${request}' parsing error:`, error
)
2006 let commandName
: IncomingRequestCommand
| undefined
2007 let requestCommandName
: IncomingRequestCommand
| RequestCommand
| undefined
2008 let errorCallback
: ErrorCallback
2009 const [, messageId
] = request
2010 switch (messageType
) {
2011 case MessageType
.CALL_ERROR_MESSAGE
:
2012 case MessageType
.CALL_RESULT_MESSAGE
:
2013 if (this.requests
.has(messageId
)) {
2014 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2015 ;[, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
2016 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2017 errorCallback(error
as OCPPError
, false)
2019 // Remove the request from the cache in case of error at response handling
2020 this.requests
.delete(messageId
)
2023 case MessageType
.CALL_MESSAGE
:
2024 ;[, , commandName
] = request
as IncomingRequest
2026 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
)
2029 if (!(error
instanceof OCPPError
)) {
2031 `${this.logPrefix()} Error thrown at incoming OCPP command ${
2032 commandName ?? requestCommandName ?? Constants.UNKNOWN_OCPP_COMMAND
2033 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2034 } message '${data.toString()}' handling is not an OCPPError:`,
2039 `${this.logPrefix()} Incoming OCPP command '${
2040 commandName ?? requestCommandName ?? Constants.UNKNOWN_OCPP_COMMAND
2041 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2042 }' message '${data.toString()}'${
2043 this.requests.has(messageId)
2044 ? ` matching cached request
'${JSON.stringify(
2045 this.getCachedRequest(messageType, messageId)
2048 } processing error:`,
2054 private async onOpen (): Promise
<void> {
2055 if (this.isWebSocketConnectionOpened()) {
2056 this.emit(ChargingStationEvents
.connected
)
2057 this.emit(ChargingStationEvents
.updated
)
2059 `${this.logPrefix()} Connection to OCPP server through ${
2060 this.wsConnectionUrl.href
2063 let registrationRetryCount
= 0
2064 if (!this.inAcceptedState()) {
2065 // Send BootNotification
2067 await this.ocppRequestService
.requestHandler
<
2068 BootNotificationRequest
,
2069 BootNotificationResponse
2070 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2071 skipBufferingOnError
: true,
2073 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2074 this.bootNotificationResponse
!.currentTime
= convertToDate(
2075 this.bootNotificationResponse
?.currentTime
2077 if (!this.inAcceptedState()) {
2078 ++registrationRetryCount
2081 registrationRetryCount
,
2082 this.bootNotificationResponse
?.interval
!= null
2083 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
2084 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
2089 !this.inAcceptedState() &&
2090 (this.stationInfo
?.registrationMaxRetries
=== -1 ||
2091 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2092 registrationRetryCount
<= this.stationInfo
!.registrationMaxRetries
!)
2095 if (!this.inAcceptedState()) {
2097 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2098 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount.toString()}) or retry disabled (${this.stationInfo?.registrationMaxRetries?.toString()})`
2101 this.emit(ChargingStationEvents
.updated
)
2104 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} failed`
2109 private onPing (): void {
2110 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
2113 private onPong (): void {
2114 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
2117 private async reconnect (): Promise
<void> {
2119 this.stationInfo
?.autoReconnectMaxRetries
=== -1 ||
2120 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2121 this.wsConnectionRetryCount
< this.stationInfo
!.autoReconnectMaxRetries
!
2123 ++this.wsConnectionRetryCount
2124 const reconnectDelay
=
2125 this.stationInfo
?.reconnectExponentialDelay
=== true
2126 ? exponentialDelay(this.wsConnectionRetryCount
)
2127 : secondsToMilliseconds(this.getConnectionTimeout())
2128 const reconnectDelayWithdraw
= 1000
2129 const reconnectTimeout
=
2130 reconnectDelay
- reconnectDelayWithdraw
> 0 ? reconnectDelay
- reconnectDelayWithdraw
: 0
2132 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2135 ).toString()}ms, timeout ${reconnectTimeout.toString()}ms`
2137 await sleep(reconnectDelay
)
2139 `${this.logPrefix()} WebSocket connection retry #${this.wsConnectionRetryCount.toString()}`
2141 this.openWSConnection(
2143 handshakeTimeout
: reconnectTimeout
,
2145 { closeOpened
: true }
2147 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2149 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2150 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${this.wsConnectionRetryCount.toString()}) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries?.toString()})`
2155 private saveAutomaticTransactionGeneratorConfiguration (): void {
2156 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
2157 this.saveConfiguration()
2161 private saveConfiguration (): void {
2162 if (isNotEmptyString(this.configurationFile
)) {
2164 if (!existsSync(dirname(this.configurationFile
))) {
2165 mkdirSync(dirname(this.configurationFile
), { recursive
: true })
2167 const configurationFromFile
= this.getConfigurationFromFile()
2168 let configurationData
: ChargingStationConfiguration
=
2169 configurationFromFile
!= null
2170 ? clone
<ChargingStationConfiguration
>(configurationFromFile
)
2172 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
2173 configurationData
.stationInfo
= this.stationInfo
2175 delete configurationData
.stationInfo
2178 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
2179 Array.isArray(this.ocppConfiguration
?.configurationKey
)
2181 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
2183 delete configurationData
.configurationKey
2185 configurationData
= mergeDeepRight
<ChargingStationConfiguration
>(
2187 buildChargingStationAutomaticTransactionGeneratorConfiguration(
2189 ) as Partial
<ChargingStationConfiguration
>
2191 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
!== true) {
2192 delete configurationData
.automaticTransactionGenerator
2194 if (this.connectors
.size
> 0) {
2195 configurationData
.connectorsStatus
= buildConnectorsStatus(this)
2197 delete configurationData
.connectorsStatus
2199 if (this.evses
.size
> 0) {
2200 configurationData
.evsesStatus
= buildEvsesStatus(this)
2202 delete configurationData
.evsesStatus
2204 delete configurationData
.configurationHash
2205 const configurationHash
= hash(
2206 Constants
.DEFAULT_HASH_ALGORITHM
,
2208 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
2209 configurationKey
: configurationData
.configurationKey
,
2210 stationInfo
: configurationData
.stationInfo
,
2211 ...(this.connectors
.size
> 0 && {
2212 connectorsStatus
: configurationData
.connectorsStatus
,
2214 ...(this.evses
.size
> 0 && {
2215 evsesStatus
: configurationData
.evsesStatus
,
2217 } satisfies ChargingStationConfiguration
),
2220 if (this.configurationFileHash
!== configurationHash
) {
2221 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
2222 configurationData
.configurationHash
= configurationHash
2223 const measureId
= `${FileType.ChargingStationConfiguration} write`
2224 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
2226 this.configurationFile
,
2227 JSON
.stringify(configurationData
, undefined, 2),
2230 PerformanceStatistics
.endMeasure(measureId
, beginId
)
2231 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
2232 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
)
2233 this.configurationFileHash
= configurationHash
2234 }).catch((error
: unknown
) => {
2235 handleFileException(
2236 this.configurationFile
,
2237 FileType
.ChargingStationConfiguration
,
2238 error
as NodeJS
.ErrnoException
,
2244 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
2245 this.configurationFile
2250 handleFileException(
2251 this.configurationFile
,
2252 FileType
.ChargingStationConfiguration
,
2253 error
as NodeJS
.ErrnoException
,
2259 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
2264 private saveConnectorsStatus (): void {
2265 this.saveConfiguration()
2268 private saveEvsesStatus (): void {
2269 this.saveConfiguration()
2272 private saveStationInfo (): void {
2273 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
2274 this.saveConfiguration()
2278 private readonly sendMessageBuffer
= (
2279 onCompleteCallback
: () => void,
2282 if (this.messageQueue
.length
> 0) {
2283 const message
= this.messageQueue
[0]
2284 let beginId
: string | undefined
2285 let commandName
: RequestCommand
| undefined
2286 let parsedMessage
: ErrorResponse
| OutgoingRequest
| Response
2289 parsedMessage
= JSON
.parse(message
) as ErrorResponse
| OutgoingRequest
| Response
2292 `${this.logPrefix()} Error while parsing buffered OCPP message '${message}' to JSON:`,
2295 this.messageQueue
.shift()
2296 this.sendMessageBuffer(onCompleteCallback
, messageIdx
)
2299 const [messageType
] = parsedMessage
2300 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
2302 ;[, , commandName
] = parsedMessage
as OutgoingRequest
2303 beginId
= PerformanceStatistics
.beginMeasure(commandName
)
2305 this.wsConnection
?.send(message
, (error
?: Error) => {
2306 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2307 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!)
2308 if (error
== null) {
2310 `${this.logPrefix()} >> Buffered ${getMessageTypeString(messageType)} OCPP message sent '${message}'`
2312 this.messageQueue
.shift()
2315 `${this.logPrefix()} >> Buffered ${getMessageTypeString(messageType)} OCPP message '${message}' send failed:`,
2319 // eslint-disable-next-line promise/catch-or-return, @typescript-eslint/no-floating-promises, promise/no-promise-in-callback
2320 sleep(exponentialDelay(messageIdx
))
2321 // eslint-disable-next-line promise/always-return
2323 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2325 this.sendMessageBuffer(onCompleteCallback
, messageIdx
)
2329 onCompleteCallback()
2333 private setIntervalFlushMessageBuffer (): void {
2334 this.flushMessageBufferSetInterval
??= setInterval(() => {
2335 if (this.isWebSocketConnectionOpened() && this.inAcceptedState()) {
2336 this.flushMessageBuffer()
2338 if (!this.isWebSocketConnectionOpened() || this.messageQueue
.length
=== 0) {
2339 this.clearIntervalFlushMessageBuffer()
2341 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
)
2344 private async startMessageSequence (ATGStopAbsoluteDuration
?: boolean): Promise
<void> {
2345 if (this.stationInfo
?.autoRegister
=== true) {
2346 await this.ocppRequestService
.requestHandler
<
2347 BootNotificationRequest
,
2348 BootNotificationResponse
2349 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2350 skipBufferingOnError
: true,
2353 // Start WebSocket ping
2354 if (this.wsPingSetInterval
== null) {
2355 this.startWebSocketPing()
2358 if (this.heartbeatSetInterval
== null) {
2359 this.startHeartbeat()
2361 // Initialize connectors status
2362 if (this.hasEvses
) {
2363 for (const [evseId
, evseStatus
] of this.evses
) {
2365 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2366 await sendAndSetConnectorStatus(
2369 getBootConnectorStatus(this, connectorId
, connectorStatus
),
2376 for (const connectorId
of this.connectors
.keys()) {
2377 if (connectorId
> 0) {
2378 await sendAndSetConnectorStatus(
2381 getBootConnectorStatus(
2384 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2385 this.getConnectorStatus(connectorId
)!
2391 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2392 await this.ocppRequestService
.requestHandler
<
2393 FirmwareStatusNotificationRequest
,
2394 FirmwareStatusNotificationResponse
2395 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2396 status: FirmwareStatus
.Installed
,
2398 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
2402 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2403 this.startAutomaticTransactionGenerator(undefined, ATGStopAbsoluteDuration
)
2405 this.flushMessageBuffer()
2408 private startWebSocketPing (): void {
2409 const webSocketPingInterval
= this.getWebSocketPingInterval()
2410 if (webSocketPingInterval
> 0 && this.wsPingSetInterval
== null) {
2411 this.wsPingSetInterval
= setInterval(() => {
2412 if (this.isWebSocketConnectionOpened()) {
2413 this.wsConnection
?.ping()
2415 }, secondsToMilliseconds(webSocketPingInterval
))
2417 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2418 webSocketPingInterval
2421 } else if (this.wsPingSetInterval
!= null) {
2423 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2424 webSocketPingInterval
2429 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval.toString()}, not starting the WebSocket ping`
2434 private stopHeartbeat (): void {
2435 if (this.heartbeatSetInterval
!= null) {
2436 clearInterval(this.heartbeatSetInterval
)
2437 delete this.heartbeatSetInterval
2441 private async stopMessageSequence (
2442 reason
?: StopTransactionReason
,
2443 stopTransactions
?: boolean
2445 this.internalStopMessageSequence()
2446 // Stop ongoing transactions
2447 stopTransactions
&& (await this.stopRunningTransactions(reason
))
2448 if (this.hasEvses
) {
2449 for (const [evseId
, evseStatus
] of this.evses
) {
2451 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2452 await sendAndSetConnectorStatus(
2455 ConnectorStatusEnum
.Unavailable
,
2458 delete connectorStatus
.status
2463 for (const connectorId
of this.connectors
.keys()) {
2464 if (connectorId
> 0) {
2465 await sendAndSetConnectorStatus(this, connectorId
, ConnectorStatusEnum
.Unavailable
)
2466 delete this.getConnectorStatus(connectorId
)?.status
2472 private async stopRunningTransactions (reason
?: StopTransactionReason
): Promise
<void> {
2473 if (this.hasEvses
) {
2474 for (const [evseId
, evseStatus
] of this.evses
) {
2478 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2479 if (connectorStatus
.transactionStarted
=== true) {
2480 await this.stopTransactionOnConnector(connectorId
, reason
)
2485 for (const connectorId
of this.connectors
.keys()) {
2486 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2487 await this.stopTransactionOnConnector(connectorId
, reason
)
2493 private stopWebSocketPing (): void {
2494 if (this.wsPingSetInterval
!= null) {
2495 clearInterval(this.wsPingSetInterval
)
2496 delete this.wsPingSetInterval
2500 private terminateWSConnection (): void {
2501 if (this.isWebSocketConnectionOpened()) {
2502 this.wsConnection
?.terminate()
2503 this.wsConnection
= null