@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.
@@ -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
  */
@@ -152,6 +152,15 @@ export declare class SunspecModbusClient {
152
152
  * if every unit succeeded.
153
153
  */
154
154
  private attemptConnection;
155
+ /**
156
+ * Build the ordered host list handed to the transport's `host` option for a single connect.
157
+ * The attempt's primary target leads, followed by every OTHER known host (the other of
158
+ * primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
159
+ * DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
160
+ * only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
161
+ * no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
162
+ */
163
+ private buildConnectHosts;
155
164
  /**
156
165
  * Open a unit, retrying the connect on a transient failure per the resilience config
157
166
  * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
@@ -167,6 +176,14 @@ export declare class SunspecModbusClient {
167
176
  * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
168
177
  * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
169
178
  * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
179
+ *
180
+ * When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
181
+ * full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
182
+ * known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
183
+ * waiting for the client's own sequential primary→secondary retry. The transport walks the list
184
+ * in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
185
+ * the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
186
+ * false to keep speculative RS485 scans a fast-fail single-host probe.
170
187
  */
171
188
  private _openUnitOnce;
172
189
  /**
@@ -349,9 +366,38 @@ export declare class SunspecModbusClient {
349
366
  */
350
367
  private extractValue;
351
368
  /**
352
- * Helper to read register value(s) using the fault-tolerant reader with data type conversion
369
+ * Read a contiguous span of `quantity` registers starting at `address` in a single logical
370
+ * transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
371
+ * other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
372
+ * when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
373
+ * the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
374
+ * individual fields out of the returned buffer with {@link decodeBlockValue}.
375
+ */
376
+ readRegisterBlock(unitId: number, address: number, quantity: number, useInputRegisters?: boolean): Promise<Buffer>;
377
+ /**
378
+ * Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
379
+ * from the block start. A thin public wrapper over the same block-extraction the SunSpec model
380
+ * readers use internally.
381
+ */
382
+ decodeBlockValue(buffer: Buffer, registerOffset: number, dataType: EnergyAppModbusDataType, quantity?: number): number | string | number[];
383
+ /**
384
+ * Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
385
+ * conversion.
353
386
  */
354
387
  readRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
388
+ /**
389
+ * Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
390
+ * conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
391
+ * {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
392
+ * not implement `readInputRegisters`.
393
+ */
394
+ readInputRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
395
+ /**
396
+ * Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
397
+ * the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
398
+ * connection health on both success and failure.
399
+ */
400
+ private readTypedRegisters;
355
401
  /**
356
402
  * Helper to write register value(s)
357
403
  */
@@ -224,6 +224,10 @@ export class SunspecModbusClient {
224
224
  await this._openUnit(host, port, unitId, {
225
225
  connectRetries: 0,
226
226
  connectTimeoutMs: opts.timeoutMs ?? this.resilience.connectTimeoutMs,
227
+ // Fast-fail scan: a mostly-dead RS485 range must cost ~one timeout per unit, so do
228
+ // NOT let the transport also walk a fallback host (which would double the per-unit
229
+ // cost). Warm connects/reconnects still get the in-band fallback.
230
+ useFallbackHosts: false,
227
231
  });
228
232
  console.log(`Probed Sunspec unit ${unitId} at ${host}:${port} — open (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
229
233
  });
@@ -395,6 +399,25 @@ export class SunspecModbusClient {
395
399
  return false;
396
400
  }
397
401
  }
402
+ /**
403
+ * Build the ordered host list handed to the transport's `host` option for a single connect.
404
+ * The attempt's primary target leads, followed by every OTHER known host (the other of
405
+ * primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
406
+ * DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
407
+ * only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
408
+ * no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
409
+ */
410
+ buildConnectHosts(primaryTarget) {
411
+ const hosts = [primaryTarget];
412
+ const params = this.connectionParams;
413
+ if (params) {
414
+ for (const h of [params.primaryHost, params.secondaryHost]) {
415
+ if (h && !hosts.includes(h))
416
+ hosts.push(h);
417
+ }
418
+ }
419
+ return hosts.length === 1 ? hosts[0] : hosts;
420
+ }
398
421
  /**
399
422
  * Open a unit, retrying the connect on a transient failure per the resilience config
400
423
  * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
@@ -408,7 +431,11 @@ export class SunspecModbusClient {
408
431
  async _openUnit(host, port, unitId, override) {
409
432
  const connectTimeoutMs = override?.connectTimeoutMs ?? this.resilience.connectTimeoutMs;
410
433
  const attempts = (override?.connectRetries ?? this.resilience.connectRetries) + 1;
411
- await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs), {
434
+ // Default ON: a normal connect/reconnect hands the transport BOTH known hosts so a single
435
+ // attempt tolerates DNS/DHCP drift on the first one. probeUnit opts out to stay a fast-fail
436
+ // single-host scan (see probeUnit / _openUnitOnce).
437
+ const useFallbackHosts = override?.useFallbackHosts ?? true;
438
+ await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs, useFallbackHosts), {
412
439
  attempts,
413
440
  delayMs: this.resilience.connectRetryDelayMs,
414
441
  onRetry: (error, attempt) => console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} failed ` +
@@ -420,15 +447,28 @@ export class SunspecModbusClient {
420
447
  * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
421
448
  * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
422
449
  * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
423
- */
424
- async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
450
+ *
451
+ * When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
452
+ * full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
453
+ * known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
454
+ * waiting for the client's own sequential primary→secondary retry. The transport walks the list
455
+ * in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
456
+ * the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
457
+ * false to keep speculative RS485 scans a fast-fail single-host probe.
458
+ */
459
+ async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs, useFallbackHosts = true) {
425
460
  let candidate = null;
461
+ const hosts = useFallbackHosts ? this.buildConnectHosts(host) : host;
462
+ const hostCount = Array.isArray(hosts) ? hosts.length : 1;
463
+ // Each host in the list gets its own `timeout`; bound the whole walk at count × budget so we
464
+ // don't kill a genuine fallback to the second host with the single-host budget.
465
+ const overallBudgetMs = connectTimeoutMs * hostCount;
426
466
  try {
427
467
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
428
468
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
429
469
  // can still leave the returned promise pending — bound it independently.
430
- candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
431
- host,
470
+ candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.energyApp.useModbus().connect({
471
+ host: hosts,
432
472
  port,
433
473
  unitId,
434
474
  timeout: connectTimeoutMs,
@@ -701,7 +741,16 @@ export class SunspecModbusClient {
701
741
  */
702
742
  async detectSunspecBaseAddress(unitId, customBaseAddress) {
703
743
  const instance = this.getInstance(unitId);
704
- // If custom base address provided, try it first (1-based, then 0-based variant)
744
+ // If a custom base address is provided, try it first (0-based, then 1-based variant).
745
+ //
746
+ // A custom base is only a real SunSpec anchor for a device whose map genuinely starts
747
+ // there. It is NOT an anchor when it points at a *model block* inside a shared unit —
748
+ // e.g. a SolarEdge meter block (~40188) co-resident with the inverter on unit 1: the
749
+ // "SunS" marker lives ONLY at the unit's SunSpec root (40000/40001), never at the meter
750
+ // block. So a miss here must NOT fail discovery; fall through to the standard root probe
751
+ // below. (This is exactly the reconnect path that used to strand the meter — its
752
+ // rediscovery threw "not SunSpec compliant" at 40188, returned no models, and poisoned
753
+ // the shared socket, dragging the inverter offline too.)
705
754
  if (customBaseAddress !== undefined) {
706
755
  console.log(`Detect models for custom base address '${customBaseAddress}' ...`);
707
756
  // Try 0-based at custom address
@@ -734,41 +783,44 @@ export class SunspecModbusClient {
734
783
  catch (error) {
735
784
  console.debug(`Could not read SunS at ${customBaseAddress + 1}:`, error);
736
785
  }
786
+ console.debug(`No "SunS" marker at custom base ${customBaseAddress}/${customBaseAddress + 1} on unit ${unitId} — ` +
787
+ `falling back to the standard SunSpec root (40001/40000). Expected when the custom base points at a ` +
788
+ `model block inside a shared unit (e.g. a co-resident meter), whose anchor is the unit root.`);
737
789
  }
738
- else {
739
- // Try 1-based addressing first (most common)
740
- try {
741
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
742
- if (sunspecId.includes('SunS')) {
743
- console.log('Detected 1-based addressing mode (base address: 40001)');
744
- return {
745
- baseAddress: 40001,
746
- isZeroBased: false,
747
- nextAddress: 40003
748
- };
749
- }
750
- }
751
- catch (error) {
752
- console.debug('Could not read SunS at 40001:', error);
753
- }
754
- // Try 0-based addressing
755
- try {
756
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
757
- if (sunspecId.includes('SunS')) {
758
- console.log('Detected 0-based addressing mode (base address: 40000)');
759
- return {
760
- baseAddress: 40000,
761
- isZeroBased: true,
762
- nextAddress: 40002
763
- };
764
- }
790
+ // Standard SunSpec root probe. Runs when no custom base was given, OR as the fallback
791
+ // when the custom base carried no marker. Try 1-based (40001) first (most common), then
792
+ // 0-based (40000).
793
+ try {
794
+ const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
795
+ if (sunspecId.includes('SunS')) {
796
+ console.log('Detected 1-based addressing mode (base address: 40001)');
797
+ return {
798
+ baseAddress: 40001,
799
+ isZeroBased: false,
800
+ nextAddress: 40003
801
+ };
765
802
  }
766
- catch (error) {
767
- console.debug('Could not read SunS at 40000:', error);
803
+ }
804
+ catch (error) {
805
+ console.debug('Could not read SunS at 40001:', error);
806
+ }
807
+ // Try 0-based addressing
808
+ try {
809
+ const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
810
+ if (sunspecId.includes('SunS')) {
811
+ console.log('Detected 0-based addressing mode (base address: 40000)');
812
+ return {
813
+ baseAddress: 40000,
814
+ isZeroBased: true,
815
+ nextAddress: 40002
816
+ };
768
817
  }
769
818
  }
819
+ catch (error) {
820
+ console.debug('Could not read SunS at 40000:', error);
821
+ }
770
822
  const addressesChecked = customBaseAddress !== undefined
771
- ? `${customBaseAddress}, ${customBaseAddress + 1}`
823
+ ? `${customBaseAddress}, ${customBaseAddress + 1}, 40001, 40000`
772
824
  : '40000 or 40001';
773
825
  throw new Error(`Device is not SunSpec compliant - "SunS" identifier not found at addresses ${addressesChecked}`);
774
826
  }
@@ -779,29 +831,35 @@ export class SunspecModbusClient {
779
831
  async discoverModels(unitId, customBaseAddress) {
780
832
  const instance = this.getInstance(unitId);
781
833
  const models = this.getModelsMap(unitId);
782
- models.clear();
783
834
  const modelList = this.getModelList(unitId);
784
- modelList.length = 0;
785
835
  const maxAddress = 50000; // Safety limit
786
- let currentAddress = 0;
787
836
  console.log(`Starting Sunspec model discovery for unit ${unitId}...`);
788
837
  // Probe for the SunS identifier first. A missing identifier means the unit ID isn't a
789
838
  // SunSpec device — common during unit-ID scans — and is logged at debug level so probes
790
839
  // don't surface as errors. Mid-scan failures below remain at error level since they
791
840
  // indicate a partial / malformed SunSpec map.
841
+ //
842
+ // IMPORTANT: we discover into TEMP buffers and only commit into the stored map once the
843
+ // walk yields at least one model. A reconnect probe can transiently fail (e.g. a single-
844
+ // session SolarEdge endpoint drops the socket with ECONNRESET on the first read after
845
+ // accepting the connection). Clearing the stored map up-front — as this used to — turned
846
+ // that blip into "no usable models", which trips tryReconnect()'s gate into invalidating
847
+ // a unit whose model map was perfectly good a moment ago. Preserving the last known-good
848
+ // map keeps a genuinely-connected sibling alive; a device that is really gone is still
849
+ // caught by read-health (isHealthy()).
792
850
  let addressInfo;
793
851
  try {
794
852
  addressInfo = await this.detectSunspecBaseAddress(unitId, customBaseAddress);
795
853
  }
796
854
  catch (error) {
797
855
  console.debug(`No SunSpec device at unit ${unitId}: ${error}`);
798
- // Discovery summary at line 594 below is the info-level outcome.
799
- // This 0-models branch is the same outcome as a normal "no device found",
800
- // covered already by the debug above. Keep at debug.
801
- console.debug(`Discovery complete for unit ${unitId}. Found 0 models: []`);
856
+ // Same outcome as a normal "no device found"; keep at debug. Do NOT wipe the stored
857
+ // map — return it untouched so a transient probe failure can't erase good discovery.
858
+ console.debug(`Discovery incomplete for unit ${unitId}; keeping ${models.size} previously-discovered model(s).`);
802
859
  return models;
803
860
  }
804
- currentAddress = addressInfo.nextAddress;
861
+ const discovered = [];
862
+ let currentAddress = addressInfo.nextAddress;
805
863
  try {
806
864
  while (currentAddress < maxAddress) {
807
865
  const buffer = await this.runExclusive(unitId, () => instance.readHoldingRegisters(currentAddress, 2));
@@ -817,19 +875,12 @@ export class SunspecModbusClient {
817
875
  console.debug(`Found end marker at address ${currentAddress}`);
818
876
  break;
819
877
  }
820
- // Store discovered model
821
878
  const model = {
822
879
  id: modelId,
823
880
  address: currentAddress,
824
881
  length: modelLength
825
882
  };
826
- // Keep the FIRST (lowest-address) instance per id in the keyed directory so
827
- // findModel() resolves to the device's own block. Record every instance —
828
- // including repeats like a meter's Common (id 1) — in the ordered list.
829
- if (!models.has(modelId)) {
830
- models.set(modelId, model);
831
- }
832
- modelList.push(model);
883
+ discovered.push(model);
833
884
  // Per-model discovery step. The end-of-discovery summary below is the
834
885
  // info-level outcome; the per-model walk is debug-only.
835
886
  console.debug(`Discovered Model ${modelId} at address ${currentAddress} with length ${modelLength} (unit ${unitId})`);
@@ -840,6 +891,24 @@ export class SunspecModbusClient {
840
891
  catch (error) {
841
892
  console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
842
893
  }
894
+ if (discovered.length > 0) {
895
+ // Commit the fresh discovery atomically. Keep the FIRST (lowest-address) instance per
896
+ // id in the keyed directory so findModel() resolves to the device's own block; record
897
+ // every instance — including repeats like a meter's Common (id 1) — in the ordered list.
898
+ models.clear();
899
+ modelList.length = 0;
900
+ for (const model of discovered) {
901
+ if (!models.has(model.id)) {
902
+ models.set(model.id, model);
903
+ }
904
+ modelList.push(model);
905
+ }
906
+ }
907
+ else {
908
+ // The anchor answered but the walk yielded nothing (e.g. the socket dropped right
909
+ // after the SunS probe). Preserve the last known-good map rather than clobbering it.
910
+ console.debug(`Discovery for unit ${unitId} yielded no models; keeping ${models.size} previously-discovered model(s).`);
911
+ }
843
912
  // Report every instance in address order so repeated ids (e.g. two Common blocks, or
844
913
  // multiple meters) are visible — models.size would hide them behind the unique keys.
845
914
  console.log(`Discovery complete for unit ${unitId}. Found ${modelList.length} model instance(s): [${modelList.map(m => m.id).join(', ')}]`);
@@ -981,12 +1050,87 @@ export class SunspecModbusClient {
981
1050
  return value;
982
1051
  }
983
1052
  /**
984
- * Helper to read register value(s) using the fault-tolerant reader with data type conversion
1053
+ * Read a contiguous span of `quantity` registers starting at `address` in a single logical
1054
+ * transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
1055
+ * other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
1056
+ * when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
1057
+ * the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
1058
+ * individual fields out of the returned buffer with {@link decodeBlockValue}.
1059
+ */
1060
+ async readRegisterBlock(unitId, address, quantity, useInputRegisters = false) {
1061
+ const reader = this.getReader(unitId);
1062
+ const MAX_REGISTERS_PER_READ = 125;
1063
+ try {
1064
+ const chunks = await this.runExclusive(unitId, async () => {
1065
+ const acc = [];
1066
+ for (let offset = 0; offset < quantity; offset += MAX_REGISTERS_PER_READ) {
1067
+ const count = Math.min(MAX_REGISTERS_PER_READ, quantity - offset);
1068
+ let result;
1069
+ if (useInputRegisters) {
1070
+ if (!reader.readInputRegisters) {
1071
+ throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
1072
+ }
1073
+ result = await reader.readInputRegisters(address + offset, count);
1074
+ }
1075
+ else {
1076
+ result = await reader.readHoldingRegisters(address + offset, count);
1077
+ }
1078
+ if (!result.success || !result.value) {
1079
+ throw new Error(`Failed to read register block at address ${address + offset} (unit ${unitId}): ${result.error?.message || 'Unknown error'}`);
1080
+ }
1081
+ acc.push(result.value);
1082
+ }
1083
+ return acc;
1084
+ });
1085
+ this.connectionHealth.recordSuccess();
1086
+ return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
1087
+ }
1088
+ catch (error) {
1089
+ this.connectionHealth.recordFailure(error);
1090
+ throw error;
1091
+ }
1092
+ }
1093
+ /**
1094
+ * Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
1095
+ * from the block start. A thin public wrapper over the same block-extraction the SunSpec model
1096
+ * readers use internally.
1097
+ */
1098
+ decodeBlockValue(buffer, registerOffset, dataType, quantity = 1) {
1099
+ return this.extractValue(buffer, registerOffset, dataType, quantity);
1100
+ }
1101
+ /**
1102
+ * Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
1103
+ * conversion.
985
1104
  */
986
1105
  async readRegisterValue(unitId, address, quantity = 1, dataType) {
1106
+ return this.readTypedRegisters(unitId, address, quantity, dataType, false);
1107
+ }
1108
+ /**
1109
+ * Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
1110
+ * conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
1111
+ * {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
1112
+ * not implement `readInputRegisters`.
1113
+ */
1114
+ async readInputRegisterValue(unitId, address, quantity = 1, dataType) {
1115
+ return this.readTypedRegisters(unitId, address, quantity, dataType, true);
1116
+ }
1117
+ /**
1118
+ * Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
1119
+ * the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
1120
+ * connection health on both success and failure.
1121
+ */
1122
+ async readTypedRegisters(unitId, address, quantity, dataType, useInputRegisters) {
987
1123
  const reader = this.getReader(unitId);
988
1124
  try {
989
- const result = await this.runExclusive(unitId, () => reader.readHoldingRegisters(address, quantity));
1125
+ const result = await this.runExclusive(unitId, () => {
1126
+ if (useInputRegisters) {
1127
+ if (!reader.readInputRegisters) {
1128
+ throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
1129
+ }
1130
+ return reader.readInputRegisters(address, quantity);
1131
+ }
1132
+ return reader.readHoldingRegisters(address, quantity);
1133
+ });
990
1134
  // Check if the read was successful
991
1135
  if (!result.success || !result.value) {
992
1136
  throw new Error(`Failed to read register at address ${address}: ${result.error?.message || 'Unknown error'}`);
package/dist/version.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export declare const SDK_VERSION = "0.0.101";
8
+ export declare const SDK_VERSION = "0.0.103";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/dist/version.js CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export const SDK_VERSION = '0.0.101';
8
+ export const SDK_VERSION = '0.0.103';
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enyo-energy/sunspec-sdk",
3
- "version": "0.0.101",
3
+ "version": "0.0.103",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -40,8 +40,8 @@
40
40
  "vitest": "^2.1.9"
41
41
  },
42
42
  "dependencies": {
43
- "@enyo-energy/appliance-calibration": "0.0.2",
44
- "@enyo-energy/energy-app-sdk": "^0.0.175"
43
+ "@enyo-energy/appliance-calibration": "0.0.3",
44
+ "@enyo-energy/energy-app-sdk": "^0.0.180"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"