@enyo-energy/sunspec-sdk 1.6.0 → 1.8.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.
@@ -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.6.0';
12
+ exports.SDK_VERSION = '1.8.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.6.0";
8
+ export declare const SDK_VERSION = "1.8.0";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
@@ -1,12 +1,14 @@
1
1
  import { BatteryCalibrator, type BatteryCalibratorOptions, type CalibrationResult } from "@enyo-energy/appliance-calibration";
2
2
  import { EnyoBatteryFeature } from "@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js";
3
3
  import { BatteryControlsClient } from "./sunspec-battery-schedule-handler.js";
4
- import { type SunspecBatteryControls, type SunspecBatteryData } from "./sunspec-interfaces.js";
4
+ import { type SunspecBatteryControls, type SunspecBatteryData, SunspecGridChargeMethod } from "./sunspec-interfaces.js";
5
5
  export interface SunspecBatteryFeatureCalibratorOptions extends BatteryCalibratorOptions<SunspecBatteryControls> {
6
6
  sunspecClient: BatteryControlsClient;
7
7
  unitId: number;
8
8
  /** Pulls the latest battery data so the orchestrator can pre-check SoC. */
9
9
  readBatteryData: () => Promise<SunspecBatteryData | null>;
10
+ /** Register form the grid-charge probe tests; must match the schedule handler's. Defaults to ChargeRateLimit. */
11
+ gridChargeMethod?: SunspecGridChargeMethod;
10
12
  }
