@enyo-energy/sunspec-sdk 0.0.101 → 0.0.103
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 +418 -10
- package/dist/cjs/sunspec-devices.d.cts +108 -3
- package/dist/cjs/sunspec-interfaces.d.cts +81 -0
- package/dist/cjs/sunspec-modbus-client.cjs +198 -54
- package/dist/cjs/sunspec-modbus-client.d.cts +47 -1
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/sunspec-devices.d.ts +108 -3
- package/dist/sunspec-devices.js +416 -9
- package/dist/sunspec-interfaces.d.ts +81 -0
- package/dist/sunspec-modbus-client.d.ts +47 -1
- package/dist/sunspec-modbus-client.js +198 -54
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -3
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { EnyoBatteryFeature } from "@enyo-energy/energy-app-sdk/dist/types/enyo-battery-appliance.js";
|
|
5
5
|
import { EnyoBatteryStateEnum, EnyoDataBusInverterValuesV1String, EnyoInverterStateEnum } from "@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js";
|
|
6
|
+
import { EnergyAppModbusDataType } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
|
|
6
7
|
/**
|
|
7
8
|
* A single phase in the tiered retry schedule
|
|
8
9
|
*/
|
|
@@ -98,6 +99,86 @@ export interface IModbusResilienceConfig {
|
|
|
98
99
|
connectRetryDelayMs?: number;
|
|
99
100
|
}
|
|
100
101
|
export declare const DEFAULT_MODBUS_RESILIENCE_CONFIG: Required<IModbusResilienceConfig>;
|
|
102
|
+
/**
|
|
103
|
+
* The appliance role a {@link SunspecCustomDeviceConfig} emulates. Selects the appliance type created
|
|
104
|
+
* on connect and which EnyoDataBus values message {@link SunspecCustomDevice.readData} publishes.
|
|
105
|
+
*/
|
|
106
|
+
export type SunspecCustomDeviceRole = 'meter' | 'inverter' | 'battery';
|
|
107
|
+
/**
|
|
108
|
+
* A single pre-defined register a {@link SunspecCustomDevice} reads each poll. Unlike the SunSpec
|
|
109
|
+
* model readers, there is no discovery, scale-factor register, or NOT_IMPLEMENTED sentinel handling:
|
|
110
|
+
* the caller supplies the exact address, type and (optional) fixed scaling for a plain-Modbus device.
|
|
111
|
+
*/
|
|
112
|
+
export interface SunspecCustomRegister {
|
|
113
|
+
/**
|
|
114
|
+
* The databus data-field this register populates for the configured role (e.g. `gridPowerW` for a
|
|
115
|
+
* meter, `pvPowerW` for an inverter, `batterySoC` for a battery). Validated against the role's
|
|
116
|
+
* numeric field set at read time; unknown fields are ignored with a warning.
|
|
117
|
+
*/
|
|
118
|
+
field: string;
|
|
119
|
+
/** Modbus register address (absolute). */
|
|
120
|
+
address: number;
|
|
121
|
+
/** How to decode the raw registers. */
|
|
122
|
+
dataType: EnergyAppModbusDataType;
|
|
123
|
+
/** Registers to read. Defaults to the natural width of {@link dataType} (1 for 16-bit, 2 for 32-bit). */
|
|
124
|
+
quantity?: number;
|
|
125
|
+
/** Fixed decimal scaling applied as `value * 10^scaleFactor`. Default 0 (no scaling). */
|
|
126
|
+
scaleFactor?: number;
|
|
127
|
+
/** Modbus function code: 3 = holding registers (default), 4 = input registers. */
|
|
128
|
+
functionCode?: 3 | 4;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* A writable register exposed through {@link SunspecCustomDevice.writeCustomRegister}. Limited to the
|
|
132
|
+
* data types the client's {@link writeRegisterValue} can serialize (uint16/int16/uint32/int32).
|
|
133
|
+
*/
|
|
134
|
+
export interface SunspecCustomWriteRegister {
|
|
135
|
+
/** Caller-facing handle passed to `writeCustomRegister(name, value)`. */
|
|
136
|
+
name: string;
|
|
137
|
+
/** Modbus register address (absolute). */
|
|
138
|
+
address: number;
|
|
139
|
+
/** How to serialize the value. */
|
|
140
|
+
dataType: EnergyAppModbusDataType;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Declarative configuration for a {@link SunspecCustomDevice}: a plain-Modbus device polled through
|
|
144
|
+
* the SDK's resilient connection management but read from a hand-defined static register map rather
|
|
145
|
+
* than a discovered SunSpec model directory.
|
|
146
|
+
*/
|
|
147
|
+
export interface SunspecCustomDeviceConfig {
|
|
148
|
+
/** Which appliance role to emulate (drives appliance type + emitted databus message). */
|
|
149
|
+
role: SunspecCustomDeviceRole;
|
|
150
|
+
/** The static registers read every poll and mapped onto the role's databus message. */
|
|
151
|
+
registers: SunspecCustomRegister[];
|
|
152
|
+
/**
|
|
153
|
+
* Maximum registers spanned by a single block read. Registers (grouped per function code) are
|
|
154
|
+
* sorted by address and coalesced — across gaps — into as few reads as possible, each spanning at
|
|
155
|
+
* most this many registers; every register is then sliced out of its block buffer by offset, just
|
|
156
|
+
* like a SunSpec model block. Larger blocks mean fewer round-trips but read any unmapped registers
|
|
157
|
+
* in the gaps (which some devices reject). Default 125 (the Modbus FC03/FC04 per-read limit); a
|
|
158
|
+
* block wider than 125 is still chunked internally.
|
|
159
|
+
*/
|
|
160
|
+
blockSize?: number;
|
|
161
|
+
/** Optional writable registers exposed via `writeCustomRegister`. */
|
|
162
|
+
writeRegisters?: SunspecCustomWriteRegister[];
|
|
163
|
+
/**
|
|
164
|
+
* Static operating state to publish for the `inverter` role. Without SunSpec status models there is
|
|
165
|
+
* no register to derive it from, so callers may pin one (e.g. `Mppt`). Ignored for other roles.
|
|
166
|
+
*/
|
|
167
|
+
defaultInverterState?: EnyoInverterStateEnum;
|
|
168
|
+
/**
|
|
169
|
+
* Static operating state to publish for the `battery` role. Ignored for other roles.
|
|
170
|
+
*/
|
|
171
|
+
defaultBatteryState?: EnyoBatteryStateEnum;
|
|
172
|
+
/**
|
|
173
|
+
* Optional identity written to appliance metadata. There is no SunSpec Common block to read it
|
|
174
|
+
* from, so the caller supplies serial/model/vendor if they want them populated.
|
|
175
|
+
*/
|
|
176
|
+
identity?: {
|
|
177
|
+
serialNumber?: string;
|
|
178
|
+
modelName?: string;
|
|
179
|
+
vendorName?: string;
|
|
180
|
+
};
|
|
181
|
+
}
|
|
101
182
|
/**
|
|
102
183
|
* Base interface for all SunSpec blocks
|
|
103
184
|
*/
|
|
@@ -231,6 +231,10 @@ class SunspecModbusClient {
|
|
|
231
231
|
await this._openUnit(host, port, unitId, {
|
|
232
232
|
connectRetries: 0,
|
|
233
233
|
connectTimeoutMs: opts.timeoutMs ?? this.resilience.connectTimeoutMs,
|
|
234
|
+
// Fast-fail scan: a mostly-dead RS485 range must cost ~one timeout per unit, so do
|
|
235
|
+
// NOT let the transport also walk a fallback host (which would double the per-unit
|
|
236
|
+
// cost). Warm connects/reconnects still get the in-band fallback.
|
|
237
|
+
useFallbackHosts: false,
|
|
234
238
|
});
|
|
235
239
|
console.log(`Probed Sunspec unit ${unitId} at ${host}:${port} — open (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
|
|
236
240
|
});
|
|
@@ -402,6 +406,25 @@ class SunspecModbusClient {
|
|
|
402
406
|
return false;
|
|
403
407
|
}
|
|
404
408
|
}
|
|
409
|
+
/**
|
|
410
|
+
* Build the ordered host list handed to the transport's `host` option for a single connect.
|
|
411
|
+
* The attempt's primary target leads, followed by every OTHER known host (the other of
|
|
412
|
+
* primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
|
|
413
|
+
* DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
|
|
414
|
+
* only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
|
|
415
|
+
* no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
|
|
416
|
+
*/
|
|
417
|
+
buildConnectHosts(primaryTarget) {
|
|
418
|
+
const hosts = [primaryTarget];
|
|
419
|
+
const params = this.connectionParams;
|
|
420
|
+
if (params) {
|
|
421
|
+
for (const h of [params.primaryHost, params.secondaryHost]) {
|
|
422
|
+
if (h && !hosts.includes(h))
|
|
423
|
+
hosts.push(h);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return hosts.length === 1 ? hosts[0] : hosts;
|
|
427
|
+
}
|
|
405
428
|
/**
|
|
406
429
|
* Open a unit, retrying the connect on a transient failure per the resilience config
|
|
407
430
|
* ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
|
|
@@ -415,7 +438,11 @@ class SunspecModbusClient {
|
|
|
415
438
|
async _openUnit(host, port, unitId, override) {
|
|
416
439
|
const connectTimeoutMs = override?.connectTimeoutMs ?? this.resilience.connectTimeoutMs;
|
|
417
440
|
const attempts = (override?.connectRetries ?? this.resilience.connectRetries) + 1;
|
|
418
|
-
|
|
441
|
+
// Default ON: a normal connect/reconnect hands the transport BOTH known hosts so a single
|
|
442
|
+
// attempt tolerates DNS/DHCP drift on the first one. probeUnit opts out to stay a fast-fail
|
|
443
|
+
// single-host scan (see probeUnit / _openUnitOnce).
|
|
444
|
+
const useFallbackHosts = override?.useFallbackHosts ?? true;
|
|
445
|
+
await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs, useFallbackHosts), {
|
|
419
446
|
attempts,
|
|
420
447
|
delayMs: this.resilience.connectRetryDelayMs,
|
|
421
448
|
onRetry: (error, attempt) => console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} failed ` +
|
|
@@ -427,15 +454,28 @@ class SunspecModbusClient {
|
|
|
427
454
|
* Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
|
|
428
455
|
* connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
|
|
429
456
|
* we never leak. Caller must hold the connection lock and ensure the unit is not already open.
|
|
430
|
-
|
|
431
|
-
|
|
457
|
+
*
|
|
458
|
+
* When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
|
|
459
|
+
* full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
|
|
460
|
+
* known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
|
|
461
|
+
* waiting for the client's own sequential primary→secondary retry. The transport walks the list
|
|
462
|
+
* in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
|
|
463
|
+
* the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
|
|
464
|
+
* false to keep speculative RS485 scans a fast-fail single-host probe.
|
|
465
|
+
*/
|
|
466
|
+
async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs, useFallbackHosts = true) {
|
|
432
467
|
let candidate = null;
|
|
468
|
+
const hosts = useFallbackHosts ? this.buildConnectHosts(host) : host;
|
|
469
|
+
const hostCount = Array.isArray(hosts) ? hosts.length : 1;
|
|
470
|
+
// Each host in the list gets its own `timeout`; bound the whole walk at count × budget so we
|
|
471
|
+
// don't kill a genuine fallback to the second host with the single-host budget.
|
|
472
|
+
const overallBudgetMs = connectTimeoutMs * hostCount;
|
|
433
473
|
try {
|
|
434
474
|
// Enforce the connect budget ourselves in addition to forwarding it as the transport's
|
|
435
475
|
// `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
|
|
436
476
|
// can still leave the returned promise pending — bound it independently.
|
|
437
|
-
candidate = await this.withTimeout('connect', unitId,
|
|
438
|
-
host,
|
|
477
|
+
candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.energyApp.useModbus().connect({
|
|
478
|
+
host: hosts,
|
|
439
479
|
port,
|
|
440
480
|
unitId,
|
|
441
481
|
timeout: connectTimeoutMs,
|
|
@@ -708,7 +748,16 @@ class SunspecModbusClient {
|
|
|
708
748
|
*/
|
|
709
749
|
async detectSunspecBaseAddress(unitId, customBaseAddress) {
|
|
710
750
|
const instance = this.getInstance(unitId);
|
|
711
|
-
// If custom base address provided, try it first (
|
|
751
|
+
// If a custom base address is provided, try it first (0-based, then 1-based variant).
|
|
752
|
+
//
|
|
753
|
+
// A custom base is only a real SunSpec anchor for a device whose map genuinely starts
|
|
754
|
+
// there. It is NOT an anchor when it points at a *model block* inside a shared unit —
|
|
755
|
+
// e.g. a SolarEdge meter block (~40188) co-resident with the inverter on unit 1: the
|
|
756
|
+
// "SunS" marker lives ONLY at the unit's SunSpec root (40000/40001), never at the meter
|
|
757
|
+
// block. So a miss here must NOT fail discovery; fall through to the standard root probe
|
|
758
|
+
// below. (This is exactly the reconnect path that used to strand the meter — its
|
|
759
|
+
// rediscovery threw "not SunSpec compliant" at 40188, returned no models, and poisoned
|
|
760
|
+
// the shared socket, dragging the inverter offline too.)
|
|
712
761
|
if (customBaseAddress !== undefined) {
|
|
713
762
|
console.log(`Detect models for custom base address '${customBaseAddress}' ...`);
|
|
714
763
|
// Try 0-based at custom address
|
|
@@ -741,41 +790,44 @@ class SunspecModbusClient {
|
|
|
741
790
|
catch (error) {
|
|
742
791
|
console.debug(`Could not read SunS at ${customBaseAddress + 1}:`, error);
|
|
743
792
|
}
|
|
793
|
+
console.debug(`No "SunS" marker at custom base ${customBaseAddress}/${customBaseAddress + 1} on unit ${unitId} — ` +
|
|
794
|
+
`falling back to the standard SunSpec root (40001/40000). Expected when the custom base points at a ` +
|
|
795
|
+
`model block inside a shared unit (e.g. a co-resident meter), whose anchor is the unit root.`);
|
|
744
796
|
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
catch (error) {
|
|
759
|
-
console.debug('Could not read SunS at 40001:', error);
|
|
760
|
-
}
|
|
761
|
-
// Try 0-based addressing
|
|
762
|
-
try {
|
|
763
|
-
const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
|
|
764
|
-
if (sunspecId.includes('SunS')) {
|
|
765
|
-
console.log('Detected 0-based addressing mode (base address: 40000)');
|
|
766
|
-
return {
|
|
767
|
-
baseAddress: 40000,
|
|
768
|
-
isZeroBased: true,
|
|
769
|
-
nextAddress: 40002
|
|
770
|
-
};
|
|
771
|
-
}
|
|
797
|
+
// Standard SunSpec root probe. Runs when no custom base was given, OR as the fallback
|
|
798
|
+
// when the custom base carried no marker. Try 1-based (40001) first (most common), then
|
|
799
|
+
// 0-based (40000).
|
|
800
|
+
try {
|
|
801
|
+
const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
|
|
802
|
+
if (sunspecId.includes('SunS')) {
|
|
803
|
+
console.log('Detected 1-based addressing mode (base address: 40001)');
|
|
804
|
+
return {
|
|
805
|
+
baseAddress: 40001,
|
|
806
|
+
isZeroBased: false,
|
|
807
|
+
nextAddress: 40003
|
|
808
|
+
};
|
|
772
809
|
}
|
|
773
|
-
|
|
774
|
-
|
|
810
|
+
}
|
|
811
|
+
catch (error) {
|
|
812
|
+
console.debug('Could not read SunS at 40001:', error);
|
|
813
|
+
}
|
|
814
|
+
// Try 0-based addressing
|
|
815
|
+
try {
|
|
816
|
+
const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
|
|
817
|
+
if (sunspecId.includes('SunS')) {
|
|
818
|
+
console.log('Detected 0-based addressing mode (base address: 40000)');
|
|
819
|
+
return {
|
|
820
|
+
baseAddress: 40000,
|
|
821
|
+
isZeroBased: true,
|
|
822
|
+
nextAddress: 40002
|
|
823
|
+
};
|
|
775
824
|
}
|
|
776
825
|
}
|
|
826
|
+
catch (error) {
|
|
827
|
+
console.debug('Could not read SunS at 40000:', error);
|
|
828
|
+
}
|
|
777
829
|
const addressesChecked = customBaseAddress !== undefined
|
|
778
|
-
? `${customBaseAddress}, ${customBaseAddress + 1}`
|
|
830
|
+
? `${customBaseAddress}, ${customBaseAddress + 1}, 40001, 40000`
|
|
779
831
|
: '40000 or 40001';
|
|
780
832
|
throw new Error(`Device is not SunSpec compliant - "SunS" identifier not found at addresses ${addressesChecked}`);
|
|
781
833
|
}
|
|
@@ -786,29 +838,35 @@ class SunspecModbusClient {
|
|
|
786
838
|
async discoverModels(unitId, customBaseAddress) {
|
|
787
839
|
const instance = this.getInstance(unitId);
|
|
788
840
|
const models = this.getModelsMap(unitId);
|
|
789
|
-
models.clear();
|
|
790
841
|
const modelList = this.getModelList(unitId);
|
|
791
|
-
modelList.length = 0;
|
|
792
842
|
const maxAddress = 50000; // Safety limit
|
|
793
|
-
let currentAddress = 0;
|
|
794
843
|
console.log(`Starting Sunspec model discovery for unit ${unitId}...`);
|
|
795
844
|
// Probe for the SunS identifier first. A missing identifier means the unit ID isn't a
|
|
796
845
|
// SunSpec device — common during unit-ID scans — and is logged at debug level so probes
|
|
797
846
|
// don't surface as errors. Mid-scan failures below remain at error level since they
|
|
798
847
|
// indicate a partial / malformed SunSpec map.
|
|
848
|
+
//
|
|
849
|
+
// IMPORTANT: we discover into TEMP buffers and only commit into the stored map once the
|
|
850
|
+
// walk yields at least one model. A reconnect probe can transiently fail (e.g. a single-
|
|
851
|
+
// session SolarEdge endpoint drops the socket with ECONNRESET on the first read after
|
|
852
|
+
// accepting the connection). Clearing the stored map up-front — as this used to — turned
|
|
853
|
+
// that blip into "no usable models", which trips tryReconnect()'s gate into invalidating
|
|
854
|
+
// a unit whose model map was perfectly good a moment ago. Preserving the last known-good
|
|
855
|
+
// map keeps a genuinely-connected sibling alive; a device that is really gone is still
|
|
856
|
+
// caught by read-health (isHealthy()).
|
|
799
857
|
let addressInfo;
|
|
800
858
|
try {
|
|
801
859
|
addressInfo = await this.detectSunspecBaseAddress(unitId, customBaseAddress);
|
|
802
860
|
}
|
|
803
861
|
catch (error) {
|
|
804
862
|
console.debug(`No SunSpec device at unit ${unitId}: ${error}`);
|
|
805
|
-
//
|
|
806
|
-
//
|
|
807
|
-
|
|
808
|
-
console.debug(`Discovery complete for unit ${unitId}. Found 0 models: []`);
|
|
863
|
+
// Same outcome as a normal "no device found"; keep at debug. Do NOT wipe the stored
|
|
864
|
+
// map — return it untouched so a transient probe failure can't erase good discovery.
|
|
865
|
+
console.debug(`Discovery incomplete for unit ${unitId}; keeping ${models.size} previously-discovered model(s).`);
|
|
809
866
|
return models;
|
|
810
867
|
}
|
|
811
|
-
|
|
868
|
+
const discovered = [];
|
|
869
|
+
let currentAddress = addressInfo.nextAddress;
|
|
812
870
|
try {
|
|
813
871
|
while (currentAddress < maxAddress) {
|
|
814
872
|
const buffer = await this.runExclusive(unitId, () => instance.readHoldingRegisters(currentAddress, 2));
|
|
@@ -824,19 +882,12 @@ class SunspecModbusClient {
|
|
|
824
882
|
console.debug(`Found end marker at address ${currentAddress}`);
|
|
825
883
|
break;
|
|
826
884
|
}
|
|
827
|
-
// Store discovered model
|
|
828
885
|
const model = {
|
|
829
886
|
id: modelId,
|
|
830
887
|
address: currentAddress,
|
|
831
888
|
length: modelLength
|
|
832
889
|
};
|
|
833
|
-
|
|
834
|
-
// findModel() resolves to the device's own block. Record every instance —
|
|
835
|
-
// including repeats like a meter's Common (id 1) — in the ordered list.
|
|
836
|
-
if (!models.has(modelId)) {
|
|
837
|
-
models.set(modelId, model);
|
|
838
|
-
}
|
|
839
|
-
modelList.push(model);
|
|
890
|
+
discovered.push(model);
|
|
840
891
|
// Per-model discovery step. The end-of-discovery summary below is the
|
|
841
892
|
// info-level outcome; the per-model walk is debug-only.
|
|
842
893
|
console.debug(`Discovered Model ${modelId} at address ${currentAddress} with length ${modelLength} (unit ${unitId})`);
|
|
@@ -847,6 +898,24 @@ class SunspecModbusClient {
|
|
|
847
898
|
catch (error) {
|
|
848
899
|
console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
|
|
849
900
|
}
|
|
901
|
+
if (discovered.length > 0) {
|
|
902
|
+
// Commit the fresh discovery atomically. Keep the FIRST (lowest-address) instance per
|
|
903
|
+
// id in the keyed directory so findModel() resolves to the device's own block; record
|
|
904
|
+
// every instance — including repeats like a meter's Common (id 1) — in the ordered list.
|
|
905
|
+
models.clear();
|
|
906
|
+
modelList.length = 0;
|
|
907
|
+
for (const model of discovered) {
|
|
908
|
+
if (!models.has(model.id)) {
|
|
909
|
+
models.set(model.id, model);
|
|
910
|
+
}
|
|
911
|
+
modelList.push(model);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
else {
|
|
915
|
+
// The anchor answered but the walk yielded nothing (e.g. the socket dropped right
|
|
916
|
+
// after the SunS probe). Preserve the last known-good map rather than clobbering it.
|
|
917
|
+
console.debug(`Discovery for unit ${unitId} yielded no models; keeping ${models.size} previously-discovered model(s).`);
|
|
918
|
+
}
|
|
850
919
|
// Report every instance in address order so repeated ids (e.g. two Common blocks, or
|
|
851
920
|
// multiple meters) are visible — models.size would hide them behind the unique keys.
|
|
852
921
|
console.log(`Discovery complete for unit ${unitId}. Found ${modelList.length} model instance(s): [${modelList.map(m => m.id).join(', ')}]`);
|
|
@@ -988,12 +1057,87 @@ class SunspecModbusClient {
|
|
|
988
1057
|
return value;
|
|
989
1058
|
}
|
|
990
1059
|
/**
|
|
991
|
-
*
|
|
1060
|
+
* Read a contiguous span of `quantity` registers starting at `address` in a single logical
|
|
1061
|
+
* transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
|
|
1062
|
+
* other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
|
|
1063
|
+
* when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
|
|
1064
|
+
* the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
|
|
1065
|
+
* individual fields out of the returned buffer with {@link decodeBlockValue}.
|
|
1066
|
+
*/
|
|
1067
|
+
async readRegisterBlock(unitId, address, quantity, useInputRegisters = false) {
|
|
1068
|
+
const reader = this.getReader(unitId);
|
|
1069
|
+
const MAX_REGISTERS_PER_READ = 125;
|
|
1070
|
+
try {
|
|
1071
|
+
const chunks = await this.runExclusive(unitId, async () => {
|
|
1072
|
+
const acc = [];
|
|
1073
|
+
for (let offset = 0; offset < quantity; offset += MAX_REGISTERS_PER_READ) {
|
|
1074
|
+
const count = Math.min(MAX_REGISTERS_PER_READ, quantity - offset);
|
|
1075
|
+
let result;
|
|
1076
|
+
if (useInputRegisters) {
|
|
1077
|
+
if (!reader.readInputRegisters) {
|
|
1078
|
+
throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
|
|
1079
|
+
}
|
|
1080
|
+
result = await reader.readInputRegisters(address + offset, count);
|
|
1081
|
+
}
|
|
1082
|
+
else {
|
|
1083
|
+
result = await reader.readHoldingRegisters(address + offset, count);
|
|
1084
|
+
}
|
|
1085
|
+
if (!result.success || !result.value) {
|
|
1086
|
+
throw new Error(`Failed to read register block at address ${address + offset} (unit ${unitId}): ${result.error?.message || 'Unknown error'}`);
|
|
1087
|
+
}
|
|
1088
|
+
acc.push(result.value);
|
|
1089
|
+
}
|
|
1090
|
+
return acc;
|
|
1091
|
+
});
|
|
1092
|
+
this.connectionHealth.recordSuccess();
|
|
1093
|
+
return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
|
|
1094
|
+
}
|
|
1095
|
+
catch (error) {
|
|
1096
|
+
this.connectionHealth.recordFailure(error);
|
|
1097
|
+
throw error;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
|
|
1102
|
+
* from the block start. A thin public wrapper over the same block-extraction the SunSpec model
|
|
1103
|
+
* readers use internally.
|
|
1104
|
+
*/
|
|
1105
|
+
decodeBlockValue(buffer, registerOffset, dataType, quantity = 1) {
|
|
1106
|
+
return this.extractValue(buffer, registerOffset, dataType, quantity);
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
|
|
1110
|
+
* conversion.
|
|
992
1111
|
*/
|
|
993
1112
|
async readRegisterValue(unitId, address, quantity = 1, dataType) {
|
|
1113
|
+
return this.readTypedRegisters(unitId, address, quantity, dataType, false);
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
|
|
1117
|
+
* conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
|
|
1118
|
+
* {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
|
|
1119
|
+
* not implement `readInputRegisters`.
|
|
1120
|
+
*/
|
|
1121
|
+
async readInputRegisterValue(unitId, address, quantity = 1, dataType) {
|
|
1122
|
+
return this.readTypedRegisters(unitId, address, quantity, dataType, true);
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
|
|
1126
|
+
* the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
|
|
1127
|
+
* connection health on both success and failure.
|
|
1128
|
+
*/
|
|
1129
|
+
async readTypedRegisters(unitId, address, quantity, dataType, useInputRegisters) {
|
|
994
1130
|
const reader = this.getReader(unitId);
|
|
995
1131
|
try {
|
|
996
|
-
const result = await this.runExclusive(unitId, () =>
|
|
1132
|
+
const result = await this.runExclusive(unitId, () => {
|
|
1133
|
+
if (useInputRegisters) {
|
|
1134
|
+
if (!reader.readInputRegisters) {
|
|
1135
|
+
throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
|
|
1136
|
+
}
|
|
1137
|
+
return reader.readInputRegisters(address, quantity);
|
|
1138
|
+
}
|
|
1139
|
+
return reader.readHoldingRegisters(address, quantity);
|
|
1140
|
+
});
|
|
997
1141
|
// Check if the read was successful
|
|
998
1142
|
if (!result.success || !result.value) {
|
|
999
1143
|
throw new Error(`Failed to read register at address ${address}: ${result.error?.message || 'Unknown error'}`);
|
|
@@ -152,6 +152,15 @@ export declare class SunspecModbusClient {
|
|
|
152
152
|
* if every unit succeeded.
|
|
153
153
|
*/
|
|
154
154
|
private attemptConnection;
|
|
155
|
+
/**
|
|
156
|
+
* Build the ordered host list handed to the transport's `host` option for a single connect.
|
|
157
|
+
* The attempt's primary target leads, followed by every OTHER known host (the other of
|
|
158
|
+
* primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
|
|
159
|
+
* DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
|
|
160
|
+
* only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
|
|
161
|
+
* no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
|
|
162
|
+
*/
|
|
163
|
+
private buildConnectHosts;
|
|
155
164
|
/**
|
|
156
165
|
* Open a unit, retrying the connect on a transient failure per the resilience config
|
|
157
166
|
* ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
|
|
@@ -167,6 +176,14 @@ export declare class SunspecModbusClient {
|
|
|
167
176
|
* Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
|
|
168
177
|
* connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
|
|
169
178
|
* we never leak. Caller must hold the connection lock and ensure the unit is not already open.
|
|
179
|
+
*
|
|
180
|
+
* When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
|
|
181
|
+
* full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
|
|
182
|
+
* known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
|
|
183
|
+
* waiting for the client's own sequential primary→secondary retry. The transport walks the list
|
|
184
|
+
* in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
|
|
185
|
+
* the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
|
|
186
|
+
* false to keep speculative RS485 scans a fast-fail single-host probe.
|
|
170
187
|
*/
|
|
171
188
|
private _openUnitOnce;
|
|
172
189
|
/**
|
|
@@ -349,9 +366,38 @@ export declare class SunspecModbusClient {
|
|
|
349
366
|
*/
|
|
350
367
|
private extractValue;
|
|
351
368
|
/**
|
|
352
|
-
*
|
|
369
|
+
* Read a contiguous span of `quantity` registers starting at `address` in a single logical
|
|
370
|
+
* transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
|
|
371
|
+
* other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
|
|
372
|
+
* when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
|
|
373
|
+
* the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
|
|
374
|
+
* individual fields out of the returned buffer with {@link decodeBlockValue}.
|
|
375
|
+
*/
|
|
376
|
+
readRegisterBlock(unitId: number, address: number, quantity: number, useInputRegisters?: boolean): Promise<Buffer>;
|
|
377
|
+
/**
|
|
378
|
+
* Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
|
|
379
|
+
* from the block start. A thin public wrapper over the same block-extraction the SunSpec model
|
|
380
|
+
* readers use internally.
|
|
381
|
+
*/
|
|
382
|
+
decodeBlockValue(buffer: Buffer, registerOffset: number, dataType: EnergyAppModbusDataType, quantity?: number): number | string | number[];
|
|
383
|
+
/**
|
|
384
|
+
* Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
|
|
385
|
+
* conversion.
|
|
353
386
|
*/
|
|
354
387
|
readRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
|
|
388
|
+
/**
|
|
389
|
+
* Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
|
|
390
|
+
* conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
|
|
391
|
+
* {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
|
|
392
|
+
* not implement `readInputRegisters`.
|
|
393
|
+
*/
|
|
394
|
+
readInputRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
|
|
395
|
+
/**
|
|
396
|
+
* Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
|
|
397
|
+
* the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
|
|
398
|
+
* connection health on both success and failure.
|
|
399
|
+
*/
|
|
400
|
+
private readTypedRegisters;
|
|
355
401
|
/**
|
|
356
402
|
* Helper to write register value(s)
|
|
357
403
|
*/
|
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.103';
|
|
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