@enyo-energy/sunspec-sdk 0.0.104 → 1.0.0

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,7 +704,10 @@ 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
  }
617
712
  try {
618
713
  const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, fn);
@@ -641,17 +736,72 @@ class SunspecModbusClient {
641
736
  clearTimeout(timer);
642
737
  });
643
738
  }
739
+ /**
740
+ * Log a failed Modbus transaction from a reader/writer catch block.
741
+ *
742
+ * A {@link SunspecUnavailableError} is not a failure — it is this client refusing I/O on a link
743
+ * it has already reported dead once (one WARN on the transition, one INFO on recovery). Logging
744
+ * it at ERROR once per read, per read path, per poll cycle, for the whole outage, is what buries
745
+ * the errors that are actually actionable. So it drops to debug; everything else stays ERROR.
746
+ */
747
+ logConnectFailure(key, message) {
748
+ const count = (this.consecutiveConnectFailures.get(key) ?? 0) + 1;
749
+ this.consecutiveConnectFailures.set(key, count);
750
+ if (count === 1) {
751
+ console.error(message);
752
+ }
753
+ else {
754
+ console.debug(`${message} (consecutive failure #${count})`);
755
+ }
756
+ }
757
+ /** True while `key`'s last attempt failed — used to keep repeat attempt chatter at debug. */
758
+ isRetryingAfterFailure(key) {
759
+ return (this.consecutiveConnectFailures.get(key) ?? 0) > 0;
760
+ }
761
+ /** Forget `key`'s failure run on a success, so the next outage logs its first failure again. */
762
+ clearConnectFailures(key) {
763
+ this.consecutiveConnectFailures.delete(key);
764
+ }
765
+ logTransactionError(context, error) {
766
+ if (isSunspecUnavailableError(error)) {
767
+ console.debug(`${context}: ${error.message}`);
768
+ return;
769
+ }
770
+ console.error(`${context}: ${error}`);
771
+ }
644
772
  /**
645
773
  * Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
646
774
  * gate immediately, so isHealthy() flips false this cycle instead of after the coarse
647
775
  * 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
648
776
  */
649
777
  poisonUnit(unitId, error) {
778
+ this.enterPoisoned(unitId, `${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
779
+ this.connectionHealth.recordFailure(error);
780
+ }
781
+ /**
782
+ * Enter the poisoned state for a unit, logging the TRANSITION only. Everything downstream of
783
+ * this (every refused read, every poll cycle) is the same known state and must stay silent —
784
+ * one WARN in, one INFO out (see {@link logPoisonRecovery}), nothing in between.
785
+ */
786
+ enterPoisoned(unitId, reason) {
650
787
  if (!this.poisonedUnits.has(unitId)) {
651
- console.warn(`SunspecModbusClient: ${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
788
+ console.warn(`SunspecModbusClient: ${reason}`);
789
+ this.poisonedAtByUnit.set(unitId, Date.now());
652
790
  }
653
791
  this.poisonedUnits.add(unitId);
654
- this.connectionHealth.recordFailure(error);
792
+ }
793
+ /**
794
+ * Close out a poisoned episode on a successful (re)open: one INFO carrying how long the unit
795
+ * was refusing I/O. No-op for a unit that was never poisoned, so a normal first connect stays
796
+ * quiet.
797
+ */
798
+ logPoisonRecovery(unitId) {
799
+ const since = this.poisonedAtByUnit.get(unitId);
800
+ if (since === undefined)
801
+ return;
802
+ this.poisonedAtByUnit.delete(unitId);
803
+ console.info(`SunspecModbusClient: unit ${unitId} socket recovered after reconnect ` +
804
+ `(poisonedForMs=${Date.now() - since})`);
655
805
  }
656
806
  /**
657
807
  * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
@@ -666,10 +816,7 @@ class SunspecModbusClient {
666
816
  * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
667
817
  */
668
818
  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);
