@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.
@@ -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
  */
@@ -14,6 +15,14 @@ export interface IRetryPhase {
14
15
  */
15
16
  export interface IRetryConfig {
16
17
  phases: IRetryPhase[];
18
+ /**
19
+ * Optional jitter fraction (0..1) applied to each phase interval so a fleet of devices that
20
+ * dropped together (e.g. a gateway reboot or a shared outage) does not line up its reconnect
21
+ * attempts on the same 10s/30s/… boundaries and stampede one bridge. The effective gate for a
22
+ * given attempt becomes `intervalMs * (1 + random(-jitter, +jitter))`. The very first attempt
23
+ * after a disconnect still fires immediately. Default 0.2 (±20%); set 0 to disable.
24
+ */
25
+ jitter?: number;
17
26
  }
18
27
  export declare const DEFAULT_RETRY_CONFIG: IRetryConfig;
19
28
  /**
@@ -36,6 +45,45 @@ export interface IModbusPacingConfig {
36
45
  */
37
46
  waitBetweenMessagesMs?: number;
38
47
  }
48
+ /**
49
+ * Resilience configuration for the Modbus client: per-operation timeouts and half-open socket
50
+ * detection. All fields are optional and default to sensible values, so existing consumers are
51
+ * unaffected.
52
+ *
53
+ * These guard the "stuck connection" failure mode: the injected transport's `connect({ timeout })`
54
+ * only bounds the TCP handshake, NOT individual reads/writes. On a half-open socket (the peer stops
55
+ * answering while the OS still reports the connection ESTABLISHED) a read can stay pending forever,
56
+ * wedging the affected unit's transaction chain and stalling its whole poll loop with no failure
57
+ * ever recorded. A per-operation timeout plus a freshness clock turn that silent hang into a fast,
58
+ * observable failure the reconnect path can recover from.
59
+ */
60
+ export interface IModbusResilienceConfig {
61
+ /**
62
+ * Max ms a single Modbus transaction (a read/write, including a multi-chunk block read) may take
63
+ * before it is abandoned with a timeout, the socket is poisoned, and the reconnect path recycles
64
+ * it. Default 5000.
65
+ */
66
+ readTimeoutMs?: number;
67
+ /**
68
+ * Max ms the initial TCP connect for a unit may take before it is abandoned. Enforced by the
69
+ * client independently of the transport-level `timeout` it also forwards. Default 5000.
70
+ */
71
+ connectTimeoutMs?: number;
72
+ /**
73
+ * Max ms a `disconnect()` may take before it is abandoned. A half-open socket can hang even on
74
+ * close, which would otherwise re-wedge the connection lock. Default 5000.
75
+ */
76
+ disconnectTimeoutMs?: number;
77
+ /**
78
+ * If a unit has completed at least one successful transaction but none within this window, its
79
+ * socket is treated as stale (presumed half-open) even when the transport still reports it
80
+ * connected — so `isHealthy()` flips false and the device's reconnect path recycles it before
81
+ * the coarse 5-minute health staleness would. Default 30000 (~3 poll cycles at a 10s poll).
82
+ * Set 0 to disable staleness detection.
83
+ */
84
+ staleSocketMs?: number;
85
+ }
86
+ export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
39
87
  /**
40
88
  * Base interface for all SunSpec blocks
41
89
  */
@@ -665,6 +713,98 @@ export declare enum SunspecPvPowerSource {
665
713
  Mppt = "mppt",
666
714
  Inverter = "inverter"
667
715
  }
