@enyo-energy/sunspec-sdk 0.0.100 → 0.0.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,12 +68,55 @@ 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.
74
88
  * Returns true if reconnection succeeded.
75
89
  */
76
90
  protected tryReconnect(): Promise<boolean>;
91
+ /**
92
+ * Model IDs this device needs to produce a reading; presence of ANY one means a
93
+ * discovery is usable (one-of semantics — devices expose mutually-exclusive
94
+ * encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
95
+ * (the base default) means no specific requirement, so any model present
96
+ * suffices. Concrete devices override with their acceptable set — this is the
97
+ * single per-device source of truth reused by both the reconnect discovery gate
98
+ * ({@link isDiscoveryUsable}) and the connect-time presence gate
99
+ * ({@link hasRequiredModels}).
100
+ */
101
+ protected getRequiredModelIds(): readonly number[];
102
+ /**
103
+ * True if the current per-unit discovered-model map satisfies this device's
104
+ * requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
105
+ * the already-populated map via findModel() rather than a freshly-returned one.
106
+ * Only meaningful for devices that declare a non-empty required set.
107
+ */
108
+ protected hasRequiredModels(): boolean;
109
+ /**
110
+ * Decide whether a post-reconnect model discovery is usable. A reconnect that
111
+ * establishes the TCP socket but comes back empty (or with only a Common block)
112
+ * means the device accepted the connection before it was ready to answer the
113
+ * SunSpec scan; the discovered-model map is now missing this device's data
114
+ * model, so trusting the reconnect would leave every read finding no model.
115
+ * Validated generically against {@link getRequiredModelIds}: with a declared
116
+ * set, at least one of those ids must be present; with none declared, fall back
117
+ * to "any model present".
118
+ */
119
+ protected isDiscoveryUsable(models: Map<number, SunspecModel>): boolean;
77
120
  /**
78
121
  * Hook for subclasses to react to a failed reconnect attempt. Called once
79
122
  * per failed attempt with the running consecutive-failure count.
@@ -142,6 +185,13 @@ export declare class SunspecInverter extends BaseSunspecDevice {
142
185
  private readonly pvPowerSource;
143
186
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
144
187
  private static readonly CONNECTION_FAULT_THRESHOLD;
188
+ /**
189
+ * The inverter data models this device can read (int+SF 101/103 and IEEE-754
190
+ * float 111/112/113). A post-reconnect discovery that finds none of these has
191
+ * not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
192
+ * see the override below.
193
+ */
194
+ private static readonly INVERTER_MODEL_IDS;
145
195
  /**
146
196
  * Require this many consecutive operatingState=7 (FAULT) reads before
147
197
  * reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
@@ -218,6 +268,14 @@ export declare class SunspecInverter extends BaseSunspecDevice {
218
268
  private hasErrorSetChanged;
219
269
  private buildStatusMessage;
220
270
  private detectAndEmitStatusTransition;
271
+ /**
272
+ * A reconnect has only recovered the inverter if discovery finds one of its
273
+ * data models. An SE gateway can accept the new socket and answer a partial
274
+ * scan (e.g. only the Common block) before the inverter map is ready — the
275
+ * base size>0 rule would accept that, but every inverter read would then find
276
+ * no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
277
+ */
278
+ protected getRequiredModelIds(): readonly number[];
221
279
  protected onConnectionFailure(consecutiveFailures: number): Promise<void>;
222
280
  protected onConnectionRestored(): Promise<void>;
223
281
  /**
@@ -430,6 +488,13 @@ export declare function filterFeaturesByCalibrationResult(detected: EnyoBatteryF
430
488
  export declare class SunspecBattery extends BaseSunspecDevice {
431
489
  private readonly featureMode;
432
490
  private readonly capabilities;
491
+ /**
492
+ * Battery data models this device can read: Battery (124, full decode) and
493
+ * BatteryBase (802, derived decode). BatteryControl (803) is intentionally
494
+ * excluded — it is a decode stub that yields no telemetry — so a rediscovery
495
+ * that returns only 803 is treated as unrecovered, matching the connect() gate.
496
+ */
497
+ private static readonly BATTERY_MODEL_IDS;
433
498
  private snapshotService?;
434
499
  private calibrationDriver?;
435
500
  private batteryCalibrator?;
@@ -478,6 +543,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
478
543
  * `CalibrationTrigger`.
479
544
  */
480
545
  getBatteryCalibrator(): BatteryCalibrator<SunspecBatteryControls> | undefined;
