@enyo-energy/sunspec-sdk 0.0.98 → 0.0.99
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 +9 -2
- package/dist/cjs/sunspec-interfaces.d.cts +47 -0
- package/dist/cjs/sunspec-modbus-client.cjs +145 -20
- package/dist/cjs/sunspec-modbus-client.d.cts +54 -6
- 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 +47 -0
- package/dist/sunspec-interfaces.js +8 -1
- package/dist/sunspec-modbus-client.d.ts +54 -6
- package/dist/sunspec-modbus-client.js +144 -20
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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,14 @@ 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,
|
|
16
23
|
};
|
|
17
24
|
/**
|
|
18
25
|
* 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,45 @@ 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
|
+
export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
|
|
40
87
|
/**
|
|
41
88
|
* Base interface for all SunSpec blocks
|
|
42
89
|
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
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
6
|
/**
|
|
@@ -25,6 +25,23 @@ const sunspec_interfaces_js_1 = require("./sunspec-interfaces.cjs");
|
|
|
25
25
|
const EnergyAppModbusConnectionHealth_js_1 = require("@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusConnectionHealth.js");
|
|
26
26
|
const EnergyAppModbusFaultTolerantReader_js_1 = require("@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusFaultTolerantReader.js");
|
|
27
27
|
const EnergyAppModbusDataTypeConverter_js_1 = require("@enyo-energy/energy-app-sdk/dist/implementations/modbus/EnergyAppModbusDataTypeConverter.js");
|
|
28
|
+
/**
|
|
29
|
+
* Thrown when a single Modbus transaction (read/write/connect/disconnect) exceeds its configured
|
|
30
|
+
* time budget. Surfaced instead of letting a half-open socket leave the operation pending forever.
|
|
31
|
+
*/
|
|
32
|
+
class ModbusOperationTimeoutError extends Error {
|
|
33
|
+
operation;
|
|
34
|
+
unitId;
|
|
35
|
+
timeoutMs;
|
|
36
|
+
constructor(operation, unitId, timeoutMs) {
|
|
37
|
+
super(`Modbus ${operation} on unit ${unitId} timed out after ${timeoutMs}ms`);
|
|
38
|
+
this.operation = operation;
|
|
39
|
+
this.unitId = unitId;
|
|
40
|
+
this.timeoutMs = timeoutMs;
|
|
41
|
+
this.name = 'ModbusOperationTimeoutError';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
exports.ModbusOperationTimeoutError = ModbusOperationTimeoutError;
|
|
28
45
|
/**
|
|
29
46
|
* Module-level registry: one SunspecModbusClient per network device (host:port).
|
|
30
47
|
* Refcounted so the underlying connection only tears down when the last consumer releases.
|
|
@@ -35,15 +52,15 @@ const registryKey = (host, port) => `${host}:${port}`;
|
|
|
35
52
|
* Get (or create) the singleton SunspecModbusClient for this network device.
|
|
36
53
|
* Increments the refcount; pair with `releaseSunspecClient` on teardown.
|
|
37
54
|
*
|
|
38
|
-
* NOTE: `pacing`
|
|
39
|
-
* Because the client is cached and refcounted, a later caller passing
|
|
55
|
+
* NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
|
|
56
|
+
* host:port. Because the client is cached and refcounted, a later caller passing different config
|
|
40
57
|
* receives the already-created instance and its config is ignored.
|
|
41
58
|
*/
|
|
42
|
-
function getOrCreateSunspecClient(energyApp, host, port = 502, pacing) {
|
|
59
|
+
function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience) {
|
|
43
60
|
const key = registryKey(host, port);
|
|
44
61
|
let entry = CLIENT_REGISTRY.get(key);
|
|
45
62
|
if (!entry) {
|
|
46
|
-
entry = { client: new SunspecModbusClient(energyApp, pacing), refcount: 0 };
|
|
63
|
+
entry = { client: new SunspecModbusClient(energyApp, pacing, resilience), refcount: 0 };
|
|
47
64
|
CLIENT_REGISTRY.set(key, entry);
|
|
48
65
|
}
|
|
49
66
|
entry.refcount++;
|
|
@@ -116,15 +133,30 @@ class SunspecModbusClient {
|
|
|
116
133
|
// operationChain (the connection lock) to avoid re-entrancy: a transaction never waits
|
|
117
134
|
// on a connect/disconnect, and vice versa.
|
|
118
135
|
txChains = new Map();
|
|
136
|
+
// Effective resilience config (per-op timeouts + staleness window), merged with defaults.
|
|
137
|
+
resilience;
|
|
138
|
+
// Units whose last transaction timed out. A timed-out Promise.race abandons the in-flight
|
|
139
|
+
// request but cannot cancel it — the response may still land later and desync the next
|
|
140
|
+
// transaction's framing. So a poisoned unit refuses further I/O until reconnectUnit() tears
|
|
141
|
+
// the socket down and reopens it (which clears the flag).
|
|
142
|
+
poisonedUnits = new Set();
|
|
143
|
+
// Wall-clock of each unit's last SUCCESSFUL transaction. Drives half-open detection: a socket
|
|
144
|
+
// the transport still reports connected but that has gone quiet past staleSocketMs is presumed
|
|
145
|
+
// dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
|
|
146
|
+
lastOkAtByUnit = new Map();
|
|
119
147
|
constructor(energyApp,
|
|
120
148
|
// Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
|
|
121
149
|
// serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
|
|
122
150
|
// connection. An empty object leaves both undefined so the SDK applies its own defaults.
|
|
123
|
-
pacing = {}
|
|
151
|
+
pacing = {},
|
|
152
|
+
// Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
|
|
153
|
+
// so omitted fields keep their defaults.
|
|
154
|
+
resilience = {}) {
|
|
124
155
|
this.energyApp = energyApp;
|
|
125
156
|
this.pacing = pacing;
|
|
126
157
|
this.connectionHealth = new EnergyAppModbusConnectionHealth_js_1.EnergyAppModbusConnectionHealth();
|
|
127
158
|
this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter_js_1.EnergyAppModbusDataTypeConverter();
|
|
159
|
+
this.resilience = { ...sunspec_interfaces_js_1.DEFAULT_MODBUS_RESILIENCE_CONFIG, ...resilience };
|
|
128
160
|
}
|
|
129
161
|
/**
|
|
130
162
|
* Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
|
|
@@ -319,11 +351,14 @@ class SunspecModbusClient {
|
|
|
319
351
|
async _openUnit(host, port, unitId) {
|
|
320
352
|
let candidate = null;
|
|
321
353
|
try {
|
|
322
|
-
|
|
354
|
+
// Enforce the connect budget ourselves in addition to forwarding it as the transport's
|
|
355
|
+
// `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
|
|
356
|
+
// can still leave the returned promise pending — bound it independently.
|
|
357
|
+
candidate = await this.withTimeout('connect', unitId, this.resilience.connectTimeoutMs, () => this.energyApp.useModbus().connect({
|
|
323
358
|
host,
|
|
324
359
|
port,
|
|
325
360
|
unitId,
|
|
326
|
-
timeout:
|
|
361
|
+
timeout: this.resilience.connectTimeoutMs,
|
|
327
362
|
useTls: this.connectionParams?.useTls,
|
|
328
363
|
cert: this.connectionParams?.cert,
|
|
329
364
|
key: this.connectionParams?.key,
|
|
@@ -331,22 +366,23 @@ class SunspecModbusClient {
|
|
|
331
366
|
rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
|
|
332
367
|
noParallelRequests: this.pacing.noParallelRequests,
|
|
333
368
|
waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
|
|
334
|
-
});
|
|
369
|
+
}));
|
|
335
370
|
if (!candidate) {
|
|
336
371
|
throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
|
|
337
372
|
}
|
|
338
373
|
const reader = new EnergyAppModbusFaultTolerantReader_js_1.EnergyAppModbusFaultTolerantReader(candidate, this.connectionHealth);
|
|
339
374
|
this.modbusInstances.set(unitId, candidate);
|
|
340
375
|
this.faultTolerantReaders.set(unitId, reader);
|
|
376
|
+
// Fresh socket: clear any prior poison and start the freshness clock so a just-opened
|
|
377
|
+
// unit isn't immediately judged stale.
|
|
378
|
+
this.poisonedUnits.delete(unitId);
|
|
379
|
+
this.lastOkAtByUnit.set(unitId, Date.now());
|
|
341
380
|
this.connectionHealth.recordSuccess();
|
|
342
381
|
this.recordOpen();
|
|
343
382
|
}
|
|
344
383
|
catch (err) {
|
|
345
384
|
if (candidate) {
|
|
346
|
-
|
|
347
|
-
await candidate.disconnect();
|
|
348
|
-
}
|
|
349
|
-
catch { /* ignore */ }
|
|
385
|
+
await this.disconnectInstanceBounded(candidate, unitId);
|
|
350
386
|
}
|
|
351
387
|
this.modbusInstances.delete(unitId);
|
|
352
388
|
this.faultTolerantReaders.delete(unitId);
|
|
@@ -364,15 +400,31 @@ class SunspecModbusClient {
|
|
|
364
400
|
this.faultTolerantReaders.delete(unitId);
|
|
365
401
|
this.discoveredModelsByUnit.delete(unitId);
|
|
366
402
|
this.discoveredModelListByUnit.delete(unitId);
|
|
403
|
+
// Drop per-unit resilience state so a later reopen starts clean.
|
|
404
|
+
this.poisonedUnits.delete(unitId);
|
|
405
|
+
this.lastOkAtByUnit.delete(unitId);
|
|
367
406
|
if (instance) {
|
|
368
|
-
|
|
369
|
-
await instance.disconnect();
|
|
370
|
-
}
|
|
371
|
-
catch { /* ignore */ }
|
|
407
|
+
await this.disconnectInstanceBounded(instance, unitId);
|
|
372
408
|
}
|
|
373
409
|
if (wasOpen)
|
|
374
410
|
this.recordClose();
|
|
375
411
|
}
|
|
412
|
+
/**
|
|
413
|
+
* Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
|
|
414
|
+
* left unbounded that would wedge the connection lock and stall every later connect/disconnect.
|
|
415
|
+
* Swallows all errors (including the timeout) — a close that can't complete is abandoned.
|
|
416
|
+
*/
|
|
417
|
+
async disconnectInstanceBounded(instance, unitId) {
|
|
418
|
+
try {
|
|
419
|
+
await this.withTimeout('disconnect', unitId, this.resilience.disconnectTimeoutMs, () => instance.disconnect());
|
|
420
|
+
}
|
|
421
|
+
catch (err) {
|
|
422
|
+
if (err instanceof ModbusOperationTimeoutError) {
|
|
423
|
+
console.warn(`SunspecModbusClient: disconnect of unit ${unitId} timed out after ${this.resilience.disconnectTimeoutMs}ms — abandoning socket`);
|
|
424
|
+
}
|
|
425
|
+
/* ignore: best-effort close */
|
|
426
|
+
}
|
|
427
|
+
}
|
|
376
428
|
/**
|
|
377
429
|
* Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
|
|
378
430
|
* behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
|
|
@@ -394,10 +446,74 @@ class SunspecModbusClient {
|
|
|
394
446
|
*/
|
|
395
447
|
runExclusive(unitId, fn) {
|
|
396
448
|
const prev = this.txChains.get(unitId) ?? Promise.resolve();
|
|
397
|
-
const
|
|
449
|
+
const guarded = () => this.guardTransaction(unitId, fn);
|
|
450
|
+
const run = prev.then(guarded, guarded);
|
|
398
451
|
this.txChains.set(unitId, run.catch(() => undefined));
|
|
399
452
|
return run;
|
|
400
453
|
}
|
|
454
|
+
/**
|
|
455
|
+
* Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
|
|
456
|
+
* On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
|
|
457
|
+
* transaction reuses the hung socket before the reconnect path recycles it. A unit already
|
|
458
|
+
* poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
|
|
459
|
+
* and desync the next transaction's framing.
|
|
460
|
+
*/
|
|
461
|
+
async guardTransaction(unitId, fn) {
|
|
462
|
+
if (this.poisonedUnits.has(unitId)) {
|
|
463
|
+
throw new Error(`Modbus unit ${unitId} socket is poisoned (awaiting reconnect) — transaction refused`);
|
|
464
|
+
}
|
|
465
|
+
try {
|
|
466
|
+
const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, fn);
|
|
467
|
+
this.lastOkAtByUnit.set(unitId, Date.now());
|
|
468
|
+
return result;
|
|
469
|
+
}
|
|
470
|
+
catch (error) {
|
|
471
|
+
if (error instanceof ModbusOperationTimeoutError) {
|
|
472
|
+
this.poisonUnit(unitId, error);
|
|
473
|
+
}
|
|
474
|
+
throw error;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
|
|
479
|
+
* the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
|
|
480
|
+
* timer is always cleared so a fast `fn` doesn't keep the event loop alive.
|
|
481
|
+
*/
|
|
482
|
+
withTimeout(operation, unitId, timeoutMs, fn) {
|
|
483
|
+
let timer;
|
|
484
|
+
const timeout = new Promise((_, reject) => {
|
|
485
|
+
timer = setTimeout(() => reject(new ModbusOperationTimeoutError(operation, unitId, timeoutMs)), timeoutMs);
|
|
486
|
+
});
|
|
487
|
+
return Promise.race([fn(), timeout]).finally(() => {
|
|
488
|
+
if (timer !== undefined)
|
|
489
|
+
clearTimeout(timer);
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
|
|
494
|
+
* gate immediately, so isHealthy() flips false this cycle instead of after the coarse
|
|
495
|
+
* 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
|
|
496
|
+
*/
|
|
497
|
+
poisonUnit(unitId, error) {
|
|
498
|
+
if (!this.poisonedUnits.has(unitId)) {
|
|
499
|
+
console.warn(`SunspecModbusClient: ${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
|
|
500
|
+
}
|
|
501
|
+
this.poisonedUnits.add(unitId);
|
|
502
|
+
this.connectionHealth.recordFailure(error);
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
506
|
+
* transaction has completed within staleSocketMs — the signature of a half-open link where
|
|
507
|
+
* the peer silently stopped answering. Units with no successful op yet are never stale.
|
|
508
|
+
*/
|
|
509
|
+
isStale(unitId) {
|
|
510
|
+
if (this.resilience.staleSocketMs <= 0)
|
|
511
|
+
return false;
|
|
512
|
+
const last = this.lastOkAtByUnit.get(unitId);
|
|
513
|
+
if (last === undefined)
|
|
514
|
+
return false;
|
|
515
|
+
return Date.now() - last > this.resilience.staleSocketMs;
|
|
516
|
+
}
|
|
401
517
|
recordOpen() {
|
|
402
518
|
this.openCount++;
|
|
403
519
|
const expected = this.modbusInstances.size;
|
|
@@ -2235,10 +2351,19 @@ class SunspecModbusClient {
|
|
|
2235
2351
|
return this.modbusInstances.has(unitId);
|
|
2236
2352
|
}
|
|
2237
2353
|
/**
|
|
2238
|
-
* Check if a specific unit's connection is healthy
|
|
2354
|
+
* Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
|
|
2355
|
+
* unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
|
|
2356
|
+
* (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
|
|
2357
|
+
* recycles the socket rather than trusting a hung link.
|
|
2239
2358
|
*/
|
|
2240
2359
|
isHealthy(unitId) {
|
|
2241
|
-
|
|
2360
|
+
if (!this.modbusInstances.has(unitId))
|
|
2361
|
+
return false;
|
|
2362
|
+
if (this.poisonedUnits.has(unitId))
|
|
2363
|
+
return false;
|
|
2364
|
+
if (this.isStale(unitId))
|
|
2365
|
+
return false;
|
|
2366
|
+
return this.connectionHealth.isHealthy();
|
|
2242
2367
|
}
|
|
2243
2368
|
/**
|
|
2244
2369
|
* Get connection health details (shared across all units on this network device)
|
|
@@ -16,19 +16,29 @@
|
|
|
16
16
|
* - pad: 0x8000 (always returns this value)
|
|
17
17
|
* - string: all registers 0x0000 (NULL)
|
|
18
18
|
*/
|
|
19
|
-
import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig } from "./sunspec-interfaces.cjs";
|
|
19
|
+
import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.cjs";
|
|
20
20
|
import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
|
|
21
21
|
import { EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
|
|
22
22
|
import { EnergyApp } from "@enyo-energy/energy-app-sdk";
|
|
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 declare class ModbusOperationTimeoutError extends Error {
|
|
28
|
+
readonly operation: string;
|
|
29
|
+
readonly unitId: number;
|
|
30
|
+
readonly timeoutMs: number;
|
|
31
|
+
constructor(operation: string, unitId: number, timeoutMs: number);
|
|
32
|
+
}
|
|
23
33
|
/**
|
|
24
34
|
* Get (or create) the singleton SunspecModbusClient for this network device.
|
|
25
35
|
* Increments the refcount; pair with `releaseSunspecClient` on teardown.
|
|
26
36
|
*
|
|
27
|
-
* NOTE: `pacing`
|
|
28
|
-
* Because the client is cached and refcounted, a later caller passing
|
|
37
|
+
* NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
|
|
38
|
+
* host:port. Because the client is cached and refcounted, a later caller passing different config
|
|
29
39
|
* receives the already-created instance and its config is ignored.
|
|
30
40
|
*/
|
|
31
|
-
export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig): SunspecModbusClient;
|
|
41
|
+
export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig): SunspecModbusClient;
|
|
32
42
|
/**
|
|
33
43
|
* Release a refcount on the network-device client. When the last consumer releases,
|
|
34
44
|
* the client is fully disconnected (all units closed) and removed from the registry.
|
|
@@ -53,7 +63,10 @@ export declare class SunspecModbusClient {
|
|
|
53
63
|
private closeCount;
|
|
54
64
|
private operationChain;
|
|
55
65
|
private txChains;
|
|
56
|
-
|
|
66
|
+
private resilience;
|
|
67
|
+
private poisonedUnits;
|
|
68
|
+
private lastOkAtByUnit;
|
|
69
|
+
constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig);
|
|
57
70
|
/**
|
|
58
71
|
* Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
|
|
59
72
|
* client; calling connect() with different unit IDs adds each as a separately-managed unit.
|
|
@@ -117,6 +130,12 @@ export declare class SunspecModbusClient {
|
|
|
117
130
|
* connection lock.
|
|
118
131
|
*/
|
|
119
132
|
private _closeUnit;
|
|
133
|
+
/**
|
|
134
|
+
* Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
|
|
135
|
+
* left unbounded that would wedge the connection lock and stall every later connect/disconnect.
|
|
136
|
+
* Swallows all errors (including the timeout) — a close that can't complete is abandoned.
|
|
137
|
+
*/
|
|
138
|
+
private disconnectInstanceBounded;
|
|
120
139
|
/**
|
|
121
140
|
* Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
|
|
122
141
|
* behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
|
|
@@ -133,6 +152,32 @@ export declare class SunspecModbusClient {
|
|
|
133
152
|
* unit — that re-enters the unit's chain and deadlocks.
|
|
134
153
|
*/
|
|
135
154
|
private runExclusive;
|
|
155
|
+
/**
|
|
156
|
+
* Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
|
|
157
|
+
* On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
|
|
158
|
+
* transaction reuses the hung socket before the reconnect path recycles it. A unit already
|
|
159
|
+
* poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
|
|
160
|
+
* and desync the next transaction's framing.
|
|
161
|
+
*/
|
|
162
|
+
private guardTransaction;
|
|
163
|
+
/**
|
|
164
|
+
* Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
|
|
165
|
+
* the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
|
|
166
|
+
* timer is always cleared so a fast `fn` doesn't keep the event loop alive.
|
|
167
|
+
*/
|
|
168
|
+
private withTimeout;
|
|
169
|
+
/**
|
|
170
|
+
* Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
|
|
171
|
+
* gate immediately, so isHealthy() flips false this cycle instead of after the coarse
|
|
172
|
+
* 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
|
|
173
|
+
*/
|
|
174
|
+
private poisonUnit;
|
|
175
|
+
/**
|
|
176
|
+
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
177
|
+
* transaction has completed within staleSocketMs — the signature of a half-open link where
|
|
178
|
+
* the peer silently stopped answering. Units with no successful op yet are never stale.
|
|
179
|
+
*/
|
|
180
|
+
private isStale;
|
|
136
181
|
private recordOpen;
|
|
137
182
|
private recordClose;
|
|
138
183
|
/**
|
|
@@ -444,7 +489,10 @@ export declare class SunspecModbusClient {
|
|
|
444
489
|
*/
|
|
445
490
|
isConnected(unitId: number): boolean;
|
|
446
491
|
/**
|
|
447
|
-
* Check if a specific unit's connection is healthy
|
|
492
|
+
* Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
|
|
493
|
+
* unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
|
|
494
|
+
* (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
|
|
495
|
+
* recycles the socket rather than trusting a hung link.
|
|
448
496
|
*/
|
|
449
497
|
isHealthy(unitId: number): boolean;
|
|
450
498
|
/**
|
package/dist/cjs/version.cjs
CHANGED
|
@@ -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.
|
|
12
|
+
exports.SDK_VERSION = '0.0.99';
|
|
13
13
|
/**
|
|
14
14
|
* Gets the current SDK version.
|
|
15
15
|
* @returns The semantic version string of the SDK
|
package/dist/cjs/version.d.cts
CHANGED
|
@@ -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
|
*/
|
|
@@ -18,6 +18,10 @@ export class ConnectionRetryManager {
|
|
|
18
18
|
disconnectedSince = null;
|
|
19
19
|
lastAttemptTime = 0;
|
|
20
20
|
attemptCount = 0;
|
|
21
|
+
// Jittered gate for the NEXT attempt, computed when the previous one is recorded. 0 means
|
|
22
|
+
// "use the raw phase interval" — the state before any attempt, so the first reconnect after a
|
|
23
|
+
// disconnect fires immediately (preserving the original behaviour).
|
|
24
|
+
nextIntervalMs = 0;
|
|
21
25
|
constructor(config) {
|
|
22
26
|
this.config = config ?? DEFAULT_RETRY_CONFIG;
|
|
23
27
|
}
|
|
@@ -36,6 +40,7 @@ export class ConnectionRetryManager {
|
|
|
36
40
|
this.disconnectedSince = null;
|
|
37
41
|
this.lastAttemptTime = 0;
|
|
38
42
|
this.attemptCount = 0;
|
|
43
|
+
this.nextIntervalMs = 0;
|
|
39
44
|
}
|
|
40
45
|
/**
|
|
41
46
|
* Determine which retry phase we're currently in based on elapsed time since disconnect.
|
|
@@ -66,7 +71,11 @@ export class ConnectionRetryManager {
|
|
|
66
71
|
}
|
|
67
72
|
const now = Date.now();
|
|
68
73
|
const phase = this.getCurrentPhase();
|
|
69
|
-
|
|
74
|
+
// Before the first attempt (nextIntervalMs === 0), lastAttemptTime is 0 so the gate is
|
|
75
|
+
// effectively open — the first reconnect fires right away. Afterwards, honour the jittered
|
|
76
|
+
// interval computed at the previous recordAttempt().
|
|
77
|
+
const interval = this.nextIntervalMs > 0 ? this.nextIntervalMs : phase.intervalMs;
|
|
78
|
+
return (now - this.lastAttemptTime) >= interval;
|
|
70
79
|
}
|
|
71
80
|
/**
|
|
72
81
|
* Record that an attempt was just made.
|
|
@@ -74,6 +83,21 @@ export class ConnectionRetryManager {
|
|
|
74
83
|
recordAttempt() {
|
|
75
84
|
this.lastAttemptTime = Date.now();
|
|
76
85
|
this.attemptCount++;
|
|
86
|
+
// Pre-compute the (jittered) gate for the next attempt so a fleet that dropped together
|
|
87
|
+
// spreads its retries instead of stampeding one gateway on every phase boundary.
|
|
88
|
+
this.nextIntervalMs = this.applyJitter(this.getCurrentPhase().intervalMs);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Spread an interval by ±jitter fraction. Returns the interval unchanged when jitter is
|
|
92
|
+
* unset/zero. Never returns a negative value.
|
|
93
|
+
*/
|
|
94
|
+
applyJitter(intervalMs) {
|
|
95
|
+
const jitter = this.config.jitter ?? 0;
|
|
96
|
+
if (jitter <= 0) {
|
|
97
|
+
return intervalMs;
|
|
98
|
+
}
|
|
99
|
+
const factor = 1 + (Math.random() * 2 - 1) * jitter;
|
|
100
|
+
return Math.max(0, Math.round(intervalMs * factor));
|
|
77
101
|
}
|
|
78
102
|
/**
|
|
79
103
|
* Get the number of reconnection attempts made.
|
|
@@ -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,45 @@ 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
|
+
export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
|
|
40
87
|
/**
|
|
41
88
|
* Base interface for all SunSpec blocks
|
|
42
89
|
*/
|
|
@@ -9,7 +9,14 @@ export const DEFAULT_RETRY_CONFIG = {
|
|
|
9
9
|
{ intervalMs: 60_000, durationMs: 300_000 }, // Phase 3: every 1m for 5 minutes
|
|
10
10
|
{ intervalMs: 300_000, durationMs: 600_000 }, // Phase 4: every 5m for 10 minutes
|
|
11
11
|
{ intervalMs: 900_000, durationMs: 0 }, // Phase 5: every 15m forever
|
|
12
|
-
]
|
|
12
|
+
],
|
|
13
|
+
jitter: 0.2,
|
|
14
|
+
};
|
|
15
|
+
export const DEFAULT_MODBUS_RESILIENCE_CONFIG = {
|
|
16
|
+
readTimeoutMs: 5_000,
|
|
17
|
+
connectTimeoutMs: 5_000,
|
|
18
|
+
disconnectTimeoutMs: 5_000,
|
|
19
|
+
staleSocketMs: 30_000,
|
|
13
20
|
};
|
|
14
21
|
/**
|
|
15
22
|
* Common Sunspec Model IDs
|
|
@@ -16,19 +16,29 @@
|
|
|
16
16
|
* - pad: 0x8000 (always returns this value)
|
|
17
17
|
* - string: all registers 0x0000 (NULL)
|
|
18
18
|
*/
|
|
19
|
-
import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig } from "./sunspec-interfaces.js";
|
|
19
|
+
import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.js";
|
|
20
20
|
import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
|
|
21
21
|
import { EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
|
|
22
22
|
import { EnergyApp } from "@enyo-energy/energy-app-sdk";
|
|
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 declare class ModbusOperationTimeoutError extends Error {
|
|
28
|
+
readonly operation: string;
|
|
29
|
+
readonly unitId: number;
|
|
30
|
+
readonly timeoutMs: number;
|
|
31
|
+
constructor(operation: string, unitId: number, timeoutMs: number);
|
|
32
|
+
}
|
|
23
33
|
/**
|
|
24
34
|
* Get (or create) the singleton SunspecModbusClient for this network device.
|
|
25
35
|
* Increments the refcount; pair with `releaseSunspecClient` on teardown.
|
|
26
36
|
*
|
|
27
|
-
* NOTE: `pacing`
|
|
28
|
-
* Because the client is cached and refcounted, a later caller passing
|
|
37
|
+
* NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
|
|
38
|
+
* host:port. Because the client is cached and refcounted, a later caller passing different config
|
|
29
39
|
* receives the already-created instance and its config is ignored.
|
|
30
40
|
*/
|
|
31
|
-
export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig): SunspecModbusClient;
|
|
41
|
+
export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig): SunspecModbusClient;
|
|
32
42
|
/**
|
|
33
43
|
* Release a refcount on the network-device client. When the last consumer releases,
|
|
34
44
|
* the client is fully disconnected (all units closed) and removed from the registry.
|
|
@@ -53,7 +63,10 @@ export declare class SunspecModbusClient {
|
|
|
53
63
|
private closeCount;
|
|
54
64
|
private operationChain;
|
|
55
65
|
private txChains;
|
|
56
|
-
|
|
66
|
+
private resilience;
|
|
67
|
+
private poisonedUnits;
|
|
68
|
+
private lastOkAtByUnit;
|
|
69
|
+
constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig);
|
|
57
70
|
/**
|
|
58
71
|
* Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
|
|
59
72
|
* client; calling connect() with different unit IDs adds each as a separately-managed unit.
|
|
@@ -117,6 +130,12 @@ export declare class SunspecModbusClient {
|
|
|
117
130
|
* connection lock.
|
|
118
131
|
*/
|
|
119
132
|
private _closeUnit;
|
|
133
|
+
/**
|
|
134
|
+
* Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
|
|
135
|
+
* left unbounded that would wedge the connection lock and stall every later connect/disconnect.
|
|
136
|
+
* Swallows all errors (including the timeout) — a close that can't complete is abandoned.
|
|
137
|
+
*/
|
|
138
|
+
private disconnectInstanceBounded;
|
|
120
139
|
/**
|
|
121
140
|
* Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
|
|
122
141
|
* behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
|
|
@@ -133,6 +152,32 @@ export declare class SunspecModbusClient {
|
|
|
133
152
|
* unit — that re-enters the unit's chain and deadlocks.
|
|
134
153
|
*/
|
|
135
154
|
private runExclusive;
|
|
155
|
+
/**
|
|
156
|
+
* Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
|
|
157
|
+
* On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
|
|
158
|
+
* transaction reuses the hung socket before the reconnect path recycles it. A unit already
|
|
159
|
+
* poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
|
|
160
|
+
* and desync the next transaction's framing.
|
|
161
|
+
*/
|
|
162
|
+
private guardTransaction;
|
|
163
|
+
/**
|
|
164
|
+
* Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
|
|
165
|
+
* the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
|
|
166
|
+
* timer is always cleared so a fast `fn` doesn't keep the event loop alive.
|
|
167
|
+
*/
|
|
168
|
+
private withTimeout;
|
|
169
|
+
/**
|
|
170
|
+
* Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
|
|
171
|
+
* gate immediately, so isHealthy() flips false this cycle instead of after the coarse
|
|
172
|
+
* 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
|
|
173
|
+
*/
|
|
174
|
+
private poisonUnit;
|
|
175
|
+
/**
|
|
176
|
+
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
177
|
+
* transaction has completed within staleSocketMs — the signature of a half-open link where
|
|
178
|
+
* the peer silently stopped answering. Units with no successful op yet are never stale.
|
|
179
|
+
*/
|
|
180
|
+
private isStale;
|
|
136
181
|
private recordOpen;
|
|
137
182
|
private recordClose;
|
|
138
183
|
/**
|
|
@@ -444,7 +489,10 @@ export declare class SunspecModbusClient {
|
|
|
444
489
|
*/
|
|
445
490
|
isConnected(unitId: number): boolean;
|
|
446
491
|
/**
|
|
447
|
-
* Check if a specific unit's connection is healthy
|
|
492
|
+
* Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
|
|
493
|
+
* unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
|
|
494
|
+
* (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
|
|
495
|
+
* recycles the socket rather than trusting a hung link.
|
|
448
496
|
*/
|
|
449
497
|
isHealthy(unitId: number): boolean;
|
|
450
498
|
/**
|
|
@@ -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++;
|
|
@@ -111,15 +127,30 @@ export class SunspecModbusClient {
|
|
|
111
127
|
// operationChain (the connection lock) to avoid re-entrancy: a transaction never waits
|
|
112
128
|
// on a connect/disconnect, and vice versa.
|
|
113
129
|
txChains = new Map();
|
|
130
|
+
// Effective resilience config (per-op timeouts + staleness window), merged with defaults.
|
|
131
|
+
resilience;
|
|
132
|
+
// Units whose last transaction timed out. A timed-out Promise.race abandons the in-flight
|
|
133
|
+
// request but cannot cancel it — the response may still land later and desync the next
|
|
134
|
+
// transaction's framing. So a poisoned unit refuses further I/O until reconnectUnit() tears
|
|
135
|
+
// the socket down and reopens it (which clears the flag).
|
|
136
|
+
poisonedUnits = new Set();
|
|
137
|
+
// Wall-clock of each unit's last SUCCESSFUL transaction. Drives half-open detection: a socket
|
|
138
|
+
// the transport still reports connected but that has gone quiet past staleSocketMs is presumed
|
|
139
|
+
// dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
|
|
140
|
+
lastOkAtByUnit = new Map();
|
|
114
141
|
constructor(energyApp,
|
|
115
142
|
// Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
|
|
116
143
|
// serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
|
|
117
144
|
// connection. An empty object leaves both undefined so the SDK applies its own defaults.
|
|
118
|
-
pacing = {}
|
|
145
|
+
pacing = {},
|
|
146
|
+
// Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
|
|
147
|
+
// so omitted fields keep their defaults.
|
|
148
|
+
resilience = {}) {
|
|
119
149
|
this.energyApp = energyApp;
|
|
120
150
|
this.pacing = pacing;
|
|
121
151
|
this.connectionHealth = new EnergyAppModbusConnectionHealth();
|
|
122
152
|
this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter();
|
|
153
|
+
this.resilience = { ...DEFAULT_MODBUS_RESILIENCE_CONFIG, ...resilience };
|
|
123
154
|
}
|
|
124
155
|
/**
|
|
125
156
|
* Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
|
|
@@ -314,11 +345,14 @@ export class SunspecModbusClient {
|
|
|
314
345
|
async _openUnit(host, port, unitId) {
|
|
315
346
|
let candidate = null;
|
|
316
347
|
try {
|
|
317
|
-
|
|
348
|
+
// Enforce the connect budget ourselves in addition to forwarding it as the transport's
|
|
349
|
+
// `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
|
|
350
|
+
// can still leave the returned promise pending — bound it independently.
|
|
351
|
+
candidate = await this.withTimeout('connect', unitId, this.resilience.connectTimeoutMs, () => this.energyApp.useModbus().connect({
|
|
318
352
|
host,
|
|
319
353
|
port,
|
|
320
354
|
unitId,
|
|
321
|
-
timeout:
|
|
355
|
+
timeout: this.resilience.connectTimeoutMs,
|
|
322
356
|
useTls: this.connectionParams?.useTls,
|
|
323
357
|
cert: this.connectionParams?.cert,
|
|
324
358
|
key: this.connectionParams?.key,
|
|
@@ -326,22 +360,23 @@ export class SunspecModbusClient {
|
|
|
326
360
|
rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
|
|
327
361
|
noParallelRequests: this.pacing.noParallelRequests,
|
|
328
362
|
waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
|
|
329
|
-
});
|
|
363
|
+
}));
|
|
330
364
|
if (!candidate) {
|
|
331
365
|
throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
|
|
332
366
|
}
|
|
333
367
|
const reader = new EnergyAppModbusFaultTolerantReader(candidate, this.connectionHealth);
|
|
334
368
|
this.modbusInstances.set(unitId, candidate);
|
|
335
369
|
this.faultTolerantReaders.set(unitId, reader);
|
|
370
|
+
// Fresh socket: clear any prior poison and start the freshness clock so a just-opened
|
|
371
|
+
// unit isn't immediately judged stale.
|
|
372
|
+
this.poisonedUnits.delete(unitId);
|
|
373
|
+
this.lastOkAtByUnit.set(unitId, Date.now());
|
|
336
374
|
this.connectionHealth.recordSuccess();
|
|
337
375
|
this.recordOpen();
|
|
338
376
|
}
|
|
339
377
|
catch (err) {
|
|
340
378
|
if (candidate) {
|
|
341
|
-
|
|
342
|
-
await candidate.disconnect();
|
|
343
|
-
}
|
|
344
|
-
catch { /* ignore */ }
|
|
379
|
+
await this.disconnectInstanceBounded(candidate, unitId);
|
|
345
380
|
}
|
|
346
381
|
this.modbusInstances.delete(unitId);
|
|
347
382
|
this.faultTolerantReaders.delete(unitId);
|
|
@@ -359,15 +394,31 @@ export class SunspecModbusClient {
|
|
|
359
394
|
this.faultTolerantReaders.delete(unitId);
|
|
360
395
|
this.discoveredModelsByUnit.delete(unitId);
|
|
361
396
|
this.discoveredModelListByUnit.delete(unitId);
|
|
397
|
+
// Drop per-unit resilience state so a later reopen starts clean.
|
|
398
|
+
this.poisonedUnits.delete(unitId);
|
|
399
|
+
this.lastOkAtByUnit.delete(unitId);
|
|
362
400
|
if (instance) {
|
|
363
|
-
|
|
364
|
-
await instance.disconnect();
|
|
365
|
-
}
|
|
366
|
-
catch { /* ignore */ }
|
|
401
|
+
await this.disconnectInstanceBounded(instance, unitId);
|
|
367
402
|
}
|
|
368
403
|
if (wasOpen)
|
|
369
404
|
this.recordClose();
|
|
370
405
|
}
|
|
406
|
+
/**
|
|
407
|
+
* Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
|
|
408
|
+
* left unbounded that would wedge the connection lock and stall every later connect/disconnect.
|
|
409
|
+
* Swallows all errors (including the timeout) — a close that can't complete is abandoned.
|
|
410
|
+
*/
|
|
411
|
+
async disconnectInstanceBounded(instance, unitId) {
|
|
412
|
+
try {
|
|
413
|
+
await this.withTimeout('disconnect', unitId, this.resilience.disconnectTimeoutMs, () => instance.disconnect());
|
|
414
|
+
}
|
|
415
|
+
catch (err) {
|
|
416
|
+
if (err instanceof ModbusOperationTimeoutError) {
|
|
417
|
+
console.warn(`SunspecModbusClient: disconnect of unit ${unitId} timed out after ${this.resilience.disconnectTimeoutMs}ms — abandoning socket`);
|
|
418
|
+
}
|
|
419
|
+
/* ignore: best-effort close */
|
|
420
|
+
}
|
|
421
|
+
}
|
|
371
422
|
/**
|
|
372
423
|
* Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
|
|
373
424
|
* behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
|
|
@@ -389,10 +440,74 @@ export class SunspecModbusClient {
|
|
|
389
440
|
*/
|
|
390
441
|
runExclusive(unitId, fn) {
|
|
391
442
|
const prev = this.txChains.get(unitId) ?? Promise.resolve();
|
|
392
|
-
const
|
|
443
|
+
const guarded = () => this.guardTransaction(unitId, fn);
|
|
444
|
+
const run = prev.then(guarded, guarded);
|
|
393
445
|
this.txChains.set(unitId, run.catch(() => undefined));
|
|
394
446
|
return run;
|
|
395
447
|
}
|
|
448
|
+
/**
|
|
449
|
+
* Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
|
|
450
|
+
* On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
|
|
451
|
+
* transaction reuses the hung socket before the reconnect path recycles it. A unit already
|
|
452
|
+
* poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
|
|
453
|
+
* and desync the next transaction's framing.
|
|
454
|
+
*/
|
|
455
|
+
async guardTransaction(unitId, fn) {
|
|
456
|
+
if (this.poisonedUnits.has(unitId)) {
|
|
457
|
+
throw new Error(`Modbus unit ${unitId} socket is poisoned (awaiting reconnect) — transaction refused`);
|
|
458
|
+
}
|
|
459
|
+
try {
|
|
460
|
+
const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, fn);
|
|
461
|
+
this.lastOkAtByUnit.set(unitId, Date.now());
|
|
462
|
+
return result;
|
|
463
|
+
}
|
|
464
|
+
catch (error) {
|
|
465
|
+
if (error instanceof ModbusOperationTimeoutError) {
|
|
466
|
+
this.poisonUnit(unitId, error);
|
|
467
|
+
}
|
|
468
|
+
throw error;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
|
|
473
|
+
* the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
|
|
474
|
+
* timer is always cleared so a fast `fn` doesn't keep the event loop alive.
|
|
475
|
+
*/
|
|
476
|
+
withTimeout(operation, unitId, timeoutMs, fn) {
|
|
477
|
+
let timer;
|
|
478
|
+
const timeout = new Promise((_, reject) => {
|
|
479
|
+
timer = setTimeout(() => reject(new ModbusOperationTimeoutError(operation, unitId, timeoutMs)), timeoutMs);
|
|
480
|
+
});
|
|
481
|
+
return Promise.race([fn(), timeout]).finally(() => {
|
|
482
|
+
if (timer !== undefined)
|
|
483
|
+
clearTimeout(timer);
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
|
|
488
|
+
* gate immediately, so isHealthy() flips false this cycle instead of after the coarse
|
|
489
|
+
* 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
|
|
490
|
+
*/
|
|
491
|
+
poisonUnit(unitId, error) {
|
|
492
|
+
if (!this.poisonedUnits.has(unitId)) {
|
|
493
|
+
console.warn(`SunspecModbusClient: ${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
|
|
494
|
+
}
|
|
495
|
+
this.poisonedUnits.add(unitId);
|
|
496
|
+
this.connectionHealth.recordFailure(error);
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
500
|
+
* transaction has completed within staleSocketMs — the signature of a half-open link where
|
|
501
|
+
* the peer silently stopped answering. Units with no successful op yet are never stale.
|
|
502
|
+
*/
|
|
503
|
+
isStale(unitId) {
|
|
504
|
+
if (this.resilience.staleSocketMs <= 0)
|
|
505
|
+
return false;
|
|
506
|
+
const last = this.lastOkAtByUnit.get(unitId);
|
|
507
|
+
if (last === undefined)
|
|
508
|
+
return false;
|
|
509
|
+
return Date.now() - last > this.resilience.staleSocketMs;
|
|
510
|
+
}
|
|
396
511
|
recordOpen() {
|
|
397
512
|
this.openCount++;
|
|
398
513
|
const expected = this.modbusInstances.size;
|
|
@@ -2230,10 +2345,19 @@ export class SunspecModbusClient {
|
|
|
2230
2345
|
return this.modbusInstances.has(unitId);
|
|
2231
2346
|
}
|
|
2232
2347
|
/**
|
|
2233
|
-
* Check if a specific unit's connection is healthy
|
|
2348
|
+
* Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
|
|
2349
|
+
* unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
|
|
2350
|
+
* (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
|
|
2351
|
+
* recycles the socket rather than trusting a hung link.
|
|
2234
2352
|
*/
|
|
2235
2353
|
isHealthy(unitId) {
|
|
2236
|
-
|
|
2354
|
+
if (!this.modbusInstances.has(unitId))
|
|
2355
|
+
return false;
|
|
2356
|
+
if (this.poisonedUnits.has(unitId))
|
|
2357
|
+
return false;
|
|
2358
|
+
if (this.isStale(unitId))
|
|
2359
|
+
return false;
|
|
2360
|
+
return this.connectionHealth.isHealthy();
|
|
2237
2361
|
}
|
|
2238
2362
|
/**
|
|
2239
2363
|
* Get connection health details (shared across all units on this network device)
|
package/dist/version.d.ts
CHANGED
package/dist/version.js
CHANGED