@enyo-energy/sunspec-sdk 0.0.105 → 1.0.1

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.
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SunspecModbusClient = exports.ModbusOperationTimeoutError = void 0;
3
+ exports.SunspecModbusClient = exports.SunspecUnavailableError = exports.ModbusOperationTimeoutError = void 0;
4
+ exports.isSunspecUnavailableError = isSunspecUnavailableError;
4
5
  exports.getOrCreateSunspecClient = getOrCreateSunspecClient;
5
6
  exports.releaseSunspecClient = releaseSunspecClient;
6
7
  exports.retryAsync = retryAsync;
@@ -41,8 +42,66 @@ class ModbusOperationTimeoutError extends Error {
41
42
  this.timeoutMs = timeoutMs;
42
43
  this.name = 'ModbusOperationTimeoutError';
43
44
  }
45
+ /**
46
+ * `Error` has no enumerable own properties, so a consumer that logs `{ err }` through a
47
+ * JSON serializer emits `{}` and loses the message entirely. Give every error this client
48
+ * rejects with an explicit JSON shape so it survives `JSON.stringify` with a usable message.
49
+ */
50
+ toJSON() {
51
+ return {
52
+ name: this.name,
53
+ message: this.message,
54
+ operation: this.operation,
55
+ unitId: this.unitId,
56
+ timeoutMs: this.timeoutMs
57
+ };
58
+ }
44
59
  }
45
60
  exports.ModbusOperationTimeoutError = ModbusOperationTimeoutError;
61
+ /**
62
+ * Thrown when the client refuses a transaction because the unit is **already known to be down**,
63
+ * as opposed to a transaction that was actually attempted and failed.
64
+ *
65
+ * The distinction matters for logging. A poisoned socket produces exactly one genuine event (the
66
+ * timeout that poisoned it), but every read that lands during the outage would otherwise throw an
67
+ * error indistinguishable from real I/O failure — so a consumer catching per read has no choice but
68
+ * to log each one at ERROR. Callers should log the first {@link SunspecUnavailableError} of an
69
+ * outage (or nothing at all: the SDK already logs the transition) and stay quiet on the rest.
70
+ *
71
+ * {@link sinceMs} is how long the unit has been in this state, so a consumer that does want one
72
+ * line can say how stale the link is without tracking the outage itself.
73
+ */
74
+ class SunspecUnavailableError extends Error {
75
+ reason;
76
+ unitId;
77
+ sinceMs;
78
+ constructor(reason, unitId, sinceMs) {
79
+ super(`Modbus unit ${unitId} is unavailable (${reason}, for ${sinceMs}ms) — ` +
80
+ `transaction refused without attempting I/O`);
81
+ this.reason = reason;
82
+ this.unitId = unitId;
83
+ this.sinceMs = sinceMs;
84
+ this.name = 'SunspecUnavailableError';
85
+ }
86
+ /** See {@link ModbusOperationTimeoutError.toJSON}. */
87
+ toJSON() {
88
+ return {
89
+ name: this.name,
90
+ message: this.message,
91
+ reason: this.reason,
92
+ unitId: this.unitId,
93
+ sinceMs: this.sinceMs
94
+ };
95
+ }
96
+ }
97
+ exports.SunspecUnavailableError = SunspecUnavailableError;
98
+ /**
99
+ * Type guard for {@link SunspecUnavailableError}. Prefer this over `instanceof` at package
100
+ * boundaries, where a duplicated copy of the SDK in the module graph would break identity.
101
+ */
102
+ function isSunspecUnavailableError(error) {
103
+ return error instanceof Error && error.name === 'SunspecUnavailableError';
104
+ }
46
105
  /**
47
106
  * Module-level registry: one SunspecModbusClient per network device (host:port).
48
107
  * Refcounted so the underlying connection only tears down when the last consumer releases.
@@ -53,7 +112,7 @@ const registryKey = (host, port) => `${host}:${port}`;
53
112
  * Get (or create) the singleton SunspecModbusClient for this network device.
54
113
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
55
114
  *
56
- * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
115
+ * NOTE: `transport`, `resilience` and `modbusFactory` are only applied when the client is FIRST
57
116
  * created for a given host:port. Because the client is cached and refcounted, a later caller
58
117
  * passing different config receives the already-created instance and its config is ignored.
59
118
  *
@@ -61,11 +120,11 @@ const registryKey = (host, port) => `${host}:${port}`;
61
120
  * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
62
121
  * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
63
122
  */
