1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { createHash
} from
'node:crypto';
13 import { dirname
, join
} from
'node:path';
14 import { URL
} from
'node:url';
15 import { parentPort
} from
'node:worker_threads';
17 import { millisecondsToSeconds
, secondsToMilliseconds
} from
'date-fns';
18 import merge from
'just-merge';
19 import { type RawData
, WebSocket
} from
'ws';
21 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
22 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
25 deleteConfigurationKey
,
27 setConfigurationKeyValue
,
28 } from
'./ConfigurationKeyUtils';
32 checkConnectorsConfiguration
,
33 checkStationInfoConnectorStatus
,
35 createBootNotificationRequest
,
37 getAmperageLimitationUnitDivider
,
38 getBootConnectorStatus
,
39 getChargingStationConnectorChargingProfilesPowerLimit
,
45 getNumberOfReservableConnectors
,
46 getPhaseRotationValue
,
48 hasReservationExpired
,
49 initializeConnectorsMapStatus
,
50 propagateSerialNumber
,
51 removeExpiredReservations
,
52 stationTemplateToStationInfo
,
53 warnTemplateKeysDeprecation
,
55 import { IdTagsCache
} from
'./IdTagsCache';
57 OCPP16IncomingRequestService
,
59 OCPP16ResponseService
,
61 OCPP20IncomingRequestService
,
63 OCPP20ResponseService
,
64 type OCPPIncomingRequestService
,
65 type OCPPRequestService
,
68 import { SharedLRUCache
} from
'./SharedLRUCache';
69 import { BaseError
, OCPPError
} from
'../exception';
70 import { PerformanceStatistics
} from
'../performance';
72 type AutomaticTransactionGeneratorConfiguration
,
74 type BootNotificationRequest
,
75 type BootNotificationResponse
,
77 type ChargingStationConfiguration
,
78 type ChargingStationInfo
,
79 type ChargingStationOcppConfiguration
,
80 type ChargingStationTemplate
,
88 type EvseStatusConfiguration
,
91 type FirmwareStatusNotificationRequest
,
92 type FirmwareStatusNotificationResponse
,
94 type HeartbeatRequest
,
95 type HeartbeatResponse
,
97 type IncomingRequestCommand
,
102 type MeterValuesRequest
,
103 type MeterValuesResponse
,
105 type OutgoingRequest
,
107 RegistrationStatusEnumType
,
111 ReservationTerminationReason
,
113 StandardParametersKey
,
115 type StatusNotificationRequest
,
116 type StatusNotificationResponse
,
117 StopTransactionReason
,
118 type StopTransactionRequest
,
119 type StopTransactionResponse
,
120 SupervisionUrlDistribution
,
121 SupportedFeatureProfiles
,
124 WebSocketCloseEventStatusCode
,
134 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
135 buildConnectorsStatus
,
144 formatDurationMilliSeconds
,
145 formatDurationSeconds
,
147 getWebSocketCloseEventStatusString
,
161 export class ChargingStation
{
162 public readonly index
: number;
163 public readonly templateFile
: string;
164 public stationInfo
!: ChargingStationInfo
;
165 public started
: boolean;
166 public starting
: boolean;
167 public idTagsCache
: IdTagsCache
;
168 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
169 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
170 public wsConnection
!: WebSocket
| null;
171 public readonly connectors
: Map
<number, ConnectorStatus
>;
172 public readonly evses
: Map
<number, EvseStatus
>;
173 public readonly requests
: Map
<string, CachedRequest
>;
174 public performanceStatistics
!: PerformanceStatistics
| undefined;
175 public heartbeatSetInterval
?: NodeJS
.Timeout
;
176 public ocppRequestService
!: OCPPRequestService
;
177 public bootNotificationRequest
!: BootNotificationRequest
;
178 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
179 public powerDivider
!: number;
180 private stopping
: boolean;
181 private configurationFile
!: string;
182 private configurationFileHash
!: string;
183 private connectorsConfigurationHash
!: string;
184 private evsesConfigurationHash
!: string;
185 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
;
186 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
187 private readonly messageBuffer
: Set
<string>;
188 private configuredSupervisionUrl
!: URL
;
189 private wsConnectionRestarted
: boolean;
190 private autoReconnectRetryCount
: number;
191 private templateFileWatcher
!: FSWatcher
| undefined;
192 private templateFileHash
!: string;
193 private readonly sharedLRUCache
: SharedLRUCache
;
194 private webSocketPingSetInterval
?: NodeJS
.Timeout
;
195 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
196 private reservationExpirationSetInterval
?: NodeJS
.Timeout
;
198 constructor(index
: number, templateFile
: string) {
199 this.started
= false;
200 this.starting
= false;
201 this.stopping
= false;
202 this.wsConnectionRestarted
= false;
203 this.autoReconnectRetryCount
= 0;
205 this.templateFile
= templateFile
;
206 this.connectors
= new Map
<number, ConnectorStatus
>();
207 this.evses
= new Map
<number, EvseStatus
>();
208 this.requests
= new Map
<string, CachedRequest
>();
209 this.messageBuffer
= new Set
<string>();
210 this.sharedLRUCache
= SharedLRUCache
.getInstance();
211 this.idTagsCache
= IdTagsCache
.getInstance();
212 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
217 public get
hasEvses(): boolean {
218 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
221 private get
wsConnectionUrl(): URL
{
224 this.getSupervisionUrlOcppConfiguration() &&
225 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
226 isNotEmptyString(getConfigurationKey(this, this.getSupervisionUrlOcppKey())?.value)
227 ? getConfigurationKey(this, this.getSupervisionUrlOcppKey())!.value
228 : this.configuredSupervisionUrl.href
229 }/${this.stationInfo.chargingStationId}`,
233 public logPrefix
= (): string => {
236 (isNotEmptyString(this?.stationInfo?.chargingStationId)
237 ? this?.stationInfo?.chargingStationId
238 : getChargingStationId(this.index, this.getTemplateFromFile()!)) ??
239 'Error at building log prefix'
244 public hasIdTags(): boolean {
245 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)!));
248 public getEnableStatistics(): boolean {
249 return this.stationInfo
.enableStatistics
?? false;
252 public getRemoteAuthorization(): boolean {
253 return this.stationInfo
.remoteAuthorization
?? true;
256 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number {
257 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
258 switch (this.getCurrentOutType(stationInfo
)) {
260 return !isUndefined(localStationInfo
.numberOfPhases
) ? localStationInfo
.numberOfPhases
! : 3;
266 public isWebSocketConnectionOpened(): boolean {
267 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
270 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
271 return this?.bootNotificationResponse
?.status;
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 getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
350 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
353 public getOcppStrictCompliance(): boolean {
354 return this.stationInfo
?.ocppStrictCompliance
?? true;
357 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number {
358 const defaultVoltageOut
= getDefaultVoltageOut(
359 this.getCurrentOutType(stationInfo
),
363 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
366 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
367 const localStationInfo
= stationInfo
?? this.stationInfo
;
369 (localStationInfo
['maxPower' as keyof ChargingStationInfo
] as number) ??
370 localStationInfo
.maximumPower
374 public getConnectorMaximumAvailablePower(connectorId
: number): number {
375 let connectorAmperageLimitationPowerLimit
: number | undefined;
377 !isNullOrUndefined(this.getAmperageLimitation()) &&
378 this.getAmperageLimitation()! < this.stationInfo
.maximumAmperage
!
380 connectorAmperageLimitationPowerLimit
=
381 (this.getCurrentOutType() === CurrentType
.AC
382 ? ACElectricUtils
.powerTotal(
383 this.getNumberOfPhases(),
384 this.getVoltageOut(),
385 this.getAmperageLimitation()! *
386 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
388 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation()!)) /
391 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
392 const connectorChargingProfilesPowerLimit
=
393 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
395 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
396 isNaN(connectorAmperageLimitationPowerLimit
!)
398 : connectorAmperageLimitationPowerLimit
!,
399 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!,
403 public getTransactionIdTag(transactionId
: number): string | undefined {
405 for (const evseStatus
of this.evses
.values()) {
406 for (const connectorStatus
of evseStatus
.connectors
.values()) {
407 if (connectorStatus
.transactionId
=== transactionId
) {
408 return connectorStatus
.transactionIdTag
;
413 for (const connectorId
of this.connectors
.keys()) {
414 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
415 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
421 public getNumberOfRunningTransactions(): number {
422 let numberOfRunningTransactions
= 0;
424 for (const [evseId
, evseStatus
] of this.evses
) {
428 for (const connectorStatus
of evseStatus
.connectors
.values()) {
429 if (connectorStatus
.transactionStarted
=== true) {
430 ++numberOfRunningTransactions
;
435 for (const connectorId
of this.connectors
.keys()) {
436 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
437 ++numberOfRunningTransactions
;
441 return numberOfRunningTransactions
;
444 public getOutOfOrderEndMeterValues(): boolean {
445 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
448 public getBeginEndMeterValues(): boolean {
449 return this.stationInfo
?.beginEndMeterValues
?? false;
452 public getMeteringPerTransaction(): boolean {
453 return this.stationInfo
?.meteringPerTransaction
?? true;
456 public getTransactionDataMeterValues(): boolean {
457 return this.stationInfo
?.transactionDataMeterValues
?? false;
460 public getMainVoltageMeterValues(): boolean {
461 return this.stationInfo
?.mainVoltageMeterValues
?? true;
464 public getPhaseLineToLineVoltageMeterValues(): boolean {
465 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
468 public getCustomValueLimitationMeterValues(): boolean {
469 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
472 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
474 for (const evseStatus
of this.evses
.values()) {
475 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
476 if (connectorStatus
.transactionId
=== transactionId
) {
482 for (const connectorId
of this.connectors
.keys()) {
483 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
490 public getEnergyActiveImportRegisterByTransactionId(
491 transactionId
: number,
494 return this.getEnergyActiveImportRegister(
495 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
500 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
501 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
);
504 public getAuthorizeRemoteTxRequests(): boolean {
505 const authorizeRemoteTxRequests
= getConfigurationKey(
507 StandardParametersKey
.AuthorizeRemoteTxRequests
,
509 return authorizeRemoteTxRequests
? convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
512 public getLocalAuthListEnabled(): boolean {
513 const localAuthListEnabled
= getConfigurationKey(
515 StandardParametersKey
.LocalAuthListEnabled
,
517 return localAuthListEnabled
? convertToBoolean(localAuthListEnabled
.value
) : false;
520 public getHeartbeatInterval(): number {
521 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
);
522 if (HeartbeatInterval
) {
523 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
));
525 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
);
526 if (HeartBeatInterval
) {
527 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
));
529 this.stationInfo
?.autoRegister
=== false &&
531 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
532 Constants.DEFAULT_HEARTBEAT_INTERVAL
535 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
538 public setSupervisionUrl(url
: string): void {
540 this.getSupervisionUrlOcppConfiguration() &&
541 isNotEmptyString(this.getSupervisionUrlOcppKey())
543 setConfigurationKeyValue(this, this.getSupervisionUrlOcppKey(), url
);
545 this.stationInfo
.supervisionUrls
= url
;
546 this.saveStationInfo();
547 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
551 public startHeartbeat(): void {
552 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
553 this.heartbeatSetInterval
= setInterval(() => {
554 this.ocppRequestService
555 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
558 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
562 }, this.getHeartbeatInterval());
564 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
565 this.getHeartbeatInterval(),
568 } else if (this.heartbeatSetInterval
) {
570 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
571 this.getHeartbeatInterval(),
576 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()},
577 not starting the heartbeat`,
582 public restartHeartbeat(): void {
584 this.stopHeartbeat();
586 this.startHeartbeat();
589 public restartWebSocketPing(): void {
590 // Stop WebSocket ping
591 this.stopWebSocketPing();
592 // Start WebSocket ping
593 this.startWebSocketPing();
596 public startMeterValues(connectorId
: number, interval
: number): void {
597 if (connectorId
=== 0) {
599 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`,
603 if (!this.getConnectorStatus(connectorId
)) {
605 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
610 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
612 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
613 with no transaction started`,
617 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
618 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
621 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
622 with no transaction id`,
627 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
628 // FIXME: Implement OCPP version agnostic helpers
629 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
632 this.getConnectorStatus(connectorId
)!.transactionId
!,
635 this.ocppRequestService
636 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
638 RequestCommand
.METER_VALUES
,
641 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
642 meterValue
: [meterValue
],
647 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
654 `${this.logPrefix()} Charging station ${
655 StandardParametersKey.MeterValueSampleInterval
656 } configuration set to ${interval}, not sending MeterValues`,
661 public stopMeterValues(connectorId
: number) {
662 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
663 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
667 public start(): void {
668 if (this.started
=== false) {
669 if (this.starting
=== false) {
670 this.starting
= true;
671 if (this.getEnableStatistics() === true) {
672 this.performanceStatistics
?.start();
674 if (hasFeatureProfile(this, SupportedFeatureProfiles
.Reservation
)) {
675 this.startReservationExpirationSetInterval();
677 this.openWSConnection();
678 // Monitor charging station template file
679 this.templateFileWatcher
= watchJsonFile(
681 FileType
.ChargingStationTemplate
,
684 (event
, filename
): void => {
685 if (isNotEmptyString(filename
) && event
=== 'change') {
688 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
690 } file have changed, reload`,
692 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
695 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
)!);
697 this.stopAutomaticTransactionGenerator();
698 delete this.automaticTransactionGeneratorConfiguration
;
699 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
700 this.startAutomaticTransactionGenerator();
702 if (this.getEnableStatistics() === true) {
703 this.performanceStatistics
?.restart();
705 this.performanceStatistics
?.stop();
707 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
710 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
718 parentPort
?.postMessage(buildStartedMessage(this));
719 this.starting
= false;
721 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
724 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
728 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
729 if (this.started
=== true) {
730 if (this.stopping
=== false) {
731 this.stopping
= true;
732 await this.stopMessageSequence(reason
);
733 this.closeWSConnection();
734 if (this.getEnableStatistics() === true) {
735 this.performanceStatistics
?.stop();
737 if (hasFeatureProfile(this, SupportedFeatureProfiles
.Reservation
)) {
738 this.stopReservationExpirationSetInterval();
740 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
741 this.templateFileWatcher
?.close();
742 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
743 delete this.bootNotificationResponse
;
744 this.started
= false;
745 this.saveConfiguration();
746 parentPort
?.postMessage(buildStoppedMessage(this));
747 this.stopping
= false;
749 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
752 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
756 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
757 await this.stop(reason
);
758 await sleep(this.stationInfo
.resetTime
!);
763 public saveOcppConfiguration(): void {
764 if (this.getOcppPersistentConfiguration()) {
765 this.saveConfiguration();
769 public bufferMessage(message
: string): void {
770 this.messageBuffer
.add(message
);
773 public openWSConnection(
775 params
?: { closeOpened
?: boolean; terminateOpened
?: boolean },
778 handshakeTimeout
: secondsToMilliseconds(this.getConnectionTimeout()),
779 ...this.stationInfo
?.wsOptions
,
782 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
783 if (!checkChargingStation(this, this.logPrefix())) {
787 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
788 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
790 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
792 if (params
?.closeOpened
) {
793 this.closeWSConnection();
795 if (params
?.terminateOpened
) {
796 this.terminateWSConnection();
799 if (this.isWebSocketConnectionOpened() === true) {
801 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()}
808 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`,
811 this.wsConnection
= new WebSocket(
812 this.wsConnectionUrl
,
813 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
817 // Handle WebSocket message
818 this.wsConnection
.on(
820 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void,
822 // Handle WebSocket error
823 this.wsConnection
.on(
825 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void,
827 // Handle WebSocket close
828 this.wsConnection
.on(
830 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void,
832 // Handle WebSocket open
833 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
834 // Handle WebSocket ping
835 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
836 // Handle WebSocket pong
837 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
840 public closeWSConnection(): void {
841 if (this.isWebSocketConnectionOpened() === true) {
842 this.wsConnection
?.close();
843 this.wsConnection
= null;
847 public getAutomaticTransactionGeneratorConfiguration(): AutomaticTransactionGeneratorConfiguration
{
848 if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration
)) {
849 let automaticTransactionGeneratorConfiguration
:
850 | AutomaticTransactionGeneratorConfiguration
852 const automaticTransactionGeneratorConfigurationFromFile
=
853 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
855 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
856 automaticTransactionGeneratorConfigurationFromFile
858 automaticTransactionGeneratorConfiguration
=
859 automaticTransactionGeneratorConfigurationFromFile
;
861 automaticTransactionGeneratorConfiguration
=
862 this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
864 this.automaticTransactionGeneratorConfiguration
= {
865 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
866 ...automaticTransactionGeneratorConfiguration
,
869 return this.automaticTransactionGeneratorConfiguration
!;
872 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
873 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
876 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
877 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
878 if (isNotEmptyArray(connectorIds
)) {
879 for (const connectorId
of connectorIds
!) {
880 this.automaticTransactionGenerator
?.startConnector(connectorId
);
883 this.automaticTransactionGenerator
?.start();
885 this.saveAutomaticTransactionGeneratorConfiguration();
886 parentPort
?.postMessage(buildUpdatedMessage(this));
889 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
890 if (isNotEmptyArray(connectorIds
)) {
891 for (const connectorId
of connectorIds
!) {
892 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
895 this.automaticTransactionGenerator
?.stop();
897 this.saveAutomaticTransactionGeneratorConfiguration();
898 parentPort
?.postMessage(buildUpdatedMessage(this));
901 public async stopTransactionOnConnector(
903 reason
= StopTransactionReason
.NONE
,
904 ): Promise
<StopTransactionResponse
> {
905 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
907 this.getBeginEndMeterValues() === true &&
908 this.getOcppStrictCompliance() === true &&
909 this.getOutOfOrderEndMeterValues() === false
911 // FIXME: Implement OCPP version agnostic helpers
912 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
915 this.getEnergyActiveImportRegisterByTransactionId(transactionId
!),
917 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
919 RequestCommand
.METER_VALUES
,
923 meterValue
: [transactionEndMeterValue
],
927 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
929 RequestCommand
.STOP_TRANSACTION
,
932 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
!, true),
938 public getReserveConnectorZeroSupported(): boolean {
939 return convertToBoolean(
940 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
,
944 public async addReservation(reservation
: Reservation
): Promise
<void> {
945 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
);
946 if (!isUndefined(reservationFound
)) {
947 await this.removeReservation(
949 ReservationTerminationReason
.REPLACE_EXISTING
,
952 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
;
953 await OCPPServiceUtils
.sendAndSetConnectorStatus(
955 reservation
.connectorId
,
956 ConnectorStatusEnum
.Reserved
,
958 { send
: reservation
.connectorId
!== 0 },
962 public async removeReservation(
963 reservation
: Reservation
,
964 reason
: ReservationTerminationReason
,
966 const connector
= this.getConnectorStatus(reservation
.connectorId
)!;
968 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
969 case ReservationTerminationReason
.TRANSACTION_STARTED
:
970 delete connector
.reservation
;
972 case ReservationTerminationReason
.RESERVATION_CANCELED
:
973 case ReservationTerminationReason
.REPLACE_EXISTING
:
974 case ReservationTerminationReason
.EXPIRED
:
975 await OCPPServiceUtils
.sendAndSetConnectorStatus(
977 reservation
.connectorId
,
978 ConnectorStatusEnum
.Available
,
980 { send
: reservation
.connectorId
!== 0 },
982 delete connector
.reservation
;
985 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
986 throw new BaseError(`Unknown reservation termination reason '${reason}'`);
990 public getReservationBy(
991 filterKey
: ReservationKey
,
992 value
: number | string,
993 ): Reservation
| undefined {
995 for (const evseStatus
of this.evses
.values()) {
996 for (const connectorStatus
of evseStatus
.connectors
.values()) {
997 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
998 return connectorStatus
.reservation
;
1003 for (const connectorStatus
of this.connectors
.values()) {
1004 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1005 return connectorStatus
.reservation
;
1011 public isConnectorReservable(
1012 reservationId
: number,
1014 connectorId
?: number,
1016 const reservation
= this.getReservationBy('reservationId', reservationId
);
1017 const reservationExists
= !isUndefined(reservation
) && !hasReservationExpired(reservation
!);
1018 if (arguments.length
=== 1) {
1019 return !reservationExists
;
1020 } else if (arguments.length
> 1) {
1021 const userReservation
= !isUndefined(idTag
)
1022 ? this.getReservationBy('idTag', idTag
!)
1024 const userReservationExists
=
1025 !isUndefined(userReservation
) && !hasReservationExpired(userReservation
!);
1026 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
! > 0;
1027 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
1029 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
1035 private startReservationExpirationSetInterval(customInterval
?: number): void {
1037 customInterval
?? Constants
.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL
;
1040 `${this.logPrefix()} Reservation expiration date checks started every ${formatDurationMilliSeconds(
1044 this.reservationExpirationSetInterval
= setInterval((): void => {
1045 removeExpiredReservations(this).catch(Constants
.EMPTY_FUNCTION
);
1050 private stopReservationExpirationSetInterval(): void {
1051 if (this.reservationExpirationSetInterval
) {
1052 clearInterval(this.reservationExpirationSetInterval
);
1056 // private restartReservationExpiryDateSetInterval(): void {
1057 // this.stopReservationExpirationSetInterval();
1058 // this.startReservationExpirationSetInterval();
1061 private getNumberOfReservableConnectors(): number {
1062 let numberOfReservableConnectors
= 0;
1063 if (this.hasEvses
) {
1064 for (const evseStatus
of this.evses
.values()) {
1065 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
);
1068 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
);
1070 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1073 private getNumberOfReservationsOnConnectorZero(): number {
1075 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1076 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) ||
1077 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
)
1084 private flushMessageBuffer(): void {
1085 if (this.messageBuffer
.size
> 0) {
1086 for (const message
of this.messageBuffer
.values()) {
1087 let beginId
: string | undefined;
1088 let commandName
: RequestCommand
| undefined;
1089 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1090 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1092 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1093 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1095 this.wsConnection
?.send(message
);
1096 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!);
1098 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1100 )} payload sent: ${message}`,
1102 this.messageBuffer
.delete(message
);
1107 private getSupervisionUrlOcppConfiguration(): boolean {
1108 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
1111 private getSupervisionUrlOcppKey(): string {
1112 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
1115 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1116 let template
: ChargingStationTemplate
| undefined;
1118 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1119 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1121 const measureId
= `${FileType.ChargingStationTemplate} read`;
1122 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1123 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1124 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1125 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1126 .update(JSON
.stringify(template
))
1128 this.sharedLRUCache
.setChargingStationTemplate(template
);
1129 this.templateFileHash
= template
.templateHash
;
1132 handleFileException(
1134 FileType
.ChargingStationTemplate
,
1135 error
as NodeJS
.ErrnoException
,
1142 private getStationInfoFromTemplate(): ChargingStationInfo
{
1143 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile()!;
1144 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1145 warnTemplateKeysDeprecation(stationTemplate
, this.logPrefix(), this.templateFile
);
1146 if (stationTemplate
?.Connectors
) {
1147 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1149 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1150 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1151 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1152 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1153 createSerialNumber(stationTemplate
, stationInfo
);
1154 if (isNotEmptyArray(stationTemplate
?.power
)) {
1155 stationTemplate
.power
= stationTemplate
.power
as number[];
1156 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1157 stationInfo
.maximumPower
=
1158 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1159 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1160 : stationTemplate
.power
[powerArrayRandomIndex
];
1162 stationTemplate
.power
= stationTemplate
?.power
as number;
1163 stationInfo
.maximumPower
=
1164 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1165 ? stationTemplate
.power
* 1000
1166 : stationTemplate
.power
;
1168 stationInfo
.firmwareVersionPattern
=
1169 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1171 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1172 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!) === false
1175 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1177 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`,
1180 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1187 stationTemplate
?.firmwareUpgrade
?? {},
1189 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1190 ? secondsToMilliseconds(stationTemplate
.resetTime
!)
1191 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1192 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1196 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1197 let stationInfo
: ChargingStationInfo
| undefined;
1198 if (this.getStationInfoPersistentConfiguration()) {
1199 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1201 delete stationInfo
?.infoHash
;
1207 private getStationInfo(): ChargingStationInfo
{
1208 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1209 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1211 // 1. charging station info from template
1212 // 2. charging station info from configuration file
1213 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1214 return stationInfoFromFile
!;
1216 stationInfoFromFile
&&
1217 propagateSerialNumber(
1218 this.getTemplateFromFile()!,
1219 stationInfoFromFile
,
1220 stationInfoFromTemplate
,
1222 return stationInfoFromTemplate
;
1225 private saveStationInfo(): void {
1226 if (this.getStationInfoPersistentConfiguration()) {
1227 this.saveConfiguration();
1231 private getOcppPersistentConfiguration(): boolean {
1232 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1235 private getStationInfoPersistentConfiguration(): boolean {
1236 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1239 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1240 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1243 private handleUnsupportedVersion(version
: OCPPVersion
) {
1244 const errorMsg
= `Unsupported protocol version '${version}' configured
1245 in template file ${this.templateFile}`;
1246 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1247 throw new BaseError(errorMsg
);
1250 private initialize(): void {
1251 const stationTemplate
= this.getTemplateFromFile()!;
1252 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1253 this.configurationFile
= join(
1254 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1255 `${getHashId(this.index, stationTemplate)}.json`,
1257 const chargingStationConfiguration
= this.getConfigurationFromFile();
1259 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1260 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1261 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1263 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1265 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1267 this.stationInfo
= this.getStationInfo();
1269 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1270 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1271 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1273 const patternGroup
: number | undefined =
1274 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1275 this.stationInfo
.firmwareVersion
?.split('.').length
;
1276 const match
= this.stationInfo
1277 .firmwareVersion
!.match(new RegExp(this.stationInfo
.firmwareVersionPattern
!))!
1278 .slice(1, patternGroup
! + 1);
1279 const patchLevelIndex
= match
.length
- 1;
1280 match
[patchLevelIndex
] = (
1281 convertToInt(match
[patchLevelIndex
]) +
1282 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1284 this.stationInfo
.firmwareVersion
= match
?.join('.');
1286 this.saveStationInfo();
1287 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1288 if (this.getEnableStatistics() === true) {
1289 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1290 this.stationInfo
.hashId
,
1291 this.stationInfo
.chargingStationId
!,
1292 this.configuredSupervisionUrl
,
1295 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
);
1296 this.powerDivider
= this.getPowerDivider();
1297 // OCPP configuration
1298 this.ocppConfiguration
= this.getOcppConfiguration();
1299 this.initializeOcppConfiguration();
1300 this.initializeOcppServices();
1301 if (this.stationInfo
?.autoRegister
=== true) {
1302 this.bootNotificationResponse
= {
1303 currentTime
: new Date(),
1304 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1305 status: RegistrationStatusEnumType
.ACCEPTED
,
1310 private initializeOcppServices(): void {
1311 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1312 switch (ocppVersion
) {
1313 case OCPPVersion
.VERSION_16
:
1314 this.ocppIncomingRequestService
=
1315 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1316 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1317 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(),
1320 case OCPPVersion
.VERSION_20
:
1321 case OCPPVersion
.VERSION_201
:
1322 this.ocppIncomingRequestService
=
1323 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1324 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1325 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>(),
1329 this.handleUnsupportedVersion(ocppVersion
);
1334 private initializeOcppConfiguration(): void {
1335 if (!getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)) {
1336 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0');
1338 if (!getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)) {
1339 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false });
1342 this.getSupervisionUrlOcppConfiguration() &&
1343 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1344 !getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1346 addConfigurationKey(
1348 this.getSupervisionUrlOcppKey(),
1349 this.configuredSupervisionUrl
.href
,
1353 !this.getSupervisionUrlOcppConfiguration() &&
1354 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1355 getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1357 deleteConfigurationKey(this, this.getSupervisionUrlOcppKey(), { save
: false });
1360 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1361 !getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)
1363 addConfigurationKey(
1365 this.stationInfo
.amperageLimitationOcppKey
!,
1367 this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)
1371 if (!getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)) {
1372 addConfigurationKey(
1374 StandardParametersKey
.SupportedFeatureProfiles
,
1375 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`,
1378 addConfigurationKey(
1380 StandardParametersKey
.NumberOfConnectors
,
1381 this.getNumberOfConnectors().toString(),
1383 { overwrite
: true },
1385 if (!getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
)) {
1386 addConfigurationKey(
1388 StandardParametersKey
.MeterValuesSampledData
,
1389 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
1392 if (!getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
)) {
1393 const connectorsPhaseRotation
: string[] = [];
1394 if (this.hasEvses
) {
1395 for (const evseStatus
of this.evses
.values()) {
1396 for (const connectorId
of evseStatus
.connectors
.keys()) {
1397 connectorsPhaseRotation
.push(
1398 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1403 for (const connectorId
of this.connectors
.keys()) {
1404 connectorsPhaseRotation
.push(
1405 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1409 addConfigurationKey(
1411 StandardParametersKey
.ConnectorPhaseRotation
,
1412 connectorsPhaseRotation
.toString(),
1415 if (!getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1416 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1419 !getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) &&
1420 getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)?.value
?.includes(
1421 SupportedFeatureProfiles
.LocalAuthListManagement
,
1424 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false');
1426 if (!getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)) {
1427 addConfigurationKey(
1429 StandardParametersKey
.ConnectionTimeOut
,
1430 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString(),
1433 this.saveOcppConfiguration();
1436 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1437 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1438 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1439 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1441 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1442 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1443 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1444 delete evseStatus
.connectorsStatus
;
1445 this.evses
.set(evseId
, {
1446 ...(evseStatus
as EvseStatus
),
1447 connectors
: new Map
<number, ConnectorStatus
>(
1448 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1455 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1456 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1457 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1458 throw new BaseError(errorMsg
);
1460 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1461 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1462 throw new BaseError(errorMsg
);
1466 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1467 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1468 this.initializeConnectorsFromTemplate(stationTemplate
);
1469 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1470 this.initializeEvsesFromTemplate(stationTemplate
);
1471 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1472 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1473 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1474 throw new BaseError(errorMsg
);
1476 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1477 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1478 throw new BaseError(errorMsg
);
1482 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1483 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1484 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1485 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1486 throw new BaseError(errorMsg
);
1488 if (!stationTemplate
?.Connectors
?.[0]) {
1490 `${this.logPrefix()} Charging station information from template ${
1492 } with no connector id 0 configuration`,
1495 if (stationTemplate
?.Connectors
) {
1496 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1497 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1498 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1500 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`,
1503 const connectorsConfigChanged
=
1504 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1505 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1506 connectorsConfigChanged
&& this.connectors
.clear();
1507 this.connectorsConfigurationHash
= connectorsConfigHash
;
1508 if (templateMaxConnectors
> 0) {
1509 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1511 connectorId
=== 0 &&
1512 (!stationTemplate
?.Connectors
[connectorId
] ||
1513 this.getUseConnectorId0(stationTemplate
) === false)
1517 const templateConnectorId
=
1518 connectorId
> 0 && stationTemplate
?.randomConnectors
1519 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1521 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1522 checkStationInfoConnectorStatus(
1523 templateConnectorId
,
1528 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1530 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1531 this.saveConnectorsStatus();
1534 `${this.logPrefix()} Charging station information from template ${
1536 } with no connectors configuration defined, cannot create connectors`,
1542 `${this.logPrefix()} Charging station information from template ${
1544 } with no connectors configuration defined, using already defined connectors`,
1549 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1550 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1551 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1552 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1553 throw new BaseError(errorMsg
);
1555 if (!stationTemplate
?.Evses
?.[0]) {
1557 `${this.logPrefix()} Charging station information from template ${
1559 } with no evse id 0 configuration`,
1562 if (!stationTemplate
?.Evses
?.[0]?.Connectors
?.[0]) {
1564 `${this.logPrefix()} Charging station information from template ${
1566 } with evse id 0 with no connector id 0 configuration`,
1569 if (Object.keys(stationTemplate
?.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1571 `${this.logPrefix()} Charging station information from template ${
1573 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`,
1576 if (stationTemplate
?.Evses
) {
1577 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1578 .update(JSON
.stringify(stationTemplate
?.Evses
))
1580 const evsesConfigChanged
=
1581 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1582 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1583 evsesConfigChanged
&& this.evses
.clear();
1584 this.evsesConfigurationHash
= evsesConfigHash
;
1585 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1586 if (templateMaxEvses
> 0) {
1587 for (const evseKey
in stationTemplate
.Evses
) {
1588 const evseId
= convertToInt(evseKey
);
1589 this.evses
.set(evseId
, {
1590 connectors
: buildConnectorsMap(
1591 stationTemplate
?.Evses
[evseKey
]?.Connectors
,
1595 availability
: AvailabilityType
.Operative
,
1597 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix());
1599 this.saveEvsesStatus();
1602 `${this.logPrefix()} Charging station information from template ${
1604 } with no evses configuration defined, cannot create evses`,
1610 `${this.logPrefix()} Charging station information from template ${
1612 } with no evses configuration defined, using already defined evses`,
1617 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1618 let configuration
: ChargingStationConfiguration
| undefined;
1619 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1621 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1622 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1623 this.configurationFileHash
,
1626 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1627 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1628 configuration
= JSON
.parse(
1629 readFileSync(this.configurationFile
, 'utf8'),
1630 ) as ChargingStationConfiguration
;
1631 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1632 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1633 this.configurationFileHash
= configuration
.configurationHash
!;
1636 handleFileException(
1637 this.configurationFile
,
1638 FileType
.ChargingStationConfiguration
,
1639 error
as NodeJS
.ErrnoException
,
1644 return configuration
;
1647 private saveAutomaticTransactionGeneratorConfiguration(): void {
1648 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1649 this.saveConfiguration();
1653 private saveConnectorsStatus() {
1654 this.saveConfiguration();
1657 private saveEvsesStatus() {
1658 this.saveConfiguration();
1661 private saveConfiguration(): void {
1662 if (isNotEmptyString(this.configurationFile
)) {
1664 if (!existsSync(dirname(this.configurationFile
))) {
1665 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1667 let configurationData
: ChargingStationConfiguration
= this.getConfigurationFromFile()
1668 ? cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()!)
1670 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1671 configurationData
.stationInfo
= this.stationInfo
;
1673 delete configurationData
.stationInfo
;
1675 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1676 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1678 delete configurationData
.configurationKey
;
1680 configurationData
= merge
<ChargingStationConfiguration
>(
1682 buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
1685 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1686 !this.getAutomaticTransactionGeneratorConfiguration()
1688 delete configurationData
.automaticTransactionGenerator
;
1690 if (this.connectors
.size
> 0) {
1691 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1693 delete configurationData
.connectorsStatus
;
1695 if (this.evses
.size
> 0) {
1696 configurationData
.evsesStatus
= buildEvsesStatus(this);
1698 delete configurationData
.evsesStatus
;
1700 delete configurationData
.configurationHash
;
1701 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1704 stationInfo
: configurationData
.stationInfo
,
1705 configurationKey
: configurationData
.configurationKey
,
1706 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1707 } as ChargingStationConfiguration
),
1710 if (this.configurationFileHash
!== configurationHash
) {
1711 AsyncLock
.acquire(AsyncLockType
.configuration
)
1713 configurationData
.configurationHash
= configurationHash
;
1714 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1715 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1716 const fileDescriptor
= openSync(this.configurationFile
, 'w');
1717 writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1718 closeSync(fileDescriptor
);
1719 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1720 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1721 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1722 this.configurationFileHash
= configurationHash
;
1725 handleFileException(
1726 this.configurationFile
,
1727 FileType
.ChargingStationConfiguration
,
1728 error
as NodeJS
.ErrnoException
,
1733 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1737 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1738 this.configurationFile
1743 handleFileException(
1744 this.configurationFile
,
1745 FileType
.ChargingStationConfiguration
,
1746 error
as NodeJS
.ErrnoException
,
1752 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`,
1757 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1758 return this.getTemplateFromFile()?.Configuration
;
1761 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1762 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1763 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1764 return { configurationKey
};
1769 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1770 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1771 this.getOcppConfigurationFromFile();
1772 if (!ocppConfiguration
) {
1773 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1775 return ocppConfiguration
;
1778 private async onOpen(): Promise
<void> {
1779 if (this.isWebSocketConnectionOpened() === true) {
1781 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`,
1783 if (this.isRegistered() === false) {
1784 // Send BootNotification
1785 let registrationRetryCount
= 0;
1787 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1788 BootNotificationRequest
,
1789 BootNotificationResponse
1790 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1791 skipBufferingOnError
: true,
1793 if (this.isRegistered() === false) {
1794 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1796 this?.bootNotificationResponse
?.interval
1797 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1798 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
,
1802 this.isRegistered() === false &&
1803 (registrationRetryCount
<= this.getRegistrationMaxRetries()! ||
1804 this.getRegistrationMaxRetries() === -1)
1807 if (this.isRegistered() === true) {
1808 if (this.inAcceptedState() === true) {
1809 await this.startMessageSequence();
1813 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`,
1816 this.wsConnectionRestarted
= false;
1817 this.autoReconnectRetryCount
= 0;
1818 parentPort
?.postMessage(buildUpdatedMessage(this));
1821 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`,
1826 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1829 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1830 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1832 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1834 )}' and reason '${reason.toString()}'`,
1836 this.autoReconnectRetryCount
= 0;
1841 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1843 )}' and reason '${reason.toString()}'`,
1845 this.started
=== true && (await this.reconnect());
1848 parentPort
?.postMessage(buildUpdatedMessage(this));
1851 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1852 const cachedRequest
= this.requests
.get(messageId
);
1853 if (Array.isArray(cachedRequest
) === true) {
1854 return cachedRequest
;
1856 throw new OCPPError(
1857 ErrorType
.PROTOCOL_ERROR
,
1858 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1860 )} is not an array`,
1862 cachedRequest
as JsonType
,
1866 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1867 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1868 if (this.getEnableStatistics() === true) {
1869 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1872 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1876 // Process the message
1877 await this.ocppIncomingRequestService
.incomingRequestHandler(
1885 private handleResponseMessage(response
: Response
): void {
1886 const [messageType
, messageId
, commandPayload
] = response
;
1887 if (this.requests
.has(messageId
) === false) {
1889 throw new OCPPError(
1890 ErrorType
.INTERNAL_ERROR
,
1891 `Response for unknown message id ${messageId}`,
1897 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1902 `${this.logPrefix()} << Command '${
1903 requestCommandName ?? Constants.UNKNOWN_COMMAND
1904 }' received response payload: ${JSON.stringify(response)}`,
1906 responseCallback(commandPayload
, requestPayload
);
1909 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1910 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1911 if (this.requests
.has(messageId
) === false) {
1913 throw new OCPPError(
1914 ErrorType
.INTERNAL_ERROR
,
1915 `Error response for unknown message id ${messageId}`,
1917 { errorType
, errorMessage
, errorDetails
},
1920 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1922 `${this.logPrefix()} << Command '${
1923 requestCommandName ?? Constants.UNKNOWN_COMMAND
1924 }' received error response payload: ${JSON.stringify(errorResponse)}`,
1926 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1929 private async onMessage(data
: RawData
): Promise
<void> {
1930 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined;
1931 let messageType
: number | undefined;
1932 let errorMsg
: string;
1934 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1935 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1936 if (Array.isArray(request
) === true) {
1937 [messageType
] = request
;
1938 // Check the type of message
1939 switch (messageType
) {
1941 case MessageType
.CALL_MESSAGE
:
1942 await this.handleIncomingMessage(request
as IncomingRequest
);
1945 case MessageType
.CALL_RESULT_MESSAGE
:
1946 this.handleResponseMessage(request
as Response
);
1949 case MessageType
.CALL_ERROR_MESSAGE
:
1950 this.handleErrorMessage(request
as ErrorResponse
);
1954 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1955 errorMsg
= `Wrong message type ${messageType}`;
1956 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1957 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1959 parentPort
?.postMessage(buildUpdatedMessage(this));
1961 throw new OCPPError(
1962 ErrorType
.PROTOCOL_ERROR
,
1963 'Incoming message is not an array',
1971 let commandName
: IncomingRequestCommand
| undefined;
1972 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined;
1973 let errorCallback
: ErrorCallback
;
1974 const [, messageId
] = request
!;
1975 switch (messageType
) {
1976 case MessageType
.CALL_MESSAGE
:
1977 [, , commandName
] = request
as IncomingRequest
;
1979 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1981 case MessageType
.CALL_RESULT_MESSAGE
:
1982 case MessageType
.CALL_ERROR_MESSAGE
:
1983 if (this.requests
.has(messageId
) === true) {
1984 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1985 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1986 errorCallback(error
as OCPPError
, false);
1988 // Remove the request from the cache in case of error at response handling
1989 this.requests
.delete(messageId
);
1993 if (error
instanceof OCPPError
=== false) {
1995 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1996 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1997 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1998 }' message '${data.toString()}' handling is not an OCPPError:`,
2003 `${this.logPrefix()} Incoming OCPP command '${
2004 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2005 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2006 }' message '${data.toString()}'${
2007 messageType !== MessageType.CALL_MESSAGE
2008 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2010 } processing error:`,
2016 private onPing(): void {
2017 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
2020 private onPong(): void {
2021 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
2024 private onError(error
: WSError
): void {
2025 this.closeWSConnection();
2026 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
2029 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2030 if (this.getMeteringPerTransaction() === true) {
2033 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
2034 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2039 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2040 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2044 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2045 return stationTemplate
?.useConnectorId0
?? true;
2048 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
2049 if (this.hasEvses
) {
2050 for (const [evseId
, evseStatus
] of this.evses
) {
2054 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2055 if (connectorStatus
.transactionStarted
=== true) {
2056 await this.stopTransactionOnConnector(connectorId
, reason
);
2061 for (const connectorId
of this.connectors
.keys()) {
2062 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2063 await this.stopTransactionOnConnector(connectorId
, reason
);
2070 private getConnectionTimeout(): number {
2071 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)) {
2073 parseInt(getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)!.value
!) ??
2074 Constants
.DEFAULT_CONNECTION_TIMEOUT
2077 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2080 // -1 for unlimited, 0 for disabling
2081 private getAutoReconnectMaxRetries(): number | undefined {
2083 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
2088 private getRegistrationMaxRetries(): number | undefined {
2089 return this.stationInfo
.registrationMaxRetries
?? -1;
2092 private getPowerDivider(): number {
2093 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2094 if (this.stationInfo
?.powerSharedByConnectors
) {
2095 powerDivider
= this.getNumberOfRunningTransactions();
2097 return powerDivider
;
2100 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2101 const maximumPower
= this.getMaximumPower(stationInfo
);
2102 switch (this.getCurrentOutType(stationInfo
)) {
2103 case CurrentType
.AC
:
2104 return ACElectricUtils
.amperagePerPhaseFromPower(
2105 this.getNumberOfPhases(stationInfo
),
2106 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2107 this.getVoltageOut(stationInfo
),
2109 case CurrentType
.DC
:
2110 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2114 private getAmperageLimitation(): number | undefined {
2116 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2117 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)
2121 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)?.value
,
2122 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2127 private async startMessageSequence(): Promise
<void> {
2128 if (this.stationInfo
?.autoRegister
=== true) {
2129 await this.ocppRequestService
.requestHandler
<
2130 BootNotificationRequest
,
2131 BootNotificationResponse
2132 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2133 skipBufferingOnError
: true,
2136 // Start WebSocket ping
2137 this.startWebSocketPing();
2139 this.startHeartbeat();
2140 // Initialize connectors status
2141 if (this.hasEvses
) {
2142 for (const [evseId
, evseStatus
] of this.evses
) {
2144 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2145 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2146 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2149 connectorBootStatus
,
2156 for (const connectorId
of this.connectors
.keys()) {
2157 if (connectorId
> 0) {
2158 const connectorBootStatus
= getBootConnectorStatus(
2161 this.getConnectorStatus(connectorId
)!,
2163 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2167 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2168 await this.ocppRequestService
.requestHandler
<
2169 FirmwareStatusNotificationRequest
,
2170 FirmwareStatusNotificationResponse
2171 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2172 status: FirmwareStatus
.Installed
,
2174 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2178 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2179 this.startAutomaticTransactionGenerator();
2181 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2184 private async stopMessageSequence(
2185 reason
: StopTransactionReason
= StopTransactionReason
.NONE
,
2187 // Stop WebSocket ping
2188 this.stopWebSocketPing();
2190 this.stopHeartbeat();
2191 // Stop ongoing transactions
2192 if (this.automaticTransactionGenerator
?.started
=== true) {
2193 this.stopAutomaticTransactionGenerator();
2195 await this.stopRunningTransactions(reason
);
2197 if (this.hasEvses
) {
2198 for (const [evseId
, evseStatus
] of this.evses
) {
2200 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2201 await this.ocppRequestService
.requestHandler
<
2202 StatusNotificationRequest
,
2203 StatusNotificationResponse
2206 RequestCommand
.STATUS_NOTIFICATION
,
2207 OCPPServiceUtils
.buildStatusNotificationRequest(
2210 ConnectorStatusEnum
.Unavailable
,
2214 delete connectorStatus
?.status;
2219 for (const connectorId
of this.connectors
.keys()) {
2220 if (connectorId
> 0) {
2221 await this.ocppRequestService
.requestHandler
<
2222 StatusNotificationRequest
,
2223 StatusNotificationResponse
2226 RequestCommand
.STATUS_NOTIFICATION
,
2227 OCPPServiceUtils
.buildStatusNotificationRequest(
2230 ConnectorStatusEnum
.Unavailable
,
2233 delete this.getConnectorStatus(connectorId
)?.status;
2239 private startWebSocketPing(): void {
2240 const webSocketPingInterval
: number = getConfigurationKey(
2242 StandardParametersKey
.WebSocketPingInterval
,
2244 ? convertToInt(getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
)
2246 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2247 this.webSocketPingSetInterval
= setInterval(() => {
2248 if (this.isWebSocketConnectionOpened() === true) {
2249 this.wsConnection
?.ping();
2251 }, secondsToMilliseconds(webSocketPingInterval
));
2253 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2254 webSocketPingInterval,
2257 } else if (this.webSocketPingSetInterval
) {
2259 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2260 webSocketPingInterval,
2265 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`,
2270 private stopWebSocketPing(): void {
2271 if (this.webSocketPingSetInterval
) {
2272 clearInterval(this.webSocketPingSetInterval
);
2273 delete this.webSocketPingSetInterval
;
2277 private getConfiguredSupervisionUrl(): URL
{
2278 let configuredSupervisionUrl
: string;
2279 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2280 if (isNotEmptyArray(supervisionUrls
)) {
2281 let configuredSupervisionUrlIndex
: number;
2282 switch (Configuration
.getSupervisionUrlDistribution()) {
2283 case SupervisionUrlDistribution
.RANDOM
:
2284 configuredSupervisionUrlIndex
= Math.floor(
2285 secureRandom() * (supervisionUrls
as string[]).length
,
2288 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2289 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2291 Object.values(SupervisionUrlDistribution
).includes(
2292 Configuration
.getSupervisionUrlDistribution()!,
2295 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2296 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2297 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2300 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
;
2303 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
];
2305 configuredSupervisionUrl
= supervisionUrls
as string;
2307 if (isNotEmptyString(configuredSupervisionUrl
)) {
2308 return new URL(configuredSupervisionUrl
);
2310 const errorMsg
= 'No supervision url(s) configured';
2311 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2312 throw new BaseError(`${errorMsg}`);
2315 private stopHeartbeat(): void {
2316 if (this.heartbeatSetInterval
) {
2317 clearInterval(this.heartbeatSetInterval
);
2318 delete this.heartbeatSetInterval
;
2322 private terminateWSConnection(): void {
2323 if (this.isWebSocketConnectionOpened() === true) {
2324 this.wsConnection
?.terminate();
2325 this.wsConnection
= null;
2329 private getReconnectExponentialDelay(): boolean {
2330 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2333 private async reconnect(): Promise
<void> {
2334 // Stop WebSocket ping
2335 this.stopWebSocketPing();
2337 this.stopHeartbeat();
2338 // Stop the ATG if needed
2339 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2340 this.stopAutomaticTransactionGenerator();
2343 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries()! ||
2344 this.getAutoReconnectMaxRetries() === -1
2346 ++this.autoReconnectRetryCount
;
2347 const reconnectDelay
= this.getReconnectExponentialDelay()
2348 ? exponentialDelay(this.autoReconnectRetryCount
)
2349 : secondsToMilliseconds(this.getConnectionTimeout());
2350 const reconnectDelayWithdraw
= 1000;
2351 const reconnectTimeout
=
2352 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2353 ? reconnectDelay
- reconnectDelayWithdraw
2356 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2359 )}ms, timeout ${reconnectTimeout}ms`,
2361 await sleep(reconnectDelay
);
2363 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`,
2365 this.openWSConnection(
2367 handshakeTimeout
: reconnectTimeout
,
2369 { closeOpened
: true },
2371 this.wsConnectionRestarted
= true;
2372 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2374 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2375 this.autoReconnectRetryCount
2376 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`,