@enyo-energy/sunspec-sdk 0.0.93 → 0.0.95

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,16 @@ 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
+ 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 = sunspec_interfaces_js_1.SunspecPvPowerSource.Auto) {
365
372
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
366
373
  this.capabilities = capabilities;
374
+ this.pvPowerSource = pvPowerSource;
367
375
  }
368
376
  async connect() {
369
377
  // Ensure Sunspec client is connected
@@ -481,8 +489,8 @@ class SunspecInverter extends BaseSunspecDevice {
481
489
  // to Connected. No-op unless this device is still marked offline.
482
490
  await this.reassertConnectedIfRecovered();
483
491
  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`);
492
+ const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, inverterData);
493
+ console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
486
494
  const inverterMessage = {
487
495
  id: (0, node_crypto_1.randomUUID)(),
488
496
  message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.InverterValuesUpdateV1,
@@ -727,6 +735,48 @@ class SunspecInverter extends BaseSunspecDevice {
727
735
  };
728
736
  return stateMap[state] || enyo_data_bus_value_js_1.EnyoInverterStateEnum.Off;
729
737
  }
738
+ /**
739
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
740
+ *
741
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
742
+ * present — most granular, isolates PV — otherwise the inverter total via
743
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
744
+ * consulted when there are no strings, so inverters with working MPPT are
745
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
746
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
747
+ * real production instead of 0 W.
748
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
749
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
750
+ *
751
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
752
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
753
+ * 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.
757
+ */
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' };
764
+ }
765
+ return this.inverterTotalPvPowerW(inverterData);
766
+ }
767
+ /**
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.
770
+ */
771
+ inverterTotalPvPowerW(inverterData) {
772
+ if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
773
+ return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
774
+ }
775
+ if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
776
+ return { pvPowerW: inverterData.acPower, source: 'AC power (Model 101)' };
777
+ }
778
+ return { pvPowerW: 0, source: 'none' };
779
+ }
730
780
  /**
731
781
  * Map MPPT data to DC string structure for data bus
732
782
  * 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,7 +142,7 @@ 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
+ 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
146
  connect(): Promise<void>;
146
147
  disconnect(): Promise<void>;
147
148
  readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
@@ -190,6 +191,35 @@ export declare class SunspecInverter extends BaseSunspecDevice {
190
191
  */
191
192
  private computeActiveProductionLimitW;
192
193
  private mapOperatingState;
194
+ /**
195
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
196
+ *
197
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
198
+ * present — most granular, isolates PV — otherwise the inverter total via
199
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
200
+ * consulted when there are no strings, so inverters with working MPPT are
201
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
202
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
203
+ * real production instead of 0 W.
204
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
205
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
206
+ *
207
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
208
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
209
+ * 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.
213
+ */
214
+ protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData): {
215
+ pvPowerW: number;
216
+ source: string;
217
+ };
218
+ /**
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.
221
+ */
222
+ private inverterTotalPvPowerW;
193
223
  /**
194
224
  * Map MPPT data to DC string structure for data bus
195
225
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -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";
@@ -16,6 +16,26 @@ export interface IRetryConfig {
16
16
  phases: IRetryPhase[];
17
17
  }
18
18
  export declare const DEFAULT_RETRY_CONFIG: IRetryConfig;
19
+ /**
20
+ * Pacing configuration for the Modbus client. Both options are opt-in and default off, so existing
21
+ * consumers are unaffected. The fields mirror the SDK's `ModbusOptions` and are passed straight
22
+ * through to `useModbus().connect()` — the SDK owns the serialization; the client only forwards the
23
+ * config it was constructed with. Omitted fields leave the SDK to apply its own defaults
24
+ * (`noParallelRequests` false, `waitBetweenMessagesMs` 0). Intended for slow devices (e.g. Solax)
25
+ * that choke when frames arrive back-to-back.
26
+ */
27
+ export interface IModbusPacingConfig {
28
+ /**
29
+ * Serialize reads and writes on the connection through the SDK's internal operation chain so
30
+ * frames don't interleave (SDK `ModbusOptions.noParallelRequests`). Default false.
31
+ */
32
+ noParallelRequests?: boolean;
33
+ /**
34
+ * Minimum ms to wait between two consecutive frames. Only honoured when `noParallelRequests` is
35
+ * true (SDK `ModbusOptions.waitBetweenMessagesMs`). Default 0.
36
+ */
37
+ waitBetweenMessagesMs?: number;
38
+ }
19
39
  /**
20
40
  * Base interface for all SunSpec blocks
21
41
  */
@@ -631,6 +651,19 @@ export declare enum SunspecStorageMode {
631
651
  export declare enum SunspecInverterCapability {
632
652
  FeedInLimit = "feed-in-limit"
633
653
  }
654
+ /**
655
+ * Where an inverter's reported PV production (pvPowerW) is sourced from.
656
+ * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
657
+ * total DC power (Model 101 DCW), else AC power (Model 101 W). Default.
658
+ * - Mppt: only summed MPPT DC strings; a stringless inverter reports 0 W.
659
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
660
+ * Use when Model 160 strings are unreliable but the inverter total is trusted.
661
+ */
662
+ export declare enum SunspecPvPowerSource {
663
+ Auto = "auto",
664
+ Mppt = "mppt",
665
+ Inverter = "inverter"
666
+ }
634
667
  export declare enum SunspecBatteryCapability {
635
668
  GridCharging = "grid-charging",
636
669
  DischargeLimit = "discharge-limit",
@@ -34,12 +34,16 @@ const registryKey = (host, port) => `${host}:${port}`;
34
34
  /**
35
35
  * Get (or create) the singleton SunspecModbusClient for this network device.
36
36
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
37
+ *
38
+ * NOTE: `pacing` is only applied when the client is FIRST created for a given host:port.
39
+ * Because the client is cached and refcounted, a later caller passing a different `pacing`
40
+ * receives the already-created instance and its config is ignored.
37
41
  */
38
- function getOrCreateSunspecClient(energyApp, host, port = 502) {
42
+ function getOrCreateSunspecClient(energyApp, host, port = 502, pacing) {
39
43
  const key = registryKey(host, port);
40
44
  let entry = CLIENT_REGISTRY.get(key);
41
45
  if (!entry) {
42
- entry = { client: new SunspecModbusClient(energyApp), refcount: 0 };
46
+ entry = { client: new SunspecModbusClient(energyApp, pacing), refcount: 0 };
43
47
  CLIENT_REGISTRY.set(key, entry);
44
48
  }
45
49
  entry.refcount++;
@@ -79,6 +83,7 @@ async function releaseSunspecClient(host, port = 502) {
79
83
  }
80
84
  class SunspecModbusClient {
81
85
  energyApp;
86
+ pacing;
82
87
  // Per-unit Modbus instance/reader/discovered-models maps. One client = one network device,
83
88
  // many unit IDs share that client (each unit ID is one EnergyAppModbusInstance underneath).
84
89
  modbusInstances = new Map();
@@ -111,8 +116,13 @@ class SunspecModbusClient {
111
116
  // operationChain (the connection lock) to avoid re-entrancy: a transaction never waits
112
117
  // on a connect/disconnect, and vice versa.
113
118
  txChains = new Map();
114
- constructor(energyApp) {
119
+ constructor(energyApp,
120
+ // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
121
+ // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
122
+ // connection. An empty object leaves both undefined so the SDK applies its own defaults.
123
+ pacing = {}) {
115
124
  this.energyApp = energyApp;
125
+ this.pacing = pacing;
116
126
  this.connectionHealth = new EnergyAppModbusConnectionHealth_js_1.EnergyAppModbusConnectionHealth();
117
127
  this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter_js_1.EnergyAppModbusDataTypeConverter();
118
128
  }
@@ -318,7 +328,9 @@ class SunspecModbusClient {
318
328
  cert: this.connectionParams?.cert,
319
329
  key: this.connectionParams?.key,
320
330
  ca: this.connectionParams?.ca,
321
- rejectUnauthorized: this.connectionParams?.rejectUnauthorized
331
+ rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
332
+ noParallelRequests: this.pacing.noParallelRequests,
333
+ waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
322
334
  });
323
335
  if (!candidate) {
324
336
  throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
@@ -16,15 +16,19 @@
16
16
  * - pad: 0x8000 (always returns this value)
17
17
  * - string: all registers 0x0000 (NULL)
18
18
  */
19
- import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode } from "./sunspec-interfaces.cjs";
19
+ import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig } from "./sunspec-interfaces.cjs";
20
20
  import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
21
21
  import { EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
22
22
  import { EnergyApp } from "@enyo-energy/energy-app-sdk";
23
23
  /**
24
24
  * Get (or create) the singleton SunspecModbusClient for this network device.
25
25
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
26
+ *
27
+ * NOTE: `pacing` is only applied when the client is FIRST created for a given host:port.
28
+ * Because the client is cached and refcounted, a later caller passing a different `pacing`
29
+ * receives the already-created instance and its config is ignored.
26
30
  */
27
- export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number): SunspecModbusClient;
31
+ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig): SunspecModbusClient;
28
32
  /**
29
33
  * Release a refcount on the network-device client. When the last consumer releases,
30
34
  * the client is fully disconnected (all units closed) and removed from the registry.
@@ -35,6 +39,7 @@ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: str
35
39
  export declare function releaseSunspecClient(host: string, port?: number): Promise<void>;
36
40
  export declare class SunspecModbusClient {
37
41
  private energyApp;
42
+ private pacing;
38
43
  private modbusInstances;
39
44
  private faultTolerantReaders;
40
45
  private discoveredModelsByUnit;
@@ -48,7 +53,7 @@ export declare class SunspecModbusClient {
48
53
  private closeCount;
49
54
  private operationChain;
50
55
  private txChains;
51
- constructor(energyApp: EnergyApp);
56
+ constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig);
52
57
  /**
53
58
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
54
59
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -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.93';
12
+ exports.SDK_VERSION = '0.0.95';
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.93";
8
+ export declare const SDK_VERSION = "0.0.95";
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,7 +142,7 @@ 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
+ 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
146
  connect(): Promise<void>;
146
147
  disconnect(): Promise<void>;
147
148
  readData(clockId: string, resolution: '10s' | '30s' | '1m' | '15m'): Promise<EnyoDataBusMessage[]>;
@@ -190,6 +191,35 @@ export declare class SunspecInverter extends BaseSunspecDevice {
190
191
  */
191
192
  private computeActiveProductionLimitW;
192
193
  private mapOperatingState;
194
+ /**
195
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
196
+ *
197
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
198
+ * present — most granular, isolates PV — otherwise the inverter total via
199
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
200
+ * consulted when there are no strings, so inverters with working MPPT are
201
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
202
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
203
+ * real production instead of 0 W.
204
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
205
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
206
+ *
207
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
208
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
209
+ * 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.
213
+ */
214
+ protected selectPvPowerW(dcStrings: EnyoDataBusInverterValuesV1String[], inverterData: SunspecInverterData): {
215
+ pvPowerW: number;
216
+ source: string;
217
+ };
218
+ /**
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.
221
+ */
222
+ private inverterTotalPvPowerW;
193
223
  /**
194
224
  * Map MPPT data to DC string structure for data bus
195
225
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -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,16 @@ 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
+ constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
359
+ // Where pvPowerW is sourced from — see SunspecPvPowerSource. Defaults to
360
+ // Auto (MPPT strings, then Model 101 DCW/AC fallback). Use Mppt to report
361
+ // only summed MPPT strings, or Inverter to use only the inverter total —
362
+ // e.g. for devices whose Model 160 strings are unreliable or whose AC
363
+ // includes non-PV sources (a hybrid's battery discharge).
364
+ pvPowerSource = SunspecPvPowerSource.Auto) {
358
365
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
359
366
  this.capabilities = capabilities;
367
+ this.pvPowerSource = pvPowerSource;
360
368
  }
361
369
  async connect() {
362
370
  // Ensure Sunspec client is connected
@@ -474,8 +482,8 @@ export class SunspecInverter extends BaseSunspecDevice {
474
482
  // to Connected. No-op unless this device is still marked offline.
475
483
  await this.reassertConnectedIfRecovered();
476
484
  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`);
485
+ const { pvPowerW, source: pvPowerSource } = this.selectPvPowerW(dcStrings, inverterData);
486
+ console.debug(`Got PV Power from ${pvPowerSource}: ${pvPowerW}W`);
479
487
  const inverterMessage = {
480
488
  id: randomUUID(),
481
489
  message: EnyoDataBusMessageEnum.InverterValuesUpdateV1,
@@ -720,6 +728,48 @@ export class SunspecInverter extends BaseSunspecDevice {
720
728
  };
721
729
  return stateMap[state] || EnyoInverterStateEnum.Off;
722
730
  }
731
+ /**
732
+ * PV production in Watt, sourced according to the configured `pvPowerSource`:
733
+ *
734
+ * - Auto (default): summed per-string MPPT DC power (Model 160) when strings are
735
+ * present — most granular, isolates PV — otherwise the inverter total via
736
+ * {@link inverterTotalPvPowerW} (Model 101 DCW, then AC). The fallback is only
737
+ * consulted when there are no strings, so inverters with working MPPT are
738
+ * unaffected. It lets a producing inverter that exposes no DC telemetry (e.g. an
739
+ * SMA Sunny Boy with Model 160 unreadable and DCW NOT_IMPLEMENTED) still report
740
+ * real production instead of 0 W.
741
+ * - Mppt: only the summed MPPT strings; a stringless inverter reports 0 W.
742
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
743
+ *
744
+ * Both inverter-total steps require a strictly positive value, so NOT_IMPLEMENTED
745
+ * DCW (decodes to 0) falls through to AC, and a negative AC reading (e.g. a hybrid
746
+ * 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.
750
+ */
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' };
757
+ }
758
+ return this.inverterTotalPvPowerW(inverterData);
759
+ }
760
+ /**
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.
763
+ */
764
+ inverterTotalPvPowerW(inverterData) {
765
+ if (typeof inverterData.dcPower === 'number' && inverterData.dcPower > 0) {
766
+ return { pvPowerW: inverterData.dcPower, source: 'DC power (Model 101)' };
767
+ }
768
+ if (typeof inverterData.acPower === 'number' && inverterData.acPower > 0) {
769
+ return { pvPowerW: inverterData.acPower, source: 'AC power (Model 101)' };
770
+ }
771
+ return { pvPowerW: 0, source: 'none' };
772
+ }
723
773
  /**
724
774
  * Map MPPT data to DC string structure for data bus
725
775
  * Filters out battery-related strings (StCha 3, StDisCha 4)
@@ -16,6 +16,26 @@ export interface IRetryConfig {
16
16
  phases: IRetryPhase[];
17
17
  }
18
18
  export declare const DEFAULT_RETRY_CONFIG: IRetryConfig;
19
+ /**
20
+ * Pacing configuration for the Modbus client. Both options are opt-in and default off, so existing
21
+ * consumers are unaffected. The fields mirror the SDK's `ModbusOptions` and are passed straight
22
+ * through to `useModbus().connect()` — the SDK owns the serialization; the client only forwards the
23
+ * config it was constructed with. Omitted fields leave the SDK to apply its own defaults
24
+ * (`noParallelRequests` false, `waitBetweenMessagesMs` 0). Intended for slow devices (e.g. Solax)
25
+ * that choke when frames arrive back-to-back.
26
+ */
27
+ export interface IModbusPacingConfig {
28
+ /**
29
+ * Serialize reads and writes on the connection through the SDK's internal operation chain so
30
+ * frames don't interleave (SDK `ModbusOptions.noParallelRequests`). Default false.
31
+ */
32
+ noParallelRequests?: boolean;
33
+ /**
34
+ * Minimum ms to wait between two consecutive frames. Only honoured when `noParallelRequests` is
35
+ * true (SDK `ModbusOptions.waitBetweenMessagesMs`). Default 0.
36
+ */
37
+ waitBetweenMessagesMs?: number;
38
+ }
19
39
  /**
20
40
  * Base interface for all SunSpec blocks
21
41
  */
