@enyo-energy/sunspec-sdk 0.0.99 → 0.0.101
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sunspec-devices.cjs +119 -16
- package/dist/cjs/sunspec-devices.d.cts +63 -0
- package/dist/cjs/sunspec-interfaces.cjs +2 -0
- package/dist/cjs/sunspec-interfaces.d.cts +14 -0
- package/dist/cjs/sunspec-modbus-client.cjs +141 -42
- package/dist/cjs/sunspec-modbus-client.d.cts +60 -3
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/sunspec-devices.d.ts +63 -0
- package/dist/sunspec-devices.js +119 -16
- package/dist/sunspec-interfaces.d.ts +14 -0
- package/dist/sunspec-interfaces.js +2 -0
- package/dist/sunspec-modbus-client.d.ts +60 -3
- package/dist/sunspec-modbus-client.js +140 -42
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -183,8 +183,26 @@ class BaseSunspecDevice {
|
|
|
183
183
|
// device's poll loop detects a dropped connection.
|
|
184
184
|
const success = await this.sunspecClient.reconnectUnit(this.unitId);
|
|
185
185
|
if (success) {
|
|
186
|
-
// Re-discover models for this unit after reconnect
|
|
187
|
-
|
|
186
|
+
// Re-discover models for this unit after reconnect. discoverModels() clears
|
|
187
|
+
// and repopulates the per-unit model map, so a reconnect that opens the TCP
|
|
188
|
+
// socket but comes back with no usable models (a gateway that accepted the
|
|
189
|
+
// connection before it was ready to answer the SunSpec scan) would leave the
|
|
190
|
+
// map empty. Trusting that would cache an empty map — every read then finds no
|
|
191
|
+
// model while the socket looks healthy, and because reset() disables retry,
|
|
192
|
+
// nothing ever triggers another reconnect. So validate discovery here and, when
|
|
193
|
+
// it's unusable, treat this as a failed reconnect: invalidate the socket so the
|
|
194
|
+
// next poll re-enters tryReconnect(), keep the backoff schedule running, and do
|
|
195
|
+
// NOT reset().
|
|
196
|
+
const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
|
|
197
|
+
if (!this.isDiscoveryUsable(models)) {
|
|
198
|
+
this.sunspecClient.invalidateUnit(this.unitId, `reconnect discovery found no usable models for unit ${this.unitId}`);
|
|
199
|
+
this.consecutiveReconnectFailures += 1;
|
|
200
|
+
await this.onConnectionFailure(this.consecutiveReconnectFailures);
|
|
201
|
+
console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
|
|
202
|
+
`opened the socket but discovery returned no usable models ` +
|
|
203
|
+
`(found [${[...models.keys()].join(', ')}]) — retrying with backoff`);
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
188
206
|
this.retryManager.reset();
|
|
189
207
|
this.consecutiveReconnectFailures = 0;
|
|
190
208
|
// Update appliance state to Connected
|
|
@@ -207,6 +225,42 @@ class BaseSunspecDevice {
|
|
|
207
225
|
}
|
|
208
226
|
return false;
|
|
209
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* Model IDs this device needs to produce a reading; presence of ANY one means a
|
|
230
|
+
* discovery is usable (one-of semantics — devices expose mutually-exclusive
|
|
231
|
+
* encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
|
|
232
|
+
* (the base default) means no specific requirement, so any model present
|
|
233
|
+
* suffices. Concrete devices override with their acceptable set — this is the
|
|
234
|
+
* single per-device source of truth reused by both the reconnect discovery gate
|
|
235
|
+
* ({@link isDiscoveryUsable}) and the connect-time presence gate
|
|
236
|
+
* ({@link hasRequiredModels}).
|
|
237
|
+
*/
|
|
238
|
+
getRequiredModelIds() {
|
|
239
|
+
return [];
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* True if the current per-unit discovered-model map satisfies this device's
|
|
243
|
+
* requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
|
|
244
|
+
* the already-populated map via findModel() rather than a freshly-returned one.
|
|
245
|
+
* Only meaningful for devices that declare a non-empty required set.
|
|
246
|
+
*/
|
|
247
|
+
hasRequiredModels() {
|
|
248
|
+
return this.getRequiredModelIds().some(id => this.sunspecClient.findModel(this.unitId, id) !== undefined);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Decide whether a post-reconnect model discovery is usable. A reconnect that
|
|
252
|
+
* establishes the TCP socket but comes back empty (or with only a Common block)
|
|
253
|
+
* means the device accepted the connection before it was ready to answer the
|
|
254
|
+
* SunSpec scan; the discovered-model map is now missing this device's data
|
|
255
|
+
* model, so trusting the reconnect would leave every read finding no model.
|
|
256
|
+
* Validated generically against {@link getRequiredModelIds}: with a declared
|
|
257
|
+
* set, at least one of those ids must be present; with none declared, fall back
|
|
258
|
+
* to "any model present".
|
|
259
|
+
*/
|
|
260
|
+
isDiscoveryUsable(models) {
|
|
261
|
+
const required = this.getRequiredModelIds();
|
|
262
|
+
return required.length === 0 ? models.size > 0 : required.some(id => models.has(id));
|
|
263
|
+
}
|
|
210
264
|
/**
|
|
211
265
|
* Hook for subclasses to react to a failed reconnect attempt. Called once
|
|
212
266
|
* per failed attempt with the running consecutive-failure count.
|
|
@@ -364,6 +418,19 @@ class SunspecInverter extends BaseSunspecDevice {
|
|
|
364
418
|
pvPowerSource;
|
|
365
419
|
/** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
|
|
366
420
|
static CONNECTION_FAULT_THRESHOLD = 3;
|
|
421
|
+
/**
|
|
422
|
+
* The inverter data models this device can read (int+SF 101/103 and IEEE-754
|
|
423
|
+
* float 111/112/113). A post-reconnect discovery that finds none of these has
|
|
424
|
+
* not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
|
|
425
|
+
* see the override below.
|
|
426
|
+
*/
|
|
427
|
+
static INVERTER_MODEL_IDS = [
|
|
428
|
+
sunspec_interfaces_js_1.SunspecModelId.InverterSinglePhase,
|
|
429
|
+
sunspec_interfaces_js_1.SunspecModelId.Inverter3Phase,
|
|
430
|
+
sunspec_interfaces_js_1.SunspecModelId.InverterSinglePhaseFloat,
|
|
431
|
+
sunspec_interfaces_js_1.SunspecModelId.InverterSplitPhaseFloat,
|
|
432
|
+
sunspec_interfaces_js_1.SunspecModelId.Inverter3PhaseFloat
|
|
433
|
+
];
|
|
367
434
|
/**
|
|
368
435
|
* Require this many consecutive operatingState=7 (FAULT) reads before
|
|
369
436
|
* reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
|
|
@@ -746,6 +813,16 @@ class SunspecInverter extends BaseSunspecDevice {
|
|
|
746
813
|
lastStatus: newLastStatus,
|
|
747
814
|
};
|
|
748
815
|
}
|
|
816
|
+
/**
|
|
817
|
+
* A reconnect has only recovered the inverter if discovery finds one of its
|
|
818
|
+
* data models. An SE gateway can accept the new socket and answer a partial
|
|
819
|
+
* scan (e.g. only the Common block) before the inverter map is ready — the
|
|
820
|
+
* base size>0 rule would accept that, but every inverter read would then find
|
|
821
|
+
* no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
|
|
822
|
+
*/
|
|
823
|
+
getRequiredModelIds() {
|
|
824
|
+
return SunspecInverter.INVERTER_MODEL_IDS;
|
|
825
|
+
}
|
|
749
826
|
async onConnectionFailure(consecutiveFailures) {
|
|
750
827
|
if (!this.applianceId || !this.dataBus)
|
|
751
828
|
return;
|
|
@@ -1295,6 +1372,16 @@ function filterFeaturesByCalibrationResult(detected, result, controllable) {
|
|
|
1295
1372
|
class SunspecBattery extends BaseSunspecDevice {
|
|
1296
1373
|
featureMode;
|
|
1297
1374
|
capabilities;
|
|
1375
|
+
/**
|
|
1376
|
+
* Battery data models this device can read: Battery (124, full decode) and
|
|
1377
|
+
* BatteryBase (802, derived decode). BatteryControl (803) is intentionally
|
|
1378
|
+
* excluded — it is a decode stub that yields no telemetry — so a rediscovery
|
|
1379
|
+
* that returns only 803 is treated as unrecovered, matching the connect() gate.
|
|
1380
|
+
*/
|
|
1381
|
+
static BATTERY_MODEL_IDS = [
|
|
1382
|
+
sunspec_interfaces_js_1.SunspecModelId.Battery,
|
|
1383
|
+
sunspec_interfaces_js_1.SunspecModelId.BatteryBase
|
|
1384
|
+
];
|
|
1298
1385
|
snapshotService;
|
|
1299
1386
|
calibrationDriver;
|
|
1300
1387
|
batteryCalibrator;
|
|
@@ -1398,16 +1485,17 @@ class SunspecBattery extends BaseSunspecDevice {
|
|
|
1398
1485
|
getBatteryCalibrator() {
|
|
1399
1486
|
return this.batteryCalibrator;
|
|
1400
1487
|
}
|
|
1488
|
+
getRequiredModelIds() {
|
|
1489
|
+
return SunspecBattery.BATTERY_MODEL_IDS;
|
|
1490
|
+
}
|
|
1401
1491
|
/**
|
|
1402
1492
|
* Connect to the battery and create/update the appliance
|
|
1403
1493
|
*/
|
|
1404
1494
|
async connect(inverterApplianceId) {
|
|
1405
1495
|
// Ensure Sunspec client is connected
|
|
1406
1496
|
await this.ensureConnected();
|
|
1407
|
-
// Check if battery models exist
|
|
1408
|
-
|
|
1409
|
-
this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.BatteryBase) !== undefined;
|
|
1410
|
-
if (!hasBattery) {
|
|
1497
|
+
// Check if battery models exist (124 or 802 — see BATTERY_MODEL_IDS).
|
|
1498
|
+
if (!this.hasRequiredModels()) {
|
|
1411
1499
|
throw new Error('No battery model found in device');
|
|
1412
1500
|
}
|
|
1413
1501
|
// Get device info
|
|
@@ -1983,6 +2071,20 @@ exports.SunspecBattery = SunspecBattery;
|
|
|
1983
2071
|
*/
|
|
1984
2072
|
class SunspecMeter extends BaseSunspecDevice {
|
|
1985
2073
|
capabilities;
|
|
2074
|
+
/**
|
|
2075
|
+
* Meter data models this device can read, across int+SF (201/203/204) and
|
|
2076
|
+
* IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
|
|
2077
|
+
* variants. Used when the meter is not bound to a specific instance.
|
|
2078
|
+
*/
|
|
2079
|
+
static METER_MODEL_IDS = [
|
|
2080
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhase,
|
|
2081
|
+
sunspec_interfaces_js_1.SunspecModelId.Meter3Phase,
|
|
2082
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterWye,
|
|
2083
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhaseFloat,
|
|
2084
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterSplitPhaseFloat,
|
|
2085
|
+
sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseWyeFloat,
|
|
2086
|
+
sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseDeltaFloat
|
|
2087
|
+
];
|
|
1986
2088
|
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
|
|
1987
2089
|
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
1988
2090
|
this.capabilities = capabilities;
|
|
@@ -2001,22 +2103,23 @@ class SunspecMeter extends BaseSunspecDevice {
|
|
|
2001
2103
|
bindMeterModel(model) {
|
|
2002
2104
|
this.meterModel = model;
|
|
2003
2105
|
}
|
|
2106
|
+
/**
|
|
2107
|
+
* A bound meter requires ITS own pinned model id to reappear after a
|
|
2108
|
+
* rediscovery; an unbound meter accepts any meter model on its unit.
|
|
2109
|
+
*/
|
|
2110
|
+
getRequiredModelIds() {
|
|
2111
|
+
return this.meterModel ? [this.meterModel.id] : SunspecMeter.METER_MODEL_IDS;
|
|
2112
|
+
}
|
|
2004
2113
|
/**
|
|
2005
2114
|
* Connect to the meter and create/update the appliance
|
|
2006
2115
|
*/
|
|
2007
2116
|
async connect() {
|
|
2008
2117
|
// Connect with specific unit ID for meter
|
|
2009
2118
|
await this.ensureConnected();
|
|
2010
|
-
// Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214)
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhase) !== undefined ||
|
|
2015
|
-
this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseWyeFloat) !== undefined ||
|
|
2016
|
-
this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseDeltaFloat) !== undefined ||
|
|
2017
|
-
this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.MeterSplitPhaseFloat) !== undefined ||
|
|
2018
|
-
this.sunspecClient.findModel(this.unitId, sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhaseFloat) !== undefined;
|
|
2019
|
-
if (!hasMeter) {
|
|
2119
|
+
// Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214).
|
|
2120
|
+
// A bound meter short-circuits: getRequiredModelIds() returns [meterModel.id],
|
|
2121
|
+
// which the just-completed discovery re-listed for the same physical device.
|
|
2122
|
+
if (!this.hasRequiredModels()) {
|
|
2020
2123
|
throw new Error('No meter model found in device');
|
|
2021
2124
|
}
|
|
2022
2125
|
// Get device info. For a bound meter instance, read ITS own Common block (the one
|
|
@@ -74,6 +74,35 @@ export declare abstract class BaseSunspecDevice {
|
|
|
74
74
|
* Returns true if reconnection succeeded.
|
|
75
75
|
*/
|
|
76
76
|
protected tryReconnect(): Promise<boolean>;
|
|
77
|
+
/**
|
|
78
|
+
* Model IDs this device needs to produce a reading; presence of ANY one means a
|
|
79
|
+
* discovery is usable (one-of semantics — devices expose mutually-exclusive
|
|
80
|
+
* encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
|
|
81
|
+
* (the base default) means no specific requirement, so any model present
|
|
82
|
+
* suffices. Concrete devices override with their acceptable set — this is the
|
|
83
|
+
* single per-device source of truth reused by both the reconnect discovery gate
|
|
84
|
+
* ({@link isDiscoveryUsable}) and the connect-time presence gate
|
|
85
|
+
* ({@link hasRequiredModels}).
|
|
86
|
+
*/
|
|
87
|
+
protected getRequiredModelIds(): readonly number[];
|
|
88
|
+
/**
|
|
89
|
+
* True if the current per-unit discovered-model map satisfies this device's
|
|
90
|
+
* requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
|
|
91
|
+
* the already-populated map via findModel() rather than a freshly-returned one.
|
|
92
|
+
* Only meaningful for devices that declare a non-empty required set.
|
|
93
|
+
*/
|
|
94
|
+
protected hasRequiredModels(): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Decide whether a post-reconnect model discovery is usable. A reconnect that
|
|
97
|
+
* establishes the TCP socket but comes back empty (or with only a Common block)
|
|
98
|
+
* means the device accepted the connection before it was ready to answer the
|
|
99
|
+
* SunSpec scan; the discovered-model map is now missing this device's data
|
|
100
|
+
* model, so trusting the reconnect would leave every read finding no model.
|
|
101
|
+
* Validated generically against {@link getRequiredModelIds}: with a declared
|
|
102
|
+
* set, at least one of those ids must be present; with none declared, fall back
|
|
103
|
+
* to "any model present".
|
|
104
|
+
*/
|
|
105
|
+
protected isDiscoveryUsable(models: Map<number, SunspecModel>): boolean;
|
|
77
106
|
/**
|
|
78
107
|
* Hook for subclasses to react to a failed reconnect attempt. Called once
|
|
79
108
|
* per failed attempt with the running consecutive-failure count.
|
|
@@ -142,6 +171,13 @@ export declare class SunspecInverter extends BaseSunspecDevice {
|
|
|
142
171
|
private readonly pvPowerSource;
|
|
143
172
|
/** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
|
|
144
173
|
private static readonly CONNECTION_FAULT_THRESHOLD;
|
|
174
|
+
/**
|
|
175
|
+
* The inverter data models this device can read (int+SF 101/103 and IEEE-754
|
|
176
|
+
* float 111/112/113). A post-reconnect discovery that finds none of these has
|
|
177
|
+
* not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
|
|
178
|
+
* see the override below.
|
|
179
|
+
*/
|
|
180
|
+
private static readonly INVERTER_MODEL_IDS;
|
|
145
181
|
/**
|
|
146
182
|
* Require this many consecutive operatingState=7 (FAULT) reads before
|
|
147
183
|
* reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
|
|
@@ -218,6 +254,14 @@ export declare class SunspecInverter extends BaseSunspecDevice {
|
|
|
218
254
|
private hasErrorSetChanged;
|
|
219
255
|
private buildStatusMessage;
|
|
220
256
|
private detectAndEmitStatusTransition;
|
|
257
|
+
/**
|
|
258
|
+
* A reconnect has only recovered the inverter if discovery finds one of its
|
|
259
|
+
* data models. An SE gateway can accept the new socket and answer a partial
|
|
260
|
+
* scan (e.g. only the Common block) before the inverter map is ready — the
|
|
261
|
+
* base size>0 rule would accept that, but every inverter read would then find
|
|
262
|
+
* no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
|
|
263
|
+
*/
|
|
264
|
+
protected getRequiredModelIds(): readonly number[];
|
|
221
265
|
protected onConnectionFailure(consecutiveFailures: number): Promise<void>;
|
|
222
266
|
protected onConnectionRestored(): Promise<void>;
|
|
223
267
|
/**
|
|
@@ -430,6 +474,13 @@ export declare function filterFeaturesByCalibrationResult(detected: EnyoBatteryF
|
|
|
430
474
|
export declare class SunspecBattery extends BaseSunspecDevice {
|
|
431
475
|
private readonly featureMode;
|
|
432
476
|
private readonly capabilities;
|
|
477
|
+
/**
|
|
478
|
+
* Battery data models this device can read: Battery (124, full decode) and
|
|
479
|
+
* BatteryBase (802, derived decode). BatteryControl (803) is intentionally
|
|
480
|
+
* excluded — it is a decode stub that yields no telemetry — so a rediscovery
|
|
481
|
+
* that returns only 803 is treated as unrecovered, matching the connect() gate.
|
|
482
|
+
*/
|
|
483
|
+
private static readonly BATTERY_MODEL_IDS;
|
|
433
484
|
private snapshotService?;
|
|
434
485
|
private calibrationDriver?;
|
|
435
486
|
private batteryCalibrator?;
|
|
@@ -478,6 +529,7 @@ export declare class SunspecBattery extends BaseSunspecDevice {
|
|
|
478
529
|
* `CalibrationTrigger`.
|
|
479
530
|
*/
|
|
480
531
|
getBatteryCalibrator(): BatteryCalibrator<SunspecBatteryControls> | undefined;
|
|
532
|
+
protected getRequiredModelIds(): readonly number[];
|
|
481
533
|
/**
|
|
482
534
|
* Connect to the battery and create/update the appliance
|
|
483
535
|
*/
|
|
@@ -646,6 +698,12 @@ export declare class SunspecBattery extends BaseSunspecDevice {
|
|
|
646
698
|
*/
|
|
647
699
|
export declare class SunspecMeter extends BaseSunspecDevice {
|
|
648
700
|
private readonly capabilities;
|
|
701
|
+
/**
|
|
702
|
+
* Meter data models this device can read, across int+SF (201/203/204) and
|
|
703
|
+
* IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
|
|
704
|
+
* variants. Used when the meter is not bound to a specific instance.
|
|
705
|
+
*/
|
|
706
|
+
private static readonly METER_MODEL_IDS;
|
|
649
707
|
constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, unitId?: number, port?: number, baseAddress?: number, capabilities?: SunspecMeterCapability[], retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean);
|
|
650
708
|
/**
|
|
651
709
|
* The specific meter model instance this meter reads, when its unit hosts more than one
|
|
@@ -659,6 +717,11 @@ export declare class SunspecMeter extends BaseSunspecDevice {
|
|
|
659
717
|
* {@link SunspecModbusClient.findModels}). Call before {@link connect}.
|
|
660
718
|
*/
|
|
661
719
|
bindMeterModel(model: SunspecModel): void;
|
|
720
|
+
/**
|
|
721
|
+
* A bound meter requires ITS own pinned model id to reappear after a
|
|
722
|
+
* rediscovery; an unbound meter accepts any meter model on its unit.
|
|
723
|
+
*/
|
|
724
|
+
protected getRequiredModelIds(): readonly number[];
|
|
662
725
|
/**
|
|
663
726
|
* Connect to the meter and create/update the appliance
|
|
664
727
|
*/
|
|
@@ -82,6 +82,20 @@ export interface IModbusResilienceConfig {
|
|
|
82
82
|
* Set 0 to disable staleness detection.
|
|
83
83
|
*/
|
|
84
84
|
staleSocketMs?: number;
|
|
85
|
+
/**
|
|
86
|
+
* Number of extra attempts to retry the initial per-unit TCP connect after the first one fails,
|
|
87
|
+
* before giving up and throwing. A transient gateway hiccup at (re)connect time — e.g. a
|
|
88
|
+
* SolarEdge gateway still waking up in the seconds right after an app restart — would otherwise
|
|
89
|
+
* fail the whole unit for a full reconnect cycle and cascade into a long telemetry gap. Each
|
|
90
|
+
* attempt is independently bounded by {@link connectTimeoutMs}. Default 1 (2 attempts total).
|
|
91
|
+
* Set 0 to preserve the old fail-fast behaviour.
|
|
92
|
+
*/
|
|
93
|
+
connectRetries?: number;
|
|
94
|
+
/**
|
|
95
|
+
* Fixed backoff between consecutive connect attempts, in ms. Only applies when
|
|
96
|
+
* {@link connectRetries} > 0. Default 500.
|
|
97
|
+
*/
|
|
98
|
+
connectRetryDelayMs?: number;
|
|
85
99
|
}
|
|
86
100
|
export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
|
|
87
101
|
/**
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.SunspecModbusClient = exports.ModbusOperationTimeoutError = void 0;
|
|
4
4
|
exports.getOrCreateSunspecClient = getOrCreateSunspecClient;
|
|
5
5
|
exports.releaseSunspecClient = releaseSunspecClient;
|
|
6
|
+
exports.retryAsync = retryAsync;
|
|
6
7
|
/**
|
|
7
8
|
* Sunspec Modbus Client Implementation
|
|
8
9
|
*
|
|
@@ -98,6 +99,31 @@ async function releaseSunspecClient(host, port = 502) {
|
|
|
98
99
|
}
|
|
99
100
|
}
|
|
100
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Retry an async operation a bounded number of times with a fixed backoff between attempts,
|
|
104
|
+
* rethrowing the last error if every attempt fails. Used to make the initial per-unit connect
|
|
105
|
+
* resilient to a transient gateway hiccup at (re)connect time — the failure mode where a single
|
|
106
|
+
* connect timeout at launch would otherwise cascade into a long outage for the whole device.
|
|
107
|
+
* `sleep` is injectable so tests don't incur real delay; `onRetry` reports each retried failure.
|
|
108
|
+
*/
|
|
109
|
+
async function retryAsync(fn, opts) {
|
|
110
|
+
const attempts = Math.max(1, opts.attempts);
|
|
111
|
+
const sleep = opts.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
|
|
112
|
+
let lastError;
|
|
113
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
114
|
+
try {
|
|
115
|
+
return await fn(attempt);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
lastError = error;
|
|
119
|
+
if (attempt < attempts) {
|
|
120
|
+
opts.onRetry?.(error, attempt);
|
|
121
|
+
await sleep(opts.delayMs);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
throw lastError;
|
|
126
|
+
}
|
|
101
127
|
class SunspecModbusClient {
|
|
102
128
|
energyApp;
|
|
103
129
|
pacing;
|
|
@@ -175,42 +201,7 @@ class SunspecModbusClient {
|
|
|
175
201
|
*/
|
|
176
202
|
async connect(host, port = 502, unitId = 1, secondaryHost, useTls, tls) {
|
|
177
203
|
return this.withConnectionLock(async () => {
|
|
178
|
-
|
|
179
|
-
if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
|
|
180
|
-
throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
|
|
181
|
-
`cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
|
|
182
|
-
}
|
|
183
|
-
if (secondaryHost && !this.connectionParams.secondaryHost) {
|
|
184
|
-
this.connectionParams.secondaryHost = secondaryHost;
|
|
185
|
-
}
|
|
186
|
-
if (useTls !== undefined) {
|
|
187
|
-
this.connectionParams.useTls = useTls;
|
|
188
|
-
}
|
|
189
|
-
if (tls?.cert !== undefined) {
|
|
190
|
-
this.connectionParams.cert = tls.cert;
|
|
191
|
-
}
|
|
192
|
-
if (tls?.key !== undefined) {
|
|
193
|
-
this.connectionParams.key = tls.key;
|
|
194
|
-
}
|
|
195
|
-
if (tls?.ca !== undefined) {
|
|
196
|
-
this.connectionParams.ca = tls.ca;
|
|
197
|
-
}
|
|
198
|
-
if (tls?.rejectUnauthorized !== undefined) {
|
|
199
|
-
this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
else {
|
|
203
|
-
this.connectionParams = {
|
|
204
|
-
primaryHost: host,
|
|
205
|
-
secondaryHost,
|
|
206
|
-
port,
|
|
207
|
-
useTls,
|
|
208
|
-
cert: tls?.cert,
|
|
209
|
-
key: tls?.key,
|
|
210
|
-
ca: tls?.ca,
|
|
211
|
-
rejectUnauthorized: tls?.rejectUnauthorized,
|
|
212
|
-
};
|
|
213
|
-
}
|
|
204
|
+
this.reconcileConnectionParams(host, port, secondaryHost, useTls, tls);
|
|
214
205
|
this.knownUnits.add(unitId);
|
|
215
206
|
if (this.modbusInstances.has(unitId)) {
|
|
216
207
|
console.debug(`connect(): unit ${unitId} on ${host}:${port} already open, skipping`);
|
|
@@ -220,6 +211,74 @@ class SunspecModbusClient {
|
|
|
220
211
|
console.log(`Connected to Sunspec device at ${host}:${port} unit ${unitId} (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
|
|
221
212
|
});
|
|
222
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Fast-fail probe of a unit for speculative RS485-chain scans, where most candidate unit IDs
|
|
216
|
+
* are absent. On success the unit is opened and kept exactly as {@link connect} would; the
|
|
217
|
+
* difference is the FAILURE path: a probe does NOT retry the connect (unlike connect(), which
|
|
218
|
+
* honours {@link IModbusResilienceConfig.connectRetries}) and uses a caller-supplied, typically
|
|
219
|
+
* shorter, connect timeout. So scanning a range of mostly-dead units costs ~`timeoutMs` each
|
|
220
|
+
* instead of the full retrying connect budget — the reason a warm reconnect must never queue
|
|
221
|
+
* its meter/battery attach behind such a scan. Throws on failure; nothing is left open.
|
|
222
|
+
*/
|
|
223
|
+
async probeUnit(host, port = 502, unitId = 1, opts = {}) {
|
|
224
|
+
return this.withConnectionLock(async () => {
|
|
225
|
+
this.reconcileConnectionParams(host, port, opts.secondaryHost);
|
|
226
|
+
this.knownUnits.add(unitId);
|
|
227
|
+
if (this.modbusInstances.has(unitId)) {
|
|
228
|
+
console.debug(`probeUnit(): unit ${unitId} on ${host}:${port} already open, skipping`);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
await this._openUnit(host, port, unitId, {
|
|
232
|
+
connectRetries: 0,
|
|
233
|
+
connectTimeoutMs: opts.timeoutMs ?? this.resilience.connectTimeoutMs,
|
|
234
|
+
});
|
|
235
|
+
console.log(`Probed Sunspec unit ${unitId} at ${host}:${port} — open (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Reconcile/lock in this client's connection parameters. The first call binds the client to a
|
|
240
|
+
* single (host, port); later calls for a different endpoint throw (use one client per endpoint
|
|
241
|
+
* via {@link getOrCreateSunspecClient}). Optional secondaryHost/TLS material fills in on first
|
|
242
|
+
* sight without clobbering. Caller must hold the connection lock.
|
|
243
|
+
*/
|
|
244
|
+
reconcileConnectionParams(host, port, secondaryHost, useTls, tls) {
|
|
245
|
+
if (this.connectionParams) {
|
|
246
|
+
if (this.connectionParams.primaryHost !== host || this.connectionParams.port !== port) {
|
|
247
|
+
throw new Error(`SunspecModbusClient is bound to ${this.connectionParams.primaryHost}:${this.connectionParams.port}; ` +
|
|
248
|
+
`cannot reuse it for ${host}:${port}. Use getOrCreateSunspecClient() per (host, port).`);
|
|
249
|
+
}
|
|
250
|
+
if (secondaryHost && !this.connectionParams.secondaryHost) {
|
|
251
|
+
this.connectionParams.secondaryHost = secondaryHost;
|
|
252
|
+
}
|
|
253
|
+
if (useTls !== undefined) {
|
|
254
|
+
this.connectionParams.useTls = useTls;
|
|
255
|
+
}
|
|
256
|
+
if (tls?.cert !== undefined) {
|
|
257
|
+
this.connectionParams.cert = tls.cert;
|
|
258
|
+
}
|
|
259
|
+
if (tls?.key !== undefined) {
|
|
260
|
+
this.connectionParams.key = tls.key;
|
|
261
|
+
}
|
|
262
|
+
if (tls?.ca !== undefined) {
|
|
263
|
+
this.connectionParams.ca = tls.ca;
|
|
264
|
+
}
|
|
265
|
+
if (tls?.rejectUnauthorized !== undefined) {
|
|
266
|
+
this.connectionParams.rejectUnauthorized = tls.rejectUnauthorized;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
this.connectionParams = {
|
|
271
|
+
primaryHost: host,
|
|
272
|
+
secondaryHost,
|
|
273
|
+
port,
|
|
274
|
+
useTls,
|
|
275
|
+
cert: tls?.cert,
|
|
276
|
+
key: tls?.key,
|
|
277
|
+
ca: tls?.ca,
|
|
278
|
+
rejectUnauthorized: tls?.rejectUnauthorized,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
}
|
|
223
282
|
/**
|
|
224
283
|
* Disconnect from all units of this network device.
|
|
225
284
|
*
|
|
@@ -344,21 +403,42 @@ class SunspecModbusClient {
|
|
|
344
403
|
}
|
|
345
404
|
}
|
|
346
405
|
/**
|
|
347
|
-
* Open a
|
|
348
|
-
*
|
|
349
|
-
*
|
|
406
|
+
* Open a unit, retrying the connect on a transient failure per the resilience config
|
|
407
|
+
* ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
|
|
408
|
+
* — which independently bounds its connect at {@link IModbusResilienceConfig.connectTimeoutMs}
|
|
409
|
+
* and tears down any half-open candidate before rethrowing — so retries never leak a socket.
|
|
410
|
+
*
|
|
411
|
+
* `override` lets a caller tune this single open: {@link probeUnit} passes `connectRetries: 0`
|
|
412
|
+
* and a shorter `connectTimeoutMs` to fast-fail a speculative scan; omitted fields fall back to
|
|
413
|
+
* the client's resilience config.
|
|
414
|
+
*/
|
|
415
|
+
async _openUnit(host, port, unitId, override) {
|
|
416
|
+
const connectTimeoutMs = override?.connectTimeoutMs ?? this.resilience.connectTimeoutMs;
|
|
417
|
+
const attempts = (override?.connectRetries ?? this.resilience.connectRetries) + 1;
|
|
418
|
+
await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs), {
|
|
419
|
+
attempts,
|
|
420
|
+
delayMs: this.resilience.connectRetryDelayMs,
|
|
421
|
+
onRetry: (error, attempt) => console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} failed ` +
|
|
422
|
+
`(attempt ${attempt}/${attempts}): ${error instanceof Error ? error.message : String(error)}; ` +
|
|
423
|
+
`retrying in ${this.resilience.connectRetryDelayMs}ms`),
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
|
|
428
|
+
* connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
|
|
429
|
+
* we never leak. Caller must hold the connection lock and ensure the unit is not already open.
|
|
350
430
|
*/
|
|
351
|
-
async
|
|
431
|
+
async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
|
|
352
432
|
let candidate = null;
|
|
353
433
|
try {
|
|
354
434
|
// Enforce the connect budget ourselves in addition to forwarding it as the transport's
|
|
355
435
|
// `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
|
|
356
436
|
// can still leave the returned promise pending — bound it independently.
|
|
357
|
-
candidate = await this.withTimeout('connect', unitId,
|
|
437
|
+
candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
|
|
358
438
|
host,
|
|
359
439
|
port,
|
|
360
440
|
unitId,
|
|
361
|
-
timeout:
|
|
441
|
+
timeout: connectTimeoutMs,
|
|
362
442
|
useTls: this.connectionParams?.useTls,
|
|
363
443
|
cert: this.connectionParams?.cert,
|
|
364
444
|
key: this.connectionParams?.key,
|
|
@@ -501,6 +581,25 @@ class SunspecModbusClient {
|
|
|
501
581
|
this.poisonedUnits.add(unitId);
|
|
502
582
|
this.connectionHealth.recordFailure(error);
|
|
503
583
|
}
|
|
584
|
+
/**
|
|
585
|
+
* Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
|
|
586
|
+
* readData()/tryReconnect() cycle recycles it — the same effect as a timeout poison but
|
|
587
|
+
* for a caller-detected fault that isn't itself a Modbus timeout.
|
|
588
|
+
*
|
|
589
|
+
* The motivating case: a TCP reconnect succeeds but the follow-up model discovery comes
|
|
590
|
+
* back empty because the gateway (e.g. a SolarEdge unit) accepted the socket before it was
|
|
591
|
+
* ready to answer the SunSpec scan. The link looks alive, so without this the reconnect
|
|
592
|
+
* would be trusted, an empty model map cached, and every subsequent read would find no
|
|
593
|
+
* model while nothing ever triggers another reconnect. Poisoning here keeps the retry
|
|
594
|
+
* schedule firing until a real discovery lands. Idempotent; only logs on the first call.
|
|
595
|
+
*/
|
|
596
|
+
invalidateUnit(unitId, reason) {
|
|
597
|
+
if (!this.poisonedUnits.has(unitId)) {
|
|
598
|
+
console.warn(`SunspecModbusClient: invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
|
|
599
|
+
}
|
|
600
|
+
this.poisonedUnits.add(unitId);
|
|
601
|
+
this.connectionHealth.recordFailure(new Error(reason));
|
|
602
|
+
}
|
|
504
603
|
/**
|
|
505
604
|
* A unit's socket is stale when the transport still reports it connected but no successful
|
|
506
605
|
* transaction has completed within staleSocketMs — the signature of a half-open link where
|