@enyo-energy/sunspec-sdk 0.0.99 → 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.
@@ -20,6 +20,8 @@ exports.DEFAULT_MODBUS_RESILIENCE_CONFIG = {
20
20
  connectTimeoutMs: 5_000,
21
21
  disconnectTimeoutMs: 5_000,
22
22
  staleSocketMs: 30_000,
23
+ connectRetries: 1,
24
+ connectRetryDelayMs: 500,
23
25
  };
24
26
  /**
25
27
  * Common Sunspec Model IDs
@@ -82,6 +82,20 @@ export interface IModbusResilienceConfig {
82
82
  * Set 0 to disable staleness detection.
83
83
  */
84
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;
85
99
  }
86
100
  export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
87
101
  /**
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
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
  *
@@ -98,6 +99,31 @@ async function releaseSunspecClient(host, port = 502) {
98
99
  }
99
100
  }
100
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
+ }
101
127
  class SunspecModbusClient {
102
128
  energyApp;
103
129
  pacing;
@@ -175,42 +201,7 @@ class SunspecModbusClient {
175
201
  */
176
202
  async connect(host, port = 502, unitId = 1, secondaryHost, useTls, tls) {
177
203
  return this.withConnectionLock(async () => {
178
- if (this.connectionParams) {
179
- if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
180
- throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
181
- `cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
182
- }
183
- if (secondaryHost && !this.connectionParams.secondaryHost) {
184
- this.connectionParams.secondaryHost = secondaryHost;
185
- }
186
- if (useTls !== undefined) {
187
- this.connectionParams.useTls = useTls;
188
- }
189
- if (tls?.cert !== undefined) {
190
- this.connectionParams.cert = tls.cert;
191
- }
192
- if (tls?.key !== undefined) {
193
- this.connectionParams.key = tls.key;
194
- }
195
- if (tls?.ca !== undefined) {
196
- this.connectionParams.ca = tls.ca;
197
- }
198
- if (tls?.rejectUnauthorized !== undefined) {
199
- this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
200
- }
201
- }
202
- else {
203
- this.connectionParams = {
204
- primaryHost: host,
205
- secondaryHost,
206
- port,
207
- useTls,
208
- cert: tls?.cert,
209
- key: tls?.key,
210
- ca: tls?.ca,
211
- rejectUnauthorized: tls?.rejectUnauthorized,
212
- };
213
- }
204
+ this.reconcileConnectionParams(host, port, secondaryHost, useTls, tls);
214
205
  this.knownUnits.add(unitId);
215
206
  if (this.modbusInstances.has(unitId)) {
216
207
  console.debug(`connect(): unit ${unitId} on ${host}:${port} already open, skipping`);
@@ -220,6 +211,74 @@ class SunspecModbusClient {
220
211
  console.log(`Connected to Sunspec device at ${host}:${port} unit ${unitId} (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
221
212
  });
222
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
+ }
223
282
  /**
224
283
  * Disconnect from all units of this network device.
225
284
  *
@@ -344,21 +403,42 @@ class SunspecModbusClient {
344
403
  }
345
404
  }
346
405
  /**
347
- * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader.
348
- * On any failure, the just-opened instance (if any) is closed so we never leak. Caller must
349
- * 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.
350
430
  */
351
- async _openUnit(host, port, unitId) {
431
+ async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
352
432
  let candidate = null;
353
433
  try {
354
434
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
355
435
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
356
436
  // can still leave the returned promise pending — bound it independently.
357
- candidate = await this.withTimeout('connect', unitId, this.resilience.connectTimeoutMs, () => this.energyApp.useModbus().connect({
437
+ candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
358
438
  host,
359
439
  port,
360
440
  unitId,
361
- timeout: this.resilience.connectTimeoutMs,
441
+ timeout: connectTimeoutMs,
362
442
  useTls: this.connectionParams?.useTls,
363
443
  cert: this.connectionParams?.cert,
364
444
  key: this.connectionParams?.key,
@@ -47,6 +47,19 @@ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: str
47
47
  * is clamped at zero so repeat releases are no-ops.
48
48
  */
49
49
  export declare function releaseSunspecClient(host: string, port?: number): Promise<void>;
50
+ /**
51
+ * Retry an async operation a bounded number of times with a fixed backoff between attempts,
52
+ * rethrowing the last error if every attempt fails. Used to make the initial per-unit connect
53
+ * resilient to a transient gateway hiccup at (re)connect time — the failure mode where a single
54
+ * connect timeout at launch would otherwise cascade into a long outage for the whole device.
55
+ * `sleep` is injectable so tests don't incur real delay; `onRetry` reports each retried failure.
56
+ */
57
+ export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts: {
58
+ attempts: number;
59
+ delayMs: number;
60
+ sleep?: (ms: number) => Promise<void>;
61
+ onRetry?: (error: unknown, attempt: number) => void;
62
+ }): Promise<T>;
50
63
  export declare class SunspecModbusClient {
51
64
  private energyApp;
52
65
  private pacing;
@@ -88,6 +101,26 @@ export declare class SunspecModbusClient {
88
101
  ca?: string | Buffer | Array<string | Buffer>;
89
102
  rejectUnauthorized?: boolean;
90
103
  }): Promise<void>;
104
+ /**
105
+ * Fast-fail probe of a unit for speculative RS485-chain scans, where most candidate unit IDs
106
+ * are absent. On success the unit is opened and kept exactly as {@link connect} would; the
107
+ * difference is the FAILURE path: a probe does NOT retry the connect (unlike connect(), which
108
+ * honours {@link IModbusResilienceConfig.connectRetries}) and uses a caller-supplied, typically
109
+ * shorter, connect timeout. So scanning a range of mostly-dead units costs ~`timeoutMs` each
110
+ * instead of the full retrying connect budget — the reason a warm reconnect must never queue
111
+ * its meter/battery attach behind such a scan. Throws on failure; nothing is left open.
112
+ */
113
+ probeUnit(host: string, port?: number, unitId?: number, opts?: {
114
+ secondaryHost?: string;
115
+ timeoutMs?: number;
116
+ }): Promise<void>;
117
+ /**
118
+ * Reconcile/lock in this client's connection parameters. The first call binds the client to a
119
+ * single (host, port); later calls for a different endpoint throw (use one client per endpoint
120
+ * via {@link getOrCreateSunspecClient}). Optional secondaryHost/TLS material fills in on first
121
+ * sight without clobbering. Caller must hold the connection lock.
122
+ */
123
+ private reconcileConnectionParams;
91
124
  /**
92
125
  * Disconnect from all units of this network device.
93
126
  *
@@ -120,11 +153,22 @@ export declare class SunspecModbusClient {
120
153
  */
121
154
  private attemptConnection;
122
155
  /**
123
- * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader.
124
- * On any failure, the just-opened instance (if any) is closed so we never leak. Caller must
125
- * hold the connection lock and ensure the unit is not already open.
156
+ * Open a unit, retrying the connect on a transient failure per the resilience config
157
+ * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
158
+ * — which independently bounds its connect at {@link IModbusResilienceConfig.connectTimeoutMs}
159
+ * and tears down any half-open candidate before rethrowing — so retries never leak a socket.
160
+ *
161
+ * `override` lets a caller tune this single open: {@link probeUnit} passes `connectRetries: 0`
162
+ * and a shorter `connectTimeoutMs` to fast-fail a speculative scan; omitted fields fall back to
163
+ * the client's resilience config.
126
164
  */
127
165
  private _openUnit;
166
+ /**
167
+ * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
168
+ * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
169
+ * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
170
+ */
171
+ private _openUnitOnce;
128
172
  /**
129
173
  * Close the Modbus instance for a single unit. Idempotent. Caller must hold the
130
174
  * connection lock.
@@ -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.99';
12
+ exports.SDK_VERSION = '0.0.100';
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.99";
8
+ export declare const SDK_VERSION = "0.0.100";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
@@ -82,6 +82,20 @@ export interface IModbusResilienceConfig {
82
82
  * Set 0 to disable staleness detection.
83
83
  */
84
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;
85
99
  }
86
100
  export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
87
101
  /**
@@ -17,6 +17,8 @@ export const DEFAULT_MODBUS_RESILIENCE_CONFIG = {
17
17
  connectTimeoutMs: 5_000,
18
18
  disconnectTimeoutMs: 5_000,
19
19
  staleSocketMs: 30_000,
20
+ connectRetries: 1,
21
+ connectRetryDelayMs: 500,
20
22
  };
21
23
  /**
22
24
  * Common Sunspec Model IDs
@@ -47,6 +47,19 @@ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: str
47
47
  * is clamped at zero so repeat releases are no-ops.
48
48
  */
49
49
  export declare function releaseSunspecClient(host: string, port?: number): Promise<void>;
50
+ /**
51
+ * Retry an async operation a bounded number of times with a fixed backoff between attempts,
52
+ * rethrowing the last error if every attempt fails. Used to make the initial per-unit connect
53
+ * resilient to a transient gateway hiccup at (re)connect time — the failure mode where a single
54
+ * connect timeout at launch would otherwise cascade into a long outage for the whole device.
55
+ * `sleep` is injectable so tests don't incur real delay; `onRetry` reports each retried failure.
56
+ */
57
+ export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts: {
58
+ attempts: number;
59
+ delayMs: number;
60
+ sleep?: (ms: number) => Promise<void>;
61
+ onRetry?: (error: unknown, attempt: number) => void;
62
+ }): Promise<T>;
50
63
  export declare class SunspecModbusClient {
51
64
  private energyApp;
52
65
  private pacing;
@@ -88,6 +101,26 @@ export declare class SunspecModbusClient {
88
101
  ca?: string | Buffer | Array<string | Buffer>;
89
102
  rejectUnauthorized?: boolean;
90
103
  }): Promise<void>;
104
+ /**
105
+ * Fast-fail probe of a unit for speculative RS485-chain scans, where most candidate unit IDs
106
+ * are absent. On success the unit is opened and kept exactly as {@link connect} would; the
107
+ * difference is the FAILURE path: a probe does NOT retry the connect (unlike connect(), which
108
+ * honours {@link IModbusResilienceConfig.connectRetries}) and uses a caller-supplied, typically
109
+ * shorter, connect timeout. So scanning a range of mostly-dead units costs ~`timeoutMs` each
110
+ * instead of the full retrying connect budget — the reason a warm reconnect must never queue
111
+ * its meter/battery attach behind such a scan. Throws on failure; nothing is left open.
112
+ */
113
+ probeUnit(host: string, port?: number, unitId?: number, opts?: {
114
+ secondaryHost?: string;
115
+ timeoutMs?: number;
116
+ }): Promise<void>;
117
+ /**
118
+ * Reconcile/lock in this client's connection parameters. The first call binds the client to a
119
+ * single (host, port); later calls for a different endpoint throw (use one client per endpoint
120
+ * via {@link getOrCreateSunspecClient}). Optional secondaryHost/TLS material fills in on first
121
+ * sight without clobbering. Caller must hold the connection lock.
122
+ */
123
+ private reconcileConnectionParams;
91
124
  /**
92
125
  * Disconnect from all units of this network device.
93
126
  *
@@ -120,11 +153,22 @@ export declare class SunspecModbusClient {
120
153
  */
121
154
  private attemptConnection;
122
155
  /**
123
- * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader.
124
- * On any failure, the just-opened instance (if any) is closed so we never leak. Caller must
125
- * hold the connection lock and ensure the unit is not already open.
156
+ * Open a unit, retrying the connect on a transient failure per the resilience config
157
+ * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
158
+ * — which independently bounds its connect at {@link IModbusResilienceConfig.connectTimeoutMs}
159
+ * and tears down any half-open candidate before rethrowing — so retries never leak a socket.
160
+ *
161
+ * `override` lets a caller tune this single open: {@link probeUnit} passes `connectRetries: 0`
162
+ * and a shorter `connectTimeoutMs` to fast-fail a speculative scan; omitted fields fall back to
163
+ * the client's resilience config.
126
164
  */
127
165
  private _openUnit;
166
+ /**
167
+ * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
168
+ * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
169
+ * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
170
+ */
171
+ private _openUnitOnce;
128
172
  /**
129
173
  * Close the Modbus instance for a single unit. Idempotent. Caller must hold the
130
174
  * connection lock.
@@ -92,6 +92,31 @@ export async function releaseSunspecClient(host, port = 502) {
92
92
  }
93
93
  }
94
94
  }
95
+ /**
96
+ * Retry an async operation a bounded number of times with a fixed backoff between attempts,
97
+ * rethrowing the last error if every attempt fails. Used to make the initial per-unit connect
98
+ * resilient to a transient gateway hiccup at (re)connect time — the failure mode where a single
99
+ * connect timeout at launch would otherwise cascade into a long outage for the whole device.
100
+ * `sleep` is injectable so tests don't incur real delay; `onRetry` reports each retried failure.
101
+ */
102
+ export async function retryAsync(fn, opts) {
103
+ const attempts = Math.max(1, opts.attempts);
104
+ const sleep = opts.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
105
+ let lastError;
106
+ for (let attempt = 1; attempt <= attempts; attempt++) {
107
+ try {
108
+ return await fn(attempt);
109
+ }
110
+ catch (error) {
111
+ lastError = error;
112
+ if (attempt < attempts) {
113
+ opts.onRetry?.(error, attempt);
114
+ await sleep(opts.delayMs);
115
+ }
116
+ }
117
+ }
118
+ throw lastError;
119
+ }
95
120
  export class SunspecModbusClient {
96
121
  energyApp;
97
122
  pacing;
@@ -169,42 +194,7 @@ export class SunspecModbusClient {
169
194
  */
170
195
  async connect(host, port = 502, unitId = 1, secondaryHost, useTls, tls) {
171
196
  return this.withConnectionLock(async () => {
172
- if (this.connectionParams) {
173
- if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
174
- throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
175
- `cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
176
- }
177
- if (secondaryHost && !this.connectionParams.secondaryHost) {
178
- this.connectionParams.secondaryHost = secondaryHost;
179
- }
180
- if (useTls !== undefined) {
181
- this.connectionParams.useTls = useTls;
182
- }
183
- if (tls?.cert !== undefined) {
184
- this.connectionParams.cert = tls.cert;
185
- }
186
- if (tls?.key !== undefined) {
187
- this.connectionParams.key = tls.key;
188
- }
189
- if (tls?.ca !== undefined) {
190
- this.connectionParams.ca = tls.ca;
191
- }
192
- if (tls?.rejectUnauthorized !== undefined) {
193
- this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
194
- }
195
- }
196
- else {
197
- this.connectionParams = {
198
- primaryHost: host,
199
- secondaryHost,
200
- port,
201
- useTls,
202
- cert: tls?.cert,
203
- key: tls?.key,
204
- ca: tls?.ca,
205
- rejectUnauthorized: tls?.rejectUnauthorized,
206
- };
207
- }
197
+ this.reconcileConnectionParams(host, port, secondaryHost, useTls, tls);
208
198
  this.knownUnits.add(unitId);
209
199
  if (this.modbusInstances.has(unitId)) {
210
200
  console.debug(`connect(): unit ${unitId} on ${host}:${port} already open, skipping`);
@@ -214,6 +204,74 @@ export class SunspecModbusClient {
214
204
  console.log(`Connected to Sunspec device at ${host}:${port} unit ${unitId} (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
215
205
  });
216
206
  }
207
+ /**
208
+ * Fast-fail probe of a unit for speculative RS485-chain scans, where most candidate unit IDs
209
+ * are absent. On success the unit is opened and kept exactly as {@link connect} would; the
210
+ * difference is the FAILURE path: a probe does NOT retry the connect (unlike connect(), which
211
+ * honours {@link IModbusResilienceConfig.connectRetries}) and uses a caller-supplied, typically
212
+ * shorter, connect timeout. So scanning a range of mostly-dead units costs ~`timeoutMs` each
213
+ * instead of the full retrying connect budget — the reason a warm reconnect must never queue
214
+ * its meter/battery attach behind such a scan. Throws on failure; nothing is left open.
215
+ */
216
+ async probeUnit(host, port = 502, unitId = 1, opts = {}) {
217
+ return this.withConnectionLock(async () => {
218
+ this.reconcileConnectionParams(host, port, opts.secondaryHost);
219
+ this.knownUnits.add(unitId);
220
+ if (this.modbusInstances.has(unitId)) {
221
+ console.debug(`probeUnit(): unit ${unitId} on ${host}:${port} already open, skipping`);
222
+ return;
223
+ }
224
+ await this._openUnit(host, port, unitId, {
225
+ connectRetries: 0,
226
+ connectTimeoutMs: opts.timeoutMs ?? this.resilience.connectTimeoutMs,
227
+ });
228
+ console.log(`Probed Sunspec unit ${unitId} at ${host}:${port} — open (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
229
+ });
230
+ }
231
+ /**
232
+ * Reconcile/lock in this client's connection parameters. The first call binds the client to a
233
+ * single (host, port); later calls for a different endpoint throw (use one client per endpoint
234
+ * via {@link getOrCreateSunspecClient}). Optional secondaryHost/TLS material fills in on first
235
+ * sight without clobbering. Caller must hold the connection lock.
236
+ */
237
+ reconcileConnectionParams(host, port, secondaryHost, useTls, tls) {
238
+ if (this.connectionParams) {
239
+ if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
240
+ throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
241
+ `cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
242
+ }
243
+ if (secondaryHost && !this.connectionParams.secondaryHost) {
244
+ this.connectionParams.secondaryHost = secondaryHost;
245
+ }
246
+ if (useTls !== undefined) {
247
+ this.connectionParams.useTls = useTls;
248
+ }
249
+ if (tls?.cert !== undefined) {
250
+ this.connectionParams.cert = tls.cert;
251
+ }
252
+ if (tls?.key !== undefined) {
253
+ this.connectionParams.key = tls.key;
254
+ }
255
+ if (tls?.ca !== undefined) {
256
+ this.connectionParams.ca = tls.ca;
257
+ }
258
+ if (tls?.rejectUnauthorized !== undefined) {
259
+ this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
260
+ }
261
+ }
262
+ else {
263
+ this.connectionParams = {
264
+ primaryHost: host,
265
+ secondaryHost,
266
+ port,
267
+ useTls,
268
+ cert: tls?.cert,
269
+ key: tls?.key,
270
+ ca: tls?.ca,
271
+ rejectUnauthorized: tls?.rejectUnauthorized,
272
+ };
273
+ }
274
+ }
217
275
  /**
218
276
  * Disconnect from all units of this network device.
219
277
  *
@@ -338,21 +396,42 @@ export class SunspecModbusClient {
338
396
  }
339
397
  }
340
398
  /**
341
- * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader.
342
- * On any failure, the just-opened instance (if any) is closed so we never leak. Caller must
343
- * hold the connection lock and ensure the unit is not already open.
399
+ * Open a unit, retrying the connect on a transient failure per the resilience config
400
+ * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
401
+ * — which independently bounds its connect at {@link IModbusResilienceConfig.connectTimeoutMs}
402
+ * and tears down any half-open candidate before rethrowing — so retries never leak a socket.
403
+ *
404
+ * `override` lets a caller tune this single open: {@link probeUnit} passes `connectRetries: 0`
405
+ * and a shorter `connectTimeoutMs` to fast-fail a speculative scan; omitted fields fall back to
406
+ * the client's resilience config.
407
+ */
408
+ async _openUnit(host, port, unitId, override) {
409
+ const connectTimeoutMs = override?.connectTimeoutMs ?? this.resilience.connectTimeoutMs;
410
+ const attempts = (override?.connectRetries ?? this.resilience.connectRetries) + 1;
411
+ await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs), {
412
+ attempts,
413
+ delayMs: this.resilience.connectRetryDelayMs,
414
+ onRetry: (error, attempt) => console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} failed ` +
415
+ `(attempt ${attempt}/${attempts}): ${error instanceof Error ? error.message : String(error)}; ` +
416
+ `retrying in ${this.resilience.connectRetryDelayMs}ms`),
417
+ });
418
+ }
419
+ /**
420
+ * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
421
+ * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
422
+ * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
344
423
  */
345
- async _openUnit(host, port, unitId) {
424
+ async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
346
425
  let candidate = null;
347
426
  try {
348
427
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
349
428
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
350
429
  // can still leave the returned promise pending — bound it independently.
351
- candidate = await this.withTimeout('connect', unitId, this.resilience.connectTimeoutMs, () => this.energyApp.useModbus().connect({
430
+ candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
352
431
  host,
353
432
  port,
354
433
  unitId,
355
- timeout: this.resilience.connectTimeoutMs,
434
+ timeout: connectTimeoutMs,
356
435
  useTls: this.connectionParams?.useTls,
357
436
  cert: this.connectionParams?.cert,
358
437
  key: this.connectionParams?.key,
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.99";
8
+ export declare const SDK_VERSION = "0.0.100";
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.99';
8
+ export const SDK_VERSION = '0.0.100';
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.99",
3
+ "version": "0.0.100",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",