@@ -631,6 +651,19 @@ export declare enum SunspecStorageMode {
631
651
  export declare enum SunspecInverterCapability {
632
652
  FeedInLimit = "feed-in-limit"
633
653
  }
654
+ /**
655
+ * Where an inverter's reported PV production (pvPowerW) is sourced from.
656
+ * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
657
+ * total DC power (Model 101 DCW), else AC power (Model 101 W). Default.
658
+ * - Mppt: only summed MPPT DC strings; a stringless inverter reports 0 W.
659
+ * - Inverter: only the inverter total (DCW, then AC); MPPT strings are ignored.
660
+ * Use when Model 160 strings are unreliable but the inverter total is trusted.
661
+ */
662
+ export declare enum SunspecPvPowerSource {
663
+ Auto = "auto",
664
+ Mppt = "mppt",
665
+ Inverter = "inverter"
666
+ }
634
667
  export declare enum SunspecBatteryCapability {
635
668
  GridCharging = "grid-charging",
636
669
  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";
@@ -16,15 +16,19 @@
16
16
  * - pad: 0x8000 (always returns this value)
17
17
  * - string: all registers 0x0000 (NULL)
18
18
  */
19
- import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode } from "./sunspec-interfaces.js";
19
+ import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig } from "./sunspec-interfaces.js";
20
20
  import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