64
- function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience, modbusFactory) {
123
+ function getOrCreateSunspecClient(energyApp, host, port = 502, transport, resilience, modbusFactory) {
65
124
  const key = registryKey(host, port);
66
125
  let entry = CLIENT_REGISTRY.get(key);
67
126
  if (!entry) {
68
- entry = { client: new SunspecModbusClient(energyApp, pacing, resilience, modbusFactory), refcount: 0 };
127
+ entry = { client: new SunspecModbusClient(energyApp, transport, resilience, modbusFactory), refcount: 0 };
69
128
  CLIENT_REGISTRY.set(key, entry);
70
129
  }
71
130
  entry.refcount++;
@@ -130,7 +189,7 @@ async function retryAsync(fn, opts) {
130
189
  }
131
190
  class SunspecModbusClient {
132
191
  energyApp;
133
- pacing;
192
+ transport;
134
193
  modbusFactory;
135
194
  // Per-unit Modbus instance/reader/discovered-models maps. One client = one network device,
136
195
  // many unit IDs share that client (each unit ID is one EnergyAppModbusInstance underneath).
@@ -171,18 +230,29 @@ class SunspecModbusClient {
171
230
  // transaction's framing. So a poisoned unit refuses further I/O until reconnectUnit() tears
172
231
  // the socket down and reopens it (which clears the flag).
173
232
  poisonedUnits = new Set();
233
+ // Wall-clock of the transition INTO the poisoned state, per unit. Survives the close half of a
234
+ // recycle (`_closeUnit` clears the poison flag, not this) so the reopen can report how long the
235
+ // outage lasted. Cleared on the recovery log, which is the one place the outage is considered
236
+ // over. Presence here is "was poisoned at some point since the last successful open".
237
+ poisonedAtByUnit = new Map();
174
238
  // Wall-clock of each unit's last SUCCESSFUL transaction. Drives half-open detection: a socket
175
239
  // the transport still reports connected but that has gone quiet past staleSocketMs is presumed
176
240
  // dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
177
241
  lastOkAtByUnit = new Map();
242
+ // Consecutive failed (re)connect attempts, keyed by attempt target. Drives transition-only
243
+ // logging: the first failure of a run is the news, every repeat while the peer stays down is
244
+ // the same news again. Cleared on the first success for that key.
245
+ consecutiveConnectFailures = new Map();
178
246
  constructor(
179
247
  // The host application. Only used to obtain the default Modbus backend via
180
248
  // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
181
249
  energyApp,
182
- // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
183
- // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
184
- // connection. An empty object leaves both undefined so the SDK applies its own defaults.
185
- pacing = {},
250
+ // Opt-in transport options (all default off). Passed straight through to
251
+ // `useModbus().connect()`, which serializes frames (`noParallelRequests`), spaces them
252
+ // (`waitBetweenMessagesMs`) and decides whether the socket comes from the host's shared pool
253
+ // (`pooledConnection`). An empty object leaves them all undefined so the SDK applies its own
254
+ // defaults. Typed as the superset so a plain IModbusPacingConfig still assigns.
255
+ transport = {},
186
256
  // Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
187
257
  // so omitted fields keep their defaults.
188
258
  resilience = {},
@@ -194,7 +264,7 @@ class SunspecModbusClient {
194
264
  // connections on its own schedule and needs a factory to call.
195
265
  modbusFactory) {
196
266
  this.energyApp = energyApp;
197
- this.pacing = pacing;
267
+ this.transport = transport;
198
268
  this.modbusFactory = modbusFactory;
199
269
  if (!energyApp && !modbusFactory) {
200
270
  throw new Error("SunspecModbusClient requires either an EnergyApp or a modbusFactory");
@@ -365,21 +435,29 @@ class SunspecModbusClient {
365
435
  }
366
436
  const { primaryHost, secondaryHost, port } = this.connectionParams;
367
437
  const units = [...this.knownUnits];
368
- console.log(`Attempting to reconnect to primary host ${primaryHost}:${port} units [${units.join(',')}]...`);
438
+ const failureKey = 'reconnect:all';
439
+ const retrying = this.isRetryingAfterFailure(failureKey);
440
+ const logAttempt = (message) => { if (retrying)
441
+ console.debug(message);
442
+ else
443
+ console.log(message); };
444
+ logAttempt(`Attempting to reconnect to primary host ${primaryHost}:${port} units [${units.join(',')}]...`);
369
445
  const primarySuccess = await this.attemptConnection(primaryHost, port, units);
370
446
  if (primarySuccess) {
447
+ this.clearConnectFailures(failureKey);
371
448
  console.log(`Successfully reconnected to primary host ${primaryHost}:${port} units [${units.join(',')}]`);
372
449
  return true;
373
450
  }
374
451
  if (secondaryHost && secondaryHost !== primaryHost) {
375
- console.log(`Primary host failed, attempting secondary host ${secondaryHost}:${port} units [${units.join(',')}]...`);
452
+ logAttempt(`Primary host failed, attempting secondary host ${secondaryHost}:${port} units [${units.join(',')}]...`);
376
453
  const secondarySuccess = await this.attemptConnection(secondaryHost, port, units);
377
454
  if (secondarySuccess) {
455
+ this.clearConnectFailures(failureKey);
378
456
  console.log(`Successfully reconnected to secondary host ${secondaryHost}:${port} units [${units.join(',')}]`);
379
457
  return true;
380
458
  }
381
459
  }
382
- console.error(`Reconnection failed to all available hosts`);
460
+ this.logConnectFailure(failureKey, `Reconnection failed to all available hosts`);
383
461
  return false;
384
462
  });
385
463
  }
@@ -397,21 +475,29 @@ class SunspecModbusClient {
397
475
  return false;
398
476
  }
399
477
  const { primaryHost, secondaryHost, port } = this.connectionParams;
400
- console.log(`Attempting to reconnect unit ${unitId} on primary host ${primaryHost}:${port}...`);
478
+ const failureKey = `reconnect:unit${unitId}`;
479
+ const retrying = this.isRetryingAfterFailure(failureKey);
480
+ const logAttempt = (message) => { if (retrying)
481
+ console.debug(message);
482
+ else
483
+ console.log(message); };
484
+ logAttempt(`Attempting to reconnect unit ${unitId} on primary host ${primaryHost}:${port}...`);
401
485
  const primarySuccess = await this.attemptConnection(primaryHost, port, [unitId]);
402
486
  if (primarySuccess) {
487
+ this.clearConnectFailures(failureKey);
403
488
  console.log(`Successfully reconnected unit ${unitId} on primary host ${primaryHost}:${port}`);
404
489
  return true;
405
490
  }
406
491
  if (secondaryHost && secondaryHost !== primaryHost) {
407
- console.log(`Primary host failed for unit ${unitId}, attempting secondary host ${secondaryHost}:${port}...`);
492
+ logAttempt(`Primary host failed for unit ${unitId}, attempting secondary host ${secondaryHost}:${port}...`);
408
493
  const secondarySuccess = await this.attemptConnection(secondaryHost, port, [unitId]);
409
494
  if (secondarySuccess) {
495
+ this.clearConnectFailures(failureKey);
410
496
  console.log(`Successfully reconnected unit ${unitId} on secondary host ${secondaryHost}:${port}`);
411
497
  return true;
412
498
  }
413
499
  }
414
- console.error(`Reconnection failed for unit ${unitId} on all available hosts`);
500
+ this.logConnectFailure(failureKey, `Reconnection failed for unit ${unitId} on all available hosts`);
415
501
  return false;
416
502
  });
417
503
  }
@@ -426,15 +512,17 @@ class SunspecModbusClient {
426
512
  await this._closeUnit(unitId);
427
513
  }
428
514
  }
