@enyo-energy/sunspec-sdk 1.7.0 → 1.9.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.
@@ -1726,8 +1726,8 @@ class SunspecBattery extends BaseSunspecDevice {
1726
1726
  throw new Error('No battery model found in device');
1727
1727
  }
1728
1728
  // Give every limit a revert timeout so a hub that goes offline cannot leave the
1729
- // battery blocked (devices ship with 0 = never revert). Written once here; the
1730
- // schedule handler refreshes active limits inside this window.
1729
+ // battery blocked (devices ship with 0 = never revert). Written here and re-asserted
1730
+ // by limit writes; the schedule handler refreshes active limits inside this window.
1731
1731
  await this.sunspecClient.writeBatteryRateRevertTimeout(this.unitId);
1732
1732
  // Get device info
1733
1733
  const commonData = await this.sunspecClient.readCommonBlock(this.unitId);
@@ -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.SunspecGridChargeMethod = exports.SunspecBatteryCapability = exports.SunspecPvPowerOrigin = exports.SunspecPvPowerSource = exports.SunspecInverterCapability = exports.SunspecStorageMode = exports.SunspecChargeSource = exports.SunspecVArPctMode = exports.SunspecEnableControl = exports.SunspecConnectionControl = exports.MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = exports.MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = exports.DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 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_MODBUS_RESILIENCE_CONFIG = exports.DEFAULT_RETRY_CONFIG = void 0;
6
+ exports.SUNSPEC_CONTROLLABLE_FEATURES = exports.SunspecMeterCapability = exports.SunspecBatteryFeatureModeKind = exports.SunspecGridChargeMethod = exports.SunspecBatteryCapability = exports.SunspecPvPowerOrigin = exports.SunspecPvPowerSource = exports.SunspecInverterCapability = exports.SunspecStorageMode = exports.SunspecChargeSource = exports.SunspecVArPctMode = exports.SunspecEnableControl = exports.SunspecConnectionControl = exports.BATTERY_RATE_REVERT_REASSERT_MS = exports.MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = exports.MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = exports.DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 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_MODBUS_RESILIENCE_CONFIG = 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: [
@@ -250,6 +250,11 @@ exports.MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
250
250
  * "not implemented" marker.
251
251
  */
252
252
  exports.MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 0xFFFE;
253
+ /**
254
+ * How often a battery limit write re-asserts InOutWRte_RvrtTms. Once per connect was not enough:
255
+ * a device can come up with, or be reset to, a value that drops every limit within a second.
256
+ */
257
+ exports.BATTERY_RATE_REVERT_REASSERT_MS = 60_000;
253
258
  /**
254
259
  * Enum values for connection control
255
260
  */
@@ -555,6 +555,11 @@ export declare const MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
555
555
  * "not implemented" marker.
556
556
  */
557
557
  export declare const MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 65534;
558
+ /**
559
+ * How often a battery limit write re-asserts InOutWRte_RvrtTms. Once per connect was not enough:
560
+ * a device can come up with, or be reset to, a value that drops every limit within a second.
561
+ */
562
+ export declare const BATTERY_RATE_REVERT_REASSERT_MS = 60000;
558
563
  /**
559
564
  * Battery data structure based on Model 124 (Basic Storage Controls)
560
565
  *
@@ -254,12 +254,21 @@ class SunspecModbusClient {
254
254
  // announces itself twice — once by the transport, once by this client's own close/reopen —
255
255
  // and an app must not be told to re-authenticate twice for one loss.
256
256
  unitSessionReportedLost = new Set();
257
- // Model 124 InOutWRte_RvrtTms written once when a battery connects. See
258
- // setBatteryRateRevertTimeoutSeconds().
257
+ // Model 124 InOutWRte_RvrtTms written when a battery connects and re-asserted by limit writes.
258
+ // See setBatteryRateRevertTimeoutSeconds().
259
259
  batteryRateRevertTimeoutSeconds = sunspec_interfaces_js_1.DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS;
260
260
  // Units whose InOutWRte_RvrtTms write has already failed and been warned about. Later
261
261
  // failures on the same unit stay silent so a device without the register warns once.
262
262
  batteryRateRevertWarnedUnits = new Set();
263
+ // When InOutWRte_RvrtTms was last written, per unit — failed attempts included, so a device
264
+ // that rejects the register is retried once per interval rather than on every limit write.
265
+ // A limit write re-asserts it once this is older than BATTERY_RATE_REVERT_REASSERT_MS, or
266
+ // straight away after a readback showed a new foreign value (the entry is then dropped).
267
+ batteryRateRevertAssertedAt = new Map();
268
+ // Last RvrtTms readback that disagreed with the configured value, per unit. A device stuck on
269
+ // that value warns and triggers an immediate re-assert once; after that it waits for the
270
+ // interval, so a device that clamps or ignores the write is not rewritten on every limit.
271
+ batteryRateRevertMismatchWarned = new Map();
263
272
  constructor(
264
273
  // The host application. Only used to obtain the default Modbus backend via
265
274
  // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
@@ -604,6 +613,9 @@ class SunspecModbusClient {
604
613
  */
605
614
  async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs, useFallbackHosts = true) {
606
615
  let candidate = null;
616
+ // Set once this attempt has failed; a connect that settles after that is nobody's socket.
617
+ let abandoned = false;
618
+ let connected = null;
607
619
  const hosts = useFallbackHosts ? this.buildConnectHosts(host) : host;
608
620
  const hostCount = Array.isArray(hosts) ? hosts.length : 1;
609
621
  // Each host in the list gets its own `timeout`; bound the whole walk at count × budget so we
@@ -613,20 +625,40 @@ class SunspecModbusClient {
613
625
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
614
626
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
615
627
  // can still leave the returned promise pending — bound it independently.
616
- candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.useModbus().connect({
617
- host: hosts,
618
- port,
619
- unitId,
620
- timeout: connectTimeoutMs,
621
- useTls: this.connectionParams?.useTls,
622
- cert: this.connectionParams?.cert,
623
- key: this.connectionParams?.key,
624
- ca: this.connectionParams?.ca,
625
- rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
626
- noParallelRequests: this.transport.noParallelRequests,
627
- waitBetweenMessagesMs: this.transport.waitBetweenMessagesMs,
628
- pooledConnection: this.transport.pooledConnection
629
- }));
628
+ //
629
+ // Losing that race must not leak the socket: the transport does not bound a TLS
630
+ // handshake, so it can still complete after we gave up. Nobody would own that
631
+ // instance, and with a dedicated (non-pooled) connection it stays a live session on
632
+ // the device — a KOSTAL KSEM caps its Modbus/TLS clients and locks us out once enough
633
+ // timed-out attempts have piled up. Close whatever settles after the attempt failed.
634
+ candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => {
635
+ const connecting = this.useModbus().connect({
636
+ host: hosts,
637
+ port,
638
+ unitId,
639
+ timeout: connectTimeoutMs,
640
+ useTls: this.connectionParams?.useTls,
641
+ cert: this.connectionParams?.cert,
642
+ key: this.connectionParams?.key,
643
+ ca: this.connectionParams?.ca,
644
+ rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
645
+ noParallelRequests: this.transport.noParallelRequests,
646
+ waitBetweenMessagesMs: this.transport.waitBetweenMessagesMs,
647
+ pooledConnection: this.transport.pooledConnection
648
+ });
649
+ connecting.then(instance => {
650
+ if (!instance)
651
+ return;
652
+ if (!abandoned) {
653
+ connected = instance;
654
+ return;
655
+ }
656
+ console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} completed after its ` +
657
+ `${overallBudgetMs}ms budget — closing the orphaned socket`);
658
+ void this.disconnectInstanceBounded(instance, unitId);
659
+ }, () => { });
660
+ return connecting;
661
+ });
630
662
  if (!candidate) {
631
663
  throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
632
664
  }
@@ -653,8 +685,12 @@ class SunspecModbusClient {
653
685
  this.recordOpen();
654
686
  }
655
687
  catch (err) {
656
- if (candidate) {
657
- await this.disconnectInstanceBounded(candidate, unitId);
688
+ abandoned = true;
689
+ // `connected` covers a connect that settled after the budget fired but before we got
690
+ // here; one that settles even later is closed by the handler on the connect promise.
691
+ const orphan = candidate ?? connected;
692
+ if (orphan) {
693
+ await this.disconnectInstanceBounded(orphan, unitId);
658
694
  }
659
695
  this.modbusInstances.delete(unitId);
660
696
  this.faultTolerantReaders.delete(unitId);
@@ -2467,6 +2503,7 @@ class SunspecModbusClient {
2467
2503
  // the object across many lines; stringify keeps the whole snapshot
2468
2504
  // on one log entry so it stays grep-able and round-trippable.
2469
2505
  console.debug(`[Battery] unit=${unitId} model=124 data=${JSON.stringify(data)}`);
2506
+ this.checkBatteryRateRevertReadback(unitId, data.inOutWRteRvrtTms);
2470
2507
  return data;
2471
2508
  }
2472
2509
  else if (model.id === 802) {
@@ -2523,8 +2560,9 @@ class SunspecModbusClient {
2523
2560
  }
2524
2561
  }
2525
2562
  /**
2526
- * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written once when the battery
2527
- * connects and once after every reconnect — e.g. 30 or 60. When no fresh rate write arrives within this window
2563
+ * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written when the battery connects,
2564
+ * after every reconnect, and again by a limit write at most every
2565
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} — e.g. 30 or 60. When no fresh rate write arrives within this window
2528
2566
  * the device drops the limit and manages itself again, so a hub that goes
2529
2567
  * offline cannot leave the battery blocked. The schedule handler refreshes an
2530
2568
  * active limit every third of this value.
@@ -2543,6 +2581,8 @@ class SunspecModbusClient {
2543
2581
  `${sunspec_interfaces_js_1.MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and ${sunspec_interfaces_js_1.MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}`);
2544
2582
  }
2545
2583
  this.batteryRateRevertTimeoutSeconds = seconds;
2584
+ // A new value is due on the next limit write, not a minute later.
2585
+ this.batteryRateRevertAssertedAt.clear();
2546
2586
  }
2547
2587
  /** Current Model 124 `InOutWRte_RvrtTms` in seconds. */
2548
2588
  getBatteryRateRevertTimeoutSeconds() {
@@ -2609,6 +2649,13 @@ class SunspecModbusClient {
2609
2649
  // Storage control mode (Register 5) — written LAST so all
2610
2650
  // governing parameters are already in place when the device
2611
2651
  // transitions into the new mode.
2652
+ // A limit only holds as long as InOutWRte_RvrtTms allows. Re-assert our value before
2653
+ // the mode write so the new limit gets the full window — a device left on a foreign
2654
+ // value (1 s on a GEN24 in the field) drops every limit a second after each write.
2655
+ if (controls.storCtlMod !== undefined && controls.storCtlMod !== 0
2656
+ && this.isBatteryRateRevertDue(unitId)) {
2657
+ await this.writeBatteryRateRevertTimeout(unitId);
2658
+ }
2612
2659
  if (controls.storCtlMod !== undefined) {
2613
2660
  // storCtlMod = 0 is rejected with Modbus Exception code 3 (Illegal Data Value)
2614
2661
  // by some devices (e.g. Fronius GEN24). 0 means "no external control" per the
@@ -2632,8 +2679,10 @@ class SunspecModbusClient {
2632
2679
  }
2633
2680
  /**
2634
2681
  * Write the configured InOutWRte_RvrtTms (Model 124 offset 15) to the device.
2635
- * Called once by `SunspecBattery.connect()` and once per recovered connection;
2636
- * the device keeps the value, so limit writes do not repeat it.
2682
+ * Called by `SunspecBattery.connect()`, once per recovered connection, and by
2683
+ * {@link writeBatteryControls} before a limit when the last write is older than
2684
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} or a readback disagreed. The device should keep
2685
+ * the value, but one GEN24 in the field sat on 1 s anyway.
2637
2686
  *
2638
2687
  * Never throws: a device that rejects the register still takes limits, it just
2639
2688
  * won't revert them on its own (the pre-existing behaviour). The first failure
@@ -2650,6 +2699,9 @@ class SunspecModbusClient {
2650
2699
  return false;
2651
2700
  }
2652
2701
  const seconds = this.batteryRateRevertTimeoutSeconds;
2702
+ // Stamp the attempt, not the success: a device that rejects the register must not be
2703
+ // retried (and logged as a failed write) on every limit write.
2704
+ this.batteryRateRevertAssertedAt.set(unitId, Date.now());
2653
2705
  try {
2654
2706
  await this.writeRegisterValue(unitId, model.address + 15, seconds, 'uint16');
2655
2707
  console.log(`Unit ${unitId}: set battery rate revert timeout (InOutWRte_RvrtTms) to ${seconds}s`);
@@ -2664,6 +2716,36 @@ class SunspecModbusClient {
2664
2716
  return false;
2665
2717
  }
2666
2718
  }
2719
+ /** Whether a limit write should re-assert InOutWRte_RvrtTms first. */
2720
+ isBatteryRateRevertDue(unitId) {
2721
+ const assertedAt = this.batteryRateRevertAssertedAt.get(unitId);
2722
+ return assertedAt === undefined || Date.now() - assertedAt >= sunspec_interfaces_js_1.BATTERY_RATE_REVERT_REASSERT_MS;
2723
+ }
2724
+ /**
2725
+ * Compare a Model 124 readback of InOutWRte_RvrtTms with the configured value. A mismatch
2726
+ * means our write never landed or something reset it. A new foreign value is logged once and
2727
+ * makes the next limit write re-assert immediately; if the same value is still there after
2728
+ * that, the device clamps or ignores the write and re-asserts fall back to the interval.
2729
+ */
2730
+ checkBatteryRateRevertReadback(unitId, readback) {
2731
+ if (readback === undefined)
2732
+ return;
2733
+ // Nothing written since connect or since setBatteryRateRevertTimeoutSeconds(): the device
2734
+ // still holding the old value is expected, and the next limit write asserts anyway.
2735
+ if (!this.batteryRateRevertAssertedAt.has(unitId))
2736
+ return;
2737
+ const expected = this.batteryRateRevertTimeoutSeconds;
2738
+ if (readback === expected) {
2739
+ this.batteryRateRevertMismatchWarned.delete(unitId);
2740
+ return;
2741
+ }
2742
+ if (this.batteryRateRevertMismatchWarned.get(unitId) !== readback) {
2743
+ this.batteryRateRevertMismatchWarned.set(unitId, readback);
2744
+ this.batteryRateRevertAssertedAt.delete(unitId);
2745
+ console.warn(`Unit ${unitId}: InOutWRte_RvrtTms reads ${readback}s, expected ${expected}s — ` +
2746
+ `re-asserting with the next battery limit write`);
2747
+ }
2748
+ }
2667
2749
  /**
2668
2750
  * Set battery storage mode (simplified interface)
2669
2751
  */
@@ -141,6 +141,8 @@ export declare class SunspecModbusClient {
141
141
  private unitSessionReportedLost;
142
142
  private batteryRateRevertTimeoutSeconds;
143
143
  private batteryRateRevertWarnedUnits;
144
+ private batteryRateRevertAssertedAt;
145
+ private batteryRateRevertMismatchWarned;
144
146
  constructor(energyApp: EnergyApp | undefined, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
145
147
  /**
146
148
  * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
@@ -677,8 +679,9 @@ export declare class SunspecModbusClient {
677
679
  */
678
680
  readBatteryData(unitId: number): Promise<SunspecBatteryData | null>;
679
681
  /**
680
- * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written once when the battery
681
- * connects and once after every reconnect — e.g. 30 or 60. When no fresh rate write arrives within this window
682
+ * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written when the battery connects,
683
+ * after every reconnect, and again by a limit write at most every
684
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} — e.g. 30 or 60. When no fresh rate write arrives within this window
682
685
  * the device drops the limit and manages itself again, so a hub that goes
683
686
  * offline cannot leave the battery blocked. The schedule handler refreshes an
684
687
  * active limit every third of this value.
@@ -698,8 +701,10 @@ export declare class SunspecModbusClient {
698
701
  writeBatteryControls(unitId: number, controls: Partial<SunspecBatteryControls>): Promise<boolean>;
699
702
  /**
700
703
  * Write the configured InOutWRte_RvrtTms (Model 124 offset 15) to the device.
701
- * Called once by `SunspecBattery.connect()` and once per recovered connection;
702
- * the device keeps the value, so limit writes do not repeat it.
704
+ * Called by `SunspecBattery.connect()`, once per recovered connection, and by
705
+ * {@link writeBatteryControls} before a limit when the last write is older than
706
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} or a readback disagreed. The device should keep
707
+ * the value, but one GEN24 in the field sat on 1 s anyway.
703
708
  *
704
709
  * Never throws: a device that rejects the register still takes limits, it just
705
710
  * won't revert them on its own (the pre-existing behaviour). The first failure
@@ -709,6 +714,15 @@ export declare class SunspecModbusClient {
709
714
  * or the write failed.
710
715
  */
711
716
  writeBatteryRateRevertTimeout(unitId: number): Promise<boolean>;
717
+ /** Whether a limit write should re-assert InOutWRte_RvrtTms first. */
718
+ private isBatteryRateRevertDue;
719
+ /**
720
+ * Compare a Model 124 readback of InOutWRte_RvrtTms with the configured value. A mismatch
721
+ * means our write never landed or something reset it. A new foreign value is logged once and
722
+ * makes the next limit write re-assert immediately; if the same value is still there after
723
+ * that, the device clamps or ignores the write and re-asserts fall back to the interval.
724
+ */
725
+ private checkBatteryRateRevertReadback;
712
726
  /**
713
727
  * Set battery storage mode (simplified interface)
714
728
  */
@@ -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 = '1.7.0';
12
+ exports.SDK_VERSION = '1.9.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 = "1.7.0";
8
+ export declare const SDK_VERSION = "1.9.0";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
@@ -1715,8 +1715,8 @@ export class SunspecBattery extends BaseSunspecDevice {
1715
1715
  throw new Error('No battery model found in device');
1716
1716
  }
1717
1717
  // Give every limit a revert timeout so a hub that goes offline cannot leave the
1718
- // battery blocked (devices ship with 0 = never revert). Written once here; the
1719
- // schedule handler refreshes active limits inside this window.
1718
+ // battery blocked (devices ship with 0 = never revert). Written here and re-asserted
1719
+ // by limit writes; the schedule handler refreshes active limits inside this window.
1720
1720
  await this.sunspecClient.writeBatteryRateRevertTimeout(this.unitId);
1721
1721
  // Get device info
1722
1722
  const commonData = await this.sunspecClient.readCommonBlock(this.unitId);
@@ -555,6 +555,11 @@ export declare const MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
555
555
  * "not implemented" marker.
556
556
  */
557
557
  export declare const MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 65534;
558
+ /**
559
+ * How often a battery limit write re-asserts InOutWRte_RvrtTms. Once per connect was not enough:
560
+ * a device can come up with, or be reset to, a value that drops every limit within a second.
561
+ */
562
+ export declare const BATTERY_RATE_REVERT_REASSERT_MS = 60000;
558
563
  /**
559
564
  * Battery data structure based on Model 124 (Basic Storage Controls)
560
565
  *
@@ -247,6 +247,11 @@ export const MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
247
247
  * "not implemented" marker.
248
248
  */
249
249
  export const MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 0xFFFE;
250
+ /**
251
+ * How often a battery limit write re-asserts InOutWRte_RvrtTms. Once per connect was not enough:
252
+ * a device can come up with, or be reset to, a value that drops every limit within a second.
253
+ */
254
+ export const BATTERY_RATE_REVERT_REASSERT_MS = 60_000;
250
255
  /**
251
256
  * Enum values for connection control
252
257
  */
@@ -141,6 +141,8 @@ export declare class SunspecModbusClient {
141
141
  private unitSessionReportedLost;
142
142
  private batteryRateRevertTimeoutSeconds;
143
143
  private batteryRateRevertWarnedUnits;
144
+ private batteryRateRevertAssertedAt;
145
+ private batteryRateRevertMismatchWarned;
144
146
  constructor(energyApp: EnergyApp | undefined, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
145
147
  /**
146
148
  * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
@@ -677,8 +679,9 @@ export declare class SunspecModbusClient {
677
679
  */
678
680
  readBatteryData(unitId: number): Promise<SunspecBatteryData | null>;
679
681
  /**
680
- * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written once when the battery
681
- * connects and once after every reconnect — e.g. 30 or 60. When no fresh rate write arrives within this window
682
+ * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written when the battery connects,
683
+ * after every reconnect, and again by a limit write at most every
684
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} — e.g. 30 or 60. When no fresh rate write arrives within this window
682
685
  * the device drops the limit and manages itself again, so a hub that goes
683
686
  * offline cannot leave the battery blocked. The schedule handler refreshes an
684
687
  * active limit every third of this value.
@@ -698,8 +701,10 @@ export declare class SunspecModbusClient {
698
701
  writeBatteryControls(unitId: number, controls: Partial<SunspecBatteryControls>): Promise<boolean>;
699
702
  /**
700
703
  * Write the configured InOutWRte_RvrtTms (Model 124 offset 15) to the device.
701
- * Called once by `SunspecBattery.connect()` and once per recovered connection;
702
- * the device keeps the value, so limit writes do not repeat it.
704
+ * Called by `SunspecBattery.connect()`, once per recovered connection, and by
705
+ * {@link writeBatteryControls} before a limit when the last write is older than
706
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} or a readback disagreed. The device should keep
707
+ * the value, but one GEN24 in the field sat on 1 s anyway.
703
708
  *
704
709
  * Never throws: a device that rejects the register still takes limits, it just
705
710
  * won't revert them on its own (the pre-existing behaviour). The first failure
@@ -709,6 +714,15 @@ export declare class SunspecModbusClient {
709
714
  * or the write failed.
710
715
  */
711
716
  writeBatteryRateRevertTimeout(unitId: number): Promise<boolean>;
717
+ /** Whether a limit write should re-assert InOutWRte_RvrtTms first. */
718
+ private isBatteryRateRevertDue;
719
+ /**
720
+ * Compare a Model 124 readback of InOutWRte_RvrtTms with the configured value. A mismatch
721
+ * means our write never landed or something reset it. A new foreign value is logged once and
722
+ * makes the next limit write re-assert immediately; if the same value is still there after
723
+ * that, the device clamps or ignores the write and re-asserts fall back to the interval.
724
+ */
725
+ private checkBatteryRateRevertReadback;
712
726
  /**
713
727
  * Set battery storage mode (simplified interface)
714
728
  */
@@ -16,7 +16,7 @@
16
16
  * - pad: 0x8000 (always returns this value)
17
17
  * - string: all registers 0x0000 (NULL)
18
18
  */
19
- import { SunspecModelId, SunspecBatteryChargeState, SunspecStorageControlMode, SunspecChargeSource, SunspecEnableControl, SunspecStorageMode, SunspecBatteryType, SunspecBatteryBankState, DEFAULT_MODBUS_RESILIENCE_CONFIG, DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS, MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS, MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS, } from "./sunspec-interfaces.js";
19
+ import { SunspecModelId, SunspecBatteryChargeState, SunspecStorageControlMode, SunspecChargeSource, SunspecEnableControl, SunspecStorageMode, SunspecBatteryType, SunspecBatteryBankState, DEFAULT_MODBUS_RESILIENCE_CONFIG, DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS, BATTERY_RATE_REVERT_REASSERT_MS, MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS, MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS, } from "./sunspec-interfaces.js";
20
20
  import { EnergyAppModbusConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusConnectionHealth.js";
21
21
  import { EnergyAppModbusFaultTolerantReader } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusFaultTolerantReader.js";
22
22
  import { EnergyAppModbusDataTypeConverter } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusDataTypeConverter.js";
@@ -245,12 +245,21 @@ export class SunspecModbusClient {
245
245
  // announces itself twice — once by the transport, once by this client's own close/reopen —
246
246
  // and an app must not be told to re-authenticate twice for one loss.
247
247
  unitSessionReportedLost = new Set();
248
- // Model 124 InOutWRte_RvrtTms written once when a battery connects. See
249
- // setBatteryRateRevertTimeoutSeconds().
248
+ // Model 124 InOutWRte_RvrtTms written when a battery connects and re-asserted by limit writes.
249
+ // See setBatteryRateRevertTimeoutSeconds().
250
250
  batteryRateRevertTimeoutSeconds = DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS;
251
251
  // Units whose InOutWRte_RvrtTms write has already failed and been warned about. Later
252
252
  // failures on the same unit stay silent so a device without the register warns once.
253
253
  batteryRateRevertWarnedUnits = new Set();
254
+ // When InOutWRte_RvrtTms was last written, per unit — failed attempts included, so a device
255
+ // that rejects the register is retried once per interval rather than on every limit write.
256
+ // A limit write re-asserts it once this is older than BATTERY_RATE_REVERT_REASSERT_MS, or
257
+ // straight away after a readback showed a new foreign value (the entry is then dropped).
258
+ batteryRateRevertAssertedAt = new Map();
259
+ // Last RvrtTms readback that disagreed with the configured value, per unit. A device stuck on
260
+ // that value warns and triggers an immediate re-assert once; after that it waits for the
261
+ // interval, so a device that clamps or ignores the write is not rewritten on every limit.
262
+ batteryRateRevertMismatchWarned = new Map();
254
263
  constructor(
255
264
  // The host application. Only used to obtain the default Modbus backend via
256
265
  // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
@@ -595,6 +604,9 @@ export class SunspecModbusClient {
595
604
  */
596
605
  async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs, useFallbackHosts = true) {
597
606
  let candidate = null;
607
+ // Set once this attempt has failed; a connect that settles after that is nobody's socket.
608
+ let abandoned = false;
609
+ let connected = null;
598
610
  const hosts = useFallbackHosts ? this.buildConnectHosts(host) : host;
599
611
  const hostCount = Array.isArray(hosts) ? hosts.length : 1;
600
612
  // Each host in the list gets its own `timeout`; bound the whole walk at count × budget so we
@@ -604,20 +616,40 @@ export class SunspecModbusClient {
604
616
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
605
617
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
606
618
  // can still leave the returned promise pending — bound it independently.
607
- candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.useModbus().connect({
608
- host: hosts,
609
- port,
610
- unitId,
611
- timeout: connectTimeoutMs,
612
- useTls: this.connectionParams?.useTls,
613
- cert: this.connectionParams?.cert,
614
- key: this.connectionParams?.key,
615
- ca: this.connectionParams?.ca,
616
- rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
617
- noParallelRequests: this.transport.noParallelRequests,
618
- waitBetweenMessagesMs: this.transport.waitBetweenMessagesMs,
619
- pooledConnection: this.transport.pooledConnection
620
- }));
619
+ //
620
+ // Losing that race must not leak the socket: the transport does not bound a TLS
621
+ // handshake, so it can still complete after we gave up. Nobody would own that
622
+ // instance, and with a dedicated (non-pooled) connection it stays a live session on
623
+ // the device — a KOSTAL KSEM caps its Modbus/TLS clients and locks us out once enough
624
+ // timed-out attempts have piled up. Close whatever settles after the attempt failed.
625
+ candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => {
626
+ const connecting = this.useModbus().connect({
627
+ host: hosts,
628
+ port,
629
+ unitId,
630
+ timeout: connectTimeoutMs,
631
+ useTls: this.connectionParams?.useTls,
632
+ cert: this.connectionParams?.cert,
633
+ key: this.connectionParams?.key,
634
+ ca: this.connectionParams?.ca,
635
+ rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
636
+ noParallelRequests: this.transport.noParallelRequests,
637
+ waitBetweenMessagesMs: this.transport.waitBetweenMessagesMs,
638
+ pooledConnection: this.transport.pooledConnection
639
+ });
640
+ connecting.then(instance => {
641
+ if (!instance)
642
+ return;
643
+ if (!abandoned) {
644
+ connected = instance;
645
+ return;
646
+ }
647
+ console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} completed after its ` +
648
+ `${overallBudgetMs}ms budget — closing the orphaned socket`);
649
+ void this.disconnectInstanceBounded(instance, unitId);
650
+ }, () => { });
651
+ return connecting;
652
+ });
621
653
  if (!candidate) {
622
654
  throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
623
655
  }