11
13
  /**
12
14
  * SunSpec-specific calibrator that exercises each of the four controllable
@@ -48,6 +50,7 @@ export declare class SunspecBatteryFeatureCalibrator extends BatteryCalibrator<S
48
50
  private readonly sunspecClient;
49
51
  private readonly unitId;
50
52
  private readonly readBatteryData;
53
+ private readonly gridChargeMethod;
51
54
  private readonly probeConfig;
52
55
  private readonly probeClock;
53
56
  private readonly probeSnapshotService;
@@ -1,6 +1,7 @@
1
1
  import { BatteryCalibrator, DEFAULT_BATTERY_CALIBRATOR_CONFIG, } from "@enyo-energy/appliance-calibration";
2
2
  import { EnyoBatteryFeature } from "@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js";
3
- import { SUNSPEC_CONTROLLABLE_FEATURES, SunspecChargeSource, SunspecStorageControlMode, } from "./sunspec-interfaces.js";
3
+ import { gridChargeControls } from "./sunspec-battery-grid-charge.js";
4
+ import { SUNSPEC_CONTROLLABLE_FEATURES, SunspecChargeSource, SunspecGridChargeMethod, SunspecStorageControlMode, } from "./sunspec-interfaces.js";
4
5
  /**
5
6
  * SoC band each probe needs to operate in. Outside the band the probe returns
6
7
  * `not-supported` instead of running — there's no useful signal when the
@@ -53,6 +54,7 @@ export class SunspecBatteryFeatureCalibrator extends BatteryCalibrator {
53
54
  sunspecClient;
54
55
  unitId;
55
56
  readBatteryData;
57
+ gridChargeMethod;
56
58
  probeConfig;
57
59
  probeClock;
58
60
  // Local refs to the same instances the parent stores privately. We keep
@@ -67,6 +69,7 @@ export class SunspecBatteryFeatureCalibrator extends BatteryCalibrator {
67
69
  this.sunspecClient = options.sunspecClient;
68
70
  this.unitId = options.unitId;
69
71
  this.readBatteryData = options.readBatteryData;
72
+ this.gridChargeMethod = options.gridChargeMethod ?? SunspecGridChargeMethod.ChargeRateLimit;
70
73
  this.probeConfig = { ...DEFAULT_BATTERY_CALIBRATOR_CONFIG, ...options.config };
71
74
  this.probeSnapshotService = options.snapshotService;
72
75
  this.probeResultStore = options.resultStore;
@@ -157,11 +160,10 @@ export class SunspecBatteryFeatureCalibrator extends BatteryCalibrator {
157
160
  }
158
161
  const baselineBatW = this.sunspecDriver.readBatteryPowerW() ?? 0;
159
162
  const baselineGridW = this.sunspecDriver.readGridPowerW() ?? 0;
163
+ // wChaMax is lowered to the test power, so a 100 % rate charges at exactly testPowerW.
160
164
  const wrote = await this.sunspecClient.writeBatteryControls(this.unitId, {
161
- chaGriSet: SunspecChargeSource.GRID,
162
165
  wChaMax: this.probeConfig.testPowerW,
163
- inWRte: 100,
164
- storCtlMod: SunspecStorageControlMode.CHARGE,
166
+ ...gridChargeControls(this.gridChargeMethod, 100),
165
167
  });
166
168
  if (!wrote) {
167
169
  return { verdict: 'failed', note: 'writeBatteryControls returned false for grid charge' };
@@ -0,0 +1,9 @@
1
+ import { type SunspecBatteryControls, SunspecGridChargeMethod } from "./sunspec-interfaces.js";
2
+ /**
3
+ * The Model 124 register set that charges the battery from the grid at `ratePct` of `WChaMax`,
4
+ * in the form the device acts on — see {@link SunspecGridChargeMethod}. Shared by the schedule
5
+ * handler and the calibrator's grid-charge probe, so the probe tests the write production uses.
6
+ */
7
+ export declare function gridChargeControls(method: SunspecGridChargeMethod, ratePct: number): Partial<SunspecBatteryControls>;
8
+ /** The fields {@link gridChargeControls} writes, for the snapshot service's modification record. */
9
+ export declare function gridChargeFields(controls: Partial<SunspecBatteryControls>): (keyof SunspecBatteryControls)[];
@@ -0,0 +1,28 @@
1
+ import { SunspecChargeSource, SunspecGridChargeMethod, SunspecStorageControlMode, } from "./sunspec-interfaces.js";
2
+ /**
3
+ * The Model 124 register set that charges the battery from the grid at `ratePct` of `WChaMax`,
4
+ * in the form the device acts on — see {@link SunspecGridChargeMethod}. Shared by the schedule
5
+ * handler and the calibrator's grid-charge probe, so the probe tests the write production uses.
6
+ */
7
+ export function gridChargeControls(method, ratePct) {
8
+ switch (method) {
9
+ case SunspecGridChargeMethod.ChargeRateLimit:
10
+ return {
11
+ chaGriSet: SunspecChargeSource.GRID,
12
+ inWRte: ratePct,
13
+ storCtlMod: SunspecStorageControlMode.CHARGE,
14
+ };
15
+ case SunspecGridChargeMethod.NegativeDischargeRate:
16
+ return {
17
+ chaGriSet: SunspecChargeSource.GRID,
18
+ inWRte: 100,
19
+ outWRte: -ratePct,
20
+ storCtlMod: SunspecStorageControlMode.DISCHARGE,
21
+ };
22
+ }
23
+ }
24
+ /** The fields {@link gridChargeControls} writes, for the snapshot service's modification record. */
25
+ export function gridChargeFields(controls) {
26
+ const fields = ['chaGriSet', 'inWRte', 'outWRte', 'storCtlMod'];
27
+ return fields.filter(field => controls[field] !== undefined);
28
+ }
@@ -1,7 +1,7 @@
1
1
  import { StorageScheduleHandler, type ActiveStorageScheduleEntry, type StorageScheduleHandlerOptions } from "@enyo-energy/energy-app-sdk/dist/implementations/storage/storage-schedule-handler.js";
2
2
  import { type EnyoDataBusSetStorageScheduleV1 } from "@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js";
3
3
  import { type SnapshotService } from "@enyo-energy/appliance-calibration";
