@enyo-energy/sunspec-sdk 0.0.101 → 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 +372 -7
- package/dist/cjs/sunspec-devices.d.cts +81 -1
- package/dist/cjs/sunspec-interfaces.d.cts +81 -0
- package/dist/cjs/sunspec-modbus-client.cjs +153 -49
- package/dist/cjs/sunspec-modbus-client.d.cts +30 -1
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/sunspec-devices.d.ts +81 -1
- package/dist/sunspec-devices.js +370 -6
- package/dist/sunspec-interfaces.d.ts +81 -0
- package/dist/sunspec-modbus-client.d.ts +30 -1
- package/dist/sunspec-modbus-client.js +153 -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,8 +149,32 @@ 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
|
+
}
|
|
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(', ')}])`);
|
|
153
176
|
}
|
|
177
|
+
return usable;
|
|
154
178
|
}
|
|
155
179
|
/**
|
|
156
180
|
* Attempt a reconnection if the tiered retry schedule allows it.
|
|
@@ -186,14 +210,12 @@ export class BaseSunspecDevice {
|
|
|
186
210
|
// it's unusable, treat this as a failed reconnect: invalidate the socket so the
|
|
187
211
|
// next poll re-enters tryReconnect(), keep the backoff schedule running, and do
|
|
188
212
|
// NOT reset().
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
this.sunspecClient.invalidateUnit(this.unitId, `reconnect discovery found no usable models for unit ${this.unitId}`);
|
|
213
|
+
if (!(await this.revalidateAfterReconnect())) {
|
|
214
|
+
this.sunspecClient.invalidateUnit(this.unitId, `reconnect revalidation failed for unit ${this.unitId}`);
|
|
192
215
|
this.consecutiveReconnectFailures += 1;
|
|
193
216
|
await this.onConnectionFailure(this.consecutiveReconnectFailures);
|
|
194
217
|
console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
|
|
195
|
-
`opened the socket but
|
|
196
|
-
`(found [${[...models.keys()].join(', ')}]) — retrying with backoff`);
|
|
218
|
+
`opened the socket but revalidation failed — retrying with backoff`);
|
|
197
219
|
return false;
|
|
198
220
|
}
|
|
199
221
|
this.retryManager.reset();
|
|
@@ -2231,3 +2253,345 @@ export class SunspecMeter extends BaseSunspecDevice {
|
|
|
2231
2253
|
return messages;
|
|
2232
2254
|
}
|
|
2233
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
|
*/
|
|
@@ -349,9 +349,38 @@ export declare class SunspecModbusClient {
|
|
|
349
349
|
*/
|
|
350
350
|
private extractValue;
|
|
351
351
|
/**
|
|
352
|
-
*
|
|
352
|
+
* Read a contiguous span of `quantity` registers starting at `address` in a single logical
|
|
353
|
+
* transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
|
|
354
|
+
* other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
|
|
355
|
+
* when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
|
|
356
|
+
* the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
|
|
357
|
+
* individual fields out of the returned buffer with {@link decodeBlockValue}.
|
|
358
|
+
*/
|
|
359
|
+
readRegisterBlock(unitId: number, address: number, quantity: number, useInputRegisters?: boolean): Promise<Buffer>;
|
|
360
|
+
/**
|
|
361
|
+
* Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
|
|
362
|
+
* from the block start. A thin public wrapper over the same block-extraction the SunSpec model
|
|
363
|
+
* readers use internally.
|
|
364
|
+
*/
|
|
365
|
+
decodeBlockValue(buffer: Buffer, registerOffset: number, dataType: EnergyAppModbusDataType, quantity?: number): number | string | number[];
|
|
366
|
+
/**
|
|
367
|
+
* Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
|
|
368
|
+
* conversion.
|
|
353
369
|
*/
|
|
354
370
|
readRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
|
|
371
|
+
/**
|
|
372
|
+
* Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
|
|
373
|
+
* conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
|
|
374
|
+
* {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
|
|
375
|
+
* not implement `readInputRegisters`.
|
|
376
|
+
*/
|
|
377
|
+
readInputRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
|
|
378
|
+
/**
|
|
379
|
+
* Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
|
|
380
|
+
* the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
|
|
381
|
+
* connection health on both success and failure.
|
|
382
|
+
*/
|
|
383
|
+
private readTypedRegisters;
|
|
355
384
|
/**
|
|
356
385
|
* Helper to write register value(s)
|
|
357
386
|
*/
|