@enyo-energy/sunspec-sdk 0.0.102 → 0.0.104

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.
@@ -7,5 +7,6 @@ export { SunspecCalibrationStorage, createSunspecCalibrationStorage } from './su
7
7
  export { SunspecBatteryCalibrationDriver } from './sunspec-battery-calibration-driver.cjs';
8
8
  export { SunspecBatteryFeatureCalibrator, type SunspecBatteryFeatureCalibratorOptions, decodeFeatureResults, } from './sunspec-battery-feature-calibrator.cjs';
9
9
  export { SunspecBatteryScheduleHandler, type SunspecScheduleRegisters, type SunspecBatteryScheduleHandlerOptions, } from './sunspec-battery-schedule-handler.cjs';
10
+ export { type EnergyAppModbus, type EnergyAppModbusInstance, type ModbusOptions, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
10
11
  export { type EnyoDataBusSetStorageScheduleV1, type EnyoStorageScheduleEntry, EnyoStorageScheduleModeEnum, EnyoStorageScheduleDirectionEnum, } from '@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js';
11
12
  export { AbstractCalibrationStorage, InMemoryCalibrationStorage, type AckResult, type CalibrationResult, type CalibrationState, type CalibrationSnapshot, type CalibrationRestoreCallback, type RestoreReason, SnapshotService, type SnapshotServiceOptions, DEFAULT_AUTO_STOP_MS, AbstractBatteryCalibrationDriver, BatteryCalibrator, type BatteryCalibratorOptions, type BatteryCalibratorConfig, DEFAULT_BATTERY_CALIBRATOR_CONFIG, CalibrationResultStore, type CalibrationResultStoreData, CalibrationTrigger, type CalibrationTriggerOptions, } from '@enyo-energy/appliance-calibration';
@@ -117,6 +117,19 @@ class BaseSunspecDevice {
117
117
  * would otherwise stay Offline forever despite reading data fine.
118
118
  */
119
119
  appliedOffline = false;
120
+ /**
121
+ * True once {@link reassertConnectedIfRecovered} has confirmed (via the
122
+ * appliance store) that this device is Connected, so it can stop probing
123
+ * for an *externally* applied Offline state. Distinct from
124
+ * {@link appliedOffline}, which only tracks Offline states this SDK object
125
+ * applied itself. An appliance can be marked Offline by a path outside the
126
+ * SDK object — e.g. the energy-app registering a boot-time offline
127
+ * placeholder before this device came up on a shared socket — which never
128
+ * sets appliedOffline; without reconciling against actual state, such a
129
+ * device stays Offline forever despite reading data fine. Reset in
130
+ * {@link markOffline} so a later Offline episode is re-checked.
131
+ */
132
+ reconciledExternalOffline = false;
120
133
  /**
121
134
  * Prefix used when persisting calibration snapshots via the library's
122
135
  * {@link SnapshotService}. Kept identical to the key the SDK used before
@@ -337,6 +350,7 @@ class BaseSunspecDevice {
337
350
  try {
338
351
  await this.applianceManager.updateApplianceState(this.applianceId, enyo_appliance_js_1.EnyoApplianceConnectionType.Connector, enyo_appliance_js_1.EnyoApplianceStateEnum.Offline);
339
352
  this.appliedOffline = true;
353
+ this.reconciledExternalOffline = false;
340
354
  }
341
355
  catch (error) {
342
356
  console.error(`${this.constructor.name} ${this.applianceId}: Failed to mark appliance offline: ${error}`);
@@ -352,17 +366,45 @@ class BaseSunspecDevice {
352
366
  * readData() and skip tryReconnect() entirely, so without this they would
353
367
  * stay Offline forever despite reading data fine.
354
368
  *
369
+ * Heals two ways an appliance can be stuck Offline while reads succeed:
370
+ * 1. This SDK object marked itself offline ({@link appliedOffline}) and a
371
+ * sibling won the reconnect race — the original shared-socket case.
372
+ * 2. The appliance was marked Offline by a path *outside* this object —
373
+ * e.g. the energy-app registering a boot-time offline placeholder
374
+ * before this device came up on the shared socket — which never sets
375
+ * appliedOffline. We reconcile against the actual stored state so the
376
+ * invariant "healthy reads ⇒ Connected" holds regardless of who
377
+ * applied the Offline.
378
+ *
355
379
  * Call this on the success path of readData() (after the
356
- * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). It is
357
- * a cheap no-op unless this device was previously marked offline.
380
+ * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). Cheap:
381
+ * a no-op via the appliedOffline fast path, and the external-state lookup
382
+ * runs at most once per Offline episode (latched by
383
+ * {@link reconciledExternalOffline} once Connected is confirmed).
358
384
  */
359
385
  async reassertConnectedIfRecovered() {
360
- if (!this.appliedOffline || !this.applianceId) {
386
+ if (!this.applianceId) {
361
387
  return;
362
388
  }
363
389
  if (!this.sunspecClient.isHealthy(this.unitId)) {
364
390
  return;
365
391
  }
392
+ let shouldReassert = this.appliedOffline;
393
+ // Not offline by our own hand: it may still be Offline from an
394
+ // externally applied state. Probe the store once until we confirm
395
+ // Connected, then latch so the steady state adds no extra lookups.
396
+ if (!shouldReassert && !this.reconciledExternalOffline) {
397
+ const appliance = await this.applianceManager.findApplianceById(this.applianceId);
398
+ if (appliance?.metadata?.state === enyo_appliance_js_1.EnyoApplianceStateEnum.Offline) {
399
+ shouldReassert = true;
400
+ }
401
+ else {
402
+ this.reconciledExternalOffline = true;
403
+ }
404
+ }
405
+ if (!shouldReassert) {
406
+ return;
407
+ }
366
408
  console.log(`${this.constructor.name} ${this.applianceId}: connection recovered via shared socket — re-asserting Connected`);
367
409
  try {
368
410
  await this.applianceManager.updateApplianceState(this.applianceId, enyo_appliance_js_1.EnyoApplianceConnectionType.Connector, enyo_appliance_js_1.EnyoApplianceStateEnum.Connected);
@@ -372,6 +414,7 @@ class BaseSunspecDevice {
372
414
  return;
373
415
  }
374
416
  this.appliedOffline = false;
417
+ this.reconciledExternalOffline = true;
375
418
  this.retryManager.reset();
376
419
  this.consecutiveReconnectFailures = 0;
377
420
  await this.onConnectionRestored();
@@ -37,6 +37,19 @@ export declare abstract class BaseSunspecDevice {
37
37
  * would otherwise stay Offline forever despite reading data fine.
38
38
  */
39
39
  private appliedOffline;
40
+ /**
41
+ * True once {@link reassertConnectedIfRecovered} has confirmed (via the
42
+ * appliance store) that this device is Connected, so it can stop probing
43
+ * for an *externally* applied Offline state. Distinct from
44
+ * {@link appliedOffline}, which only tracks Offline states this SDK object
45
+ * applied itself. An appliance can be marked Offline by a path outside the
46
+ * SDK object — e.g. the energy-app registering a boot-time offline
47
+ * placeholder before this device came up on a shared socket — which never
48
+ * sets appliedOffline; without reconciling against actual state, such a
49
+ * device stays Offline forever despite reading data fine. Reset in
50
+ * {@link markOffline} so a later Offline episode is re-checked.
51
+ */
52
+ private reconciledExternalOffline;
40
53
  /**
41
54
  * Prefix used when persisting calibration snapshots via the library's
42
55
  * {@link SnapshotService}. Kept identical to the key the SDK used before
@@ -152,9 +165,21 @@ export declare abstract class BaseSunspecDevice {
152
165
  * readData() and skip tryReconnect() entirely, so without this they would
153
166
  * stay Offline forever despite reading data fine.
154
167
  *
168
+ * Heals two ways an appliance can be stuck Offline while reads succeed:
169
+ * 1. This SDK object marked itself offline ({@link appliedOffline}) and a
170
+ * sibling won the reconnect race — the original shared-socket case.
171
+ * 2. The appliance was marked Offline by a path *outside* this object —
172
+ * e.g. the energy-app registering a boot-time offline placeholder
173
+ * before this device came up on the shared socket — which never sets
174
+ * appliedOffline. We reconcile against the actual stored state so the
175
+ * invariant "healthy reads ⇒ Connected" holds regardless of who
176
+ * applied the Offline.
177
+ *
155
178
  * Call this on the success path of readData() (after the
156
- * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). It is
157
- * a cheap no-op unless this device was previously marked offline.
179
+ * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). Cheap:
180
+ * a no-op via the appliedOffline fast path, and the external-state lookup
181
+ * runs at most once per Offline episode (latched by
182
+ * {@link reconciledExternalOffline} once Connected is confirmed).
158
183
  */
159
184
  protected reassertConnectedIfRecovered(): Promise<void>;
160
185
  protected sendCommandAcknowledge(messageId: string, acknowledgeMessage: EnyoDataBusMessageEnum | string, answer: EnyoCommandAcknowledgeAnswerEnum, rejectionReason?: string): void;
@@ -53,15 +53,19 @@ const registryKey = (host, port) => `${host}:${port}`;
53
53
  * Get (or create) the singleton SunspecModbusClient for this network device.
54
54
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
55
55
  *
56
- * NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
57
- * host:port. Because the client is cached and refcounted, a later caller passing different config
58
- * receives the already-created instance and its config is ignored.
56
+ * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
57
+ * created for a given host:port. Because the client is cached and refcounted, a later caller
58
+ * passing different config receives the already-created instance and its config is ignored.
59
+ *
60
+ * `modbusFactory` lets a caller supply their own Modbus backend (the factory whose `connect()`
61
+ * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
62
+ * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
59
63
  */
60
- function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience) {
64
+ function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience, modbusFactory) {
61
65
  const key = registryKey(host, port);
62
66
  let entry = CLIENT_REGISTRY.get(key);
63
67
  if (!entry) {
64
- entry = { client: new SunspecModbusClient(energyApp, pacing, resilience), refcount: 0 };
68
+ entry = { client: new SunspecModbusClient(energyApp, pacing, resilience, modbusFactory), refcount: 0 };
65
69
  CLIENT_REGISTRY.set(key, entry);
66
70
  }
67
71
  entry.refcount++;
@@ -127,6 +131,7 @@ async function retryAsync(fn, opts) {
127
131
  class SunspecModbusClient {
128
132
  energyApp;
129
133
  pacing;
134
+ modbusFactory;
130
135
  // Per-unit Modbus instance/reader/discovered-models maps. One client = one network device,
131
136
  // many unit IDs share that client (each unit ID is one EnergyAppModbusInstance underneath).
132
137
  modbusInstances = new Map();
@@ -170,20 +175,47 @@ class SunspecModbusClient {
170
175
  // the transport still reports connected but that has gone quiet past staleSocketMs is presumed
171
176
  // dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
172
177
  lastOkAtByUnit = new Map();
173
- constructor(energyApp,
178
+ constructor(
179
+ // The host application. Only used to obtain the default Modbus backend via
180
+ // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
181
+ energyApp,
174
182
  // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
175
183
  // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
176
184
  // connection. An empty object leaves both undefined so the SDK applies its own defaults.
177
185
  pacing = {},
178
186
  // Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
179
187
  // so omitted fields keep their defaults.
180
- resilience = {}) {
188
+ resilience = {},
189
+ // Optional custom Modbus backend. When provided, its `connect()` is used to open every
190
+ // per-unit connection instead of `energyApp.useModbus()` — letting callers plug in their own
191
+ // Modbus implementation (a mock for tests, or an alternative transport). All the resilience
192
+ // machinery (per-unit connect/reconnect, TLS, pacing, timeouts) is driven through this
193
+ // factory, which is why an already-connected instance would not do: the client re-opens
194
+ // connections on its own schedule and needs a factory to call.
195
+ modbusFactory) {
181
196
  this.energyApp = energyApp;
182
197
  this.pacing = pacing;
198
+ this.modbusFactory = modbusFactory;
199
+ if (!energyApp && !modbusFactory) {
200
+ throw new Error("SunspecModbusClient requires either an EnergyApp or a modbusFactory");
201
+ }
183
202
  this.connectionHealth = new EnergyAppModbusConnectionHealth_js_1.EnergyAppModbusConnectionHealth();
184
203
  this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter_js_1.EnergyAppModbusDataTypeConverter();
185
204
  this.resilience = { ...sunspec_interfaces_js_1.DEFAULT_MODBUS_RESILIENCE_CONFIG, ...resilience };
186
205
  }
206
+ /**
207
+ * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
208
+ * if one was given, otherwise the host application's default (`energyApp.useModbus()`). The
209
+ * constructor guarantees at least one of the two is present.
210
+ */
211
+ useModbus() {
212
+ if (this.modbusFactory)
213
+ return this.modbusFactory;
214
+ if (!this.energyApp) {
215
+ throw new Error("SunspecModbusClient has no Modbus backend: neither energyApp nor modbusFactory is set");
216
+ }
217
+ return this.energyApp.useModbus();
218
+ }
187
219
  /**
188
220
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
189
221
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -231,6 +263,10 @@ class SunspecModbusClient {
231
263
  await this._openUnit(host, port, unitId, {
232
264
  connectRetries: 0,
233
265
  connectTimeoutMs: opts.timeoutMs ?? this.resilience.connectTimeoutMs,
266
+ // Fast-fail scan: a mostly-dead RS485 range must cost ~one timeout per unit, so do
267
+ // NOT let the transport also walk a fallback host (which would double the per-unit
268
+ // cost). Warm connects/reconnects still get the in-band fallback.
269
+ useFallbackHosts: false,
234
270
  });
235
271
  console.log(`Probed Sunspec unit ${unitId} at ${host}:${port} — open (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
236
272
  });
@@ -402,6 +438,25 @@ class SunspecModbusClient {
402
438
  return false;
403
439
  }
404
440
  }
441
+ /**
442
+ * Build the ordered host list handed to the transport's `host` option for a single connect.
443
+ * The attempt's primary target leads, followed by every OTHER known host (the other of
444
+ * primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
445
+ * DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
446
+ * only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
447
+ * no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
448
+ */
449
+ buildConnectHosts(primaryTarget) {
450
+ const hosts = [primaryTarget];
451
+ const params = this.connectionParams;
452
+ if (params) {
453
+ for (const h of [params.primaryHost, params.secondaryHost]) {
454
+ if (h && !hosts.includes(h))
455
+ hosts.push(h);
456
+ }
457
+ }
458
+ return hosts.length === 1 ? hosts[0] : hosts;
459
+ }
405
460
  /**
406
461
  * Open a unit, retrying the connect on a transient failure per the resilience config
407
462
  * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
@@ -415,7 +470,11 @@ class SunspecModbusClient {
415
470
  async _openUnit(host, port, unitId, override) {
416
471
  const connectTimeoutMs = override?.connectTimeoutMs ?? this.resilience.connectTimeoutMs;
417
472
  const attempts = (override?.connectRetries ?? this.resilience.connectRetries) + 1;
418
- await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs), {
473
+ // Default ON: a normal connect/reconnect hands the transport BOTH known hosts so a single
474
+ // attempt tolerates DNS/DHCP drift on the first one. probeUnit opts out to stay a fast-fail
475
+ // single-host scan (see probeUnit / _openUnitOnce).
476
+ const useFallbackHosts = override?.useFallbackHosts ?? true;
477
+ await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs, useFallbackHosts), {
419
478
  attempts,
420
479
  delayMs: this.resilience.connectRetryDelayMs,
421
480
  onRetry: (error, attempt) => console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} failed ` +
@@ -427,15 +486,28 @@ class SunspecModbusClient {
427
486
  * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
428
487
  * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
429
488
  * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
430
- */
431
- async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
489
+ *
490
+ * When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
491
+ * full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
492
+ * known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
493
+ * waiting for the client's own sequential primary→secondary retry. The transport walks the list
494
+ * in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
495
+ * the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
496
+ * false to keep speculative RS485 scans a fast-fail single-host probe.
497
+ */
498
+ async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs, useFallbackHosts = true) {
432
499
  let candidate = null;
500
+ const hosts = useFallbackHosts ? this.buildConnectHosts(host) : host;
501
+ const hostCount = Array.isArray(hosts) ? hosts.length : 1;
502
+ // Each host in the list gets its own `timeout`; bound the whole walk at count × budget so we
503
+ // don't kill a genuine fallback to the second host with the single-host budget.
504
+ const overallBudgetMs = connectTimeoutMs * hostCount;
433
505
  try {
434
506
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
435
507
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
436
508
  // can still leave the returned promise pending — bound it independently.
437
- candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
438
- host,
509
+ candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.useModbus().connect({
510
+ host: hosts,
439
511
  port,
440
512
  unitId,
441
513
  timeout: connectTimeoutMs,
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.cjs";
20
20
  import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
21
- import { EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
21
+ import { EnergyAppModbus, EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
22
22
  import { EnergyApp } from "@enyo-energy/energy-app-sdk";
23
23
  /**
24
24
  * Thrown when a single Modbus transaction (read/write/connect/disconnect) exceeds its configured
@@ -34,11 +34,15 @@ export declare class ModbusOperationTimeoutError extends Error {
34
34
  * Get (or create) the singleton SunspecModbusClient for this network device.
35
35
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
36
36
  *
37
- * NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
38
- * host:port. Because the client is cached and refcounted, a later caller passing different config
39
- * receives the already-created instance and its config is ignored.
37
+ * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
38
+ * created for a given host:port. Because the client is cached and refcounted, a later caller
39
+ * passing different config receives the already-created instance and its config is ignored.
40
+ *
41
+ * `modbusFactory` lets a caller supply their own Modbus backend (the factory whose `connect()`
42
+ * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
43
+ * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
40
44
  */
41
- export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig): SunspecModbusClient;
45
+ export declare function getOrCreateSunspecClient(energyApp: EnergyApp | undefined, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus): SunspecModbusClient;
42
46
  /**
43
47
  * Release a refcount on the network-device client. When the last consumer releases,
44
48
  * the client is fully disconnected (all units closed) and removed from the registry.
@@ -63,6 +67,7 @@ export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts:
63
67
  export declare class SunspecModbusClient {
64
68
  private energyApp;
65
69
  private pacing;
70
+ private modbusFactory?;
66
71
  private modbusInstances;
67
72
  private faultTolerantReaders;
68
73
  private discoveredModelsByUnit;
@@ -79,7 +84,13 @@ export declare class SunspecModbusClient {
79
84
  private resilience;
80
85
  private poisonedUnits;
81
86
  private lastOkAtByUnit;
82
- constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig);
87
+ constructor(energyApp: EnergyApp | undefined, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
88
+ /**
89
+ * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
90
+ * if one was given, otherwise the host application's default (`energyApp.useModbus()`). The
91
+ * constructor guarantees at least one of the two is present.
92
+ */
93
+ private useModbus;
83
94
  /**
84
95
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
85
96
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -152,6 +163,15 @@ export declare class SunspecModbusClient {
152
163
  * if every unit succeeded.
153
164
  */
154
165
  private attemptConnection;
166
+ /**
167
+ * Build the ordered host list handed to the transport's `host` option for a single connect.
168
+ * The attempt's primary target leads, followed by every OTHER known host (the other of
169
+ * primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
170
+ * DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
171
+ * only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
172
+ * no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
173
+ */
174
+ private buildConnectHosts;
155
175
  /**
156
176
  * Open a unit, retrying the connect on a transient failure per the resilience config
157
177
  * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
@@ -167,6 +187,14 @@ export declare class SunspecModbusClient {
167
187
  * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
168
188
  * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
169
189
  * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
190
+ *
191
+ * When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
192
+ * full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
193
+ * known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
194
+ * waiting for the client's own sequential primary→secondary retry. The transport walks the list
195
+ * in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
196
+ * the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
197
+ * false to keep speculative RS485 scans a fast-fail single-host probe.
170
198
  */
171
199
  private _openUnitOnce;
172
200
  /**
@@ -9,7 +9,7 @@ exports.getSdkVersion = getSdkVersion;
9
9
  /**
10
10
  * Current version of the enyo Energy App SDK.
11
11
  */
12
- exports.SDK_VERSION = '0.0.102';
12
+ exports.SDK_VERSION = '0.0.104';
13
13
  /**
14
14
  * Gets the current SDK version.
15
15
  * @returns The semantic version string of the SDK
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export declare const SDK_VERSION = "0.0.102";
8
+ export declare const SDK_VERSION = "0.0.104";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/dist/index.d.ts CHANGED
@@ -7,5 +7,6 @@ export { SunspecCalibrationStorage, createSunspecCalibrationStorage } from './su
7
7
  export { SunspecBatteryCalibrationDriver } from './sunspec-battery-calibration-driver.js';
8
8
  export { SunspecBatteryFeatureCalibrator, type SunspecBatteryFeatureCalibratorOptions, decodeFeatureResults, } from './sunspec-battery-feature-calibrator.js';
9
9
  export { SunspecBatteryScheduleHandler, type SunspecScheduleRegisters, type SunspecBatteryScheduleHandlerOptions, } from './sunspec-battery-schedule-handler.js';
10
+ export { type EnergyAppModbus, type EnergyAppModbusInstance, type ModbusOptions, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
10
11
  export { type EnyoDataBusSetStorageScheduleV1, type EnyoStorageScheduleEntry, EnyoStorageScheduleModeEnum, EnyoStorageScheduleDirectionEnum, } from '@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js';
11
12
  export { AbstractCalibrationStorage, InMemoryCalibrationStorage, type AckResult, type CalibrationResult, type CalibrationState, type CalibrationSnapshot, type CalibrationRestoreCallback, type RestoreReason, SnapshotService, type SnapshotServiceOptions, DEFAULT_AUTO_STOP_MS, AbstractBatteryCalibrationDriver, BatteryCalibrator, type BatteryCalibratorOptions, type BatteryCalibratorConfig, DEFAULT_BATTERY_CALIBRATOR_CONFIG, CalibrationResultStore, type CalibrationResultStoreData, CalibrationTrigger, type CalibrationTriggerOptions, } from '@enyo-energy/appliance-calibration';
@@ -37,6 +37,19 @@ export declare abstract class BaseSunspecDevice {
37
37
  * would otherwise stay Offline forever despite reading data fine.
38
38
  */
39
39
  private appliedOffline;
40
+ /**
41
+ * True once {@link reassertConnectedIfRecovered} has confirmed (via the
42
+ * appliance store) that this device is Connected, so it can stop probing
43
+ * for an *externally* applied Offline state. Distinct from
44
+ * {@link appliedOffline}, which only tracks Offline states this SDK object
45
+ * applied itself. An appliance can be marked Offline by a path outside the
46
+ * SDK object — e.g. the energy-app registering a boot-time offline
47
+ * placeholder before this device came up on a shared socket — which never
48
+ * sets appliedOffline; without reconciling against actual state, such a
49
+ * device stays Offline forever despite reading data fine. Reset in
50
+ * {@link markOffline} so a later Offline episode is re-checked.
51
+ */
52
+ private reconciledExternalOffline;
40
53
  /**
41
54
  * Prefix used when persisting calibration snapshots via the library's
42
55
  * {@link SnapshotService}. Kept identical to the key the SDK used before
@@ -152,9 +165,21 @@ export declare abstract class BaseSunspecDevice {
152
165
  * readData() and skip tryReconnect() entirely, so without this they would
153
166
  * stay Offline forever despite reading data fine.
154
167
  *
168
+ * Heals two ways an appliance can be stuck Offline while reads succeed:
169
+ * 1. This SDK object marked itself offline ({@link appliedOffline}) and a
170
+ * sibling won the reconnect race — the original shared-socket case.
171
+ * 2. The appliance was marked Offline by a path *outside* this object —
172
+ * e.g. the energy-app registering a boot-time offline placeholder
173
+ * before this device came up on the shared socket — which never sets
174
+ * appliedOffline. We reconcile against the actual stored state so the
175
+ * invariant "healthy reads ⇒ Connected" holds regardless of who
176
+ * applied the Offline.
177
+ *
155
178
  * Call this on the success path of readData() (after the
156
- * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). It is
157
- * a cheap no-op unless this device was previously marked offline.
179
+ * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). Cheap:
180
+ * a no-op via the appliedOffline fast path, and the external-state lookup
181
+ * runs at most once per Offline episode (latched by
182
+ * {@link reconciledExternalOffline} once Connected is confirmed).
158
183
  */
159
184
  protected reassertConnectedIfRecovered(): Promise<void>;
160
185
  protected sendCommandAcknowledge(messageId: string, acknowledgeMessage: EnyoDataBusMessageEnum | string, answer: EnyoCommandAcknowledgeAnswerEnum, rejectionReason?: string): void;
@@ -110,6 +110,19 @@ export class BaseSunspecDevice {
110
110
  * would otherwise stay Offline forever despite reading data fine.
111
111
  */
112
112
  appliedOffline = false;
113
+ /**
114
+ * True once {@link reassertConnectedIfRecovered} has confirmed (via the
115
+ * appliance store) that this device is Connected, so it can stop probing
116
+ * for an *externally* applied Offline state. Distinct from
117
+ * {@link appliedOffline}, which only tracks Offline states this SDK object
118
+ * applied itself. An appliance can be marked Offline by a path outside the
119
+ * SDK object — e.g. the energy-app registering a boot-time offline
120
+ * placeholder before this device came up on a shared socket — which never
121
+ * sets appliedOffline; without reconciling against actual state, such a
122
+ * device stays Offline forever despite reading data fine. Reset in
123
+ * {@link markOffline} so a later Offline episode is re-checked.
124
+ */
125
+ reconciledExternalOffline = false;
113
126
  /**
114
127
  * Prefix used when persisting calibration snapshots via the library's
115
128
  * {@link SnapshotService}. Kept identical to the key the SDK used before
@@ -330,6 +343,7 @@ export class BaseSunspecDevice {
330
343
  try {
331
344
  await this.applianceManager.updateApplianceState(this.applianceId, EnyoApplianceConnectionType.Connector, EnyoApplianceStateEnum.Offline);
332
345
  this.appliedOffline = true;
346
+ this.reconciledExternalOffline = false;
333
347
  }
334
348
  catch (error) {
335
349
  console.error(`${this.constructor.name} ${this.applianceId}: Failed to mark appliance offline: ${error}`);
@@ -345,17 +359,45 @@ export class BaseSunspecDevice {
345
359
  * readData() and skip tryReconnect() entirely, so without this they would
346
360
  * stay Offline forever despite reading data fine.
347
361
  *
362
+ * Heals two ways an appliance can be stuck Offline while reads succeed:
363
+ * 1. This SDK object marked itself offline ({@link appliedOffline}) and a
364
+ * sibling won the reconnect race — the original shared-socket case.
365
+ * 2. The appliance was marked Offline by a path *outside* this object —
366
+ * e.g. the energy-app registering a boot-time offline placeholder
367
+ * before this device came up on the shared socket — which never sets
368
+ * appliedOffline. We reconcile against the actual stored state so the
369
+ * invariant "healthy reads ⇒ Connected" holds regardless of who
370
+ * applied the Offline.
371
+ *
348
372
  * Call this on the success path of readData() (after the
349
- * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). It is
350
- * a cheap no-op unless this device was previously marked offline.
373
+ * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). Cheap:
374
+ * a no-op via the appliedOffline fast path, and the external-state lookup
375
+ * runs at most once per Offline episode (latched by
376
+ * {@link reconciledExternalOffline} once Connected is confirmed).
351
377
  */
352
378
  async reassertConnectedIfRecovered() {
353
- if (!this.appliedOffline || !this.applianceId) {
379
+ if (!this.applianceId) {
354
380
  return;
355
381
  }
356
382
  if (!this.sunspecClient.isHealthy(this.unitId)) {
357
383
  return;
358
384
  }
385
+ let shouldReassert = this.appliedOffline;
386
+ // Not offline by our own hand: it may still be Offline from an
387
+ // externally applied state. Probe the store once until we confirm
388
+ // Connected, then latch so the steady state adds no extra lookups.
389
+ if (!shouldReassert && !this.reconciledExternalOffline) {
390
+ const appliance = await this.applianceManager.findApplianceById(this.applianceId);
391
+ if (appliance?.metadata?.state === EnyoApplianceStateEnum.Offline) {
392
+ shouldReassert = true;
393
+ }
394
+ else {
395
+ this.reconciledExternalOffline = true;
396
+ }
397
+ }
398
+ if (!shouldReassert) {
399
+ return;
400
+ }
359
401
  console.log(`${this.constructor.name} ${this.applianceId}: connection recovered via shared socket — re-asserting Connected`);
360
402
  try {
361
403
  await this.applianceManager.updateApplianceState(this.applianceId, EnyoApplianceConnectionType.Connector, EnyoApplianceStateEnum.Connected);
@@ -365,6 +407,7 @@ export class BaseSunspecDevice {
365
407
  return;
366
408
  }
367
409
  this.appliedOffline = false;
410
+ this.reconciledExternalOffline = true;
368
411
  this.retryManager.reset();
369
412
  this.consecutiveReconnectFailures = 0;
370
413
  await this.onConnectionRestored();
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { type SunspecInverterControls, type SunspecInverterData, type SunspecInverterSettings, type SunspecMeterData, type SunspecModel, type SunspecMPPTData, type SunspecBatteryData, type SunspecBatteryBaseData, type SunspecBatteryControls, SunspecStorageMode, type IModbusPacingConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.js";
20
20
  import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
21
- import { EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
21
+ import { EnergyAppModbus, EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
22
22
  import { EnergyApp } from "@enyo-energy/energy-app-sdk";
23
23
  /**
24
24
  * Thrown when a single Modbus transaction (read/write/connect/disconnect) exceeds its configured
@@ -34,11 +34,15 @@ export declare class ModbusOperationTimeoutError extends Error {
34
34
  * Get (or create) the singleton SunspecModbusClient for this network device.
35
35
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
36
36
  *
37
- * NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
38
- * host:port. Because the client is cached and refcounted, a later caller passing different config
39
- * receives the already-created instance and its config is ignored.
37
+ * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
38
+ * created for a given host:port. Because the client is cached and refcounted, a later caller
39
+ * passing different config receives the already-created instance and its config is ignored.
40
+ *
41
+ * `modbusFactory` lets a caller supply their own Modbus backend (the factory whose `connect()`
42
+ * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
43
+ * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
40
44
  */
41
- export declare function getOrCreateSunspecClient(energyApp: EnergyApp, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig): SunspecModbusClient;
45
+ export declare function getOrCreateSunspecClient(energyApp: EnergyApp | undefined, host: string, port?: number, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus): SunspecModbusClient;
42
46
  /**
43
47
  * Release a refcount on the network-device client. When the last consumer releases,
44
48
  * the client is fully disconnected (all units closed) and removed from the registry.
@@ -63,6 +67,7 @@ export declare function retryAsync<T>(fn: (attempt: number) => Promise<T>, opts:
63
67
  export declare class SunspecModbusClient {
64
68
  private energyApp;
65
69
  private pacing;
70
+ private modbusFactory?;
66
71
  private modbusInstances;
67
72
  private faultTolerantReaders;
68
73
  private discoveredModelsByUnit;
@@ -79,7 +84,13 @@ export declare class SunspecModbusClient {
79
84
  private resilience;
80
85
  private poisonedUnits;
81
86
  private lastOkAtByUnit;
82
- constructor(energyApp: EnergyApp, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig);
87
+ constructor(energyApp: EnergyApp | undefined, pacing?: IModbusPacingConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
88
+ /**
89
+ * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
90
+ * if one was given, otherwise the host application's default (`energyApp.useModbus()`). The
91
+ * constructor guarantees at least one of the two is present.
92
+ */
93
+ private useModbus;
83
94
  /**
84
95
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
85
96
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -152,6 +163,15 @@ export declare class SunspecModbusClient {
152
163
  * if every unit succeeded.
153
164
  */
154
165
  private attemptConnection;
166
+ /**
167
+ * Build the ordered host list handed to the transport's `host` option for a single connect.
168
+ * The attempt's primary target leads, followed by every OTHER known host (the other of
169
+ * primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
170
+ * DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
171
+ * only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
172
+ * no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
173
+ */
174
+ private buildConnectHosts;
155
175
  /**
156
176
  * Open a unit, retrying the connect on a transient failure per the resilience config
157
177
  * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
@@ -167,6 +187,14 @@ export declare class SunspecModbusClient {
167
187
  * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
168
188
  * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
169
189
  * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
190
+ *
191
+ * When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
192
+ * full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
193
+ * known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
194
+ * waiting for the client's own sequential primary→secondary retry. The transport walks the list
195
+ * in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
196
+ * the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
197
+ * false to keep speculative RS485 scans a fast-fail single-host probe.
170
198
  */
171
199
  private _openUnitOnce;
172
200
  /**
@@ -46,15 +46,19 @@ const registryKey = (host, port) => `${host}:${port}`;
46
46
  * Get (or create) the singleton SunspecModbusClient for this network device.
47
47
  * Increments the refcount; pair with `releaseSunspecClient` on teardown.
48
48
  *
49
- * NOTE: `pacing` and `resilience` are only applied when the client is FIRST created for a given
50
- * host:port. Because the client is cached and refcounted, a later caller passing different config
51
- * receives the already-created instance and its config is ignored.
49
+ * NOTE: `pacing`, `resilience` and `modbusFactory` are only applied when the client is FIRST
50
+ * created for a given host:port. Because the client is cached and refcounted, a later caller
51
+ * passing different config receives the already-created instance and its config is ignored.
52
+ *
53
+ * `modbusFactory` lets a caller supply their own Modbus backend (the factory whose `connect()`
54
+ * opens a per-unit connection) instead of the one from `energyApp.useModbus()` — e.g. a mock for
55
+ * tests, or an alternative transport. When provided, `energyApp` may be passed as `undefined`.
52
56
  */
53
- export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience) {
57
+ export function getOrCreateSunspecClient(energyApp, host, port = 502, pacing, resilience, modbusFactory) {
54
58
  const key = registryKey(host, port);
55
59
  let entry = CLIENT_REGISTRY.get(key);
56
60
  if (!entry) {
57
- entry = { client: new SunspecModbusClient(energyApp, pacing, resilience), refcount: 0 };
61
+ entry = { client: new SunspecModbusClient(energyApp, pacing, resilience, modbusFactory), refcount: 0 };
58
62
  CLIENT_REGISTRY.set(key, entry);
59
63
  }
60
64
  entry.refcount++;
@@ -120,6 +124,7 @@ export async function retryAsync(fn, opts) {
120
124
  export class SunspecModbusClient {
121
125
  energyApp;
122
126
  pacing;
127
+ modbusFactory;
123
128
  // Per-unit Modbus instance/reader/discovered-models maps. One client = one network device,
124
129
  // many unit IDs share that client (each unit ID is one EnergyAppModbusInstance underneath).
125
130
  modbusInstances = new Map();
@@ -163,20 +168,47 @@ export class SunspecModbusClient {
163
168
  // the transport still reports connected but that has gone quiet past staleSocketMs is presumed
164
169
  // dead. Absent entry = no successful op yet (never treated as stale — give it a chance).
165
170
  lastOkAtByUnit = new Map();
166
- constructor(energyApp,
171
+ constructor(
172
+ // The host application. Only used to obtain the default Modbus backend via
173
+ // `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
174
+ energyApp,
167
175
  // Opt-in pacing (default off). Passed straight through to `useModbus().connect()`, which
168
176
  // serializes frames (`noParallelRequests`) and spaces them (`waitBetweenMessagesMs`) on the
169
177
  // connection. An empty object leaves both undefined so the SDK applies its own defaults.
170
178
  pacing = {},
171
179
  // Per-operation timeouts + half-open detection. Merged with DEFAULT_MODBUS_RESILIENCE_CONFIG
172
180
  // so omitted fields keep their defaults.
173
- resilience = {}) {
181
+ resilience = {},
182
+ // Optional custom Modbus backend. When provided, its `connect()` is used to open every
183
+ // per-unit connection instead of `energyApp.useModbus()` — letting callers plug in their own
184
+ // Modbus implementation (a mock for tests, or an alternative transport). All the resilience
185
+ // machinery (per-unit connect/reconnect, TLS, pacing, timeouts) is driven through this
186
+ // factory, which is why an already-connected instance would not do: the client re-opens
187
+ // connections on its own schedule and needs a factory to call.
188
+ modbusFactory) {
174
189
  this.energyApp = energyApp;
175
190
  this.pacing = pacing;
191
+ this.modbusFactory = modbusFactory;
192
+ if (!energyApp && !modbusFactory) {
193
+ throw new Error("SunspecModbusClient requires either an EnergyApp or a modbusFactory");
194
+ }
176
195
  this.connectionHealth = new EnergyAppModbusConnectionHealth();
177
196
  this.modbusDataTypeConverter = new EnergyAppModbusDataTypeConverter();
178
197
  this.resilience = { ...DEFAULT_MODBUS_RESILIENCE_CONFIG, ...resilience };
179
198
  }
199
+ /**
200
+ * The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
201
+ * if one was given, otherwise the host application's default (`energyApp.useModbus()`). The
202
+ * constructor guarantees at least one of the two is present.
203
+ */
204
+ useModbus() {
205
+ if (this.modbusFactory)
206
+ return this.modbusFactory;
207
+ if (!this.energyApp) {
208
+ throw new Error("SunspecModbusClient has no Modbus backend: neither energyApp nor modbusFactory is set");
209
+ }
210
+ return this.energyApp.useModbus();
211
+ }
180
212
  /**
181
213
  * Connect to a Modbus device unit. Multiple unit IDs on the same network device share this
182
214
  * client; calling connect() with different unit IDs adds each as a separately-managed unit.
@@ -224,6 +256,10 @@ export class SunspecModbusClient {
224
256
  await this._openUnit(host, port, unitId, {
225
257
  connectRetries: 0,
226
258
  connectTimeoutMs: opts.timeoutMs ?? this.resilience.connectTimeoutMs,
259
+ // Fast-fail scan: a mostly-dead RS485 range must cost ~one timeout per unit, so do
260
+ // NOT let the transport also walk a fallback host (which would double the per-unit
261
+ // cost). Warm connects/reconnects still get the in-band fallback.
262
+ useFallbackHosts: false,
227
263
  });
228
264
  console.log(`Probed Sunspec unit ${unitId} at ${host}:${port} — open (opens=${this.openCount}, closes=${this.closeCount}, openUnits=${this.modbusInstances.size})`);
229
265
  });
@@ -395,6 +431,25 @@ export class SunspecModbusClient {
395
431
  return false;
396
432
  }
397
433
  }
434
+ /**
435
+ * Build the ordered host list handed to the transport's `host` option for a single connect.
436
+ * The attempt's primary target leads, followed by every OTHER known host (the other of
437
+ * primaryHost/secondaryHost) as an in-band fallback the transport walks in order — so a stale
438
+ * DNS name or a DHCP-changed IP on the first host is tolerated within one connect() instead of
439
+ * only via the client's sequential primary→secondary retry. Deduped; returns a bare string when
440
+ * no distinct fallback exists, leaving single-host devices (and their tests) unaffected.
441
+ */
442
+ buildConnectHosts(primaryTarget) {
443
+ const hosts = [primaryTarget];
444
+ const params = this.connectionParams;
445
+ if (params) {
446
+ for (const h of [params.primaryHost, params.secondaryHost]) {
447
+ if (h && !hosts.includes(h))
448
+ hosts.push(h);
449
+ }
450
+ }
451
+ return hosts.length === 1 ? hosts[0] : hosts;
452
+ }
398
453
  /**
399
454
  * Open a unit, retrying the connect on a transient failure per the resilience config
400
455
  * ({@link IModbusResilienceConfig.connectRetries}). Each attempt is a full {@link _openUnitOnce}
@@ -408,7 +463,11 @@ export class SunspecModbusClient {
408
463
  async _openUnit(host, port, unitId, override) {
409
464
  const connectTimeoutMs = override?.connectTimeoutMs ?? this.resilience.connectTimeoutMs;
410
465
  const attempts = (override?.connectRetries ?? this.resilience.connectRetries) + 1;
411
- await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs), {
466
+ // Default ON: a normal connect/reconnect hands the transport BOTH known hosts so a single
467
+ // attempt tolerates DNS/DHCP drift on the first one. probeUnit opts out to stay a fast-fail
468
+ // single-host scan (see probeUnit / _openUnitOnce).
469
+ const useFallbackHosts = override?.useFallbackHosts ?? true;
470
+ await retryAsync(() => this._openUnitOnce(host, port, unitId, connectTimeoutMs, useFallbackHosts), {
412
471
  attempts,
413
472
  delayMs: this.resilience.connectRetryDelayMs,
414
473
  onRetry: (error, attempt) => console.warn(`SunspecModbusClient: connect to ${host}:${port} unit ${unitId} failed ` +
@@ -420,15 +479,28 @@ export class SunspecModbusClient {
420
479
  * Open a new Modbus instance for one unit ID and wire up its fault-tolerant reader. Bounds the
421
480
  * connect at `connectTimeoutMs`. On any failure, the just-opened instance (if any) is closed so
422
481
  * we never leak. Caller must hold the connection lock and ensure the unit is not already open.
423
- */
424
- async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs) {
482
+ *
483
+ * When `useFallbackHosts` is true (the connect/reconnect default), the transport is handed the
484
+ * full host list from {@link buildConnectHosts} — the attempt's primary target plus the other
485
+ * known host — so one connect() tolerates DNS/DHCP drift on the first host in-band, rather than
486
+ * waiting for the client's own sequential primary→secondary retry. The transport walks the list
487
+ * in order, each host bounded by `timeout` (connectTimeoutMs); we scale our own outer budget by
488
+ * the host count so a legitimate multi-host walk isn't aborted mid-fallback. probeUnit passes
489
+ * false to keep speculative RS485 scans a fast-fail single-host probe.
490
+ */
491
+ async _openUnitOnce(host, port, unitId, connectTimeoutMs = this.resilience.connectTimeoutMs, useFallbackHosts = true) {
425
492
  let candidate = null;
493
+ const hosts = useFallbackHosts ? this.buildConnectHosts(host) : host;
494
+ const hostCount = Array.isArray(hosts) ? hosts.length : 1;
495
+ // Each host in the list gets its own `timeout`; bound the whole walk at count × budget so we
496
+ // don't kill a genuine fallback to the second host with the single-host budget.
497
+ const overallBudgetMs = connectTimeoutMs * hostCount;
426
498
  try {
427
499
  // Enforce the connect budget ourselves in addition to forwarding it as the transport's
428
500
  // `timeout`: the transport applies it to the TCP handshake, but a sleeping/half-open peer
429
501
  // can still leave the returned promise pending — bound it independently.
430
- candidate = await this.withTimeout('connect', unitId, connectTimeoutMs, () => this.energyApp.useModbus().connect({
431
- host,
502
+ candidate = await this.withTimeout('connect', unitId, overallBudgetMs, () => this.useModbus().connect({
503
+ host: hosts,
432
504
  port,
433
505
  unitId,
434
506
  timeout: connectTimeoutMs,
package/dist/version.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export declare const SDK_VERSION = "0.0.102";
8
+ export declare const SDK_VERSION = "0.0.104";
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/dist/version.js CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Current version of the enyo Energy App SDK.
7
7
  */
8
- export const SDK_VERSION = '0.0.102';
8
+ export const SDK_VERSION = '0.0.104';
9
9
  /**
10
10
  * Gets the current SDK version.
11
11
  * @returns The semantic version string of the SDK
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enyo-energy/sunspec-sdk",
3
- "version": "0.0.102",
3
+ "version": "0.0.104",
4
4
  "description": "enyo Energy Sunspec SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -40,8 +40,8 @@
40
40
  "vitest": "^2.1.9"
41
41
  },
42
42
  "dependencies": {
43
- "@enyo-energy/appliance-calibration": "0.0.2",
44
- "@enyo-energy/energy-app-sdk": "^0.0.177"
43
+ "@enyo-energy/appliance-calibration": "0.0.3",
44
+ "@enyo-energy/energy-app-sdk": "^0.0.188"
45
45
  },
46
46
  "volta": {
47
47
  "node": "22.17.0"