@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.
@@ -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;
@@ -156,8 +156,32 @@ class BaseSunspecDevice {
156
156
  await this.sunspecClient.connect(this.networkDevice.hostname, // primary
157
157
  this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
158
158
  this.useTls);
159
- await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
159
+ await this.discoverAfterConnect();
160
+ }
161
+ }
162
+ /**
163
+ * Populate the per-unit model directory after the socket opens. Default: run SunSpec model
164
+ * discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
165
+ * directory (see {@link SunspecCustomDevice}) override this to a no-op.
166
+ */
167
+ async discoverAfterConnect() {
168
+ await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
169
+ }
170
+ /**
171
+ * Validate that a just-completed reconnect actually restored a usable device. Default: re-run
172
+ * SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
173
+ * back with no usable models means the gateway accepted the connection before it was ready to
174
+ * answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
175
+ * running. Discovery-less devices override this to just confirm the socket is open.
176
+ */
177
+ async revalidateAfterReconnect() {
178
+ const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
179
+ const usable = this.isDiscoveryUsable(models);
180
+ if (!usable) {
181
+ console.warn(`${this.constructor.name} ${this.applianceId}: reconnect discovery returned no usable models ` +
182
+ `(found [${[...models.keys()].join(', ')}])`);
160
183
  }
184
+ return usable;
161
185
  }