4
- import { type SunspecBatteryControls } from "./sunspec-interfaces.js";
4
+ import { type SunspecBatteryControls, SunspecGridChargeMethod } from "./sunspec-interfaces.js";
5
5
  /**
6
6
  * Narrow interface covering only the modbus reads/writes the schedule handler
7
7
  * needs. The full `SunspecModbusClient` structurally satisfies this; pinning
@@ -47,6 +47,8 @@ export interface SunspecBatteryScheduleHandlerOptions extends StorageScheduleHan
47
47
  /** Lazy so the snapshot service can be initialised after the handler. */
48
48
  getSnapshotService: () => BatteryModificationRecorder | undefined;
49
49
  onErrorCallback?: (err: Error) => void;
50
+ /** Register form of a Charge entry. Defaults to {@link SunspecGridChargeMethod.ChargeRateLimit}. */
51
+ gridChargeMethod?: SunspecGridChargeMethod;
50
52
  }
51
53
  /**
52
54
  * Concrete `StorageScheduleHandler` for SunSpec Model 124 batteries. The base
@@ -61,6 +63,7 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
61
63
  private readonly applianceIdForLog;
62
64
  private readonly getSnapshotService;
63
65
  private readonly onErrorCallback?;
66
+ private readonly gridChargeMethod;
64
67
  private installedWChaMax;
65
68
  /**
66
69
  * Sticky pre-schedule snapshot, captured once on the first `onInit` and
@@ -1,6 +1,7 @@
1
1
  import { StorageScheduleHandler, } from "@enyo-energy/energy-app-sdk/dist/implementations/storage/storage-schedule-handler.js";
2
2
  import { EnyoStorageScheduleDirectionEnum, EnyoStorageScheduleModeEnum, } from "@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js";
3
- import { SunspecChargeSource, SunspecStorageControlMode, } from "./sunspec-interfaces.js";
3
+ import { SunspecChargeSource, SunspecGridChargeMethod, SunspecStorageControlMode, } from "./sunspec-interfaces.js";
4
+ import { gridChargeControls, gridChargeFields } from "./sunspec-battery-grid-charge.js";
4
5
  /**
5
6
  * How often the keepalive checks whether the active limit is due a refresh.
6
7
  * The refresh itself happens every third of the revert timeout; this only
@@ -20,6 +21,7 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
20
21
  applianceIdForLog;
21
22
  getSnapshotService;
22
23
  onErrorCallback;
24
+ gridChargeMethod;
23
25
  installedWChaMax;
24
26
  /**
25
27
  * Sticky pre-schedule snapshot, captured once on the first `onInit` and
@@ -70,6 +72,7 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
70
72
  this.applianceIdForLog = opts.applianceId;
71
73
  this.getSnapshotService = opts.getSnapshotService;
72
74
  this.onErrorCallback = opts.onErrorCallback;
75
+ this.gridChargeMethod = opts.gridChargeMethod ?? SunspecGridChargeMethod.ChargeRateLimit;
73
76
  this.interval = opts.interval;
74
77
  this.clock = opts.now ?? (() => Date.now());
75
78
  }
@@ -292,12 +295,9 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
292
295
  }
293
296
  const pct = Math.min(100, Math.max(0, (powerW / baseline) * 100));
294
297
  if (direction === EnyoStorageScheduleDirectionEnum.Charge) {
295
- await this.sunspecClient.writeBatteryControls(this.unitId, {
296
- chaGriSet: SunspecChargeSource.GRID,
297
- inWRte: pct,
298
- storCtlMod: SunspecStorageControlMode.CHARGE,
299
- });
300
- await this.getSnapshotService()?.recordModification(['chaGriSet', 'inWRte', 'storCtlMod']);
298
+ const controls = gridChargeControls(this.gridChargeMethod, pct);
299
+ await this.sunspecClient.writeBatteryControls(this.unitId, controls);
300
+ await this.getSnapshotService()?.recordModification(gridChargeFields(controls));
301
301
  }
302
302
  else {
303
303
  await this.sunspecClient.writeBatteryControls(this.unitId, {
@@ -1,4 +1,4 @@
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";
1
+ import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, type SunspecInverterMetadataConfig, type SunspecBatteryConfig, 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";
@@ -557,6 +557,8 @@ export declare class SunspecBattery extends BaseSunspecDevice {
557
557
  private batteryCalibrator?;
558
558
  private calibrationResultStore?;
559
559
  private scheduleHandler;
560
+ /** Register form of a grid charge, for both the schedule handler and the calibration probe. */
561
+ private readonly gridChargeMethod;
560
562
  /**
561
563
  * Battery features that imply outbound control writes from the host action-taker.
562
564
  * These are stripped from `appliance.battery.features` until the calibration result
@@ -564,7 +566,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
564
566
  * {@link computeAdvertisedFeatures}.
565
567
  */
