@enyo-energy/sunspec-sdk 1.0.1 → 1.1.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.
- package/README.md +58 -0
- package/dist/cjs/index.cjs +7 -1
- package/dist/cjs/index.d.cts +1 -0
- package/dist/cjs/sunspec-modbus-client.cjs +148 -0
- package/dist/cjs/sunspec-modbus-client.d.cts +66 -1
- package/dist/cjs/version.cjs +1 -1
- package/dist/cjs/version.d.cts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +4 -0
- package/dist/sunspec-modbus-client.d.ts +66 -1
- package/dist/sunspec-modbus-client.js +148 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -10,6 +10,7 @@ SunSpec Modbus client for reading data from solar inverters, batteries, meters,
|
|
|
10
10
|
- [Storage Schedule Control](#storage-schedule-control)
|
|
11
11
|
- [Connection Failures and Logging](#connection-failures-and-logging)
|
|
12
12
|
- [Transport Options](#transport-options)
|
|
13
|
+
- [Vendor Function Codes and Connection-Scoped Permission](#vendor-function-codes-and-connection-scoped-permission)
|
|
13
14
|
- [Appliance Metadata the Registers Don't Carry](#appliance-metadata-the-registers-dont-carry)
|
|
14
15
|
- [How Addressing Works](#how-addressing-works)
|
|
15
16
|
- [Bulk Register Reading](#bulk-register-reading)
|
|
@@ -416,6 +417,63 @@ The config is applied when the client for a `host:port` is **first created**; a
|
|
|
416
417
|
|
|
417
418
|
---
|
|
418
419
|
|
|
420
|
+
## Vendor Function Codes and Connection-Scoped Permission
|
|
421
|
+
|
|
422
|
+
Some devices refuse control until a proprietary handshake has succeeded, over a function code
|
|
423
|
+
outside the standard eight. The canonical case is a Huawei SUN2000 with a LUNA2000 and no EMMA:
|
|
424
|
+
its control registers are ordinary holding registers, but every write comes back with exception
|
|
425
|
+
`0x80` — *"an operation is not allowed because of a permission authentication failure or
|
|
426
|
+
permission expiration"* — until an installer login has gone out over Huawei's function code
|
|
427
|
+
`0x41`.
|
|
428
|
+
|
|
429
|
+
Two methods cover that, both vendor-agnostic. Sub-commands, credential digests and keepalives
|
|
430
|
+
belong to the consumer; the SDK contributes the socket discipline.
|
|
431
|
+
|
|
432
|
+
### `sendRawPdu(unitId, functionCode, payload)`
|
|
433
|
+
|
|
434
|
+
Puts one PDU on the wire verbatim and returns the raw answer. It runs **inside the unit's
|
|
435
|
+
transaction chain**, exactly like `readRegisterBlock` — so a handshake can never cross frames with
|
|
436
|
+
a poll already in flight, which is what the single-frame SDongles behind these devices require.
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
const challenge = await client.sendRawPdu(unitId, 0x41, Buffer.from([0x24]));
|
|
440
|
+
const accepted = await client.sendRawPdu(unitId, 0x41, Buffer.concat([Buffer.from([0x25]), digest]));
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
A device exception arrives as **data**, on `response.exceptionCode`, not as a rejection — a
|
|
444
|
+
permission probe expects to be refused, and that has to be distinguishable from a dead link. Only
|
|
445
|
+
transport failures throw. Request payloads are never logged (they carry credential digests); the
|
|
446
|
+
host logs the function code and the payload length.
|
|
447
|
+
|
|
448
|
+
Requires an energy manager running **energy-app-sdk 1.9.0 or newer**. On an older host the call
|
|
449
|
+
throws with a message saying so, which is the signal to fall back to monitor-only behaviour rather
|
|
450
|
+
than to retry.
|
|
451
|
+
|
|
452
|
+
### `onUnitReconnected(unitId, listener)`
|
|
453
|
+
|
|
454
|
+
The permission a login buys belongs to the **socket**, not the device: when the connection is
|
|
455
|
+
replaced it is gone, silently, and the next write simply comes back `0x80`. This is the hook that
|
|
456
|
+
lets a consumer re-authenticate *before* the next command instead of after a failed one.
|
|
457
|
+
|
|
458
|
+
```ts
|
|
459
|
+
const stop = client.onUnitReconnected(unitId, () => {
|
|
460
|
+
authenticated = false;
|
|
461
|
+
void loginAgain();
|
|
462
|
+
});
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
Both ways a connection can be replaced are covered — the transport recycling the socket
|
|
466
|
+
underneath (dropped link, half-open socket, stale socket) and this client's own close-and-reopen
|
|
467
|
+
(a poisoned unit, `reconnectUnit()`, `reconnect()`) — and one loss produces **exactly one**
|
|
468
|
+
notification even when both fire. A deliberate `disconnectUnit()` is not a reconnect: connecting
|
|
469
|
+
again afterwards is a new session, and the listener stays quiet.
|
|
470
|
+
|
|
471
|
+
Listeners are registered against the unit, not the socket, so they survive reconnects and keep
|
|
472
|
+
firing. `getConnectionStats().opens` is not a substitute: it counts opens across the whole client,
|
|
473
|
+
not per unit.
|
|
474
|
+
|
|
475
|
+
---
|
|
476
|
+
|
|
419
477
|
## Appliance Metadata the Registers Don't Carry
|
|
420
478
|
|
|
421
479
|
Three appliance fields added in energy-app-sdk 1.6.0 have no SunSpec register behind them, so the SDK cannot derive them — it publishes what the consumer configures, and writes nothing at all when nothing is configured (spreading an explicit `undefined` would erase a value the host set through another path).
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.CalibrationTrigger = exports.CalibrationResultStore = exports.DEFAULT_BATTERY_CALIBRATOR_CONFIG = exports.BatteryCalibrator = exports.AbstractBatteryCalibrationDriver = exports.DEFAULT_AUTO_STOP_MS = exports.SnapshotService = exports.InMemoryCalibrationStorage = exports.AbstractCalibrationStorage = exports.EnyoStorageScheduleDirectionEnum = exports.EnyoStorageScheduleModeEnum = exports.SunspecBatteryScheduleHandler = exports.decodeFeatureResults = exports.SunspecBatteryFeatureCalibrator = exports.SunspecBatteryCalibrationDriver = exports.createSunspecCalibrationStorage = exports.SunspecCalibrationStorage = exports.getSdkVersion = exports.SDK_VERSION = exports.ConnectionRetryManager = void 0;
|
|
17
|
+
exports.CalibrationTrigger = exports.CalibrationResultStore = exports.DEFAULT_BATTERY_CALIBRATOR_CONFIG = exports.BatteryCalibrator = exports.AbstractBatteryCalibrationDriver = exports.DEFAULT_AUTO_STOP_MS = exports.SnapshotService = exports.InMemoryCalibrationStorage = exports.AbstractCalibrationStorage = exports.EnyoStorageScheduleDirectionEnum = exports.EnyoStorageScheduleModeEnum = exports.ModbusExceptionError = exports.MODBUS_MAX_PDU_PAYLOAD_BYTES = exports.SunspecBatteryScheduleHandler = exports.decodeFeatureResults = exports.SunspecBatteryFeatureCalibrator = exports.SunspecBatteryCalibrationDriver = exports.createSunspecCalibrationStorage = exports.SunspecCalibrationStorage = exports.getSdkVersion = exports.SDK_VERSION = exports.ConnectionRetryManager = void 0;
|
|
18
18
|
__exportStar(require("./sunspec-interfaces.cjs"), exports);
|
|
19
19
|
__exportStar(require("./sunspec-devices.cjs"), exports);
|
|
20
20
|
__exportStar(require("./sunspec-modbus-client.cjs"), exports);
|
|
@@ -34,6 +34,12 @@ Object.defineProperty(exports, "SunspecBatteryFeatureCalibrator", { enumerable:
|
|
|
34
34
|
Object.defineProperty(exports, "decodeFeatureResults", { enumerable: true, get: function () { return sunspec_battery_feature_calibrator_js_1.decodeFeatureResults; } });
|
|
35
35
|
var sunspec_battery_schedule_handler_js_1 = require("./sunspec-battery-schedule-handler.cjs");
|
|
36
36
|
Object.defineProperty(exports, "SunspecBatteryScheduleHandler", { enumerable: true, get: function () { return sunspec_battery_schedule_handler_js_1.SunspecBatteryScheduleHandler; } });
|
|
37
|
+
// Re-export the raw-PDU surface so a consumer of `sendRawPdu` / `ModbusExceptionError`
|
|
38
|
+
// needs no second import from energy-app-sdk internals. `ModbusExceptionError` is a
|
|
39
|
+
// class, not a type: an app branches on it with `instanceof`.
|
|
40
|
+
var energy_app_modbus_js_1 = require("@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js");
|
|
41
|
+
Object.defineProperty(exports, "MODBUS_MAX_PDU_PAYLOAD_BYTES", { enumerable: true, get: function () { return energy_app_modbus_js_1.MODBUS_MAX_PDU_PAYLOAD_BYTES; } });
|
|
42
|
+
Object.defineProperty(exports, "ModbusExceptionError", { enumerable: true, get: function () { return energy_app_modbus_js_1.ModbusExceptionError; } });
|
|
37
43
|
// Re-export the schedule message types from energy-app-sdk so consumers can
|
|
38
44
|
// build/inspect SetStorageScheduleV1 messages without a second import.
|
|
39
45
|
var enyo_data_bus_value_js_1 = require("@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js");
|
package/dist/cjs/index.d.cts
CHANGED
|
@@ -8,5 +8,6 @@ export { SunspecBatteryCalibrationDriver } from './sunspec-battery-calibration-d
|
|
|
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
10
|
export { type EnergyAppModbus, type EnergyAppModbusInstance, type ModbusOptions, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
|
|
11
|
+
export { type ModbusRawPduOptions, type ModbusRawPduResponse, MODBUS_MAX_PDU_PAYLOAD_BYTES, ModbusExceptionError, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
|
|
11
12
|
export { type EnyoDataBusSetStorageScheduleV1, type EnyoStorageScheduleEntry, EnyoStorageScheduleModeEnum, EnyoStorageScheduleDirectionEnum, } from '@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js';
|
|
12
13
|
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';
|
|
@@ -243,6 +243,17 @@ class SunspecModbusClient {
|
|
|
243
243
|
// logging: the first failure of a run is the news, every repeat while the peer stays down is
|
|
244
244
|
// the same news again. Cleared on the first success for that key.
|
|
245
245
|
consecutiveConnectFailures = new Map();
|
|
246
|
+
// Listeners registered through onUnitReconnected(), per unit.
|
|
247
|
+
unitReconnectListeners = new Map();
|
|
248
|
+
// Removers for the transport-level reconnect hook, one per open unit. Dropped with the unit.
|
|
249
|
+
unitReconnectUnsubscribers = new Map();
|
|
250
|
+
// Units that have had a live session and have not been deliberately disconnected since. A
|
|
251
|
+
// reopen for a unit in here is a RECYCLE (and therefore a reconnect); the very first open is not.
|
|
252
|
+
unitsWithSession = new Set();
|
|
253
|
+
// Units whose current session has already been reported lost. A dropped socket usually
|
|
254
|
+
// announces itself twice — once by the transport, once by this client's own close/reopen —
|
|
255
|
+
// and an app must not be told to re-authenticate twice for one loss.
|
|
256
|
+
unitSessionReportedLost = new Set();
|
|
246
257
|
constructor(
|
|
247
258
|
// The host application. Only used to obtain the default Modbus backend via
|
|
248
259
|
// `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
|
|
@@ -401,6 +412,7 @@ class SunspecModbusClient {
|
|
|
401
412
|
const units = [...this.modbusInstances.keys()];
|
|
402
413
|
for (const unitId of units) {
|
|
403
414
|
await this._closeUnit(unitId);
|
|
415
|
+
this.endUnitSession(unitId);
|
|
404
416
|
}
|
|
405
417
|
console.log(`Disconnected from Sunspec device at ${host}:${port} units [${units.join(',')}] (opens=${this.openCount}, closes=${this.closeCount})`);
|
|
406
418
|
});
|
|
@@ -415,6 +427,7 @@ class SunspecModbusClient {
|
|
|
415
427
|
const host = this.connectionParams?.primaryHost ?? 'unknown';
|
|
416
428
|
const port = this.connectionParams?.port ?? 0;
|
|
417
429
|
await this._closeUnit(unitId);
|
|
430
|
+
this.endUnitSession(unitId);
|
|
418
431
|
console.log(`Disconnected unit ${unitId} from Sunspec device at ${host}:${port} (opens=${this.openCount}, closes=${this.closeCount})`);
|
|
419
432
|
});
|
|
420
433
|
}
|
|
@@ -611,9 +624,20 @@ class SunspecModbusClient {
|
|
|
611
624
|
if (!candidate) {
|
|
612
625
|
throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
|
|
613
626
|
}
|
|
627
|
+
// Reopening a unit that already had a session is itself a reconnect: whatever the
|
|
628
|
+
// device tracked for the old socket (a vendor login above all) is void. Announce it
|
|
629
|
+
// before the new instance is installed, so a listener re-authenticating on the new
|
|
630
|
+
// session cannot run against the old one.
|
|
631
|
+
if (this.unitsWithSession.has(unitId)) {
|
|
632
|
+
this.notifyUnitReconnected(unitId, 'the unit was reopened');
|
|
633
|
+
}
|
|
614
634
|
const reader = new EnergyAppModbusFaultTolerantReader_js_1.EnergyAppModbusFaultTolerantReader(candidate, this.connectionHealth);
|
|
615
635
|
this.modbusInstances.set(unitId, candidate);
|
|
616
636
|
this.faultTolerantReaders.set(unitId, reader);
|
|
637
|
+
this.watchInstanceReconnects(unitId, candidate);
|
|
638
|
+
// A new session starts clean: it has not been reported lost yet.
|
|
639
|
+
this.unitsWithSession.add(unitId);
|
|
640
|
+
this.unitSessionReportedLost.delete(unitId);
|
|
617
641
|
// Fresh socket: clear any prior poison and start the freshness clock so a just-opened
|
|
618
642
|
// unit isn't immediately judged stale.
|
|
619
643
|
this.poisonedUnits.delete(unitId);
|
|
@@ -647,6 +671,10 @@ class SunspecModbusClient {
|
|
|
647
671
|
// recovery line reports how long the unit was down.
|
|
648
672
|
this.poisonedUnits.delete(unitId);
|
|
649
673
|
this.lastOkAtByUnit.delete(unitId);
|
|
674
|
+
// The transport hook belongs to the instance being dropped. The app's own listeners
|
|
675
|
+
// (unitReconnectListeners) survive — they are registered against the unit, not the socket.
|
|
676
|
+
this.unitReconnectUnsubscribers.get(unitId)?.();
|
|
677
|
+
this.unitReconnectUnsubscribers.delete(unitId);
|
|
650
678
|
if (instance) {
|
|
651
679
|
await this.disconnectInstanceBounded(instance, unitId);
|
|
652
680
|
}
|
|
@@ -908,6 +936,126 @@ class SunspecModbusClient {
|
|
|
908
936
|
getModbusInstance(unitId) {
|
|
909
937
|
return this.getInstance(unitId);
|
|
910
938
|
}
|
|
939
|
+
/**
|
|
940
|
+
* Send one raw Modbus PDU to a unit — a vendor function code the standard Modbus surface
|
|
941
|
+
* cannot express — and return the device's raw answer.
|
|
942
|
+
*
|
|
943
|
+
* This exists for devices that gate control behind a proprietary handshake. The canonical
|
|
944
|
+
* case is a Huawei SUN2000 without an EMMA: every control write is refused with exception
|
|
945
|
+
* 0x80 ("permission authentication failure or permission expiration") until an installer
|
|
946
|
+
* login has been performed over Huawei's function code 0x41, and that permission belongs to
|
|
947
|
+
* the SOCKET — see {@link SunspecModbusClient.onUnitReconnected}.
|
|
948
|
+
*
|
|
949
|
+
* The SDK stays vendor-agnostic: sub-commands, credential digests and keepalives belong to
|
|
950
|
+
* the caller. What the SDK contributes is that the PDU runs inside the unit's existing
|
|
951
|
+
* transaction chain, exactly like {@link SunspecModbusClient.readRegisterBlock} — a login
|
|
952
|
+
* cannot interleave with a block read already in flight, which matters on the single-frame
|
|
953
|
+
* SDongles this client talks to.
|
|
954
|
+
*
|
|
955
|
+
* A device exception comes back as data on {@link ModbusRawPduResponse.exceptionCode}, not
|
|
956
|
+
* as a rejection: a permission probe expects to be refused, and that has to be
|
|
957
|
+
* distinguishable from a dead link. Only transport failures throw.
|
|
958
|
+
*
|
|
959
|
+
* @param unitId Unit whose (already open) connection carries the request.
|
|
960
|
+
* @param functionCode Modbus function code, 1…127.
|
|
961
|
+
* @param payload PDU bytes after the function code; at most 252 bytes.
|
|
962
|
+
* @throws Error if the unit is not open, if the host runtime is too old to support raw PDUs,
|
|
963
|
+
* or if the transport failed.
|
|
964
|
+
*/
|
|
965
|
+
async sendRawPdu(unitId, functionCode, payload) {
|
|
966
|
+
const instance = this.getInstance(unitId);
|
|
967
|
+
if (typeof instance.sendRawPdu !== 'function') {
|
|
968
|
+
throw new Error(`Raw Modbus PDUs are not supported by this host runtime — unit ${unitId} needs an energy manager ` +
|
|
969
|
+
`running energy-app-sdk 1.9 or newer`);
|
|
970
|
+
}
|
|
971
|
+
try {
|
|
972
|
+
// Serialized on the unit's chain: a vendor handshake must not cross frames with a poll.
|
|
973
|
+
const response = await this.runExclusive(unitId, () => instance.sendRawPdu(functionCode, payload));
|
|
974
|
+
this.connectionHealth.recordSuccess();
|
|
975
|
+
return response;
|
|
976
|
+
}
|
|
977
|
+
catch (error) {
|
|
978
|
+
this.connectionHealth.recordFailure(error);
|
|
979
|
+
this.logTransactionError(`Error sending raw PDU fc=0x${functionCode.toString(16)} to unit ${unitId}`, error);
|
|
980
|
+
throw error;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Register a listener for "this unit's connection was replaced" — the moment anything the
|
|
985
|
+
* device scoped to the socket, such as a vendor login, became void.
|
|
986
|
+
*
|
|
987
|
+
* Both ways a connection can be replaced are covered: the transport recycling the socket
|
|
988
|
+
* underneath us (a dropped link, a half-open socket, a stale socket), and this client's own
|
|
989
|
+
* close-and-reopen (a poisoned unit, {@link SunspecModbusClient.reconnectUnit},
|
|
990
|
+
* {@link SunspecModbusClient.reconnect}). One loss produces exactly one notification even
|
|
991
|
+
* when both fire. A deliberate {@link SunspecModbusClient.disconnectUnit} ends the session
|
|
992
|
+
* instead — reconnecting afterwards is a new connection, not a recovered one.
|
|
993
|
+
*
|
|
994
|
+
* Listeners are registered against the UNIT, not the socket, so they survive reconnects and
|
|
995
|
+
* keep firing. They must not throw; a throwing listener is logged and ignored.
|
|
996
|
+
*
|
|
997
|
+
* @returns A remover for this listener.
|
|
998
|
+
*/
|
|
999
|
+
onUnitReconnected(unitId, listener) {
|
|
1000
|
+
let listeners = this.unitReconnectListeners.get(unitId);
|
|
1001
|
+
if (!listeners) {
|
|
1002
|
+
listeners = new Set();
|
|
1003
|
+
this.unitReconnectListeners.set(unitId, listeners);
|
|
1004
|
+
}
|
|
1005
|
+
listeners.add(listener);
|
|
1006
|
+
return () => {
|
|
1007
|
+
const current = this.unitReconnectListeners.get(unitId);
|
|
1008
|
+
current?.delete(listener);
|
|
1009
|
+
if (current && current.size === 0) {
|
|
1010
|
+
this.unitReconnectListeners.delete(unitId);
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Subscribe to the transport's own "the socket was replaced" signal for a freshly-opened
|
|
1016
|
+
* unit. Tolerates a host runtime older than energy-app-sdk 1.9, which has no such signal —
|
|
1017
|
+
* there the close-and-reopen path in {@link SunspecModbusClient._openUnitOnce} is the only
|
|
1018
|
+
* notification, which still catches every loss this client itself acts on.
|
|
1019
|
+
*/
|
|
1020
|
+
watchInstanceReconnects(unitId, instance) {
|
|
1021
|
+
if (typeof instance.onReconnect !== 'function') {
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
const unsubscribe = instance.onReconnect(() => this.notifyUnitReconnected(unitId, 'the socket was replaced'));
|
|
1025
|
+
this.unitReconnectUnsubscribers.get(unitId)?.();
|
|
1026
|
+
this.unitReconnectUnsubscribers.set(unitId, unsubscribe);
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Announce that a unit's connection was replaced — at most once per session, whichever of the
|
|
1030
|
+
* two detection paths gets there first.
|
|
1031
|
+
*/
|
|
1032
|
+
notifyUnitReconnected(unitId, reason) {
|
|
1033
|
+
if (this.unitSessionReportedLost.has(unitId)) {
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
this.unitSessionReportedLost.add(unitId);
|
|
1037
|
+
const listeners = this.unitReconnectListeners.get(unitId);
|
|
1038
|
+
if (!listeners || listeners.size === 0) {
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
console.debug(`SunspecModbusClient: unit ${unitId} connection replaced (${reason}); notifying ${listeners.size} listener(s)`);
|
|
1042
|
+
for (const listener of listeners) {
|
|
1043
|
+
try {
|
|
1044
|
+
listener();
|
|
1045
|
+
}
|
|
1046
|
+
catch (error) {
|
|
1047
|
+
console.warn(`SunspecModbusClient: reconnect listener for unit ${unitId} threw: ${error instanceof Error ? error.message : String(error)}`);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Forget that a unit ever had a session, so a later open counts as a first connection rather
|
|
1053
|
+
* than a recovery. Called only from the deliberate disconnect paths.
|
|
1054
|
+
*/
|
|
1055
|
+
endUnitSession(unitId) {
|
|
1056
|
+
this.unitsWithSession.delete(unitId);
|
|
1057
|
+
this.unitSessionReportedLost.delete(unitId);
|
|
1058
|
+
}
|
|
911
1059
|
/**
|
|
912
1060
|
* Get the fault-tolerant reader for a unit, throwing if it isn't open.
|
|
913
1061
|
*/
|
|
@@ -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 IModbusTransportConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.cjs";
|
|
20
20
|
import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
|
|
21
|
-
import { EnergyAppModbus, EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
|
|
21
|
+
import { EnergyAppModbus, EnergyAppModbusInstance, ModbusRawPduResponse } 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
|
|
@@ -135,6 +135,10 @@ export declare class SunspecModbusClient {
|
|
|
135
135
|
private poisonedAtByUnit;
|
|
136
136
|
private lastOkAtByUnit;
|
|
137
137
|
private consecutiveConnectFailures;
|
|
138
|
+
private unitReconnectListeners;
|
|
139
|
+
private unitReconnectUnsubscribers;
|
|
140
|
+
private unitsWithSession;
|
|
141
|
+
private unitSessionReportedLost;
|
|
138
142
|
constructor(energyApp: EnergyApp | undefined, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
|
|
139
143
|
/**
|
|
140
144
|
* The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
|
|
@@ -374,6 +378,67 @@ export declare class SunspecModbusClient {
|
|
|
374
378
|
* disconnectUnit(unitId) / releaseSunspecClient() as usual.
|
|
375
379
|
*/
|
|
376
380
|
getModbusInstance(unitId: number): EnergyAppModbusInstance;
|
|
381
|
+
/**
|
|
382
|
+
* Send one raw Modbus PDU to a unit — a vendor function code the standard Modbus surface
|
|
383
|
+
* cannot express — and return the device's raw answer.
|
|
384
|
+
*
|
|
385
|
+
* This exists for devices that gate control behind a proprietary handshake. The canonical
|
|
386
|
+
* case is a Huawei SUN2000 without an EMMA: every control write is refused with exception
|
|
387
|
+
* 0x80 ("permission authentication failure or permission expiration") until an installer
|
|
388
|
+
* login has been performed over Huawei's function code 0x41, and that permission belongs to
|
|
389
|
+
* the SOCKET — see {@link SunspecModbusClient.onUnitReconnected}.
|
|
390
|
+
*
|
|
391
|
+
* The SDK stays vendor-agnostic: sub-commands, credential digests and keepalives belong to
|
|
392
|
+
* the caller. What the SDK contributes is that the PDU runs inside the unit's existing
|
|
393
|
+
* transaction chain, exactly like {@link SunspecModbusClient.readRegisterBlock} — a login
|
|
394
|
+
* cannot interleave with a block read already in flight, which matters on the single-frame
|
|
395
|
+
* SDongles this client talks to.
|
|
396
|
+
*
|
|
397
|
+
* A device exception comes back as data on {@link ModbusRawPduResponse.exceptionCode}, not
|
|
398
|
+
* as a rejection: a permission probe expects to be refused, and that has to be
|
|
399
|
+
* distinguishable from a dead link. Only transport failures throw.
|
|
400
|
+
*
|
|
401
|
+
* @param unitId Unit whose (already open) connection carries the request.
|
|
402
|
+
* @param functionCode Modbus function code, 1…127.
|
|
403
|
+
* @param payload PDU bytes after the function code; at most 252 bytes.
|
|
404
|
+
* @throws Error if the unit is not open, if the host runtime is too old to support raw PDUs,
|
|
405
|
+
* or if the transport failed.
|
|
406
|
+
*/
|
|
407
|
+
sendRawPdu(unitId: number, functionCode: number, payload: Buffer): Promise<ModbusRawPduResponse>;
|
|
408
|
+
/**
|
|
409
|
+
* Register a listener for "this unit's connection was replaced" — the moment anything the
|
|
410
|
+
* device scoped to the socket, such as a vendor login, became void.
|
|
411
|
+
*
|
|
412
|
+
* Both ways a connection can be replaced are covered: the transport recycling the socket
|
|
413
|
+
* underneath us (a dropped link, a half-open socket, a stale socket), and this client's own
|
|
414
|
+
* close-and-reopen (a poisoned unit, {@link SunspecModbusClient.reconnectUnit},
|
|
415
|
+
* {@link SunspecModbusClient.reconnect}). One loss produces exactly one notification even
|
|
416
|
+
* when both fire. A deliberate {@link SunspecModbusClient.disconnectUnit} ends the session
|
|
417
|
+
* instead — reconnecting afterwards is a new connection, not a recovered one.
|
|
418
|
+
*
|
|
419
|
+
* Listeners are registered against the UNIT, not the socket, so they survive reconnects and
|
|
420
|
+
* keep firing. They must not throw; a throwing listener is logged and ignored.
|
|
421
|
+
*
|
|
422
|
+
* @returns A remover for this listener.
|
|
423
|
+
*/
|
|
424
|
+
onUnitReconnected(unitId: number, listener: () => void): () => void;
|
|
425
|
+
/**
|
|
426
|
+
* Subscribe to the transport's own "the socket was replaced" signal for a freshly-opened
|
|
427
|
+
* unit. Tolerates a host runtime older than energy-app-sdk 1.9, which has no such signal —
|
|
428
|
+
* there the close-and-reopen path in {@link SunspecModbusClient._openUnitOnce} is the only
|
|
429
|
+
* notification, which still catches every loss this client itself acts on.
|
|
430
|
+
*/
|
|
431
|
+
private watchInstanceReconnects;
|
|
432
|
+
/**
|
|
433
|
+
* Announce that a unit's connection was replaced — at most once per session, whichever of the
|
|
434
|
+
* two detection paths gets there first.
|
|
435
|
+
*/
|
|
436
|
+
private notifyUnitReconnected;
|
|
437
|
+
/**
|
|
438
|
+
* Forget that a unit ever had a session, so a later open counts as a first connection rather
|
|
439
|
+
* than a recovery. Called only from the deliberate disconnect paths.
|
|
440
|
+
*/
|
|
441
|
+
private endUnitSession;
|
|
377
442
|
/**
|
|
378
443
|
* Get the fault-tolerant reader for a unit, throwing if it isn't open.
|
|
379
444
|
*/
|
package/dist/cjs/version.cjs
CHANGED
package/dist/cjs/version.d.cts
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -8,5 +8,6 @@ export { SunspecBatteryCalibrationDriver } from './sunspec-battery-calibration-d
|
|
|
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
10
|
export { type EnergyAppModbus, type EnergyAppModbusInstance, type ModbusOptions, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
|
|
11
|
+
export { type ModbusRawPduOptions, type ModbusRawPduResponse, MODBUS_MAX_PDU_PAYLOAD_BYTES, ModbusExceptionError, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
|
|
11
12
|
export { type EnyoDataBusSetStorageScheduleV1, type EnyoStorageScheduleEntry, EnyoStorageScheduleModeEnum, EnyoStorageScheduleDirectionEnum, } from '@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js';
|
|
12
13
|
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';
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,10 @@ export { SunspecCalibrationStorage, createSunspecCalibrationStorage } from './su
|
|
|
8
8
|
export { SunspecBatteryCalibrationDriver } from './sunspec-battery-calibration-driver.js';
|
|
9
9
|
export { SunspecBatteryFeatureCalibrator, decodeFeatureResults, } from './sunspec-battery-feature-calibrator.js';
|
|
10
10
|
export { SunspecBatteryScheduleHandler, } from './sunspec-battery-schedule-handler.js';
|
|
11
|
+
// Re-export the raw-PDU surface so a consumer of `sendRawPdu` / `ModbusExceptionError`
|
|
12
|
+
// needs no second import from energy-app-sdk internals. `ModbusExceptionError` is a
|
|
13
|
+
// class, not a type: an app branches on it with `instanceof`.
|
|
14
|
+
export { MODBUS_MAX_PDU_PAYLOAD_BYTES, ModbusExceptionError, } from '@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js';
|
|
11
15
|
// Re-export the schedule message types from energy-app-sdk so consumers can
|
|
12
16
|
// build/inspect SetStorageScheduleV1 messages without a second import.
|
|
13
17
|
export { EnyoStorageScheduleModeEnum, EnyoStorageScheduleDirectionEnum, } from '@enyo-energy/energy-app-sdk/dist/types/enyo-data-bus-value.js';
|
|
@@ -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 IModbusTransportConfig, type IModbusResilienceConfig } from "./sunspec-interfaces.js";
|
|
20
20
|
import { EnergyAppModbusDataType, IConnectionHealth } from "@enyo-energy/energy-app-sdk/dist/implementations/modbus/interfaces.js";
|
|
21
|
-
import { EnergyAppModbus, EnergyAppModbusInstance } from "@enyo-energy/energy-app-sdk/dist/packages/energy-app-modbus.js";
|
|
21
|
+
import { EnergyAppModbus, EnergyAppModbusInstance, ModbusRawPduResponse } 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
|
|
@@ -135,6 +135,10 @@ export declare class SunspecModbusClient {
|
|
|
135
135
|
private poisonedAtByUnit;
|
|
136
136
|
private lastOkAtByUnit;
|
|
137
137
|
private consecutiveConnectFailures;
|
|
138
|
+
private unitReconnectListeners;
|
|
139
|
+
private unitReconnectUnsubscribers;
|
|
140
|
+
private unitsWithSession;
|
|
141
|
+
private unitSessionReportedLost;
|
|
138
142
|
constructor(energyApp: EnergyApp | undefined, transport?: IModbusTransportConfig, resilience?: IModbusResilienceConfig, modbusFactory?: EnergyAppModbus | undefined);
|
|
139
143
|
/**
|
|
140
144
|
* The Modbus backend used to open per-unit connections: the caller-supplied {@link modbusFactory}
|
|
@@ -374,6 +378,67 @@ export declare class SunspecModbusClient {
|
|
|
374
378
|
* disconnectUnit(unitId) / releaseSunspecClient() as usual.
|
|
375
379
|
*/
|
|
376
380
|
getModbusInstance(unitId: number): EnergyAppModbusInstance;
|
|
381
|
+
/**
|
|
382
|
+
* Send one raw Modbus PDU to a unit — a vendor function code the standard Modbus surface
|
|
383
|
+
* cannot express — and return the device's raw answer.
|
|
384
|
+
*
|
|
385
|
+
* This exists for devices that gate control behind a proprietary handshake. The canonical
|
|
386
|
+
* case is a Huawei SUN2000 without an EMMA: every control write is refused with exception
|
|
387
|
+
* 0x80 ("permission authentication failure or permission expiration") until an installer
|
|
388
|
+
* login has been performed over Huawei's function code 0x41, and that permission belongs to
|
|
389
|
+
* the SOCKET — see {@link SunspecModbusClient.onUnitReconnected}.
|
|
390
|
+
*
|
|
391
|
+
* The SDK stays vendor-agnostic: sub-commands, credential digests and keepalives belong to
|
|
392
|
+
* the caller. What the SDK contributes is that the PDU runs inside the unit's existing
|
|
393
|
+
* transaction chain, exactly like {@link SunspecModbusClient.readRegisterBlock} — a login
|
|
394
|
+
* cannot interleave with a block read already in flight, which matters on the single-frame
|
|
395
|
+
* SDongles this client talks to.
|
|
396
|
+
*
|
|
397
|
+
* A device exception comes back as data on {@link ModbusRawPduResponse.exceptionCode}, not
|
|
398
|
+
* as a rejection: a permission probe expects to be refused, and that has to be
|
|
399
|
+
* distinguishable from a dead link. Only transport failures throw.
|
|
400
|
+
*
|
|
401
|
+
* @param unitId Unit whose (already open) connection carries the request.
|
|
402
|
+
* @param functionCode Modbus function code, 1…127.
|
|
403
|
+
* @param payload PDU bytes after the function code; at most 252 bytes.
|
|
404
|
+
* @throws Error if the unit is not open, if the host runtime is too old to support raw PDUs,
|
|
405
|
+
* or if the transport failed.
|
|
406
|
+
*/
|
|
407
|
+
sendRawPdu(unitId: number, functionCode: number, payload: Buffer): Promise<ModbusRawPduResponse>;
|
|
408
|
+
/**
|
|
409
|
+
* Register a listener for "this unit's connection was replaced" — the moment anything the
|
|
410
|
+
* device scoped to the socket, such as a vendor login, became void.
|
|
411
|
+
*
|
|
412
|
+
* Both ways a connection can be replaced are covered: the transport recycling the socket
|
|
413
|
+
* underneath us (a dropped link, a half-open socket, a stale socket), and this client's own
|
|
414
|
+
* close-and-reopen (a poisoned unit, {@link SunspecModbusClient.reconnectUnit},
|
|
415
|
+
* {@link SunspecModbusClient.reconnect}). One loss produces exactly one notification even
|
|
416
|
+
* when both fire. A deliberate {@link SunspecModbusClient.disconnectUnit} ends the session
|
|
417
|
+
* instead — reconnecting afterwards is a new connection, not a recovered one.
|
|
418
|
+
*
|
|
419
|
+
* Listeners are registered against the UNIT, not the socket, so they survive reconnects and
|
|
420
|
+
* keep firing. They must not throw; a throwing listener is logged and ignored.
|
|
421
|
+
*
|
|
422
|
+
* @returns A remover for this listener.
|
|
423
|
+
*/
|
|
424
|
+
onUnitReconnected(unitId: number, listener: () => void): () => void;
|
|
425
|
+
/**
|
|
426
|
+
* Subscribe to the transport's own "the socket was replaced" signal for a freshly-opened
|
|
427
|
+
* unit. Tolerates a host runtime older than energy-app-sdk 1.9, which has no such signal —
|
|
428
|
+
* there the close-and-reopen path in {@link SunspecModbusClient._openUnitOnce} is the only
|
|
429
|
+
* notification, which still catches every loss this client itself acts on.
|
|
430
|
+
*/
|
|
431
|
+
private watchInstanceReconnects;
|
|
432
|
+
/**
|
|
433
|
+
* Announce that a unit's connection was replaced — at most once per session, whichever of the
|
|
434
|
+
* two detection paths gets there first.
|
|
435
|
+
*/
|
|
436
|
+
private notifyUnitReconnected;
|
|
437
|
+
/**
|
|
438
|
+
* Forget that a unit ever had a session, so a later open counts as a first connection rather
|
|
439
|
+
* than a recovery. Called only from the deliberate disconnect paths.
|
|
440
|
+
*/
|
|
441
|
+
private endUnitSession;
|
|
377
442
|
/**
|
|
378
443
|
* Get the fault-tolerant reader for a unit, throwing if it isn't open.
|
|
379
444
|
*/
|
|
@@ -234,6 +234,17 @@ export class SunspecModbusClient {
|
|
|
234
234
|
// logging: the first failure of a run is the news, every repeat while the peer stays down is
|
|
235
235
|
// the same news again. Cleared on the first success for that key.
|
|
236
236
|
consecutiveConnectFailures = new Map();
|
|
237
|
+
// Listeners registered through onUnitReconnected(), per unit.
|
|
238
|
+
unitReconnectListeners = new Map();
|
|
239
|
+
// Removers for the transport-level reconnect hook, one per open unit. Dropped with the unit.
|
|
240
|
+
unitReconnectUnsubscribers = new Map();
|
|
241
|
+
// Units that have had a live session and have not been deliberately disconnected since. A
|
|
242
|
+
// reopen for a unit in here is a RECYCLE (and therefore a reconnect); the very first open is not.
|
|
243
|
+
unitsWithSession = new Set();
|
|
244
|
+
// Units whose current session has already been reported lost. A dropped socket usually
|
|
245
|
+
// announces itself twice — once by the transport, once by this client's own close/reopen —
|
|
246
|
+
// and an app must not be told to re-authenticate twice for one loss.
|
|
247
|
+
unitSessionReportedLost = new Set();
|
|
237
248
|
constructor(
|
|
238
249
|
// The host application. Only used to obtain the default Modbus backend via
|
|
239
250
|
// `energyApp.useModbus()`. May be omitted (`undefined`) when a `modbusFactory` is supplied.
|
|
@@ -392,6 +403,7 @@ export class SunspecModbusClient {
|
|
|
392
403
|
const units = [...this.modbusInstances.keys()];
|
|
393
404
|
for (const unitId of units) {
|
|
394
405
|
await this._closeUnit(unitId);
|
|
406
|
+
this.endUnitSession(unitId);
|
|
395
407
|
}
|
|
396
408
|
console.log(`Disconnected from Sunspec device at ${host}:${port} units [${units.join(',')}] (opens=${this.openCount}, closes=${this.closeCount})`);
|
|
397
409
|
});
|
|
@@ -406,6 +418,7 @@ export class SunspecModbusClient {
|
|
|
406
418
|
const host = this.connectionParams?.primaryHost ?? 'unknown';
|
|
407
419
|
const port = this.connectionParams?.port ?? 0;
|
|
408
420
|
await this._closeUnit(unitId);
|
|
421
|
+
this.endUnitSession(unitId);
|
|
409
422
|
console.log(`Disconnected unit ${unitId} from Sunspec device at ${host}:${port} (opens=${this.openCount}, closes=${this.closeCount})`);
|
|
410
423
|
});
|
|
411
424
|
}
|
|
@@ -602,9 +615,20 @@ export class SunspecModbusClient {
|
|
|
602
615
|
if (!candidate) {
|
|
603
616
|
throw new Error(`useModbus().connect returned null for ${host}:${port} unit ${unitId}`);
|
|
604
617
|
}
|
|
618
|
+
// Reopening a unit that already had a session is itself a reconnect: whatever the
|
|
619
|
+
// device tracked for the old socket (a vendor login above all) is void. Announce it
|
|
620
|
+
// before the new instance is installed, so a listener re-authenticating on the new
|
|
621
|
+
// session cannot run against the old one.
|
|
622
|
+
if (this.unitsWithSession.has(unitId)) {
|
|
623
|
+
this.notifyUnitReconnected(unitId, 'the unit was reopened');
|
|
624
|
+
}
|
|
605
625
|
const reader = new EnergyAppModbusFaultTolerantReader(candidate, this.connectionHealth);
|
|
606
626
|
this.modbusInstances.set(unitId, candidate);
|
|
607
627
|
this.faultTolerantReaders.set(unitId, reader);
|
|
628
|
+
this.watchInstanceReconnects(unitId, candidate);
|
|
629
|
+
// A new session starts clean: it has not been reported lost yet.
|
|
630
|
+
this.unitsWithSession.add(unitId);
|
|
631
|
+
this.unitSessionReportedLost.delete(unitId);
|
|
608
632
|
// Fresh socket: clear any prior poison and start the freshness clock so a just-opened
|
|
609
633
|
// unit isn't immediately judged stale.
|
|
610
634
|
this.poisonedUnits.delete(unitId);
|
|
@@ -638,6 +662,10 @@ export class SunspecModbusClient {
|
|
|
638
662
|
// recovery line reports how long the unit was down.
|
|
639
663
|
this.poisonedUnits.delete(unitId);
|
|
640
664
|
this.lastOkAtByUnit.delete(unitId);
|
|
665
|
+
// The transport hook belongs to the instance being dropped. The app's own listeners
|
|
666
|
+
// (unitReconnectListeners) survive — they are registered against the unit, not the socket.
|
|
667
|
+
this.unitReconnectUnsubscribers.get(unitId)?.();
|
|
668
|
+
this.unitReconnectUnsubscribers.delete(unitId);
|
|
641
669
|
if (instance) {
|
|
642
670
|
await this.disconnectInstanceBounded(instance, unitId);
|
|
643
671
|
}
|
|
@@ -899,6 +927,126 @@ export class SunspecModbusClient {
|
|
|
899
927
|
getModbusInstance(unitId) {
|
|
900
928
|
return this.getInstance(unitId);
|
|
901
929
|
}
|
|
930
|
+
/**
|
|
931
|
+
* Send one raw Modbus PDU to a unit — a vendor function code the standard Modbus surface
|
|
932
|
+
* cannot express — and return the device's raw answer.
|
|
933
|
+
*
|
|
934
|
+
* This exists for devices that gate control behind a proprietary handshake. The canonical
|
|
935
|
+
* case is a Huawei SUN2000 without an EMMA: every control write is refused with exception
|
|
936
|
+
* 0x80 ("permission authentication failure or permission expiration") until an installer
|
|
937
|
+
* login has been performed over Huawei's function code 0x41, and that permission belongs to
|
|
938
|
+
* the SOCKET — see {@link SunspecModbusClient.onUnitReconnected}.
|
|
939
|
+
*
|
|
940
|
+
* The SDK stays vendor-agnostic: sub-commands, credential digests and keepalives belong to
|
|
941
|
+
* the caller. What the SDK contributes is that the PDU runs inside the unit's existing
|
|
942
|
+
* transaction chain, exactly like {@link SunspecModbusClient.readRegisterBlock} — a login
|
|
943
|
+
* cannot interleave with a block read already in flight, which matters on the single-frame
|
|
944
|
+
* SDongles this client talks to.
|
|
945
|
+
*
|
|
946
|
+
* A device exception comes back as data on {@link ModbusRawPduResponse.exceptionCode}, not
|
|
947
|
+
* as a rejection: a permission probe expects to be refused, and that has to be
|
|
948
|
+
* distinguishable from a dead link. Only transport failures throw.
|
|
949
|
+
*
|
|
950
|
+
* @param unitId Unit whose (already open) connection carries the request.
|
|
951
|
+
* @param functionCode Modbus function code, 1…127.
|
|
952
|
+
* @param payload PDU bytes after the function code; at most 252 bytes.
|
|
953
|
+
* @throws Error if the unit is not open, if the host runtime is too old to support raw PDUs,
|
|
954
|
+
* or if the transport failed.
|
|
955
|
+
*/
|
|
956
|
+
async sendRawPdu(unitId, functionCode, payload) {
|
|
957
|
+
const instance = this.getInstance(unitId);
|
|
958
|
+
if (typeof instance.sendRawPdu !== 'function') {
|
|
959
|
+
throw new Error(`Raw Modbus PDUs are not supported by this host runtime — unit ${unitId} needs an energy manager ` +
|
|
960
|
+
`running energy-app-sdk 1.9 or newer`);
|
|
961
|
+
}
|
|
962
|
+
try {
|
|
963
|
+
// Serialized on the unit's chain: a vendor handshake must not cross frames with a poll.
|
|
964
|
+
const response = await this.runExclusive(unitId, () => instance.sendRawPdu(functionCode, payload));
|
|
965
|
+
this.connectionHealth.recordSuccess();
|
|
966
|
+
return response;
|
|
967
|
+
}
|
|
968
|
+
catch (error) {
|
|
969
|
+
this.connectionHealth.recordFailure(error);
|
|
970
|
+
this.logTransactionError(`Error sending raw PDU fc=0x${functionCode.toString(16)} to unit ${unitId}`, error);
|
|
971
|
+
throw error;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Register a listener for "this unit's connection was replaced" — the moment anything the
|
|
976
|
+
* device scoped to the socket, such as a vendor login, became void.
|
|
977
|
+
*
|
|
978
|
+
* Both ways a connection can be replaced are covered: the transport recycling the socket
|
|
979
|
+
* underneath us (a dropped link, a half-open socket, a stale socket), and this client's own
|
|
980
|
+
* close-and-reopen (a poisoned unit, {@link SunspecModbusClient.reconnectUnit},
|
|
981
|
+
* {@link SunspecModbusClient.reconnect}). One loss produces exactly one notification even
|
|
982
|
+
* when both fire. A deliberate {@link SunspecModbusClient.disconnectUnit} ends the session
|
|
983
|
+
* instead — reconnecting afterwards is a new connection, not a recovered one.
|
|
984
|
+
*
|
|
985
|
+
* Listeners are registered against the UNIT, not the socket, so they survive reconnects and
|
|
986
|
+
* keep firing. They must not throw; a throwing listener is logged and ignored.
|
|
987
|
+
*
|
|
988
|
+
* @returns A remover for this listener.
|
|
989
|
+
*/
|
|
990
|
+
onUnitReconnected(unitId, listener) {
|
|
991
|
+
let listeners = this.unitReconnectListeners.get(unitId);
|
|
992
|
+
if (!listeners) {
|
|
993
|
+
listeners = new Set();
|
|
994
|
+
this.unitReconnectListeners.set(unitId, listeners);
|
|
995
|
+
}
|
|
996
|
+
listeners.add(listener);
|
|
997
|
+
return () => {
|
|
998
|
+
const current = this.unitReconnectListeners.get(unitId);
|
|
999
|
+
current?.delete(listener);
|
|
1000
|
+
if (current && current.size === 0) {
|
|
1001
|
+
this.unitReconnectListeners.delete(unitId);
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Subscribe to the transport's own "the socket was replaced" signal for a freshly-opened
|
|
1007
|
+
* unit. Tolerates a host runtime older than energy-app-sdk 1.9, which has no such signal —
|
|
1008
|
+
* there the close-and-reopen path in {@link SunspecModbusClient._openUnitOnce} is the only
|
|
1009
|
+
* notification, which still catches every loss this client itself acts on.
|
|
1010
|
+
*/
|
|
1011
|
+
watchInstanceReconnects(unitId, instance) {
|
|
1012
|
+
if (typeof instance.onReconnect !== 'function') {
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
const unsubscribe = instance.onReconnect(() => this.notifyUnitReconnected(unitId, 'the socket was replaced'));
|
|
1016
|
+
this.unitReconnectUnsubscribers.get(unitId)?.();
|
|
1017
|
+
this.unitReconnectUnsubscribers.set(unitId, unsubscribe);
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Announce that a unit's connection was replaced — at most once per session, whichever of the
|
|
1021
|
+
* two detection paths gets there first.
|
|
1022
|
+
*/
|
|
1023
|
+
notifyUnitReconnected(unitId, reason) {
|
|
1024
|
+
if (this.unitSessionReportedLost.has(unitId)) {
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
this.unitSessionReportedLost.add(unitId);
|
|
1028
|
+
const listeners = this.unitReconnectListeners.get(unitId);
|
|
1029
|
+
if (!listeners || listeners.size === 0) {
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
console.debug(`SunspecModbusClient: unit ${unitId} connection replaced (${reason}); notifying ${listeners.size} listener(s)`);
|
|
1033
|
+
for (const listener of listeners) {
|
|
1034
|
+
try {
|
|
1035
|
+
listener();
|
|
1036
|
+
}
|
|
1037
|
+
catch (error) {
|
|
1038
|
+
console.warn(`SunspecModbusClient: reconnect listener for unit ${unitId} threw: ${error instanceof Error ? error.message : String(error)}`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Forget that a unit ever had a session, so a later open counts as a first connection rather
|
|
1044
|
+
* than a recovery. Called only from the deliberate disconnect paths.
|
|
1045
|
+
*/
|
|
1046
|
+
endUnitSession(unitId) {
|
|
1047
|
+
this.unitsWithSession.delete(unitId);
|
|
1048
|
+
this.unitSessionReportedLost.delete(unitId);
|
|
1049
|
+
}
|
|
902
1050
|
/**
|
|
903
1051
|
* Get the fault-tolerant reader for a unit, throwing if it isn't open.
|
|
904
1052
|
*/
|
package/dist/version.d.ts
CHANGED
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enyo-energy/sunspec-sdk",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "enyo Energy Sunspec SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
43
|
"@enyo-energy/appliance-calibration": "0.0.3",
|
|
44
|
-
"@enyo-energy/energy-app-sdk": "1.
|
|
44
|
+
"@enyo-energy/energy-app-sdk": "1.9.0"
|
|
45
45
|
},
|
|
46
46
|
"volta": {
|
|
47
47
|
"node": "22.17.0"
|