@enyo-energy/sunspec-sdk 0.0.98 → 0.0.100

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.
@@ -21,6 +21,10 @@ class ConnectionRetryManager {
21
21
  disconnectedSince = null;
22
22
  lastAttemptTime = 0;
23
23
  attemptCount = 0;
24
+ // Jittered gate for the NEXT attempt, computed when the previous one is recorded. 0 means
25
+ // "use the raw phase interval" — the state before any attempt, so the first reconnect after a
26
+ // disconnect fires immediately (preserving the original behaviour).
27
+ nextIntervalMs = 0;
24
28
  constructor(config) {
25
29
  this.config = config ?? sunspec_interfaces_js_1.DEFAULT_RETRY_CONFIG;
26
30
  }
@@ -39,6 +43,7 @@ class ConnectionRetryManager {
39
43
  this.disconnectedSince = null;
40
44
  this.lastAttemptTime = 0;
41
45
  this.attemptCount = 0;
46
+ this.nextIntervalMs = 0;
42
47
  }
43
48
  /**
44
49
  * Determine which retry phase we're currently in based on elapsed time since disconnect.
@@ -69,7 +74,11 @@ class ConnectionRetryManager {
69
74
  }
70
75
  const now = Date.now();
71
76
  const phase = this.getCurrentPhase();
72
- return (now - this.lastAttemptTime) >= phase.intervalMs;
77
+ // Before the first attempt (nextIntervalMs === 0), lastAttemptTime is 0 so the gate is
78
+ // effectively open — the first reconnect fires right away. Afterwards, honour the jittered
79
+ // interval computed at the previous recordAttempt().
80
+ const interval = this.nextIntervalMs > 0 ? this.nextIntervalMs : phase.intervalMs;
81
+ return (now - this.lastAttemptTime) >= interval;
73
82
  }
74
83
  /**
75
84
  * Record that an attempt was just made.
@@ -77,6 +86,21 @@ class ConnectionRetryManager {
77
86
  recordAttempt() {
78
87
  this.lastAttemptTime = Date.now();
79
88
  this.attemptCount++;
89
+ // Pre-compute the (jittered) gate for the next attempt so a fleet that dropped together
90
+ // spreads its retries instead of stampeding one gateway on every phase boundary.
91
+ this.nextIntervalMs = this.applyJitter(this.getCurrentPhase().intervalMs);
92
+ }
93
+ /**
94
+ * Spread an interval by ±jitter fraction. Returns the interval unchanged when jitter is
95
+ * unset/zero. Never returns a negative value.
96
+ */
97
+ applyJitter(intervalMs) {
98
+ const jitter = this.config.jitter ?? 0;
99
+ if (jitter <= 0) {
100
+ return intervalMs;
101
+ }
102
+ const factor = 1 + (Math.random() * 2 - 1) * jitter;
103
+ return Math.max(0, Math.round(intervalMs * factor));
80
104
  }
81
105
  /**
82
106
  * Get the number of reconnection attempts made.
@@ -18,6 +18,7 @@ export declare class ConnectionRetryManager {
18
18
  private disconnectedSince;
19
19
  private lastAttemptTime;
20
20
  private attemptCount;
21
+ private nextIntervalMs;
21
22
  constructor(config?: IRetryConfig);
22
23
  /**
23
24
  * Mark the connection as disconnected. Sets the timestamp if not already set.
@@ -40,6 +41,11 @@ export declare class ConnectionRetryManager {
40
41
  * Record that an attempt was just made.
41
42
  */
42
43
  recordAttempt(): void;
44
+ /**
45
+ * Spread an interval by ±jitter fraction. Returns the interval unchanged when jitter is
46
+ * unset/zero. Never returns a negative value.
47
+ */
48
+ private applyJitter;
43
49
  /**
44
50
  * Get the number of reconnection attempts made.
45
51
  */
@@ -3,7 +3,7 @@
3
3
  * SunSpec block interfaces with block numbers
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SUNSPEC_CONTROLLABLE_FEATURES = exports.SunspecMeterCapability = exports.SunspecBatteryFeatureModeKind = exports.SunspecBatteryCapability = exports.SunspecPvPowerOrigin = exports.SunspecPvPowerSource = exports.SunspecInverterCapability = exports.SunspecStorageMode = exports.SunspecChargeSource = exports.SunspecVArPctMode = exports.SunspecEnableControl = exports.SunspecConnectionControl = exports.SunspecStorageControlMode = exports.SunspecBatteryEvent1 = exports.SunspecBatteryBankState = exports.SunspecBatteryType = exports.SunspecBatteryControlMode = exports.SunspecBatteryChargeState = exports.SunspecInverterOperatingState = exports.SunspecMPPTOperatingState = exports.SUNSPEC_CONNECTION_LOST_CODE = exports.SunspecInverterEvent1 = exports.SunspecModelId = exports.DEFAULT_RETRY_CONFIG = void 0;
6
+ exports.SUNSPEC_CONTROLLABLE_FEATURES = exports.SunspecMeterCapability = exports.SunspecBatteryFeatureModeKind = exports.SunspecBatteryCapability = exports.SunspecPvPowerOrigin = exports.SunspecPvPowerSource = exports.SunspecInverterCapability = exports.SunspecStorageMode = exports.SunspecChargeSource = exports.SunspecVArPctMode = exports.SunspecEnableControl = exports.SunspecConnectionControl = exports.SunspecStorageControlMode = exports.SunspecBatteryEvent1 = exports.SunspecBatteryBankState = exports.SunspecBatteryType = exports.SunspecBatteryControlMode = exports.SunspecBatteryChargeState = exports.SunspecInverterOperatingState = exports.SunspecMPPTOperatingState = exports.SUNSPEC_CONNECTION_LOST_CODE = exports.SunspecInverterEvent1 = exports.SunspecModelId = exports.DEFAULT_MODBUS_RESILIENCE_CONFIG = exports.DEFAULT_RETRY_CONFIG = void 0;
7
7
  const enyo_battery_appliance_js_1 = require("@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js");
8
8
  exports.DEFAULT_RETRY_CONFIG = {
9
9
  phases: [
@@ -12,7 +12,16 @@ exports.DEFAULT_RETRY_CONFIG = {
12
12
  { intervalMs: 60_000, durationMs: 300_000 }, // Phase 3: every 1m for 5 minutes
13
13
  { intervalMs: 300_000, durationMs: 600_000 }, // Phase 4: every 5m for 10 minutes
14
14
  { intervalMs: 900_000, durationMs: 0 }, // Phase 5: every 15m forever
15
- ]
15
+ ],
16
+ jitter: 0.2,
17
+ };
18
+ exports.DEFAULT_MODBUS_RESILIENCE_CONFIG = {
19
+ readTimeoutMs: 5_000,
20
+ connectTimeoutMs: 5_000,
21
+ disconnectTimeoutMs: 5_000,
22
+ staleSocketMs: 30_000,
23
+ connectRetries: 1,
24
+ connectRetryDelayMs: 500,
16
25
  };
17
26
  /**
18
27
  * Common Sunspec Model IDs
@@ -15,6 +15,14 @@ export interface IRetryPhase {
15
15
  */
16
16
  export interface IRetryConfig {
17
17
  phases: IRetryPhase[];
18
+ /**
19
+ * Optional jitter fraction (0..1) applied to each phase interval so a fleet of devices that
20
+ * dropped together (e.g. a gateway reboot or a shared outage) does not line up its reconnect
21
+ * attempts on the same 10s/30s/… boundaries and stampede one bridge. The effective gate for a
22
+ * given attempt becomes `intervalMs * (1 + random(-jitter, +jitter))`. The very first attempt
23
+ * after a disconnect still fires immediately. Default 0.2 (±20%); set 0 to disable.
24
+ */
25
+ jitter?: number;
18
26
  }
19
27
  export declare const DEFAULT_RETRY_CONFIG: IRetryConfig;
20
28
  /**
@@ -37,6 +45,59 @@ export interface IModbusPacingConfig {
37
45
  */
38
46
  waitBetweenMessagesMs?: number;
39
47
  }
