@enyo-energy/sunspec-sdk 0.0.100 → 0.0.102
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/cjs/sunspec-devices.cjs +486 -18
- package/dist/cjs/sunspec-devices.d.cts +144 -1
- package/dist/cjs/sunspec-interfaces.d.cts +81 -0
- package/dist/cjs/sunspec-modbus-client.cjs +172 -49
- package/dist/cjs/sunspec-modbus-client.d.cts +43 -1
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/sunspec-devices.d.ts +144 -1
- package/dist/sunspec-devices.js +484 -17
- package/dist/sunspec-interfaces.d.ts +81 -0
- package/dist/sunspec-modbus-client.d.ts +43 -1
- package/dist/sunspec-modbus-client.js +172 -49
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/dist/sunspec-devices.js
CHANGED
|
@@ -149,9 +149,33 @@ export class BaseSunspecDevice {
|
|
|
149
149
|
await this.sunspecClient.connect(this.networkDevice.hostname, // primary
|
|
150
150
|
this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
|
|
151
151
|
this.useTls);
|
|
152
|
-
await this.
|
|
152
|
+
await this.discoverAfterConnect();
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Populate the per-unit model directory after the socket opens. Default: run SunSpec model
|
|
157
|
+
* discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
|
|
158
|
+
* directory (see {@link SunspecCustomDevice}) override this to a no-op.
|
|
159
|
+
*/
|
|
160
|
+
async discoverAfterConnect() {
|
|
161
|
+
await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Validate that a just-completed reconnect actually restored a usable device. Default: re-run
|
|
165
|
+
* SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
|
|
166
|
+
* back with no usable models means the gateway accepted the connection before it was ready to
|
|
167
|
+
* answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
|
|
168
|
+
* running. Discovery-less devices override this to just confirm the socket is open.
|
|
169
|
+
*/
|
|
170
|
+
async revalidateAfterReconnect() {
|
|
171
|
+
const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
|
|
172
|
+
const usable = this.isDiscoveryUsable(models);
|
|
173
|
+
if (!usable) {
|
|
174
|
+
console.warn(`${this.constructor.name} ${this.applianceId}: reconnect discovery returned no usable models ` +
|
|
175
|
+
`(found [${[...models.keys()].join(', ')}])`);
|
|
176
|
+
}
|
|
177
|
+
return usable;
|
|
178
|
+
}
|
|
155
179
|
/**
|
|
156
180
|
* Attempt a reconnection if the tiered retry schedule allows it.
|
|
157
181
|
* Called from readData() when the device is disconnected.
|
|
@@ -176,8 +200,24 @@ export class BaseSunspecDevice {
|
|
|
176
200
|
// device's poll loop detects a dropped connection.
|
|
177
201
|
const success = await this.sunspecClient.reconnectUnit(this.unitId);
|
|
178
202
|
if (success) {
|
|
179
|
-
// Re-discover models for this unit after reconnect
|
|
180
|
-
|
|
203
|
+
// Re-discover models for this unit after reconnect. discoverModels() clears
|
|
204
|
+
// and repopulates the per-unit model map, so a reconnect that opens the TCP
|
|
205
|
+
// socket but comes back with no usable models (a gateway that accepted the
|
|
206
|
+
// connection before it was ready to answer the SunSpec scan) would leave the
|
|
207
|
+
// map empty. Trusting that would cache an empty map — every read then finds no
|
|
208
|
+
// model while the socket looks healthy, and because reset() disables retry,
|
|
209
|
+
// nothing ever triggers another reconnect. So validate discovery here and, when
|
|
210
|
+
// it's unusable, treat this as a failed reconnect: invalidate the socket so the
|
|
211
|
+
// next poll re-enters tryReconnect(), keep the backoff schedule running, and do
|
|
212
|
+
// NOT reset().
|
|
213
|
+
if (!(await this.revalidateAfterReconnect())) {
|
|
214
|
+
this.sunspecClient.invalidateUnit(this.unitId, `reconnect revalidation failed for unit ${this.unitId}`);
|
|
215
|
+
this.consecutiveReconnectFailures += 1;
|
|
216
|
+
await this.onConnectionFailure(this.consecutiveReconnectFailures);
|
|
217
|
+
console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
|
|
218
|
+
`opened the socket but revalidation failed — retrying with backoff`);
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
181
221
|
this.retryManager.reset();
|
|
182
222
|
this.consecutiveReconnectFailures = 0;
|
|
183
223
|
// Update appliance state to Connected
|
|
@@ -200,6 +240,42 @@ export class BaseSunspecDevice {
|
|
|
200
240
|
}
|
|
201
241
|
return false;
|
|
202
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* Model IDs this device needs to produce a reading; presence of ANY one means a
|
|
245
|
+
* discovery is usable (one-of semantics — devices expose mutually-exclusive
|
|
246
|
+
* encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
|
|
247
|
+
* (the base default) means no specific requirement, so any model present
|
|
248
|
+
* suffices. Concrete devices override with their acceptable set — this is the
|
|
249
|
+
* single per-device source of truth reused by both the reconnect discovery gate
|
|
250
|
+
* ({@link isDiscoveryUsable}) and the connect-time presence gate
|
|
251
|
+
* ({@link hasRequiredModels}).
|
|
252
|
+
*/
|
|
253
|
+
getRequiredModelIds() {
|
|
254
|
+
return [];
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* True if the current per-unit discovered-model map satisfies this device's
|
|
258
|
+
* requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
|
|
259
|
+
* the already-populated map via findModel() rather than a freshly-returned one.
|
|
260
|
+
* Only meaningful for devices that declare a non-empty required set.
|
|
261
|
+
*/
|
|
262
|
+
hasRequiredModels() {
|
|
263
|
+
return this.getRequiredModelIds().some(id => this.sunspecClient.findModel(this.unitId, id) !== undefined);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Decide whether a post-reconnect model discovery is usable. A reconnect that
|
|
267
|
+
* establishes the TCP socket but comes back empty (or with only a Common block)
|
|
268
|
+
* means the device accepted the connection before it was ready to answer the
|
|
269
|
+
* SunSpec scan; the discovered-model map is now missing this device's data
|
|
270
|
+
* model, so trusting the reconnect would leave every read finding no model.
|
|
271
|
+
* Validated generically against {@link getRequiredModelIds}: with a declared
|
|
272
|
+
* set, at least one of those ids must be present; with none declared, fall back
|
|
273
|
+
* to "any model present".
|
|
274
|
+
*/
|
|
275
|
+
isDiscoveryUsable(models) {
|
|
276
|
+
const required = this.getRequiredModelIds();
|
|
277
|
+
return required.length === 0 ? models.size > 0 : required.some(id => models.has(id));
|
|
278
|
+
}
|
|
203
279
|
/**
|
|
204
280
|
* Hook for subclasses to react to a failed reconnect attempt. Called once
|
|
205
281
|
* per failed attempt with the running consecutive-failure count.
|
|
@@ -356,6 +432,19 @@ export class SunspecInverter extends BaseSunspecDevice {
|
|
|
356
432
|
pvPowerSource;
|
|
357
433
|
/** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
|
|
358
434
|
static CONNECTION_FAULT_THRESHOLD = 3;
|
|
435
|
+
/**
|
|
436
|
+
* The inverter data models this device can read (int+SF 101/103 and IEEE-754
|
|
437
|
+
* float 111/112/113). A post-reconnect discovery that finds none of these has
|
|
438
|
+
* not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
|
|
439
|
+
* see the override below.
|
|
440
|
+
*/
|
|
441
|
+
static INVERTER_MODEL_IDS = [
|
|
442
|
+
SunspecModelId.InverterSinglePhase,
|
|
443
|
+
SunspecModelId.Inverter3Phase,
|
|
444
|
+
SunspecModelId.InverterSinglePhaseFloat,
|
|
445
|
+
SunspecModelId.InverterSplitPhaseFloat,
|
|
446
|
+
SunspecModelId.Inverter3PhaseFloat
|
|
447
|
+
];
|
|
359
448
|
/**
|
|
360
449
|
* Require this many consecutive operatingState=7 (FAULT) reads before
|
|
361
450
|
* reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
|
|
@@ -738,6 +827,16 @@ export class SunspecInverter extends BaseSunspecDevice {
|
|
|
738
827
|
lastStatus: newLastStatus,
|
|
739
828
|
};
|
|
740
829
|
}
|
|
830
|
+
/**
|
|
831
|
+
* A reconnect has only recovered the inverter if discovery finds one of its
|
|
832
|
+
* data models. An SE gateway can accept the new socket and answer a partial
|
|
833
|
+
* scan (e.g. only the Common block) before the inverter map is ready — the
|
|
834
|
+
* base size>0 rule would accept that, but every inverter read would then find
|
|
835
|
+
* no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
|
|
836
|
+
*/
|
|
837
|
+
getRequiredModelIds() {
|
|
838
|
+
return SunspecInverter.INVERTER_MODEL_IDS;
|
|
839
|
+
}
|
|
741
840
|
async onConnectionFailure(consecutiveFailures) {
|
|
742
841
|
if (!this.applianceId || !this.dataBus)
|
|
743
842
|
return;
|
|
@@ -1286,6 +1385,16 @@ export function filterFeaturesByCalibrationResult(detected, result, controllable
|
|
|
1286
1385
|
export class SunspecBattery extends BaseSunspecDevice {
|
|
1287
1386
|
featureMode;
|
|
1288
1387
|
capabilities;
|
|
1388
|
+
/**
|
|
1389
|
+
* Battery data models this device can read: Battery (124, full decode) and
|
|
1390
|
+
* BatteryBase (802, derived decode). BatteryControl (803) is intentionally
|
|
1391
|
+
* excluded — it is a decode stub that yields no telemetry — so a rediscovery
|
|
1392
|
+
* that returns only 803 is treated as unrecovered, matching the connect() gate.
|
|
1393
|
+
*/
|
|
1394
|
+
static BATTERY_MODEL_IDS = [
|
|
1395
|
+
SunspecModelId.Battery,
|
|
1396
|
+
SunspecModelId.BatteryBase
|
|
1397
|
+
];
|
|
1289
1398
|
snapshotService;
|
|
1290
1399
|
calibrationDriver;
|
|
1291
1400
|
batteryCalibrator;
|
|
@@ -1389,16 +1498,17 @@ export class SunspecBattery extends BaseSunspecDevice {
|
|
|
1389
1498
|
getBatteryCalibrator() {
|
|
1390
1499
|
return this.batteryCalibrator;
|
|
1391
1500
|
}
|
|
1501
|
+
getRequiredModelIds() {
|
|
1502
|
+
return SunspecBattery.BATTERY_MODEL_IDS;
|
|
1503
|
+
}
|
|
1392
1504
|
/**
|
|
1393
1505
|
* Connect to the battery and create/update the appliance
|
|
1394
1506
|
*/
|
|
1395
1507
|
async connect(inverterApplianceId) {
|
|
1396
1508
|
// Ensure Sunspec client is connected
|
|
1397
1509
|
await this.ensureConnected();
|
|
1398
|
-
// Check if battery models exist
|
|
1399
|
-
|
|
1400
|
-
this.sunspecClient.findModel(this.unitId, SunspecModelId.BatteryBase) !== undefined;
|
|
1401
|
-
if (!hasBattery) {
|
|
1510
|
+
// Check if battery models exist (124 or 802 — see BATTERY_MODEL_IDS).
|
|
1511
|
+
if (!this.hasRequiredModels()) {
|
|
1402
1512
|
throw new Error('No battery model found in device');
|
|
1403
1513
|
}
|
|
1404
1514
|
// Get device info
|
|
@@ -1973,6 +2083,20 @@ export class SunspecBattery extends BaseSunspecDevice {
|
|
|
1973
2083
|
*/
|
|
1974
2084
|
export class SunspecMeter extends BaseSunspecDevice {
|
|
1975
2085
|
capabilities;
|
|
2086
|
+
/**
|
|
2087
|
+
* Meter data models this device can read, across int+SF (201/203/204) and
|
|
2088
|
+
* IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
|
|
2089
|
+
* variants. Used when the meter is not bound to a specific instance.
|
|
2090
|
+
*/
|
|
2091
|
+
static METER_MODEL_IDS = [
|
|
2092
|
+
SunspecModelId.MeterSinglePhase,
|
|
2093
|
+
SunspecModelId.Meter3Phase,
|
|
2094
|
+
SunspecModelId.MeterWye,
|
|
2095
|
+
SunspecModelId.MeterSinglePhaseFloat,
|
|
2096
|
+
SunspecModelId.MeterSplitPhaseFloat,
|
|
2097
|
+
SunspecModelId.Meter3PhaseWyeFloat,
|
|
2098
|
+
SunspecModelId.Meter3PhaseDeltaFloat
|
|
2099
|
+
];
|
|
1976
2100
|
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
|
|
1977
2101
|
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
1978
2102
|
this.capabilities = capabilities;
|
|
@@ -1991,22 +2115,23 @@ export class SunspecMeter extends BaseSunspecDevice {
|
|
|
1991
2115
|
bindMeterModel(model) {
|
|
1992
2116
|
this.meterModel = model;
|
|
1993
2117
|
}
|
|
2118
|
+
/**
|
|
2119
|
+
* A bound meter requires ITS own pinned model id to reappear after a
|
|
2120
|
+
* rediscovery; an unbound meter accepts any meter model on its unit.
|
|
2121
|
+
*/
|
|
2122
|
+
getRequiredModelIds() {
|
|
2123
|
+
return this.meterModel ? [this.meterModel.id] : SunspecMeter.METER_MODEL_IDS;
|
|
2124
|
+
}
|
|
1994
2125
|
/**
|
|
1995
2126
|
* Connect to the meter and create/update the appliance
|
|
1996
2127
|
*/
|
|
1997
2128
|
async connect() {
|
|
1998
2129
|
// Connect with specific unit ID for meter
|
|
1999
2130
|
await this.ensureConnected();
|
|
2000
|
-
// Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214)
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
this.sunspecClient.findModel(this.unitId, SunspecModelId.MeterSinglePhase) !== undefined ||
|
|
2005
|
-
this.sunspecClient.findModel(this.unitId, SunspecModelId.Meter3PhaseWyeFloat) !== undefined ||
|
|
2006
|
-
this.sunspecClient.findModel(this.unitId, SunspecModelId.Meter3PhaseDeltaFloat) !== undefined ||
|
|
2007
|
-
this.sunspecClient.findModel(this.unitId, SunspecModelId.MeterSplitPhaseFloat) !== undefined ||
|
|
2008
|
-
this.sunspecClient.findModel(this.unitId, SunspecModelId.MeterSinglePhaseFloat) !== undefined;
|
|
2009
|
-
if (!hasMeter) {
|
|
2131
|
+
// Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214).
|
|
2132
|
+
// A bound meter short-circuits: getRequiredModelIds() returns [meterModel.id],
|
|
2133
|
+
// which the just-completed discovery re-listed for the same physical device.
|
|
2134
|
+
if (!this.hasRequiredModels()) {
|
|
2010
2135
|
throw new Error('No meter model found in device');
|
|
2011
2136
|
}
|
|
2012
2137
|
// Get device info. For a bound meter instance, read ITS own Common block (the one
|
|
@@ -2128,3 +2253,345 @@ export class SunspecMeter extends BaseSunspecDevice {
|
|
|
2128
2253
|
return messages;
|
|
2129
2254
|
}
|
|
2130
2255
|
}
|
|
2256
|
+
/** Appliance type created for each custom-device role (battery emulates a Storage appliance). */
|
|
2257
|
+
const CUSTOM_ROLE_APPLIANCE_TYPE = {
|
|
2258
|
+
meter: EnyoApplianceTypeEnum.Meter,
|
|
2259
|
+
inverter: EnyoApplianceTypeEnum.Inverter,
|
|
2260
|
+
battery: EnyoApplianceTypeEnum.Storage,
|
|
2261
|
+
};
|
|
2262
|
+
/** Natural register width per data type, used when a register omits an explicit `quantity`. */
|
|
2263
|
+
const CUSTOM_REGISTER_DEFAULT_QUANTITY = {
|
|
2264
|
+
uint16: 1,
|
|
2265
|
+
int16: 1,
|
|
2266
|
+
acc16: 1,
|
|
2267
|
+
uint32: 2,
|
|
2268
|
+
int32: 2,
|
|
2269
|
+
acc32: 2,
|
|
2270
|
+
float32: 2,
|
|
2271
|
+
string: 1,
|
|
2272
|
+
};
|
|
2273
|
+
/** Numeric databus fields a `meter`-role custom device may populate. */
|
|
2274
|
+
const CUSTOM_METER_FIELDS = [
|
|
2275
|
+
'gridPowerW', 'gridPowerPhase1W', 'gridPowerPhase2W', 'gridPowerPhase3W',
|
|
2276
|
+
'gridFeedInWh', 'gridConsumptionWh', 'selfConsumptionW', 'selfConsumptionWh',
|
|
2277
|
+
];
|
|
2278
|
+
/** Numeric databus fields an `inverter`-role custom device may populate. */
|
|
2279
|
+
const CUSTOM_INVERTER_FIELDS = [
|
|
2280
|
+
'pvPowerW', 'voltageL1', 'voltageL2', 'voltageL3',
|
|
2281
|
+
'currentL1', 'currentL2', 'currentL3', 'dcPowerW',
|
|
2282
|
+
'activePowerLimitationW', 'meterValueWh',
|
|
2283
|
+
];
|
|
2284
|
+
/** Numeric databus fields a `battery`-role custom device may populate. */
|
|
2285
|
+
const CUSTOM_BATTERY_FIELDS = [
|
|
2286
|
+
'batterySoC', 'batteryPowerW', 'dcStringInputPowerW',
|
|
2287
|
+
];
|
|
2288
|
+
/** Default {@link SunspecCustomDeviceConfig.blockSize}: the Modbus FC03/FC04 per-read limit. */
|
|
2289
|
+
const CUSTOM_DEFAULT_BLOCK_SIZE = 125;
|
|
2290
|
+
/**
|
|
2291
|
+
* A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
|
|
2292
|
+
* SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
|
|
2293
|
+
* {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
|
|
2294
|
+
* per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
|
|
2295
|
+
* instead of a discovered SunSpec model directory.
|
|
2296
|
+
*
|
|
2297
|
+
* It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
|
|
2298
|
+
* the role selects the appliance type created on connect and which EnyoDataBus values message
|
|
2299
|
+
* {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
|
|
2300
|
+
* that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
|
|
2301
|
+
*
|
|
2302
|
+
* Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
|
|
2303
|
+
* validated by socket liveness rather than a SunSpec scan.
|
|
2304
|
+
*/
|
|
2305
|
+
export class SunspecCustomDevice extends BaseSunspecDevice {
|
|
2306
|
+
config;
|
|
2307
|
+
/** Read plan derived once from the static register map (see {@link planBlocks}). */
|
|
2308
|
+
plannedBlocks;
|
|
2309
|
+
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, config, unitId = 1, port = 502, baseAddress = 40000, retryConfig, appliance, useTls) {
|
|
2310
|
+
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
2311
|
+
this.config = config;
|
|
2312
|
+
}
|
|
2313
|
+
/**
|
|
2314
|
+
* No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
|
|
2315
|
+
* the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
|
|
2316
|
+
* socket without a SunS scan.
|
|
2317
|
+
*/
|
|
2318
|
+
async discoverAfterConnect() {
|
|
2319
|
+
// Intentionally empty: plain-Modbus device, no SunSpec discovery.
|
|
2320
|
+
}
|
|
2321
|
+
/**
|
|
2322
|
+
* A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
|
|
2323
|
+
* Without this override the base default would run SunSpec discovery, find nothing, and treat every
|
|
2324
|
+
* reconnect as a permanent failure.
|
|
2325
|
+
*/
|
|
2326
|
+
async revalidateAfterReconnect() {
|
|
2327
|
+
return this.sunspecClient.isConnected(this.unitId);
|
|
2328
|
+
}
|
|
2329
|
+
/**
|
|
2330
|
+
* Connect the underlying socket (no discovery) and create/update the appliance for the configured
|
|
2331
|
+
* role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
|
|
2332
|
+
* SunSpec Common block to read it from.
|
|
2333
|
+
*/
|
|
2334
|
+
async connect() {
|
|
2335
|
+
if (!this.sunspecClient.isConnected(this.unitId)) {
|
|
2336
|
+
await this.sunspecClient.connect(this.networkDevice.hostname, // primary
|
|
2337
|
+
this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
|
|
2338
|
+
this.useTls);
|
|
2339
|
+
// No discoverModels(): this device reads a pre-defined static register map.
|
|
2340
|
+
}
|
|
2341
|
+
const applianceType = CUSTOM_ROLE_APPLIANCE_TYPE[this.config.role];
|
|
2342
|
+
if (!this.applianceId) {
|
|
2343
|
+
try {
|
|
2344
|
+
this.applianceId = await this.applianceManager.createOrUpdateAppliance({
|
|
2345
|
+
name: this.name,
|
|
2346
|
+
type: applianceType,
|
|
2347
|
+
networkDevices: [this.networkDevice],
|
|
2348
|
+
metadata: {
|
|
2349
|
+
connectionType: EnyoApplianceConnectionType.Connector,
|
|
2350
|
+
state: EnyoApplianceStateEnum.Connected,
|
|
2351
|
+
serialNumber: this.config.identity?.serialNumber,
|
|
2352
|
+
modelName: this.config.identity?.modelName,
|
|
2353
|
+
vendorName: this.config.identity?.vendorName,
|
|
2354
|
+
modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
|
|
2355
|
+
},
|
|
2356
|
+
});
|
|
2357
|
+
console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
|
|
2358
|
+
}
|
|
2359
|
+
catch (error) {
|
|
2360
|
+
console.error(`Failed to create custom ${this.config.role} appliance: ${error}`);
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
else {
|
|
2364
|
+
try {
|
|
2365
|
+
const existingAppliance = await this.applianceManager.findApplianceById(this.applianceId);
|
|
2366
|
+
await this.applianceManager.updateAppliance(this.applianceId, {
|
|
2367
|
+
metadata: {
|
|
2368
|
+
...existingAppliance?.metadata,
|
|
2369
|
+
connectionType: EnyoApplianceConnectionType.Connector,
|
|
2370
|
+
state: EnyoApplianceStateEnum.Connected,
|
|
2371
|
+
modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
|
|
2372
|
+
}
|
|
2373
|
+
});
|
|
2374
|
+
console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
|
|
2375
|
+
}
|
|
2376
|
+
catch (error) {
|
|
2377
|
+
console.error(`Failed to update custom ${this.config.role} appliance: ${error}`);
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
async disconnect() {
|
|
2382
|
+
if (this.applianceId) {
|
|
2383
|
+
try {
|
|
2384
|
+
await this.applianceManager.updateApplianceState(this.applianceId, EnyoApplianceConnectionType.Connector, EnyoApplianceStateEnum.Offline);
|
|
2385
|
+
}
|
|
2386
|
+
catch (error) {
|
|
2387
|
+
console.error(`Failed to mark custom ${this.config.role} offline on disconnect: ${error}`);
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
// Close just this device's unit; siblings on the same network device stay open.
|
|
2391
|
+
await this.sunspecClient.disconnectUnit(this.unitId);
|
|
2392
|
+
}
|
|
2393
|
+
async readData(clockId, resolution) {
|
|
2394
|
+
if (!this.isConnected()) {
|
|
2395
|
+
await this.tryReconnect();
|
|
2396
|
+
if (!this.isConnected())
|
|
2397
|
+
return [];
|
|
2398
|
+
}
|
|
2399
|
+
const messages = [];
|
|
2400
|
+
const timestamp = new Date();
|
|
2401
|
+
try {
|
|
2402
|
+
const values = await this.readConfiguredRegisters();
|
|
2403
|
+
// readRegisterValue throws on a failed read (unlike the SunSpec model readers), so a dead
|
|
2404
|
+
// socket lands in catch below. This also covers the health-counter path when the transport
|
|
2405
|
+
// records failures without throwing.
|
|
2406
|
+
if (await this.markOfflineIfUnhealthy()) {
|
|
2407
|
+
return messages;
|
|
2408
|
+
}
|
|
2409
|
+
// Healthy read: if a sibling on the same shared socket reconnected us, flip our appliance
|
|
2410
|
+
// state back to Connected. No-op unless this device is still marked offline.
|
|
2411
|
+
await this.reassertConnectedIfRecovered();
|
|
2412
|
+
messages.push(this.buildRoleMessage(values, clockId, resolution, timestamp));
|
|
2413
|
+
this.lastUpdateTime = timestamp.getTime();
|
|
2414
|
+
}
|
|
2415
|
+
catch (error) {
|
|
2416
|
+
console.error(`Error updating custom ${this.config.role} data: ${error}`);
|
|
2417
|
+
await this.markOffline();
|
|
2418
|
+
}
|
|
2419
|
+
return messages;
|
|
2420
|
+
}
|
|
2421
|
+
/**
|
|
2422
|
+
* Write a value to a pre-configured writable register. Delegates to the client's resilient
|
|
2423
|
+
* {@link SunspecModbusClient.writeRegisterValue}.
|
|
2424
|
+
*/
|
|
2425
|
+
async writeCustomRegister(name, value) {
|
|
2426
|
+
const reg = this.config.writeRegisters?.find(r => r.name === name);
|
|
2427
|
+
if (!reg) {
|
|
2428
|
+
throw new Error(`No writable register named '${name}' configured for custom ${this.config.role}`);
|
|
2429
|
+
}
|
|
2430
|
+
return this.sunspecClient.writeRegisterValue(this.unitId, reg.address, value, reg.dataType);
|
|
2431
|
+
}
|
|
2432
|
+
/**
|
|
2433
|
+
* Read every configured register as a small number of block reads and extract each register from
|
|
2434
|
+
* its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
|
|
2435
|
+
* scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
|
|
2436
|
+
* populate a numeric databus field) are skipped with a warning.
|
|
2437
|
+
*/
|
|
2438
|
+
async readConfiguredRegisters() {
|
|
2439
|
+
const values = new Map();
|
|
2440
|
+
for (const block of this.getPlannedBlocks()) {
|
|
2441
|
+
const buffer = await this.sunspecClient.readRegisterBlock(this.unitId, block.startAddress, block.length, block.useInputRegisters);
|
|
2442
|
+
for (const member of block.members) {
|
|
2443
|
+
const raw = this.sunspecClient.decodeBlockValue(buffer, member.offset, member.dataType, member.quantity);
|
|
2444
|
+
if (typeof raw !== 'number') {
|
|
2445
|
+
console.warn(`Custom ${this.config.role}: register '${member.field}' returned a non-numeric value; skipping`);
|
|
2446
|
+
continue;
|
|
2447
|
+
}
|
|
2448
|
+
values.set(member.field, raw * Math.pow(10, member.scaleFactor));
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
return values;
|
|
2452
|
+
}
|
|
2453
|
+
/** Lazily compute and cache the block read plan; the register map is static per device. */
|
|
2454
|
+
getPlannedBlocks() {
|
|
2455
|
+
if (!this.plannedBlocks) {
|
|
2456
|
+
this.plannedBlocks = this.planBlocks();
|
|
2457
|
+
}
|
|
2458
|
+
return this.plannedBlocks;
|
|
2459
|
+
}
|
|
2460
|
+
/**
|
|
2461
|
+
* Group the configured registers (separately per function code) sorted by address, coalescing them
|
|
2462
|
+
* — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
|
|
2463
|
+
* starts whenever adding the next register would exceed that span. Each block records its members'
|
|
2464
|
+
* offsets so a single read can be sliced into all of them.
|
|
2465
|
+
*/
|
|
2466
|
+
planBlocks() {
|
|
2467
|
+
const blockSize = Math.max(1, this.config.blockSize ?? CUSTOM_DEFAULT_BLOCK_SIZE);
|
|
2468
|
+
const blocks = [];
|
|
2469
|
+
// Group by function code so FC03 and FC04 registers never share a block.
|
|
2470
|
+
const groups = new Map();
|
|
2471
|
+
for (const reg of this.config.registers) {
|
|
2472
|
+
const useInputRegisters = reg.functionCode === 4;
|
|
2473
|
+
const list = groups.get(useInputRegisters);
|
|
2474
|
+
if (list) {
|
|
2475
|
+
list.push(reg);
|
|
2476
|
+
}
|
|
2477
|
+
else {
|
|
2478
|
+
groups.set(useInputRegisters, [reg]);
|
|
2479
|
+
}
|
|
2480
|
+
}
|
|
2481
|
+
for (const [useInputRegisters, regs] of groups) {
|
|
2482
|
+
const spans = regs
|
|
2483
|
+
.map(reg => {
|
|
2484
|
+
const quantity = reg.quantity ?? CUSTOM_REGISTER_DEFAULT_QUANTITY[reg.dataType];
|
|
2485
|
+
return { reg, quantity, start: reg.address, end: reg.address + quantity };
|
|
2486
|
+
})
|
|
2487
|
+
.sort((a, b) => a.start - b.start);
|
|
2488
|
+
let current;
|
|
2489
|
+
let currentEnd = 0;
|
|
2490
|
+
for (const span of spans) {
|
|
2491
|
+
const member = (offset) => ({
|
|
2492
|
+
field: span.reg.field,
|
|
2493
|
+
dataType: span.reg.dataType,
|
|
2494
|
+
quantity: span.quantity,
|
|
2495
|
+
offset,
|
|
2496
|
+
scaleFactor: span.reg.scaleFactor ?? 0,
|
|
2497
|
+
});
|
|
2498
|
+
// Extend the current block only if the whole span (start .. farthest end) still fits
|
|
2499
|
+
// within blockSize. The first register always opens a block (a lone register wider than
|
|
2500
|
+
// blockSize is still read — readRegisterBlock chunks it).
|
|
2501
|
+
const mergedEnd = current ? Math.max(currentEnd, span.end) : span.end;
|
|
2502
|
+
if (current && mergedEnd - current.startAddress <= blockSize) {
|
|
2503
|
+
current.members.push(member(span.start - current.startAddress));
|
|
2504
|
+
currentEnd = mergedEnd;
|
|
2505
|
+
current.length = currentEnd - current.startAddress;
|
|
2506
|
+
}
|
|
2507
|
+
else {
|
|
2508
|
+
current = {
|
|
2509
|
+
useInputRegisters,
|
|
2510
|
+
startAddress: span.start,
|
|
2511
|
+
length: span.end - span.start,
|
|
2512
|
+
members: [member(0)],
|
|
2513
|
+
};
|
|
2514
|
+
currentEnd = span.end;
|
|
2515
|
+
blocks.push(current);
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
return blocks;
|
|
2520
|
+
}
|
|
2521
|
+
buildRoleMessage(values, clockId, resolution, timestamp) {
|
|
2522
|
+
switch (this.config.role) {
|
|
2523
|
+
case 'meter':
|
|
2524
|
+
return this.buildMeterMessage(values, clockId, resolution, timestamp);
|
|
2525
|
+
case 'inverter':
|
|
2526
|
+
return this.buildInverterMessage(values, clockId, resolution, timestamp);
|
|
2527
|
+
case 'battery':
|
|
2528
|
+
return this.buildBatteryMessage(values, clockId, resolution, timestamp);
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
buildMeterMessage(values, clockId, resolution, timestamp) {
|
|
2532
|
+
const data = { gridFeedInWh: 0, gridConsumptionWh: 0 };
|
|
2533
|
+
for (const field of CUSTOM_METER_FIELDS) {
|
|
2534
|
+
const v = values.get(field);
|
|
2535
|
+
if (v !== undefined) {
|
|
2536
|
+
data[field] = v;
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
return {
|
|
2540
|
+
id: randomUUID(),
|
|
2541
|
+
message: EnyoDataBusMessageEnum.MeterValuesUpdateV1,
|
|
2542
|
+
type: 'message',
|
|
2543
|
+
source: EnyoSourceEnum.Device,
|
|
2544
|
+
applianceId: this.applianceId,
|
|
2545
|
+
clockId,
|
|
2546
|
+
timestampIso: timestamp.toISOString(),
|
|
2547
|
+
resolution,
|
|
2548
|
+
data,
|
|
2549
|
+
};
|
|
2550
|
+
}
|
|
2551
|
+
buildInverterMessage(values, clockId, resolution, timestamp) {
|
|
2552
|
+
const data = { pvPowerW: 0, voltageL1: 0 };
|
|
2553
|
+
for (const field of CUSTOM_INVERTER_FIELDS) {
|
|
2554
|
+
const v = values.get(field);
|
|
2555
|
+
if (v !== undefined) {
|
|
2556
|
+
data[field] = v;
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
if (this.config.defaultInverterState !== undefined) {
|
|
2560
|
+
data.state = this.config.defaultInverterState;
|
|
2561
|
+
}
|
|
2562
|
+
return {
|
|
2563
|
+
id: randomUUID(),
|
|
2564
|
+
message: EnyoDataBusMessageEnum.InverterValuesUpdateV1,
|
|
2565
|
+
type: 'message',
|
|
2566
|
+
source: EnyoSourceEnum.Device,
|
|
2567
|
+
applianceId: this.applianceId,
|
|
2568
|
+
clockId,
|
|
2569
|
+
timestampIso: timestamp.toISOString(),
|
|
2570
|
+
resolution,
|
|
2571
|
+
data,
|
|
2572
|
+
};
|
|
2573
|
+
}
|
|
2574
|
+
buildBatteryMessage(values, clockId, resolution, timestamp) {
|
|
2575
|
+
const data = { batterySoC: 0 };
|
|
2576
|
+
for (const field of CUSTOM_BATTERY_FIELDS) {
|
|
2577
|
+
const v = values.get(field);
|
|
2578
|
+
if (v !== undefined) {
|
|
2579
|
+
data[field] = v;
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
if (this.config.defaultBatteryState !== undefined) {
|
|
2583
|
+
data.state = this.config.defaultBatteryState;
|
|
2584
|
+
}
|
|
2585
|
+
return {
|
|
2586
|
+
id: randomUUID(),
|
|
2587
|
+
message: EnyoDataBusMessageEnum.BatteryValuesUpdateV1,
|
|
2588
|
+
type: 'message',
|
|
2589
|
+
source: EnyoSourceEnum.Device,
|
|
2590
|
+
applianceId: this.applianceId,
|
|
2591
|
+
clockId,
|
|
2592
|
+
timestampIso: timestamp.toISOString(),
|
|
2593
|
+
resolution,
|
|
2594
|
+
data,
|
|
2595
|
+
};
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { EnyoBatteryFeature } from "@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js";
|
|
5
5
|
import { EnyoBatteryStateEnum, EnyoDataBusInverterValuesV1String, EnyoInverterStateEnum } from "@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js";
|
|
6
|
+
import { EnergyAppModbusDataType } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
|
|
6
7
|
/**
|
|
7
8
|
* A single phase in the tiered retry schedule
|
|
8
9
|
*/
|
|
@@ -98,6 +99,86 @@ export interface IModbusResilienceConfig {
|
|
|
98
99
|
connectRetryDelayMs?: number;
|
|
99
100
|
}
|
|
100
101
|
export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
|
|
102
|
+
/**
|
|
103
|
+
* The appliance role a {@link SunspecCustomDeviceConfig} emulates. Selects the appliance type created
|
|
104
|
+
* on connect and which EnyoDataBus values message {@link SunspecCustomDevice.readData} publishes.
|
|
105
|
+
*/
|
|
106
|
+
export type SunspecCustomDeviceRole = 'meter' | 'inverter' | 'battery';
|
|
107
|
+
/**
|
|
108
|
+
* A single pre-defined register a {@link SunspecCustomDevice} reads each poll. Unlike the SunSpec
|
|
109
|
+
* model readers, there is no discovery, scale-factor register, or NOT_IMPLEMENTED sentinel handling:
|
|
110
|
+
* the caller supplies the exact address, type and (optional) fixed scaling for a plain-Modbus device.
|
|
111
|
+
*/
|
|
112
|
+
export interface SunspecCustomRegister {
|
|
113
|
+
/**
|
|
114
|
+
* The databus data-field this register populates for the configured role (e.g. `gridPowerW` for a
|
|
115
|
+
* meter, `pvPowerW` for an inverter, `batterySoC` for a battery). Validated against the role's
|
|
116
|
+
* numeric field set at read time; unknown fields are ignored with a warning.
|
|
117
|
+
*/
|
|
118
|
+
field: string;
|
|
119
|
+
/** Modbus register address (absolute). */
|
|
120
|
+
address: number;
|
|
121
|
+
/** How to decode the raw registers. */
|
|
122
|
+
dataType: EnergyAppModbusDataType;
|
|
123
|
+
/** Registers to read. Defaults to the natural width of {@link dataType} (1 for 16-bit, 2 for 32-bit). */
|
|
124
|
+
quantity?: number;
|
|
125
|
+
/** Fixed decimal scaling applied as `value * 10^scaleFactor`. Default 0 (no scaling). */
|
|
126
|
+
scaleFactor?: number;
|
|
127
|
+
/** Modbus function code: 3 = holding registers (default), 4 = input registers. */
|
|
128
|
+
functionCode?: 3 | 4;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* A writable register exposed through {@link SunspecCustomDevice.writeCustomRegister}. Limited to the
|
|
132
|
+
* data types the client's {@link writeRegisterValue} can serialize (uint16/int16/uint32/int32).
|
|
133
|
+
*/
|
|
134
|
+
export interface SunspecCustomWriteRegister {
|
|
135
|
+
/** Caller-facing handle passed to `writeCustomRegister(name, value)`. */
|
|
136
|
+
name: string;
|
|
137
|
+
/** Modbus register address (absolute). */
|
|
138
|
+
address: number;
|
|
139
|
+
/** How to serialize the value. */
|
|
140
|
+
dataType: EnergyAppModbusDataType;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Declarative configuration for a {@link SunspecCustomDevice}: a plain-Modbus device polled through
|
|
144
|
+
* the SDK's resilient connection management but read from a hand-defined static register map rather
|
|
145
|
+
* than a discovered SunSpec model directory.
|
|
146
|
+
*/
|
|
147
|
+
export interface SunspecCustomDeviceConfig {
|
|
148
|
+
/** Which appliance role to emulate (drives appliance type + emitted databus message). */
|
|
149
|
+
role: SunspecCustomDeviceRole;
|
|
150
|
+
/** The static registers read every poll and mapped onto the role's databus message. */
|
|
151
|
+
registers: SunspecCustomRegister[];
|
|
152
|
+
/**
|
|
153
|
+
* Maximum registers spanned by a single block read. Registers (grouped per function code) are
|
|
154
|
+
* sorted by address and coalesced — across gaps — into as few reads as possible, each spanning at
|
|
155
|
+
* most this many registers; every register is then sliced out of its block buffer by offset, just
|
|
156
|
+
* like a SunSpec model block. Larger blocks mean fewer round-trips but read any unmapped registers
|
|
157
|
+
* in the gaps (which some devices reject). Default 125 (the Modbus FC03/FC04 per-read limit); a
|
|
158
|
+
* block wider than 125 is still chunked internally.
|
|
159
|
+
*/
|
|
160
|
+
blockSize?: number;
|
|
161
|
+
/** Optional writable registers exposed via `writeCustomRegister`. */
|
|
162
|
+
writeRegisters?: SunspecCustomWriteRegister[];
|
|
163
|
+
/**
|
|
164
|
+
* Static operating state to publish for the `inverter` role. Without SunSpec status models there is
|
|
165
|
+
* no register to derive it from, so callers may pin one (e.g. `Mppt`). Ignored for other roles.
|
|
166
|
+
*/
|
|
167
|
+
defaultInverterState?: EnyoInverterStateEnum;
|
|
168
|
+
/**
|
|
169
|
+
* Static operating state to publish for the `battery` role. Ignored for other roles.
|
|
170
|
+
*/
|
|
171
|
+
defaultBatteryState?: EnyoBatteryStateEnum;
|
|
172
|
+
/**
|
|
173
|
+
* Optional identity written to appliance metadata. There is no SunSpec Common block to read it
|
|
174
|
+
* from, so the caller supplies serial/model/vendor if they want them populated.
|
|
175
|
+
*/
|
|
176
|
+
identity?: {
|
|
177
|
+
serialNumber?: string;
|
|
178
|
+
modelName?: string;
|
|
179
|
+
vendorName?: string;
|
|
180
|
+
};
|
|
181
|
+
}
|
|
101
182
|
/**
|
|
102
183
|
* Base interface for all SunSpec blocks
|
|
103
184
|
*/
|