@enyo-energy/sunspec-sdk 0.0.103 → 0.0.105

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.
package/dist/index.d.ts CHANGED
@@ -7,5 +7,6 @@ export { SunspecCalibrationStorage, createSunspecCalibrationStorage } from './su
7
7
  export { SunspecBatteryCalibrationDriver } from './sunspec-battery-calibration-driver.js';
8
8
  export { SunspecBatteryFeatureCalibrator, type SunspecBatteryFeatureCalibratorOptions, decodeFeatureResults, } from './sunspec-battery-feature-calibrator.js';
9
9
  export { SunspecBatteryScheduleHandler, type SunspecScheduleRegisters, type SunspecBatteryScheduleHandlerOptions, } from './sunspec-battery-schedule-handler.js';
10
+ export { type EnergyAppModbus, type EnergyAppModbusInstance, type ModbusOptions, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
10
11
  export { type EnyoDataBusSetStorageScheduleV1, type EnyoStorageScheduleEntry, EnyoStorageScheduleModeEnum, EnyoStorageScheduleDirectionEnum, } from '@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js';
11
12
  export { AbstractCalibrationStorage, InMemoryCalibrationStorage, type AckResult, type CalibrationResult, type CalibrationState, type CalibrationSnapshot, type CalibrationRestoreCallback, type RestoreReason, SnapshotService, type SnapshotServiceOptions, DEFAULT_AUTO_STOP_MS, AbstractBatteryCalibrationDriver, BatteryCalibrator, type BatteryCalibratorOptions, type BatteryCalibratorConfig, DEFAULT_BATTERY_CALIBRATOR_CONFIG, CalibrationResultStore, type CalibrationResultStoreData, CalibrationTrigger, type CalibrationTriggerOptions, } from '@enyo-energy/appliance-calibration';
@@ -19,9 +19,10 @@ export interface BatteryControlsClient {
19
19
  */
20
20
  export type BatteryModificationRecorder = Pick<SnapshotService<SunspecBatteryControls>, 'recordModification'>;
21
21
  /**
22
- * Snapshot of the writable Model 124 registers taken at schedule install time
23
- * and handed back to `onRollback` when the schedule completes, is replaced, or
24
- * is restored after a process restart. JSON-serialisable because
22
+ * Snapshot of the writable Model 124 registers taken at schedule install time.
23
+ * The base library hands it back to `onRollback`, but the release path does not
24
+ * replay it — see `releaseToAuto`. It survives as the record of the installed
25
+ * `wChaMax` and the pre-schedule charge source. JSON-serialisable because
25
26
  * `EnergyAppStorage` round-trips it.
26
27
  *
27
28
  * The snapshotted `wChaMax` doubles as the denominator for the `inWRte` /
@@ -63,8 +64,9 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
63
64
  * Sticky pre-schedule snapshot, captured once on the first `onInit` and
64
65
  * held across every subsequent schedule-to-schedule replacement. Cleared
65
66
  * only when a real rollback fires (`mode: auto` from the data bus or
66
- * `dispose`). Lets the eventual restore write the *true* baseline rather
67
- * than the last-active-entry register set that the device happens to be
67
+ * `dispose`). Supplies the `wChaMax` denominator for the percentage math
68
+ * and the charge source to hand back on release — taken from the *original*
69
+ * pre-schedule read rather than the register set the device happens to be
68
70
  * in at the moment of replacement.
69
71
  */
70
72
  private originalBaseline?;
@@ -76,6 +78,11 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
76
78
  * write the snapshot back during a replacement.
77
79
  */
78
80
  private suppressNextRollbackWrite;
81
+ /**
82
+ * Mirrors the base class's private `disposed` flag so the auto-release
83
+ * path can tell "released and gone" from "released and still live".
84
+ */
85
+ private isDisposed;
79
86
  constructor(opts: SunspecBatteryScheduleHandlerOptions);
80
87
  /**
81
88
  * Override the base-class data-bus router so a schedule-to-schedule
@@ -86,9 +93,29 @@ export declare class SunspecBatteryScheduleHandler extends StorageScheduleHandle
86
93
  * normally there.
87
94
  */
88
95
  applyMessage(msg: EnyoDataBusSetStorageScheduleV1): Promise<void>;
96
+ dispose(): void;
89
97
  protected onInit(_active: ActiveStorageScheduleEntry): Promise<SunspecScheduleRegisters>;
90
98
  protected onChange(active: ActiveStorageScheduleEntry, _previous: ActiveStorageScheduleEntry | undefined): void;
91
- protected onRollback(registers: SunspecScheduleRegisters): void;
99
+ protected onRollback(_registers: SunspecScheduleRegisters): void;
100
+ /**
101
+ * Hand the battery back to its own logic: clear StorCtl_Mod and open both
102
+ * rate setpoints back up to 100 %.
103
+ *
104
+ * This deliberately does *not* replay the snapshot captured at `onInit`.
105
+ * That snapshot is whatever the registers happened to hold when the
106
+ * schedule started — and if a previous schedule had already stranded a
107
+ * limit there, restoring it re-latches the limit and the battery can never
108
+ * climb out. The only correct end state for "we are no longer controlling
109
+ * this battery" is the one written here, and it is the same set of
110
+ * registers a schedule entry touches, so nothing else is left dangling.
111
+ *
112
+ * `wChaMax` is not restored because a schedule never writes it — the
113
+ * percentage math divides against it instead.
114
+ *
115
+ * @param chargeSource - `chaGriSet` to restore; falls back to PV-only,
116
+ * since grid charging is only ever switched on by a Charge entry.
117
+ */
118
+ private releaseToAuto;
92
119
  protected onError(err: Error): void;
93
120
  private applyEntry;
94
121
  }
@@ -19,8 +19,9 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
19
19
  * Sticky pre-schedule snapshot, captured once on the first `onInit` and
20
20
  * held across every subsequent schedule-to-schedule replacement. Cleared
21
21
  * only when a real rollback fires (`mode: auto` from the data bus or
22
- * `dispose`). Lets the eventual restore write the *true* baseline rather
23
- * than the last-active-entry register set that the device happens to be
22
+ * `dispose`). Supplies the `wChaMax` denominator for the percentage math
23
+ * and the charge source to hand back on release — taken from the *original*
24
+ * pre-schedule read rather than the register set the device happens to be
24
25
  * in at the moment of replacement.