48
+ /**
49
+ * Resilience configuration for the Modbus client: per-operation timeouts and half-open socket
50
+ * detection. All fields are optional and default to sensible values, so existing consumers are
51
+ * unaffected.
52
+ *
53
+ * These guard the "stuck connection" failure mode: the injected transport's `connect({ timeout })`
54
+ * only bounds the TCP handshake, NOT individual reads/writes. On a half-open socket (the peer stops
55
+ * answering while the OS still reports the connection ESTABLISHED) a read can stay pending forever,
56
+ * wedging the affected unit's transaction chain and stalling its whole poll loop with no failure
57
+ * ever recorded. A per-operation timeout plus a freshness clock turn that silent hang into a fast,
58
+ * observable failure the reconnect path can recover from.
59
+ */
60
+ export interface IModbusResilienceConfig {
61
+ /**
62
+ * Max ms a single Modbus transaction (a read/write, including a multi-chunk block read) may take
63
+ * before it is abandoned with a timeout, the socket is poisoned, and the reconnect path recycles
64
+ * it. Default 5000.
65
+ */
66
+ readTimeoutMs?: number;
67
+ /**
68
+ * Max ms the initial TCP connect for a unit may take before it is abandoned. Enforced by the
69
+ * client independently of the transport-level `timeout` it also forwards. Default 5000.
70
+ */
71
+ connectTimeoutMs?: number;
72
+ /**
73
+ * Max ms a `disconnect()` may take before it is abandoned. A half-open socket can hang even on
74
+ * close, which would otherwise re-wedge the connection lock. Default 5000.
75
+ */
76
+ disconnectTimeoutMs?: number;
77
+ /**
78
+ * If a unit has completed at least one successful transaction but none within this window, its
79
+ * socket is treated as stale (presumed half-open) even when the transport still reports it
80
+ * connected — so `isHealthy()` flips false and the device's reconnect path recycles it before
81
+ * the coarse 5-minute health staleness would. Default 30000 (~3 poll cycles at a 10s poll).
82
+ * Set 0 to disable staleness detection.
83
+ */
84
+ staleSocketMs?: number;
85
+ /**
86
+ * Number of extra attempts to retry the initial per-unit TCP connect after the first one fails,
87
+ * before giving up and throwing. A transient gateway hiccup at (re)connect time — e.g. a
88
+ * SolarEdge gateway still waking up in the seconds right after an app restart — would otherwise
89
+ * fail the whole unit for a full reconnect cycle and cascade into a long telemetry gap. Each
90
+ * attempt is independently bounded by {@link connectTimeoutMs}. Default 1 (2 attempts total).
91
+ * Set 0 to preserve the old fail-fast behaviour.
92
+ */
93
+ connectRetries?: number;
94
+ /**
95
+ * Fixed backoff between consecutive connect attempts, in ms. Only applies when
96
+ * {@link connectRetries} > 0. Default 500.
97
+ */
98
+ connectRetryDelayMs?: number;
99
+ }
100
+ export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
40
101
  /**
41
102
  * Base interface for all SunSpec blocks
42
103
  */
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SunspecModbusClient = void 0;
3
+ exports.SunspecModbusClient = exports.ModbusOperationTimeoutError = void 0;
4
4
  exports.getOrCreateSunspecClient = getOrCreateSunspecClient;
