@enyo-energy/sunspec-sdk 0.0.94 → 0.0.96

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.
@@ -341,6 +341,7 @@ exports.BaseSunspecDevice = BaseSunspecDevice;
341
341
  */
342
342
  class SunspecInverter extends BaseSunspecDevice {
343
343
  capabilities;
344
+ pvPowerSource;
344
345
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
345
346
  static CONNECTION_FAULT_THRESHOLD = 3;
346
347
  /**
@@ -361,9 +362,23 @@ class SunspecInverter extends BaseSunspecDevice {
361
362
  // state reads healthy), so we force one re-assert of the current status on
362
363
  // the first successful read of each session to converge the core.
363
364
  statusReassertedThisSession = false;
364
- constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
365
+ // Last accepted cumulative AC-energy reading (Wh) and how many consecutive
366
+ // polls have reported a corrupt one (a decrease or a ≥½-register-quantum jump
367
+ // — the acc32 16-bit word-boundary artifact). See sanitizeAcEnergyWh.
368
+ lastGoodAcEnergyWh;
369
+ acEnergyDropStreak = 0;
370
+ /** Consecutive corrupt reads that confirm a genuine reset/resync (vs a transient glitch). */
371
+ static AC_ENERGY_RESET_CONFIRM = 3;
372
+ constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
373
+ // Where pvPowerW is sourced from — see SunspecPvPowerSource. Defaults to
374
+ // Auto (MPPT strings, then Model 101 DCW/AC fallback). Use Mppt to report
375
+ // only summed MPPT strings, or Inverter to use only the inverter total —
376
+ // e.g. for devices whose Model 160 strings are unreliable or whose AC
377
+ // includes non-PV sources (a hybrid's battery discharge).
378
+ pvPowerSource = sunspec_interfaces_js_1.SunspecPvPowerSource.Auto) {
365
379
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
366
380
  this.capabilities = capabilities;
381
+ this.pvPowerSource = pvPowerSource;
367
382
  }
