@enyo-energy/sunspec-sdk 0.0.97 → 0.0.98

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.
@@ -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_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: [
@@ -282,6 +282,28 @@ var SunspecPvPowerSource;
282
282
  SunspecPvPowerSource["Mppt"] = "mppt";
283
283
  SunspecPvPowerSource["Inverter"] = "inverter";
284
284
  })(SunspecPvPowerSource || (exports.SunspecPvPowerSource = SunspecPvPowerSource = {}));
285
+ /**
286
+ * The concrete register set an inverter's PV power reading was actually derived
287
+ * from — the *resolved* origin, as opposed to {@link SunspecPvPowerSource} which
288
+ * is the *configured* preference. Returned on {@link SunspecInverterReading} so a
289
+ * consumer can see which telemetry produced the number.
290
+ *
291
+ * - `MpptStrings`: summed per-string DC power from Model 160 (battery strings
292
+ * `StCha 3` / `StDisCha 4` excluded). Already pure PV — never battery-adjusted.
293
+ * - `InverterDc`: the inverter's total DC power (Model 101 `DCW`). Pure PV — never
294
+ * battery-adjusted.
295
+ * - `InverterAc`: the inverter's total AC power (Model 101 `W`). On a hybrid this
296
+ * includes battery flow, so `inverterPowerW` backs it out
297
+ * (PV = AC + batteryPowerW) while `inverterPowerWRaw` keeps the uncorrected AC value.
298
+ * - `None`: no strictly-positive inverter total was available; `inverterPowerW` is 0.
299
+ */
300
+ var SunspecPvPowerOrigin;
301
+ (function (SunspecPvPowerOrigin) {
302
+ SunspecPvPowerOrigin["MpptStrings"] = "mppt-strings";
303
+ SunspecPvPowerOrigin["InverterDc"] = "inverter-dc";
304
+ SunspecPvPowerOrigin["InverterAc"] = "inverter-ac";
305
+ SunspecPvPowerOrigin["None"] = "none";
306
+ })(SunspecPvPowerOrigin || (exports.SunspecPvPowerOrigin = SunspecPvPowerOrigin = {}));
285
307
  var SunspecBatteryCapability;
