@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.
@@ -216,6 +216,19 @@ export declare class SunspecModbusClient {
216
216
  * 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
217
217
  */
218
218
  private poisonUnit;
219
+ /**
220
+ * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
221
+ * readData()/tryReconnect() cycle recycles it — the same effect as a timeout poison but
222
+ * for a caller-detected fault that isn't itself a Modbus timeout.
223
+ *
224
+ * The motivating case: a TCP reconnect succeeds but the follow-up model discovery comes
225
+ * back empty because the gateway (e.g. a SolarEdge unit) accepted the socket before it was
226
+ * ready to answer the SunSpec scan. The link looks alive, so without this the reconnect
227
+ * would be trusted, an empty model map cached, and every subsequent read would find no
228
+ * model while nothing ever triggers another reconnect. Poisoning here keeps the retry
229
+ * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
230
+ */
231
+ invalidateUnit(unitId: number, reason: string): void;
219
232
  /**
220
233
  * A unit's socket is stale when the transport still reports it connected but no successful
221
234
  * transaction has completed within staleSocketMs — the signature of a half-open link where
@@ -336,9 +349,38 @@ export declare class SunspecModbusClient {
336
349
  */
337
350
  private extractValue;
338
351
  /**
339
- * Helper to read register value(s) using the fault-tolerant reader with data type conversion
352
+ * Read a contiguous span of `quantity` registers starting at `address` in a single logical
353
+ * transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
354
+ * other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
355
+ * when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
356
+ * the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
357
+ * individual fields out of the returned buffer with {@link decodeBlockValue}.
358
+ */
359
+ readRegisterBlock(unitId: number, address: number, quantity: number, useInputRegisters?: boolean): Promise<Buffer>;
360
+ /**
361
+ * Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
362
+ * from the block start. A thin public wrapper over the same block-extraction the SunSpec model
363
+ * readers use internally.
364
+ */
365
+ decodeBlockValue(buffer: Buffer, registerOffset: number, dataType: EnergyAppModbusDataType, quantity?: number): number | string | number[];
366
+ /**
367
+ * Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
368
+ * conversion.
340
369
  */
341
370
  readRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
371
+ /**
372
+ * Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
373
+ * conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
374
+ * {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
375
+ * not implement `readInputRegisters`.
376
+ */
377
+ readInputRegisterValue(unitId: number, address: number, quantity: number | undefined, dataType: EnergyAppModbusDataType): Promise<number | string | number[]>;
378
+ /**
379
+ * Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
380
+ * the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
381
+ * connection health on both success and failure.
382
+ */
383
+ private readTypedRegisters;
342
384
  /**
343
385
  * Helper to write register value(s)
344
386
  */
@@ -574,6 +574,25 @@ export class SunspecModbusClient {
574
574
  this.poisonedUnits.add(unitId);
575
575
  this.connectionHealth.recordFailure(error);
576
576
  }
577
+ /**
578
+ * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
579
+ * readData()/tryReconnect() cycle recycles it — the same effect as a timeout poison but
580
+ * for a caller-detected fault that isn't itself a Modbus timeout.
581
+ *
582
+ * The motivating case: a TCP reconnect succeeds but the follow-up model discovery comes
583
+ * back empty because the gateway (e.g. a SolarEdge unit) accepted the socket before it was
584
+ * ready to answer the SunSpec scan. The link looks alive, so without this the reconnect
585
+ * would be trusted, an empty model map cached, and every subsequent read would find no
586
+ * model while nothing ever triggers another reconnect. Poisoning here keeps the retry
587
+ * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
588
+ */
589
+ invalidateUnit(unitId, reason) {
590
+ if (!this.poisonedUnits.has(unitId)) {
591
+ console.warn(`SunspecModbusClient: invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
592
+ }
593
+ this.poisonedUnits.add(unitId);
594
+ this.connectionHealth.recordFailure(new Error(reason));
595
+ }
577
596
  /**
578
597
  * A unit's socket is stale when the transport still reports it connected but no successful
579
598
  * transaction has completed within staleSocketMs — the signature of a half-open link where
@@ -682,7 +701,16 @@ export class SunspecModbusClient {
682
701
  */
683
702
  async detectSunspecBaseAddress(unitId, customBaseAddress) {
684
703
  const instance = this.getInstance(unitId);
685
- // If custom base address provided, try it first (1-based, then 0-based variant)
704
+ // If a custom base address is provided, try it first (0-based, then 1-based variant).
705
+ //
706
+ // A custom base is only a real SunSpec anchor for a device whose map genuinely starts
707
+ // there. It is NOT an anchor when it points at a *model block* inside a shared unit —
708
+ // e.g. a SolarEdge meter block (~40188) co-resident with the inverter on unit 1: the
709
+ // "SunS" marker lives ONLY at the unit's SunSpec root (40000/40001), never at the meter
710
+ // block. So a miss here must NOT fail discovery; fall through to the standard root probe
711
+ // below. (This is exactly the reconnect path that used to strand the meter — its
712
+ // rediscovery threw "not SunSpec compliant" at 40188, returned no models, and poisoned
713
+ // the shared socket, dragging the inverter offline too.)
686
714
  if (customBaseAddress !== undefined) {
687
715
  console.log(`Detect models for custom base address '${customBaseAddress}' ...`);
688
716
  // Try 0-based at custom address
@@ -715,41 +743,44 @@ export class SunspecModbusClient {
715
743
  catch (error) {
716
744
  console.debug(`Could not read SunS at ${customBaseAddress + 1}:`, error);
717
745
  }
746
+ console.debug(`No "SunS" marker at custom base ${customBaseAddress}/${customBaseAddress + 1} on unit ${unitId} — ` +
747
+ `falling back to the standard SunSpec root (40001/40000). Expected when the custom base points at a ` +
748
+ `model block inside a shared unit (e.g. a co-resident meter), whose anchor is the unit root.`);
718
749
  }
719
- else {
720
- // Try 1-based addressing first (most common)
721
- try {
722
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
723
- if (sunspecId.includes('SunS')) {
724
- console.log('Detected 1-based addressing mode (base address: 40001)');
725
- return {
726
- baseAddress: 40001,
727
- isZeroBased: false,
728
- nextAddress: 40003
729
- };
730
- }
731
- }
732
- catch (error) {
733
- console.debug('Could not read SunS at 40001:', error);
734
- }
735
- // Try 0-based addressing
736
- try {
737
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
738
- if (sunspecId.includes('SunS')) {
739
- console.log('Detected 0-based addressing mode (base address: 40000)');
740
- return {
741
- baseAddress: 40000,
742
- isZeroBased: true,
743
- nextAddress: 40002
744
- };
745
- }
750
+ // Standard SunSpec root probe. Runs when no custom base was given, OR as the fallback
751
+ // when the custom base carried no marker. Try 1-based (40001) first (most common), then
752
+ // 0-based (40000).
753
+ try {
754
+ const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
755
+ if (sunspecId.includes('SunS')) {
756
+ console.log('Detected 1-based addressing mode (base address: 40001)');
757
+ return {
758
+ baseAddress: 40001,
759
+ isZeroBased: false,
760
+ nextAddress: 40003
761
+ };
746
762
  }
747
- catch (error) {
748
- console.debug('Could not read SunS at 40000:', error);
763
+ }
764
+ catch (error) {
765
+ console.debug('Could not read SunS at 40001:', error);
766
+ }
767
+ // Try 0-based addressing
768
+ try {
769
+ const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
770
+ if (sunspecId.includes('SunS')) {
771
+ console.log('Detected 0-based addressing mode (base address: 40000)');
772
+ return {
773
+ baseAddress: 40000,
774
+ isZeroBased: true,
775
+ nextAddress: 40002
776
+ };
749
777
  }
750
778
  }
779
+ catch (error) {
780
+ console.debug('Could not read SunS at 40000:', error);
781
+ }
751
782
  const addressesChecked = customBaseAddress !== undefined
752
- ? `${customBaseAddress}, ${customBaseAddress + 1}`
783
+ ? `${customBaseAddress}, ${customBaseAddress + 1}, 40001, 40000`
753
784
  : '40000 or 40001';
754
785
  throw new Error(`Device is not SunSpec compliant - "SunS" identifier not found at addresses ${addressesChecked}`);
755
786
  }
@@ -760,29 +791,35 @@ export class SunspecModbusClient {
760
791
  async discoverModels(unitId, customBaseAddress) {
761
792
  const instance = this.getInstance(unitId);
762
793
  const models = this.getModelsMap(unitId);
763
- models.clear();
764
794
  const modelList = this.getModelList(unitId);
765
- modelList.length = 0;
766
795
  const maxAddress = 50000; // Safety limit
767
- let currentAddress = 0;
768
796
  console.log(`Starting Sunspec model discovery for unit ${unitId}...`);
769
797
  // Probe for the SunS identifier first. A missing identifier means the unit ID isn't a
770
798
  // SunSpec device — common during unit-ID scans — and is logged at debug level so probes
771
799
  // don't surface as errors. Mid-scan failures below remain at error level since they
772
800
  // indicate a partial / malformed SunSpec map.
801
+ //
802
+ // IMPORTANT: we discover into TEMP buffers and only commit into the stored map once the
803
+ // walk yields at least one model. A reconnect probe can transiently fail (e.g. a single-
804
+ // session SolarEdge endpoint drops the socket with ECONNRESET on the first read after
805
+ // accepting the connection). Clearing the stored map up-front — as this used to — turned
806
+ // that blip into "no usable models", which trips tryReconnect()'s gate into invalidating
807
+ // a unit whose model map was perfectly good a moment ago. Preserving the last known-good
808
+ // map keeps a genuinely-connected sibling alive; a device that is really gone is still
809
+ // caught by read-health (isHealthy()).
773
810
  let addressInfo;
774
811
  try {
775
812
  addressInfo = await this.detectSunspecBaseAddress(unitId, customBaseAddress);
776
813
  }
777
814
  catch (error) {
778
815
  console.debug(`No SunSpec device at unit ${unitId}: ${error}`);
779
- // Discovery summary at line 594 below is the info-level outcome.
780
- // This 0-models branch is the same outcome as a normal "no device found",
781
- // covered already by the debug above. Keep at debug.
782
- console.debug(`Discovery complete for unit ${unitId}. Found 0 models: []`);
816
+ // Same outcome as a normal "no device found"; keep at debug. Do NOT wipe the stored
817
+ // map — return it untouched so a transient probe failure can't erase good discovery.
818
+ console.debug(`Discovery incomplete for unit ${unitId}; keeping ${models.size} previously-discovered model(s).`);
783
819
  return models;
784
820
  }
785
- currentAddress = addressInfo.nextAddress;
821
+ const discovered = [];
822
+ let currentAddress = addressInfo.nextAddress;
786
823
  try {
787
824
  while (currentAddress < maxAddress) {
788
825
  const buffer = await this.runExclusive(unitId, () => instance.readHoldingRegisters(currentAddress, 2));
@@ -798,19 +835,12 @@ export class SunspecModbusClient {
798
835
  console.debug(`Found end marker at address ${currentAddress}`);
799
836
  break;
800
837
  }
801
- // Store discovered model
802
838
  const model = {
803
839
  id: modelId,
804
840
  address: currentAddress,
805
841
  length: modelLength
806
842
  };
807
- // Keep the FIRST (lowest-address) instance per id in the keyed directory so
808
- // findModel() resolves to the device's own block. Record every instance —
809
- // including repeats like a meter's Common (id 1) — in the ordered list.
810
- if (!models.has(modelId)) {
811
- models.set(modelId, model);
812
- }
813
- modelList.push(model);
843
+ discovered.push(model);
814
844
  // Per-model discovery step. The end-of-discovery summary below is the
815
845
  // info-level outcome; the per-model walk is debug-only.
816
846
  console.debug(`Discovered Model ${modelId} at address ${currentAddress} with length ${modelLength} (unit ${unitId})`);
@@ -821,6 +851,24 @@ export class SunspecModbusClient {
821
851
  catch (error) {
822
852
  console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
823
853
  }
854
+ if (discovered.length > 0) {
855
+ // Commit the fresh discovery atomically. Keep the FIRST (lowest-address) instance per
856
+ // id in the keyed directory so findModel() resolves to the device's own block; record
857
+ // every instance — including repeats like a meter's Common (id 1) — in the ordered list.
858
+ models.clear();
859
+ modelList.length = 0;
860
+ for (const model of discovered) {
861
+ if (!models.has(model.id)) {
862
+ models.set(model.id, model);
863
+ }
864
+ modelList.push(model);
865
+ }
866
+ }
867
+ else {
868
+ // The anchor answered but the walk yielded nothing (e.g. the socket dropped right
869
+ // after the SunS probe). Preserve the last known-good map rather than clobbering it.
870
+ console.debug(`Discovery for unit ${unitId} yielded no models; keeping ${models.size} previously-discovered model(s).`);
871
+ }
824
872
  // Report every instance in address order so repeated ids (e.g. two Common blocks, or
825
873
  // multiple meters) are visible — models.size would hide them behind the unique keys.
826
874
  console.log(`Discovery complete for unit ${unitId}. Found ${modelList.length} model instance(s): [${modelList.map(m => m.id).join(', ')}]`);
@@ -962,12 +1010,87 @@ export class SunspecModbusClient {
962
1010
  return value;
963
1011
  }
964
1012
  /**
965
- * Helper to read register value(s) using the fault-tolerant reader with data type conversion
1013
+ * Read a contiguous span of `quantity` registers starting at `address` in a single logical
1014
+ * transaction — chunked at the 125-register Modbus limit and serialized on the unit's socket so no
1015
+ * other frame interleaves between chunks. FC03 holding registers by default; FC04 input registers
1016
+ * when `useInputRegisters` is true. The SunSpec model readers use {@link readModelBlock}; this is
1017
+ * the equivalent for callers reading a hand-defined block (see {@link SunspecCustomDevice}). Decode
1018
+ * individual fields out of the returned buffer with {@link decodeBlockValue}.
1019
+ */
1020
+ async readRegisterBlock(unitId, address, quantity, useInputRegisters = false) {
1021
+ const reader = this.getReader(unitId);
1022
+ const MAX_REGISTERS_PER_READ = 125;
1023
+ try {
1024
+ const chunks = await this.runExclusive(unitId, async () => {
1025
+ const acc = [];
1026
+ for (let offset = 0; offset < quantity; offset += MAX_REGISTERS_PER_READ) {
1027
+ const count = Math.min(MAX_REGISTERS_PER_READ, quantity - offset);
1028
+ let result;
1029
+ if (useInputRegisters) {
1030
+ if (!reader.readInputRegisters) {
1031
+ throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
1032
+ }
1033
+ result = await reader.readInputRegisters(address + offset, count);
1034
+ }
1035
+ else {
1036
+ result = await reader.readHoldingRegisters(address + offset, count);
1037
+ }
1038
+ if (!result.success || !result.value) {
1039
+ throw new Error(`Failed to read register block at address ${address + offset} (unit ${unitId}): ${result.error?.message || 'Unknown error'}`);
1040
+ }
1041
+ acc.push(result.value);
1042
+ }
1043
+ return acc;
1044
+ });
1045
+ this.connectionHealth.recordSuccess();
1046
+ return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
1047
+ }
1048
+ catch (error) {
1049
+ this.connectionHealth.recordFailure(error);
1050
+ throw error;
1051
+ }
1052
+ }
1053
+ /**
1054
+ * Decode a typed value out of a buffer returned by {@link readRegisterBlock}, at a register offset
1055
+ * from the block start. A thin public wrapper over the same block-extraction the SunSpec model
1056
+ * readers use internally.
1057
+ */
1058
+ decodeBlockValue(buffer, registerOffset, dataType, quantity = 1) {
1059
+ return this.extractValue(buffer, registerOffset, dataType, quantity);
1060
+ }
1061
+ /**
1062
+ * Helper to read holding register value(s) (FC03) using the fault-tolerant reader with data type
1063
+ * conversion.
966
1064
  */
967
1065
  async readRegisterValue(unitId, address, quantity = 1, dataType) {
1066
+ return this.readTypedRegisters(unitId, address, quantity, dataType, false);
1067
+ }
1068
+ /**
1069
+ * Helper to read input register value(s) (FC04) using the fault-tolerant reader with data type
1070
+ * conversion. SunSpec itself never uses input registers, but plain-Modbus devices behind a
1071
+ * {@link SunspecCustomDevice} may expose live values there. Throws if the transport's reader does
1072
+ * not implement `readInputRegisters`.
1073
+ */
1074
+ async readInputRegisterValue(unitId, address, quantity = 1, dataType) {
1075
+ return this.readTypedRegisters(unitId, address, quantity, dataType, true);
1076
+ }
1077
+ /**
1078
+ * Shared body of {@link readRegisterValue} / {@link readInputRegisterValue}. Runs the read under
1079
+ * the unit's transaction lock (so it inherits the timeout/poison/staleness resilience) and records
1080
+ * connection health on both success and failure.
1081
+ */
1082
+ async readTypedRegisters(unitId, address, quantity, dataType, useInputRegisters) {
968
1083
  const reader = this.getReader(unitId);
969
1084
  try {
970
- const result = await this.runExclusive(unitId, () => reader.readHoldingRegisters(address, quantity));
1085
+ const result = await this.runExclusive(unitId, () => {
1086
+ if (useInputRegisters) {
1087
+ if (!reader.readInputRegisters) {
1088
+ throw new Error(`Reader for unit ${unitId} does not support FC04 input registers`);
1089
+ }
1090
+ return reader.readInputRegisters(address, quantity);
1091
+ }
1092
+ return reader.readHoldingRegisters(address, quantity);
1093
+ });
971
1094
  // Check if the read was successful
972
1095
  if (!result.success || !result.value) {
973
1096
  throw new Error(`Failed to read register at address ${address}: ${result.error?.message || 'Unknown error'}`);
package/dist/version.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export declare const SDK_VERSION = "0.0.100";
8
+ export declare const SDK_VERSION = "0.0.102";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/dist/version.js CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export const SDK_VERSION = '0.0.100';
8
+ export const SDK_VERSION = '0.0.102';
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enyo-energy/sunspec-sdk",
3
- "version": "0.0.100",
3
+ "version": "0.0.102",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "dependencies": {
43
43
  "@enyo-energy/appliance-calibration": "0.0.2",
44
- "@enyo-energy/energy-app-sdk": "^0.0.175"
44
+ "@enyo-energy/energy-app-sdk": "^0.0.177"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"