546
+ protected getRequiredModelIds(): readonly number[];
481
547
  /**
482
548
  * Connect to the battery and create/update the appliance
483
549
  */
@@ -646,6 +712,12 @@ export declare class SunspecBattery extends BaseSunspecDevice {
646
712
  */
647
713
  export declare class SunspecMeter extends BaseSunspecDevice {
648
714
  private readonly capabilities;
715
+ /**
716
+ * Meter data models this device can read, across int+SF (201/203/204) and
717
+ * IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
718
+ * variants. Used when the meter is not bound to a specific instance.
719
+ */
720
+ private static readonly METER_MODEL_IDS;
649
721
  constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, unitId?: number, port?: number, baseAddress?: number, capabilities?: SunspecMeterCapability[], retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean);
650
722
  /**
651
723
  * The specific meter model instance this meter reads, when its unit hosts more than one
@@ -659,6 +731,11 @@ export declare class SunspecMeter extends BaseSunspecDevice {
659
731
  * {@link SunspecModbusClient.findModels}). Call before {@link connect}.
660
732
  */
661
733
  bindMeterModel(model: SunspecModel): void;
734
+ /**
735
+ * A bound meter requires ITS own pinned model id to reappear after a
736
+ * rediscovery; an unbound meter accepts any meter model on its unit.
737
+ */
738
+ protected getRequiredModelIds(): readonly number[];
662
739
  /**
663
740
  * Connect to the meter and create/update the appliance
664
741
  */
@@ -672,4 +749,70 @@ export declare class SunspecMeter extends BaseSunspecDevice {
672
749
  */
673
750
  readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
674
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
+ }
675
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
  */
@@ -581,6 +581,25 @@ class SunspecModbusClient {
581
581
  this.poisonedUnits.add(unitId);
582
582
  this.connectionHealth.recordFailure(error);
583
583
  }
584
+ /**
585
+ * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
586
+ * readData()/tryReconnect() cycle recycles it — the same effect as a timeout poison but
587
+ * for a caller-detected fault that isn't itself a Modbus timeout.
588
+ *
589
+ * The motivating case: a TCP reconnect succeeds but the follow-up model discovery comes
590
+ * back empty because the gateway (e.g. a SolarEdge unit) accepted the socket before it was
591
+ * ready to answer the SunSpec scan. The link looks alive, so without this the reconnect
592
+ * would be trusted, an empty model map cached, and every subsequent read would find no
593
+ * model while nothing ever triggers another reconnect. Poisoning here keeps the retry
594
+ * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
595
+ */
596
+ invalidateUnit(unitId, reason) {
597
+ if (!this.poisonedUnits.has(unitId)) {
598
+ console.warn(`SunspecModbusClient: invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
599
+ }
600
+ this.poisonedUnits.add(unitId);
601
+ this.connectionHealth.recordFailure(new Error(reason));
602
+ }
584
603
  /**
585
604
  * A unit's socket is stale when the transport still reports it connected but no successful
586
605
  * transaction has completed within staleSocketMs — the signature of a half-open link where
@@ -689,7 +708,16 @@ class SunspecModbusClient {
689
708
  */
690
709
  async detectSunspecBaseAddress(unitId, customBaseAddress) {
691
710
  const instance = this.getInstance(unitId);
692
- // If custom base address provided, try it first (1-based, then 0-based variant)
711
+ // If a custom base address is provided, try it first (0-based, then 1-based variant).
712
+ //
713
+ // A custom base is only a real SunSpec anchor for a device whose map genuinely starts
714
+ // there. It is NOT an anchor when it points at a *model block* inside a shared unit —
715
+ // e.g. a SolarEdge meter block (~40188) co-resident with the inverter on unit 1: the
716
+ // "SunS" marker lives ONLY at the unit's SunSpec root (40000/40001), never at the meter
717
+ // block. So a miss here must NOT fail discovery; fall through to the standard root probe
718
+ // below. (This is exactly the reconnect path that used to strand the meter — its
719
+ // rediscovery threw "not SunSpec compliant" at 40188, returned no models, and poisoned
720
+ // the shared socket, dragging the inverter offline too.)
693
721
  if (customBaseAddress !== undefined) {
694
722
  console.log(`Detect models for custom base address '${customBaseAddress}' ...`);
695
723
  // Try 0-based at custom address
@@ -722,41 +750,44 @@ class SunspecModbusClient {
722
750
  catch (error) {
723
751
  console.debug(`Could not read SunS at ${customBaseAddress + 1}:`, error);
724
752
  }
753
+ console.debug(`No "SunS" marker at custom base ${customBaseAddress}/${customBaseAddress + 1} on unit ${unitId} — ` +
754
+ `falling back to the standard SunSpec root (40001/40000). Expected when the custom base points at a ` +
755
+ `model block inside a shared unit (e.g. a co-resident meter), whose anchor is the unit root.`);
725
756
  }
726
- else {
727
- // Try 1-based addressing first (most common)
728
- try {
729
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
730
- if (sunspecId.includes('SunS')) {
731
- console.log('Detected 1-based addressing mode (base address: 40001)');
732
- return {
733
- baseAddress: 40001,
734
- isZeroBased: false,
735
- nextAddress: 40003
736
- };
737
- }
738
- }
739
- catch (error) {
740
- console.debug('Could not read SunS at 40001:', error);
741
- }
742
- // Try 0-based addressing
743
- try {
744
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
745
- if (sunspecId.includes('SunS')) {
746
- console.log('Detected 0-based addressing mode (base address: 40000)');
747
- return {
748
- baseAddress: 40000,
749
- isZeroBased: true,
750
- nextAddress: 40002
751
- };
752
- }
757
+ // Standard SunSpec root probe. Runs when no custom base was given, OR as the fallback
758
+ // when the custom base carried no marker. Try 1-based (40001) first (most common), then
759
+ // 0-based (40000).
760
+ try {
761
+ const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
762
+ if (sunspecId.includes('SunS')) {
763
+ console.log('Detected 1-based addressing mode (base address: 40001)');
764
+ return {
765
+ baseAddress: 40001,
766
+ isZeroBased: false,
767
+ nextAddress: 40003
768
+ };
753
769
  }
754
- catch (error) {
755
- console.debug('Could not read SunS at 40000:', error);
770
+ }
771
+ catch (error) {
772
+ console.debug('Could not read SunS at 40001:', error);
773
+ }
774
+ // Try 0-based addressing
775
+ try {
776
+ const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
777
+ if (sunspecId.includes('SunS')) {
778
+ console.log('Detected 0-based addressing mode (base address: 40000)');
779
+ return {
780
+ baseAddress: 40000,
781
+ isZeroBased: true,
782
+ nextAddress: 40002
783
+ };
756
784
  }
757
785
  }
786
+ catch (error) {
787
+ console.debug('Could not read SunS at 40000:', error);
788
+ }
758
789
  const addressesChecked = customBaseAddress !== undefined
759
- ? `${customBaseAddress}, ${customBaseAddress + 1}`
790
+ ? `${customBaseAddress}, ${customBaseAddress + 1}, 40001, 40000`
760
791
  : '40000 or 40001';
761
792
  throw new Error(`Device is not SunSpec compliant - "SunS" identifier not found at addresses ${addressesChecked}`);
762
793
  }
@@ -767,29 +798,35 @@ class SunspecModbusClient {
767
798
  async discoverModels(unitId, customBaseAddress) {
768
799
  const instance = this.getInstance(unitId);
769
800
  const models = this.getModelsMap(unitId);
770
- models.clear();
771
801
  const modelList = this.getModelList(unitId);
772
- modelList.length = 0;
773
802
  const maxAddress = 50000; // Safety limit
774
- let currentAddress = 0;
775
803
  console.log(`Starting Sunspec model discovery for unit ${unitId}...`);
776
804
  // Probe for the SunS identifier first. A missing identifier means the unit ID isn't a
777
805
  // SunSpec device — common during unit-ID scans — and is logged at debug level so probes
778
806
  // don't surface as errors. Mid-scan failures below remain at error level since they
779
807
  // indicate a partial / malformed SunSpec map.
808
+ //
809
+ // IMPORTANT: we discover into TEMP buffers and only commit into the stored map once the
810
+ // walk yields at least one model. A reconnect probe can transiently fail (e.g. a single-
811
+ // session SolarEdge endpoint drops the socket with ECONNRESET on the first read after
812
+ // accepting the connection). Clearing the stored map up-front — as this used to — turned
813
+ // that blip into "no usable models", which trips tryReconnect()'s gate into invalidating
814
+ // a unit whose model map was perfectly good a moment ago. Preserving the last known-good
815
+ // map keeps a genuinely-connected sibling alive; a device that is really gone is still
816
+ // caught by read-health (isHealthy()).
780
817
  let addressInfo;
781
818
  try {
782
819
  addressInfo = await this.detectSunspecBaseAddress(unitId, customBaseAddress);
783
820
  }
784
821
  catch (error) {
785
822
  console.debug(`No SunSpec device at unit ${unitId}: ${error}`);
786
- // Discovery summary at line 594 below is the info-level outcome.
787
- // This 0-models branch is the same outcome as a normal "no device found",
788
- // covered already by the debug above. Keep at debug.
789
- console.debug(`Discovery complete for unit ${unitId}. Found 0 models: []`);
823
+ // Same outcome as a normal "no device found"; keep at debug. Do NOT wipe the stored
824
+ // map — return it untouched so a transient probe failure can't erase good discovery.
825
+ console.debug(`Discovery incomplete for unit ${unitId}; keeping ${models.size} previously-discovered model(s).`);
790
826
  return models;
791
827
  }
792
- currentAddress = addressInfo.nextAddress;
828
+ const discovered = [];
829
+ let currentAddress = addressInfo.nextAddress;
793
830
  try {
794
831
  while (currentAddress < maxAddress) {
795
832
  const buffer = await this.runExclusive(unitId, () => instance.readHoldingRegisters(currentAddress, 2));
@@ -805,19 +842,12 @@ class SunspecModbusClient {
805
842
  console.debug(`Found end marker at address ${currentAddress}`);
806
843
  break;
807
844
  }
808
- // Store discovered model
809
845
  const model = {
810
846
  id: modelId,
811
847
  address: currentAddress,
812
848
  length: modelLength
813
849
  };
814
- // Keep the FIRST (lowest-address) instance per id in the keyed directory so
815
- // findModel() resolves to the device's own block. Record every instance —
816
- // including repeats like a meter's Common (id 1) — in the ordered list.
817
- if (!models.has(modelId)) {
818
- models.set(modelId, model);
819
- }
820
- modelList.push(model);
850
+ discovered.push(model);
821
851
  // Per-model discovery step. The end-of-discovery summary below is the
822
852
  // info-level outcome; the per-model walk is debug-only.
823
853
  console.debug(`Discovered Model ${modelId} at address ${currentAddress} with length ${modelLength} (unit ${unitId})`);
@@ -828,6 +858,24 @@ class SunspecModbusClient {
828
858
  catch (error) {
829
859
  console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
830
860
  }
861
+ if (discovered.length > 0) {
862
+ // Commit the fresh discovery atomically. Keep the FIRST (lowest-address) instance per
863
+ // id in the keyed directory so findModel() resolves to the device's own block; record
864
+ // every instance — including repeats like a meter's Common (id 1) — in the ordered list.
865
+ models.clear();
866
+ modelList.length = 0;
867
+ for (const model of discovered) {
868
+ if (!models.has(model.id)) {
869
+ models.set(model.id, model);
870
+ }
871
+ modelList.push(model);
872
+ }
873
+ }
874
+ else {
875
+ // The anchor answered but the walk yielded nothing (e.g. the socket dropped right
876
+ // after the SunS probe). Preserve the last known-good map rather than clobbering it.
877
+ console.debug(`Discovery for unit ${unitId} yielded no models; keeping ${models.size} previously-discovered model(s).`);
878
+ }
831
879
  // Report every instance in address order so repeated ids (e.g. two Common blocks, or
832
880
  // multiple meters) are visible — models.size would hide them behind the unique keys.
833
881
  console.log(`Discovery complete for unit ${unitId}. Found ${modelList.length} model instance(s): [${modelList.map(m => m.id).join(', ')}]`);
@@ -969,12 +1017,87 @@ class SunspecModbusClient {
969
1017
  return value;
970
1018
  }
971
1019
  /**
972
- * Helper to read register value(s) using the fault-tolerant reader with data type conversion
1020
+ * Read a contiguous span of `quantity` registers starting at `address` in a single logical
1021
+ * transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
1022
+ * other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
1023
+ * when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
1024
+ * the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
1025
+ * individual fields out of the returned buffer with {@link decodeBlockValue}.
1026
+ */
1027
+ async readRegisterBlock(unitId, address, quantity, useInputRegisters = false) {
1028
+ const reader = this.getReader(unitId);
1029
+ const MAX_REGISTERS_PER_READ = 125;
1030
+ try {
1031
+ const chunks = await this.runExclusive(unitId, async () => {
1032
+ const acc = [];
1033
+ for (let offset = 0; offset < quantity; offset += MAX_REGISTERS_PER_READ) {
1034
+ const count = Math.min(MAX_REGISTERS_PER_READ, quantity - offset);
1035
+ let result;
1036
+ if (useInputRegisters) {
1037
+ if (!reader.readInputRegisters) {
1038
+ throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
1039
+ }
1040
+ result = await reader.readInputRegisters(address + offset, count);
1041
+ }
1042
+ else {
1043
+ result = await reader.readHoldingRegisters(address + offset, count);
1044
+ }
1045
+ if (!result.success || !result.value) {
1046
+ throw new Error(`Failed to read register block at address ${address + offset} (unit ${unitId}): ${result.error?.message || 'Unknown error'}`);
1047
+ }
1048
+ acc.push(result.value);
1049
+ }
1050
+ return acc;
1051
+ });
1052
+ this.connectionHealth.recordSuccess();
1053
+ return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
1054
+ }
1055
+ catch (error) {
1056
+ this.connectionHealth.recordFailure(error);
1057
+ throw error;
1058
+ }
1059
+ }
1060
+ /**
1061
+ * Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
1062
+ * from the block start. A thin public wrapper over the same block-extraction the SunSpec model
1063
+ * readers use internally.
1064
+ */
1065
+ decodeBlockValue(buffer, registerOffset, dataType, quantity = 1) {
1066
+ return this.extractValue(buffer, registerOffset, dataType, quantity);
1067
+ }
1068
+ /**
1069
+ * Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
1070
+ * conversion.
973
1071
  */
974
1072
  async readRegisterValue(unitId, address, quantity = 1, dataType) {
1073
+ return this.readTypedRegisters(unitId, address, quantity, dataType, false);
1074
+ }
1075
+ /**
1076
+ * Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
1077
+ * conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
1078
+ * {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
1079
+ * not implement `readInputRegisters`.
1080
+ */
1081
+ async readInputRegisterValue(unitId, address, quantity = 1, dataType) {
1082
+ return this.readTypedRegisters(unitId, address, quantity, dataType, true);
1083
+ }
1084
+ /**
1085
+ * Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
1086
+ * the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
1087
+ * connection health on both success and failure.
1088
+ */
1089
+ async readTypedRegisters(unitId, address, quantity, dataType, useInputRegisters) {
975
1090
  const reader = this.getReader(unitId);
976
1091
  try {
977
- const result = await this.runExclusive(unitId, () => reader.readHoldingRegisters(address, quantity));
1092
+ const result = await this.runExclusive(unitId, () => {
1093
+ if (useInputRegisters) {
1094
+ if (!reader.readInputRegisters) {
1095
+ throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
1096
+ }
1097
+ return reader.readInputRegisters(address, quantity);
1098
+ }
1099
+ return reader.readHoldingRegisters(address, quantity);
1100
+ });
978
1101
  // Check if the read was successful
979
1102
  if (!result.success || !result.value) {
980
1103
  throw new Error(`Failed to read register at address ${address}: ${result.error?.message || 'Unknown error'}`);
@@ -216,6 +216,19 @@ export declare class SunspecModbusClient {
216
216
  * 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
217
217
  */
218
218
  private poisonUnit;
219
+ /**
220
+ * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
221
+ * readData()/tryReconnect() cycle recycles it — the same effect as a timeout poison but
222
+ * for a caller-detected fault that isn't itself a Modbus timeout.
223
+ *
224
+ * The motivating case: a TCP reconnect succeeds but the follow-up model discovery comes
225
+ * back empty because the gateway (e.g. a SolarEdge unit) accepted the socket before it was
226
+ * ready to answer the SunSpec scan. The link looks alive, so without this the reconnect
227
+ * would be trusted, an empty model map cached, and every subsequent read would find no
228
+ * model while nothing ever triggers another reconnect. Poisoning here keeps the retry
229
+ * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
230
+ */
231
+ invalidateUnit(unitId: number, reason: string): void;
219
232
  /**
220
233
  * A unit's socket is stale when the transport still reports it connected but no successful
221
234
  * transaction has completed within staleSocketMs — the signature of a half-open link where
@@ -336,9 +349,38 @@ export declare class SunspecModbusClient {
336
349
  */
337
350
  private extractValue;
338
351
  /**
339
- * Helper to read register value(s) using the fault-tolerant reader with data type conversion
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.
340
369
  */
341
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;
342
384
  /**
343
385
  * Helper to write register value(s)
344
386
  */