@enyo-energy/sunspec-sdk 0.0.101 → 0.0.103
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 +418 -10
- package/dist/cjs/sunspec-devices.d.cts +108 -3
- package/dist/cjs/sunspec-interfaces.d.cts +81 -0
- package/dist/cjs/sunspec-modbus-client.cjs +198 -54
- package/dist/cjs/sunspec-modbus-client.d.cts +47 -1
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/sunspec-devices.d.ts +108 -3
- package/dist/sunspec-devices.js +416 -9
- package/dist/sunspec-interfaces.d.ts +81 -0
- package/dist/sunspec-modbus-client.d.ts +47 -1
- package/dist/sunspec-modbus-client.js +198 -54
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SunspecMeter = exports.SunspecBattery = exports.SunspecInverter = exports.BaseSunspecDevice = void 0;
|
|
3
|
+
exports.SunspecCustomDevice = exports.SunspecMeter = exports.SunspecBattery = exports.SunspecInverter = exports.BaseSunspecDevice = void 0;
|
|
4
4
|
exports.detectFeaturesFromRegisters = detectFeaturesFromRegisters;
|
|
5
5
|
exports.sumMpptBatteryPowerW = sumMpptBatteryPowerW;
|
|
6
6
|
exports.selectLiveBatteryPowerW = selectLiveBatteryPowerW;
|
|
@@ -117,6 +117,19 @@ class BaseSunspecDevice {
|
|
|
117
117
|
* would otherwise stay Offline forever despite reading data fine.
|
|
118
118
|
*/
|
|
119
119
|
appliedOffline = false;
|
|
120
|
+
/**
|
|
121
|
+
* True once {@link reassertConnectedIfRecovered} has confirmed (via the
|
|
122
|
+
* appliance store) that this device is Connected, so it can stop probing
|
|
123
|
+
* for an *externally* applied Offline state. Distinct from
|
|
124
|
+
* {@link appliedOffline}, which only tracks Offline states this SDK object
|
|
125
|
+
* applied itself. An appliance can be marked Offline by a path outside the
|
|
126
|
+
* SDK object — e.g. the energy-app registering a boot-time offline
|
|
127
|
+
* placeholder before this device came up on a shared socket — which never
|
|
128
|
+
* sets appliedOffline; without reconciling against actual state, such a
|
|
129
|
+
* device stays Offline forever despite reading data fine. Reset in
|
|
130
|
+
* {@link markOffline} so a later Offline episode is re-checked.
|
|
131
|
+
*/
|
|
132
|
+
reconciledExternalOffline = false;
|
|
120
133
|
/**
|
|
121
134
|
* Prefix used when persisting calibration snapshots via the library's
|
|
122
135
|
* {@link SnapshotService}. Kept identical to the key the SDK used before
|
|
@@ -156,9 +169,33 @@ class BaseSunspecDevice {
|
|
|
156
169
|
await this.sunspecClient.connect(this.networkDevice.hostname, // primary
|
|
157
170
|
this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
|
|
158
171
|
this.useTls);
|
|
159
|
-
await this.
|
|
172
|
+
await this.discoverAfterConnect();
|
|
160
173
|
}
|
|
161
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Populate the per-unit model directory after the socket opens. Default: run SunSpec model
|
|
177
|
+
* discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
|
|
178
|
+
* directory (see {@link SunspecCustomDevice}) override this to a no-op.
|
|
179
|
+
*/
|
|
180
|
+
async discoverAfterConnect() {
|
|
181
|
+
await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Validate that a just-completed reconnect actually restored a usable device. Default: re-run
|
|
185
|
+
* SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
|
|
186
|
+
* back with no usable models means the gateway accepted the connection before it was ready to
|
|
187
|
+
* answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
|
|
188
|
+
* running. Discovery-less devices override this to just confirm the socket is open.
|
|
189
|
+
*/
|
|
190
|
+
async revalidateAfterReconnect() {
|
|
191
|
+
const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
|
|
192
|
+
const usable = this.isDiscoveryUsable(models);
|
|
193
|
+
if (!usable) {
|
|
194
|
+
console.warn(`${this.constructor.name} ${this.applianceId}: reconnect discovery returned no usable models ` +
|
|
195
|
+
`(found [${[...models.keys()].join(', ')}])`);
|
|
196
|
+
}
|
|
197
|
+
return usable;
|
|
198
|
+
}
|
|
162
199
|
/**
|
|
163
200
|
* Attempt a reconnection if the tiered retry schedule allows it.
|
|
164
201
|
* Called from readData() when the device is disconnected.
|
|
@@ -193,14 +230,12 @@ class BaseSunspecDevice {
|
|
|
193
230
|
// it's unusable, treat this as a failed reconnect: invalidate the socket so the
|
|
194
231
|
// next poll re-enters tryReconnect(), keep the backoff schedule running, and do
|
|
195
232
|
// NOT reset().
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
this.sunspecClient.invalidateUnit(this.unitId, `reconnect discovery found no usable models for unit ${this.unitId}`);
|
|
233
|
+
if (!(await this.revalidateAfterReconnect())) {
|
|
234
|
+
this.sunspecClient.invalidateUnit(this.unitId, `reconnect revalidation failed for unit ${this.unitId}`);
|
|
199
235
|
this.consecutiveReconnectFailures += 1;
|
|
200
236
|
await this.onConnectionFailure(this.consecutiveReconnectFailures);
|
|
201
237
|
console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
|
|
202
|
-
`opened the socket but
|
|
203
|
-
`(found [${[...models.keys()].join(', ')}]) — retrying with backoff`);
|
|
238
|
+
`opened the socket but revalidation failed — retrying with backoff`);
|
|
204
239
|
return false;
|
|
205
240
|
}
|
|
206
241
|
this.retryManager.reset();
|
|
@@ -315,6 +350,7 @@ class BaseSunspecDevice {
|
|
|
315
350
|
try {
|
|
316
351
|
await this.applianceManager.updateApplianceState(this.applianceId, enyo_appliance_js_1.EnyoApplianceConnectionType.Connector, enyo_appliance_js_1.EnyoApplianceStateEnum.Offline);
|
|
317
352
|
this.appliedOffline = true;
|
|
353
|
+
this.reconciledExternalOffline = false;
|
|
318
354
|
}
|
|
319
355
|
catch (error) {
|
|
320
356
|
console.error(`${this.constructor.name} ${this.applianceId}: Failed to mark appliance offline: ${error}`);
|
|
@@ -330,17 +366,45 @@ class BaseSunspecDevice {
|
|
|
330
366
|
* readData() and skip tryReconnect() entirely, so without this they would
|
|
331
367
|
* stay Offline forever despite reading data fine.
|
|
332
368
|
*
|
|
369
|
+
* Heals two ways an appliance can be stuck Offline while reads succeed:
|
|
370
|
+
* 1. This SDK object marked itself offline ({@link appliedOffline}) and a
|
|
371
|
+
* sibling won the reconnect race — the original shared-socket case.
|
|
372
|
+
* 2. The appliance was marked Offline by a path *outside* this object —
|
|
373
|
+
* e.g. the energy-app registering a boot-time offline placeholder
|
|
374
|
+
* before this device came up on the shared socket — which never sets
|
|
375
|
+
* appliedOffline. We reconcile against the actual stored state so the
|
|
376
|
+
* invariant "healthy reads ⇒ Connected" holds regardless of who
|
|
377
|
+
* applied the Offline.
|
|
378
|
+
*
|
|
333
379
|
* Call this on the success path of readData() (after the
|
|
334
|
-
* markOfflineIfUnhealthy() guard has confirmed the unit is healthy).
|
|
335
|
-
* a
|
|
380
|
+
* markOfflineIfUnhealthy() guard has confirmed the unit is healthy). Cheap:
|
|
381
|
+
* a no-op via the appliedOffline fast path, and the external-state lookup
|
|
382
|
+
* runs at most once per Offline episode (latched by
|
|
383
|
+
* {@link reconciledExternalOffline} once Connected is confirmed).
|
|
336
384
|
*/
|
|
337
385
|
async reassertConnectedIfRecovered() {
|
|
338
|
-
if (!this.
|
|
386
|
+
if (!this.applianceId) {
|
|
339
387
|
return;
|
|
340
388
|
}
|
|
341
389
|
if (!this.sunspecClient.isHealthy(this.unitId)) {
|
|
342
390
|
return;
|
|
343
391
|
}
|
|
392
|
+
let shouldReassert = this.appliedOffline;
|
|
393
|
+
// Not offline by our own hand: it may still be Offline from an
|
|
394
|
+
// externally applied state. Probe the store once until we confirm
|
|
395
|
+
// Connected, then latch so the steady state adds no extra lookups.
|
|
396
|
+
if (!shouldReassert && !this.reconciledExternalOffline) {
|
|
397
|
+
const appliance = await this.applianceManager.findApplianceById(this.applianceId);
|
|
398
|
+
if (appliance?.metadata?.state === enyo_appliance_js_1.EnyoApplianceStateEnum.Offline) {
|
|
399
|
+
shouldReassert = true;
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
this.reconciledExternalOffline = true;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (!shouldReassert) {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
344
408
|
console.log(`${this.constructor.name} ${this.applianceId}: connection recovered via shared socket — re-asserting Connected`);
|
|
345
409
|
try {
|
|
346
410
|
await this.applianceManager.updateApplianceState(this.applianceId, enyo_appliance_js_1.EnyoApplianceConnectionType.Connector, enyo_appliance_js_1.EnyoApplianceStateEnum.Connected);
|
|
@@ -350,6 +414,7 @@ class BaseSunspecDevice {
|
|
|
350
414
|
return;
|
|
351
415
|
}
|
|
352
416
|
this.appliedOffline = false;
|
|
417
|
+
this.reconciledExternalOffline = true;
|
|
353
418
|
this.retryManager.reset();
|
|
354
419
|
this.consecutiveReconnectFailures = 0;
|
|
355
420
|
await this.onConnectionRestored();
|
|
@@ -2242,3 +2307,346 @@ class SunspecMeter extends BaseSunspecDevice {
|
|
|
2242
2307
|
}
|
|
2243
2308
|
}
|
|
2244
2309
|
exports.SunspecMeter = SunspecMeter;
|
|
2310
|
+
/** Appliance type created for each custom-device role (battery emulates a Storage appliance). */
|
|
2311
|
+
const CUSTOM_ROLE_APPLIANCE_TYPE = {
|
|
2312
|
+
meter: enyo_appliance_js_1.EnyoApplianceTypeEnum.Meter,
|
|
2313
|
+
inverter: enyo_appliance_js_1.EnyoApplianceTypeEnum.Inverter,
|
|
2314
|
+
battery: enyo_appliance_js_1.EnyoApplianceTypeEnum.Storage,
|
|
2315
|
+
};
|
|
2316
|
+
/** Natural register width per data type, used when a register omits an explicit `quantity`. */
|
|
2317
|
+
const CUSTOM_REGISTER_DEFAULT_QUANTITY = {
|
|
2318
|
+
uint16: 1,
|
|
2319
|
+
int16: 1,
|
|
2320
|
+
acc16: 1,
|
|
2321
|
+
uint32: 2,
|
|
2322
|
+
int32: 2,
|
|
2323
|
+
acc32: 2,
|
|
2324
|
+
float32: 2,
|
|
2325
|
+
string: 1,
|
|
2326
|
+
};
|
|
2327
|
+
/** Numeric databus fields a `meter`-role custom device may populate. */
|
|
2328
|
+
const CUSTOM_METER_FIELDS = [
|
|
2329
|
+
'gridPowerW', 'gridPowerPhase1W', 'gridPowerPhase2W', 'gridPowerPhase3W',
|
|
2330
|
+
'gridFeedInWh', 'gridConsumptionWh', 'selfConsumptionW', 'selfConsumptionWh',
|
|
2331
|
+
];
|
|
2332
|
+
/** Numeric databus fields an `inverter`-role custom device may populate. */
|
|
2333
|
+
const CUSTOM_INVERTER_FIELDS = [
|
|
2334
|
+
'pvPowerW', 'voltageL1', 'voltageL2', 'voltageL3',
|
|
2335
|
+
'currentL1', 'currentL2', 'currentL3', 'dcPowerW',
|
|
2336
|
+
'activePowerLimitationW', 'meterValueWh',
|
|
2337
|
+
];
|
|
2338
|
+
/** Numeric databus fields a `battery`-role custom device may populate. */
|
|
2339
|
+
const CUSTOM_BATTERY_FIELDS = [
|
|
2340
|
+
'batterySoC', 'batteryPowerW', 'dcStringInputPowerW',
|
|
2341
|
+
];
|
|
2342
|
+
/** Default {@link SunspecCustomDeviceConfig.blockSize}: the Modbus FC03/FC04 per-read limit. */
|
|
2343
|
+
const CUSTOM_DEFAULT_BLOCK_SIZE = 125;
|
|
2344
|
+
/**
|
|
2345
|
+
* A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
|
|
2346
|
+
* SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
|
|
2347
|
+
* {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
|
|
2348
|
+
* per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
|
|
2349
|
+
* instead of a discovered SunSpec model directory.
|
|
2350
|
+
*
|
|
2351
|
+
* It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
|
|
2352
|
+
* the role selects the appliance type created on connect and which EnyoDataBus values message
|
|
2353
|
+
* {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
|
|
2354
|
+
* that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
|
|
2355
|
+
*
|
|
2356
|
+
* Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
|
|
2357
|
+
* validated by socket liveness rather than a SunSpec scan.
|
|
2358
|
+
*/
|
|
2359
|
+
class SunspecCustomDevice extends BaseSunspecDevice {
|
|
2360
|
+
config;
|
|
2361
|
+
/** Read plan derived once from the static register map (see {@link planBlocks}). */
|
|
2362
|
+
plannedBlocks;
|
|
2363
|
+
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, config, unitId = 1, port = 502, baseAddress = 40000, retryConfig, appliance, useTls) {
|
|
2364
|
+
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
2365
|
+
this.config = config;
|
|
2366
|
+
}
|
|
2367
|
+
/**
|
|
2368
|
+
* No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
|
|
2369
|
+
* the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
|
|
2370
|
+
* socket without a SunS scan.
|
|
2371
|
+
*/
|
|
2372
|
+
async discoverAfterConnect() {
|
|
2373
|
+
// Intentionally empty: plain-Modbus device, no SunSpec discovery.
|
|
2374
|
+
}
|
|
2375
|
+
/**
|
|
2376
|
+
* A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
|
|
2377
|
+
* Without this override the base default would run SunSpec discovery, find nothing, and treat every
|
|
2378
|
+
* reconnect as a permanent failure.
|
|
2379
|
+
*/
|
|
2380
|
+
async revalidateAfterReconnect() {
|
|
2381
|
+
return this.sunspecClient.isConnected(this.unitId);
|
|
2382
|
+
}
|
|
2383
|
+
/**
|
|
2384
|
+
* Connect the underlying socket (no discovery) and create/update the appliance for the configured
|
|
2385
|
+
* role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
|
|
2386
|
+
* SunSpec Common block to read it from.
|
|
2387
|
+
*/
|
|
2388
|
+
async connect() {
|
|
2389
|
+
if (!this.sunspecClient.isConnected(this.unitId)) {
|
|
2390
|
+
await this.sunspecClient.connect(this.networkDevice.hostname, // primary
|
|
2391
|
+
this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
|
|
2392
|
+
this.useTls);
|
|
2393
|
+
// No discoverModels(): this device reads a pre-defined static register map.
|
|
2394
|
+
}
|
|
2395
|
+
const applianceType = CUSTOM_ROLE_APPLIANCE_TYPE[this.config.role];
|
|
2396
|
+
if (!this.applianceId) {
|
|
2397
|
+
try {
|
|
2398
|
+
this.applianceId = await this.applianceManager.createOrUpdateAppliance({
|
|
2399
|
+
name: this.name,
|
|
2400
|
+
type: applianceType,
|
|
2401
|
+
networkDevices: [this.networkDevice],
|
|
2402
|
+
metadata: {
|
|
2403
|
+
connectionType: enyo_appliance_js_1.EnyoApplianceConnectionType.Connector,
|
|
2404
|
+
state: enyo_appliance_js_1.EnyoApplianceStateEnum.Connected,
|
|
2405
|
+
serialNumber: this.config.identity?.serialNumber,
|
|
2406
|
+
modelName: this.config.identity?.modelName,
|
|
2407
|
+
vendorName: this.config.identity?.vendorName,
|
|
2408
|
+
modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
|
|
2409
|
+
},
|
|
2410
|
+
});
|
|
2411
|
+
console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
|
|
2412
|
+
}
|
|
2413
|
+
catch (error) {
|
|
2414
|
+
console.error(`Failed to create custom ${this.config.role} appliance: ${error}`);
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
else {
|
|
2418
|
+
try {
|
|
2419
|
+
const existingAppliance = await this.applianceManager.findApplianceById(this.applianceId);
|
|
2420
|
+
await this.applianceManager.updateAppliance(this.applianceId, {
|
|
2421
|
+
metadata: {
|
|
2422
|
+
...existingAppliance?.metadata,
|
|
2423
|
+
connectionType: enyo_appliance_js_1.EnyoApplianceConnectionType.Connector,
|
|
2424
|
+
state: enyo_appliance_js_1.EnyoApplianceStateEnum.Connected,
|
|
2425
|
+
modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
|
|
2426
|
+
}
|
|
2427
|
+
});
|
|
2428
|
+
console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
|
|
2429
|
+
}
|
|
2430
|
+
catch (error) {
|
|
2431
|
+
console.error(`Failed to update custom ${this.config.role} appliance: ${error}`);
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
async disconnect() {
|
|
2436
|
+
if (this.applianceId) {
|
|
2437
|
+
try {
|
|
2438
|
+
await this.applianceManager.updateApplianceState(this.applianceId, enyo_appliance_js_1.EnyoApplianceConnectionType.Connector, enyo_appliance_js_1.EnyoApplianceStateEnum.Offline);
|
|
2439
|
+
}
|
|
2440
|
+
catch (error) {
|
|
2441
|
+
console.error(`Failed to mark custom ${this.config.role} offline on disconnect: ${error}`);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
// Close just this device's unit; siblings on the same network device stay open.
|
|
2445
|
+
await this.sunspecClient.disconnectUnit(this.unitId);
|
|
2446
|
+
}
|
|
2447
|
+
async readData(clockId, resolution) {
|
|
2448
|
+
if (!this.isConnected()) {
|
|
2449
|
+
await this.tryReconnect();
|
|
2450
|
+
if (!this.isConnected())
|
|
2451
|
+
return [];
|
|
2452
|
+
}
|
|
2453
|
+
const messages = [];
|
|
2454
|
+
const timestamp = new Date();
|
|
2455
|
+
try {
|
|
2456
|
+
const values = await this.readConfiguredRegisters();
|
|
2457
|
+
// readRegisterValue throws on a failed read (unlike the SunSpec model readers), so a dead
|
|
2458
|
+
// socket lands in catch below. This also covers the health-counter path when the transport
|
|
2459
|
+
// records failures without throwing.
|
|
2460
|
+
if (await this.markOfflineIfUnhealthy()) {
|
|
2461
|
+
return messages;
|
|
2462
|
+
}
|
|
2463
|
+
// Healthy read: if a sibling on the same shared socket reconnected us, flip our appliance
|
|
2464
|
+
// state back to Connected. No-op unless this device is still marked offline.
|
|
2465
|
+
await this.reassertConnectedIfRecovered();
|
|
2466
|
+
messages.push(this.buildRoleMessage(values, clockId, resolution, timestamp));
|
|
2467
|
+
this.lastUpdateTime = timestamp.getTime();
|
|
2468
|
+
}
|
|
2469
|
+
catch (error) {
|
|
2470
|
+
console.error(`Error updating custom ${this.config.role} data: ${error}`);
|
|
2471
|
+
await this.markOffline();
|
|
2472
|
+
}
|
|
2473
|
+
return messages;
|
|
2474
|
+
}
|
|
2475
|
+
/**
|
|
2476
|
+
* Write a value to a pre-configured writable register. Delegates to the client's resilient
|
|
2477
|
+
* {@link SunspecModbusClient.writeRegisterValue}.
|
|
2478
|
+
*/
|
|
2479
|
+
async writeCustomRegister(name, value) {
|
|
2480
|
+
const reg = this.config.writeRegisters?.find(r => r.name === name);
|
|
2481
|
+
if (!reg) {
|
|
2482
|
+
throw new Error(`No writable register named '${name}' configured for custom ${this.config.role}`);
|
|
2483
|
+
}
|
|
2484
|
+
return this.sunspecClient.writeRegisterValue(this.unitId, reg.address, value, reg.dataType);
|
|
2485
|
+
}
|
|
2486
|
+
/**
|
|
2487
|
+
* Read every configured register as a small number of block reads and extract each register from
|
|
2488
|
+
* its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
|
|
2489
|
+
* scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
|
|
2490
|
+
* populate a numeric databus field) are skipped with a warning.
|
|
2491
|
+
*/
|
|
2492
|
+
async readConfiguredRegisters() {
|
|
2493
|
+
const values = new Map();
|
|
2494
|
+
for (const block of this.getPlannedBlocks()) {
|
|
2495
|
+
const buffer = await this.sunspecClient.readRegisterBlock(this.unitId, block.startAddress, block.length, block.useInputRegisters);
|
|
2496
|
+
for (const member of block.members) {
|
|
2497
|
+
const raw = this.sunspecClient.decodeBlockValue(buffer, member.offset, member.dataType, member.quantity);
|
|
2498
|
+
if (typeof raw !== 'number') {
|
|
2499
|
+
console.warn(`Custom ${this.config.role}: register '${member.field}' returned a non-numeric value; skipping`);
|
|
2500
|
+
continue;
|
|
2501
|
+
}
|
|
2502
|
+
values.set(member.field, raw * Math.pow(10, member.scaleFactor));
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
return values;
|
|
2506
|
+
}
|
|
2507
|
+
/** Lazily compute and cache the block read plan; the register map is static per device. */
|
|
2508
|
+
getPlannedBlocks() {
|
|
2509
|
+
if (!this.plannedBlocks) {
|
|
2510
|
+
this.plannedBlocks = this.planBlocks();
|
|
2511
|
+
}
|
|
2512
|
+
return this.plannedBlocks;
|
|
2513
|
+
}
|
|
2514
|
+
/**
|
|
2515
|
+
* Group the configured registers (separately per function code) sorted by address, coalescing them
|
|
2516
|
+
* — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
|
|
2517
|
+
* starts whenever adding the next register would exceed that span. Each block records its members'
|
|
2518
|
+
* offsets so a single read can be sliced into all of them.
|
|
2519
|
+
*/
|
|
2520
|
+
planBlocks() {
|
|
2521
|
+
const blockSize = Math.max(1, this.config.blockSize ?? CUSTOM_DEFAULT_BLOCK_SIZE);
|
|
2522
|
+
const blocks = [];
|
|
2523
|
+
// Group by function code so FC03 and FC04 registers never share a block.
|
|
2524
|
+
const groups = new Map();
|
|
2525
|
+
for (const reg of this.config.registers) {
|
|
2526
|
+
const useInputRegisters = reg.functionCode === 4;
|
|
2527
|
+
const list = groups.get(useInputRegisters);
|
|
2528
|
+
if (list) {
|
|
2529
|
+
list.push(reg);
|
|
2530
|
+
}
|
|
2531
|
+
else {
|
|
2532
|
+
groups.set(useInputRegisters, [reg]);
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
for (const [useInputRegisters, regs] of groups) {
|
|
2536
|
+
const spans = regs
|
|
2537
|
+
.map(reg => {
|
|
2538
|
+
const quantity = reg.quantity ?? CUSTOM_REGISTER_DEFAULT_QUANTITY[reg.dataType];
|
|
2539
|
+
return { reg, quantity, start: reg.address, end: reg.address + quantity };
|
|
2540
|
+
})
|
|
2541
|
+
.sort((a, b) => a.start - b.start);
|
|
2542
|
+
let current;
|
|
2543
|
+
let currentEnd = 0;
|
|
2544
|
+
for (const span of spans) {
|
|
2545
|
+
const member = (offset) => ({
|
|
2546
|
+
field: span.reg.field,
|
|
2547
|
+
dataType: span.reg.dataType,
|
|
2548
|
+
quantity: span.quantity,
|
|
2549
|
+
offset,
|
|
2550
|
+
scaleFactor: span.reg.scaleFactor ?? 0,
|
|
2551
|
+
});
|
|
2552
|
+
// Extend the current block only if the whole span (start .. farthest end) still fits
|
|
2553
|
+
// within blockSize. The first register always opens a block (a lone register wider than
|
|
2554
|
+
// blockSize is still read — readRegisterBlock chunks it).
|
|
2555
|
+
const mergedEnd = current ? Math.max(currentEnd, span.end) : span.end;
|
|
2556
|
+
if (current && mergedEnd - current.startAddress <= blockSize) {
|
|
2557
|
+
current.members.push(member(span.start - current.startAddress));
|
|
2558
|
+
currentEnd = mergedEnd;
|
|
2559
|
+
current.length = currentEnd - current.startAddress;
|
|
2560
|
+
}
|
|
2561
|
+
else {
|
|
2562
|
+
current = {
|
|
2563
|
+
useInputRegisters,
|
|
2564
|
+
startAddress: span.start,
|
|
2565
|
+
length: span.end - span.start,
|
|
2566
|
+
members: [member(0)],
|
|
2567
|
+
};
|
|
2568
|
+
currentEnd = span.end;
|
|
2569
|
+
blocks.push(current);
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
return blocks;
|
|
2574
|
+
}
|
|
2575
|
+
buildRoleMessage(values, clockId, resolution, timestamp) {
|
|
2576
|
+
switch (this.config.role) {
|
|
2577
|
+
case 'meter':
|
|
2578
|
+
return this.buildMeterMessage(values, clockId, resolution, timestamp);
|
|
2579
|
+
case 'inverter':
|
|
2580
|
+
return this.buildInverterMessage(values, clockId, resolution, timestamp);
|
|
2581
|
+
case 'battery':
|
|
2582
|
+
return this.buildBatteryMessage(values, clockId, resolution, timestamp);
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
buildMeterMessage(values, clockId, resolution, timestamp) {
|
|
2586
|
+
const data = { gridFeedInWh: 0, gridConsumptionWh: 0 };
|
|
2587
|
+
for (const field of CUSTOM_METER_FIELDS) {
|
|
2588
|
+
const v = values.get(field);
|
|
2589
|
+
if (v !== undefined) {
|
|
2590
|
+
data[field] = v;
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
return {
|
|
2594
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
2595
|
+
message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.MeterValuesUpdateV1,
|
|
2596
|
+
type: 'message',
|
|
2597
|
+
source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
|
|
2598
|
+
applianceId: this.applianceId,
|
|
2599
|
+
clockId,
|
|
2600
|
+
timestampIso: timestamp.toISOString(),
|
|
2601
|
+
resolution,
|
|
2602
|
+
data,
|
|
2603
|
+
};
|
|
2604
|
+
}
|
|
2605
|
+
buildInverterMessage(values, clockId, resolution, timestamp) {
|
|
2606
|
+
const data = { pvPowerW: 0, voltageL1: 0 };
|
|
2607
|
+
for (const field of CUSTOM_INVERTER_FIELDS) {
|
|
2608
|
+
const v = values.get(field);
|
|
2609
|
+
if (v !== undefined) {
|
|
2610
|
+
data[field] = v;
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2613
|
+
if (this.config.defaultInverterState !== undefined) {
|
|
2614
|
+
data.state = this.config.defaultInverterState;
|
|
2615
|
+
}
|
|
2616
|
+
return {
|
|
2617
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
2618
|
+
message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.InverterValuesUpdateV1,
|
|
2619
|
+
type: 'message',
|
|
2620
|
+
source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
|
|
2621
|
+
applianceId: this.applianceId,
|
|
2622
|
+
clockId,
|
|
2623
|
+
timestampIso: timestamp.toISOString(),
|
|
2624
|
+
resolution,
|
|
2625
|
+
data,
|
|
2626
|
+
};
|
|
2627
|
+
}
|
|
2628
|
+
buildBatteryMessage(values, clockId, resolution, timestamp) {
|
|
2629
|
+
const data = { batterySoC: 0 };
|
|
2630
|
+
for (const field of CUSTOM_BATTERY_FIELDS) {
|
|
2631
|
+
const v = values.get(field);
|
|
2632
|
+
if (v !== undefined) {
|
|
2633
|
+
data[field] = v;
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
if (this.config.defaultBatteryState !== undefined) {
|
|
2637
|
+
data.state = this.config.defaultBatteryState;
|
|
2638
|
+
}
|
|
2639
|
+
return {
|
|
2640
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
2641
|
+
message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.BatteryValuesUpdateV1,
|
|
2642
|
+
type: 'message',
|
|
2643
|
+
source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
|
|
2644
|
+
applianceId: this.applianceId,
|
|
2645
|
+
clockId,
|
|
2646
|
+
timestampIso: timestamp.toISOString(),
|
|
2647
|
+
resolution,
|
|
2648
|
+
data,
|
|
2649
|
+
};
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
exports.SunspecCustomDevice = SunspecCustomDevice;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, SunspecPvPowerOrigin, type SunspecInverterReading, type SunspecBatteryReading, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode } from "./sunspec-interfaces.cjs";
|
|
1
|
+
import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, SunspecPvPowerOrigin, type SunspecInverterReading, type SunspecBatteryReading, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode, type SunspecCustomDeviceConfig } from "./sunspec-interfaces.cjs";
|
|
2
2
|
import { ApplianceManager, EnergyApp } from "@enyo-energy/energy-app-sdk";
|
|
3
3
|
import { type EnyoAppliance, type EnyoApplianceErrorCode, EnyoApplianceName } from "@enyo-energy/energy-app-sdk/dist/types/enyo-appliance.js";
|
|
4
4
|
import { EnyoNetworkDevice } from "@enyo-energy/energy-app-sdk/dist/types/enyo-network-device.js";
|
|
@@ -37,6 +37,19 @@ export declare abstract class BaseSunspecDevice {
|
|
|
37
37
|
* would otherwise stay Offline forever despite reading data fine.
|
|
38
38
|
*/
|
|
39
39
|
private appliedOffline;
|
|
40
|
+
/**
|
|
41
|
+
* True once {@link reassertConnectedIfRecovered} has confirmed (via the
|
|
42
|
+
* appliance store) that this device is Connected, so it can stop probing
|
|
43
|
+
* for an *externally* applied Offline state. Distinct from
|
|
44
|
+
* {@link appliedOffline}, which only tracks Offline states this SDK object
|
|
45
|
+
* applied itself. An appliance can be marked Offline by a path outside the
|
|
46
|
+
* SDK object — e.g. the energy-app registering a boot-time offline
|
|
47
|
+
* placeholder before this device came up on a shared socket — which never
|
|
48
|
+
* sets appliedOffline; without reconciling against actual state, such a
|
|
49
|
+
* device stays Offline forever despite reading data fine. Reset in
|
|
50
|
+
* {@link markOffline} so a later Offline episode is re-checked.
|
|
51
|
+
*/
|
|
52
|
+
private reconciledExternalOffline;
|
|
40
53
|
/**
|
|
41
54
|
* Prefix used when persisting calibration snapshots via the library's
|
|
42
55
|
* {@link SnapshotService}. Kept identical to the key the SDK used before
|
|
@@ -68,6 +81,20 @@ export declare abstract class BaseSunspecDevice {
|
|
|
68
81
|
* Ensure the Sunspec client is connected and models are discovered
|
|
69
82
|
*/
|
|
70
83
|
protected ensureConnected(): Promise<void>;
|
|
84
|
+
/**
|
|
85
|
+
* Populate the per-unit model directory after the socket opens. Default: run SunSpec model
|
|
86
|
+
* discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
|
|
87
|
+
* directory (see {@link SunspecCustomDevice}) override this to a no-op.
|
|
88
|
+
*/
|
|
89
|
+
protected discoverAfterConnect(): Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Validate that a just-completed reconnect actually restored a usable device. Default: re-run
|
|
92
|
+
* SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
|
|
93
|
+
* back with no usable models means the gateway accepted the connection before it was ready to
|
|
94
|
+
* answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
|
|
95
|
+
* running. Discovery-less devices override this to just confirm the socket is open.
|
|
96
|
+
*/
|
|
97
|
+
protected revalidateAfterReconnect(): Promise<boolean>;
|
|
71
98
|
/**
|
|
72
99
|
* Attempt a reconnection if the tiered retry schedule allows it.
|
|
73
100
|
* Called from readData() when the device is disconnected.
|
|
@@ -138,9 +165,21 @@ export declare abstract class BaseSunspecDevice {
|
|
|
138
165
|
* readData() and skip tryReconnect() entirely, so without this they would
|
|
139
166
|
* stay Offline forever despite reading data fine.
|
|
140
167
|
*
|
|
168
|
+
* Heals two ways an appliance can be stuck Offline while reads succeed:
|
|
169
|
+
* 1. This SDK object marked itself offline ({@link appliedOffline}) and a
|
|
170
|
+
* sibling won the reconnect race — the original shared-socket case.
|
|
171
|
+
* 2. The appliance was marked Offline by a path *outside* this object —
|
|
172
|
+
* e.g. the energy-app registering a boot-time offline placeholder
|
|
173
|
+
* before this device came up on the shared socket — which never sets
|
|
174
|
+
* appliedOffline. We reconcile against the actual stored state so the
|
|
175
|
+
* invariant "healthy reads ⇒ Connected" holds regardless of who
|
|
176
|
+
* applied the Offline.
|
|
177
|
+
*
|
|
141
178
|
* Call this on the success path of readData() (after the
|
|
142
|
-
* markOfflineIfUnhealthy() guard has confirmed the unit is healthy).
|
|
143
|
-
* a
|
|
179
|
+
* markOfflineIfUnhealthy() guard has confirmed the unit is healthy). Cheap:
|
|
180
|
+
* a no-op via the appliedOffline fast path, and the external-state lookup
|
|
181
|
+
* runs at most once per Offline episode (latched by
|
|
182
|
+
* {@link reconciledExternalOffline} once Connected is confirmed).
|
|
144
183
|
*/
|
|
145
184
|
protected reassertConnectedIfRecovered(): Promise<void>;
|
|
146
185
|
protected sendCommandAcknowledge(messageId: string, acknowledgeMessage: EnyoDataBusMessageEnum | string, answer: EnyoCommandAcknowledgeAnswerEnum, rejectionReason?: string): void;
|
|
@@ -735,4 +774,70 @@ export declare class SunspecMeter extends BaseSunspecDevice {
|
|
|
735
774
|
*/
|
|
736
775
|
readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
|
|
737
776
|
}
|
|
777
|
+
/**
|
|
778
|
+
* A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
|
|
779
|
+
* SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
|
|
780
|
+
* {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
|
|
781
|
+
* per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
|
|
782
|
+
* instead of a discovered SunSpec model directory.
|
|
783
|
+
*
|
|
784
|
+
* It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
|
|
785
|
+
* the role selects the appliance type created on connect and which EnyoDataBus values message
|
|
786
|
+
* {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
|
|
787
|
+
* that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
|
|
788
|
+
*
|
|
789
|
+
* Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
|
|
790
|
+
* validated by socket liveness rather than a SunSpec scan.
|
|
791
|
+
*/
|
|
792
|
+
export declare class SunspecCustomDevice extends BaseSunspecDevice {
|
|
793
|
+
private readonly config;
|
|
794
|
+
/** Read plan derived once from the static register map (see {@link planBlocks}). */
|
|
795
|
+
private plannedBlocks?;
|
|
796
|
+
constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, config: SunspecCustomDeviceConfig, unitId?: number, port?: number, baseAddress?: number, retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean);
|
|
797
|
+
/**
|
|
798
|
+
* No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
|
|
799
|
+
* the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
|
|
800
|
+
* socket without a SunS scan.
|
|
801
|
+
*/
|
|
802
|
+
protected discoverAfterConnect(): Promise<void>;
|
|
803
|
+
/**
|
|
804
|
+
* A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
|
|
805
|
+
* Without this override the base default would run SunSpec discovery, find nothing, and treat every
|
|
806
|
+
* reconnect as a permanent failure.
|
|
807
|
+
*/
|
|
808
|
+
protected revalidateAfterReconnect(): Promise<boolean>;
|
|
809
|
+
/**
|
|
810
|
+
* Connect the underlying socket (no discovery) and create/update the appliance for the configured
|
|
811
|
+
* role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
|
|
812
|
+
* SunSpec Common block to read it from.
|
|
813
|
+
*/
|
|
814
|
+
connect(): Promise<void>;
|
|
815
|
+
disconnect(): Promise<void>;
|
|
816
|
+
readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
|
|
817
|
+
/**
|
|
818
|
+
* Write a value to a pre-configured writable register. Delegates to the client's resilient
|
|
819
|
+
* {@link SunspecModbusClient.writeRegisterValue}.
|
|
820
|
+
*/
|
|
821
|
+
writeCustomRegister(name: string, value: number | number[]): Promise<boolean>;
|
|
822
|
+
/**
|
|
823
|
+
* Read every configured register as a small number of block reads and extract each register from
|
|
824
|
+
* its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
|
|
825
|
+
* scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
|
|
826
|
+
* populate a numeric databus field) are skipped with a warning.
|
|
827
|
+
*/
|
|
828
|
+
private readConfiguredRegisters;
|
|
829
|
+
/** Lazily compute and cache the block read plan; the register map is static per device. */
|
|
830
|
+
private getPlannedBlocks;
|
|
831
|
+
/**
|
|
832
|
+
* Group the configured registers (separately per function code) sorted by address, coalescing them
|
|
833
|
+
* — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
|
|
834
|
+
* starts whenever adding the next register would exceed that span. Each block records its members'
|
|
835
|
+
* offsets so a single read can be sliced into all of them.
|
|
836
|
+
*/
|
|
837
|
+
private planBlocks;
|
|
838
|
+
private buildRoleMessage;
|
|
839
|
+
private buildMeterMessage;
|
|
840
|
+
private buildInverterMessage;
|
|
841
|
+
private buildBatteryMessage;
|
|
842
|
+
}
|
|
738
843
|
export {};
|