819
+ this.enterPoisoned(unitId, `invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
673
820
  this.connectionHealth.recordFailure(new Error(reason));
674
821
  }
675
822
  /**
@@ -928,7 +1075,7 @@ class SunspecModbusClient {
928
1075
  }
929
1076
  }
930
1077
  catch (error) {
931
- console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
1078
+ this.logTransactionError(`Error during model discovery at address ${currentAddress} (unit ${unitId})`, error);
932
1079
  }
933
1080
  if (discovered.length > 0) {
934
1081
  // Commit the fresh discovery atomically. Keep the FIRST (lowest-address) instance per
@@ -1230,7 +1377,7 @@ class SunspecModbusClient {
1230
1377
  }
1231
1378
  catch (error) {
1232
1379
  this.connectionHealth.recordFailure(error);
1233
- console.error(`Error writing register at address ${address}: ${error}`);
1380
+ this.logTransactionError(`Error writing register at address ${address}`, error);
1234
1381
  throw error;
1235
1382
  }
1236
1383
  }
@@ -1376,7 +1523,7 @@ class SunspecModbusClient {
1376
1523
  return data;
1377
1524
  }
1378
1525
  catch (error) {
1379
- console.error(`Error reading inverter data: ${error}`);
1526
+ this.logTransactionError(`Error reading inverter data`, error);
1380
1527
  return null;
1381
1528
  }
1382
1529
  }
@@ -1440,7 +1587,7 @@ class SunspecModbusClient {
1440
1587
  return data;
1441
1588
  }
1442
1589
  catch (error) {
1443
- console.error(`Error reading single phase inverter data: ${error}`);
1590
+ this.logTransactionError(`Error reading single phase inverter data`, error);
1444
1591
  return null;
1445
1592
  }
1446
1593
  }
@@ -1504,7 +1651,7 @@ class SunspecModbusClient {
1504
1651
  return data;
1505
1652
  }
1506
1653
  catch (error) {
1507
- console.error(`Error reading float inverter data (Model ${blockNumber}): ${error}`);
1654
+ this.logTransactionError(`Error reading float inverter data (Model ${blockNumber})`, error);
1508
1655
  return null;
1509
1656
  }
1510
1657
  }
@@ -1623,7 +1770,7 @@ class SunspecModbusClient {
1623
1770
  return this.extractMPPTScaleFactors(buffer);
1624
1771
  }
1625
1772
  catch (error) {
1626
- console.error(`Error reading MPPT scale factors (unit ${unitId}): ${error}`);
1773
+ this.logTransactionError(`Error reading MPPT scale factors (unit ${unitId})`, error);
1627
1774
  return null;
1628
1775
  }
1629
1776
  }
@@ -1697,7 +1844,7 @@ class SunspecModbusClient {
1697
1844
  return this.extractMPPTModuleData(buffer, model, moduleId, scaleFactors);
1698
1845
  }
1699
1846
  catch (error) {
1700
- console.error(`Error reading MPPT data for module ${moduleId} (unit ${unitId}): ${error}`);
1847
+ this.logTransactionError(`Error reading MPPT data for module ${moduleId} (unit ${unitId})`, error);
1701
1848
  return null;
1702
1849
  }
1703
1850
  }
@@ -1747,7 +1894,7 @@ class SunspecModbusClient {
1747
1894
  }
1748
1895
  }
1749
1896
  catch (error) {
1750
- console.error(`Error reading all MPPT data: ${error}`);
1897
+ this.logTransactionError(`Error reading all MPPT data`, error);
1751
1898
  }
1752
1899
  return mpptData;
1753
1900
  }
@@ -2009,7 +2156,7 @@ class SunspecModbusClient {
2009
2156
  return data;
2010
2157
  }
2011
2158
  catch (error) {
2012
- console.error(`Error reading battery base data: ${error}`);
2159
+ this.logTransactionError(`Error reading battery base data`, error);
2013
2160
  return null;
2014
2161
  }
2015
2162
  }
@@ -2187,7 +2334,7 @@ class SunspecModbusClient {
2187
2334
  }
2188
2335
  }
2189
2336
  catch (error) {
2190
- console.error(`Error reading battery data: ${error}`);
2337
+ this.logTransactionError(`Error reading battery data`, error);
2191
2338
  return null;
2192
2339
  }
2193
2340
  }
@@ -2269,7 +2416,7 @@ class SunspecModbusClient {
2269
2416
  return true;
2270
2417
  }
2271
2418
  catch (error) {
2272
- console.error(`Error writing battery controls: ${error}`);
2419
+ this.logTransactionError(`Error writing battery controls`, error);
2273
2420
  return false;
2274
2421
  }
2275
2422
  }
@@ -2277,30 +2424,43 @@ class SunspecModbusClient {
2277
2424
  * Set battery storage mode (simplified interface)
2278
2425
  */
2279
2426
  async setStorageMode(unitId, mode) {
2280
- let storCtlMod;
2427
+ // StorCtl_Mod says *which rate setpoint is enforced*, not what the
2428
+ // battery is allowed to do — so releasing control means clearing the
2429
+ // bits, and the rate registers have to be written alongside them.
2430
+ // Setting the bits without touching InWRte/OutWRte would enforce
2431
+ // whatever percentage was left behind by an earlier command.
2432
+ let controls;
2281
2433
  switch (mode) {
2282
2434
  case sunspec_interfaces_js_1.SunspecStorageMode.CHARGE:
2283
- // Enable charge only (bit 0 = 1, bit 1 = 0)
2284
- storCtlMod = sunspec_interfaces_js_1.SunspecStorageControlMode.CHARGE;
2435
+ // Enforce the charge-rate setpoint only (bit 0 = 1, bit 1 = 0).
2436
+ controls = { storCtlMod: sunspec_interfaces_js_1.SunspecStorageControlMode.CHARGE };
2285
2437
  break;
2286
2438
  case sunspec_interfaces_js_1.SunspecStorageMode.DISCHARGE:
2287
- // Enable discharge only (bit 0 = 0, bit 1 = 1)
2288
- storCtlMod = sunspec_interfaces_js_1.SunspecStorageControlMode.DISCHARGE;
2439
+ // Enforce the discharge-rate setpoint only (bit 0 = 0, bit 1 = 1).
2440
+ controls = { storCtlMod: sunspec_interfaces_js_1.SunspecStorageControlMode.DISCHARGE };
2289
2441
  break;
2290
2442
  case sunspec_interfaces_js_1.SunspecStorageMode.HOLDING:
2291
- // Disable both charge and discharge (bits 0 and 1 = 0)
2292
- storCtlMod = 0;
2443
+ // Park the battery: both setpoints enforced, both clamped to 0 %.
2444
+ controls = {
2445
+ storCtlMod: sunspec_interfaces_js_1.SunspecStorageControlMode.CHARGE | sunspec_interfaces_js_1.SunspecStorageControlMode.DISCHARGE,
2446
+ inWRte: 0,
2447
+ outWRte: 0,
2448
+ };
2293
2449
  break;
2294
2450
  case sunspec_interfaces_js_1.SunspecStorageMode.AUTO:
2295
- // Enable both charge and discharge (bits 0 and 1 = 1)
2296
- storCtlMod = sunspec_interfaces_js_1.SunspecStorageControlMode.CHARGE | sunspec_interfaces_js_1.SunspecStorageControlMode.DISCHARGE;
2451
+ // Hand control back: no setpoint enforced, both rates wide open.
2452
+ controls = {
2453
+ storCtlMod: sunspec_interfaces_js_1.SunspecStorageControlMode.NONE,
2454
+ inWRte: 100,
2455
+ outWRte: 100,
2456
+ };
2297
2457
  break;
2298
2458
  default:
2299
2459
  console.error(`Invalid storage mode: ${mode}`);
2300
2460
  return false;
2301
2461
  }
2302
- console.log(`Setting storage mode to ${mode} (control bits: 0x${storCtlMod.toString(16)})`);
2303
- return this.writeBatteryControls(unitId, { storCtlMod });
2462
+ console.log(`Setting storage mode to ${mode} (${JSON.stringify(controls)})`);
2463
+ return this.writeBatteryControls(unitId, controls);
2304
2464
  }
2305
2465
  /**
2306
2466
  * Enable or disable grid charging
@@ -2356,7 +2516,7 @@ class SunspecModbusClient {
2356
2516
  return controls;
2357
2517
  }
2358
2518
  catch (error) {
2359
- console.error(`Error reading battery controls: ${error}`);
2519
+ this.logTransactionError(`Error reading battery controls`, error);
2360
2520
  return null;
2361
2521
  }
2362
2522
  }
@@ -2488,7 +2648,7 @@ class SunspecModbusClient {
2488
2648
  return data;
2489
2649
  }
2490
2650
  catch (error) {
2491
- console.error(`Error reading meter data: ${error}`);
2651
+ this.logTransactionError(`Error reading meter data`, error);
2492
2652
  return null;
2493
2653
  }
2494
2654
  }
@@ -2530,7 +2690,7 @@ class SunspecModbusClient {
2530
2690
  return data;
2531
2691
  }
2532
2692
  catch (error) {
2533
- console.error(`Error reading float meter data (Model ${blockNumber}): ${error}`);
2693
+ this.logTransactionError(`Error reading float meter data (Model ${blockNumber})`, error);
2534
2694
  return null;
2535
2695
  }
2536
2696
  }
@@ -2608,7 +2768,7 @@ class SunspecModbusClient {
2608
2768
  return data;
2609
2769
  }
2610
2770
  catch (error) {
2611
- console.error(`Error reading common block: ${error}`);
2771
+ this.logTransactionError(`Error reading common block`, error);
2612
2772
  return null;
2613
2773
  }
2614
2774
  }
@@ -2734,7 +2894,7 @@ class SunspecModbusClient {
2734
2894
  return settings;
2735
2895
  }
2736
2896
  catch (error) {
2737
- console.error(`Error reading inverter settings: ${error}`);
2897
+ this.logTransactionError(`Error reading inverter settings`, error);
2738
2898
  return null;
2739
2899
  }
2740
2900
  }
@@ -2751,74 +2911,76 @@ class SunspecModbusClient {
2751
2911
  try {
2752
2912
  // Read entire model block in a single Modbus call
2753
2913
  const buffer = await this.readModelBlock(unitId, model);
2754
- // Extract scale factors from buffer (offsets 21-23)
2914
+ // Buffer offsets are SunSpec point offsets + 2: readModelBlock() returns the
2915
+ // 2-register model header (ID + length) ahead of the data registers. Scale
2916
+ // factors are points 21-23 -> buffer offsets 23-25.
2755
2917
  const scaleFactors = {
2756
- WMaxLimPct_SF: this.extractValue(buffer, 21, 'int16'),
2757
- OutPFSet_SF: this.extractValue(buffer, 22, 'int16'),
2758
- VArPct_SF: this.extractValue(buffer, 23, 'int16')
2918
+ WMaxLimPct_SF: this.extractValue(buffer, 23, 'int16'),
2919
+ OutPFSet_SF: this.extractValue(buffer, 24, 'int16'),
2920
+ VArPct_SF: this.extractValue(buffer, 25, 'int16')
2759
2921
  };
2760
- this.logRegisterRead(123, 21, 'WMaxLimPct_SF', scaleFactors.WMaxLimPct_SF, 'int16');
2761
- this.logRegisterRead(123, 22, 'OutPFSet_SF', scaleFactors.OutPFSet_SF, 'int16');
2762
- this.logRegisterRead(123, 23, 'VArPct_SF', scaleFactors.VArPct_SF, 'int16');
2922
+ this.logRegisterRead(123, 23, 'WMaxLimPct_SF', scaleFactors.WMaxLimPct_SF, 'int16');
2923
+ this.logRegisterRead(123, 24, 'OutPFSet_SF', scaleFactors.OutPFSet_SF, 'int16');
2924
+ this.logRegisterRead(123, 25, 'VArPct_SF', scaleFactors.VArPct_SF, 'int16');
2763
2925
  // Extract non-scaled fields from buffer
2764
- const connWinTmsRaw = this.extractValue(buffer, 0, 'uint16');
2765
- const connRvrtTmsRaw = this.extractValue(buffer, 1, 'uint16');
2766
- const connRaw = this.extractValue(buffer, 2, 'uint16');
2767
- const wMaxLimPctWinTmsRaw = this.extractValue(buffer, 4, 'uint16');
2768
- const wMaxLimPctRvrtTmsRaw = this.extractValue(buffer, 5, 'uint16');
2769
- const wMaxLimPctRmpTmsRaw = this.extractValue(buffer, 6, 'uint16');
2770
- const wMaxLimEnaRaw = this.extractValue(buffer, 7, 'uint16');
2771
- const outPFSetWinTmsRaw = this.extractValue(buffer, 9, 'uint16');
2772
- const outPFSetRvrtTmsRaw = this.extractValue(buffer, 10, 'uint16');
2773
- const outPFSetRmpTmsRaw = this.extractValue(buffer, 11, 'uint16');
2774
- const outPFSetEnaRaw = this.extractValue(buffer, 12, 'uint16');
2775
- const vArPctWinTmsRaw = this.extractValue(buffer, 16, 'uint16');
2776
- const vArPctRvrtTmsRaw = this.extractValue(buffer, 17, 'uint16');
2777
- const vArPctRmpTmsRaw = this.extractValue(buffer, 18, 'uint16');
2778
- const vArPctModRaw = this.extractValue(buffer, 19, 'uint16');
2779
- const vArPctEnaRaw = this.extractValue(buffer, 20, 'uint16');
2780
- this.logRegisterRead(123, 0, 'Conn_WinTms', connWinTmsRaw, 'uint16');
2781
- this.logRegisterRead(123, 1, 'Conn_RvrtTms', connRvrtTmsRaw, 'uint16');
2782
- this.logRegisterRead(123, 2, 'Conn', connRaw, 'enum16');
2783
- this.logRegisterRead(123, 4, 'WMaxLimPct_WinTms', wMaxLimPctWinTmsRaw, 'uint16');
2784
- this.logRegisterRead(123, 5, 'WMaxLimPct_RvrtTms', wMaxLimPctRvrtTmsRaw, 'uint16');
2785
- this.logRegisterRead(123, 6, 'WMaxLimPct_RmpTms', wMaxLimPctRmpTmsRaw, 'uint16');
2786
- this.logRegisterRead(123, 7, 'WMaxLim_Ena', wMaxLimEnaRaw, 'enum16');
2787
- this.logRegisterRead(123, 9, 'OutPFSet_WinTms', outPFSetWinTmsRaw, 'uint16');
2788
- this.logRegisterRead(123, 10, 'OutPFSet_RvrtTms', outPFSetRvrtTmsRaw, 'uint16');
2789
- this.logRegisterRead(123, 11, 'OutPFSet_RmpTms', outPFSetRmpTmsRaw, 'uint16');
2790
- this.logRegisterRead(123, 12, 'OutPFSet_Ena', outPFSetEnaRaw, 'enum16');
2791
- this.logRegisterRead(123, 16, 'VArPct_WinTms', vArPctWinTmsRaw, 'uint16');
2792
- this.logRegisterRead(123, 17, 'VArPct_RvrtTms', vArPctRvrtTmsRaw, 'uint16');
2793
- this.logRegisterRead(123, 18, 'VArPct_RmpTms', vArPctRmpTmsRaw, 'uint16');
2794
- this.logRegisterRead(123, 19, 'VArPct_Mod', vArPctModRaw, 'enum16');
2795
- this.logRegisterRead(123, 20, 'VArPct_Ena', vArPctEnaRaw, 'enum16');
2926
+ const connWinTmsRaw = this.extractValue(buffer, 2, 'uint16');
2927
+ const connRvrtTmsRaw = this.extractValue(buffer, 3, 'uint16');
2928
+ const connRaw = this.extractValue(buffer, 4, 'uint16');
2929
+ const wMaxLimPctWinTmsRaw = this.extractValue(buffer, 6, 'uint16');
2930
+ const wMaxLimPctRvrtTmsRaw = this.extractValue(buffer, 7, 'uint16');
2931
+ const wMaxLimPctRmpTmsRaw = this.extractValue(buffer, 8, 'uint16');
2932
+ const wMaxLimEnaRaw = this.extractValue(buffer, 9, 'uint16');
2933
+ const outPFSetWinTmsRaw = this.extractValue(buffer, 11, 'uint16');
2934
+ const outPFSetRvrtTmsRaw = this.extractValue(buffer, 12, 'uint16');
2935
+ const outPFSetRmpTmsRaw = this.extractValue(buffer, 13, 'uint16');
2936
+ const outPFSetEnaRaw = this.extractValue(buffer, 14, 'uint16');
2937
+ const vArPctWinTmsRaw = this.extractValue(buffer, 18, 'uint16');
2938
+ const vArPctRvrtTmsRaw = this.extractValue(buffer, 19, 'uint16');
2939
+ const vArPctRmpTmsRaw = this.extractValue(buffer, 20, 'uint16');
2940
+ const vArPctModRaw = this.extractValue(buffer, 21, 'uint16');
2941
+ const vArPctEnaRaw = this.extractValue(buffer, 22, 'uint16');
2942
+ this.logRegisterRead(123, 2, 'Conn_WinTms', connWinTmsRaw, 'uint16');
2943
+ this.logRegisterRead(123, 3, 'Conn_RvrtTms', connRvrtTmsRaw, 'uint16');
2944
+ this.logRegisterRead(123, 4, 'Conn', connRaw, 'enum16');
2945
+ this.logRegisterRead(123, 6, 'WMaxLimPct_WinTms', wMaxLimPctWinTmsRaw, 'uint16');
2946
+ this.logRegisterRead(123, 7, 'WMaxLimPct_RvrtTms', wMaxLimPctRvrtTmsRaw, 'uint16');
2947
+ this.logRegisterRead(123, 8, 'WMaxLimPct_RmpTms', wMaxLimPctRmpTmsRaw, 'uint16');
2948
+ this.logRegisterRead(123, 9, 'WMaxLim_Ena', wMaxLimEnaRaw, 'enum16');
2949
+ this.logRegisterRead(123, 11, 'OutPFSet_WinTms', outPFSetWinTmsRaw, 'uint16');
2950
+ this.logRegisterRead(123, 12, 'OutPFSet_RvrtTms', outPFSetRvrtTmsRaw, 'uint16');
2951
+ this.logRegisterRead(123, 13, 'OutPFSet_RmpTms', outPFSetRmpTmsRaw, 'uint16');
2952
+ this.logRegisterRead(123, 14, 'OutPFSet_Ena', outPFSetEnaRaw, 'enum16');
2953
+ this.logRegisterRead(123, 18, 'VArPct_WinTms', vArPctWinTmsRaw, 'uint16');
2954
+ this.logRegisterRead(123, 19, 'VArPct_RvrtTms', vArPctRvrtTmsRaw, 'uint16');
2955
+ this.logRegisterRead(123, 20, 'VArPct_RmpTms', vArPctRmpTmsRaw, 'uint16');
2956
+ this.logRegisterRead(123, 21, 'VArPct_Mod', vArPctModRaw, 'enum16');
2957
+ this.logRegisterRead(123, 22, 'VArPct_Ena', vArPctEnaRaw, 'enum16');
2796
2958
  const controls = {
2797
2959
  blockNumber: 123,
2798
2960
  blockAddress: model.address,
2799
2961
  blockLength: model.length,
2800
- // Connection control - Offsets 0-2
2962
+ // Connection control - points 0-2 (buffer 2-4)
2801
2963
  Conn_WinTms: connWinTmsRaw,
2802
2964
  Conn_RvrtTms: connRvrtTmsRaw,
2803
2965
  Conn: connRaw,
2804
- // Power limit control - Offsets 3-7
2805
- WMaxLimPct: this.applyScaleFactor(this.extractValue(buffer, 3, 'uint16'), scaleFactors.WMaxLimPct_SF, 'uint16', 'Power Limit Percentage', 3, 123),
2966
+ // Power limit control - points 3-7 (buffer 5-9)
2967
+ WMaxLimPct: this.applyScaleFactor(this.extractValue(buffer, 5, 'uint16'), scaleFactors.WMaxLimPct_SF, 'uint16', 'Power Limit Percentage', 5, 123),
2806
2968
  WMaxLimPct_SF: scaleFactors.WMaxLimPct_SF,
2807
2969
  WMaxLimPct_WinTms: wMaxLimPctWinTmsRaw,
2808
2970
  WMaxLimPct_RvrtTms: wMaxLimPctRvrtTmsRaw,
2809
2971
  WMaxLimPct_RmpTms: wMaxLimPctRmpTmsRaw,
2810
2972
  WMaxLim_Ena: wMaxLimEnaRaw,
2811
- // Power factor control - Offsets 8-12
2812
- OutPFSet: this.applyScaleFactor(this.extractValue(buffer, 8, 'int16'), scaleFactors.OutPFSet_SF, 'int16', 'Output Power Factor Set', 8, 123),
2973
+ // Power factor control - points 8-12 (buffer 10-14)
2974
+ OutPFSet: this.applyScaleFactor(this.extractValue(buffer, 10, 'int16'), scaleFactors.OutPFSet_SF, 'int16', 'Output Power Factor Set', 10, 123),
2813
2975
  OutPFSet_SF: scaleFactors.OutPFSet_SF,
2814
2976
  OutPFSet_WinTms: outPFSetWinTmsRaw,
2815
2977
  OutPFSet_RvrtTms: outPFSetRvrtTmsRaw,
2816
2978
  OutPFSet_RmpTms: outPFSetRmpTmsRaw,
2817
2979
  OutPFSet_Ena: outPFSetEnaRaw,
2818
- // Reactive power control - Offsets 13-20
2819
- VArWMaxPct: this.applyScaleFactor(this.extractValue(buffer, 13, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Reactive Power at Max Power %', 13, 123),
2820
- VArMaxPct: this.applyScaleFactor(this.extractValue(buffer, 14, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Max Reactive Power %', 14, 123),
2821
- VArAvalPct: this.applyScaleFactor(this.extractValue(buffer, 15, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Available Reactive Power %', 15, 123),
2980
+ // Reactive power control - points 13-20 (buffer 15-22)
2981
+ VArWMaxPct: this.applyScaleFactor(this.extractValue(buffer, 15, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Reactive Power at Max Power %', 15, 123),
2982
+ VArMaxPct: this.applyScaleFactor(this.extractValue(buffer, 16, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Max Reactive Power %', 16, 123),
2983
+ VArAvalPct: this.applyScaleFactor(this.extractValue(buffer, 17, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Available Reactive Power %', 17, 123),
2822
2984
  VArPct_SF: scaleFactors.VArPct_SF,
2823
2985
  VArPct_WinTms: vArPctWinTmsRaw,
2824
2986
  VArPct_RvrtTms: vArPctRvrtTmsRaw,
@@ -2830,7 +2992,7 @@ class SunspecModbusClient {
2830
2992
  return controls;
2831
2993
  }
2832
2994
  catch (error) {
2833
- console.error(`Error reading inverter controls: ${error}`);
2995
+ this.logTransactionError(`Error reading inverter controls`, error);
2834
2996
  return null;
2835
2997
  }
2836
2998
  }
@@ -2868,7 +3030,7 @@ class SunspecModbusClient {
2868
3030
  return true;
2869
3031
  }
2870
3032
  catch (error) {
2871
- console.error(`Error writing inverter settings: ${error}`);
3033
+ this.logTransactionError(`Error writing inverter settings`, error);
2872
3034
  return false;
2873
3035
  }
2874
3036
  }
@@ -2881,43 +3043,45 @@ class SunspecModbusClient {
2881
3043
  console.error(`Controls model 123 not found on unit ${unitId}`);
2882
3044
  return false;
2883
3045
  }
3046
+ // model.address points at the 2-register model header (ID + length), so a
3047
+ // SunSpec point at offset N lives at baseAddr + 2 + N.
2884
3048
  const baseAddr = model.address;
2885
3049
  try {
2886
3050
  // Per-field inverter-control writes are debug-only; the high-level callers
2887
3051
  // (`setFeedInLimit`, etc.) still log the action and outcome at info level.
2888
3052
  if (controls.Conn !== undefined) {
2889
- await this.writeRegisterValue(unitId, baseAddr + 2, controls.Conn, 'uint16');
3053
+ await this.writeRegisterValue(unitId, baseAddr + 4, controls.Conn, 'uint16');
2890
3054
  console.debug(`Set connection control to ${controls.Conn}`);
2891
3055
  }
2892
- // Power limit control (Register 3) - needs scale factor
3056
+ // Power limit control (point 3 -> baseAddr + 5) - needs scale factor
2893
3057
  if (controls.WMaxLimPct !== undefined) {
2894
- const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 21, 1, 'int16');
3058
+ const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 23, 1, 'int16');
2895
3059
  const scaledValue = Math.round(controls.WMaxLimPct / Math.pow(10, scaleFactor));
2896
- await this.writeRegisterValue(unitId, baseAddr + 3, scaledValue, 'uint16');
3060
+ await this.writeRegisterValue(unitId, baseAddr + 5, scaledValue, 'uint16');
2897
3061
  console.debug(`Set power limit to ${controls.WMaxLimPct}% (scaled: ${scaledValue})`);
2898
3062
  }
2899
- // Throttle enable/disable (Register 7)
3063
+ // Throttle enable/disable (point 7 -> baseAddr + 9)
2900
3064
  if (controls.WMaxLim_Ena !== undefined) {
2901
- await this.writeRegisterValue(unitId, baseAddr + 7, controls.WMaxLim_Ena, 'uint16');
3065
+ await this.writeRegisterValue(unitId, baseAddr + 9, controls.WMaxLim_Ena, 'uint16');
2902
3066
  console.debug(`Set throttle enable to ${controls.WMaxLim_Ena}`);
2903
3067
  }
2904
- // Power factor control (Register 8) - needs scale factor
3068
+ // Power factor control (point 8 -> baseAddr + 10) - needs scale factor
2905
3069
  if (controls.OutPFSet !== undefined) {
2906
- const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 22, 1, 'int16');
3070
+ const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 24, 1, 'int16');
2907
3071
  const scaledValue = Math.round(controls.OutPFSet / Math.pow(10, scaleFactor));
2908
- await this.writeRegisterValue(unitId, baseAddr + 8, scaledValue, 'int16');
3072
+ await this.writeRegisterValue(unitId, baseAddr + 10, scaledValue, 'int16');
2909
3073
  console.debug(`Set power factor to ${controls.OutPFSet} (scaled: ${scaledValue})`);
2910
3074
  }
2911
- // Power factor enable/disable (Register 12)
3075
+ // Power factor enable/disable (point 12 -> baseAddr + 14)
2912
3076
  if (controls.OutPFSet_Ena !== undefined) {
2913
- await this.writeRegisterValue(unitId, baseAddr + 12, controls.OutPFSet_Ena, 'uint16');
3077
+ await this.writeRegisterValue(unitId, baseAddr + 14, controls.OutPFSet_Ena, 'uint16');
2914
3078
  console.debug(`Set PF enable to ${controls.OutPFSet_Ena}`);
2915
3079
  }
2916
3080
  console.debug('Inverter controls written successfully');
2917
3081
  return true;
2918
3082
  }
2919
3083
  catch (error) {
2920
- console.error(`Error writing inverter controls: ${error}`);
3084
+ this.logTransactionError(`Error writing inverter controls`, error);
2921
3085
  return false;
2922
3086
  }
2923
3087
  }