@enyo-energy/sunspec-sdk 0.0.101 → 0.0.103

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, SunspecPvPowerOrigin, type SunspecInverterReading, type SunspecBatteryReading, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode } from "./sunspec-interfaces.js";
1
+ import { type IRetryConfig, type SunspecBatteryBaseData, SunspecBatteryCapability, type SunspecBatteryControls, type SunspecBatteryData, type SunspecBatteryFeatureMode, type SunspecInverterData, SunspecInverterCapability, SunspecPvPowerSource, SunspecPvPowerOrigin, type SunspecInverterReading, type SunspecBatteryReading, SunspecMeterCapability, type SunspecMPPTData, SunspecStorageMode, type SunspecCustomDeviceConfig } from "./sunspec-interfaces.js";
2
2
  import { ApplianceManager, EnergyApp } from "@enyo-energy/energy-app-sdk";
3
3
  import { type EnyoAppliance, type EnyoApplianceErrorCode, EnyoApplianceName } from "@enyo-energy/energy-app-sdk/dist/types/enyo-appliance.js";
4
4
  import { EnyoNetworkDevice } from "@enyo-energy/energy-app-sdk/dist/types/enyo-network-device.js";
@@ -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
@@ -68,6 +81,20 @@ export declare abstract class BaseSunspecDevice {
68
81
  * Ensure the Sunspec client is connected and models are discovered
69
82
  */
70
83
  protected ensureConnected(): Promise<void>;
84
+ /**
85
+ * Populate the per-unit model directory after the socket opens. Default: run SunSpec model
86
+ * discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
87
+ * directory (see {@link SunspecCustomDevice}) override this to a no-op.
88
+ */
89
+ protected discoverAfterConnect(): Promise<void>;
90
+ /**
91
+ * Validate that a just-completed reconnect actually restored a usable device. Default: re-run
92
+ * SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
93
+ * back with no usable models means the gateway accepted the connection before it was ready to
94
+ * answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
95
+ * running. Discovery-less devices override this to just confirm the socket is open.
96
+ */
97
+ protected revalidateAfterReconnect(): Promise<boolean>;
71
98
  /**
72
99
  * Attempt a reconnection if the tiered retry schedule allows it.
73
100
  * Called from readData() when the device is disconnected.
@@ -138,9 +165,21 @@ export declare abstract class BaseSunspecDevice {
138
165
  * readData() and skip tryReconnect() entirely, so without this they would
139
166
  * stay Offline forever despite reading data fine.
140
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
+ *
141
178
  * Call this on the success path of readData() (after the
142
- * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). It is
143
- * 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).
144
183
  */
145
184
  protected reassertConnectedIfRecovered(): Promise<void>;
146
185
  protected sendCommandAcknowledge(messageId: string, acknowledgeMessage: EnyoDataBusMessageEnum | string, answer: EnyoCommandAcknowledgeAnswerEnum, rejectionReason?: string): void;
@@ -735,4 +774,70 @@ export declare class SunspecMeter extends BaseSunspecDevice {
735
774
  */
736
775
  readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
737
776
  }
777
+ /**
778
+ * A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
779
+ * SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
780
+ * {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
781
+ * per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
782
+ * instead of a discovered SunSpec model directory.
783
+ *
784
+ * It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
785
+ * the role selects the appliance type created on connect and which EnyoDataBus values message
786
+ * {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
787
+ * that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
788
+ *
789
+ * Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
790
+ * validated by socket liveness rather than a SunSpec scan.
791
+ */
792
+ export declare class SunspecCustomDevice extends BaseSunspecDevice {
793
+ private readonly config;
794
+ /** Read plan derived once from the static register map (see {@link planBlocks}). */
795
+ private plannedBlocks?;
796
+ constructor(energyApp: EnergyApp, name: EnyoApplianceName[], networkDevice: EnyoNetworkDevice, sunspecClient: SunspecModbusClient, applianceManager: ApplianceManager, config: SunspecCustomDeviceConfig, unitId?: number, port?: number, baseAddress?: number, retryConfig?: IRetryConfig, appliance?: EnyoAppliance, useTls?: boolean);
797
+ /**
798
+ * No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
799
+ * the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
800
+ * socket without a SunS scan.
801
+ */
802
+ protected discoverAfterConnect(): Promise<void>;
803
+ /**
804
+ * A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
805
+ * Without this override the base default would run SunSpec discovery, find nothing, and treat every
806
+ * reconnect as a permanent failure.
807
+ */
808
+ protected revalidateAfterReconnect(): Promise<boolean>;
809
+ /**
810
+ * Connect the underlying socket (no discovery) and create/update the appliance for the configured
811
+ * role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
812
+ * SunSpec Common block to read it from.
813
+ */
814
+ connect(): Promise<void>;
815
+ disconnect(): Promise<void>;
816
+ readData(clockId: string, resolution: EnyoDataBusMessageResolution): Promise<EnyoDataBusMessage[]>;
817
+ /**
818
+ * Write a value to a pre-configured writable register. Delegates to the client's resilient
819
+ * {@link SunspecModbusClient.writeRegisterValue}.
820
+ */
821
+ writeCustomRegister(name: string, value: number | number[]): Promise<boolean>;
822
+ /**
823
+ * Read every configured register as a small number of block reads and extract each register from
824
+ * its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
825
+ * scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
826
+ * populate a numeric databus field) are skipped with a warning.
827
+ */
828
+ private readConfiguredRegisters;
829
+ /** Lazily compute and cache the block read plan; the register map is static per device. */
830
+ private getPlannedBlocks;
831
+ /**
832
+ * Group the configured registers (separately per function code) sorted by address, coalescing them
833
+ * — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
834
+ * starts whenever adding the next register would exceed that span. Each block records its members'
835
+ * offsets so a single read can be sliced into all of them.
836
+ */
837
+ private planBlocks;
838
+ private buildRoleMessage;
839
+ private buildMeterMessage;
840
+ private buildInverterMessage;
841
+ private buildBatteryMessage;
842
+ }
738
843
  export {};
@@ -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
@@ -149,8 +162,32 @@ export class BaseSunspecDevice {
149
162
  await this.sunspecClient.connect(this.networkDevice.hostname, // primary
150
163
  this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
151
164
  this.useTls);
152
- await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
165
+ await this.discoverAfterConnect();
166
+ }
167
+ }
168
+ /**
169
+ * Populate the per-unit model directory after the socket opens. Default: run SunSpec model
170
+ * discovery. Devices that read a hand-defined static register map instead of a discovered SunSpec
171
+ * directory (see {@link SunspecCustomDevice}) override this to a no-op.
172
+ */
173
+ async discoverAfterConnect() {
174
+ await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
175
+ }
176
+ /**
177
+ * Validate that a just-completed reconnect actually restored a usable device. Default: re-run
178
+ * SunSpec discovery and check it against {@link getRequiredModelIds} (a socket that opens but comes
179
+ * back with no usable models means the gateway accepted the connection before it was ready to
180
+ * answer the scan). Returns false to treat the reconnect as failed so the backoff schedule keeps
181
+ * running. Discovery-less devices override this to just confirm the socket is open.
182
+ */
183
+ async revalidateAfterReconnect() {
184
+ const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
185
+ const usable = this.isDiscoveryUsable(models);
186
+ if (!usable) {
187
+ console.warn(`${this.constructor.name} ${this.applianceId}: reconnect discovery returned no usable models ` +
188
+ `(found [${[...models.keys()].join(', ')}])`);
153
189
  }
190
+ return usable;
154
191
  }
