@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.
- package/dist/cjs/connection-retry-manager.cjs +25 -1
- package/dist/cjs/connection-retry-manager.d.cts +6 -0
- package/dist/cjs/sunspec-interfaces.cjs +11 -2
- package/dist/cjs/sunspec-interfaces.d.cts +61 -0
- package/dist/cjs/sunspec-modbus-client.cjs +265 -60
- package/dist/cjs/sunspec-modbus-client.d.cts +101 -9
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/connection-retry-manager.d.ts +6 -0
- package/dist/connection-retry-manager.js +25 -1
- package/dist/sunspec-interfaces.d.ts +61 -0
- package/dist/sunspec-interfaces.js +10 -1
- package/dist/sunspec-modbus-client.d.ts +101 -9
- package/dist/sunspec-modbus-client.js +263 -60
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -16,10 +16,26 @@
|
|
|
16
16
|
* - pad: 0x8000 (always returns this value)
|
|
17
17
|
* - string: all registers 0x0000 (NULL)
|
|
18
18
|
*/
|
|
19
|
-
import { SunspecModelId, SunspecBatteryChargeState, SunspecStorageControlMode, SunspecChargeSource, SunspecEnableControl, SunspecStorageMode, SunspecBatteryType, SunspecBatteryBankState, } from "./sunspec-interfaces.js";
|
|
19
|
+
import { SunspecModelId, SunspecBatteryChargeState, SunspecStorageControlMode, SunspecChargeSource, SunspecEnableControl, SunspecStorageMode, SunspecBatteryType, SunspecBatteryBankState, DEFAULT_MODBUS_RESILIENCE_CONFIG, } from "./sunspec-interfaces.js";
|
|
20
20
|
import { EnergyAppModbusConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusConnectionHealth.js";
|
|
21
21
|
import { EnergyAppModbusFaultTolerantReader } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusFaultTolerantReader.js";
|
|
22
22
|
import { EnergyAppModbusDataTypeConverter } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusDataTypeConverter.js";
|
|
23
|
+
/**
|
|
24
|
+
* Thrown when a single Modbus transaction (read/write/connect/disconnect) exceeds its configured
|
|
25
|
+
* time budget. Surfaced instead of letting a half-open socket leave the operation pending forever.
|
|
26
|
+
*/
|
|
27
|
+
export class ModbusOperationTimeoutError extends Error {
|
|
28
|
+
operation;
|
|
29
|
+
unitId;
|
|
30
|
+
timeoutMs;
|
|
31
|
+
constructor(operation, unitId, timeoutMs) {
|
|
32
|
+
super(`Modbus ${operation} on unit ${unitId} timed out after ${timeoutMs}ms`);
|
|
33
|
+
this.operation = operation;
|
|
34
|
+
this.unitId = unitId;
|
|
35
|
+
this.timeoutMs = timeoutMs;
|
|
36
|
+
this.name = 'ModbusOperationTimeoutError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
23
39
|
/**
|
|
24
40
|
* Module-level registry: one SunspecModbusClient per network device (host:port).
|
|
25
41
|
* Refcounted so the underlying connection only tears down when the last consumer releases.
|
|
@@ -30,15 +46,15 @@ const registryKey = (host, port) => `${host}:${port}`;
|
|
|
30
46
|
* Get (or create) the singleton SunspecModbusClient for this network device.
|
|
31
47
|
* Increments the refcount; pair with `releaseSunspecClient` on teardown.
|
|
32
48
|
*
|
|
33
|
-
* NOTE: `pacing`
|
|
34
|
-
* Because the client is cached and refcounted, a later caller passing
|
|
49
|
+
* NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
|
|
50
|
+
* host:port. Because the client is cached and refcounted, a later caller passing different config
|
|
35
51
|
* receives the already-created instance and its config is ignored.
|
|
36
52
|
*/
|
|
37
|
-
export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing) {
|
|
53
|
+
export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience) {
|
|
38
54
|
const key = registryKey(host, port);
|
|
39
55
|
let entry = CLIENT_REGISTRY.get(key);
|
|
40
56
|
if (!entry) {
|
|
41
|
-
entry = { client: new SunspecModbusClient(energyApp, pacing), refcount: 0 };
|
|
57
|
+
entry = { client: new SunspecModbusClient(energyApp, pacing, resilience), refcount: 0 };
|
|
42
58
|
CLIENT_REGISTRY.set(key, entry);
|
|
43
59
|
}
|
|
44
60
|
entry.refcount++;
|
|
@@ -76,6 +92,31 @@ export async function releaseSunspecClient(host, port = 502) {
|
|
|
76
92
|
}
|
|
77
93
|
}
|
|
78
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
|
+
}
|
|
79
120
|
export class SunspecModbusClient {
|
|
80
121
|
energyApp;
|
|
81
122
|
pacing;
|
|
@@ -111,15 +152,30 @@ export class SunspecModbusClient {
|
|
|
111
152
|
// operationChain (the connection lock) to avoid re-entrancy: a transaction never waits
|
|
112
153
|
// on a connect/disconnect, and vice versa.
|
|
113
154
|
txChains = new Map();
|
|
155
|
+
// Effective resilience config (per-op timeouts + staleness window), merged with defaults.
|
|
156
|
+
resilience;
|
|
157
|
+
// Units whose last transaction timed out. A timed-out Promise.race abandons the in-flight
|
|
158
|
+
// request but cannot cancel it — the response may still land later and desync the next
|
|
159
|
+
// transaction's framing. So a poisoned unit refuses further I/O until reconnectUnit() tears
|
|
160
|
+
// the socket down and reopens it (which clears the flag).
|
|
161
|
+
poisonedUnits = new Set();
|
|
162
|
+
// Wall-clock of each unit's last SUCCESSFUL transaction. Drives half-open detection: a socket
|
|
163
|
+
// the transport still reports connected but that has gone quiet past staleSocketMs is presumed
|
|
164
|
+
// dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
|
|
165
|
+
lastOkAtByUnit = new Map();
|
|
114
166
|
constructor(energyApp,
|
|
115
167
|
// Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
|
|
116
168
|
// serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
|
|
117
169
|
// connection. An empty object leaves both undefined so the SDK applies its own defaults.
|
|
118
|
-
pacing = {}
|
|
170
|
+
pacing = {},
|
|
171
|
+
// Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
|
|
172
|
+
// so omitted fields keep their defaults.
|
|
173
|
+
resilience = {}) {
|
|
119
174
|
this.energyApp = energyApp;
|
|
120
175
|
this.pacing = pacing;
|
|
121
176
|
this.connectionHealth = new EnergyAppModbusConnectionHealth();
|
|
122
177
|
this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter();
|
|
178
|
+
this.resilience = { ...DEFAULT_MODBUS_RESILIENCE_CONFIG, ...resilience };
|
|
123
179
|
}
|
|
124
180
|
/**
|
|
125
181
|
* Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
|
|
@@ -138,42 +194,7 @@ export class SunspecModbusClient {
|
|
|
138
194
|
*/
|
|
139
195
|
async connect(host, port = 502, unitId = 1, secondaryHost, useTls, tls) {
|
|
140
196
|
return this.withConnectionLock(async () => {
|
|
141
|
-
|
|
142
|
-
if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
|
|
143
|
-
throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
|
|
144
|
-
`cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
|
|
145
|
-
}
|
|
146
|
-
if (secondaryHost && !this.connectionParams.secondaryHost) {
|
|
147
|
-
this.connectionParams.secondaryHost = secondaryHost;
|
|
148
|
-
}
|
|
149
|
-
if (useTls !== undefined) {
|
|
150
|
-
this.connectionParams.useTls = useTls;
|
|
151
|
-
}
|
|
152
|
-
if (tls?.cert !== undefined) {
|
|
153
|
-
this.connectionParams.cert = tls.cert;
|
|
154
|
-
}
|
|
155
|
-
if (tls?.key !== undefined) {
|
|
156
|
-
this.connectionParams.key = tls.key;
|
|
157
|
-
}
|
|
158
|
-
if (tls?.ca !== undefined) {
|
|
159
|
-
this.connectionParams.ca = tls.ca;
|
|
160
|
-
}
|
|
161
|
-
if (tls?.rejectUnauthorized !== undefined) {
|
|
162
|
-
this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
else {
|
|
166
|
-
this.connectionParams = {
|
|
167
|
-
primaryHost: host,
|
|
168
|
-
secondaryHost,
|
|
169
|
-
port,
|
|
170
|
-
useTls,
|
|
171
|
-
cert: tls?.cert,
|
|
172
|
-
key: tls?.key,
|
|
173
|
-
ca: tls?.ca,
|
|
174
|
-
rejectUnauthorized: tls?.rejectUnauthorized,
|
|
175
|
-
};
|
|
176
|
-
}
|
|
197
|
+
this.reconcileConnectionParams(host, port, secondaryHost, useTls, tls);
|
|
177
198
|
this.knownUnits.add(unitId);
|
|
178
199
|
if (this.modbusInstances.has(unitId)) {
|
|
179
200
|
console.debug(`connect(): unit ${unitId} on ${host}:${port} already open, skipping`);
|
|
@@ -183,6 +204,74 @@ export class SunspecModbusClient {
|
|
|
183
204
|
console.log(`Connected to Sunspec device at ${host}:${port} unit ${unitId} (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
|
|
184
205
|
});
|
|
185
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
|
+
}
|
|
186
275
|
/**
|
|
187
276
|
* Disconnect from all units of this network device.
|
|
188
277
|
*
|
|
@@ -307,18 +396,42 @@ export class SunspecModbusClient {
|
|
|
307
396
|
}
|
|
308
397
|
}
|
|
309
398
|
/**
|
|
310
|
-
* Open a
|
|
311
|
-
*
|
|
312
|
-
*
|
|
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.
|
|
313
423
|
*/
|
|
314
|
-
async
|
|
424
|
+
async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
|
|
315
425
|
let candidate = null;
|
|
316
426
|
try {
|
|
317
|
-
|
|
427
|
+
// Enforce the connect budget ourselves in addition to forwarding it as the transport's
|
|
428
|
+
// `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
|
|
429
|
+
// can still leave the returned promise pending — bound it independently.
|
|
430
|
+
candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
|
|
318
431
|
host,
|
|
319
432
|
port,
|
|
320
433
|
unitId,
|
|
321
|
-
timeout:
|
|
434
|
+
timeout: connectTimeoutMs,
|
|
322
435
|
useTls: this.connectionParams?.useTls,
|
|
323
436
|
cert: this.connectionParams?.cert,
|
|
324
437
|
key: this.connectionParams?.key,
|
|
@@ -326,22 +439,23 @@ export class SunspecModbusClient {
|
|
|
326
439
|
rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
|
|
327
440
|
noParallelRequests: this.pacing.noParallelRequests,
|
|
328
441
|
waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
|
|
329
|
-
});
|
|
442
|
+
}));
|
|
330
443
|
if (!candidate) {
|
|
331
444
|
throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
|
|
332
445
|
}
|
|
333
446
|
const reader = new EnergyAppModbusFaultTolerantReader(candidate, this.connectionHealth);
|
|
334
447
|
this.modbusInstances.set(unitId, candidate);
|
|
335
448
|
this.faultTolerantReaders.set(unitId, reader);
|
|
449
|
+
// Fresh socket: clear any prior poison and start the freshness clock so a just-opened
|
|
450
|
+
// unit isn't immediately judged stale.
|
|
451
|
+
this.poisonedUnits.delete(unitId);
|
|
452
|
+
this.lastOkAtByUnit.set(unitId, Date.now());
|
|
336
453
|
this.connectionHealth.recordSuccess();
|
|
337
454
|
this.recordOpen();
|
|
338
455
|
}
|
|
339
456
|
catch (err) {
|
|
340
457
|
if (candidate) {
|
|
341
|
-
|
|
342
|
-
await candidate.disconnect();
|
|
343
|
-
}
|
|
344
|
-
catch { /* ignore */ }
|
|
458
|
+
await this.disconnectInstanceBounded(candidate, unitId);
|
|
345
459
|
}
|
|
346
460
|
this.modbusInstances.delete(unitId);
|
|
347
461
|
this.faultTolerantReaders.delete(unitId);
|
|
@@ -359,15 +473,31 @@ export class SunspecModbusClient {
|
|
|
359
473
|
this.faultTolerantReaders.delete(unitId);
|
|
360
474
|
this.discoveredModelsByUnit.delete(unitId);
|
|
361
475
|
this.discoveredModelListByUnit.delete(unitId);
|
|
476
|
+
// Drop per-unit resilience state so a later reopen starts clean.
|
|
477
|
+
this.poisonedUnits.delete(unitId);
|
|
478
|
+
this.lastOkAtByUnit.delete(unitId);
|
|
362
479
|
if (instance) {
|
|
363
|
-
|
|
364
|
-
await instance.disconnect();
|
|
365
|
-
}
|
|
366
|
-
catch { /* ignore */ }
|
|
480
|
+
await this.disconnectInstanceBounded(instance, unitId);
|
|
367
481
|
}
|
|
368
482
|
if (wasOpen)
|
|
369
483
|
this.recordClose();
|
|
370
484
|
}
|
|
485
|
+
/**
|
|
486
|
+
* Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
|
|
487
|
+
* left unbounded that would wedge the connection lock and stall every later connect/disconnect.
|
|
488
|
+
* Swallows all errors (including the timeout) — a close that can't complete is abandoned.
|
|
489
|
+
*/
|
|
490
|
+
async disconnectInstanceBounded(instance, unitId) {
|
|
491
|
+
try {
|
|
492
|
+
await this.withTimeout('disconnect', unitId, this.resilience.disconnectTimeoutMs, () => instance.disconnect());
|
|
493
|
+
}
|
|
494
|
+
catch (err) {
|
|
495
|
+
if (err instanceof ModbusOperationTimeoutError) {
|
|
496
|
+
console.warn(`SunspecModbusClient: disconnect of unit ${unitId} timed out after ${this.resilience.disconnectTimeoutMs}ms — abandoning socket`);
|
|
497
|
+
}
|
|
498
|
+
/* ignore: best-effort close */
|
|
499
|
+
}
|
|
500
|
+
}
|
|
371
501
|
/**
|
|
372
502
|
* Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
|
|
373
503
|
* behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
|
|
@@ -389,10 +519,74 @@ export class SunspecModbusClient {
|
|
|
389
519
|
*/
|
|
390
520
|
runExclusive(unitId, fn) {
|
|
391
521
|
const prev = this.txChains.get(unitId) ?? Promise.resolve();
|
|
392
|
-
const
|
|
522
|
+
const guarded = () => this.guardTransaction(unitId, fn);
|
|
523
|
+
const run = prev.then(guarded, guarded);
|
|
393
524
|
this.txChains.set(unitId, run.catch(() => undefined));
|
|
394
525
|
return run;
|
|
395
526
|
}
|
|
527
|
+
/**
|
|
528
|
+
* Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
|
|
529
|
+
* On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
|
|
530
|
+
* transaction reuses the hung socket before the reconnect path recycles it. A unit already
|
|
531
|
+
* poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
|
|
532
|
+
* and desync the next transaction's framing.
|
|
533
|
+
*/
|
|
534
|
+
async guardTransaction(unitId, fn) {
|
|
535
|
+
if (this.poisonedUnits.has(unitId)) {
|
|
536
|
+
throw new Error(`Modbus unit ${unitId} socket is poisoned (awaiting reconnect) — transaction refused`);
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, fn);
|
|
540
|
+
this.lastOkAtByUnit.set(unitId, Date.now());
|
|
541
|
+
return result;
|
|
542
|
+
}
|
|
543
|
+
catch (error) {
|
|
544
|
+
if (error instanceof ModbusOperationTimeoutError) {
|
|
545
|
+
this.poisonUnit(unitId, error);
|
|
546
|
+
}
|
|
547
|
+
throw error;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
|
|
552
|
+
* the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
|
|
553
|
+
* timer is always cleared so a fast `fn` doesn't keep the event loop alive.
|
|
554
|
+
*/
|
|
555
|
+
withTimeout(operation, unitId, timeoutMs, fn) {
|
|
556
|
+
let timer;
|
|
557
|
+
const timeout = new Promise((_, reject) => {
|
|
558
|
+
timer = setTimeout(() => reject(new ModbusOperationTimeoutError(operation, unitId, timeoutMs)), timeoutMs);
|
|
559
|
+
});
|
|
560
|
+
return Promise.race([fn(), timeout]).finally(() => {
|
|
561
|
+
if (timer !== undefined)
|
|
562
|
+
clearTimeout(timer);
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
|
|
567
|
+
* gate immediately, so isHealthy() flips false this cycle instead of after the coarse
|
|
568
|
+
* 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
|
|
569
|
+
*/
|
|
570
|
+
poisonUnit(unitId, error) {
|
|
571
|
+
if (!this.poisonedUnits.has(unitId)) {
|
|
572
|
+
console.warn(`SunspecModbusClient: ${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
|
|
573
|
+
}
|
|
574
|
+
this.poisonedUnits.add(unitId);
|
|
575
|
+
this.connectionHealth.recordFailure(error);
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
579
|
+
* transaction has completed within staleSocketMs — the signature of a half-open link where
|
|
580
|
+
* the peer silently stopped answering. Units with no successful op yet are never stale.
|
|
581
|
+
*/
|
|
582
|
+
isStale(unitId) {
|
|
583
|
+
if (this.resilience.staleSocketMs <= 0)
|
|
584
|
+
return false;
|
|
585
|
+
const last = this.lastOkAtByUnit.get(unitId);
|
|
586
|
+
if (last === undefined)
|
|
587
|
+
return false;
|
|
588
|
+
return Date.now() - last > this.resilience.staleSocketMs;
|
|
589
|
+
}
|
|
396
590
|
recordOpen() {
|
|
397
591
|
this.openCount++;
|
|
398
592
|
const expected = this.modbusInstances.size;
|
|
@@ -2230,10 +2424,19 @@ export class SunspecModbusClient {
|
|
|
2230
2424
|
return this.modbusInstances.has(unitId);
|
|
2231
2425
|
}
|
|
2232
2426
|
/**
|
|
2233
|
-
* Check if a specific unit's connection is healthy
|
|
2427
|
+
* Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
|
|
2428
|
+
* unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
|
|
2429
|
+
* (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
|
|
2430
|
+
* recycles the socket rather than trusting a hung link.
|
|
2234
2431
|
*/
|
|
2235
2432
|
isHealthy(unitId) {
|
|
2236
|
-
|
|
2433
|
+
if (!this.modbusInstances.has(unitId))
|
|
2434
|
+
return false;
|
|
2435
|
+
if (this.poisonedUnits.has(unitId))
|
|
2436
|
+
return false;
|
|
2437
|
+
if (this.isStale(unitId))
|
|
2438
|
+
return false;
|
|
2439
|
+
return this.connectionHealth.isHealthy();
|
|
2237
2440
|
}
|
|
2238
2441
|
/**
|
|
2239
2442
|
* Get connection health details (shared across all units on this network device)
|
package/dist/version.d.ts
CHANGED
package/dist/version.js
CHANGED