@enyo-energy/sunspec-sdk 0.0.97 → 0.0.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,10 @@ class ConnectionRetryManager {
21
21
  disconnectedSince = null;
22
22
  lastAttemptTime = 0;
23
23
  attemptCount = 0;
24
+ // Jittered gate for the NEXT attempt, computed when the previous one is recorded. 0 means
25
+ // "use the raw phase interval" — the state before any attempt, so the first reconnect after a
26
+ // disconnect fires immediately (preserving the original behaviour).
27
+ nextIntervalMs = 0;
24
28
  constructor(config) {
25
29
  this.config = config ?? sunspec_interfaces_js_1.DEFAULT_RETRY_CONFIG;
26
30
  }
@@ -39,6 +43,7 @@ class ConnectionRetryManager {
39
43
  this.disconnectedSince = null;
40
44
  this.lastAttemptTime = 0;
41
45
  this.attemptCount = 0;
46
+ this.nextIntervalMs = 0;
42
47
  }
43
48
  /**
44
49
  * Determine which retry phase we're currently in based on elapsed time since disconnect.
@@ -69,7 +74,11 @@ class ConnectionRetryManager {
69
74
  }
70
75
  const now = Date.now();
71
76
  const phase = this.getCurrentPhase();
72
- return (now - this.lastAttemptTime) >= phase.intervalMs;
77
+ // Before the first attempt (nextIntervalMs === 0), lastAttemptTime is 0 so the gate is
78
+ // effectively open — the first reconnect fires right away. Afterwards, honour the jittered
79
+ // interval computed at the previous recordAttempt().
80
+ const interval = this.nextIntervalMs > 0 ? this.nextIntervalMs : phase.intervalMs;
81
+ return (now - this.lastAttemptTime) >= interval;
73
82
  }
74
83
  /**
75
84
  * Record that an attempt was just made.
@@ -77,6 +86,21 @@ class ConnectionRetryManager {
77
86
  recordAttempt() {
78
87
  this.lastAttemptTime = Date.now();
79
88
  this.attemptCount++;
89
+ // Pre-compute the (jittered) gate for the next attempt so a fleet that dropped together
90
+ // spreads its retries instead of stampeding one gateway on every phase boundary.
91
+ this.nextIntervalMs = this.applyJitter(this.getCurrentPhase().intervalMs);
92
+ }
93
+ /**
94
+ * Spread an interval by ±jitter fraction. Returns the interval unchanged when jitter is
95
+ * unset/zero. Never returns a negative value.
96
+ */
97
+ applyJitter(intervalMs) {
98
+ const jitter = this.config.jitter ?? 0;
99
+ if (jitter <= 0) {
100
+ return intervalMs;
101
+ }
102
+ const factor = 1 + (Math.random() * 2 - 1) * jitter;
103
+ return Math.max(0, Math.round(intervalMs * factor));
80
104
  }
81
105
  /**
82
106
  * Get the number of reconnection attempts made.
@@ -18,6 +18,7 @@ export declare class ConnectionRetryManager {
18
18
  private disconnectedSince;
19
19
  private lastAttemptTime;
20
20
  private attemptCount;
21
+ private nextIntervalMs;
21
22
  constructor(config?: IRetryConfig);
22
23
  /**
23
24
  * Mark the connection as disconnected. Sets the timestamp if not already set.
@@ -40,6 +41,11 @@ export declare class ConnectionRetryManager {
40
41
  * Record that an attempt was just made.
41
42
  */
42
43
  recordAttempt(): void;
44
+ /**
45
+ * Spread an interval by ±jitter fraction. Returns the interval unchanged when jitter is
46
+ * unset/zero. Never returns a negative value.
47
+ */
48
+ private applyJitter;
43
49
  /**
44
50
  * Get the number of reconnection attempts made.
45
51
  */
@@ -337,6 +337,25 @@ class BaseSunspecDevice {
337
337
  }
338
338
  }
339
339
  exports.BaseSunspecDevice = BaseSunspecDevice;