155
192
  /**
156
193
  * Attempt a reconnection if the tiered retry schedule allows it.
@@ -186,14 +223,12 @@ export class BaseSunspecDevice {
186
223
  // it's unusable, treat this as a failed reconnect: invalidate the socket so the
187
224
  // next poll re-enters tryReconnect(), keep the backoff schedule running, and do
188
225
  // NOT reset().
189
- const models = await this.sunspecClient.discoverModels(this.unitId, this.baseAddress);
190
- if (!this.isDiscoveryUsable(models)) {
191
- this.sunspecClient.invalidateUnit(this.unitId, `reconnect discovery found no usable models for unit ${this.unitId}`);
226
+ if (!(await this.revalidateAfterReconnect())) {
227
+ this.sunspecClient.invalidateUnit(this.unitId, `reconnect revalidation failed for unit ${this.unitId}`);
192
228
  this.consecutiveReconnectFailures += 1;
193
229
  await this.onConnectionFailure(this.consecutiveReconnectFailures);
194
230
  console.warn(`${this.constructor.name} ${this.applianceId}: Reconnect attempt #${attempt} ` +
195
- `opened the socket but discovery returned no usable models ` +
196
- `(found [${[...models.keys()].join(', ')}]) — retrying with backoff`);
231
+ `opened the socket but revalidation failed — retrying with backoff`);
197
232
  return false;
198
233
  }
199
234
  this.retryManager.reset();
@@ -308,6 +343,7 @@ export class BaseSunspecDevice {
308
343
  try {
309
344
  await this.applianceManager.updateApplianceState(this.applianceId, EnyoApplianceConnectionType.Connector, EnyoApplianceStateEnum.Offline);
310
345
  this.appliedOffline = true;
346
+ this.reconciledExternalOffline = false;
311
347
  }
312
348
  catch (error) {
313
349
  console.error(`${this.constructor.name} ${this.applianceId}: Failed to mark appliance offline: ${error}`);
@@ -323,17 +359,45 @@ export class BaseSunspecDevice {
323
359
  * readData() and skip tryReconnect() entirely, so without this they would
324
360
  * stay Offline forever despite reading data fine.
325
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
+ *
326
372
  * Call this on the success path of readData() (after the
327
- * markOfflineIfUnhealthy() guard has confirmed the unit is healthy). It is
328
- * 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).
329
377
  */
