@enyo-energy/sunspec-sdk 1.3.0 → 1.5.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.
@@ -4,6 +4,12 @@ exports.SunspecBatteryScheduleHandler = void 0;
4
4
  const storage_schedule_handler_js_1 = require("@enyo-energy/energy-app-sdk/dist/implementations/storage/storage-schedule-handler.js");
5
5
  const enyo_data_bus_value_js_1 = require("@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js");
6
6
  const sunspec_interfaces_js_1 = require("./sunspec-interfaces.cjs");
7
+ /**
8
+ * How often the keepalive checks whether the active limit is due a refresh.
9
+ * The refresh itself happens every third of the revert timeout; this only
10
+ * bounds how late it can be.
11
+ */
12
+ const KEEPALIVE_CHECK_INTERVAL = '5s';
7
13
  /**
8
14
  * Concrete `StorageScheduleHandler` for SunSpec Model 124 batteries. The base
9
15
  * class owns the data-bus subscription, the 1-second tick, schedule
@@ -41,6 +47,25 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
41
47
  * path can tell "released and gone" from "released and still live".
42
48
  */
43
49
  isDisposed = false;
50
+ clock;
51
+ /**
52
+ * The Charge / Discharge entry currently enforced on the device, kept alive
53
+ * by {@link onKeepalive}. The battery is given an InOutWRte_RvrtTms on
54
+ * connect, so the device drops a limit nobody refreshes — which is the point
55
+ * when the hub is gone, but would also end a long entry early if the hub is
56
+ * alive and simply has nothing new to send. Undefined while idle / released.
57
+ */
58
+ limitEntry;
59
+ lastLimitWriteAtMs = 0;
60
+ keepaliveIntervalId;
61
+ interval;
62
+ /**
63
+ * Every Model 124 write goes through this chain. Each write is several
64
+ * register transactions; a keepalive refresh interleaved with an entry
65
+ * transition could otherwise leave the old entry's rate under the new
66
+ * entry's mode.
67
+ */
68
+ writeChain = Promise.resolve();
44
69
  constructor(opts) {
45
70
  super(opts);
46
71
  this.sunspecClient = opts.sunspecClient;
@@ -48,6 +73,8 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
48
73
  this.applianceIdForLog = opts.applianceId;
49
74
  this.getSnapshotService = opts.getSnapshotService;
50
75
  this.onErrorCallback = opts.onErrorCallback;
76
+ this.interval = opts.interval;
77
+ this.clock = opts.now ?? (() => Date.now());
51
78
  }