5
5
  exports.releaseSunspecClient = releaseSunspecClient;
6
+ exports.retryAsync = retryAsync;
6
7
  /**
7
8
  * Sunspec Modbus Client Implementation
8
9
  *
@@ -25,6 +26,23 @@ const sunspec_interfaces_js_1 = require("./sunspec-interfaces.cjs");
25
26
  const EnergyAppModbusConnectionHealth_js_1 = require("@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusConnectionHealth.js");
26
27
  const EnergyAppModbusFaultTolerantReader_js_1 = require("@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusFaultTolerantReader.js");
27
28
  const EnergyAppModbusDataTypeConverter_js_1 = require("@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusDataTypeConverter.js");
29
+ /**
30
+ * Thrown when a single Modbus transaction (read/write/connect/disconnect) exceeds its configured
31
+ * time budget. Surfaced instead of letting a half-open socket leave the operation pending forever.
32
+ */
33
+ class ModbusOperationTimeoutError extends Error {
34
+ operation;
35
+ unitId;
36
+ timeoutMs;
37
+ constructor(operation, unitId, timeoutMs) {
38
+ super(`Modbus ${operation} on unit ${unitId} timed out after ${timeoutMs}ms`);
39
+ this.operation = operation;
40
+ this.unitId = unitId;
41
+ this.timeoutMs = timeoutMs;
42
+ this.name = 'ModbusOperationTimeoutError';
43
+ }
44
+ }
45
+ exports.ModbusOperationTimeoutError = ModbusOperationTimeoutError;
28
46
  /**
29
47
  * Module-level registry: one SunspecModbusClient per network device (host:port).
30
48
  * Refcounted so the underlying connection only tears down when the last consumer releases.
@@ -35,15 +53,15 @@ const registryKey = (host, port) => `${host}:${port}`;
35
53
  * Get (or create) the singleton SunspecModbusClient for this network device.
36
54
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
37
55
  *
38
- * NOTE: `pacing` is only applied when the client is FIRST created for a given host:port.
39
- * Because the client is cached and refcounted, a later caller passing a different `pacing`
56
+ * NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
57
+ * host:port. Because the client is cached and refcounted, a later caller passing different config
40
58
  * receives the already-created instance and its config is ignored.
41
59
  */
