@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.
@@ -35,6 +35,63 @@ export class ModbusOperationTimeoutError extends Error {
35
35
  this.timeoutMs = timeoutMs;
36
36
  this.name = 'ModbusOperationTimeoutError';
37
37
  }
38
+ /**
39
+ * `Error` has no enumerable own properties, so a consumer that logs `{ err }` through a
40
+ * JSON serializer emits `{}` and loses the message entirely. Give every error this client
41
+ * rejects with an explicit JSON shape so it survives `JSON.stringify` with a usable message.
42
+ */
43
+ toJSON() {
44
+ return {
45
+ name: this.name,
46
+ message: this.message,
47
+ operation: this.operation,
48
+ unitId: this.unitId,
49
+ timeoutMs: this.timeoutMs
50
+ };
51
+ }
52
+ }
53
+ /**
54
+ * Thrown when the client refuses a transaction because the unit is **already known to be down**,
55
+ * as opposed to a transaction that was actually attempted and failed.
56
+ *
57
+ * The distinction matters for logging. A poisoned socket produces exactly one genuine event (the
58
+ * timeout that poisoned it), but every read that lands during the outage would otherwise throw an
59
+ * error indistinguishable from real I/O failure — so a consumer catching per read has no choice but
60
+ * to log each one at ERROR. Callers should log the first {@link SunspecUnavailableError} of an
61
+ * outage (or nothing at all: the SDK already logs the transition) and stay quiet on the rest.
62
+ *
63
+ * {@link sinceMs} is how long the unit has been in this state, so a consumer that does want one
64
+ * line can say how stale the link is without tracking the outage itself.
65
+ */
66
+ export class SunspecUnavailableError extends Error {
67
+ reason;
68
+ unitId;
69
+ sinceMs;
70
+ constructor(reason, unitId, sinceMs) {
71
+ super(`Modbus unit ${unitId} is unavailable (${reason}, for ${sinceMs}ms) — ` +
72
+ `transaction refused without attempting I/O`);
73
+ this.reason = reason;
74
+ this.unitId = unitId;
75
+ this.sinceMs = sinceMs;
76
+ this.name = 'SunspecUnavailableError';
77
+ }
78
+ /** See {@link ModbusOperationTimeoutError.toJSON}. */
79
+ toJSON() {
80
+ return {
81
+ name: this.name,
82
+ message: this.message,
83
+ reason: this.reason,
84
+ unitId: this.unitId,
85
+ sinceMs: this.sinceMs
86
+ };
87
+ }
88
+ }
89
+ /**
90
+ * Type guard for {@link SunspecUnavailableError}. Prefer this over `instanceof` at package
91
+ * boundaries, where a duplicated copy of the SDK in the module graph would break identity.
92
+ */
93
+ export function isSunspecUnavailableError(error) {
94
+ return error instanceof Error && error.name === 'SunspecUnavailableError';
38
95
  }
39
96
  /**
40
97
  * Module-level registry: one SunspecModbusClient per network device (host:port).
@@ -46,7 +103,7 @@ const registryKey = (host, port) => `${host}:${port}`;
46
103
  * Get (or create) the singleton SunspecModbusClient for this network device.
47
104
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
48
105
  *
49
- * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
106
+ * NOTE: `transport`, `resilience` and `modbusFactory` are only applied when the client is FIRST
50
107
  * created for a given host:port. Because the client is cached and refcounted, a later caller
51
108
  * passing different config receives the already-created instance and its config is ignored.
52
109
  *
@@ -54,11 +111,11 @@ const registryKey = (host, port) => `${host}:${port}`;
54
111
  * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
55
112
  * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
56
113
  */