330
378
  async reassertConnectedIfRecovered() {
331
- if (!this.appliedOffline || !this.applianceId) {
379
+ if (!this.applianceId) {
332
380
  return;
333
381
  }
334
382
  if (!this.sunspecClient.isHealthy(this.unitId)) {
335
383
  return;
336
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
+ }
337
401
  console.log(`${this.constructor.name} ${this.applianceId}: connection recovered via shared socket — re-asserting Connected`);
338
402
  try {
339
403
  await this.applianceManager.updateApplianceState(this.applianceId, EnyoApplianceConnectionType.Connector, EnyoApplianceStateEnum.Connected);
@@ -343,6 +407,7 @@ export class BaseSunspecDevice {
343
407
  return;
344
408
  }
345
409
  this.appliedOffline = false;
410
+ this.reconciledExternalOffline = true;
346
411
  this.retryManager.reset();
347
412
  this.consecutiveReconnectFailures = 0;
348
413
  await this.onConnectionRestored();
@@ -2231,3 +2296,345 @@ export class SunspecMeter extends BaseSunspecDevice {
2231
2296
  return messages;
2232
2297
  }
2233
2298
  }
2299
+ /** Appliance type created for each custom-device role (battery emulates a Storage appliance). */
2300
+ const CUSTOM_ROLE_APPLIANCE_TYPE = {
2301
+ meter: EnyoApplianceTypeEnum.Meter,
2302
+ inverter: EnyoApplianceTypeEnum.Inverter,
2303
+ battery: EnyoApplianceTypeEnum.Storage,
2304
+ };
2305
+ /** Natural register width per data type, used when a register omits an explicit `quantity`. */
2306
+ const CUSTOM_REGISTER_DEFAULT_QUANTITY = {
2307
+ uint16: 1,
2308
+ int16: 1,
2309
+ acc16: 1,
2310
+ uint32: 2,
2311
+ int32: 2,
2312
+ acc32: 2,
2313
+ float32: 2,
2314
+ string: 1,
2315
+ };
2316
+ /** Numeric databus fields a `meter`-role custom device may populate. */
2317
+ const CUSTOM_METER_FIELDS = [
2318
+ 'gridPowerW', 'gridPowerPhase1W', 'gridPowerPhase2W', 'gridPowerPhase3W',
2319
+ 'gridFeedInWh', 'gridConsumptionWh', 'selfConsumptionW', 'selfConsumptionWh',
2320
+ ];
2321
+ /** Numeric databus fields an `inverter`-role custom device may populate. */
2322
+ const CUSTOM_INVERTER_FIELDS = [
2323
+ 'pvPowerW', 'voltageL1', 'voltageL2', 'voltageL3',
2324
+ 'currentL1', 'currentL2', 'currentL3', 'dcPowerW',
2325
+ 'activePowerLimitationW', 'meterValueWh',
2326
+ ];
2327
+ /** Numeric databus fields a `battery`-role custom device may populate. */
2328
+ const CUSTOM_BATTERY_FIELDS = [
2329
+ 'batterySoC', 'batteryPowerW', 'dcStringInputPowerW',
2330
+ ];
2331
+ /** Default {@link SunspecCustomDeviceConfig.blockSize}: the Modbus FC03/FC04 per-read limit. */
2332
+ const CUSTOM_DEFAULT_BLOCK_SIZE = 125;
2333
+ /**
2334
+ * A generic, pre-configured Modbus device that plugs into the exact same resilient lifecycle as the
2335
+ * SunSpec devices — the per-device {@link ConnectionRetryManager}, {@link tryReconnect} tiered backoff,
2336
+ * {@link markOffline}/{@link reassertConnectedIfRecovered} shared-socket healing, and the client's
2337
+ * per-transaction timeout/poison/staleness guards — but reads a **hand-defined static register map**
2338
+ * instead of a discovered SunSpec model directory.
2339
+ *
2340
+ * It emulates a configurable {@link SunspecCustomDeviceConfig.role} (`meter` | `inverter` | `battery`):
2341
+ * the role selects the appliance type created on connect and which EnyoDataBus values message
2342
+ * {@link readData} publishes, and each {@link SunspecCustomRegister} maps onto one numeric field of
2343
+ * that message. Supports FC03 holding registers (default), FC04 input registers, and writes.
2344
+ *
2345
+ * Discovery is fully bypassed: {@link connect} opens the socket only, and the reconnect path is
2346
+ * validated by socket liveness rather than a SunSpec scan.
2347
+ */
2348
+ export class SunspecCustomDevice extends BaseSunspecDevice {
2349
+ config;
2350
+ /** Read plan derived once from the static register map (see {@link planBlocks}). */
2351
+ plannedBlocks;
2352
+ constructor(energyApp, name, networkDevice, sunspecClient, applianceManager, config, unitId = 1, port = 502, baseAddress = 40000, retryConfig, appliance, useTls) {
2353
+ super(energyApp, name, networkDevice, sunspecClient, applianceManager, unitId, port, baseAddress, retryConfig, appliance, useTls);
2354
+ this.config = config;
2355
+ }
2356
+ /**
2357
+ * No SunSpec model directory to build — this device reads pre-defined static addresses. Overriding
2358
+ * the base discovery hook to a no-op is what lets {@link ensureConnected}/{@link connect} open the
2359
+ * socket without a SunS scan.
2360
+ */
2361
+ async discoverAfterConnect() {
2362
+ // Intentionally empty: plain-Modbus device, no SunSpec discovery.
2363
+ }
2364
+ /**
2365
+ * A reconnect is usable as soon as the socket is open again — there is no model map to revalidate.
2366
+ * Without this override the base default would run SunSpec discovery, find nothing, and treat every
2367
+ * reconnect as a permanent failure.
2368
+ */
2369
+ async revalidateAfterReconnect() {
2370
+ return this.sunspecClient.isConnected(this.unitId);
2371
+ }
2372
+ /**
2373
+ * Connect the underlying socket (no discovery) and create/update the appliance for the configured
2374
+ * role. Identity metadata comes from {@link SunspecCustomDeviceConfig.identity} since there is no
2375
+ * SunSpec Common block to read it from.
2376
+ */
2377
+ async connect() {
2378
+ if (!this.sunspecClient.isConnected(this.unitId)) {
2379
+ await this.sunspecClient.connect(this.networkDevice.hostname, // primary
2380
+ this.port, this.unitId, this.networkDevice.ipAddress, // secondary fallback
2381
+ this.useTls);
2382
+ // No discoverModels(): this device reads a pre-defined static register map.
2383
+ }
2384
+ const applianceType = CUSTOM_ROLE_APPLIANCE_TYPE[this.config.role];
2385
+ if (!this.applianceId) {
2386
+ try {
2387
+ this.applianceId = await this.applianceManager.createOrUpdateAppliance({
2388
+ name: this.name,
2389
+ type: applianceType,
2390
+ networkDevices: [this.networkDevice],
2391
+ metadata: {
2392
+ connectionType: EnyoApplianceConnectionType.Connector,
2393
+ state: EnyoApplianceStateEnum.Connected,
2394
+ serialNumber: this.config.identity?.serialNumber,
2395
+ modelName: this.config.identity?.modelName,
2396
+ vendorName: this.config.identity?.vendorName,
2397
+ modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
2398
+ },
2399
+ });
2400
+ console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
2401
+ }
2402
+ catch (error) {
2403
+ console.error(`Failed to create custom ${this.config.role} appliance: ${error}`);
2404
+ }
2405
+ }
2406
+ else {
2407
+ try {
2408
+ const existingAppliance = await this.applianceManager.findApplianceById(this.applianceId);
2409
+ await this.applianceManager.updateAppliance(this.applianceId, {
2410
+ metadata: {
2411
+ ...existingAppliance?.metadata,
2412
+ connectionType: EnyoApplianceConnectionType.Connector,
2413
+ state: EnyoApplianceStateEnum.Connected,
2414
+ modbus: { unitId: this.unitId, baseAddress: this.baseAddress },
2415
+ }
2416
+ });
2417
+ console.log(`Sunspec custom ${this.config.role} connected: ${this.networkDevice.hostname} unit ${this.unitId} (${this.applianceId})`);
2418
+ }
2419
+ catch (error) {
2420
+ console.error(`Failed to update custom ${this.config.role} appliance: ${error}`);
2421
+ }
2422
+ }
2423
+ }
2424
+ async disconnect() {
2425
+ if (this.applianceId) {
2426
+ try {
2427
+ await this.applianceManager.updateApplianceState(this.applianceId, EnyoApplianceConnectionType.Connector, EnyoApplianceStateEnum.Offline);
2428
+ }
2429
+ catch (error) {
2430
+ console.error(`Failed to mark custom ${this.config.role} offline on disconnect: ${error}`);
2431
+ }
2432
+ }
2433
+ // Close just this device's unit; siblings on the same network device stay open.
2434
+ await this.sunspecClient.disconnectUnit(this.unitId);
2435
+ }
2436
+ async readData(clockId, resolution) {
2437
+ if (!this.isConnected()) {
2438
+ await this.tryReconnect();
2439
+ if (!this.isConnected())
2440
+ return [];
2441
+ }
2442
+ const messages = [];
2443
+ const timestamp = new Date();
2444
+ try {
2445
+ const values = await this.readConfiguredRegisters();
2446
+ // readRegisterValue throws on a failed read (unlike the SunSpec model readers), so a dead
2447
+ // socket lands in catch below. This also covers the health-counter path when the transport
2448
+ // records failures without throwing.
2449
+ if (await this.markOfflineIfUnhealthy()) {
2450
+ return messages;
2451
+ }
2452
+ // Healthy read: if a sibling on the same shared socket reconnected us, flip our appliance
2453
+ // state back to Connected. No-op unless this device is still marked offline.
2454
+ await this.reassertConnectedIfRecovered();
2455
+ messages.push(this.buildRoleMessage(values, clockId, resolution, timestamp));
2456
+ this.lastUpdateTime = timestamp.getTime();
2457
+ }
2458
+ catch (error) {
2459
+ console.error(`Error updating custom ${this.config.role} data: ${error}`);
2460
+ await this.markOffline();
2461
+ }
2462
+ return messages;
2463
+ }
2464
+ /**
2465
+ * Write a value to a pre-configured writable register. Delegates to the client's resilient
2466
+ * {@link SunspecModbusClient.writeRegisterValue}.
2467
+ */
2468
+ async writeCustomRegister(name, value) {
2469
+ const reg = this.config.writeRegisters?.find(r => r.name === name);
2470
+ if (!reg) {
2471
+ throw new Error(`No writable register named '${name}' configured for custom ${this.config.role}`);
2472
+ }
2473
+ return this.sunspecClient.writeRegisterValue(this.unitId, reg.address, value, reg.dataType);
2474
+ }
2475
+ /**
2476
+ * Read every configured register as a small number of block reads and extract each register from
2477
+ * its block buffer by offset (mirroring the SunSpec model-block read). Applies the fixed decimal
2478
+ * scaling and returns a field → value map. Non-numeric reads (e.g. a `string` dataType that can't
2479
+ * populate a numeric databus field) are skipped with a warning.
2480
+ */
2481
+ async readConfiguredRegisters() {
2482
+ const values = new Map();
2483
+ for (const block of this.getPlannedBlocks()) {
2484
+ const buffer = await this.sunspecClient.readRegisterBlock(this.unitId, block.startAddress, block.length, block.useInputRegisters);
2485
+ for (const member of block.members) {
2486
+ const raw = this.sunspecClient.decodeBlockValue(buffer, member.offset, member.dataType, member.quantity);
2487
+ if (typeof raw !== 'number') {
2488
+ console.warn(`Custom ${this.config.role}: register '${member.field}' returned a non-numeric value; skipping`);
2489
+ continue;
2490
+ }
2491
+ values.set(member.field, raw * Math.pow(10, member.scaleFactor));
2492
+ }
2493
+ }
2494
+ return values;
2495
+ }
2496
+ /** Lazily compute and cache the block read plan; the register map is static per device. */
2497
+ getPlannedBlocks() {
2498
+ if (!this.plannedBlocks) {
2499
+ this.plannedBlocks = this.planBlocks();
2500
+ }
2501
+ return this.plannedBlocks;
2502
+ }
2503
+ /**
2504
+ * Group the configured registers (separately per function code) sorted by address, coalescing them
2505
+ * — across gaps — into blocks no wider than {@link SunspecCustomDeviceConfig.blockSize}. A new block
2506
+ * starts whenever adding the next register would exceed that span. Each block records its members'
2507
+ * offsets so a single read can be sliced into all of them.
2508
+ */
2509
+ planBlocks() {
2510
+ const blockSize = Math.max(1, this.config.blockSize ?? CUSTOM_DEFAULT_BLOCK_SIZE);
2511
+ const blocks = [];
2512
+ // Group by function code so FC03 and FC04 registers never share a block.
2513
+ const groups = new Map();
2514
+ for (const reg of this.config.registers) {
2515
+ const useInputRegisters = reg.functionCode === 4;
2516
+ const list = groups.get(useInputRegisters);
2517
+ if (list) {
2518
+ list.push(reg);
2519
+ }
2520
+ else {
2521
+ groups.set(useInputRegisters, [reg]);
2522
+ }
2523
+ }
2524
+ for (const [useInputRegisters, regs] of groups) {
2525
+ const spans = regs
2526
+ .map(reg => {
2527
+ const quantity = reg.quantity ?? CUSTOM_REGISTER_DEFAULT_QUANTITY[reg.dataType];
2528
+ return { reg, quantity, start: reg.address, end: reg.address + quantity };
2529
+ })
2530
+ .sort((a, b) => a.start - b.start);
2531
+ let current;
2532
+ let currentEnd = 0;
2533
+ for (const span of spans) {
2534
+ const member = (offset) => ({
2535
+ field: span.reg.field,
2536
+ dataType: span.reg.dataType,
2537
+ quantity: span.quantity,
2538
+ offset,
2539
+ scaleFactor: span.reg.scaleFactor ?? 0,
2540
+ });
2541
+ // Extend the current block only if the whole span (start .. farthest end) still fits
2542
+ // within blockSize. The first register always opens a block (a lone register wider than
2543
+ // blockSize is still read — readRegisterBlock chunks it).
2544
+ const mergedEnd = current ? Math.max(currentEnd, span.end) : span.end;
2545
+ if (current && mergedEnd - current.startAddress <= blockSize) {
2546
+ current.members.push(member(span.start - current.startAddress));
2547
+ currentEnd = mergedEnd;
2548
+ current.length = currentEnd - current.startAddress;
2549
+ }
2550
+ else {
2551
+ current = {
2552
+ useInputRegisters,
2553
+ startAddress: span.start,
2554
+ length: span.end - span.start,
2555
+ members: [member(0)],
2556
+ };
2557
+ currentEnd = span.end;
2558
+ blocks.push(current);
2559
+ }
2560
+ }
2561
+ }
2562
+ return blocks;
2563
+ }
2564
+ buildRoleMessage(values, clockId, resolution, timestamp) {
2565
+ switch (this.config.role) {
2566
+ case 'meter':
2567
+ return this.buildMeterMessage(values, clockId, resolution, timestamp);
2568
+ case 'inverter':
2569
+ return this.buildInverterMessage(values, clockId, resolution, timestamp);
2570
+ case 'battery':
2571
+ return this.buildBatteryMessage(values, clockId, resolution, timestamp);
2572
+ }
2573
+ }
2574
+ buildMeterMessage(values, clockId, resolution, timestamp) {
2575
+ const data = { gridFeedInWh: 0, gridConsumptionWh: 0 };
2576
+ for (const field of CUSTOM_METER_FIELDS) {
2577
+ const v = values.get(field);
2578
+ if (v !== undefined) {
2579
+ data[field] = v;
2580
+ }
2581
+ }
2582
+ return {
2583
+ id: randomUUID(),
2584
+ message: EnyoDataBusMessageEnum.MeterValuesUpdateV1,
2585
+ type: 'message',
2586
+ source: EnyoSourceEnum.Device,
2587
+ applianceId: this.applianceId,
2588
+ clockId,
2589
+ timestampIso: timestamp.toISOString(),
2590
+ resolution,
2591
+ data,
2592
+ };
2593
+ }
2594
+ buildInverterMessage(values, clockId, resolution, timestamp) {
2595
+ const data = { pvPowerW: 0, voltageL1: 0 };
2596
+ for (const field of CUSTOM_INVERTER_FIELDS) {
2597
+ const v = values.get(field);
2598
+ if (v !== undefined) {
2599
+ data[field] = v;
2600
+ }
2601
+ }
2602
+ if (this.config.defaultInverterState !== undefined) {
2603
+ data.state = this.config.defaultInverterState;
2604
+ }
2605
+ return {
2606
+ id: randomUUID(),
2607
+ message: EnyoDataBusMessageEnum.InverterValuesUpdateV1,
2608
+ type: 'message',
2609
+ source: EnyoSourceEnum.Device,
2610
+ applianceId: this.applianceId,
2611
+ clockId,
2612
+ timestampIso: timestamp.toISOString(),
2613
+ resolution,
2614
+ data,
2615
+ };
2616
+ }
2617
+ buildBatteryMessage(values, clockId, resolution, timestamp) {
2618
+ const data = { batterySoC: 0 };
2619
+ for (const field of CUSTOM_BATTERY_FIELDS) {
2620
+ const v = values.get(field);
2621
+ if (v !== undefined) {
2622
+ data[field] = v;
2623
+ }
2624
+ }
2625
+ if (this.config.defaultBatteryState !== undefined) {
2626
+ data.state = this.config.defaultBatteryState;
2627
+ }
2628
+ return {
2629
+ id: randomUUID(),
2630
+ message: EnyoDataBusMessageEnum.BatteryValuesUpdateV1,
2631
+ type: 'message',
2632
+ source: EnyoSourceEnum.Device,
2633
+ applianceId: this.applianceId,
2634
+ clockId,
2635
+ timestampIso: timestamp.toISOString(),
2636
+ resolution,
2637
+ data,
2638
+ };
2639
+ }
2640
+ }