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
,
58 buildStatusNotificationRequest
,
60 sendAndSetConnectorStatus
,
62 import { SharedLRUCache
} from
'./SharedLRUCache';
63 import { BaseError
, OCPPError
} from
'../exception';
64 import { PerformanceStatistics
} from
'../performance';
66 type AutomaticTransactionGeneratorConfiguration
,
68 type BootNotificationRequest
,
69 type BootNotificationResponse
,
71 type ChargingStationConfiguration
,
72 ChargingStationEvents
,
73 type ChargingStationInfo
,
74 type ChargingStationOcppConfiguration
,
75 type ChargingStationTemplate
,
83 type EvseStatusConfiguration
,
86 type FirmwareStatusNotificationRequest
,
87 type FirmwareStatusNotificationResponse
,
89 type HeartbeatRequest
,
90 type HeartbeatResponse
,
92 type IncomingRequestCommand
,
97 type MeterValuesRequest
,
98 type MeterValuesResponse
,
100 type OutgoingRequest
,
102 RegistrationStatusEnumType
,
106 ReservationTerminationReason
,
108 StandardParametersKey
,
110 type StatusNotificationRequest
,
111 type StatusNotificationResponse
,
112 StopTransactionReason
,
113 type StopTransactionRequest
,
114 type StopTransactionResponse
,
115 SupervisionUrlDistribution
,
116 SupportedFeatureProfiles
,
120 WebSocketCloseEventStatusCode
,
130 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
131 buildConnectorsStatus
,
140 formatDurationMilliSeconds
,
141 formatDurationSeconds
,
143 getWebSocketCloseEventStatusString
,
159 export class ChargingStation
extends EventEmitter
{
160 public readonly index
: number;
161 public readonly templateFile
: string;
162 public stationInfo
!: ChargingStationInfo
;
163 public started
: boolean;
164 public starting
: boolean;
165 public idTagsCache
: IdTagsCache
;
166 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
167 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
168 public wsConnection
: WebSocket
| null;
169 public readonly connectors
: Map
<number, ConnectorStatus
>;
170 public readonly evses
: Map
<number, EvseStatus
>;
171 public readonly requests
: Map
<string, CachedRequest
>;
172 public performanceStatistics
!: PerformanceStatistics
| undefined;
173 public heartbeatSetInterval
?: NodeJS
.Timeout
;
174 public ocppRequestService
!: OCPPRequestService
;
175 public bootNotificationRequest
!: BootNotificationRequest
;
176 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
177 public powerDivider
!: number;
178 private stopping
: boolean;
179 private configurationFile
!: string;
180 private configurationFileHash
!: string;
181 private connectorsConfigurationHash
!: string;
182 private evsesConfigurationHash
!: string;
183 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
;
184 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
185 private readonly messageBuffer
: Set
<string>;
186 private configuredSupervisionUrl
!: URL
;
187 private autoReconnectRetryCount
: number;
188 private templateFileWatcher
!: FSWatcher
| undefined;
189 private templateFileHash
!: string;
190 private readonly sharedLRUCache
: SharedLRUCache
;
191 private webSocketPingSetInterval
?: NodeJS
.Timeout
;
192 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
193 private flushMessageBufferSetInterval
?: NodeJS
.Timeout
;
195 constructor(index
: number, templateFile
: string) {
197 this.started
= false;
198 this.starting
= false;
199 this.stopping
= false;
200 this.wsConnection
= null;
201 this.autoReconnectRetryCount
= 0;
203 this.templateFile
= templateFile
;
204 this.connectors
= new Map
<number, ConnectorStatus
>();
205 this.evses
= new Map
<number, EvseStatus
>();
206 this.requests
= new Map
<string, CachedRequest
>();
207 this.messageBuffer
= new Set
<string>();
208 this.sharedLRUCache
= SharedLRUCache
.getInstance();
209 this.idTagsCache
= IdTagsCache
.getInstance();
210 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
212 this.on(ChargingStationEvents
.started
, () => {
213 parentPort
?.postMessage(buildStartedMessage(this));
215 this.on(ChargingStationEvents
.stopped
, () => {
216 parentPort
?.postMessage(buildStoppedMessage(this));
218 this.on(ChargingStationEvents
.updated
, () => {
219 parentPort
?.postMessage(buildUpdatedMessage(this));
225 public get
hasEvses(): boolean {
226 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
229 private get
wsConnectionUrl(): URL
{
232 this.stationInfo?.supervisionUrlOcppConfiguration === true &&
233 isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) &&
234 isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)?.value)
235 ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)!.value
236 : this.configuredSupervisionUrl.href
237 }/${this.stationInfo.chargingStationId}`,
241 public logPrefix
= (): string => {
242 if (isNotEmptyString(this?.stationInfo
?.chargingStationId
)) {
243 return logPrefix(` ${this?.stationInfo?.chargingStationId} |`);
245 let stationTemplate
: ChargingStationTemplate
| undefined;
247 stationTemplate
= JSON
.parse(
248 readFileSync(this.templateFile
, 'utf8'),
249 ) as ChargingStationTemplate
;
251 stationTemplate
= undefined;
253 return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`);
256 public hasIdTags(): boolean {
257 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)!));
260 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number {
261 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
262 switch (this.getCurrentOutType(stationInfo
)) {
264 return localStationInfo
.numberOfPhases
?? 3;
270 public isWebSocketConnectionOpened(): boolean {
271 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
274 public inUnknownState(): boolean {
275 return isNullOrUndefined(this?.bootNotificationResponse
?.status);
278 public inPendingState(): boolean {
279 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
282 public inAcceptedState(): boolean {
283 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
286 public inRejectedState(): boolean {
287 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
290 public isRegistered(): boolean {
292 this.inUnknownState() === false &&
293 (this.inAcceptedState() === true || this.inPendingState() === true)
297 public isChargingStationAvailable(): boolean {
298 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
301 public hasConnector(connectorId
: number): boolean {
303 for (const evseStatus
of this.evses
.values()) {
304 if (evseStatus
.connectors
.has(connectorId
)) {
310 return this.connectors
.has(connectorId
);
313 public isConnectorAvailable(connectorId
: number): boolean {
316 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
320 public getNumberOfConnectors(): number {
322 let numberOfConnectors
= 0;
323 for (const [evseId
, evseStatus
] of this.evses
) {
325 numberOfConnectors
+= evseStatus
.connectors
.size
;
328 return numberOfConnectors
;
330 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
333 public getNumberOfEvses(): number {
334 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
337 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
339 for (const evseStatus
of this.evses
.values()) {
340 if (evseStatus
.connectors
.has(connectorId
)) {
341 return evseStatus
.connectors
.get(connectorId
);
346 return this.connectors
.get(connectorId
);
349 public getConnectorMaximumAvailablePower(connectorId
: number): number {
350 let connectorAmperageLimitationPowerLimit
: number | undefined;
352 !isNullOrUndefined(this.getAmperageLimitation()) &&
353 this.getAmperageLimitation()! < this.stationInfo
.maximumAmperage
!
355 connectorAmperageLimitationPowerLimit
=
356 (this.stationInfo
?.currentOutType
=== CurrentType
.AC
357 ? ACElectricUtils
.powerTotal(
358 this.getNumberOfPhases(),
359 this.stationInfo
.voltageOut
!,
360 this.getAmperageLimitation()! *
361 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
363 : DCElectricUtils
.power(this.stationInfo
.voltageOut
!, this.getAmperageLimitation()!)) /
366 const connectorMaximumPower
= this.stationInfo
.maximumPower
! / this.powerDivider
;
367 const connectorChargingProfilesPowerLimit
=
368 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
370 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
371 isNaN(connectorAmperageLimitationPowerLimit
!)
373 : connectorAmperageLimitationPowerLimit
!,
374 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!,
378 public getTransactionIdTag(transactionId
: number): string | undefined {
380 for (const evseStatus
of this.evses
.values()) {
381 for (const connectorStatus
of evseStatus
.connectors
.values()) {
382 if (connectorStatus
.transactionId
=== transactionId
) {
383 return connectorStatus
.transactionIdTag
;
388 for (const connectorId
of this.connectors
.keys()) {
389 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
390 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
396 public getNumberOfRunningTransactions(): number {
397 let numberOfRunningTransactions
= 0;
399 for (const [evseId
, evseStatus
] of this.evses
) {
403 for (const connectorStatus
of evseStatus
.connectors
.values()) {
404 if (connectorStatus
.transactionStarted
=== true) {
405 ++numberOfRunningTransactions
;
410 for (const connectorId
of this.connectors
.keys()) {
411 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
412 ++numberOfRunningTransactions
;
416 return numberOfRunningTransactions
;
419 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
421 for (const evseStatus
of this.evses
.values()) {
422 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
423 if (connectorStatus
.transactionId
=== transactionId
) {
429 for (const connectorId
of this.connectors
.keys()) {
430 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
437 public getEnergyActiveImportRegisterByTransactionId(
438 transactionId
: number,
441 return this.getEnergyActiveImportRegister(
442 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
447 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
448 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
);
451 public getAuthorizeRemoteTxRequests(): boolean {
452 const authorizeRemoteTxRequests
= getConfigurationKey(
454 StandardParametersKey
.AuthorizeRemoteTxRequests
,
456 return authorizeRemoteTxRequests
!== undefined
457 ? convertToBoolean(authorizeRemoteTxRequests
.value
)
461 public getLocalAuthListEnabled(): boolean {
462 const localAuthListEnabled
= getConfigurationKey(
464 StandardParametersKey
.LocalAuthListEnabled
,
466 return localAuthListEnabled
!== undefined
467 ? convertToBoolean(localAuthListEnabled
.value
)
471 public getHeartbeatInterval(): number {
472 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
);
473 if (HeartbeatInterval
!== undefined) {
474 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
));
476 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
);
477 if (HeartBeatInterval
!== undefined) {
478 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
));
480 this.stationInfo
?.autoRegister
=== false &&
482 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
483 Constants.DEFAULT_HEARTBEAT_INTERVAL
486 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
489 public setSupervisionUrl(url
: string): void {
491 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
492 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
)
494 setConfigurationKeyValue(this, this.stationInfo
.supervisionUrlOcppKey
!, url
);
496 this.stationInfo
.supervisionUrls
= url
;
497 this.saveStationInfo();
498 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
502 public startHeartbeat(): void {
503 if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval
=== undefined) {
504 this.heartbeatSetInterval
= setInterval(() => {
505 this.ocppRequestService
506 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
509 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
513 }, this.getHeartbeatInterval());
515 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
516 this.getHeartbeatInterval(),
519 } else if (this.heartbeatSetInterval
!== undefined) {
521 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
522 this.getHeartbeatInterval(),
527 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`,
532 public restartHeartbeat(): void {
534 this.stopHeartbeat();
536 this.startHeartbeat();
539 public restartWebSocketPing(): void {
540 // Stop WebSocket ping
541 this.stopWebSocketPing();
542 // Start WebSocket ping
543 this.startWebSocketPing();
546 public startMeterValues(connectorId
: number, interval
: number): void {
547 if (connectorId
=== 0) {
549 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`,
553 if (!this.getConnectorStatus(connectorId
)) {
555 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
560 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
562 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started`,
566 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
567 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
570 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id`,
575 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
576 // FIXME: Implement OCPP version agnostic helpers
577 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
580 this.getConnectorStatus(connectorId
)!.transactionId
!,
583 this.ocppRequestService
584 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
586 RequestCommand
.METER_VALUES
,
589 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
590 meterValue
: [meterValue
],
595 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
602 `${this.logPrefix()} Charging station ${
603 StandardParametersKey.MeterValueSampleInterval
604 } configuration set to ${interval}, not sending MeterValues`,
609 public stopMeterValues(connectorId
: number) {
610 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
!== undefined) {
611 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
615 public start(): void {
616 if (this.started
=== false) {
617 if (this.starting
=== false) {
618 this.starting
= true;
619 if (this.stationInfo
?.enableStatistics
=== true) {
620 this.performanceStatistics
?.start();
622 this.openWSConnection();
623 // Monitor charging station template file
624 this.templateFileWatcher
= watchJsonFile(
626 FileType
.ChargingStationTemplate
,
629 (event
, filename
): void => {
630 if (isNotEmptyString(filename
) && event
=== 'change') {
633 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
635 } file have changed, reload`,
637 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
640 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
)!);
642 this.stopAutomaticTransactionGenerator();
643 delete this.automaticTransactionGeneratorConfiguration
;
644 if (this.getAutomaticTransactionGeneratorConfiguration().enable
=== true) {
645 this.startAutomaticTransactionGenerator();
647 if (this.stationInfo
?.enableStatistics
=== true) {
648 this.performanceStatistics
?.restart();
650 this.performanceStatistics
?.stop();
652 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
655 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
663 this.emit(ChargingStationEvents
.started
);
664 this.starting
= false;
666 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
669 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
673 public async stop(reason
?: StopTransactionReason
, stopTransactions
?: boolean): Promise
<void> {
674 if (this.started
=== true) {
675 if (this.stopping
=== false) {
676 this.stopping
= true;
677 await this.stopMessageSequence(reason
, stopTransactions
);
678 this.closeWSConnection();
679 if (this.stationInfo
?.enableStatistics
=== true) {
680 this.performanceStatistics
?.stop();
682 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
683 this.templateFileWatcher
?.close();
684 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
685 delete this.bootNotificationResponse
;
686 this.started
= false;
687 this.saveConfiguration();
688 this.emit(ChargingStationEvents
.stopped
);
689 this.stopping
= false;
691 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
694 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
698 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
699 await this.stop(reason
);
700 await sleep(this.stationInfo
.resetTime
!);
705 public saveOcppConfiguration(): void {
706 if (this.stationInfo
?.ocppPersistentConfiguration
=== true) {
707 this.saveConfiguration();
711 public bufferMessage(message
: string): void {
712 this.messageBuffer
.add(message
);
713 this.setIntervalFlushMessageBuffer();
716 public openWSConnection(
718 params
?: { closeOpened
?: boolean; terminateOpened
?: boolean },
721 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
722 ...this.stationInfo
?.wsOptions
,
725 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
726 if (!checkChargingStation(this, this.logPrefix())) {
730 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
731 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
733 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
735 if (params
?.closeOpened
) {
736 this.closeWSConnection();
738 if (params
?.terminateOpened
) {
739 this.terminateWSConnection();
742 if (this.isWebSocketConnectionOpened() === true) {
744 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`,
750 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`,
753 this.wsConnection
= new WebSocket(
754 this.wsConnectionUrl
,
755 `ocpp${this.stationInfo?.ocppVersion}`,
759 // Handle WebSocket message
760 this.wsConnection
.on(
762 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void,
764 // Handle WebSocket error
765 this.wsConnection
.on(
767 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void,
769 // Handle WebSocket close
770 this.wsConnection
.on(
772 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void,
774 // Handle WebSocket open
775 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
776 // Handle WebSocket ping
777 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
778 // Handle WebSocket pong
779 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
782 public closeWSConnection(): void {
783 if (this.isWebSocketConnectionOpened() === true) {
784 this.wsConnection
?.close();
785 this.wsConnection
= null;
789 public getAutomaticTransactionGeneratorConfiguration(): AutomaticTransactionGeneratorConfiguration
{
790 if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration
)) {
791 let automaticTransactionGeneratorConfiguration
:
792 | AutomaticTransactionGeneratorConfiguration
794 const stationTemplate
= this.getTemplateFromFile();
795 const stationConfiguration
= this.getConfigurationFromFile();
797 this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true &&
798 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
799 stationConfiguration
?.automaticTransactionGenerator
801 automaticTransactionGeneratorConfiguration
=
802 stationConfiguration
?.automaticTransactionGenerator
;
804 automaticTransactionGeneratorConfiguration
= stationTemplate
?.AutomaticTransactionGenerator
;
806 this.automaticTransactionGeneratorConfiguration
= {
807 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
808 ...automaticTransactionGeneratorConfiguration
,
811 return this.automaticTransactionGeneratorConfiguration
!;
814 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
815 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
818 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
819 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
820 if (isNotEmptyArray(connectorIds
)) {
821 for (const connectorId
of connectorIds
!) {
822 this.automaticTransactionGenerator
?.startConnector(connectorId
);
825 this.automaticTransactionGenerator
?.start();
827 this.saveAutomaticTransactionGeneratorConfiguration();
828 this.emit(ChargingStationEvents
.updated
);
831 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
832 if (isNotEmptyArray(connectorIds
)) {
833 for (const connectorId
of connectorIds
!) {
834 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
837 this.automaticTransactionGenerator
?.stop();
839 this.saveAutomaticTransactionGeneratorConfiguration();
840 this.emit(ChargingStationEvents
.updated
);
843 public async stopTransactionOnConnector(
845 reason
?: StopTransactionReason
,
846 ): Promise
<StopTransactionResponse
> {
847 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
849 this.stationInfo
?.beginEndMeterValues
=== true &&
850 this.stationInfo
?.ocppStrictCompliance
=== true &&
851 this.stationInfo
?.outOfOrderEndMeterValues
=== false
853 // FIXME: Implement OCPP version agnostic helpers
854 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
857 this.getEnergyActiveImportRegisterByTransactionId(transactionId
!),
859 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
861 RequestCommand
.METER_VALUES
,
865 meterValue
: [transactionEndMeterValue
],
869 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
871 RequestCommand
.STOP_TRANSACTION
,
874 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
!, true),
875 ...(isNullOrUndefined(reason
) && { reason
}),
880 public getReserveConnectorZeroSupported(): boolean {
881 return convertToBoolean(
882 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
,
886 public async addReservation(reservation
: Reservation
): Promise
<void> {
887 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
);
888 if (reservationFound
!== undefined) {
889 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
);
891 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
;
892 await sendAndSetConnectorStatus(
894 reservation
.connectorId
,
895 ConnectorStatusEnum
.Reserved
,
897 { send
: reservation
.connectorId
!== 0 },
901 public async removeReservation(
902 reservation
: Reservation
,
903 reason
: ReservationTerminationReason
,
905 const connector
= this.getConnectorStatus(reservation
.connectorId
)!;
907 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
908 case ReservationTerminationReason
.TRANSACTION_STARTED
:
909 delete connector
.reservation
;
911 case ReservationTerminationReason
.RESERVATION_CANCELED
:
912 case ReservationTerminationReason
.REPLACE_EXISTING
:
913 case ReservationTerminationReason
.EXPIRED
:
914 await sendAndSetConnectorStatus(
916 reservation
.connectorId
,
917 ConnectorStatusEnum
.Available
,
919 { send
: reservation
.connectorId
!== 0 },
921 delete connector
.reservation
;
924 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
925 throw new BaseError(`Unknown reservation termination reason '${reason}'`);
929 public getReservationBy(
930 filterKey
: ReservationKey
,
931 value
: number | string,
932 ): Reservation
| undefined {
934 for (const evseStatus
of this.evses
.values()) {
935 for (const connectorStatus
of evseStatus
.connectors
.values()) {
936 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
937 return connectorStatus
.reservation
;
942 for (const connectorStatus
of this.connectors
.values()) {
943 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
944 return connectorStatus
.reservation
;
950 public isConnectorReservable(
951 reservationId
: number,
953 connectorId
?: number,
955 const reservation
= this.getReservationBy('reservationId', reservationId
);
956 const reservationExists
= !isUndefined(reservation
) && !hasReservationExpired(reservation
!);
957 if (arguments.length
=== 1) {
958 return !reservationExists
;
959 } else if (arguments.length
> 1) {
960 const userReservation
= !isUndefined(idTag
)
961 ? this.getReservationBy('idTag', idTag
!)
963 const userReservationExists
=
964 !isUndefined(userReservation
) && !hasReservationExpired(userReservation
!);
965 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
! > 0;
966 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
968 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
974 private setIntervalFlushMessageBuffer(): void {
975 if (this.flushMessageBufferSetInterval
=== undefined) {
976 this.flushMessageBufferSetInterval
= setInterval(() => {
977 if (this.isWebSocketConnectionOpened() === true && this.inAcceptedState() === true) {
978 this.flushMessageBuffer();
980 if (this.messageBuffer
.size
=== 0) {
981 this.clearIntervalFlushMessageBuffer();
983 }, Constants
.DEFAULT_MESSAGE_BUFFER_FLUSH_INTERVAL
);
987 private clearIntervalFlushMessageBuffer() {
988 if (this.flushMessageBufferSetInterval
!== undefined) {
989 clearInterval(this.flushMessageBufferSetInterval
);
990 delete this.flushMessageBufferSetInterval
;
994 private getNumberOfReservableConnectors(): number {
995 let numberOfReservableConnectors
= 0;
997 for (const evseStatus
of this.evses
.values()) {
998 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
);
1001 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
);
1003 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1006 private getNumberOfReservationsOnConnectorZero(): number {
1008 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1009 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) ||
1010 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
)
1017 private flushMessageBuffer(): void {
1018 if (this.messageBuffer
.size
> 0) {
1019 for (const message
of this.messageBuffer
.values()) {
1020 let beginId
: string | undefined;
1021 let commandName
: RequestCommand
| undefined;
1022 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1023 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1025 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1026 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1028 this.wsConnection
?.send(message
, (error
?: Error) => {
1029 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!);
1030 if (isNullOrUndefined(error
)) {
1032 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1034 )} OCPP message sent '${JSON.stringify(message)}'`,
1036 this.messageBuffer
.delete(message
);
1039 `${this.logPrefix()} >> Buffered ${getMessageTypeString(
1041 )} OCPP message '${JSON.stringify(message)}' send failed:`,
1050 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1051 let template
: ChargingStationTemplate
| undefined;
1053 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1054 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1056 const measureId
= `${FileType.ChargingStationTemplate} read`;
1057 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1058 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1059 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1060 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1061 .update(JSON
.stringify(template
))
1063 this.sharedLRUCache
.setChargingStationTemplate(template
);
1064 this.templateFileHash
= template
.templateHash
;
1067 handleFileException(
1069 FileType
.ChargingStationTemplate
,
1070 error
as NodeJS
.ErrnoException
,
1077 private getStationInfoFromTemplate(): ChargingStationInfo
{
1078 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile()!;
1079 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1080 const warnTemplateKeysDeprecationOnce
= once(warnTemplateKeysDeprecation
, this);
1081 warnTemplateKeysDeprecationOnce(stationTemplate
, this.logPrefix(), this.templateFile
);
1082 if (stationTemplate
?.Connectors
) {
1083 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1085 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1086 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1087 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1088 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1089 createSerialNumber(stationTemplate
, stationInfo
);
1090 stationInfo
.voltageOut
= this.getVoltageOut(stationInfo
);
1091 if (isNotEmptyArray(stationTemplate
?.power
)) {
1092 stationTemplate
.power
= stationTemplate
.power
as number[];
1093 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1094 stationInfo
.maximumPower
=
1095 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1096 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1097 : stationTemplate
.power
[powerArrayRandomIndex
];
1099 stationTemplate
.power
= stationTemplate
?.power
as number;
1100 stationInfo
.maximumPower
=
1101 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1102 ? stationTemplate
.power
* 1000
1103 : stationTemplate
.power
;
1105 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1106 stationInfo
.firmwareVersionPattern
=
1107 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1109 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1110 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!) === false
1113 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1115 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`,
1118 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1125 stationTemplate
?.firmwareUpgrade
?? {},
1127 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1128 ? secondsToMilliseconds(stationTemplate
.resetTime
!)
1129 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1133 private getStationInfoFromFile(
1134 stationInfoPersistentConfiguration
= true,
1135 ): ChargingStationInfo
| undefined {
1136 let stationInfo
: ChargingStationInfo
| undefined;
1137 if (stationInfoPersistentConfiguration
=== true) {
1138 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1140 delete stationInfo
?.infoHash
;
1146 private getStationInfo(): ChargingStationInfo
{
1147 const defaultStationInfo
: Partial
<ChargingStationInfo
> = {
1148 enableStatistics
: false,
1149 remoteAuthorization
: true,
1150 currentOutType
: CurrentType
.AC
,
1151 mainVoltageMeterValues
: true,
1152 phaseLineToLineVoltageMeterValues
: false,
1153 customValueLimitationMeterValues
: true,
1154 ocppStrictCompliance
: true,
1155 outOfOrderEndMeterValues
: false,
1156 beginEndMeterValues
: false,
1157 meteringPerTransaction
: true,
1158 transactionDataMeterValues
: false,
1159 supervisionUrlOcppConfiguration
: false,
1160 supervisionUrlOcppKey
: VendorParametersKey
.ConnectionUrl
,
1161 ocppVersion
: OCPPVersion
.VERSION_16
,
1162 ocppPersistentConfiguration
: true,
1163 stationInfoPersistentConfiguration
: true,
1164 automaticTransactionGeneratorPersistentConfiguration
: true,
1165 autoReconnectMaxRetries
: -1,
1166 registrationMaxRetries
: -1,
1167 reconnectExponentialDelay
: false,
1168 stopTransactionsOnStopped
: true,
1170 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1171 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile(
1172 stationInfoFromTemplate
?.stationInfoPersistentConfiguration
,
1175 // 1. charging station info from template
1176 // 2. charging station info from configuration file
1177 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1178 return { ...defaultStationInfo
, ...stationInfoFromFile
! };
1180 stationInfoFromFile
&&
1181 propagateSerialNumber(
1182 this.getTemplateFromFile()!,
1183 stationInfoFromFile
,
1184 stationInfoFromTemplate
,
1186 return { ...defaultStationInfo
, ...stationInfoFromTemplate
};
1189 private saveStationInfo(): void {
1190 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true) {
1191 this.saveConfiguration();
1195 private handleUnsupportedVersion(version
: OCPPVersion
| undefined) {
1196 const errorMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1197 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1198 throw new BaseError(errorMsg
);
1201 private initialize(): void {
1202 const stationTemplate
= this.getTemplateFromFile()!;
1203 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1204 this.configurationFile
= join(
1205 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1206 `${getHashId(this.index, stationTemplate)}.json`,
1208 const stationConfiguration
= this.getConfigurationFromFile();
1210 stationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1211 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1212 (stationConfiguration
?.connectorsStatus
|| stationConfiguration
?.evsesStatus
)
1214 checkConfiguration(stationConfiguration
, this.logPrefix(), this.configurationFile
);
1215 this.initializeConnectorsOrEvsesFromFile(stationConfiguration
);
1217 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1219 this.stationInfo
= this.getStationInfo();
1221 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1222 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1223 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1225 const patternGroup
: number | undefined =
1226 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1227 this.stationInfo
.firmwareVersion
?.split('.').length
;
1228 const match
= this.stationInfo
1229 .firmwareVersion
!.match(new RegExp(this.stationInfo
.firmwareVersionPattern
!))!
1230 .slice(1, patternGroup
! + 1);
1231 const patchLevelIndex
= match
.length
- 1;
1232 match
[patchLevelIndex
] = (
1233 convertToInt(match
[patchLevelIndex
]) +
1234 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1236 this.stationInfo
.firmwareVersion
= match
?.join('.');
1238 this.saveStationInfo();
1239 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1240 if (this.stationInfo
?.enableStatistics
=== true) {
1241 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1242 this.stationInfo
.hashId
,
1243 this.stationInfo
.chargingStationId
!,
1244 this.configuredSupervisionUrl
,
1247 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
);
1248 this.powerDivider
= this.getPowerDivider();
1249 // OCPP configuration
1250 this.ocppConfiguration
= this.getOcppConfiguration();
1251 this.initializeOcppConfiguration();
1252 this.initializeOcppServices();
1253 this.once(ChargingStationEvents
.accepted
, () => {
1254 this.startMessageSequence().catch((error
) => {
1255 logger
.error(`${this.logPrefix()} Error while starting the message sequence:`, error
);
1258 if (this.stationInfo
?.autoRegister
=== true) {
1259 this.bootNotificationResponse
= {
1260 currentTime
: new Date(),
1261 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1262 status: RegistrationStatusEnumType
.ACCEPTED
,
1267 private initializeOcppServices(): void {
1268 const ocppVersion
= this.stationInfo
?.ocppVersion
;
1269 switch (ocppVersion
) {
1270 case OCPPVersion
.VERSION_16
:
1271 this.ocppIncomingRequestService
=
1272 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1273 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1274 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(),
1277 case OCPPVersion
.VERSION_20
:
1278 case OCPPVersion
.VERSION_201
:
1279 this.ocppIncomingRequestService
=
1280 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1281 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1282 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>(),
1286 this.handleUnsupportedVersion(ocppVersion
);
1291 private initializeOcppConfiguration(): void {
1292 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
))) {
1293 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0');
1295 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
))) {
1296 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false });
1299 this.stationInfo
?.supervisionUrlOcppConfiguration
=== true &&
1300 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
) &&
1301 isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!))
1303 addConfigurationKey(
1305 this.stationInfo
.supervisionUrlOcppKey
!,
1306 this.configuredSupervisionUrl
.href
,
1310 this.stationInfo
?.supervisionUrlOcppConfiguration
=== false &&
1311 isNotEmptyString(this.stationInfo
?.supervisionUrlOcppKey
) &&
1312 !isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!))
1314 deleteConfigurationKey(this, this.stationInfo
.supervisionUrlOcppKey
!, { save
: false });
1317 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1318 isNullOrUndefined(getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!))
1320 addConfigurationKey(
1322 this.stationInfo
.amperageLimitationOcppKey
!,
1324 this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)
1329 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
))
1331 addConfigurationKey(
1333 StandardParametersKey
.SupportedFeatureProfiles
,
1334 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`,
1337 addConfigurationKey(
1339 StandardParametersKey
.NumberOfConnectors
,
1340 this.getNumberOfConnectors().toString(),
1342 { overwrite
: true },
1345 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
))
1347 addConfigurationKey(
1349 StandardParametersKey
.MeterValuesSampledData
,
1350 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
1354 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
))
1356 const connectorsPhaseRotation
: string[] = [];
1357 if (this.hasEvses
) {
1358 for (const evseStatus
of this.evses
.values()) {
1359 for (const connectorId
of evseStatus
.connectors
.keys()) {
1360 connectorsPhaseRotation
.push(
1361 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1366 for (const connectorId
of this.connectors
.keys()) {
1367 connectorsPhaseRotation
.push(
1368 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1372 addConfigurationKey(
1374 StandardParametersKey
.ConnectorPhaseRotation
,
1375 connectorsPhaseRotation
.toString(),
1379 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
))
1381 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1384 isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
)) &&
1385 getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)?.value
?.includes(
1386 SupportedFeatureProfiles
.LocalAuthListManagement
,
1389 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false');
1391 if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
))) {
1392 addConfigurationKey(
1394 StandardParametersKey
.ConnectionTimeOut
,
1395 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString(),
1398 this.saveOcppConfiguration();
1401 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1402 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1403 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1404 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1406 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1407 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1408 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1409 delete evseStatus
.connectorsStatus
;
1410 this.evses
.set(evseId
, {
1411 ...(evseStatus
as EvseStatus
),
1412 connectors
: new Map
<number, ConnectorStatus
>(
1413 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1420 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1421 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1422 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1423 throw new BaseError(errorMsg
);
1425 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1426 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1427 throw new BaseError(errorMsg
);
1431 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1432 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1433 this.initializeConnectorsFromTemplate(stationTemplate
);
1434 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1435 this.initializeEvsesFromTemplate(stationTemplate
);
1436 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1437 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1438 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1439 throw new BaseError(errorMsg
);
1441 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1442 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1443 throw new BaseError(errorMsg
);
1447 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1448 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1449 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1450 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1451 throw new BaseError(errorMsg
);
1453 if (!stationTemplate
?.Connectors
?.[0]) {
1455 `${this.logPrefix()} Charging station information from template ${
1457 } with no connector id 0 configuration`,
1460 if (stationTemplate
?.Connectors
) {
1461 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1462 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1463 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1465 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`,
1468 const connectorsConfigChanged
=
1469 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1470 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1471 connectorsConfigChanged
&& this.connectors
.clear();
1472 this.connectorsConfigurationHash
= connectorsConfigHash
;
1473 if (templateMaxConnectors
> 0) {
1474 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1476 connectorId
=== 0 &&
1477 (!stationTemplate
?.Connectors
?.[connectorId
] ||
1478 this.getUseConnectorId0(stationTemplate
) === false)
1482 const templateConnectorId
=
1483 connectorId
> 0 && stationTemplate
?.randomConnectors
1484 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1486 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1487 checkStationInfoConnectorStatus(
1488 templateConnectorId
,
1493 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1495 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1496 this.saveConnectorsStatus();
1499 `${this.logPrefix()} Charging station information from template ${
1501 } with no connectors configuration defined, cannot create connectors`,
1507 `${this.logPrefix()} Charging station information from template ${
1509 } with no connectors configuration defined, using already defined connectors`,
1514 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1515 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1516 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1517 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1518 throw new BaseError(errorMsg
);
1520 if (!stationTemplate
?.Evses
?.[0]) {
1522 `${this.logPrefix()} Charging station information from template ${
1524 } with no evse id 0 configuration`,
1527 if (!stationTemplate
?.Evses
?.[0]?.Connectors
?.[0]) {
1529 `${this.logPrefix()} Charging station information from template ${
1531 } with evse id 0 with no connector id 0 configuration`,
1534 if (Object.keys(stationTemplate
?.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1536 `${this.logPrefix()} Charging station information from template ${
1538 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`,
1541 if (stationTemplate
?.Evses
) {
1542 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1543 .update(JSON
.stringify(stationTemplate
?.Evses
))
1545 const evsesConfigChanged
=
1546 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1547 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1548 evsesConfigChanged
&& this.evses
.clear();
1549 this.evsesConfigurationHash
= evsesConfigHash
;
1550 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1551 if (templateMaxEvses
> 0) {
1552 for (const evseKey
in stationTemplate
.Evses
) {
1553 const evseId
= convertToInt(evseKey
);
1554 this.evses
.set(evseId
, {
1555 connectors
: buildConnectorsMap(
1556 stationTemplate
?.Evses
[evseKey
]?.Connectors
,
1560 availability
: AvailabilityType
.Operative
,
1562 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix());
1564 this.saveEvsesStatus();
1567 `${this.logPrefix()} Charging station information from template ${
1569 } with no evses configuration defined, cannot create evses`,
1575 `${this.logPrefix()} Charging station information from template ${
1577 } with no evses configuration defined, using already defined evses`,
1582 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1583 let configuration
: ChargingStationConfiguration
| undefined;
1584 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1586 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1587 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1588 this.configurationFileHash
,
1591 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1592 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1593 configuration
= JSON
.parse(
1594 readFileSync(this.configurationFile
, 'utf8'),
1595 ) as ChargingStationConfiguration
;
1596 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1597 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1598 this.configurationFileHash
= configuration
.configurationHash
!;
1601 handleFileException(
1602 this.configurationFile
,
1603 FileType
.ChargingStationConfiguration
,
1604 error
as NodeJS
.ErrnoException
,
1609 return configuration
;
1612 private saveAutomaticTransactionGeneratorConfiguration(): void {
1613 if (this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
=== true) {
1614 this.saveConfiguration();
1618 private saveConnectorsStatus() {
1619 this.saveConfiguration();
1622 private saveEvsesStatus() {
1623 this.saveConfiguration();
1626 private saveConfiguration(): void {
1627 if (isNotEmptyString(this.configurationFile
)) {
1629 if (!existsSync(dirname(this.configurationFile
))) {
1630 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1632 let configurationData
: ChargingStationConfiguration
= this.getConfigurationFromFile()
1633 ? cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()!)
1635 if (this.stationInfo
?.stationInfoPersistentConfiguration
=== true && this.stationInfo
) {
1636 configurationData
.stationInfo
= this.stationInfo
;
1638 delete configurationData
.stationInfo
;
1641 this.stationInfo
?.ocppPersistentConfiguration
=== true &&
1642 Array.isArray(this.ocppConfiguration
?.configurationKey
)
1644 configurationData
.configurationKey
= this.ocppConfiguration
?.configurationKey
;
1646 delete configurationData
.configurationKey
;
1648 configurationData
= merge
<ChargingStationConfiguration
>(
1650 buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
1653 !this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
||
1654 !this.getAutomaticTransactionGeneratorConfiguration()
1656 delete configurationData
.automaticTransactionGenerator
;
1658 if (this.connectors
.size
> 0) {
1659 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1661 delete configurationData
.connectorsStatus
;
1663 if (this.evses
.size
> 0) {
1664 configurationData
.evsesStatus
= buildEvsesStatus(this);
1666 delete configurationData
.evsesStatus
;
1668 delete configurationData
.configurationHash
;
1669 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1672 stationInfo
: configurationData
.stationInfo
,
1673 configurationKey
: configurationData
.configurationKey
,
1674 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1675 ...(this.connectors
.size
> 0 && {
1676 connectorsStatus
: configurationData
.connectorsStatus
,
1678 ...(this.evses
.size
> 0 && { evsesStatus
: configurationData
.evsesStatus
}),
1679 } as ChargingStationConfiguration
),
1682 if (this.configurationFileHash
!== configurationHash
) {
1683 AsyncLock
.runExclusive(AsyncLockType
.configuration
, () => {
1684 configurationData
.configurationHash
= configurationHash
;
1685 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1686 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1688 this.configurationFile
,
1689 JSON
.stringify(configurationData
, undefined, 2),
1692 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1693 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1694 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1695 this.configurationFileHash
= configurationHash
;
1696 }).catch((error
) => {
1697 handleFileException(
1698 this.configurationFile
,
1699 FileType
.ChargingStationConfiguration
,
1700 error
as NodeJS
.ErrnoException
,
1706 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1707 this.configurationFile
1712 handleFileException(
1713 this.configurationFile
,
1714 FileType
.ChargingStationConfiguration
,
1715 error
as NodeJS
.ErrnoException
,
1721 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`,
1726 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1727 return this.getTemplateFromFile()?.Configuration
;
1730 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1731 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1732 if (this.stationInfo
?.ocppPersistentConfiguration
=== true && Array.isArray(configurationKey
)) {
1733 return { configurationKey
};
1738 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1739 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1740 this.getOcppConfigurationFromFile();
1741 if (!ocppConfiguration
) {
1742 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1744 return ocppConfiguration
;
1747 private async onOpen(): Promise
<void> {
1748 if (this.isWebSocketConnectionOpened() === true) {
1750 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`,
1752 let registrationRetryCount
= 0;
1753 if (this.isRegistered() === false) {
1754 // Send BootNotification
1756 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1757 BootNotificationRequest
,
1758 BootNotificationResponse
1759 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1760 skipBufferingOnError
: true,
1762 if (this.isRegistered() === false) {
1763 this.stationInfo
?.registrationMaxRetries
!== -1 && ++registrationRetryCount
;
1765 this?.bootNotificationResponse
?.interval
1766 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1767 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
,
1771 this.isRegistered() === false &&
1772 (registrationRetryCount
<= this.stationInfo
.registrationMaxRetries
! ||
1773 this.stationInfo
?.registrationMaxRetries
=== -1)
1776 if (this.isRegistered() === true) {
1777 this.emit(ChargingStationEvents
.registered
);
1778 if (this.inAcceptedState() === true) {
1779 this.emit(ChargingStationEvents
.accepted
);
1783 `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${this
1784 .stationInfo?.registrationMaxRetries})`,
1787 this.autoReconnectRetryCount
= 0;
1788 this.emit(ChargingStationEvents
.updated
);
1791 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`,
1796 private async onClose(code
: WebSocketCloseEventStatusCode
, reason
: Buffer
): Promise
<void> {
1799 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1800 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1802 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1804 )}' and reason '${reason.toString()}'`,
1806 this.autoReconnectRetryCount
= 0;
1811 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1813 )}' and reason '${reason.toString()}'`,
1815 this.started
=== true && (await this.reconnect());
1818 this.emit(ChargingStationEvents
.updated
);
1821 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1822 const cachedRequest
= this.requests
.get(messageId
);
1823 if (Array.isArray(cachedRequest
) === true) {
1824 return cachedRequest
;
1826 throw new OCPPError(
1827 ErrorType
.PROTOCOL_ERROR
,
1828 `Cached request for message id ${messageId} ${getMessageTypeString(
1830 )} is not an array`,
1832 cachedRequest
as JsonType
,
1836 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1837 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1838 if (this.stationInfo
?.enableStatistics
=== true) {
1839 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1842 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1846 // Process the message
1847 await this.ocppIncomingRequestService
.incomingRequestHandler(
1853 this.emit(ChargingStationEvents
.updated
);
1856 private handleResponseMessage(response
: Response
): void {
1857 const [messageType
, messageId
, commandPayload
] = response
;
1858 if (this.requests
.has(messageId
) === false) {
1860 throw new OCPPError(
1861 ErrorType
.INTERNAL_ERROR
,
1862 `Response for unknown message id ${messageId}`,
1868 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1873 `${this.logPrefix()} << Command '${
1874 requestCommandName ?? Constants.UNKNOWN_COMMAND
1875 }' received response payload: ${JSON.stringify(response)}`,
1877 responseCallback(commandPayload
, requestPayload
);
1880 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1881 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1882 if (this.requests
.has(messageId
) === false) {
1884 throw new OCPPError(
1885 ErrorType
.INTERNAL_ERROR
,
1886 `Error response for unknown message id ${messageId}`,
1888 { errorType
, errorMessage
, errorDetails
},
1891 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1893 `${this.logPrefix()} << Command '${
1894 requestCommandName ?? Constants.UNKNOWN_COMMAND
1895 }' received error response payload: ${JSON.stringify(errorResponse)}`,
1897 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1900 private async onMessage(data
: RawData
): Promise
<void> {
1901 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined;
1902 let messageType
: MessageType
| undefined;
1903 let errorMsg
: string;
1905 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1906 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1907 if (Array.isArray(request
) === true) {
1908 [messageType
] = request
;
1909 // Check the type of message
1910 switch (messageType
) {
1912 case MessageType
.CALL_MESSAGE
:
1913 await this.handleIncomingMessage(request
as IncomingRequest
);
1916 case MessageType
.CALL_RESULT_MESSAGE
:
1917 this.handleResponseMessage(request
as Response
);
1920 case MessageType
.CALL_ERROR_MESSAGE
:
1921 this.handleErrorMessage(request
as ErrorResponse
);
1925 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1926 errorMsg
= `Wrong message type ${messageType}`;
1927 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1928 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1931 throw new OCPPError(
1932 ErrorType
.PROTOCOL_ERROR
,
1933 'Incoming message is not an array',
1941 let commandName
: IncomingRequestCommand
| undefined;
1942 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined;
1943 let errorCallback
: ErrorCallback
;
1944 const [, messageId
] = request
!;
1945 switch (messageType
) {
1946 case MessageType
.CALL_MESSAGE
:
1947 [, , commandName
] = request
as IncomingRequest
;
1949 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1951 case MessageType
.CALL_RESULT_MESSAGE
:
1952 case MessageType
.CALL_ERROR_MESSAGE
:
1953 if (this.requests
.has(messageId
) === true) {
1954 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1955 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1956 errorCallback(error
as OCPPError
, false);
1958 // Remove the request from the cache in case of error at response handling
1959 this.requests
.delete(messageId
);
1963 if (error
instanceof OCPPError
=== false) {
1965 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1966 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1967 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1968 }' message '${data.toString()}' handling is not an OCPPError:`,
1973 `${this.logPrefix()} Incoming OCPP command '${
1974 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1975 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1976 }' message '${data.toString()}'${
1977 messageType !== MessageType.CALL_MESSAGE
1978 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1980 } processing error:`,
1986 private onPing(): void {
1987 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1990 private onPong(): void {
1991 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1994 private onError(error
: WSError
): void {
1995 this.closeWSConnection();
1996 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1999 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2000 if (this.stationInfo
?.meteringPerTransaction
=== true) {
2003 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
2004 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2009 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2010 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2014 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2015 return stationTemplate
?.useConnectorId0
?? true;
2018 private async stopRunningTransactions(reason
?: StopTransactionReason
): Promise
<void> {
2019 if (this.hasEvses
) {
2020 for (const [evseId
, evseStatus
] of this.evses
) {
2024 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2025 if (connectorStatus
.transactionStarted
=== true) {
2026 await this.stopTransactionOnConnector(connectorId
, reason
);
2031 for (const connectorId
of this.connectors
.keys()) {
2032 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2033 await this.stopTransactionOnConnector(connectorId
, reason
);
2040 private getConnectionTimeout(): number {
2041 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
) !== undefined) {
2042 return convertToInt(
2043 getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)!.value
! ??
2044 Constants
.DEFAULT_CONNECTION_TIMEOUT
,
2047 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2050 private getPowerDivider(): number {
2051 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2052 if (this.stationInfo
?.powerSharedByConnectors
=== true) {
2053 powerDivider
= this.getNumberOfRunningTransactions();
2055 return powerDivider
;
2058 private getMaximumAmperage(stationInfo
?: ChargingStationInfo
): number | undefined {
2059 const maximumPower
= (stationInfo
?? this.stationInfo
).maximumPower
!;
2060 switch (this.getCurrentOutType(stationInfo
)) {
2061 case CurrentType
.AC
:
2062 return ACElectricUtils
.amperagePerPhaseFromPower(
2063 this.getNumberOfPhases(stationInfo
),
2064 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2065 this.getVoltageOut(stationInfo
),
2067 case CurrentType
.DC
:
2068 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2072 private getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
2073 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
2076 private getVoltageOut(stationInfo
?: ChargingStationInfo
): Voltage
{
2078 (stationInfo
?? this.stationInfo
).voltageOut
??
2079 getDefaultVoltageOut(this.getCurrentOutType(stationInfo
), this.logPrefix(), this.templateFile
)
2083 private getAmperageLimitation(): number | undefined {
2085 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2086 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!) !== undefined
2090 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)?.value
,
2091 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2096 private async startMessageSequence(): Promise
<void> {
2097 if (this.stationInfo
?.autoRegister
=== true) {
2098 await this.ocppRequestService
.requestHandler
<
2099 BootNotificationRequest
,
2100 BootNotificationResponse
2101 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2102 skipBufferingOnError
: true,
2105 // Start WebSocket ping
2106 this.startWebSocketPing();
2108 this.startHeartbeat();
2109 // Initialize connectors status
2110 if (this.hasEvses
) {
2111 for (const [evseId
, evseStatus
] of this.evses
) {
2113 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2114 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2115 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
, evseId
);
2120 for (const connectorId
of this.connectors
.keys()) {
2121 if (connectorId
> 0) {
2122 const connectorBootStatus
= getBootConnectorStatus(
2125 this.getConnectorStatus(connectorId
)!,
2127 await sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2131 if (this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
) {
2132 await this.ocppRequestService
.requestHandler
<
2133 FirmwareStatusNotificationRequest
,
2134 FirmwareStatusNotificationResponse
2135 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2136 status: FirmwareStatus
.Installed
,
2138 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2142 if (this.getAutomaticTransactionGeneratorConfiguration().enable
=== true) {
2143 this.startAutomaticTransactionGenerator();
2145 this.flushMessageBuffer();
2148 private async stopMessageSequence(
2149 reason
?: StopTransactionReason
,
2150 stopTransactions
= this.stationInfo
?.stopTransactionsOnStopped
,
2152 // Stop WebSocket ping
2153 this.stopWebSocketPing();
2155 this.stopHeartbeat();
2157 if (this.automaticTransactionGenerator
?.started
=== true) {
2158 this.stopAutomaticTransactionGenerator();
2160 // Stop ongoing transactions
2161 stopTransactions
&& (await this.stopRunningTransactions(reason
));
2162 if (this.hasEvses
) {
2163 for (const [evseId
, evseStatus
] of this.evses
) {
2165 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2166 await this.ocppRequestService
.requestHandler
<
2167 StatusNotificationRequest
,
2168 StatusNotificationResponse
2171 RequestCommand
.STATUS_NOTIFICATION
,
2172 buildStatusNotificationRequest(
2175 ConnectorStatusEnum
.Unavailable
,
2179 delete connectorStatus
?.status;
2184 for (const connectorId
of this.connectors
.keys()) {
2185 if (connectorId
> 0) {
2186 await this.ocppRequestService
.requestHandler
<
2187 StatusNotificationRequest
,
2188 StatusNotificationResponse
2191 RequestCommand
.STATUS_NOTIFICATION
,
2192 buildStatusNotificationRequest(this, connectorId
, 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})`,