@enyo-energy/sunspec-sdk 0.0.104 → 1.0.0

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.
@@ -231,7 +231,14 @@ export class BaseSunspecDevice {
231
231
  `opened the socket but revalidation failed — retrying with backoff`);
232
232
  return false;
233
233
  }
234
- this.retryManager.reset();
234
+ // NOT reset() here — a reopened TCP socket is not yet a working device. On a peer
235
+ // that accepts connections but stops answering reads, resetting on the reconnect
236
+ // restarts the backoff schedule from its shortest phase on every cycle, so the
237
+ // schedule never advances past 10s no matter how long the outage runs: reconnect,
238
+ // read, time out, poison, mark offline, reconnect — indefinitely, at poll rate. The
239
+ // schedule is cleared instead by the first genuinely healthy read cycle (see
240
+ // markOfflineIfUnhealthy), which is the only evidence the link actually carries
241
+ // data. Until then `elapsed` keeps growing and the phases widen as intended.
235
242
  this.consecutiveReconnectFailures = 0;
236
243
  // Update appliance state to Connected
237
244
  if (this.applianceId) {
@@ -247,7 +254,15 @@ export class BaseSunspecDevice {
247
254
  await this.onConnectionFailure(this.consecutiveReconnectFailures);
248
255
  }
249
256
  catch (error) {
250
- console.error(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} failed: ${error}`);
257
+ // Transition-only: the first throw of an outage is the news; every repeat while the
258
+ // peer stays down is the same news again, so it drops to debug.
259
+ const line = `${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} failed: ${error}`;
260
+ if (this.consecutiveReconnectFailures === 0) {
261
+ console.error(line);
262
+ }
263
+ else {
264
+ console.debug(line);
265
+ }
251
266
  this.consecutiveReconnectFailures += 1;
252
267
  await this.onConnectionFailure(this.consecutiveReconnectFailures);
253
268
  }
@@ -315,6 +330,12 @@ export class BaseSunspecDevice {
315
330
  */
316
331
  async markOfflineIfUnhealthy() {
317
332
  if (this.sunspecClient.isHealthy(this.unitId)) {
333
+ // A completed read cycle on a healthy unit is the only proof the link carries data, so
334
+ // it — not a successful reconnect — is what clears the tiered retry schedule. See the
335
+ // note in tryReconnect(): resetting on reconnect alone pins a flapping device to the
336
+ // shortest retry phase forever.
337
+ this.retryManager.reset();
338
+ this.consecutiveReconnectFailures = 0;
318
339
  return false;
319
340
  }
320
341
  console.warn(`${this.constructor.name} ${this.applianceId}: connection unhealthy after read cycle ` +
@@ -473,6 +494,7 @@ function finiteOrUndefined(value) {
473
494
  export class SunspecInverter extends BaseSunspecDevice {
474
495
  capabilities;
475
496
  pvPowerSource;
497
+ metadataConfig;
476
498
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
477
499
  static CONNECTION_FAULT_THRESHOLD = 3;
478
500
  /**
@@ -519,10 +541,29 @@ export class SunspecInverter extends BaseSunspecDevice {
519
541
  // only summed MPPT strings, or Inverter to use only the inverter total —
520
542
  // e.g. for devices whose Model 160 strings are unreliable or whose AC
521
543
  // includes non-PV sources (a hybrid's battery discharge).
522
- pvPowerSource = SunspecPvPowerSource.Auto) {
544
+ pvPowerSource = SunspecPvPowerSource.Auto,
545
+ // Facts about the installation that no register carries (control policy, module peak power).
546
+ // Forwarded onto `appliance.inverter` on connect; see SunspecInverterMetadataConfig.
547
+ metadataConfig = {}) {
523
548
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
524
549
  this.capabilities = capabilities;
525
550
  this.pvPowerSource = pvPowerSource;
551
+ this.metadataConfig = metadataConfig;
552
+ }
553
+ /**
554
+ * The consumer-supplied inverter facts, as a spreadable object that only contains the keys that
555
+ * were actually configured. Spreading `{ controlAllowed: undefined }` over an existing appliance
556
+ * would erase a value the host set elsewhere; omitting the key leaves it alone.
557
+ */
558
+ configuredInverterMetadata() {
559
+ const configured = {};
560
+ if (this.metadataConfig.controlAllowed !== undefined) {
561
+ configured.controlAllowed = this.metadataConfig.controlAllowed;
562
+ }
563
+ if (this.metadataConfig.installedPeakPowerWp !== undefined) {
564
+ configured.installedPeakPowerWp = this.metadataConfig.installedPeakPowerWp;
565
+ }
566
+ return configured;
526
567
  }
527
568
  async connect() {
528
569
  // Ensure Sunspec client is connected
@@ -556,7 +597,8 @@ export class SunspecInverter extends BaseSunspecDevice {
556
597
  inverter: {
557
598
  dcStrings: this.mapDcStringToApplianceMetadata(this.mapMPPTToStrings(mpptDataList)),
558
599
  maxPvProductionW: inverterSettings?.WMax,
559
- activeProductionLimitationW: activeProductionLimitationW
600
+ activeProductionLimitationW: activeProductionLimitationW,
601
+ ...this.configuredInverterMetadata()
560
602
  }
561
603
  });
562
604
  console.log(`Sunspec Inverter connected: ${this.networkDevice.hostname} (${this.applianceId})`);
@@ -583,7 +625,8 @@ export class SunspecInverter extends BaseSunspecDevice {
583
625
  ...existingAppliance?.inverter,
584
626
  dcStrings: this.mapDcStringToApplianceMetadata(this.mapMPPTToStrings(mpptDataList)),
585
627
  maxPvProductionW: inverterSettings?.WMax,
586
- activeProductionLimitationW: activeProductionLimitationW
628
+ activeProductionLimitationW: activeProductionLimitationW,
629
+ ...this.configuredInverterMetadata()
587
630
  }
588
631
  });
589
632
  console.log(`Sunspec Inverter connected: ${this.networkDevice.hostname} (${this.applianceId})`);
@@ -1425,6 +1468,37 @@ export function filterFeaturesByCalibrationResult(detected, result, controllable
1425
1468
  /**
1426
1469
  * Sunspec Battery implementation
1427
1470
  */
1471
+ /**
1472
+ * Derive the storage mode from Model 124's StorCtl_Mod bitfield.
1473
+ *
1474
+ * The bits mark *which rate setpoint the device is enforcing* — bit 0 for
1475
+ * InWRte, bit 1 for OutWRte — not which direction is permitted. So no bit set
1476
+ * is the autonomous mode, and both bits set is the most externally controlled
1477
+ * state there is, which is the opposite of what the naming suggests. Reading
1478
+ * them the other way round meant a battery running its own logic reported
1479
+ * `holding`, a fully clamped one reported `auto`, and no appliance could ever
1480
+ * report that it had been handed back to itself.
1481
+ *
1482
+ * @param controls - Model 124 control registers, or null when unreadable.
1483
+ * @returns The mode, or null when StorCtl_Mod could not be read.
1484
+ */
1485
+ export function deriveStorageMode(controls) {
1486
+ if (!controls || controls.storCtlMod === undefined) {
1487
+ return null;
1488
+ }
1489
+ const chargeLimited = (controls.storCtlMod & 0x0001) !== 0;
1490
+ const dischargeLimited = (controls.storCtlMod & 0x0002) !== 0;
1491
+ if (!chargeLimited && !dischargeLimited) {
1492
+ return SunspecStorageMode.AUTO;
1493
+ }
1494
+ // Both directions clamped to zero — the battery is parked, not idling.
1495
+ if (chargeLimited && dischargeLimited && controls.inWRte === 0 && controls.outWRte === 0) {
1496
+ return SunspecStorageMode.HOLDING;
1497
+ }
1498
+ return dischargeLimited && !chargeLimited
1499
+ ? SunspecStorageMode.DISCHARGE
1500
+ : SunspecStorageMode.CHARGE;
1501
+ }
1428
1502
  export class SunspecBattery extends BaseSunspecDevice {
1429
1503
  featureMode;
1430
1504
  capabilities;
@@ -1455,10 +1529,59 @@ export class SunspecBattery extends BaseSunspecDevice {
1455
1529
  EnyoBatteryFeature.ChargeLimitation,
1456
1530
  EnyoBatteryFeature.DischargeLimitation,
1457
1531
  ];
1458
- constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, featureMode, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
1532
+ constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, featureMode, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
1533
+ // Battery facts no register carries (currently the measured round-trip efficiency).
1534
+ // Forwarded onto `appliance.battery` on connect; see SunspecBatteryMetadataConfig.
1535
+ metadataConfig = {}) {
1459
1536
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
1460
1537
  this.featureMode = featureMode;
1461
1538
  this.capabilities = capabilities;
1539
+ this.roundTripEfficiencyPercent = metadataConfig.roundTripEfficiencyPercent;
1540
+ }
1541
+ /**
1542
+ * Last known round-trip efficiency, seeded from the constructor config and replaceable at
1543
+ * runtime via {@link setRoundTripEfficiencyPercent}. Undefined = not yet known; the SDK then
1544
+ * writes nothing, leaving whatever the appliance store already holds.
1545
+ */
1546
+ roundTripEfficiencyPercent;
1547
+ /**
1548
+ * Update the battery's measured round-trip efficiency (percent, 0-100) and push it to the
1549
+ * appliance immediately. Meant to be called whenever the host recomputes the figure from
1550
+ * completed cycles - it drifts with cell age and temperature, so a value fixed at construction
1551
+ * goes stale. Pass `undefined` to stop asserting a value (the last published one stays in the
1552
+ * appliance store; the SDK does not erase it).
1553
+ *
1554
+ * Safe to call before {@link connect}: the value is remembered and published with the rest of
1555
+ * the metadata once the appliance exists.
1556
+ */
1557
+ async setRoundTripEfficiencyPercent(percent) {
1558
+ if (percent !== undefined && (!Number.isFinite(percent) || percent < 0 || percent > 100)) {
1559
+ throw new Error(`setRoundTripEfficiencyPercent: ${percent} is not a percentage between 0 and 100`);
1560
+ }
1561
+ this.roundTripEfficiencyPercent = percent;
1562
+ if (percent === undefined || !this.applianceId)
1563
+ return;
1564
+ try {
1565
+ const existingAppliance = await this.applianceManager.findApplianceById(this.applianceId);
1566
+ await this.applianceManager.updateAppliance(this.applianceId, {
1567
+ battery: {
1568
+ ...existingAppliance?.battery,
1569
+ roundTripEfficiencyPercent: percent
1570
+ }
1571
+ });
1572
+ }
1573
+ catch (error) {
1574
+ console.error(`Failed to publish round-trip efficiency for battery ${this.applianceId}: ${error}`);
1575
+ }
1576
+ }
1577
+ /**
1578
+ * The configured battery facts as a spreadable object holding only the keys actually known.
1579
+ * Spreading an explicit `undefined` would erase a value the host set elsewhere.
1580
+ */
1581
+ configuredBatteryMetadata() {
1582
+ return this.roundTripEfficiencyPercent === undefined
1583
+ ? {}
1584
+ : { roundTripEfficiencyPercent: this.roundTripEfficiencyPercent };
1462
1585
  }
1463
1586
  /**
1464
1587
  * Wire the battery into `@enyo-energy/appliance-calibration`'s
@@ -1579,12 +1702,13 @@ export class SunspecBattery extends BaseSunspecDevice {
1579
1702
  battery: {
1580
1703
  connectedToApplianceId: inverterApplianceId,
1581
1704
  storageMode: this.mapToEnyoStorageMode(storageMode),
1582
- maxChargingPowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.inWRte !== undefined ? batteryData.wChaMax * batteryData.inWRte : undefined,
1705
+ maxChargingPowerW: batteryData?.wChaMax,
1583
1706
  maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1584
1707
  activeChargeLimitW: activeChargeLimitW,
1585
1708
  activeDischargeLimitW: activeDischargeLimitW,
1586
1709
  features,
1587
- gridChargingEnabled: batteryData?.chaGriSet === 1
1710
+ gridChargingEnabled: batteryData?.chaGriSet === 1,
1711
+ ...this.configuredBatteryMetadata()
1588
1712
  }
1589
1713
  });
1590
1714
  console.log(`Sunspec Battery connected: ${this.networkDevice.hostname} (${this.applianceId})`);
@@ -1607,12 +1731,13 @@ export class SunspecBattery extends BaseSunspecDevice {
1607
1731
  ...existingAppliance?.battery,
1608
1732
  connectedToApplianceId: inverterApplianceId,
1609
1733
  storageMode: this.mapToEnyoStorageMode(storageMode),
1610
- maxChargingPowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.inWRte !== undefined ? batteryData.wChaMax * batteryData.inWRte : undefined,
1734
+ maxChargingPowerW: batteryData?.wChaMax,
1611
1735
  maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1612
1736
  activeChargeLimitW: activeChargeLimitW,
1613
1737
  activeDischargeLimitW: activeDischargeLimitW,
1614
1738
  features,
1615
- gridChargingEnabled: batteryData?.chaGriSet === 1
1739
+ gridChargingEnabled: batteryData?.chaGriSet === 1,
1740
+ ...this.configuredBatteryMetadata()
1616
1741
  }
1617
1742
  });
1618
1743
  console.log(`Sunspec Battery connected: ${this.networkDevice.hostname} (${this.applianceId})`);
@@ -1766,12 +1891,13 @@ export class SunspecBattery extends BaseSunspecDevice {
1766
1891
  battery: {
1767
1892
  ...appliance?.battery,
1768
1893
  storageMode: this.mapToEnyoStorageMode(storageMode),
1769
- maxChargingPowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.inWRte !== undefined ? batteryData.wChaMax * batteryData.inWRte : undefined,
1894
+ maxChargingPowerW: batteryData?.wChaMax,
1770
1895
  maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1771
1896
  activeChargeLimitW: this.computeActiveChargeLimitW(batteryData),
1772
1897
  activeDischargeLimitW: this.computeActiveDischargeLimitW(batteryData),
1773
1898
  features,
1774
- gridChargingEnabled: batteryData?.chaGriSet === 1
1899
+ gridChargingEnabled: batteryData?.chaGriSet === 1,
1900
+ ...this.configuredBatteryMetadata()
1775
1901
  }
1776
1902
  });
1777
1903
  }
@@ -1970,23 +2096,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1970
2096
  return (batteryData.wChaMax * batteryData.outWRte) / 100;
1971
2097
  }
1972
2098
  determineStorageMode(controls) {
1973
- if (!controls || controls.storCtlMod === undefined) {
1974
- return null;
1975
- }
1976
- const chargeEnabled = (controls.storCtlMod & 0x0001) !== 0;
1977
- const dischargeEnabled = (controls.storCtlMod & 0x0002) !== 0;
1978
- if (chargeEnabled && dischargeEnabled) {
1979
- return SunspecStorageMode.AUTO;
1980
- }
1981
- else if (chargeEnabled && !dischargeEnabled) {
1982
- return SunspecStorageMode.CHARGE;
1983
- }
1984
- else if (!chargeEnabled && dischargeEnabled) {
1985
- return SunspecStorageMode.DISCHARGE;
1986
- }
1987
- else {
1988
- return SunspecStorageMode.HOLDING;
1989
- }
2099
+ return deriveStorageMode(controls);
1990
2100
  }
1991
2101
  /**
1992
2102
  * Check if grid charging is enabled
@@ -46,6 +46,26 @@ export interface IModbusPacingConfig {
46
46
  */
47
47
  waitBetweenMessagesMs?: number;
48
48
  }
49
+ /**
50
+ * Everything the client forwards verbatim to `useModbus().connect()`: the pacing options above plus
51
+ * the transport options added in energy-app-sdk 1.6.0. Kept as a superset of
52
+ * {@link IModbusPacingConfig} so callers that already pass a pacing object keep working unchanged.
53
+ */
54
+ export interface IModbusTransportConfig extends IModbusPacingConfig {
55
+ /**
56
+ * Take the connection from the host's shared pool of sockets — keyed by host, port, unit ID and
57
+ * transport settings — instead of opening one that belongs exclusively to this client (SDK
58
+ * `ModbusOptions.pooledConnection`, available from energy-app-sdk 1.6.0). Pooling lets several
59
+ * consumers of the same physical device share one TCP connection, which matters for devices that
60
+ * accept only a handful of simultaneous Modbus clients. A pooled `disconnect()` releases the
61
+ * connection back to the pool rather than necessarily closing the socket.
62
+ *
63
+ * Note that this SDK already refcounts one client per `host:port`
64
+ * ({@link getOrCreateSunspecClient}), so pooling only adds anything when something *outside* this
65
+ * client also talks to the same device. Leave it unset to keep the SDK's own default.
66
+ */
67
+ pooledConnection?: boolean;
68
+ }
49
69
  /**
50
70
  * Resilience configuration for the Modbus client: per-operation timeouts and half-open socket
51
71
  * detection. All fields are optional and default to sensible values, so existing consumers are
@@ -503,7 +523,14 @@ export declare enum SunspecBatteryEvent1 {
503
523
  * - To ensure external control works properly, the appropriate bits must be set
504
524
  */
505
525
  export declare enum SunspecStorageControlMode {
506
- CHARGE = 1,// Bit 0 - Enable charge mode (allow external charge control)
526
+ /**
527
+ * No bit set — no external setpoint is active and the battery runs its own
528
+ * autonomous logic. This, not `CHARGE | DISCHARGE`, is what "auto" means on
529
+ * Model 124: the bits say *which rate setpoint is being enforced*, so
530
+ * clearing them is what hands control back to the device.
531
+ */
532
+ NONE = 0,
533
+ CHARGE = 1,// Bit 0 - the InWRte charge-rate setpoint is active
507
534
  DISCHARGE = 2
508
535
  }
509
536
  /**
@@ -778,9 +805,9 @@ export declare enum SunspecChargeSource {
778
805
  * Storage modes for simplified battery control
779
806
  */
780
807
  export declare enum SunspecStorageMode {
781
- CHARGE = "charge",// Allow charging only
782
- DISCHARGE = "discharge",// Allow discharging only
783
- HOLDING = "holding",// No charge or discharge (holding mode)
808
+ CHARGE = "charge",// Charging is externally rate-limited via InWRte
809
+ DISCHARGE = "discharge",// Discharging is externally rate-limited via OutWRte
810
+ HOLDING = "holding",// Both directions clamped to 0 % — battery is parked
784
811
  AUTO = "auto"
785
812
  }
786
813
  /**
@@ -795,6 +822,29 @@ export declare enum SunspecStorageMode {
795
822
  export declare enum SunspecInverterCapability {
796
823
  FeedInLimit = "feed-in-limit"
797
824
  }
825
+ /**
826
+ * Nameplate/policy facts about an inverter that live outside the SunSpec register map, published
827
+ * onto `appliance.inverter` when the device connects. Nothing here is readable from Modbus — the
828
+ * installation record (Anlagenpass) or the host's own configuration is the source of truth — so the
829
+ * SDK only forwards what the consumer supplies. Fields left `undefined` are not written, so an
830
+ * existing value in the appliance store survives a reconnect.
831
+ *
832
+ * Both fields were added to the appliance model in energy-app-sdk 1.6.0.
833
+ */
834
+ export interface SunspecInverterMetadataConfig {
835
+ /**
836
+ * Whether the energy manager may actively steer this inverter (e.g. curtail production). Omit
837
+ * to leave the decision to the consumer's configured default — `undefined` is "not configured",
838
+ * which is not the same as `false`.
839
+ */
840
+ controlAllowed?: boolean;
841
+ /**
842
+ * Peak power of the PV modules attached to this inverter, in Watt-peak. Distinct from
843
+ * `maxPvProductionW`, which the SDK reads from the inverter's own AC nameplate (Model 121
844
+ * `WMax`): the module side of the installation is not in any register.
845
+ */
846
+ installedPeakPowerWp?: number;
847
+ }
798
848
  /**
799
849
  * Where an inverter's reported PV production (pvPowerW) is sourced from.
800
850
  * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
@@ -905,6 +955,25 @@ export declare enum SunspecBatteryCapability {
905
955
  DischargeLimit = "discharge-limit",
906
956
  ChargeLimit = "charge-limit"
907
957
  }
958
+ /**
959
+ * Battery facts that live outside the SunSpec register map, published onto `appliance.battery` when
960
+ * the device connects. Fields left `undefined` are not written, so an existing value in the
961
+ * appliance store survives a reconnect.
962
+ */
963
+ export interface SunspecBatteryMetadataConfig {
964
+ /**
965
+ * Observed AC-to-AC round-trip efficiency in percent (0–100): of the energy put into the
966
+ * battery, how much comes back out. Added to the appliance model in energy-app-sdk 1.6.0.
967
+ *
968
+ * A *measured* figure, not a datasheet one — it drifts with cell age, temperature and depth of
969
+ * discharge, and no SunSpec model reports it, so the SDK cannot derive it. Supply it from
970
+ * whatever the host computes over completed cycles, either here at construction or later via
971
+ * {@link SunspecBattery.setRoundTripEfficiencyPercent}. Leave it unset until enough cycles have
972
+ * been observed: a missing value means "not yet known", and is more useful to an optimizer than
973
+ * a nameplate number that overstates what the pack returns.
974
+ */
975
+ roundTripEfficiencyPercent?: number;
976
+ }
908
977
  /**
909
978
  * Selects how `SunspecBattery` populates `appliance.battery.features`.
910
979
  *
@@ -213,8 +213,15 @@ export var SunspecBatteryEvent1;
213
213
  */
214
214
  export var SunspecStorageControlMode;
215
215
  (function (SunspecStorageControlMode) {
216
+ /**
217
+ * No bit set — no external setpoint is active and the battery runs its own
218
+ * autonomous logic. This, not `CHARGE | DISCHARGE`, is what "auto" means on
219
+ * Model 124: the bits say *which rate setpoint is being enforced*, so
220
+ * clearing them is what hands control back to the device.
221
+ */
222
+ SunspecStorageControlMode[SunspecStorageControlMode["NONE"] = 0] = "NONE";
216
223
  SunspecStorageControlMode[SunspecStorageControlMode["CHARGE"] = 1] = "CHARGE";
217
- SunspecStorageControlMode[SunspecStorageControlMode["DISCHARGE"] = 2] = "DISCHARGE"; // Bit 1 - Enable discharge mode (allow external discharge control)
224
+ SunspecStorageControlMode[SunspecStorageControlMode["DISCHARGE"] = 2] = "DISCHARGE"; // Bit 1 - the OutWRte discharge-rate setpoint is active
218
225
  // Note: Higher bits may control other modes like autonomous/self-consumption
219
226
  // but these are device-specific and not standardized in SunSpec
220
227
  })(SunspecStorageControlMode || (SunspecStorageControlMode = {}));
@@ -259,7 +266,7 @@ export var SunspecStorageMode;
259
266
  SunspecStorageMode["CHARGE"] = "charge";
260
267
  SunspecStorageMode["DISCHARGE"] = "discharge";
261
268
  SunspecStorageMode["HOLDING"] = "holding";
262
- SunspecStorageMode["AUTO"] = "auto"; // Both charge and discharge allowed
269
+ SunspecStorageMode["AUTO"] = "auto"; // No external setpoint active (StorCtl_Mod = 0)
263
270
  })(SunspecStorageMode || (SunspecStorageMode = {}));
264
271
  /**
265
272
  * Battery control structure for writing to Model 124
@@ -16,7 +16,7 @@
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, type IModbusPacingConfig, type IModbusResilienceConfig } 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 IModbusTransportConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.js";
20
20
  import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
21
21
  import { EnergyAppModbus, EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
22
22
  import { EnergyApp } from "@enyo-energy/energy-app-sdk";
@@ -29,12 +29,61 @@ export declare class ModbusOperationTimeoutError extends Error {
29
29
  readonly unitId: number;
30
30
  readonly timeoutMs: number;
31
31
  constructor(operation: string, unitId: number, timeoutMs: number);
32
+ /**
33
+ * `Error` has no enumerable own properties, so a consumer that logs `{ err }` through a
34
+ * JSON serializer emits `{}` and loses the message entirely. Give every error this client
35
+ * rejects with an explicit JSON shape so it survives `JSON.stringify` with a usable message.
36
+ */
37
+ toJSON(): {
38
+ name: string;
39
+ message: string;
40
+ operation: string;
41
+ unitId: number;
42
+ timeoutMs: number;
43
+ };
44
+ }
45
+ /**
46
+ * Why a unit is refusing I/O without having attempted it. A discriminant field rather than a
47
+ * class hierarchy, so consumers can branch on the cause with a plain `===`.
48
+ */
49
+ export type SunspecUnavailableReason = 'socket-poisoned';
50
+ /**
51
+ * Thrown when the client refuses a transaction because the unit is **already known to be down**,
52
+ * as opposed to a transaction that was actually attempted and failed.
53
+ *
54
+ * The distinction matters for logging. A poisoned socket produces exactly one genuine event (the
55
+ * timeout that poisoned it), but every read that lands during the outage would otherwise throw an
56
+ * error indistinguishable from real I/O failure — so a consumer catching per read has no choice but
57
+ * to log each one at ERROR. Callers should log the first {@link SunspecUnavailableError} of an
58
+ * outage (or nothing at all: the SDK already logs the transition) and stay quiet on the rest.
59
+ *
60
+ * {@link sinceMs} is how long the unit has been in this state, so a consumer that does want one
61
+ * line can say how stale the link is without tracking the outage itself.
62
+ */
63
+ export declare class SunspecUnavailableError extends Error {
64
+ readonly reason: SunspecUnavailableReason;
65
+ readonly unitId: number;
66
+ readonly sinceMs: number;
67
+ constructor(reason: SunspecUnavailableReason, unitId: number, sinceMs: number);
68
+ /** See {@link ModbusOperationTimeoutError.toJSON}. */
69
+ toJSON(): {
70
+ name: string;
71
+ message: string;
72
+ reason: SunspecUnavailableReason;
73
+ unitId: number;
74
+ sinceMs: number;
75
+ };
32
76
  }
77
+ /**
78
+ * Type guard for {@link SunspecUnavailableError}. Prefer this over `instanceof` at package
79
+ * boundaries, where a duplicated copy of the SDK in the module graph would break identity.
80
+ */
81
+ export declare function isSunspecUnavailableError(error: unknown): error is SunspecUnavailableError;
33
82
  /**
34
83
  * Get (or create) the singleton SunspecModbusClient for this network device.
35
84
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
36
85
  *
37
- * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
86
+ * NOTE: `transport`, `resilience` and `modbusFactory` are only applied when the client is FIRST
38
87
  * created for a given host:port. Because the client is cached and refcounted, a later caller
39
88
  * passing different config receives the already-created instance and its config is ignored.
40
89
  *
@@ -42,7 +91,7 @@ export declare class ModbusOperationTimeoutError extends Error {
42
91
  * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
43
92
  * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
44
93
  */
45
- export declare function getOrCreateSunspecClient(energyApp: EnergyApp | undefined, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus): SunspecModbusClient;
94
+ export declare function getOrCreateSunspecClient(energyApp: EnergyApp | undefined, host: string, port?: number, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus): SunspecModbusClient;
46
95
  /**
47
96
  * Release a refcount on the network-device client. When the last consumer releases,
48
97
  * the client is fully disconnected (all units closed) and removed from the registry.
@@ -66,7 +115,7 @@ export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts:
66
115
  }): Promise<T>;
67
116
  export declare class SunspecModbusClient {
68
117
  private energyApp;
69
- private pacing;
118
+ private transport;
70
119
  private modbusFactory?;
71
120
  private modbusInstances;
72
121
  private faultTolerantReaders;
@@ -83,8 +132,10 @@ export declare class SunspecModbusClient {
83
132
  private txChains;
84
133
  private resilience;
85
134
  private poisonedUnits;
135
+ private poisonedAtByUnit;
86
136
  private lastOkAtByUnit;
87
- constructor(energyApp: EnergyApp | undefined, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
137
+ private consecutiveConnectFailures;
138
+ constructor(energyApp: EnergyApp | undefined, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
88
139
  /**
89
140
  * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
90
141
  * if one was given, otherwise the host application's default (`energyApp.useModbus()`). The
@@ -238,12 +289,38 @@ export declare class SunspecModbusClient {
238
289
  * timer is always cleared so a fast `fn` doesn't keep the event loop alive.
239
290
  */
240
291
  private withTimeout;
292
+ /**
293
+ * Log a failed Modbus transaction from a reader/writer catch block.
294
+ *
295
+ * A {@link SunspecUnavailableError} is not a failure — it is this client refusing I/O on a link
296
+ * it has already reported dead once (one WARN on the transition, one INFO on recovery). Logging
297
+ * it at ERROR once per read, per read path, per poll cycle, for the whole outage, is what buries
298
+ * the errors that are actually actionable. So it drops to debug; everything else stays ERROR.
299
+ */
300
+ private logConnectFailure;
301
+ /** True while `key`'s last attempt failed — used to keep repeat attempt chatter at debug. */
302
+ private isRetryingAfterFailure;
303
+ /** Forget `key`'s failure run on a success, so the next outage logs its first failure again. */
304
+ private clearConnectFailures;
305
+ private logTransactionError;
241
306
  /**
242
307
  * Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
243
308
  * gate immediately, so isHealthy() flips false this cycle instead of after the coarse
244
309
  * 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
245
310
  */
246
311
  private poisonUnit;
312
+ /**
313
+ * Enter the poisoned state for a unit, logging the TRANSITION only. Everything downstream of
314
+ * this (every refused read, every poll cycle) is the same known state and must stay silent —
315
+ * one WARN in, one INFO out (see {@link logPoisonRecovery}), nothing in between.
316
+ */
317
+ private enterPoisoned;
318
+ /**
319
+ * Close out a poisoned episode on a successful (re)open: one INFO carrying how long the unit
320
+ * was refusing I/O. No-op for a unit that was never poisoned, so a normal first connect stays
321
+ * quiet.
322
+ */
323
+ private logPoisonRecovery;
247
324
  /**
248
325
  * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
249
326
  * readData()/tryReconnect() cycle recycles it — the same effect as a timeout poison but