@enyo-energy/sunspec-sdk 0.0.100 → 0.0.102
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 +486 -18
- package/dist/cjs/sunspec-devices.d.cts +144 -1
- package/dist/cjs/sunspec-interfaces.d.cts +81 -0
- package/dist/cjs/sunspec-modbus-client.cjs +172 -49
- package/dist/cjs/sunspec-modbus-client.d.cts +43 -1
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/sunspec-devices.d.ts +144 -1
- package/dist/sunspec-devices.js +484 -17
- package/dist/sunspec-interfaces.d.ts +81 -0
- package/dist/sunspec-modbus-client.d.ts +43 -1
- package/dist/sunspec-modbus-client.js +172 -49
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SunspecMeter = exports.SunspecBattery = exports.SunspecInverter = exports.BaseSunspecDevice = void 0;
|
|
3
|
+
exports.SunspecCustomDevice = exports.SunspecMeter = exports.SunspecBattery = exports.SunspecInverter = exports.BaseSunspecDevice = void 0;
|
|
4
4
|
exports.detectFeaturesFromRegisters = detectFeaturesFromRegisters;
|
|
5
5
|
exports.sumMpptBatteryPowerW = sumMpptBatteryPowerW;
|
|
6
6
|
exports.selectLiveBatteryPowerW = selectLiveBatteryPowerW;
|
|
@@ -156,9 +156,33 @@ class BaseSunspecDevice {
|
|
|
156
156
|
await this.sunspecClient.connect(this.networkDevice.hostname, // primary
|
|
157
157
|
this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
|
|
158
158
|
this.useTls);
|
|
159
|
-
await this.
|
|
159
|
+
await this.discoverAfterConnect();
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
|
+
/**
|
|
163
|
+
* Populate the per-unit model directory after the socket opens. Default: run SunSpec model
|
|
164
|
+
* discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
|
|
165
|
+
* directory (see {@link SunspecCustomDevice}) override this to a no-op.
|
|
166
|
+
*/
|
|
167
|
+
async discoverAfterConnect() {
|
|
168
|
+
await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Validate that a just-completed reconnect actually restored a usable device. Default: re-run
|
|
172
|
+
* SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
|
|
173
|
+
* back with no usable models means the gateway accepted the connection before it was ready to
|
|
174
|
+
* answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
|
|
175
|
+
* running. Discovery-less devices override this to just confirm the socket is open.
|
|
176
|
+
*/
|
|
177
|
+
async revalidateAfterReconnect() {
|
|
178
|
+
const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
|
|
179
|
+
const usable = this.isDiscoveryUsable(models);
|
|
180
|
+
if (!usable) {
|
|
181
|
+
console.warn(`${this.constructor.name} ${this.applianceId}: reconnect discovery returned no usable models ` +
|
|
182
|
+
`(found [${[...models.keys()].join(', ')}])`);
|
|
183
|
+
}
|
|
184
|
+
return usable;
|
|
185
|
+
}
|
|
162
186
|
/**
|
|
163
187
|
* Attempt a reconnection if the tiered retry schedule allows it.
|
|
164
188
|
* Called from readData() when the device is disconnected.
|
|
@@ -183,8 +207,24 @@ class BaseSunspecDevice {
|
|
|
183
207
|
// device's poll loop detects a dropped connection.
|
|
184
208
|
const success = await this.sunspecClient.reconnectUnit(this.unitId);
|
|
185
209
|
if (success) {
|
|
186
|
-
// Re-discover models for this unit after reconnect
|
|
187
|
-
|
|
210
|
+
// Re-discover models for this unit after reconnect. discoverModels() clears
|
|
211
|
+
// and repopulates the per-unit model map, so a reconnect that opens the TCP
|
|
212
|
+
// socket but comes back with no usable models (a gateway that accepted the
|
|
213
|
+
// connection before it was ready to answer the SunSpec scan) would leave the
|
|
214
|
+
// map empty. Trusting that would cache an empty map — every read then finds no
|
|
215
|
+
// model while the socket looks healthy, and because reset() disables retry,
|
|
216
|
+
// nothing ever triggers another reconnect. So validate discovery here and, when
|
|
217
|
+
// it's unusable, treat this as a failed reconnect: invalidate the socket so the
|
|
218
|
+
// next poll re-enters tryReconnect(), keep the backoff schedule running, and do
|
|
219
|
+
// NOT reset().
|
|
220
|
+
if (!(await this.revalidateAfterReconnect())) {
|
|
221
|
+
this.sunspecClient.invalidateUnit(this.unitId, `reconnect revalidation failed for unit ${this.unitId}`);
|
|
222
|
+
this.consecutiveReconnectFailures += 1;
|
|
223
|
+
await this.onConnectionFailure(this.consecutiveReconnectFailures);
|
|
224
|
+
console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
|
|
225
|
+
`opened the socket but revalidation failed — retrying with backoff`);
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
188
228
|
this.retryManager.reset();
|
|
189
229
|
this.consecutiveReconnectFailures = 0;
|
|
190
230
|
// Update appliance state to Connected
|
|
@@ -207,6 +247,42 @@ class BaseSunspecDevice {
|
|
|
207
247
|
}
|
|
208
248
|
return false;
|
|
209
249
|
}
|
|
250
|
+
/**
|
|
251
|
+
* Model IDs this device needs to produce a reading; presence of ANY one means a
|
|
252
|
+
* discovery is usable (one-of semantics — devices expose mutually-exclusive
|
|
253
|
+
* encoding/phase variants, e.g. int+SF vs float, single- vs three-phase). Empty
|
|
254
|
+
* (the base default) means no specific requirement, so any model present
|
|
255
|
+
* suffices. Concrete devices override with their acceptable set — this is the
|
|
256
|
+
* single per-device source of truth reused by both the reconnect discovery gate
|
|
257
|
+
* ({@link isDiscoveryUsable}) and the connect-time presence gate
|
|
258
|
+
* ({@link hasRequiredModels}).
|
|
259
|
+
*/
|
|
260
|
+
getRequiredModelIds() {
|
|
261
|
+
return [];
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* True if the current per-unit discovered-model map satisfies this device's
|
|
265
|
+
* requirement. The connect-time twin of {@link isDiscoveryUsable}: it inspects
|
|
266
|
+
* the already-populated map via findModel() rather than a freshly-returned one.
|
|
267
|
+
* Only meaningful for devices that declare a non-empty required set.
|
|
268
|
+
*/
|
|
269
|
+
hasRequiredModels() {
|
|
270
|
+
return this.getRequiredModelIds().some(id => this.sunspecClient.findModel(this.unitId, id) !== undefined);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Decide whether a post-reconnect model discovery is usable. A reconnect that
|
|
274
|
+
* establishes the TCP socket but comes back empty (or with only a Common block)
|
|
275
|
+
* means the device accepted the connection before it was ready to answer the
|
|
276
|
+
* SunSpec scan; the discovered-model map is now missing this device's data
|
|
277
|
+
* model, so trusting the reconnect would leave every read finding no model.
|
|
278
|
+
* Validated generically against {@link getRequiredModelIds}: with a declared
|
|
279
|
+
* set, at least one of those ids must be present; with none declared, fall back
|
|
280
|
+
* to "any model present".
|
|
281
|
+
*/
|
|
282
|
+
isDiscoveryUsable(models) {
|
|
283
|
+
const required = this.getRequiredModelIds();
|
|
284
|
+
return required.length === 0 ? models.size > 0 : required.some(id => models.has(id));
|
|
285
|
+
}
|
|
210
286
|
/**
|
|
211
287
|
* Hook for subclasses to react to a failed reconnect attempt. Called once
|
|
212
288
|
* per failed attempt with the running consecutive-failure count.
|
|
@@ -364,6 +440,19 @@ class SunspecInverter extends BaseSunspecDevice {
|
|
|
364
440
|
pvPowerSource;
|
|
365
441
|
/** Emit a connection-lost faulted status after this many consecutive failed reconnect attempts. */
|
|
366
442
|
static CONNECTION_FAULT_THRESHOLD = 3;
|
|
443
|
+
/**
|
|
444
|
+
* The inverter data models this device can read (int+SF 101/103 and IEEE-754
|
|
445
|
+
* float 111/112/113). A post-reconnect discovery that finds none of these has
|
|
446
|
+
* not really recovered the inverter, so {@link isDiscoveryUsable} rejects it —
|
|
447
|
+
* see the override below.
|
|
448
|
+
*/
|
|
449
|
+
static INVERTER_MODEL_IDS = [
|
|
450
|
+
sunspec_interfaces_js_1.SunspecModelId.InverterSinglePhase,
|
|
451
|
+
sunspec_interfaces_js_1.SunspecModelId.Inverter3Phase,
|
|
452
|
+
sunspec_interfaces_js_1.SunspecModelId.InverterSinglePhaseFloat,
|
|
453
|
+
sunspec_interfaces_js_1.SunspecModelId.InverterSplitPhaseFloat,
|
|
454
|
+
sunspec_interfaces_js_1.SunspecModelId.Inverter3PhaseFloat
|
|
455
|
+
];
|
|
367
456
|
/**
|
|
368
457
|
* Require this many consecutive operatingState=7 (FAULT) reads before
|
|
369
458
|
* reporting Faulted. Debounces transient single-poll FAULT reads (e.g. a
|
|
@@ -746,6 +835,16 @@ class SunspecInverter extends BaseSunspecDevice {
|
|
|
746
835
|
lastStatus: newLastStatus,
|
|
747
836
|
};
|
|
748
837
|
}
|
|
838
|
+
/**
|
|
839
|
+
* A reconnect has only recovered the inverter if discovery finds one of its
|
|
840
|
+
* data models. An SE gateway can accept the new socket and answer a partial
|
|
841
|
+
* scan (e.g. only the Common block) before the inverter map is ready — the
|
|
842
|
+
* base size>0 rule would accept that, but every inverter read would then find
|
|
843
|
+
* no 101/103/111/112/113 model and report 0 W. Require an actual inverter model.
|
|
844
|
+
*/
|
|
845
|
+
getRequiredModelIds() {
|
|
846
|
+
return SunspecInverter.INVERTER_MODEL_IDS;
|
|
847
|
+
}
|
|
749
848
|
async onConnectionFailure(consecutiveFailures) {
|
|
750
849
|
if (!this.applianceId || !this.dataBus)
|
|
751
850
|
return;
|
|
@@ -1295,6 +1394,16 @@ function filterFeaturesByCalibrationResult(detected, result, controllable) {
|
|
|
1295
1394
|
class SunspecBattery extends BaseSunspecDevice {
|
|
1296
1395
|
featureMode;
|
|
1297
1396
|
capabilities;
|
|
1397
|
+
/**
|
|
1398
|
+
* Battery data models this device can read: Battery (124, full decode) and
|
|
1399
|
+
* BatteryBase (802, derived decode). BatteryControl (803) is intentionally
|
|
1400
|
+
* excluded — it is a decode stub that yields no telemetry — so a rediscovery
|
|
1401
|
+
* that returns only 803 is treated as unrecovered, matching the connect() gate.
|
|
1402
|
+
*/
|
|
1403
|
+
static BATTERY_MODEL_IDS = [
|
|
1404
|
+
sunspec_interfaces_js_1.SunspecModelId.Battery,
|
|
1405
|
+
sunspec_interfaces_js_1.SunspecModelId.BatteryBase
|
|
1406
|
+
];
|
|
1298
1407
|
snapshotService;
|
|
1299
1408
|
calibrationDriver;
|
|
1300
1409
|
batteryCalibrator;
|
|
@@ -1398,16 +1507,17 @@ class SunspecBattery extends BaseSunspecDevice {
|
|
|
1398
1507
|
getBatteryCalibrator() {
|
|
1399
1508
|
return this.batteryCalibrator;
|
|
1400
1509
|
}
|
|
1510
|
+
getRequiredModelIds() {
|
|
1511
|
+
return SunspecBattery.BATTERY_MODEL_IDS;
|
|
1512
|
+
}
|
|
1401
1513
|
/**
|
|
1402
1514
|
* Connect to the battery and create/update the appliance
|
|
1403
1515
|
*/
|
|
1404
1516
|
async connect(inverterApplianceId) {
|
|
1405
1517
|
// Ensure Sunspec client is connected
|
|
1406
1518
|
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) {
|
|
1519
|
+
// Check if battery models exist (124 or 802 — see BATTERY_MODEL_IDS).
|
|
1520
|
+
if (!this.hasRequiredModels()) {
|
|
1411
1521
|
throw new Error('No battery model found in device');
|
|
1412
1522
|
}
|
|
1413
1523
|
// Get device info
|
|
@@ -1983,6 +2093,20 @@ exports.SunspecBattery = SunspecBattery;
|
|
|
1983
2093
|
*/
|
|
1984
2094
|
class SunspecMeter extends BaseSunspecDevice {
|
|
1985
2095
|
capabilities;
|
|
2096
|
+
/**
|
|
2097
|
+
* Meter data models this device can read, across int+SF (201/203/204) and
|
|
2098
|
+
* IEEE-754 float (211/212/213/214) encodings and single/split/three-phase
|
|
2099
|
+
* variants. Used when the meter is not bound to a specific instance.
|
|
2100
|
+
*/
|
|
2101
|
+
static METER_MODEL_IDS = [
|
|
2102
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhase,
|
|
2103
|
+
sunspec_interfaces_js_1.SunspecModelId.Meter3Phase,
|
|
2104
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterWye,
|
|
2105
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterSinglePhaseFloat,
|
|
2106
|
+
sunspec_interfaces_js_1.SunspecModelId.MeterSplitPhaseFloat,
|
|
2107
|
+
sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseWyeFloat,
|
|
2108
|
+
sunspec_interfaces_js_1.SunspecModelId.Meter3PhaseDeltaFloat
|
|
2109
|
+
];
|
|
1986
2110
|
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId = 1, port = 502, baseAddress = 40000, capabilities = [], retryConfig, appliance, useTls) {
|
|
1987
2111
|
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
1988
2112
|
this.capabilities = capabilities;
|
|
@@ -2001,22 +2125,23 @@ class SunspecMeter extends BaseSunspecDevice {
|
|
|
2001
2125
|
bindMeterModel(model) {
|
|
2002
2126
|
this.meterModel = model;
|
|
2003
2127
|
}
|
|
2128
|
+
/**
|
|
2129
|
+
* A bound meter requires ITS own pinned model id to reappear after a
|
|
2130
|
+
* rediscovery; an unbound meter accepts any meter model on its unit.
|
|
2131
|
+
*/
|
|
2132
|
+
getRequiredModelIds() {
|
|
2133
|
+
return this.meterModel ? [this.meterModel.id] : SunspecMeter.METER_MODEL_IDS;
|
|
2134
|
+
}
|
|
2004
2135
|
/**
|
|
2005
2136
|
* Connect to the meter and create/update the appliance
|
|
2006
2137
|
*/
|
|
2007
2138
|
async connect() {
|
|
2008
2139
|
// Connect with specific unit ID for meter
|
|
2009
2140
|
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) {
|
|
2141
|
+
// Check if meter models exist (int+SF: 201/203/204, float: 211/212/213/214).
|
|
2142
|
+
// A bound meter short-circuits: getRequiredModelIds() returns [meterModel.id],
|
|
2143
|
+
// which the just-completed discovery re-listed for the same physical device.
|
|
2144
|
+
if (!this.hasRequiredModels()) {
|
|
2020
2145
|
throw new Error('No meter model found in device');
|
|
2021
2146
|
}
|
|
2022
2147
|
// Get device info. For a bound meter instance, read ITS own Common block (the one
|
|
@@ -2139,3 +2264,346 @@ class SunspecMeter extends BaseSunspecDevice {
|
|
|
2139
2264
|
}
|
|
2140
2265
|
}
|
|
2141
2266
|
exports.SunspecMeter = SunspecMeter;
|
|
2267
|
+
/** Appliance type created for each custom-device role (battery emulates a Storage appliance). */
|
|
2268
|
+
const CUSTOM_ROLE_APPLIANCE_TYPE = {
|
|
2269
|
+
meter: enyo_appliance_js_1.EnyoApplianceTypeEnum.Meter,
|
|
2270
|
+
inverter: enyo_appliance_js_1.EnyoApplianceTypeEnum.Inverter,
|
|
2271
|
+
battery: enyo_appliance_js_1.EnyoApplianceTypeEnum.Storage,
|
|
2272
|
+
};
|
|
2273
|
+
/** Natural register width per data type, used when a register omits an explicit `quantity`. */
|
|
2274
|
+
const CUSTOM_REGISTER_DEFAULT_QUANTITY = {
|
|
2275
|
+
uint16: 1,
|
|
2276
|
+
int16: 1,
|
|
2277
|
+
acc16: 1,
|
|
2278
|
+
uint32: 2,
|
|
2279
|
+
int32: 2,
|
|
2280
|
+
acc32: 2,
|
|
2281
|
+
float32: 2,
|
|
2282
|
+
string: 1,
|
|
2283
|
+
};
|
|
2284
|
+
/** Numeric databus fields a `meter`-role custom device may populate. */
|
|
2285
|
+
const CUSTOM_METER_FIELDS = [
|
|
2286
|
+
'gridPowerW', 'gridPowerPhase1W', 'gridPowerPhase2W', 'gridPowerPhase3W',
|
|
2287
|
+
'gridFeedInWh', 'gridConsumptionWh', 'selfConsumptionW', 'selfConsumptionWh',
|
|
2288
|
+
];
|
|
2289
|
+
/** Numeric databus fields an `inverter`-role custom device may populate. */
|
|
2290
|
+
const CUSTOM_INVERTER_FIELDS = [
|
|
2291
|
+
'pvPowerW', 'voltageL1', 'voltageL2', 'voltageL3',
|
|
2292
|
+
'currentL1', 'currentL2', 'currentL3', 'dcPowerW',
|
|
2293
|
+
'activePowerLimitationW', 'meterValueWh',
|
|
2294
|
+
];
|
|
2295
|
+
/** Numeric databus fields a `battery`-role custom device may populate. */
|
|
2296
|
+
const CUSTOM_BATTERY_FIELDS = [
|
|
2297
|
+
'batterySoC', 'batteryPowerW', 'dcStringInputPowerW',
|
|
2298
|
+
];
|
|
2299
|
+
/** Default {@link SunspecCustomDeviceConfig.blockSize}: the Modbus FC03/FC04 per-read limit. */
|
|
2300
|
+
const CUSTOM_DEFAULT_BLOCK_SIZE = 125;
|
|
2301
|
+
/**
|
|
2302
|
+
* A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
|
|
2303
|
+
* SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
|
|
2304
|
+
* {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
|
|
2305
|
+
* per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
|
|
2306
|
+
* instead of a discovered SunSpec model directory.
|
|
2307
|
+
*
|
|
2308
|
+
* It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
|
|
2309
|
+
* the role selects the appliance type created on connect and which EnyoDataBus values message
|
|
2310
|
+
* {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
|
|
2311
|
+
* that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
|
|
2312
|
+
*
|
|
2313
|
+
* Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
|
|
2314
|
+
* validated by socket liveness rather than a SunSpec scan.
|
|
2315
|
+
*/
|
|
2316
|
+
class SunspecCustomDevice extends BaseSunspecDevice {
|
|
2317
|
+
config;
|
|
2318
|
+
/** Read plan derived once from the static register map (see {@link planBlocks}). */
|
|
2319
|
+
plannedBlocks;
|
|
2320
|
+
constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, config, unitId = 1, port = 502, baseAddress = 40000, retryConfig, appliance, useTls) {
|
|
2321
|
+
super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
|
|
2322
|
+
this.config = config;
|
|
2323
|
+
}
|
|
2324
|
+
/**
|
|
2325
|
+
* No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
|
|
2326
|
+
* the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
|
|
2327
|
+
* socket without a SunS scan.
|
|
2328
|
+
*/
|
|
2329
|
+
async discoverAfterConnect() {
|
|
2330
|
+
// Intentionally empty: plain-Modbus device, no SunSpec discovery.
|
|
2331
|
+
}
|
|
2332
|
+
/**
|
|
2333
|
+
* A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
|
|
2334
|
+
* Without this override the base default would run SunSpec discovery, find nothing, and treat every
|
|
2335
|
+
* reconnect as a permanent failure.
|
|
2336
|
+
*/
|
|
2337
|
+
async revalidateAfterReconnect() {
|
|
2338
|
+
return this.sunspecClient.isConnected(this.unitId);
|
|
2339
|
+
}
|
|
2340
|
+
/**
|
|
2341
|
+
* Connect the underlying socket (no discovery) and create/update the appliance for the configured
|
|
2342
|
+
* role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
|
|
2343
|
+
* SunSpec Common block to read it from.
|
|
2344
|
+
*/
|
|
2345
|
+
async connect() {
|
|
2346
|
+
if (!this.sunspecClient.isConnected(this.unitId)) {
|
|
2347
|
+
await this.sunspecClient.connect(this.networkDevice.hostname, // primary
|
|
2348
|
+
this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
|
|
2349
|
+
this.useTls);
|
|
2350
|
+
// No discoverModels(): this device reads a pre-defined static register map.
|
|
2351
|
+
}
|
|
2352
|
+
const applianceType = CUSTOM_ROLE_APPLIANCE_TYPE[this.config.role];
|
|
2353
|
+
if (!this.applianceId) {
|
|
2354
|
+
try {
|
|
2355
|
+
this.applianceId = await this.applianceManager.createOrUpdateAppliance({
|
|
2356
|
+
name: this.name,
|
|
2357
|
+
type: applianceType,
|
|
2358
|
+
networkDevices: [this.networkDevice],
|
|
2359
|
+
metadata: {
|
|
2360
|
+
connectionType: enyo_appliance_js_1.EnyoApplianceConnectionType.Connector,
|
|
2361
|
+
state: enyo_appliance_js_1.EnyoApplianceStateEnum.Connected,
|
|
2362
|
+
serialNumber: this.config.identity?.serialNumber,
|
|
2363
|
+
modelName: this.config.identity?.modelName,
|
|
2364
|
+
vendorName: this.config.identity?.vendorName,
|
|
2365
|
+
modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
|
|
2366
|
+
},
|
|
2367
|
+
});
|
|
2368
|
+
console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
|
|
2369
|
+
}
|
|
2370
|
+
catch (error) {
|
|
2371
|
+
console.error(`Failed to create custom ${this.config.role} appliance: ${error}`);
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
else {
|
|
2375
|
+
try {
|
|
2376
|
+
const existingAppliance = await this.applianceManager.findApplianceById(this.applianceId);
|
|
2377
|
+
await this.applianceManager.updateAppliance(this.applianceId, {
|
|
2378
|
+
metadata: {
|
|
2379
|
+
...existingAppliance?.metadata,
|
|
2380
|
+
connectionType: enyo_appliance_js_1.EnyoApplianceConnectionType.Connector,
|
|
2381
|
+
state: enyo_appliance_js_1.EnyoApplianceStateEnum.Connected,
|
|
2382
|
+
modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
|
|
2383
|
+
}
|
|
2384
|
+
});
|
|
2385
|
+
console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
|
|
2386
|
+
}
|
|
2387
|
+
catch (error) {
|
|
2388
|
+
console.error(`Failed to update custom ${this.config.role} appliance: ${error}`);
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
async disconnect() {
|
|
2393
|
+
if (this.applianceId) {
|
|
2394
|
+
try {
|
|
2395
|
+
await this.applianceManager.updateApplianceState(this.applianceId, enyo_appliance_js_1.EnyoApplianceConnectionType.Connector, enyo_appliance_js_1.EnyoApplianceStateEnum.Offline);
|
|
2396
|
+
}
|
|
2397
|
+
catch (error) {
|
|
2398
|
+
console.error(`Failed to mark custom ${this.config.role} offline on disconnect: ${error}`);
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
// Close just this device's unit; siblings on the same network device stay open.
|
|
2402
|
+
await this.sunspecClient.disconnectUnit(this.unitId);
|
|
2403
|
+
}
|
|
2404
|
+
async readData(clockId, resolution) {
|
|
2405
|
+
if (!this.isConnected()) {
|
|
2406
|
+
await this.tryReconnect();
|
|
2407
|
+
if (!this.isConnected())
|
|
2408
|
+
return [];
|
|
2409
|
+
}
|
|
2410
|
+
const messages = [];
|
|
2411
|
+
const timestamp = new Date();
|
|
2412
|
+
try {
|
|
2413
|
+
const values = await this.readConfiguredRegisters();
|
|
2414
|
+
// readRegisterValue throws on a failed read (unlike the SunSpec model readers), so a dead
|
|
2415
|
+
// socket lands in catch below. This also covers the health-counter path when the transport
|
|
2416
|
+
// records failures without throwing.
|
|
2417
|
+
if (await this.markOfflineIfUnhealthy()) {
|
|
2418
|
+
return messages;
|
|
2419
|
+
}
|
|
2420
|
+
// Healthy read: if a sibling on the same shared socket reconnected us, flip our appliance
|
|
2421
|
+
// state back to Connected. No-op unless this device is still marked offline.
|
|
2422
|
+
await this.reassertConnectedIfRecovered();
|
|
2423
|
+
messages.push(this.buildRoleMessage(values, clockId, resolution, timestamp));
|
|
2424
|
+
this.lastUpdateTime = timestamp.getTime();
|
|
2425
|
+
}
|
|
2426
|
+
catch (error) {
|
|
2427
|
+
console.error(`Error updating custom ${this.config.role} data: ${error}`);
|
|
2428
|
+
await this.markOffline();
|
|
2429
|
+
}
|
|
2430
|
+
return messages;
|
|
2431
|
+
}
|
|
2432
|
+
/**
|
|
2433
|
+
* Write a value to a pre-configured writable register. Delegates to the client's resilient
|
|
2434
|
+
* {@link SunspecModbusClient.writeRegisterValue}.
|
|
2435
|
+
*/
|
|
2436
|
+
async writeCustomRegister(name, value) {
|
|
2437
|
+
const reg = this.config.writeRegisters?.find(r => r.name === name);
|
|
2438
|
+
if (!reg) {
|
|
2439
|
+
throw new Error(`No writable register named '${name}' configured for custom ${this.config.role}`);
|
|
2440
|
+
}
|
|
2441
|
+
return this.sunspecClient.writeRegisterValue(this.unitId, reg.address, value, reg.dataType);
|
|
2442
|
+
}
|
|
2443
|
+
/**
|
|
2444
|
+
* Read every configured register as a small number of block reads and extract each register from
|
|
2445
|
+
* its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
|
|
2446
|
+
* scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
|
|
2447
|
+
* populate a numeric databus field) are skipped with a warning.
|
|
2448
|
+
*/
|
|
2449
|
+
async readConfiguredRegisters() {
|
|
2450
|
+
const values = new Map();
|
|
2451
|
+
for (const block of this.getPlannedBlocks()) {
|
|
2452
|
+
const buffer = await this.sunspecClient.readRegisterBlock(this.unitId, block.startAddress, block.length, block.useInputRegisters);
|
|
2453
|
+
for (const member of block.members) {
|
|
2454
|
+
const raw = this.sunspecClient.decodeBlockValue(buffer, member.offset, member.dataType, member.quantity);
|
|
2455
|
+
if (typeof raw !== 'number') {
|
|
2456
|
+
console.warn(`Custom ${this.config.role}: register '${member.field}' returned a non-numeric value; skipping`);
|
|
2457
|
+
continue;
|
|
2458
|
+
}
|
|
2459
|
+
values.set(member.field, raw * Math.pow(10, member.scaleFactor));
|
|
2460
|
+
}
|
|
2461
|
+
}
|
|
2462
|
+
return values;
|
|
2463
|
+
}
|
|
2464
|
+
/** Lazily compute and cache the block read plan; the register map is static per device. */
|
|
2465
|
+
getPlannedBlocks() {
|
|
2466
|
+
if (!this.plannedBlocks) {
|
|
2467
|
+
this.plannedBlocks = this.planBlocks();
|
|
2468
|
+
}
|
|
2469
|
+
return this.plannedBlocks;
|
|
2470
|
+
}
|
|
2471
|
+
/**
|
|
2472
|
+
* Group the configured registers (separately per function code) sorted by address, coalescing them
|
|
2473
|
+
* — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
|
|
2474
|
+
* starts whenever adding the next register would exceed that span. Each block records its members'
|
|
2475
|
+
* offsets so a single read can be sliced into all of them.
|
|
2476
|
+
*/
|
|
2477
|
+
planBlocks() {
|
|
2478
|
+
const blockSize = Math.max(1, this.config.blockSize ?? CUSTOM_DEFAULT_BLOCK_SIZE);
|
|
2479
|
+
const blocks = [];
|
|
2480
|
+
// Group by function code so FC03 and FC04 registers never share a block.
|
|
2481
|
+
const groups = new Map();
|
|
2482
|
+
for (const reg of this.config.registers) {
|
|
2483
|
+
const useInputRegisters = reg.functionCode === 4;
|
|
2484
|
+
const list = groups.get(useInputRegisters);
|
|
2485
|
+
if (list) {
|
|
2486
|
+
list.push(reg);
|
|
2487
|
+
}
|
|
2488
|
+
else {
|
|
2489
|
+
groups.set(useInputRegisters, [reg]);
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
for (const [useInputRegisters, regs] of groups) {
|
|
2493
|
+
const spans = regs
|
|
2494
|
+
.map(reg => {
|
|
2495
|
+
const quantity = reg.quantity ?? CUSTOM_REGISTER_DEFAULT_QUANTITY[reg.dataType];
|
|
2496
|
+
return { reg, quantity, start: reg.address, end: reg.address + quantity };
|
|
2497
|
+
})
|
|
2498
|
+
.sort((a, b) => a.start - b.start);
|
|
2499
|
+
let current;
|
|
2500
|
+
let currentEnd = 0;
|
|
2501
|
+
for (const span of spans) {
|
|
2502
|
+
const member = (offset) => ({
|
|
2503
|
+
field: span.reg.field,
|
|
2504
|
+
dataType: span.reg.dataType,
|
|
2505
|
+
quantity: span.quantity,
|
|
2506
|
+
offset,
|
|
2507
|
+
scaleFactor: span.reg.scaleFactor ?? 0,
|
|
2508
|
+
});
|
|
2509
|
+
// Extend the current block only if the whole span (start .. farthest end) still fits
|
|
2510
|
+
// within blockSize. The first register always opens a block (a lone register wider than
|
|
2511
|
+
// blockSize is still read — readRegisterBlock chunks it).
|
|
2512
|
+
const mergedEnd = current ? Math.max(currentEnd, span.end) : span.end;
|
|
2513
|
+
if (current && mergedEnd - current.startAddress <= blockSize) {
|
|
2514
|
+
current.members.push(member(span.start - current.startAddress));
|
|
2515
|
+
currentEnd = mergedEnd;
|
|
2516
|
+
current.length = currentEnd - current.startAddress;
|
|
2517
|
+
}
|
|
2518
|
+
else {
|
|
2519
|
+
current = {
|
|
2520
|
+
useInputRegisters,
|
|
2521
|
+
startAddress: span.start,
|
|
2522
|
+
length: span.end - span.start,
|
|
2523
|
+
members: [member(0)],
|
|
2524
|
+
};
|
|
2525
|
+
currentEnd = span.end;
|
|
2526
|
+
blocks.push(current);
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
return blocks;
|
|
2531
|
+
}
|
|
2532
|
+
buildRoleMessage(values, clockId, resolution, timestamp) {
|
|
2533
|
+
switch (this.config.role) {
|
|
2534
|
+
case 'meter':
|
|
2535
|
+
return this.buildMeterMessage(values, clockId, resolution, timestamp);
|
|
2536
|
+
case 'inverter':
|
|
2537
|
+
return this.buildInverterMessage(values, clockId, resolution, timestamp);
|
|
2538
|
+
case 'battery':
|
|
2539
|
+
return this.buildBatteryMessage(values, clockId, resolution, timestamp);
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
buildMeterMessage(values, clockId, resolution, timestamp) {
|
|
2543
|
+
const data = { gridFeedInWh: 0, gridConsumptionWh: 0 };
|
|
2544
|
+
for (const field of CUSTOM_METER_FIELDS) {
|
|
2545
|
+
const v = values.get(field);
|
|
2546
|
+
if (v !== undefined) {
|
|
2547
|
+
data[field] = v;
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
return {
|
|
2551
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
2552
|
+
message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.MeterValuesUpdateV1,
|
|
2553
|
+
type: 'message',
|
|
2554
|
+
source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
|
|
2555
|
+
applianceId: this.applianceId,
|
|
2556
|
+
clockId,
|
|
2557
|
+
timestampIso: timestamp.toISOString(),
|
|
2558
|
+
resolution,
|
|
2559
|
+
data,
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2562
|
+
buildInverterMessage(values, clockId, resolution, timestamp) {
|
|
2563
|
+
const data = { pvPowerW: 0, voltageL1: 0 };
|
|
2564
|
+
for (const field of CUSTOM_INVERTER_FIELDS) {
|
|
2565
|
+
const v = values.get(field);
|
|
2566
|
+
if (v !== undefined) {
|
|
2567
|
+
data[field] = v;
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
if (this.config.defaultInverterState !== undefined) {
|
|
2571
|
+
data.state = this.config.defaultInverterState;
|
|
2572
|
+
}
|
|
2573
|
+
return {
|
|
2574
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
2575
|
+
message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.InverterValuesUpdateV1,
|
|
2576
|
+
type: 'message',
|
|
2577
|
+
source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
|
|
2578
|
+
applianceId: this.applianceId,
|
|
2579
|
+
clockId,
|
|
2580
|
+
timestampIso: timestamp.toISOString(),
|
|
2581
|
+
resolution,
|
|
2582
|
+
data,
|
|
2583
|
+
};
|
|
2584
|
+
}
|
|
2585
|
+
buildBatteryMessage(values, clockId, resolution, timestamp) {
|
|
2586
|
+
const data = { batterySoC: 0 };
|
|
2587
|
+
for (const field of CUSTOM_BATTERY_FIELDS) {
|
|
2588
|
+
const v = values.get(field);
|
|
2589
|
+
if (v !== undefined) {
|
|
2590
|
+
data[field] = v;
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
if (this.config.defaultBatteryState !== undefined) {
|
|
2594
|
+
data.state = this.config.defaultBatteryState;
|
|
2595
|
+
}
|
|
2596
|
+
return {
|
|
2597
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
2598
|
+
message: enyo_data_bus_value_js_1.EnyoDataBusMessageEnum.BatteryValuesUpdateV1,
|
|
2599
|
+
type: 'message',
|
|
2600
|
+
source: enyo_source_enum_js_1.EnyoSourceEnum.Device,
|
|
2601
|
+
applianceId: this.applianceId,
|
|
2602
|
+
clockId,
|
|
2603
|
+
timestampIso: timestamp.toISOString(),
|
|
2604
|
+
resolution,
|
|
2605
|
+
data,
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
}
|
|
2609
|
+
exports.SunspecCustomDevice = SunspecCustomDevice;
|