@enyo-energy/sunspec-sdk 0.0.105 → 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.
@@ -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.cjs";
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.cjs";
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
@@ -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.105';
12
+ exports.SDK_VERSION = '1.0.0';
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.105";
8
+ export declare const SDK_VERSION = "1.0.0";
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, SunspecPvPowerSource, SunspecPvPowerOrigin, type SunspecInverterReading, type SunspecBatteryReading, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode, type SunspecCustomDeviceConfig } from "./sunspec-interfaces.js";
1
+ import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, type SunspecInverterMetadataConfig, type SunspecBatteryMetadataConfig, SunspecPvPowerOrigin, type SunspecInverterReading, type SunspecBatteryReading, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode, type SunspecCustomDeviceConfig } 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";
@@ -208,6 +208,7 @@ type SunspecPvPower = {
208
208
  export declare class SunspecInverter extends BaseSunspecDevice {
209
209
  private readonly capabilities;
210
210
  private readonly pvPowerSource;
211
+ private readonly metadataConfig;
211
212
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
212
213
  private static readonly CONNECTION_FAULT_THRESHOLD;
213
214
  /**
@@ -233,7 +234,13 @@ export declare class SunspecInverter extends BaseSunspecDevice {
233
234
  private acEnergyDropStreak;
234
235
  /** Consecutive corrupt reads that confirm a genuine reset/resync (vs a transient glitch). */
235
236
  private static readonly AC_ENERGY_RESET_CONFIRM;
236
- 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);
237
+ 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, metadataConfig?: SunspecInverterMetadataConfig);
238
+ /**
239
+ * The consumer-supplied inverter facts, as a spreadable object that only contains the keys that
240
+ * were actually configured. Spreading `{ controlAllowed: undefined }` over an existing appliance
241
+ * would erase a value the host set elsewhere; omitting the key leaves it alone.
242
+ */
243
+ private configuredInverterMetadata;
237
244
  connect(): Promise<void>;
238
245
  disconnect(): Promise<void>;
239
246
  readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
@@ -547,7 +554,29 @@ export declare class SunspecBattery extends BaseSunspecDevice {
547
554
  * {@link computeAdvertisedFeatures}.
548
555
  */
549
556
  private static readonly CONTROLLABLE_FEATURES;
550
- constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, featureMode: SunspecBatteryFeatureMode, unitId?: number, port?: number, baseAddress?: number, capabilities?: SunspecBatteryCapability[], retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean);
557
+ constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, featureMode: SunspecBatteryFeatureMode, unitId?: number, port?: number, baseAddress?: number, capabilities?: SunspecBatteryCapability[], retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean, metadataConfig?: SunspecBatteryMetadataConfig);
558
+ /**
559
+ * Last known round-trip efficiency, seeded from the constructor config and replaceable at
560
+ * runtime via {@link setRoundTripEfficiencyPercent}. Undefined = not yet known; the SDK then
561
+ * writes nothing, leaving whatever the appliance store already holds.
562
+ */
563
+ private roundTripEfficiencyPercent?;
564
+ /**
565
+ * Update the battery's measured round-trip efficiency (percent, 0-100) and push it to the
566
+ * appliance immediately. Meant to be called whenever the host recomputes the figure from
567
+ * completed cycles - it drifts with cell age and temperature, so a value fixed at construction
568
+ * goes stale. Pass `undefined` to stop asserting a value (the last published one stays in the
569
+ * appliance store; the SDK does not erase it).
570
+ *
571
+ * Safe to call before {@link connect}: the value is remembered and published with the rest of
572
+ * the metadata once the appliance exists.
573
+ */
574
+ setRoundTripEfficiencyPercent(percent: number | undefined): Promise<void>;
575
+ /**
576
+ * The configured battery facts as a spreadable object holding only the keys actually known.
577
+ * Spreading an explicit `undefined` would erase a value the host set elsewhere.
578
+ */
579
+ private configuredBatteryMetadata;
551
580
  /**
552
581
  * Wire the battery into `@enyo-energy/appliance-calibration`'s
553
582
  * `BatteryCalibrator` test-charge flow. Call once after {@link connect}.
@@ -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})`);
@@ -1486,10 +1529,59 @@ export class SunspecBattery extends BaseSunspecDevice {
1486
1529
  EnyoBatteryFeature.ChargeLimitation,
1487
1530
  EnyoBatteryFeature.DischargeLimitation,
1488
1531
  ];
1489
- 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 = {}) {
1490
1536
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
1491
1537
  this.featureMode = featureMode;
1492
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 };
1493
1585
  }
1494
1586
  /**
1495
1587
  * Wire the battery into `@enyo-energy/appliance-calibration`'s
@@ -1615,7 +1707,8 @@ export class SunspecBattery extends BaseSunspecDevice {
1615
1707
  activeChargeLimitW: activeChargeLimitW,
1616
1708
  activeDischargeLimitW: activeDischargeLimitW,
1617
1709
  features,
1618
- gridChargingEnabled: batteryData?.chaGriSet === 1
1710
+ gridChargingEnabled: batteryData?.chaGriSet === 1,
1711
+ ...this.configuredBatteryMetadata()
1619
1712
  }
1620
1713
  });
1621
1714
  console.log(`Sunspec Battery connected: ${this.networkDevice.hostname} (${this.applianceId})`);
@@ -1643,7 +1736,8 @@ export class SunspecBattery extends BaseSunspecDevice {
1643
1736
  activeChargeLimitW: activeChargeLimitW,
1644
1737
  activeDischargeLimitW: activeDischargeLimitW,
1645
1738
  features,
1646
- gridChargingEnabled: batteryData?.chaGriSet === 1
1739
+ gridChargingEnabled: batteryData?.chaGriSet === 1,
1740
+ ...this.configuredBatteryMetadata()
1647
1741
  }
1648
1742
  });
1649
1743
  console.log(`Sunspec Battery connected: ${this.networkDevice.hostname} (${this.applianceId})`);
@@ -1802,7 +1896,8 @@ export class SunspecBattery extends BaseSunspecDevice {
1802
1896
  activeChargeLimitW: this.computeActiveChargeLimitW(batteryData),
1803
1897
  activeDischargeLimitW: this.computeActiveDischargeLimitW(batteryData),
1804
1898
  features,
1805
- gridChargingEnabled: batteryData?.chaGriSet === 1
1899
+ gridChargingEnabled: batteryData?.chaGriSet === 1,
1900
+ ...this.configuredBatteryMetadata()
1806
1901
  }
1807
1902
  });
1808
1903
  }
@@ -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
@@ -802,6 +822,29 @@ export declare enum SunspecStorageMode {
802
822
  export declare enum SunspecInverterCapability {
803
823
  FeedInLimit = "feed-in-limit"
804
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
+ }
805
848
  /**
806
849
  * Where an inverter's reported PV production (pvPowerW) is sourced from.
807
850
  * - Auto: summed MPPT DC strings (Model 160) when present, else the inverter's
@@ -912,6 +955,25 @@ export declare enum SunspecBatteryCapability {
912
955
  DischargeLimit = "discharge-limit",
913
956
  ChargeLimit = "charge-limit"
914
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
+ }
915
977
  /**
916
978
  * Selects how `SunspecBattery` populates `appliance.battery.features`.
917
979
  *
@@ -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