340
+ /**
341
+ * Coerce a possibly-`undefined`, `NaN`, or `±Infinity` register value to a finite
342
+ * number, substituting `fallback` (default `0`) otherwise. SunSpec scale-factor
343
+ * decodes and IEEE-754 float models can surface `NaN`/`Infinity` for a
344
+ * NOT_IMPLEMENTED or corrupt register, and `typeof NaN === 'number'` /
345
+ * `Infinity > 0 === true` slip past naive guards — this is the single choke point
346
+ * that keeps every published power/voltage/energy value finite.
347
+ */
348
+ function finiteOr(value, fallback = 0) {
349
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
350
+ }
351
+ /**
352
+ * Like {@link finiteOr} but yields `undefined` for a non-finite/absent value, for
353
+ * optional reading fields (voltageL2/L3, acEnergyWh, batteryPowerW) where "no
354
+ * reliable value" is more honest than a fabricated `0`.
355
+ */
356
+ function finiteOrUndefined(value) {
357
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
358
+ }
340
359
  /**
341
360
  * Sunspec Inverter implementation using dynamic model discovery
342
361
  */
@@ -497,21 +516,13 @@ class SunspecInverter extends BaseSunspecDevice {
497
516
  // to Connected. No-op unless this device is still marked offline.
498
517
  await this.reassertConnectedIfRecovered();
499
518
  if (inverterData) {
500
- // When PV is sourced from the inverter total (no usable MPPT strings),
501
- // the AC fallback includes any battery charge/discharge on a hybrid.
502
- // Fetch the live battery power (positive = charging, negative =
503
- // discharging) so selectPvPowerW can back it out — otherwise a battery
504
- // discharging at night is reported as phantom PV production.
505
- let batteryPowerW;
506
- if (this.wouldUseInverterTotal(dcStrings.length)) {
507
- batteryPowerW = sumMpptBatteryPowerW(mpptDataList);
508
- if (batteryPowerW === undefined) {
509
- const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
510
- batteryPowerW = selectLiveBatteryPowerW(undefined, batteryData);
511
- }
512
- }
513
- const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, inverterData, batteryPowerW);
514
- console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
519
+ // Build the same decoupled reading a direct getInverterReading() caller
520
+ // would get, then wrap it in the data-bus message. The battery-adjusted
521
+ // power is what we publish; meterValueWh is sanitized only here on the
522
+ // publish path (the raw reading intentionally leaves it unguarded).
523
+ const batteryPowerW = await this.fetchAcCorrectionBatteryPowerW(dcStrings.length, mpptDataList);
524
+ const reading = this.buildInverterReading(inverterData, dcStrings, batteryPowerW);
525
+ console.debug(`Got PV Power from ${reading.powerOrigin}: ${reading.inverterPowerW}W (inverter total raw ${reading.inverterPowerWRaw}W, DC strings ${reading.inverterPowerWDcStrings}W)`);
515
526
  const inverterMessage = {
516
527
  id: (0, node_crypto_1.randomUUID)(),
517
528
  message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.InverterValuesUpdateV1,
@@ -522,14 +533,14 @@ class SunspecInverter extends BaseSunspecDevice {
522
533
  timestampIso: timestamp.toISOString(),
523
534
  resolution,
524
535
  data: {
525
- pvPowerW,
536
+ pvPowerW: reading.inverterPowerW,
526
537
  activePowerLimitationW: inverterSettings?.WMax,
527
- state: this.mapOperatingState(inverterData.operatingState),
528
- voltageL1: inverterData.voltageAN || 0,
529
- voltageL2: inverterData.voltageBN ?? undefined,
530
- voltageL3: inverterData.voltageCN ?? undefined,
538
+ state: reading.state,
539
+ voltageL1: reading.voltageL1,
540
+ voltageL2: reading.voltageL2,
541
+ voltageL3: reading.voltageL3,
531
542
  meterValueWh: this.sanitizeAcEnergyWh(inverterData.acEnergy, inverterData.acEnergyScaleFactor),
532
- strings: dcStrings
543
+ strings: reading.strings
533
544
  }
534
545
  };
535
546
  messages.push(inverterMessage);
@@ -832,6 +843,93 @@ class SunspecInverter extends BaseSunspecDevice {
832
843
  };
833
844
  return stateMap[state] || enyo_data_bus_value_js_1.EnyoInverterStateEnum.Off;
834
845
  }
846
+ /**
847
+ * Read a decoupled snapshot of the inverter's live telemetry — PV power (raw
848
+ * and battery-adjusted), its resolved origin, operating state, voltages, AC
849
+ * energy and per-string DC data — WITHOUT constructing or sending any data-bus
850
+ * message. The consumer decides whether and how to publish it.
851
+ *
852
+ * This is the clean read primitive the SDK's own polling (`readData`) is built
853
+ * on, so a direct caller gets exactly the same numbers the bus would carry
854
+ * (except `acEnergyWh`, which is returned raw here and sanitized only on the
855
+ * publish path — see {@link SunspecInverterReading.acEnergyWh}).
856
+ *
857
+ * Returns `null` when not connected (after a reconnect attempt) or when the
858
+ * device exposes no readable inverter model.
859
+ */
860
+ async getInverterReading() {
861
+ try {
862
+ if (!this.isConnected()) {
863
+ await this.tryReconnect();
864
+ if (!this.isConnected())
865
+ return null;
866
+ }
867
+ const inverterData = await this.sunspecClient.readInverterData(this.unitId);
868
+ if (!inverterData)
869
+ return null;
870
+ const mpptDataList = await this.sunspecClient.readAllMPPTData(this.unitId);
871
+ const dcStrings = this.mapMPPTToStrings(mpptDataList ?? []);
872
+ const batteryPowerW = await this.fetchAcCorrectionBatteryPowerW(dcStrings.length, mpptDataList ?? []);
873
+ return this.buildInverterReading(inverterData, dcStrings, batteryPowerW);
874
+ }
875
+ catch (error) {
876
+ // Bullet-proof contract: a decode/comms fault never propagates to the
877
+ // caller — it surfaces as a null reading, same as "no readable model".
878
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: getInverterReading failed: ${error}`);
879
+ return null;
880
+ }
881
+ }
882
+ /**
883
+ * Fetch the live battery power (signed: positive = charging, negative =
884
+ * discharging) that {@link inverterTotalPvPowerW} backs out of the AC fallback.
885
+ * Only fetched when the inverter-total fallback will actually be used — the
886
+ * correction is irrelevant for the MPPT-string path — so a device with working
887
+ * strings never pays the extra battery read. Prefers the Model 160
888
+ * `StCha`/`StDisCha` strings, falling back to Model 124/802. `undefined` when
889
+ * no correction is needed or no live battery source exists.
890
+ */
891
+ async fetchAcCorrectionBatteryPowerW(dcStringCount, mpptDataList) {
892
+ if (!this.wouldUseInverterTotal(dcStringCount))
893
+ return undefined;
894
+ const mpptBatteryPowerW = sumMpptBatteryPowerW(mpptDataList);
895
+ if (mpptBatteryPowerW !== undefined)
896
+ return mpptBatteryPowerW;
897
+ const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
898
+ return selectLiveBatteryPowerW(undefined, batteryData);
899
+ }
900
+ /**
901
+ * Assemble a {@link SunspecInverterReading} from an already-read register set.
902
+ * Pure (no I/O, no side effects) so both `getInverterReading` and the polling
903
+ * `readData` produce identical readings from a single shared code path.
904
+ */
905
+ buildInverterReading(inverterData, dcStrings, batteryPowerW) {
906
+ // Independent breakdown: compute each candidate power regardless of which the
907
+ // configured source selects, so nothing is hidden by the selection.
908
+ // - inverterPowerWDcStrings: the summed MPPT DC strings (always).
909
+ // - inverterPowerWRaw: the inverter's own total (DCW→AC), uncorrected (always).
910
+ // - inverterPowerW: the auto-calc value to use — selected source,
911
+ // battery-adjusted (via selectPvPowerW, overridable).
912
+ const dcStringsW = this.sumDcStringsW(dcStrings);
913
+ const inverterTotal = this.inverterTotalPvPowerW(inverterData, batteryPowerW);
914
+ const selected = this.selectPvPowerW(dcStrings, inverterData, batteryPowerW);
915
+ // Final clamp: the helpers already sanitize, but re-assert the finite/≥0
916
+ // contract here so an override of selectPvPowerW can never leak a non-finite
917
+ // or negative value onto the reading.
918
+ return {
919
+ inverterPowerW: Math.max(0, finiteOr(selected.batteryAdjustedPowerW)),
920
+ inverterPowerWRaw: Math.max(0, finiteOr(inverterTotal.rawPowerW)),
921
+ inverterPowerWDcStrings: Math.max(0, finiteOr(dcStringsW)),
922
+ powerOrigin: selected.origin,
923
+ batteryPowerW: finiteOrUndefined(batteryPowerW),
924
+ state: this.mapOperatingState(inverterData.operatingState),
925
+ operatingState: finiteOrUndefined(inverterData.operatingState),
926
+ voltageL1: finiteOr(inverterData.voltageAN),
927
+ voltageL2: finiteOrUndefined(inverterData.voltageBN),
928
+ voltageL3: finiteOrUndefined(inverterData.voltageCN),
929
+ acEnergyWh: finiteOrUndefined(inverterData.acEnergy),
930
+ strings: Array.isArray(dcStrings) ? dcStrings : [],
931
+ };
932
+ }
835
933
  /**
836
934
  * PV production in Watt, sourced according to the configured `pvPowerSource`:
837
935
  *
@@ -860,9 +958,11 @@ class SunspecInverter extends BaseSunspecDevice {
860
958
  * definition and must never surface as a negative value on the data bus.
861
959
  */
862
960
  selectPvPowerW(dcStrings, inverterData, batteryPowerW) {
863
- if (!this.wouldUseInverterTotal(dcStrings.length)) {
864
- const stringSumW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
865
- return { pvPowerW: Math.max(0, stringSumW), source: 'DC strings' };
961
+ const strings = Array.isArray(dcStrings) ? dcStrings : [];
962
+ if (!this.wouldUseInverterTotal(strings.length)) {
963
+ const stringSumW = this.sumDcStringsW(strings);
964
+ // MPPT strings are already pure PV — raw and battery-adjusted coincide.
965
+ return { rawPowerW: stringSumW, batteryAdjustedPowerW: stringSumW, origin: sunspec_interfaces_js_1.SunspecPvPowerOrigin.MpptStrings };
866
966
  }
867
967
  return this.inverterTotalPvPowerW(inverterData, batteryPowerW);
868
968
  }
@@ -885,19 +985,34 @@ class SunspecInverter extends BaseSunspecDevice {
885
985
  * {@link selectPvPowerW} for the battery correction and why positivity matters.
886
986
  */
887
987
  inverterTotalPvPowerW(inverterData, batteryPowerW) {
888
- if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
889
- return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
890
- }
891
- if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
988
+ // finiteOr collapses NaN/Infinity to 0 so a corrupt decode fails the `> 0`
989
+ // guard (Infinity would otherwise pass `typeof === 'number' && > 0`).
990
+ const dcW = finiteOr(inverterData.dcPower);
991
+ if (dcW > 0) {
992
+ // Inverter DC total is already pure PV — no battery correction applies.
993
+ return { rawPowerW: dcW, batteryAdjustedPowerW: dcW, origin: sunspec_interfaces_js_1.SunspecPvPowerOrigin.InverterDc };
994
+ }
995
+ const acW = finiteOr(inverterData.acPower);
996
+ if (acW > 0) {
892
997
  // AC = PV − charge + discharge on a hybrid; batteryPowerW is signed
893
998
  // (positive = charging, negative = discharging), so PV = AC + batteryPowerW.
894
- const correctedW = inverterData.acPower + (batteryPowerW ?? 0);
895
- if (correctedW > 0) {
896
- return { pvPowerW: correctedW, source: 'AC power (Model 101)' };
897
- }
898
- return { pvPowerW: 0, source: 'none' };
999
+ // rawPowerW keeps the uncorrected AC total; batteryAdjustedPowerW backs the
1000
+ // battery out and is clamped to ≥ 0. finiteOr(batteryPowerW) guarantees the
1001
+ // sum stays finite even if the battery source returned garbage.
1002
+ const correctedW = Math.max(0, acW + finiteOr(batteryPowerW));
1003
+ return { rawPowerW: acW, batteryAdjustedPowerW: correctedW, origin: sunspec_interfaces_js_1.SunspecPvPowerOrigin.InverterAc };
899
1004
  }
900
- return { pvPowerW: 0, source: 'none' };
1005
+ return { rawPowerW: 0, batteryAdjustedPowerW: 0, origin: sunspec_interfaces_js_1.SunspecPvPowerOrigin.None };
1006
+ }
1007
+ /**
1008
+ * Summed per-string MPPT DC power (Model 160), battery strings already filtered
1009
+ * out by {@link mapMPPTToStrings}. finiteOr per-string so one NaN/Infinity powerW
1010
+ * cannot poison the sum; clamped to ≥ 0. Feeds both the MPPT-source selection and
1011
+ * the always-reported {@link SunspecInverterReading.inverterPowerWDcStrings}.
1012
+ */
1013
+ sumDcStringsW(dcStrings) {
1014
+ const strings = Array.isArray(dcStrings) ? dcStrings : [];
1015
+ return Math.max(0, strings.reduce((sum, s) => sum + finiteOr(s?.powerW), 0));
901
1016
  }
902
1017
  /**
903
1018
  * Map MPPT data to DC string structure for data bus
@@ -1406,6 +1521,43 @@ class SunspecBattery extends BaseSunspecDevice {
1406
1521
  return undefined;
1407
1522
  }
1408
1523
  }
1524
+ /**
1525
+ * Read a decoupled snapshot of the battery's live telemetry — state of charge,
1526
+ * signed power (positive = charging, negative = discharging) and charge state —
1527
+ * WITHOUT constructing or sending any data-bus message. The consumer decides
1528
+ * whether and how to publish it.
1529
+ *
1530
+ * This is the clean read primitive the SDK's own polling (`readData`) is built
1531
+ * on, so a direct caller gets exactly the same numbers the bus would carry.
1532
+ * Returns `null` when not connected (after a reconnect attempt) or when the
1533
+ * device exposes no readable battery model.
1534
+ */
1535
+ async getBatteryReading() {
1536
+ if (!this.isConnected()) {
1537
+ await this.tryReconnect();
1538
+ if (!this.isConnected())
1539
+ return null;
1540
+ }
1541
+ const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
1542
+ if (!batteryData)
1543
+ return null;
1544
+ const mpptDataList = await this.sunspecClient.readAllMPPTData(this.unitId);
1545
+ const mpptBatteryPowerW = this.extractBatteryPowerFromMPPT(mpptDataList);
1546
+ return this.buildBatteryReading(batteryData, mpptBatteryPowerW);
1547
+ }
1548
+ /**
1549
+ * Assemble a {@link SunspecBatteryReading} from an already-read register set.
1550
+ * Pure (no I/O, no side effects) so both `getBatteryReading` and the polling
1551
+ * `readData` produce identical readings from a single shared code path. See
1552
+ * {@link selectLiveBatteryPowerW} for the power source-preference rationale.
1553
+ */
1554
+ buildBatteryReading(batteryData, mpptBatteryPowerW) {
1555
+ return {
1556
+ soc: batteryData.soc || batteryData.chaState || 0,
1557
+ powerW: selectLiveBatteryPowerW(mpptBatteryPowerW, batteryData),
1558
+ state: this.mapToEnyoBatteryState(batteryData.chaSt),
1559
+ };
1560
+ }
1409
1561
  /**
1410
1562
  * Update battery data and return data bus messages
1411
1563
  */
@@ -1432,12 +1584,13 @@ class SunspecBattery extends BaseSunspecDevice {
1432
1584
  // to Connected. No-op unless this device is still marked offline.
1433
1585
  await this.reassertConnectedIfRecovered();
1434
1586
  if (batteryData) {
1435
- // See `selectLiveBatteryPowerW` for the source-preference rationale.
1436
- const batteryPowerW = selectLiveBatteryPowerW(mpptBatteryPowerW, batteryData);
1587
+ // Build the same decoupled reading a direct getBatteryReading() caller
1588
+ // would get, then wrap it in the data-bus message.
1589
+ const reading = this.buildBatteryReading(batteryData, mpptBatteryPowerW);
1437
1590
  // Feed the calibration driver's synchronous power cache. No-op when calibration
1438
1591
  // was never configured.
1439
- if (batteryPowerW !== undefined && this.calibrationDriver) {
1440
- this.calibrationDriver.updateBatteryPowerCache(batteryPowerW);
1592
+ if (reading.powerW !== undefined && this.calibrationDriver) {
1593
+ this.calibrationDriver.updateBatteryPowerCache(reading.powerW);
1441
1594
  }
1442
1595
  const batteryMessage = {
1443
1596
  id: (0, node_crypto_1.randomUUID)(),
@@ -1449,9 +1602,9 @@ class SunspecBattery extends BaseSunspecDevice {
1449
1602
  timestampIso: timestamp.toISOString(),
1450
1603
  resolution,
1451
1604
  data: {
1452
- batterySoC: batteryData.soc || batteryData.chaState || 0,
1453
- batteryPowerW,
1454
- state: this.mapToEnyoBatteryState(batteryData.chaSt),
1605
+ batterySoC: reading.soc,
1606
+ batteryPowerW: reading.powerW,
1607
+ state: reading.state,
1455
1608
  }
1456
1609
  };
1457
1610
  messages.push(batteryMessage);
@@ -1,4 +1,4 @@
1
- import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode } from "./sunspec-interfaces.cjs";
1
+ import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, SunspecPvPowerOrigin, type SunspecInverterReading, type SunspecBatteryReading, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode } from "./sunspec-interfaces.cjs";
2
2
  import { ApplianceManager, EnergyApp } from "@enyo-energy/energy-app-sdk";
3
3
  import { type EnyoAppliance, type EnyoApplianceErrorCode, EnyoApplianceName } from "@enyo-energy/energy-app-sdk/dist/types/enyo-appliance.js";
4
4
  import { EnyoNetworkDevice } from "@enyo-energy/energy-app-sdk/dist/types/enyo-network-device.js";
@@ -122,6 +122,18 @@ export declare abstract class BaseSunspecDevice {
122
122
  */
123
123
  protected buildSnapshotService<T>(onRestore: (snapshot: CalibrationSnapshot<T>, reason: RestoreReason) => Promise<void>): SnapshotService<T> | undefined;
124
124
  }
125
+ /**
126
+ * The result of the configured PV-source selection: the picked source's raw and
127
+ * battery-adjusted power plus its resolved origin. Internal to the
128
+ * source-selection helpers (`selectPvPowerW` / `inverterTotalPvPowerW`); the
129
+ * public {@link SunspecInverterReading} exposes an independent breakdown built
130
+ * from these plus the always-computed DC-strings and inverter-total figures.
131
+ */
132
+ type SunspecPvPower = {
133
+ rawPowerW: number;
134
+ batteryAdjustedPowerW: number;
135
+ origin: SunspecPvPowerOrigin;
136
+ };
125
137
  /**
126
138
  * Sunspec Inverter implementation using dynamic model discovery
127
139
  */
@@ -239,6 +251,37 @@ export declare class SunspecInverter extends BaseSunspecDevice {
239
251
  */
240
252
  getPowerProductionLimit(): Promise<number | null>;
241
253
  private mapOperatingState;
254
+ /**
255
+ * Read a decoupled snapshot of the inverter's live telemetry — PV power (raw
256
+ * and battery-adjusted), its resolved origin, operating state, voltages, AC
257
+ * energy and per-string DC data — WITHOUT constructing or sending any data-bus
258
+ * message. The consumer decides whether and how to publish it.
259
+ *
260
+ * This is the clean read primitive the SDK's own polling (`readData`) is built
261
+ * on, so a direct caller gets exactly the same numbers the bus would carry
262
+ * (except `acEnergyWh`, which is returned raw here and sanitized only on the
263
+ * publish path — see {@link SunspecInverterReading.acEnergyWh}).
264
+ *
265
+ * Returns `null` when not connected (after a reconnect attempt) or when the
266
+ * device exposes no readable inverter model.
267
+ */
268
+ getInverterReading(): Promise<SunspecInverterReading | null>;
269
+ /**
270
+ * Fetch the live battery power (signed: positive = charging, negative =
271
+ * discharging) that {@link inverterTotalPvPowerW} backs out of the AC fallback.
272
+ * Only fetched when the inverter-total fallback will actually be used — the
273
+ * correction is irrelevant for the MPPT-string path — so a device with working
274
+ * strings never pays the extra battery read. Prefers the Model 160
275
+ * `StCha`/`StDisCha` strings, falling back to Model 124/802. `undefined` when
276
+ * no correction is needed or no live battery source exists.
277
+ */
278
+ private fetchAcCorrectionBatteryPowerW;
279
+ /**
280
+ * Assemble a {@link SunspecInverterReading} from an already-read register set.
281
+ * Pure (no I/O, no side effects) so both `getInverterReading` and the polling
282
+ * `readData` produce identical readings from a single shared code path.
283
+ */
284
+ private buildInverterReading;
242
285
  /**
243
286
  * PV production in Watt, sourced according to the configured `pvPowerSource`:
244
287
  *
@@ -266,10 +309,7 @@ export declare class SunspecInverter extends BaseSunspecDevice {
266
309
  * The returned `pvPowerW` is always clamped to ≥ 0 — PV production is non-negative by
267
310
  * definition and must never surface as a negative value on the data bus.
268
311
  */
269
- protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData, batteryPowerW?: number): {
270
- pvPowerW: number;
271
- source: string;
272
- };
312
+ protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData, batteryPowerW?: number): SunspecPvPower;
273
313
  /**
274
314
  * Whether {@link selectPvPowerW} will source PV from the inverter total (rather than
275
315
  * the summed MPPT strings) for the given string count. Mppt never does; Inverter
@@ -283,6 +323,13 @@ export declare class SunspecInverter extends BaseSunspecDevice {
283
323
  * {@link selectPvPowerW} for the battery correction and why positivity matters.
284
324
  */
285
325
  private inverterTotalPvPowerW;
326
+ /**
327
+ * Summed per-string MPPT DC power (Model 160), battery strings already filtered
328
+ * out by {@link mapMPPTToStrings}. finiteOr per-string so one NaN/Infinity powerW
329
+ * cannot poison the sum; clamped to ≥ 0. Feeds both the MPPT-source selection and
330
+ * the always-reported {@link SunspecInverterReading.inverterPowerWDcStrings}.
331
+ */
332
+ private sumDcStringsW;
286
333
  /**
287
334
  * Map MPPT data to DC string structure for data bus
288
335
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -440,6 +487,25 @@ export declare class SunspecBattery extends BaseSunspecDevice {
440
487
  * Map SunSpec battery charge state to Enyo battery state
441
488
  */
442
489
  private mapToEnyoBatteryState;
490
+ /**
491
+ * Read a decoupled snapshot of the battery's live telemetry — state of charge,
492
+ * signed power (positive = charging, negative = discharging) and charge state —
493
+ * WITHOUT constructing or sending any data-bus message. The consumer decides
494
+ * whether and how to publish it.
495
+ *
496
+ * This is the clean read primitive the SDK's own polling (`readData`) is built
497
+ * on, so a direct caller gets exactly the same numbers the bus would carry.
498
+ * Returns `null` when not connected (after a reconnect attempt) or when the
499
+ * device exposes no readable battery model.
500
+ */
501
+ getBatteryReading(): Promise<SunspecBatteryReading | null>;
502
+ /**
503
+ * Assemble a {@link SunspecBatteryReading} from an already-read register set.
504
+ * Pure (no I/O, no side effects) so both `getBatteryReading` and the polling
505
+ * `readData` produce identical readings from a single shared code path. See
506
+ * {@link selectLiveBatteryPowerW} for the power source-preference rationale.
507
+ */
508
+ private buildBatteryReading;
443
509
  /**
444
510
  * Update battery data and return data bus messages
445
511
  */
@@ -606,3 +672,4 @@ export declare class SunspecMeter extends BaseSunspecDevice {
606
672
  */
607
673
  readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
608
674
  }
675
+ export {};
@@ -3,7 +3,7 @@
3
3
  * SunSpec block interfaces with block numbers
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SUNSPEC_CONTROLLABLE_FEATURES = exports.SunspecMeterCapability = exports.SunspecBatteryFeatureModeKind = exports.SunspecBatteryCapability = exports.SunspecPvPowerSource = exports.SunspecInverterCapability = exports.SunspecStorageMode = exports.SunspecChargeSource = exports.SunspecVArPctMode = exports.SunspecEnableControl = exports.SunspecConnectionControl = exports.SunspecStorageControlMode = exports.SunspecBatteryEvent1 = exports.SunspecBatteryBankState = exports.SunspecBatteryType = exports.SunspecBatteryControlMode = exports.SunspecBatteryChargeState = exports.SunspecInverterOperatingState = exports.SunspecMPPTOperatingState = exports.SUNSPEC_CONNECTION_LOST_CODE = exports.SunspecInverterEvent1 = exports.SunspecModelId = exports.DEFAULT_RETRY_CONFIG = void 0;
6
+ exports.SUNSPEC_CONTROLLABLE_FEATURES = exports.SunspecMeterCapability = exports.SunspecBatteryFeatureModeKind = exports.SunspecBatteryCapability = exports.SunspecPvPowerOrigin = exports.SunspecPvPowerSource = exports.SunspecInverterCapability = exports.SunspecStorageMode = exports.SunspecChargeSource = exports.SunspecVArPctMode = exports.SunspecEnableControl = exports.SunspecConnectionControl = exports.SunspecStorageControlMode = exports.SunspecBatteryEvent1 = exports.SunspecBatteryBankState = exports.SunspecBatteryType = exports.SunspecBatteryControlMode = exports.SunspecBatteryChargeState = exports.SunspecInverterOperatingState = exports.SunspecMPPTOperatingState = exports.SUNSPEC_CONNECTION_LOST_CODE = exports.SunspecInverterEvent1 = exports.SunspecModelId = exports.DEFAULT_MODBUS_RESILIENCE_CONFIG = exports.DEFAULT_RETRY_CONFIG = void 0;
7
7
  const enyo_battery_appliance_js_1 = require("@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js");
8
8
  exports.DEFAULT_RETRY_CONFIG = {
9
9
  phases: [
@@ -12,7 +12,14 @@ exports.DEFAULT_RETRY_CONFIG = {
12
12
  { intervalMs: 60_000, durationMs: 300_000 }, // Phase 3: every 1m for 5 minutes
13
13
  { intervalMs: 300_000, durationMs: 600_000 }, // Phase 4: every 5m for 10 minutes
14
14
  { intervalMs: 900_000, durationMs: 0 }, // Phase 5: every 15m forever
15
- ]
15
+ ],
16
+ jitter: 0.2,
17
+ };
18
+ exports.DEFAULT_MODBUS_RESILIENCE_CONFIG = {
19
+ readTimeoutMs: 5_000,
20
+ connectTimeoutMs: 5_000,
21
+ disconnectTimeoutMs: 5_000,
22
+ staleSocketMs: 30_000,
16
23
  };
17
24
  /**
18
25
  * Common Sunspec Model IDs
@@ -282,6 +289,28 @@ var SunspecPvPowerSource;
282
289
  SunspecPvPowerSource["Mppt"] = "mppt";
283
290
  SunspecPvPowerSource["Inverter"] = "inverter";
284
291
  })(SunspecPvPowerSource || (exports.SunspecPvPowerSource = SunspecPvPowerSource = {}));
292
+ /**
293
+ * The concrete register set an inverter's PV power reading was actually derived
294
+ * from — the *resolved* origin, as opposed to {@link SunspecPvPowerSource} which
295
+ * is the *configured* preference. Returned on {@link SunspecInverterReading} so a
296
+ * consumer can see which telemetry produced the number.
297
+ *
298
+ * - `MpptStrings`: summed per-string DC power from Model 160 (battery strings
299
+ * `StCha 3` / `StDisCha 4` excluded). Already pure PV — never battery-adjusted.
300
+ * - `InverterDc`: the inverter's total DC power (Model 101 `DCW`). Pure PV — never
301
+ * battery-adjusted.
302
+ * - `InverterAc`: the inverter's total AC power (Model 101 `W`). On a hybrid this
303
+ * includes battery flow, so `inverterPowerW` backs it out
304
+ * (PV = AC + batteryPowerW) while `inverterPowerWRaw` keeps the uncorrected AC value.
305
+ * - `None`: no strictly-positive inverter total was available; `inverterPowerW` is 0.
306
+ */
307
+ var SunspecPvPowerOrigin;
308
+ (function (SunspecPvPowerOrigin) {
309
+ SunspecPvPowerOrigin["MpptStrings"] = "mppt-strings";
310
+ SunspecPvPowerOrigin["InverterDc"] = "inverter-dc";
311
+ SunspecPvPowerOrigin["InverterAc"] = "inverter-ac";
312
+ SunspecPvPowerOrigin["None"] = "none";
313
+ })(SunspecPvPowerOrigin || (exports.SunspecPvPowerOrigin = SunspecPvPowerOrigin = {}));
285
314
  var SunspecBatteryCapability;
286
315
  (function (SunspecBatteryCapability) {
287
316
  SunspecBatteryCapability["GridCharging"] = "grid-charging";