@@ -644,8 +676,12 @@ export class SunspecModbusClient {
644
676
  this.recordOpen();
645
677
  }
646
678
  catch (err) {
647
- if (candidate) {
648
- await this.disconnectInstanceBounded(candidate, unitId);
679
+ abandoned = true;
680
+ // `connected` covers a connect that settled after the budget fired but before we got
681
+ // here; one that settles even later is closed by the handler on the connect promise.
682
+ const orphan = candidate ?? connected;
683
+ if (orphan) {
684
+ await this.disconnectInstanceBounded(orphan, unitId);
649
685
  }
650
686
  this.modbusInstances.delete(unitId);
651
687
  this.faultTolerantReaders.delete(unitId);
@@ -2458,6 +2494,7 @@ export class SunspecModbusClient {
2458
2494
  // the object across many lines; stringify keeps the whole snapshot
2459
2495
  // on one log entry so it stays grep-able and round-trippable.
2460
2496
  console.debug(`[Battery] unit=${unitId} model=124 data=${JSON.stringify(data)}`);
2497
+ this.checkBatteryRateRevertReadback(unitId, data.inOutWRteRvrtTms);
2461
2498
  return data;
2462
2499
  }
2463
2500
  else if (model.id === 802) {
@@ -2514,8 +2551,9 @@ export class SunspecModbusClient {
2514
2551
  }
2515
2552
  }
2516
2553
  /**
2517
- * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written once when the battery
2518
- * connects and once after every reconnect — e.g. 30 or 60. When no fresh rate write arrives within this window
2554
+ * Set the Model 124 `InOutWRte_RvrtTms` (seconds) written when the battery connects,
2555
+ * after every reconnect, and again by a limit write at most every
2556
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} — e.g. 30 or 60. When no fresh rate write arrives within this window
2519
2557
  * the device drops the limit and manages itself again, so a hub that goes
2520
2558
  * offline cannot leave the battery blocked. The schedule handler refreshes an
2521
2559
  * active limit every third of this value.
@@ -2534,6 +2572,8 @@ export class SunspecModbusClient {
2534
2572
  `${MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and ${MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}`);
2535
2573
  }
2536
2574
  this.batteryRateRevertTimeoutSeconds = seconds;
2575
+ // A new value is due on the next limit write, not a minute later.
2576
+ this.batteryRateRevertAssertedAt.clear();
2537
2577
  }
2538
2578
  /** Current Model 124 `InOutWRte_RvrtTms` in seconds. */
2539
2579
  getBatteryRateRevertTimeoutSeconds() {
@@ -2600,6 +2640,13 @@ export class SunspecModbusClient {
2600
2640
  // Storage control mode (Register 5) — written LAST so all
2601
2641
  // governing parameters are already in place when the device
2602
2642
  // transitions into the new mode.
2643
+ // A limit only holds as long as InOutWRte_RvrtTms allows. Re-assert our value before
2644
+ // the mode write so the new limit gets the full window — a device left on a foreign
2645
+ // value (1 s on a GEN24 in the field) drops every limit a second after each write.
2646
+ if (controls.storCtlMod !== undefined && controls.storCtlMod !== 0
2647
+ && this.isBatteryRateRevertDue(unitId)) {
2648
+ await this.writeBatteryRateRevertTimeout(unitId);
2649
+ }
2603
2650
  if (controls.storCtlMod !== undefined) {
2604
2651
  // storCtlMod = 0 is rejected with Modbus Exception code 3 (Illegal Data Value)
2605
2652
  // by some devices (e.g. Fronius GEN24). 0 means "no external control" per the
@@ -2623,8 +2670,10 @@ export class SunspecModbusClient {
2623
2670
  }
2624
2671
  /**
2625
2672
  * Write the configured InOutWRte_RvrtTms (Model 124 offset 15) to the device.
2626
- * Called once by `SunspecBattery.connect()` and once per recovered connection;
2627
- * the device keeps the value, so limit writes do not repeat it.
2673
+ * Called by `SunspecBattery.connect()`, once per recovered connection, and by
2674
+ * {@link writeBatteryControls} before a limit when the last write is older than
2675
+ * {@link BATTERY_RATE_REVERT_REASSERT_MS} or a readback disagreed. The device should keep
2676
+ * the value, but one GEN24 in the field sat on 1 s anyway.
2628
2677
  *
2629
2678
  * Never throws: a device that rejects the register still takes limits, it just
2630
2679
  * won't revert them on its own (the pre-existing behaviour). The first failure
@@ -2641,6 +2690,9 @@ export class SunspecModbusClient {
2641
2690
  return false;
2642
2691
  }
2643
2692
  const seconds = this.batteryRateRevertTimeoutSeconds;
2693
+ // Stamp the attempt, not the success: a device that rejects the register must not be
2694
+ // retried (and logged as a failed write) on every limit write.
2695
+ this.batteryRateRevertAssertedAt.set(unitId, Date.now());
2644
2696
  try {
2645
2697
  await this.writeRegisterValue(unitId, model.address + 15, seconds, 'uint16');
2646
2698
  console.log(`Unit ${unitId}: set battery rate revert timeout (InOutWRte_RvrtTms) to ${seconds}s`);
@@ -2655,6 +2707,36 @@ export class SunspecModbusClient {
2655
2707
  return false;
2656
2708
  }
2657
2709
  }
2710
+ /** Whether a limit write should re-assert InOutWRte_RvrtTms first. */
2711
+ isBatteryRateRevertDue(unitId) {
2712
+ const assertedAt = this.batteryRateRevertAssertedAt.get(unitId);
2713
+ return assertedAt === undefined || Date.now() - assertedAt >= BATTERY_RATE_REVERT_REASSERT_MS;
2714
+ }
2715
+ /**
2716
+ * Compare a Model 124 readback of InOutWRte_RvrtTms with the configured value. A mismatch
2717
+ * means our write never landed or something reset it. A new foreign value is logged once and
2718
+ * makes the next limit write re-assert immediately; if the same value is still there after
2719
+ * that, the device clamps or ignores the write and re-asserts fall back to the interval.
2720
+ */
2721
+ checkBatteryRateRevertReadback(unitId, readback) {
2722
+ if (readback === undefined)
2723
+ return;
2724
+ // Nothing written since connect or since setBatteryRateRevertTimeoutSeconds(): the device
2725
+ // still holding the old value is expected, and the next limit write asserts anyway.
2726
+ if (!this.batteryRateRevertAssertedAt.has(unitId))
2727
+ return;
2728
+ const expected = this.batteryRateRevertTimeoutSeconds;
2729
+ if (readback === expected) {
2730
+ this.batteryRateRevertMismatchWarned.delete(unitId);
2731
+ return;
2732
+ }
2733
+ if (this.batteryRateRevertMismatchWarned.get(unitId) !== readback) {
2734
+ this.batteryRateRevertMismatchWarned.set(unitId, readback);
2735
+ this.batteryRateRevertAssertedAt.delete(unitId);
2736
+ console.warn(`Unit ${unitId}: InOutWRte_RvrtTms reads ${readback}s, expected ${expected}s — ` +
2737
+ `re-asserting with the next battery limit write`);
2738
+ }
2739
+ }
2658
2740
  /**
2659
2741
  * Set battery storage mode (simplified interface)
2660
2742
  */
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 = "1.7.0";
8
+ export declare const SDK_VERSION = "1.9.0";
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 = '1.7.0';
8
+ export const SDK_VERSION = '1.9.0';
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": "1.7.0",
3
+ "version": "1.9.0",
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.3",
44
- "@enyo-energy/energy-app-sdk": "1.40.0"
44
+ "@enyo-energy/energy-app-sdk": "1.58.0"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"