716
+ /**
717
+ * The concrete register set an inverter's PV power reading was actually derived
718
+ * from — the *resolved* origin, as opposed to {@link SunspecPvPowerSource} which
719
+ * is the *configured* preference. Returned on {@link SunspecInverterReading} so a
720
+ * consumer can see which telemetry produced the number.
721
+ *
722
+ * - `MpptStrings`: summed per-string DC power from Model 160 (battery strings
723
+ * `StCha 3` / `StDisCha 4` excluded). Already pure PV — never battery-adjusted.
724
+ * - `InverterDc`: the inverter's total DC power (Model 101 `DCW`). Pure PV — never
725
+ * battery-adjusted.
726
+ * - `InverterAc`: the inverter's total AC power (Model 101 `W`). On a hybrid this
727
+ * includes battery flow, so `inverterPowerW` backs it out
728
+ * (PV = AC + batteryPowerW) while `inverterPowerWRaw` keeps the uncorrected AC value.
729
+ * - `None`: no strictly-positive inverter total was available; `inverterPowerW` is 0.
730
+ */
731
+ export declare enum SunspecPvPowerOrigin {
732
+ MpptStrings = "mppt-strings",
733
+ InverterDc = "inverter-dc",
734
+ InverterAc = "inverter-ac",
735
+ None = "none"
736
+ }
737
+ /**
738
+ * A decoupled snapshot of an inverter's live telemetry, produced by
739
+ * `SunspecInverter.getInverterReading()`. Contains no data-bus message and is
740
+ * never sent anywhere — the consumer decides whether to publish it. The same
741
+ * data drives the SDK's own `InverterValuesUpdateV1` message when polling is used.
742
+ */
743
+ export interface SunspecInverterReading {
744
+ /**
745
+ * The auto-calculated PV production (W) to use — the configured source's value
746
+ * (see {@link SunspecPvPowerSource}) with battery charge/discharge backed out of
747
+ * the AC fallback, clamped to ≥ 0. `powerOrigin` says which source produced it.
748
+ * This is the value the SDK publishes as `pvPowerW` when it builds the data-bus
749
+ * message itself.
750
+ */
751
+ inverterPowerW: number;
752
+ /**
753
+ * The inverter's own total power (W), UNCORRECTED: Model 101 `DCW` when strictly
754
+ * positive, else AC (`W`) when strictly positive, else 0. Clamped to ≥ 0. Always
755
+ * computed and reported independently of `powerOrigin`, so it is available even
756
+ * when {@link inverterPowerW} is sourced from the MPPT strings. Battery flow is
757
+ * NOT backed out here — for the AC branch that is exactly {@link inverterPowerW}
758
+ * minus the battery correction.
759
+ */
760
+ inverterPowerWRaw: number;
761
+ /**
762
+ * Summed per-string MPPT DC power (W) from Model 160 (battery strings
763
+ * `StCha 3` / `StDisCha 4` excluded), clamped to ≥ 0. Always computed and
764
+ * reported independently of `powerOrigin` — `0` when no PV strings are readable.
765
+ */
766
+ inverterPowerWDcStrings: number;
767
+ /** Which register set {@link inverterPowerW} was selected from. */
768
+ powerOrigin: SunspecPvPowerOrigin;
769
+ /**
770
+ * The live battery power (W) backed out of the AC fallback, signed
771
+ * (positive = charging, negative = discharging). Only fetched when the AC/DC
772
+ * inverter-total fallback is in use; `undefined` otherwise or when no live
773
+ * battery source is available.
774
+ */
775
+ batteryPowerW?: number;
776
+ /** Operating state mapped to the Enyo enum. */
777
+ state: EnyoInverterStateEnum;
778
+ /** Raw SunSpec operating state (`St`), unmapped. */
779
+ operatingState?: number;
780
+ voltageL1: number;
781
+ voltageL2?: number;
782
+ voltageL3?: number;
783
+ /**
784
+ * Raw cumulative AC energy (Wh) straight from the register. NOT sanitized —
785
+ * the SDK's acc32 word-boundary guard is applied only on the publish path, so
786
+ * a consumer reading directly should expect the occasional register artifact.
787
+ */
788
+ acEnergyWh?: number;
789
+ /** Per-string DC telemetry (Model 160), battery strings filtered out. */
790
+ strings: EnyoDataBusInverterValuesV1String[];
791
+ }
792
+ /**
793
+ * A decoupled snapshot of a battery's live telemetry, produced by
794
+ * `SunspecBattery.getBatteryReading()`. Contains no data-bus message.
795
+ */
796
+ export interface SunspecBatteryReading {
797
+ /** State of charge (%). */
798
+ soc: number;
799
+ /**
800
+ * Live battery power (W), signed: positive = charging, negative = discharging.
801
+ * `undefined` when the device exposes no live power source (e.g. a Model
802
+ * 124-only battery with no MPPT battery strings).
803
+ */
804
+ powerW?: number;
805
+ /** Charge/discharge state mapped to the Enyo enum. */
806
+ state?: EnyoBatteryStateEnum;
807
+ }
668
808
  export declare enum SunspecBatteryCapability {
669
809
  GridCharging = "grid-charging",
670
810
  DischargeLimit = "discharge-limit",
@@ -9,7 +9,14 @@ export const DEFAULT_RETRY_CONFIG = {
9
9
  { intervalMs: 60_000, durationMs: 300_000 }, // Phase 3: every 1m for 5 minutes
10
10
  { intervalMs: 300_000, durationMs: 600_000 }, // Phase 4: every 5m for 10 minutes
11
11
  { intervalMs: 900_000, durationMs: 0 }, // Phase 5: every 15m forever
12
- ]
12
+ ],
13
+ jitter: 0.2,
14
+ };
15
+ export const DEFAULT_MODBUS_RESILIENCE_CONFIG = {
16
+ readTimeoutMs: 5_000,
17
+ connectTimeoutMs: 5_000,
18
+ disconnectTimeoutMs: 5_000,
19
+ staleSocketMs: 30_000,
13
20
  };