21
21
  import { EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
22
22
  import { EnergyApp } from "@enyo-energy/energy-app-sdk";
23
23
  /**
24
24
  * Get (or create) the singleton SunspecModbusClient for this network device.
25
25
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
26
+ *
27
+ * NOTE: `pacing` is only applied when the client is FIRST created for a given host:port.
28
+ * Because the client is cached and refcounted, a later caller passing a different `pacing`
29
+ * receives the already-created instance and its config is ignored.
26
30
  */
27
- export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number): SunspecModbusClient;
31
+ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig): SunspecModbusClient;
28
32
  /**
29
33
  * Release a refcount on the network-device client. When the last consumer releases,
30
34
  * the client is fully disconnected (all units closed) and removed from the registry.
@@ -35,6 +39,7 @@ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: str
35
39
  export declare function releaseSunspecClient(host: string, port?: number): Promise<void>;
36
40
  export declare class SunspecModbusClient {
37
41
  private energyApp;
42
+ private pacing;
38
43
  private modbusInstances;
39
44
  private faultTolerantReaders;
40
45
  private discoveredModelsByUnit;
@@ -48,7 +53,7 @@ export declare class SunspecModbusClient {
48
53
  private closeCount;
49
54
  private operationChain;
50
55
  private txChains;
51
- constructor(energyApp: EnergyApp);
56
+ constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig);
52
57
  /**
53
58
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
54
59
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -29,12 +29,16 @@ const registryKey = (host, port) => `${host}:${port}`;
29
29
  /**
30
30
  * Get (or create) the singleton SunspecModbusClient for this network device.
31
31
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
32
+ *
33
+ * NOTE: `pacing` is only applied when the client is FIRST created for a given host:port.
34
+ * Because the client is cached and refcounted, a later caller passing a different `pacing`
35
+ * receives the already-created instance and its config is ignored.
32
36
  */