42
- function getOrCreateSunspecClient(energyApp, host, port = 502, pacing) {
60
+ function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience) {
43
61
  const key = registryKey(host, port);
44
62
  let entry = CLIENT_REGISTRY.get(key);
45
63
  if (!entry) {
46
- entry = { client: new SunspecModbusClient(energyApp, pacing), refcount: 0 };
64
+ entry = { client: new SunspecModbusClient(energyApp, pacing, resilience), refcount: 0 };
47
65
  CLIENT_REGISTRY.set(key, entry);
48
66
  }
49
67
  entry.refcount++;
@@ -81,6 +99,31 @@ async function releaseSunspecClient(host, port = 502) {
81
99
  }
82
100
  }
83
101
  }
102
+ /**
103
+ * Retry an async operation a bounded number of times with a fixed backoff between attempts,
104
+ * rethrowing the last error if every attempt fails. Used to make the initial per-unit connect
105
+ * resilient to a transient gateway hiccup at (re)connect time — the failure mode where a single
106
+ * connect timeout at launch would otherwise cascade into a long outage for the whole device.
107
+ * `sleep` is injectable so tests don't incur real delay; `onRetry` reports each retried failure.
108
+ */
109
+ async function retryAsync(fn, opts) {
110
+ const attempts = Math.max(1, opts.attempts);
111
+ const sleep = opts.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
112
+ let lastError;
113
+ for (let attempt = 1; attempt <= attempts; attempt++) {
114
+ try {
115
+ return await fn(attempt);
116
+ }
117
+ catch (error) {
118
+ lastError = error;
119
+ if (attempt < attempts) {
120
+ opts.onRetry?.(error, attempt);
121
+ await sleep(opts.delayMs);
122
+ }
123
+ }
124
+ }
125
+ throw lastError;
126
+ }
84
127
  class SunspecModbusClient {
85
128
  energyApp;
86
129
  pacing;
@@ -116,15 +159,30 @@ class SunspecModbusClient {
116
159
  // operationChain (the connection lock) to avoid re-entrancy: a transaction never waits
117
160
  // on a connect/disconnect, and vice versa.
118
161
  txChains = new Map();
162
+ // Effective resilience config (per-op timeouts + staleness window), merged with defaults.
163
+ resilience;
164
+ // Units whose last transaction timed out. A timed-out Promise.race abandons the in-flight
165
+ // request but cannot cancel it — the response may still land later and desync the next
166
+ // transaction's framing. So a poisoned unit refuses further I/O until reconnectUnit() tears
167
+ // the socket down and reopens it (which clears the flag).
168
+ poisonedUnits = new Set();
169
+ // Wall-clock of each unit's last SUCCESSFUL transaction. Drives half-open detection: a socket
170
+ // the transport still reports connected but that has gone quiet past staleSocketMs is presumed
171
+ // dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
172
+ lastOkAtByUnit = new Map();
119
173
  constructor(energyApp,
120
174
  // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
121
175
  // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
122
176
  // connection. An empty object leaves both undefined so the SDK applies its own defaults.
123
- pacing = {}) {
177
+ pacing = {},
178
+ // Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
179
+ // so omitted fields keep their defaults.
180
+ resilience = {}) {
124
181
  this.energyApp = energyApp;
125
182
  this.pacing = pacing;
126
183
  this.connectionHealth = new EnergyAppModbusConnectionHealth_js_1.EnergyAppModbusConnectionHealth();
127
184
  this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter_js_1.EnergyAppModbusDataTypeConverter();
185
+ this.resilience = { ...sunspec_interfaces_js_1.DEFAULT_MODBUS_RESILIENCE_CONFIG, ...resilience };
128
186
  }
129
187
  /**
130
188
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
@@ -143,42 +201,7 @@ class SunspecModbusClient {
143
201
  */
144
202
  async connect(host, port = 502, unitId = 1, secondaryHost, useTls, tls) {
145
203
  return this.withConnectionLock(async () => {
146
- if (this.connectionParams) {
147
- if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
148
- throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
149
- `cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
150
- }
151
- if (secondaryHost && !this.connectionParams.secondaryHost) {
152
- this.connectionParams.secondaryHost = secondaryHost;
153
- }
154
- if (useTls !== undefined) {
155
- this.connectionParams.useTls = useTls;
156
- }
157
- if (tls?.cert !== undefined) {
158
- this.connectionParams.cert = tls.cert;
159
- }
160
- if (tls?.key !== undefined) {
161
- this.connectionParams.key = tls.key;
162
- }
163
- if (tls?.ca !== undefined) {
164
- this.connectionParams.ca = tls.ca;
165
- }
166
- if (tls?.rejectUnauthorized !== undefined) {
167
- this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
168
- }
169
- }
170
- else {
171
- this.connectionParams = {
172
- primaryHost: host,
173
- secondaryHost,
174
- port,
175
- useTls,
176
- cert: tls?.cert,
177
- key: tls?.key,
178
- ca: tls?.ca,
179
- rejectUnauthorized: tls?.rejectUnauthorized,
180
- };
181
- }
204
+ this.reconcileConnectionParams(host, port, secondaryHost, useTls, tls);
182
205
  this.knownUnits.add(unitId);
183
206
  if (this.modbusInstances.has(unitId)) {
184
207
  console.debug(`connect(): unit ${unitId} on ${host}:${port} already open, skipping`);
@@ -188,6 +211,74 @@ class SunspecModbusClient {
188
211
  console.log(`Connected to Sunspec device at ${host}:${port} unit ${unitId} (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
189
212
  });
190
213
  }
214
+ /**
215
+ * Fast-fail probe of a unit for speculative RS485-chain scans, where most candidate unit IDs
216
+ * are absent. On success the unit is opened and kept exactly as {@link connect} would; the
217
+ * difference is the FAILURE path: a probe does NOT retry the connect (unlike connect(), which
218
+ * honours {@link IModbusResilienceConfig.connectRetries}) and uses a caller-supplied, typically
219
+ * shorter, connect timeout. So scanning a range of mostly-dead units costs ~`timeoutMs` each
220
+ * instead of the full retrying connect budget — the reason a warm reconnect must never queue
221
+ * its meter/battery attach behind such a scan. Throws on failure; nothing is left open.
222
+ */
223
+ async probeUnit(host, port = 502, unitId = 1, opts = {}) {
224
+ return this.withConnectionLock(async () => {
225
+ this.reconcileConnectionParams(host, port, opts.secondaryHost);
226
+ this.knownUnits.add(unitId);
227
+ if (this.modbusInstances.has(unitId)) {
228
+ console.debug(`probeUnit(): unit ${unitId} on ${host}:${port} already open, skipping`);
229
+ return;
230
+ }
231
+ await this._openUnit(host, port, unitId, {
232
+ connectRetries: 0,
233
+ connectTimeoutMs: opts.timeoutMs ?? this.resilience.connectTimeoutMs,
234
+ });
235
+ console.log(`Probed Sunspec unit ${unitId} at ${host}:${port} — open (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
236
+ });
237
+ }
238
+ /**
239
+ * Reconcile/lock in this client's connection parameters. The first call binds the client to a
240
+ * single (host, port); later calls for a different endpoint throw (use one client per endpoint
241
+ * via {@link getOrCreateSunspecClient}). Optional secondaryHost/TLS material fills in on first
242
+ * sight without clobbering. Caller must hold the connection lock.
243
+ */
244
+ reconcileConnectionParams(host, port, secondaryHost, useTls, tls) {
245
+ if (this.connectionParams) {
246
+ if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
247
+ throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
248
+ `cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
249
+ }
250
+ if (secondaryHost && !this.connectionParams.secondaryHost) {
251
+ this.connectionParams.secondaryHost = secondaryHost;
252
+ }
253
+ if (useTls !== undefined) {
254
+ this.connectionParams.useTls = useTls;
255
+ }
256
+ if (tls?.cert !== undefined) {
257
+ this.connectionParams.cert = tls.cert;
258
+ }
259
+ if (tls?.key !== undefined) {
260
+ this.connectionParams.key = tls.key;
261
+ }
262
+ if (tls?.ca !== undefined) {
263
+ this.connectionParams.ca = tls.ca;
264
+ }
265
+ if (tls?.rejectUnauthorized !== undefined) {
266
+ this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
267
+ }
268
+ }
269
+ else {
270
+ this.connectionParams = {
271
+ primaryHost: host,
272
+ secondaryHost,
273
+ port,
274
+ useTls,
275
+ cert: tls?.cert,
276
+ key: tls?.key,
277
+ ca: tls?.ca,
278
+ rejectUnauthorized: tls?.rejectUnauthorized,
279
+ };
280
+ }
281
+ }
191
282
  /**
192
283
  * Disconnect from all units of this network device.
193
284
  *
@@ -312,18 +403,42 @@ class SunspecModbusClient {
312
403
  }
313
404
  }
314
405
  /**
315
- * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader.
316
- * On any failure, the just-opened instance (if any) is closed so we never leak. Caller must
317
- * hold the connection lock and ensure the unit is not already open.
406
+ * Open a unit, retrying the connect on a transient failure per the resilience config
407
+ * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
408
+ * — which independently bounds its connect at {@link IModbusResilienceConfig.connectTimeoutMs}
409
+ * and tears down any half-open candidate before rethrowing — so retries never leak a socket.
410
+ *
411
+ * `override` lets a caller tune this single open: {@link probeUnit} passes `connectRetries: 0`
412
+ * and a shorter `connectTimeoutMs` to fast-fail a speculative scan; omitted fields fall back to
413
+ * the client's resilience config.
414
+ */
415
+ async _openUnit(host, port, unitId, override) {
416
+ const connectTimeoutMs = override?.connectTimeoutMs ?? this.resilience.connectTimeoutMs;
417
+ const attempts = (override?.connectRetries ?? this.resilience.connectRetries) + 1;
418
+ await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs), {
419
+ attempts,
420
+ delayMs: this.resilience.connectRetryDelayMs,
421
+ onRetry: (error, attempt) => console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} failed ` +
422
+ `(attempt ${attempt}/${attempts}): ${error instanceof Error ? error.message : String(error)}; ` +
423
+ `retrying in ${this.resilience.connectRetryDelayMs}ms`),
424
+ });
425
+ }
426
+ /**
427
+ * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
428
+ * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
429
+ * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
318
430
  */
319
- async _openUnit(host, port, unitId) {
431
+ async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
320
432
  let candidate = null;
321
433
  try {
322
- candidate = await this.energyApp.useModbus().connect({
434
+ // Enforce the connect budget ourselves in addition to forwarding it as the transport's
435
+ // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
436
+ // can still leave the returned promise pending — bound it independently.
437
+ candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
323
438
  host,
324
439
  port,
325
440
  unitId,
326
- timeout: 5000,
441
+ timeout: connectTimeoutMs,
327
442
  useTls: this.connectionParams?.useTls,
328
443
  cert: this.connectionParams?.cert,
329
444
  key: this.connectionParams?.key,
@@ -331,22 +446,23 @@ class SunspecModbusClient {
331
446
  rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
332
447
  noParallelRequests: this.pacing.noParallelRequests,
333
448
  waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
334
- });
449
+ }));
335
450
  if (!candidate) {
336
451
  throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
337
452
  }
338
453
  const reader = new EnergyAppModbusFaultTolerantReader_js_1.EnergyAppModbusFaultTolerantReader(candidate, this.connectionHealth);
339
454
  this.modbusInstances.set(unitId, candidate);
340
455
  this.faultTolerantReaders.set(unitId, reader);
456
+ // Fresh socket: clear any prior poison and start the freshness clock so a just-opened
457
+ // unit isn't immediately judged stale.
458
+ this.poisonedUnits.delete(unitId);
459
+ this.lastOkAtByUnit.set(unitId, Date.now());
341
460
  this.connectionHealth.recordSuccess();
342
461
  this.recordOpen();
343
462
  }
344
463
  catch (err) {
345
464
  if (candidate) {
346
- try {
347
- await candidate.disconnect();
348
- }
349
- catch { /* ignore */ }
465
+ await this.disconnectInstanceBounded(candidate, unitId);
350
466
  }
351
467
  this.modbusInstances.delete(unitId);
352
468
  this.faultTolerantReaders.delete(unitId);
@@ -364,15 +480,31 @@ class SunspecModbusClient {
364
480
  this.faultTolerantReaders.delete(unitId);
365
481
  this.discoveredModelsByUnit.delete(unitId);
366
482
  this.discoveredModelListByUnit.delete(unitId);
483
+ // Drop per-unit resilience state so a later reopen starts clean.
484
+ this.poisonedUnits.delete(unitId);
485
+ this.lastOkAtByUnit.delete(unitId);
367
486
  if (instance) {
368
- try {
369
- await instance.disconnect();
370
- }
371
- catch { /* ignore */ }
487
+ await this.disconnectInstanceBounded(instance, unitId);
372
488
  }
373
489
  if (wasOpen)
374
490
  this.recordClose();
375
491
  }
492
+ /**
493
+ * Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
494
+ * left unbounded that would wedge the connection lock and stall every later connect/disconnect.
495
+ * Swallows all errors (including the timeout) — a close that can't complete is abandoned.
496
+ */
497
+ async disconnectInstanceBounded(instance, unitId) {
498
+ try {
499
+ await this.withTimeout('disconnect', unitId, this.resilience.disconnectTimeoutMs, () => instance.disconnect());
500
+ }
501
+ catch (err) {
502
+ if (err instanceof ModbusOperationTimeoutError) {
503
+ console.warn(`SunspecModbusClient: disconnect of unit ${unitId} timed out after ${this.resilience.disconnectTimeoutMs}ms — abandoning socket`);
504
+ }
505
+ /* ignore: best-effort close */
506
+ }
507
+ }
376
508
  /**
377
509
  * Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
378
510
  * behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
@@ -394,10 +526,74 @@ class SunspecModbusClient {
394
526
  */
395
527
  runExclusive(unitId, fn) {
396
528
  const prev = this.txChains.get(unitId) ?? Promise.resolve();
397
- const run = prev.then(fn, fn);
529
+ const guarded = () => this.guardTransaction(unitId, fn);
530
+ const run = prev.then(guarded, guarded);
398
531
  this.txChains.set(unitId, run.catch(() => undefined));
399
532
  return run;
400
533
  }
534
+ /**
535
+ * Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
536
+ * On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
537
+ * transaction reuses the hung socket before the reconnect path recycles it. A unit already
538
+ * poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
539
+ * and desync the next transaction's framing.
540
+ */
541
+ async guardTransaction(unitId, fn) {
542
+ if (this.poisonedUnits.has(unitId)) {
543
+ throw new Error(`Modbus unit ${unitId} socket is poisoned (awaiting reconnect) — transaction refused`);
544
+ }
545
+ try {
546
+ const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, fn);
547
+ this.lastOkAtByUnit.set(unitId, Date.now());
548
+ return result;
549
+ }
550
+ catch (error) {
551
+ if (error instanceof ModbusOperationTimeoutError) {
552
+ this.poisonUnit(unitId, error);
553
+ }
554
+ throw error;
555
+ }
556
+ }
557
+ /**
558
+ * Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
559
+ * the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
560
+ * timer is always cleared so a fast `fn` doesn't keep the event loop alive.
561
+ */
562
+ withTimeout(operation, unitId, timeoutMs, fn) {
563
+ let timer;
564
+ const timeout = new Promise((_, reject) => {
565
+ timer = setTimeout(() => reject(new ModbusOperationTimeoutError(operation, unitId, timeoutMs)), timeoutMs);
566
+ });
567
+ return Promise.race([fn(), timeout]).finally(() => {
568
+ if (timer !== undefined)
569
+ clearTimeout(timer);
570
+ });
571
+ }
572
+ /**
573
+ * Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
574
+ * gate immediately, so isHealthy() flips false this cycle instead of after the coarse
575
+ * 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
576
+ */
577
+ poisonUnit(unitId, error) {
578
+ if (!this.poisonedUnits.has(unitId)) {
579
+ console.warn(`SunspecModbusClient: ${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
580
+ }
581
+ this.poisonedUnits.add(unitId);
582
+ this.connectionHealth.recordFailure(error);
583
+ }
584
+ /**
585
+ * A unit's socket is stale when the transport still reports it connected but no successful
586
+ * transaction has completed within staleSocketMs — the signature of a half-open link where
587
+ * the peer silently stopped answering. Units with no successful op yet are never stale.
588
+ */
589
+ isStale(unitId) {
590
+ if (this.resilience.staleSocketMs <= 0)
591
+ return false;
592
+ const last = this.lastOkAtByUnit.get(unitId);
593
+ if (last === undefined)
594
+ return false;
595
+ return Date.now() - last > this.resilience.staleSocketMs;
596
+ }
401
597
  recordOpen() {
402
598
  this.openCount++;
403
599
  const expected = this.modbusInstances.size;
@@ -2235,10 +2431,19 @@ class SunspecModbusClient {
2235
2431
  return this.modbusInstances.has(unitId);
2236
2432
  }
2237
2433
  /**
2238
- * Check if a specific unit's connection is healthy
2434
+ * Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
2435
+ * unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
2436
+ * (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
2437
+ * recycles the socket rather than trusting a hung link.
2239
2438
  */
2240
2439
  isHealthy(unitId) {
2241
- return this.modbusInstances.has(unitId) && this.connectionHealth.isHealthy();
2440
+ if (!this.modbusInstances.has(unitId))
2441
+ return false;
2442
+ if (this.poisonedUnits.has(unitId))
2443
+ return false;
2444
+ if (this.isStale(unitId))
2445
+ return false;
2446
+ return this.connectionHealth.isHealthy();
2242
2447
  }
2243
2448
  /**
2244
2449
  * Get connection health details (shared across all units on this network device)