@enyo-energy/sunspec-sdk 0.0.99 → 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.
@@ -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,
@@ -495,6 +574,25 @@ export class SunspecModbusClient {
495
574
  this.poisonedUnits.add(unitId);
496
575
  this.connectionHealth.recordFailure(error);
497
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
+ }
498
596
  /**
499
597
  * A unit's socket is stale when the transport still reports it connected but no successful
500
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.99";
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.99';
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.99",
3
+ "version": "0.0.101",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",