14
21
  /**
15
22
  * Common Sunspec Model IDs
@@ -279,6 +286,28 @@ export var SunspecPvPowerSource;
279
286
  SunspecPvPowerSource["Mppt"] = "mppt";
280
287
  SunspecPvPowerSource["Inverter"] = "inverter";
281
288
  })(SunspecPvPowerSource || (SunspecPvPowerSource = {}));
289
+ /**
290
+ * The concrete register set an inverter's PV power reading was actually derived
291
+ * from — the *resolved* origin, as opposed to {@link SunspecPvPowerSource} which
292
+ * is the *configured* preference. Returned on {@link SunspecInverterReading} so a
293
+ * consumer can see which telemetry produced the number.
294
+ *
295
+ * - `MpptStrings`: summed per-string DC power from Model 160 (battery strings
296
+ * `StCha 3` / `StDisCha 4` excluded). Already pure PV — never battery-adjusted.
297
+ * - `InverterDc`: the inverter's total DC power (Model 101 `DCW`). Pure PV — never
298
+ * battery-adjusted.
299
+ * - `InverterAc`: the inverter's total AC power (Model 101 `W`). On a hybrid this
300
+ * includes battery flow, so `inverterPowerW` backs it out
301
+ * (PV = AC + batteryPowerW) while `inverterPowerWRaw` keeps the uncorrected AC value.
302
+ * - `None`: no strictly-positive inverter total was available; `inverterPowerW` is 0.
303
+ */
304
+ export var SunspecPvPowerOrigin;
305
+ (function (SunspecPvPowerOrigin) {
306
+ SunspecPvPowerOrigin["MpptStrings"] = "mppt-strings";
307
+ SunspecPvPowerOrigin["InverterDc"] = "inverter-dc";
308
+ SunspecPvPowerOrigin["InverterAc"] = "inverter-ac";
309
+ SunspecPvPowerOrigin["None"] = "none";
310
+ })(SunspecPvPowerOrigin || (SunspecPvPowerOrigin = {}));
282
311
  export var SunspecBatteryCapability;
283
312
  (function (SunspecBatteryCapability) {
284
313
  SunspecBatteryCapability["GridCharging"] = "grid-charging";