@enyo-energy/sunspec-sdk 0.0.104 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -0
- package/dist/cjs/sunspec-battery-schedule-handler.cjs +76 -28
- package/dist/cjs/sunspec-battery-schedule-handler.d.cts +33 -6
- package/dist/cjs/sunspec-devices.cjs +140 -29
- package/dist/cjs/sunspec-devices.d.cts +47 -3
- package/dist/cjs/sunspec-interfaces.cjs +9 -2
- package/dist/cjs/sunspec-interfaces.d.cts +73 -4
- package/dist/cjs/sunspec-modbus-client.cjs +280 -116
- package/dist/cjs/sunspec-modbus-client.d.cts +82 -5
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/sunspec-battery-schedule-handler.d.ts +33 -6
- package/dist/sunspec-battery-schedule-handler.js +76 -28
- package/dist/sunspec-devices.d.ts +47 -3
- package/dist/sunspec-devices.js +139 -29
- package/dist/sunspec-interfaces.d.ts +73 -4
- package/dist/sunspec-interfaces.js +9 -2
- package/dist/sunspec-modbus-client.d.ts +82 -5
- package/dist/sunspec-modbus-client.js +277 -115
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -8,6 +8,9 @@ SunSpec Modbus client for reading data from solar inverters, batteries, meters,
|
|
|
8
8
|
- [Battery Feature Modes](#battery-feature-modes)
|
|
9
9
|
- [Battery Calibration](#battery-calibration)
|
|
10
10
|
- [Storage Schedule Control](#storage-schedule-control)
|
|
11
|
+
- [Connection Failures and Logging](#connection-failures-and-logging)
|
|
12
|
+
- [Transport Options](#transport-options)
|
|
13
|
+
- [Appliance Metadata the Registers Don't Carry](#appliance-metadata-the-registers-dont-carry)
|
|
11
14
|
- [How Addressing Works](#how-addressing-works)
|
|
12
15
|
- [Bulk Register Reading](#bulk-register-reading)
|
|
13
16
|
- [Data Types](#data-types)
|
|
@@ -352,6 +355,93 @@ The earlier `StartStorageGridChargeV1` / `StopStorageGridChargeV1` / `SetStorage
|
|
|
352
355
|
|
|
353
356
|
---
|
|
354
357
|
|
|
358
|
+
## Connection Failures and Logging
|
|
359
|
+
|
|
360
|
+
### Two kinds of failure
|
|
361
|
+
|
|
362
|
+
The client distinguishes a transaction that was **attempted and failed** from one **refused because the link is already known to be dead**. On a half-open socket (the peer stops answering while the OS still reports ESTABLISHED) the first read times out and *poisons* the unit's socket; every read that lands afterwards is refused outright, without touching the wire, until the reconnect path recycles it.
|
|
363
|
+
|
|
364
|
+
| Situation | Rejection | Log level |
|
|
365
|
+
| --- | --- | --- |
|
|
366
|
+
| Read/write attempted, timed out | `ModbusOperationTimeoutError` | one WARN on the poison transition |
|
|
367
|
+
| Read/write refused, unit already down | `SunspecUnavailableError` (`reason: 'socket-poisoned'`) | none — `debug` only |
|
|
368
|
+
| Socket recovered on reconnect | — | one INFO with `poisonedForMs` |
|
|
369
|
+
|
|
370
|
+
```ts
|
|
371
|
+
import { isSunspecUnavailableError } from '@enyo-energy/sunspec-sdk';
|
|
372
|
+
|
|
373
|
+
try {
|
|
374
|
+
await client.readRegisterValue(unitId, 40100, 1, 'uint16');
|
|
375
|
+
} catch (error) {
|
|
376
|
+
if (isSunspecUnavailableError(error)) {
|
|
377
|
+
// Already reported by the SDK — `error.reason` says why, `error.sinceMs` says
|
|
378
|
+
// how long it has been down. Log the first one of an outage at most.
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
console.error(`read failed`, error);
|
|
382
|
+
}
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
Prefer `isSunspecUnavailableError()` over `instanceof` at package boundaries, where a duplicated copy of the SDK in the module graph would break class identity.
|
|
386
|
+
|
|
387
|
+
Both error classes implement `toJSON()`, so `JSON.stringify(error)` yields a usable `{ name, message, ... }` instead of the `{}` a bare `Error` serialises to.
|
|
388
|
+
|
|
389
|
+
### One event, one line
|
|
390
|
+
|
|
391
|
+
The SDK logs **state transitions**, not states. A unit that is unreachable for an hour produces one WARN entering the poisoned state and one INFO on recovery — not one ERROR per read per poll cycle. The same rule applies to reconnect attempts: the first failure of a run is logged at ERROR, every repeat while the peer stays down at `debug`, and a success re-arms the logging for the next outage.
|
|
392
|
+
|
|
393
|
+
### Backoff
|
|
394
|
+
|
|
395
|
+
The tiered `ConnectionRetryManager` schedule is cleared by a **healthy read cycle**, not by a reconnect that merely reopened the socket. A peer that accepts TCP connections but never answers Modbus would otherwise restart the schedule at its shortest phase on every cycle and retry forever at poll rate. Because the schedule now survives such a cycle, the elapsed clock keeps growing and the intervals widen as configured (default: 10s → 30s → 1m → 5m → 15m, infinite retry). Tune with the `retryConfig` constructor argument on any device.
|
|
396
|
+
|
|
397
|
+
---
|
|
398
|
+
|
|
399
|
+
## Transport Options
|
|
400
|
+
|
|
401
|
+
Everything in `IModbusTransportConfig` is forwarded verbatim to the host's `useModbus().connect()` — the SDK owns the behaviour, this client only passes the config it was constructed with. Omitted fields stay `undefined` so the host's own defaults apply.
|
|
402
|
+
|
|
403
|
+
```ts
|
|
404
|
+
const client = getOrCreateSunspecClient(energyApp, host, 502, {
|
|
405
|
+
noParallelRequests: true, // serialize frames (slow devices, e.g. Solax)
|
|
406
|
+
waitBetweenMessagesMs: 40, // spacing between frames; only with noParallelRequests
|
|
407
|
+
pooledConnection: true, // share one socket per device (energy-app-sdk >= 1.6.0)
|
|
408
|
+
});
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
`pooledConnection` takes the socket from the host's shared pool — keyed by host, port, unit ID and transport settings — instead of opening one owned exclusively by this client, and its `disconnect()` releases the connection back to the pool rather than necessarily closing it. It exists for devices that accept only a handful of simultaneous Modbus clients.
|
|
412
|
+
|
|
413
|
+
Note this SDK **already** refcounts one client per `host:port` (`getOrCreateSunspecClient` / `releaseSunspecClient`), so several devices behind one gateway share a connection either way. Pooling only adds something when code *outside* this client talks to the same device — a native driver in the same app, say. Leave it unset otherwise.
|
|
414
|
+
|
|
415
|
+
The config is applied when the client for a `host:port` is **first created**; a later caller passing a different config gets the cached instance and its config is ignored.
|
|
416
|
+
|
|
417
|
+
---
|
|
418
|
+
|
|
419
|
+
## Appliance Metadata the Registers Don't Carry
|
|
420
|
+
|
|
421
|
+
Three appliance fields added in energy-app-sdk 1.6.0 have no SunSpec register behind them, so the SDK cannot derive them — it publishes what the consumer configures, and writes nothing at all when nothing is configured (spreading an explicit `undefined` would erase a value the host set through another path).
|
|
422
|
+
|
|
423
|
+
```ts
|
|
424
|
+
new SunspecInverter(energyApp, name, networkDevice, client, applianceManager,
|
|
425
|
+
1, 502, 40000, [], retryConfig, appliance, useTls, SunspecPvPowerSource.Auto,
|
|
426
|
+
{ controlAllowed: true, installedPeakPowerWp: 12_400 });
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
| Field | Meaning |
|
|
430
|
+
| --- | --- |
|
|
431
|
+
| `inverter.controlAllowed` | Whether the energy manager may steer this inverter (e.g. curtail). Unset = "not configured", which is not `false`. |
|
|
432
|
+
| `inverter.installedPeakPowerWp` | Module peak power from the Anlagenpass. Distinct from `maxPvProductionW`, which the SDK reads from Model 121 `WMax` (the AC side). |
|
|
433
|
+
| `battery.roundTripEfficiencyPercent` | Measured AC-to-AC round-trip efficiency (0–100). |
|
|
434
|
+
|
|
435
|
+
Round-trip efficiency is a *measured* figure that drifts with cell age and temperature, so a value fixed at construction goes stale. Push a recomputed one at any time:
|
|
436
|
+
|
|
437
|
+
```ts
|
|
438
|
+
await battery.setRoundTripEfficiencyPercent(83.2); // publishes immediately
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
Values outside 0–100 throw. Calling it before `connect()` is fine — the value is remembered and published with the rest of the metadata once the appliance exists. Leave it unset until enough cycles have been observed: a missing value means "not yet known", which is more useful to an optimizer than a datasheet number that overstates what the pack returns.
|
|
442
|
+
|
|
443
|
+
---
|
|
444
|
+
|
|
355
445
|
## How Addressing Works
|
|
356
446
|
|
|
357
447
|
### Base Address Detection
|
|
@@ -22,8 +22,9 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
|
|
|
22
22
|
* Sticky pre-schedule snapshot, captured once on the first `onInit` and
|
|
23
23
|
* held across every subsequent schedule-to-schedule replacement. Cleared
|
|
24
24
|
* only when a real rollback fires (`mode: auto` from the data bus or
|
|
25
|
-
* `dispose`).
|
|
26
|
-
*
|
|
25
|
+
* `dispose`). Supplies the `wChaMax` denominator for the percentage math
|
|
26
|
+
* and the charge source to hand back on release — taken from the *original*
|
|
27
|
+
* pre-schedule read rather than the register set the device happens to be
|
|
27
28
|
* in at the moment of replacement.
|
|
28
29
|
*/
|
|
29
30
|
originalBaseline;
|
|
@@ -35,6 +36,11 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
|
|
|
35
36
|
* write the snapshot back during a replacement.
|
|
36
37
|
*/
|
|
37
38
|
suppressNextRollbackWrite = false;
|
|
39
|
+
/**
|
|
40
|
+
* Mirrors the base class's private `disposed` flag so the auto-release
|
|
41
|
+
* path can tell "released and gone" from "released and still live".
|
|
42
|
+
*/
|
|
43
|
+
isDisposed = false;
|
|
38
44
|
constructor(opts) {
|
|
39
45
|
super(opts);
|
|
40
46
|
this.sunspecClient = opts.sunspecClient;
|
|
@@ -52,11 +58,15 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
|
|
|
52
58
|
* normally there.
|
|
53
59
|
*/
|
|
54
60
|
async applyMessage(msg) {
|
|
55
|
-
|
|
61
|
+
const isForThisAppliance = msg.applianceId === this.applianceIdForLog;
|
|
62
|
+
if (isForThisAppliance
|
|
56
63
|
&& msg.data.mode === enyo_data_bus_value_js_1.EnyoStorageScheduleModeEnum.Schedule
|
|
57
64
|
&& this.getActiveEntry() !== undefined) {
|
|
58
65
|
this.suppressNextRollbackWrite = true;
|
|
59
66
|
}
|
|
67
|
+
// Captured before the base class runs: with a schedule active, its
|
|
68
|
+
// `doReleaseSchedule → onRollback` already performs the auto release.
|
|
69
|
+
const hadActiveSchedule = this.getActiveEntry() !== undefined;
|
|
60
70
|
try {
|
|
61
71
|
await super.applyMessage(msg);
|
|
62
72
|
}
|
|
@@ -66,6 +76,30 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
|
|
|
66
76
|
// otherwise stay set and silently swallow the next real rollback.
|
|
67
77
|
this.suppressNextRollbackWrite = false;
|
|
68
78
|
}
|
|
79
|
+
if (isForThisAppliance
|
|
80
|
+
&& msg.data.mode === enyo_data_bus_value_js_1.EnyoStorageScheduleModeEnum.Auto
|
|
81
|
+
&& !hadActiveSchedule
|
|
82
|
+
&& !this.isDisposed) {
|
|
83
|
+
// `mode: auto` with no schedule running is a no-op in the base
|
|
84
|
+
// library (`doReleaseSchedule` returns early when idle), so nothing
|
|
85
|
+
// would reach the device. That is not harmless: Model 124 setpoints
|
|
86
|
+
// latch — an interrupted schedule (modbus drop, package restart)
|
|
87
|
+
// leaves StorCtl_Mod and InWRte set, and with InOutWRte_RvrtTms = 0
|
|
88
|
+
// the inverter never reverts on its own. Seen in production as a
|
|
89
|
+
// battery pinned at ~2 % charge rate for hours while the energy
|
|
90
|
+
// manager sent `auto` every 40 s and got an `Accepted` back.
|
|
91
|
+
//
|
|
92
|
+
// Writing the release unconditionally is safe because it is
|
|
93
|
+
// idempotent: it is exactly the register set that means
|
|
94
|
+
// "no external control".
|
|
95
|
+
await this.releaseToAuto().catch(err => {
|
|
96
|
+
console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: auto release failed: ${err}`);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
dispose() {
|
|
101
|
+
this.isDisposed = true;
|
|
102
|
+
super.dispose();
|
|
69
103
|
}
|
|
70
104
|
async onInit(_active) {
|
|
71
105
|
if (this.originalBaseline !== undefined) {
|
|
@@ -104,7 +138,7 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
|
|
|
104
138
|
console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onChange write failed for entry ${active.indexInSchedule}: ${err}`);
|
|
105
139
|
});
|
|
106
140
|
}
|
|
107
|
-
onRollback(
|
|
141
|
+
onRollback(_registers) {
|
|
108
142
|
if (this.suppressNextRollbackWrite) {
|
|
109
143
|
// Schedule-to-schedule replacement. Do NOT write the snapshot
|
|
110
144
|
// back; the new schedule's first `onChange` will own the
|
|
@@ -122,19 +156,41 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
|
|
|
122
156
|
// that follows — so a concurrent `onInit` queued behind this one
|
|
123
157
|
// (impossible today, but defensive) cannot observe a half-cleared
|
|
124
158
|
// state.
|
|
159
|
+
const chargeSource = this.originalBaseline?.chaGriSet;
|
|
125
160
|
this.originalBaseline = undefined;
|
|
126
161
|
this.installedWChaMax = undefined;
|
|
127
|
-
void (
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
162
|
+
void this.releaseToAuto(chargeSource).catch(err => {
|
|
163
|
+
console.error(`SunspecBatteryScheduleHandler ${this.applianceIdForLog}: onRollback failed: ${err}`);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Hand the battery back to its own logic: clear StorCtl_Mod and open both
|
|
168
|
+
* rate setpoints back up to 100 %.
|
|
169
|
+
*
|
|
170
|
+
* This deliberately does *not* replay the snapshot captured at `onInit`.
|
|
171
|
+
* That snapshot is whatever the registers happened to hold when the
|
|
172
|
+
* schedule started — and if a previous schedule had already stranded a
|
|
173
|
+
* limit there, restoring it re-latches the limit and the battery can never
|
|
174
|
+
* climb out. The only correct end state for "we are no longer controlling
|
|
175
|
+
* this battery" is the one written here, and it is the same set of
|
|
176
|
+
* registers a schedule entry touches, so nothing else is left dangling.
|
|
177
|
+
*
|
|
178
|
+
* `wChaMax` is not restored because a schedule never writes it — the
|
|
179
|
+
* percentage math divides against it instead.
|
|
180
|
+
*
|
|
181
|
+
* @param chargeSource - `chaGriSet` to restore; falls back to PV-only,
|
|
182
|
+
* since grid charging is only ever switched on by a Charge entry.
|
|
183
|
+
*/
|
|
184
|
+
async releaseToAuto(chargeSource) {
|
|
185
|
+
await this.sunspecClient.writeBatteryControls(this.unitId, {
|
|
186
|
+
storCtlMod: sunspec_interfaces_js_1.SunspecStorageControlMode.NONE,
|
|
187
|
+
chaGriSet: chargeSource ?? sunspec_interfaces_js_1.SunspecChargeSource.PV,
|
|
188
|
+
inWRte: 100,
|
|
189
|
+
outWRte: 100,
|
|
190
|
+
});
|
|
191
|
+
await this.getSnapshotService()?.recordModification([
|
|
192
|
+
'storCtlMod', 'chaGriSet', 'inWRte', 'outWRte',
|
|
193
|
+
]);
|
|
138
194
|
}
|
|
139
195
|
onError(err) {
|
|
140
196
|
this.onErrorCallback?.(err);
|
|
@@ -142,19 +198,11 @@ class SunspecBatteryScheduleHandler extends storage_schedule_handler_js_1.Storag
|
|
|
142
198
|
async applyEntry(active) {
|
|
143
199
|
const { direction, powerW } = active.entry;
|
|
144
200
|
if (direction === enyo_data_bus_value_js_1.EnyoStorageScheduleDirectionEnum.Idle) {
|
|
145
|
-
// Idle entry: hand the battery back to its own autonomous logic
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
const baselineRegisters = this.originalBaseline;
|
|
151
|
-
if (!baselineRegisters) {
|
|
152
|
-
throw new Error(`no usable baseline for idle entry (originalBaseline=undefined)`);
|
|
153
|
-
}
|
|
154
|
-
await this.sunspecClient.writeBatteryControls(this.unitId, baselineRegisters);
|
|
155
|
-
await this.getSnapshotService()?.recordModification([
|
|
156
|
-
'storCtlMod', 'chaGriSet', 'wChaMax', 'inWRte', 'outWRte',
|
|
157
|
-
]);
|
|
201
|
+
// Idle entry: hand the battery back to its own autonomous logic —
|
|
202
|
+
// the same release the `mode: auto` path performs. The schedule
|
|
203
|
+
// itself keeps running, so a subsequent Charge / Discharge entry
|
|
204
|
+
// can resume external control.
|
|
205
|
+
await this.releaseToAuto(this.originalBaseline?.chaGriSet);
|
|
158
206
|
return;
|
|
159
207
|
}
|
|
160
208
|
const baseline = this.installedWChaMax;
|
|
@@ -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
|
-
*
|
|
24
|
-
*
|
|
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`).
|
|
67
|
-
*
|
|
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(
|
|
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
|
}
|
|
@@ -5,6 +5,7 @@ exports.detectFeaturesFromRegisters = detectFeaturesFromRegisters;
|
|
|
5
5
|
exports.sumMpptBatteryPowerW = sumMpptBatteryPowerW;
|
|
6
6
|
exports.selectLiveBatteryPowerW = selectLiveBatteryPowerW;
|
|
7
7
|
exports.filterFeaturesByCalibrationResult = filterFeaturesByCalibrationResult;
|
|
8
|
+
exports.deriveStorageMode = deriveStorageMode;
|
|
8
9
|
const sunspec_interfaces_js_1 = require("./sunspec-interfaces.cjs");
|
|
9
10
|
const node_crypto_1 = require("node:crypto");
|
|
10
11
|
const enyo_appliance_js_1 = require("@enyo-energy/energy-app-sdk/dist/types/enyo-appliance.js");
|
|
@@ -238,7 +239,14 @@ class BaseSunspecDevice {
|
|
|
238
239
|
`opened the socket but revalidation failed — retrying with backoff`);
|
|
239
240
|
return false;
|
|
240
241
|
}
|
|
241
|
-
|
|
242
|
+
// NOT reset() here — a reopened TCP socket is not yet a working device. On a peer
|
|
243
|
+
// that accepts connections but stops answering reads, resetting on the reconnect
|
|
244
|
+
// restarts the backoff schedule from its shortest phase on every cycle, so the
|
|
245
|
+
// schedule never advances past 10s no matter how long the outage runs: reconnect,
|
|
246
|
+
// read, time out, poison, mark offline, reconnect — indefinitely, at poll rate. The
|
|
247
|
+
// schedule is cleared instead by the first genuinely healthy read cycle (see
|
|
248
|
+
// markOfflineIfUnhealthy), which is the only evidence the link actually carries
|
|
249
|
+
// data. Until then `elapsed` keeps growing and the phases widen as intended.
|
|
242
250
|
this.consecutiveReconnectFailures = 0;
|
|
243
251
|
// Update appliance state to Connected
|
|
244
252
|
if (this.applianceId) {
|
|
@@ -254,7 +262,15 @@ class BaseSunspecDevice {
|
|
|
254
262
|
await this.onConnectionFailure(this.consecutiveReconnectFailures);
|
|
255
263
|
}
|
|
256
264
|
catch (error) {
|
|
257
|
-
|
|
265
|
+
// Transition-only: the first throw of an outage is the news; every repeat while the
|
|
266
|
+
// peer stays down is the same news again, so it drops to debug.
|
|
267
|
+
const line = `${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} failed: ${error}`;
|
|
268
|
+
if (this.consecutiveReconnectFailures === 0) {
|
|
269
|
+
console.error(line);
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
console.debug(line);
|
|
273
|
+
}
|
|
258
274
|
this.consecutiveReconnectFailures += 1;
|
|
259
275
|
await this.onConnectionFailure(this.consecutiveReconnectFailures);
|
|
260
276
|
}
|
|
@@ -322,6 +338,12 @@ class BaseSunspecDevice {
|
|
|
322
338
|
*/
|
|
323
339
|
async markOfflineIfUnhealthy() {
|
|
324
340
|
if (this.sunspecClient.isHealthy(this.unitId)) {
|
|
341
|
+
// A completed read cycle on a healthy unit is the only proof the link carries data, so
|
|
342
|
+
// it — not a successful reconnect — is what clears the tiered retry schedule. See the
|
|
343
|
+
// note in tryReconnect(): resetting on reconnect alone pins a flapping device to the
|
|
344
|
+
// shortest retry phase forever.
|
|
345
|
+
this.retryManager.reset();
|
|
346
|
+
this.consecutiveReconnectFailures = 0;
|
|
325
347
|
return false;
|
|
326
348
|
}
|
|
327
349
|
console.warn(`${this.constructor.name} ${this.applianceId}: connection unhealthy after read cycle ` +
|
|
@@ -481,6 +503,7 @@ function finiteOrUndefined(value) {
|
|
|
481
503
|
class SunspecInverter extends BaseSunspecDevice {
|
|
482
504
|
capabilities;
|
|
483
505
|
pvPowerSource;
|
|
506
|
+
metadataConfig;
|
|
484
507
|
/** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
|
|
485
508
|
static CONNECTION_FAULT_THRESHOLD = 3;
|
|
486
509
|
/**
|
|
@@ -527,10 +550,29 @@ class SunspecInverter extends BaseSunspecDevice {
|
|
|
527
550
|
// only summed MPPT strings, or Inverter to use only the inverter total —
|
|
528
551
|
// e.g. for devices whose Model 160 strings are unreliable or whose AC
|
|
529
552
|
// includes non-PV sources (a hybrid's battery discharge).
|
|
530
|
-
pvPowerSource = sunspec_interfaces_js_1.SunspecPvPowerSource.Auto
|
|
553
|
+
pvPowerSource = sunspec_interfaces_js_1.SunspecPvPowerSource.Auto,
|
|
554
|
+
// Facts about the installation that no register carries (control policy, module peak power).
|
|
555
|
+
// Forwarded onto `appliance.inverter` on connect; see SunspecInverterMetadataConfig.
|
|
556
|
+
metadataConfig = {}) {
|
|
531
557
|
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
532
558
|
this.capabilities = capabilities;
|
|
533
559
|
this.pvPowerSource = pvPowerSource;
|
|
560
|
+
this.metadataConfig = metadataConfig;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* The consumer-supplied inverter facts, as a spreadable object that only contains the keys that
|
|
564
|
+
* were actually configured. Spreading `{ controlAllowed: undefined }` over an existing appliance
|
|
565
|
+
* would erase a value the host set elsewhere; omitting the key leaves it alone.
|
|
566
|
+
*/
|
|
567
|
+
configuredInverterMetadata() {
|
|
568
|
+
const configured = {};
|
|
569
|
+
if (this.metadataConfig.controlAllowed !== undefined) {
|
|
570
|
+
configured.controlAllowed = this.metadataConfig.controlAllowed;
|
|
571
|
+
}
|
|
572
|
+
if (this.metadataConfig.installedPeakPowerWp !== undefined) {
|
|
573
|
+
configured.installedPeakPowerWp = this.metadataConfig.installedPeakPowerWp;
|
|
574
|
+
}
|
|
575
|
+
return configured;
|
|
534
576
|
}
|
|
535
577
|
async connect() {
|
|
536
578
|
// Ensure Sunspec client is connected
|
|
@@ -564,7 +606,8 @@ class SunspecInverter extends BaseSunspecDevice {
|
|
|
564
606
|
inverter: {
|
|
565
607
|
dcStrings: this.mapDcStringToApplianceMetadata(this.mapMPPTToStrings(mpptDataList)),
|
|
566
608
|
maxPvProductionW: inverterSettings?.WMax,
|
|
567
|
-
activeProductionLimitationW: activeProductionLimitationW
|
|
609
|
+
activeProductionLimitationW: activeProductionLimitationW,
|
|
610
|
+
...this.configuredInverterMetadata()
|
|
568
611
|
}
|
|
569
612
|
});
|
|
570
613
|
console.log(`Sunspec Inverter connected: ${this.networkDevice.hostname} (${this.applianceId})`);
|
|
@@ -591,7 +634,8 @@ class SunspecInverter extends BaseSunspecDevice {
|
|
|
591
634
|
...existingAppliance?.inverter,
|
|
592
635
|
dcStrings: this.mapDcStringToApplianceMetadata(this.mapMPPTToStrings(mpptDataList)),
|
|
593
636
|
maxPvProductionW: inverterSettings?.WMax,
|
|
594
|
-
activeProductionLimitationW: activeProductionLimitationW
|
|
637
|
+
activeProductionLimitationW: activeProductionLimitationW,
|
|
638
|
+
...this.configuredInverterMetadata()
|
|
595
639
|
}
|
|
596
640
|
});
|
|
597
641
|
console.log(`Sunspec Inverter connected: ${this.networkDevice.hostname} (${this.applianceId})`);
|
|
@@ -1434,6 +1478,37 @@ function filterFeaturesByCalibrationResult(detected, result, controllable) {
|
|
|
1434
1478
|
/**
|
|
1435
1479
|
* Sunspec Battery implementation
|
|
1436
1480
|
*/
|
|
1481
|
+
/**
|
|
1482
|
+
* Derive the storage mode from Model 124's StorCtl_Mod bitfield.
|
|
1483
|
+
*
|
|
1484
|
+
* The bits mark *which rate setpoint the device is enforcing* — bit 0 for
|
|
1485
|
+
* InWRte, bit 1 for OutWRte — not which direction is permitted. So no bit set
|
|
1486
|
+
* is the autonomous mode, and both bits set is the most externally controlled
|
|
1487
|
+
* state there is, which is the opposite of what the naming suggests. Reading
|
|
1488
|
+
* them the other way round meant a battery running its own logic reported
|
|
1489
|
+
* `holding`, a fully clamped one reported `auto`, and no appliance could ever
|
|
1490
|
+
* report that it had been handed back to itself.
|
|
1491
|
+
*
|
|
1492
|
+
* @param controls - Model 124 control registers, or null when unreadable.
|
|
1493
|
+
* @returns The mode, or null when StorCtl_Mod could not be read.
|
|
1494
|
+
*/
|
|
1495
|
+
function deriveStorageMode(controls) {
|
|
1496
|
+
if (!controls || controls.storCtlMod === undefined) {
|
|
1497
|
+
return null;
|
|
1498
|
+
}
|
|
1499
|
+
const chargeLimited = (controls.storCtlMod & 0x0001) !== 0;
|
|
1500
|
+
const dischargeLimited = (controls.storCtlMod & 0x0002) !== 0;
|
|
1501
|
+
if (!chargeLimited && !dischargeLimited) {
|
|
1502
|
+
return sunspec_interfaces_js_1.SunspecStorageMode.AUTO;
|
|
1503
|
+
}
|
|
1504
|
+
// Both directions clamped to zero — the battery is parked, not idling.
|
|
1505
|
+
if (chargeLimited && dischargeLimited && controls.inWRte === 0 && controls.outWRte === 0) {
|
|
1506
|
+
return sunspec_interfaces_js_1.SunspecStorageMode.HOLDING;
|
|
1507
|
+
}
|
|
1508
|
+
return dischargeLimited && !chargeLimited
|
|
1509
|
+
? sunspec_interfaces_js_1.SunspecStorageMode.DISCHARGE
|
|
1510
|
+
: sunspec_interfaces_js_1.SunspecStorageMode.CHARGE;
|
|
1511
|
+
}
|
|
1437
1512
|
class SunspecBattery extends BaseSunspecDevice {
|
|
1438
1513
|
featureMode;
|
|
1439
1514
|
capabilities;
|
|
@@ -1464,10 +1539,59 @@ class SunspecBattery extends BaseSunspecDevice {
|
|
|
1464
1539
|
enyo_battery_appliance_js_1.EnyoBatteryFeature.ChargeLimitation,
|
|
1465
1540
|
enyo_battery_appliance_js_1.EnyoBatteryFeature.DischargeLimitation,
|
|
1466
1541
|
];
|
|
1467
|
-
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, featureMode, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls
|
|
1542
|
+
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, featureMode, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls,
|
|
1543
|
+
// Battery facts no register carries (currently the measured round-trip efficiency).
|
|
1544
|
+
// Forwarded onto `appliance.battery` on connect; see SunspecBatteryMetadataConfig.
|
|
1545
|
+
metadataConfig = {}) {
|
|
1468
1546
|
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
1469
1547
|
this.featureMode = featureMode;
|
|
1470
1548
|
this.capabilities = capabilities;
|
|
1549
|
+
this.roundTripEfficiencyPercent = metadataConfig.roundTripEfficiencyPercent;
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* Last known round-trip efficiency, seeded from the constructor config and replaceable at
|
|
1553
|
+
* runtime via {@link setRoundTripEfficiencyPercent}. Undefined = not yet known; the SDK then
|
|
1554
|
+
* writes nothing, leaving whatever the appliance store already holds.
|
|
1555
|
+
*/
|
|
1556
|
+
roundTripEfficiencyPercent;
|
|
1557
|
+
/**
|
|
1558
|
+
* Update the battery's measured round-trip efficiency (percent, 0-100) and push it to the
|
|
1559
|
+
* appliance immediately. Meant to be called whenever the host recomputes the figure from
|
|
1560
|
+
* completed cycles - it drifts with cell age and temperature, so a value fixed at construction
|
|
1561
|
+
* goes stale. Pass `undefined` to stop asserting a value (the last published one stays in the
|
|
1562
|
+
* appliance store; the SDK does not erase it).
|
|
1563
|
+
*
|
|
1564
|
+
* Safe to call before {@link connect}: the value is remembered and published with the rest of
|
|
1565
|
+
* the metadata once the appliance exists.
|
|
1566
|
+
*/
|
|
1567
|
+
async setRoundTripEfficiencyPercent(percent) {
|
|
1568
|
+
if (percent !== undefined && (!Number.isFinite(percent) || percent < 0 || percent > 100)) {
|
|
1569
|
+
throw new Error(`setRoundTripEfficiencyPercent: ${percent} is not a percentage between 0 and 100`);
|
|
1570
|
+
}
|
|
1571
|
+
this.roundTripEfficiencyPercent = percent;
|
|
1572
|
+
if (percent === undefined || !this.applianceId)
|
|
1573
|
+
return;
|
|
1574
|
+
try {
|
|
1575
|
+
const existingAppliance = await this.applianceManager.findApplianceById(this.applianceId);
|
|
1576
|
+
await this.applianceManager.updateAppliance(this.applianceId, {
|
|
1577
|
+
battery: {
|
|
1578
|
+
...existingAppliance?.battery,
|
|
1579
|
+
roundTripEfficiencyPercent: percent
|
|
1580
|
+
}
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
catch (error) {
|
|
1584
|
+
console.error(`Failed to publish round-trip efficiency for battery ${this.applianceId}: ${error}`);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
/**
|
|
1588
|
+
* The configured battery facts as a spreadable object holding only the keys actually known.
|
|
1589
|
+
* Spreading an explicit `undefined` would erase a value the host set elsewhere.
|
|
1590
|
+
*/
|
|
1591
|
+
configuredBatteryMetadata() {
|
|
1592
|
+
return this.roundTripEfficiencyPercent === undefined
|
|
1593
|
+
? {}
|
|
1594
|
+
: { roundTripEfficiencyPercent: this.roundTripEfficiencyPercent };
|
|
1471
1595
|
}
|
|
1472
1596
|
/**
|
|
1473
1597
|
* Wire the battery into `@enyo-energy/appliance-calibration`'s
|
|
@@ -1588,12 +1712,13 @@ class SunspecBattery extends BaseSunspecDevice {
|
|
|
1588
1712
|
battery: {
|
|
1589
1713
|
connectedToApplianceId: inverterApplianceId,
|
|
1590
1714
|
storageMode: this.mapToEnyoStorageMode(storageMode),
|
|
1591
|
-
maxChargingPowerW: batteryData
|
|
1715
|
+
maxChargingPowerW: batteryData?.wChaMax,
|
|
1592
1716
|
maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
|
|
1593
1717
|
activeChargeLimitW: activeChargeLimitW,
|
|
1594
1718
|
activeDischargeLimitW: activeDischargeLimitW,
|
|
1595
1719
|
features,
|
|
1596
|
-
gridChargingEnabled: batteryData?.chaGriSet === 1
|
|
1720
|
+
gridChargingEnabled: batteryData?.chaGriSet === 1,
|
|
1721
|
+
...this.configuredBatteryMetadata()
|
|
1597
1722
|
}
|
|
1598
1723
|
});
|
|
1599
1724
|
console.log(`Sunspec Battery connected: ${this.networkDevice.hostname} (${this.applianceId})`);
|
|
@@ -1616,12 +1741,13 @@ class SunspecBattery extends BaseSunspecDevice {
|
|
|
1616
1741
|
...existingAppliance?.battery,
|
|
1617
1742
|
connectedToApplianceId: inverterApplianceId,
|
|
1618
1743
|
storageMode: this.mapToEnyoStorageMode(storageMode),
|
|
1619
|
-
maxChargingPowerW: batteryData
|
|
1744
|
+
maxChargingPowerW: batteryData?.wChaMax,
|
|
1620
1745
|
maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
|
|
1621
1746
|
activeChargeLimitW: activeChargeLimitW,
|
|
1622
1747
|
activeDischargeLimitW: activeDischargeLimitW,
|
|
1623
1748
|
features,
|
|
1624
|
-
gridChargingEnabled: batteryData?.chaGriSet === 1
|
|
1749
|
+
gridChargingEnabled: batteryData?.chaGriSet === 1,
|
|
1750
|
+
...this.configuredBatteryMetadata()
|
|
1625
1751
|
}
|
|
1626
1752
|
});
|
|
1627
1753
|
console.log(`Sunspec Battery connected: ${this.networkDevice.hostname} (${this.applianceId})`);
|
|
@@ -1775,12 +1901,13 @@ class SunspecBattery extends BaseSunspecDevice {
|
|
|
1775
1901
|
battery: {
|
|
1776
1902
|
...appliance?.battery,
|
|
1777
1903
|
storageMode: this.mapToEnyoStorageMode(storageMode),
|
|
1778
|
-
maxChargingPowerW: batteryData
|
|
1904
|
+
maxChargingPowerW: batteryData?.wChaMax,
|
|
1779
1905
|
maxDischargePowerW: batteryData && batteryData.wChaMax !== undefined && batteryData.outWRte !== undefined ? batteryData.wChaMax * batteryData.outWRte : undefined,
|
|
1780
1906
|
activeChargeLimitW: this.computeActiveChargeLimitW(batteryData),
|
|
1781
1907
|
activeDischargeLimitW: this.computeActiveDischargeLimitW(batteryData),
|
|
1782
1908
|
features,
|
|
1783
|
-
gridChargingEnabled: batteryData?.chaGriSet === 1
|
|
1909
|
+
gridChargingEnabled: batteryData?.chaGriSet === 1,
|
|
1910
|
+
...this.configuredBatteryMetadata()
|
|
1784
1911
|
}
|
|
1785
1912
|
});
|
|
1786
1913
|
}
|
|
@@ -1979,23 +2106,7 @@ class SunspecBattery extends BaseSunspecDevice {
|
|
|
1979
2106
|
return (batteryData.wChaMax * batteryData.outWRte) / 100;
|
|
1980
2107
|
}
|
|
1981
2108
|
determineStorageMode(controls) {
|
|
1982
|
-
|
|
1983
|
-
return null;
|
|
1984
|
-
}
|
|
1985
|
-
const chargeEnabled = (controls.storCtlMod & 0x0001) !== 0;
|
|
1986
|
-
const dischargeEnabled = (controls.storCtlMod & 0x0002) !== 0;
|
|
1987
|
-
if (chargeEnabled && dischargeEnabled) {
|
|
1988
|
-
return sunspec_interfaces_js_1.SunspecStorageMode.AUTO;
|
|
1989
|
-
}
|
|
1990
|
-
else if (chargeEnabled && !dischargeEnabled) {
|
|
1991
|
-
return sunspec_interfaces_js_1.SunspecStorageMode.CHARGE;
|
|
1992
|
-
}
|
|
1993
|
-
else if (!chargeEnabled && dischargeEnabled) {
|
|
1994
|
-
return sunspec_interfaces_js_1.SunspecStorageMode.DISCHARGE;
|
|
1995
|
-
}
|
|
1996
|
-
else {
|
|
1997
|
-
return sunspec_interfaces_js_1.SunspecStorageMode.HOLDING;
|
|
1998
|
-
}
|
|
2109
|
+
return deriveStorageMode(controls);
|
|
1999
2110
|
}
|
|
2000
2111
|
/**
|
|
2001
2112
|
* Check if grid charging is enabled
|