1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { createHash
} from
'node:crypto';
4 import { EventEmitter
} from
'node:events';
5 import { type FSWatcher
, existsSync
, mkdirSync
, readFileSync
, writeFileSync
} from
'node:fs';
6 import { dirname
, join
} from
'node:path';
7 import { URL
} from
'node:url';
8 import { parentPort
} from
'node:worker_threads';
10 import { millisecondsToSeconds
, secondsToMilliseconds
} from
'date-fns';
11 import merge from
'just-merge';
12 import { type RawData
, WebSocket
} from
'ws';
14 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
15 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
18 deleteConfigurationKey
,
20 setConfigurationKeyValue
,
21 } from
'./ConfigurationKeyUtils';
26 checkConnectorsConfiguration
,
27 checkStationInfoConnectorStatus
,
29 createBootNotificationRequest
,
31 getAmperageLimitationUnitDivider
,
32 getBootConnectorStatus
,
33 getChargingStationConnectorChargingProfilesPowerLimit
,
39 getNumberOfReservableConnectors
,
40 getPhaseRotationValue
,
41 hasReservationExpired
,
42 initializeConnectorsMapStatus
,
43 propagateSerialNumber
,
44 stationTemplateToStationInfo
,
45 warnTemplateKeysDeprecation
,
47 import { IdTagsCache
} from
'./IdTagsCache';
49 OCPP16IncomingRequestService
,
51 OCPP16ResponseService
,
53 OCPP20IncomingRequestService
,
55 OCPP20ResponseService
,
56 type OCPPIncomingRequestService
,
57 type OCPPRequestService
,
60 import { SharedLRUCache
} from
'./SharedLRUCache';
61 import { BaseError
, OCPPError
} from
'../exception';
62 import { PerformanceStatistics
} from
'../performance';
64 type AutomaticTransactionGeneratorConfiguration
,
66 type BootNotificationRequest
,
67 type BootNotificationResponse
,
69 type ChargingStationConfiguration
,
70 ChargingStationEvents
,
71 type ChargingStationInfo
,
72 type ChargingStationOcppConfiguration
,
73 type ChargingStationTemplate
,
81 type EvseStatusConfiguration
,
84 type FirmwareStatusNotificationRequest
,
85 type FirmwareStatusNotificationResponse
,
87 type HeartbeatRequest
,
88 type HeartbeatResponse
,
90 type IncomingRequestCommand
,
95 type MeterValuesRequest
,
96 type MeterValuesResponse
,
100 RegistrationStatusEnumType
,
104 ReservationTerminationReason
,
106 StandardParametersKey
,
108 type StatusNotificationRequest
,
109 type StatusNotificationResponse
,
110 StopTransactionReason
,
111 type StopTransactionRequest
,
112 type StopTransactionResponse
,
113 SupervisionUrlDistribution
,
114 SupportedFeatureProfiles
,
118 WebSocketCloseEventStatusCode
,
128 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
129 buildConnectorsStatus
,
138 formatDurationMilliSeconds
,
139 formatDurationSeconds
,
141 getWebSocketCloseEventStatusString
,
157 export class ChargingStation
extends EventEmitter
{
158 public readonly index
: number;
159 public readonly templateFile
: string;
160 public stationInfo
!: ChargingStationInfo
;
161 public started
: boolean;
162 public starting
: boolean;
163 public idTagsCache
: IdTagsCache
;
164 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
165 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
166 public wsConnection
: WebSocket
| null;
167 public readonly connectors
: Map
<number, ConnectorStatus
>;
168 public readonly evses
: Map
<number, EvseStatus
>;
169 public readonly requests
: Map
<string, CachedRequest
>;
170 public performanceStatistics
!: PerformanceStatistics
| undefined;
171 public heartbeatSetInterval
?: NodeJS
.Timeout
;
172 public ocppRequestService
!: OCPPRequestService
;
173 public bootNotificationRequest
!: BootNotificationRequest
;
174 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
175 public powerDivider
!: number;
176 private stopping
: boolean;
177 private configurationFile
!: string;
178 private configurationFileHash
!: string;
179 private connectorsConfigurationHash
!: string;
180 private evsesConfigurationHash
!: string;
181 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
;
182 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
183 private readonly messageBuffer
: Set
<string>;
184 private configuredSupervisionUrl
!: URL
;
185 private autoReconnectRetryCount
: number;
186 private templateFileWatcher
!: FSWatcher
| undefined;
187 private templateFileHash
!: string;
188 private readonly sharedLRUCache
: SharedLRUCache
;
189 private webSocketPingSetInterval
?: NodeJS
.Timeout
;
190 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
191 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
;
193 constructor(index
: number, templateFile
: string) {
195 this.started
= false;
196 this.starting
= false;
197 this.stopping
= false;
198 this.wsConnection
= null;
199 this.autoReconnectRetryCount
= 0;
201 this.templateFile
= templateFile
;
202 this.connectors
= new Map
<number, ConnectorStatus
>();
203 this.evses
= new Map
<number, EvseStatus
>();
204 this.requests
= new Map
<string, CachedRequest
>();
205 this.messageBuffer
= new Set
<string>();
206 this.sharedLRUCache
= SharedLRUCache
.getInstance();
207 this.idTagsCache
= IdTagsCache
.getInstance();
208 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
210 this.on(ChargingStationEvents
.started
, () => {
211 parentPort
?.postMessage(buildStartedMessage(this));
213 this.on(ChargingStationEvents
.stopped
, () => {
214 parentPort
?.postMessage(buildStoppedMessage(this));
216 this.on(ChargingStationEvents
.updated
, () => {
217 parentPort
?.postMessage(buildUpdatedMessage(this));
223 public get
hasEvses(): boolean {
224 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
227 private get
wsConnectionUrl(): URL
{
230 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
231 isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) &&
232 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)?.value)
233 ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)!.value
234 : this.configuredSupervisionUrl.href
235 }/${this.stationInfo.chargingStationId}`,
239 public logPrefix
= (): string => {
240 if (isNotEmptyString(this?.stationInfo
?.chargingStationId
)) {
241 return logPrefix(` ${this?.stationInfo?.chargingStationId} |`);
243 let stationTemplate
: ChargingStationTemplate
| undefined;
245 stationTemplate
= JSON
.parse(
246 readFileSync(this.templateFile
, 'utf8'),
247 ) as ChargingStationTemplate
;
249 stationTemplate
= undefined;
251 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`);
254 public hasIdTags(): boolean {
255 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)!));
258 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number {
259 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
260 switch (this.getCurrentOutType(stationInfo
)) {
262 return localStationInfo
.numberOfPhases
?? 3;
268 public isWebSocketConnectionOpened(): boolean {
269 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
272 public inUnknownState(): boolean {
273 return isNullOrUndefined(this?.bootNotificationResponse
?.status);
276 public inPendingState(): boolean {
277 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
280 public inAcceptedState(): boolean {
281 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
284 public inRejectedState(): boolean {
285 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
288 public isRegistered(): boolean {
290 this.inUnknownState() === false &&
291 (this.inAcceptedState() === true || this.inPendingState() === true)
295 public isChargingStationAvailable(): boolean {
296 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
299 public hasConnector(connectorId
: number): boolean {
301 for (const evseStatus
of this.evses
.values()) {
302 if (evseStatus
.connectors
.has(connectorId
)) {
308 return this.connectors
.has(connectorId
);
311 public isConnectorAvailable(connectorId
: number): boolean {
314 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
318 public getNumberOfConnectors(): number {
320 let numberOfConnectors
= 0;
321 for (const [evseId
, evseStatus
] of this.evses
) {
323 numberOfConnectors
+= evseStatus
.connectors
.size
;
326 return numberOfConnectors
;
328 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
331 public getNumberOfEvses(): number {
332 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
335 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
337 for (const evseStatus
of this.evses
.values()) {
338 if (evseStatus
.connectors
.has(connectorId
)) {
339 return evseStatus
.connectors
.get(connectorId
);
344 return this.connectors
.get(connectorId
);
347 public getConnectorMaximumAvailablePower(connectorId
: number): number {
348 let connectorAmperageLimitationPowerLimit
: number | undefined;
350 !isNullOrUndefined(this.getAmperageLimitation()) &&
351 this.getAmperageLimitation()! < this.stationInfo
.maximumAmperage
!
353 connectorAmperageLimitationPowerLimit
=
354 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
355 ? ACElectricUtils
.powerTotal(
356 this.getNumberOfPhases(),
357 this.stationInfo
.voltageOut
!,
358 this.getAmperageLimitation()! *
359 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
361 : DCElectricUtils
.power(this.stationInfo
.voltageOut
!, this.getAmperageLimitation()!)) /
364 const connectorMaximumPower
= this.stationInfo
.maximumPower
! / this.powerDivider
;
365 const connectorChargingProfilesPowerLimit
=
366 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
368 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
369 isNaN(connectorAmperageLimitationPowerLimit
!)
371 : connectorAmperageLimitationPowerLimit
!,
372 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!,
376 public getTransactionIdTag(transactionId
: number): string | undefined {
378 for (const evseStatus
of this.evses
.values()) {
379 for (const connectorStatus
of evseStatus
.connectors
.values()) {
380 if (connectorStatus
.transactionId
=== transactionId
) {
381 return connectorStatus
.transactionIdTag
;
386 for (const connectorId
of this.connectors
.keys()) {
387 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
388 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
394 public getNumberOfRunningTransactions(): number {
395 let numberOfRunningTransactions
= 0;
397 for (const [evseId
, evseStatus
] of this.evses
) {
401 for (const connectorStatus
of evseStatus
.connectors
.values()) {
402 if (connectorStatus
.transactionStarted
=== true) {
403 ++numberOfRunningTransactions
;
408 for (const connectorId
of this.connectors
.keys()) {
409 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
410 ++numberOfRunningTransactions
;
414 return numberOfRunningTransactions
;
417 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
419 for (const evseStatus
of this.evses
.values()) {
420 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
421 if (connectorStatus
.transactionId
=== transactionId
) {
427 for (const connectorId
of this.connectors
.keys()) {
428 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
435 public getEnergyActiveImportRegisterByTransactionId(
436 transactionId
: number,
439 return this.getEnergyActiveImportRegister(
440 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
445 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
446 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
);
449 public getAuthorizeRemoteTxRequests(): boolean {
450 const authorizeRemoteTxRequests
= getConfigurationKey(
452 StandardParametersKey
.AuthorizeRemoteTxRequests
,
454 return authorizeRemoteTxRequests
!== undefined
455 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
459 public getLocalAuthListEnabled(): boolean {
460 const localAuthListEnabled
= getConfigurationKey(
462 StandardParametersKey
.LocalAuthListEnabled
,
464 return localAuthListEnabled
!== undefined
465 ? convertToBoolean(localAuthListEnabled
.value
)
469 public getHeartbeatInterval(): number {
470 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
);
471 if (HeartbeatInterval
!== undefined) {
472 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
));
474 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
);
475 if (HeartBeatInterval
!== undefined) {
476 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
));
478 this.stationInfo
?.autoRegister
=== false &&
480 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
481 Constants.DEFAULT_HEARTBEAT_INTERVAL
484 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
487 public setSupervisionUrl(url
: string): void {
489 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
490 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
)
492 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
!, url
);
494 this.stationInfo
.supervisionUrls
= url
;
495 this.saveStationInfo();
496 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
500 public startHeartbeat(): void {
501 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
=== undefined) {
502 this.heartbeatSetInterval
= setInterval(() => {
503 this.ocppRequestService
504 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
507 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
511 }, this.getHeartbeatInterval());
513 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
514 this.getHeartbeatInterval(),
517 } else if (this.heartbeatSetInterval
!== undefined) {
519 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
520 this.getHeartbeatInterval(),
525 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`,
530 public restartHeartbeat(): void {
532 this.stopHeartbeat();
534 this.startHeartbeat();
537 public restartWebSocketPing(): void {
538 // Stop WebSocket ping
539 this.stopWebSocketPing();
540 // Start WebSocket ping
541 this.startWebSocketPing();
544 public startMeterValues(connectorId
: number, interval
: number): void {
545 if (connectorId
=== 0) {
547 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`,
551 if (!this.getConnectorStatus(connectorId
)) {
553 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
558 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
560 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`,
564 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
565 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
568 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`,
573 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
574 // FIXME: Implement OCPP version agnostic helpers
575 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
578 this.getConnectorStatus(connectorId
)!.transactionId
!,
581 this.ocppRequestService
582 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
584 RequestCommand
.METER_VALUES
,
587 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
588 meterValue
: [meterValue
],
593 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
600 `${this.logPrefix()} Charging station ${
601 StandardParametersKey.MeterValueSampleInterval
602 } configuration set to ${interval}, not sending MeterValues`,
607 public stopMeterValues(connectorId
: number) {
608 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
!== undefined) {
609 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
613 public start(): void {
614 if (this.started
=== false) {
615 if (this.starting
=== false) {
616 this.starting
= true;
617 if (this.stationInfo
?.enableStatistics
=== true) {
618 this.performanceStatistics
?.start();
620 this.openWSConnection();
621 // Monitor charging station template file
622 this.templateFileWatcher
= watchJsonFile(
624 FileType
.ChargingStationTemplate
,
627 (event
, filename
): void => {
628 if (isNotEmptyString(filename
) && event
=== 'change') {
631 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
633 } file have changed, reload`,
635 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
638 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
)!);
640 this.stopAutomaticTransactionGenerator();
641 delete this.automaticTransactionGeneratorConfiguration
;
642 if (this.getAutomaticTransactionGeneratorConfiguration().enable
=== true) {
643 this.startAutomaticTransactionGenerator();
645 if (this.stationInfo
?.enableStatistics
=== true) {
646 this.performanceStatistics
?.restart();
648 this.performanceStatistics
?.stop();
650 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
653 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
661 this.emit(ChargingStationEvents
.started
);
662 this.starting
= false;
664 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
667 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
671 public async stop(reason
?: StopTransactionReason
, stopTransactions
?: boolean): Promise
<void> {
672 if (this.started
=== true) {
673 if (this.stopping
=== false) {
674 this.stopping
= true;
675 await this.stopMessageSequence(reason
, stopTransactions
);
676 this.closeWSConnection();
677 if (this.stationInfo
?.enableStatistics
=== true) {
678 this.performanceStatistics
?.stop();
680 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
681 this.templateFileWatcher
?.close();
682 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
683 delete this.bootNotificationResponse
;
684 this.started
= false;
685 this.saveConfiguration();
686 this.emit(ChargingStationEvents
.stopped
);
687 this.stopping
= false;
689 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
692 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
696 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
697 await this.stop(reason
);
698 await sleep(this.stationInfo
.resetTime
!);
703 public saveOcppConfiguration(): void {
704 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
705 this.saveConfiguration();
709 public bufferMessage(message
: string): void {
710 this.messageBuffer
.add(message
);
711 this.setIntervalFlushMessageBuffer();
714 public openWSConnection(
716 params
?: { closeOpened
?: boolean; terminateOpened
?: boolean },
719 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
720 ...this.stationInfo
?.wsOptions
,
723 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
724 if (!checkChargingStation(this, this.logPrefix())) {
728 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
729 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
731 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
733 if (params
?.closeOpened
) {
734 this.closeWSConnection();
736 if (params
?.terminateOpened
) {
737 this.terminateWSConnection();
740 if (this.isWebSocketConnectionOpened() === true) {
742 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`,
748 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`,
751 this.wsConnection
= new WebSocket(
752 this.wsConnectionUrl
,
753 `ocpp${this.stationInfo?.ocppVersion}`,
757 // Handle WebSocket message
758 this.wsConnection
.on(
760 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void,
762 // Handle WebSocket error
763 this.wsConnection
.on(
765 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void,
767 // Handle WebSocket close
768 this.wsConnection
.on(
770 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void,
772 // Handle WebSocket open
773 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
774 // Handle WebSocket ping
775 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
776 // Handle WebSocket pong
777 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
780 public closeWSConnection(): void {
781 if (this.isWebSocketConnectionOpened() === true) {
782 this.wsConnection
?.close();
783 this.wsConnection
= null;
787 public getAutomaticTransactionGeneratorConfiguration(): AutomaticTransactionGeneratorConfiguration
{
788 if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration
)) {
789 let automaticTransactionGeneratorConfiguration
:
790 | AutomaticTransactionGeneratorConfiguration
792 const stationTemplate
= this.getTemplateFromFile();
793 const stationConfiguration
= this.getConfigurationFromFile();
795 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
796 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
797 stationConfiguration
?.automaticTransactionGenerator
799 automaticTransactionGeneratorConfiguration
=
800 stationConfiguration
?.automaticTransactionGenerator
;
802 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
;
804 this.automaticTransactionGeneratorConfiguration
= {
805 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
806 ...automaticTransactionGeneratorConfiguration
,
809 return this.automaticTransactionGeneratorConfiguration
!;
812 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
813 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
816 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
817 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
818 if (isNotEmptyArray(connectorIds
)) {
819 for (const connectorId
of connectorIds
!) {
820 this.automaticTransactionGenerator
?.startConnector(connectorId
);
823 this.automaticTransactionGenerator
?.start();
825 this.saveAutomaticTransactionGeneratorConfiguration();
826 this.emit(ChargingStationEvents
.updated
);
829 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
830 if (isNotEmptyArray(connectorIds
)) {
831 for (const connectorId
of connectorIds
!) {
832 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
835 this.automaticTransactionGenerator
?.stop();
837 this.saveAutomaticTransactionGeneratorConfiguration();
838 this.emit(ChargingStationEvents
.updated
);
841 public async stopTransactionOnConnector(
843 reason
?: StopTransactionReason
,
844 ): Promise
<StopTransactionResponse
> {
845 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
847 this.stationInfo
?.beginEndMeterValues
=== true &&
848 this.stationInfo
?.ocppStrictCompliance
=== true &&
849 this.stationInfo
?.outOfOrderEndMeterValues
=== false
851 // FIXME: Implement OCPP version agnostic helpers
852 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
855 this.getEnergyActiveImportRegisterByTransactionId(transactionId
!),
857 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
859 RequestCommand
.METER_VALUES
,
863 meterValue
: [transactionEndMeterValue
],
867 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
869 RequestCommand
.STOP_TRANSACTION
,
872 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
!, true),
873 ...(isNullOrUndefined(reason
) && { reason
}),
878 public getReserveConnectorZeroSupported(): boolean {
879 return convertToBoolean(
880 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
,
884 public async addReservation(reservation
: Reservation
): Promise
<void> {
885 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
);
886 if (reservationFound
!== undefined) {
887 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
);
889 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
;
890 await OCPPServiceUtils
.sendAndSetConnectorStatus(
892 reservation
.connectorId
,
893 ConnectorStatusEnum
.Reserved
,
895 { send
: reservation
.connectorId
!== 0 },
899 public async removeReservation(
900 reservation
: Reservation
,
901 reason
: ReservationTerminationReason
,
903 const connector
= this.getConnectorStatus(reservation
.connectorId
)!;
905 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
906 case ReservationTerminationReason
.TRANSACTION_STARTED
:
907 delete connector
.reservation
;
909 case ReservationTerminationReason
.RESERVATION_CANCELED
:
910 case ReservationTerminationReason
.REPLACE_EXISTING
:
911 case ReservationTerminationReason
.EXPIRED
:
912 await OCPPServiceUtils
.sendAndSetConnectorStatus(
914 reservation
.connectorId
,
915 ConnectorStatusEnum
.Available
,
917 { send
: reservation
.connectorId
!== 0 },
919 delete connector
.reservation
;
922 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
923 throw new BaseError(`Unknown reservation termination reason '${reason}'`);
927 public getReservationBy(
928 filterKey
: ReservationKey
,
929 value
: number | string,
930 ): Reservation
| undefined {
932 for (const evseStatus
of this.evses
.values()) {
933 for (const connectorStatus
of evseStatus
.connectors
.values()) {
934 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
935 return connectorStatus
.reservation
;
940 for (const connectorStatus
of this.connectors
.values()) {
941 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
942 return connectorStatus
.reservation
;
948 public isConnectorReservable(
949 reservationId
: number,
951 connectorId
?: number,
953 const reservation
= this.getReservationBy('reservationId', reservationId
);
954 const reservationExists
= !isUndefined(reservation
) && !hasReservationExpired(reservation
!);
955 if (arguments.length
=== 1) {
956 return !reservationExists
;
957 } else if (arguments.length
> 1) {
958 const userReservation
= !isUndefined(idTag
)
959 ? this.getReservationBy('idTag', idTag
!)
961 const userReservationExists
=
962 !isUndefined(userReservation
) && !hasReservationExpired(userReservation
!);
963 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
! > 0;
964 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
966 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
972 private setIntervalFlushMessageBuffer(): void {
973 if (this.flushMessageBufferSetInterval
=== undefined) {
974 this.flushMessageBufferSetInterval
= setInterval(() => {
975 if (this.isWebSocketConnectionOpened() === true && this.inAcceptedState() === true) {
976 this.flushMessageBuffer();
978 if (this.messageBuffer
.size
=== 0) {
979 this.clearIntervalFlushMessageBuffer();
981 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
);
985 private clearIntervalFlushMessageBuffer() {
986 if (this.flushMessageBufferSetInterval
!== undefined) {
987 clearInterval(this.flushMessageBufferSetInterval
);
988 delete this.flushMessageBufferSetInterval
;
992 private getNumberOfReservableConnectors(): number {
993 let numberOfReservableConnectors
= 0;
995 for (const evseStatus
of this.evses
.values()) {
996 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
);
999 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
);
1001 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1004 private getNumberOfReservationsOnConnectorZero(): number {
1006 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1007 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) ||
1008 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
)
1015 private flushMessageBuffer(): void {
1016 if (this.messageBuffer
.size
> 0) {
1017 for (const message
of this.messageBuffer
.values()) {
1018 let beginId
: string | undefined;
1019 let commandName
: RequestCommand
| undefined;
1020 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1021 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1023 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1024 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1026 this.wsConnection
?.send(message
, (error
?: Error) => {
1027 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!);
1028 if (isNullOrUndefined(error
)) {
1030 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1032 )} payload sent: ${message}`,
1034 this.messageBuffer
.delete(message
);
1041 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1042 let template
: ChargingStationTemplate
| undefined;
1044 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1045 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1047 const measureId
= `${FileType.ChargingStationTemplate} read`;
1048 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1049 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1050 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1051 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1052 .update(JSON
.stringify(template
))
1054 this.sharedLRUCache
.setChargingStationTemplate(template
);
1055 this.templateFileHash
= template
.templateHash
;
1058 handleFileException(
1060 FileType
.ChargingStationTemplate
,
1061 error
as NodeJS
.ErrnoException
,
1068 private getStationInfoFromTemplate(): ChargingStationInfo
{
1069 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile()!;
1070 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1071 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this);
1072 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
);
1073 if (stationTemplate
?.Connectors
) {
1074 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1076 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1077 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1078 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1079 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1080 createSerialNumber(stationTemplate
, stationInfo
);
1081 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
);
1082 if (isNotEmptyArray(stationTemplate
?.power
)) {
1083 stationTemplate
.power
= stationTemplate
.power
as number[];
1084 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1085 stationInfo
.maximumPower
=
1086 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1087 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1088 : stationTemplate
.power
[powerArrayRandomIndex
];
1090 stationTemplate
.power
= stationTemplate
?.power
as number;
1091 stationInfo
.maximumPower
=
1092 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1093 ? stationTemplate
.power
* 1000
1094 : stationTemplate
.power
;
1096 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1097 stationInfo
.firmwareVersionPattern
=
1098 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1100 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1101 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!) === false
1104 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1106 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`,
1109 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1116 stationTemplate
?.firmwareUpgrade
?? {},
1118 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1119 ? secondsToMilliseconds(stationTemplate
.resetTime
!)
1120 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1124 private getStationInfoFromFile(
1125 stationInfoPersistentConfiguration
= true,
1126 ): ChargingStationInfo
| undefined {
1127 let stationInfo
: ChargingStationInfo
| undefined;
1128 if (stationInfoPersistentConfiguration
=== true) {
1129 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1131 delete stationInfo
?.infoHash
;
1137 private getStationInfo(): ChargingStationInfo
{
1138 const defaultStationInfo
: Partial
<ChargingStationInfo
> = {
1139 enableStatistics
: false,
1140 remoteAuthorization
: true,
1141 currentOutType
: CurrentType
.AC
,
1142 mainVoltageMeterValues
: true,
1143 phaseLineToLineVoltageMeterValues
: false,
1144 customValueLimitationMeterValues
: true,
1145 ocppStrictCompliance
: true,
1146 outOfOrderEndMeterValues
: false,
1147 beginEndMeterValues
: false,
1148 meteringPerTransaction
: true,
1149 transactionDataMeterValues
: false,
1150 supervisionUrlOcppConfiguration
: false,
1151 supervisionUrlOcppKey
: VendorParametersKey
.ConnectionUrl
,
1152 ocppVersion
: OCPPVersion
.VERSION_16
,
1153 ocppPersistentConfiguration
: true,
1154 stationInfoPersistentConfiguration
: true,
1155 automaticTransactionGeneratorPersistentConfiguration
: true,
1156 autoReconnectMaxRetries
: -1,
1157 registrationMaxRetries
: -1,
1158 reconnectExponentialDelay
: false,
1159 stopTransactionsOnStopped
: true,
1161 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1162 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile(
1163 stationInfoFromTemplate
?.stationInfoPersistentConfiguration
,
1166 // 1. charging station info from template
1167 // 2. charging station info from configuration file
1168 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1169 return { ...defaultStationInfo
, ...stationInfoFromFile
! };
1171 stationInfoFromFile
&&
1172 propagateSerialNumber(
1173 this.getTemplateFromFile()!,
1174 stationInfoFromFile
,
1175 stationInfoFromTemplate
,
1177 return { ...defaultStationInfo
, ...stationInfoFromTemplate
};
1180 private saveStationInfo(): void {
1181 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1182 this.saveConfiguration();
1186 private handleUnsupportedVersion(version
: OCPPVersion
| undefined) {
1187 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1188 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1189 throw new BaseError(errorMsg
);
1192 private initialize(): void {
1193 const stationTemplate
= this.getTemplateFromFile()!;
1194 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1195 this.configurationFile
= join(
1196 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1197 `${getHashId(this.index, stationTemplate)}.json`,
1199 const stationConfiguration
= this.getConfigurationFromFile();
1201 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1202 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1203 (stationConfiguration
?.connectorsStatus
|| stationConfiguration
?.evsesStatus
)
1205 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
);
1206 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
);
1208 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1210 this.stationInfo
= this.getStationInfo();
1212 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1213 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1214 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1216 const patternGroup
: number | undefined =
1217 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1218 this.stationInfo
.firmwareVersion
?.split('.').length
;
1219 const match
= this.stationInfo
1220 .firmwareVersion
!.match(new RegExp(this.stationInfo
.firmwareVersionPattern
!))!
1221 .slice(1, patternGroup
! + 1);
1222 const patchLevelIndex
= match
.length
- 1;
1223 match
[patchLevelIndex
] = (
1224 convertToInt(match
[patchLevelIndex
]) +
1225 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1227 this.stationInfo
.firmwareVersion
= match
?.join('.');
1229 this.saveStationInfo();
1230 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1231 if (this.stationInfo
?.enableStatistics
=== true) {
1232 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1233 this.stationInfo
.hashId
,
1234 this.stationInfo
.chargingStationId
!,
1235 this.configuredSupervisionUrl
,
1238 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
);
1239 this.powerDivider
= this.getPowerDivider();
1240 // OCPP configuration
1241 this.ocppConfiguration
= this.getOcppConfiguration();
1242 this.initializeOcppConfiguration();
1243 this.initializeOcppServices();
1244 this.once(ChargingStationEvents
.accepted
, () => {
1245 this.startMessageSequence().catch((error
) => {
1246 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
);
1249 if (this.stationInfo
?.autoRegister
=== true) {
1250 this.bootNotificationResponse
= {
1251 currentTime
: new Date(),
1252 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1253 status: RegistrationStatusEnumType
.ACCEPTED
,
1258 private initializeOcppServices(): void {
1259 const ocppVersion
= this.stationInfo
?.ocppVersion
;
1260 switch (ocppVersion
) {
1261 case OCPPVersion
.VERSION_16
:
1262 this.ocppIncomingRequestService
=
1263 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1264 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1265 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(),
1268 case OCPPVersion
.VERSION_20
:
1269 case OCPPVersion
.VERSION_201
:
1270 this.ocppIncomingRequestService
=
1271 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1272 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1273 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>(),
1277 this.handleUnsupportedVersion(ocppVersion
);
1282 private initializeOcppConfiguration(): void {
1283 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
))) {
1284 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0');
1286 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
))) {
1287 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false });
1290 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1291 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
) &&
1292 isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!))
1294 addConfigurationKey(
1296 this.stationInfo
.supervisionUrlOcppKey
!,
1297 this.configuredSupervisionUrl
.href
,
1301 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1302 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
) &&
1303 !isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!))
1305 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!, { save
: false });
1308 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1309 isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!))
1311 addConfigurationKey(
1313 this.stationInfo
.amperageLimitationOcppKey
!,
1315 this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)
1320 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
))
1322 addConfigurationKey(
1324 StandardParametersKey
.SupportedFeatureProfiles
,
1325 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`,
1328 addConfigurationKey(
1330 StandardParametersKey
.NumberOfConnectors
,
1331 this.getNumberOfConnectors().toString(),
1333 { overwrite
: true },
1336 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
))
1338 addConfigurationKey(
1340 StandardParametersKey
.MeterValuesSampledData
,
1341 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
1345 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
))
1347 const connectorsPhaseRotation
: string[] = [];
1348 if (this.hasEvses
) {
1349 for (const evseStatus
of this.evses
.values()) {
1350 for (const connectorId
of evseStatus
.connectors
.keys()) {
1351 connectorsPhaseRotation
.push(
1352 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1357 for (const connectorId
of this.connectors
.keys()) {
1358 connectorsPhaseRotation
.push(
1359 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1363 addConfigurationKey(
1365 StandardParametersKey
.ConnectorPhaseRotation
,
1366 connectorsPhaseRotation
.toString(),
1370 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
))
1372 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1375 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
)) &&
1376 getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)?.value
?.includes(
1377 SupportedFeatureProfiles
.LocalAuthListManagement
,
1380 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false');
1382 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
))) {
1383 addConfigurationKey(
1385 StandardParametersKey
.ConnectionTimeOut
,
1386 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString(),
1389 this.saveOcppConfiguration();
1392 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1393 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1394 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1395 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1397 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1398 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1399 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1400 delete evseStatus
.connectorsStatus
;
1401 this.evses
.set(evseId
, {
1402 ...(evseStatus
as EvseStatus
),
1403 connectors
: new Map
<number, ConnectorStatus
>(
1404 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1411 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1412 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1413 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1414 throw new BaseError(errorMsg
);
1416 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1417 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1418 throw new BaseError(errorMsg
);
1422 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1423 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1424 this.initializeConnectorsFromTemplate(stationTemplate
);
1425 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1426 this.initializeEvsesFromTemplate(stationTemplate
);
1427 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1428 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1429 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1430 throw new BaseError(errorMsg
);
1432 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1433 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1434 throw new BaseError(errorMsg
);
1438 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1439 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1440 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1441 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1442 throw new BaseError(errorMsg
);
1444 if (!stationTemplate
?.Connectors
?.[0]) {
1446 `${this.logPrefix()} Charging station information from template ${
1448 } with no connector id 0 configuration`,
1451 if (stationTemplate
?.Connectors
) {
1452 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1453 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1454 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1456 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`,
1459 const connectorsConfigChanged
=
1460 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1461 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1462 connectorsConfigChanged
&& this.connectors
.clear();
1463 this.connectorsConfigurationHash
= connectorsConfigHash
;
1464 if (templateMaxConnectors
> 0) {
1465 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1467 connectorId
=== 0 &&
1468 (!stationTemplate
?.Connectors
?.[connectorId
] ||
1469 this.getUseConnectorId0(stationTemplate
) === false)
1473 const templateConnectorId
=
1474 connectorId
> 0 && stationTemplate
?.randomConnectors
1475 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1477 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1478 checkStationInfoConnectorStatus(
1479 templateConnectorId
,
1484 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1486 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1487 this.saveConnectorsStatus();
1490 `${this.logPrefix()} Charging station information from template ${
1492 } with no connectors configuration defined, cannot create connectors`,
1498 `${this.logPrefix()} Charging station information from template ${
1500 } with no connectors configuration defined, using already defined connectors`,
1505 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1506 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1507 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1508 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1509 throw new BaseError(errorMsg
);
1511 if (!stationTemplate
?.Evses
?.[0]) {
1513 `${this.logPrefix()} Charging station information from template ${
1515 } with no evse id 0 configuration`,
1518 if (!stationTemplate
?.Evses
?.[0]?.Connectors
?.[0]) {
1520 `${this.logPrefix()} Charging station information from template ${
1522 } with evse id 0 with no connector id 0 configuration`,
1525 if (Object.keys(stationTemplate
?.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1527 `${this.logPrefix()} Charging station information from template ${
1529 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`,
1532 if (stationTemplate
?.Evses
) {
1533 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1534 .update(JSON
.stringify(stationTemplate
?.Evses
))
1536 const evsesConfigChanged
=
1537 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1538 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1539 evsesConfigChanged
&& this.evses
.clear();
1540 this.evsesConfigurationHash
= evsesConfigHash
;
1541 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1542 if (templateMaxEvses
> 0) {
1543 for (const evseKey
in stationTemplate
.Evses
) {
1544 const evseId
= convertToInt(evseKey
);
1545 this.evses
.set(evseId
, {
1546 connectors
: buildConnectorsMap(
1547 stationTemplate
?.Evses
[evseKey
]?.Connectors
,
1551 availability
: AvailabilityType
.Operative
,
1553 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix());
1555 this.saveEvsesStatus();
1558 `${this.logPrefix()} Charging station information from template ${
1560 } with no evses configuration defined, cannot create evses`,
1566 `${this.logPrefix()} Charging station information from template ${
1568 } with no evses configuration defined, using already defined evses`,
1573 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1574 let configuration
: ChargingStationConfiguration
| undefined;
1575 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1577 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1578 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1579 this.configurationFileHash
,
1582 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1583 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1584 configuration
= JSON
.parse(
1585 readFileSync(this.configurationFile
, 'utf8'),
1586 ) as ChargingStationConfiguration
;
1587 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1588 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1589 this.configurationFileHash
= configuration
.configurationHash
!;
1592 handleFileException(
1593 this.configurationFile
,
1594 FileType
.ChargingStationConfiguration
,
1595 error
as NodeJS
.ErrnoException
,
1600 return configuration
;
1603 private saveAutomaticTransactionGeneratorConfiguration(): void {
1604 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1605 this.saveConfiguration();
1609 private saveConnectorsStatus() {
1610 this.saveConfiguration();
1613 private saveEvsesStatus() {
1614 this.saveConfiguration();
1617 private saveConfiguration(): void {
1618 if (isNotEmptyString(this.configurationFile
)) {
1620 if (!existsSync(dirname(this.configurationFile
))) {
1621 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1623 let configurationData
: ChargingStationConfiguration
= this.getConfigurationFromFile()
1624 ? cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()!)
1626 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true && this.stationInfo
) {
1627 configurationData
.stationInfo
= this.stationInfo
;
1629 delete configurationData
.stationInfo
;
1632 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1633 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1635 configurationData
.configurationKey
= this.ocppConfiguration
?.configurationKey
;
1637 delete configurationData
.configurationKey
;
1639 configurationData
= merge
<ChargingStationConfiguration
>(
1641 buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
1644 !this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
||
1645 !this.getAutomaticTransactionGeneratorConfiguration()
1647 delete configurationData
.automaticTransactionGenerator
;
1649 if (this.connectors
.size
> 0) {
1650 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1652 delete configurationData
.connectorsStatus
;
1654 if (this.evses
.size
> 0) {
1655 configurationData
.evsesStatus
= buildEvsesStatus(this);
1657 delete configurationData
.evsesStatus
;
1659 delete configurationData
.configurationHash
;
1660 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1663 stationInfo
: configurationData
.stationInfo
,
1664 configurationKey
: configurationData
.configurationKey
,
1665 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1666 ...(this.connectors
.size
> 0 && {
1667 connectorsStatus
: configurationData
.connectorsStatus
,
1669 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
}),
1670 } as ChargingStationConfiguration
),
1673 if (this.configurationFileHash
!== configurationHash
) {
1674 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1675 configurationData
.configurationHash
= configurationHash
;
1676 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1677 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1679 this.configurationFile
,
1680 JSON
.stringify(configurationData
, undefined, 2),
1683 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1684 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1685 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1686 this.configurationFileHash
= configurationHash
;
1687 }).catch((error
) => {
1688 handleFileException(
1689 this.configurationFile
,
1690 FileType
.ChargingStationConfiguration
,
1691 error
as NodeJS
.ErrnoException
,
1697 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1698 this.configurationFile
1703 handleFileException(
1704 this.configurationFile
,
1705 FileType
.ChargingStationConfiguration
,
1706 error
as NodeJS
.ErrnoException
,
1712 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`,
1717 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1718 return this.getTemplateFromFile()?.Configuration
;
1721 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1722 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1723 if (this.stationInfo
?.ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1724 return { configurationKey
};
1729 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1730 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1731 this.getOcppConfigurationFromFile();
1732 if (!ocppConfiguration
) {
1733 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1735 return ocppConfiguration
;
1738 private async onOpen(): Promise
<void> {
1739 if (this.isWebSocketConnectionOpened() === true) {
1741 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`,
1743 let registrationRetryCount
= 0;
1744 if (this.isRegistered() === false) {
1745 // Send BootNotification
1747 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1748 BootNotificationRequest
,
1749 BootNotificationResponse
1750 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1751 skipBufferingOnError
: true,
1753 if (this.isRegistered() === false) {
1754 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
;
1756 this?.bootNotificationResponse
?.interval
1757 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1758 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
,
1762 this.isRegistered() === false &&
1763 (registrationRetryCount
<= this.stationInfo
.registrationMaxRetries
! ||
1764 this.stationInfo
?.registrationMaxRetries
=== -1)
1767 if (this.isRegistered() === true) {
1768 this.emit(ChargingStationEvents
.registered
);
1769 if (this.inAcceptedState() === true) {
1770 this.emit(ChargingStationEvents
.accepted
);
1774 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${this
1775 .stationInfo?.registrationMaxRetries})`,
1778 this.autoReconnectRetryCount
= 0;
1779 this.emit(ChargingStationEvents
.updated
);
1782 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`,
1787 private async onClose(code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): Promise
<void> {
1790 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1791 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1793 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1795 )}' and reason '${reason.toString()}'`,
1797 this.autoReconnectRetryCount
= 0;
1802 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1804 )}' and reason '${reason.toString()}'`,
1806 this.started
=== true && (await this.reconnect());
1809 this.emit(ChargingStationEvents
.updated
);
1812 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1813 const cachedRequest
= this.requests
.get(messageId
);
1814 if (Array.isArray(cachedRequest
) === true) {
1815 return cachedRequest
;
1817 throw new OCPPError(
1818 ErrorType
.PROTOCOL_ERROR
,
1819 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1821 )} is not an array`,
1823 cachedRequest
as JsonType
,
1827 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1828 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1829 if (this.stationInfo
?.enableStatistics
=== true) {
1830 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1833 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1837 // Process the message
1838 await this.ocppIncomingRequestService
.incomingRequestHandler(
1844 this.emit(ChargingStationEvents
.updated
);
1847 private handleResponseMessage(response
: Response
): void {
1848 const [messageType
, messageId
, commandPayload
] = response
;
1849 if (this.requests
.has(messageId
) === false) {
1851 throw new OCPPError(
1852 ErrorType
.INTERNAL_ERROR
,
1853 `Response for unknown message id ${messageId}`,
1859 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1864 `${this.logPrefix()} << Command '${
1865 requestCommandName ?? Constants.UNKNOWN_COMMAND
1866 }' received response payload: ${JSON.stringify(response)}`,
1868 responseCallback(commandPayload
, requestPayload
);
1871 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1872 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1873 if (this.requests
.has(messageId
) === false) {
1875 throw new OCPPError(
1876 ErrorType
.INTERNAL_ERROR
,
1877 `Error response for unknown message id ${messageId}`,
1879 { errorType
, errorMessage
, errorDetails
},
1882 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1884 `${this.logPrefix()} << Command '${
1885 requestCommandName ?? Constants.UNKNOWN_COMMAND
1886 }' received error response payload: ${JSON.stringify(errorResponse)}`,
1888 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1891 private async onMessage(data
: RawData
): Promise
<void> {
1892 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined;
1893 let messageType
: MessageType
| undefined;
1894 let errorMsg
: string;
1896 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1897 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1898 if (Array.isArray(request
) === true) {
1899 [messageType
] = request
;
1900 // Check the type of message
1901 switch (messageType
) {
1903 case MessageType
.CALL_MESSAGE
:
1904 await this.handleIncomingMessage(request
as IncomingRequest
);
1907 case MessageType
.CALL_RESULT_MESSAGE
:
1908 this.handleResponseMessage(request
as Response
);
1911 case MessageType
.CALL_ERROR_MESSAGE
:
1912 this.handleErrorMessage(request
as ErrorResponse
);
1916 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1917 errorMsg
= `Wrong message type ${messageType}`;
1918 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1919 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1922 throw new OCPPError(
1923 ErrorType
.PROTOCOL_ERROR
,
1924 'Incoming message is not an array',
1932 let commandName
: IncomingRequestCommand
| undefined;
1933 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined;
1934 let errorCallback
: ErrorCallback
;
1935 const [, messageId
] = request
!;
1936 switch (messageType
) {
1937 case MessageType
.CALL_MESSAGE
:
1938 [, , commandName
] = request
as IncomingRequest
;
1940 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1942 case MessageType
.CALL_RESULT_MESSAGE
:
1943 case MessageType
.CALL_ERROR_MESSAGE
:
1944 if (this.requests
.has(messageId
) === true) {
1945 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1946 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1947 errorCallback(error
as OCPPError
, false);
1949 // Remove the request from the cache in case of error at response handling
1950 this.requests
.delete(messageId
);
1954 if (error
instanceof OCPPError
=== false) {
1956 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1957 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1958 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1959 }' message '${data.toString()}' handling is not an OCPPError:`,
1964 `${this.logPrefix()} Incoming OCPP command '${
1965 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1966 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1967 }' message '${data.toString()}'${
1968 messageType !== MessageType.CALL_MESSAGE
1969 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1971 } processing error:`,
1977 private onPing(): void {
1978 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1981 private onPong(): void {
1982 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1985 private onError(error
: WSError
): void {
1986 this.closeWSConnection();
1987 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1990 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1991 if (this.stationInfo
?.meteringPerTransaction
=== true) {
1994 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
1995 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2000 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2001 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2005 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2006 return stationTemplate
?.useConnectorId0
?? true;
2009 private async stopRunningTransactions(reason
?: StopTransactionReason
): Promise
<void> {
2010 if (this.hasEvses
) {
2011 for (const [evseId
, evseStatus
] of this.evses
) {
2015 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2016 if (connectorStatus
.transactionStarted
=== true) {
2017 await this.stopTransactionOnConnector(connectorId
, reason
);
2022 for (const connectorId
of this.connectors
.keys()) {
2023 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2024 await this.stopTransactionOnConnector(connectorId
, reason
);
2031 private getConnectionTimeout(): number {
2032 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) !== undefined) {
2033 return convertToInt(
2034 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)!.value
! ??
2035 Constants
.DEFAULT_CONNECTION_TIMEOUT
,
2038 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2041 private getPowerDivider(): number {
2042 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2043 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2044 powerDivider
= this.getNumberOfRunningTransactions();
2046 return powerDivider
;
2049 private getMaximumAmperage(stationInfo
?: ChargingStationInfo
): number | undefined {
2050 const maximumPower
= (stationInfo
?? this.stationInfo
).maximumPower
!;
2051 switch (this.getCurrentOutType(stationInfo
)) {
2052 case CurrentType
.AC
:
2053 return ACElectricUtils
.amperagePerPhaseFromPower(
2054 this.getNumberOfPhases(stationInfo
),
2055 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2056 this.getVoltageOut(stationInfo
),
2058 case CurrentType
.DC
:
2059 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2063 private getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
2064 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
2067 private getVoltageOut(stationInfo
?: ChargingStationInfo
): Voltage
{
2069 (stationInfo
?? this.stationInfo
).voltageOut
??
2070 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2074 private getAmperageLimitation(): number | undefined {
2076 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2077 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!) !== undefined
2081 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)?.value
,
2082 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2087 private async startMessageSequence(): Promise
<void> {
2088 if (this.stationInfo
?.autoRegister
=== true) {
2089 await this.ocppRequestService
.requestHandler
<
2090 BootNotificationRequest
,
2091 BootNotificationResponse
2092 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2093 skipBufferingOnError
: true,
2096 // Start WebSocket ping
2097 this.startWebSocketPing();
2099 this.startHeartbeat();
2100 // Initialize connectors status
2101 if (this.hasEvses
) {
2102 for (const [evseId
, evseStatus
] of this.evses
) {
2104 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2105 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2106 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2109 connectorBootStatus
,
2116 for (const connectorId
of this.connectors
.keys()) {
2117 if (connectorId
> 0) {
2118 const connectorBootStatus
= getBootConnectorStatus(
2121 this.getConnectorStatus(connectorId
)!,
2123 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2127 if (this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
) {
2128 await this.ocppRequestService
.requestHandler
<
2129 FirmwareStatusNotificationRequest
,
2130 FirmwareStatusNotificationResponse
2131 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2132 status: FirmwareStatus
.Installed
,
2134 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2138 if (this.getAutomaticTransactionGeneratorConfiguration().enable
=== true) {
2139 this.startAutomaticTransactionGenerator();
2141 this.flushMessageBuffer();
2144 private async stopMessageSequence(
2145 reason
?: StopTransactionReason
,
2146 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
,
2148 // Stop WebSocket ping
2149 this.stopWebSocketPing();
2151 this.stopHeartbeat();
2153 if (this.automaticTransactionGenerator
?.started
=== true) {
2154 this.stopAutomaticTransactionGenerator();
2156 // Stop ongoing transactions
2157 stopTransactions
&& (await this.stopRunningTransactions(reason
));
2158 if (this.hasEvses
) {
2159 for (const [evseId
, evseStatus
] of this.evses
) {
2161 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2162 await this.ocppRequestService
.requestHandler
<
2163 StatusNotificationRequest
,
2164 StatusNotificationResponse
2167 RequestCommand
.STATUS_NOTIFICATION
,
2168 OCPPServiceUtils
.buildStatusNotificationRequest(
2171 ConnectorStatusEnum
.Unavailable
,
2175 delete connectorStatus
?.status;
2180 for (const connectorId
of this.connectors
.keys()) {
2181 if (connectorId
> 0) {
2182 await this.ocppRequestService
.requestHandler
<
2183 StatusNotificationRequest
,
2184 StatusNotificationResponse
2187 RequestCommand
.STATUS_NOTIFICATION
,
2188 OCPPServiceUtils
.buildStatusNotificationRequest(
2191 ConnectorStatusEnum
.Unavailable
,
2194 delete this.getConnectorStatus(connectorId
)?.status;
2200 private startWebSocketPing(): void {
2201 const webSocketPingInterval
: number =
2202 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
) !== undefined
2204 getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
,
2207 if (webSocketPingInterval
> 0 && this.webSocketPingSetInterval
=== undefined) {
2208 this.webSocketPingSetInterval
= setInterval(() => {
2209 if (this.isWebSocketConnectionOpened() === true) {
2210 this.wsConnection
?.ping();
2212 }, secondsToMilliseconds(webSocketPingInterval
));
2214 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2215 webSocketPingInterval,
2218 } else if (this.webSocketPingSetInterval
!== undefined) {
2220 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2221 webSocketPingInterval,
2226 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`,
2231 private stopWebSocketPing(): void {
2232 if (this.webSocketPingSetInterval
!== undefined) {
2233 clearInterval(this.webSocketPingSetInterval
);
2234 delete this.webSocketPingSetInterval
;
2238 private getConfiguredSupervisionUrl(): URL
{
2239 let configuredSupervisionUrl
: string;
2240 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2241 if (isNotEmptyArray(supervisionUrls
)) {
2242 let configuredSupervisionUrlIndex
: number;
2243 switch (Configuration
.getSupervisionUrlDistribution()) {
2244 case SupervisionUrlDistribution
.RANDOM
:
2245 configuredSupervisionUrlIndex
= Math.floor(
2246 secureRandom() * (supervisionUrls
as string[]).length
,
2249 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2250 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2252 Object.values(SupervisionUrlDistribution
).includes(
2253 Configuration
.getSupervisionUrlDistribution()!,
2256 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2257 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2258 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2261 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
;
2264 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
];
2266 configuredSupervisionUrl
= supervisionUrls
as string;
2268 if (isNotEmptyString(configuredSupervisionUrl
)) {
2269 return new URL(configuredSupervisionUrl
);
2271 const errorMsg
= 'No supervision url(s) configured';
2272 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2273 throw new BaseError(`${errorMsg}`);
2276 private stopHeartbeat(): void {
2277 if (this.heartbeatSetInterval
!== undefined) {
2278 clearInterval(this.heartbeatSetInterval
);
2279 delete this.heartbeatSetInterval
;
2283 private terminateWSConnection(): void {
2284 if (this.isWebSocketConnectionOpened() === true) {
2285 this.wsConnection
?.terminate();
2286 this.wsConnection
= null;
2290 private async reconnect(): Promise
<void> {
2291 // Stop WebSocket ping
2292 this.stopWebSocketPing();
2294 this.stopHeartbeat();
2295 // Stop the ATG if needed
2296 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2297 this.stopAutomaticTransactionGenerator();
2300 this.autoReconnectRetryCount
< this.stationInfo
.autoReconnectMaxRetries
! ||
2301 this.stationInfo
?.autoReconnectMaxRetries
=== -1
2303 ++this.autoReconnectRetryCount
;
2304 const reconnectDelay
=
2305 this.stationInfo
?.reconnectExponentialDelay
=== true
2306 ? exponentialDelay(this.autoReconnectRetryCount
)
2307 : secondsToMilliseconds(this.getConnectionTimeout());
2308 const reconnectDelayWithdraw
= 1000;
2309 const reconnectTimeout
=
2310 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2311 ? reconnectDelay
- reconnectDelayWithdraw
2314 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2317 )}ms, timeout ${reconnectTimeout}ms`,
2319 await sleep(reconnectDelay
);
2321 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`,
2323 this.openWSConnection(
2325 handshakeTimeout
: reconnectTimeout
,
2327 { closeOpened
: true },
2329 } else if (this.stationInfo
?.autoReconnectMaxRetries
!== -1) {
2331 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2332 this.autoReconnectRetryCount
2333 }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`,