368
383
  async connect() {
369
384
  // Ensure Sunspec client is connected
@@ -481,8 +496,8 @@ class SunspecInverter extends BaseSunspecDevice {
481
496
  // to Connected. No-op unless this device is still marked offline.
482
497
  await this.reassertConnectedIfRecovered();
483
498
  if (inverterData) {
484
- const pvPowerW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
485
- console.debug(`Got PV Power from DC strings: ${pvPowerW}W`);
499
+ const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, inverterData);
500
+ console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
486
501
  const inverterMessage = {
487
502
  id: (0, node_crypto_1.randomUUID)(),
488
503
  message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.InverterValuesUpdateV1,
@@ -499,7 +514,7 @@ class SunspecInverter extends BaseSunspecDevice {
499
514
  voltageL1: inverterData.voltageAN || 0,
500
515
  voltageL2: inverterData.voltageBN ?? undefined,
501
516
  voltageL3: inverterData.voltageCN ?? undefined,
502
- meterValueWh: inverterData.acEnergy,
517
+ meterValueWh: this.sanitizeAcEnergyWh(inverterData.acEnergy, inverterData.acEnergyScaleFactor),
503
518
  strings: dcStrings
504
519
  }
505
520
  };
@@ -525,6 +540,54 @@ class SunspecInverter extends BaseSunspecDevice {
525
540
  }
526
541
  return messages;
527
542
  }
543
+ /**
544
+ * Guard the cumulative AC-energy reading before it is published as
545
+ * `meterValueWh`. The SunSpec `WH` register is an `acc32` (high word + low
546
+ * word) × 10^WH_SF; at a low-word rollover / wake-up the words can be
547
+ * mis-combined, so a poll jumps by exactly one 16-bit word
548
+ * (`65536 × 10^WH_SF`) up or down and back — Dirk Wasow's flip-flop of
549
+ * 6,553,600 Wh. A lifetime accumulator is also monotonic non-decreasing.
550
+ *
551
+ * So a reading is corrupt when it either DECREASES or JUMPS UP by ≥ half a
552
+ * register quantum (real per-poll production is orders of magnitude smaller):
553
+ * we republish the last good value rather than emit it (a raw `max-min`
554
+ * downstream would otherwise inflate it into ~a whole register word). A
555
+ * suspect level that persists for `AC_ENERGY_RESET_CONFIRM` consecutive polls
556
+ * is treated as a genuine reset/resync and adopted.
557
+ *
558
+ * Float models (111/112/113) report `WH` as an IEEE-754 float with no acc32
559
+ * word-boundary artifact; they leave `scaleFactor` undefined. For them there
560
+ * is no register quantum, so we enforce monotonicity only (reject decreases)
561
+ * and accept any increase — the ½-quantum upper bound applies to int+SF
562
+ * models (101/103) alone.
563
+ */
564
+ sanitizeAcEnergyWh(raw, scaleFactor) {
565
+ if (raw == null)
566
+ return undefined;
567
+ if (this.lastGoodAcEnergyWh == null) {
568
+ this.lastGoodAcEnergyWh = raw;
569
+ this.acEnergyDropStreak = 0;
570
+ return raw;
571
+ }
572
+ const halfQuantumWh = scaleFactor != null ? 0.5 * 65536 * Math.pow(10, scaleFactor) : Infinity;
573
+ const delta = raw - this.lastGoodAcEnergyWh;
574
+ const plausible = delta >= 0 && delta < halfQuantumWh;
575
+ if (plausible) {
576
+ this.lastGoodAcEnergyWh = raw;
577
+ this.acEnergyDropStreak = 0;
578
+ return raw;
579
+ }
580
+ // A decrease or a ≥½-quantum jump — the acc32 word-boundary artifact.
581
+ this.acEnergyDropStreak++;
582
+ if (this.acEnergyDropStreak >= SunspecInverter.AC_ENERGY_RESET_CONFIRM) {
583
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: AC energy resync confirmed (${this.lastGoodAcEnergyWh} -> ${raw} Wh), adopting new baseline`);
584
+ this.lastGoodAcEnergyWh = raw;
585
+ this.acEnergyDropStreak = 0;
586
+ return raw;
587
+ }
588
+ 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`);
589
+ return this.lastGoodAcEnergyWh;
590
+ }
528
591
  /**
529
592
  * Decode all active error bits from the inverter event registers into
530
593
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -712,6 +775,34 @@ class SunspecInverter extends BaseSunspecDevice {
712
775
  return null;
713
776
  return limitW;
714
777
  }
778
+ /**
779
+ * Set the grid-operator power production (feed-in) limit on the inverter.
780
+ *
781
+ * Writes Model 123 `WMaxLimPct` + `WMaxLim_Ena` (as a percentage of the
782
+ * Model 121 `WMax` nameplate). Pass `null` to remove the limit and return
783
+ * the inverter to unthrottled production.
784
+ *
785
+ * The SDK exposes this so a consumer that receives a grid-operator
786
+ * production-limit command (from the data bus or elsewhere) can apply it;
787
+ * subscribing to and reacting to that command is the consumer's job.
788
+ *
789
+ * @param limitW - Maximum production power in Watts, or `null` to remove the limit
790
+ * @returns `true` if the write succeeded, `false` otherwise
791
+ */
792
+ async setPowerProductionLimit(limitW) {
793
+ return this.sunspecClient.setFeedInLimit(this.unitId, limitW);
794
+ }
795
+ /**
796
+ * Read the currently active grid-operator power production (feed-in) limit
797
+ * from the inverter, in Watts. Returns `null` when no limit is active, the
798
+ * registers cannot be read, or the configured limit is not actually
799
+ * throttling (limit ≥ `WMax`). See {@link computeActiveProductionLimitW}.
800
+ */
801
+ async getPowerProductionLimit() {
802
+ const settings = await this.sunspecClient.readInverterSettings(this.unitId);
803
+ const controls = await this.sunspecClient.readInverterControls(this.unitId);
804
+ return this.computeActiveProductionLimitW(settings, controls);
805
+ }
715
806
  mapOperatingState(state) {
716
807
  if (!state)
717
808
  return enyo_data_bus_value_js_1.EnyoInverterStateEnum.Off;
@@ -727,6 +818,48 @@ class SunspecInverter extends BaseSunspecDevice {
727
818
  };
728
819
  return stateMap[state] || enyo_data_bus_value_js_1.EnyoInverterStateEnum.Off;
729
820
  }
821
+ /**
822
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
823
+ *
824
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
825
+ * present — most granular, isolates PV — otherwise the inverter total via
826
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
827
+ * consulted when there are no strings, so inverters with working MPPT are
828
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
829
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
830
+ * real production instead of 0 W.
831
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
832
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
833
+ *
834
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
835
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
836
+ * importing from grid) falls through to 0 rather than reporting negative production.
837
+ * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
838
+ * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
839
+ * better than reporting 0.
840
+ */
841
+ selectPvPowerW(dcStrings, inverterData) {
842
+ const stringSumW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
843
+ const useStrings = this.pvPowerSource === sunspec_interfaces_js_1.SunspecPvPowerSource.Mppt ||
844
+ (this.pvPowerSource === sunspec_interfaces_js_1.SunspecPvPowerSource.Auto && dcStrings.length > 0);
845
+ if (useStrings) {
846
+ return { pvPowerW: stringSumW, source: 'DC strings' };
847
+ }
848
+ return this.inverterTotalPvPowerW(inverterData);
849
+ }
850
+ /**
851
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
852
+ * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
853
+ */
854
+ inverterTotalPvPowerW(inverterData) {
855
+ if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
856
+ return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
857
+ }
858
+ if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
859
+ return { pvPowerW: inverterData.acPower, source: 'AC power (Model 101)' };
860
+ }
861
+ return { pvPowerW: 0, source: 'none' };
862
+ }
730
863
  /**
731
864
  * Map MPPT data to DC string structure for data bus
732
865
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -1,4 +1,4 @@
1
- import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, 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, 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";
@@ -127,6 +127,7 @@ export declare abstract class BaseSunspecDevice {
127
127
  */