162
186
  /**
163
187
  * Attempt a reconnection if the tiered retry schedule allows it.
@@ -193,14 +217,12 @@ class BaseSunspecDevice {
193
217
  // it's unusable, treat this as a failed reconnect: invalidate the socket so the
194
218
  // next poll re-enters tryReconnect(), keep the backoff schedule running, and do
195
219
  // NOT reset().
196
- const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
197
- if (!this.isDiscoveryUsable(models)) {
198
- this.sunspecClient.invalidateUnit(this.unitId, `reconnect discovery found no usable models for unit ${this.unitId}`);
220
+ if (!(await this.revalidateAfterReconnect())) {
221
+ this.sunspecClient.invalidateUnit(this.unitId, `reconnect revalidation failed for unit ${this.unitId}`);
199
222
  this.consecutiveReconnectFailures += 1;
200
223
  await this.onConnectionFailure(this.consecutiveReconnectFailures);
201
224
  console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
202
- `opened the socket but discovery returned no usable models ` +
203
- `(found [${[...models.keys()].join(', ')}]) — retrying with backoff`);
225
+ `opened the socket but revalidation failed — retrying with backoff`);
204
226
  return false;
205
227
  }
206
228
  this.retryManager.reset();
@@ -2242,3 +2264,346 @@ class SunspecMeter extends BaseSunspecDevice {
2242
2264
  }
2243
2265
  }
2244
2266
  exports.SunspecMeter = SunspecMeter;
2267
+ /** Appliance type created for each custom-device role (battery emulates a Storage appliance). */
2268
+ const CUSTOM_ROLE_APPLIANCE_TYPE = {
2269
+ meter: enyo_appliance_js_1.EnyoApplianceTypeEnum.Meter,
2270
+ inverter: enyo_appliance_js_1.EnyoApplianceTypeEnum.Inverter,
2271
+ battery: enyo_appliance_js_1.EnyoApplianceTypeEnum.Storage,
2272
+ };
2273
+ /** Natural register width per data type, used when a register omits an explicit `quantity`. */
2274
+ const CUSTOM_REGISTER_DEFAULT_QUANTITY = {
2275
+ uint16: 1,
2276
+ int16: 1,
2277
+ acc16: 1,
2278
+ uint32: 2,
2279
+ int32: 2,
2280
+ acc32: 2,
2281
+ float32: 2,
2282
+ string: 1,
2283
+ };
2284
+ /** Numeric databus fields a `meter`-role custom device may populate. */
2285
+ const CUSTOM_METER_FIELDS = [
2286
+ 'gridPowerW', 'gridPowerPhase1W', 'gridPowerPhase2W', 'gridPowerPhase3W',
2287
+ 'gridFeedInWh', 'gridConsumptionWh', 'selfConsumptionW', 'selfConsumptionWh',
2288
+ ];
2289
+ /** Numeric databus fields an `inverter`-role custom device may populate. */
2290
+ const CUSTOM_INVERTER_FIELDS = [
2291
+ 'pvPowerW', 'voltageL1', 'voltageL2', 'voltageL3',
2292
+ 'currentL1', 'currentL2', 'currentL3', 'dcPowerW',
2293
+ 'activePowerLimitationW', 'meterValueWh',
2294
+ ];
2295
+ /** Numeric databus fields a `battery`-role custom device may populate. */
2296
+ const CUSTOM_BATTERY_FIELDS = [
2297
+ 'batterySoC', 'batteryPowerW', 'dcStringInputPowerW',
2298
+ ];
2299
+ /** Default {@link SunspecCustomDeviceConfig.blockSize}: the Modbus FC03/FC04 per-read limit. */
2300
+ const CUSTOM_DEFAULT_BLOCK_SIZE = 125;
2301
+ /**
2302
+ * A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
2303
+ * SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
2304
+ * {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
2305
+ * per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
2306
+ * instead of a discovered SunSpec model directory.
2307
+ *
2308
+ * It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
2309
+ * the role selects the appliance type created on connect and which EnyoDataBus values message
2310
+ * {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
2311
+ * that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
2312
+ *
2313
+ * Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
2314
+ * validated by socket liveness rather than a SunSpec scan.
2315
+ */
2316
+ class SunspecCustomDevice extends BaseSunspecDevice {
2317
+ config;
2318
+ /** Read plan derived once from the static register map (see {@link planBlocks}). */
2319
+ plannedBlocks;
2320
+ constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, config, unitId = 1, port = 502, baseAddress = 40000, retryConfig, appliance, useTls) {
2321
+ super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
2322
+ this.config = config;
2323
+ }
2324
+ /**
2325
+ * No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
2326
+ * the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
2327
+ * socket without a SunS scan.
2328
+ */
2329
+ async discoverAfterConnect() {
2330
+ // Intentionally empty: plain-Modbus device, no SunSpec discovery.
2331
+ }
2332
+ /**
2333
+ * A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
2334
+ * Without this override the base default would run SunSpec discovery, find nothing, and treat every
2335
+ * reconnect as a permanent failure.
2336
+ */
2337
+ async revalidateAfterReconnect() {
2338
+ return this.sunspecClient.isConnected(this.unitId);
2339
+ }
2340
+ /**
2341
+ * Connect the underlying socket (no discovery) and create/update the appliance for the configured
2342
+ * role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
2343
+ * SunSpec Common block to read it from.
2344
+ */
2345
+ async connect() {
2346
+ if (!this.sunspecClient.isConnected(this.unitId)) {
2347
+ await this.sunspecClient.connect(this.networkDevice.hostname, // primary
2348
+ this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
2349
+ this.useTls);
2350
+ // No discoverModels(): this device reads a pre-defined static register map.
2351
+ }
2352
+ const applianceType = CUSTOM_ROLE_APPLIANCE_TYPE[this.config.role];
2353
+ if (!this.applianceId) {
2354
+ try {
2355
+ this.applianceId = await this.applianceManager.createOrUpdateAppliance({
2356
+ name: this.name,
2357
+ type: applianceType,
2358
+ networkDevices: [this.networkDevice],
2359
+ metadata: {
2360
+ connectionType: enyo_appliance_js_1.EnyoApplianceConnectionType.Connector,
2361
+ state: enyo_appliance_js_1.EnyoApplianceStateEnum.Connected,
2362
+ serialNumber: this.config.identity?.serialNumber,
2363
+ modelName: this.config.identity?.modelName,
2364
+ vendorName: this.config.identity?.vendorName,
2365
+ modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
2366
+ },
2367
+ });
2368
+ console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
2369
+ }
2370
+ catch (error) {
2371
+ console.error(`Failed to create custom ${this.config.role} appliance: ${error}`);
2372
+ }
2373
+ }
2374
+ else {
2375
+ try {
2376
+ const existingAppliance = await this.applianceManager.findApplianceById(this.applianceId);
2377
+ await this.applianceManager.updateAppliance(this.applianceId, {
2378
+ metadata: {
2379
+ ...existingAppliance?.metadata,
2380
+ connectionType: enyo_appliance_js_1.EnyoApplianceConnectionType.Connector,
2381
+ state: enyo_appliance_js_1.EnyoApplianceStateEnum.Connected,
2382
+ modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
2383
+ }
2384
+ });
2385
+ console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
2386
+ }
2387
+ catch (error) {
2388
+ console.error(`Failed to update custom ${this.config.role} appliance: ${error}`);
2389
+ }
2390
+ }
2391
+ }
2392
+ async disconnect() {
2393
+ if (this.applianceId) {
2394
+ try {
2395
+ await this.applianceManager.updateApplianceState(this.applianceId, enyo_appliance_js_1.EnyoApplianceConnectionType.Connector, enyo_appliance_js_1.EnyoApplianceStateEnum.Offline);
2396
+ }
2397
+ catch (error) {
2398
+ console.error(`Failed to mark custom ${this.config.role} offline on disconnect: ${error}`);
2399
+ }
2400
+ }
2401
+ // Close just this device's unit; siblings on the same network device stay open.
2402
+ await this.sunspecClient.disconnectUnit(this.unitId);
2403
+ }
2404
+ async readData(clockId, resolution) {
2405
+ if (!this.isConnected()) {
2406
+ await this.tryReconnect();
2407
+ if (!this.isConnected())
2408
+ return [];
2409
+ }
2410
+ const messages = [];
2411
+ const timestamp = new Date();
2412
+ try {
2413
+ const values = await this.readConfiguredRegisters();
2414
+ // readRegisterValue throws on a failed read (unlike the SunSpec model readers), so a dead
2415
+ // socket lands in catch below. This also covers the health-counter path when the transport
2416
+ // records failures without throwing.
2417
+ if (await this.markOfflineIfUnhealthy()) {
2418
+ return messages;
2419
+ }
2420
+ // Healthy read: if a sibling on the same shared socket reconnected us, flip our appliance
2421
+ // state back to Connected. No-op unless this device is still marked offline.
2422
+ await this.reassertConnectedIfRecovered();
2423
+ messages.push(this.buildRoleMessage(values, clockId, resolution, timestamp));
2424
+ this.lastUpdateTime = timestamp.getTime();
2425
+ }
2426
+ catch (error) {
2427
+ console.error(`Error updating custom ${this.config.role} data: ${error}`);
2428
+ await this.markOffline();
2429
+ }
2430
+ return messages;
2431
+ }
2432
+ /**
2433
+ * Write a value to a pre-configured writable register. Delegates to the client's resilient
2434
+ * {@link SunspecModbusClient.writeRegisterValue}.
2435
+ */
2436
+ async writeCustomRegister(name, value) {
2437
+ const reg = this.config.writeRegisters?.find(r => r.name === name);
2438
+ if (!reg) {
2439
+ throw new Error(`No writable register named '${name}' configured for custom ${this.config.role}`);
2440
+ }
2441
+ return this.sunspecClient.writeRegisterValue(this.unitId, reg.address, value, reg.dataType);
2442
+ }
2443
+ /**
2444
+ * Read every configured register as a small number of block reads and extract each register from
2445
+ * its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
2446
+ * scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
2447
+ * populate a numeric databus field) are skipped with a warning.
2448
+ */
2449
+ async readConfiguredRegisters() {
2450
+ const values = new Map();
2451
+ for (const block of this.getPlannedBlocks()) {
2452
+ const buffer = await this.sunspecClient.readRegisterBlock(this.unitId, block.startAddress, block.length, block.useInputRegisters);
2453
+ for (const member of block.members) {
2454
+ const raw = this.sunspecClient.decodeBlockValue(buffer, member.offset, member.dataType, member.quantity);
2455
+ if (typeof raw !== 'number') {
2456
+ console.warn(`Custom ${this.config.role}: register '${member.field}' returned a non-numeric value; skipping`);
2457
+ continue;
2458
+ }
2459
+ values.set(member.field, raw * Math.pow(10, member.scaleFactor));
2460
+ }
2461
+ }
2462
+ return values;
2463
+ }
2464
+ /** Lazily compute and cache the block read plan; the register map is static per device. */
2465
+ getPlannedBlocks() {
2466
+ if (!this.plannedBlocks) {
2467
+ this.plannedBlocks = this.planBlocks();
2468
+ }
2469
+ return this.plannedBlocks;
2470
+ }
2471
+ /**
2472
+ * Group the configured registers (separately per function code) sorted by address, coalescing them
2473
+ * — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
2474
+ * starts whenever adding the next register would exceed that span. Each block records its members'
2475
+ * offsets so a single read can be sliced into all of them.
2476
+ */
2477
+ planBlocks() {
2478
+ const blockSize = Math.max(1, this.config.blockSize ?? CUSTOM_DEFAULT_BLOCK_SIZE);
2479
+ const blocks = [];
2480
+ // Group by function code so FC03 and FC04 registers never share a block.
2481
+ const groups = new Map();
2482
+ for (const reg of this.config.registers) {
2483
+ const useInputRegisters = reg.functionCode === 4;
2484
+ const list = groups.get(useInputRegisters);
2485
+ if (list) {
2486
+ list.push(reg);
2487
+ }
2488
+ else {
2489
+ groups.set(useInputRegisters, [reg]);
2490
+ }
2491
+ }
2492
+ for (const [useInputRegisters, regs] of groups) {
2493
+ const spans = regs
2494
+ .map(reg => {
2495
+ const quantity = reg.quantity ?? CUSTOM_REGISTER_DEFAULT_QUANTITY[reg.dataType];
2496
+ return { reg, quantity, start: reg.address, end: reg.address + quantity };
2497
+ })
2498
+ .sort((a, b) => a.start - b.start);
2499
+ let current;
2500
+ let currentEnd = 0;
2501
+ for (const span of spans) {
2502
+ const member = (offset) => ({
2503
+ field: span.reg.field,
2504
+ dataType: span.reg.dataType,
2505
+ quantity: span.quantity,
2506
+ offset,
2507
+ scaleFactor: span.reg.scaleFactor ?? 0,
2508
+ });
2509
+ // Extend the current block only if the whole span (start .. farthest end) still fits
2510
+ // within blockSize. The first register always opens a block (a lone register wider than
2511
+ // blockSize is still read — readRegisterBlock chunks it).
2512
+ const mergedEnd = current ? Math.max(currentEnd, span.end) : span.end;
2513
+ if (current && mergedEnd - current.startAddress <= blockSize) {
2514
+ current.members.push(member(span.start - current.startAddress));
2515
+ currentEnd = mergedEnd;
2516
+ current.length = currentEnd - current.startAddress;
2517
+ }
2518
+ else {
2519
+ current = {
2520
+ useInputRegisters,
2521
+ startAddress: span.start,
2522
+ length: span.end - span.start,
2523
+ members: [member(0)],
2524
+ };
2525
+ currentEnd = span.end;
2526
+ blocks.push(current);
2527
+ }
2528
+ }
2529
+ }
2530
+ return blocks;
2531
+ }
2532
+ buildRoleMessage(values, clockId, resolution, timestamp) {
2533
+ switch (this.config.role) {
2534
+ case 'meter':
2535
+ return this.buildMeterMessage(values, clockId, resolution, timestamp);
2536
+ case 'inverter':
2537
+ return this.buildInverterMessage(values, clockId, resolution, timestamp);
2538
+ case 'battery':
2539
+ return this.buildBatteryMessage(values, clockId, resolution, timestamp);
2540
+ }
2541
+ }
2542
+ buildMeterMessage(values, clockId, resolution, timestamp) {
2543
+ const data = { gridFeedInWh: 0, gridConsumptionWh: 0 };
2544
+ for (const field of CUSTOM_METER_FIELDS) {
2545
+ const v = values.get(field);
2546
+ if (v !== undefined) {
2547
+ data[field] = v;
2548
+ }
2549
+ }
2550
+ return {
2551
+ id: (0, node_crypto_1.randomUUID)(),
2552
+ message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.MeterValuesUpdateV1,
2553
+ type: 'message',
2554
+ source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
2555
+ applianceId: this.applianceId,
2556
+ clockId,
2557
+ timestampIso: timestamp.toISOString(),
2558
+ resolution,
2559
+ data,
2560
+ };
2561
+ }
2562
+ buildInverterMessage(values, clockId, resolution, timestamp) {
2563
+ const data = { pvPowerW: 0, voltageL1: 0 };
2564
+ for (const field of CUSTOM_INVERTER_FIELDS) {
2565
+ const v = values.get(field);
2566
+ if (v !== undefined) {
2567
+ data[field] = v;
2568
+ }
2569
+ }
2570
+ if (this.config.defaultInverterState !== undefined) {
2571
+ data.state = this.config.defaultInverterState;
2572
+ }
2573
+ return {
2574
+ id: (0, node_crypto_1.randomUUID)(),
2575
+ message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.InverterValuesUpdateV1,
2576
+ type: 'message',
2577
+ source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
2578
+ applianceId: this.applianceId,
2579
+ clockId,
2580
+ timestampIso: timestamp.toISOString(),
2581
+ resolution,
2582
+ data,
2583
+ };
2584
+ }
2585
+ buildBatteryMessage(values, clockId, resolution, timestamp) {
2586
+ const data = { batterySoC: 0 };
2587
+ for (const field of CUSTOM_BATTERY_FIELDS) {
2588
+ const v = values.get(field);
2589
+ if (v !== undefined) {
2590
+ data[field] = v;
2591
+ }
2592
+ }
2593
+ if (this.config.defaultBatteryState !== undefined) {
2594
+ data.state = this.config.defaultBatteryState;
2595
+ }
2596
+ return {
2597
+ id: (0, node_crypto_1.randomUUID)(),
2598
+ message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.BatteryValuesUpdateV1,
2599
+ type: 'message',
2600
+ source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
2601
+ applianceId: this.applianceId,
2602
+ clockId,
2603
+ timestampIso: timestamp.toISOString(),
2604
+ resolution,
2605
+ data,
2606
+ };
2607
+ }
2608
+ }
2609
+ 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";
@@ -68,6 +68,20 @@ export declare abstract class BaseSunspecDevice {
68
68
  * Ensure the Sunspec client is connected and models are discovered
69
69
  */
70
70
  protected ensureConnected(): Promise<void>;
71
+ /**
72
+ * Populate the per-unit model directory after the socket opens. Default: run SunSpec model
73
+ * discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
74
+ * directory (see {@link SunspecCustomDevice}) override this to a no-op.
75
+ */
76
+ protected discoverAfterConnect(): Promise<void>;
77
+ /**
78
+ * Validate that a just-completed reconnect actually restored a usable device. Default: re-run
79
+ * SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
80
+ * back with no usable models means the gateway accepted the connection before it was ready to
81
+ * answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
82
+ * running. Discovery-less devices override this to just confirm the socket is open.
83
+ */
84
+ protected revalidateAfterReconnect(): Promise<boolean>;
71
85
  /**
72
86
  * Attempt a reconnection if the tiered retry schedule allows it.
73
87
  * Called from readData() when the device is disconnected.
@@ -735,4 +749,70 @@ export declare class SunspecMeter extends BaseSunspecDevice {
735
749
  */
736
750
  readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
737
751
  }