566
568
  private static readonly CONTROLLABLE_FEATURES;
567
- 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);
569
+ 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, config?: SunspecBatteryConfig);
568
570
  /**
569
571
  * Last known round-trip efficiency, seeded from the constructor config and replaceable at
570
572
  * runtime via {@link setRoundTripEfficiencyPercent}. Undefined = not yet known; the SDK then
@@ -587,6 +589,17 @@ export declare class SunspecBattery extends BaseSunspecDevice {
587
589
  * Spreading an explicit `undefined` would erase a value the host set elsewhere.
588
590
  */
589
591
  private configuredBatteryMetadata;
592
+ /**
593
+ * Whether the host may charge this battery from the grid. Follows the advertised
594
+ * `GridCharging` feature, NOT the live `chaGriSet` register: our own schedule handler
595
+ * writes GRID on every Charge and PV on Discharge/Auto, so the register only says
596
+ * whether we are grid-charging right now. Publishing it made the flag `false` whenever
597
+ * the pack sat on Auto (all night), and enyo-control honours an explicit `false` by
598
+ * planning no buys at all (ENY-1241). The value is always set, never omitted, because
599
+ * `updateAppliance` merges `battery` and would otherwise keep a stale `false`.
600
+ * The live register stays available through {@link isGridChargingEnabled}.
601
+ */
602
+ private gridChargingEnabled;
590
603
  /**
591
604
  * Wire the battery into `@enyo-energy/appliance-calibration`'s
592
605
  * `BatteryCalibrator` test-charge flow. Call once after {@link connect}.
@@ -1,4 +1,4 @@
1
- import { SunspecBatteryChargeState, SunspecBatteryFeatureModeKind, SunspecEnableControl, SunspecInverterCapability, SunspecPvPowerSource, SunspecPvPowerOrigin, SunspecInverterEvent1, SunspecInverterOperatingState, SunspecModelId, SunspecMPPTOperatingState, SunspecStorageMode, SUNSPEC_CONNECTION_LOST_CODE } from "./sunspec-interfaces.js";
1
+ import { SunspecBatteryChargeState, SunspecBatteryFeatureModeKind, SunspecEnableControl, SunspecInverterCapability, SunspecPvPowerSource, SunspecGridChargeMethod, SunspecPvPowerOrigin, SunspecInverterEvent1, SunspecInverterOperatingState, SunspecModelId, SunspecMPPTOperatingState, SunspecStorageMode, SUNSPEC_CONNECTION_LOST_CODE } from "./sunspec-interfaces.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { EnyoApplianceConnectionType, EnyoApplianceStateEnum, EnyoApplianceStatusEnum, EnyoApplianceTopologyFeatureEnum, EnyoApplianceTypeEnum } from "@enyo-energy/energy-app-sdk/dist/types/enyo-appliance.js";
4
4
  import { ConnectionRetryManager } from "./connection-retry-manager.js";
@@ -1507,6 +1507,14 @@ export function deriveStorageMode(controls) {
1507
1507
  if (chargeLimited && dischargeLimited && controls.inWRte === 0 && controls.outWRte === 0) {
1508
1508
  return SunspecStorageMode.HOLDING;
1509
1509
  }
1510
+ // A limit below zero reverses its direction: a negative discharge rate is a forced charge
1511
+ // (SunspecGridChargeMethod.NegativeDischargeRate), a negative charge rate a forced discharge.
1512
+ if (dischargeLimited && controls.outWRte !== undefined && controls.outWRte < 0) {
1513
+ return SunspecStorageMode.CHARGE;
1514
+ }
1515
+ if (chargeLimited && controls.inWRte !== undefined && controls.inWRte < 0) {
1516
+ return SunspecStorageMode.DISCHARGE;
1517
+ }
1510
1518
  return dischargeLimited && !chargeLimited
1511
1519
  ? SunspecStorageMode.DISCHARGE
1512
1520
  : SunspecStorageMode.CHARGE;
@@ -1529,6 +1537,8 @@ export class SunspecBattery extends BaseSunspecDevice {
1529
1537
  batteryCalibrator;
1530
1538
  calibrationResultStore;
1531
1539
  scheduleHandler;
1540
+ /** Register form of a grid charge, for both the schedule handler and the calibration probe. */
1541
+ gridChargeMethod;
1532
1542
  /**
1533
1543
  * Battery features that imply outbound control writes from the host action-taker.
1534
1544
  * These are stripped from `appliance.battery.features` until the calibration result
@@ -1542,13 +1552,14 @@ export class SunspecBattery extends BaseSunspecDevice {
1542
1552
  EnyoBatteryFeature.DischargeLimitation,
1543
1553
  ];
1544
1554
  constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, featureMode, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
1545
- // Battery facts no register carries (currently the measured round-trip efficiency).
1546
- // Forwarded onto `appliance.battery` on connect; see SunspecBatteryMetadataConfig.
1547
- metadataConfig = {}) {
1555
+ // Battery facts no register carries (forwarded onto `appliance.battery` on connect;
1556
+ // see SunspecBatteryMetadataConfig) plus how the device is driven.
1557
+ config = {}) {
1548
1558
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
1549
1559
  this.featureMode = featureMode;
1550
1560
  this.capabilities = capabilities;
1551
- this.roundTripEfficiencyPercent = metadataConfig.roundTripEfficiencyPercent;
1561
+ this.roundTripEfficiencyPercent = config.roundTripEfficiencyPercent;
1562
+ this.gridChargeMethod = config.gridChargeMethod ?? SunspecGridChargeMethod.ChargeRateLimit;
1552
1563
  }
1553
1564
  /**
1554
1565
  * Last known round-trip efficiency, seeded from the constructor config and replaceable at
@@ -1595,6 +1606,19 @@ export class SunspecBattery extends BaseSunspecDevice {
1595
1606
  ? {}
1596
1607
  : { roundTripEfficiencyPercent: this.roundTripEfficiencyPercent };
1597
1608
  }
1609
+ /**
1610
+ * Whether the host may charge this battery from the grid. Follows the advertised
1611
+ * `GridCharging` feature, NOT the live `chaGriSet` register: our own schedule handler
1612
+ * writes GRID on every Charge and PV on Discharge/Auto, so the register only says
1613
+ * whether we are grid-charging right now. Publishing it made the flag `false` whenever
1614
+ * the pack sat on Auto (all night), and enyo-control honours an explicit `false` by
1615
+ * planning no buys at all (ENY-1241). The value is always set, never omitted, because
1616
+ * `updateAppliance` merges `battery` and would otherwise keep a stale `false`.
1617
+ * The live register stays available through {@link isGridChargingEnabled}.
1618
+ */
1619
+ gridChargingEnabled(features) {
1620
+ return features.includes(EnyoBatteryFeature.GridCharging);
1621
+ }
1598
1622
  /**
1599
1623
  * Wire the battery into `@enyo-energy/appliance-calibration`'s
1600
1624
  * `BatteryCalibrator` test-charge flow. Call once after {@link connect}.
@@ -1629,6 +1653,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1629
1653
  sunspecClient: this.sunspecClient,
1630
1654
  unitId: this.unitId,
1631
1655
  readBatteryData: () => this.sunspecClient.readBatteryData(this.unitId),
1656
+ gridChargeMethod: this.gridChargeMethod,
1632
1657
  snapshotService: this.snapshotService,
1633
1658
  resultStore: opts.resultStore,
1634
1659
  config: opts.config,
@@ -1690,8 +1715,8 @@ export class SunspecBattery extends BaseSunspecDevice {
1690
1715
  throw new Error('No battery model found in device');
1691
1716
  }
1692
1717
  // Give every limit a revert timeout so a hub that goes offline cannot leave the
1693
- // battery blocked (devices ship with 0 = never revert). Written once here; the
1694
- // 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.
1695
1720
  await this.sunspecClient.writeBatteryRateRevertTimeout(this.unitId);
1696
1721
  // Get device info
1697
1722
  const commonData = await this.sunspecClient.readCommonBlock(this.unitId);
@@ -1723,7 +1748,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1723
1748
  activeChargeLimitW: activeChargeLimitW,
1724
1749
  activeDischargeLimitW: activeDischargeLimitW,
1725
1750
  features,
1726
- gridChargingEnabled: batteryData?.chaGriSet === 1,
1751
+ gridChargingEnabled: this.gridChargingEnabled(features),
1727
1752
  ...this.configuredBatteryMetadata()
1728
1753
  }
1729
1754
  });
@@ -1752,7 +1777,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1752
1777
  activeChargeLimitW: activeChargeLimitW,
1753
1778
  activeDischargeLimitW: activeDischargeLimitW,
1754
1779
  features,
1755
- gridChargingEnabled: batteryData?.chaGriSet === 1,
1780
+ gridChargingEnabled: this.gridChargingEnabled(features),
1756
1781
  ...this.configuredBatteryMetadata()
1757
1782
  }
1758
1783
  });
@@ -1921,7 +1946,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1921
1946
  activeChargeLimitW: this.computeActiveChargeLimitW(batteryData),
1922
1947
  activeDischargeLimitW: this.computeActiveDischargeLimitW(batteryData),
1923
1948
  features,
1924
- gridChargingEnabled: batteryData?.chaGriSet === 1,
1949
+ gridChargingEnabled: this.gridChargingEnabled(features),
1925
1950
  ...this.configuredBatteryMetadata()
1926
1951
  }
1927
1952
  });
@@ -2105,7 +2130,7 @@ export class SunspecBattery extends BaseSunspecDevice {
2105
2130
  }
2106
2131
  if (batteryData.inWRte >= 100)
2107
2132
  return null;
2108
- return (batteryData.wChaMax * batteryData.inWRte) / 100;
2133
+ return (batteryData.wChaMax * Math.max(0, batteryData.inWRte)) / 100;
2109
2134
  }
2110
2135
  /**
2111
2136
  * Compute the currently active discharge limit in Watts from Model 124's
@@ -2118,7 +2143,8 @@ export class SunspecBattery extends BaseSunspecDevice {
2118
2143
  }
2119
2144
  if (batteryData.outWRte >= 100)
2120
2145
  return null;
2121
- return (batteryData.wChaMax * batteryData.outWRte) / 100;
2146
+ // A negative rate is a forced charge, not a negative limit: nothing may be discharged.
2147
+ return (batteryData.wChaMax * Math.max(0, batteryData.outWRte)) / 100;
2122
2148
  }
2123
2149
  determineStorageMode(controls) {
2124
2150
  return deriveStorageMode(controls);
@@ -2160,6 +2186,7 @@ export class SunspecBattery extends BaseSunspecDevice {
2160
2186
  sunspecClient: this.sunspecClient,
2161
2187
  unitId: this.unitId,
2162
2188
  getSnapshotService: () => this.snapshotService,
2189
+ gridChargeMethod: this.gridChargeMethod,
2163
2190
  onErrorCallback: (err) => console.warn(`Battery ${this.applianceId}: schedule handler rejected input: ${err.message}`),
2164
2191
  });
2165
2192
  console.log(`Battery ${this.applianceId}: started data bus listening (listener ${this.dataBusListenerId})`);