57
- export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience, modbusFactory) {
114
+ export function getOrCreateSunspecClient(energyApp, host, port = 502, transport, resilience, modbusFactory) {
58
115
  const key = registryKey(host, port);
59
116
  let entry = CLIENT_REGISTRY.get(key);
60
117
  if (!entry) {
61
- entry = { client: new SunspecModbusClient(energyApp, pacing, resilience, modbusFactory), refcount: 0 };
118
+ entry = { client: new SunspecModbusClient(energyApp, transport, resilience, modbusFactory), refcount: 0 };
62
119
  CLIENT_REGISTRY.set(key, entry);
63
120
  }
64
121
  entry.refcount++;
@@ -123,7 +180,7 @@ export async function retryAsync(fn, opts) {
123
180
  }
124
181
  export class SunspecModbusClient {
125
182
  energyApp;
126
- pacing;
183
+ transport;
127
184
  modbusFactory;
128
185
  // Per-unit Modbus instance/reader/discovered-models maps. One client = one network device,
129
186
  // many unit IDs share that client (each unit ID is one EnergyAppModbusInstance underneath).
@@ -164,18 +221,29 @@ export class SunspecModbusClient {
164
221
  // transaction's framing. So a poisoned unit refuses further I/O until reconnectUnit() tears
165
222
  // the socket down and reopens it (which clears the flag).
166
223
  poisonedUnits = new Set();
224
+ // Wall-clock of the transition INTO the poisoned state, per unit. Survives the close half of a
225
+ // recycle (`_closeUnit` clears the poison flag, not this) so the reopen can report how long the
226
+ // outage lasted. Cleared on the recovery log, which is the one place the outage is considered
227
+ // over. Presence here is "was poisoned at some point since the last successful open".
228
+ poisonedAtByUnit = new Map();
167
229
  // Wall-clock of each unit's last SUCCESSFUL transaction. Drives half-open detection: a socket
168
230
  // the transport still reports connected but that has gone quiet past staleSocketMs is presumed
169
231
  // dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
170
232
  lastOkAtByUnit = new Map();
233
+ // Consecutive failed (re)connect attempts, keyed by attempt target. Drives transition-only
234
+ // logging: the first failure of a run is the news, every repeat while the peer stays down is
235
+ // the same news again. Cleared on the first success for that key.
236
+ consecutiveConnectFailures = new Map();
171
237
  constructor(
172
238
  // The host application. Only used to obtain the default Modbus backend via
173
239
  // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
174
240
  energyApp,
175
- // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
176
- // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
177
- // connection. An empty object leaves both undefined so the SDK applies its own defaults.
178
- pacing = {},
241
+ // Opt-in transport options (all default off). Passed straight through to
242
+ // `useModbus().connect()`, which serializes frames (`noParallelRequests`), spaces them
243
+ // (`waitBetweenMessagesMs`) and decides whether the socket comes from the host's shared pool
244
+ // (`pooledConnection`). An empty object leaves them all undefined so the SDK applies its own
245
+ // defaults. Typed as the superset so a plain IModbusPacingConfig still assigns.
246
+ transport = {},
179
247
  // Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
180
248
  // so omitted fields keep their defaults.
181
249
  resilience = {},
@@ -187,7 +255,7 @@ export class SunspecModbusClient {
187
255
  // connections on its own schedule and needs a factory to call.
188
256
  modbusFactory) {
189
257
  this.energyApp = energyApp;
190
- this.pacing = pacing;
258
+ this.transport = transport;
191
259
  this.modbusFactory = modbusFactory;
192
260
  if (!energyApp && !modbusFactory) {
193
261
  throw new Error("SunspecModbusClient requires either an EnergyApp or a modbusFactory");
@@ -358,21 +426,29 @@ export class SunspecModbusClient {
358
426
  }
359
427
  const { primaryHost, secondaryHost, port } = this.connectionParams;
360
428
  const units = [...this.knownUnits];
361
- console.log(`Attempting to reconnect to primary host ${primaryHost}:${port} units [${units.join(',')}]...`);
429
+ const failureKey = 'reconnect:all';
430
+ const retrying = this.isRetryingAfterFailure(failureKey);
431
+ const logAttempt = (message) => { if (retrying)
432
+ console.debug(message);
433
+ else
434
+ console.log(message); };
435
+ logAttempt(`Attempting to reconnect to primary host ${primaryHost}:${port} units [${units.join(',')}]...`);
362
436
  const primarySuccess = await this.attemptConnection(primaryHost, port, units);
363
437
  if (primarySuccess) {
438
+ this.clearConnectFailures(failureKey);
364
439
  console.log(`Successfully reconnected to primary host ${primaryHost}:${port} units [${units.join(',')}]`);
365
440
  return true;
366
441
  }
367
442
  if (secondaryHost && secondaryHost !== primaryHost) {
368
- console.log(`Primary host failed, attempting secondary host ${secondaryHost}:${port} units [${units.join(',')}]...`);
443
+ logAttempt(`Primary host failed, attempting secondary host ${secondaryHost}:${port} units [${units.join(',')}]...`);
369
444
  const secondarySuccess = await this.attemptConnection(secondaryHost, port, units);
370
445
  if (secondarySuccess) {
446
+ this.clearConnectFailures(failureKey);
371
447
  console.log(`Successfully reconnected to secondary host ${secondaryHost}:${port} units [${units.join(',')}]`);
372
448
  return true;
373
449
  }
374
450
  }
375
- console.error(`Reconnection failed to all available hosts`);
451
+ this.logConnectFailure(failureKey, `Reconnection failed to all available hosts`);
376
452
  return false;
377
453
  });
378
454
  }
@@ -390,21 +466,29 @@ export class SunspecModbusClient {
390
466
  return false;
391
467
  }
392
468
  const { primaryHost, secondaryHost, port } = this.connectionParams;
393
- console.log(`Attempting to reconnect unit ${unitId} on primary host ${primaryHost}:${port}...`);
469
+ const failureKey = `reconnect:unit${unitId}`;
470
+ const retrying = this.isRetryingAfterFailure(failureKey);
471
+ const logAttempt = (message) => { if (retrying)
472
+ console.debug(message);
473
+ else
474
+ console.log(message); };
475
+ logAttempt(`Attempting to reconnect unit ${unitId} on primary host ${primaryHost}:${port}...`);
394
476
  const primarySuccess = await this.attemptConnection(primaryHost, port, [unitId]);
395
477
  if (primarySuccess) {
478
+ this.clearConnectFailures(failureKey);
396
479
  console.log(`Successfully reconnected unit ${unitId} on primary host ${primaryHost}:${port}`);
397
480
  return true;
398
481
  }
399
482
  if (secondaryHost && secondaryHost !== primaryHost) {
400
- console.log(`Primary host failed for unit ${unitId}, attempting secondary host ${secondaryHost}:${port}...`);
483
+ logAttempt(`Primary host failed for unit ${unitId}, attempting secondary host ${secondaryHost}:${port}...`);
401
484
  const secondarySuccess = await this.attemptConnection(secondaryHost, port, [unitId]);
402
485
  if (secondarySuccess) {
486
+ this.clearConnectFailures(failureKey);
403
487
  console.log(`Successfully reconnected unit ${unitId} on secondary host ${secondaryHost}:${port}`);
404
488
  return true;
405
489
  }
406
490
  }
407
- console.error(`Reconnection failed for unit ${unitId} on all available hosts`);
491
+ this.logConnectFailure(failureKey, `Reconnection failed for unit ${unitId} on all available hosts`);
408
492
  return false;
409
493
  });
410
494
  }
@@ -419,15 +503,17 @@ export class SunspecModbusClient {
419
503
  await this._closeUnit(unitId);
420
504
  }
421
505
  }