52
79
  /**
53
80
  * Override the base-class data-bus router so a schedule-to-schedule
@@ -92,13 +119,14 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
92
119
  // Writing the release unconditionally is safe because it is
93
120
  // idempotent: it is exactly the register set that means
94
121
  // "no external control".
95
- await this.releaseToAuto().catch(err => {
122
+ await this.serialized(() => this.releaseToAuto()).catch(err => {
96
123
  console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: auto release failed: ${err}`);
97
124
  });
98
125
  }
99
126
  }
100
127
  dispose() {
101
128
  this.isDisposed = true;
129
+ this.stopKeepalive();
102
130
  super.dispose();
103
131
  }
104
132
  async onInit(_active) {
@@ -134,11 +162,24 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
134
162
  return { ...baseline };
135
163
  }
136
164
  onChange(active, _previous) {
137
- void this.applyEntry(active).catch(err => {
165
+ if (active.entry.direction === enyo_data_bus_value_js_1.EnyoStorageScheduleDirectionEnum.Idle) {
166
+ this.stopKeepalive();
167
+ }
168
+ else {
169
+ this.limitEntry = active;
170
+ this.lastLimitWriteAtMs = this.clock();
171
+ this.startKeepalive();
172
+ }
173
+ void this.serialized(() => this.applyEntry(active)).catch(err => {
138
174
  console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onChange write failed for entry ${active.indexInSchedule}: ${err}`);
139
175
  });
140
176
  }
141
177
  onRollback(_registers) {
178
+ // Stop refreshing in both branches. On a replacement the new schedule's
179
+ // first onChange restarts it; if that install fails instead, the old
180
+ // limit must be left to expire rather than kept alive with no schedule
181
+ // running.
182
+ this.stopKeepalive();
142
183
  if (this.suppressNextRollbackWrite) {
143
184
  // Schedule-to-schedule replacement. Do NOT write the snapshot
144
185
  // back; the new schedule's first `onChange` will own the
@@ -159,7 +200,7 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
159
200
  const chargeSource = this.originalBaseline?.chaGriSet;
160
201
  this.originalBaseline = undefined;
161
202
  this.installedWChaMax = undefined;
162
- void this.releaseToAuto(chargeSource).catch(err => {
203
+ void this.serialized(() => this.releaseToAuto(chargeSource)).catch(err => {
163
204
  console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onRollback failed: ${err}`);
164
205
  });
165
206
  }
@@ -192,6 +233,49 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
192
233
  'storCtlMod', 'chaGriSet', 'inWRte', 'outWRte',
193
234
  ]);
194
235
  }
236
+ serialized(write) {
237
+ const run = this.writeChain.then(write);
238
+ // The chain itself never rejects, so one failed write does not block the next.
239
+ this.writeChain = run.catch(() => undefined);
240
+ return run;
241
+ }
242
+ startKeepalive() {
243
+ if (this.keepaliveIntervalId === undefined) {
244
+ this.keepaliveIntervalId = this.interval.createInterval(KEEPALIVE_CHECK_INTERVAL, () => this.onKeepalive());
245
+ }
246
+ }
247
+ stopKeepalive() {
248
+ this.limitEntry = undefined;
249
+ if (this.keepaliveIntervalId !== undefined) {
250
+ this.interval.stopInterval(this.keepaliveIntervalId);
251
+ this.keepaliveIntervalId = undefined;
252
+ }
253
+ }
254
+ /**
255
+ * Rewrite the active limit every third of the revert timeout, so it outlives
256
+ * the device's InOutWRte_RvrtTms for as long as this handler is alive — and
257
+ * lapses on its own once it is not.
258
+ */
259
+ onKeepalive() {
260
+ const entry = this.limitEntry;
261
+ if (!entry || this.isDisposed || this.getActiveEntry() === undefined) {
262
+ this.stopKeepalive();
263
+ return;
264
+ }
265
+ const refreshMs = this.sunspecClient.getBatteryRateRevertTimeoutSeconds() * 1000 / 3;
266
+ if (this.clock() - this.lastLimitWriteAtMs < refreshMs) {
267
+ return;
268
+ }
269
+ this.lastLimitWriteAtMs = this.clock();
270
+ void this.serialized(async () => {
271
+ // An entry transition may have queued ahead of us; refresh only what is still active.
272
+ if (this.limitEntry !== entry)
273
+ return;
274
+ await this.applyEntry(entry);
275
+ }).catch(err => {
276
+ console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: keepalive refresh failed for entry ${entry.indexInSchedule}: ${err}`);
277
+ });
278
+ }
195
279
  onError(err) {
196
280
  this.onErrorCallback?.(err);
197
281
  }
@@ -11,6 +11,8 @@ import { type SunspecBatteryControls } from "./sunspec-interfaces.cjs";
11
11
  export interface BatteryControlsClient {
12
12
  readBatteryControls(unitId: number): Promise<SunspecBatteryControls | null>;
13
13
  writeBatteryControls(unitId: number, controls: Partial<SunspecBatteryControls>): Promise<boolean>;
14
+ /** Model 124 InOutWRte_RvrtTms the battery is configured with on connect; drives the keepalive. */
15
+ getBatteryRateRevertTimeoutSeconds(): number;
14
16
  }
15
17
  /**
16
18
  * Narrow interface for the only `SnapshotService` method the schedule handler
@@ -83,6 +85,25 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
83
85
  * path can tell "released and gone" from "released and still live".
84
86
  */
85
87
  private isDisposed;
88
+ private readonly clock;
89
+ /**
90
+ * The Charge / Discharge entry currently enforced on the device, kept alive
91
+ * by {@link onKeepalive}. The battery is given an InOutWRte_RvrtTms on
92
+ * connect, so the device drops a limit nobody refreshes — which is the point
93
+ * when the hub is gone, but would also end a long entry early if the hub is
94
+ * alive and simply has nothing new to send. Undefined while idle / released.
95
+ */
96
+ private limitEntry?;
97
+ private lastLimitWriteAtMs;
98
+ private keepaliveIntervalId?;
99
+ private readonly interval;
100
+ /**
101
+ * Every Model 124 write goes through this chain. Each write is several
102
+ * register transactions; a keepalive refresh interleaved with an entry
103
+ * transition could otherwise leave the old entry's rate under the new
104
+ * entry's mode.
105
+ */
106
+ private writeChain;
86
107
  constructor(opts: SunspecBatteryScheduleHandlerOptions);
87
108
  /**
88
109
  * Override the base-class data-bus router so a schedule-to-schedule
@@ -116,6 +137,15 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
116
137
  * since grid charging is only ever switched on by a Charge entry.
117
138
  */
118
139
  private releaseToAuto;
140
+ private serialized;
141
+ private startKeepalive;
142
+ private stopKeepalive;
143
+ /**
144
+ * Rewrite the active limit every third of the revert timeout, so it outlives
145
+ * the device's InOutWRte_RvrtTms for as long as this handler is alive — and
146
+ * lapses on its own once it is not.
147
+ */
148
+ private onKeepalive;
119
149
  protected onError(err: Error): void;
120
150
  private applyEntry;
121
151
  }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SunspecCustomDevice = exports.SunspecMeter = exports.SunspecBattery = exports.SunspecInverter = exports.BaseSunspecDevice = void 0;
4
4
  exports.detectFeaturesFromRegisters = detectFeaturesFromRegisters;
5
+ exports.ratedDischargePowerW = ratedDischargePowerW;
5
6
  exports.sumMpptBatteryPowerW = sumMpptBatteryPowerW;
6
7
  exports.selectLiveBatteryPowerW = selectLiveBatteryPowerW;
7
8
  exports.filterFeaturesByCalibrationResult = filterFeaturesByCalibrationResult;
@@ -1396,6 +1397,18 @@ function detectFeaturesFromRegisters(batteryData) {
1396
1397
  features.push(enyo_battery_appliance_js_1.EnyoBatteryFeature.GridDischarging);
1397
1398
  return features;
1398
1399
  }
1400
+ /**
1401
+ * Rated discharge power in Watts — the battery's capability, never the live
1402
+ * limit. Model 124 carries no discharge nameplate of its own, so WChaMax stands
1403
+ * in for it. OutWRte must not be folded in: it is the discharge rate the host
1404
+ * writes to cap the battery, so `WChaMax × OutWRte` turned our own "discharge
1405
+ * 0" into a rated power of 0 W, the energy manager stopped offering the
1406
+ * battery, and nothing ever lifted the cap again. The live cap is reported
1407
+ * separately as `activeDischargeLimitW`.
1408
+ */
1409
+ function ratedDischargePowerW(batteryData) {
1410
+ return batteryData?.wChaMax;
1411
+ }
1399
1412
  /**
1400
1413
  * Apply the per-feature calibration filter to a register-detected set.
1401
1414
  * Exported for unit-test access to the legacy-result fallback branch.
@@ -1687,6 +1700,10 @@ class SunspecBattery extends BaseSunspecDevice {
1687
1700
  if (!this.hasRequiredModels()) {
1688
1701
  throw new Error('No battery model found in device');
1689
1702
  }
1703
+ // Give every limit a revert timeout so a hub that goes offline cannot leave the
1704
+ // battery blocked (devices ship with 0 = never revert). Written once here; the
1705
+ // schedule handler refreshes active limits inside this window.
1706
+ await this.sunspecClient.writeBatteryRateRevertTimeout(this.unitId);
1690
1707
  // Get device info
1691
1708
  const commonData = await this.sunspecClient.readCommonBlock(this.unitId);
1692
1709
  const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
@@ -1713,7 +1730,7 @@ class SunspecBattery extends BaseSunspecDevice {
1713
1730
  connectedToApplianceId: inverterApplianceId,
1714
1731
  storageMode: this.mapToEnyoStorageMode(storageMode),
1715
1732
  maxChargingPowerW: batteryData?.wChaMax,
1716
- maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1733
+ maxDischargePowerW: ratedDischargePowerW(batteryData),
1717
1734
  activeChargeLimitW: activeChargeLimitW,
1718
1735
  activeDischargeLimitW: activeDischargeLimitW,
1719
1736
  features,
@@ -1742,7 +1759,7 @@ class SunspecBattery extends BaseSunspecDevice {
1742
1759
  connectedToApplianceId: inverterApplianceId,
1743
1760
  storageMode: this.mapToEnyoStorageMode(storageMode),
1744
1761
  maxChargingPowerW: batteryData?.wChaMax,
1745
- maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1762
+ maxDischargePowerW: ratedDischargePowerW(batteryData),
1746
1763
  activeChargeLimitW: activeChargeLimitW,
1747
1764
  activeDischargeLimitW: activeDischargeLimitW,
1748
1765
  features,
@@ -1758,6 +1775,15 @@ class SunspecBattery extends BaseSunspecDevice {
1758
1775
  }
1759
1776
  this.startDataBusListening();
1760
1777
  }
1778
+ /**
1779
+ * Re-apply the rate revert timeout once per recovered connection. An outage long
1780
+ * enough to need a reconnect may be the inverter rebooting, and nothing guarantees
1781
+ * the register survives that. Runs after reconnect revalidation, so Model 124 has
1782
+ * been rediscovered and the new socket is in place.
1783
+ */
1784
+ async onConnectionRestored() {
1785
+ await this.sunspecClient.writeBatteryRateRevertTimeout(this.unitId);
1786
+ }
1761
1787
  async disconnect() {
1762
1788
  this.stopDataBusListening();
1763
1789
  if (this.calibrationDriver) {
@@ -1902,7 +1928,7 @@ class SunspecBattery extends BaseSunspecDevice {
1902
1928
  ...appliance?.battery,
1903
1929
  storageMode: this.mapToEnyoStorageMode(storageMode),
1904
1930
  maxChargingPowerW: batteryData?.wChaMax,
1905
- maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1931
+ maxDischargePowerW: ratedDischargePowerW(batteryData),
1906
1932
  activeChargeLimitW: this.computeActiveChargeLimitW(batteryData),
1907
1933
  activeDischargeLimitW: this.computeActiveDischargeLimitW(batteryData),
1908
1934
  features,
@@ -465,6 +465,16 @@ export declare class SunspecInverter extends BaseSunspecDevice {
465
465
  * control is available; the inverter decides where it goes)
466
466
  */
467
467
  export declare function detectFeaturesFromRegisters(batteryData: SunspecBatteryData | null): EnyoBatteryFeature[];
468
+ /**
469
+ * Rated discharge power in Watts — the battery's capability, never the live
470
+ * limit. Model 124 carries no discharge nameplate of its own, so WChaMax stands
471
+ * in for it. OutWRte must not be folded in: it is the discharge rate the host
472
+ * writes to cap the battery, so `WChaMax × OutWRte` turned our own "discharge
473
+ * 0" into a rated power of 0 W, the energy manager stopped offering the
474
+ * battery, and nothing ever lifted the cap again. The live cap is reported
475
+ * separately as `activeDischargeLimitW`.
476
+ */
477
+ export declare function ratedDischargePowerW(batteryData: SunspecBatteryData | null | undefined): number | undefined;
468
478
  /**
469
479
  * Apply the per-feature calibration filter to a register-detected set.
470
480
  * Exported for unit-test access to the legacy-result fallback branch.
@@ -617,6 +627,13 @@ export declare class SunspecBattery extends BaseSunspecDevice {
617
627
  * Connect to the battery and create/update the appliance
618
628
  */
619
629
  connect(inverterApplianceId?: string): Promise<void>;
630
+ /**
631
+ * Re-apply the rate revert timeout once per recovered connection. An outage long
632
+ * enough to need a reconnect may be the inverter rebooting, and nothing guarantees
633
+ * the register survives that. Runs after reconnect revalidation, so Model 124 has
634
+ * been rediscovered and the new socket is in place.
635
+ */
636
+ protected onConnectionRestored(): Promise<void>;
620
637
  disconnect(): Promise<void>;
621
638
  /**
622
639
  * Map SunSpec battery charge state to Enyo battery state
@@ -3,7 +3,7 @@
3
3
  * SunSpec block interfaces with block numbers
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SUNSPEC_CONTROLLABLE_FEATURES = exports.SunspecMeterCapability = exports.SunspecBatteryFeatureModeKind = exports.SunspecBatteryCapability = exports.SunspecPvPowerOrigin = exports.SunspecPvPowerSource = exports.SunspecInverterCapability = exports.SunspecStorageMode = exports.SunspecChargeSource = exports.SunspecVArPctMode = exports.SunspecEnableControl = exports.SunspecConnectionControl = exports.SunspecStorageControlMode = exports.SunspecBatteryEvent1 = exports.SunspecBatteryBankState = exports.SunspecBatteryType = exports.SunspecBatteryControlMode = exports.SunspecBatteryChargeState = exports.SunspecInverterOperatingState = exports.SunspecMPPTOperatingState = exports.SUNSPEC_CONNECTION_LOST_CODE = exports.SunspecInverterEvent1 = exports.SunspecModelId = exports.DEFAULT_MODBUS_RESILIENCE_CONFIG = exports.DEFAULT_RETRY_CONFIG = void 0;
6
+ exports.SUNSPEC_CONTROLLABLE_FEATURES = exports.SunspecMeterCapability = exports.SunspecBatteryFeatureModeKind = 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;
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: [
@@ -228,6 +228,28 @@ var SunspecStorageControlMode;
228
228
  // Note: Higher bits may control other modes like autonomous/self-consumption
229
229
  // but these are device-specific and not standardized in SunSpec
230
230
  })(SunspecStorageControlMode || (exports.SunspecStorageControlMode = SunspecStorageControlMode = {}));
231
+ /**
232
+ * Default for Model 124 `InOutWRte_RvrtTms` (offset 15), written once when the
233
+ * battery connects. After this many seconds without a fresh rate write the device
234
+ * drops the InWRte / OutWRte setpoint and goes back to managing itself, so a hub
235
+ * that dies mid-schedule cannot leave the battery blocked. 0 on the device means
236
+ * "never revert", which is exactly the stuck state this guards against.
237
+ *
238
+ * Long enough to cover several refreshes by the schedule handler (it rewrites the
239
+ * active limit every third of the timeout), short enough that a dead hub is
240
+ * noticed within a couple of minutes.
241
+ */
242
+ exports.DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 90;
243
+ /**
244
+ * Lower bound for the configurable revert timeout. Below this a single slow
245
+ * Modbus round-trip or a missed refresh lets the limit lapse mid-entry.
246
+ */
247
+ exports.MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
248
+ /**
249
+ * Upper bound: InOutWRte_RvrtTms is a uint16 and 0xFFFF is the SunSpec
250
+ * "not implemented" marker.
251
+ */
252
+ exports.MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 0xFFFE;
231
253
  /**
232
254
  * Enum values for connection control
233
255
  */
@@ -533,6 +533,28 @@ export declare enum SunspecStorageControlMode {
533
533
  CHARGE = 1,// Bit 0 - the InWRte charge-rate setpoint is active
534
534
  DISCHARGE = 2
535
535
  }
536
+ /**
537
+ * Default for Model 124 `InOutWRte_RvrtTms` (offset 15), written once when the
538
+ * battery connects. After this many seconds without a fresh rate write the device
539
+ * drops the InWRte / OutWRte setpoint and goes back to managing itself, so a hub
540
+ * that dies mid-schedule cannot leave the battery blocked. 0 on the device means
541
+ * "never revert", which is exactly the stuck state this guards against.
542
+ *
543
+ * Long enough to cover several refreshes by the schedule handler (it rewrites the
544
+ * active limit every third of the timeout), short enough that a dead hub is
545
+ * noticed within a couple of minutes.
546
+ */
547
+ export declare const DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 90;
548
+ /**
549
+ * Lower bound for the configurable revert timeout. Below this a single slow
550
+ * Modbus round-trip or a missed refresh lets the limit lapse mid-entry.
551
+ */
552
+ export declare const MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
553
+ /**
554
+ * Upper bound: InOutWRte_RvrtTms is a uint16 and 0xFFFF is the SunSpec
555
+ * "not implemented" marker.
556
+ */
557
+ export declare const MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 65534;
536
558
  /**
537
559
  * Battery data structure based on Model 124 (Basic Storage Controls)
538
560
  *
@@ -254,6 +254,12 @@ 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().
259
+ batteryRateRevertTimeoutSeconds = sunspec_interfaces_js_1.DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS;
260
+ // Units whose InOutWRte_RvrtTms write has already failed and been warned about. Later
261
+ // failures on the same unit stay silent so a device without the register warns once.
262
+ batteryRateRevertWarnedUnits = new Set();
257
263
  constructor(
258
264
  // The host application. Only used to obtain the default Modbus backend via
259
265
  // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
@@ -2516,6 +2522,32 @@ class SunspecModbusClient {
2516
2522
  return null;
2517
2523
  }
2518
2524
  }
2525
+ /**
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
2528
+ * the device drops the limit and manages itself again, so a hub that goes
2529
+ * offline cannot leave the battery blocked. The schedule handler refreshes an
2530
+ * active limit every third of this value.
2531
+ *
2532
+ * Call before `SunspecBattery.connect()`; a later change only reaches the
2533
+ * device on the next {@link writeBatteryRateRevertTimeout}. Must be an integer between
2534
+ * {@link MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and
2535
+ * {@link MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}; 0 ("never revert") is
2536
+ * deliberately not accepted.
2537
+ */
2538
+ setBatteryRateRevertTimeoutSeconds(seconds) {
2539
+ if (!Number.isInteger(seconds)
2540
+ || seconds < sunspec_interfaces_js_1.MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS
2541
+ || seconds > sunspec_interfaces_js_1.MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS) {
2542
+ throw new Error(`setBatteryRateRevertTimeoutSeconds: ${seconds} must be an integer between ` +
2543
+ `${sunspec_interfaces_js_1.MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and ${sunspec_interfaces_js_1.MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}`);
2544
+ }
2545
+ this.batteryRateRevertTimeoutSeconds = seconds;
2546
+ }
2547
+ /** Current Model 124 `InOutWRte_RvrtTms` in seconds. */
2548
+ getBatteryRateRevertTimeoutSeconds() {
2549
+ return this.batteryRateRevertTimeoutSeconds;
2550
+ }
2519
2551
  /**
2520
2552
  * Write battery control settings to Model 124
2521
2553
  */
@@ -2598,6 +2630,40 @@ class SunspecModbusClient {
2598
2630
  return false;
2599
2631
  }
2600
2632
  }
2633
+ /**
2634
+ * 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.
2637
+ *
2638
+ * Never throws: a device that rejects the register still takes limits, it just
2639
+ * won't revert them on its own (the pre-existing behaviour). The first failure
2640
+ * per unit is warned about, later ones are silent.
2641
+ *
2642
+ * @returns true when the value was written; false when the unit has no Model 124
2643
+ * or the write failed.
2644
+ */
2645
+ async writeBatteryRateRevertTimeout(unitId) {
2646
+ const model = this.findModel(unitId, sunspec_interfaces_js_1.SunspecModelId.Battery);
2647
+ if (!model) {
2648
+ // 802-only batteries have no Model 124 and therefore nothing to revert.
2649
+ console.debug(`Battery model 124 not found on unit ${unitId}, skipping InOutWRte_RvrtTms`);
2650
+ return false;
2651
+ }
2652
+ const seconds = this.batteryRateRevertTimeoutSeconds;
2653
+ try {
2654
+ await this.writeRegisterValue(unitId, model.address + 15, seconds, 'uint16');
2655
+ console.log(`Unit ${unitId}: set battery rate revert timeout (InOutWRte_RvrtTms) to ${seconds}s`);
2656
+ return true;
2657
+ }
2658
+ catch (error) {
2659
+ if (!this.batteryRateRevertWarnedUnits.has(unitId)) {
2660
+ this.batteryRateRevertWarnedUnits.add(unitId);
2661
+ console.warn(`Unit ${unitId}: writing InOutWRte_RvrtTms=${seconds}s failed, battery limits will not ` +
2662
+ `auto-revert on this device: ${error instanceof Error ? error.message : String(error)}`);
2663
+ }
2664
+ return false;
2665
+ }
2666
+ }
2601
2667
  /**
2602
2668
  * Set battery storage mode (simplified interface)
2603
2669
  */
@@ -139,6 +139,8 @@ export declare class SunspecModbusClient {
139
139
  private unitReconnectUnsubscribers;
140
140
  private unitsWithSession;
141
141
  private unitSessionReportedLost;
142
+ private batteryRateRevertTimeoutSeconds;
143
+ private batteryRateRevertWarnedUnits;
142
144
  constructor(energyApp: EnergyApp | undefined, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
143
145
  /**
144
146
  * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
@@ -674,10 +676,39 @@ export declare class SunspecModbusClient {
674
676
  * Read battery data from Model 124 (Basic Storage) with fallback to Model 802 / Model 803
675
677
  */
676
678
  readBatteryData(unitId: number): Promise<SunspecBatteryData | null>;
679
+ /**
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
+ * the device drops the limit and manages itself again, so a hub that goes
683
+ * offline cannot leave the battery blocked. The schedule handler refreshes an
684
+ * active limit every third of this value.
685
+ *
686
+ * Call before `SunspecBattery.connect()`; a later change only reaches the
687
+ * device on the next {@link writeBatteryRateRevertTimeout}. Must be an integer between
688
+ * {@link MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and
689
+ * {@link MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}; 0 ("never revert") is
690
+ * deliberately not accepted.
691
+ */
692
+ setBatteryRateRevertTimeoutSeconds(seconds: number): void;
693
+ /** Current Model 124 `InOutWRte_RvrtTms` in seconds. */
694
+ getBatteryRateRevertTimeoutSeconds(): number;
677
695
  /**
678
696
  * Write battery control settings to Model 124
679
697
  */
680
698
  writeBatteryControls(unitId: number, controls: Partial<SunspecBatteryControls>): Promise<boolean>;
699
+ /**
700
+ * 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.
703
+ *
704
+ * Never throws: a device that rejects the register still takes limits, it just
705
+ * won't revert them on its own (the pre-existing behaviour). The first failure
706
+ * per unit is warned about, later ones are silent.
707
+ *
708
+ * @returns true when the value was written; false when the unit has no Model 124
709
+ * or the write failed.
710
+ */
711
+ writeBatteryRateRevertTimeout(unitId: number): Promise<boolean>;
681
712
  /**
682
713
  * Set battery storage mode (simplified interface)
683
714
  */
@@ -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.3.0';
12
+ exports.SDK_VERSION = '1.5.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.3.0";
8
+ export declare const SDK_VERSION = "1.5.0";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
@@ -11,6 +11,8 @@ import { type SunspecBatteryControls } from "./sunspec-interfaces.js";
11
11
  export interface BatteryControlsClient {
12
12
  readBatteryControls(unitId: number): Promise<SunspecBatteryControls | null>;
13
13
  writeBatteryControls(unitId: number, controls: Partial<SunspecBatteryControls>): Promise<boolean>;
14
+ /** Model 124 InOutWRte_RvrtTms the battery is configured with on connect; drives the keepalive. */
15
+ getBatteryRateRevertTimeoutSeconds(): number;
14
16
  }
15
17
  /**
16
18
  * Narrow interface for the only `SnapshotService` method the schedule handler
@@ -83,6 +85,25 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
83
85
  * path can tell "released and gone" from "released and still live".
84
86
  */
85
87
  private isDisposed;
88
+ private readonly clock;
89
+ /**
90
+ * The Charge / Discharge entry currently enforced on the device, kept alive
91
+ * by {@link onKeepalive}. The battery is given an InOutWRte_RvrtTms on
92
+ * connect, so the device drops a limit nobody refreshes — which is the point
93
+ * when the hub is gone, but would also end a long entry early if the hub is
94
+ * alive and simply has nothing new to send. Undefined while idle / released.
95
+ */
96
+ private limitEntry?;
97
+ private lastLimitWriteAtMs;
98
+ private keepaliveIntervalId?;
99
+ private readonly interval;
100
+ /**
101
+ * Every Model 124 write goes through this chain. Each write is several
102
+ * register transactions; a keepalive refresh interleaved with an entry
103
+ * transition could otherwise leave the old entry's rate under the new
104
+ * entry's mode.
105
+ */
106
+ private writeChain;
86
107
  constructor(opts: SunspecBatteryScheduleHandlerOptions);
87
108
  /**
88
109
  * Override the base-class data-bus router so a schedule-to-schedule
@@ -116,6 +137,15 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
116
137
  * since grid charging is only ever switched on by a Charge entry.
117
138
  */
118
139
  private releaseToAuto;
140
+ private serialized;
141
+ private startKeepalive;
142
+ private stopKeepalive;
143
+ /**
144
+ * Rewrite the active limit every third of the revert timeout, so it outlives
145
+ * the device's InOutWRte_RvrtTms for as long as this handler is alive — and
146
+ * lapses on its own once it is not.
147
+ */
148
+ private onKeepalive;
119
149
  protected onError(err: Error): void;
120
150
  private applyEntry;
121
151
  }
@@ -1,6 +1,12 @@
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
3
  import { SunspecChargeSource, SunspecStorageControlMode, } from "./sunspec-interfaces.js";
4
+ /**
5
+ * How often the keepalive checks whether the active limit is due a refresh.
6
+ * The refresh itself happens every third of the revert timeout; this only
7
+ * bounds how late it can be.
8
+ */
9
+ const KEEPALIVE_CHECK_INTERVAL = '5s';
4
10
  /**
5
11
  * Concrete `StorageScheduleHandler` for SunSpec Model 124 batteries. The base
6
12
  * class owns the data-bus subscription, the 1-second tick, schedule
@@ -38,6 +44,25 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
38
44
  * path can tell "released and gone" from "released and still live".
39
45
  */
40
46
  isDisposed = false;
47
+ clock;
48
+ /**
49
+ * The Charge / Discharge entry currently enforced on the device, kept alive
50
+ * by {@link onKeepalive}. The battery is given an InOutWRte_RvrtTms on
51
+ * connect, so the device drops a limit nobody refreshes — which is the point
52
+ * when the hub is gone, but would also end a long entry early if the hub is
53
+ * alive and simply has nothing new to send. Undefined while idle / released.
54
+ */
55
+ limitEntry;
56
+ lastLimitWriteAtMs = 0;
57
+ keepaliveIntervalId;
58
+ interval;
59
+ /**
60
+ * Every Model 124 write goes through this chain. Each write is several
61
+ * register transactions; a keepalive refresh interleaved with an entry
62
+ * transition could otherwise leave the old entry's rate under the new
63
+ * entry's mode.
64
+ */
65
+ writeChain = Promise.resolve();
41
66
  constructor(opts) {
42
67
  super(opts);
43
68
  this.sunspecClient = opts.sunspecClient;
@@ -45,6 +70,8 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
45
70
  this.applianceIdForLog = opts.applianceId;
46
71
  this.getSnapshotService = opts.getSnapshotService;
47
72
  this.onErrorCallback = opts.onErrorCallback;
73
+ this.interval = opts.interval;
74
+ this.clock = opts.now ?? (() => Date.now());
48
75
  }
49
76
  /**
50
77
  * Override the base-class data-bus router so a schedule-to-schedule
@@ -89,13 +116,14 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
89
116
  // Writing the release unconditionally is safe because it is
90
117
  // idempotent: it is exactly the register set that means
91
118
  // "no external control".
92
- await this.releaseToAuto().catch(err => {
119
+ await this.serialized(() => this.releaseToAuto()).catch(err => {
93
120
  console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: auto release failed: ${err}`);
94
121
  });
95
122
  }