515
+ const failureKey = `connect:${host}:${port}:[${units.join(',')}]`;
429
516
  try {
430
517
  for (const unitId of units) {
431
518
  await this._openUnit(host, port, unitId);
432
519
  }
520
+ this.clearConnectFailures(failureKey);
433
521
  console.log(`Connection attempt to ${host}:${port} units [${units.join(',')}] succeeded (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
434
522
  return true;
435
523
  }
436
524
  catch (error) {
437
- console.error(`Connection attempt to ${host}:${port} failed: ${error}`);
525
+ this.logConnectFailure(failureKey, `Connection attempt to ${host}:${port} failed: ${error}`);
438
526
  return false;
439
527
  }
440
528
  }
@@ -516,8 +604,9 @@ class SunspecModbusClient {
516
604
  key: this.connectionParams?.key,
517
605
  ca: this.connectionParams?.ca,
518
606
  rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
519
- noParallelRequests: this.pacing.noParallelRequests,
520
- waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
607
+ noParallelRequests: this.transport.noParallelRequests,
608
+ waitBetweenMessagesMs: this.transport.waitBetweenMessagesMs,
609
+ pooledConnection: this.transport.pooledConnection
521
610
  }));
522
611
  if (!candidate) {
523
612
  throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
@@ -528,6 +617,7 @@ class SunspecModbusClient {
528
617
  // Fresh socket: clear any prior poison and start the freshness clock so a just-opened
529
618
  // unit isn't immediately judged stale.
530
619
  this.poisonedUnits.delete(unitId);
620
+ this.logPoisonRecovery(unitId);
531
621
  this.lastOkAtByUnit.set(unitId, Date.now());
532
622
  this.connectionHealth.recordSuccess();
533
623
  this.recordOpen();
@@ -552,7 +642,9 @@ class SunspecModbusClient {
552
642
  this.faultTolerantReaders.delete(unitId);
553
643
  this.discoveredModelsByUnit.delete(unitId);
554
644
  this.discoveredModelListByUnit.delete(unitId);
555
- // Drop per-unit resilience state so a later reopen starts clean.
645
+ // Drop per-unit resilience state so a later reopen starts clean. `poisonedAtByUnit` is
646
+ // deliberately NOT dropped: a recycle closes before it reopens, and the reopen is where the
647
+ // recovery line reports how long the unit was down.
556
648
  this.poisonedUnits.delete(unitId);
557
649
  this.lastOkAtByUnit.delete(unitId);
558
650
  if (instance) {
@@ -612,10 +704,26 @@ class SunspecModbusClient {
612
704
  */
613
705
  async guardTransaction(unitId, fn) {
614
706
  if (this.poisonedUnits.has(unitId)) {
615
- throw new Error(`Modbus unit ${unitId} socket is poisoned (awaiting reconnect) — transaction refused`);
707
+ // Known-down, not newly-failed: a typed rejection so callers can stay quiet for the
708
+ // duration of an outage the SDK has already logged once. See SunspecUnavailableError.
709
+ const since = this.poisonedAtByUnit.get(unitId);
710
+ throw new SunspecUnavailableError('socket-poisoned', unitId, since === undefined ? 0 : Date.now() - since);
616
711
  }
712
+ let op;
617
713
  try {
618
- const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, fn);
714
+ op = fn();
715
+ }
716
+ catch (error) {
717
+ // A transport throws synchronously (rather than rejecting) when it refuses the
718
+ // transaction before it ever reaches the wire — the socket was closed underneath us,
719
+ // e.g. a poll in flight racing a shutdown. The link is dead, so poison the unit the
720
+ // same way a timeout does; otherwise the client keeps believing the socket is open and
721
+ // every later read repeats the throw with nothing triggering a reconnect.
722
+ this.invalidateUnit(unitId, `transaction threw synchronously (${error})`);
723
+ throw error;
724
+ }
725
+ try {
726
+ const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, () => op);
619
727
  this.lastOkAtByUnit.set(unitId, Date.now());
620
728
  return result;
621
729
  }
@@ -630,28 +738,100 @@ class SunspecModbusClient {
630
738
  * Race `fn` against a timeout. If the timeout wins, reject with a {@link ModbusOperationTimeoutError};
631
739
  * the abandoned `fn` promise keeps running (JS can't cancel it) but is no longer awaited. The
632
740
  * timer is always cleared so a fast `fn` doesn't keep the event loop alive.
741
+ *
742
+ * `fn()` is invoked inside a try/catch rather than inline in the Promise.race argument list. A
743
+ * transport can throw synchronously (a transaction issued against an already-closed socket), and
744
+ * evaluating it while the array literal is built means the throw escapes before Promise.race
745
+ * exists: nothing ever consumes `timeout`, `.finally()` never runs, and the armed timer rejects
746
+ * `timeoutMs` later into an empty stack — an unhandled rejection that kills the process, blaming
747
+ * a timeout for a failure that actually happened a full timeout window earlier.
633
748
  */
634
749
  withTimeout(operation, unitId, timeoutMs, fn) {
635
750
  let timer;
636
751
  const timeout = new Promise((_, reject) => {
637
752
  timer = setTimeout(() => reject(new ModbusOperationTimeoutError(operation, unitId, timeoutMs)), timeoutMs);
638
753
  });
639
- return Promise.race([fn(), timeout]).finally(() => {
754
+ let op;
755
+ try {
756
+ op = fn();
757
+ }
758
+ catch (err) {
759
+ // Nothing will race `timeout`; disarm it so it can't reject unobserved.
760
+ if (timer !== undefined)
761
+ clearTimeout(timer);
762
+ return Promise.reject(err);
763
+ }
764
+ return Promise.race([op, timeout]).finally(() => {
640
765
  if (timer !== undefined)
641
766
  clearTimeout(timer);
642
767
  });
643
768
  }
769
+ /**
770
+ * Log a failed Modbus transaction from a reader/writer catch block.
771
+ *
772
+ * A {@link SunspecUnavailableError} is not a failure — it is this client refusing I/O on a link
773
+ * it has already reported dead once (one WARN on the transition, one INFO on recovery). Logging
774
+ * it at ERROR once per read, per read path, per poll cycle, for the whole outage, is what buries
775
+ * the errors that are actually actionable. So it drops to debug; everything else stays ERROR.
776
+ */
777
+ logConnectFailure(key, message) {
778
+ const count = (this.consecutiveConnectFailures.get(key) ?? 0) + 1;
779
+ this.consecutiveConnectFailures.set(key, count);
780
+ if (count === 1) {
781
+ console.error(message);
782
+ }
783
+ else {
784
+ console.debug(`${message} (consecutive failure #${count})`);
785
+ }
786
+ }
787
+ /** True while `key`'s last attempt failed — used to keep repeat attempt chatter at debug. */
788
+ isRetryingAfterFailure(key) {
789
+ return (this.consecutiveConnectFailures.get(key) ?? 0) > 0;
790
+ }
791
+ /** Forget `key`'s failure run on a success, so the next outage logs its first failure again. */
792
+ clearConnectFailures(key) {
793
+ this.consecutiveConnectFailures.delete(key);
794
+ }
795
+ logTransactionError(context, error) {
796
+ if (isSunspecUnavailableError(error)) {
797
+ console.debug(`${context}: ${error.message}`);
798
+ return;
799
+ }
800
+ console.error(`${context}: ${error}`);
801
+ }
644
802
  /**
645
803
  * Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
646
804
  * gate immediately, so isHealthy() flips false this cycle instead of after the coarse
647
805
  * 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
648
806
  */
649
807
  poisonUnit(unitId, error) {
808
+ this.enterPoisoned(unitId, `${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
809
+ this.connectionHealth.recordFailure(error);
810
+ }
811
+ /**
812
+ * Enter the poisoned state for a unit, logging the TRANSITION only. Everything downstream of
813
+ * this (every refused read, every poll cycle) is the same known state and must stay silent —
814
+ * one WARN in, one INFO out (see {@link logPoisonRecovery}), nothing in between.
815
+ */
816
+ enterPoisoned(unitId, reason) {
650
817
  if (!this.poisonedUnits.has(unitId)) {
651
- console.warn(`SunspecModbusClient: ${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
818
+ console.warn(`SunspecModbusClient: ${reason}`);
819
+ this.poisonedAtByUnit.set(unitId, Date.now());
652
820
  }
653
821
  this.poisonedUnits.add(unitId);
654
- this.connectionHealth.recordFailure(error);
822
+ }
823
+ /**
824
+ * Close out a poisoned episode on a successful (re)open: one INFO carrying how long the unit
825
+ * was refusing I/O. No-op for a unit that was never poisoned, so a normal first connect stays
826
+ * quiet.
827
+ */
828
+ logPoisonRecovery(unitId) {
829
+ const since = this.poisonedAtByUnit.get(unitId);
830
+ if (since === undefined)
831
+ return;
832
+ this.poisonedAtByUnit.delete(unitId);
833
+ console.info(`SunspecModbusClient: unit ${unitId} socket recovered after reconnect ` +
834
+ `(poisonedForMs=${Date.now() - since})`);
655
835
  }
656
836
  /**
657
837
  * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
@@ -666,10 +846,7 @@ class SunspecModbusClient {
666
846
  * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
667
847
  */
668
848
  invalidateUnit(unitId, reason) {
669
- if (!this.poisonedUnits.has(unitId)) {
670
- console.warn(`SunspecModbusClient: invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
671
- }
672
- this.poisonedUnits.add(unitId);
849
+ this.enterPoisoned(unitId, `invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
673
850
  this.connectionHealth.recordFailure(new Error(reason));
674
851
  }
675
852
  /**
@@ -928,7 +1105,7 @@ class SunspecModbusClient {
928
1105
  }
929
1106
  }
930
1107
  catch (error) {
931
- console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
1108
+ this.logTransactionError(`Error during model discovery at address ${currentAddress} (unit ${unitId})`, error);
932
1109
  }
933
1110
  if (discovered.length > 0) {
934
1111
  // Commit the fresh discovery atomically. Keep the FIRST (lowest-address) instance per
@@ -1230,7 +1407,7 @@ class SunspecModbusClient {
1230
1407
  }
1231
1408
  catch (error) {
1232
1409
  this.connectionHealth.recordFailure(error);
1233
- console.error(`Error writing register at address ${address}: ${error}`);
1410
+ this.logTransactionError(`Error writing register at address ${address}`, error);
1234
1411
  throw error;
1235
1412
  }
1236
1413
  }
@@ -1376,7 +1553,7 @@ class SunspecModbusClient {
1376
1553
  return data;
1377
1554
  }
1378
1555
  catch (error) {
1379
- console.error(`Error reading inverter data: ${error}`);
1556
+ this.logTransactionError(`Error reading inverter data`, error);
1380
1557
  return null;
1381
1558
  }
1382
1559
  }
@@ -1440,7 +1617,7 @@ class SunspecModbusClient {
1440
1617
  return data;
1441
1618
  }
1442
1619
  catch (error) {
1443
- console.error(`Error reading single phase inverter data: ${error}`);
1620
+ this.logTransactionError(`Error reading single phase inverter data`, error);
1444
1621
  return null;
1445
1622
  }
1446
1623
  }
@@ -1504,7 +1681,7 @@ class SunspecModbusClient {
1504
1681
  return data;
1505
1682
  }
1506
1683
  catch (error) {
1507
- console.error(`Error reading float inverter data (Model ${blockNumber}): ${error}`);
1684
+ this.logTransactionError(`Error reading float inverter data (Model ${blockNumber})`, error);
1508
1685
  return null;
1509
1686
  }
1510
1687
  }
@@ -1623,7 +1800,7 @@ class SunspecModbusClient {
1623
1800
  return this.extractMPPTScaleFactors(buffer);
1624
1801
  }
1625
1802
  catch (error) {
1626
- console.error(`Error reading MPPT scale factors (unit ${unitId}): ${error}`);
1803
+ this.logTransactionError(`Error reading MPPT scale factors (unit ${unitId})`, error);
1627
1804
  return null;
1628
1805
  }
1629
1806
  }
@@ -1697,7 +1874,7 @@ class SunspecModbusClient {
1697
1874
  return this.extractMPPTModuleData(buffer, model, moduleId, scaleFactors);
1698
1875
  }
1699
1876
  catch (error) {
1700
- console.error(`Error reading MPPT data for module ${moduleId} (unit ${unitId}): ${error}`);
1877
+ this.logTransactionError(`Error reading MPPT data for module ${moduleId} (unit ${unitId})`, error);
1701
1878
  return null;
1702
1879
  }
1703
1880
  }
@@ -1747,7 +1924,7 @@ class SunspecModbusClient {
1747
1924
  }
1748
1925
  }
1749
1926
  catch (error) {
1750
- console.error(`Error reading all MPPT data: ${error}`);
1927
+ this.logTransactionError(`Error reading all MPPT data`, error);
1751
1928
  }
1752
1929
  return mpptData;
1753
1930
  }
@@ -2009,7 +2186,7 @@ class SunspecModbusClient {
2009
2186
  return data;
2010
2187
  }
2011
2188
  catch (error) {
2012
- console.error(`Error reading battery base data: ${error}`);
2189
+ this.logTransactionError(`Error reading battery base data`, error);
2013
2190
  return null;
2014
2191
  }
2015
2192
  }
@@ -2187,7 +2364,7 @@ class SunspecModbusClient {
2187
2364
  }
2188
2365
  }
2189
2366
  catch (error) {
2190
- console.error(`Error reading battery data: ${error}`);
2367
+ this.logTransactionError(`Error reading battery data`, error);
2191
2368
  return null;
2192
2369
  }
2193
2370
  }
@@ -2269,7 +2446,7 @@ class SunspecModbusClient {
2269
2446
  return true;
2270
2447
  }
2271
2448
  catch (error) {
2272
- console.error(`Error writing battery controls: ${error}`);
2449
+ this.logTransactionError(`Error writing battery controls`, error);
2273
2450
  return false;
2274
2451
  }
2275
2452
  }
@@ -2369,7 +2546,7 @@ class SunspecModbusClient {
2369
2546
  return controls;
2370
2547
  }
2371
2548
  catch (error) {
2372
- console.error(`Error reading battery controls: ${error}`);
2549
+ this.logTransactionError(`Error reading battery controls`, error);
2373
2550
  return null;
2374
2551
  }
2375
2552
  }
@@ -2501,7 +2678,7 @@ class SunspecModbusClient {
2501
2678
  return data;
2502
2679
  }
2503
2680
  catch (error) {
2504
- console.error(`Error reading meter data: ${error}`);
2681
+ this.logTransactionError(`Error reading meter data`, error);
2505
2682
  return null;
2506
2683
  }
2507
2684
  }
@@ -2543,7 +2720,7 @@ class SunspecModbusClient {
2543
2720
  return data;
2544
2721
  }
2545
2722
  catch (error) {
2546
- console.error(`Error reading float meter data (Model ${blockNumber}): ${error}`);
2723
+ this.logTransactionError(`Error reading float meter data (Model ${blockNumber})`, error);
2547
2724
  return null;
2548
2725
  }
2549
2726
  }
@@ -2621,7 +2798,7 @@ class SunspecModbusClient {
2621
2798
  return data;
2622
2799
  }
2623
2800
  catch (error) {
2624
- console.error(`Error reading common block: ${error}`);
2801
+ this.logTransactionError(`Error reading common block`, error);
2625
2802
  return null;
2626
2803
  }
2627
2804
  }
@@ -2747,7 +2924,7 @@ class SunspecModbusClient {
2747
2924
  return settings;
2748
2925
  }
2749
2926
  catch (error) {
2750
- console.error(`Error reading inverter settings: ${error}`);
2927
+ this.logTransactionError(`Error reading inverter settings`, error);
2751
2928
  return null;
2752
2929
  }
2753
2930
  }
@@ -2764,74 +2941,76 @@ class SunspecModbusClient {
2764
2941
  try {
2765
2942
  // Read entire model block in a single Modbus call
2766
2943
  const buffer = await this.readModelBlock(unitId, model);
2767
- // Extract scale factors from buffer (offsets 21-23)
2944
+ // Buffer offsets are SunSpec point offsets + 2: readModelBlock() returns the
2945
+ // 2-register model header (ID + length) ahead of the data registers. Scale
2946
+ // factors are points 21-23 -> buffer offsets 23-25.
2768
2947
  const scaleFactors = {
2769
- WMaxLimPct_SF: this.extractValue(buffer, 21, 'int16'),
2770
- OutPFSet_SF: this.extractValue(buffer, 22, 'int16'),
2771
- VArPct_SF: this.extractValue(buffer, 23, 'int16')
2948
+ WMaxLimPct_SF: this.extractValue(buffer, 23, 'int16'),
2949
+ OutPFSet_SF: this.extractValue(buffer, 24, 'int16'),
2950
+ VArPct_SF: this.extractValue(buffer, 25, 'int16')
2772
2951
  };
2773
- this.logRegisterRead(123, 21, 'WMaxLimPct_SF', scaleFactors.WMaxLimPct_SF, 'int16');
2774
- this.logRegisterRead(123, 22, 'OutPFSet_SF', scaleFactors.OutPFSet_SF, 'int16');
2775
- this.logRegisterRead(123, 23, 'VArPct_SF', scaleFactors.VArPct_SF, 'int16');
2952
+ this.logRegisterRead(123, 23, 'WMaxLimPct_SF', scaleFactors.WMaxLimPct_SF, 'int16');
2953
+ this.logRegisterRead(123, 24, 'OutPFSet_SF', scaleFactors.OutPFSet_SF, 'int16');
2954
+ this.logRegisterRead(123, 25, 'VArPct_SF', scaleFactors.VArPct_SF, 'int16');
2776
2955
  // Extract non-scaled fields from buffer
2777
- const connWinTmsRaw = this.extractValue(buffer, 0, 'uint16');
2778
- const connRvrtTmsRaw = this.extractValue(buffer, 1, 'uint16');
2779
- const connRaw = this.extractValue(buffer, 2, 'uint16');
2780
- const wMaxLimPctWinTmsRaw = this.extractValue(buffer, 4, 'uint16');
2781
- const wMaxLimPctRvrtTmsRaw = this.extractValue(buffer, 5, 'uint16');
2782
- const wMaxLimPctRmpTmsRaw = this.extractValue(buffer, 6, 'uint16');
2783
- const wMaxLimEnaRaw = this.extractValue(buffer, 7, 'uint16');
2784
- const outPFSetWinTmsRaw = this.extractValue(buffer, 9, 'uint16');
2785
- const outPFSetRvrtTmsRaw = this.extractValue(buffer, 10, 'uint16');
2786
- const outPFSetRmpTmsRaw = this.extractValue(buffer, 11, 'uint16');
2787
- const outPFSetEnaRaw = this.extractValue(buffer, 12, 'uint16');
2788
- const vArPctWinTmsRaw = this.extractValue(buffer, 16, 'uint16');
2789
- const vArPctRvrtTmsRaw = this.extractValue(buffer, 17, 'uint16');
2790
- const vArPctRmpTmsRaw = this.extractValue(buffer, 18, 'uint16');
2791
- const vArPctModRaw = this.extractValue(buffer, 19, 'uint16');
2792
- const vArPctEnaRaw = this.extractValue(buffer, 20, 'uint16');
2793
- this.logRegisterRead(123, 0, 'Conn_WinTms', connWinTmsRaw, 'uint16');
2794
- this.logRegisterRead(123, 1, 'Conn_RvrtTms', connRvrtTmsRaw, 'uint16');
2795
- this.logRegisterRead(123, 2, 'Conn', connRaw, 'enum16');
2796
- this.logRegisterRead(123, 4, 'WMaxLimPct_WinTms', wMaxLimPctWinTmsRaw, 'uint16');
2797
- this.logRegisterRead(123, 5, 'WMaxLimPct_RvrtTms', wMaxLimPctRvrtTmsRaw, 'uint16');
2798
- this.logRegisterRead(123, 6, 'WMaxLimPct_RmpTms', wMaxLimPctRmpTmsRaw, 'uint16');
2799
- this.logRegisterRead(123, 7, 'WMaxLim_Ena', wMaxLimEnaRaw, 'enum16');
2800
- this.logRegisterRead(123, 9, 'OutPFSet_WinTms', outPFSetWinTmsRaw, 'uint16');
2801
- this.logRegisterRead(123, 10, 'OutPFSet_RvrtTms', outPFSetRvrtTmsRaw, 'uint16');
2802
- this.logRegisterRead(123, 11, 'OutPFSet_RmpTms', outPFSetRmpTmsRaw, 'uint16');
2803
- this.logRegisterRead(123, 12, 'OutPFSet_Ena', outPFSetEnaRaw, 'enum16');
2804
- this.logRegisterRead(123, 16, 'VArPct_WinTms', vArPctWinTmsRaw, 'uint16');
2805
- this.logRegisterRead(123, 17, 'VArPct_RvrtTms', vArPctRvrtTmsRaw, 'uint16');
2806
- this.logRegisterRead(123, 18, 'VArPct_RmpTms', vArPctRmpTmsRaw, 'uint16');
2807
- this.logRegisterRead(123, 19, 'VArPct_Mod', vArPctModRaw, 'enum16');
2808
- this.logRegisterRead(123, 20, 'VArPct_Ena', vArPctEnaRaw, 'enum16');
2956
+ const connWinTmsRaw = this.extractValue(buffer, 2, 'uint16');
2957
+ const connRvrtTmsRaw = this.extractValue(buffer, 3, 'uint16');
2958
+ const connRaw = this.extractValue(buffer, 4, 'uint16');
2959
+ const wMaxLimPctWinTmsRaw = this.extractValue(buffer, 6, 'uint16');
2960
+ const wMaxLimPctRvrtTmsRaw = this.extractValue(buffer, 7, 'uint16');
2961
+ const wMaxLimPctRmpTmsRaw = this.extractValue(buffer, 8, 'uint16');
2962
+ const wMaxLimEnaRaw = this.extractValue(buffer, 9, 'uint16');
2963
+ const outPFSetWinTmsRaw = this.extractValue(buffer, 11, 'uint16');
2964
+ const outPFSetRvrtTmsRaw = this.extractValue(buffer, 12, 'uint16');
2965
+ const outPFSetRmpTmsRaw = this.extractValue(buffer, 13, 'uint16');
2966
+ const outPFSetEnaRaw = this.extractValue(buffer, 14, 'uint16');
2967
+ const vArPctWinTmsRaw = this.extractValue(buffer, 18, 'uint16');
2968
+ const vArPctRvrtTmsRaw = this.extractValue(buffer, 19, 'uint16');
2969
+ const vArPctRmpTmsRaw = this.extractValue(buffer, 20, 'uint16');
2970
+ const vArPctModRaw = this.extractValue(buffer, 21, 'uint16');
2971
+ const vArPctEnaRaw = this.extractValue(buffer, 22, 'uint16');
2972
+ this.logRegisterRead(123, 2, 'Conn_WinTms', connWinTmsRaw, 'uint16');
2973
+ this.logRegisterRead(123, 3, 'Conn_RvrtTms', connRvrtTmsRaw, 'uint16');
2974
+ this.logRegisterRead(123, 4, 'Conn', connRaw, 'enum16');
2975
+ this.logRegisterRead(123, 6, 'WMaxLimPct_WinTms', wMaxLimPctWinTmsRaw, 'uint16');
2976
+ this.logRegisterRead(123, 7, 'WMaxLimPct_RvrtTms', wMaxLimPctRvrtTmsRaw, 'uint16');
2977
+ this.logRegisterRead(123, 8, 'WMaxLimPct_RmpTms', wMaxLimPctRmpTmsRaw, 'uint16');
2978
+ this.logRegisterRead(123, 9, 'WMaxLim_Ena', wMaxLimEnaRaw, 'enum16');
2979
+ this.logRegisterRead(123, 11, 'OutPFSet_WinTms', outPFSetWinTmsRaw, 'uint16');
2980
+ this.logRegisterRead(123, 12, 'OutPFSet_RvrtTms', outPFSetRvrtTmsRaw, 'uint16');
2981
+ this.logRegisterRead(123, 13, 'OutPFSet_RmpTms', outPFSetRmpTmsRaw, 'uint16');
2982
+ this.logRegisterRead(123, 14, 'OutPFSet_Ena', outPFSetEnaRaw, 'enum16');
2983
+ this.logRegisterRead(123, 18, 'VArPct_WinTms', vArPctWinTmsRaw, 'uint16');
2984
+ this.logRegisterRead(123, 19, 'VArPct_RvrtTms', vArPctRvrtTmsRaw, 'uint16');
2985
+ this.logRegisterRead(123, 20, 'VArPct_RmpTms', vArPctRmpTmsRaw, 'uint16');
2986
+ this.logRegisterRead(123, 21, 'VArPct_Mod', vArPctModRaw, 'enum16');
2987
+ this.logRegisterRead(123, 22, 'VArPct_Ena', vArPctEnaRaw, 'enum16');
2809
2988
  const controls = {
2810
2989
  blockNumber: 123,
2811
2990
  blockAddress: model.address,
2812
2991
  blockLength: model.length,
2813
- // Connection control - Offsets 0-2
2992
+ // Connection control - points 0-2 (buffer 2-4)
2814
2993
  Conn_WinTms: connWinTmsRaw,
2815
2994
  Conn_RvrtTms: connRvrtTmsRaw,
2816
2995
  Conn: connRaw,
2817
- // Power limit control - Offsets 3-7
2818
- WMaxLimPct: this.applyScaleFactor(this.extractValue(buffer, 3, 'uint16'), scaleFactors.WMaxLimPct_SF, 'uint16', 'Power Limit Percentage', 3, 123),
2996
+ // Power limit control - points 3-7 (buffer 5-9)
2997
+ WMaxLimPct: this.applyScaleFactor(this.extractValue(buffer, 5, 'uint16'), scaleFactors.WMaxLimPct_SF, 'uint16', 'Power Limit Percentage', 5, 123),
2819
2998
  WMaxLimPct_SF: scaleFactors.WMaxLimPct_SF,
2820
2999
  WMaxLimPct_WinTms: wMaxLimPctWinTmsRaw,
2821
3000
  WMaxLimPct_RvrtTms: wMaxLimPctRvrtTmsRaw,
2822
3001
  WMaxLimPct_RmpTms: wMaxLimPctRmpTmsRaw,
2823
3002
  WMaxLim_Ena: wMaxLimEnaRaw,
2824
- // Power factor control - Offsets 8-12
2825
- OutPFSet: this.applyScaleFactor(this.extractValue(buffer, 8, 'int16'), scaleFactors.OutPFSet_SF, 'int16', 'Output Power Factor Set', 8, 123),
3003
+ // Power factor control - points 8-12 (buffer 10-14)
3004
+ OutPFSet: this.applyScaleFactor(this.extractValue(buffer, 10, 'int16'), scaleFactors.OutPFSet_SF, 'int16', 'Output Power Factor Set', 10, 123),
2826
3005
  OutPFSet_SF: scaleFactors.OutPFSet_SF,
2827
3006
  OutPFSet_WinTms: outPFSetWinTmsRaw,
2828
3007
  OutPFSet_RvrtTms: outPFSetRvrtTmsRaw,
2829
3008
  OutPFSet_RmpTms: outPFSetRmpTmsRaw,
2830
3009
  OutPFSet_Ena: outPFSetEnaRaw,
2831
- // Reactive power control - Offsets 13-20
2832
- VArWMaxPct: this.applyScaleFactor(this.extractValue(buffer, 13, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Reactive Power at Max Power %', 13, 123),
2833
- VArMaxPct: this.applyScaleFactor(this.extractValue(buffer, 14, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Max Reactive Power %', 14, 123),
2834
- VArAvalPct: this.applyScaleFactor(this.extractValue(buffer, 15, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Available Reactive Power %', 15, 123),
3010
+ // Reactive power control - points 13-20 (buffer 15-22)
3011
+ VArWMaxPct: this.applyScaleFactor(this.extractValue(buffer, 15, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Reactive Power at Max Power %', 15, 123),
3012
+ VArMaxPct: this.applyScaleFactor(this.extractValue(buffer, 16, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Max Reactive Power %', 16, 123),
3013
+ VArAvalPct: this.applyScaleFactor(this.extractValue(buffer, 17, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Available Reactive Power %', 17, 123),
2835
3014
  VArPct_SF: scaleFactors.VArPct_SF,
2836
3015
  VArPct_WinTms: vArPctWinTmsRaw,
2837
3016
  VArPct_RvrtTms: vArPctRvrtTmsRaw,
@@ -2843,7 +3022,7 @@ class SunspecModbusClient {
2843
3022
  return controls;
2844
3023
  }
2845
3024
  catch (error) {
2846
- console.error(`Error reading inverter controls: ${error}`);
3025
+ this.logTransactionError(`Error reading inverter controls`, error);
2847
3026
  return null;
2848
3027
  }
2849
3028
  }
@@ -2881,7 +3060,7 @@ class SunspecModbusClient {
2881
3060
  return true;
2882
3061
  }
2883
3062
  catch (error) {
2884
- console.error(`Error writing inverter settings: ${error}`);
3063
+ this.logTransactionError(`Error writing inverter settings`, error);
2885
3064
  return false;
2886
3065
  }
2887
3066
  }
@@ -2894,43 +3073,45 @@ class SunspecModbusClient {
2894
3073
  console.error(`Controls model 123 not found on unit ${unitId}`);
2895
3074
  return false;
2896
3075
  }
3076
+ // model.address points at the 2-register model header (ID + length), so a
3077
+ // SunSpec point at offset N lives at baseAddr + 2 + N.
2897
3078
  const baseAddr = model.address;
2898
3079
  try {
2899
3080
  // Per-field inverter-control writes are debug-only; the high-level callers
2900
3081
  // (`setFeedInLimit`, etc.) still log the action and outcome at info level.
2901
3082
  if (controls.Conn !== undefined) {
2902
- await this.writeRegisterValue(unitId, baseAddr + 2, controls.Conn, 'uint16');
3083
+ await this.writeRegisterValue(unitId, baseAddr + 4, controls.Conn, 'uint16');
2903
3084
  console.debug(`Set connection control to ${controls.Conn}`);
2904
3085
  }
2905
- // Power limit control (Register 3) - needs scale factor
3086
+ // Power limit control (point 3 -> baseAddr + 5) - needs scale factor
2906
3087
  if (controls.WMaxLimPct !== undefined) {
2907
- const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 21, 1, 'int16');
3088
+ const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 23, 1, 'int16');
2908
3089
  const scaledValue = Math.round(controls.WMaxLimPct / Math.pow(10, scaleFactor));
2909
- await this.writeRegisterValue(unitId, baseAddr + 3, scaledValue, 'uint16');
3090
+ await this.writeRegisterValue(unitId, baseAddr + 5, scaledValue, 'uint16');
2910
3091
  console.debug(`Set power limit to ${controls.WMaxLimPct}% (scaled: ${scaledValue})`);
2911
3092
  }
2912
- // Throttle enable/disable (Register 7)
3093
+ // Throttle enable/disable (point 7 -> baseAddr + 9)
2913
3094
  if (controls.WMaxLim_Ena !== undefined) {
2914
- await this.writeRegisterValue(unitId, baseAddr + 7, controls.WMaxLim_Ena, 'uint16');
3095
+ await this.writeRegisterValue(unitId, baseAddr + 9, controls.WMaxLim_Ena, 'uint16');
2915
3096
  console.debug(`Set throttle enable to ${controls.WMaxLim_Ena}`);
2916
3097
  }
2917
- // Power factor control (Register 8) - needs scale factor
3098
+ // Power factor control (point 8 -> baseAddr + 10) - needs scale factor
2918
3099
  if (controls.OutPFSet !== undefined) {
2919
- const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 22, 1, 'int16');
3100
+ const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 24, 1, 'int16');
2920
3101
  const scaledValue = Math.round(controls.OutPFSet / Math.pow(10, scaleFactor));
2921
- await this.writeRegisterValue(unitId, baseAddr + 8, scaledValue, 'int16');
3102
+ await this.writeRegisterValue(unitId, baseAddr + 10, scaledValue, 'int16');
2922
3103
  console.debug(`Set power factor to ${controls.OutPFSet} (scaled: ${scaledValue})`);
2923
3104
  }
2924
- // Power factor enable/disable (Register 12)
3105
+ // Power factor enable/disable (point 12 -> baseAddr + 14)
2925
3106
  if (controls.OutPFSet_Ena !== undefined) {
2926
- await this.writeRegisterValue(unitId, baseAddr + 12, controls.OutPFSet_Ena, 'uint16');
3107
+ await this.writeRegisterValue(unitId, baseAddr + 14, controls.OutPFSet_Ena, 'uint16');
2927
3108
  console.debug(`Set PF enable to ${controls.OutPFSet_Ena}`);
2928
3109
  }
2929
3110
  console.debug('Inverter controls written successfully');
2930
3111
  return true;
2931
3112
  }
2932
3113
  catch (error) {
2933
- console.error(`Error writing inverter controls: ${error}`);
3114
+ this.logTransactionError(`Error writing inverter controls`, error);
2934
3115
  return false;
2935
3116
  }
2936
3117
  }