@enyo-energy/sunspec-sdk 0.0.101 → 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.
@@ -701,7 +701,16 @@ export class SunspecModbusClient {
701
701
  */
702
702
  async detectSunspecBaseAddress(unitId, customBaseAddress) {
703
703
  const instance = this.getInstance(unitId);
704
- // 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.)
705
714
  if (customBaseAddress !== undefined) {
706
715
  console.log(`Detect models for custom base address '${customBaseAddress}' ...`);
707
716
  // Try 0-based at custom address
@@ -734,41 +743,44 @@ export class SunspecModbusClient {
734
743
  catch (error) {
735
744
  console.debug(`Could not read SunS at ${customBaseAddress + 1}:`, error);
736
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.`);
737
749
  }
738
- else {
739
- // Try 1-based addressing first (most common)
740
- try {
741
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40001, 2));
742
- if (sunspecId.includes('SunS')) {
743
- console.log('Detected 1-based addressing mode (base address: 40001)');
744
- return {
745
- baseAddress: 40001,
746
- isZeroBased: false,
747
- nextAddress: 40003
748
- };
749
- }
750
- }
751
- catch (error) {
752
- console.debug('Could not read SunS at 40001:', error);
753
- }
754
- // Try 0-based addressing
755
- try {
756
- const sunspecId = await this.runExclusive(unitId, () => instance.readRegisterStringValue(40000, 2));
757
- if (sunspecId.includes('SunS')) {
758
- console.log('Detected 0-based addressing mode (base address: 40000)');
759
- return {
760
- baseAddress: 40000,
761
- isZeroBased: true,
762
- nextAddress: 40002
763
- };
764
- }
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
+ };
765
762
  }
766
- catch (error) {
767
- 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
+ };
768
777
  }
769
778
  }
779
+ catch (error) {
780
+ console.debug('Could not read SunS at 40000:', error);
781
+ }
770
782
  const addressesChecked = customBaseAddress !== undefined
771
- ? `${customBaseAddress}, ${customBaseAddress + 1}`
783
+ ? `${customBaseAddress}, ${customBaseAddress + 1}, 40001, 40000`
772
784
  : '40000 or 40001';
773
785
  throw new Error(`Device is not SunSpec compliant - "SunS" identifier not found at addresses ${addressesChecked}`);
774
786
  }
@@ -779,29 +791,35 @@ export class SunspecModbusClient {
779
791
  async discoverModels(unitId, customBaseAddress) {
780
792
  const instance = this.getInstance(unitId);
781
793
  const models = this.getModelsMap(unitId);
782
- models.clear();
783
794
  const modelList = this.getModelList(unitId);
784
- modelList.length = 0;
785
795
  const maxAddress = 50000; // Safety limit
786
- let currentAddress = 0;
787
796
  console.log(`Starting Sunspec model discovery for unit ${unitId}...`);
788
797
  // Probe for the SunS identifier first. A missing identifier means the unit ID isn't a
789
798
  // SunSpec device — common during unit-ID scans — and is logged at debug level so probes
790
799
  // don't surface as errors. Mid-scan failures below remain at error level since they
791
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()).
792
810
  let addressInfo;
793
811
  try {
794
812
  addressInfo = await this.detectSunspecBaseAddress(unitId, customBaseAddress);
795
813
  }
796
814
  catch (error) {
797
815
  console.debug(`No SunSpec device at unit ${unitId}: ${error}`);
798
- // Discovery summary at line 594 below is the info-level outcome.
799
- // This 0-models branch is the same outcome as a normal "no device found",
800
- // covered already by the debug above. Keep at debug.
801
- 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).`);
802
819
  return models;
803
820
  }
804
- currentAddress = addressInfo.nextAddress;
821
+ const discovered = [];
822
+ let currentAddress = addressInfo.nextAddress;
805
823
  try {
806
824
  while (currentAddress < maxAddress) {
807
825
  const buffer = await this.runExclusive(unitId, () => instance.readHoldingRegisters(currentAddress, 2));
@@ -817,19 +835,12 @@ export class SunspecModbusClient {
817
835
  console.debug(`Found end marker at address ${currentAddress}`);
818
836
  break;
819
837
  }
820
- // Store discovered model
821
838
  const model = {
822
839
  id: modelId,
823
840
  address: currentAddress,
824
841
  length: modelLength
825
842
  };
826
- // Keep the FIRST (lowest-address) instance per id in the keyed directory so
827
- // findModel() resolves to the device's own block. Record every instance —
828
- // including repeats like a meter's Common (id 1) — in the ordered list.
829
- if (!models.has(modelId)) {
830
- models.set(modelId, model);
831
- }
832
- modelList.push(model);
843
+ discovered.push(model);
833
844
  // Per-model discovery step. The end-of-discovery summary below is the
834
845
  // info-level outcome; the per-model walk is debug-only.
835
846
  console.debug(`Discovered Model ${modelId} at address ${currentAddress} with length ${modelLength} (unit ${unitId})`);
@@ -840,6 +851,24 @@ export class SunspecModbusClient {
840
851
  catch (error) {
841
852
  console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
842
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
+ }
843
872
  // Report every instance in address order so repeated ids (e.g. two Common blocks, or
844
873
  // multiple meters) are visible — models.size would hide them behind the unique keys.
845
874
  console.log(`Discovery complete for unit ${unitId}. Found ${modelList.length} model instance(s): [${modelList.map(m => m.id).join(', ')}]`);
@@ -981,12 +1010,87 @@ export class SunspecModbusClient {
981
1010
  return value;
982
1011
  }
983
1012
  /**
984
- * 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.
985
1064
  */
986
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) {
987
1083
  const reader = this.getReader(unitId);
988
1084
  try {
989
- 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
+ });
990
1094
  // Check if the read was successful
991
1095
  if (!result.success || !result.value) {
992
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.101";
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.101';
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.101",
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"