96
123
  }
97
124
  dispose() {
98
125
  this.isDisposed = true;
126
+ this.stopKeepalive();
99
127
  super.dispose();
100
128
  }
101
129
  async onInit(_active) {
@@ -131,11 +159,24 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
131
159
  return { ...baseline };
132
160
  }
133
161
  onChange(active, _previous) {
134
- void this.applyEntry(active).catch(err => {
162
+ if (active.entry.direction === EnyoStorageScheduleDirectionEnum.Idle) {
163
+ this.stopKeepalive();
164
+ }
165
+ else {
166
+ this.limitEntry = active;
167
+ this.lastLimitWriteAtMs = this.clock();
168
+ this.startKeepalive();
169
+ }
170
+ void this.serialized(() => this.applyEntry(active)).catch(err => {
135
171
  console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onChange write failed for entry ${active.indexInSchedule}: ${err}`);
136
172
  });
137
173
  }
138
174
  onRollback(_registers) {
175
+ // Stop refreshing in both branches. On a replacement the new schedule's
176
+ // first onChange restarts it; if that install fails instead, the old
177
+ // limit must be left to expire rather than kept alive with no schedule
178
+ // running.
179
+ this.stopKeepalive();
139
180
  if (this.suppressNextRollbackWrite) {
140
181
  // Schedule-to-schedule replacement. Do NOT write the snapshot
141
182
  // back; the new schedule's first `onChange` will own the
@@ -156,7 +197,7 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
156
197
  const chargeSource = this.originalBaseline?.chaGriSet;
157
198
  this.originalBaseline = undefined;
158
199
  this.installedWChaMax = undefined;
159
- void this.releaseToAuto(chargeSource).catch(err => {
200
+ void this.serialized(() => this.releaseToAuto(chargeSource)).catch(err => {
160
201
  console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onRollback failed: ${err}`);
161
202
  });
162
203
  }
@@ -189,6 +230,49 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
189
230
  'storCtlMod', 'chaGriSet', 'inWRte', 'outWRte',
190
231
  ]);
