@mega-yfue/eufy-sdk 0.5.0-beta.2 → 0.5.0-beta.20

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/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // dist/client/eufy-mega.js
8
- import { EventEmitter as EventEmitter9 } from "node:events";
8
+ import { EventEmitter as EventEmitter12 } from "node:events";
9
9
 
10
10
  // dist/transport/http/mega-client.js
11
11
  import { createHash as createHash3 } from "node:crypto";
@@ -1563,6 +1563,8 @@ function withoutTokenEcho(text2) {
1563
1563
  var MegaHttpClient = class {
1564
1564
  cfg;
1565
1565
  region;
1566
+ /** The host `estimate_domain` answered, persisted with the session. */
1567
+ estimatedDomain = "";
1566
1568
  bootstrapDomain;
1567
1569
  sessionKey;
1568
1570
  /** Per-host ECDH session keys for non-mega gateways (e.g. eufylife) keyed by host. */
@@ -1643,6 +1645,7 @@ var MegaHttpClient = class {
1643
1645
  if (!isSessionValid(saved) || !saved)
1644
1646
  return void 0;
1645
1647
  this.region = saved.region;
1648
+ this.estimatedDomain = saved.estimatedDomain ?? "";
1646
1649
  this.auth_ = {
1647
1650
  userId: saved.userId,
1648
1651
  accountUserId: saved.accountUserId,
@@ -1667,6 +1670,24 @@ var MegaHttpClient = class {
1667
1670
  get regionShard() {
1668
1671
  return this.region;
1669
1672
  }
1673
+ /**
1674
+ * The shard the RTC signalling signs on: the regional prefix of the estimated domain
1675
+ * (`…-ie-…`/`…-ie.` → `ie-pr`), else {@link regionShard}. The eu/us classification cannot name shards
1676
+ * like `ie-pr`, whose accounts need the IE sign host and cluster.
1677
+ */
1678
+ get rtcShard() {
1679
+ const m = /-([a-z]{2})(?:[.-]|$)/i.exec(this.estimatedDomain);
1680
+ return m ? `${m[1].toLowerCase()}-pr` : this.region;
1681
+ }
1682
+ /**
1683
+ * The credentials the RTC signalling needs; `undefined` while logged out. The sign is refused
1684
+ * ("gtoken not equal userid") unless its gtoken is the one every authed HTTP call carries.
1685
+ */
1686
+ rtcIdentity() {
1687
+ if (!this.auth_)
1688
+ return void 0;
1689
+ return { authToken: this.auth_.authToken, userId: this.auth_.userId, gtoken: gtoken(this.gtokenUserId()) };
1690
+ }
1670
1691
  /**
1671
1692
  * The name commands attribute themselves to — {@link MegaClientConfig.accountName} when the config
1672
1693
  * pins one (trimmed; blank counts as unset), otherwise the logged-in account's display name, which
@@ -1764,6 +1785,7 @@ var MegaHttpClient = class {
1764
1785
  const env = res.data;
1765
1786
  const d = env?.data ?? {};
1766
1787
  const domain = d.domain ?? d.host ?? d.server_secret_info ?? "";
1788
+ this.estimatedDomain = domain;
1767
1789
  const blob = JSON.stringify(d);
1768
1790
  if (blob.includes("-eu-") || domain.includes("-eu-"))
1769
1791
  this.region = "eu-pr";
@@ -1974,6 +1996,17 @@ ${this.auth_?.authToken ?? ""}`;
1974
1996
  device_sns: [deviceSn]
1975
1997
  });
1976
1998
  }
1999
+ /**
2000
+ * Fetch the account's devices as the `devicerelation` service lists them, `{attribute: 7, house_id: ""}`.
2001
+ *
2002
+ * Each entry is `{device: {device_sn, dps, …}}`, and `dps` is the cloud's last-known value of every
2003
+ * data point that device has reported, keyed by DP number. Answered for an account a device is shared
2004
+ * with as well as for its owner. Sent with `category: eufy_home`, without which the service answers
2005
+ * `10000`.
2006
+ */
2007
+ getDeviceRelationList() {
2008
+ return this.post("devicerelation", "/app/devicerelation/get_device_list", { attribute: 7, house_id: "" }, { category: "eufy_home" });
2009
+ }
1977
2010
  /**
1978
2011
  * Fetch one page of a device's **cleaning history** from the mega `clean` service.
1979
2012
  *
@@ -2422,6 +2455,7 @@ ${this.auth_?.authToken ?? ""}`;
2422
2455
  authToken: this.auth_.authToken,
2423
2456
  geoKey: this.auth_.geoKey,
2424
2457
  region: this.region,
2458
+ estimatedDomain: this.estimatedDomain,
2425
2459
  openudid: this.openudid,
2426
2460
  phoneModel: this.phoneModel,
2427
2461
  mediaUserAgent: this.mediaUserAgent,
@@ -5060,6 +5094,7 @@ var isIndoorCamera = (ctx) => has(INDOOR_CAMERA_TYPES, ctx.deviceType);
5060
5094
  var isIndoorCamMini = (ctx) => ctx.deviceType === DeviceType.INDOOR_COST_DOWN_CAMERA;
5061
5095
  var isIndoorPanTiltS350 = (ctx) => has(INDOOR_PT_S350_TYPES, ctx.deviceType);
5062
5096
  var isHomeBase = (ctx) => has(HOMEBASE_TYPES, ctx.deviceType);
5097
+ var isStation9000 = (ctx) => ctx.deviceType === DeviceType.STATION_9000;
5063
5098
  var isAiotVacuum = (ctx) => ctx.category !== "eufy_home_tuya";
5064
5099
  var isTuyaVacuum = (ctx) => ctx.category === "eufy_home_tuya";
5065
5100
 
@@ -5205,6 +5240,8 @@ var AUDIO = {
5205
5240
 
5206
5241
  // dist/model/capabilities/camera.js
5207
5242
  var CAMERA_CMD = {
5243
+ /** Camera-reported Wi-Fi signal (app `CMD_GET_WIFI_RSSI`). */
5244
+ WIFI_RSSI: 1142,
5208
5245
  /** Camera on/off. Read and write polarity depend on the family and topology. */
5209
5246
  CAMERA_ENABLE: 1035,
5210
5247
  /** Wrapped T8410 power switch on HomeBase 3. */
@@ -5484,6 +5521,14 @@ function refuseWhenDisabled(ctx, read) {
5484
5521
  throw new CameraDisabledError(ctx.name ?? ctx.serial);
5485
5522
  }
5486
5523
  var CAMERA_MEMBERS = {
5524
+ /** Reads the latest cached report and exposes no setter. */
5525
+ wifiRssi: {
5526
+ param: CAMERA_CMD.WIFI_RSSI,
5527
+ type: "number",
5528
+ kind: "scalar",
5529
+ provenance: "apk",
5530
+ description: "Camera-reported Wi-Fi signal; physical units and a quality scale are unspecified."
5531
+ },
5487
5532
  /**
5488
5533
  * The default READ is the *disable*-bit convention (1035 "0" ⇒ ON, 2001 direct); the WRITE polarity is
5489
5534
  * family-dependent — see `powerValue` / `isEnableBitPolarity`. Battery/solo cams report the state under
@@ -5640,16 +5685,14 @@ var CAMERA_MEMBERS = {
5640
5685
  * Live-view quality, the pair to {@link CAMERA_MEMBERS.recordingQuality} and a different setting on a
5641
5686
  * different wire: changing one leaves the other's parameter untouched.
5642
5687
  *
5643
- * The READ is 1020, which reports the resolved tier as a plain integer. 1020 is also the name the
5644
- * param dictionary already gives that id, and `Device` keys state by NAME — a member claiming 2730
5645
- * under this name would collide with it on a device reporting both.
5688
+ * The READ is 1020, which reports the resolved tier as a plain integer, while the WRITE rides 2730's
5689
+ * `1350` payload. They are two ids for one setting because 2730 carries a per-mode config and 1020
5690
+ * carries the tier in force; the tier is what this property means. 1020 is also the name the param
5691
+ * dictionary already gives that id, and `Device` keys state by NAME — a member claiming 2730 under
5692
+ * this name would collide with it on a device reporting both.
5646
5693
  *
5647
- * `unverified: true` with no `write`: the app's 2730 frame is captured byte-exact, but replaying it
5648
- * from this SDK produced no observable change on a standalone T8171, where the recording sibling's
5649
- * 2731 write on the same envelope and the same session does land. The one difference the capture
5650
- * shows is that the app's frame carries no `mChannel`/`mValue3`, which this envelope always emits.
5651
- * Until a send is confirmed, the setter is absent — a control that silently does nothing is worse
5652
- * than none — and the read ships ahead of it, which verification per direction allows.
5694
+ * `transaction` is part of the frame that was captured, so it is sent. The recording sibling's own
5695
+ * confirmed frame carries no such field; neither is inferred from the other.
5653
5696
  */
5654
5697
  streamingQuality: {
5655
5698
  param: 1020,
@@ -5657,8 +5700,13 @@ var CAMERA_MEMBERS = {
5657
5700
  kind: "enum",
5658
5701
  enumValues: STREAMING_QUALITY_TIERS,
5659
5702
  provenance: "verified",
5660
- unverified: true,
5661
- description: "Live-view quality as a tier, 0 = Auto (1020). Distinct from recordingQuality, which is what gets stored. All four tiers confirmed on a T8170 and a T8171. The WRITE (2730) is unconfirmed from this SDK, so no setter is offered rather than one that reports success without acting \u2014 see CAMERA_CMD.STREAMING_QUALITY_SET."
5703
+ args: [{ name: "quality", kind: "enum", description: "A tier, or the name it maps to. 0 is Auto." }],
5704
+ ...accepts(),
5705
+ description: "Live-view quality as a tier, 0 = Auto (1020; the write rides 2730 APP_CMD_MULTI_CAM_SET_VIDEO_QUALITY). Distinct from recordingQuality, which is what gets stored. All four tiers wire-verified live on a T8170 and read back on 1020. Sent from this SDK to a standalone T8170 and T8171, tier 1 holds the live stream at 1280x720 and tier 0 restores the camera's own resolution ladder \u2014 see CAMERA_CMD.STREAMING_QUALITY_SET. A value outside the tier set is REJECTED, not clamped: every tier in range is a real quality, so a bad one would silently pick another.",
5706
+ write: (v, ctx) => {
5707
+ const q = resolveStreamingQualityTier(v);
5708
+ return q == null ? void 0 : setPayload(CAMERA_CMD.STREAMING_QUALITY_SET, { channel: 0, mode: 0, primary_view: 0, quality: q, transaction: String(Date.now()) }, ctx, 0, void 0, "auto");
5709
+ }
5662
5710
  },
5663
5711
  /**
5664
5712
  * `type` is how the value is STORED, and 2731 stores the whole config — the ACTIVE tier is lifted out
@@ -6188,6 +6236,9 @@ var LIGHT_MEMBERS = {
6188
6236
  * This is the switch a user changes and expects to STAY changed. {@link isOn} is a different fact:
6189
6237
  * the lamp being lit right now, driven by whichever
6190
6238
  * client is streaming — the vendor app lights it for a live view and drops it on quitting.
6239
+ *
6240
+ * The T8423 write takes the session-chosen level; level-1 int+string was verified live on a standalone
6241
+ * unit.
6191
6242
  */
6192
6243
  spotlightEnabled: {
6193
6244
  param: LIGHT_CMD.SPOTLIGHT_ENABLE,
@@ -6195,7 +6246,7 @@ var LIGHT_MEMBERS = {
6195
6246
  kind: "boolean",
6196
6247
  provenance: "verified",
6197
6248
  description: "The spotlight master switch, distinct from the on/off above \u2014 whether the spotlight may light at all. Read verified live on a T8170 (param 1403, direct polarity: 1 = enabled).",
6198
- write: (v, ctx) => directBinary(LIGHT_CMD.SPOTLIGHT_ENABLE, asBool(v) ? 1 : 0, ctx),
6249
+ write: (v, ctx) => setScalar(LIGHT_CMD.SPOTLIGHT_ENABLE, asBool(v) ? 1 : 0, ctx, ctx.deviceType === DeviceType.FLOODLIGHT_CAMERA_8423 ? "auto" : "direct-binary"),
6199
6250
  writeAs: "setEnabled"
6200
6251
  }
6201
6252
  };
@@ -8312,8 +8363,6 @@ var MODE_CTRL_FIELD = {
8312
8363
  SEQ: 2
8313
8364
  };
8314
8365
  var ModeCtrlMethod = {
8315
- /** Live-verified on a T2351. Zero, so it is omitted from the wire per the proto3 default rule. */
8316
- START_AUTO_CLEAN: 0,
8317
8366
  /** Live-verified on a T2351. */
8318
8367
  START_GOHOME: 6,
8319
8368
  /** Live-verified on a T2351. */
@@ -8337,6 +8386,8 @@ var ModeCtrlMethod = {
8337
8386
  START_GLOBAL_CRUISE: 20
8338
8387
  };
8339
8388
  var ModeCtrlParamMethod = {
8389
+ /** `START_AUTO_CLEAN` with an `AutoClean` payload — clean the whole floor. */
8390
+ AUTO: { method: 0, param: 3 },
8340
8391
  /** `START_SELECT_ROOMS_CLEAN` — clean the named rooms of a named map. */
8341
8392
  SELECT_ROOMS: { method: 1, param: 4 },
8342
8393
  /** `START_SELECT_ZONES_CLEAN` — clean the given rectangles of a named map. */
@@ -8373,6 +8424,7 @@ var SELECT_ZONES_FIELD = {
8373
8424
  POINT_Y: 2
8374
8425
  };
8375
8426
  var SCENE_CLEAN_ID = 1;
8427
+ var AUTO_CLEAN_TIMES = 1;
8376
8428
  function encodeModeCtrlParam(method2, paramField, build) {
8377
8429
  return rawDp((w) => {
8378
8430
  if (method2 !== 0)
@@ -8419,14 +8471,17 @@ function encodeSceneClean(sceneId) {
8419
8471
  const { method: method2, param } = ModeCtrlParamMethod.SCENE;
8420
8472
  return encodeModeCtrlParam(method2, param, (p) => p.int(SCENE_CLEAN_ID, sceneId));
8421
8473
  }
8474
+ function encodeAutoClean() {
8475
+ const { method: method2, param } = ModeCtrlParamMethod.AUTO;
8476
+ return encodeModeCtrlParam(method2, param, (p) => p.int(AUTO_CLEAN_TIMES, 1));
8477
+ }
8422
8478
  var modeCtrlSeq = 111;
8423
8479
  function nextModeCtrlSeq() {
8424
8480
  return ++modeCtrlSeq;
8425
8481
  }
8426
8482
  function encodeModeCtrl(method2, seq) {
8427
8483
  return rawDp((w) => {
8428
- if (method2 !== 0)
8429
- w.int(MODE_CTRL_FIELD.METHOD, method2);
8484
+ w.int(MODE_CTRL_FIELD.METHOD, method2);
8430
8485
  w.int(MODE_CTRL_FIELD.SEQ, seq);
8431
8486
  });
8432
8487
  }
@@ -10268,8 +10323,8 @@ var VACUUM_CLEAN_MEMBERS = {
10268
10323
  provenance: "mega",
10269
10324
  description: "Stop smart-follow mode (ModeCtrlRequest method 18 over DP 152). Method number not captured \u2014 unverified."
10270
10325
  },
10271
- /** Start an auto-clean run via ModeCtrlRequest method 0 (DP 152). AIoT only — Tuya write unverified. */
10272
- startCleaning: method(({ sink }) => () => sink.dispatch(aiotDp(VACUUM_DP.MODE_CTRL, encodeModeCtrl(ModeCtrlMethod.START_AUTO_CLEAN, nextModeCtrlSeq()))), "Start an auto-clean run (ModeCtrlRequest method 0 over DP 152).", isAiotVacuum),
10326
+ /** Start an auto-clean run via ModeCtrlRequest method 0 with one `AutoClean` pass (DP 152). AIoT only — Tuya write unverified. */
10327
+ startCleaning: method(({ sink }) => () => sink.dispatch(aiotDp(VACUUM_DP.MODE_CTRL, encodeAutoClean())), "Start an auto-clean run (ModeCtrlRequest method 0, AutoClean clean_times 1, over DP 152).", isAiotVacuum),
10273
10328
  /** Return to the dock via ModeCtrlRequest method 6 (DP 152). AIoT only — Tuya write unverified. */
10274
10329
  returnToDock: method(({ sink }) => () => sink.dispatch(aiotDp(VACUUM_DP.MODE_CTRL, encodeModeCtrl(ModeCtrlMethod.START_GOHOME, nextModeCtrlSeq()))), "Return to the dock (ModeCtrlRequest method 6 over DP 152).", isAiotVacuum),
10275
10330
  /** Pause the current cleaning task via ModeCtrlRequest method 13 (DP 152). AIoT only — Tuya write unverified. */
@@ -11018,6 +11073,8 @@ var MODEL_REGISTRY = {
11018
11073
  T8210: { codec: "camera", caps: ["doorbell", "battery"], name: "Video Doorbell" },
11019
11074
  // Confirmed against a real owned unit (named "Doorbell"): Video Doorbell Dual.
11020
11075
  T8214: { codec: "camera", caps: ["doorbell", "battery"], name: "Video Doorbell Dual" },
11076
+ // Battery Video Doorbell Dual, vendor deviceType 91 (BATTERY_DOORBELL_PLUS), reported by two users.
11077
+ T8213: { codec: "camera", caps: ["doorbell", "battery"], name: "Video Doorbell Dual" },
11021
11078
  // Confirmed against a real owned unit: the mains-powered Wired Doorbell 2K. No `battery` row
11022
11079
  // member on purpose — this model is wired, so the codec baseline plus inference is the whole
11023
11080
  // truth for power. Without this row it classified as a plain camera, so the doorbell capability
@@ -11179,8 +11236,10 @@ function resolveDevice(rec) {
11179
11236
  }
11180
11237
  function resolveProperties(rec, codec, capabilities) {
11181
11238
  const paramIds = /* @__PURE__ */ new Set();
11182
- if (rec.params && typeof rec.params === "object") {
11183
- for (const k of Object.keys(rec.params)) {
11239
+ for (const reported of [rec.params, rec.dpParams]) {
11240
+ if (!reported || typeof reported !== "object")
11241
+ continue;
11242
+ for (const k of Object.keys(reported)) {
11184
11243
  const n = Number(k);
11185
11244
  if (Number.isFinite(n))
11186
11245
  paramIds.add(n);
@@ -15699,8 +15758,8 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
15699
15758
  return this.connected;
15700
15759
  }
15701
15760
  /**
15702
- * Ask the OS for {@link RECEIVE_BUFFER_BYTES} on a bound socket, and warn once per session when it grants
15703
- * less or refuses.
15761
+ * Ask the OS for {@link RECEIVE_BUFFER_BYTES} on a bound socket, and log once per session when it grants
15762
+ * less (debug) or refuses (warn).
15704
15763
  *
15705
15764
  * The request is made here rather than through `createSocket`'s `recvBufferSize`: Node applies that option
15706
15765
  * inside the bind callback, where a refusal is thrown out of reach of this session and ends the process.
@@ -15716,7 +15775,8 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
15716
15775
  if (granted >= RECEIVE_BUFFER_BYTES || this.receiveBufferReported)
15717
15776
  return;
15718
15777
  this.receiveBufferReported = true;
15719
- this.logger.warn(`[p2p] ${this.cfg.stationSn} UDP receive buffer below the ${RECEIVE_BUFFER_BYTES} bytes requested` + (granted > 0 ? ` (granted ${granted})` : " (request refused)") + `; live video can lose keyframes. Raise the OS limit (net.core.rmem_max on Linux, kern.ipc.maxsockbuf on BSD) to at least ${RECEIVE_BUFFER_BYTES}.`);
15778
+ const [level, outcome] = granted > 0 ? ["debug", ` (granted ${granted})`] : ["warn", " (request refused)"];
15779
+ this.logger[level](`[p2p] ${this.cfg.stationSn} UDP receive buffer below the ${RECEIVE_BUFFER_BYTES} bytes requested` + outcome + `; live video can lose keyframes. Raise the OS limit (net.core.rmem_max on Linux, kern.ipc.maxsockbuf on BSD) to at least ${RECEIVE_BUFFER_BYTES}.`);
15720
15780
  }
15721
15781
  /** Open the socket and start the lookup → hole-punch handshake. */
15722
15782
  async connect() {
@@ -16248,6 +16308,21 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16248
16308
  this.send(this.connectAddress, RequestMessageType.DATA, data);
16249
16309
  return true;
16250
16310
  }
16311
+ /**
16312
+ * The level-1 twin of {@link sendRawLevel2Bytes}: the plaintext `payload` sealed AES-128-ECB under the
16313
+ * level-1 key, signCode 1 — the seal of the level-1 media start. Returns `false` when not connected.
16314
+ */
16315
+ sendRawLevel1Bytes(payload, channel, outerCmd) {
16316
+ if (!this.connectAddress)
16317
+ return false;
16318
+ const data = Buffer.concat([
16319
+ buildCommandHeader(this.seqNumber, outerCmd),
16320
+ buildRawCommandPayload(encryptP2PData(paddingP2PData(payload), this.level1Key), channel, 1)
16321
+ ]);
16322
+ this.seqNumber = this.seqNumber + 1 & 65535;
16323
+ this.send(this.connectAddress, RequestMessageType.DATA, data);
16324
+ return true;
16325
+ }
16251
16326
  /**
16252
16327
  * Stop the realtime media stream (`CMD_STOP_REALTIME_MEDIA`, 1004) on a camera `channel`, in the shape
16253
16328
  * its runtime topology takes, as {@link startLiveMedia} selects its start:
@@ -16468,7 +16543,7 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16468
16543
  camera_type: 0,
16469
16544
  entrytype: 0,
16470
16545
  key: this.rsaModulus(),
16471
- streamtype: 1,
16546
+ streamtype: 2,
16472
16547
  ...payload
16473
16548
  } : payload;
16474
16549
  const value = JSON.stringify({
@@ -16809,11 +16884,13 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16809
16884
  if (advance > SEQUENCE_LOOKBACK) {
16810
16885
  if (65536 - advance <= STALE_RETRANSMIT_DEPTH)
16811
16886
  return;
16812
- if (this.pendingByDataType.has(dataType) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
16887
+ if ((dataType === P2PDataType.VIDEO || this.pendingByDataType.has(dataType)) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
16813
16888
  this.trace({ phase: "sequence-restart", dataType });
16814
16889
  this.clearReorderTimer(dataType);
16815
16890
  this.reorderByType.delete(dataType);
16816
16891
  this.pendingByDataType.delete(dataType);
16892
+ if (dataType === P2PDataType.VIDEO)
16893
+ this.emit("videoGap");
16817
16894
  this.lastSeqByType.set(dataType, seqNo);
16818
16895
  this.reassemble(dataType, msg.subarray(8));
16819
16896
  return;
@@ -16879,9 +16956,11 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16879
16956
  */
16880
16957
  abandonHole(dataType) {
16881
16958
  const held = this.reorderByType.get(dataType).held;
16882
- if (this.pendingByDataType.has(dataType) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
16959
+ if ((dataType === P2PDataType.VIDEO || this.pendingByDataType.has(dataType)) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
16883
16960
  this.trace({ phase: "datagram-gap", dataType });
16884
16961
  this.pendingByDataType.delete(dataType);
16962
+ if (dataType === P2PDataType.VIDEO)
16963
+ this.emit("videoGap");
16885
16964
  const last = this.lastSeqByType.get(dataType);
16886
16965
  const earliest = [...held.keys()].sort((a, b) => (a - last & 65535) - (b - last & 65535))[0];
16887
16966
  this.lastSeqByType.set(dataType, earliest - 1 & 65535);
@@ -17518,7 +17597,8 @@ var AccessUnitAssembler = class {
17518
17597
  * `decode` extracts the payload of a frame, whatever the stream's encryption: it is called for EVERY
17519
17598
  * frame, including a continuation, because a continuation carries its own wrapped key ahead of its share
17520
17599
  * of the payload (measured: 129 bytes beyond what its header declares, exactly as a unit's first frame
17521
- * carries).
17600
+ * carries). A continuation without its matching open unit has no Annex-B start code and cannot be emitted
17601
+ * as a complete unit, even if its repeated header says keyframe.
17522
17602
  */
17523
17603
  push(payload, decode) {
17524
17604
  const header = parseVideoFrameHeader(payload);
@@ -17538,6 +17618,8 @@ var AccessUnitAssembler = class {
17538
17618
  return [unitOf(open2.header, Buffer.concat(open2.chunks))];
17539
17619
  }
17540
17620
  this.discard();
17621
+ if (!beginsAccessUnit(body))
17622
+ return [];
17541
17623
  if (full) {
17542
17624
  this.open = { header, chunks: [body], carried: body.length };
17543
17625
  return [];
@@ -17878,6 +17960,7 @@ var AUDIO_HEADER_LEN = 16;
17878
17960
  var AUDIO_TYPE_OFFSET = 5;
17879
17961
  var SC4 = Buffer.from([0, 0, 0, 1]);
17880
17962
  var SC3 = Buffer.from([0, 0, 1]);
17963
+ var AAC_ELD_AUDIO_SPECIFIC_CONFIG = Buffer.from("f8f03000", "hex");
17881
17964
  var AUDIO_CODECS = { 0: "aac-lc", 2: "g711a", 7: "aac-eld" };
17882
17965
  var MAX_TRACED_DECODE_FAILURES = 3;
17883
17966
  var DEFAULT_KEEPALIVE_MS = 3e3;
@@ -17891,6 +17974,12 @@ var LiveStream = class extends EventEmitter3 {
17891
17974
  lastCodec = "h264";
17892
17975
  /** Rebuilds an access unit the station split across several frames — see {@link AccessUnitAssembler}. */
17893
17976
  units = new AccessUnitAssembler((drop) => this.reportDroppedUnit(drop));
17977
+ /** Whether a missing video datagram or incomplete unit invalidated the current reference chain. */
17978
+ awaitingKeyframeAfterGap = false;
17979
+ videoGapHandler = () => {
17980
+ this.units.discard();
17981
+ this.awaitingKeyframeAfterGap = true;
17982
+ };
17894
17983
  /** The channel inbound media must be tagged with, once {@link acceptsMedia} trusts the station's tag. */
17895
17984
  mediaChannel;
17896
17985
  tracedFirstVideoCommand = false;
@@ -17933,6 +18022,7 @@ var LiveStream = class extends EventEmitter3 {
17933
18022
  return this;
17934
18023
  this.listening = true;
17935
18024
  this.session.on("data", this.handler);
18025
+ this.session.on("videoGap", this.videoGapHandler);
17936
18026
  this.session.on("liveStartUnacknowledged", this.unackedHandler);
17937
18027
  this.sendStart();
17938
18028
  const keepAliveMs = this.opts.keepAliveMs ?? DEFAULT_KEEPALIVE_MS;
@@ -18030,6 +18120,8 @@ var LiveStream = class extends EventEmitter3 {
18030
18120
  return;
18031
18121
  this.listening = false;
18032
18122
  this.session.off("data", this.handler);
18123
+ this.session.off("videoGap", this.videoGapHandler);
18124
+ this.awaitingKeyframeAfterGap = false;
18033
18125
  this.session.off("liveStartUnacknowledged", this.unackedHandler);
18034
18126
  if (this.kaTimer)
18035
18127
  clearInterval(this.kaTimer);
@@ -18065,6 +18157,11 @@ var LiveStream = class extends EventEmitter3 {
18065
18157
  try {
18066
18158
  if (f.commandId === CMD_VIDEO_FRAME2) {
18067
18159
  for (const unit of this.units.push(f.data, (payload) => this.annexbOf(payload, f.signCode))) {
18160
+ if (this.awaitingKeyframeAfterGap) {
18161
+ if (!unit.keyframe)
18162
+ continue;
18163
+ this.awaitingKeyframeAfterGap = false;
18164
+ }
18068
18165
  if (!this.tracedFirstVideoUnit) {
18069
18166
  this.tracedFirstVideoUnit = true;
18070
18167
  this.trace({ phase: "first-video-unit", keyframe: unit.keyframe });
@@ -18092,7 +18189,7 @@ var LiveStream = class extends EventEmitter3 {
18092
18189
  if (!codec) {
18093
18190
  this.logger.debug(`[live] dropping audio frame: unknown codec id ${codecId ?? "missing"}`);
18094
18191
  } else {
18095
- this.emit("audio", { codec, data: audio });
18192
+ this.emit("audio", codec === "aac-eld" ? { codec, data: audio, config: AAC_ELD_AUDIO_SPECIFIC_CONFIG } : { codec, data: audio });
18096
18193
  }
18097
18194
  }
18098
18195
  }
@@ -18159,6 +18256,7 @@ var LiveStream = class extends EventEmitter3 {
18159
18256
  * otherwise silent in both directions: no frame reaches a consumer, and nothing states why.
18160
18257
  */
18161
18258
  reportDroppedUnit(drop) {
18259
+ this.awaitingKeyframeAfterGap = true;
18162
18260
  const message = `[live] dropped an incomplete access unit (${drop.carried} bytes in ${drop.chunks} frame(s), tail never arrived, ${drop.count} so far)`;
18163
18261
  if (drop.count === 1)
18164
18262
  this.logger.warn(message);
@@ -19828,7 +19926,8 @@ var AdtsFrameReader = class {
19828
19926
  };
19829
19927
 
19830
19928
  // dist/transport/p2p/talkback.js
19831
- var DEFAULT_HIGH_WATER_FRAMES = Math.ceil(2e3 / AAC_FRAME_MS);
19929
+ var HIGH_WATER_MS = 2e3;
19930
+ var TALKBACK_ELD_FRAME_MS = 32;
19832
19931
  var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
19833
19932
  var Talkback = class extends EventEmitter5 {
19834
19933
  sink;
@@ -19836,7 +19935,8 @@ var Talkback = class extends EventEmitter5 {
19836
19935
  reader = new AdtsFrameReader();
19837
19936
  queue = [];
19838
19937
  logger;
19839
- highWater;
19938
+ /** Playback duration of one queued frame, the pacer's step: 64 ms for `aac-lc`, 32 ms for `aac-eld`. */
19939
+ frameMs = AAC_FRAME_MS;
19840
19940
  idleTimeoutMs;
19841
19941
  timer;
19842
19942
  started = false;
@@ -19862,9 +19962,14 @@ var Talkback = class extends EventEmitter5 {
19862
19962
  this.sink = sink;
19863
19963
  this.opts = opts;
19864
19964
  this.logger = opts.logger ?? noopLogger;
19865
- this.highWater = opts.highWaterFrames ?? DEFAULT_HIGH_WATER_FRAMES;
19866
19965
  this.idleTimeoutMs = opts.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
19867
19966
  }
19967
+ /** Frames the pacing queue holds before a writable applies backpressure: {@link HIGH_WATER_MS} of this codec. */
19968
+ get highWater() {
19969
+ return this.opts.highWaterFrames ?? Math.ceil(HIGH_WATER_MS / this.frameMs);
19970
+ }
19971
+ /** The codec this talkback sends, set by {@link start}. */
19972
+ codec = "aac-lc";
19868
19973
  /** Frames still queued for the wire. */
19869
19974
  get pending() {
19870
19975
  return this.queue.length;
@@ -19873,25 +19978,33 @@ var Talkback = class extends EventEmitter5 {
19873
19978
  * Open the device's talkback path and begin the pacing tick. Throws when the topology's control
19874
19979
  * frame could not be sent — for a HomeBase-attached camera that means the level-2 key was never
19875
19980
  * negotiated, which would otherwise leave a silent session that accepts audio nobody hears.
19981
+ *
19982
+ * `codec` is the codec the camera's speaker plays; it fixes the input this talkback accepts and the pacing step.
19876
19983
  */
19877
- start() {
19984
+ start(codec) {
19878
19985
  if (this.started)
19879
19986
  return this;
19987
+ if (codec === "aac-eld" && this.opts.encoder) {
19988
+ throw new Error("talkback: this camera plays aac-eld; an AacEncoder produces aac-lc");
19989
+ }
19990
+ this.codec = codec;
19991
+ this.frameMs = codec === "aac-eld" ? TALKBACK_ELD_FRAME_MS : AAC_FRAME_MS;
19880
19992
  if (!this.sink.startTalkback(this.opts.channel, this.opts.homeBaseAttached)) {
19881
19993
  throw new Error(`talkback: could not open the audio path on channel ${this.opts.channel}`);
19882
19994
  }
19883
19995
  this.started = true;
19884
19996
  const now2 = Date.now();
19885
- this.nextDueAt = now2 + AAC_FRAME_MS;
19997
+ this.nextDueAt = now2 + this.frameMs;
19886
19998
  this.lastWriteAt = now2;
19887
- this.timer = setInterval(() => this.tick(), AAC_FRAME_MS);
19999
+ this.timer = setInterval(() => this.tick(), this.frameMs);
19888
20000
  this.timer.unref?.();
19889
20001
  this.sink.on?.("audioGap", this.onAudioGap);
19890
20002
  return this;
19891
20003
  }
19892
20004
  /**
19893
- * Queue audio. Bytes are ADTS AAC, or PCM when an encoder was supplied; either way the input is
19894
- * treated as a stream, so a chunk carrying part of a frame is held until the rest arrives.
20005
+ * Queue audio in the codec this talkback sends. For `aac-lc` the bytes are ADTS, or PCM when an encoder was
20006
+ * supplied, read as a stream, so a chunk carrying part of a frame is held until the rest arrives. For `aac-eld`
20007
+ * each call is one whole access unit; a unit over the device's length limit is dropped with an `error`.
19895
20008
  *
19896
20009
  * Audio written after {@link end} is dropped with an `error` rather than queued: `finished` has
19897
20010
  * either already fired or is owed on the frames written before it, so a late chunk would either play
@@ -19905,6 +20018,15 @@ var Talkback = class extends EventEmitter5 {
19905
20018
  return;
19906
20019
  }
19907
20020
  this.lastWriteAt = Date.now();
20021
+ if (this.codec === "aac-eld") {
20022
+ if (chunk.length > MAX_AUDIO_FRAME_BYTES) {
20023
+ this.fail(new Error(`talkback: frame of ${chunk.length} B exceeds the device's ${MAX_AUDIO_FRAME_BYTES} B limit`));
20024
+ return;
20025
+ }
20026
+ if (chunk.length)
20027
+ this.queue.push(chunk);
20028
+ return;
20029
+ }
19908
20030
  if (!this.opts.encoder) {
19909
20031
  this.enqueue(this.reader.push(chunk));
19910
20032
  return;
@@ -19973,14 +20095,14 @@ var Talkback = class extends EventEmitter5 {
19973
20095
  return;
19974
20096
  const now2 = Date.now();
19975
20097
  if (!this.queue.length) {
19976
- this.nextDueAt = now2 + AAC_FRAME_MS;
20098
+ this.nextDueAt = now2 + this.frameMs;
19977
20099
  this.idleCheck(now2);
19978
20100
  this.announceFinishIfDone();
19979
20101
  return;
19980
20102
  }
19981
20103
  while (this.queue.length && now2 >= this.nextDueAt) {
19982
20104
  const frame = this.queue.shift();
19983
- this.nextDueAt += AAC_FRAME_MS;
20105
+ this.nextDueAt += this.frameMs;
19984
20106
  try {
19985
20107
  this.sink.sendAudioFrame(this.opts.channel, frame);
19986
20108
  } catch (e) {
@@ -20038,9 +20160,11 @@ var Talkback = class extends EventEmitter5 {
20038
20160
  /**
20039
20161
  * A Writable over {@link write} that withholds its callback while the queue is at the high-water
20040
20162
  * mark — which is what turns `pipe()` from a file into playback at speed rather than a memory spike.
20163
+ * For `aac-eld` it is object-mode: each write is one access unit.
20041
20164
  */
20042
20165
  writable() {
20043
20166
  return new Writable({
20167
+ objectMode: this.codec === "aac-eld",
20044
20168
  write: (chunk, _enc, cb) => {
20045
20169
  this.write(chunk);
20046
20170
  if (this.queue.length < this.highWater)
@@ -20109,7 +20233,7 @@ var CODEC_BOXES = {
20109
20233
  h264: { sample: "avc1", config: "avcC" },
20110
20234
  h265: { sample: "hvc1", config: "hvcC" }
20111
20235
  };
20112
- var AAC_ELD_SAMPLES_PER_FRAME = 512;
20236
+ var AAC_ELD_SAMPLES_PER_FRAME = 480;
20113
20237
  var ADTS_FREQUENCY_INDEX_16K = 8;
20114
20238
  var ADTS_CHANNELS_MONO = 1;
20115
20239
  var Fmp4Muxer = class {
@@ -20127,6 +20251,8 @@ var Fmp4Muxer = class {
20127
20251
  lastVideoTimestampMs;
20128
20252
  audioRequested;
20129
20253
  audioCodec;
20254
+ /** Decoder config of an AAC-ELD track, taken from its frames; absent for AAC-LC, whose `esds` config is fixed. */
20255
+ audioConfig;
20130
20256
  audioDisabled = false;
20131
20257
  audioSamples = [];
20132
20258
  audioBaseDecodeTime = 0;
@@ -20193,7 +20319,10 @@ var Fmp4Muxer = class {
20193
20319
  }
20194
20320
  return void 0;
20195
20321
  }
20196
- /** Add one station-declared AAC access unit to the audio track. G.711 remains available via `live()`. */
20322
+ /**
20323
+ * Add one station-declared AAC access unit to the audio track: an ADTS frame for AAC-LC, a raw access unit
20324
+ * described by its frame's config for AAC-ELD. G.711 remains available via `live()`.
20325
+ */
20197
20326
  pushAudio(frame, timestampMs = now()) {
20198
20327
  if (!this.audioRequested || this.audioDisabled)
20199
20328
  return void 0;
@@ -20209,12 +20338,19 @@ var Fmp4Muxer = class {
20209
20338
  if (this.audioCodec && this.audioCodec !== frame.codec) {
20210
20339
  return this.disableAudio();
20211
20340
  }
20212
- const header = parseAdtsHeader(frame.data);
20213
- if (!header || header.frameLength > frame.data.length) {
20214
- throw new Error(`fMP4 muxer: ${frame.codec} frame is not a complete ADTS access unit`);
20215
- }
20216
- if (header.frequencyIndex !== ADTS_FREQUENCY_INDEX_16K || header.channels !== ADTS_CHANNELS_MONO) {
20217
- return this.disableAudio();
20341
+ let sample;
20342
+ if (frame.codec === "aac-eld") {
20343
+ this.audioConfig = frame.config;
20344
+ sample = frame.data;
20345
+ } else {
20346
+ const header = parseAdtsHeader(frame.data);
20347
+ if (!header || header.frameLength > frame.data.length) {
20348
+ throw new Error(`fMP4 muxer: ${frame.codec} frame is not a complete ADTS access unit`);
20349
+ }
20350
+ if (header.frequencyIndex !== ADTS_FREQUENCY_INDEX_16K || header.channels !== ADTS_CHANNELS_MONO) {
20351
+ return this.disableAudio();
20352
+ }
20353
+ sample = frame.data.subarray(header.headerLength, header.frameLength);
20218
20354
  }
20219
20355
  this.audioCodec = frame.codec;
20220
20356
  this.firstAudioTimestampMs ??= timestampMs;
@@ -20226,7 +20362,7 @@ var Fmp4Muxer = class {
20226
20362
  this.audioSamples[this.audioSamples.length - 1].duration = measured;
20227
20363
  }
20228
20364
  this.audioSamples.push({
20229
- data: frame.data.subarray(header.headerLength, header.frameLength),
20365
+ data: sample,
20230
20366
  duration: frame.codec === "aac-eld" ? AAC_ELD_SAMPLES_PER_FRAME : AAC_SAMPLES_PER_FRAME,
20231
20367
  keyframe: true
20232
20368
  });
@@ -20499,7 +20635,7 @@ var Fmp4Muxer = class {
20499
20635
  return box("mp4a", head, this.esds());
20500
20636
  }
20501
20637
  esds() {
20502
- const config = this.audioCodec === "aac-eld" ? Buffer.from([248, 240, 32]) : Buffer.from([20, 8]);
20638
+ const config = this.audioConfig ?? Buffer.from([20, 8]);
20503
20639
  const specific = descriptor(5, config);
20504
20640
  const decoder = descriptor(4, Buffer.concat([Buffer.from([64, 21, 0, 0, 0]), u32(64e3), u32(32e3), specific]));
20505
20641
  const sl = descriptor(6, Buffer.from([2]));
@@ -20756,6 +20892,30 @@ var P2P_STATION_WAITS = {
20756
20892
  level2Settle: LEVEL2_SETTLE_MS
20757
20893
  };
20758
20894
  var RTSP_URL_READ_TIMEOUT_MS = 12e3;
20895
+ var TALKBACK_CODEC_WAIT_MS = 3e3;
20896
+ var ELD_TALKBACK_MODELS = /* @__PURE__ */ new Set(["T8410C"]);
20897
+ function speakerCodec(consumer, talk, timeoutMs) {
20898
+ return new Promise((resolve) => {
20899
+ let timer;
20900
+ const settle = (codec) => {
20901
+ clearTimeout(timer);
20902
+ consumer.off("video", onVideo);
20903
+ consumer.off("audio", onAudio);
20904
+ consumer.off("stop", onStop);
20905
+ talk.off("stop", onStop);
20906
+ resolve(codec);
20907
+ };
20908
+ const onVideo = () => {
20909
+ timer ??= setTimeout(() => settle("aac-lc"), timeoutMs);
20910
+ };
20911
+ const onAudio = (frame) => settle(frame.codec === "aac-eld" ? "aac-eld" : "aac-lc");
20912
+ const onStop = () => settle("aac-lc");
20913
+ consumer.on("video", onVideo);
20914
+ consumer.on("audio", onAudio);
20915
+ consumer.on("stop", onStop);
20916
+ talk.once("stop", onStop);
20917
+ });
20918
+ }
20759
20919
  var SHARED_LIVE_OPT_KEYS = [
20760
20920
  "eccPrivateKey",
20761
20921
  "keepAliveMs",
@@ -21174,14 +21334,20 @@ var P2PCommandRouter = class _P2PCommandRouter {
21174
21334
  }
21175
21335
  }
21176
21336
  /**
21177
- * Restart a HomeBase. `RESTART_HUB` (1034) is a station-scalar on the broadcast channel 255: a
21178
- * level-2 frame whose body is `[u32 value][account_id padded]` — the same shape as the hub
21179
- * alarm-volume control. ✅ Wire-confirmed byte-exact from a capture of the app's own Restart
21180
- * (2026-08-03) and HW-tested: the captured frame carried value `0` and rebooted the hub. Replays
21181
- * like every other level-2 control, so a single dropped datagram doesn't lose it.
21337
+ * Restart the station that owns `sn`'s P2P session. `RESTART_HUB` (1034) is a station-scalar on the
21338
+ * broadcast channel 255 whose body is `[u32 value][account_id padded]`, value `0`. ✅ Wire-confirmed
21339
+ * byte-exact as a level-2 frame from a capture of the app's own HomeBase Restart (2026-08-03).
21340
+ *
21341
+ * The seal follows the session, as {@link sendBySessionLevel} defines it: a keyed session takes the
21342
+ * level-2 frame, a keyless one — a standalone camera, which never negotiates a key — the same body
21343
+ * sealed level-1. Both are replayed {@link DIRECT_CMD_SENDS}× at 200ms, as every other unacknowledged
21344
+ * control here is.
21182
21345
  */
21183
21346
  async rebootStation(sn) {
21184
- await this.replayLevel2Send(sn, `reboot ${sn}`, ({ session, accountId }) => session.sendRawLevel2Bytes(buildDirectBinaryBody(0, accountId), 255, P2P_ENVELOPE.RESTART_HUB, 8));
21347
+ await this.sendBySessionLevel(sn, {
21348
+ l2: (resolved) => this.replayLevel2Send(sn, `reboot ${sn}`, ({ session, accountId }) => session.sendRawLevel2Bytes(buildDirectBinaryBody(0, accountId), 255, P2P_ENVELOPE.RESTART_HUB, 8), resolved),
21349
+ l1: (resolved) => this.replayLevel2Send(sn, `reboot ${sn}`, ({ session, accountId }) => session.sendRawLevel1Bytes(buildDirectBinaryBody(0, accountId), 255, P2P_ENVELOPE.RESTART_HUB), resolved)
21350
+ });
21185
21351
  }
21186
21352
  /**
21187
21353
  * A {@link MediaProvider} bound to one serial — resolves the session then calls `p2p/media`.
@@ -21303,6 +21469,11 @@ var P2PCommandRouter = class _P2PCommandRouter {
21303
21469
  * stream costs nothing extra and a talkback on an otherwise idle camera opens the session it needs
21304
21470
  * instead of playing into silence.
21305
21471
  *
21472
+ * **On a model in {@link ELD_TALKBACK_MODELS}, the speaker plays the codec the camera sends.** So the first
21473
+ * audio frame of the media session this talkback holds decides its codec ({@link speakerCodec}), within
21474
+ * {@link TALKBACK_CODEC_WAIT_MS} of the session's first frame, and the claim is re-checked after that wait as
21475
+ * after the warm-up. Every other model opens `aac-lc` at once.
21476
+ *
21306
21477
  * The level-2 key is waited for softly: only the HomeBase-attached path requires it, and
21307
21478
  * {@link Talkback.start} reports that failure precisely, so a hard wait here would reject an
21308
21479
  * own-session camera that legitimately never negotiates one.
@@ -21372,7 +21543,11 @@ var P2PCommandRouter = class _P2PCommandRouter {
21372
21543
  consumer.on("stop", () => {
21373
21544
  void talk.stop().catch((e) => logger.warn?.(`talkback: stop for ${sn} failed: ${String(e)}`));
21374
21545
  });
21375
- return talk.start();
21546
+ const codec = ELD_TALKBACK_MODELS.has(this.recordFor(sn)?.model ?? "") ? await speakerCodec(consumer, talk, TALKBACK_CODEC_WAIT_MS) : "aac-lc";
21547
+ if (this.talkbacks.get(key) !== talk) {
21548
+ throw new Error(`talkback: ${sn} was closed while its speaker codec was being read`);
21549
+ }
21550
+ return talk.start(codec);
21376
21551
  } catch (e) {
21377
21552
  if (this.talkbacks.get(key) === talk)
21378
21553
  this.talkbacks.delete(key);
@@ -22357,6 +22532,1237 @@ var P2PCommandRouter = class _P2PCommandRouter {
22357
22532
  }
22358
22533
  };
22359
22534
 
22535
+ // dist/transport/rtc/session.js
22536
+ import { EventEmitter as EventEmitter9 } from "node:events";
22537
+
22538
+ // dist/transport/rtc/peer.js
22539
+ import { EventEmitter as EventEmitter7 } from "node:events";
22540
+
22541
+ // dist/transport/rtc/portal-packet.js
22542
+ var MAGIC2 = Buffer.from("XZYH", "ascii");
22543
+ var PORTAL_HEADER_LENGTH = 16;
22544
+ var PortalLinkType = {
22545
+ /** Command channel: requests out, acknowledgements back. */
22546
+ COMMAND: 1,
22547
+ /** Station-originated frames: pushes, notify payloads, control results. */
22548
+ NOTIFY: 3
22549
+ };
22550
+ function encodeLe(value, width) {
22551
+ const buf = Buffer.alloc(width);
22552
+ let v = value >>> 0;
22553
+ for (let i = 0; i < width; i++) {
22554
+ buf[i] = v & 255;
22555
+ v >>>= 8;
22556
+ }
22557
+ return buf;
22558
+ }
22559
+ function buildPortalHeader(commandId, paramLength, channel, segment, isResponse = 0, devType = 2) {
22560
+ const header = Buffer.alloc(PORTAL_HEADER_LENGTH);
22561
+ MAGIC2.copy(header, 0);
22562
+ encodeLe(commandId, 2).copy(header, 4);
22563
+ encodeLe(paramLength, 4).copy(header, 6);
22564
+ header[10] = 0;
22565
+ header[11] = segment & 255;
22566
+ header[12] = channel & 255;
22567
+ header[13] = 0;
22568
+ header[14] = isResponse & 255;
22569
+ header[15] = devType & 255;
22570
+ return header;
22571
+ }
22572
+ function parsePortalHeader(buf) {
22573
+ if (buf.length < PORTAL_HEADER_LENGTH || buf.subarray(0, 4).compare(MAGIC2) !== 0)
22574
+ return void 0;
22575
+ return {
22576
+ commandId: buf.readUInt16LE(4),
22577
+ paramLength: buf.readUInt32LE(6),
22578
+ segment: buf[11],
22579
+ channel: buf[12],
22580
+ isResponse: buf[14],
22581
+ devType: buf[15]
22582
+ };
22583
+ }
22584
+ function isPortalPacket(buf) {
22585
+ return buf.length >= PORTAL_HEADER_LENGTH && buf.subarray(0, 4).compare(MAGIC2) === 0;
22586
+ }
22587
+ function buildPortalPacket(req) {
22588
+ const body = Buffer.from(JSON.stringify(req.payload), "utf8");
22589
+ const header = buildPortalHeader(req.commandId, body.length, req.channel, req.segment, req.isResponse ?? 0, req.devType ?? 2);
22590
+ return Buffer.concat([header, body]);
22591
+ }
22592
+ function parseJsonBody(buf) {
22593
+ let text2 = buf.toString("utf8");
22594
+ while (text2.endsWith("\0"))
22595
+ text2 = text2.slice(0, -1);
22596
+ try {
22597
+ return JSON.parse(text2);
22598
+ } catch {
22599
+ return text2;
22600
+ }
22601
+ }
22602
+ function parsePortalPacket(buf, linkType = PortalLinkType.COMMAND) {
22603
+ const header = parsePortalHeader(buf);
22604
+ if (!header)
22605
+ return void 0;
22606
+ const body = buf.subarray(PORTAL_HEADER_LENGTH, PORTAL_HEADER_LENGTH + header.paramLength);
22607
+ if (linkType === PortalLinkType.NOTIFY) {
22608
+ const data = parseJsonBody(body);
22609
+ const cmd = typeof data === "object" && data !== null && "cmd" in data ? Number(data.cmd) : void 0;
22610
+ return {
22611
+ commandId: header.commandId,
22612
+ channel: header.channel,
22613
+ segment: header.segment,
22614
+ isResponse: header.isResponse,
22615
+ linkType,
22616
+ cmd,
22617
+ data
22618
+ };
22619
+ }
22620
+ return {
22621
+ commandId: header.commandId,
22622
+ channel: header.channel,
22623
+ segment: header.segment,
22624
+ isResponse: header.isResponse,
22625
+ linkType,
22626
+ errCode: body.length >= 4 ? body.readInt32LE(0) : -1,
22627
+ data: body.length > 4 ? parseJsonBody(body.subarray(4)) : void 0
22628
+ };
22629
+ }
22630
+ var SegmentCounter = class {
22631
+ current = 0;
22632
+ next() {
22633
+ this.current = this.current + 1 & 255;
22634
+ if (this.current === 0)
22635
+ this.current = 1;
22636
+ return this.current;
22637
+ }
22638
+ };
22639
+
22640
+ // dist/transport/rtc/ptcs-framer.js
22641
+ var MAGIC3 = Buffer.from("PTCS", "ascii");
22642
+ var PTCS_HEADER_LENGTH = 28;
22643
+ var PTCS_DEFAULT_PAYLOAD_BYTES = 1e3;
22644
+ var FLAG_BASE = 16384;
22645
+ var FLAG_LAST = 1024;
22646
+ var LENGTH_MASK = 1023;
22647
+ var PtcsChannel = {
22648
+ COMMAND: 0,
22649
+ NOTIFY: 2
22650
+ };
22651
+ function linkTypeForChannel(channel) {
22652
+ return channel === PtcsChannel.NOTIFY ? PortalLinkType.NOTIFY : PortalLinkType.COMMAND;
22653
+ }
22654
+ var PTCS_STALE_MS = 15e3;
22655
+ function parsePtcsHeader(packet) {
22656
+ if (packet.length < PTCS_HEADER_LENGTH || packet.subarray(0, 4).compare(MAGIC3) !== 0)
22657
+ return void 0;
22658
+ const flags = packet.readUInt16LE(18);
22659
+ return {
22660
+ channel: packet[5],
22661
+ sequence: packet.readUInt16LE(6),
22662
+ frameId: packet.readUInt32LE(8),
22663
+ frameLength: packet.readUInt32LE(12),
22664
+ index: packet.readUInt16LE(16),
22665
+ last: (flags & FLAG_LAST) !== 0,
22666
+ payloadLength: flags & LENGTH_MASK
22667
+ };
22668
+ }
22669
+ function packetize(frame, opts) {
22670
+ const size = opts.payloadBytes ?? PTCS_DEFAULT_PAYLOAD_BYTES;
22671
+ if (size <= 0 || size > LENGTH_MASK)
22672
+ throw new RangeError(`PTCS payload size ${size} out of range`);
22673
+ const channel = opts.channel ?? PtcsChannel.COMMAND;
22674
+ const count2 = Math.max(1, Math.ceil(frame.length / size));
22675
+ const sequence = (opts.sequence ?? 0) & 65535;
22676
+ const packets = [];
22677
+ for (let i = 0; i < count2; i++) {
22678
+ const chunk = frame.subarray(i * size, Math.min(frame.length, (i + 1) * size));
22679
+ const last = i === count2 - 1;
22680
+ const packet = Buffer.alloc(PTCS_HEADER_LENGTH + size);
22681
+ MAGIC3.copy(packet, 0);
22682
+ packet[4] = 3;
22683
+ packet[5] = channel & 255;
22684
+ packet.writeUInt16LE(sequence, 6);
22685
+ packet.writeUInt32LE(opts.frameId >>> 0, 8);
22686
+ packet.writeUInt32LE(frame.length >>> 0, 12);
22687
+ packet.writeUInt16LE(i, 16);
22688
+ packet.writeUInt16LE(FLAG_BASE | (last ? FLAG_LAST : 0) | chunk.length, 18);
22689
+ chunk.copy(packet, PTCS_HEADER_LENGTH);
22690
+ packets.push(packet);
22691
+ }
22692
+ return packets;
22693
+ }
22694
+ var PtcsReassembler = class {
22695
+ onFrame;
22696
+ now;
22697
+ partials = /* @__PURE__ */ new Map();
22698
+ constructor(onFrame, now2 = Date.now) {
22699
+ this.onFrame = onFrame;
22700
+ this.now = now2;
22701
+ }
22702
+ push(packet) {
22703
+ const h = parsePtcsHeader(packet);
22704
+ if (!h)
22705
+ return false;
22706
+ const body = packet.subarray(PTCS_HEADER_LENGTH, PTCS_HEADER_LENGTH + h.payloadLength);
22707
+ if (body.length !== h.payloadLength)
22708
+ return false;
22709
+ const key = `${h.channel}:${h.frameId}`;
22710
+ const now2 = this.now();
22711
+ let p = this.partials.get(key);
22712
+ if (!p) {
22713
+ p = { channel: h.channel, frameLength: h.frameLength, chunks: /* @__PURE__ */ new Map(), touched: now2 };
22714
+ this.partials.set(key, p);
22715
+ }
22716
+ p.touched = now2;
22717
+ p.chunks.set(h.index, Buffer.from(body));
22718
+ if (h.last)
22719
+ p.lastIndex = h.index;
22720
+ if (p.lastIndex === void 0)
22721
+ return true;
22722
+ let total = 0;
22723
+ const parts = [];
22724
+ for (let i = 0; i <= p.lastIndex; i++) {
22725
+ const c = p.chunks.get(i);
22726
+ if (!c)
22727
+ return true;
22728
+ parts.push(c);
22729
+ total += c.length;
22730
+ }
22731
+ this.partials.delete(key);
22732
+ if (total !== p.frameLength)
22733
+ return false;
22734
+ this.onFrame(Buffer.concat(parts, total), p.channel);
22735
+ return true;
22736
+ }
22737
+ /** Drop frames that stopped arriving; call periodically. */
22738
+ expire() {
22739
+ const now2 = this.now();
22740
+ for (const [key, p] of this.partials) {
22741
+ if (now2 - p.touched > PTCS_STALE_MS)
22742
+ this.partials.delete(key);
22743
+ }
22744
+ }
22745
+ };
22746
+ function frameIdClock(now2 = Date.now) {
22747
+ let last = 0;
22748
+ return () => {
22749
+ let id = now2() >>> 0;
22750
+ if (id <= last)
22751
+ id = last + 1 >>> 0;
22752
+ last = id;
22753
+ return id;
22754
+ };
22755
+ }
22756
+ var PtcsFramer = class {
22757
+ onWire;
22758
+ onFrame;
22759
+ reassembler;
22760
+ sweep;
22761
+ ready = false;
22762
+ nextFrameId = frameIdClock();
22763
+ sequence = 0;
22764
+ /** Arm the two callbacks; `sendFrame` may be called from here on. */
22765
+ init(onWirePacket, onFrame) {
22766
+ this.onWire = onWirePacket;
22767
+ this.onFrame = onFrame;
22768
+ this.reassembler = new PtcsReassembler((frame, channel) => this.onFrame?.(frame, linkTypeForChannel(channel)));
22769
+ this.sweep = setInterval(() => this.reassembler?.expire(), 1e3);
22770
+ this.sweep.unref?.();
22771
+ this.ready = true;
22772
+ }
22773
+ isReady() {
22774
+ return this.ready;
22775
+ }
22776
+ sendFrame(portalPacket) {
22777
+ if (!this.ready)
22778
+ throw new Error("PTCS framer not initialised");
22779
+ const packets = packetize(portalPacket, { frameId: this.nextFrameId(), sequence: this.sequence });
22780
+ this.sequence = this.sequence + 1 & 65535;
22781
+ for (const packet of packets)
22782
+ this.onWire?.(packet);
22783
+ }
22784
+ recvPacket(wirePacket) {
22785
+ if (!this.ready)
22786
+ return;
22787
+ if (isPortalPacket(wirePacket)) {
22788
+ this.onFrame?.(wirePacket, PortalLinkType.COMMAND);
22789
+ return;
22790
+ }
22791
+ this.reassembler?.push(wirePacket);
22792
+ }
22793
+ destroy() {
22794
+ this.ready = false;
22795
+ if (this.sweep)
22796
+ clearInterval(this.sweep);
22797
+ this.sweep = void 0;
22798
+ this.reassembler = void 0;
22799
+ this.onWire = void 0;
22800
+ this.onFrame = void 0;
22801
+ }
22802
+ };
22803
+
22804
+ // dist/transport/rtc/scall-sdp.js
22805
+ var HUB_SDP_MID = "2";
22806
+ var ANKER_MAX_MESSAGE_SIZE = 262144;
22807
+ function scallJsonToSdp(json, now2 = Date.now) {
22808
+ let sdp = "";
22809
+ sdp += "v=0\r\n";
22810
+ sdp += `o=- ${Math.floor(now2())} 1 IN IP4 127.0.0.1\r
22811
+ `;
22812
+ sdp += "s=Anker Webrtc Stream\r\n";
22813
+ sdp += "t=0 0\r\n";
22814
+ sdp += `a=group:BUNDLE ${HUB_SDP_MID}\r
22815
+ `;
22816
+ sdp += "a=msid-semantic: WMS\r\n";
22817
+ sdp += "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n";
22818
+ sdp += "c=IN IP4 127.0.0.1\r\n";
22819
+ sdp += `a=mid:${HUB_SDP_MID}\r
22820
+ `;
22821
+ sdp += "a=ice-options:trickle\r\n";
22822
+ if (json.ice?.ufrag)
22823
+ sdp += `a=ice-ufrag:${json.ice.ufrag}\r
22824
+ `;
22825
+ if (json.ice?.pwd)
22826
+ sdp += `a=ice-pwd:${json.ice.pwd}\r
22827
+ `;
22828
+ if (json.ice?.fingerprint) {
22829
+ const fp = json.ice.fingerprint.replace(/(.{2})(?=.)/g, "$1:");
22830
+ sdp += `a=fingerprint:${json.ice.fingerprint_type ?? "sha-256"} ${fp}\r
22831
+ `;
22832
+ }
22833
+ sdp += `a=setup:${json.setup ?? "actpass"}\r
22834
+ `;
22835
+ sdp += "a=sctp-port:5000\r\n";
22836
+ sdp += `a=max-message-size:${ANKER_MAX_MESSAGE_SIZE}\r
22837
+ `;
22838
+ for (const c of json.candidate ?? [])
22839
+ sdp += `a=candidate:${c}\r
22840
+ `;
22841
+ return sdp;
22842
+ }
22843
+ function sdpToScallJson(sdp) {
22844
+ const json = { ice: { ufrag: "", pwd: "", fingerprint: "" } };
22845
+ const setup = sdp.match(/a=setup:([^\r\n]+)/)?.[1];
22846
+ if (setup && setup !== "actpass")
22847
+ json.setup = setup;
22848
+ const ufrag = sdp.match(/a=ice-ufrag:([^\r\n]+)/)?.[1];
22849
+ if (ufrag)
22850
+ json.ice.ufrag = ufrag;
22851
+ const pwd = sdp.match(/a=ice-pwd:([^\r\n]+)/)?.[1];
22852
+ if (pwd)
22853
+ json.ice.pwd = pwd;
22854
+ const fp = sdp.match(/a=fingerprint:([^\s]+)\s+([^\r\n]+)/);
22855
+ if (fp?.[2]) {
22856
+ json.ice.fingerprint_type = fp[1];
22857
+ json.ice.fingerprint = fp[2].replace(/:/g, "");
22858
+ }
22859
+ const candidates = [];
22860
+ for (const line of sdp.split(/\r\n|\r|\n/)) {
22861
+ const m = line.match(/^a=candidate:(.+)/);
22862
+ if (m?.[1])
22863
+ candidates.push(m[1]);
22864
+ }
22865
+ if (candidates.length)
22866
+ json.candidate = candidates;
22867
+ return json;
22868
+ }
22869
+ function iceCandidateType(candidate) {
22870
+ return candidate.match(/typ (\w+)/)?.[1] ?? "unknown";
22871
+ }
22872
+ function pinMaxMessageSize(sdp) {
22873
+ return sdp.replace(/a=max-message-size:\d+/g, `a=max-message-size:${ANKER_MAX_MESSAGE_SIZE}`);
22874
+ }
22875
+ function forceDtlsRole(sdp, role) {
22876
+ if (/a=setup:(active|passive|actpass)/.test(sdp))
22877
+ return sdp.replace(/a=setup:(active|passive|actpass)/g, `a=setup:${role}`);
22878
+ return sdp.replace(/(m=application[^\r\n]*\r?\n)/, `$1a=setup:${role}\r
22879
+ `);
22880
+ }
22881
+ function toWireCandidate(candidate) {
22882
+ return candidate.trim().replace(/^a=/, "");
22883
+ }
22884
+
22885
+ // dist/transport/rtc/peer.js
22886
+ var DATA_CHANNEL_LABELS = ["WebrtcDataChannel", "audio", "idr", "video", "notify", "download"];
22887
+ var COMMAND_CHANNEL = DATA_CHANNEL_LABELS[0];
22888
+ var DATA_CHANNEL_IDS = {
22889
+ WebrtcDataChannel: 0,
22890
+ audio: 2,
22891
+ idr: 4,
22892
+ video: 6,
22893
+ notify: 8,
22894
+ download: 10
22895
+ };
22896
+ function turnServers(turn) {
22897
+ const both = (hostname, port) => [
22898
+ { hostname, port, username: turn.turn_user, password: turn.turn_password, relayType: "TurnUdp" },
22899
+ { hostname, port, username: turn.turn_user, password: turn.turn_password, relayType: "TurnTcp" }
22900
+ ];
22901
+ const servers = both(turn.turn_addr, turn.turn_port);
22902
+ if (turn.alt_turn_addr && turn.alt_turn_port)
22903
+ servers.push(...both(turn.alt_turn_addr, turn.alt_turn_port));
22904
+ return servers;
22905
+ }
22906
+ var UNBUILT_ARCHES = /* @__PURE__ */ new Set(["arm", "ia32"]);
22907
+ async function loadNativePeerFactory() {
22908
+ let ndc;
22909
+ try {
22910
+ ndc = await import("node-datachannel");
22911
+ } catch (err) {
22912
+ const message = UNBUILT_ARCHES.has(process.arch) ? `the WebRTC transport for a HomeBase S1 Pro (T9000) needs 'node-datachannel', which has no build for ${process.arch}; a 64-bit OS is needed to drive a T9000` : "the WebRTC transport for a HomeBase S1 Pro (T9000) needs the optional peer dependency 'node-datachannel' (`npm install node-datachannel`)";
22913
+ throw new Error(message, { cause: err });
22914
+ }
22915
+ return (name, config) => new ndc.PeerConnection(name, config);
22916
+ }
22917
+ var ANSWER_TIMEOUT_MS = 15e3;
22918
+ var RtcPeer = class extends EventEmitter7 {
22919
+ opts;
22920
+ pc;
22921
+ channels = /* @__PURE__ */ new Map();
22922
+ framer;
22923
+ wireTally = /* @__PURE__ */ new Map();
22924
+ commandOpen = false;
22925
+ remoteSet = false;
22926
+ handlingOffer = false;
22927
+ channelsCreated = false;
22928
+ gatheringDone = false;
22929
+ /** Set by the framer's wire callback when the native channel refused a packet mid-send. */
22930
+ wireSendFailed = false;
22931
+ pending = [];
22932
+ localAnswer;
22933
+ logger;
22934
+ constructor(opts = {}) {
22935
+ super();
22936
+ this.opts = opts;
22937
+ this.logger = opts.logger ?? noopLogger;
22938
+ }
22939
+ /** Create the native peer on the relay the hub granted in `scall 100`. */
22940
+ async init(turn) {
22941
+ if (this.pc)
22942
+ return;
22943
+ const createPeer = this.opts.createPeer ?? await loadNativePeerFactory();
22944
+ const config = {
22945
+ iceServers: turnServers(turn),
22946
+ iceTransportPolicy: "relay",
22947
+ maxMessageSize: ANKER_MAX_MESSAGE_SIZE,
22948
+ enableIceTcp: true
22949
+ };
22950
+ const pc = createPeer("eufy-sdk", config);
22951
+ this.pc = pc;
22952
+ pc.onLocalDescription((sdp, type) => {
22953
+ if (String(type).toLowerCase() === "answer" && this.localAnswer) {
22954
+ clearTimeout(this.localAnswer.timer);
22955
+ this.localAnswer.resolve(sdp);
22956
+ this.localAnswer = void 0;
22957
+ }
22958
+ });
22959
+ pc.onLocalCandidate((candidate) => {
22960
+ if (!candidate)
22961
+ return;
22962
+ if (!this.acceptsCandidate(candidate))
22963
+ return;
22964
+ this.emit("iceCandidate", candidate);
22965
+ });
22966
+ pc.onGatheringStateChange((state) => {
22967
+ if (state === "complete" && !this.gatheringDone) {
22968
+ this.gatheringDone = true;
22969
+ this.emit("iceGatheringComplete");
22970
+ }
22971
+ });
22972
+ pc.onStateChange((state) => {
22973
+ this.logger.debug(`[rtc] peer state ${state}`);
22974
+ this.emit("connectionState", state);
22975
+ });
22976
+ pc.onDataChannel((dc) => this.wireChannel(dc.getLabel(), dc));
22977
+ }
22978
+ /**
22979
+ * The hub offered: apply the offer, declare the channels, return the answer SDP to signal back.
22980
+ *
22981
+ * The offer is pinned to `passive` before it is applied, so the native peer has one legal answer,
22982
+ * `active`: the role is fixed where it is decided, since rewriting the answer afterwards would change
22983
+ * only what is announced. The offer goes in before the channels are declared: `createDataChannel` on
22984
+ * a peer without a remote description starts its own negotiation and leaves it in `have-local-offer`.
22985
+ * The data channels need no m-line of their own; the offer's SCTP m-line carries them. Only an ANSWER
22986
+ * is taken as the local description: one read in `have-local-offer` is an offer.
22987
+ */
22988
+ async handleRemoteOffer(offerSdp) {
22989
+ const pc = this.pc;
22990
+ if (!pc)
22991
+ throw new Error("RTC peer not initialised");
22992
+ if (this.handlingOffer)
22993
+ throw new Error("RTC peer already handling an offer");
22994
+ this.handlingOffer = true;
22995
+ try {
22996
+ const offer = forceDtlsRole(offerSdp, "passive");
22997
+ const answerWait = new Promise((resolve, reject) => {
22998
+ const timer = setTimeout(() => {
22999
+ this.localAnswer = void 0;
23000
+ reject(new Error("timed out waiting for the local SDP answer"));
23001
+ }, ANSWER_TIMEOUT_MS);
23002
+ this.localAnswer = { resolve, reject, timer };
23003
+ });
23004
+ pc.setRemoteDescription(offer, "offer");
23005
+ this.remoteSet = true;
23006
+ this.createChannels();
23007
+ const local = pc.localDescription();
23008
+ let answer = String(local?.type ?? "").toLowerCase() === "answer" ? local?.sdp ?? "" : "";
23009
+ if (!answer)
23010
+ answer = await answerWait;
23011
+ else if (this.localAnswer) {
23012
+ clearTimeout(this.localAnswer.timer);
23013
+ this.localAnswer = void 0;
23014
+ }
23015
+ this.flushPending();
23016
+ return pinMaxMessageSize(answer);
23017
+ } finally {
23018
+ this.handlingOffer = false;
23019
+ }
23020
+ }
23021
+ addRemoteCandidate(candidate) {
23022
+ if (!this.pc)
23023
+ return;
23024
+ if (!this.acceptsCandidate(candidate))
23025
+ return;
23026
+ if (!this.remoteSet || this.handlingOffer) {
23027
+ this.pending.push(candidate);
23028
+ return;
23029
+ }
23030
+ this.addNow(candidate);
23031
+ }
23032
+ /**
23033
+ * Send one portal packet on the command channel, through the framer. False when the channel is not
23034
+ * usable or the native send refused a wire packet, so a dropped frame does not read as success.
23035
+ */
23036
+ sendCommand(portalPacket) {
23037
+ const dc = this.channels.get(COMMAND_CHANNEL);
23038
+ if (!dc?.isOpen() || !this.commandOpen || !this.framer?.isReady())
23039
+ return false;
23040
+ this.wireSendFailed = false;
23041
+ try {
23042
+ this.framer.sendFrame(portalPacket);
23043
+ } catch (e) {
23044
+ this.logger.warn(`[rtc] command send failed: ${e instanceof Error ? e.message : String(e)}`);
23045
+ return false;
23046
+ }
23047
+ return !this.wireSendFailed;
23048
+ }
23049
+ /** Tear the peer down. A pending answer is rejected, so a `handleRemoteOffer` in flight settles. */
23050
+ close() {
23051
+ this.framer?.destroy();
23052
+ this.framer = void 0;
23053
+ if (this.localAnswer) {
23054
+ clearTimeout(this.localAnswer.timer);
23055
+ const pending = this.localAnswer;
23056
+ this.localAnswer = void 0;
23057
+ pending.reject(new Error("RTC peer closed while waiting for the local SDP answer"));
23058
+ }
23059
+ this.commandOpen = false;
23060
+ this.gatheringDone = false;
23061
+ this.pc?.close();
23062
+ this.pc = void 0;
23063
+ this.channels.clear();
23064
+ this.channelsCreated = false;
23065
+ this.remoteSet = false;
23066
+ this.pending.length = 0;
23067
+ }
23068
+ acceptsCandidate(candidate) {
23069
+ return iceCandidateType(candidate) === "relay";
23070
+ }
23071
+ createChannels() {
23072
+ if (!this.pc || this.channelsCreated)
23073
+ return;
23074
+ this.channelsCreated = true;
23075
+ for (const label of DATA_CHANNEL_LABELS) {
23076
+ const dc = this.pc.createDataChannel(label, { id: DATA_CHANNEL_IDS[label], unordered: false });
23077
+ this.wireChannel(label, dc);
23078
+ }
23079
+ }
23080
+ /**
23081
+ * Wire one data channel. Every channel feeds the framer once the command channel has opened it; a
23082
+ * message before that has nothing to reassemble into and is dropped.
23083
+ */
23084
+ wireChannel(label, dc) {
23085
+ if (this.channels.has(label))
23086
+ return;
23087
+ this.channels.set(label, dc);
23088
+ dc.onOpen(() => {
23089
+ this.logger.debug(`[rtc] data channel open ${label}`);
23090
+ if (label !== COMMAND_CHANNEL)
23091
+ return;
23092
+ if (!this.framer) {
23093
+ const framer = new PtcsFramer();
23094
+ framer.init((packet) => {
23095
+ if (!dc.isOpen() || !dc.sendMessageBinary(packet))
23096
+ this.wireSendFailed = true;
23097
+ }, (frame, linkType) => this.emit("data", frame, linkType));
23098
+ this.framer = framer;
23099
+ }
23100
+ this.commandOpen = true;
23101
+ this.emit("commandChannelOpen");
23102
+ });
23103
+ dc.onClosed(() => {
23104
+ this.logger.debug(`[rtc] data channel closed ${label}`);
23105
+ if (label !== COMMAND_CHANNEL)
23106
+ return;
23107
+ const wasOpen = this.commandOpen;
23108
+ this.commandOpen = false;
23109
+ if (wasOpen)
23110
+ this.emit("commandChannelClosed");
23111
+ });
23112
+ dc.onError((err) => this.emit("error", new Error(`RTC data channel ${label}: ${err}`)));
23113
+ dc.onMessage((msg) => {
23114
+ const buf = typeof msg === "string" ? Buffer.from(msg) : Buffer.isBuffer(msg) ? msg : Buffer.from(msg);
23115
+ const n = (this.wireTally.get(label) ?? 0) + 1;
23116
+ this.wireTally.set(label, n);
23117
+ if (n <= 3 || n % 100 === 0) {
23118
+ this.logger.debug(`[rtc] wire ${label} #${n} ${buf.length}B ${buf.subarray(0, 8).toString("hex")}`);
23119
+ }
23120
+ this.framer?.recvPacket(buf);
23121
+ });
23122
+ }
23123
+ addNow(candidate) {
23124
+ try {
23125
+ this.pc?.addRemoteCandidate(candidate, HUB_SDP_MID);
23126
+ } catch (e) {
23127
+ this.logger.warn(`[rtc] addRemoteCandidate failed: ${e instanceof Error ? e.message : String(e)}`);
23128
+ }
23129
+ }
23130
+ flushPending() {
23131
+ const queued = this.pending.splice(0);
23132
+ for (const c of queued)
23133
+ this.addNow(c);
23134
+ }
23135
+ };
23136
+
23137
+ // dist/transport/rtc/signaling.js
23138
+ import { EventEmitter as EventEmitter8 } from "node:events";
23139
+ import { createHmac as createHmac3, randomUUID as randomUUID2 } from "node:crypto";
23140
+ var RTC_WS_PATH = "/v1/rtc/ws/join?reqtype=nvr";
23141
+ var RTC_SIGN_PATH = "/v1/smart/nvr/ws/sign";
23142
+ var PORTAL_ORIGIN = "https://security.eufy.com";
23143
+ var SIGNALING_KEEPALIVE_MS = 25e3;
23144
+ var SIGNALING_CONNECT_TIMEOUT_MS = 15e3;
23145
+ var SOURCE = "WEB";
23146
+ function sessionAccount(channelId, adminUserId, ts, authToken) {
23147
+ return createHmac3("sha256", authToken).update(`${channelId}${adminUserId}${ts}`).digest("hex");
23148
+ }
23149
+ var WS_OPEN = 1;
23150
+ var defaultSocket = (url, init) => new WebSocket(url, {
23151
+ protocols: init.protocols,
23152
+ headers: { Origin: init.origin }
23153
+ });
23154
+ var RtcSignalingClient = class extends EventEmitter8 {
23155
+ opts;
23156
+ ws;
23157
+ sign;
23158
+ keepalive;
23159
+ wsUrl;
23160
+ signUrl;
23161
+ wsRegion;
23162
+ fetchImpl;
23163
+ createSocket;
23164
+ logger;
23165
+ now;
23166
+ makeMsgId;
23167
+ constructor(opts) {
23168
+ super();
23169
+ this.opts = opts;
23170
+ const prefix = (opts.shard.split("-")[0] || "us").toLowerCase();
23171
+ const smartHost = prefix === "us" ? "security-smart.eufylife.com" : `security-smart-${prefix}.eufylife.com`;
23172
+ this.wsUrl = `wss://${smartHost}${RTC_WS_PATH}`;
23173
+ this.signUrl = `https://${smartHost}${RTC_SIGN_PATH}`;
23174
+ this.wsRegion = prefix.toUpperCase();
23175
+ this.fetchImpl = opts.fetch ?? fetch;
23176
+ this.createSocket = opts.createSocket ?? defaultSocket;
23177
+ this.logger = opts.logger ?? noopLogger;
23178
+ this.now = opts.now ?? Date.now;
23179
+ this.makeMsgId = opts.makeMsgId ?? (() => randomUUID2().replace(/-/g, ""));
23180
+ }
23181
+ get isOpen() {
23182
+ return this.ws?.readyState === WS_OPEN;
23183
+ }
23184
+ /** Step 1: the sign blob the socket and every auth message carry. A non-JSON body is reported by status. */
23185
+ async fetchSign() {
23186
+ const res = await this.fetchImpl(this.signUrl, {
23187
+ headers: {
23188
+ "Web-Country": this.opts.country.toUpperCase(),
23189
+ "X-Auth-Token": this.opts.authToken,
23190
+ "App-Name": "eufy_mega",
23191
+ "Model-Type": "WEB",
23192
+ GToken: this.opts.gtoken,
23193
+ Origin: PORTAL_ORIGIN
23194
+ }
23195
+ });
23196
+ const body = await res.json().catch(() => ({})) ?? {};
23197
+ if (!res.ok || body.code !== 0 || !body.data) {
23198
+ throw new Error(`RTC sign for ${this.opts.stationSn} refused: HTTP ${res.status} code ${body.code ?? "?"} ${body.msg ?? ""}`.trim());
23199
+ }
23200
+ this.sign = body.data;
23201
+ return body.data;
23202
+ }
23203
+ /**
23204
+ * Step 2: open the socket and send the first auth; resolves on `open`. A socket that closes or errors
23205
+ * before it ever opened rejects, so the call always settles.
23206
+ */
23207
+ async connect() {
23208
+ if (this.ws)
23209
+ return;
23210
+ const sign = this.sign ?? await this.fetchSign();
23211
+ const auth = {
23212
+ region: this.wsRegion,
23213
+ type: "NVR",
23214
+ sn: this.opts.stationSn,
23215
+ token: this.opts.authToken,
23216
+ gtoken: this.opts.gtoken,
23217
+ sign,
23218
+ appName: "eufy_mega",
23219
+ modelType: "WEB"
23220
+ };
23221
+ const protocols = ["v1", Buffer.from(JSON.stringify(auth)).toString("base64url")];
23222
+ this.logger.debug(`[rtc] ${this.opts.stationSn} signalling connect ${this.wsUrl}`);
23223
+ await new Promise((resolve, reject) => {
23224
+ const timer = setTimeout(() => {
23225
+ reject(new Error(`RTC signalling connect timeout after ${SIGNALING_CONNECT_TIMEOUT_MS}ms`));
23226
+ this.close();
23227
+ }, SIGNALING_CONNECT_TIMEOUT_MS);
23228
+ const ws = this.createSocket(this.wsUrl, { protocols, origin: PORTAL_ORIGIN });
23229
+ this.ws = ws;
23230
+ let opened = false;
23231
+ ws.addEventListener("open", () => {
23232
+ opened = true;
23233
+ clearTimeout(timer);
23234
+ this.sendAuth(sign);
23235
+ this.startKeepalive();
23236
+ this.emit("open");
23237
+ resolve();
23238
+ });
23239
+ ws.addEventListener("message", (ev) => {
23240
+ void this.handleWireMessage(ev.data);
23241
+ });
23242
+ ws.addEventListener("close", (ev) => {
23243
+ clearTimeout(timer);
23244
+ this.stopKeepalive();
23245
+ this.ws = void 0;
23246
+ const code = ev.code ?? 1006;
23247
+ const reason = ev.reason ?? "";
23248
+ this.logger.debug(`[rtc] ${this.opts.stationSn} signalling closed ${code} ${reason}`);
23249
+ if (!opened)
23250
+ reject(new Error(`RTC signalling closed before open: ${code} ${reason}`.trim()));
23251
+ this.emit("close", code, reason);
23252
+ });
23253
+ ws.addEventListener("error", (ev) => {
23254
+ clearTimeout(timer);
23255
+ const detail = ev ?? {};
23256
+ const cause = detail.error?.message ?? detail.error?.code ?? detail.message ?? "";
23257
+ reject(new Error(`RTC signalling socket error${cause ? ": " + cause : ""}`));
23258
+ });
23259
+ });
23260
+ }
23261
+ /** `action 1`, also what keeps the socket alive when re-sent. */
23262
+ sendAuth(sign) {
23263
+ const s = sign ?? this.sign;
23264
+ if (!s)
23265
+ throw new Error("RTC signalling: no sign to authenticate with");
23266
+ this.sendEnvelope("0", {
23267
+ code: 200,
23268
+ action: 1,
23269
+ data: s,
23270
+ sn: this.opts.stationSn,
23271
+ source: SOURCE,
23272
+ ts: Math.floor(this.now() / 1e3)
23273
+ });
23274
+ }
23275
+ /**
23276
+ * `action 3`, a session message on channel 0, the hub's own session; `scall` opens the negotiation.
23277
+ * `subSn` is empty for the hub's session.
23278
+ */
23279
+ sendSession(dataType, payload = {}) {
23280
+ const channelId = 0;
23281
+ const ts = Math.floor(this.now() / 1e3);
23282
+ const inner = {
23283
+ code: 200,
23284
+ action: 3,
23285
+ sessionId: this.sign,
23286
+ sn: this.opts.stationSn,
23287
+ subSn: "",
23288
+ channelId,
23289
+ isResponse: 0,
23290
+ dataType,
23291
+ source: SOURCE,
23292
+ ts,
23293
+ data: JSON.stringify({
23294
+ timestamp: ts,
23295
+ account: sessionAccount(channelId, this.opts.adminUserId, ts, this.opts.authToken),
23296
+ ...payload
23297
+ })
23298
+ };
23299
+ this.sendEnvelope(`${this.opts.authToken}_${this.makeMsgId()}`, inner);
23300
+ }
23301
+ sendCall() {
23302
+ this.sendSession("scall");
23303
+ }
23304
+ sendAck() {
23305
+ this.sendSession("ack");
23306
+ }
23307
+ /** The SDP answer, as scall JSON text, in an `info`. */
23308
+ sendInfoSdp(scallJson) {
23309
+ this.sendSession("info", { sdp: scallJson });
23310
+ }
23311
+ /** Trickle a candidate on the session's channel, like its SDP answer. An empty candidate ends them. */
23312
+ sendInfoCandidate(candidate) {
23313
+ this.sendSession("info", { candidate });
23314
+ }
23315
+ sendHangup() {
23316
+ this.sendSession("hangup");
23317
+ }
23318
+ close() {
23319
+ this.stopKeepalive();
23320
+ const ws = this.ws;
23321
+ this.ws = void 0;
23322
+ try {
23323
+ ws?.close();
23324
+ } catch {
23325
+ }
23326
+ }
23327
+ startKeepalive() {
23328
+ this.stopKeepalive();
23329
+ this.keepalive = setInterval(() => {
23330
+ if (!this.isOpen)
23331
+ return;
23332
+ try {
23333
+ this.sendAuth();
23334
+ } catch (e) {
23335
+ this.logger.warn(`[rtc] ${this.opts.stationSn} signalling keepalive failed`, e);
23336
+ }
23337
+ }, SIGNALING_KEEPALIVE_MS);
23338
+ this.keepalive.unref?.();
23339
+ }
23340
+ stopKeepalive() {
23341
+ if (this.keepalive)
23342
+ clearInterval(this.keepalive);
23343
+ this.keepalive = void 0;
23344
+ }
23345
+ sendEnvelope(msgid, inner) {
23346
+ if (!this.isOpen || !this.ws)
23347
+ throw new Error("RTC signalling not connected");
23348
+ const envelope = { msgid, data: JSON.stringify(inner) };
23349
+ this.ws.send(JSON.stringify(envelope));
23350
+ }
23351
+ async handleWireMessage(raw) {
23352
+ let text2;
23353
+ if (typeof raw === "string")
23354
+ text2 = raw;
23355
+ else if (Buffer.isBuffer(raw))
23356
+ text2 = raw.toString("utf8");
23357
+ else if (raw instanceof ArrayBuffer)
23358
+ text2 = Buffer.from(raw).toString("utf8");
23359
+ else if (typeof raw?.text === "function")
23360
+ text2 = await raw.text();
23361
+ else
23362
+ return;
23363
+ let envelope;
23364
+ let inner;
23365
+ try {
23366
+ envelope = JSON.parse(text2);
23367
+ if (typeof envelope?.data !== "string")
23368
+ return;
23369
+ inner = JSON.parse(envelope.data);
23370
+ } catch {
23371
+ return;
23372
+ }
23373
+ this.emit("message", inner, envelope);
23374
+ }
23375
+ };
23376
+
23377
+ // dist/transport/rtc/session.js
23378
+ var AUTH_TIMEOUT_MS = 15e3;
23379
+ var RtcSession = class extends EventEmitter9 {
23380
+ opts;
23381
+ signaling;
23382
+ peer;
23383
+ logger;
23384
+ turn;
23385
+ authOk = false;
23386
+ authWaiter;
23387
+ connected = false;
23388
+ closed = false;
23389
+ closeAnnounced = false;
23390
+ sdpHandled = false;
23391
+ chain = Promise.resolve();
23392
+ constructor(opts) {
23393
+ super();
23394
+ this.opts = opts;
23395
+ this.logger = opts.logger ?? noopLogger;
23396
+ this.signaling = (opts.createSignaling ?? ((o) => new RtcSignalingClient(o)))(opts);
23397
+ this.peer = (opts.createPeer ?? ((o) => new RtcPeer(o)))({ logger: this.logger, ...opts.peer });
23398
+ this.signaling.on("message", (inner) => {
23399
+ this.chain = this.chain.then(() => this.onSignaling(inner)).catch((e) => {
23400
+ this.emit("error", e instanceof Error ? e : new Error(String(e)));
23401
+ });
23402
+ });
23403
+ this.signaling.on("close", () => {
23404
+ this.connected = false;
23405
+ this.announceClose();
23406
+ });
23407
+ this.signaling.on("error", (e) => this.emit("error", e));
23408
+ this.peer.on("iceCandidate", (c) => this.signaling.sendInfoCandidate(toWireCandidate(c)));
23409
+ this.peer.on("iceGatheringComplete", () => this.signaling.sendInfoCandidate(""));
23410
+ this.peer.on("commandChannelOpen", () => {
23411
+ if (this.connected)
23412
+ return;
23413
+ this.connected = true;
23414
+ this.logger.debug(`[rtc] ${this.opts.stationSn} command channel open`);
23415
+ this.emit("connected");
23416
+ });
23417
+ this.peer.on("commandChannelClosed", () => {
23418
+ if (!this.connected)
23419
+ return;
23420
+ this.connected = false;
23421
+ this.logger.debug(`[rtc] ${this.opts.stationSn} command channel closed`);
23422
+ this.announceClose();
23423
+ });
23424
+ this.peer.on("connectionState", (state) => {
23425
+ if ((state === "failed" || state === "closed") && this.connected) {
23426
+ this.connected = false;
23427
+ this.announceClose();
23428
+ }
23429
+ });
23430
+ this.peer.on("error", (e) => this.emit("error", e));
23431
+ this.peer.on("data", (frame, linkType) => this.emit("commandData", frame, linkType));
23432
+ }
23433
+ get isConnected() {
23434
+ return this.connected;
23435
+ }
23436
+ /**
23437
+ * Start the sequence; resolves once `scall` is sent. `connected` fires when the channel opens. A session
23438
+ * closed by the time the sign fetch or the auth completes rejects instead of opening the socket or
23439
+ * placing the call.
23440
+ */
23441
+ async connect() {
23442
+ await this.signaling.fetchSign();
23443
+ if (this.closed)
23444
+ throw new Error("RTC session closed before the call was placed");
23445
+ await this.signaling.connect();
23446
+ await this.waitForAuth();
23447
+ if (this.closed)
23448
+ throw new Error("RTC session closed before the call was placed");
23449
+ this.logger.debug(`[rtc] ${this.opts.stationSn} authenticated \u2014 scall`);
23450
+ this.signaling.sendCall();
23451
+ }
23452
+ /** Send one portal packet; false when the command channel isn't open. */
23453
+ sendCommand(portalPacket) {
23454
+ return this.peer.sendCommand(portalPacket);
23455
+ }
23456
+ /**
23457
+ * Hang up and tear both sides down; `close` fires once, here if nothing announced it before. A
23458
+ * `connect()` still waiting for the signalling auth is rejected and its timer stopped.
23459
+ */
23460
+ close() {
23461
+ if (this.closed)
23462
+ return;
23463
+ this.closed = true;
23464
+ this.connected = false;
23465
+ try {
23466
+ if (this.signaling.isOpen)
23467
+ this.signaling.sendHangup();
23468
+ } catch {
23469
+ }
23470
+ this.signaling.close();
23471
+ this.peer.close();
23472
+ this.settleAuth(new Error("RTC session closed while waiting for signalling auth"));
23473
+ this.announceClose();
23474
+ }
23475
+ announceClose() {
23476
+ if (this.closeAnnounced)
23477
+ return;
23478
+ this.closeAnnounced = true;
23479
+ this.emit("close");
23480
+ }
23481
+ waitForAuth() {
23482
+ if (this.authOk)
23483
+ return Promise.resolve();
23484
+ return new Promise((resolve, reject) => {
23485
+ const timer = setTimeout(() => {
23486
+ this.authWaiter = void 0;
23487
+ reject(new Error("RTC signalling auth timeout"));
23488
+ }, AUTH_TIMEOUT_MS);
23489
+ this.authWaiter = { resolve, reject, timer };
23490
+ });
23491
+ }
23492
+ /** Settle a pending auth wait: resolve it, or reject it with `err`; either way its timer stops. */
23493
+ settleAuth(err) {
23494
+ const waiter = this.authWaiter;
23495
+ if (!waiter)
23496
+ return;
23497
+ this.authWaiter = void 0;
23498
+ clearTimeout(waiter.timer);
23499
+ if (err)
23500
+ waiter.reject(err);
23501
+ else
23502
+ waiter.resolve();
23503
+ }
23504
+ async onSignaling(inner) {
23505
+ if (inner.action === 1 && inner.code === 200) {
23506
+ this.authOk = true;
23507
+ this.settleAuth();
23508
+ }
23509
+ if (!inner.data)
23510
+ return;
23511
+ let payload;
23512
+ try {
23513
+ payload = JSON.parse(inner.data);
23514
+ } catch {
23515
+ return;
23516
+ }
23517
+ switch (inner.dataType) {
23518
+ case "scall":
23519
+ case "call":
23520
+ await this.onCall(payload);
23521
+ return;
23522
+ case "info":
23523
+ await this.onInfo(payload);
23524
+ return;
23525
+ case "hangup":
23526
+ this.logger.debug(`[rtc] ${this.opts.stationSn} hub hung up`);
23527
+ return;
23528
+ default:
23529
+ return;
23530
+ }
23531
+ }
23532
+ /** A `scall` status: `100` grants the relay, `200` is acknowledged, `486`/`408` fail the session. */
23533
+ async onCall(payload) {
23534
+ if (this.closed)
23535
+ return;
23536
+ const status = payload.status;
23537
+ if (status === 100 && payload.turn) {
23538
+ this.turn = payload.turn;
23539
+ await this.peer.init(payload.turn);
23540
+ return;
23541
+ }
23542
+ if (status === 200) {
23543
+ this.signaling.sendAck();
23544
+ return;
23545
+ }
23546
+ if (status === 486 || status === 408) {
23547
+ this.emit("error", new Error(`RTC ${this.opts.stationSn} scall answered ${status}`));
23548
+ this.close();
23549
+ }
23550
+ }
23551
+ /**
23552
+ * An `info`: trickle ICE, in either of the two shapes the hub sends, or the hub's SDP offer. The offer
23553
+ * is answered only once a TURN grant is in: the peer is relay-only, so an offer ahead of `scall 100`
23554
+ * is reported and left unanswered.
23555
+ */
23556
+ async onInfo(payload) {
23557
+ if (this.closed)
23558
+ return;
23559
+ if (payload.format === "CANDIDATE") {
23560
+ if (payload.value)
23561
+ this.peer.addRemoteCandidate(payload.value);
23562
+ return;
23563
+ }
23564
+ if (payload.candidate !== void 0) {
23565
+ if (payload.candidate)
23566
+ this.peer.addRemoteCandidate(payload.candidate);
23567
+ return;
23568
+ }
23569
+ const sdpText = payload.value ?? payload.sdp;
23570
+ if (!sdpText || payload.format !== "SDP" && !payload.sdp)
23571
+ return;
23572
+ if (this.sdpHandled)
23573
+ return;
23574
+ if (!this.turn) {
23575
+ this.emit("error", new Error(`RTC ${this.opts.stationSn} offered before granting a relay`));
23576
+ return;
23577
+ }
23578
+ this.sdpHandled = true;
23579
+ let offer;
23580
+ try {
23581
+ offer = scallJsonToSdp(JSON.parse(sdpText));
23582
+ } catch {
23583
+ offer = sdpText;
23584
+ }
23585
+ const answer = await this.peer.handleRemoteOffer(offer);
23586
+ this.signaling.sendInfoSdp(JSON.stringify(sdpToScallJson(answer)));
23587
+ this.logger.debug(`[rtc] ${this.opts.stationSn} answered the hub's offer`);
23588
+ }
23589
+ };
23590
+
23591
+ // dist/transport/rtc/command-router.js
23592
+ var PORTAL_CMD_SET_PAYLOAD = 1350;
23593
+ var PORTAL_CMD_CONTROL_PAYLOAD = 1700;
23594
+ var PORTAL_CMD_NOTIFY_PAYLOAD = 1351;
23595
+ var PORTAL_STATION_CHANNEL = 255;
23596
+ var ACK_TIMEOUT_MS = 8e3;
23597
+ var CONNECT_TIMEOUT_MS2 = 12e3;
23598
+ var IDLE_CLOSE_MS = 6e4;
23599
+ var RtcCommandRouter = class {
23600
+ deps;
23601
+ sessions = /* @__PURE__ */ new Map();
23602
+ constructor(deps) {
23603
+ this.deps = deps;
23604
+ }
23605
+ async dispatchCommand(route, cmd) {
23606
+ if (cmd.kind !== "set-payload" && cmd.kind !== "set-json") {
23607
+ throw new Error(`rtc: ${cmd.kind} is not routable over the T9000 control channel (only set-payload or set-json)`);
23608
+ }
23609
+ const identity = this.deps.identity();
23610
+ if (!identity)
23611
+ throw new Error(`rtc: not logged in, cannot drive ${route.stationSn}`);
23612
+ const { stationSn } = route;
23613
+ const adminUserId = route.adminUserId || identity.userId;
23614
+ const channel = route.attached ? cmd.channel : PORTAL_STATION_CHANNEL;
23615
+ const st = await this.stationSession(stationSn, adminUserId, identity);
23616
+ const outerCmd = cmd.kind === "set-json" ? PORTAL_CMD_CONTROL_PAYLOAD : PORTAL_CMD_SET_PAYLOAD;
23617
+ const innerCmd = cmd.kind === "set-json" ? cmd.param : cmd.cmd;
23618
+ const payload = cmd.kind === "set-json" ? { account_id: adminUserId, cmd: cmd.param, commandType: cmd.param, data: cmd.data } : { account_id: adminUserId, cmd: cmd.cmd, mValue3: cmd.mValue3 ?? 0, payload: cmd.payload };
23619
+ const segment = st.seg.next();
23620
+ const packet = buildPortalPacket({ commandId: outerCmd, channel, segment, payload });
23621
+ const run = st.queue.then(() => this.sendAwaitAck(stationSn, st, packet, outerCmd, innerCmd, channel, segment));
23622
+ st.queue = run.catch(() => void 0);
23623
+ return run;
23624
+ }
23625
+ /** Tear down every station session (logout / shutdown). */
23626
+ close() {
23627
+ for (const [sn, st] of this.sessions)
23628
+ this.drop(sn, st);
23629
+ }
23630
+ /**
23631
+ * Completes on the command ACK or a correlated control-result notification. The notification must
23632
+ * match the request channel, parameter and segment and contain a structured payload. Receipt does
23633
+ * not establish physical actuation. The command is sent once, bounded by {@link ACK_TIMEOUT_MS}.
23634
+ */
23635
+ sendAwaitAck(sn, st, packet, outerCmd, innerCmd, channel, segment) {
23636
+ return new Promise((resolve, reject) => {
23637
+ const onData = (frame, linkType) => {
23638
+ const p = parsePortalPacket(frame, linkType);
23639
+ if (!p || p.segment !== segment)
23640
+ return;
23641
+ const acknowledgement = linkType === PortalLinkType.COMMAND && p.commandId === outerCmd && !!p.isResponse;
23642
+ const d = p.data;
23643
+ const notification = outerCmd === PORTAL_CMD_CONTROL_PAYLOAD && linkType === PortalLinkType.NOTIFY && p.commandId === PORTAL_CMD_NOTIFY_PAYLOAD && p.isResponse === 0 && p.channel === channel && p.cmd === innerCmd && typeof d?.payload === "object" && d.payload !== null;
23644
+ if (!acknowledgement && !notification)
23645
+ return;
23646
+ cleanup();
23647
+ if (acknowledgement && p.errCode !== 0) {
23648
+ reject(new Error(`rtc: ${sn} rejected cmd ${innerCmd} (err ${p.errCode})`));
23649
+ } else {
23650
+ this.deps.logger?.debug?.(`[rtc] ${sn} cmd ${innerCmd} acked`);
23651
+ resolve();
23652
+ }
23653
+ };
23654
+ const onClose = () => {
23655
+ cleanup();
23656
+ reject(new Error(`rtc: ${sn} session closed while waiting for cmd ${innerCmd} ACK`));
23657
+ };
23658
+ const timer = setTimeout(() => {
23659
+ cleanup();
23660
+ reject(new Error(`rtc: ${sn} cmd ${innerCmd} ACK timed out after ${ACK_TIMEOUT_MS}ms`));
23661
+ }, ACK_TIMEOUT_MS);
23662
+ const cleanup = () => {
23663
+ clearTimeout(timer);
23664
+ st.session.off("commandData", onData);
23665
+ st.session.off("close", onClose);
23666
+ this.touch(sn, st);
23667
+ };
23668
+ st.session.on("commandData", onData);
23669
+ st.session.on("close", onClose);
23670
+ if (!st.session.sendCommand(packet)) {
23671
+ cleanup();
23672
+ reject(new Error(`rtc: ${sn} command channel not open, cmd ${innerCmd} not sent`));
23673
+ }
23674
+ });
23675
+ }
23676
+ async stationSession(sn, adminUserId, identity) {
23677
+ const existing = this.sessions.get(sn);
23678
+ if (existing) {
23679
+ await existing.ready;
23680
+ if (existing.session.isConnected) {
23681
+ this.touch(sn, existing);
23682
+ return existing;
23683
+ }
23684
+ this.drop(sn, existing);
23685
+ }
23686
+ const session = (this.deps.createSession ?? ((o) => new RtcSession(o)))({
23687
+ authToken: identity.authToken,
23688
+ gtoken: identity.gtoken,
23689
+ stationSn: sn,
23690
+ adminUserId,
23691
+ shard: this.deps.shard(),
23692
+ country: this.deps.country ?? "US",
23693
+ logger: this.deps.logger,
23694
+ peer: { logger: this.deps.logger }
23695
+ });
23696
+ const ready = this.bringUp(sn, session);
23697
+ const st = { session, seg: new SegmentCounter(), ready, queue: Promise.resolve() };
23698
+ session.on("error", (e) => this.deps.onError?.(e));
23699
+ session.on("close", () => {
23700
+ if (this.sessions.get(sn) === st)
23701
+ this.sessions.delete(sn);
23702
+ });
23703
+ this.sessions.set(sn, st);
23704
+ try {
23705
+ await ready;
23706
+ } catch (e) {
23707
+ this.drop(sn, st);
23708
+ throw e;
23709
+ }
23710
+ this.touch(sn, st);
23711
+ return st;
23712
+ }
23713
+ /**
23714
+ * One bounded bring-up: the session is up when its command channel opens, and it fails, with the
23715
+ * session closed and every listener gone, when `connect()` throws, the session closes first, or
23716
+ * {@link CONNECT_TIMEOUT_MS} passes. A single promise, so an early failure cannot leave a second one
23717
+ * rejecting unheard.
23718
+ */
23719
+ bringUp(sn, session) {
23720
+ return new Promise((resolve, reject) => {
23721
+ let settled = false;
23722
+ const finish = (err) => {
23723
+ if (settled)
23724
+ return;
23725
+ settled = true;
23726
+ clearTimeout(timer);
23727
+ session.off("connected", onConnected);
23728
+ session.off("close", onClose);
23729
+ if (err) {
23730
+ try {
23731
+ session.close();
23732
+ } catch {
23733
+ }
23734
+ reject(err);
23735
+ } else {
23736
+ this.deps.logger?.info?.(`[rtc] ${sn} command channel up`);
23737
+ resolve();
23738
+ }
23739
+ };
23740
+ const onConnected = () => finish();
23741
+ const onClose = () => finish(new Error(`rtc: ${sn} session closed before the command channel opened`));
23742
+ const timer = setTimeout(() => finish(new Error(`rtc: ${sn} did not come up within ${CONNECT_TIMEOUT_MS2}ms`)), CONNECT_TIMEOUT_MS2);
23743
+ session.once("connected", onConnected);
23744
+ session.once("close", onClose);
23745
+ Promise.resolve().then(() => session.connect()).catch((e) => finish(e instanceof Error ? e : new Error(String(e))));
23746
+ });
23747
+ }
23748
+ touch(sn, st) {
23749
+ if (st.idle)
23750
+ clearTimeout(st.idle);
23751
+ st.idle = setTimeout(() => this.drop(sn, st), IDLE_CLOSE_MS);
23752
+ st.idle.unref?.();
23753
+ }
23754
+ drop(sn, st) {
23755
+ if (st.idle)
23756
+ clearTimeout(st.idle);
23757
+ if (this.sessions.get(sn) === st)
23758
+ this.sessions.delete(sn);
23759
+ try {
23760
+ st.session.close();
23761
+ } catch {
23762
+ }
23763
+ }
23764
+ };
23765
+
22360
23766
  // dist/transport/mqtt/command-router.js
22361
23767
  import { randomBytes as randomBytes3 } from "node:crypto";
22362
23768
 
@@ -22660,10 +24066,10 @@ function dpColorFields(spec) {
22660
24066
  }
22661
24067
 
22662
24068
  // dist/transport/mqtt/clean-codec.js
22663
- import { randomUUID as randomUUID2 } from "node:crypto";
24069
+ import { randomUUID as randomUUID3 } from "node:crypto";
22664
24070
  function buildCleanDpEnvelope(accountId, deviceSn, dp, value, opts) {
22665
24071
  const payload = JSON.stringify({
22666
- t: opts?.uuid ?? randomUUID2(),
24072
+ t: opts?.uuid ?? randomUUID3(),
22667
24073
  protocol: 2,
22668
24074
  account_id: accountId,
22669
24075
  device_sn: deviceSn,
@@ -23350,7 +24756,7 @@ function deriveTuyaAccount(eufyUserId, phoneCode) {
23350
24756
  }
23351
24757
 
23352
24758
  // dist/transport/tuya/sign.js
23353
- import { createHash as createHash5, createHmac as createHmac3 } from "node:crypto";
24759
+ import { createHash as createHash5, createHmac as createHmac4 } from "node:crypto";
23354
24760
  var SIGN_ALLOWLIST = /* @__PURE__ */ new Set([
23355
24761
  "a",
23356
24762
  "v",
@@ -23393,7 +24799,7 @@ var HmacSigner = class {
23393
24799
  this.key = key ?? process.env.TUYA_SIGN_KEY ?? TUYA_SIGN_K;
23394
24800
  }
23395
24801
  sign(preimage) {
23396
- return createHmac3("sha256", this.key).update(preimage, "utf-8").digest("hex");
24802
+ return createHmac4("sha256", this.key).update(preimage, "utf-8").digest("hex");
23397
24803
  }
23398
24804
  };
23399
24805
  var TUYA_CHKEY = "7cbfe6d8";
@@ -23402,7 +24808,7 @@ var TUYA_CHKEY = "7cbfe6d8";
23402
24808
  import { randomBytes as randomBytes4, createHash as createHash6, createPublicKey, publicEncrypt, constants as constants2 } from "node:crypto";
23403
24809
 
23404
24810
  // dist/transport/tuya/request.js
23405
- import { randomUUID as randomUUID3 } from "node:crypto";
24811
+ import { randomUUID as randomUUID4 } from "node:crypto";
23406
24812
  var TUYA_API_ENDPOINT = "https://a1.tuyaeu.com/api.json";
23407
24813
  var TUYA_APP_KEY = "w8x4ppqkdxvqnd73ahj9";
23408
24814
  var TUYA_APP_SECRET = "pt585qhmt75hwcynchnps9dnxh9suhwd";
@@ -23434,7 +24840,7 @@ function buildApiParams(action, opts) {
23434
24840
  a: action.a,
23435
24841
  v: action.v,
23436
24842
  time: String(opts.time ?? Math.floor(Date.now() / 1e3)),
23437
- requestId: opts.requestId ?? randomUUID3(),
24843
+ requestId: opts.requestId ?? randomUUID4(),
23438
24844
  sid: opts.session.sid,
23439
24845
  deviceId: opts.session.deviceId,
23440
24846
  chKey: opts.session.chKey,
@@ -23971,7 +25377,7 @@ async function resolveLightEffect(mega, lightId) {
23971
25377
  }
23972
25378
 
23973
25379
  // dist/transport/push/push-client.js
23974
- import { EventEmitter as EventEmitter8 } from "node:events";
25380
+ import { EventEmitter as EventEmitter11 } from "node:events";
23975
25381
  import tls2 from "node:tls";
23976
25382
 
23977
25383
  // dist/transport/push/proto.js
@@ -24226,7 +25632,7 @@ var MessageTag;
24226
25632
  })(MessageTag || (MessageTag = {}));
24227
25633
 
24228
25634
  // dist/transport/push/parser.js
24229
- import { EventEmitter as EventEmitter7 } from "node:events";
25635
+ import { EventEmitter as EventEmitter10 } from "node:events";
24230
25636
  var State;
24231
25637
  (function(State2) {
24232
25638
  State2[State2["VERSION_TAG_AND_SIZE"] = 0] = "VERSION_TAG_AND_SIZE";
@@ -24244,7 +25650,7 @@ var TAG_TO_TYPE = {
24244
25650
  [MessageTag.DataMessageStanza]: "mcs_proto.DataMessageStanza",
24245
25651
  [MessageTag.StreamErrorStanza]: "mcs_proto.StreamErrorStanza"
24246
25652
  };
24247
- var McsParser = class extends EventEmitter7 {
25653
+ var McsParser = class extends EventEmitter10 {
24248
25654
  data = Buffer.alloc(0);
24249
25655
  state = State.VERSION_TAG_AND_SIZE;
24250
25656
  messageTag = 0;
@@ -24422,7 +25828,7 @@ function normalizePushEvent(raw) {
24422
25828
  raw
24423
25829
  };
24424
25830
  }
24425
- var PushClient = class _PushClient extends EventEmitter8 {
25831
+ var PushClient = class _PushClient extends EventEmitter11 {
24426
25832
  creds;
24427
25833
  logger;
24428
25834
  /** Consecutive MCS login rejections tolerated (self-healing propagation) before surfacing an error. */
@@ -25012,7 +26418,14 @@ function deviceClassOf(codec, realtime) {
25012
26418
  const cls = CLASS_BY_CODEC[codec];
25013
26419
  return cls === "camera" && realtime !== "p2p" ? "other" : cls;
25014
26420
  }
26421
+ function recordName(raw, deviceClass) {
26422
+ if (deviceClass === "vacuum") {
26423
+ return raw.alias_name || raw.device_alias_name || raw.device_name || void 0;
26424
+ }
26425
+ return raw.device_name ?? raw.device_alias_name ?? raw.alias_name;
26426
+ }
25015
26427
  var LIST_REUSE_MS = 5e3;
26428
+ var CLOUD_DPS_MODELS = /* @__PURE__ */ new Set(["T2351"]);
25016
26429
  var DeviceRegistry = class {
25017
26430
  mega;
25018
26431
  onError;
@@ -25037,6 +26450,8 @@ var DeviceRegistry = class {
25037
26450
  overlayRefusalReported = false;
25038
26451
  /** Per-serial capability cache for {@link capabilitiesForDevice}; `null` = negative hit. */
25039
26452
  deviceCapsCache = /* @__PURE__ */ new Map();
26453
+ /** Per-serial cloud data points of an AIoT robot, joined beneath the params in {@link record} — see {@link loadCloudDps}. */
26454
+ cloudDps = /* @__PURE__ */ new Map();
25040
26455
  /** Per-serial realtime state, keyed by param id in the device's own namespace (see {@link DeviceRecord.dpParams}). */
25041
26456
  dpParams = /* @__PURE__ */ new Map();
25042
26457
  /** Callers blocked in {@link awaitRealtimeState}, released by the device's first report. */
@@ -25131,9 +26546,10 @@ var DeviceRegistry = class {
25131
26546
  category: raw.category,
25132
26547
  params
25133
26548
  }).codec;
26549
+ const deviceClass = deviceClassOf(codec, c.realtime);
25134
26550
  seen.set(raw.device_sn, {
25135
26551
  sn: raw.device_sn,
25136
- name: raw.device_name ?? raw.device_alias_name ?? raw.alias_name,
26552
+ name: recordName(raw, deviceClass),
25137
26553
  model: raw.device_model,
25138
26554
  stationSn: resolvedStationSn(raw, raw.device_sn),
25139
26555
  p2pDid: raw.p2p_did,
@@ -25141,11 +26557,12 @@ var DeviceRegistry = class {
25141
26557
  paramUpdatedAt,
25142
26558
  lastSeenMs: lastSeenMsOf(paramUpdatedAt),
25143
26559
  raw,
25144
- deviceClass: deviceClassOf(codec, c.realtime),
26560
+ deviceClass,
25145
26561
  ...c
25146
26562
  });
25147
26563
  }
25148
26564
  }
26565
+ await this.loadCloudDps(seen);
25149
26566
  this.lastRefreshPartial = partial;
25150
26567
  if (partial) {
25151
26568
  for (const prev of this.devices)
@@ -25236,9 +26653,46 @@ var DeviceRegistry = class {
25236
26653
  }
25237
26654
  return dev;
25238
26655
  }
26656
+ /**
26657
+ * Hold an AIoT robot's cloud data points: the cloud's last-known value of each one it has reported,
26658
+ * from `getDeviceRelationList`'s per-device `dps`.
26659
+ *
26660
+ * The device list carries only some of a robot's data points, so a point the robot publishes on change
26661
+ * alone (its scene list, its schedules, its consumables) has no value until it next reports. The
26662
+ * relation list holds every one, for an account the robot is shared with as well as its owner.
26663
+ *
26664
+ * Kept apart from the device list's params rather than merged into them: those are what a poll diffs,
26665
+ * and a diff retires the realtime report for that id, so a cloud value lagging the robot's last report
26666
+ * would replace it. {@link record} joins this beneath both halves. A failure keeps what was held.
26667
+ *
26668
+ * Limited to {@link CLOUD_DPS_MODELS}, the models whose relation-list `dps` are checked to carry the
26669
+ * DP numbers their realtime reports use.
26670
+ */
26671
+ async loadCloudDps(seen) {
26672
+ const robots = [...seen.values()].filter((d) => CLOUD_DPS_MODELS.has(d.model ?? ""));
26673
+ if (!robots.length)
26674
+ return;
26675
+ let res;
26676
+ try {
26677
+ res = await this.mega.getDeviceRelationList();
26678
+ } catch (e) {
26679
+ if (e instanceof SessionExpiredError)
26680
+ throw e;
26681
+ this.logger.debug(`[registry] device relation list unavailable: ${e?.message ?? e}`);
26682
+ return;
26683
+ }
26684
+ const wanted = new Set(robots.map((d) => d.sn));
26685
+ for (const entry of res.devices ?? []) {
26686
+ const sn = entry?.device?.device_sn;
26687
+ const dps = parseAiotDpReport({ payload: entry?.device?.dps });
26688
+ if (sn && wanted.has(sn) && dps)
26689
+ this.cloudDps.set(sn, dps);
26690
+ }
26691
+ }
25239
26692
  /**
25240
26693
  * Resolve a serial to a {@link DeviceRecord} with current params: starts from the device-list params, then
25241
- * overlays a fresh `get_device_param_list` when that call is available to this account.
26694
+ * overlays a fresh `get_device_param_list` when that call is available to this account. An AIoT robot's
26695
+ * cloud data points ({@link loadCloudDps}) sit beneath both, filling only ids neither carries.
25242
26696
  *
25243
26697
  * The overlay is **owner-gated** — a shared or member account is refused it for every device, permanently,
25244
26698
  * which {@link OWNER_ONLY_CODE} identifies — so when it is unavailable the device list is the source
@@ -25267,7 +26721,7 @@ var DeviceRegistry = class {
25267
26721
  let dev = this.devices.find((d) => d.sn === sn);
25268
26722
  if (!dev)
25269
26723
  throw new Error(`device ${sn} not found (have: ${this.devices.map((d) => d.sn).join(", ")})`);
25270
- const params = { ...dev.params ?? {} };
26724
+ const params = { ...this.cloudDps.get(sn), ...dev.params ?? {} };
25271
26725
  const paramUpdatedAt = { ...dev.paramUpdatedAt ?? {} };
25272
26726
  if (!this.overlayRefused.has(sn)) {
25273
26727
  try {
@@ -25575,7 +27029,7 @@ function readinessSnapshot(readiness, state = readiness.state) {
25575
27029
  wiredP2p: Object.freeze({ ...readiness.wiredP2p })
25576
27030
  });
25577
27031
  }
25578
- var EufyMega = class extends EventEmitter9 {
27032
+ var EufyMega = class extends EventEmitter12 {
25579
27033
  opts;
25580
27034
  mega;
25581
27035
  /**
@@ -25635,6 +27089,8 @@ var EufyMega = class extends EventEmitter9 {
25635
27089
  prewarmTiers;
25636
27090
  /** Transport-side owner of the P2P sessions + all wire senders. */
25637
27091
  p2p;
27092
+ /** Transport-side owner of the T9000 station sessions (sibling of {@link p2p}). */
27093
+ rtc;
25638
27094
  /** Transport-side owner of the secure-MQTT ff09 lock/garage command path (sibling of {@link p2p}). */
25639
27095
  mqtt;
25640
27096
  /** Transport-side owner of the legacy Tuya REST command path for non-AIoT vacuums (G-series). */
@@ -25695,6 +27151,13 @@ var EufyMega = class extends EventEmitter9 {
25695
27151
  onLevel2Ready: (sn, cipherId) => this.emit("p2pLevel2Ready", { stationSn: sn, cipherId }),
25696
27152
  onFrame: (stationSn, f) => this.onP2PFrame(stationSn, f)
25697
27153
  });
27154
+ this.rtc = new RtcCommandRouter({
27155
+ identity: () => this.mega.rtcIdentity(),
27156
+ shard: () => this.mega.rtcShard,
27157
+ country: opts.countryCode,
27158
+ logger: opts.logger,
27159
+ onError: (e) => this.reportError(e)
27160
+ });
25698
27161
  this.mqtt = new MqttCommandRouter({
25699
27162
  mega: this.mega,
25700
27163
  logger: opts.logger,
@@ -25960,13 +27423,22 @@ var EufyMega = class extends EventEmitter9 {
25960
27423
  *
25961
27424
  * The evidence set is widened, never replaced: the ids come back through the cloud record, and a
25962
27425
  * record that omits a realtime-only id would otherwise un-know it and re-trigger on the next report.
27426
+ *
27427
+ * The device is re-resolved against the fresh record before binding. A property gated on a
27428
+ * realtime-only param enters the schema only once that param is evidence, and the value that made it
27429
+ * evidence was stored before the property existed, so the record's realtime params are applied again
27430
+ * to land it under the property's name.
25963
27431
  */
25964
27432
  async rebindReads(sn) {
25965
27433
  const dev = this.liveDevices.get(sn)?.deref();
25966
27434
  if (!dev)
25967
27435
  return;
25968
27436
  try {
25969
- const ctx = await this.commandContext(sn);
27437
+ const rec = await this.registry.record(sn);
27438
+ dev.reresolve(rec);
27439
+ if (rec.dpParams)
27440
+ this.applyAndAnnounce(dev, rec.dpParams);
27441
+ const ctx = await this.commandContext(sn, rec);
25970
27442
  dev.bindActions(ctx, this.commandSinkFor(sn), this.mediaProviderFor(sn), this.ff09SettingsReaderFor(sn, ctx), rawDpCodec);
25971
27443
  this.boundParamIds.set(sn, /* @__PURE__ */ new Set([...this.boundParamIds.get(sn) ?? [], ...ctx.paramIds]));
25972
27444
  this.emit("deviceState", this.deviceState(sn));
@@ -26026,6 +27498,8 @@ var EufyMega = class extends EventEmitter9 {
26026
27498
  * only "differs from what was read before", which state already on hand can satisfy spuriously — and the
26027
27499
  * caller that has no expectation is the push path, where the signal itself is the news that a re-read is owed.
26028
27500
  *
27501
+ * Only a write's observation throws at the deadline; a push with nothing moved answers `false`.
27502
+ *
26029
27503
  * The cloud half is asked for through {@link DeviceRegistry.refreshedList}, never by fetching the account
26030
27504
  * list outright. The fetch is account-wide — one house list plus one device list per house — so a param that
26031
27505
  * never converges would otherwise spend a whole burst of those every iteration of this loop, and concurrent
@@ -26076,6 +27550,8 @@ var EufyMega = class extends EventEmitter9 {
26076
27550
  if (refresh.expected !== void 0 && settled())
26077
27551
  return true;
26078
27552
  }
27553
+ if (refresh.expected === void 0)
27554
+ return false;
26079
27555
  throw new StateConvergenceError({
26080
27556
  sn,
26081
27557
  property: refresh.property,
@@ -26428,8 +27904,9 @@ var EufyMega = class extends EventEmitter9 {
26428
27904
  * The `eufy_life` DP writes (smart lights) are secure-MQTT-only. `aiot-dp` routes to either the
26429
27905
  * Anker AIoT MQTT stack or the legacy Tuya REST router depending on the device's category
26430
27906
  * (`eufy_home_tuya` → Tuya, everything else → MQTT). The capability layer emits a single `aiot-dp`
26431
- * kind and stays transport-agnostic; only the facade sees both sides and decides here. Everything
26432
- * else is P2P.
27907
+ * kind and stays transport-agnostic; only the facade sees both sides and decides here. A T9000
27908
+ * station and the devices attached to it go over RTC, with an attached device's command refused
27909
+ * unless its channel resolves back to it on the station. Everything else is P2P.
26433
27910
  */
26434
27911
  routeCommand(sn, cmd) {
26435
27912
  if (cmd.kind === "ff09-actuate" || cmd.kind === "ff09-autolock" || cmd.kind === "ff09-setting-toggle") {
@@ -26449,6 +27926,20 @@ var EufyMega = class extends EventEmitter9 {
26449
27926
  return this.tuya.dispatchCommand(sn, cmd);
26450
27927
  return this.mqtt.dispatchCommand(sn, cmd);
26451
27928
  }
27929
+ const devices = this.registry.list();
27930
+ const target = devices.find((d) => d.sn === sn);
27931
+ const stationSn = target?.stationSn || sn;
27932
+ const station = devices.find((d) => d.sn === stationSn);
27933
+ const stationRaw = station?.raw ?? {};
27934
+ const deviceType = typeof stationRaw.device_type === "number" ? stationRaw.device_type : void 0;
27935
+ if (target && station && isStation9000({ deviceType, model: station.model })) {
27936
+ const attached = stationSn !== sn;
27937
+ if (attached && this.registry.serialForFrame(stationSn, cmd.channel) !== sn)
27938
+ return Promise.reject(new Error("RTC command requires an unambiguous attached-device channel"));
27939
+ const member = stationRaw.member?.admin_user_id;
27940
+ const adminUserId = typeof member === "string" && member ? member : void 0;
27941
+ return this.rtc.dispatchCommand({ stationSn, adminUserId, attached }, cmd);
27942
+ }
26452
27943
  return this.p2p.dispatchCommand(sn, cmd);
26453
27944
  }
26454
27945
  /**
@@ -27287,16 +28778,20 @@ var EufyMega = class extends EventEmitter9 {
27287
28778
  await this.commandSinkFor(sn).dispatch(cmd);
27288
28779
  }
27289
28780
  /**
27290
- * Restart a HomeBase.
28781
+ * Restart a station: a HomeBase, or a camera-family device that is its own station.
27291
28782
  *
27292
- * **HomeBases only** — restart is a hub operation, so a non-HomeBase serial (a camera, an NVR)
27293
- * throws rather than doing nothing. The hub drops its connection and returns after a minute or two,
27294
- * so everything behind it is briefly offline. Verified on real hardware.
28783
+ * The restart is `RESTART_HUB` on the station's broadcast channel, so it reaches whatever owns the
28784
+ * P2P session. A standalone camera or doorbell owns its own session and is the station it restarts.
28785
+ * A camera attached to a HomeBase is not — the same frame would restart its HomeBase — so its serial
28786
+ * throws, as does any non-camera serial, rather than doing nothing. The device drops its connection
28787
+ * and returns after a minute or two; a HomeBase takes everything behind it offline meanwhile.
28788
+ * Verified on real hardware against a HomeBase and a standalone indoor camera.
27295
28789
  */
27296
28790
  async reboot(sn) {
27297
28791
  const ctx = await this.commandContext(sn);
27298
- if (!isHomeBase({ deviceType: ctx.deviceType, model: ctx.model })) {
27299
- throw new Error(`reboot: ${sn} is not a HomeBase (deviceType ${ctx.deviceType ?? "?"}, model ${ctx.model ?? "?"}) \u2014 restart is a hub-only operation`);
28792
+ const standaloneCamera = ctx.codec === "camera" && this.p2p.stationKeyOf(sn) === sn;
28793
+ if (!isHomeBase({ deviceType: ctx.deviceType, model: ctx.model }) && !standaloneCamera) {
28794
+ throw new Error(`reboot: ${sn} is neither a HomeBase nor a standalone camera (deviceType ${ctx.deviceType ?? "?"}, model ${ctx.model ?? "?"}) \u2014 restart addresses the station that owns the P2P session`);
27300
28795
  }
27301
28796
  await this.p2p.rebootStation(sn);
27302
28797
  }
@@ -27328,8 +28823,9 @@ var EufyMega = class extends EventEmitter9 {
27328
28823
  return EMPTY_DP_CATALOG;
27329
28824
  }
27330
28825
  }
27331
- async commandContext(sn) {
27332
- const rec = await this.registry.record(sn);
28826
+ /** The {@link CommandContext} for a device, built from `known` when that record is already in hand. */
28827
+ async commandContext(sn, known) {
28828
+ const rec = known ?? await this.registry.record(sn);
27333
28829
  const dev = this.registry.require(sn);
27334
28830
  const raw = dev.raw ?? {};
27335
28831
  const rawChannel = raw.device_channel;
@@ -27542,6 +29038,7 @@ var EufyMega = class extends EventEmitter9 {
27542
29038
  this.pollTimer.cancel();
27543
29039
  this.lastStateAnnounced.clear();
27544
29040
  await this.closeMqttTransports();
29041
+ this.rtc.close();
27545
29042
  await this.p2p.closeAll();
27546
29043
  this.pushClient?.close();
27547
29044
  this.pushClient = void 0;
@@ -28046,7 +29543,7 @@ var SolixClient = class _SolixClient {
28046
29543
  };
28047
29544
 
28048
29545
  // dist/transport/mqtt/solix-mqtt.js
28049
- import { EventEmitter as EventEmitter10 } from "node:events";
29546
+ import { EventEmitter as EventEmitter13 } from "node:events";
28050
29547
  var SOLIX_METER_FIELD_NAMES = {
28051
29548
  168: "meterPowerL1",
28052
29549
  // Anker Modbus: primary_phase_1_active_power
@@ -28224,7 +29721,7 @@ function addSolarbankScalars(frame, out) {
28224
29721
  out.gridExportLimit = df.readUInt16LE(5);
28225
29722
  }
28226
29723
  }
28227
- var SolixMqtt = class extends EventEmitter10 {
29724
+ var SolixMqtt = class extends EventEmitter13 {
28228
29725
  transport;
28229
29726
  appName;
28230
29727
  userId;