@enyo-energy/sunspec-sdk 0.0.95 → 0.0.97

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.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SunspecMeter = exports.SunspecBattery = exports.SunspecInverter = exports.BaseSunspecDevice = void 0;
4
4
  exports.detectFeaturesFromRegisters = detectFeaturesFromRegisters;
5
+ exports.sumMpptBatteryPowerW = sumMpptBatteryPowerW;
5
6
  exports.selectLiveBatteryPowerW = selectLiveBatteryPowerW;
6
7
  exports.filterFeaturesByCalibrationResult = filterFeaturesByCalibrationResult;
7
8
  const sunspec_interfaces_js_1 = require("./sunspec-interfaces.cjs");
@@ -362,6 +363,13 @@ class SunspecInverter extends BaseSunspecDevice {
362
363
  // state reads healthy), so we force one re-assert of the current status on
363
364
  // the first successful read of each session to converge the core.
364
365
  statusReassertedThisSession = false;
366
+ // Last accepted cumulative AC-energy reading (Wh) and how many consecutive
367
+ // polls have reported a corrupt one (a decrease or a ≥½-register-quantum jump
368
+ // — the acc32 16-bit word-boundary artifact). See sanitizeAcEnergyWh.
369
+ lastGoodAcEnergyWh;
370
+ acEnergyDropStreak = 0;
371
+ /** Consecutive corrupt reads that confirm a genuine reset/resync (vs a transient glitch). */
372
+ static AC_ENERGY_RESET_CONFIRM = 3;
365
373
  constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
366
374
  // Where pvPowerW is sourced from — see SunspecPvPowerSource. Defaults to
367
375
  // Auto (MPPT strings, then Model 101 DCW/AC fallback). Use Mppt to report
@@ -489,7 +497,20 @@ class SunspecInverter extends BaseSunspecDevice {
489
497
  // to Connected. No-op unless this device is still marked offline.
490
498
  await this.reassertConnectedIfRecovered();
491
499
  if (inverterData) {
492
- const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, 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);
493
514
  console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
494
515
  const inverterMessage = {
495
516
  id: (0, node_crypto_1.randomUUID)(),
@@ -507,7 +528,7 @@ class SunspecInverter extends BaseSunspecDevice {
507
528
  voltageL1: inverterData.voltageAN || 0,
508
529
  voltageL2: inverterData.voltageBN ?? undefined,
509
530
  voltageL3: inverterData.voltageCN ?? undefined,
510
- meterValueWh: inverterData.acEnergy,
531
+ meterValueWh: this.sanitizeAcEnergyWh(inverterData.acEnergy, inverterData.acEnergyScaleFactor),
511
532
  strings: dcStrings
512
533
  }
513
534
  };
@@ -533,6 +554,54 @@ class SunspecInverter extends BaseSunspecDevice {
533
554
  }
534
555
  return messages;
535
556
  }
557
+ /**
558
+ * Guard the cumulative AC-energy reading before it is published as
559
+ * `meterValueWh`. The SunSpec `WH` register is an `acc32` (high word + low
560
+ * word) × 10^WH_SF; at a low-word rollover / wake-up the words can be
561
+ * mis-combined, so a poll jumps by exactly one 16-bit word
562
+ * (`65536 × 10^WH_SF`) up or down and back — Dirk Wasow's flip-flop of
563
+ * 6,553,600 Wh. A lifetime accumulator is also monotonic non-decreasing.
564
+ *
565
+ * So a reading is corrupt when it either DECREASES or JUMPS UP by ≥ half a
566
+ * register quantum (real per-poll production is orders of magnitude smaller):
567
+ * we republish the last good value rather than emit it (a raw `max-min`
568
+ * downstream would otherwise inflate it into ~a whole register word). A
569
+ * suspect level that persists for `AC_ENERGY_RESET_CONFIRM` consecutive polls
570
+ * is treated as a genuine reset/resync and adopted.
571
+ *
572
+ * Float models (111/112/113) report `WH` as an IEEE-754 float with no acc32
573
+ * word-boundary artifact; they leave `scaleFactor` undefined. For them there
574
+ * is no register quantum, so we enforce monotonicity only (reject decreases)
575
+ * and accept any increase — the ½-quantum upper bound applies to int+SF
576
+ * models (101/103) alone.
577
+ */
578
+ sanitizeAcEnergyWh(raw, scaleFactor) {
579
+ if (raw == null)
580
+ return undefined;
581
+ if (this.lastGoodAcEnergyWh == null) {
582
+ this.lastGoodAcEnergyWh = raw;
583
+ this.acEnergyDropStreak = 0;
584
+ return raw;
585
+ }
586
+ const halfQuantumWh = scaleFactor != null ? 0.5 * 65536 * Math.pow(10, scaleFactor) : Infinity;
587
+ const delta = raw - this.lastGoodAcEnergyWh;
588
+ const plausible = delta >= 0 && delta < halfQuantumWh;
589
+ if (plausible) {
590
+ this.lastGoodAcEnergyWh = raw;
591
+ this.acEnergyDropStreak = 0;
592
+ return raw;
593
+ }
594
+ // A decrease or a ≥½-quantum jump — the acc32 word-boundary artifact.
595
+ this.acEnergyDropStreak++;
596
+ if (this.acEnergyDropStreak >= SunspecInverter.AC_ENERGY_RESET_CONFIRM) {
597
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: AC energy resync confirmed (${this.lastGoodAcEnergyWh} -> ${raw} Wh), adopting new baseline`);
598
+ this.lastGoodAcEnergyWh = raw;
599
+ this.acEnergyDropStreak = 0;
600
+ return raw;
601
+ }
602
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: rejecting corrupt AC energy reading ${raw} Wh (last good ${this.lastGoodAcEnergyWh} Wh, Δ=${delta}), republishing last good`);
603
+ return this.lastGoodAcEnergyWh;
604
+ }
536
605
  /**
537
606
  * Decode all active error bits from the inverter event registers into
538
607
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -720,6 +789,34 @@ class SunspecInverter extends BaseSunspecDevice {
720
789
  return null;
721
790
  return limitW;
722
791
  }
792
+ /**
793
+ * Set the grid-operator power production (feed-in) limit on the inverter.
794
+ *
795
+ * Writes Model 123 `WMaxLimPct` + `WMaxLim_Ena` (as a percentage of the
796
+ * Model 121 `WMax` nameplate). Pass `null` to remove the limit and return
797
+ * the inverter to unthrottled production.
798
+ *
799
+ * The SDK exposes this so a consumer that receives a grid-operator
800
+ * production-limit command (from the data bus or elsewhere) can apply it;
801
+ * subscribing to and reacting to that command is the consumer's job.
802
+ *
803
+ * @param limitW - Maximum production power in Watts, or `null` to remove the limit
804
+ * @returns `true` if the write succeeded, `false` otherwise
805
+ */
806
+ async setPowerProductionLimit(limitW) {
807
+ return this.sunspecClient.setFeedInLimit(this.unitId, limitW);
808
+ }
809
+ /**
810
+ * Read the currently active grid-operator power production (feed-in) limit
811
+ * from the inverter, in Watts. Returns `null` when no limit is active, the
812
+ * registers cannot be read, or the configured limit is not actually
813
+ * throttling (limit ≥ `WMax`). See {@link computeActiveProductionLimitW}.
814
+ */
815
+ async getPowerProductionLimit() {
816
+ const settings = await this.sunspecClient.readInverterSettings(this.unitId);
817
+ const controls = await this.sunspecClient.readInverterControls(this.unitId);
818
+ return this.computeActiveProductionLimitW(settings, controls);
819
+ }
723
820
  mapOperatingState(state) {
724
821
  if (!state)
725
822
  return enyo_data_bus_value_js_1.EnyoInverterStateEnum.Off;
@@ -751,29 +848,54 @@ class SunspecInverter extends BaseSunspecDevice {
751
848
  * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
752
849
  * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
753
850
  * importing from grid) falls through to 0 rather than reporting negative production.
754
- * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
755
- * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
756
- * better than reporting 0.
851
+ *
852
+ * The AC fallback backs out battery power via `batteryPowerW` (signed: positive =
853
+ * charging, negative = discharging). A hybrid's AC total is PV − charge + discharge,
854
+ * so real PV = AC + batteryPowerW. Without this, a battery discharging at night while
855
+ * the MPPT is unreadable would be reported as phantom PV production. `batteryPowerW`
856
+ * is undefined when no live battery source is available, in which case AC is used
857
+ * uncorrected (still better than reporting 0).
858
+ *
859
+ * The returned `pvPowerW` is always clamped to ≥ 0 — PV production is non-negative by
860
+ * definition and must never surface as a negative value on the data bus.
757
861
  */
758
- selectPvPowerW(dcStrings, inverterData) {
759
- const stringSumW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
760
- const useStrings = this.pvPowerSource === sunspec_interfaces_js_1.SunspecPvPowerSource.Mppt ||
761
- (this.pvPowerSource === sunspec_interfaces_js_1.SunspecPvPowerSource.Auto && dcStrings.length > 0);
762
- if (useStrings) {
763
- return { pvPowerW: stringSumW, source: 'DC strings' };
862
+ 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' };
764
866
  }
765
- return this.inverterTotalPvPowerW(inverterData);
867
+ return this.inverterTotalPvPowerW(inverterData, batteryPowerW);
766
868
  }
767
869
  /**
768
- * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
769
- * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
870
+ * Whether {@link selectPvPowerW} will source PV from the inverter total (rather than
871
+ * the summed MPPT strings) for the given string count. Mppt never does; Inverter
872
+ * always does; Auto does only when there are no strings. Exposed so `readData` can
873
+ * decide up front whether it needs to fetch battery power for the AC correction.
770
874
  */
771
- inverterTotalPvPowerW(inverterData) {
875
+ wouldUseInverterTotal(dcStringCount) {
876
+ if (this.pvPowerSource === sunspec_interfaces_js_1.SunspecPvPowerSource.Mppt)
877
+ return false;
878
+ if (this.pvPowerSource === sunspec_interfaces_js_1.SunspecPvPowerSource.Inverter)
879
+ return true;
880
+ return dcStringCount === 0; // Auto
881
+ }
882
+ /**
883
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC (with
884
+ * battery power backed out) when the result is strictly positive, else 0. See
885
+ * {@link selectPvPowerW} for the battery correction and why positivity matters.
886
+ */
887
+ inverterTotalPvPowerW(inverterData, batteryPowerW) {
772
888
  if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
773
889
  return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
774
890
  }
775
891
  if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
776
- return { pvPowerW: inverterData.acPower, source: 'AC power (Model 101)' };
892
+ // AC = PV − charge + discharge on a hybrid; batteryPowerW is signed
893
+ // (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' };
777
899
  }
778
900
  return { pvPowerW: 0, source: 'none' };
779
901
  }
@@ -1006,6 +1128,31 @@ function detectFeaturesFromRegisters(batteryData) {
1006
1128
  * Exported as a free function so the preference logic can be unit-tested
1007
1129
  * without the full `SunspecBattery` scaffold.
1008
1130
  */
1131
+ /**
1132
+ * Sum battery charge/discharge power from Model 160 MPPT strings.
1133
+ *
1134
+ * - `StCha 3` → charging power (added, positive)
1135
+ * - `StDisCha 4` → discharging power (subtracted)
1136
+ *
1137
+ * The result follows the battery-power sign convention used across this file:
1138
+ * positive = charging, negative = discharging. Returns `undefined` when neither
1139
+ * battery string is present, so callers can fall through to another source.
1140
+ *
1141
+ * Exported as a free function so it can be unit-tested and reused by both the
1142
+ * SunspecBattery live-power path and the SunspecInverter AC-fallback correction.
1143
+ */
1144
+ function sumMpptBatteryPowerW(mpptDataList) {
1145
+ let batteryPowerW;
1146
+ for (const mppt of mpptDataList) {
1147
+ if (mppt.stringId === 'StCha 3' && mppt.dcPower !== undefined) {
1148
+ batteryPowerW = (batteryPowerW ?? 0) + mppt.dcPower;
1149
+ }
1150
+ else if (mppt.stringId === 'StDisCha 4' && mppt.dcPower !== undefined) {
1151
+ batteryPowerW = (batteryPowerW ?? 0) - mppt.dcPower;
1152
+ }
1153
+ }
1154
+ return batteryPowerW;
1155
+ }
1009
1156
  function selectLiveBatteryPowerW(mpptBatteryPowerW, batteryData) {
1010
1157
  if (mpptBatteryPowerW !== undefined) {
1011
1158
  return mpptBatteryPowerW;
@@ -1345,18 +1492,7 @@ class SunspecBattery extends BaseSunspecDevice {
1345
1492
  * StDisCha 4: Battery discharging power (negative)
1346
1493
  */
1347
1494
  extractBatteryPowerFromMPPT(mpptDataList) {
1348
- let batteryPowerW;
1349
- mpptDataList.forEach((mppt) => {
1350
- if (mppt.stringId === 'StCha 3' && mppt.dcPower !== undefined) {
1351
- // Charging power is positive
1352
- batteryPowerW = (batteryPowerW || 0) + mppt.dcPower;
1353
- }
1354
- else if (mppt.stringId === 'StDisCha 4' && mppt.dcPower !== undefined) {
1355
- // Discharging power is negative
1356
- batteryPowerW = (batteryPowerW || 0) - mppt.dcPower;
1357
- }
1358
- });
1359
- return batteryPowerW;
1495
+ return sumMpptBatteryPowerW(mpptDataList);
1360
1496
  }
1361
1497
  /**
1362
1498
  * Determine battery state from MPPT strings
@@ -142,10 +142,36 @@ export declare class SunspecInverter extends BaseSunspecDevice {
142
142
  private errorState;
143
143
  private snapshotService?;
144
144
  private statusReassertedThisSession;
145
+ private lastGoodAcEnergyWh?;
146
+ private acEnergyDropStreak;
147
+ /** Consecutive corrupt reads that confirm a genuine reset/resync (vs a transient glitch). */
148
+ private static readonly AC_ENERGY_RESET_CONFIRM;
145
149
  constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, unitId?: number, port?: number, baseAddress?: number, capabilities?: SunspecInverterCapability[], retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean, pvPowerSource?: SunspecPvPowerSource);
146
150
  connect(): Promise<void>;
147
151
  disconnect(): Promise<void>;
148
- readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
152
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
153
+ /**
154
+ * Guard the cumulative AC-energy reading before it is published as
155
+ * `meterValueWh`. The SunSpec `WH` register is an `acc32` (high word + low
156
+ * word) × 10^WH_SF; at a low-word rollover / wake-up the words can be
157
+ * mis-combined, so a poll jumps by exactly one 16-bit word
158
+ * (`65536 × 10^WH_SF`) up or down and back — Dirk Wasow's flip-flop of
159
+ * 6,553,600 Wh. A lifetime accumulator is also monotonic non-decreasing.
160
+ *
161
+ * So a reading is corrupt when it either DECREASES or JUMPS UP by ≥ half a
162
+ * register quantum (real per-poll production is orders of magnitude smaller):
163
+ * we republish the last good value rather than emit it (a raw `max-min`
164
+ * downstream would otherwise inflate it into ~a whole register word). A
165
+ * suspect level that persists for `AC_ENERGY_RESET_CONFIRM` consecutive polls
166
+ * is treated as a genuine reset/resync and adopted.
167
+ *
168
+ * Float models (111/112/113) report `WH` as an IEEE-754 float with no acc32
169
+ * word-boundary artifact; they leave `scaleFactor` undefined. For them there
170
+ * is no register quantum, so we enforce monotonicity only (reject decreases)
171
+ * and accept any increase — the ½-quantum upper bound applies to int+SF
172
+ * models (101/103) alone.
173
+ */
174
+ private sanitizeAcEnergyWh;
149
175
  /**
150
176
  * Decode all active error bits from the inverter event registers into
151
177
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -190,6 +216,28 @@ export declare class SunspecInverter extends BaseSunspecDevice {
190
216
  * returned (not undefined) so the field is cleared on the appliance.
191
217
  */
192
218
  private computeActiveProductionLimitW;
219
+ /**
220
+ * Set the grid-operator power production (feed-in) limit on the inverter.
221
+ *
222
+ * Writes Model 123 `WMaxLimPct` + `WMaxLim_Ena` (as a percentage of the
223
+ * Model 121 `WMax` nameplate). Pass `null` to remove the limit and return
224
+ * the inverter to unthrottled production.
225
+ *
226
+ * The SDK exposes this so a consumer that receives a grid-operator
227
+ * production-limit command (from the data bus or elsewhere) can apply it;
228
+ * subscribing to and reacting to that command is the consumer's job.
229
+ *
230
+ * @param limitW - Maximum production power in Watts, or `null` to remove the limit
231
+ * @returns `true` if the write succeeded, `false` otherwise
232
+ */
233
+ setPowerProductionLimit(limitW: number | null): Promise<boolean>;
234
+ /**
235
+ * Read the currently active grid-operator power production (feed-in) limit
236
+ * from the inverter, in Watts. Returns `null` when no limit is active, the
237
+ * registers cannot be read, or the configured limit is not actually
238
+ * throttling (limit ≥ `WMax`). See {@link computeActiveProductionLimitW}.
239
+ */
240
+ getPowerProductionLimit(): Promise<number | null>;
193
241
  private mapOperatingState;
194
242
  /**
195
243
  * PV production in Watt, sourced according to the configured `pvPowerSource`:
@@ -207,17 +255,32 @@ export declare class SunspecInverter extends BaseSunspecDevice {
207
255
  * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
208
256
  * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
209
257
  * importing from grid) falls through to 0 rather than reporting negative production.
210
- * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
211
- * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
212
- * better than reporting 0.
258
+ *
259
+ * The AC fallback backs out battery power via `batteryPowerW` (signed: positive =
260
+ * charging, negative = discharging). A hybrid's AC total is PV − charge + discharge,
261
+ * so real PV = AC + batteryPowerW. Without this, a battery discharging at night while
262
+ * the MPPT is unreadable would be reported as phantom PV production. `batteryPowerW`
263
+ * is undefined when no live battery source is available, in which case AC is used
264
+ * uncorrected (still better than reporting 0).
265
+ *
266
+ * The returned `pvPowerW` is always clamped to ≥ 0 — PV production is non-negative by
267
+ * definition and must never surface as a negative value on the data bus.
213
268
  */
214
- protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData): {
269
+ protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData, batteryPowerW?: number): {
215
270
  pvPowerW: number;
216
271
  source: string;
217
272
  };
218
273
  /**
219
- * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
220
- * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
274
+ * Whether {@link selectPvPowerW} will source PV from the inverter total (rather than
275
+ * the summed MPPT strings) for the given string count. Mppt never does; Inverter
276
+ * always does; Auto does only when there are no strings. Exposed so `readData` can
277
+ * decide up front whether it needs to fetch battery power for the AC correction.
278
+ */
279
+ private wouldUseInverterTotal;
280
+ /**
281
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC (with
282
+ * battery power backed out) when the result is strictly positive, else 0. See
283
+ * {@link selectPvPowerW} for the battery correction and why positivity matters.
221
284
  */
222
285
  private inverterTotalPvPowerW;
223
286
  /**
@@ -298,6 +361,20 @@ export declare function detectFeaturesFromRegisters(batteryData: SunspecBatteryD
298
361
  * Exported as a free function so the preference logic can be unit-tested
299
362
  * without the full `SunspecBattery` scaffold.
300
363
  */
364
+ /**
365
+ * Sum battery charge/discharge power from Model 160 MPPT strings.
366
+ *
367
+ * - `StCha 3` → charging power (added, positive)
368
+ * - `StDisCha 4` → discharging power (subtracted)
369
+ *
370
+ * The result follows the battery-power sign convention used across this file:
371
+ * positive = charging, negative = discharging. Returns `undefined` when neither
372
+ * battery string is present, so callers can fall through to another source.
373
+ *
374
+ * Exported as a free function so it can be unit-tested and reused by both the
375
+ * SunspecBattery live-power path and the SunspecInverter AC-fallback correction.
376
+ */
377
+ export declare function sumMpptBatteryPowerW(mpptDataList: SunspecMPPTData[]): number | undefined;
301
378
  export declare function selectLiveBatteryPowerW(mpptBatteryPowerW: number | undefined, batteryData: SunspecBatteryData | null): number | undefined;
302
379
  export declare function filterFeaturesByCalibrationResult(detected: EnyoBatteryFeature[], result: CalibrationResult | undefined, controllable: readonly EnyoBatteryFeature[]): EnyoBatteryFeature[];
303
380
  /**
@@ -366,7 +443,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
366
443
  /**
367
444
  * Update battery data and return data bus messages
368
445
  */
369
- readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
446
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
370
447
  /**
371
448
  * Extract battery power from MPPT strings with specific IDs
372
449
  * StCha 3: Battery charging power (positive)
@@ -124,6 +124,7 @@ export interface SunspecInverterData extends SunspecBlock {
124
124
  reactivePower?: number;
125
125
  powerFactor?: number;
126
126
  acEnergy?: number;
127
+ acEnergyScaleFactor?: number;
127
128
  dcCurrent?: number;
128
129
  dcVoltage?: number;
129
130
  dcPower?: number;
@@ -976,9 +976,11 @@ class SunspecModbusClient {
976
976
  this.logRegisterRead(103, 50, 'Vendor Events 4', data.vendorEvents4, 'bitfield32');
977
977
  const acEnergy = this.extractValue(buffer, 24, 'uint32', 2);
978
978
  this.logRegisterRead(103, 24, 'AC Energy', acEnergy, 'acc32');
979
+ const whSf = this.isUnimplementedValue(scaleFactors.WH_SF, 'int16') ? 0 : scaleFactors.WH_SF;
979
980
  data.acEnergy = !this.isUnimplementedValue(acEnergy, 'acc32')
980
- ? acEnergy * Math.pow(10, scaleFactors.WH_SF)
981
+ ? acEnergy * Math.pow(10, whSf)
981
982
  : undefined;
983
+ data.acEnergyScaleFactor = whSf;
982
984
  console.debug('[Model 103] Inverter Data:', data);
983
985
  return data;
984
986
  }
@@ -1038,9 +1040,11 @@ class SunspecModbusClient {
1038
1040
  // Read AC Energy (32-bit accumulator) - Offset 24-25
1039
1041
  const acEnergy = this.extractValue(buffer, 24, 'uint32', 2);
1040
1042
  this.logRegisterRead(101, 24, 'AC Energy', acEnergy, 'acc32');
1043
+ const whSf = this.isUnimplementedValue(scaleFactors.WH_SF, 'int16') ? 0 : scaleFactors.WH_SF;
1041
1044
  data.acEnergy = !this.isUnimplementedValue(acEnergy, 'acc32')
1042
- ? acEnergy * Math.pow(10, scaleFactors.WH_SF)
1045
+ ? acEnergy * Math.pow(10, whSf)
1043
1046
  : undefined;
1047
+ data.acEnergyScaleFactor = whSf;
1044
1048
  console.debug('[Model 101] Single Phase Inverter Data:', data);
1045
1049
  return data;
1046
1050
  }
@@ -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.95';
12
+ exports.SDK_VERSION = '0.0.97';
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.95";
8
+ export declare const SDK_VERSION = "0.0.97";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
@@ -142,10 +142,36 @@ export declare class SunspecInverter extends BaseSunspecDevice {
142
142
  private errorState;
143
143
  private snapshotService?;
144
144
  private statusReassertedThisSession;
145
+ private lastGoodAcEnergyWh?;
146
+ private acEnergyDropStreak;
147
+ /** Consecutive corrupt reads that confirm a genuine reset/resync (vs a transient glitch). */
148
+ private static readonly AC_ENERGY_RESET_CONFIRM;
145
149
  constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, unitId?: number, port?: number, baseAddress?: number, capabilities?: SunspecInverterCapability[], retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean, pvPowerSource?: SunspecPvPowerSource);
146
150
  connect(): Promise<void>;
147
151
  disconnect(): Promise<void>;
148
- readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
152
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
153
+ /**
154
+ * Guard the cumulative AC-energy reading before it is published as
155
+ * `meterValueWh`. The SunSpec `WH` register is an `acc32` (high word + low
156
+ * word) × 10^WH_SF; at a low-word rollover / wake-up the words can be
157
+ * mis-combined, so a poll jumps by exactly one 16-bit word
158
+ * (`65536 × 10^WH_SF`) up or down and back — Dirk Wasow's flip-flop of
159
+ * 6,553,600 Wh. A lifetime accumulator is also monotonic non-decreasing.
160
+ *
161
+ * So a reading is corrupt when it either DECREASES or JUMPS UP by ≥ half a
162
+ * register quantum (real per-poll production is orders of magnitude smaller):
163
+ * we republish the last good value rather than emit it (a raw `max-min`
164
+ * downstream would otherwise inflate it into ~a whole register word). A
165
+ * suspect level that persists for `AC_ENERGY_RESET_CONFIRM` consecutive polls
166
+ * is treated as a genuine reset/resync and adopted.
167
+ *
168
+ * Float models (111/112/113) report `WH` as an IEEE-754 float with no acc32
169
+ * word-boundary artifact; they leave `scaleFactor` undefined. For them there
170
+ * is no register quantum, so we enforce monotonicity only (reject decreases)
171
+ * and accept any increase — the ½-quantum upper bound applies to int+SF
172
+ * models (101/103) alone.
173
+ */
174
+ private sanitizeAcEnergyWh;
149
175
  /**
150
176
  * Decode all active error bits from the inverter event registers into
151
177
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -190,6 +216,28 @@ export declare class SunspecInverter extends BaseSunspecDevice {
190
216
  * returned (not undefined) so the field is cleared on the appliance.
191
217
  */
192
218
  private computeActiveProductionLimitW;
219
+ /**
220
+ * Set the grid-operator power production (feed-in) limit on the inverter.
221
+ *
222
+ * Writes Model 123 `WMaxLimPct` + `WMaxLim_Ena` (as a percentage of the
223
+ * Model 121 `WMax` nameplate). Pass `null` to remove the limit and return
224
+ * the inverter to unthrottled production.
225
+ *
226
+ * The SDK exposes this so a consumer that receives a grid-operator
227
+ * production-limit command (from the data bus or elsewhere) can apply it;
228
+ * subscribing to and reacting to that command is the consumer's job.
229
+ *
230
+ * @param limitW - Maximum production power in Watts, or `null` to remove the limit
231
+ * @returns `true` if the write succeeded, `false` otherwise
232
+ */
233
+ setPowerProductionLimit(limitW: number | null): Promise<boolean>;
234
+ /**
235
+ * Read the currently active grid-operator power production (feed-in) limit
236
+ * from the inverter, in Watts. Returns `null` when no limit is active, the
237
+ * registers cannot be read, or the configured limit is not actually
238
+ * throttling (limit ≥ `WMax`). See {@link computeActiveProductionLimitW}.
239
+ */
240
+ getPowerProductionLimit(): Promise<number | null>;
193
241
  private mapOperatingState;
194
242
  /**
195
243
  * PV production in Watt, sourced according to the configured `pvPowerSource`:
@@ -207,17 +255,32 @@ export declare class SunspecInverter extends BaseSunspecDevice {
207
255
  * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
208
256
  * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
209
257
  * importing from grid) falls through to 0 rather than reporting negative production.
210
- * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
211
- * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
212
- * better than reporting 0.
258
+ *
259
+ * The AC fallback backs out battery power via `batteryPowerW` (signed: positive =
260
+ * charging, negative = discharging). A hybrid's AC total is PV − charge + discharge,
261
+ * so real PV = AC + batteryPowerW. Without this, a battery discharging at night while
262
+ * the MPPT is unreadable would be reported as phantom PV production. `batteryPowerW`
263
+ * is undefined when no live battery source is available, in which case AC is used
264
+ * uncorrected (still better than reporting 0).
265
+ *
266
+ * The returned `pvPowerW` is always clamped to ≥ 0 — PV production is non-negative by
267
+ * definition and must never surface as a negative value on the data bus.
213
268
  */
214
- protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData): {
269
+ protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData, batteryPowerW?: number): {
215
270
  pvPowerW: number;
216
271
  source: string;
217
272
  };
218
273
  /**
219
- * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
220
- * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
274
+ * Whether {@link selectPvPowerW} will source PV from the inverter total (rather than
275
+ * the summed MPPT strings) for the given string count. Mppt never does; Inverter
276
+ * always does; Auto does only when there are no strings. Exposed so `readData` can
277
+ * decide up front whether it needs to fetch battery power for the AC correction.
278
+ */
279
+ private wouldUseInverterTotal;
280
+ /**
281
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC (with
282
+ * battery power backed out) when the result is strictly positive, else 0. See
283
+ * {@link selectPvPowerW} for the battery correction and why positivity matters.
221
284
  */
222
285
  private inverterTotalPvPowerW;
223
286
  /**
@@ -298,6 +361,20 @@ export declare function detectFeaturesFromRegisters(batteryData: SunspecBatteryD
298
361
  * Exported as a free function so the preference logic can be unit-tested
299
362
  * without the full `SunspecBattery` scaffold.
300
363
  */
364
+ /**
365
+ * Sum battery charge/discharge power from Model 160 MPPT strings.
366
+ *
367
+ * - `StCha 3` → charging power (added, positive)
368
+ * - `StDisCha 4` → discharging power (subtracted)
369
+ *
370
+ * The result follows the battery-power sign convention used across this file:
371
+ * positive = charging, negative = discharging. Returns `undefined` when neither
372
+ * battery string is present, so callers can fall through to another source.
373
+ *
374
+ * Exported as a free function so it can be unit-tested and reused by both the
375
+ * SunspecBattery live-power path and the SunspecInverter AC-fallback correction.
376
+ */
377
+ export declare function sumMpptBatteryPowerW(mpptDataList: SunspecMPPTData[]): number | undefined;
301
378
  export declare function selectLiveBatteryPowerW(mpptBatteryPowerW: number | undefined, batteryData: SunspecBatteryData | null): number | undefined;
302
379
  export declare function filterFeaturesByCalibrationResult(detected: EnyoBatteryFeature[], result: CalibrationResult | undefined, controllable: readonly EnyoBatteryFeature[]): EnyoBatteryFeature[];
303
380
  /**
@@ -366,7 +443,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
366
443
  /**
367
444
  * Update battery data and return data bus messages
368
445
  */
369
- readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
446
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
370
447
  /**
371
448
  * Extract battery power from MPPT strings with specific IDs
372
449
  * StCha 3: Battery charging power (positive)
@@ -355,6 +355,13 @@ export class SunspecInverter extends BaseSunspecDevice {
355
355
  // state reads healthy), so we force one re-assert of the current status on
356
356
  // the first successful read of each session to converge the core.
357
357
  statusReassertedThisSession = false;
358
+ // Last accepted cumulative AC-energy reading (Wh) and how many consecutive
359
+ // polls have reported a corrupt one (a decrease or a ≥½-register-quantum jump
360
+ // — the acc32 16-bit word-boundary artifact). See sanitizeAcEnergyWh.
361
+ lastGoodAcEnergyWh;
362
+ acEnergyDropStreak = 0;
363
+ /** Consecutive corrupt reads that confirm a genuine reset/resync (vs a transient glitch). */
364
+ static AC_ENERGY_RESET_CONFIRM = 3;
358
365
  constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
359
366
  // Where pvPowerW is sourced from — see SunspecPvPowerSource. Defaults to
360
367
  // Auto (MPPT strings, then Model 101 DCW/AC fallback). Use Mppt to report
@@ -482,7 +489,20 @@ export class SunspecInverter extends BaseSunspecDevice {
482
489
  // to Connected. No-op unless this device is still marked offline.
483
490
  await this.reassertConnectedIfRecovered();
484
491
  if (inverterData) {
485
- const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, 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);
486
506
  console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
487
507
  const inverterMessage = {
488
508
  id: randomUUID(),
@@ -500,7 +520,7 @@ export class SunspecInverter extends BaseSunspecDevice {
500
520
  voltageL1: inverterData.voltageAN || 0,
501
521
  voltageL2: inverterData.voltageBN ?? undefined,
502
522
  voltageL3: inverterData.voltageCN ?? undefined,
503
- meterValueWh: inverterData.acEnergy,
523
+ meterValueWh: this.sanitizeAcEnergyWh(inverterData.acEnergy, inverterData.acEnergyScaleFactor),
504
524
  strings: dcStrings
505
525
  }
506
526
  };
@@ -526,6 +546,54 @@ export class SunspecInverter extends BaseSunspecDevice {
526
546
  }
527
547
  return messages;
528
548
  }
549
+ /**
550
+ * Guard the cumulative AC-energy reading before it is published as
551
+ * `meterValueWh`. The SunSpec `WH` register is an `acc32` (high word + low
552
+ * word) × 10^WH_SF; at a low-word rollover / wake-up the words can be
553
+ * mis-combined, so a poll jumps by exactly one 16-bit word
554
+ * (`65536 × 10^WH_SF`) up or down and back — Dirk Wasow's flip-flop of
555
+ * 6,553,600 Wh. A lifetime accumulator is also monotonic non-decreasing.
556
+ *
557
+ * So a reading is corrupt when it either DECREASES or JUMPS UP by ≥ half a
558
+ * register quantum (real per-poll production is orders of magnitude smaller):
559
+ * we republish the last good value rather than emit it (a raw `max-min`
560
+ * downstream would otherwise inflate it into ~a whole register word). A
561
+ * suspect level that persists for `AC_ENERGY_RESET_CONFIRM` consecutive polls
562
+ * is treated as a genuine reset/resync and adopted.
563
+ *
564
+ * Float models (111/112/113) report `WH` as an IEEE-754 float with no acc32
565
+ * word-boundary artifact; they leave `scaleFactor` undefined. For them there
566
+ * is no register quantum, so we enforce monotonicity only (reject decreases)
567
+ * and accept any increase — the ½-quantum upper bound applies to int+SF
568
+ * models (101/103) alone.
569
+ */
570
+ sanitizeAcEnergyWh(raw, scaleFactor) {
571
+ if (raw == null)
572
+ return undefined;
573
+ if (this.lastGoodAcEnergyWh == null) {
574
+ this.lastGoodAcEnergyWh = raw;
575
+ this.acEnergyDropStreak = 0;
576
+ return raw;
577
+ }
578
+ const halfQuantumWh = scaleFactor != null ? 0.5 * 65536 * Math.pow(10, scaleFactor) : Infinity;
579
+ const delta = raw - this.lastGoodAcEnergyWh;
580
+ const plausible = delta >= 0 && delta < halfQuantumWh;
581
+ if (plausible) {
582
+ this.lastGoodAcEnergyWh = raw;
583
+ this.acEnergyDropStreak = 0;
584
+ return raw;
585
+ }
586
+ // A decrease or a ≥½-quantum jump — the acc32 word-boundary artifact.
587
+ this.acEnergyDropStreak++;
588
+ if (this.acEnergyDropStreak >= SunspecInverter.AC_ENERGY_RESET_CONFIRM) {
589
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: AC energy resync confirmed (${this.lastGoodAcEnergyWh} -> ${raw} Wh), adopting new baseline`);
590
+ this.lastGoodAcEnergyWh = raw;
591
+ this.acEnergyDropStreak = 0;
592
+ return raw;
593
+ }
594
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: rejecting corrupt AC energy reading ${raw} Wh (last good ${this.lastGoodAcEnergyWh} Wh, Δ=${delta}), republishing last good`);
595
+ return this.lastGoodAcEnergyWh;
596
+ }
529
597
  /**
530
598
  * Decode all active error bits from the inverter event registers into
531
599
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -713,6 +781,34 @@ export class SunspecInverter extends BaseSunspecDevice {
713
781
  return null;
714
782
  return limitW;
715
783
  }
784
+ /**
785
+ * Set the grid-operator power production (feed-in) limit on the inverter.
786
+ *
787
+ * Writes Model 123 `WMaxLimPct` + `WMaxLim_Ena` (as a percentage of the
788
+ * Model 121 `WMax` nameplate). Pass `null` to remove the limit and return
789
+ * the inverter to unthrottled production.
790
+ *
791
+ * The SDK exposes this so a consumer that receives a grid-operator
792
+ * production-limit command (from the data bus or elsewhere) can apply it;
793
+ * subscribing to and reacting to that command is the consumer's job.
794
+ *
795
+ * @param limitW - Maximum production power in Watts, or `null` to remove the limit
796
+ * @returns `true` if the write succeeded, `false` otherwise
797
+ */
798
+ async setPowerProductionLimit(limitW) {
799
+ return this.sunspecClient.setFeedInLimit(this.unitId, limitW);
800
+ }
801
+ /**
802
+ * Read the currently active grid-operator power production (feed-in) limit
803
+ * from the inverter, in Watts. Returns `null` when no limit is active, the
804
+ * registers cannot be read, or the configured limit is not actually
805
+ * throttling (limit ≥ `WMax`). See {@link computeActiveProductionLimitW}.
806
+ */
807
+ async getPowerProductionLimit() {
808
+ const settings = await this.sunspecClient.readInverterSettings(this.unitId);
809
+ const controls = await this.sunspecClient.readInverterControls(this.unitId);
810
+ return this.computeActiveProductionLimitW(settings, controls);
811
+ }
716
812
  mapOperatingState(state) {
717
813
  if (!state)
718
814
  return EnyoInverterStateEnum.Off;
@@ -744,29 +840,54 @@ export class SunspecInverter extends BaseSunspecDevice {
744
840
  * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
745
841
  * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
746
842
  * importing from grid) falls through to 0 rather than reporting negative production.
747
- * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
748
- * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
749
- * better than reporting 0.
843
+ *
844
+ * The AC fallback backs out battery power via `batteryPowerW` (signed: positive =
845
+ * charging, negative = discharging). A hybrid's AC total is PV − charge + discharge,
846
+ * so real PV = AC + batteryPowerW. Without this, a battery discharging at night while
847
+ * the MPPT is unreadable would be reported as phantom PV production. `batteryPowerW`
848
+ * is undefined when no live battery source is available, in which case AC is used
849
+ * uncorrected (still better than reporting 0).
850
+ *
851
+ * The returned `pvPowerW` is always clamped to ≥ 0 — PV production is non-negative by
852
+ * definition and must never surface as a negative value on the data bus.
750
853
  */
751
- selectPvPowerW(dcStrings, inverterData) {
752
- const stringSumW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
753
- const useStrings = this.pvPowerSource === SunspecPvPowerSource.Mppt ||
754
- (this.pvPowerSource === SunspecPvPowerSource.Auto && dcStrings.length > 0);
755
- if (useStrings) {
756
- return { pvPowerW: stringSumW, source: 'DC strings' };
854
+ 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' };
757
858
  }
758
- return this.inverterTotalPvPowerW(inverterData);
859
+ return this.inverterTotalPvPowerW(inverterData, batteryPowerW);
759
860
  }
760
861
  /**
761
- * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
762
- * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
862
+ * Whether {@link selectPvPowerW} will source PV from the inverter total (rather than
863
+ * the summed MPPT strings) for the given string count. Mppt never does; Inverter
864
+ * always does; Auto does only when there are no strings. Exposed so `readData` can
865
+ * decide up front whether it needs to fetch battery power for the AC correction.
763
866
  */
764
- inverterTotalPvPowerW(inverterData) {
867
+ wouldUseInverterTotal(dcStringCount) {
868
+ if (this.pvPowerSource === SunspecPvPowerSource.Mppt)
869
+ return false;
870
+ if (this.pvPowerSource === SunspecPvPowerSource.Inverter)
871
+ return true;
872
+ return dcStringCount === 0; // Auto
873
+ }
874
+ /**
875
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC (with
876
+ * battery power backed out) when the result is strictly positive, else 0. See
877
+ * {@link selectPvPowerW} for the battery correction and why positivity matters.
878
+ */
879
+ inverterTotalPvPowerW(inverterData, batteryPowerW) {
765
880
  if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
766
881
  return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
767
882
  }
768
883
  if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
769
- return { pvPowerW: inverterData.acPower, source: 'AC power (Model 101)' };
884
+ // AC = PV − charge + discharge on a hybrid; batteryPowerW is signed
885
+ // (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' };
770
891
  }
771
892
  return { pvPowerW: 0, source: 'none' };
772
893
  }
@@ -998,6 +1119,31 @@ export function detectFeaturesFromRegisters(batteryData) {
998
1119
  * Exported as a free function so the preference logic can be unit-tested
999
1120
  * without the full `SunspecBattery` scaffold.
1000
1121
  */
1122
+ /**
1123
+ * Sum battery charge/discharge power from Model 160 MPPT strings.
1124
+ *
1125
+ * - `StCha 3` → charging power (added, positive)
1126
+ * - `StDisCha 4` → discharging power (subtracted)
1127
+ *
1128
+ * The result follows the battery-power sign convention used across this file:
1129
+ * positive = charging, negative = discharging. Returns `undefined` when neither
1130
+ * battery string is present, so callers can fall through to another source.
1131
+ *
1132
+ * Exported as a free function so it can be unit-tested and reused by both the
1133
+ * SunspecBattery live-power path and the SunspecInverter AC-fallback correction.
1134
+ */
1135
+ export function sumMpptBatteryPowerW(mpptDataList) {
1136
+ let batteryPowerW;
1137
+ for (const mppt of mpptDataList) {
1138
+ if (mppt.stringId === 'StCha 3' && mppt.dcPower !== undefined) {
1139
+ batteryPowerW = (batteryPowerW ?? 0) + mppt.dcPower;
1140
+ }
1141
+ else if (mppt.stringId === 'StDisCha 4' && mppt.dcPower !== undefined) {
1142
+ batteryPowerW = (batteryPowerW ?? 0) - mppt.dcPower;
1143
+ }
1144
+ }
1145
+ return batteryPowerW;
1146
+ }
1001
1147
  export function selectLiveBatteryPowerW(mpptBatteryPowerW, batteryData) {
1002
1148
  if (mpptBatteryPowerW !== undefined) {
1003
1149
  return mpptBatteryPowerW;
@@ -1337,18 +1483,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1337
1483
  * StDisCha 4: Battery discharging power (negative)
1338
1484
  */
1339
1485
  extractBatteryPowerFromMPPT(mpptDataList) {
1340
- let batteryPowerW;
1341
- mpptDataList.forEach((mppt) => {
1342
- if (mppt.stringId === 'StCha 3' && mppt.dcPower !== undefined) {
1343
- // Charging power is positive
1344
- batteryPowerW = (batteryPowerW || 0) + mppt.dcPower;
1345
- }
1346
- else if (mppt.stringId === 'StDisCha 4' && mppt.dcPower !== undefined) {
1347
- // Discharging power is negative
1348
- batteryPowerW = (batteryPowerW || 0) - mppt.dcPower;
1349
- }
1350
- });
1351
- return batteryPowerW;
1486
+ return sumMpptBatteryPowerW(mpptDataList);
1352
1487
  }
1353
1488
  /**
1354
1489
  * Determine battery state from MPPT strings
@@ -124,6 +124,7 @@ export interface SunspecInverterData extends SunspecBlock {
124
124
  reactivePower?: number;
125
125
  powerFactor?: number;
126
126
  acEnergy?: number;
127
+ acEnergyScaleFactor?: number;
127
128
  dcCurrent?: number;
128
129
  dcVoltage?: number;
129
130
  dcPower?: number;
@@ -971,9 +971,11 @@ export class SunspecModbusClient {
971
971
  this.logRegisterRead(103, 50, 'Vendor Events 4', data.vendorEvents4, 'bitfield32');
972
972
  const acEnergy = this.extractValue(buffer, 24, 'uint32', 2);
973
973
  this.logRegisterRead(103, 24, 'AC Energy', acEnergy, 'acc32');
974
+ const whSf = this.isUnimplementedValue(scaleFactors.WH_SF, 'int16') ? 0 : scaleFactors.WH_SF;
974
975
  data.acEnergy = !this.isUnimplementedValue(acEnergy, 'acc32')
975
- ? acEnergy * Math.pow(10, scaleFactors.WH_SF)
976
+ ? acEnergy * Math.pow(10, whSf)
976
977
  : undefined;
978
+ data.acEnergyScaleFactor = whSf;
977
979
  console.debug('[Model 103] Inverter Data:', data);
978
980
  return data;
979
981
  }
@@ -1033,9 +1035,11 @@ export class SunspecModbusClient {
1033
1035
  // Read AC Energy (32-bit accumulator) - Offset 24-25
1034
1036
  const acEnergy = this.extractValue(buffer, 24, 'uint32', 2);
1035
1037
  this.logRegisterRead(101, 24, 'AC Energy', acEnergy, 'acc32');
1038
+ const whSf = this.isUnimplementedValue(scaleFactors.WH_SF, 'int16') ? 0 : scaleFactors.WH_SF;
1036
1039
  data.acEnergy = !this.isUnimplementedValue(acEnergy, 'acc32')
1037
- ? acEnergy * Math.pow(10, scaleFactors.WH_SF)
1040
+ ? acEnergy * Math.pow(10, whSf)
1038
1041
  : undefined;
1042
+ data.acEnergyScaleFactor = whSf;
1039
1043
  console.debug('[Model 101] Single Phase Inverter Data:', data);
1040
1044
  return data;
1041
1045
  }
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.95";
8
+ export declare const SDK_VERSION = "0.0.97";
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.95';
8
+ export const SDK_VERSION = '0.0.97';
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.95",
3
+ "version": "0.0.97",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "dependencies": {
43
43
  "@enyo-energy/appliance-calibration": "0.0.2",
44
- "@enyo-energy/energy-app-sdk": "^0.0.172"
44
+ "@enyo-energy/energy-app-sdk": "^0.0.175"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"