128
128
  export declare class SunspecInverter extends BaseSunspecDevice {
129
129
  private readonly capabilities;
130
+ private readonly pvPowerSource;
130
131
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
131
132
  private static readonly CONNECTION_FAULT_THRESHOLD;
132
133
  /**
@@ -141,10 +142,36 @@ export declare class SunspecInverter extends BaseSunspecDevice {
141
142
  private errorState;
142
143
  private snapshotService?;
143
144
  private statusReassertedThisSession;
144
- 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);
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;
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);
145
150
  connect(): Promise<void>;
146
151
  disconnect(): Promise<void>;
147
- 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;
148
175
  /**
149
176
  * Decode all active error bits from the inverter event registers into
150
177
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -189,7 +216,58 @@ export declare class SunspecInverter extends BaseSunspecDevice {
189
216
  * returned (not undefined) so the field is cleared on the appliance.
190
217
  */
191
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>;
192
241
  private mapOperatingState;
242
+ /**
243
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
244
+ *
245
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
246
+ * present — most granular, isolates PV — otherwise the inverter total via
247
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
248
+ * consulted when there are no strings, so inverters with working MPPT are
249
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
250
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
251
+ * real production instead of 0 W.
252
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
253
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
254
+ *
255
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
256
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
257
+ * importing from grid) falls through to 0 rather than reporting negative production.
258
+ * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
259
+ * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
260
+ * better than reporting 0.
261
+ */
262
+ protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData): {
263
+ pvPowerW: number;
264
+ source: string;
265
+ };
266
+ /**
267
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
268
+ * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
269
+ */
270
+ private inverterTotalPvPowerW;
193
271
  /**
194
272
  * Map MPPT data to DC string structure for data bus
195
273
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -336,7 +414,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
336
414
  /**
337
415
  * Update battery data and return data bus messages
338
416
  */