286
308
  (function (SunspecBatteryCapability) {
287
309
  SunspecBatteryCapability["GridCharging"] = "grid-charging";
@@ -2,6 +2,7 @@
2
2
  * SunSpec block interfaces with block numbers
3
3
  */
4
4
  import { EnyoBatteryFeature } from "@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js";
5
+ import { EnyoBatteryStateEnum, EnyoDataBusInverterValuesV1String, EnyoInverterStateEnum } from "@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js";
5
6
  /**
6
7
  * A single phase in the tiered retry schedule
7
8
  */
@@ -665,6 +666,98 @@ export declare enum SunspecPvPowerSource {
665
666
  Mppt = "mppt",
666
667
  Inverter = "inverter"
667
668
  }
669
+ /**
670
+ * The concrete register set an inverter's PV power reading was actually derived
671
+ * from — the *resolved* origin, as opposed to {@link SunspecPvPowerSource} which
672
+ * is the *configured* preference. Returned on {@link SunspecInverterReading} so a
673
+ * consumer can see which telemetry produced the number.
674
+ *
675
+ * - `MpptStrings`: summed per-string DC power from Model 160 (battery strings
676
+ * `StCha 3` / `StDisCha 4` excluded). Already pure PV — never battery-adjusted.
677
+ * - `InverterDc`: the inverter's total DC power (Model 101 `DCW`). Pure PV — never
678
+ * battery-adjusted.
679
+ * - `InverterAc`: the inverter's total AC power (Model 101 `W`). On a hybrid this
680
+ * includes battery flow, so `inverterPowerW` backs it out
681
+ * (PV = AC + batteryPowerW) while `inverterPowerWRaw` keeps the uncorrected AC value.
682
+ * - `None`: no strictly-positive inverter total was available; `inverterPowerW` is 0.
683
+ */
684
+ export declare enum SunspecPvPowerOrigin {
685
+ MpptStrings = "mppt-strings",
686
+ InverterDc = "inverter-dc",
687
+ InverterAc = "inverter-ac",
688
+ None = "none"
689
+ }
690
+ /**
691
+ * A decoupled snapshot of an inverter's live telemetry, produced by
692
+ * `SunspecInverter.getInverterReading()`. Contains no data-bus message and is
693
+ * never sent anywhere — the consumer decides whether to publish it. The same
694
+ * data drives the SDK's own `InverterValuesUpdateV1` message when polling is used.
695
+ */
696
+ export interface SunspecInverterReading {
697
+ /**
698
+ * The auto-calculated PV production (W) to use — the configured source's value
699
+ * (see {@link SunspecPvPowerSource}) with battery charge/discharge backed out of
700
+ * the AC fallback, clamped to ≥ 0. `powerOrigin` says which source produced it.
701
+ * This is the value the SDK publishes as `pvPowerW` when it builds the data-bus
702
+ * message itself.
703
+ */
704
+ inverterPowerW: number;
705
+ /**
706
+ * The inverter's own total power (W), UNCORRECTED: Model 101 `DCW` when strictly
707
+ * positive, else AC (`W`) when strictly positive, else 0. Clamped to ≥ 0. Always
708
+ * computed and reported independently of `powerOrigin`, so it is available even
709
+ * when {@link inverterPowerW} is sourced from the MPPT strings. Battery flow is
710
+ * NOT backed out here — for the AC branch that is exactly {@link inverterPowerW}
711
+ * minus the battery correction.
712
+ */
713
+ inverterPowerWRaw: number;
714
+ /**
715
+ * Summed per-string MPPT DC power (W) from Model 160 (battery strings
716
+ * `StCha 3` / `StDisCha 4` excluded), clamped to ≥ 0. Always computed and
717
+ * reported independently of `powerOrigin` — `0` when no PV strings are readable.
718
+ */
719
+ inverterPowerWDcStrings: number;
720
+ /** Which register set {@link inverterPowerW} was selected from. */
721
+ powerOrigin: SunspecPvPowerOrigin;
722
+ /**
723
+ * The live battery power (W) backed out of the AC fallback, signed
724
+ * (positive = charging, negative = discharging). Only fetched when the AC/DC
725
+ * inverter-total fallback is in use; `undefined` otherwise or when no live
726
+ * battery source is available.
727
+ */
728
+ batteryPowerW?: number;
729
+ /** Operating state mapped to the Enyo enum. */
730
+ state: EnyoInverterStateEnum;
731
+ /** Raw SunSpec operating state (`St`), unmapped. */
732
+ operatingState?: number;
733
+ voltageL1: number;
734
+ voltageL2?: number;
735
+ voltageL3?: number;
736
+ /**
737
+ * Raw cumulative AC energy (Wh) straight from the register. NOT sanitized —
738
+ * the SDK's acc32 word-boundary guard is applied only on the publish path, so
739
+ * a consumer reading directly should expect the occasional register artifact.
740
+ */
741
+ acEnergyWh?: number;
742
+ /** Per-string DC telemetry (Model 160), battery strings filtered out. */
743
+ strings: EnyoDataBusInverterValuesV1String[];
744
+ }
745
+ /**
746
+ * A decoupled snapshot of a battery's live telemetry, produced by
747
+ * `SunspecBattery.getBatteryReading()`. Contains no data-bus message.
748
+ */
749
+ export interface SunspecBatteryReading {
750
+ /** State of charge (%). */
751
+ soc: number;
752
+ /**
753
+ * Live battery power (W), signed: positive = charging, negative = discharging.
754
+ * `undefined` when the device exposes no live power source (e.g. a Model
755
+ * 124-only battery with no MPPT battery strings).
756
+ */
757
+ powerW?: number;
758
+ /** Charge/discharge state mapped to the Enyo enum. */
759
+ state?: EnyoBatteryStateEnum;
760
+ }
668
761
  export declare enum SunspecBatteryCapability {
669
762
  GridCharging = "grid-charging",
670
763
  DischargeLimit = "discharge-limit",
@@ -9,7 +9,7 @@ exports.getSdkVersion = getSdkVersion;
9
9
  /**
10
10
  * Current version of the enyo Energy App SDK.
11
11
  */
12
- exports.SDK_VERSION = '0.0.97';
12
+ exports.SDK_VERSION = '0.0.98';
13
13
  /**
14
14
  * Gets the current SDK version.
15
15
  * @returns The semantic version string of the SDK
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export declare const SDK_VERSION = "0.0.97";
8
+ export declare const SDK_VERSION = "0.0.98";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
@@ -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.js";
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.js";
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 {};
@@ -1,4 +1,4 @@
1
- import { SunspecBatteryChargeState, SunspecBatteryFeatureModeKind, SunspecEnableControl, SunspecInverterCapability, SunspecPvPowerSource, SunspecInverterEvent1, SunspecInverterOperatingState, SunspecModelId, SunspecMPPTOperatingState, SunspecStorageMode, SUNSPEC_CONNECTION_LOST_CODE } from "./sunspec-interfaces.js";
1
+ import { SunspecBatteryChargeState, SunspecBatteryFeatureModeKind, SunspecEnableControl, SunspecInverterCapability, SunspecPvPowerSource, SunspecPvPowerOrigin, SunspecInverterEvent1, SunspecInverterOperatingState, SunspecModelId, SunspecMPPTOperatingState, SunspecStorageMode, SUNSPEC_CONNECTION_LOST_CODE } from "./sunspec-interfaces.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { EnyoApplianceConnectionType, EnyoApplianceStateEnum, EnyoApplianceStatusEnum, EnyoApplianceTopologyFeatureEnum, EnyoApplianceTypeEnum } from "@enyo-energy/energy-app-sdk/dist/types/enyo-appliance.js";
4
4
  import { ConnectionRetryManager } from "./connection-retry-manager.js";
@@ -329,6 +329,25 @@ export class BaseSunspecDevice {
329
329
  });
330
330
  }
331
331
  }
332
+ /**
333
+ * Coerce a possibly-`undefined`, `NaN`, or `±Infinity` register value to a finite
334
+ * number, substituting `fallback` (default `0`) otherwise. SunSpec scale-factor
335
+ * decodes and IEEE-754 float models can surface `NaN`/`Infinity` for a
336
+ * NOT_IMPLEMENTED or corrupt register, and `typeof NaN === 'number'` /
337
+ * `Infinity > 0 === true` slip past naive guards — this is the single choke point
338
+ * that keeps every published power/voltage/energy value finite.
339
+ */
340
+ function finiteOr(value, fallback = 0) {
341
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
342
+ }
343
+ /**
344
+ * Like {@link finiteOr} but yields `undefined` for a non-finite/absent value, for
345
+ * optional reading fields (voltageL2/L3, acEnergyWh, batteryPowerW) where "no
346
+ * reliable value" is more honest than a fabricated `0`.
347
+ */
348
+ function finiteOrUndefined(value) {
349
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
350
+ }
332
351
  /**
333
352
  * Sunspec Inverter implementation using dynamic model discovery
334
353
  */
@@ -489,21 +508,13 @@ export class SunspecInverter extends BaseSunspecDevice {
489
508
  // to Connected. No-op unless this device is still marked offline.
490
509
  await this.reassertConnectedIfRecovered();
491
510
  if (inverterData) {
492
- // When PV is sourced from the inverter total (no usable MPPT strings),
493
- // the AC fallback includes any battery charge/discharge on a hybrid.
494
- // Fetch the live battery power (positive = charging, negative =
495
- // discharging) so selectPvPowerW can back it out — otherwise a battery
496
- // discharging at night is reported as phantom PV production.
497
- let batteryPowerW;
498
- if (this.wouldUseInverterTotal(dcStrings.length)) {
499
- batteryPowerW = sumMpptBatteryPowerW(mpptDataList);
500
- if (batteryPowerW === undefined) {
501
- const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
502
- batteryPowerW = selectLiveBatteryPowerW(undefined, batteryData);
503
- }
504
- }
505
- const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, inverterData, batteryPowerW);
506
- console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
511
+ // Build the same decoupled reading a direct getInverterReading() caller
512
+ // would get, then wrap it in the data-bus message. The battery-adjusted
513
+ // power is what we publish; meterValueWh is sanitized only here on the
514
+ // publish path (the raw reading intentionally leaves it unguarded).
515
+ const batteryPowerW = await this.fetchAcCorrectionBatteryPowerW(dcStrings.length, mpptDataList);
516
+ const reading = this.buildInverterReading(inverterData, dcStrings, batteryPowerW);
517
+ console.debug(`Got PV Power from ${reading.powerOrigin}: ${reading.inverterPowerW}W (inverter total raw ${reading.inverterPowerWRaw}W, DC strings ${reading.inverterPowerWDcStrings}W)`);
507
518
  const inverterMessage = {
508
519
  id: randomUUID(),
509
520
  message: EnyoDataBusMessageEnum.InverterValuesUpdateV1,
@@ -514,14 +525,14 @@ export class SunspecInverter extends BaseSunspecDevice {
514
525
  timestampIso: timestamp.toISOString(),
515
526
  resolution,
516
527
  data: {
517
- pvPowerW,
528
+ pvPowerW: reading.inverterPowerW,
518
529
  activePowerLimitationW: inverterSettings?.WMax,
519
- state: this.mapOperatingState(inverterData.operatingState),
520
- voltageL1: inverterData.voltageAN || 0,
521
- voltageL2: inverterData.voltageBN ?? undefined,
522
- voltageL3: inverterData.voltageCN ?? undefined,
530
+ state: reading.state,
531
+ voltageL1: reading.voltageL1,
532
+ voltageL2: reading.voltageL2,
533
+ voltageL3: reading.voltageL3,
523
534
  meterValueWh: this.sanitizeAcEnergyWh(inverterData.acEnergy, inverterData.acEnergyScaleFactor),
524
- strings: dcStrings
535
+ strings: reading.strings
525
536
  }
526
537
  };
527
538
  messages.push(inverterMessage);
@@ -824,6 +835,93 @@ export class SunspecInverter extends BaseSunspecDevice {
824
835
  };
825
836
  return stateMap[state] || EnyoInverterStateEnum.Off;
826
837
  }
838
+ /**
839
+ * Read a decoupled snapshot of the inverter's live telemetry — PV power (raw
840
+ * and battery-adjusted), its resolved origin, operating state, voltages, AC
841
+ * energy and per-string DC data — WITHOUT constructing or sending any data-bus
842
+ * message. The consumer decides whether and how to publish it.
843
+ *
844
+ * This is the clean read primitive the SDK's own polling (`readData`) is built
845
+ * on, so a direct caller gets exactly the same numbers the bus would carry
846
+ * (except `acEnergyWh`, which is returned raw here and sanitized only on the
847
+ * publish path — see {@link SunspecInverterReading.acEnergyWh}).
848
+ *
849
+ * Returns `null` when not connected (after a reconnect attempt) or when the
850
+ * device exposes no readable inverter model.
851
+ */
852
+ async getInverterReading() {
853
+ try {
854
+ if (!this.isConnected()) {
855
+ await this.tryReconnect();
856
+ if (!this.isConnected())
857
+ return null;
858
+ }
859
+ const inverterData = await this.sunspecClient.readInverterData(this.unitId);
860
+ if (!inverterData)
861
+ return null;
862
+ const mpptDataList = await this.sunspecClient.readAllMPPTData(this.unitId);
863
+ const dcStrings = this.mapMPPTToStrings(mpptDataList ?? []);
864
+ const batteryPowerW = await this.fetchAcCorrectionBatteryPowerW(dcStrings.length, mpptDataList ?? []);
865
+ return this.buildInverterReading(inverterData, dcStrings, batteryPowerW);
866
+ }
867
+ catch (error) {
868
+ // Bullet-proof contract: a decode/comms fault never propagates to the
869
+ // caller — it surfaces as a null reading, same as "no readable model".
870
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: getInverterReading failed: ${error}`);
871
+ return null;
872
+ }
873
+ }
874
+ /**
875
+ * Fetch the live battery power (signed: positive = charging, negative =
876
+ * discharging) that {@link inverterTotalPvPowerW} backs out of the AC fallback.
877
+ * Only fetched when the inverter-total fallback will actually be used — the
878
+ * correction is irrelevant for the MPPT-string path — so a device with working
879
+ * strings never pays the extra battery read. Prefers the Model 160
880
+ * `StCha`/`StDisCha` strings, falling back to Model 124/802. `undefined` when
881
+ * no correction is needed or no live battery source exists.
882
+ */
883
+ async fetchAcCorrectionBatteryPowerW(dcStringCount, mpptDataList) {
884
+ if (!this.wouldUseInverterTotal(dcStringCount))
885
+ return undefined;
886
+ const mpptBatteryPowerW = sumMpptBatteryPowerW(mpptDataList);
887
+ if (mpptBatteryPowerW !== undefined)
888
+ return mpptBatteryPowerW;
889
+ const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
890
+ return selectLiveBatteryPowerW(undefined, batteryData);
891
+ }
892
+ /**
893
+ * Assemble a {@link SunspecInverterReading} from an already-read register set.
894
+ * Pure (no I/O, no side effects) so both `getInverterReading` and the polling
895
+ * `readData` produce identical readings from a single shared code path.
896
+ */
897
+ buildInverterReading(inverterData, dcStrings, batteryPowerW) {
898
+ // Independent breakdown: compute each candidate power regardless of which the
899
+ // configured source selects, so nothing is hidden by the selection.
900
+ // - inverterPowerWDcStrings: the summed MPPT DC strings (always).
901
+ // - inverterPowerWRaw: the inverter's own total (DCW→AC), uncorrected (always).
902
+ // - inverterPowerW: the auto-calc value to use — selected source,
903
+ // battery-adjusted (via selectPvPowerW, overridable).
904
+ const dcStringsW = this.sumDcStringsW(dcStrings);
905
+ const inverterTotal = this.inverterTotalPvPowerW(inverterData, batteryPowerW);
906
+ const selected = this.selectPvPowerW(dcStrings, inverterData, batteryPowerW);
907
+ // Final clamp: the helpers already sanitize, but re-assert the finite/≥0
908
+ // contract here so an override of selectPvPowerW can never leak a non-finite
909
+ // or negative value onto the reading.
910
+ return {
911
+ inverterPowerW: Math.max(0, finiteOr(selected.batteryAdjustedPowerW)),
912
+ inverterPowerWRaw: Math.max(0, finiteOr(inverterTotal.rawPowerW)),
913
+ inverterPowerWDcStrings: Math.max(0, finiteOr(dcStringsW)),
914
+ powerOrigin: selected.origin,
915
+ batteryPowerW: finiteOrUndefined(batteryPowerW),
916
+ state: this.mapOperatingState(inverterData.operatingState),
917
+ operatingState: finiteOrUndefined(inverterData.operatingState),
918
+ voltageL1: finiteOr(inverterData.voltageAN),
919
+ voltageL2: finiteOrUndefined(inverterData.voltageBN),
920
+ voltageL3: finiteOrUndefined(inverterData.voltageCN),
921
+ acEnergyWh: finiteOrUndefined(inverterData.acEnergy),
922
+ strings: Array.isArray(dcStrings) ? dcStrings : [],
923
+ };
924
+ }
827
925
  /**
828
926
  * PV production in Watt, sourced according to the configured `pvPowerSource`:
829
927
  *
@@ -852,9 +950,11 @@ export class SunspecInverter extends BaseSunspecDevice {
852
950
  * definition and must never surface as a negative value on the data bus.
853
951
  */
854
952
  selectPvPowerW(dcStrings, inverterData, batteryPowerW) {
855
- if (!this.wouldUseInverterTotal(dcStrings.length)) {
856
- const stringSumW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
857
- return { pvPowerW: Math.max(0, stringSumW), source: 'DC strings' };
953
+ const strings = Array.isArray(dcStrings) ? dcStrings : [];
954
+ if (!this.wouldUseInverterTotal(strings.length)) {
955
+ const stringSumW = this.sumDcStringsW(strings);
956
+ // MPPT strings are already pure PV — raw and battery-adjusted coincide.
957
+ return { rawPowerW: stringSumW, batteryAdjustedPowerW: stringSumW, origin: SunspecPvPowerOrigin.MpptStrings };
858
958
  }
859
959
  return this.inverterTotalPvPowerW(inverterData, batteryPowerW);
860
960
  }
@@ -877,19 +977,34 @@ export class SunspecInverter extends BaseSunspecDevice {
877
977
  * {@link selectPvPowerW} for the battery correction and why positivity matters.
878
978
  */
879
979
  inverterTotalPvPowerW(inverterData, batteryPowerW) {
880
- if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
881
- return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
882
- }
883
- if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
980
+ // finiteOr collapses NaN/Infinity to 0 so a corrupt decode fails the `> 0`
981
+ // guard (Infinity would otherwise pass `typeof === 'number' && > 0`).
982
+ const dcW = finiteOr(inverterData.dcPower);
983
+ if (dcW > 0) {
984
+ // Inverter DC total is already pure PV — no battery correction applies.
985
+ return { rawPowerW: dcW, batteryAdjustedPowerW: dcW, origin: SunspecPvPowerOrigin.InverterDc };
986
+ }
987
+ const acW = finiteOr(inverterData.acPower);
988
+ if (acW > 0) {
884
989
  // AC = PV − charge + discharge on a hybrid; batteryPowerW is signed
885
990
  // (positive = charging, negative = discharging), so PV = AC + batteryPowerW.
886
- const correctedW = inverterData.acPower + (batteryPowerW ?? 0);
887
- if (correctedW > 0) {
888
- return { pvPowerW: correctedW, source: 'AC power (Model 101)' };
889
- }
890
- return { pvPowerW: 0, source: 'none' };
991
+ // rawPowerW keeps the uncorrected AC total; batteryAdjustedPowerW backs the
992
+ // battery out and is clamped to ≥ 0. finiteOr(batteryPowerW) guarantees the
993
+ // sum stays finite even if the battery source returned garbage.
994
+ const correctedW = Math.max(0, acW + finiteOr(batteryPowerW));
995
+ return { rawPowerW: acW, batteryAdjustedPowerW: correctedW, origin: SunspecPvPowerOrigin.InverterAc };
891
996
  }
892
- return { pvPowerW: 0, source: 'none' };
997
+ return { rawPowerW: 0, batteryAdjustedPowerW: 0, origin: SunspecPvPowerOrigin.None };
998
+ }
999
+ /**
1000
+ * Summed per-string MPPT DC power (Model 160), battery strings already filtered
1001
+ * out by {@link mapMPPTToStrings}. finiteOr per-string so one NaN/Infinity powerW
1002
+ * cannot poison the sum; clamped to ≥ 0. Feeds both the MPPT-source selection and
1003
+ * the always-reported {@link SunspecInverterReading.inverterPowerWDcStrings}.
1004
+ */
1005
+ sumDcStringsW(dcStrings) {
1006
+ const strings = Array.isArray(dcStrings) ? dcStrings : [];
1007
+ return Math.max(0, strings.reduce((sum, s) => sum + finiteOr(s?.powerW), 0));
893
1008
  }
894
1009
  /**
895
1010
  * Map MPPT data to DC string structure for data bus
@@ -1397,6 +1512,43 @@ export class SunspecBattery extends BaseSunspecDevice {
1397
1512
  return undefined;
1398
1513
  }
1399
1514
  }
1515
+ /**
1516
+ * Read a decoupled snapshot of the battery's live telemetry — state of charge,
1517
+ * signed power (positive = charging, negative = discharging) and charge state —
1518
+ * WITHOUT constructing or sending any data-bus message. The consumer decides
1519
+ * whether and how to publish it.
1520
+ *
1521
+ * This is the clean read primitive the SDK's own polling (`readData`) is built
1522
+ * on, so a direct caller gets exactly the same numbers the bus would carry.
1523
+ * Returns `null` when not connected (after a reconnect attempt) or when the
1524
+ * device exposes no readable battery model.
1525
+ */
1526
+ async getBatteryReading() {
1527
+ if (!this.isConnected()) {
1528
+ await this.tryReconnect();
1529
+ if (!this.isConnected())
1530
+ return null;
1531
+ }
1532
+ const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
1533
+ if (!batteryData)
1534
+ return null;
1535
+ const mpptDataList = await this.sunspecClient.readAllMPPTData(this.unitId);
1536
+ const mpptBatteryPowerW = this.extractBatteryPowerFromMPPT(mpptDataList);
1537
+ return this.buildBatteryReading(batteryData, mpptBatteryPowerW);
1538
+ }
1539
+ /**
1540
+ * Assemble a {@link SunspecBatteryReading} from an already-read register set.
1541
+ * Pure (no I/O, no side effects) so both `getBatteryReading` and the polling
1542
+ * `readData` produce identical readings from a single shared code path. See
1543
+ * {@link selectLiveBatteryPowerW} for the power source-preference rationale.
1544
+ */
1545
+ buildBatteryReading(batteryData, mpptBatteryPowerW) {
1546
+ return {
1547
+ soc: batteryData.soc || batteryData.chaState || 0,
1548
+ powerW: selectLiveBatteryPowerW(mpptBatteryPowerW, batteryData),
1549
+ state: this.mapToEnyoBatteryState(batteryData.chaSt),
1550
+ };
1551
+ }
1400
1552
  /**
1401
1553
  * Update battery data and return data bus messages
1402
1554
  */
@@ -1423,12 +1575,13 @@ export class SunspecBattery extends BaseSunspecDevice {
1423
1575
  // to Connected. No-op unless this device is still marked offline.
1424
1576
  await this.reassertConnectedIfRecovered();
1425
1577
  if (batteryData) {
1426
- // See `selectLiveBatteryPowerW` for the source-preference rationale.
1427
- const batteryPowerW = selectLiveBatteryPowerW(mpptBatteryPowerW, batteryData);
1578
+ // Build the same decoupled reading a direct getBatteryReading() caller
1579
+ // would get, then wrap it in the data-bus message.
1580
+ const reading = this.buildBatteryReading(batteryData, mpptBatteryPowerW);
1428
1581
  // Feed the calibration driver's synchronous power cache. No-op when calibration
1429
1582
  // was never configured.
1430
- if (batteryPowerW !== undefined && this.calibrationDriver) {
1431
- this.calibrationDriver.updateBatteryPowerCache(batteryPowerW);
1583
+ if (reading.powerW !== undefined && this.calibrationDriver) {
1584
+ this.calibrationDriver.updateBatteryPowerCache(reading.powerW);
1432
1585
  }
1433
1586
  const batteryMessage = {
1434
1587
  id: randomUUID(),
@@ -1440,9 +1593,9 @@ export class SunspecBattery extends BaseSunspecDevice {
1440
1593
  timestampIso: timestamp.toISOString(),
1441
1594
  resolution,
1442
1595
  data: {
1443
- batterySoC: batteryData.soc || batteryData.chaState || 0,
1444
- batteryPowerW,
1445
- state: this.mapToEnyoBatteryState(batteryData.chaSt),
1596
+ batterySoC: reading.soc,
1597
+ batteryPowerW: reading.powerW,
1598
+ state: reading.state,
1446
1599
  }
1447
1600
  };
1448
1601
  messages.push(batteryMessage);
@@ -2,6 +2,7 @@
2
2
  * SunSpec block interfaces with block numbers
3
3
  */
4
4
  import { EnyoBatteryFeature } from "@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js";
5
+ import { EnyoBatteryStateEnum, EnyoDataBusInverterValuesV1String, EnyoInverterStateEnum } from "@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js";
5
6
  /**
6
7
  * A single phase in the tiered retry schedule
7
8
  */
@@ -665,6 +666,98 @@ export declare enum SunspecPvPowerSource {
665
666
  Mppt = "mppt",
666
667
  Inverter = "inverter"
667
668
  }
669
+ /**
670
+ * The concrete register set an inverter's PV power reading was actually derived
671
+ * from — the *resolved* origin, as opposed to {@link SunspecPvPowerSource} which
672
+ * is the *configured* preference. Returned on {@link SunspecInverterReading} so a
673
+ * consumer can see which telemetry produced the number.
674
+ *
675
+ * - `MpptStrings`: summed per-string DC power from Model 160 (battery strings
676
+ * `StCha 3` / `StDisCha 4` excluded). Already pure PV — never battery-adjusted.
677
+ * - `InverterDc`: the inverter's total DC power (Model 101 `DCW`). Pure PV — never
678
+ * battery-adjusted.
679
+ * - `InverterAc`: the inverter's total AC power (Model 101 `W`). On a hybrid this
680
+ * includes battery flow, so `inverterPowerW` backs it out
681
+ * (PV = AC + batteryPowerW) while `inverterPowerWRaw` keeps the uncorrected AC value.
682
+ * - `None`: no strictly-positive inverter total was available; `inverterPowerW` is 0.
683
+ */
684
+ export declare enum SunspecPvPowerOrigin {
685
+ MpptStrings = "mppt-strings",
686
+ InverterDc = "inverter-dc",
687
+ InverterAc = "inverter-ac",
688
+ None = "none"
689
+ }
690
+ /**
691
+ * A decoupled snapshot of an inverter's live telemetry, produced by
692
+ * `SunspecInverter.getInverterReading()`. Contains no data-bus message and is
693
+ * never sent anywhere — the consumer decides whether to publish it. The same
694
+ * data drives the SDK's own `InverterValuesUpdateV1` message when polling is used.
695
+ */
696
+ export interface SunspecInverterReading {
697
+ /**
698
+ * The auto-calculated PV production (W) to use — the configured source's value
699
+ * (see {@link SunspecPvPowerSource}) with battery charge/discharge backed out of
700
+ * the AC fallback, clamped to ≥ 0. `powerOrigin` says which source produced it.
701
+ * This is the value the SDK publishes as `pvPowerW` when it builds the data-bus
702
+ * message itself.
703
+ */
704
+ inverterPowerW: number;
705
+ /**
706
+ * The inverter's own total power (W), UNCORRECTED: Model 101 `DCW` when strictly
707
+ * positive, else AC (`W`) when strictly positive, else 0. Clamped to ≥ 0. Always
708
+ * computed and reported independently of `powerOrigin`, so it is available even
709
+ * when {@link inverterPowerW} is sourced from the MPPT strings. Battery flow is
710
+ * NOT backed out here — for the AC branch that is exactly {@link inverterPowerW}
711
+ * minus the battery correction.
712
+ */
713
+ inverterPowerWRaw: number;
714
+ /**
715
+ * Summed per-string MPPT DC power (W) from Model 160 (battery strings
716
+ * `StCha 3` / `StDisCha 4` excluded), clamped to ≥ 0. Always computed and
717
+ * reported independently of `powerOrigin` — `0` when no PV strings are readable.
718
+ */
719
+ inverterPowerWDcStrings: number;
720
+ /** Which register set {@link inverterPowerW} was selected from. */
721
+ powerOrigin: SunspecPvPowerOrigin;
722
+ /**
723
+ * The live battery power (W) backed out of the AC fallback, signed
724
+ * (positive = charging, negative = discharging). Only fetched when the AC/DC
725
+ * inverter-total fallback is in use; `undefined` otherwise or when no live
726
+ * battery source is available.
727
+ */
728
+ batteryPowerW?: number;
729
+ /** Operating state mapped to the Enyo enum. */
730
+ state: EnyoInverterStateEnum;
731
+ /** Raw SunSpec operating state (`St`), unmapped. */
732
+ operatingState?: number;
733
+ voltageL1: number;
734
+ voltageL2?: number;
735
+ voltageL3?: number;
736
+ /**
737
+ * Raw cumulative AC energy (Wh) straight from the register. NOT sanitized —
738
+ * the SDK's acc32 word-boundary guard is applied only on the publish path, so
739
+ * a consumer reading directly should expect the occasional register artifact.
740
+ */
741
+ acEnergyWh?: number;
742
+ /** Per-string DC telemetry (Model 160), battery strings filtered out. */
743
+ strings: EnyoDataBusInverterValuesV1String[];
744
+ }
745
+ /**
746
+ * A decoupled snapshot of a battery's live telemetry, produced by
747
+ * `SunspecBattery.getBatteryReading()`. Contains no data-bus message.
748
+ */
749
+ export interface SunspecBatteryReading {
750
+ /** State of charge (%). */
751
+ soc: number;
752
+ /**
753
+ * Live battery power (W), signed: positive = charging, negative = discharging.
754
+ * `undefined` when the device exposes no live power source (e.g. a Model
755
+ * 124-only battery with no MPPT battery strings).
756
+ */
757
+ powerW?: number;
758
+ /** Charge/discharge state mapped to the Enyo enum. */
759
+ state?: EnyoBatteryStateEnum;
760
+ }
668
761
  export declare enum SunspecBatteryCapability {
669
762
  GridCharging = "grid-charging",
670
763
  DischargeLimit = "discharge-limit",
@@ -279,6 +279,28 @@ export var SunspecPvPowerSource;
279
279
  SunspecPvPowerSource["Mppt"] = "mppt";
280
280
  SunspecPvPowerSource["Inverter"] = "inverter";
281
281
  })(SunspecPvPowerSource || (SunspecPvPowerSource = {}));
282
+ /**
283
+ * The concrete register set an inverter's PV power reading was actually derived
284
+ * from — the *resolved* origin, as opposed to {@link SunspecPvPowerSource} which
285
+ * is the *configured* preference. Returned on {@link SunspecInverterReading} so a
286
+ * consumer can see which telemetry produced the number.
287
+ *
288
+ * - `MpptStrings`: summed per-string DC power from Model 160 (battery strings
289
+ * `StCha 3` / `StDisCha 4` excluded). Already pure PV — never battery-adjusted.
290
+ * - `InverterDc`: the inverter's total DC power (Model 101 `DCW`). Pure PV — never
291
+ * battery-adjusted.
292
+ * - `InverterAc`: the inverter's total AC power (Model 101 `W`). On a hybrid this
293
+ * includes battery flow, so `inverterPowerW` backs it out
294
+ * (PV = AC + batteryPowerW) while `inverterPowerWRaw` keeps the uncorrected AC value.
295
+ * - `None`: no strictly-positive inverter total was available; `inverterPowerW` is 0.
296
+ */
297
+ export var SunspecPvPowerOrigin;
298
+ (function (SunspecPvPowerOrigin) {
299
+ SunspecPvPowerOrigin["MpptStrings"] = "mppt-strings";
300
+ SunspecPvPowerOrigin["InverterDc"] = "inverter-dc";
301
+ SunspecPvPowerOrigin["InverterAc"] = "inverter-ac";
302
+ SunspecPvPowerOrigin["None"] = "none";
303
+ })(SunspecPvPowerOrigin || (SunspecPvPowerOrigin = {}));
282
304
  export var SunspecBatteryCapability;
283
305
  (function (SunspecBatteryCapability) {
284
306
  SunspecBatteryCapability["GridCharging"] = "grid-charging";
package/dist/version.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export declare const SDK_VERSION = "0.0.97";
8
+ export declare const SDK_VERSION = "0.0.98";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/dist/version.js CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export const SDK_VERSION = '0.0.97';
8
+ export const SDK_VERSION = '0.0.98';
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enyo-energy/sunspec-sdk",
3
- "version": "0.0.97",
3
+ "version": "0.0.98",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",