@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,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.
|
|
@@ -37,6 +47,19 @@ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: str
|
|
|
37
47
|
* is clamped at zero so repeat releases are no-ops.
|
|
38
48
|
*/
|
|
39
49
|
export declare function releaseSunspecClient(host: string, port?: number): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Retry an async operation a bounded number of times with a fixed backoff between attempts,
|
|
52
|
+
* rethrowing the last error if every attempt fails. Used to make the initial per-unit connect
|
|
53
|
+
* resilient to a transient gateway hiccup at (re)connect time — the failure mode where a single
|
|
54
|
+
* connect timeout at launch would otherwise cascade into a long outage for the whole device.
|
|
55
|
+
* `sleep` is injectable so tests don't incur real delay; `onRetry` reports each retried failure.
|
|
56
|
+
*/
|
|
57
|
+
export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts: {
|
|
58
|
+
attempts: number;
|
|
59
|
+
delayMs: number;
|
|
60
|
+
sleep?: (ms: number) => Promise<void>;
|
|
61
|
+
onRetry?: (error: unknown, attempt: number) => void;
|
|
62
|
+
}): Promise<T>;
|
|
40
63
|
export declare class SunspecModbusClient {
|
|
41
64
|
private energyApp;
|
|
42
65
|
private pacing;
|
|
@@ -53,7 +76,10 @@ export declare class SunspecModbusClient {
|
|
|
53
76
|
private closeCount;
|
|
54
77
|
private operationChain;
|
|
55
78
|
private txChains;
|
|
56
|
-
|
|
79
|
+
private resilience;
|
|
80
|
+
private poisonedUnits;
|
|
81
|
+
private lastOkAtByUnit;
|
|
82
|
+
constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig);
|
|
57
83
|
/**
|
|
58
84
|
* Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
|
|
59
85
|
* client; calling connect() with different unit IDs adds each as a separately-managed unit.
|
|
@@ -75,6 +101,26 @@ export declare class SunspecModbusClient {
|
|
|
75
101
|
ca?: string | Buffer | Array<string | Buffer>;
|
|
76
102
|
rejectUnauthorized?: boolean;
|
|
77
103
|
}): Promise<void>;
|
|
104
|
+
/**
|
|
105
|
+
* Fast-fail probe of a unit for speculative RS485-chain scans, where most candidate unit IDs
|
|
106
|
+
* are absent. On success the unit is opened and kept exactly as {@link connect} would; the
|
|
107
|
+
* difference is the FAILURE path: a probe does NOT retry the connect (unlike connect(), which
|
|
108
|
+
* honours {@link IModbusResilienceConfig.connectRetries}) and uses a caller-supplied, typically
|
|
109
|
+
* shorter, connect timeout. So scanning a range of mostly-dead units costs ~`timeoutMs` each
|
|
110
|
+
* instead of the full retrying connect budget — the reason a warm reconnect must never queue
|
|
111
|
+
* its meter/battery attach behind such a scan. Throws on failure; nothing is left open.
|
|
112
|
+
*/
|
|
113
|
+
probeUnit(host: string, port?: number, unitId?: number, opts?: {
|
|
114
|
+
secondaryHost?: string;
|
|
115
|
+
timeoutMs?: number;
|
|
116
|
+
}): Promise<void>;
|
|
117
|
+
/**
|
|
118
|
+
* Reconcile/lock in this client's connection parameters. The first call binds the client to a
|
|
119
|
+
* single (host, port); later calls for a different endpoint throw (use one client per endpoint
|
|
120
|
+
* via {@link getOrCreateSunspecClient}). Optional secondaryHost/TLS material fills in on first
|
|
121
|
+
* sight without clobbering. Caller must hold the connection lock.
|
|
122
|
+
*/
|
|
123
|
+
private reconcileConnectionParams;
|
|
78
124
|
/**
|
|
79
125
|
* Disconnect from all units of this network device.
|
|
80
126
|
*
|
|
@@ -107,16 +153,33 @@ export declare class SunspecModbusClient {
|
|
|
107
153
|
*/
|
|
108
154
|
private attemptConnection;
|
|
109
155
|
/**
|
|
110
|
-
* Open a
|
|
111
|
-
*
|
|
112
|
-
*
|
|
156
|
+
* Open a unit, retrying the connect on a transient failure per the resilience config
|
|
157
|
+
* ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
|
|
158
|
+
* — which independently bounds its connect at {@link IModbusResilienceConfig.connectTimeoutMs}
|
|
159
|
+
* and tears down any half-open candidate before rethrowing — so retries never leak a socket.
|
|
160
|
+
*
|
|
161
|
+
* `override` lets a caller tune this single open: {@link probeUnit} passes `connectRetries: 0`
|
|
162
|
+
* and a shorter `connectTimeoutMs` to fast-fail a speculative scan; omitted fields fall back to
|
|
163
|
+
* the client's resilience config.
|
|
113
164
|
*/
|
|
114
165
|
private _openUnit;
|
|
166
|
+
/**
|
|
167
|
+
* Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
|
|
168
|
+
* connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
|
|
169
|
+
* we never leak. Caller must hold the connection lock and ensure the unit is not already open.
|
|
170
|
+
*/
|
|
171
|
+
private _openUnitOnce;
|
|
115
172
|
/**
|
|
116
173
|
* Close the Modbus instance for a single unit. Idempotent. Caller must hold the
|
|
117
174
|
* connection lock.
|
|
118
175
|
*/
|
|
119
176
|
private _closeUnit;
|
|
177
|
+
/**
|
|
178
|
+
* Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
|
|
179
|
+
* left unbounded that would wedge the connection lock and stall every later connect/disconnect.
|
|
180
|
+
* Swallows all errors (including the timeout) — a close that can't complete is abandoned.
|
|
181
|
+
*/
|
|
182
|
+
private disconnectInstanceBounded;
|
|
120
183
|
/**
|
|
121
184
|
* Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
|
|
122
185
|
* behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
|
|
@@ -133,6 +196,32 @@ export declare class SunspecModbusClient {
|
|
|
133
196
|
* unit — that re-enters the unit's chain and deadlocks.
|
|
134
197
|
*/
|
|
135
198
|
private runExclusive;
|
|
199
|
+
/**
|
|
200
|
+
* Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
|
|
201
|
+
* On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
|
|
202
|
+
* transaction reuses the hung socket before the reconnect path recycles it. A unit already
|
|
203
|
+
* poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
|
|
204
|
+
* and desync the next transaction's framing.
|
|
205
|
+
*/
|
|
206
|
+
private guardTransaction;
|
|
207
|
+
/**
|
|
208
|
+
* Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
|
|
209
|
+
* the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
|
|
210
|
+
* timer is always cleared so a fast `fn` doesn't keep the event loop alive.
|
|
211
|
+
*/
|
|
212
|
+
private withTimeout;
|
|
213
|
+
/**
|
|
214
|
+
* Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
|
|
215
|
+
* gate immediately, so isHealthy() flips false this cycle instead of after the coarse
|
|
216
|
+
* 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
|
|
217
|
+
*/
|
|
218
|
+
private poisonUnit;
|
|
219
|
+
/**
|
|
220
|
+
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
221
|
+
* transaction has completed within staleSocketMs — the signature of a half-open link where
|
|
222
|
+
* the peer silently stopped answering. Units with no successful op yet are never stale.
|
|
223
|
+
*/
|
|
224
|
+
private isStale;
|
|
136
225
|
private recordOpen;
|
|
137
226
|
private recordClose;
|
|
138
227
|
/**
|
|
@@ -444,7 +533,10 @@ export declare class SunspecModbusClient {
|
|
|
444
533
|
*/
|
|
445
534
|
isConnected(unitId: number): boolean;
|
|
446
535
|
/**
|
|
447
|
-
* Check if a specific unit's connection is healthy
|
|
536
|
+
* Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
|
|
537
|
+
* unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
|
|
538
|
+
* (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
|
|
539
|
+
* recycles the socket rather than trusting a hung link.
|
|
448
540
|
*/
|
|
449
541
|
isHealthy(unitId: number): boolean;
|
|
450
542
|
/**
|
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.100';
|
|
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,59 @@ export interface IModbusPacingConfig {
|
|
|
37
45
|
*/
|
|
38
46
|
waitBetweenMessagesMs?: number;
|
|
39
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Resilience configuration for the Modbus client: per-operation timeouts and half-open socket
|
|
50
|
+
* detection. All fields are optional and default to sensible values, so existing consumers are
|
|
51
|
+
* unaffected.
|
|
52
|
+
*
|
|
53
|
+
* These guard the "stuck connection" failure mode: the injected transport's `connect({ timeout })`
|
|
54
|
+
* only bounds the TCP handshake, NOT individual reads/writes. On a half-open socket (the peer stops
|
|
55
|
+
* answering while the OS still reports the connection ESTABLISHED) a read can stay pending forever,
|
|
56
|
+
* wedging the affected unit's transaction chain and stalling its whole poll loop with no failure
|
|
57
|
+
* ever recorded. A per-operation timeout plus a freshness clock turn that silent hang into a fast,
|
|
58
|
+
* observable failure the reconnect path can recover from.
|
|
59
|
+
*/
|
|
60
|
+
export interface IModbusResilienceConfig {
|
|
61
|
+
/**
|
|
62
|
+
* Max ms a single Modbus transaction (a read/write, including a multi-chunk block read) may take
|
|
63
|
+
* before it is abandoned with a timeout, the socket is poisoned, and the reconnect path recycles
|
|
64
|
+
* it. Default 5000.
|
|
65
|
+
*/
|
|
66
|
+
readTimeoutMs?: number;
|
|
67
|
+
/**
|
|
68
|
+
* Max ms the initial TCP connect for a unit may take before it is abandoned. Enforced by the
|
|
69
|
+
* client independently of the transport-level `timeout` it also forwards. Default 5000.
|
|
70
|
+
*/
|
|
71
|
+
connectTimeoutMs?: number;
|
|
72
|
+
/**
|
|
73
|
+
* Max ms a `disconnect()` may take before it is abandoned. A half-open socket can hang even on
|
|
74
|
+
* close, which would otherwise re-wedge the connection lock. Default 5000.
|
|
75
|
+
*/
|
|
76
|
+
disconnectTimeoutMs?: number;
|
|
77
|
+
/**
|
|
78
|
+
* If a unit has completed at least one successful transaction but none within this window, its
|
|
79
|
+
* socket is treated as stale (presumed half-open) even when the transport still reports it
|
|
80
|
+
* connected — so `isHealthy()` flips false and the device's reconnect path recycles it before
|
|
81
|
+
* the coarse 5-minute health staleness would. Default 30000 (~3 poll cycles at a 10s poll).
|
|
82
|
+
* Set 0 to disable staleness detection.
|
|
83
|
+
*/
|
|
84
|
+
staleSocketMs?: number;
|
|
85
|
+
/**
|
|
86
|
+
* Number of extra attempts to retry the initial per-unit TCP connect after the first one fails,
|
|
87
|
+
* before giving up and throwing. A transient gateway hiccup at (re)connect time — e.g. a
|
|
88
|
+
* SolarEdge gateway still waking up in the seconds right after an app restart — would otherwise
|
|
89
|
+
* fail the whole unit for a full reconnect cycle and cascade into a long telemetry gap. Each
|
|
90
|
+
* attempt is independently bounded by {@link connectTimeoutMs}. Default 1 (2 attempts total).
|
|
91
|
+
* Set 0 to preserve the old fail-fast behaviour.
|
|
92
|
+
*/
|
|
93
|
+
connectRetries?: number;
|
|
94
|
+
/**
|
|
95
|
+
* Fixed backoff between consecutive connect attempts, in ms. Only applies when
|
|
96
|
+
* {@link connectRetries} > 0. Default 500.
|
|
97
|
+
*/
|
|
98
|
+
connectRetryDelayMs?: number;
|
|
99
|
+
}
|
|
100
|
+
export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
|
|
40
101
|
/**
|
|
41
102
|
* Base interface for all SunSpec blocks
|
|
42
103
|
*/
|
|
@@ -9,7 +9,16 @@ 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,
|
|
20
|
+
connectRetries: 1,
|
|
21
|
+
connectRetryDelayMs: 500,
|
|
13
22
|
};
|
|
14
23
|
/**
|
|
15
24
|
* 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.
|
|
@@ -37,6 +47,19 @@ export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: str
|
|
|
37
47
|
* is clamped at zero so repeat releases are no-ops.
|
|
38
48
|
*/
|
|
39
49
|
export declare function releaseSunspecClient(host: string, port?: number): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Retry an async operation a bounded number of times with a fixed backoff between attempts,
|
|
52
|
+
* rethrowing the last error if every attempt fails. Used to make the initial per-unit connect
|
|
53
|
+
* resilient to a transient gateway hiccup at (re)connect time — the failure mode where a single
|
|
54
|
+
* connect timeout at launch would otherwise cascade into a long outage for the whole device.
|
|
55
|
+
* `sleep` is injectable so tests don't incur real delay; `onRetry` reports each retried failure.
|
|
56
|
+
*/
|
|
57
|
+
export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts: {
|
|
58
|
+
attempts: number;
|
|
59
|
+
delayMs: number;
|
|
60
|
+
sleep?: (ms: number) => Promise<void>;
|
|
61
|
+
onRetry?: (error: unknown, attempt: number) => void;
|
|
62
|
+
}): Promise<T>;
|
|
40
63
|
export declare class SunspecModbusClient {
|
|
41
64
|
private energyApp;
|
|
42
65
|
private pacing;
|
|
@@ -53,7 +76,10 @@ export declare class SunspecModbusClient {
|
|
|
53
76
|
private closeCount;
|
|
54
77
|
private operationChain;
|
|
55
78
|
private txChains;
|
|
56
|
-
|
|
79
|
+
private resilience;
|
|
80
|
+
private poisonedUnits;
|
|
81
|
+
private lastOkAtByUnit;
|
|
82
|
+
constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig);
|
|
57
83
|
/**
|
|
58
84
|
* Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
|
|
59
85
|
* client; calling connect() with different unit IDs adds each as a separately-managed unit.
|
|
@@ -75,6 +101,26 @@ export declare class SunspecModbusClient {
|
|
|
75
101
|
ca?: string | Buffer | Array<string | Buffer>;
|
|
76
102
|
rejectUnauthorized?: boolean;
|
|
77
103
|
}): Promise<void>;
|
|
104
|
+
/**
|
|
105
|
+
* Fast-fail probe of a unit for speculative RS485-chain scans, where most candidate unit IDs
|
|
106
|
+
* are absent. On success the unit is opened and kept exactly as {@link connect} would; the
|
|
107
|
+
* difference is the FAILURE path: a probe does NOT retry the connect (unlike connect(), which
|
|
108
|
+
* honours {@link IModbusResilienceConfig.connectRetries}) and uses a caller-supplied, typically
|
|
109
|
+
* shorter, connect timeout. So scanning a range of mostly-dead units costs ~`timeoutMs` each
|
|
110
|
+
* instead of the full retrying connect budget — the reason a warm reconnect must never queue
|
|
111
|
+
* its meter/battery attach behind such a scan. Throws on failure; nothing is left open.
|
|
112
|
+
*/
|
|
113
|
+
probeUnit(host: string, port?: number, unitId?: number, opts?: {
|
|
114
|
+
secondaryHost?: string;
|
|
115
|
+
timeoutMs?: number;
|
|
116
|
+
}): Promise<void>;
|
|
117
|
+
/**
|
|
118
|
+
* Reconcile/lock in this client's connection parameters. The first call binds the client to a
|
|
119
|
+
* single (host, port); later calls for a different endpoint throw (use one client per endpoint
|
|
120
|
+
* via {@link getOrCreateSunspecClient}). Optional secondaryHost/TLS material fills in on first
|
|
121
|
+
* sight without clobbering. Caller must hold the connection lock.
|
|
122
|
+
*/
|
|
123
|
+
private reconcileConnectionParams;
|
|
78
124
|
/**
|
|
79
125
|
* Disconnect from all units of this network device.
|
|
80
126
|
*
|
|
@@ -107,16 +153,33 @@ export declare class SunspecModbusClient {
|
|
|
107
153
|
*/
|
|
108
154
|
private attemptConnection;
|
|
109
155
|
/**
|
|
110
|
-
* Open a
|
|
111
|
-
*
|
|
112
|
-
*
|
|
156
|
+
* Open a unit, retrying the connect on a transient failure per the resilience config
|
|
157
|
+
* ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
|
|
158
|
+
* — which independently bounds its connect at {@link IModbusResilienceConfig.connectTimeoutMs}
|
|
159
|
+
* and tears down any half-open candidate before rethrowing — so retries never leak a socket.
|
|
160
|
+
*
|
|
161
|
+
* `override` lets a caller tune this single open: {@link probeUnit} passes `connectRetries: 0`
|
|
162
|
+
* and a shorter `connectTimeoutMs` to fast-fail a speculative scan; omitted fields fall back to
|
|
163
|
+
* the client's resilience config.
|
|
113
164
|
*/
|
|
114
165
|
private _openUnit;
|
|
166
|
+
/**
|
|
167
|
+
* Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
|
|
168
|
+
* connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
|
|
169
|
+
* we never leak. Caller must hold the connection lock and ensure the unit is not already open.
|
|
170
|
+
*/
|
|
171
|
+
private _openUnitOnce;
|
|
115
172
|
/**
|
|
116
173
|
* Close the Modbus instance for a single unit. Idempotent. Caller must hold the
|
|
117
174
|
* connection lock.
|
|
118
175
|
*/
|
|
119
176
|
private _closeUnit;
|
|
177
|
+
/**
|
|
178
|
+
* Close an instance under a hard time budget. A half-open socket can hang even on disconnect();
|
|
179
|
+
* left unbounded that would wedge the connection lock and stall every later connect/disconnect.
|
|
180
|
+
* Swallows all errors (including the timeout) — a close that can't complete is abandoned.
|
|
181
|
+
*/
|
|
182
|
+
private disconnectInstanceBounded;
|
|
120
183
|
/**
|
|
121
184
|
* Run `fn` with exclusive access to connection-state transitions. Subsequent calls queue
|
|
122
185
|
* behind any in-flight one. A rejected `fn` does not poison the chain for later callers.
|
|
@@ -133,6 +196,32 @@ export declare class SunspecModbusClient {
|
|
|
133
196
|
* unit — that re-enters the unit's chain and deadlocks.
|
|
134
197
|
*/
|
|
135
198
|
private runExclusive;
|
|
199
|
+
/**
|
|
200
|
+
* Wrap one serialized transaction with the per-operation timeout and half-open bookkeeping.
|
|
201
|
+
* On success, stamp the unit's freshness clock. On timeout, poison the unit so no further
|
|
202
|
+
* transaction reuses the hung socket before the reconnect path recycles it. A unit already
|
|
203
|
+
* poisoned refuses I/O outright — the abandoned in-flight response could otherwise land later
|
|
204
|
+
* and desync the next transaction's framing.
|
|
205
|
+
*/
|
|
206
|
+
private guardTransaction;
|
|
207
|
+
/**
|
|
208
|
+
* Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
|
|
209
|
+
* the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
|
|
210
|
+
* timer is always cleared so a fast `fn` doesn't keep the event loop alive.
|
|
211
|
+
*/
|
|
212
|
+
private withTimeout;
|
|
213
|
+
/**
|
|
214
|
+
* Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
|
|
215
|
+
* gate immediately, so isHealthy() flips false this cycle instead of after the coarse
|
|
216
|
+
* 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
|
|
217
|
+
*/
|
|
218
|
+
private poisonUnit;
|
|
219
|
+
/**
|
|
220
|
+
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
221
|
+
* transaction has completed within staleSocketMs — the signature of a half-open link where
|
|
222
|
+
* the peer silently stopped answering. Units with no successful op yet are never stale.
|
|
223
|
+
*/
|
|
224
|
+
private isStale;
|
|
136
225
|
private recordOpen;
|
|
137
226
|
private recordClose;
|
|
138
227
|
/**
|
|
@@ -444,7 +533,10 @@ export declare class SunspecModbusClient {
|
|
|
444
533
|
*/
|
|
445
534
|
isConnected(unitId: number): boolean;
|
|
446
535
|
/**
|
|
447
|
-
* Check if a specific unit's connection is healthy
|
|
536
|
+
* Check if a specific unit's connection is healthy. Beyond the shared health counter, a unit is
|
|
537
|
+
* unhealthy if its socket has been poisoned by a timed-out transaction or has gone stale
|
|
538
|
+
* (half-open) — both flip false immediately so the device's readData()/tryReconnect() path
|
|
539
|
+
* recycles the socket rather than trusting a hung link.
|
|
448
540
|
*/
|
|
449
541
|
isHealthy(unitId: number): boolean;
|
|
450
542
|
/**
|