752
+ /**
753
+ * A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
754
+ * SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
755
+ * {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
756
+ * per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
757
+ * instead of a discovered SunSpec model directory.
758
+ *
759
+ * It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
760
+ * the role selects the appliance type created on connect and which EnyoDataBus values message
761
+ * {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
762
+ * that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
763
+ *
764
+ * Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
765
+ * validated by socket liveness rather than a SunSpec scan.
766
+ */
767
+ export declare class SunspecCustomDevice extends BaseSunspecDevice {
768
+ private readonly config;
769
+ /** Read plan derived once from the static register map (see {@link planBlocks}). */
770
+ private plannedBlocks?;
771
+ 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);
772
+ /**
773
+ * No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
774
+ * the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
775
+ * socket without a SunS scan.
776
+ */
777
+ protected discoverAfterConnect(): Promise<void>;
778
+ /**
779
+ * A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
780
+ * Without this override the base default would run SunSpec discovery, find nothing, and treat every
781
+ * reconnect as a permanent failure.
782
+ */
783
+ protected revalidateAfterReconnect(): Promise<boolean>;
784
+ /**
785
+ * Connect the underlying socket (no discovery) and create/update the appliance for the configured
786
+ * role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
787
+ * SunSpec Common block to read it from.
788
+ */
789
+ connect(): Promise<void>;
790
+ disconnect(): Promise<void>;
791
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
792
+ /**
793
+ * Write a value to a pre-configured writable register. Delegates to the client's resilient
794
+ * {@link SunspecModbusClient.writeRegisterValue}.
795
+ */
796
+ writeCustomRegister(name: string, value: number | number[]): Promise<boolean>;
797
+ /**
798
+ * Read every configured register as a small number of block reads and extract each register from
799
+ * its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
800
+ * scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
801
+ * populate a numeric databus field) are skipped with a warning.
802
+ */
803
+ private readConfiguredRegisters;
804
+ /** Lazily compute and cache the block read plan; the register map is static per device. */
805
+ private getPlannedBlocks;
806
+ /**
807
+ * Group the configured registers (separately per function code) sorted by address, coalescing them
808
+ * — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
809
+ * starts whenever adding the next register would exceed that span. Each block records its members'
810
+ * offsets so a single read can be sliced into all of them.
811
+ */
812
+ private planBlocks;
813
+ private buildRoleMessage;
814
+ private buildMeterMessage;
815
+ private buildInverterMessage;
816
+ private buildBatteryMessage;
817
+ }
738
818
  export {};
@@ -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
  */