33
- export function getOrCreateSunspecClient(energyApp, host, port = 502) {
37
+ export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing) {
34
38
  const key = registryKey(host, port);
35
39
  let entry = CLIENT_REGISTRY.get(key);
36
40
  if (!entry) {
37
- entry = { client: new SunspecModbusClient(energyApp), refcount: 0 };
41
+ entry = { client: new SunspecModbusClient(energyApp, pacing), refcount: 0 };
38
42
  CLIENT_REGISTRY.set(key, entry);
39
43
  }
40
44
  entry.refcount++;
@@ -74,6 +78,7 @@ export async function releaseSunspecClient(host, port = 502) {
74
78
  }
75
79
  export class SunspecModbusClient {
76
80
  energyApp;
81
+ pacing;
77
82
  // Per-unit Modbus instance/reader/discovered-models maps. One client = one network device,
78
83
  // many unit IDs share that client (each unit ID is one EnergyAppModbusInstance underneath).
79
84
  modbusInstances = new Map();
@@ -106,8 +111,13 @@ export class SunspecModbusClient {
106
111
  // operationChain (the connection lock) to avoid re-entrancy: a transaction never waits
107
112
  // on a connect/disconnect, and vice versa.
108
113
  txChains = new Map();
109
- constructor(energyApp) {
114
+ constructor(energyApp,
115
+ // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
116
+ // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
117
+ // connection. An empty object leaves both undefined so the SDK applies its own defaults.
118
+ pacing = {}) {
110
119
  this.energyApp = energyApp;
120
+ this.pacing = pacing;
111
121
  this.connectionHealth = new EnergyAppModbusConnectionHealth();
112
122
  this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter();
113
123
  }
@@ -313,7 +323,9 @@ export class SunspecModbusClient {
313
323
  cert: this.connectionParams?.cert,
314
324
  key: this.connectionParams?.key,
315
325
  ca: this.connectionParams?.ca,
316
- rejectUnauthorized: this.connectionParams?.rejectUnauthorized
326
+ rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
327
+ noParallelRequests: this.pacing.noParallelRequests,
328
+ waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
317
329
  });
318
330
  if (!candidate) {
319
331
  throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
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.93";
8
+ export declare const SDK_VERSION = "0.0.95";
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.93';
8
+ export const SDK_VERSION = '0.0.95';
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.93",
3
+ "version": "0.0.95",
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.170"
44
+ "@enyo-energy/energy-app-sdk": "^0.0.172"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"