@enyo-energy/sunspec-sdk 0.0.100 → 0.0.101

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.
@@ -183,8 +183,26 @@ class BaseSunspecDevice {
183
183
  // device's poll loop detects a dropped connection.
184
184
  const success = await this.sunspecClient.reconnectUnit(this.unitId);
185
185
  if (success) {
186
- // Re-discover models for this unit after reconnect
187
- await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
186
+ // Re-discover models for this unit after reconnect. discoverModels() clears
187
+ // and repopulates the per-unit model map, so a reconnect that opens the TCP
188
+ // socket but comes back with no usable models (a gateway that accepted the
189
+ // connection before it was ready to answer the SunSpec scan) would leave the
190
+ // map empty. Trusting that would cache an empty map — every read then finds no
191
+ // model while the socket looks healthy, and because reset() disables retry,
192
+ // nothing ever triggers another reconnect. So validate discovery here and, when
193
+ // it's unusable, treat this as a failed reconnect: invalidate the socket so the
194
+ // next poll re-enters tryReconnect(), keep the backoff schedule running, and do
195
+ // 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}`);
199
+ this.consecutiveReconnectFailures += 1;
200
+ await this.onConnectionFailure(this.consecutiveReconnectFailures);
201
+ 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`);
204
+ return false;
205
+ }
188
206
  this.retryManager.reset();
189
207
  this.consecutiveReconnectFailures = 0;
190
208
  // Update appliance state to Connected
@@ -207,6 +225,42 @@ class BaseSunspecDevice {
207
225
  }
208
226
  return false;
209
227
  }
228
+ /**
229
+ * Model IDs this device needs to produce a reading; presence of ANY one means a
230
+ * discovery is usable (one-of semantics — devices expose mutually-exclusive
231
+ * encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
232
+ * (the base default) means no specific requirement, so any model present
233
+ * suffices. Concrete devices override with their acceptable set — this is the
234
+ * single per-device source of truth reused by both the reconnect discovery gate
235
+ * ({@link isDiscoveryUsable}) and the connect-time presence gate
236
+ * ({@link hasRequiredModels}).
237
+ */
238
+ getRequiredModelIds() {
239
+ return [];
240
+ }
241
+ /**
242
+ * True if the current per-unit discovered-model map satisfies this device's
243
+ * requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
244
+ * the already-populated map via findModel() rather than a freshly-returned one.
245
+ * Only meaningful for devices that declare a non-empty required set.
246
+ */
247
+ hasRequiredModels() {
248
+ return this.getRequiredModelIds().some(id => this.sunspecClient.findModel(this.unitId, id) !== undefined);
249
+ }
250
+ /**
251
+ * Decide whether a post-reconnect model discovery is usable. A reconnect that
252
+ * establishes the TCP socket but comes back empty (or with only a Common block)
253
+ * means the device accepted the connection before it was ready to answer the
254
+ * SunSpec scan; the discovered-model map is now missing this device's data
255
+ * model, so trusting the reconnect would leave every read finding no model.
256
+ * Validated generically against {@link getRequiredModelIds}: with a declared
257
+ * set, at least one of those ids must be present; with none declared, fall back
258
+ * to "any model present".
259
+ */
260
+ isDiscoveryUsable(models) {
261
+ const required = this.getRequiredModelIds();
262
+ return required.length === 0 ? models.size > 0 : required.some(id => models.has(id));
263
+ }
210
264
  /**
211
265
  * Hook for subclasses to react to a failed reconnect attempt. Called once
212
266
  * per failed attempt with the running consecutive-failure count.
@@ -364,6 +418,19 @@ class SunspecInverter extends BaseSunspecDevice {
364
418
  pvPowerSource;
365
419
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
366
420
  static CONNECTION_FAULT_THRESHOLD = 3;
421
+ /**
422
+ * The inverter data models this device can read (int+SF 101/103 and IEEE-754
423
+ * float 111/112/113). A post-reconnect discovery that finds none of these has
424
+ * not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
425
+ * see the override below.
426
+ */
427
+ static INVERTER_MODEL_IDS = [
428
+ sunspec_interfaces_js_1.SunspecModelId.InverterSinglePhase,
429
+ sunspec_interfaces_js_1.SunspecModelId.Inverter3Phase,
430
+ sunspec_interfaces_js_1.SunspecModelId.InverterSinglePhaseFloat,
431
+ sunspec_interfaces_js_1.SunspecModelId.InverterSplitPhaseFloat,
432
+ sunspec_interfaces_js_1.SunspecModelId.Inverter3PhaseFloat
433
+ ];
367
434
  /**
368
435
  * Require this many consecutive operatingState=7 (FAULT) reads before
369
436
  * reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
@@ -746,6 +813,16 @@ class SunspecInverter extends BaseSunspecDevice {
746
813
  lastStatus: newLastStatus,
747
814
  };
748
815
  }
816
+ /**
817
+ * A reconnect has only recovered the inverter if discovery finds one of its
818
+ * data models. An SE gateway can accept the new socket and answer a partial
819
+ * scan (e.g. only the Common block) before the inverter map is ready — the
820
+ * base size>0 rule would accept that, but every inverter read would then find
821
+ * no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
822
+ */
823
+ getRequiredModelIds() {
824
+ return SunspecInverter.INVERTER_MODEL_IDS;
825
+ }
749
826
  async onConnectionFailure(consecutiveFailures) {
750
827
  if (!this.applianceId || !this.dataBus)
751
828
  return;
@@ -1295,6 +1372,16 @@ function filterFeaturesByCalibrationResult(detected, result, controllable) {
1295
1372
  class SunspecBattery extends BaseSunspecDevice {
1296
1373
  featureMode;
1297
1374
  capabilities;
1375
+ /**
1376
+ * Battery data models this device can read: Battery (124, full decode) and
1377
+ * BatteryBase (802, derived decode). BatteryControl (803) is intentionally
1378
+ * excluded — it is a decode stub that yields no telemetry — so a rediscovery
1379
+ * that returns only 803 is treated as unrecovered, matching the connect() gate.
1380
+ */
1381
+ static BATTERY_MODEL_IDS = [
1382
+ sunspec_interfaces_js_1.SunspecModelId.Battery,
1383
+ sunspec_interfaces_js_1.SunspecModelId.BatteryBase
1384
+ ];
1298
1385
  snapshotService;
1299
1386
  calibrationDriver;
1300
1387
  batteryCalibrator;
@@ -1398,16 +1485,17 @@ class SunspecBattery extends BaseSunspecDevice {
1398
1485
  getBatteryCalibrator() {
1399
1486
  return this.batteryCalibrator;
1400
1487
  }
1488
+ getRequiredModelIds() {
1489
+ return SunspecBattery.BATTERY_MODEL_IDS;
1490
+ }
1401
1491
  /**
1402
1492
  * Connect to the battery and create/update the appliance
1403
1493
  */
1404
1494
  async connect(inverterApplianceId) {
1405
1495
  // Ensure Sunspec client is connected
1406
1496
  await this.ensureConnected();
1407
- // Check if battery models exist
1408
- const hasBattery = this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.Battery) !== undefined ||
1409
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.BatteryBase) !== undefined;
1410
- if (!hasBattery) {
1497
+ // Check if battery models exist (124 or 802 — see BATTERY_MODEL_IDS).
1498
+ if (!this.hasRequiredModels()) {
1411
1499
  throw new Error('No battery model found in device');
1412
1500
  }
1413
1501
  // Get device info
@@ -1983,6 +2071,20 @@ exports.SunspecBattery = SunspecBattery;
1983
2071
  */
1984
2072
  class SunspecMeter extends BaseSunspecDevice {
1985
2073
  capabilities;
2074
+ /**
2075
+ * Meter data models this device can read, across int+SF (201/203/204) and
2076
+ * IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
2077
+ * variants. Used when the meter is not bound to a specific instance.
2078
+ */
2079
+ static METER_MODEL_IDS = [
2080
+ sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhase,
2081
+ sunspec_interfaces_js_1.SunspecModelId.Meter3Phase,
2082
+ sunspec_interfaces_js_1.SunspecModelId.MeterWye,
2083
+ sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhaseFloat,
2084
+ sunspec_interfaces_js_1.SunspecModelId.MeterSplitPhaseFloat,
2085
+ sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseWyeFloat,
2086
+ sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseDeltaFloat
2087
+ ];
1986
2088
  constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
1987
2089
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
1988
2090
  this.capabilities = capabilities;
@@ -2001,22 +2103,23 @@ class SunspecMeter extends BaseSunspecDevice {
2001
2103
  bindMeterModel(model) {
2002
2104
  this.meterModel = model;
2003
2105
  }
2106
+ /**
2107
+ * A bound meter requires ITS own pinned model id to reappear after a
2108
+ * rediscovery; an unbound meter accepts any meter model on its unit.
2109
+ */
2110
+ getRequiredModelIds() {
2111
+ return this.meterModel ? [this.meterModel.id] : SunspecMeter.METER_MODEL_IDS;
2112
+ }
2004
2113
  /**
2005
2114
  * Connect to the meter and create/update the appliance
2006
2115
  */
2007
2116
  async connect() {
2008
2117
  // Connect with specific unit ID for meter
2009
2118
  await this.ensureConnected();
2010
- // Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214)
2011
- const hasMeter = this.meterModel !== undefined ||
2012
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.Meter3Phase) !== undefined ||
2013
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.MeterWye) !== undefined ||
2014
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhase) !== undefined ||
2015
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseWyeFloat) !== undefined ||
2016
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseDeltaFloat) !== undefined ||
2017
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.MeterSplitPhaseFloat) !== undefined ||
2018
- this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhaseFloat) !== undefined;
2019
- if (!hasMeter) {
2119
+ // Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214).
2120
+ // A bound meter short-circuits: getRequiredModelIds() returns [meterModel.id],
2121
+ // which the just-completed discovery re-listed for the same physical device.
2122
+ if (!this.hasRequiredModels()) {
2020
2123
  throw new Error('No meter model found in device');
2021
2124
  }
2022
2125
  // Get device info. For a bound meter instance, read ITS own Common block (the one
@@ -74,6 +74,35 @@ export declare abstract class BaseSunspecDevice {
74
74
  * Returns true if reconnection succeeded.
75
75
  */
76
76
  protected tryReconnect(): Promise<boolean>;
77
+ /**
78
+ * Model IDs this device needs to produce a reading; presence of ANY one means a
79
+ * discovery is usable (one-of semantics — devices expose mutually-exclusive
80
+ * encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
81
+ * (the base default) means no specific requirement, so any model present
82
+ * suffices. Concrete devices override with their acceptable set — this is the
83
+ * single per-device source of truth reused by both the reconnect discovery gate
84
+ * ({@link isDiscoveryUsable}) and the connect-time presence gate
85
+ * ({@link hasRequiredModels}).
86
+ */
87
+ protected getRequiredModelIds(): readonly number[];
88
+ /**
89
+ * True if the current per-unit discovered-model map satisfies this device's
90
+ * requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
91
+ * the already-populated map via findModel() rather than a freshly-returned one.
92
+ * Only meaningful for devices that declare a non-empty required set.
93
+ */
94
+ protected hasRequiredModels(): boolean;
95
+ /**
96
+ * Decide whether a post-reconnect model discovery is usable. A reconnect that
97
+ * establishes the TCP socket but comes back empty (or with only a Common block)
98
+ * means the device accepted the connection before it was ready to answer the
99
+ * SunSpec scan; the discovered-model map is now missing this device's data
100
+ * model, so trusting the reconnect would leave every read finding no model.
101
+ * Validated generically against {@link getRequiredModelIds}: with a declared
102
+ * set, at least one of those ids must be present; with none declared, fall back
103
+ * to "any model present".
104
+ */
105
+ protected isDiscoveryUsable(models: Map<number, SunspecModel>): boolean;
77
106
  /**
78
107
  * Hook for subclasses to react to a failed reconnect attempt. Called once
79
108
  * per failed attempt with the running consecutive-failure count.
@@ -142,6 +171,13 @@ export declare class SunspecInverter extends BaseSunspecDevice {
142
171
  private readonly pvPowerSource;
143
172
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
144
173
  private static readonly CONNECTION_FAULT_THRESHOLD;
174
+ /**
175
+ * The inverter data models this device can read (int+SF 101/103 and IEEE-754
176
+ * float 111/112/113). A post-reconnect discovery that finds none of these has
177
+ * not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
178
+ * see the override below.
179
+ */
180
+ private static readonly INVERTER_MODEL_IDS;
145
181
  /**
146
182
  * Require this many consecutive operatingState=7 (FAULT) reads before
147
183
  * reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
@@ -218,6 +254,14 @@ export declare class SunspecInverter extends BaseSunspecDevice {
218
254
  private hasErrorSetChanged;
219
255
  private buildStatusMessage;
220
256
  private detectAndEmitStatusTransition;
257
+ /**
258
+ * A reconnect has only recovered the inverter if discovery finds one of its
259
+ * data models. An SE gateway can accept the new socket and answer a partial
260
+ * scan (e.g. only the Common block) before the inverter map is ready — the
261
+ * base size>0 rule would accept that, but every inverter read would then find
262
+ * no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
263
+ */
264
+ protected getRequiredModelIds(): readonly number[];
221
265
  protected onConnectionFailure(consecutiveFailures: number): Promise<void>;
222
266
  protected onConnectionRestored(): Promise<void>;
223
267
  /**
@@ -430,6 +474,13 @@ export declare function filterFeaturesByCalibrationResult(detected: EnyoBatteryF
430
474
  export declare class SunspecBattery extends BaseSunspecDevice {
431
475
  private readonly featureMode;
432
476
  private readonly capabilities;
477
+ /**
478
+ * Battery data models this device can read: Battery (124, full decode) and
479
+ * BatteryBase (802, derived decode). BatteryControl (803) is intentionally
480
+ * excluded — it is a decode stub that yields no telemetry — so a rediscovery
481
+ * that returns only 803 is treated as unrecovered, matching the connect() gate.
482
+ */
483
+ private static readonly BATTERY_MODEL_IDS;
433
484
  private snapshotService?;
434
485
  private calibrationDriver?;
435
486
  private batteryCalibrator?;
@@ -478,6 +529,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
478
529
  * `CalibrationTrigger`.
479
530
  */
480
531
  getBatteryCalibrator(): BatteryCalibrator<SunspecBatteryControls> | undefined;
532
+ protected getRequiredModelIds(): readonly number[];
481
533
  /**
482
534
  * Connect to the battery and create/update the appliance
483
535
  */
@@ -646,6 +698,12 @@ export declare class SunspecBattery extends BaseSunspecDevice {
646
698
  */
647
699
  export declare class SunspecMeter extends BaseSunspecDevice {
648
700
  private readonly capabilities;
701
+ /**
702
+ * Meter data models this device can read, across int+SF (201/203/204) and
703
+ * IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
704
+ * variants. Used when the meter is not bound to a specific instance.
705
+ */
706
+ private static readonly METER_MODEL_IDS;
649
707
  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
708
  /**
651
709
  * The specific meter model instance this meter reads, when its unit hosts more than one
@@ -659,6 +717,11 @@ export declare class SunspecMeter extends BaseSunspecDevice {
659
717
  * {@link SunspecModbusClient.findModels}). Call before {@link connect}.
660
718
  */
661
719
  bindMeterModel(model: SunspecModel): void;
720
+ /**
721
+ * A bound meter requires ITS own pinned model id to reappear after a
722
+ * rediscovery; an unbound meter accepts any meter model on its unit.
723
+ */
724
+ protected getRequiredModelIds(): readonly number[];
662
725
  /**
663
726
  * Connect to the meter and create/update the appliance
664
727
  */
@@ -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
@@ -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
@@ -9,7 +9,7 @@ exports.getSdkVersion = getSdkVersion;
9
9
  /**
10
10
  * Current version of the enyo Energy App SDK.
11
11
  */
12
- exports.SDK_VERSION = '0.0.100';
12
+ exports.SDK_VERSION = '0.0.101';
13
13
  /**
14
14
  * Gets the current SDK version.
15
15
  * @returns The semantic version string of the SDK
@@ -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.100";
8
+ export declare const SDK_VERSION = "0.0.101";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
@@ -74,6 +74,35 @@ export declare abstract class BaseSunspecDevice {
74
74
  * Returns true if reconnection succeeded.
75
75
  */
76
76
  protected tryReconnect(): Promise<boolean>;
77
+ /**
78
+ * Model IDs this device needs to produce a reading; presence of ANY one means a
79
+ * discovery is usable (one-of semantics — devices expose mutually-exclusive
80
+ * encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
81
+ * (the base default) means no specific requirement, so any model present
82
+ * suffices. Concrete devices override with their acceptable set — this is the
83
+ * single per-device source of truth reused by both the reconnect discovery gate
84
+ * ({@link isDiscoveryUsable}) and the connect-time presence gate
85
+ * ({@link hasRequiredModels}).
86
+ */
87
+ protected getRequiredModelIds(): readonly number[];
88
+ /**
89
+ * True if the current per-unit discovered-model map satisfies this device's
90
+ * requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
91
+ * the already-populated map via findModel() rather than a freshly-returned one.
92
+ * Only meaningful for devices that declare a non-empty required set.
93
+ */
94
+ protected hasRequiredModels(): boolean;
95
+ /**
96
+ * Decide whether a post-reconnect model discovery is usable. A reconnect that
97
+ * establishes the TCP socket but comes back empty (or with only a Common block)
98
+ * means the device accepted the connection before it was ready to answer the
99
+ * SunSpec scan; the discovered-model map is now missing this device's data
100
+ * model, so trusting the reconnect would leave every read finding no model.
101
+ * Validated generically against {@link getRequiredModelIds}: with a declared
102
+ * set, at least one of those ids must be present; with none declared, fall back
103
+ * to "any model present".
104
+ */
105
+ protected isDiscoveryUsable(models: Map<number, SunspecModel>): boolean;
77
106
  /**
78
107
  * Hook for subclasses to react to a failed reconnect attempt. Called once
79
108
  * per failed attempt with the running consecutive-failure count.
@@ -142,6 +171,13 @@ export declare class SunspecInverter extends BaseSunspecDevice {
142
171
  private readonly pvPowerSource;
143
172
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
144
173
  private static readonly CONNECTION_FAULT_THRESHOLD;
174
+ /**
175
+ * The inverter data models this device can read (int+SF 101/103 and IEEE-754
176
+ * float 111/112/113). A post-reconnect discovery that finds none of these has
177
+ * not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
178
+ * see the override below.
179
+ */
180
+ private static readonly INVERTER_MODEL_IDS;
145
181
  /**
146
182
  * Require this many consecutive operatingState=7 (FAULT) reads before
147
183
  * reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
@@ -218,6 +254,14 @@ export declare class SunspecInverter extends BaseSunspecDevice {
218
254
  private hasErrorSetChanged;
219
255
  private buildStatusMessage;
220
256
  private detectAndEmitStatusTransition;
257
+ /**
258
+ * A reconnect has only recovered the inverter if discovery finds one of its
259
+ * data models. An SE gateway can accept the new socket and answer a partial
260
+ * scan (e.g. only the Common block) before the inverter map is ready — the
261
+ * base size>0 rule would accept that, but every inverter read would then find
262
+ * no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
263
+ */
264
+ protected getRequiredModelIds(): readonly number[];
221
265
  protected onConnectionFailure(consecutiveFailures: number): Promise<void>;
222
266
  protected onConnectionRestored(): Promise<void>;
223
267
  /**
@@ -430,6 +474,13 @@ export declare function filterFeaturesByCalibrationResult(detected: EnyoBatteryF
430
474
  export declare class SunspecBattery extends BaseSunspecDevice {
431
475
  private readonly featureMode;
432
476
  private readonly capabilities;
477
+ /**
478
+ * Battery data models this device can read: Battery (124, full decode) and
479
+ * BatteryBase (802, derived decode). BatteryControl (803) is intentionally
480
+ * excluded — it is a decode stub that yields no telemetry — so a rediscovery
481
+ * that returns only 803 is treated as unrecovered, matching the connect() gate.
482
+ */
483
+ private static readonly BATTERY_MODEL_IDS;
433
484
  private snapshotService?;
434
485
  private calibrationDriver?;
435
486
  private batteryCalibrator?;
@@ -478,6 +529,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
478
529
  * `CalibrationTrigger`.
479
530
  */
480
531
  getBatteryCalibrator(): BatteryCalibrator<SunspecBatteryControls> | undefined;
532
+ protected getRequiredModelIds(): readonly number[];
481
533
  /**
482
534
  * Connect to the battery and create/update the appliance
483
535
  */
@@ -646,6 +698,12 @@ export declare class SunspecBattery extends BaseSunspecDevice {
646
698
  */
647
699
  export declare class SunspecMeter extends BaseSunspecDevice {
648
700
  private readonly capabilities;
701
+ /**
702
+ * Meter data models this device can read, across int+SF (201/203/204) and
703
+ * IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
704
+ * variants. Used when the meter is not bound to a specific instance.
705
+ */
706
+ private static readonly METER_MODEL_IDS;
649
707
  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
708
  /**
651
709
  * The specific meter model instance this meter reads, when its unit hosts more than one
@@ -659,6 +717,11 @@ export declare class SunspecMeter extends BaseSunspecDevice {
659
717
  * {@link SunspecModbusClient.findModels}). Call before {@link connect}.
660
718
  */
661
719
  bindMeterModel(model: SunspecModel): void;
720
+ /**
721
+ * A bound meter requires ITS own pinned model id to reappear after a
722
+ * rediscovery; an unbound meter accepts any meter model on its unit.
723
+ */
724
+ protected getRequiredModelIds(): readonly number[];
662
725
  /**
663
726
  * Connect to the meter and create/update the appliance
664
727
  */
@@ -176,8 +176,26 @@ export class BaseSunspecDevice {
176
176
  // device's poll loop detects a dropped connection.
177
177
  const success = await this.sunspecClient.reconnectUnit(this.unitId);
178
178
  if (success) {
179
- // Re-discover models for this unit after reconnect
180
- await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
179
+ // Re-discover models for this unit after reconnect. discoverModels() clears
180
+ // and repopulates the per-unit model map, so a reconnect that opens the TCP
181
+ // socket but comes back with no usable models (a gateway that accepted the
182
+ // connection before it was ready to answer the SunSpec scan) would leave the
183
+ // map empty. Trusting that would cache an empty map — every read then finds no
184
+ // model while the socket looks healthy, and because reset() disables retry,
185
+ // nothing ever triggers another reconnect. So validate discovery here and, when
186
+ // it's unusable, treat this as a failed reconnect: invalidate the socket so the
187
+ // next poll re-enters tryReconnect(), keep the backoff schedule running, and do
188
+ // NOT reset().
189
+ const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
190
+ if (!this.isDiscoveryUsable(models)) {
191
+ this.sunspecClient.invalidateUnit(this.unitId, `reconnect discovery found no usable models for unit ${this.unitId}`);
192
+ this.consecutiveReconnectFailures += 1;
193
+ await this.onConnectionFailure(this.consecutiveReconnectFailures);
194
+ console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
195
+ `opened the socket but discovery returned no usable models ` +
196
+ `(found [${[...models.keys()].join(', ')}]) — retrying with backoff`);
197
+ return false;
198
+ }
181
199
  this.retryManager.reset();
182
200
  this.consecutiveReconnectFailures = 0;
183
201
  // Update appliance state to Connected
@@ -200,6 +218,42 @@ export class BaseSunspecDevice {
200
218
  }
201
219
  return false;
202
220
  }
221
+ /**
222
+ * Model IDs this device needs to produce a reading; presence of ANY one means a
223
+ * discovery is usable (one-of semantics — devices expose mutually-exclusive
224
+ * encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
225
+ * (the base default) means no specific requirement, so any model present
226
+ * suffices. Concrete devices override with their acceptable set — this is the
227
+ * single per-device source of truth reused by both the reconnect discovery gate
228
+ * ({@link isDiscoveryUsable}) and the connect-time presence gate
229
+ * ({@link hasRequiredModels}).
230
+ */
231
+ getRequiredModelIds() {
232
+ return [];
233
+ }
234
+ /**
235
+ * True if the current per-unit discovered-model map satisfies this device's
236
+ * requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
237
+ * the already-populated map via findModel() rather than a freshly-returned one.
238
+ * Only meaningful for devices that declare a non-empty required set.
239
+ */
240
+ hasRequiredModels() {
241
+ return this.getRequiredModelIds().some(id => this.sunspecClient.findModel(this.unitId, id) !== undefined);
242
+ }
243
+ /**
244
+ * Decide whether a post-reconnect model discovery is usable. A reconnect that
245
+ * establishes the TCP socket but comes back empty (or with only a Common block)
246
+ * means the device accepted the connection before it was ready to answer the
247
+ * SunSpec scan; the discovered-model map is now missing this device's data
248
+ * model, so trusting the reconnect would leave every read finding no model.
249
+ * Validated generically against {@link getRequiredModelIds}: with a declared
250
+ * set, at least one of those ids must be present; with none declared, fall back
251
+ * to "any model present".
252
+ */
253
+ isDiscoveryUsable(models) {
254
+ const required = this.getRequiredModelIds();
255
+ return required.length === 0 ? models.size > 0 : required.some(id => models.has(id));
256
+ }
203
257
  /**
204
258
  * Hook for subclasses to react to a failed reconnect attempt. Called once
205
259
  * per failed attempt with the running consecutive-failure count.
@@ -356,6 +410,19 @@ export class SunspecInverter extends BaseSunspecDevice {
356
410
  pvPowerSource;
357
411
  /** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
358
412
  static CONNECTION_FAULT_THRESHOLD = 3;
413
+ /**
414
+ * The inverter data models this device can read (int+SF 101/103 and IEEE-754
415
+ * float 111/112/113). A post-reconnect discovery that finds none of these has
416
+ * not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
417
+ * see the override below.
418
+ */
419
+ static INVERTER_MODEL_IDS = [
420
+ SunspecModelId.InverterSinglePhase,
421
+ SunspecModelId.Inverter3Phase,
422
+ SunspecModelId.InverterSinglePhaseFloat,
423
+ SunspecModelId.InverterSplitPhaseFloat,
424
+ SunspecModelId.Inverter3PhaseFloat
425
+ ];
359
426
  /**
360
427
  * Require this many consecutive operatingState=7 (FAULT) reads before
361
428
  * reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
@@ -738,6 +805,16 @@ export class SunspecInverter extends BaseSunspecDevice {
738
805
  lastStatus: newLastStatus,
739
806
  };
740
807
  }
808
+ /**
809
+ * A reconnect has only recovered the inverter if discovery finds one of its
810
+ * data models. An SE gateway can accept the new socket and answer a partial
811
+ * scan (e.g. only the Common block) before the inverter map is ready — the
812
+ * base size>0 rule would accept that, but every inverter read would then find
813
+ * no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
814
+ */
815
+ getRequiredModelIds() {
816
+ return SunspecInverter.INVERTER_MODEL_IDS;
817
+ }
741
818
  async onConnectionFailure(consecutiveFailures) {
742
819
  if (!this.applianceId || !this.dataBus)
743
820
  return;
@@ -1286,6 +1363,16 @@ export function filterFeaturesByCalibrationResult(detected, result, controllable
1286
1363
  export class SunspecBattery extends BaseSunspecDevice {
1287
1364
  featureMode;
1288
1365
  capabilities;
1366
+ /**
1367
+ * Battery data models this device can read: Battery (124, full decode) and
1368
+ * BatteryBase (802, derived decode). BatteryControl (803) is intentionally
1369
+ * excluded — it is a decode stub that yields no telemetry — so a rediscovery
1370
+ * that returns only 803 is treated as unrecovered, matching the connect() gate.
1371
+ */
1372
+ static BATTERY_MODEL_IDS = [
1373
+ SunspecModelId.Battery,
1374
+ SunspecModelId.BatteryBase
1375
+ ];
1289
1376
  snapshotService;
1290
1377
  calibrationDriver;
1291
1378
  batteryCalibrator;
@@ -1389,16 +1476,17 @@ export class SunspecBattery extends BaseSunspecDevice {
1389
1476
  getBatteryCalibrator() {
1390
1477
  return this.batteryCalibrator;
1391
1478
  }
1479
+ getRequiredModelIds() {
1480
+ return SunspecBattery.BATTERY_MODEL_IDS;
1481
+ }
1392
1482
  /**
1393
1483
  * Connect to the battery and create/update the appliance
1394
1484
  */
1395
1485
  async connect(inverterApplianceId) {
1396
1486
  // Ensure Sunspec client is connected
1397
1487
  await this.ensureConnected();
1398
- // Check if battery models exist
1399
- const hasBattery = this.sunspecClient.findModel(this.unitId, SunspecModelId.Battery) !== undefined ||
1400
- this.sunspecClient.findModel(this.unitId, SunspecModelId.BatteryBase) !== undefined;
1401
- if (!hasBattery) {
1488
+ // Check if battery models exist (124 or 802 — see BATTERY_MODEL_IDS).
1489
+ if (!this.hasRequiredModels()) {
1402
1490
  throw new Error('No battery model found in device');
1403
1491
  }
1404
1492
  // Get device info
@@ -1973,6 +2061,20 @@ export class SunspecBattery extends BaseSunspecDevice {
1973
2061
  */
1974
2062
  export class SunspecMeter extends BaseSunspecDevice {
1975
2063
  capabilities;
2064
+ /**
2065
+ * Meter data models this device can read, across int+SF (201/203/204) and
2066
+ * IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
2067
+ * variants. Used when the meter is not bound to a specific instance.
2068
+ */
2069
+ static METER_MODEL_IDS = [
2070
+ SunspecModelId.MeterSinglePhase,
2071
+ SunspecModelId.Meter3Phase,
2072
+ SunspecModelId.MeterWye,
2073
+ SunspecModelId.MeterSinglePhaseFloat,
2074
+ SunspecModelId.MeterSplitPhaseFloat,
2075
+ SunspecModelId.Meter3PhaseWyeFloat,
2076
+ SunspecModelId.Meter3PhaseDeltaFloat
2077
+ ];
1976
2078
  constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
1977
2079
  super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
1978
2080
  this.capabilities = capabilities;
@@ -1991,22 +2093,23 @@ export class SunspecMeter extends BaseSunspecDevice {
1991
2093
  bindMeterModel(model) {
1992
2094
  this.meterModel = model;
1993
2095
  }
2096
+ /**
2097
+ * A bound meter requires ITS own pinned model id to reappear after a
2098
+ * rediscovery; an unbound meter accepts any meter model on its unit.
2099
+ */
2100
+ getRequiredModelIds() {
2101
+ return this.meterModel ? [this.meterModel.id] : SunspecMeter.METER_MODEL_IDS;
2102
+ }
1994
2103
  /**
1995
2104
  * Connect to the meter and create/update the appliance
1996
2105
  */
1997
2106
  async connect() {
1998
2107
  // Connect with specific unit ID for meter
1999
2108
  await this.ensureConnected();
2000
- // Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214)
2001
- const hasMeter = this.meterModel !== undefined ||
2002
- this.sunspecClient.findModel(this.unitId, SunspecModelId.Meter3Phase) !== undefined ||
2003
- this.sunspecClient.findModel(this.unitId, SunspecModelId.MeterWye) !== undefined ||
2004
- this.sunspecClient.findModel(this.unitId, SunspecModelId.MeterSinglePhase) !== undefined ||
2005
- this.sunspecClient.findModel(this.unitId, SunspecModelId.Meter3PhaseWyeFloat) !== undefined ||
2006
- this.sunspecClient.findModel(this.unitId, SunspecModelId.Meter3PhaseDeltaFloat) !== undefined ||
2007
- this.sunspecClient.findModel(this.unitId, SunspecModelId.MeterSplitPhaseFloat) !== undefined ||
2008
- this.sunspecClient.findModel(this.unitId, SunspecModelId.MeterSinglePhaseFloat) !== undefined;
2009
- if (!hasMeter) {
2109
+ // Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214).
2110
+ // A bound meter short-circuits: getRequiredModelIds() returns [meterModel.id],
2111
+ // which the just-completed discovery re-listed for the same physical device.
2112
+ if (!this.hasRequiredModels()) {
2010
2113
  throw new Error('No meter model found in device');
2011
2114
  }
2012
2115
  // Get device info. For a bound meter instance, read ITS own Common block (the one
@@ -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
@@ -574,6 +574,25 @@ export class SunspecModbusClient {
574
574
  this.poisonedUnits.add(unitId);
575
575
  this.connectionHealth.recordFailure(error);
576
576
  }
577
+ /**
578
+ * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
579
+ * readData()/tryReconnect() cycle recycles it — the same effect as a timeout poison but
580
+ * for a caller-detected fault that isn't itself a Modbus timeout.
581
+ *
582
+ * The motivating case: a TCP reconnect succeeds but the follow-up model discovery comes
583
+ * back empty because the gateway (e.g. a SolarEdge unit) accepted the socket before it was
584
+ * ready to answer the SunSpec scan. The link looks alive, so without this the reconnect
585
+ * would be trusted, an empty model map cached, and every subsequent read would find no
586
+ * model while nothing ever triggers another reconnect. Poisoning here keeps the retry
587
+ * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
588
+ */
589
+ invalidateUnit(unitId, reason) {
590
+ if (!this.poisonedUnits.has(unitId)) {
591
+ console.warn(`SunspecModbusClient: invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
592
+ }
593
+ this.poisonedUnits.add(unitId);
594
+ this.connectionHealth.recordFailure(new Error(reason));
595
+ }
577
596
  /**
578
597
  * A unit's socket is stale when the transport still reports it connected but no successful
579
598
  * transaction has completed within staleSocketMs — the signature of a half-open link where
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.100";
8
+ export declare const SDK_VERSION = "0.0.101";
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.100';
8
+ export const SDK_VERSION = '0.0.101';
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.100",
3
+ "version": "0.0.101",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",