339
- readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
417
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
340
418
  /**
341
419
  * Extract battery power from MPPT strings with specific IDs
342
420
  * StCha 3: Battery charging power (positive)
@@ -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.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.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: [
@@ -268,6 +268,20 @@ var SunspecInverterCapability;
268
268
  (function (SunspecInverterCapability) {
269
269
  SunspecInverterCapability["FeedInLimit"] = "feed-in-limit";
270
270
  })(SunspecInverterCapability || (exports.SunspecInverterCapability = SunspecInverterCapability = {}));
271
+ /**
272
+ * Where an inverter's reported PV production (pvPowerW) is sourced from.
273
+ * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
274
+ * total DC power (Model 101 DCW), else AC power (Model 101 W). Default.
275
+ * - Mppt: only summed MPPT DC strings; a stringless inverter reports 0 W.
276
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
277
+ * Use when Model 160 strings are unreliable but the inverter total is trusted.
278
+ */
279
+ var SunspecPvPowerSource;
280
+ (function (SunspecPvPowerSource) {
281
+ SunspecPvPowerSource["Auto"] = "auto";
282
+ SunspecPvPowerSource["Mppt"] = "mppt";
283
+ SunspecPvPowerSource["Inverter"] = "inverter";
284
+ })(SunspecPvPowerSource || (exports.SunspecPvPowerSource = SunspecPvPowerSource = {}));
271
285
  var SunspecBatteryCapability;