191
232
  }
233
+ serialized(write) {
234
+ const run = this.writeChain.then(write);
235
+ // The chain itself never rejects, so one failed write does not block the next.
236
+ this.writeChain = run.catch(() => undefined);
237
+ return run;
238
+ }
239
+ startKeepalive() {
240
+ if (this.keepaliveIntervalId === undefined) {
241
+ this.keepaliveIntervalId = this.interval.createInterval(KEEPALIVE_CHECK_INTERVAL, () => this.onKeepalive());
242
+ }
243
+ }
244
+ stopKeepalive() {
245
+ this.limitEntry = undefined;
246
+ if (this.keepaliveIntervalId !== undefined) {
247
+ this.interval.stopInterval(this.keepaliveIntervalId);
248
+ this.keepaliveIntervalId = undefined;
249
+ }
250
+ }
251
+ /**
252
+ * Rewrite the active limit every third of the revert timeout, so it outlives
253
+ * the device's InOutWRte_RvrtTms for as long as this handler is alive — and
254
+ * lapses on its own once it is not.
255
+ */
256
+ onKeepalive() {
257
+ const entry = this.limitEntry;
258
+ if (!entry || this.isDisposed || this.getActiveEntry() === undefined) {
259
+ this.stopKeepalive();
260
+ return;
261
+ }
262
+ const refreshMs = this.sunspecClient.getBatteryRateRevertTimeoutSeconds() * 1000 / 3;
263
+ if (this.clock() - this.lastLimitWriteAtMs < refreshMs) {
264
+ return;
265
+ }
266
+ this.lastLimitWriteAtMs = this.clock();
267
+ void this.serialized(async () => {
268
+ // An entry transition may have queued ahead of us; refresh only what is still active.
269
+ if (this.limitEntry !== entry)
270
+ return;
271
+ await this.applyEntry(entry);
272
+ }).catch(err => {
273
+ console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: keepalive refresh failed for entry ${entry.indexInSchedule}: ${err}`);
274
+ });
275
+ }
192
276
  onError(err) {
193
277
  this.onErrorCallback?.(err);
194
278
  }
@@ -465,6 +465,16 @@ export declare class SunspecInverter extends BaseSunspecDevice {
465
465
  * control is available; the inverter decides where it goes)
466
466
  */
467
467
  export declare function detectFeaturesFromRegisters(batteryData: SunspecBatteryData | null): EnyoBatteryFeature[];
468
+ /**
469
+ * Rated discharge power in Watts — the battery's capability, never the live
470
+ * limit. Model 124 carries no discharge nameplate of its own, so WChaMax stands
471
+ * in for it. OutWRte must not be folded in: it is the discharge rate the host
472
+ * writes to cap the battery, so `WChaMax × OutWRte` turned our own "discharge
473
+ * 0" into a rated power of 0 W, the energy manager stopped offering the
474
+ * battery, and nothing ever lifted the cap again. The live cap is reported
475
+ * separately as `activeDischargeLimitW`.
476
+ */
477
+ export declare function ratedDischargePowerW(batteryData: SunspecBatteryData | null | undefined): number | undefined;
468
478
  /**
469
479
  * Apply the per-feature calibration filter to a register-detected set.
470
480
  * Exported for unit-test access to the legacy-result fallback branch.
@@ -617,6 +627,13 @@ export declare class SunspecBattery extends BaseSunspecDevice {
617
627
  * Connect to the battery and create/update the appliance
618
628
  */
619
629
  connect(inverterApplianceId?: string): Promise<void>;
630
+ /**
631
+ * Re-apply the rate revert timeout once per recovered connection. An outage long
632
+ * enough to need a reconnect may be the inverter rebooting, and nothing guarantees
633
+ * the register survives that. Runs after reconnect revalidation, so Model 124 has
634
+ * been rediscovered and the new socket is in place.
635
+ */
636
+ protected onConnectionRestored(): Promise<void>;
620
637
  disconnect(): Promise<void>;
621
638
  /**
622
639
  * Map SunSpec battery charge state to Enyo battery state
@@ -1386,6 +1386,18 @@ export function detectFeaturesFromRegisters(batteryData) {
1386
1386
  features.push(EnyoBatteryFeature.GridDischarging);
1387
1387
  return features;
1388
1388
  }
1389
+ /**
1390
+ * Rated discharge power in Watts — the battery's capability, never the live
1391
+ * limit. Model 124 carries no discharge nameplate of its own, so WChaMax stands
1392
+ * in for it. OutWRte must not be folded in: it is the discharge rate the host
1393
+ * writes to cap the battery, so `WChaMax × OutWRte` turned our own "discharge
1394
+ * 0" into a rated power of 0 W, the energy manager stopped offering the
1395
+ * battery, and nothing ever lifted the cap again. The live cap is reported
1396
+ * separately as `activeDischargeLimitW`.
1397
+ */
1398
+ export function ratedDischargePowerW(batteryData) {
1399
+ return batteryData?.wChaMax;
1400
+ }
1389
1401
  /**
1390
1402
  * Apply the per-feature calibration filter to a register-detected set.
1391
1403
  * Exported for unit-test access to the legacy-result fallback branch.
@@ -1677,6 +1689,10 @@ export class SunspecBattery extends BaseSunspecDevice {
1677
1689
  if (!this.hasRequiredModels()) {
1678
1690
  throw new Error('No battery model found in device');
1679
1691
  }
1692
+ // 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.
1695
+ await this.sunspecClient.writeBatteryRateRevertTimeout(this.unitId);
1680
1696
  // Get device info
1681
1697
  const commonData = await this.sunspecClient.readCommonBlock(this.unitId);
1682
1698
  const batteryData = await this.sunspecClient.readBatteryData(this.unitId);
@@ -1703,7 +1719,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1703
1719
  connectedToApplianceId: inverterApplianceId,
1704
1720
  storageMode: this.mapToEnyoStorageMode(storageMode),
1705
1721
  maxChargingPowerW: batteryData?.wChaMax,
1706
- maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1722
+ maxDischargePowerW: ratedDischargePowerW(batteryData),
1707
1723
  activeChargeLimitW: activeChargeLimitW,
1708
1724
  activeDischargeLimitW: activeDischargeLimitW,
1709
1725
  features,
@@ -1732,7 +1748,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1732
1748
  connectedToApplianceId: inverterApplianceId,
1733
1749
  storageMode: this.mapToEnyoStorageMode(storageMode),
1734
1750
  maxChargingPowerW: batteryData?.wChaMax,
1735
- maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1751
+ maxDischargePowerW: ratedDischargePowerW(batteryData),
1736
1752
  activeChargeLimitW: activeChargeLimitW,
1737
1753
  activeDischargeLimitW: activeDischargeLimitW,
1738
1754
  features,
@@ -1748,6 +1764,15 @@ export class SunspecBattery extends BaseSunspecDevice {
1748
1764
  }
1749
1765
  this.startDataBusListening();
1750
1766
  }
1767
+ /**
1768
+ * Re-apply the rate revert timeout once per recovered connection. An outage long
1769
+ * enough to need a reconnect may be the inverter rebooting, and nothing guarantees
1770
+ * the register survives that. Runs after reconnect revalidation, so Model 124 has
1771
+ * been rediscovered and the new socket is in place.
1772
+ */
1773
+ async onConnectionRestored() {
1774
+ await this.sunspecClient.writeBatteryRateRevertTimeout(this.unitId);
1775
+ }
1751
1776
  async disconnect() {
1752
1777
  this.stopDataBusListening();
1753
1778
  if (this.calibrationDriver) {
@@ -1892,7 +1917,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1892
1917
  ...appliance?.battery,
1893
1918
  storageMode: this.mapToEnyoStorageMode(storageMode),
1894
1919
  maxChargingPowerW: batteryData?.wChaMax,
1895
- maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1920
+ maxDischargePowerW: ratedDischargePowerW(batteryData),
1896
1921
  activeChargeLimitW: this.computeActiveChargeLimitW(batteryData),
1897
1922
  activeDischargeLimitW: this.computeActiveDischargeLimitW(batteryData),
1898
1923
  features,
@@ -533,6 +533,28 @@ export declare enum SunspecStorageControlMode {
533
533
  CHARGE = 1,// Bit 0 - the InWRte charge-rate setpoint is active
534
534
  DISCHARGE = 2
535
535
  }
536
+ /**
537
+ * Default for Model 124 `InOutWRte_RvrtTms` (offset 15), written once when the
538
+ * battery connects. After this many seconds without a fresh rate write the device
539
+ * drops the InWRte / OutWRte setpoint and goes back to managing itself, so a hub
540
+ * that dies mid-schedule cannot leave the battery blocked. 0 on the device means
541
+ * "never revert", which is exactly the stuck state this guards against.
542
+ *
543
+ * Long enough to cover several refreshes by the schedule handler (it rewrites the
544
+ * active limit every third of the timeout), short enough that a dead hub is
545
+ * noticed within a couple of minutes.
546
+ */
547
+ export declare const DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 90;
548
+ /**
549
+ * Lower bound for the configurable revert timeout. Below this a single slow
550
+ * Modbus round-trip or a missed refresh lets the limit lapse mid-entry.
551
+ */
552
+ export declare const MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
553
+ /**
554
+ * Upper bound: InOutWRte_RvrtTms is a uint16 and 0xFFFF is the SunSpec
555
+ * "not implemented" marker.
556
+ */
557
+ export declare const MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 65534;
536
558
  /**
537
559
  * Battery data structure based on Model 124 (Basic Storage Controls)
538
560
  *
@@ -225,6 +225,28 @@ export var SunspecStorageControlMode;
225
225
  // Note: Higher bits may control other modes like autonomous/self-consumption
226
226
  // but these are device-specific and not standardized in SunSpec
227
227
  })(SunspecStorageControlMode || (SunspecStorageControlMode = {}));
228
+ /**
229
+ * Default for Model 124 `InOutWRte_RvrtTms` (offset 15), written once when the
230
+ * battery connects. After this many seconds without a fresh rate write the device
231
+ * drops the InWRte / OutWRte setpoint and goes back to managing itself, so a hub
232
+ * that dies mid-schedule cannot leave the battery blocked. 0 on the device means
233
+ * "never revert", which is exactly the stuck state this guards against.
234
+ *
235
+ * Long enough to cover several refreshes by the schedule handler (it rewrites the
236
+ * active limit every third of the timeout), short enough that a dead hub is
237
+ * noticed within a couple of minutes.
238
+ */
239
+ export const DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 90;
240
+ /**
241
+ * Lower bound for the configurable revert timeout. Below this a single slow
242
+ * Modbus round-trip or a missed refresh lets the limit lapse mid-entry.
243
+ */
244
+ export const MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 15;
245
+ /**
246
+ * Upper bound: InOutWRte_RvrtTms is a uint16 and 0xFFFF is the SunSpec
247
+ * "not implemented" marker.
248
+ */
249
+ export const MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS = 0xFFFE;
228
250
  /**
229
251
  * Enum values for connection control
230
252
  */
@@ -139,6 +139,8 @@ export declare class SunspecModbusClient {
139
139
  private unitReconnectUnsubscribers;
140
140
  private unitsWithSession;
141
141
  private unitSessionReportedLost;
142
+ private batteryRateRevertTimeoutSeconds;
143
+ private batteryRateRevertWarnedUnits;
142
144
  constructor(energyApp: EnergyApp | undefined, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
143
145
  /**
144
146
  * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
@@ -674,10 +676,39 @@ export declare class SunspecModbusClient {
674
676
  * Read battery data from Model 124 (Basic Storage) with fallback to Model 802 / Model 803
675
677
  */
676
678
  readBatteryData(unitId: number): Promise<SunspecBatteryData | null>;
679
+ /**
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
+ * the device drops the limit and manages itself again, so a hub that goes
683
+ * offline cannot leave the battery blocked. The schedule handler refreshes an
684
+ * active limit every third of this value.
685
+ *
686
+ * Call before `SunspecBattery.connect()`; a later change only reaches the
687
+ * device on the next {@link writeBatteryRateRevertTimeout}. Must be an integer between
688
+ * {@link MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and
689
+ * {@link MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}; 0 ("never revert") is
690
+ * deliberately not accepted.
691
+ */
692
+ setBatteryRateRevertTimeoutSeconds(seconds: number): void;
693
+ /** Current Model 124 `InOutWRte_RvrtTms` in seconds. */
694
+ getBatteryRateRevertTimeoutSeconds(): number;
677
695
  /**
678
696
  * Write battery control settings to Model 124
679
697
  */
680
698
  writeBatteryControls(unitId: number, controls: Partial<SunspecBatteryControls>): Promise<boolean>;
699
+ /**
700
+ * 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.
703
+ *
704
+ * Never throws: a device that rejects the register still takes limits, it just
705
+ * won't revert them on its own (the pre-existing behaviour). The first failure
706
+ * per unit is warned about, later ones are silent.
707
+ *
708
+ * @returns true when the value was written; false when the unit has no Model 124
709
+ * or the write failed.
710
+ */
711
+ writeBatteryRateRevertTimeout(unitId: number): Promise<boolean>;
681
712
  /**
682
713
  * Set battery storage mode (simplified interface)
683
714
  */
@@ -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, } from "./sunspec-interfaces.js";
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";
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,6 +245,12 @@ 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().
250
+ batteryRateRevertTimeoutSeconds = DEFAULT_BATTERY_RATE_REVERT_TIMEOUT_SECONDS;
251
+ // Units whose InOutWRte_RvrtTms write has already failed and been warned about. Later
252
+ // failures on the same unit stay silent so a device without the register warns once.
253
+ batteryRateRevertWarnedUnits = new Set();
248
254
  constructor(
249
255
  // The host application. Only used to obtain the default Modbus backend via
250
256
  // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
@@ -2507,6 +2513,32 @@ export class SunspecModbusClient {
2507
2513
  return null;
2508
2514
  }
2509
2515
  }
2516
+ /**
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
2519
+ * the device drops the limit and manages itself again, so a hub that goes
2520
+ * offline cannot leave the battery blocked. The schedule handler refreshes an
2521
+ * active limit every third of this value.
2522
+ *
2523
+ * Call before `SunspecBattery.connect()`; a later change only reaches the
2524
+ * device on the next {@link writeBatteryRateRevertTimeout}. Must be an integer between
2525
+ * {@link MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and
2526
+ * {@link MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}; 0 ("never revert") is
2527
+ * deliberately not accepted.
2528
+ */
2529
+ setBatteryRateRevertTimeoutSeconds(seconds) {
2530
+ if (!Number.isInteger(seconds)
2531
+ || seconds < MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS
2532
+ || seconds > MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS) {
2533
+ throw new Error(`setBatteryRateRevertTimeoutSeconds: ${seconds} must be an integer between ` +
2534
+ `${MIN_BATTERY_RATE_REVERT_TIMEOUT_SECONDS} and ${MAX_BATTERY_RATE_REVERT_TIMEOUT_SECONDS}`);
2535
+ }
2536
+ this.batteryRateRevertTimeoutSeconds = seconds;
2537
+ }
2538
+ /** Current Model 124 `InOutWRte_RvrtTms` in seconds. */
2539
+ getBatteryRateRevertTimeoutSeconds() {
2540
+ return this.batteryRateRevertTimeoutSeconds;
2541
+ }
2510
2542
  /**
2511
2543
  * Write battery control settings to Model 124
2512
2544
  */
@@ -2589,6 +2621,40 @@ export class SunspecModbusClient {
2589
2621
  return false;
2590
2622
  }
2591
2623
  }
2624
+ /**
2625
+ * 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.
2628
+ *
2629
+ * Never throws: a device that rejects the register still takes limits, it just
2630
+ * won't revert them on its own (the pre-existing behaviour). The first failure
2631
+ * per unit is warned about, later ones are silent.
2632
+ *
2633
+ * @returns true when the value was written; false when the unit has no Model 124
2634
+ * or the write failed.
2635
+ */
2636
+ async writeBatteryRateRevertTimeout(unitId) {
2637
+ const model = this.findModel(unitId, SunspecModelId.Battery);
2638
+ if (!model) {
2639
+ // 802-only batteries have no Model 124 and therefore nothing to revert.
2640
+ console.debug(`Battery model 124 not found on unit ${unitId}, skipping InOutWRte_RvrtTms`);
2641
+ return false;
2642
+ }
2643
+ const seconds = this.batteryRateRevertTimeoutSeconds;
2644
+ try {
2645
+ await this.writeRegisterValue(unitId, model.address + 15, seconds, 'uint16');
2646
+ console.log(`Unit ${unitId}: set battery rate revert timeout (InOutWRte_RvrtTms) to ${seconds}s`);
2647
+ return true;
2648
+ }
2649
+ catch (error) {
2650
+ if (!this.batteryRateRevertWarnedUnits.has(unitId)) {
2651
+ this.batteryRateRevertWarnedUnits.add(unitId);
2652
+ console.warn(`Unit ${unitId}: writing InOutWRte_RvrtTms=${seconds}s failed, battery limits will not ` +
2653
+ `auto-revert on this device: ${error instanceof Error ? error.message : String(error)}`);
2654
+ }
2655
+ return false;
2656
+ }
2657
+ }
2592
2658
  /**
2593
2659
  * Set battery storage mode (simplified interface)
2594
2660
  */
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.3.0";
8
+ export declare const SDK_VERSION = "1.5.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.3.0';
8
+ export const SDK_VERSION = '1.5.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.3.0",
3
+ "version": "1.5.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.27.0"
44
+ "@enyo-energy/energy-app-sdk": "1.31.0"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"