506
+ const failureKey = `connect:${host}:${port}:[${units.join(',')}]`;
422
507
  try {
423
508
  for (const unitId of units) {
424
509
  await this._openUnit(host, port, unitId);
425
510
  }
511
+ this.clearConnectFailures(failureKey);
426
512
  console.log(`Connection attempt to ${host}:${port} units [${units.join(',')}] succeeded (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
427
513
  return true;
428
514
  }
429
515
  catch (error) {
430
- console.error(`Connection attempt to ${host}:${port} failed: ${error}`);
516
+ this.logConnectFailure(failureKey, `Connection attempt to ${host}:${port} failed: ${error}`);
431
517
  return false;
432
518
  }
433
519
  }
@@ -509,8 +595,9 @@ export class SunspecModbusClient {
509
595
  key: this.connectionParams?.key,
510
596
  ca: this.connectionParams?.ca,
511
597
  rejectUnauthorized: this.connectionParams?.rejectUnauthorized,
512
- noParallelRequests: this.pacing.noParallelRequests,
513
- waitBetweenMessagesMs: this.pacing.waitBetweenMessagesMs
598
+ noParallelRequests: this.transport.noParallelRequests,
599
+ waitBetweenMessagesMs: this.transport.waitBetweenMessagesMs,
600
+ pooledConnection: this.transport.pooledConnection
514
601
  }));
515
602
  if (!candidate) {
516
603
  throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
@@ -521,6 +608,7 @@ export class SunspecModbusClient {
521
608
  // Fresh socket: clear any prior poison and start the freshness clock so a just-opened
522
609
  // unit isn't immediately judged stale.
523
610
  this.poisonedUnits.delete(unitId);
611
+ this.logPoisonRecovery(unitId);
524
612
  this.lastOkAtByUnit.set(unitId, Date.now());
525
613
  this.connectionHealth.recordSuccess();
526
614
  this.recordOpen();
@@ -545,7 +633,9 @@ export class SunspecModbusClient {
545
633
  this.faultTolerantReaders.delete(unitId);
546
634
  this.discoveredModelsByUnit.delete(unitId);
547
635
  this.discoveredModelListByUnit.delete(unitId);
548
- // Drop per-unit resilience state so a later reopen starts clean.
636
+ // Drop per-unit resilience state so a later reopen starts clean. `poisonedAtByUnit` is
637
+ // deliberately NOT dropped: a recycle closes before it reopens, and the reopen is where the
638
+ // recovery line reports how long the unit was down.
549
639
  this.poisonedUnits.delete(unitId);
550
640
  this.lastOkAtByUnit.delete(unitId);
551
641
  if (instance) {
@@ -605,7 +695,10 @@ export class SunspecModbusClient {
605
695
  */
606
696
  async guardTransaction(unitId, fn) {
607
697
  if (this.poisonedUnits.has(unitId)) {
608
- throw new Error(`Modbus unit ${unitId} socket is poisoned (awaiting reconnect) — transaction refused`);
698
+ // Known-down, not newly-failed: a typed rejection so callers can stay quiet for the
699
+ // duration of an outage the SDK has already logged once. See SunspecUnavailableError.
700
+ const since = this.poisonedAtByUnit.get(unitId);
701
+ throw new SunspecUnavailableError('socket-poisoned', unitId, since === undefined ? 0 : Date.now() - since);
609
702
  }
610
703
  try {
611
704
  const result = await this.withTimeout('transaction', unitId, this.resilience.readTimeoutMs, fn);
@@ -634,17 +727,72 @@ export class SunspecModbusClient {
634
727
  clearTimeout(timer);
635
728
  });
636
729
  }
730
+ /**
731
+ * Log a failed Modbus transaction from a reader/writer catch block.
732
+ *
733
+ * A {@link SunspecUnavailableError} is not a failure — it is this client refusing I/O on a link
734
+ * it has already reported dead once (one WARN on the transition, one INFO on recovery). Logging
735
+ * it at ERROR once per read, per read path, per poll cycle, for the whole outage, is what buries
736
+ * the errors that are actually actionable. So it drops to debug; everything else stays ERROR.
737
+ */
738
+ logConnectFailure(key, message) {
739
+ const count = (this.consecutiveConnectFailures.get(key) ?? 0) + 1;
740
+ this.consecutiveConnectFailures.set(key, count);
741
+ if (count === 1) {
742
+ console.error(message);
743
+ }
744
+ else {
745
+ console.debug(`${message} (consecutive failure #${count})`);
746
+ }
747
+ }
748
+ /** True while `key`'s last attempt failed — used to keep repeat attempt chatter at debug. */
749
+ isRetryingAfterFailure(key) {
750
+ return (this.consecutiveConnectFailures.get(key) ?? 0) > 0;
751
+ }
752
+ /** Forget `key`'s failure run on a success, so the next outage logs its first failure again. */
753
+ clearConnectFailures(key) {
754
+ this.consecutiveConnectFailures.delete(key);
755
+ }
756
+ logTransactionError(context, error) {
757
+ if (isSunspecUnavailableError(error)) {
758
+ console.debug(`${context}: ${error.message}`);
759
+ return;
760
+ }
761
+ console.error(`${context}: ${error}`);
762
+ }
637
763
  /**
638
764
  * Mark a unit's socket as poisoned after a timeout and reflect the hang in the shared health
639
765
  * gate immediately, so isHealthy() flips false this cycle instead of after the coarse
640
766
  * 5-failure / 5-minute-staleness thresholds. Idempotent; only logs on the first poison.
641
767
  */
642
768
  poisonUnit(unitId, error) {
769
+ this.enterPoisoned(unitId, `${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
770
+ this.connectionHealth.recordFailure(error);
771
+ }
772
+ /**
773
+ * Enter the poisoned state for a unit, logging the TRANSITION only. Everything downstream of
774
+ * this (every refused read, every poll cycle) is the same known state and must stay silent —
775
+ * one WARN in, one INFO out (see {@link logPoisonRecovery}), nothing in between.
776
+ */
777
+ enterPoisoned(unitId, reason) {
643
778
  if (!this.poisonedUnits.has(unitId)) {
644
- console.warn(`SunspecModbusClient: ${error.message} — poisoning unit ${unitId} socket; reconnect path will recycle it`);
779
+ console.warn(`SunspecModbusClient: ${reason}`);
780
+ this.poisonedAtByUnit.set(unitId, Date.now());
645
781
  }
646
782
  this.poisonedUnits.add(unitId);
647
- this.connectionHealth.recordFailure(error);
783
+ }
784
+ /**
785
+ * Close out a poisoned episode on a successful (re)open: one INFO carrying how long the unit
786
+ * was refusing I/O. No-op for a unit that was never poisoned, so a normal first connect stays
787
+ * quiet.
788
+ */
789
+ logPoisonRecovery(unitId) {
790
+ const since = this.poisonedAtByUnit.get(unitId);
791
+ if (since === undefined)
792
+ return;
793
+ this.poisonedAtByUnit.delete(unitId);
794
+ console.info(`SunspecModbusClient: unit ${unitId} socket recovered after reconnect ` +
795
+ `(poisonedForMs=${Date.now() - since})`);
648
796
  }
649
797
  /**
650
798
  * Publicly invalidate a unit's socket so {@link isHealthy} returns false and the next
@@ -659,10 +807,7 @@ export class SunspecModbusClient {
659
807
  * schedule firing until a real discovery lands. Idempotent; only logs on the first call.
660
808
  */
661
809
  invalidateUnit(unitId, reason) {
662
- if (!this.poisonedUnits.has(unitId)) {
663
- console.warn(`SunspecModbusClient: invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
664
- }
665
- this.poisonedUnits.add(unitId);
810
+ this.enterPoisoned(unitId, `invalidating unit ${unitId} socket — ${reason}; reconnect path will recycle it`);
666
811
  this.connectionHealth.recordFailure(new Error(reason));
667
812
  }
668
813
  /**
@@ -921,7 +1066,7 @@ export class SunspecModbusClient {
921
1066
  }
922
1067
  }
923
1068
  catch (error) {
924
- console.error(`Error during model discovery at address ${currentAddress} (unit ${unitId}): ${error}`);
1069
+ this.logTransactionError(`Error during model discovery at address ${currentAddress} (unit ${unitId})`, error);
925
1070
  }
926
1071
  if (discovered.length > 0) {
927
1072
  // Commit the fresh discovery atomically. Keep the FIRST (lowest-address) instance per
@@ -1223,7 +1368,7 @@ export class SunspecModbusClient {
1223
1368
  }
1224
1369
  catch (error) {
1225
1370
  this.connectionHealth.recordFailure(error);
1226
- console.error(`Error writing register at address ${address}: ${error}`);
1371
+ this.logTransactionError(`Error writing register at address ${address}`, error);
1227
1372
  throw error;
1228
1373
  }
1229
1374
  }
@@ -1369,7 +1514,7 @@ export class SunspecModbusClient {
1369
1514
  return data;
1370
1515
  }
1371
1516
  catch (error) {
1372
- console.error(`Error reading inverter data: ${error}`);
1517
+ this.logTransactionError(`Error reading inverter data`, error);
1373
1518
  return null;
1374
1519
  }
1375
1520
  }
@@ -1433,7 +1578,7 @@ export class SunspecModbusClient {
1433
1578
  return data;
1434
1579
  }
1435
1580
  catch (error) {
1436
- console.error(`Error reading single phase inverter data: ${error}`);
1581
+ this.logTransactionError(`Error reading single phase inverter data`, error);
1437
1582
  return null;
1438
1583
  }
1439
1584
  }
@@ -1497,7 +1642,7 @@ export class SunspecModbusClient {
1497
1642
  return data;
1498
1643
  }
1499
1644
  catch (error) {
1500
- console.error(`Error reading float inverter data (Model ${blockNumber}): ${error}`);
1645
+ this.logTransactionError(`Error reading float inverter data (Model ${blockNumber})`, error);
1501
1646
  return null;
1502
1647
  }
1503
1648
  }
@@ -1616,7 +1761,7 @@ export class SunspecModbusClient {
1616
1761
  return this.extractMPPTScaleFactors(buffer);
1617
1762
  }
1618
1763
  catch (error) {
1619
- console.error(`Error reading MPPT scale factors (unit ${unitId}): ${error}`);
1764
+ this.logTransactionError(`Error reading MPPT scale factors (unit ${unitId})`, error);
1620
1765
  return null;
1621
1766
  }
1622
1767
  }
@@ -1690,7 +1835,7 @@ export class SunspecModbusClient {
1690
1835
  return this.extractMPPTModuleData(buffer, model, moduleId, scaleFactors);
1691
1836
  }
1692
1837
  catch (error) {
1693
- console.error(`Error reading MPPT data for module ${moduleId} (unit ${unitId}): ${error}`);
1838
+ this.logTransactionError(`Error reading MPPT data for module ${moduleId} (unit ${unitId})`, error);
1694
1839
  return null;
1695
1840
  }
1696
1841
  }
@@ -1740,7 +1885,7 @@ export class SunspecModbusClient {
1740
1885
  }
1741
1886
  }
1742
1887
  catch (error) {
1743
- console.error(`Error reading all MPPT data: ${error}`);
1888
+ this.logTransactionError(`Error reading all MPPT data`, error);
1744
1889
  }
1745
1890
  return mpptData;
1746
1891
  }
@@ -2002,7 +2147,7 @@ export class SunspecModbusClient {
2002
2147
  return data;
2003
2148
  }
2004
2149
  catch (error) {
2005
- console.error(`Error reading battery base data: ${error}`);
2150
+ this.logTransactionError(`Error reading battery base data`, error);
2006
2151
  return null;
2007
2152
  }
2008
2153
  }
@@ -2180,7 +2325,7 @@ export class SunspecModbusClient {
2180
2325
  }
2181
2326
  }
2182
2327
  catch (error) {
2183
- console.error(`Error reading battery data: ${error}`);
2328
+ this.logTransactionError(`Error reading battery data`, error);
2184
2329
  return null;
2185
2330
  }
2186
2331
  }
@@ -2262,7 +2407,7 @@ export class SunspecModbusClient {
2262
2407
  return true;
2263
2408
  }
2264
2409
  catch (error) {
2265
- console.error(`Error writing battery controls: ${error}`);
2410
+ this.logTransactionError(`Error writing battery controls`, error);
2266
2411
  return false;
2267
2412
  }
2268
2413
  }
@@ -2270,30 +2415,43 @@ export class SunspecModbusClient {
2270
2415
  * Set battery storage mode (simplified interface)
2271
2416
  */
2272
2417
  async setStorageMode(unitId, mode) {
2273
- let storCtlMod;
2418
+ // StorCtl_Mod says *which rate setpoint is enforced*, not what the
2419
+ // battery is allowed to do — so releasing control means clearing the
2420
+ // bits, and the rate registers have to be written alongside them.
2421
+ // Setting the bits without touching InWRte/OutWRte would enforce
2422
+ // whatever percentage was left behind by an earlier command.
2423
+ let controls;
2274
2424
  switch (mode) {
2275
2425
  case SunspecStorageMode.CHARGE:
2276
- // Enable charge only (bit 0 = 1, bit 1 = 0)
2277
- storCtlMod = SunspecStorageControlMode.CHARGE;
2426
+ // Enforce the charge-rate setpoint only (bit 0 = 1, bit 1 = 0).
2427
+ controls = { storCtlMod: SunspecStorageControlMode.CHARGE };
2278
2428
  break;
2279
2429
  case SunspecStorageMode.DISCHARGE:
2280
- // Enable discharge only (bit 0 = 0, bit 1 = 1)
2281
- storCtlMod = SunspecStorageControlMode.DISCHARGE;
2430
+ // Enforce the discharge-rate setpoint only (bit 0 = 0, bit 1 = 1).
2431
+ controls = { storCtlMod: SunspecStorageControlMode.DISCHARGE };
2282
2432
  break;
2283
2433
  case SunspecStorageMode.HOLDING:
2284
- // Disable both charge and discharge (bits 0 and 1 = 0)
2285
- storCtlMod = 0;
2434
+ // Park the battery: both setpoints enforced, both clamped to 0 %.
2435
+ controls = {
2436
+ storCtlMod: SunspecStorageControlMode.CHARGE | SunspecStorageControlMode.DISCHARGE,
2437
+ inWRte: 0,
2438
+ outWRte: 0,
2439
+ };
2286
2440
  break;
2287
2441
  case SunspecStorageMode.AUTO:
2288
- // Enable both charge and discharge (bits 0 and 1 = 1)
2289
- storCtlMod = SunspecStorageControlMode.CHARGE | SunspecStorageControlMode.DISCHARGE;
2442
+ // Hand control back: no setpoint enforced, both rates wide open.
2443
+ controls = {
2444
+ storCtlMod: SunspecStorageControlMode.NONE,
2445
+ inWRte: 100,
2446
+ outWRte: 100,
2447
+ };
2290
2448
  break;
2291
2449
  default:
2292
2450
  console.error(`Invalid storage mode: ${mode}`);
2293
2451
  return false;
2294
2452
  }
2295
- console.log(`Setting storage mode to ${mode} (control bits: 0x${storCtlMod.toString(16)})`);
2296
- return this.writeBatteryControls(unitId, { storCtlMod });
2453
+ console.log(`Setting storage mode to ${mode} (${JSON.stringify(controls)})`);
2454
+ return this.writeBatteryControls(unitId, controls);
2297
2455
  }
2298
2456
  /**
2299
2457
  * Enable or disable grid charging
@@ -2349,7 +2507,7 @@ export class SunspecModbusClient {
2349
2507
  return controls;
2350
2508
  }
2351
2509
  catch (error) {
2352
- console.error(`Error reading battery controls: ${error}`);
2510
+ this.logTransactionError(`Error reading battery controls`, error);
2353
2511
  return null;
2354
2512
  }
2355
2513
  }
@@ -2481,7 +2639,7 @@ export class SunspecModbusClient {
2481
2639
  return data;
2482
2640
  }
2483
2641
  catch (error) {
2484
- console.error(`Error reading meter data: ${error}`);
2642
+ this.logTransactionError(`Error reading meter data`, error);
2485
2643
  return null;
2486
2644
  }
2487
2645
  }
@@ -2523,7 +2681,7 @@ export class SunspecModbusClient {
2523
2681
  return data;
2524
2682
  }
2525
2683
  catch (error) {
2526
- console.error(`Error reading float meter data (Model ${blockNumber}): ${error}`);
2684
+ this.logTransactionError(`Error reading float meter data (Model ${blockNumber})`, error);
2527
2685
  return null;
2528
2686
  }
2529
2687
  }
@@ -2601,7 +2759,7 @@ export class SunspecModbusClient {
2601
2759
  return data;
2602
2760
  }
2603
2761
  catch (error) {
2604
- console.error(`Error reading common block: ${error}`);
2762
+ this.logTransactionError(`Error reading common block`, error);
2605
2763
  return null;
2606
2764
  }
2607
2765
  }
@@ -2727,7 +2885,7 @@ export class SunspecModbusClient {
2727
2885
  return settings;
2728
2886
  }
2729
2887
  catch (error) {
2730
- console.error(`Error reading inverter settings: ${error}`);
2888
+ this.logTransactionError(`Error reading inverter settings`, error);
2731
2889
  return null;
2732
2890
  }
2733
2891
  }
@@ -2744,74 +2902,76 @@ export class SunspecModbusClient {
2744
2902
  try {
2745
2903
  // Read entire model block in a single Modbus call
2746
2904
  const buffer = await this.readModelBlock(unitId, model);
2747
- // Extract scale factors from buffer (offsets 21-23)
2905
+ // Buffer offsets are SunSpec point offsets + 2: readModelBlock() returns the
2906
+ // 2-register model header (ID + length) ahead of the data registers. Scale
2907
+ // factors are points 21-23 -> buffer offsets 23-25.
2748
2908
  const scaleFactors = {
2749
- WMaxLimPct_SF: this.extractValue(buffer, 21, 'int16'),
2750
- OutPFSet_SF: this.extractValue(buffer, 22, 'int16'),
2751
- VArPct_SF: this.extractValue(buffer, 23, 'int16')
2909
+ WMaxLimPct_SF: this.extractValue(buffer, 23, 'int16'),
2910
+ OutPFSet_SF: this.extractValue(buffer, 24, 'int16'),
2911
+ VArPct_SF: this.extractValue(buffer, 25, 'int16')
2752
2912
  };
2753
- this.logRegisterRead(123, 21, 'WMaxLimPct_SF', scaleFactors.WMaxLimPct_SF, 'int16');
2754
- this.logRegisterRead(123, 22, 'OutPFSet_SF', scaleFactors.OutPFSet_SF, 'int16');
2755
- this.logRegisterRead(123, 23, 'VArPct_SF', scaleFactors.VArPct_SF, 'int16');
2913
+ this.logRegisterRead(123, 23, 'WMaxLimPct_SF', scaleFactors.WMaxLimPct_SF, 'int16');
2914
+ this.logRegisterRead(123, 24, 'OutPFSet_SF', scaleFactors.OutPFSet_SF, 'int16');
2915
+ this.logRegisterRead(123, 25, 'VArPct_SF', scaleFactors.VArPct_SF, 'int16');
2756
2916
  // Extract non-scaled fields from buffer
2757
- const connWinTmsRaw = this.extractValue(buffer, 0, 'uint16');
2758
- const connRvrtTmsRaw = this.extractValue(buffer, 1, 'uint16');
2759
- const connRaw = this.extractValue(buffer, 2, 'uint16');
2760
- const wMaxLimPctWinTmsRaw = this.extractValue(buffer, 4, 'uint16');
2761
- const wMaxLimPctRvrtTmsRaw = this.extractValue(buffer, 5, 'uint16');
2762
- const wMaxLimPctRmpTmsRaw = this.extractValue(buffer, 6, 'uint16');
2763
- const wMaxLimEnaRaw = this.extractValue(buffer, 7, 'uint16');
2764
- const outPFSetWinTmsRaw = this.extractValue(buffer, 9, 'uint16');
2765
- const outPFSetRvrtTmsRaw = this.extractValue(buffer, 10, 'uint16');
2766
- const outPFSetRmpTmsRaw = this.extractValue(buffer, 11, 'uint16');
2767
- const outPFSetEnaRaw = this.extractValue(buffer, 12, 'uint16');
2768
- const vArPctWinTmsRaw = this.extractValue(buffer, 16, 'uint16');
2769
- const vArPctRvrtTmsRaw = this.extractValue(buffer, 17, 'uint16');
2770
- const vArPctRmpTmsRaw = this.extractValue(buffer, 18, 'uint16');
2771
- const vArPctModRaw = this.extractValue(buffer, 19, 'uint16');
2772
- const vArPctEnaRaw = this.extractValue(buffer, 20, 'uint16');
2773
- this.logRegisterRead(123, 0, 'Conn_WinTms', connWinTmsRaw, 'uint16');
2774
- this.logRegisterRead(123, 1, 'Conn_RvrtTms', connRvrtTmsRaw, 'uint16');
2775
- this.logRegisterRead(123, 2, 'Conn', connRaw, 'enum16');
2776
- this.logRegisterRead(123, 4, 'WMaxLimPct_WinTms', wMaxLimPctWinTmsRaw, 'uint16');
2777
- this.logRegisterRead(123, 5, 'WMaxLimPct_RvrtTms', wMaxLimPctRvrtTmsRaw, 'uint16');
2778
- this.logRegisterRead(123, 6, 'WMaxLimPct_RmpTms', wMaxLimPctRmpTmsRaw, 'uint16');
2779
- this.logRegisterRead(123, 7, 'WMaxLim_Ena', wMaxLimEnaRaw, 'enum16');
2780
- this.logRegisterRead(123, 9, 'OutPFSet_WinTms', outPFSetWinTmsRaw, 'uint16');
2781
- this.logRegisterRead(123, 10, 'OutPFSet_RvrtTms', outPFSetRvrtTmsRaw, 'uint16');
2782
- this.logRegisterRead(123, 11, 'OutPFSet_RmpTms', outPFSetRmpTmsRaw, 'uint16');
2783
- this.logRegisterRead(123, 12, 'OutPFSet_Ena', outPFSetEnaRaw, 'enum16');
2784
- this.logRegisterRead(123, 16, 'VArPct_WinTms', vArPctWinTmsRaw, 'uint16');
2785
- this.logRegisterRead(123, 17, 'VArPct_RvrtTms', vArPctRvrtTmsRaw, 'uint16');
2786
- this.logRegisterRead(123, 18, 'VArPct_RmpTms', vArPctRmpTmsRaw, 'uint16');
2787
- this.logRegisterRead(123, 19, 'VArPct_Mod', vArPctModRaw, 'enum16');
2788
- this.logRegisterRead(123, 20, 'VArPct_Ena', vArPctEnaRaw, 'enum16');
2917
+ const connWinTmsRaw = this.extractValue(buffer, 2, 'uint16');
2918
+ const connRvrtTmsRaw = this.extractValue(buffer, 3, 'uint16');
2919
+ const connRaw = this.extractValue(buffer, 4, 'uint16');
2920
+ const wMaxLimPctWinTmsRaw = this.extractValue(buffer, 6, 'uint16');
2921
+ const wMaxLimPctRvrtTmsRaw = this.extractValue(buffer, 7, 'uint16');
2922
+ const wMaxLimPctRmpTmsRaw = this.extractValue(buffer, 8, 'uint16');
2923
+ const wMaxLimEnaRaw = this.extractValue(buffer, 9, 'uint16');
2924
+ const outPFSetWinTmsRaw = this.extractValue(buffer, 11, 'uint16');
2925
+ const outPFSetRvrtTmsRaw = this.extractValue(buffer, 12, 'uint16');
2926
+ const outPFSetRmpTmsRaw = this.extractValue(buffer, 13, 'uint16');
2927
+ const outPFSetEnaRaw = this.extractValue(buffer, 14, 'uint16');
2928
+ const vArPctWinTmsRaw = this.extractValue(buffer, 18, 'uint16');
2929
+ const vArPctRvrtTmsRaw = this.extractValue(buffer, 19, 'uint16');
2930
+ const vArPctRmpTmsRaw = this.extractValue(buffer, 20, 'uint16');
2931
+ const vArPctModRaw = this.extractValue(buffer, 21, 'uint16');
2932
+ const vArPctEnaRaw = this.extractValue(buffer, 22, 'uint16');
2933
+ this.logRegisterRead(123, 2, 'Conn_WinTms', connWinTmsRaw, 'uint16');
2934
+ this.logRegisterRead(123, 3, 'Conn_RvrtTms', connRvrtTmsRaw, 'uint16');
2935
+ this.logRegisterRead(123, 4, 'Conn', connRaw, 'enum16');
2936
+ this.logRegisterRead(123, 6, 'WMaxLimPct_WinTms', wMaxLimPctWinTmsRaw, 'uint16');
2937
+ this.logRegisterRead(123, 7, 'WMaxLimPct_RvrtTms', wMaxLimPctRvrtTmsRaw, 'uint16');
2938
+ this.logRegisterRead(123, 8, 'WMaxLimPct_RmpTms', wMaxLimPctRmpTmsRaw, 'uint16');
2939
+ this.logRegisterRead(123, 9, 'WMaxLim_Ena', wMaxLimEnaRaw, 'enum16');
2940
+ this.logRegisterRead(123, 11, 'OutPFSet_WinTms', outPFSetWinTmsRaw, 'uint16');
2941
+ this.logRegisterRead(123, 12, 'OutPFSet_RvrtTms', outPFSetRvrtTmsRaw, 'uint16');
2942
+ this.logRegisterRead(123, 13, 'OutPFSet_RmpTms', outPFSetRmpTmsRaw, 'uint16');
2943
+ this.logRegisterRead(123, 14, 'OutPFSet_Ena', outPFSetEnaRaw, 'enum16');
2944
+ this.logRegisterRead(123, 18, 'VArPct_WinTms', vArPctWinTmsRaw, 'uint16');
2945
+ this.logRegisterRead(123, 19, 'VArPct_RvrtTms', vArPctRvrtTmsRaw, 'uint16');
2946
+ this.logRegisterRead(123, 20, 'VArPct_RmpTms', vArPctRmpTmsRaw, 'uint16');
2947
+ this.logRegisterRead(123, 21, 'VArPct_Mod', vArPctModRaw, 'enum16');
2948
+ this.logRegisterRead(123, 22, 'VArPct_Ena', vArPctEnaRaw, 'enum16');
2789
2949
  const controls = {
2790
2950
  blockNumber: 123,
2791
2951
  blockAddress: model.address,
2792
2952
  blockLength: model.length,
2793
- // Connection control - Offsets 0-2
2953
+ // Connection control - points 0-2 (buffer 2-4)
2794
2954
  Conn_WinTms: connWinTmsRaw,
2795
2955
  Conn_RvrtTms: connRvrtTmsRaw,
2796
2956
  Conn: connRaw,
2797
- // Power limit control - Offsets 3-7
2798
- WMaxLimPct: this.applyScaleFactor(this.extractValue(buffer, 3, 'uint16'), scaleFactors.WMaxLimPct_SF, 'uint16', 'Power Limit Percentage', 3, 123),
2957
+ // Power limit control - points 3-7 (buffer 5-9)
2958
+ WMaxLimPct: this.applyScaleFactor(this.extractValue(buffer, 5, 'uint16'), scaleFactors.WMaxLimPct_SF, 'uint16', 'Power Limit Percentage', 5, 123),
2799
2959
  WMaxLimPct_SF: scaleFactors.WMaxLimPct_SF,
2800
2960
  WMaxLimPct_WinTms: wMaxLimPctWinTmsRaw,
2801
2961
  WMaxLimPct_RvrtTms: wMaxLimPctRvrtTmsRaw,
2802
2962
  WMaxLimPct_RmpTms: wMaxLimPctRmpTmsRaw,
2803
2963
  WMaxLim_Ena: wMaxLimEnaRaw,
2804
- // Power factor control - Offsets 8-12
2805
- OutPFSet: this.applyScaleFactor(this.extractValue(buffer, 8, 'int16'), scaleFactors.OutPFSet_SF, 'int16', 'Output Power Factor Set', 8, 123),
2964
+ // Power factor control - points 8-12 (buffer 10-14)
2965
+ OutPFSet: this.applyScaleFactor(this.extractValue(buffer, 10, 'int16'), scaleFactors.OutPFSet_SF, 'int16', 'Output Power Factor Set', 10, 123),
2806
2966
  OutPFSet_SF: scaleFactors.OutPFSet_SF,
2807
2967
  OutPFSet_WinTms: outPFSetWinTmsRaw,
2808
2968
  OutPFSet_RvrtTms: outPFSetRvrtTmsRaw,
2809
2969
  OutPFSet_RmpTms: outPFSetRmpTmsRaw,
2810
2970
  OutPFSet_Ena: outPFSetEnaRaw,
2811
- // Reactive power control - Offsets 13-20
2812
- VArWMaxPct: this.applyScaleFactor(this.extractValue(buffer, 13, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Reactive Power at Max Power %', 13, 123),
2813
- VArMaxPct: this.applyScaleFactor(this.extractValue(buffer, 14, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Max Reactive Power %', 14, 123),
2814
- VArAvalPct: this.applyScaleFactor(this.extractValue(buffer, 15, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Available Reactive Power %', 15, 123),
2971
+ // Reactive power control - points 13-20 (buffer 15-22)
2972
+ VArWMaxPct: this.applyScaleFactor(this.extractValue(buffer, 15, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Reactive Power at Max Power %', 15, 123),
2973
+ VArMaxPct: this.applyScaleFactor(this.extractValue(buffer, 16, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Max Reactive Power %', 16, 123),
2974
+ VArAvalPct: this.applyScaleFactor(this.extractValue(buffer, 17, 'int16'), scaleFactors.VArPct_SF, 'int16', 'Available Reactive Power %', 17, 123),
2815
2975
  VArPct_SF: scaleFactors.VArPct_SF,
2816
2976
  VArPct_WinTms: vArPctWinTmsRaw,
2817
2977
  VArPct_RvrtTms: vArPctRvrtTmsRaw,
@@ -2823,7 +2983,7 @@ export class SunspecModbusClient {
2823
2983
  return controls;
2824
2984
  }
2825
2985
  catch (error) {
2826
- console.error(`Error reading inverter controls: ${error}`);
2986
+ this.logTransactionError(`Error reading inverter controls`, error);
2827
2987
  return null;
2828
2988
  }
2829
2989
  }
@@ -2861,7 +3021,7 @@ export class SunspecModbusClient {
2861
3021
  return true;
2862
3022
  }
2863
3023
  catch (error) {
2864
- console.error(`Error writing inverter settings: ${error}`);
3024
+ this.logTransactionError(`Error writing inverter settings`, error);
2865
3025
  return false;
2866
3026
  }
2867
3027
  }
@@ -2874,43 +3034,45 @@ export class SunspecModbusClient {
2874
3034
  console.error(`Controls model 123 not found on unit ${unitId}`);
2875
3035
  return false;
2876
3036
  }
3037
+ // model.address points at the 2-register model header (ID + length), so a
3038
+ // SunSpec point at offset N lives at baseAddr + 2 + N.
2877
3039
  const baseAddr = model.address;
2878
3040
  try {
2879
3041
  // Per-field inverter-control writes are debug-only; the high-level callers
2880
3042
  // (`setFeedInLimit`, etc.) still log the action and outcome at info level.
2881
3043
  if (controls.Conn !== undefined) {
2882
- await this.writeRegisterValue(unitId, baseAddr + 2, controls.Conn, 'uint16');
3044
+ await this.writeRegisterValue(unitId, baseAddr + 4, controls.Conn, 'uint16');
2883
3045
  console.debug(`Set connection control to ${controls.Conn}`);
2884
3046
  }
2885
- // Power limit control (Register 3) - needs scale factor
3047
+ // Power limit control (point 3 -> baseAddr + 5) - needs scale factor
2886
3048
  if (controls.WMaxLimPct !== undefined) {
2887
- const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 21, 1, 'int16');
3049
+ const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 23, 1, 'int16');
2888
3050
  const scaledValue = Math.round(controls.WMaxLimPct / Math.pow(10, scaleFactor));
2889
- await this.writeRegisterValue(unitId, baseAddr + 3, scaledValue, 'uint16');
3051
+ await this.writeRegisterValue(unitId, baseAddr + 5, scaledValue, 'uint16');
2890
3052
  console.debug(`Set power limit to ${controls.WMaxLimPct}% (scaled: ${scaledValue})`);
2891
3053
  }
2892
- // Throttle enable/disable (Register 7)
3054
+ // Throttle enable/disable (point 7 -> baseAddr + 9)
2893
3055
  if (controls.WMaxLim_Ena !== undefined) {
2894
- await this.writeRegisterValue(unitId, baseAddr + 7, controls.WMaxLim_Ena, 'uint16');
3056
+ await this.writeRegisterValue(unitId, baseAddr + 9, controls.WMaxLim_Ena, 'uint16');
2895
3057
  console.debug(`Set throttle enable to ${controls.WMaxLim_Ena}`);
2896
3058
  }
2897
- // Power factor control (Register 8) - needs scale factor
3059
+ // Power factor control (point 8 -> baseAddr + 10) - needs scale factor
2898
3060
  if (controls.OutPFSet !== undefined) {
2899
- const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 22, 1, 'int16');
3061
+ const scaleFactor = await this.readRegisterValue(unitId, baseAddr + 24, 1, 'int16');
2900
3062
  const scaledValue = Math.round(controls.OutPFSet / Math.pow(10, scaleFactor));
2901
- await this.writeRegisterValue(unitId, baseAddr + 8, scaledValue, 'int16');
3063
+ await this.writeRegisterValue(unitId, baseAddr + 10, scaledValue, 'int16');
2902
3064
  console.debug(`Set power factor to ${controls.OutPFSet} (scaled: ${scaledValue})`);
2903
3065
  }
2904
- // Power factor enable/disable (Register 12)
3066
+ // Power factor enable/disable (point 12 -> baseAddr + 14)
2905
3067
  if (controls.OutPFSet_Ena !== undefined) {
2906
- await this.writeRegisterValue(unitId, baseAddr + 12, controls.OutPFSet_Ena, 'uint16');
3068
+ await this.writeRegisterValue(unitId, baseAddr + 14, controls.OutPFSet_Ena, 'uint16');
2907
3069
  console.debug(`Set PF enable to ${controls.OutPFSet_Ena}`);
2908
3070
  }
2909
3071
  console.debug('Inverter controls written successfully');
2910
3072
  return true;
2911
3073
  }
2912
3074
  catch (error) {
2913
- console.error(`Error writing inverter controls: ${error}`);
3075
+ this.logTransactionError(`Error writing inverter controls`, error);
2914
3076
  return false;
2915
3077
  }
2916
3078
  }