272
286
  (function (SunspecBatteryCapability) {
273
287
  SunspecBatteryCapability["GridCharging"] = "grid-charging";
@@ -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;
@@ -651,6 +652,19 @@ export declare enum SunspecStorageMode {
651
652
  export declare enum SunspecInverterCapability {
652
653
  FeedInLimit = "feed-in-limit"
653
654
  }
655
+ /**
656
+ * Where an inverter's reported PV production (pvPowerW) is sourced from.
657
+ * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
658
+ * total DC power (Model 101 DCW), else AC power (Model 101 W). Default.
659
+ * - Mppt: only summed MPPT DC strings; a stringless inverter reports 0 W.
660
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
661
+ * Use when Model 160 strings are unreliable but the inverter total is trusted.
662
+ */
663
+ export declare enum SunspecPvPowerSource {
664
+ Auto = "auto",
665
+ Mppt = "mppt",
666
+ Inverter = "inverter"
667
+ }
654
668
  export declare enum SunspecBatteryCapability {
655
669
  GridCharging = "grid-charging",
656
670
  DischargeLimit = "discharge-limit",
@@ -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.94';
12
+ exports.SDK_VERSION = '0.0.96';
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.94";
8
+ export declare const SDK_VERSION = "0.0.96";
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, 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, 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";
@@ -127,6 +127,7 @@ export declare abstract class BaseSunspecDevice {
127
127
  */
128
128
  export declare class SunspecInverter extends BaseSunspecDevice {
129
129
  private readonly capabilities;
130
+ private readonly pvPowerSource;
130
131
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
131
132
  private static readonly CONNECTION_FAULT_THRESHOLD;
132
133
  /**
@@ -141,10 +142,36 @@ export declare class SunspecInverter extends BaseSunspecDevice {
141
142
  private errorState;
142
143
  private snapshotService?;
143
144
  private statusReassertedThisSession;
144
- 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);
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;
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);
145
150
  connect(): Promise<void>;
146
151
  disconnect(): Promise<void>;
147
- 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;
148
175
  /**
149
176
  * Decode all active error bits from the inverter event registers into
150
177
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -189,7 +216,58 @@ export declare class SunspecInverter extends BaseSunspecDevice {
189
216
  * returned (not undefined) so the field is cleared on the appliance.
190
217
  */
191
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>;
192
241
  private mapOperatingState;
242
+ /**
243
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
244
+ *
245
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
246
+ * present — most granular, isolates PV — otherwise the inverter total via
247
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
248
+ * consulted when there are no strings, so inverters with working MPPT are
249
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
250
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
251
+ * real production instead of 0 W.
252
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
253
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
254
+ *
255
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
256
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
257
+ * importing from grid) falls through to 0 rather than reporting negative production.
258
+ * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
259
+ * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
260
+ * better than reporting 0.
261
+ */
262
+ protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData): {
263
+ pvPowerW: number;
264
+ source: string;
265
+ };
266
+ /**
267
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
268
+ * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
269
+ */
270
+ private inverterTotalPvPowerW;
193
271
  /**
194
272
  * Map MPPT data to DC string structure for data bus
195
273
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -336,7 +414,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
336
414
  /**
337
415
  * Update battery data and return data bus messages
338
416
  */
339
- readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
417
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
340
418
  /**
341
419
  * Extract battery power from MPPT strings with specific IDs
342
420
  * StCha 3: Battery charging power (positive)
@@ -1,4 +1,4 @@
1
- import { SunspecBatteryChargeState, SunspecBatteryFeatureModeKind, SunspecEnableControl, SunspecInverterCapability, SunspecInverterEvent1, SunspecInverterOperatingState, SunspecModelId, SunspecMPPTOperatingState, SunspecStorageMode, SUNSPEC_CONNECTION_LOST_CODE } from "./sunspec-interfaces.js";
1
+ import { SunspecBatteryChargeState, SunspecBatteryFeatureModeKind, SunspecEnableControl, SunspecInverterCapability, SunspecPvPowerSource, 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";
@@ -334,6 +334,7 @@ export class BaseSunspecDevice {
334
334
  */
335
335
  export class SunspecInverter extends BaseSunspecDevice {
336
336
  capabilities;
337
+ pvPowerSource;
337
338
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
338
339
  static CONNECTION_FAULT_THRESHOLD = 3;
339
340
  /**
@@ -354,9 +355,23 @@ export class SunspecInverter extends BaseSunspecDevice {
354
355
  // state reads healthy), so we force one re-assert of the current status on
355
356
  // the first successful read of each session to converge the core.
356
357
  statusReassertedThisSession = false;
357
- constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
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;
365
+ constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
366
+ // Where pvPowerW is sourced from — see SunspecPvPowerSource. Defaults to
367
+ // Auto (MPPT strings, then Model 101 DCW/AC fallback). Use Mppt to report
368
+ // only summed MPPT strings, or Inverter to use only the inverter total —
369
+ // e.g. for devices whose Model 160 strings are unreliable or whose AC
370
+ // includes non-PV sources (a hybrid's battery discharge).
371
+ pvPowerSource = SunspecPvPowerSource.Auto) {
358
372
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
359
373
  this.capabilities = capabilities;
374
+ this.pvPowerSource = pvPowerSource;
360
375
  }
361
376
  async connect() {
362
377
  // Ensure Sunspec client is connected
@@ -474,8 +489,8 @@ export class SunspecInverter extends BaseSunspecDevice {
474
489
  // to Connected. No-op unless this device is still marked offline.
475
490
  await this.reassertConnectedIfRecovered();
476
491
  if (inverterData) {
477
- const pvPowerW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
478
- console.debug(`Got PV Power from DC strings: ${pvPowerW}W`);
492
+ const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, inverterData);
493
+ console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
479
494
  const inverterMessage = {
480
495
  id: randomUUID(),
481
496
  message: EnyoDataBusMessageEnum.InverterValuesUpdateV1,
@@ -492,7 +507,7 @@ export class SunspecInverter extends BaseSunspecDevice {
492
507
  voltageL1: inverterData.voltageAN || 0,
493
508
  voltageL2: inverterData.voltageBN ?? undefined,
494
509
  voltageL3: inverterData.voltageCN ?? undefined,
495
- meterValueWh: inverterData.acEnergy,
510
+ meterValueWh: this.sanitizeAcEnergyWh(inverterData.acEnergy, inverterData.acEnergyScaleFactor),
496
511
  strings: dcStrings
497
512
  }
498
513
  };
@@ -518,6 +533,54 @@ export class SunspecInverter extends BaseSunspecDevice {
518
533
  }
519
534
  return messages;
520
535
  }
536
+ /**
537
+ * Guard the cumulative AC-energy reading before it is published as
538
+ * `meterValueWh`. The SunSpec `WH` register is an `acc32` (high word + low
539
+ * word) × 10^WH_SF; at a low-word rollover / wake-up the words can be
540
+ * mis-combined, so a poll jumps by exactly one 16-bit word
541
+ * (`65536 × 10^WH_SF`) up or down and back — Dirk Wasow's flip-flop of
542
+ * 6,553,600 Wh. A lifetime accumulator is also monotonic non-decreasing.
543
+ *
544
+ * So a reading is corrupt when it either DECREASES or JUMPS UP by ≥ half a
545
+ * register quantum (real per-poll production is orders of magnitude smaller):
546
+ * we republish the last good value rather than emit it (a raw `max-min`
547
+ * downstream would otherwise inflate it into ~a whole register word). A
548
+ * suspect level that persists for `AC_ENERGY_RESET_CONFIRM` consecutive polls
549
+ * is treated as a genuine reset/resync and adopted.
550
+ *
551
+ * Float models (111/112/113) report `WH` as an IEEE-754 float with no acc32
552
+ * word-boundary artifact; they leave `scaleFactor` undefined. For them there
553
+ * is no register quantum, so we enforce monotonicity only (reject decreases)
554
+ * and accept any increase — the ½-quantum upper bound applies to int+SF
555
+ * models (101/103) alone.
556
+ */
557
+ sanitizeAcEnergyWh(raw, scaleFactor) {
558
+ if (raw == null)
559
+ return undefined;
560
+ if (this.lastGoodAcEnergyWh == null) {
561
+ this.lastGoodAcEnergyWh = raw;
562
+ this.acEnergyDropStreak = 0;
563
+ return raw;
564
+ }
565
+ const halfQuantumWh = scaleFactor != null ? 0.5 * 65536 * Math.pow(10, scaleFactor) : Infinity;
566
+ const delta = raw - this.lastGoodAcEnergyWh;
567
+ const plausible = delta >= 0 && delta < halfQuantumWh;
568
+ if (plausible) {
569
+ this.lastGoodAcEnergyWh = raw;
570
+ this.acEnergyDropStreak = 0;
571
+ return raw;
572
+ }
573
+ // A decrease or a ≥½-quantum jump — the acc32 word-boundary artifact.
574
+ this.acEnergyDropStreak++;
575
+ if (this.acEnergyDropStreak >= SunspecInverter.AC_ENERGY_RESET_CONFIRM) {
576
+ console.warn(`Notify_Devs: ${this.constructor.name} ${this.applianceId}: AC energy resync confirmed (${this.lastGoodAcEnergyWh} -> ${raw} Wh), adopting new baseline`);
577
+ this.lastGoodAcEnergyWh = raw;
578
+ this.acEnergyDropStreak = 0;
579
+ return raw;
580
+ }
581
+ 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`);
582
+ return this.lastGoodAcEnergyWh;
583
+ }
521
584
  /**
522
585
  * Decode all active error bits from the inverter event registers into
523
586
  * `EnyoApplianceErrorCode`s. Override in a subclass to customize the
@@ -705,6 +768,34 @@ export class SunspecInverter extends BaseSunspecDevice {
705
768
  return null;
706
769
  return limitW;
707
770
  }
771
+ /**
772
+ * Set the grid-operator power production (feed-in) limit on the inverter.
773
+ *
774
+ * Writes Model 123 `WMaxLimPct` + `WMaxLim_Ena` (as a percentage of the
775
+ * Model 121 `WMax` nameplate). Pass `null` to remove the limit and return
776
+ * the inverter to unthrottled production.
777
+ *
778
+ * The SDK exposes this so a consumer that receives a grid-operator
779
+ * production-limit command (from the data bus or elsewhere) can apply it;
780
+ * subscribing to and reacting to that command is the consumer's job.
781
+ *
782
+ * @param limitW - Maximum production power in Watts, or `null` to remove the limit
783
+ * @returns `true` if the write succeeded, `false` otherwise
784
+ */
785
+ async setPowerProductionLimit(limitW) {
786
+ return this.sunspecClient.setFeedInLimit(this.unitId, limitW);
787
+ }
788
+ /**
789
+ * Read the currently active grid-operator power production (feed-in) limit
790
+ * from the inverter, in Watts. Returns `null` when no limit is active, the
791
+ * registers cannot be read, or the configured limit is not actually
792
+ * throttling (limit ≥ `WMax`). See {@link computeActiveProductionLimitW}.
793
+ */
794
+ async getPowerProductionLimit() {
795
+ const settings = await this.sunspecClient.readInverterSettings(this.unitId);
796
+ const controls = await this.sunspecClient.readInverterControls(this.unitId);
797
+ return this.computeActiveProductionLimitW(settings, controls);
798
+ }
708
799
  mapOperatingState(state) {
709
800
  if (!state)
710
801
  return EnyoInverterStateEnum.Off;
@@ -720,6 +811,48 @@ export class SunspecInverter extends BaseSunspecDevice {
720
811
  };
721
812
  return stateMap[state] || EnyoInverterStateEnum.Off;
722
813
  }
814
+ /**
815
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
816
+ *
817
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
818
+ * present — most granular, isolates PV — otherwise the inverter total via
819
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
820
+ * consulted when there are no strings, so inverters with working MPPT are
821
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
822
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
823
+ * real production instead of 0 W.
824
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
825
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
826
+ *
827
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
828
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
829
+ * importing from grid) falls through to 0 rather than reporting negative production.
830
+ * Edge case: in Auto/Inverter a hybrid discharging its battery while its MPPT is
831
+ * unreadable reports AC (incl. battery) rather than 0 — acceptable, and strictly
832
+ * better than reporting 0.
833
+ */
834
+ selectPvPowerW(dcStrings, inverterData) {
835
+ const stringSumW = dcStrings.reduce((sum, s) => sum + (s.powerW || 0), 0);
836
+ const useStrings = this.pvPowerSource === SunspecPvPowerSource.Mppt ||
837
+ (this.pvPowerSource === SunspecPvPowerSource.Auto && dcStrings.length > 0);
838
+ if (useStrings) {
839
+ return { pvPowerW: stringSumW, source: 'DC strings' };
840
+ }
841
+ return this.inverterTotalPvPowerW(inverterData);
842
+ }
843
+ /**
844
+ * Inverter total PV power from Model 101: DCW when strictly positive, else AC when
845
+ * strictly positive, else 0. See {@link selectPvPowerW} for why positivity matters.
846
+ */
847
+ inverterTotalPvPowerW(inverterData) {
848
+ if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
849
+ return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
850
+ }
851
+ if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
852
+ return { pvPowerW: inverterData.acPower, source: 'AC power (Model 101)' };
853
+ }
854
+ return { pvPowerW: 0, source: 'none' };
855
+ }
723
856
  /**
724
857
  * Map MPPT data to DC string structure for data bus
725
858
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -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;
@@ -651,6 +652,19 @@ export declare enum SunspecStorageMode {
651
652
  export declare enum SunspecInverterCapability {
652
653
  FeedInLimit = "feed-in-limit"
653
654
  }
655
+ /**
656
+ * Where an inverter's reported PV production (pvPowerW) is sourced from.
657
+ * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
658
+ * total DC power (Model 101 DCW), else AC power (Model 101 W). Default.
659
+ * - Mppt: only summed MPPT DC strings; a stringless inverter reports 0 W.
660
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
661
+ * Use when Model 160 strings are unreliable but the inverter total is trusted.
662
+ */
663
+ export declare enum SunspecPvPowerSource {
664
+ Auto = "auto",
665
+ Mppt = "mppt",
666
+ Inverter = "inverter"
667
+ }
654
668
  export declare enum SunspecBatteryCapability {
655
669
  GridCharging = "grid-charging",
656
670
  DischargeLimit = "discharge-limit",
@@ -265,6 +265,20 @@ export var SunspecInverterCapability;
265
265
  (function (SunspecInverterCapability) {
266
266
  SunspecInverterCapability["FeedInLimit"] = "feed-in-limit";
267
267
  })(SunspecInverterCapability || (SunspecInverterCapability = {}));
268
+ /**
269
+ * Where an inverter's reported PV production (pvPowerW) is sourced from.
270
+ * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
271
+ * total DC power (Model 101 DCW), else AC power (Model 101 W). Default.
272
+ * - Mppt: only summed MPPT DC strings; a stringless inverter reports 0 W.
273
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
274
+ * Use when Model 160 strings are unreliable but the inverter total is trusted.
275
+ */
276
+ export var SunspecPvPowerSource;
277
+ (function (SunspecPvPowerSource) {
278
+ SunspecPvPowerSource["Auto"] = "auto";
279
+ SunspecPvPowerSource["Mppt"] = "mppt";
280
+ SunspecPvPowerSource["Inverter"] = "inverter";
281
+ })(SunspecPvPowerSource || (SunspecPvPowerSource = {}));
268
282
  export var SunspecBatteryCapability;
269
283
  (function (SunspecBatteryCapability) {
270
284
  SunspecBatteryCapability["GridCharging"] = "grid-charging";
@@ -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.94";
8
+ export declare const SDK_VERSION = "0.0.96";
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.94';
8
+ export const SDK_VERSION = '0.0.96';
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.94",
3
+ "version": "0.0.96",
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"