1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { createHash
} from
'node:crypto'
4 import { EventEmitter
} from
'node:events'
5 import { type FSWatcher
, existsSync
, mkdirSync
, readFileSync
, writeFileSync
} from
'node:fs'
6 import { dirname
, join
, parse
} from
'node:path'
7 import { URL
} from
'node:url'
8 import { parentPort
} from
'node:worker_threads'
10 import { millisecondsToSeconds
, secondsToMilliseconds
} from
'date-fns'
11 import merge from
'just-merge'
12 import { type RawData
, WebSocket
} from
'ws'
14 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator.js'
15 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel.js'
18 deleteConfigurationKey
,
20 setConfigurationKeyValue
21 } from
'./ConfigurationKeyUtils.js'
26 checkConnectorsConfiguration
,
27 checkStationInfoConnectorStatus
,
29 createBootNotificationRequest
,
31 getAmperageLimitationUnitDivider
,
32 getBootConnectorStatus
,
33 getChargingStationConnectorChargingProfilesPowerLimit
,
39 getNumberOfReservableConnectors
,
40 getPhaseRotationValue
,
42 hasReservationExpired
,
43 initializeConnectorsMapStatus
,
44 propagateSerialNumber
,
45 stationTemplateToStationInfo
,
46 warnTemplateKeysDeprecation
48 import { IdTagsCache
} from
'./IdTagsCache.js'
50 OCPP16IncomingRequestService
,
52 OCPP16ResponseService
,
53 OCPP20IncomingRequestService
,
55 OCPP20ResponseService
,
56 type OCPPIncomingRequestService
,
57 type OCPPRequestService
,
59 buildTransactionEndMeterValue
,
61 sendAndSetConnectorStatus
62 } from
'./ocpp/index.js'
63 import { SharedLRUCache
} from
'./SharedLRUCache.js'
64 import { BaseError
, OCPPError
} from
'../exception/index.js'
65 import { PerformanceStatistics
} from
'../performance/index.js'
67 type AutomaticTransactionGeneratorConfiguration
,
69 type BootNotificationRequest
,
70 type BootNotificationResponse
,
72 type ChargingStationConfiguration
,
73 ChargingStationEvents
,
74 type ChargingStationInfo
,
75 type ChargingStationOcppConfiguration
,
76 type ChargingStationOptions
,
77 type ChargingStationTemplate
,
85 type EvseStatusConfiguration
,
88 type FirmwareStatusNotificationRequest
,
89 type FirmwareStatusNotificationResponse
,
91 type HeartbeatRequest
,
92 type HeartbeatResponse
,
94 type IncomingRequestCommand
,
97 type MeterValuesRequest
,
98 type MeterValuesResponse
,
100 type OutgoingRequest
,
102 RegistrationStatusEnumType
,
106 ReservationTerminationReason
,
108 StandardParametersKey
,
110 type StopTransactionReason
,
111 type StopTransactionRequest
,
112 type StopTransactionResponse
,
113 SupervisionUrlDistribution
,
114 SupportedFeatureProfiles
,
117 WebSocketCloseEventStatusCode
,
119 } from
'../types/index.js'
128 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
129 buildConnectorsStatus
,
139 formatDurationMilliSeconds
,
140 formatDurationSeconds
,
142 getWebSocketCloseEventStatusString
,
154 } from
'../utils/index.js'
156 export class ChargingStation
extends EventEmitter
{
157 public readonly index
: number
158 public readonly templateFile
: string
159 public stationInfo
?: ChargingStationInfo
160 public started
: boolean
161 public starting
: boolean
162 public idTagsCache
: IdTagsCache
163 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined
164 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined
165 public wsConnection
: WebSocket
| null
166 public readonly connectors
: Map
<number, ConnectorStatus
>
167 public readonly evses
: Map
<number, EvseStatus
>
168 public readonly requests
: Map
<string, CachedRequest
>
169 public performanceStatistics
!: PerformanceStatistics
| undefined
170 public heartbeatSetInterval
?: NodeJS
.Timeout
171 public ocppRequestService
!: OCPPRequestService
172 public bootNotificationRequest
?: BootNotificationRequest
173 public bootNotificationResponse
?: BootNotificationResponse
174 public powerDivider
?: number
175 private stopping
: boolean
176 private configurationFile
!: string
177 private configurationFileHash
!: string
178 private connectorsConfigurationHash
!: string
179 private evsesConfigurationHash
!: string
180 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
181 private ocppIncomingRequestService
!: OCPPIncomingRequestService
182 private readonly messageBuffer
: Set
<string>
183 private configuredSupervisionUrl
!: URL
184 private wsConnectionRetried
: boolean
185 private wsConnectionRetryCount
: number
186 private templateFileWatcher
!: FSWatcher
| undefined
187 private templateFileHash
!: string
188 private readonly sharedLRUCache
: SharedLRUCache
189 private wsPingSetInterval
?: NodeJS
.Timeout
190 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
191 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
193 constructor (index
: number, templateFile
: string, options
?: ChargingStationOptions
) {
196 this.starting
= false
197 this.stopping
= false
198 this.wsConnection
= null
199 this.wsConnectionRetried
= false
200 this.wsConnectionRetryCount
= 0
202 this.templateFile
= templateFile
203 this.connectors
= new Map
<number, ConnectorStatus
>()
204 this.evses
= new Map
<number, EvseStatus
>()
205 this.requests
= new Map
<string, CachedRequest
>()
206 this.messageBuffer
= new Set
<string>()
207 this.sharedLRUCache
= SharedLRUCache
.getInstance()
208 this.idTagsCache
= IdTagsCache
.getInstance()
209 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this)
211 this.on(ChargingStationEvents
.added
, () => {
212 parentPort
?.postMessage(buildAddedMessage(this))
214 this.on(ChargingStationEvents
.started
, () => {
215 parentPort
?.postMessage(buildStartedMessage(this))
217 this.on(ChargingStationEvents
.stopped
, () => {
218 parentPort
?.postMessage(buildStoppedMessage(this))
220 this.on(ChargingStationEvents
.updated
, () => {
221 parentPort
?.postMessage(buildUpdatedMessage(this))
223 this.on(ChargingStationEvents
.accepted
, () => {
224 this.startMessageSequence(
225 this.wsConnectionRetried
227 : this.getAutomaticTransactionGeneratorConfiguration()?.stopAbsoluteDuration
229 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
)
231 this.wsConnectionRetried
= false
233 this.on(ChargingStationEvents
.rejected
, () => {
234 this.wsConnectionRetried
= false
236 this.on(ChargingStationEvents
.disconnected
, () => {
238 this.internalStopMessageSequence()
241 `${this.logPrefix()} Error while stopping the internal message sequence:`,
247 this.initialize(options
)
251 if (options
?.autoStart
!= null) {
252 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
253 this.stationInfo
!.autoStart
= options
.autoStart
256 if (this.stationInfo
?.autoStart
=== true) {
261 public get
hasEvses (): boolean {
262 return this.connectors
.size
=== 0 && this.evses
.size
> 0
265 public get
wsConnectionUrl (): URL
{
268 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
269 isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
270 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value)
271 ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value
272 : this.configuredSupervisionUrl.href
273 }/${this.stationInfo?.chargingStationId}`
277 public logPrefix
= (): string => {
279 this instanceof ChargingStation
&&
280 this.stationInfo
!= null &&
281 isNotEmptyString(this.stationInfo
.chargingStationId
)
283 return logPrefix(` ${this.stationInfo.chargingStationId} |`)
285 let stationTemplate
: ChargingStationTemplate
| undefined
287 stationTemplate
= JSON
.parse(
288 readFileSync(this.templateFile
, 'utf8')
289 ) as ChargingStationTemplate
291 stationTemplate
= undefined
293 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`)
296 public hasIdTags (): boolean {
297 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
298 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
!)!))
301 public getNumberOfPhases (stationInfo
?: ChargingStationInfo
): number {
302 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
303 const localStationInfo
= stationInfo
?? this.stationInfo
!
304 switch (this.getCurrentOutType(stationInfo
)) {
306 return localStationInfo
.numberOfPhases
?? 3
312 public isWebSocketConnectionOpened (): boolean {
313 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
316 public inUnknownState (): boolean {
317 return this.bootNotificationResponse
?.status == null
320 public inPendingState (): boolean {
321 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
324 public inAcceptedState (): boolean {
325 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
328 public inRejectedState (): boolean {
329 return this.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
332 public isRegistered (): boolean {
333 return !this.inUnknownState() && (this.inAcceptedState() || this.inPendingState())
336 public isChargingStationAvailable (): boolean {
337 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
340 public hasConnector (connectorId
: number): boolean {
342 for (const evseStatus
of this.evses
.values()) {
343 if (evseStatus
.connectors
.has(connectorId
)) {
349 return this.connectors
.has(connectorId
)
352 public isConnectorAvailable (connectorId
: number): boolean {
355 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
359 public getNumberOfConnectors (): number {
361 let numberOfConnectors
= 0
362 for (const [evseId
, evseStatus
] of this.evses
) {
364 numberOfConnectors
+= evseStatus
.connectors
.size
367 return numberOfConnectors
369 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
372 public getNumberOfEvses (): number {
373 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
376 public getConnectorStatus (connectorId
: number): ConnectorStatus
| undefined {
378 for (const evseStatus
of this.evses
.values()) {
379 if (evseStatus
.connectors
.has(connectorId
)) {
380 return evseStatus
.connectors
.get(connectorId
)
385 return this.connectors
.get(connectorId
)
388 public getConnectorMaximumAvailablePower (connectorId
: number): number {
389 let connectorAmperageLimitationPowerLimit
: number | undefined
390 const amperageLimitation
= this.getAmperageLimitation()
392 amperageLimitation
!= null &&
393 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
394 amperageLimitation
< this.stationInfo
!.maximumAmperage
!
396 connectorAmperageLimitationPowerLimit
=
397 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
398 ? ACElectricUtils
.powerTotal(
399 this.getNumberOfPhases(),
400 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
401 this.stationInfo
.voltageOut
!,
403 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
405 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
406 DCElectricUtils
.power(this.stationInfo
!.voltageOut
!, amperageLimitation
)) /
407 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
410 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
411 const connectorMaximumPower
= this.stationInfo
!.maximumPower
! / this.powerDivider
!
412 const connectorChargingProfilesPowerLimit
=
413 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
)
415 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
416 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
417 isNaN(connectorAmperageLimitationPowerLimit
!)
419 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
420 connectorAmperageLimitationPowerLimit
!,
421 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
422 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!
426 public getTransactionIdTag (transactionId
: number): string | undefined {
428 for (const evseStatus
of this.evses
.values()) {
429 for (const connectorStatus
of evseStatus
.connectors
.values()) {
430 if (connectorStatus
.transactionId
=== transactionId
) {
431 return connectorStatus
.transactionIdTag
436 for (const connectorId
of this.connectors
.keys()) {
437 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
438 return this.getConnectorStatus(connectorId
)?.transactionIdTag
444 public getNumberOfRunningTransactions (): number {
445 let numberOfRunningTransactions
= 0
447 for (const [evseId
, evseStatus
] of this.evses
) {
451 for (const connectorStatus
of evseStatus
.connectors
.values()) {
452 if (connectorStatus
.transactionStarted
=== true) {
453 ++numberOfRunningTransactions
458 for (const connectorId
of this.connectors
.keys()) {
459 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
460 ++numberOfRunningTransactions
464 return numberOfRunningTransactions
467 public getConnectorIdByTransactionId (transactionId
: number | undefined): number | undefined {
468 if (transactionId
== null) {
470 } else if (this.hasEvses
) {
471 for (const evseStatus
of this.evses
.values()) {
472 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
473 if (connectorStatus
.transactionId
=== transactionId
) {
479 for (const connectorId
of this.connectors
.keys()) {
480 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
487 public getEnergyActiveImportRegisterByTransactionId (
488 transactionId
: number | undefined,
491 return this.getEnergyActiveImportRegister(
492 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
493 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!),
498 public getEnergyActiveImportRegisterByConnectorId (connectorId
: number, rounded
= false): number {
499 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
)
502 public getAuthorizeRemoteTxRequests (): boolean {
503 const authorizeRemoteTxRequests
= getConfigurationKey(
505 StandardParametersKey
.AuthorizeRemoteTxRequests
507 return authorizeRemoteTxRequests
!= null
508 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
512 public getLocalAuthListEnabled (): boolean {
513 const localAuthListEnabled
= getConfigurationKey(
515 StandardParametersKey
.LocalAuthListEnabled
517 return localAuthListEnabled
!= null ? convertToBoolean(localAuthListEnabled
.value
) : false
520 public getHeartbeatInterval (): number {
521 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)
522 if (HeartbeatInterval
!= null) {
523 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
))
525 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)
526 if (HeartBeatInterval
!= null) {
527 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
))
529 this.stationInfo
?.autoRegister
=== false &&
531 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
532 Constants.DEFAULT_HEARTBEAT_INTERVAL
535 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
538 public setSupervisionUrl (url
: string): void {
540 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
541 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
)
543 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
, url
)
545 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
546 this.stationInfo
!.supervisionUrls
= url
547 this.saveStationInfo()
548 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
552 public startHeartbeat (): void {
553 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
== null) {
554 this.heartbeatSetInterval
= setInterval(() => {
555 this.ocppRequestService
556 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
559 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
563 }, this.getHeartbeatInterval())
565 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
566 this.getHeartbeatInterval()
569 } else if (this.heartbeatSetInterval
!= null) {
571 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
572 this.getHeartbeatInterval()
577 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
582 public restartHeartbeat (): void {
586 this.startHeartbeat()
589 public restartWebSocketPing (): void {
590 // Stop WebSocket ping
591 this.stopWebSocketPing()
592 // Start WebSocket ping
593 this.startWebSocketPing()
596 public startMeterValues (connectorId
: number, interval
: number): void {
597 if (connectorId
=== 0) {
598 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`)
601 const connectorStatus
= this.getConnectorStatus(connectorId
)
602 if (connectorStatus
== null) {
604 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
609 if (connectorStatus
.transactionStarted
=== false) {
611 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`
615 connectorStatus
.transactionStarted
=== true &&
616 connectorStatus
.transactionId
== null
619 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`
624 connectorStatus
.transactionSetInterval
= setInterval(() => {
625 const meterValue
= buildMeterValue(
628 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
629 connectorStatus
.transactionId
!,
632 this.ocppRequestService
633 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
635 RequestCommand
.METER_VALUES
,
638 transactionId
: connectorStatus
.transactionId
,
639 meterValue
: [meterValue
]
644 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
651 `${this.logPrefix()} Charging station ${
652 StandardParametersKey.MeterValueSampleInterval
653 } configuration set to ${interval}, not sending MeterValues`
658 public stopMeterValues (connectorId
: number): void {
659 const connectorStatus
= this.getConnectorStatus(connectorId
)
660 if (connectorStatus
?.transactionSetInterval
!= null) {
661 clearInterval(connectorStatus
.transactionSetInterval
)
665 private add (): void {
666 this.emit(ChargingStationEvents
.added
)
669 public start (): void {
671 if (!this.starting
) {
673 if (this.stationInfo
?.enableStatistics
=== true) {
674 this.performanceStatistics
?.start()
676 this.openWSConnection()
677 // Monitor charging station template file
678 this.templateFileWatcher
= watchJsonFile(
680 FileType
.ChargingStationTemplate
,
683 (event
, filename
): void => {
684 if (isNotEmptyString(filename
) && event
=== 'change') {
687 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
689 } file have changed, reload`
691 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
694 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
695 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
!)!)
697 const ATGStarted
= this.automaticTransactionGenerator
?.started
698 if (ATGStarted
=== true) {
699 this.stopAutomaticTransactionGenerator()
701 delete this.automaticTransactionGeneratorConfiguration
703 this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true &&
706 this.startAutomaticTransactionGenerator(undefined, true)
708 if (this.stationInfo
?.enableStatistics
=== true) {
709 this.performanceStatistics
?.restart()
711 this.performanceStatistics
?.stop()
713 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
716 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
724 this.emit(ChargingStationEvents
.started
)
725 this.starting
= false
727 logger
.warn(`${this.logPrefix()} Charging station is already starting...`)
730 logger
.warn(`${this.logPrefix()} Charging station is already started...`)
735 reason
?: StopTransactionReason
,
736 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
739 if (!this.stopping
) {
741 await this.stopMessageSequence(reason
, stopTransactions
)
742 this.closeWSConnection()
743 if (this.stationInfo
?.enableStatistics
=== true) {
744 this.performanceStatistics
?.stop()
746 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
747 this.templateFileWatcher
?.close()
748 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
)
749 delete this.bootNotificationResponse
751 this.saveConfiguration()
752 this.emit(ChargingStationEvents
.stopped
)
753 this.stopping
= false
755 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`)
758 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`)
762 public async reset (reason
?: StopTransactionReason
): Promise
<void> {
763 await this.stop(reason
)
764 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
765 await sleep(this.stationInfo
!.resetTime
!)
770 public saveOcppConfiguration (): void {
771 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
772 this.saveConfiguration()
776 public bufferMessage (message
: string): void {
777 this.messageBuffer
.add(message
)
778 this.setIntervalFlushMessageBuffer()
781 public openWSConnection (
783 params
?: { closeOpened
?: boolean, terminateOpened
?: boolean }
786 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
787 ...this.stationInfo
?.wsOptions
,
790 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
}
791 if (!checkChargingStation(this, this.logPrefix())) {
794 if (this.stationInfo
?.supervisionUser
!= null && this.stationInfo
.supervisionPassword
!= null) {
795 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`
797 if (params
.closeOpened
=== true) {
798 this.closeWSConnection()
800 if (params
.terminateOpened
=== true) {
801 this.terminateWSConnection()
804 if (this.isWebSocketConnectionOpened()) {
806 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.href} is already opened`
811 logger
.info(`${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.href}`)
813 this.wsConnection
= new WebSocket(
814 this.wsConnectionUrl
,
815 `ocpp${this.stationInfo?.ocppVersion}`,
819 // Handle WebSocket message
820 this.wsConnection
.on('message', data
=> {
821 this.onMessage(data
).catch(Constants
.EMPTY_FUNCTION
)
823 // Handle WebSocket error
824 this.wsConnection
.on('error', this.onError
.bind(this))
825 // Handle WebSocket close
826 this.wsConnection
.on('close', this.onClose
.bind(this))
827 // Handle WebSocket open
828 this.wsConnection
.on('open', () => {
829 this.onOpen().catch(error
=>
830 logger
.error(`${this.logPrefix()} Error while opening WebSocket connection:`, error
)
833 // Handle WebSocket ping
834 this.wsConnection
.on('ping', this.onPing
.bind(this))
835 // Handle WebSocket pong
836 this.wsConnection
.on('pong', this.onPong
.bind(this))
839 public closeWSConnection (): void {
840 if (this.isWebSocketConnectionOpened()) {
841 this.wsConnection
?.close()
842 this.wsConnection
= null
846 public getAutomaticTransactionGeneratorConfiguration ():
847 | AutomaticTransactionGeneratorConfiguration
849 if (this.automaticTransactionGeneratorConfiguration
== null) {
850 let automaticTransactionGeneratorConfiguration
:
851 | AutomaticTransactionGeneratorConfiguration
853 const stationTemplate
= this.getTemplateFromFile()
854 const stationConfiguration
= this.getConfigurationFromFile()
856 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
857 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
858 stationConfiguration
?.automaticTransactionGenerator
!= null
860 automaticTransactionGeneratorConfiguration
=
861 stationConfiguration
.automaticTransactionGenerator
863 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
865 this.automaticTransactionGeneratorConfiguration
= {
866 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
867 ...automaticTransactionGeneratorConfiguration
870 return this.automaticTransactionGeneratorConfiguration
873 public getAutomaticTransactionGeneratorStatuses (): Status
[] | undefined {
874 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
877 public startAutomaticTransactionGenerator (
878 connectorIds
?: number[],
879 stopAbsoluteDuration
?: boolean
881 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this)
882 if (isNotEmptyArray(connectorIds
)) {
883 for (const connectorId
of connectorIds
) {
884 this.automaticTransactionGenerator
?.startConnector(connectorId
, stopAbsoluteDuration
)
887 this.automaticTransactionGenerator
?.start(stopAbsoluteDuration
)
889 this.saveAutomaticTransactionGeneratorConfiguration()
890 this.emit(ChargingStationEvents
.updated
)
893 public stopAutomaticTransactionGenerator (connectorIds
?: number[]): void {
894 if (isNotEmptyArray(connectorIds
)) {
895 for (const connectorId
of connectorIds
) {
896 this.automaticTransactionGenerator
?.stopConnector(connectorId
)
899 this.automaticTransactionGenerator
?.stop()
901 this.saveAutomaticTransactionGeneratorConfiguration()
902 this.emit(ChargingStationEvents
.updated
)
905 public async stopTransactionOnConnector (
907 reason
?: StopTransactionReason
908 ): Promise
<StopTransactionResponse
> {
909 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
911 this.stationInfo
?.beginEndMeterValues
=== true &&
912 this.stationInfo
.ocppStrictCompliance
=== true &&
913 this.stationInfo
.outOfOrderEndMeterValues
=== false
915 const transactionEndMeterValue
= buildTransactionEndMeterValue(
918 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
920 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
922 RequestCommand
.METER_VALUES
,
926 meterValue
: [transactionEndMeterValue
]
930 return await this.ocppRequestService
.requestHandler
<
931 StopTransactionRequest
,
932 StopTransactionResponse
933 >(this, RequestCommand
.STOP_TRANSACTION
, {
935 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
936 ...(reason
!= null && { reason
})
940 public getReserveConnectorZeroSupported (): boolean {
941 return convertToBoolean(
942 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
943 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
947 public async addReservation (reservation
: Reservation
): Promise
<void> {
948 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
)
949 if (reservationFound
!= null) {
950 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
)
952 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
953 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
954 await sendAndSetConnectorStatus(
956 reservation
.connectorId
,
957 ConnectorStatusEnum
.Reserved
,
959 { send
: reservation
.connectorId
!== 0 }
963 public async removeReservation (
964 reservation
: Reservation
,
965 reason
: ReservationTerminationReason
967 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
968 const connector
= this.getConnectorStatus(reservation
.connectorId
)!
970 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
971 case ReservationTerminationReason
.TRANSACTION_STARTED
:
972 delete connector
.reservation
974 case ReservationTerminationReason
.RESERVATION_CANCELED
:
975 case ReservationTerminationReason
.REPLACE_EXISTING
:
976 case ReservationTerminationReason
.EXPIRED
:
977 await sendAndSetConnectorStatus(
979 reservation
.connectorId
,
980 ConnectorStatusEnum
.Available
,
982 { send
: reservation
.connectorId
!== 0 }
984 delete connector
.reservation
987 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
988 throw new BaseError(`Unknown reservation termination reason '${reason}'`)
992 public getReservationBy (
993 filterKey
: ReservationKey
,
994 value
: number | string
995 ): Reservation
| undefined {
997 for (const evseStatus
of this.evses
.values()) {
998 for (const connectorStatus
of evseStatus
.connectors
.values()) {
999 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
1000 return connectorStatus
.reservation
1005 for (const connectorStatus
of this.connectors
.values()) {
1006 if (connectorStatus
.reservation
?.[filterKey
] === value
) {
1007 return connectorStatus
.reservation
1013 public isConnectorReservable (
1014 reservationId
: number,
1016 connectorId
?: number
1018 const reservation
= this.getReservationBy('reservationId', reservationId
)
1019 const reservationExists
= reservation
!== undefined && !hasReservationExpired(reservation
)
1020 if (arguments.length
=== 1) {
1021 return !reservationExists
1022 } else if (arguments.length
> 1) {
1023 const userReservation
=
1024 idTag
!== undefined ? this.getReservationBy('idTag', idTag
) : undefined
1025 const userReservationExists
=
1026 userReservation
!== undefined && !hasReservationExpired(userReservation
)
1027 const notConnectorZero
= connectorId
=== undefined ? true : connectorId
> 0
1028 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0
1030 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
1036 private setIntervalFlushMessageBuffer (): void {
1037 if (this.flushMessageBufferSetInterval
== null) {
1038 this.flushMessageBufferSetInterval
= setInterval(() => {
1039 if (this.isWebSocketConnectionOpened() && this.inAcceptedState()) {
1040 this.flushMessageBuffer()
1042 if (this.messageBuffer
.size
=== 0) {
1043 this.clearIntervalFlushMessageBuffer()
1045 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
)
1049 private clearIntervalFlushMessageBuffer (): void {
1050 if (this.flushMessageBufferSetInterval
!= null) {
1051 clearInterval(this.flushMessageBufferSetInterval
)
1052 delete this.flushMessageBufferSetInterval
1056 private getNumberOfReservableConnectors (): number {
1057 let numberOfReservableConnectors
= 0
1058 if (this.hasEvses
) {
1059 for (const evseStatus
of this.evses
.values()) {
1060 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
)
1063 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
)
1065 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero()
1068 private getNumberOfReservationsOnConnectorZero (): number {
1070 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
!= null) ||
1071 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
!= null)
1078 private flushMessageBuffer (): void {
1079 if (this.messageBuffer
.size
> 0) {
1080 for (const message
of this.messageBuffer
.values()) {
1081 let beginId
: string | undefined
1082 let commandName
: RequestCommand
| undefined
1083 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
1084 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
1086 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
1087 beginId
= PerformanceStatistics
.beginMeasure(commandName
)
1089 this.wsConnection
?.send(message
, (error
?: Error) => {
1090 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1091 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!)
1092 if (error
== null) {
1094 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1096 )} OCPP message sent '${JSON.stringify(message)}'`
1098 this.messageBuffer
.delete(message
)
1101 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1103 )} OCPP message '${JSON.stringify(message)}' send failed:`,
1112 private getTemplateFromFile (): ChargingStationTemplate
| undefined {
1113 let template
: ChargingStationTemplate
| undefined
1115 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1116 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
)
1118 const measureId
= `${FileType.ChargingStationTemplate} read`
1119 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1120 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
1121 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1122 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1123 .update(JSON
.stringify(template
))
1125 this.sharedLRUCache
.setChargingStationTemplate(template
)
1126 this.templateFileHash
= template
.templateHash
1129 handleFileException(
1131 FileType
.ChargingStationTemplate
,
1132 error
as NodeJS
.ErrnoException
,
1139 private getStationInfoFromTemplate (): ChargingStationInfo
{
1140 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1141 const stationTemplate
= this.getTemplateFromFile()!
1142 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1143 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this)
1144 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
)
1145 if (stationTemplate
.Connectors
!= null) {
1146 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1148 const stationInfo
= stationTemplateToStationInfo(stationTemplate
)
1149 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
)
1150 stationInfo
.autoStart
= stationTemplate
.autoStart
?? true
1151 stationInfo
.templateName
= parse(this.templateFile
).name
1152 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
)
1153 stationInfo
.ocppVersion
= stationTemplate
.ocppVersion
?? OCPPVersion
.VERSION_16
1154 createSerialNumber(stationTemplate
, stationInfo
)
1155 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
)
1156 if (isNotEmptyArray(stationTemplate
.power
)) {
1157 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
)
1158 stationInfo
.maximumPower
=
1159 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1160 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1161 : stationTemplate
.power
[powerArrayRandomIndex
]
1163 stationInfo
.maximumPower
=
1164 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
1165 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1166 stationTemplate
.power
! * 1000
1167 : stationTemplate
.power
1169 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
)
1170 stationInfo
.firmwareVersionPattern
=
1171 stationTemplate
.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
1173 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1174 !new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
)
1177 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1179 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1182 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1189 stationTemplate
.firmwareUpgrade
?? {}
1191 stationInfo
.resetTime
=
1192 stationTemplate
.resetTime
!= null
1193 ? secondsToMilliseconds(stationTemplate
.resetTime
)
1194 : Constants
.DEFAULT_CHARGING_STATION_RESET_TIME
1198 private getStationInfoFromFile (
1199 stationInfoPersistentConfiguration
: boolean | undefined = Constants
.DEFAULT_STATION_INFO
1200 .stationInfoPersistentConfiguration
1201 ): ChargingStationInfo
| undefined {
1202 let stationInfo
: ChargingStationInfo
| undefined
1203 if (stationInfoPersistentConfiguration
=== true) {
1204 stationInfo
= this.getConfigurationFromFile()?.stationInfo
1205 if (stationInfo
!= null) {
1206 delete stationInfo
.infoHash
1207 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1208 if (stationInfo
.templateName
== null) {
1209 stationInfo
.templateName
= parse(this.templateFile
).name
1211 if (stationInfo
.autoStart
== null) {
1212 stationInfo
.autoStart
= true
1219 private getStationInfo (stationInfoPersistentConfiguration
?: boolean): ChargingStationInfo
{
1220 const stationInfoFromTemplate
= this.getStationInfoFromTemplate()
1221 stationInfoPersistentConfiguration
!= null &&
1222 (stationInfoFromTemplate
.stationInfoPersistentConfiguration
=
1223 stationInfoPersistentConfiguration
)
1224 const stationInfoFromFile
= this.getStationInfoFromFile(
1225 stationInfoFromTemplate
.stationInfoPersistentConfiguration
1228 // 1. charging station info from template
1229 // 2. charging station info from configuration file
1231 stationInfoFromFile
!= null &&
1232 stationInfoFromFile
.templateHash
=== stationInfoFromTemplate
.templateHash
1234 return { ...Constants
.DEFAULT_STATION_INFO
, ...stationInfoFromFile
}
1236 stationInfoFromFile
!= null &&
1237 propagateSerialNumber(
1238 this.getTemplateFromFile(),
1239 stationInfoFromFile
,
1240 stationInfoFromTemplate
1242 return { ...Constants
.DEFAULT_STATION_INFO
, ...stationInfoFromTemplate
}
1245 private saveStationInfo (): void {
1246 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1247 this.saveConfiguration()
1251 private handleUnsupportedVersion (version
: OCPPVersion
| undefined): void {
1252 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`
1253 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1254 throw new BaseError(errorMsg
)
1257 private initialize (options
?: ChargingStationOptions
): void {
1258 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1259 const stationTemplate
= this.getTemplateFromFile()!
1260 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
)
1261 this.configurationFile
= join(
1262 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1263 `${getHashId(this.index, stationTemplate)}.json`
1265 const stationConfiguration
= this.getConfigurationFromFile()
1267 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
.templateHash
&&
1268 (stationConfiguration
?.connectorsStatus
!= null || stationConfiguration
?.evsesStatus
!= null)
1270 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
)
1271 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
)
1273 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
)
1275 this.stationInfo
= this.getStationInfo(options
?.persistentConfiguration
)
1276 if (options
?.persistentConfiguration
!= null) {
1277 this.stationInfo
.ocppPersistentConfiguration
= options
.persistentConfiguration
1279 if (options
?.persistentConfiguration
!= null) {
1280 this.stationInfo
.automaticTransactionGeneratorPersistentConfiguration
=
1281 options
.persistentConfiguration
1283 if (options
?.autoRegister
!= null) {
1284 this.stationInfo
.autoRegister
= options
.autoRegister
1286 if (options
?.enableStatistics
!= null) {
1287 this.stationInfo
.enableStatistics
= options
.enableStatistics
1289 if (options
?.ocppStrictCompliance
!= null) {
1290 this.stationInfo
.ocppStrictCompliance
= options
.ocppStrictCompliance
1293 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1294 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1295 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1297 const patternGroup
=
1298 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1299 this.stationInfo
.firmwareVersion
.split('.').length
1300 const match
= new RegExp(this.stationInfo
.firmwareVersionPattern
)
1301 .exec(this.stationInfo
.firmwareVersion
)
1302 ?.slice(1, patternGroup
+ 1)
1303 if (match
!= null) {
1304 const patchLevelIndex
= match
.length
- 1
1305 match
[patchLevelIndex
] = (
1306 convertToInt(match
[patchLevelIndex
]) +
1307 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1308 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1310 this.stationInfo
.firmwareVersion
= match
.join('.')
1313 this.saveStationInfo()
1314 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl()
1315 if (this.stationInfo
.enableStatistics
=== true) {
1316 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1317 this.stationInfo
.hashId
,
1318 this.stationInfo
.chargingStationId
,
1319 this.configuredSupervisionUrl
1322 const bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
)
1323 if (bootNotificationRequest
== null) {
1324 const errorMsg
= 'Error while creating boot notification request'
1325 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1326 throw new BaseError(errorMsg
)
1328 this.bootNotificationRequest
= bootNotificationRequest
1329 this.powerDivider
= this.getPowerDivider()
1330 // OCPP configuration
1331 this.ocppConfiguration
= this.getOcppConfiguration(options
?.persistentConfiguration
)
1332 this.initializeOcppConfiguration()
1333 this.initializeOcppServices()
1334 if (this.stationInfo
.autoRegister
=== true) {
1335 this.bootNotificationResponse
= {
1336 currentTime
: new Date(),
1337 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1338 status: RegistrationStatusEnumType
.ACCEPTED
1343 private initializeOcppServices (): void {
1344 const ocppVersion
= this.stationInfo
?.ocppVersion
1345 switch (ocppVersion
) {
1346 case OCPPVersion
.VERSION_16
:
1347 this.ocppIncomingRequestService
=
1348 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>()
1349 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1350 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1353 case OCPPVersion
.VERSION_20
:
1354 case OCPPVersion
.VERSION_201
:
1355 this.ocppIncomingRequestService
=
1356 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>()
1357 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1358 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1362 this.handleUnsupportedVersion(ocppVersion
)
1367 private initializeOcppConfiguration (): void {
1368 if (getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
) == null) {
1369 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0')
1371 if (getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
) == null) {
1372 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false })
1375 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1376 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1377 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) == null
1379 addConfigurationKey(
1381 this.stationInfo
.supervisionUrlOcppKey
,
1382 this.configuredSupervisionUrl
.href
,
1386 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1387 isNotEmptyString(this.stationInfo
.supervisionUrlOcppKey
) &&
1388 getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
) != null
1390 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
, { save
: false })
1393 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1394 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) == null
1396 addConfigurationKey(
1398 this.stationInfo
.amperageLimitationOcppKey
,
1400 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1401 (this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)).toString()
1404 if (getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
) == null) {
1405 addConfigurationKey(
1407 StandardParametersKey
.SupportedFeatureProfiles
,
1408 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1411 addConfigurationKey(
1413 StandardParametersKey
.NumberOfConnectors
,
1414 this.getNumberOfConnectors().toString(),
1418 if (getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
) == null) {
1419 addConfigurationKey(
1421 StandardParametersKey
.MeterValuesSampledData
,
1422 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1425 if (getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
) == null) {
1426 const connectorsPhaseRotation
: string[] = []
1427 if (this.hasEvses
) {
1428 for (const evseStatus
of this.evses
.values()) {
1429 for (const connectorId
of evseStatus
.connectors
.keys()) {
1430 connectorsPhaseRotation
.push(
1431 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1432 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1437 for (const connectorId
of this.connectors
.keys()) {
1438 connectorsPhaseRotation
.push(
1439 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1440 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!
1444 addConfigurationKey(
1446 StandardParametersKey
.ConnectorPhaseRotation
,
1447 connectorsPhaseRotation
.toString()
1450 if (getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
) == null) {
1451 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true')
1454 getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) == null &&
1455 hasFeatureProfile(this, SupportedFeatureProfiles
.LocalAuthListManagement
) === true
1457 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false')
1459 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) == null) {
1460 addConfigurationKey(
1462 StandardParametersKey
.ConnectionTimeOut
,
1463 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1466 this.saveOcppConfiguration()
1469 private initializeConnectorsOrEvsesFromFile (configuration
: ChargingStationConfiguration
): void {
1470 if (configuration
.connectorsStatus
!= null && configuration
.evsesStatus
== null) {
1471 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1472 this.connectors
.set(connectorId
, clone
<ConnectorStatus
>(connectorStatus
))
1474 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
== null) {
1475 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1476 const evseStatus
= clone
<EvseStatusConfiguration
>(evseStatusConfiguration
)
1477 delete evseStatus
.connectorsStatus
1478 this.evses
.set(evseId
, {
1479 ...(evseStatus
as EvseStatus
),
1480 connectors
: new Map
<number, ConnectorStatus
>(
1481 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1482 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1489 } else if (configuration
.evsesStatus
!= null && configuration
.connectorsStatus
!= null) {
1490 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`
1491 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1492 throw new BaseError(errorMsg
)
1494 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`
1495 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1496 throw new BaseError(errorMsg
)
1500 private initializeConnectorsOrEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1501 if (stationTemplate
.Connectors
!= null && stationTemplate
.Evses
== null) {
1502 this.initializeConnectorsFromTemplate(stationTemplate
)
1503 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
== null) {
1504 this.initializeEvsesFromTemplate(stationTemplate
)
1505 } else if (stationTemplate
.Evses
!= null && stationTemplate
.Connectors
!= null) {
1506 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`
1507 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1508 throw new BaseError(errorMsg
)
1510 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`
1511 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1512 throw new BaseError(errorMsg
)
1516 private initializeConnectorsFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1517 if (stationTemplate
.Connectors
== null && this.connectors
.size
=== 0) {
1518 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`
1519 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1520 throw new BaseError(errorMsg
)
1522 if (stationTemplate
.Connectors
?.[0] == null) {
1524 `${this.logPrefix()} Charging station information from template ${
1526 } with no connector id 0 configuration`
1529 if (stationTemplate
.Connectors
!= null) {
1530 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1531 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
)
1532 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1534 `${JSON.stringify(stationTemplate.Connectors)}${configuredMaxConnectors.toString()}`
1537 const connectorsConfigChanged
=
1538 this.connectors
.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
1539 if (this.connectors
.size
=== 0 || connectorsConfigChanged
) {
1540 connectorsConfigChanged
&& this.connectors
.clear()
1541 this.connectorsConfigurationHash
= connectorsConfigHash
1542 if (templateMaxConnectors
> 0) {
1543 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1545 connectorId
=== 0 &&
1546 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1547 (stationTemplate
.Connectors
[connectorId
] == null ||
1548 !this.getUseConnectorId0(stationTemplate
))
1552 const templateConnectorId
=
1553 connectorId
> 0 && stationTemplate
.randomConnectors
=== true
1554 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1556 const connectorStatus
= stationTemplate
.Connectors
[templateConnectorId
]
1557 checkStationInfoConnectorStatus(
1558 templateConnectorId
,
1563 this.connectors
.set(connectorId
, clone
<ConnectorStatus
>(connectorStatus
))
1565 initializeConnectorsMapStatus(this.connectors
, this.logPrefix())
1566 this.saveConnectorsStatus()
1569 `${this.logPrefix()} Charging station information from template ${
1571 } with no connectors configuration defined, cannot create connectors`
1577 `${this.logPrefix()} Charging station information from template ${
1579 } with no connectors configuration defined, using already defined connectors`
1584 private initializeEvsesFromTemplate (stationTemplate
: ChargingStationTemplate
): void {
1585 if (stationTemplate
.Evses
== null && this.evses
.size
=== 0) {
1586 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`
1587 logger
.error(`${this.logPrefix()} ${errorMsg}`)
1588 throw new BaseError(errorMsg
)
1590 if (stationTemplate
.Evses
?.[0] == null) {
1592 `${this.logPrefix()} Charging station information from template ${
1594 } with no evse id 0 configuration`
1597 if (stationTemplate
.Evses
?.[0]?.Connectors
[0] == null) {
1599 `${this.logPrefix()} Charging station information from template ${
1601 } with evse id 0 with no connector id 0 configuration`
1604 if (Object.keys(stationTemplate
.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1606 `${this.logPrefix()} Charging station information from template ${
1608 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`
1611 if (stationTemplate
.Evses
!= null) {
1612 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1613 .update(JSON
.stringify(stationTemplate
.Evses
))
1615 const evsesConfigChanged
=
1616 this.evses
.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
1617 if (this.evses
.size
=== 0 || evsesConfigChanged
) {
1618 evsesConfigChanged
&& this.evses
.clear()
1619 this.evsesConfigurationHash
= evsesConfigHash
1620 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
.Evses
)
1621 if (templateMaxEvses
> 0) {
1622 for (const evseKey
in stationTemplate
.Evses
) {
1623 const evseId
= convertToInt(evseKey
)
1624 this.evses
.set(evseId
, {
1625 connectors
: buildConnectorsMap(
1626 stationTemplate
.Evses
[evseKey
].Connectors
,
1630 availability
: AvailabilityType
.Operative
1632 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1633 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix())
1635 this.saveEvsesStatus()
1638 `${this.logPrefix()} Charging station information from template ${
1640 } with no evses configuration defined, cannot create evses`
1646 `${this.logPrefix()} Charging station information from template ${
1648 } with no evses configuration defined, using already defined evses`
1653 private getConfigurationFromFile (): ChargingStationConfiguration
| undefined {
1654 let configuration
: ChargingStationConfiguration
| undefined
1655 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1657 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1658 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1659 this.configurationFileHash
1662 const measureId
= `${FileType.ChargingStationConfiguration} read`
1663 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1664 configuration
= JSON
.parse(
1665 readFileSync(this.configurationFile
, 'utf8')
1666 ) as ChargingStationConfiguration
1667 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1668 this.sharedLRUCache
.setChargingStationConfiguration(configuration
)
1669 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1670 this.configurationFileHash
= configuration
.configurationHash
!
1673 handleFileException(
1674 this.configurationFile
,
1675 FileType
.ChargingStationConfiguration
,
1676 error
as NodeJS
.ErrnoException
,
1681 return configuration
1684 private saveAutomaticTransactionGeneratorConfiguration (): void {
1685 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1686 this.saveConfiguration()
1690 private saveConnectorsStatus (): void {
1691 this.saveConfiguration()
1694 private saveEvsesStatus (): void {
1695 this.saveConfiguration()
1698 private saveConfiguration (): void {
1699 if (isNotEmptyString(this.configurationFile
)) {
1701 if (!existsSync(dirname(this.configurationFile
))) {
1702 mkdirSync(dirname(this.configurationFile
), { recursive
: true })
1704 const configurationFromFile
= this.getConfigurationFromFile()
1705 let configurationData
: ChargingStationConfiguration
=
1706 configurationFromFile
!= null
1707 ? clone
<ChargingStationConfiguration
>(configurationFromFile
)
1709 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1710 configurationData
.stationInfo
= this.stationInfo
1712 delete configurationData
.stationInfo
1715 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1716 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1718 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
1720 delete configurationData
.configurationKey
1722 configurationData
= merge
<ChargingStationConfiguration
>(
1724 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1726 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
!== true) {
1727 delete configurationData
.automaticTransactionGenerator
1729 if (this.connectors
.size
> 0) {
1730 configurationData
.connectorsStatus
= buildConnectorsStatus(this)
1732 delete configurationData
.connectorsStatus
1734 if (this.evses
.size
> 0) {
1735 configurationData
.evsesStatus
= buildEvsesStatus(this)
1737 delete configurationData
.evsesStatus
1739 delete configurationData
.configurationHash
1740 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1743 stationInfo
: configurationData
.stationInfo
,
1744 configurationKey
: configurationData
.configurationKey
,
1745 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1746 ...(this.connectors
.size
> 0 && {
1747 connectorsStatus
: configurationData
.connectorsStatus
1749 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
})
1750 } satisfies ChargingStationConfiguration
)
1753 if (this.configurationFileHash
!== configurationHash
) {
1754 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1755 configurationData
.configurationHash
= configurationHash
1756 const measureId
= `${FileType.ChargingStationConfiguration} write`
1757 const beginId
= PerformanceStatistics
.beginMeasure(measureId
)
1759 this.configurationFile
,
1760 JSON
.stringify(configurationData
, undefined, 2),
1763 PerformanceStatistics
.endMeasure(measureId
, beginId
)
1764 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
)
1765 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
)
1766 this.configurationFileHash
= configurationHash
1768 handleFileException(
1769 this.configurationFile
,
1770 FileType
.ChargingStationConfiguration
,
1771 error
as NodeJS
.ErrnoException
,
1777 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1778 this.configurationFile
1783 handleFileException(
1784 this.configurationFile
,
1785 FileType
.ChargingStationConfiguration
,
1786 error
as NodeJS
.ErrnoException
,
1792 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1797 private getOcppConfigurationFromTemplate (): ChargingStationOcppConfiguration
| undefined {
1798 return this.getTemplateFromFile()?.Configuration
1801 private getOcppConfigurationFromFile (
1802 ocppPersistentConfiguration
?: boolean
1803 ): ChargingStationOcppConfiguration
| undefined {
1804 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
1805 if (ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1806 return { configurationKey
}
1811 private getOcppConfiguration (
1812 ocppPersistentConfiguration
: boolean | undefined = Constants
.DEFAULT_STATION_INFO
1813 .ocppPersistentConfiguration
1814 ): ChargingStationOcppConfiguration
| undefined {
1815 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1816 this.getOcppConfigurationFromFile(ocppPersistentConfiguration
)
1817 if (ocppConfiguration
== null) {
1818 ocppConfiguration
= this.getOcppConfigurationFromTemplate()
1820 return ocppConfiguration
1823 private async onOpen (): Promise
<void> {
1824 if (this.isWebSocketConnectionOpened()) {
1826 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} succeeded`
1828 let registrationRetryCount
= 0
1829 if (!this.isRegistered()) {
1830 // Send BootNotification
1832 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1833 BootNotificationRequest
,
1834 BootNotificationResponse
1835 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1836 skipBufferingOnError
: true
1838 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1839 if (this.bootNotificationResponse
?.currentTime
!= null) {
1840 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1841 this.bootNotificationResponse
.currentTime
= convertToDate(
1842 this.bootNotificationResponse
.currentTime
1845 if (!this.isRegistered()) {
1846 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
1848 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1849 this.bootNotificationResponse
?.interval
!= null
1850 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1851 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1855 !this.isRegistered() &&
1856 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1857 (registrationRetryCount
<= this.stationInfo
!.registrationMaxRetries
! ||
1858 this.stationInfo
?.registrationMaxRetries
=== -1)
1861 if (this.isRegistered()) {
1862 this.emit(ChargingStationEvents
.registered
)
1863 if (this.inAcceptedState()) {
1864 this.emit(ChargingStationEvents
.accepted
)
1867 if (this.inRejectedState()) {
1868 this.emit(ChargingStationEvents
.rejected
)
1871 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${
1872 this.stationInfo?.registrationMaxRetries
1876 this.wsConnectionRetryCount
= 0
1877 this.emit(ChargingStationEvents
.updated
)
1880 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} failed`
1885 private onClose (code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): void {
1886 this.emit(ChargingStationEvents
.disconnected
)
1889 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1890 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1892 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1894 )}' and reason '${reason.toString()}'`
1896 this.wsConnectionRetryCount
= 0
1901 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1903 )}' and reason '${reason.toString()}'`
1906 this.reconnect().catch(error
=>
1907 logger
.error(`${this.logPrefix()} Error while reconnecting:`, error
)
1911 this.emit(ChargingStationEvents
.updated
)
1914 private getCachedRequest (
1915 messageType
: MessageType
| undefined,
1917 ): CachedRequest
| undefined {
1918 const cachedRequest
= this.requests
.get(messageId
)
1919 if (Array.isArray(cachedRequest
)) {
1920 return cachedRequest
1922 throw new OCPPError(
1923 ErrorType
.PROTOCOL_ERROR
,
1924 `Cached request for message id ${messageId} ${getMessageTypeString(
1926 )} is not an array`,
1932 private async handleIncomingMessage (request
: IncomingRequest
): Promise
<void> {
1933 const [messageType
, messageId
, commandName
, commandPayload
] = request
1934 if (this.stationInfo
?.enableStatistics
=== true) {
1935 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
)
1938 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1942 // Process the message
1943 await this.ocppIncomingRequestService
.incomingRequestHandler(
1949 this.emit(ChargingStationEvents
.updated
)
1952 private handleResponseMessage (response
: Response
): void {
1953 const [messageType
, messageId
, commandPayload
] = response
1954 if (!this.requests
.has(messageId
)) {
1956 throw new OCPPError(
1957 ErrorType
.INTERNAL_ERROR
,
1958 `Response for unknown message id ${messageId}`,
1964 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1965 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1970 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1974 responseCallback(commandPayload
, requestPayload
)
1977 private handleErrorMessage (errorResponse
: ErrorResponse
): void {
1978 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
1979 if (!this.requests
.has(messageId
)) {
1981 throw new OCPPError(
1982 ErrorType
.INTERNAL_ERROR
,
1983 `Error response for unknown message id ${messageId}`,
1985 { errorType
, errorMessage
, errorDetails
}
1988 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1989 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
1991 `${this.logPrefix()} << Command '${requestCommandName}' received error response payload: ${JSON.stringify(
1995 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
))
1998 private async onMessage (data
: RawData
): Promise
<void> {
1999 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined
2000 let messageType
: MessageType
| undefined
2001 let errorMsg
: string
2003 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2004 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
2005 if (Array.isArray(request
)) {
2006 [messageType
] = request
2007 // Check the type of message
2008 switch (messageType
) {
2010 case MessageType
.CALL_MESSAGE
:
2011 await this.handleIncomingMessage(request
as IncomingRequest
)
2014 case MessageType
.CALL_RESULT_MESSAGE
:
2015 this.handleResponseMessage(request
as Response
)
2018 case MessageType
.CALL_ERROR_MESSAGE
:
2019 this.handleErrorMessage(request
as ErrorResponse
)
2023 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2024 errorMsg
= `Wrong message type ${messageType}`
2025 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2026 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
)
2029 throw new OCPPError(
2030 ErrorType
.PROTOCOL_ERROR
,
2031 'Incoming message is not an array',
2039 if (!Array.isArray(request
)) {
2040 logger
.error(`${this.logPrefix()} Incoming message '${request}' parsing error:`, error
)
2043 let commandName
: IncomingRequestCommand
| undefined
2044 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined
2045 let errorCallback
: ErrorCallback
2046 const [, messageId
] = request
2047 switch (messageType
) {
2048 case MessageType
.CALL_MESSAGE
:
2049 [, , commandName
] = request
as IncomingRequest
2051 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
)
2053 case MessageType
.CALL_RESULT_MESSAGE
:
2054 case MessageType
.CALL_ERROR_MESSAGE
:
2055 if (this.requests
.has(messageId
)) {
2056 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2057 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!
2058 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2059 errorCallback(error
as OCPPError
, false)
2061 // Remove the request from the cache in case of error at response handling
2062 this.requests
.delete(messageId
)
2066 if (!(error
instanceof OCPPError
)) {
2068 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2069 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2070 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2071 }' message '${data.toString()}' handling is not an OCPPError:`,
2076 `${this.logPrefix()} Incoming OCPP command '${
2077 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2078 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2079 }' message '${data.toString()}'${
2080 this.requests.has(messageId)
2081 ? ` matching cached request
'${JSON.stringify(this.getCachedRequest(messageType, messageId))}'`
2083 } processing error:`,
2089 private onPing (): void {
2090 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`)
2093 private onPong (): void {
2094 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`)
2097 private onError (error
: WSError
): void {
2098 this.closeWSConnection()
2099 logger
.error(`${this.logPrefix()} WebSocket error:`, error
)
2102 private getEnergyActiveImportRegister (
2103 connectorStatus
: ConnectorStatus
| undefined,
2106 if (this.stationInfo
?.meteringPerTransaction
=== true) {
2109 ? connectorStatus
?.transactionEnergyActiveImportRegisterValue
!= null
2110 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
)
2112 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2117 ? connectorStatus
?.energyActiveImportRegisterValue
!= null
2118 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
)
2120 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2124 private getUseConnectorId0 (stationTemplate
?: ChargingStationTemplate
): boolean {
2125 return stationTemplate
?.useConnectorId0
?? true
2128 private async stopRunningTransactions (reason
?: StopTransactionReason
): Promise
<void> {
2129 if (this.hasEvses
) {
2130 for (const [evseId
, evseStatus
] of this.evses
) {
2134 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2135 if (connectorStatus
.transactionStarted
=== true) {
2136 await this.stopTransactionOnConnector(connectorId
, reason
)
2141 for (const connectorId
of this.connectors
.keys()) {
2142 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2143 await this.stopTransactionOnConnector(connectorId
, reason
)
2150 private getConnectionTimeout (): number {
2151 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) != null) {
2152 return convertToInt(
2153 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)?.value
??
2154 Constants
.DEFAULT_CONNECTION_TIMEOUT
2157 return Constants
.DEFAULT_CONNECTION_TIMEOUT
2160 private getPowerDivider (): number {
2161 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()
2162 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2163 powerDivider
= this.getNumberOfRunningTransactions()
2168 private getMaximumAmperage (stationInfo
?: ChargingStationInfo
): number | undefined {
2169 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2170 const maximumPower
= (stationInfo
?? this.stationInfo
!).maximumPower
!
2171 switch (this.getCurrentOutType(stationInfo
)) {
2172 case CurrentType
.AC
:
2173 return ACElectricUtils
.amperagePerPhaseFromPower(
2174 this.getNumberOfPhases(stationInfo
),
2175 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2176 this.getVoltageOut(stationInfo
)
2178 case CurrentType
.DC
:
2179 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
))
2183 private getCurrentOutType (stationInfo
?: ChargingStationInfo
): CurrentType
{
2184 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2185 return (stationInfo
?? this.stationInfo
!).currentOutType
?? CurrentType
.AC
2188 private getVoltageOut (stationInfo
?: ChargingStationInfo
): Voltage
{
2190 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2191 (stationInfo
?? this.stationInfo
!).voltageOut
??
2192 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2196 private getAmperageLimitation (): number | undefined {
2198 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2199 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
) != null
2202 convertToInt(getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
)?.value
) /
2203 getAmperageLimitationUnitDivider(this.stationInfo
)
2208 private async startMessageSequence (ATGStopAbsoluteDuration
?: boolean): Promise
<void> {
2209 if (this.stationInfo
?.autoRegister
=== true) {
2210 await this.ocppRequestService
.requestHandler
<
2211 BootNotificationRequest
,
2212 BootNotificationResponse
2213 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2214 skipBufferingOnError
: true
2217 // Start WebSocket ping
2218 this.startWebSocketPing()
2220 this.startHeartbeat()
2221 // Initialize connectors status
2222 if (this.hasEvses
) {
2223 for (const [evseId
, evseStatus
] of this.evses
) {
2225 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2226 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
)
2227 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
, evseId
)
2232 for (const connectorId
of this.connectors
.keys()) {
2233 if (connectorId
> 0) {
2234 const connectorBootStatus
= getBootConnectorStatus(
2237 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2238 this.getConnectorStatus(connectorId
)!
2240 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
)
2244 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2245 await this.ocppRequestService
.requestHandler
<
2246 FirmwareStatusNotificationRequest
,
2247 FirmwareStatusNotificationResponse
2248 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2249 status: FirmwareStatus
.Installed
2251 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
2255 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2256 this.startAutomaticTransactionGenerator(undefined, ATGStopAbsoluteDuration
)
2258 this.flushMessageBuffer()
2261 private internalStopMessageSequence (): void {
2262 // Stop WebSocket ping
2263 this.stopWebSocketPing()
2265 this.stopHeartbeat()
2267 if (this.automaticTransactionGenerator
?.started
=== true) {
2268 this.stopAutomaticTransactionGenerator()
2272 private async stopMessageSequence (
2273 reason
?: StopTransactionReason
,
2274 stopTransactions
?: boolean
2276 this.internalStopMessageSequence()
2277 // Stop ongoing transactions
2278 stopTransactions
=== true && (await this.stopRunningTransactions(reason
))
2279 if (this.hasEvses
) {
2280 for (const [evseId
, evseStatus
] of this.evses
) {
2282 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2283 await sendAndSetConnectorStatus(
2286 ConnectorStatusEnum
.Unavailable
,
2289 delete connectorStatus
.status
2294 for (const connectorId
of this.connectors
.keys()) {
2295 if (connectorId
> 0) {
2296 await sendAndSetConnectorStatus(this, connectorId
, ConnectorStatusEnum
.Unavailable
)
2297 delete this.getConnectorStatus(connectorId
)?.status
2303 private startWebSocketPing (): void {
2304 const webSocketPingInterval
=
2305 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) != null
2307 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
2310 if (webSocketPingInterval
> 0 && this.wsPingSetInterval
== null) {
2311 this.wsPingSetInterval
= setInterval(() => {
2312 if (this.isWebSocketConnectionOpened()) {
2313 this.wsConnection
?.ping()
2315 }, secondsToMilliseconds(webSocketPingInterval
))
2317 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2318 webSocketPingInterval
2321 } else if (this.wsPingSetInterval
!= null) {
2323 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2324 webSocketPingInterval
2329 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2334 private stopWebSocketPing (): void {
2335 if (this.wsPingSetInterval
!= null) {
2336 clearInterval(this.wsPingSetInterval
)
2337 delete this.wsPingSetInterval
2341 private getConfiguredSupervisionUrl (): URL
{
2342 let configuredSupervisionUrl
: string
2343 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls()
2344 if (isNotEmptyArray(supervisionUrls
)) {
2345 let configuredSupervisionUrlIndex
: number
2346 switch (Configuration
.getSupervisionUrlDistribution()) {
2347 case SupervisionUrlDistribution
.RANDOM
:
2348 configuredSupervisionUrlIndex
= Math.floor(secureRandom() * supervisionUrls
.length
)
2350 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2351 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2353 !Object.values(SupervisionUrlDistribution
).includes(
2354 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2355 Configuration
.getSupervisionUrlDistribution()!
2358 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2359 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2360 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2363 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
2366 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
]
2368 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2369 configuredSupervisionUrl
= supervisionUrls
!
2371 if (isNotEmptyString(configuredSupervisionUrl
)) {
2372 return new URL(configuredSupervisionUrl
)
2374 const errorMsg
= 'No supervision url(s) configured'
2375 logger
.error(`${this.logPrefix()} ${errorMsg}`)
2376 throw new BaseError(errorMsg
)
2379 private stopHeartbeat (): void {
2380 if (this.heartbeatSetInterval
!= null) {
2381 clearInterval(this.heartbeatSetInterval
)
2382 delete this.heartbeatSetInterval
2386 private terminateWSConnection (): void {
2387 if (this.isWebSocketConnectionOpened()) {
2388 this.wsConnection
?.terminate()
2389 this.wsConnection
= null
2393 private async reconnect (): Promise
<void> {
2395 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2396 this.wsConnectionRetryCount
< this.stationInfo
!.autoReconnectMaxRetries
! ||
2397 this.stationInfo
?.autoReconnectMaxRetries
=== -1
2399 this.wsConnectionRetried
= true
2400 ++this.wsConnectionRetryCount
2401 const reconnectDelay
=
2402 this.stationInfo
?.reconnectExponentialDelay
=== true
2403 ? exponentialDelay(this.wsConnectionRetryCount
)
2404 : secondsToMilliseconds(this.getConnectionTimeout())
2405 const reconnectDelayWithdraw
= 1000
2406 const reconnectTimeout
=
2407 reconnectDelay
- reconnectDelayWithdraw
> 0 ? reconnectDelay
- reconnectDelayWithdraw
: 0
2409 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2412 )}ms, timeout ${reconnectTimeout}ms`
2414 await sleep(reconnectDelay
)
2416 `${this.logPrefix()} WebSocket connection retry #${this.wsConnectionRetryCount.toString()}`
2418 this.openWSConnection(
2420 handshakeTimeout
: reconnectTimeout
2422 { closeOpened
: true }
2424 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2426 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2427 this.wsConnectionRetryCount
2428 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`