25
26
  */
26
27
  originalBaseline;
@@ -32,6 +33,11 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
32
33
  * write the snapshot back during a replacement.
33
34
  */
34
35
  suppressNextRollbackWrite = false;
36
+ /**
37
+ * Mirrors the base class's private `disposed` flag so the auto-release
38
+ * path can tell "released and gone" from "released and still live".
39
+ */
40
+ isDisposed = false;
35
41
  constructor(opts) {
36
42
  super(opts);
37
43
  this.sunspecClient = opts.sunspecClient;
@@ -49,11 +55,15 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
49
55
  * normally there.
50
56
  */
51
57
  async applyMessage(msg) {
52
- if (msg.applianceId === this.applianceIdForLog
58
+ const isForThisAppliance = msg.applianceId === this.applianceIdForLog;
59
+ if (isForThisAppliance
53
60
  && msg.data.mode === EnyoStorageScheduleModeEnum.Schedule
54
61
  && this.getActiveEntry() !== undefined) {
55
62
  this.suppressNextRollbackWrite = true;
56
63
  }
64
+ // Captured before the base class runs: with a schedule active, its
65
+ // `doReleaseSchedule → onRollback` already performs the auto release.
66
+ const hadActiveSchedule = this.getActiveEntry() !== undefined;
57
67
  try {
58
68
  await super.applyMessage(msg);
59
69
  }
@@ -63,6 +73,30 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
63
73
  // otherwise stay set and silently swallow the next real rollback.
64
74
  this.suppressNextRollbackWrite = false;
65
75
  }
76
+ if (isForThisAppliance
77
+ && msg.data.mode === EnyoStorageScheduleModeEnum.Auto
78
+ && !hadActiveSchedule
79
+ && !this.isDisposed) {
80
+ // `mode: auto` with no schedule running is a no-op in the base
81
+ // library (`doReleaseSchedule` returns early when idle), so nothing
82
+ // would reach the device. That is not harmless: Model 124 setpoints
83
+ // latch — an interrupted schedule (modbus drop, package restart)
84
+ // leaves StorCtl_Mod and InWRte set, and with InOutWRte_RvrtTms = 0
85
+ // the inverter never reverts on its own. Seen in production as a
86
+ // battery pinned at ~2 % charge rate for hours while the energy
87
+ // manager sent `auto` every 40 s and got an `Accepted` back.
88
+ //
89
+ // Writing the release unconditionally is safe because it is
90
+ // idempotent: it is exactly the register set that means
91
+ // "no external control".
92
+ await this.releaseToAuto().catch(err => {
93
+ console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: auto release failed: ${err}`);
94
+ });
95
+ }
96
+ }
97
+ dispose() {
98
+ this.isDisposed = true;
99
+ super.dispose();
66
100
  }
67
101
  async onInit(_active) {
68
102
  if (this.originalBaseline !== undefined) {
@@ -101,7 +135,7 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
101
135
  console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onChange write failed for entry ${active.indexInSchedule}: ${err}`);
102
136
  });
103
137
  }
104
- onRollback(registers) {
138
+ onRollback(_registers) {
105
139
  if (this.suppressNextRollbackWrite) {
106
140
  // Schedule-to-schedule replacement. Do NOT write the snapshot
107
141
  // back; the new schedule's first `onChange` will own the
@@ -119,19 +153,41 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
119
153
  // that follows — so a concurrent `onInit` queued behind this one
120
154
  // (impossible today, but defensive) cannot observe a half-cleared
121
155
  // state.
156
+ const chargeSource = this.originalBaseline?.chaGriSet;
122
157
  this.originalBaseline = undefined;
123
158
  this.installedWChaMax = undefined;
124
- void (async () => {
125
- try {
126
- await this.sunspecClient.writeBatteryControls(this.unitId, registers);
127
- await this.getSnapshotService()?.recordModification([
128
- 'storCtlMod', 'chaGriSet', 'wChaMax', 'inWRte', 'outWRte',
129
- ]);
130
- }
131
- catch (err) {
132
- console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onRollback failed: ${err}`);
133
- }
134
- })();
159
+ void this.releaseToAuto(chargeSource).catch(err => {
160
+ console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onRollback failed: ${err}`);
161
+ });
162
+ }
163
+ /**
164
+ * Hand the battery back to its own logic: clear StorCtl_Mod and open both
165
+ * rate setpoints back up to 100 %.
166
+ *
167
+ * This deliberately does *not* replay the snapshot captured at `onInit`.
168
+ * That snapshot is whatever the registers happened to hold when the
169
+ * schedule started — and if a previous schedule had already stranded a
170
+ * limit there, restoring it re-latches the limit and the battery can never
171
+ * climb out. The only correct end state for "we are no longer controlling
172
+ * this battery" is the one written here, and it is the same set of
173
+ * registers a schedule entry touches, so nothing else is left dangling.
174
+ *
175
+ * `wChaMax` is not restored because a schedule never writes it — the
176
+ * percentage math divides against it instead.
177
+ *
178
+ * @param chargeSource - `chaGriSet` to restore; falls back to PV-only,
179
+ * since grid charging is only ever switched on by a Charge entry.
180
+ */
181
+ async releaseToAuto(chargeSource) {
182
+ await this.sunspecClient.writeBatteryControls(this.unitId, {
183
+ storCtlMod: SunspecStorageControlMode.NONE,
184
+ chaGriSet: chargeSource ?? SunspecChargeSource.PV,
185
+ inWRte: 100,
186
+ outWRte: 100,
187
+ });
188
+ await this.getSnapshotService()?.recordModification([
189
+ 'storCtlMod', 'chaGriSet', 'inWRte', 'outWRte',
190
+ ]);
135
191
  }
136
192
  onError(err) {
137
193
  this.onErrorCallback?.(err);
@@ -139,19 +195,11 @@ export class SunspecBatteryScheduleHandler extends StorageScheduleHandler {
139
195
  async applyEntry(active) {
140
196
  const { direction, powerW } = active.entry;
141
197
  if (direction === EnyoStorageScheduleDirectionEnum.Idle) {
142
- // Idle entry: hand the battery back to its own autonomous logic
143
- // by restoring the snapshotted pre-schedule registers (same write
144
- // set as the `mode: auto` rollback path). The schedule itself
145
- // keeps running, so a subsequent Charge / Discharge entry can
146
- // resume external control.
147
- const baselineRegisters = this.originalBaseline;
148
- if (!baselineRegisters) {
149
- throw new Error(`no usable baseline for idle entry (originalBaseline=undefined)`);
150
- }
151
- await this.sunspecClient.writeBatteryControls(this.unitId, baselineRegisters);
152
- await this.getSnapshotService()?.recordModification([
153
- 'storCtlMod', 'chaGriSet', 'wChaMax', 'inWRte', 'outWRte',
154
- ]);
198
+ // Idle entry: hand the battery back to its own autonomous logic —
199
+ // the same release the `mode: auto` path performs. The schedule
200
+ // itself keeps running, so a subsequent Charge / Discharge entry
201
+ // can resume external control.
202
+ await this.releaseToAuto(this.originalBaseline?.chaGriSet);
155
203
  return;
156
204
  }
157
205
  const baseline = this.installedWChaMax;
@@ -510,6 +510,21 @@ export declare function filterFeaturesByCalibrationResult(detected: EnyoBatteryF
510
510
  /**
511
511
  * Sunspec Battery implementation
512
512
  */
513
+ /**
514
+ * Derive the storage mode from Model 124's StorCtl_Mod bitfield.
515
+ *
516
+ * The bits mark *which rate setpoint the device is enforcing* — bit 0 for
517
+ * InWRte, bit 1 for OutWRte — not which direction is permitted. So no bit set
518
+ * is the autonomous mode, and both bits set is the most externally controlled
519
+ * state there is, which is the opposite of what the naming suggests. Reading
520
+ * them the other way round meant a battery running its own logic reported
521
+ * `holding`, a fully clamped one reported `auto`, and no appliance could ever
522
+ * report that it had been handed back to itself.
523
+ *
524
+ * @param controls - Model 124 control registers, or null when unreadable.
525
+ * @returns The mode, or null when StorCtl_Mod could not be read.
526
+ */
527
+ export declare function deriveStorageMode(controls: SunspecBatteryControls | null): SunspecStorageMode | null;
513
528
  export declare class SunspecBattery extends BaseSunspecDevice {
514
529
  private readonly featureMode;
515
530
  private readonly capabilities;
@@ -1425,6 +1425,37 @@ export function filterFeaturesByCalibrationResult(detected, result, controllable
1425
1425
  /**
1426
1426
  * Sunspec Battery implementation
1427
1427
  */
1428
+ /**
1429
+ * Derive the storage mode from Model 124's StorCtl_Mod bitfield.
1430
+ *
1431
+ * The bits mark *which rate setpoint the device is enforcing* — bit 0 for
1432
+ * InWRte, bit 1 for OutWRte — not which direction is permitted. So no bit set
1433
+ * is the autonomous mode, and both bits set is the most externally controlled
1434
+ * state there is, which is the opposite of what the naming suggests. Reading
1435
+ * them the other way round meant a battery running its own logic reported
1436
+ * `holding`, a fully clamped one reported `auto`, and no appliance could ever
1437
+ * report that it had been handed back to itself.
1438
+ *
1439
+ * @param controls - Model 124 control registers, or null when unreadable.
1440
+ * @returns The mode, or null when StorCtl_Mod could not be read.
1441
+ */
1442
+ export function deriveStorageMode(controls) {
1443
+ if (!controls || controls.storCtlMod === undefined) {
1444
+ return null;
1445
+ }
1446
+ const chargeLimited = (controls.storCtlMod & 0x0001) !== 0;
1447
+ const dischargeLimited = (controls.storCtlMod & 0x0002) !== 0;
1448
+ if (!chargeLimited && !dischargeLimited) {
1449
+ return SunspecStorageMode.AUTO;
1450
+ }
1451
+ // Both directions clamped to zero — the battery is parked, not idling.
1452
+ if (chargeLimited && dischargeLimited && controls.inWRte === 0 && controls.outWRte === 0) {
1453
+ return SunspecStorageMode.HOLDING;
1454
+ }
1455
+ return dischargeLimited && !chargeLimited
1456
+ ? SunspecStorageMode.DISCHARGE
1457
+ : SunspecStorageMode.CHARGE;
1458
+ }
1428
1459
  export class SunspecBattery extends BaseSunspecDevice {
1429
1460
  featureMode;
1430
1461
  capabilities;
@@ -1579,7 +1610,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1579
1610
  battery: {
1580
1611
  connectedToApplianceId: inverterApplianceId,
1581
1612
  storageMode: this.mapToEnyoStorageMode(storageMode),
1582
- maxChargingPowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.inWRte !== undefined ? batteryData.wChaMax * batteryData.inWRte : undefined,
1613
+ maxChargingPowerW: batteryData?.wChaMax,
1583
1614
  maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1584
1615
  activeChargeLimitW: activeChargeLimitW,
1585
1616
  activeDischargeLimitW: activeDischargeLimitW,
@@ -1607,7 +1638,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1607
1638
  ...existingAppliance?.battery,
1608
1639
  connectedToApplianceId: inverterApplianceId,
1609
1640
  storageMode: this.mapToEnyoStorageMode(storageMode),
1610
- maxChargingPowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.inWRte !== undefined ? batteryData.wChaMax * batteryData.inWRte : undefined,
1641
+ maxChargingPowerW: batteryData?.wChaMax,
1611
1642
  maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1612
1643
  activeChargeLimitW: activeChargeLimitW,
1613
1644
  activeDischargeLimitW: activeDischargeLimitW,
@@ -1766,7 +1797,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1766
1797
  battery: {
1767
1798
  ...appliance?.battery,
1768
1799
  storageMode: this.mapToEnyoStorageMode(storageMode),
1769
- maxChargingPowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.inWRte !== undefined ? batteryData.wChaMax * batteryData.inWRte : undefined,
1800
+ maxChargingPowerW: batteryData?.wChaMax,
1770
1801
  maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
1771
1802
  activeChargeLimitW: this.computeActiveChargeLimitW(batteryData),
1772
1803
  activeDischargeLimitW: this.computeActiveDischargeLimitW(batteryData),
@@ -1970,23 +2001,7 @@ export class SunspecBattery extends BaseSunspecDevice {
1970
2001
  return (batteryData.wChaMax * batteryData.outWRte) / 100;
1971
2002
  }
1972
2003
  determineStorageMode(controls) {
1973
- if (!controls || controls.storCtlMod === undefined) {
1974
- return null;
1975
- }
1976
- const chargeEnabled = (controls.storCtlMod & 0x0001) !== 0;
1977
- const dischargeEnabled = (controls.storCtlMod & 0x0002) !== 0;
1978
- if (chargeEnabled && dischargeEnabled) {
1979
- return SunspecStorageMode.AUTO;
1980
- }
1981
- else if (chargeEnabled && !dischargeEnabled) {
1982
- return SunspecStorageMode.CHARGE;
1983
- }
1984
- else if (!chargeEnabled && dischargeEnabled) {
1985
- return SunspecStorageMode.DISCHARGE;
1986
- }
1987
- else {
1988
- return SunspecStorageMode.HOLDING;
1989
- }
2004
+ return deriveStorageMode(controls);
1990
2005
  }
1991
2006
  /**
1992
2007
  * Check if grid charging is enabled
@@ -503,7 +503,14 @@ export declare enum SunspecBatteryEvent1 {
503
503
  * - To ensure external control works properly, the appropriate bits must be set
504
504
  */
505
505
  export declare enum SunspecStorageControlMode {
506
- CHARGE = 1,// Bit 0 - Enable charge mode (allow external charge control)
506
+ /**
507
+ * No bit set — no external setpoint is active and the battery runs its own
508
+ * autonomous logic. This, not `CHARGE | DISCHARGE`, is what "auto" means on
509
+ * Model 124: the bits say *which rate setpoint is being enforced*, so
510
+ * clearing them is what hands control back to the device.
511
+ */
512
+ NONE = 0,
513
+ CHARGE = 1,// Bit 0 - the InWRte charge-rate setpoint is active
507
514
  DISCHARGE = 2
508
515
  }
509
516
  /**
@@ -778,9 +785,9 @@ export declare enum SunspecChargeSource {
778
785
  * Storage modes for simplified battery control
779
786
  */
780
787
  export declare enum SunspecStorageMode {
781
- CHARGE = "charge",// Allow charging only
782
- DISCHARGE = "discharge",// Allow discharging only
783
- HOLDING = "holding",// No charge or discharge (holding mode)
788
+ CHARGE = "charge",// Charging is externally rate-limited via InWRte
789
+ DISCHARGE = "discharge",// Discharging is externally rate-limited via OutWRte
790
+ HOLDING = "holding",// Both directions clamped to 0 % — battery is parked
784
791
  AUTO = "auto"
785
792
  }
786
793
  /**
@@ -213,8 +213,15 @@ export var SunspecBatteryEvent1;
213
213
  */
214
214
  export var SunspecStorageControlMode;
215
215
  (function (SunspecStorageControlMode) {
216
+ /**
217
+ * No bit set — no external setpoint is active and the battery runs its own
218
+ * autonomous logic. This, not `CHARGE | DISCHARGE`, is what "auto" means on
219
+ * Model 124: the bits say *which rate setpoint is being enforced*, so
220
+ * clearing them is what hands control back to the device.
221
+ */
222
+ SunspecStorageControlMode[SunspecStorageControlMode["NONE"] = 0] = "NONE";
216
223
  SunspecStorageControlMode[SunspecStorageControlMode["CHARGE"] = 1] = "CHARGE";
217
- SunspecStorageControlMode[SunspecStorageControlMode["DISCHARGE"] = 2] = "DISCHARGE"; // Bit 1 - Enable discharge mode (allow external discharge control)
224
+ SunspecStorageControlMode[SunspecStorageControlMode["DISCHARGE"] = 2] = "DISCHARGE"; // Bit 1 - the OutWRte discharge-rate setpoint is active
218
225
  // Note: Higher bits may control other modes like autonomous/self-consumption
219
226
  // but these are device-specific and not standardized in SunSpec
220
227
  })(SunspecStorageControlMode || (SunspecStorageControlMode = {}));
@@ -259,7 +266,7 @@ export var SunspecStorageMode;
259
266
  SunspecStorageMode["CHARGE"] = "charge";
260
267
  SunspecStorageMode["DISCHARGE"] = "discharge";
261
268
  SunspecStorageMode["HOLDING"] = "holding";
262
- SunspecStorageMode["AUTO"] = "auto"; // Both charge and discharge allowed
269
+ SunspecStorageMode["AUTO"] = "auto"; // No external setpoint active (StorCtl_Mod = 0)
263
270
  })(SunspecStorageMode || (SunspecStorageMode = {}));
264
271
  /**
265
272
  * Battery control structure for writing to Model 124
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.js";
20
20
  import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
21
- import { EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
21
+ import { EnergyAppModbus, EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
22
22
  import { EnergyApp } from "@enyo-energy/energy-app-sdk";
23
23
  /**
24
24
  * Thrown when a single Modbus transaction (read/write/connect/disconnect) exceeds its configured
@@ -34,11 +34,15 @@ export declare class ModbusOperationTimeoutError extends Error {
34
34
  * Get (or create) the singleton SunspecModbusClient for this network device.
35
35
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
36
36
  *
37
- * NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
38
- * host:port. Because the client is cached and refcounted, a later caller passing different config
39
- * receives the already-created instance and its config is ignored.
37
+ * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
38
+ * created for a given host:port. Because the client is cached and refcounted, a later caller
39
+ * passing different config receives the already-created instance and its config is ignored.
40
+ *
41
+ * `modbusFactory` lets a caller supply their own Modbus backend (the factory whose `connect()`
42
+ * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
43
+ * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
40
44
  */
41
- export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig): SunspecModbusClient;
45
+ export declare function getOrCreateSunspecClient(energyApp: EnergyApp | undefined, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus): SunspecModbusClient;
42
46
  /**
43
47
  * Release a refcount on the network-device client. When the last consumer releases,
44
48
  * the client is fully disconnected (all units closed) and removed from the registry.
@@ -63,6 +67,7 @@ export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts:
63
67
  export declare class SunspecModbusClient {
64
68
  private energyApp;
65
69
  private pacing;
70
+ private modbusFactory?;
66
71
  private modbusInstances;
67
72
  private faultTolerantReaders;
68
73
  private discoveredModelsByUnit;
@@ -79,7 +84,13 @@ export declare class SunspecModbusClient {
79
84
  private resilience;
80
85
  private poisonedUnits;
81
86
  private lastOkAtByUnit;
82
- constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig);
87
+ constructor(energyApp: EnergyApp | undefined, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
88
+ /**
89
+ * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
90
+ * if one was given, otherwise the host application's default (`energyApp.useModbus()`). The
91
+ * constructor guarantees at least one of the two is present.
92
+ */
93
+ private useModbus;
83
94
  /**
84
95
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
85
96
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -46,15 +46,19 @@ const registryKey = (host, port) => `${host}:${port}`;
46
46
  * Get (or create) the singleton SunspecModbusClient for this network device.
47
47
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
48
48
  *
49
- * NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
50
- * host:port. Because the client is cached and refcounted, a later caller passing different config
51
- * receives the already-created instance and its config is ignored.
49
+ * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
50
+ * created for a given host:port. Because the client is cached and refcounted, a later caller
51
+ * passing different config receives the already-created instance and its config is ignored.
52
+ *
53
+ * `modbusFactory` lets a caller supply their own Modbus backend (the factory whose `connect()`
54
+ * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
55
+ * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
52
56
  */
53
- export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience) {
57
+ export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience, modbusFactory) {
54
58
  const key = registryKey(host, port);
55
59
  let entry = CLIENT_REGISTRY.get(key);
56
60
  if (!entry) {
57
- entry = { client: new SunspecModbusClient(energyApp, pacing, resilience), refcount: 0 };
61
+ entry = { client: new SunspecModbusClient(energyApp, pacing, resilience, modbusFactory), refcount: 0 };
58
62
  CLIENT_REGISTRY.set(key, entry);
59
63
  }
60
64
  entry.refcount++;
@@ -120,6 +124,7 @@ export async function retryAsync(fn, opts) {
120
124
  export class SunspecModbusClient {
121
125
  energyApp;
122
126
  pacing;
127
+ modbusFactory;
123
128
  // Per-unit Modbus instance/reader/discovered-models maps. One client = one network device,
124
129
  // many unit IDs share that client (each unit ID is one EnergyAppModbusInstance underneath).
125
130
  modbusInstances = new Map();
@@ -163,20 +168,47 @@ export class SunspecModbusClient {
163
168
  // the transport still reports connected but that has gone quiet past staleSocketMs is presumed
164
169
  // dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
165
170
  lastOkAtByUnit = new Map();
166
- constructor(energyApp,
171
+ constructor(
172
+ // The host application. Only used to obtain the default Modbus backend via
173
+ // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
174
+ energyApp,
167
175
  // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
168
176
  // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
169
177
  // connection. An empty object leaves both undefined so the SDK applies its own defaults.
170
178
  pacing = {},
171
179
  // Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
172
180
  // so omitted fields keep their defaults.
173
- resilience = {}) {
181
+ resilience = {},
182
+ // Optional custom Modbus backend. When provided, its `connect()` is used to open every
183
+ // per-unit connection instead of `energyApp.useModbus()` — letting callers plug in their own
184
+ // Modbus implementation (a mock for tests, or an alternative transport). All the resilience
185
+ // machinery (per-unit connect/reconnect, TLS, pacing, timeouts) is driven through this
186
+ // factory, which is why an already-connected instance would not do: the client re-opens
187
+ // connections on its own schedule and needs a factory to call.
188
+ modbusFactory) {
174
189
  this.energyApp = energyApp;
175
190
  this.pacing = pacing;
191
+ this.modbusFactory = modbusFactory;
192
+ if (!energyApp && !modbusFactory) {
193
+ throw new Error("SunspecModbusClient requires either an EnergyApp or a modbusFactory");
194
+ }
176
195
  this.connectionHealth = new EnergyAppModbusConnectionHealth();
177
196
  this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter();
178
197
  this.resilience = { ...DEFAULT_MODBUS_RESILIENCE_CONFIG, ...resilience };
179
198
  }
199
+ /**
200
+ * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
201
+ * if one was given, otherwise the host application's default (`energyApp.useModbus()`). The
202
+ * constructor guarantees at least one of the two is present.
203
+ */
204
+ useModbus() {
205
+ if (this.modbusFactory)
206
+ return this.modbusFactory;
207
+ if (!this.energyApp) {
208
+ throw new Error("SunspecModbusClient has no Modbus backend: neither energyApp nor modbusFactory is set");
209
+ }
210
+ return this.energyApp.useModbus();
211
+ }
180
212
  /**
181
213
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
182
214
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -467,7 +499,7 @@ export class SunspecModbusClient {
467
499
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
468
500
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
469
501
  // can still leave the returned promise pending — bound it independently.
470
- candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.energyApp.useModbus().connect({
502
+ candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.useModbus().connect({
471
503
  host: hosts,
472
504
  port,
473
505
  unitId,
@@ -2238,30 +2270,43 @@ export class SunspecModbusClient {
2238
2270
  * Set battery storage mode (simplified interface)
2239
2271
  */
2240
2272
  async setStorageMode(unitId, mode) {
2241
- let storCtlMod;
2273
+ // StorCtl_Mod says *which rate setpoint is enforced*, not what the
2274
+ // battery is allowed to do — so releasing control means clearing the
2275
+ // bits, and the rate registers have to be written alongside them.
2276
+ // Setting the bits without touching InWRte/OutWRte would enforce
2277
+ // whatever percentage was left behind by an earlier command.
2278
+ let controls;
2242
2279
  switch (mode) {
2243
2280
  case SunspecStorageMode.CHARGE:
2244
- // Enable charge only (bit 0 = 1, bit 1 = 0)
2245
- storCtlMod = SunspecStorageControlMode.CHARGE;
2281
+ // Enforce the charge-rate setpoint only (bit 0 = 1, bit 1 = 0).
2282
+ controls = { storCtlMod: SunspecStorageControlMode.CHARGE };
2246
2283
  break;
2247
2284
  case SunspecStorageMode.DISCHARGE:
2248
- // Enable discharge only (bit 0 = 0, bit 1 = 1)
2249
- storCtlMod = SunspecStorageControlMode.DISCHARGE;
2285
+ // Enforce the discharge-rate setpoint only (bit 0 = 0, bit 1 = 1).
2286
+ controls = { storCtlMod: SunspecStorageControlMode.DISCHARGE };
2250
2287
  break;
2251
2288
  case SunspecStorageMode.HOLDING:
2252
- // Disable both charge and discharge (bits 0 and 1 = 0)
2253
- storCtlMod = 0;
2289
+ // Park the battery: both setpoints enforced, both clamped to 0 %.
2290
+ controls = {
2291
+ storCtlMod: SunspecStorageControlMode.CHARGE | SunspecStorageControlMode.DISCHARGE,
2292
+ inWRte: 0,
2293
+ outWRte: 0,
2294
+ };
2254
2295
  break;
2255
2296
  case SunspecStorageMode.AUTO:
2256
- // Enable both charge and discharge (bits 0 and 1 = 1)
2257
- storCtlMod = SunspecStorageControlMode.CHARGE | SunspecStorageControlMode.DISCHARGE;
2297
+ // Hand control back: no setpoint enforced, both rates wide open.
2298
+ controls = {
2299
+ storCtlMod: SunspecStorageControlMode.NONE,
2300
+ inWRte: 100,
2301
+ outWRte: 100,
2302
+ };
2258
2303
  break;
2259
2304
  default:
2260
2305
  console.error(`Invalid storage mode: ${mode}`);
2261
2306
  return false;
2262
2307
  }
2263
- console.log(`Setting storage mode to ${mode} (control bits: 0x${storCtlMod.toString(16)})`);
2264
- return this.writeBatteryControls(unitId, { storCtlMod });
2308
+ console.log(`Setting storage mode to ${mode} (${JSON.stringify(controls)})`);
2309
+ return this.writeBatteryControls(unitId, controls);
2265
2310
  }
2266
2311
  /**
2267
2312
  * Enable or disable grid charging
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 = "0.0.103";
8
+ export declare const SDK_VERSION = "0.0.105";
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 = '0.0.103';
8
+ export const SDK_VERSION = '0.0.105';
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": "0.0.103",
3
+ "version": "0.0.105",
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": "^0.0.180"
44
+ "@enyo-energy/energy-app-sdk": "^0.0.188"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"