@camstack/addon-provider-reolink 1.2.259 → 1.2.261

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/addon.mjs CHANGED
@@ -29159,7 +29159,7 @@ var require_lz4 = /* @__PURE__ */ __commonJSMin(((exports) => {
29159
29159
  };
29160
29160
  }));
29161
29161
  //#endregion
29162
- //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-2XVZ5ZZL.js
29162
+ //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-MC2CLGY2.js
29163
29163
  var import_fxp = require_fxp();
29164
29164
  var import_lz4 = /* @__PURE__ */ __toESM(require_lz4(), 1);
29165
29165
  function bcHeaderLen(messageClass, buf, bodyLen) {
@@ -29992,6 +29992,21 @@ var BcUdpStream = class extends EventEmitter {
29992
29992
  lastAcceptAtMs;
29993
29993
  ackScheduled = false;
29994
29994
  ackLatency = new AckLatency();
29995
+ /** When the data phase started (timers armed); the session's age base. */
29996
+ connectedAtMs;
29997
+ /** Last datagram of any kind received from the camera. */
29998
+ lastRxAtMs;
29999
+ /** Last DATA packet received from the camera, and its packet id. */
30000
+ lastDataRxAtMs;
30001
+ lastDataRxPacketId;
30002
+ /** Last ACK from the camera (acknowledging OUR packets), and its id. */
30003
+ lastAckRxAtMs;
30004
+ lastAckRxPacketId;
30005
+ /** Set when the camera sent D2C_DISC (it, not us, ended the session). */
30006
+ discFromCameraAtMs;
30007
+ /** One log per stall; re-armed when the stalled condition clears. */
30008
+ ackWindowStallLogged = false;
30009
+ rxSilenceStallLogged = false;
29995
30010
  lastAckPacket = Buffer.alloc(0);
29996
30011
  ackSentCount = 0;
29997
30012
  pendingData = [];
@@ -30781,6 +30796,9 @@ var BcUdpStream = class extends EventEmitter {
30781
30796
  }
30782
30797
  startTimers() {
30783
30798
  if (!this.sock || !this.remote || this.clientId == null || this.cameraId == null) throw new Error("BCUDP not ready");
30799
+ this.connectedAtMs = Date.now();
30800
+ this.ackWindowStallLogged = false;
30801
+ this.rxSilenceStallLogged = false;
30784
30802
  this.updateAckPacket();
30785
30803
  this.sendHeartbeat();
30786
30804
  this.ackTimer = setInterval$1(() => {
@@ -30793,6 +30811,7 @@ var BcUdpStream = class extends EventEmitter {
30793
30811
  this.resendTimer = setInterval$1(() => {
30794
30812
  try {
30795
30813
  this.resendOutstanding();
30814
+ this.checkStalls(Date.now());
30796
30815
  } catch (e) {
30797
30816
  this.emit("error", e instanceof Error ? e : new Error(String(e)));
30798
30817
  }
@@ -30878,6 +30897,49 @@ var BcUdpStream = class extends EventEmitter {
30878
30897
  this.emit("debug", "ack_scheduled", { reason });
30879
30898
  }
30880
30899
  }
30900
+ /**
30901
+ * Snapshot of the session's health, for the disconnect log of the owner.
30902
+ * Packet ids are the camera's (rx) and ours acknowledged by the camera (ack).
30903
+ */
30904
+ getSessionDiagnostics(now = Date.now()) {
30905
+ let oldestUnackedAgeMs;
30906
+ for (const entry of this.sent.values()) {
30907
+ const age = now - entry.ts;
30908
+ if (oldestUnackedAgeMs === void 0 || age > oldestUnackedAgeMs) oldestUnackedAgeMs = age;
30909
+ }
30910
+ return {
30911
+ sessionAgeMs: this.connectedAtMs !== void 0 ? now - this.connectedAtMs : void 0,
30912
+ lastRxAgoMs: this.lastRxAtMs !== void 0 ? now - this.lastRxAtMs : void 0,
30913
+ lastDataRxPacketId: this.lastDataRxPacketId,
30914
+ lastDataRxAgoMs: this.lastDataRxAtMs !== void 0 ? now - this.lastDataRxAtMs : void 0,
30915
+ lastAckRxPacketId: this.lastAckRxPacketId,
30916
+ lastAckRxAgoMs: this.lastAckRxAtMs !== void 0 ? now - this.lastAckRxAtMs : void 0,
30917
+ unackedPackets: this.sent.size,
30918
+ ...oldestUnackedAgeMs !== void 0 ? { oldestUnackedAgeMs } : {},
30919
+ discFromCamera: this.discFromCameraAtMs !== void 0
30920
+ };
30921
+ }
30922
+ /**
30923
+ * Logs (once per stall) when the camera stops acknowledging our packets or
30924
+ * stops sending anything at all, with the session's age. Runs on the 500 ms
30925
+ * resend tick; purely diagnostic, it never closes the session.
30926
+ */
30927
+ checkStalls(now) {
30928
+ const age = this.connectedAtMs !== void 0 ? now - this.connectedAtMs : void 0;
30929
+ const diag = this.getSessionDiagnostics(now);
30930
+ const ackStalled = diag.oldestUnackedAgeMs !== void 0 && diag.oldestUnackedAgeMs >= 5e3;
30931
+ if (ackStalled && !this.ackWindowStallLogged) {
30932
+ this.ackWindowStallLogged = true;
30933
+ this.discoveryLogger?.warn?.(`[BcUdpStream] ack window stalled: ${diag.unackedPackets} packet(s) unacked, oldest ${diag.oldestUnackedAgeMs}ms, lastAckRxPacketId=${diag.lastAckRxPacketId ?? "none"} sessionAgeMs=${age}`);
30934
+ this.emit("debug", "ack_window_stall", { ...diag });
30935
+ } else if (!ackStalled) this.ackWindowStallLogged = false;
30936
+ const rxSilent = ackStalled && diag.lastRxAgoMs !== void 0 && diag.lastRxAgoMs >= 5e3;
30937
+ if (rxSilent && !this.rxSilenceStallLogged) {
30938
+ this.rxSilenceStallLogged = true;
30939
+ this.discoveryLogger?.warn?.(`[BcUdpStream] camera silent while requests are outstanding: nothing received for ${diag.lastRxAgoMs}ms lastDataRxPacketId=${diag.lastDataRxPacketId ?? "none"} lastAckRxPacketId=${diag.lastAckRxPacketId ?? "none"} sessionAgeMs=${age}`);
30940
+ this.emit("debug", "rx_silence_stall", { ...diag });
30941
+ } else if (!rxSilent) this.rxSilenceStallLogged = false;
30942
+ }
30881
30943
  resendOutstanding() {
30882
30944
  if (!this.sock || !this.remote) return;
30883
30945
  for (const [, entry] of this.sent) this.sock.send(entry.buf, this.remote.port, this.remote.host);
@@ -30933,9 +30995,12 @@ var BcUdpStream = class extends EventEmitter {
30933
30995
  }
30934
30996
  };
30935
30997
  if (!this.remote) updateRemote("first_packet");
30998
+ this.lastRxAtMs = Date.now();
30936
30999
  if (p.kind === "ack") {
30937
31000
  if (this.clientId != null && p.connectionId === this.clientId) {
30938
31001
  updateRemote("ack");
31002
+ this.lastAckRxAtMs = Date.now();
31003
+ this.lastAckRxPacketId = p.packetId;
30939
31004
  this.handleAckFromCamera(p.packetId, p.payload);
30940
31005
  }
30941
31006
  return;
@@ -30943,6 +31008,8 @@ var BcUdpStream = class extends EventEmitter {
30943
31008
  if (p.kind === "data") {
30944
31009
  if (this.clientId != null && p.connectionId === this.clientId) {
30945
31010
  updateRemote("data");
31011
+ this.lastDataRxAtMs = Date.now();
31012
+ this.lastDataRxPacketId = p.packetId;
30946
31013
  if (p.packetId >= this.packetsWant) {
30947
31014
  this.received.set(p.packetId, p.payload);
30948
31015
  this.flushReceived();
@@ -31034,6 +31101,7 @@ var BcUdpStream = class extends EventEmitter {
31034
31101
  rhost,
31035
31102
  rport
31036
31103
  });
31104
+ this.discFromCameraAtMs = Date.now();
31037
31105
  this.emit("error", /* @__PURE__ */ new Error(`BCUDP disconnected by camera (D2C_DISC${this.sid != null ? ` sid=${this.sid}` : ""})`));
31038
31106
  this.close();
31039
31107
  return;
@@ -31247,6 +31315,20 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
31247
31315
  msgNum = 0;
31248
31316
  loggedIn = false;
31249
31317
  subscribed = false;
31318
+ /**
31319
+ * Consecutive request timeouts with no received frame in between, after
31320
+ * which the session is declared stalled (`sessionStalled`). 3 because one
31321
+ * timeout is a lost packet or a slow command, two happen on a lossy radio
31322
+ * link, but three with total receive silence (see
31323
+ * {@link BaichuanClient.SESSION_STALL_MIN_SILENCE_MS}) is a dead session.
31324
+ */
31325
+ static SESSION_STALL_TIMEOUTS = 3;
31326
+ /** Receive silence required on top of the timeout count (ignored-command guard). */
31327
+ static SESSION_STALL_MIN_SILENCE_MS = 2e4;
31328
+ consecutiveRequestTimeouts = 0;
31329
+ sessionStalledEmitted = false;
31330
+ /** When the current socket session was opened (age base for diagnostics). */
31331
+ sessionStartedAtMs;
31250
31332
  keepAliveTimer;
31251
31333
  keepAlivePingInFlight = false;
31252
31334
  consecutiveKeepalivePingFailures = 0;
@@ -31319,6 +31401,68 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
31319
31401
  newSocketSessionId(transport) {
31320
31402
  return `${transport}-${randomUUID().split("-")[0] ?? randomUUID().slice(0, 8)}`;
31321
31403
  }
31404
+ /**
31405
+ * Re-emit a socket error to consumers. EventEmitter throws when an `error`
31406
+ * event has no listener, and the constructor's safety listener is gone once
31407
+ * a caller runs `removeAllListeners()` on a client it is discarding. A late
31408
+ * reset on that discarded socket must stay a log line, never a thrown
31409
+ * exception out of the socket's event handler.
31410
+ */
31411
+ emitSocketError(err) {
31412
+ if (this.listenerCount("error") === 0) {
31413
+ this.logFixed("error_no_listener", {
31414
+ message: err?.message ?? String(err),
31415
+ code: err?.code
31416
+ });
31417
+ return;
31418
+ }
31419
+ this.emit("error", err);
31420
+ }
31421
+ /**
31422
+ * Fields appended to the `disconnected` line so a session that dies on a
31423
+ * schedule (e.g. every ~30 min) can be told apart from a camera that ends it
31424
+ * (`discFromCamera=true`) and from silent loss (`lastRxAgoMs` large).
31425
+ */
31426
+ describeSessionForDisconnect(udp) {
31427
+ const now = Date.now();
31428
+ const parts = [];
31429
+ const age = this.sessionStartedAtMs !== void 0 ? now - this.sessionStartedAtMs : udp?.sessionAgeMs;
31430
+ if (age !== void 0) parts.push(`sessionAgeMs=${age}`);
31431
+ if (this.lastRxAtMs) parts.push(`lastRxAgoMs=${now - this.lastRxAtMs}`);
31432
+ if (udp) {
31433
+ parts.push(`lastRxPktId=${udp.lastDataRxPacketId ?? "none"}`);
31434
+ parts.push(`lastAckPktId=${udp.lastAckRxPacketId ?? "none"}`);
31435
+ parts.push(`unackedPkts=${udp.unackedPackets}`);
31436
+ parts.push(`discFromCamera=${udp.discFromCamera}`);
31437
+ }
31438
+ if (this.consecutiveRequestTimeouts > 0) parts.push(`consecutiveTimeouts=${this.consecutiveRequestTimeouts}`);
31439
+ return parts;
31440
+ }
31441
+ resetStallTracking() {
31442
+ this.consecutiveRequestTimeouts = 0;
31443
+ this.sessionStalledEmitted = false;
31444
+ }
31445
+ /**
31446
+ * Called by every request path when its reply did not arrive in time.
31447
+ * Emits `sessionStalled` once per session when the run of timeouts is long
31448
+ * enough AND the session has received nothing for a while.
31449
+ */
31450
+ noteRequestTimeout() {
31451
+ this.consecutiveRequestTimeouts++;
31452
+ if (this.sessionStalledEmitted) return;
31453
+ if (this.consecutiveRequestTimeouts < _BaichuanClient.SESSION_STALL_TIMEOUTS) return;
31454
+ const now = Date.now();
31455
+ const lastRxAgo = this.lastRxAtMs ? now - this.lastRxAtMs : void 0;
31456
+ if (lastRxAgo !== void 0 && lastRxAgo < _BaichuanClient.SESSION_STALL_MIN_SILENCE_MS) return;
31457
+ this.sessionStalledEmitted = true;
31458
+ this.emit("sessionStalled", {
31459
+ consecutiveTimeouts: this.consecutiveRequestTimeouts,
31460
+ sessionAgeMs: this.sessionStartedAtMs !== void 0 ? now - this.sessionStartedAtMs : void 0,
31461
+ lastRxAgoMs: lastRxAgo,
31462
+ lastRxCmdId: this.lastRxInfo?.cmdId,
31463
+ transport: this.transport
31464
+ });
31465
+ }
31322
31466
  logFixed(event, data) {
31323
31467
  const msg = `[BaichuanClient] ${event}`;
31324
31468
  const l = this.logger;
@@ -31935,6 +32079,8 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
31935
32079
  this.socketClosed = false;
31936
32080
  this.consecutiveKeepalivePingFailures = 0;
31937
32081
  this.socketSessionId = this.newSocketSessionId("tcp");
32082
+ this.sessionStartedAtMs = Date.now();
32083
+ this.resetStallTracking();
31938
32084
  try {
31939
32085
  sock.setKeepAlive(true, 3e4);
31940
32086
  } catch (e) {
@@ -31969,6 +32115,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
31969
32115
  if (tcpPort != null) tcpDisconnectParts.push(`port=${tcpPort}`);
31970
32116
  if (this.lastRxInfo?.cmdId != null) tcpDisconnectParts.push(`lastRxCmdId=${this.lastRxInfo.cmdId}`);
31971
32117
  if (this.lastTxInfo?.cmdId != null) tcpDisconnectParts.push(`lastTxCmdId=${this.lastTxInfo.cmdId}`);
32118
+ tcpDisconnectParts.push(...this.describeSessionForDisconnect(void 0));
31972
32119
  this.logFixed("disconnected", tcpDisconnectParts.join(" "));
31973
32120
  this.socketSessionId = void 0;
31974
32121
  this.loggedIn = false;
@@ -31989,7 +32136,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
31989
32136
  message: err?.message ?? String(err),
31990
32137
  code
31991
32138
  } });
31992
- this.emit("error", err);
32139
+ this.emitSocketError(err);
31993
32140
  });
31994
32141
  await new Promise((resolve, reject) => {
31995
32142
  let settled = false;
@@ -32058,6 +32205,8 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
32058
32205
  this.transport = "udp";
32059
32206
  this.socketClosed = false;
32060
32207
  this.socketSessionId = this.newSocketSessionId("udp");
32208
+ this.sessionStartedAtMs = Date.now();
32209
+ this.resetStallTracking();
32061
32210
  sock.on("data", (chunk) => {
32062
32211
  const frames = this.parser.push(chunk);
32063
32212
  for (const f of frames) this.handleFrame(f);
@@ -32065,6 +32214,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
32065
32214
  sock.on("close", () => {
32066
32215
  this.logSocketState("udp_close_event", { udpConnected: sock.isConnected?.() });
32067
32216
  const sid2 = this.socketSessionId;
32217
+ const udpDiag = sock.getSessionDiagnostics?.();
32068
32218
  if (sock === this.udpSocket) this.udpSocket = void 0;
32069
32219
  if (sock.removeAllListeners) sock.removeAllListeners();
32070
32220
  this.stopKeepAlive();
@@ -32088,6 +32238,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
32088
32238
  }
32089
32239
  if (this.lastRxInfo?.cmdId != null) udpDisconnectParts.push(`lastRxCmdId=${this.lastRxInfo.cmdId}`);
32090
32240
  if (this.lastTxInfo?.cmdId != null) udpDisconnectParts.push(`lastTxCmdId=${this.lastTxInfo.cmdId}`);
32241
+ udpDisconnectParts.push(...this.describeSessionForDisconnect(udpDiag));
32091
32242
  this.logFixed("disconnected", udpDisconnectParts.join(" "));
32092
32243
  this.socketSessionId = void 0;
32093
32244
  this.loggedIn = false;
@@ -32297,6 +32448,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
32297
32448
  handleFrame(frame) {
32298
32449
  const now = Date.now();
32299
32450
  this.lastRxAtMs = now;
32451
+ this.consecutiveRequestTimeouts = 0;
32300
32452
  this.lastRxInfo = {
32301
32453
  atMs: now,
32302
32454
  cmdId: frame.header.cmdId,
@@ -32955,6 +33107,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
32955
33107
  const framePromise = new Promise((resolve, reject) => {
32956
33108
  const t = setTimeout(() => {
32957
33109
  this.pending.delete(pendingKey);
33110
+ this.noteRequestTimeout();
32958
33111
  reject(/* @__PURE__ */ new Error(`Baichuan timeout cmdId=${cmdId} msgNum=${msgNum}`));
32959
33112
  }, remainingMs);
32960
33113
  this.pending.set(pendingKey, {
@@ -33042,6 +33195,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
33042
33195
  const framePromise = new Promise((resolve, reject) => {
33043
33196
  const t = setTimeout(() => {
33044
33197
  this.pending.delete(pendingKey);
33198
+ this.noteRequestTimeout();
33045
33199
  reject(/* @__PURE__ */ new Error(`Baichuan timeout cmdId=${cmdId} msgNum=${msgNum}`));
33046
33200
  }, remainingMs);
33047
33201
  this.pending.set(pendingKey, {
@@ -33137,6 +33291,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
33137
33291
  const framePromise = new Promise((resolve, reject) => {
33138
33292
  const t = setTimeout(() => {
33139
33293
  this.pending.delete(pendingKey);
33294
+ this.noteRequestTimeout();
33140
33295
  reject(/* @__PURE__ */ new Error(`Baichuan timeout cmdId=${cmdId} msgNum=${msgNum}`));
33141
33296
  }, timeoutMs);
33142
33297
  this.pending.set(pendingKey, {
@@ -41160,6 +41315,124 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41160
41315
  }
41161
41316
  }
41162
41317
  /**
41318
+ * Consumer decision on recycling a stalled general session. `true` asserts
41319
+ * the camera is awake and always on (a recycle logs in, which wakes a
41320
+ * sleeper); `false` forbids it. Without a guard only a camera KNOWN to be
41321
+ * awake, or one with no battery signal at all (wired TCP), is recycled.
41322
+ */
41323
+ generalRecycleGuard;
41324
+ /** `false` disables recycling entirely (default: enabled). */
41325
+ generalRecycleEnabled = true;
41326
+ generalRecycling = false;
41327
+ /** Minimum time between two recycles: a camera that logs in but never answers must not loop. */
41328
+ generalRecycleMinIntervalMs = 5 * 6e4;
41329
+ /** Recycles allowed in any rolling hour. */
41330
+ generalRecycleMaxPerHour = 6;
41331
+ generalRecycleAtMs = [];
41332
+ /**
41333
+ * Configure recycling of a general session that stays silently dead.
41334
+ *
41335
+ * Without a `guard`, a camera is recycled only when known awake, or when it
41336
+ * shows no battery signal. That signal is a received battery push or a BCUDP
41337
+ * transport, so a TCP battery camera that has not pushed battery info yet
41338
+ * looks wired and CAN be woken by the login. Consumers that know battery
41339
+ * status should pass a `guard` (`true` = always on, `false` = never).
41340
+ */
41341
+ setGeneralSessionRecycling(opts) {
41342
+ if (opts.enabled !== void 0) this.generalRecycleEnabled = opts.enabled;
41343
+ if ("guard" in opts) this.generalRecycleGuard = opts.guard;
41344
+ if (opts.minIntervalMs !== void 0) this.generalRecycleMinIntervalMs = Math.max(0, opts.minIntervalMs);
41345
+ if (opts.maxPerHour !== void 0) this.generalRecycleMaxPerHour = Math.max(0, opts.maxPerHour);
41346
+ }
41347
+ /**
41348
+ * Whether a recycle may log in without waking a sleeping camera. The sleep
41349
+ * state is only known once inference ran (UDP) or a probe answered, so an
41350
+ * unknown state on a camera that may be battery-powered is a refusal.
41351
+ */
41352
+ generalRecycleSleepVerdict() {
41353
+ if (this.generalRecycleGuard) {
41354
+ let v = false;
41355
+ try {
41356
+ v = this.generalRecycleGuard();
41357
+ } catch {
41358
+ v = false;
41359
+ }
41360
+ return {
41361
+ ok: v,
41362
+ why: v ? "guard allows" : "consumer guard refuses"
41363
+ };
41364
+ }
41365
+ const states = Array.from(this.udpLastInferredSleepStateByChannel.values());
41366
+ if (states.includes("sleeping")) return {
41367
+ ok: false,
41368
+ why: "camera is asleep"
41369
+ };
41370
+ const probe = this.lastSleepProbe;
41371
+ if (probe && Date.now() - probe.atMs < 12e4) {
41372
+ if (probe.status.state === "sleeping") return {
41373
+ ok: false,
41374
+ why: "camera is asleep"
41375
+ };
41376
+ if (probe.status.state === "awake") return {
41377
+ ok: true,
41378
+ why: "awake"
41379
+ };
41380
+ }
41381
+ if (states.length > 0 && states.every((x) => x === "awake")) return {
41382
+ ok: true,
41383
+ why: "awake"
41384
+ };
41385
+ if (this.lastBatteryPushKey.size > 0 || this.client?.getTransport?.() === "udp") return {
41386
+ ok: false,
41387
+ why: "sleep state unknown on a camera that may be battery-powered"
41388
+ };
41389
+ return {
41390
+ ok: true,
41391
+ why: "no battery signal"
41392
+ };
41393
+ }
41394
+ /**
41395
+ * Tear down a general session the client declared stalled and open a new one.
41396
+ * `client` is the one that raised the event: a late event from an already
41397
+ * replaced client is ignored.
41398
+ */
41399
+ async recycleStalledGeneralSession(client, info) {
41400
+ if (this._closed || !this.generalRecycleEnabled || this.generalRecycling) return;
41401
+ if (this.socketPool.get("general")?.client !== client) return;
41402
+ const verdict2 = this.generalRecycleSleepVerdict();
41403
+ if (!verdict2.ok) {
41404
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session stalled (${info.consecutiveTimeouts} consecutive timeouts, age=${info.sessionAgeMs}ms) but not recycled: ${verdict2.why}`);
41405
+ return;
41406
+ }
41407
+ const now = Date.now();
41408
+ while (this.generalRecycleAtMs.length > 0 && now - this.generalRecycleAtMs[0] >= 36e5) this.generalRecycleAtMs.shift();
41409
+ const last = this.generalRecycleAtMs[this.generalRecycleAtMs.length - 1];
41410
+ if (last !== void 0 && now - last < this.generalRecycleMinIntervalMs) {
41411
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session stalled again ${now - last}ms after the last recycle; not recycling before ${this.generalRecycleMinIntervalMs}ms`);
41412
+ return;
41413
+ }
41414
+ if (this.generalRecycleAtMs.length >= this.generalRecycleMaxPerHour) {
41415
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session recycle bound hit (${this.generalRecycleAtMs.length} in the last hour); giving up on recycling until it clears`);
41416
+ return;
41417
+ }
41418
+ this.generalRecycleAtMs.push(now);
41419
+ this.generalRecycling = true;
41420
+ try {
41421
+ this.logger.warn?.(`[ReolinkBaichuanApi] recycling general session: ${info.consecutiveTimeouts} consecutive command timeouts, nothing received for ${info.lastRxAgoMs ?? "?"}ms, session age=${info.sessionAgeMs ?? "?"}ms`);
41422
+ if (!this._ensureConnectedPromise) this._ensureConnectedPromise = this.reconnectGeneralSocket();
41423
+ try {
41424
+ await this._ensureConnectedPromise;
41425
+ } finally {
41426
+ this._ensureConnectedPromise = void 0;
41427
+ }
41428
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session recycled (previous age=${info.sessionAgeMs ?? "?"}ms)`);
41429
+ } catch (e) {
41430
+ this.logger.warn?.(`[ReolinkBaichuanApi] recycling the general session failed: ${e instanceof Error ? e.message : String(e)}`);
41431
+ } finally {
41432
+ this.generalRecycling = false;
41433
+ }
41434
+ }
41435
+ /**
41163
41436
  * Internal: destroy the current general socket (if any), create a new one,
41164
41437
  * login, and re-attach all listeners.
41165
41438
  */
@@ -41167,6 +41440,12 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41167
41440
  const oldEntry = this.socketPool.get("general");
41168
41441
  if (oldEntry) {
41169
41442
  oldEntry.client.removeAllListeners();
41443
+ oldEntry.client.on("error", (err) => {
41444
+ (this.logger.debug ?? this.logger.log)?.call(this.logger, "general socket (discarded) late error", {
41445
+ message: err?.message ?? String(err),
41446
+ code: err?.code
41447
+ });
41448
+ });
41170
41449
  if (oldEntry.idleCloseTimer) clearTimeout(oldEntry.idleCloseTimer);
41171
41450
  if (oldEntry.generalPermitRelease) try {
41172
41451
  oldEntry.generalPermitRelease();
@@ -41227,6 +41506,9 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41227
41506
  this.logger?.debug?.(`[ReolinkBaichuanApi] general error handler threw: ${e}`);
41228
41507
  }
41229
41508
  });
41509
+ client.on("sessionStalled", (info) => {
41510
+ this.recycleStalledGeneralSession(client, info);
41511
+ });
41230
41512
  client.on("event", (event) => {
41231
41513
  const mapped = mapToSimpleEvent(event);
41232
41514
  if (!mapped) return;
@@ -41875,6 +42157,8 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41875
42157
  resolveSocketTag(sessionKey) {
41876
42158
  const replayMatch = sessionKey.match(/^replay:([^:]+)(?::ch(\d+))?/);
41877
42159
  if (replayMatch) return `replay:${replayMatch[1]}:ch${replayMatch[2] ?? "0"}`;
42160
+ const renewMatch = sessionKey.match(/^(.*)#renew(\d+)$/);
42161
+ if (renewMatch && renewMatch[1]) return `${this.resolveSocketTag(renewMatch[1])}:renew${renewMatch[2]}`;
41878
42162
  const liveMatch = sessionKey.match(/^live:[^:]+:ch(\d+):(\w+)$/);
41879
42163
  if (liveMatch && liveMatch[1] && liveMatch[2]) {
41880
42164
  const channel = parseInt(liveMatch[1], 10);
@@ -42183,8 +42467,27 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
42183
42467
  */
42184
42468
  async createDedicatedSession(sessionKey, logger) {
42185
42469
  const tag2 = this.resolveSocketTag(sessionKey);
42186
- (logger ?? this.logger)?.debug?.(`[SocketPool] createDedicatedSession sessionKey=${sessionKey} \u2192 tag=${tag2}`);
42187
- return await this.acquirePooledSocket(tag2, logger);
42470
+ const log = logger ?? this.logger;
42471
+ log?.debug?.(`[SocketPool] createDedicatedSession sessionKey=${sessionKey} \u2192 tag=${tag2}`);
42472
+ const acquired = await this.acquirePooledSocket(tag2, logger);
42473
+ const stillHoldsPooledSocket = () => this.socketPool.get(tag2)?.client === acquired.client;
42474
+ let settled = false;
42475
+ return {
42476
+ client: acquired.client,
42477
+ release: async () => {
42478
+ if (settled) return;
42479
+ settled = true;
42480
+ if (!stillHoldsPooledSocket()) return;
42481
+ await acquired.release();
42482
+ },
42483
+ invalidate: async (reason) => {
42484
+ if (settled) return;
42485
+ settled = true;
42486
+ if (!stillHoldsPooledSocket()) return;
42487
+ log?.warn?.(`[SocketPool] Discarding socket for tag=${tag2} (sessionKey=${sessionKey}): ${reason}`);
42488
+ await this.forceClosePooledSocket(tag2, logger);
42489
+ }
42490
+ };
42188
42491
  }
42189
42492
  /**
42190
42493
  * @deprecated Use forceClosePooledSocket via createDedicatedSession instead.
@@ -48004,6 +48307,7 @@ ${stderr}`));
48004
48307
  if (n !== void 0) modifiedXml = modifiedXml.replace(/<reduceFalseAlarm>[^<]*<\/reduceFalseAlarm>/, `<reduceFalseAlarm>${n}</reduceFalseAlarm>`);
48005
48308
  }
48006
48309
  if (params.interval !== void 0) modifiedXml = modifiedXml.replace(/<interval>[^<]*<\/interval>/, `<interval>${params.interval}</interval>`);
48310
+ modifiedXml = modifiedXml.replace(/<maxAlarmTime>\s*([^<]*?)\s*<\/maxAlarmTime>/, (match, raw) => /^\d+$/.test(raw) && Number.isSafeInteger(Number(raw)) ? match : "");
48007
48311
  await this.sendXml({
48008
48312
  cmdId: 213,
48009
48313
  channel: ch,
@@ -98736,20 +99040,20 @@ var Rfc4571Muxer = class _Rfc4571Muxer {
98736
99040
  state.untrustedDeltaCount++;
98737
99041
  if (now - state.lastUntrustedDeltaLogMs < intervalMs) return;
98738
99042
  state.lastUntrustedDeltaLogMs = now;
98739
- this.logger.warn(`[rfc4571] video timing: ${message} (untrustedDeltaCount=${state.untrustedDeltaCount})`);
99043
+ this.logger?.warn?.(`[rfc4571] video timing: ${message} (untrustedDeltaCount=${state.untrustedDeltaCount})`);
98740
99044
  return;
98741
99045
  }
98742
99046
  if (kind === "wrap") {
98743
99047
  state.wrapCount++;
98744
99048
  if (now - state.lastWrapLogMs < intervalMs) return;
98745
99049
  state.lastWrapLogMs = now;
98746
- this.logger.warn(`[rfc4571] video timing: ${message} (wrapCount=${state.wrapCount})`);
99050
+ this.logger?.warn?.(`[rfc4571] video timing: ${message} (wrapCount=${state.wrapCount})`);
98747
99051
  return;
98748
99052
  }
98749
99053
  state.resetCount++;
98750
99054
  if (now - state.lastResetLogMs < intervalMs) return;
98751
99055
  state.lastResetLogMs = now;
98752
- this.logger.warn(`[rfc4571] video timing: ${message} (resetCount=${state.resetCount})`);
99056
+ this.logger?.warn?.(`[rfc4571] video timing: ${message} (resetCount=${state.resetCount})`);
98753
99057
  }
98754
99058
  advanceVideoTimestampFallback() {
98755
99059
  this.videoRtp.advanceTimestamp(this.fallbackVideoIncrement);
@@ -98958,6 +99262,547 @@ var Rfc4571Muxer = class _Rfc4571Muxer {
98958
99262
  if (isKeyframeLike) for (const c of this.clients) c.needsKeyframe = false;
98959
99263
  }
98960
99264
  };
99265
+ var RESILIENT_STREAM_DEFAULTS = {
99266
+ silenceMs: 1e4,
99267
+ startTimeoutMs: 15e3,
99268
+ maxRecoveryMs: 10 * 6e4,
99269
+ retryDelayMs: 1e3,
99270
+ maxRetryDelayMs: 15e3,
99271
+ renewKeyframeTimeoutMs: 15e3,
99272
+ renewRetryDelayMs: 3e4,
99273
+ maxRenewAttempts: 2
99274
+ };
99275
+ var UDP_SESSION_RENEW_AFTER_MS = 27 * 6e4;
99276
+ var transportLastVideoAt = /* @__PURE__ */ new WeakMap();
99277
+ var ResilientVideoStream = class extends EventEmitter {
99278
+ constructor(opts) {
99279
+ super();
99280
+ this.opts = opts;
99281
+ const d = RESILIENT_STREAM_DEFAULTS;
99282
+ this.silenceMs = Math.max(0, opts.silenceMs ?? d.silenceMs);
99283
+ this.startTimeoutMs = Math.max(1, opts.startTimeoutMs ?? d.startTimeoutMs);
99284
+ this.maxRecoveryMs = Math.max(0, opts.maxRecoveryMs ?? d.maxRecoveryMs);
99285
+ this.retryDelayMs = Math.max(1, opts.retryDelayMs ?? d.retryDelayMs);
99286
+ this.maxRetryDelayMs = Math.max(this.retryDelayMs, opts.maxRetryDelayMs ?? d.maxRetryDelayMs);
99287
+ this.renewAfterMs = Math.max(0, opts.renewAfterMs ?? 0);
99288
+ this.renewKeyframeTimeoutMs = Math.max(1, opts.renewKeyframeTimeoutMs ?? d.renewKeyframeTimeoutMs);
99289
+ this.renewRetryDelayMs = Math.max(1, opts.renewRetryDelayMs ?? d.renewRetryDelayMs);
99290
+ this.maxRenewAttempts = Math.max(1, opts.maxRenewAttempts ?? d.maxRenewAttempts);
99291
+ this.logger = opts.logger;
99292
+ this.prefix = `[ResilientVideoStream${opts.label ? ` ${opts.label}` : ""}]`;
99293
+ }
99294
+ silenceMs;
99295
+ startTimeoutMs;
99296
+ maxRecoveryMs;
99297
+ retryDelayMs;
99298
+ maxRetryDelayMs;
99299
+ logger;
99300
+ prefix;
99301
+ session = null;
99302
+ stopped = false;
99303
+ started = false;
99304
+ /** Set while the source is lost; cleared by the first video frame after it. */
99305
+ outage = null;
99306
+ /** True while a recovery attempt (teardown + reopen) is in flight. */
99307
+ reopening = false;
99308
+ lastMediaAt = 0;
99309
+ /** Last video from the current session only (0 until it delivers). */
99310
+ lastVideoAt = 0;
99311
+ silenceTimer = null;
99312
+ retryTimer = null;
99313
+ recoveries = 0;
99314
+ renewAfterMs;
99315
+ renewKeyframeTimeoutMs;
99316
+ renewRetryDelayMs;
99317
+ maxRenewAttempts;
99318
+ /** When the live session was opened (its age base). */
99319
+ sessionOpenedAt = 0;
99320
+ renewTimer = null;
99321
+ renewing = false;
99322
+ renewalCount = 0;
99323
+ renewFailures = 0;
99324
+ /** After failed renewals: reopen proactively at the next keyframe. */
99325
+ renewFallbackArmed = false;
99326
+ candidate = null;
99327
+ /**
99328
+ * Added to every `microseconds` the consumer sees, so a renewed session
99329
+ * (its own camera clock) continues the previous one instead of jumping.
99330
+ */
99331
+ tsOffsetUs = 0;
99332
+ /** Last `microseconds` handed to the consumer, and the last frame spacing. */
99333
+ lastEmittedUs;
99334
+ lastFrameDeltaUs = 4e4;
99335
+ /** Number of outages this stream has recovered from. */
99336
+ getRecoveryCount() {
99337
+ return this.recoveries;
99338
+ }
99339
+ isRecovering() {
99340
+ return this.outage !== null;
99341
+ }
99342
+ consumePendingStartupError() {
99343
+ return this.session?.stream.consumePendingStartupError?.();
99344
+ }
99345
+ /**
99346
+ * Opens the first session. A failure here is the caller's: nothing was
99347
+ * delivered yet, so there is no stream to keep alive.
99348
+ */
99349
+ async start() {
99350
+ if (this.stopped) throw new Error("ResilientVideoStream is stopped");
99351
+ if (this.started) return;
99352
+ await this.openAndStart();
99353
+ if (this.stopped) return;
99354
+ this.started = true;
99355
+ this.lastMediaAt = Date.now();
99356
+ this.startSilenceWatch();
99357
+ }
99358
+ async stop() {
99359
+ if (this.stopped) return;
99360
+ this.stopped = true;
99361
+ this.stopSilenceWatch();
99362
+ this.clearRenewTimer();
99363
+ await this.abandonCandidate("stopped");
99364
+ if (this.retryTimer) {
99365
+ clearTimeout(this.retryTimer);
99366
+ this.retryTimer = null;
99367
+ }
99368
+ await this.dropSession(false, "stopped");
99369
+ this.emit("close");
99370
+ }
99371
+ async openAndStart(purpose = "initial") {
99372
+ const session = await this.opts.openSession({ purpose });
99373
+ if (this.stopped) {
99374
+ await session.release().catch(() => {});
99375
+ throw new Error("ResilientVideoStream stopped while opening a session");
99376
+ }
99377
+ this.session = session;
99378
+ this.lastVideoAt = 0;
99379
+ this.tsOffsetUs = 0;
99380
+ this.lastEmittedUs = void 0;
99381
+ this.attach(session.stream);
99382
+ try {
99383
+ await this.startWithDeadline(session.stream);
99384
+ } catch (e) {
99385
+ await this.dropSession(true, `start failed: ${errorMessage$1(e)}`);
99386
+ throw e;
99387
+ }
99388
+ this.sessionOpenedAt = Date.now();
99389
+ this.renewFallbackArmed = false;
99390
+ this.renewFailures = 0;
99391
+ this.scheduleRenewal(this.renewAfterMs);
99392
+ }
99393
+ async startWithDeadline(stream) {
99394
+ let timer;
99395
+ const startPromise = stream.start();
99396
+ const deadline = new Promise((_, reject) => {
99397
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`stream start not answered in ${this.startTimeoutMs}ms`)), this.startTimeoutMs);
99398
+ });
99399
+ try {
99400
+ await Promise.race([startPromise, deadline]);
99401
+ } catch (e) {
99402
+ startPromise.catch(() => {});
99403
+ throw e;
99404
+ } finally {
99405
+ if (timer) clearTimeout(timer);
99406
+ }
99407
+ }
99408
+ attach(stream) {
99409
+ stream.on("videoAccessUnit", this.onAccessUnit);
99410
+ stream.on("additionalHeader", this.onAdditionalHeader);
99411
+ stream.on("audioFrame", this.onAudioFrame);
99412
+ stream.on("error", this.onInnerError);
99413
+ stream.on("close", this.onInnerClose);
99414
+ }
99415
+ detach(stream) {
99416
+ stream.off("videoAccessUnit", this.onAccessUnit);
99417
+ stream.off("additionalHeader", this.onAdditionalHeader);
99418
+ stream.off("audioFrame", this.onAudioFrame);
99419
+ stream.off("error", this.onInnerError);
99420
+ stream.off("close", this.onInnerClose);
99421
+ }
99422
+ /** Detaches and stops the current inner stream, then returns its session. */
99423
+ async dropSession(invalidate, reason, forceDiscard = false) {
99424
+ const session = this.session;
99425
+ if (!session) return;
99426
+ this.session = null;
99427
+ this.detach(session.stream);
99428
+ const discard = invalidate && (forceDiscard || !this.siblingStillFlowing(session));
99429
+ if (invalidate && !discard) this.logger?.warn?.(`${this.prefix} the transport still carries another stream; keeping it and asking again on it`);
99430
+ await session.stream.stop().catch(() => {});
99431
+ if (discard) await session.invalidate(reason).catch(() => {});
99432
+ else await session.release().catch(() => {});
99433
+ }
99434
+ /**
99435
+ * A transport that delivered video to another stream after this one last
99436
+ * saw any is alive: only this stream's request is stuck, and closing the
99437
+ * transport would cut the stream that works.
99438
+ */
99439
+ siblingStillFlowing(session) {
99440
+ if (!session.transport) return false;
99441
+ const transportAt = transportLastVideoAt.get(session.transport);
99442
+ if (transportAt === void 0) return false;
99443
+ const window = this.silenceMs > 0 ? this.silenceMs : 1e4;
99444
+ return transportAt > this.lastVideoAt && Date.now() - transportAt < window;
99445
+ }
99446
+ startSilenceWatch() {
99447
+ if (this.silenceMs <= 0 || this.silenceTimer) return;
99448
+ const tickMs = Math.max(50, Math.min(1e3, Math.floor(this.silenceMs / 4)));
99449
+ this.silenceTimer = setInterval(() => {
99450
+ if (this.stopped || this.reopening || this.retryTimer) return;
99451
+ const silentFor = Date.now() - this.lastMediaAt;
99452
+ if (silentFor < this.silenceMs) return;
99453
+ this.sourceLost(`no media for ${silentFor}ms`);
99454
+ }, tickMs);
99455
+ this.silenceTimer.unref?.();
99456
+ }
99457
+ stopSilenceWatch() {
99458
+ if (!this.silenceTimer) return;
99459
+ clearInterval(this.silenceTimer);
99460
+ this.silenceTimer = null;
99461
+ }
99462
+ /**
99463
+ * The guard's verdict, with a throw read as a refusal: not knowing whether
99464
+ * the camera sleeps is not permission to wake it.
99465
+ */
99466
+ recoveryVerdict() {
99467
+ const guard = this.opts.recoveryGuard;
99468
+ if (!guard) return { allowed: true };
99469
+ try {
99470
+ return guard();
99471
+ } catch (e) {
99472
+ return {
99473
+ allowed: false,
99474
+ reason: `sleep state unknown (${errorMessage$1(e)})`
99475
+ };
99476
+ }
99477
+ }
99478
+ /** Ends the stream without reopening: the camera must not be woken by us. */
99479
+ async refuseRecovery(lost, refusal) {
99480
+ if (this.stopped) return;
99481
+ this.stopped = true;
99482
+ this.stopSilenceWatch();
99483
+ this.clearRenewTimer();
99484
+ await this.abandonCandidate("recovery refused");
99485
+ if (this.retryTimer) {
99486
+ clearTimeout(this.retryTimer);
99487
+ this.retryTimer = null;
99488
+ }
99489
+ this.logger?.warn?.(`${this.prefix} source lost (${lost}); not recovering: ${refusal}`);
99490
+ await this.dropSession(true, lost);
99491
+ const err = /* @__PURE__ */ new Error(`${this.prefix} source lost (${lost}); recovery refused: ${refusal}`);
99492
+ if (this.listenerCount("error") > 0) this.emit("error", err);
99493
+ this.emit("close");
99494
+ }
99495
+ /** Entry point for every way the source can be lost. */
99496
+ sourceLost(reason) {
99497
+ if (this.stopped || !this.started) return;
99498
+ if (this.reopening || this.retryTimer) return;
99499
+ this.clearRenewTimer();
99500
+ this.abandonCandidate(`source lost (${reason})`);
99501
+ const verdict = this.recoveryVerdict();
99502
+ if (!verdict.allowed) {
99503
+ this.refuseRecovery(reason, verdict.reason);
99504
+ return;
99505
+ }
99506
+ if (!this.outage) {
99507
+ this.outage = {
99508
+ reason,
99509
+ lostAt: Date.now(),
99510
+ attempts: 0
99511
+ };
99512
+ this.logger?.warn?.(`${this.prefix} source lost (${reason}); recovering on a new session`);
99513
+ this.emit("recovering", { reason });
99514
+ } else this.logger?.warn?.(`${this.prefix} still no video after attempt ${this.outage.attempts} (${reason}); retrying`);
99515
+ const delay = this.outage.attempts > 0 ? this.backoffDelay(this.outage.attempts) : 0;
99516
+ if (delay === 0) {
99517
+ this.reopen(reason);
99518
+ return;
99519
+ }
99520
+ this.logger?.warn?.(`${this.prefix} next attempt in ${delay}ms (silence after attempt ${this.outage.attempts})`);
99521
+ this.dropSession(true, reason);
99522
+ this.scheduleReopen(reason, delay);
99523
+ }
99524
+ backoffDelay(attempts) {
99525
+ return Math.min(this.maxRetryDelayMs, this.retryDelayMs * 2 ** Math.min(Math.max(attempts - 1, 0), 10));
99526
+ }
99527
+ scheduleReopen(reason, delay) {
99528
+ this.retryTimer = setTimeout(() => {
99529
+ this.retryTimer = null;
99530
+ this.reopen(reason);
99531
+ }, delay);
99532
+ this.retryTimer.unref?.();
99533
+ }
99534
+ async reopen(reason, forceDiscard = false) {
99535
+ const outage = this.outage;
99536
+ if (!outage || this.stopped || this.reopening) return;
99537
+ this.reopening = true;
99538
+ try {
99539
+ await this.dropSession(true, reason, forceDiscard);
99540
+ if (this.stopped) return;
99541
+ if (Date.now() - outage.lostAt >= this.maxRecoveryMs) {
99542
+ this.giveUp(outage);
99543
+ return;
99544
+ }
99545
+ const verdict = this.recoveryVerdict();
99546
+ if (!verdict.allowed) {
99547
+ this.reopening = false;
99548
+ await this.refuseRecovery(reason, verdict.reason);
99549
+ return;
99550
+ }
99551
+ outage.attempts++;
99552
+ try {
99553
+ await this.openAndStart("recovery");
99554
+ this.lastMediaAt = Date.now();
99555
+ this.logger?.debug?.(`${this.prefix} attempt ${outage.attempts}: stream re-requested, waiting for video`);
99556
+ } catch (e) {
99557
+ if (this.stopped) return;
99558
+ const delay = this.backoffDelay(outage.attempts);
99559
+ this.logger?.warn?.(`${this.prefix} attempt ${outage.attempts} failed (${errorMessage$1(e)}); next in ${delay}ms`);
99560
+ this.scheduleReopen(reason, delay);
99561
+ }
99562
+ } finally {
99563
+ this.reopening = false;
99564
+ }
99565
+ }
99566
+ clearRenewTimer() {
99567
+ if (!this.renewTimer) return;
99568
+ clearTimeout(this.renewTimer);
99569
+ this.renewTimer = null;
99570
+ }
99571
+ /** Arms the renewal for when the live session reaches `renewAfterMs`. */
99572
+ scheduleRenewal(delayMs) {
99573
+ this.clearRenewTimer();
99574
+ if (this.renewAfterMs <= 0 || this.stopped) return;
99575
+ this.renewTimer = setTimeout(() => {
99576
+ this.renewTimer = null;
99577
+ this.renewSession();
99578
+ }, Math.max(0, delayMs));
99579
+ this.renewTimer.unref?.();
99580
+ }
99581
+ async renewSession() {
99582
+ if (this.stopped || !this.started) return;
99583
+ if (this.renewing || this.candidate) return;
99584
+ if (this.reopening || this.retryTimer || this.outage) return;
99585
+ const verdict = this.recoveryVerdict();
99586
+ if (!verdict.allowed) {
99587
+ const retry = this.withinRenewWindow();
99588
+ this.logger?.warn?.(`${this.prefix} session renewal refused: ${verdict.reason}${retry ? `; asking again in ${this.renewRetryDelayMs}ms` : "; past the renewal window, leaving it to recovery"}`);
99589
+ if (retry) this.scheduleRenewal(this.renewRetryDelayMs);
99590
+ return;
99591
+ }
99592
+ const age = Date.now() - this.sessionOpenedAt;
99593
+ this.renewing = true;
99594
+ this.logger?.info?.(`${this.prefix} renewing session at age=${age}ms (make-before-break)`);
99595
+ const renewalId = this.renewalCount++ % 2;
99596
+ let session;
99597
+ try {
99598
+ session = await this.opts.openSession({
99599
+ purpose: "renewal",
99600
+ renewalId
99601
+ });
99602
+ } catch (e) {
99603
+ this.renewing = false;
99604
+ this.renewalFailed(`could not open a second session: ${errorMessage$1(e)}`);
99605
+ return;
99606
+ }
99607
+ if (this.stopped || this.outage) {
99608
+ this.renewing = false;
99609
+ await session.invalidate("renewal no longer needed").catch(() => {});
99610
+ return;
99611
+ }
99612
+ const cand = {
99613
+ session,
99614
+ openedAt: Date.now(),
99615
+ header: void 0,
99616
+ onAccessUnit: (...args) => this.onCandidateAccessUnit(cand, args[0]),
99617
+ onHeader: (...args) => {
99618
+ cand.header = args;
99619
+ },
99620
+ onFail: (...args) => {
99621
+ this.abandonCandidate(`renewal session failed: ${errorMessage$1(args[0])}`).then(() => this.renewalFailed(`renewal session failed: ${errorMessage$1(args[0])}`));
99622
+ },
99623
+ deadline: null
99624
+ };
99625
+ this.candidate = cand;
99626
+ session.stream.on("videoAccessUnit", cand.onAccessUnit);
99627
+ session.stream.on("additionalHeader", cand.onHeader);
99628
+ session.stream.on("error", cand.onFail);
99629
+ session.stream.on("close", cand.onFail);
99630
+ try {
99631
+ await this.startWithDeadline(session.stream);
99632
+ } catch (e) {
99633
+ this.renewing = false;
99634
+ if (this.candidate !== cand) return;
99635
+ await this.abandonCandidate("start failed");
99636
+ this.renewalFailed(`second session did not start: ${errorMessage$1(e)}`);
99637
+ return;
99638
+ }
99639
+ this.renewing = false;
99640
+ if (this.candidate !== cand) return;
99641
+ cand.deadline = setTimeout(() => {
99642
+ cand.deadline = null;
99643
+ this.abandonCandidate("no keyframe in time").then(() => this.renewalFailed(`second session delivered no keyframe in ${this.renewKeyframeTimeoutMs}ms`));
99644
+ }, this.renewKeyframeTimeoutMs);
99645
+ cand.deadline.unref?.();
99646
+ }
99647
+ /** First keyframe of the candidate: switch the consumer over, then close the old one. */
99648
+ onCandidateAccessUnit(cand, au) {
99649
+ if (this.candidate !== cand || !au.isKeyframe) return;
99650
+ const old = this.session;
99651
+ this.candidate = null;
99652
+ if (cand.deadline) clearTimeout(cand.deadline);
99653
+ cand.deadline = null;
99654
+ this.detachCandidate(cand);
99655
+ if (this.stopped) {
99656
+ cand.session.invalidate("stopped").catch(() => {});
99657
+ return;
99658
+ }
99659
+ const previousAgeMs = Date.now() - this.sessionOpenedAt;
99660
+ if (old) this.detach(old.stream);
99661
+ this.session = cand.session;
99662
+ this.sessionOpenedAt = cand.openedAt;
99663
+ this.lastVideoAt = 0;
99664
+ this.renewFailures = 0;
99665
+ this.attach(cand.session.stream);
99666
+ if (this.lastEmittedUs !== void 0) this.tsOffsetUs = this.lastEmittedUs + this.lastFrameDeltaUs - au.microseconds | 0;
99667
+ if (cand.header) this.emit("additionalHeader", this.rebaseHeader(cand.header[0]));
99668
+ this.onAccessUnit(au);
99669
+ this.scheduleRenewal(this.renewAfterMs);
99670
+ this.logger?.info?.(`${this.prefix} switched to the renewed session (previous age=${previousAgeMs}ms); closing the old one`);
99671
+ this.emit("renewed", { previousAgeMs });
99672
+ if (old) (async () => {
99673
+ await old.stream.stop().catch(() => {});
99674
+ await old.invalidate("session renewed").catch(() => {});
99675
+ })();
99676
+ }
99677
+ detachCandidate(cand) {
99678
+ cand.session.stream.off("videoAccessUnit", cand.onAccessUnit);
99679
+ cand.session.stream.off("additionalHeader", cand.onHeader);
99680
+ cand.session.stream.off("error", cand.onFail);
99681
+ cand.session.stream.off("close", cand.onFail);
99682
+ }
99683
+ /** Discards a candidate that never took over. The live session is untouched. */
99684
+ async abandonCandidate(reason) {
99685
+ const cand = this.candidate;
99686
+ if (!cand) return;
99687
+ this.candidate = null;
99688
+ if (cand.deadline) clearTimeout(cand.deadline);
99689
+ cand.deadline = null;
99690
+ this.detachCandidate(cand);
99691
+ await cand.session.stream.stop().catch(() => {});
99692
+ await cand.session.invalidate(reason).catch(() => {});
99693
+ }
99694
+ renewalFailed(why) {
99695
+ if (this.stopped) return;
99696
+ this.renewFailures++;
99697
+ if (this.renewFailures >= this.maxRenewAttempts) {
99698
+ this.logger?.warn?.(`${this.prefix} session renewal failed ${this.renewFailures}x (${why}); falling back to a proactive reopen at the next keyframe`);
99699
+ this.renewFallbackArmed = true;
99700
+ return;
99701
+ }
99702
+ this.logger?.warn?.(`${this.prefix} session renewal failed (${why}); retrying in ${this.renewRetryDelayMs}ms`);
99703
+ this.scheduleRenewal(this.renewRetryDelayMs);
99704
+ }
99705
+ /**
99706
+ * Renewal is pointless once the session is well past the age at which the
99707
+ * camera ends it (~30 min against a 27 min default): +3 min of margin.
99708
+ */
99709
+ withinRenewWindow() {
99710
+ return Date.now() - this.sessionOpenedAt < this.renewAfterMs + 18e4;
99711
+ }
99712
+ /** Planned break-before-make renewal, entered right after a keyframe. */
99713
+ proactiveReopen() {
99714
+ if (this.stopped || this.reopening || this.outage || this.retryTimer) return;
99715
+ if (!this.recoveryVerdict().allowed) {
99716
+ this.renewFallbackArmed = this.withinRenewWindow();
99717
+ return;
99718
+ }
99719
+ const reason = `proactive session renewal at age=${Date.now() - this.sessionOpenedAt}ms`;
99720
+ this.outage = {
99721
+ reason,
99722
+ lostAt: Date.now(),
99723
+ attempts: 0
99724
+ };
99725
+ this.logger?.warn?.(`${this.prefix} ${reason}; reopening on a new session`);
99726
+ this.emit("recovering", { reason });
99727
+ this.reopen(reason, true);
99728
+ }
99729
+ giveUp(outage) {
99730
+ const err = /* @__PURE__ */ new Error(`${this.prefix} source not recovered after ${Date.now() - outage.lostAt}ms and ${outage.attempts} attempt(s) (${outage.reason})`);
99731
+ this.logger?.warn?.(err.message);
99732
+ this.stopped = true;
99733
+ this.stopSilenceWatch();
99734
+ this.clearRenewTimer();
99735
+ this.abandonCandidate("gave up");
99736
+ if (this.listenerCount("error") > 0) this.emit("error", err);
99737
+ this.emit("close");
99738
+ }
99739
+ onAccessUnit = (...args) => {
99740
+ const au = this.rebase(args[0]);
99741
+ this.lastMediaAt = Date.now();
99742
+ this.lastVideoAt = this.lastMediaAt;
99743
+ const transport = this.session?.transport;
99744
+ if (transport) transportLastVideoAt.set(transport, this.lastMediaAt);
99745
+ const outage = this.outage;
99746
+ if (outage) {
99747
+ if (!au.isKeyframe) return;
99748
+ this.outage = null;
99749
+ this.recoveries++;
99750
+ const info = {
99751
+ reason: outage.reason,
99752
+ outageMs: Date.now() - outage.lostAt,
99753
+ attempts: outage.attempts
99754
+ };
99755
+ (this.logger?.info ?? this.logger?.log)?.call(this.logger, `${this.prefix} recovered after ${info.outageMs}ms attempts=${info.attempts} (${info.reason})`);
99756
+ this.emit("recovered", info);
99757
+ }
99758
+ this.trackEmittedUs(au.microseconds);
99759
+ this.emit("videoAccessUnit", au);
99760
+ if (this.renewFallbackArmed && au.isKeyframe && !this.outage) {
99761
+ this.renewFallbackArmed = false;
99762
+ this.proactiveReopen();
99763
+ }
99764
+ };
99765
+ onAdditionalHeader = (...args) => {
99766
+ this.emit("additionalHeader", this.rebaseHeader(args[0]));
99767
+ };
99768
+ rebase(au) {
99769
+ if (this.tsOffsetUs === 0) return au;
99770
+ return {
99771
+ ...au,
99772
+ microseconds: au.microseconds + this.tsOffsetUs >>> 0
99773
+ };
99774
+ }
99775
+ rebaseHeader(h) {
99776
+ if (this.tsOffsetUs === 0 || typeof h !== "object" || h === null) return h;
99777
+ const us = h.microseconds;
99778
+ if (typeof us !== "number") return h;
99779
+ return {
99780
+ ...h,
99781
+ microseconds: us + this.tsOffsetUs >>> 0
99782
+ };
99783
+ }
99784
+ trackEmittedUs(us) {
99785
+ if (this.lastEmittedUs !== void 0) {
99786
+ const d = us - this.lastEmittedUs >>> 0;
99787
+ if (d >= 1e3 && d <= 1e6) this.lastFrameDeltaUs = d;
99788
+ }
99789
+ this.lastEmittedUs = us;
99790
+ }
99791
+ onAudioFrame = (...args) => {
99792
+ if (this.outage) return;
99793
+ this.emit("audioFrame", args[0]);
99794
+ };
99795
+ onInnerError = (...args) => {
99796
+ this.sourceLost(`stream error: ${errorMessage$1(args[0])}`);
99797
+ };
99798
+ onInnerClose = () => {
99799
+ this.sourceLost("stream closed by the camera or the transport");
99800
+ };
99801
+ };
99802
+ function errorMessage$1(e) {
99803
+ if (e instanceof Error) return e.message;
99804
+ return String(e);
99805
+ }
98961
99806
  function calculateOverlayPosition(position, mainWidth, mainHeight, pipWidth, pipHeight, margin) {
98962
99807
  const pipW = Math.floor(pipWidth);
98963
99808
  const pipH = Math.floor(pipHeight);
@@ -99709,6 +100554,17 @@ var CompositeStream = class extends EventEmitter {
99709
100554
  return this.active;
99710
100555
  }
99711
100556
  };
100557
+ var STREAM_METADATA_DEADLINE_MS = 5e3;
100558
+ function withDeadline(work, deadlineMs, what) {
100559
+ let timer;
100560
+ const deadline = new Promise((_, reject) => {
100561
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} not answered in ${deadlineMs}ms`)), deadlineMs);
100562
+ });
100563
+ work.catch(() => {});
100564
+ return Promise.race([work, deadline]).finally(() => {
100565
+ if (timer) clearTimeout(timer);
100566
+ });
100567
+ }
99712
100568
  async function createRfc4571TcpServer(options) {
99713
100569
  const sharedProcessId = typeof process !== "undefined" && typeof process.pid === "number" ? process.pid : "n/a";
99714
100570
  const sharedInstanceId = (() => {
@@ -99872,7 +100728,10 @@ async function createRfc4571TcpServerInternal(options) {
99872
100728
  apisToClose.add(baseApi);
99873
100729
  if (resolvedCompositeApis?.widerApi) apisToClose.add(resolvedCompositeApis.widerApi);
99874
100730
  if (resolvedCompositeApis?.teleApi) apisToClose.add(resolvedCompositeApis.teleApi);
99875
- const uptimeRestartMs = Boolean(options.alwaysOn?.enabled) && !isComposite ? 0 : uptimeRestartMsOpt ?? (isComposite ? 6e4 : 1e4);
100731
+ const alwaysOnEnabled = Boolean(options.alwaysOn?.enabled) && !isComposite;
100732
+ const resilienceEnabled = !isComposite && !alwaysOnEnabled && Boolean(options.deviceId) && options.resilience?.enabled !== false;
100733
+ const sourceSilenceMs = options.resilience?.silenceMs ?? uptimeRestartMsOpt ?? 1e4;
100734
+ const uptimeRestartMs = alwaysOnEnabled || resilienceEnabled ? 0 : uptimeRestartMsOpt ?? (isComposite ? 6e4 : 1e4);
99876
100735
  const variantSuffix = variant && variant !== "default" ? ` variant=${variant}` : "";
99877
100736
  const logPrefix = isComposite ? `[native-rfc4571 composite profile=${profile}${variantSuffix}${requestedId ? ` id=${requestedId}` : ""}]` : `[native-rfc4571 ch=${channel} profile=${profile}${variantSuffix}]`;
99878
100737
  const log = (message) => {
@@ -99989,8 +100848,8 @@ async function createRfc4571TcpServerInternal(options) {
99989
100848
  const ch = channel;
99990
100849
  const deviceId = options.deviceId;
99991
100850
  let streamClient;
100851
+ const sessionKey = `live:${deviceId}:ch${ch}:${profile}${variant && variant !== "default" ? `:${variant}` : ""}`;
99992
100852
  if (deviceId) {
99993
- const sessionKey = `live:${deviceId}:ch${ch}:${profile}${variant && variant !== "default" ? `:${variant}` : ""}`;
99994
100853
  dedicatedSession = await baseApi.createDedicatedSession(sessionKey, logger);
99995
100854
  streamClient = dedicatedSession.client;
99996
100855
  logSessionsSummary(`dedicated session created: ${sessionKey}`);
@@ -100022,6 +100881,53 @@ async function createRfc4571TcpServerInternal(options) {
100022
100881
  await alwaysOnController.start();
100023
100882
  videoStream = cvs;
100024
100883
  log(`always-on stream started (ch=${ch} profile=${profile}${deviceId ? ` dedicated=${deviceId}` : ""})`);
100884
+ } else if (resilienceEnabled && dedicatedSession) {
100885
+ let firstSession = dedicatedSession;
100886
+ const resilient = new ResilientVideoStream({
100887
+ label: `ch=${ch} profile=${profile}`,
100888
+ silenceMs: sourceSilenceMs,
100889
+ renewAfterMs: resolveRenewAfterMs(options.resilience, baseApi.client.getTransport?.()),
100890
+ recoveryGuard: resolveRecoveryGuard(options.resilience, () => baseApi.client.getTransport?.()),
100891
+ ...options.resilience?.maxRecoveryMs !== void 0 ? { maxRecoveryMs: options.resilience.maxRecoveryMs } : {},
100892
+ logger,
100893
+ openSession: async (ctx) => {
100894
+ const key = ctx?.purpose === "renewal" ? `${sessionKey}#renew${ctx.renewalId ?? 0}` : sessionKey;
100895
+ const session = firstSession ?? await baseApi.createDedicatedSession(key, logger);
100896
+ firstSession = void 0;
100897
+ return {
100898
+ stream: new BaichuanVideoStream({
100899
+ client: session.client,
100900
+ api: baseApi,
100901
+ channel: ch,
100902
+ profile,
100903
+ variant,
100904
+ logger
100905
+ }),
100906
+ release: session.release,
100907
+ invalidate: session.invalidate,
100908
+ transport: session.client
100909
+ };
100910
+ }
100911
+ });
100912
+ let releaseRecoveryPermit;
100913
+ const dropRecoveryPermit = () => {
100914
+ const release = releaseRecoveryPermit;
100915
+ releaseRecoveryPermit = void 0;
100916
+ try {
100917
+ release?.();
100918
+ } catch {}
100919
+ };
100920
+ resilient.on("recovering", () => {
100921
+ dropRecoveryPermit();
100922
+ try {
100923
+ releaseRecoveryPermit = baseApi.client.acquirePermit?.(options.resilience?.maxRecoveryMs ?? RESILIENT_STREAM_DEFAULTS.maxRecoveryMs, `stream-recovery:${sessionKey}`);
100924
+ } catch {}
100925
+ });
100926
+ resilient.on("recovered", dropRecoveryPermit);
100927
+ resilient.on("close", dropRecoveryPermit);
100928
+ await resilient.start();
100929
+ videoStream = resilient;
100930
+ log(`stream started (ch=${ch} profile=${profile} dedicated=${deviceId} self-healing silenceMs=${sourceSilenceMs})`);
100025
100931
  } else {
100026
100932
  const live = await createLiveStream();
100027
100933
  await live.start();
@@ -100153,8 +101059,10 @@ async function createRfc4571TcpServerInternal(options) {
100153
101059
  }
100154
101060
  throw e;
100155
101061
  }
101062
+ log(`keyframe received (video=${keyframe.videoType})`);
100156
101063
  if (expectedVideoType && keyframe.videoType !== expectedVideoType) log(`expectedVideoType mismatch (expected=${expectedVideoType} actual=${keyframe.videoType})`);
100157
101064
  let fps = 25;
101065
+ const metadataStartedAt = Date.now();
100158
101066
  try {
100159
101067
  if (isComposite) {
100160
101068
  const widerChannel = compositeOptions?.widerChannel ?? 0;
@@ -100172,12 +101080,14 @@ async function createRfc4571TcpServerInternal(options) {
100172
101080
  const fr = Number(stream?.frameRate);
100173
101081
  if (Number.isFinite(fr) && fr > 0) fps = fr;
100174
101082
  } else {
100175
- const metadata = await baseApi.getStreamMetadata(channel);
101083
+ const metadata = await withDeadline(baseApi.getStreamMetadata(channel), STREAM_METADATA_DEADLINE_MS, "stream metadata");
100176
101084
  const stream = (Array.isArray(metadata) ? metadata : Array.isArray(metadata?.streams) ? metadata.streams : []).find((s) => s?.profile === profile);
100177
101085
  const fr = Number(stream?.frameRate);
100178
101086
  if (Number.isFinite(fr) && fr > 0) fps = fr;
100179
101087
  }
100180
- } catch {}
101088
+ } catch (e) {
101089
+ log(`stream metadata unavailable after ${Date.now() - metadataStartedAt}ms, keeping fps=${fps} (${e instanceof Error ? e.message : String(e)})`);
101090
+ }
100181
101091
  let audio;
100182
101092
  const tryPrimeAudio = async () => {
100183
101093
  return await new Promise((resolve) => {
@@ -100521,6 +101431,21 @@ async function createRfc4571TcpServerInternal(options) {
100521
101431
  close
100522
101432
  };
100523
101433
  }
101434
+ var SLEEPER_REFUSAL = {
101435
+ allowed: false,
101436
+ reason: "the camera sleeps: a new session would wake it, so dialling again is the caller's decision"
101437
+ };
101438
+ var ALWAYS_RECOVER = { allowed: true };
101439
+ function resolveRenewAfterMs(resilience, transport) {
101440
+ if (resilience?.renewAfterMs !== void 0) return resilience.renewAfterMs;
101441
+ return transport === "udp" ? UDP_SESSION_RENEW_AFTER_MS : 0;
101442
+ }
101443
+ function resolveRecoveryGuard(resilience, transport) {
101444
+ if (resilience?.recoveryGuard) return resilience.recoveryGuard;
101445
+ if (resilience?.sleeps === true) return () => SLEEPER_REFUSAL;
101446
+ if (resilience?.sleeps === false) return () => ALWAYS_RECOVER;
101447
+ return () => transport() === "udp" ? SLEEPER_REFUSAL : ALWAYS_RECOVER;
101448
+ }
100524
101449
  Buffer.from([
100525
101450
  0,
100526
101451
  0,
@@ -105890,7 +106815,9 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
105890
106815
  * only way to keep the broker dialable. Camera providers (Reolink
105891
106816
  * Baichuan native, …) subscribe and respond by re-running their publish
105892
106817
  * pipeline.
105893
- * Payload: `{ deviceId, camStreamId, brokerId }`.
106818
+ * Payload: `{ deviceId, camStreamId, brokerId, reason? }`. `reason` is
106819
+ * `'source-silent'` when a no-packet watchdog asked: a still-listening cached
106820
+ * server is then the dead one and must be recreated.
105894
106821
  */
105895
106822
  EventCategory["StreamBrokerOnRequestStreamSourceRefresh"] = "stream-broker.onRequestStreamSourceRefresh";
105896
106823
  /**
@@ -105922,9 +106849,9 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
105922
106849
  */
105923
106850
  EventCategory["DeviceStateChanged"] = "device.state-changed";
105924
106851
  /**
105925
- * A device COMMAND (a vocabulary action, D920/D983) settled in the hub's
105926
- * transition audit (D1022): confirmed, already in place, unconfirmed or
105927
- * failed. Never a device's own change. Payload: `DeviceCommandSettledEvent`
106852
+ * A device COMMAND (a vocabulary action, D920/D983) completed, as the hub's
106853
+ * command audit saw it (D1022, D1084): the call returned (`ok`) or threw
106854
+ * (`failed`). Never a device's own change, and never proof the device obeyed. Payload: `DeviceCommandSettledEvent`
105928
106855
  * (`{deviceId, action, outcome, actor, at}`, no arguments). It feeds
105929
106856
  * the Notification Center `device-command` kind. Telemetry (D8): losing one
105930
106857
  * costs a notification, never state; the audit row is the record.
@@ -106695,7 +107622,8 @@ function typeOf(field) {
106695
107622
  case "timezone":
106696
107623
  case "datetime": return "string";
106697
107624
  case "number":
106698
- case "slider": return "number";
107625
+ case "slider":
107626
+ case "duration": return "number";
106699
107627
  case "boolean": return "boolean";
106700
107628
  default: return "other";
106701
107629
  }
@@ -106793,12 +107721,41 @@ async function guarded(work) {
106793
107721
  };
106794
107722
  }
106795
107723
  }
107724
+ var WAITING_REASON = /^dependency-(?:pending|blocked):(.+)$/;
107725
+ /**
107726
+ * What an owner keeps between runs: the steps blocked only on a predecessor not yet applied.
107727
+ * The engine announces every applied id (`migration.applied`); {@link releasedBy} says which
107728
+ * waiting steps that frees, so the owner runs them again without a restart or a timer.
107729
+ */
107730
+ var MigrationDependencyWaits = class {
107731
+ waiting = /* @__PURE__ */ new Map();
107732
+ /** Replace what is waiting for the ids this run judged (a step that moved on stops waiting). */
107733
+ record(report, judged) {
107734
+ for (const id of judged) this.waiting.delete(id);
107735
+ for (const entry of report.awaiting) this.waiting.set(entry.id, entry.on);
107736
+ }
107737
+ /** Waiting steps whose predecessor is among `applied`; they stop waiting (the rerun re-records). */
107738
+ releasedBy(applied) {
107739
+ const freed = [...this.waiting].filter(([, on]) => applied.includes(on)).map(([id]) => id);
107740
+ for (const id of freed) this.waiting.delete(id);
107741
+ return freed;
107742
+ }
107743
+ get size() {
107744
+ return this.waiting.size;
107745
+ }
107746
+ };
107747
+ /** The ids a `migration.applied` event carries; anything else yields none. */
107748
+ function appliedIdsOf(data) {
107749
+ if (typeof data !== "object" || data === null || !("ids" in data) || !Array.isArray(data.ids)) return [];
107750
+ return data.ids.filter((id) => typeof id === "string");
107751
+ }
106796
107752
  var NOT_RUN = {
106797
107753
  declared: false,
106798
107754
  snapshot: null,
106799
107755
  applied: [],
106800
107756
  failed: [],
106801
107757
  blocked: [],
107758
+ awaiting: [],
106802
107759
  skipped: [],
106803
107760
  blockOwner: []
106804
107761
  };
@@ -106818,7 +107775,8 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106818
107775
  declaration = await host.declareOwner({
106819
107776
  owner,
106820
107777
  metas: migrations.map((m) => m.meta),
106821
- ...options.retired === void 0 ? {} : { retired: [...options.retired] }
107778
+ ...options.retired === void 0 ? {} : { retired: [...options.retired] },
107779
+ ...options.complete === void 0 ? {} : { complete: options.complete }
106822
107780
  });
106823
107781
  } catch (err) {
106824
107782
  log.error("the migration engine refused or could not take this addon catalogue — none ran", { meta: { error: errMsg$3(err) } });
@@ -106830,6 +107788,7 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106830
107788
  const applied = [];
106831
107789
  const failed = [];
106832
107790
  const blocked = [];
107791
+ const awaiting = [];
106833
107792
  const skipped = [];
106834
107793
  const settle = (id, status) => {
106835
107794
  if (status === "applied") applied.push(id);
@@ -106839,10 +107798,12 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106839
107798
  };
106840
107799
  const selected = options.only === void 0 ? null : new Set(options.only);
106841
107800
  const deferred = /* @__PURE__ */ new Set();
107801
+ const settledEarlier = new Set(options.settledEarlier ?? []);
106842
107802
  const deferredBy = (reason) => {
106843
107803
  if (selected === null || reason === null) return null;
106844
107804
  const dep = /^dependency-(?:pending|blocked):(.+)$/.exec(reason)?.[1];
106845
107805
  if (dep === void 0 || !byId.has(dep)) return null;
107806
+ if (settledEarlier.has(dep)) return null;
106846
107807
  return !selected.has(dep) || deferred.has(dep) ? dep : null;
106847
107808
  };
106848
107809
  for (const step of declaration.steps) {
@@ -106876,6 +107837,11 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106876
107837
  reason: gate.reason
106877
107838
  }
106878
107839
  });
107840
+ const on = WAITING_REASON.exec(gate.reason ?? "")?.[1];
107841
+ if (on !== void 0) awaiting.push({
107842
+ id: step.id,
107843
+ on
107844
+ });
106879
107845
  settle(step.id, gate.state === "pending" ? "blocked" : gate.state);
106880
107846
  continue;
106881
107847
  }
@@ -106908,6 +107874,7 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106908
107874
  applied,
106909
107875
  failed,
106910
107876
  blocked,
107877
+ awaiting,
106911
107878
  skipped,
106912
107879
  blockOwner
106913
107880
  };
@@ -108975,6 +109942,7 @@ var BaseAddon = class {
108975
109942
  });
108976
109943
  await this.hydrateSwitches();
108977
109944
  const result = await this.onInitialize();
109945
+ this.catalogueOpen = false;
108978
109946
  await this.moveLateInstanceKinds();
108979
109947
  await this.adoptUnrowed();
108980
109948
  if (this.switchesHydrated) {
@@ -109022,7 +109990,23 @@ var BaseAddon = class {
109022
109990
  registrySwitchSpec = null;
109023
109991
  /** The instance kinds whose switch move this process already ran (or tried), by record kind name. */
109024
109992
  switchMoved = /* @__PURE__ */ new Set();
109025
- lastDeclared = [];
109993
+ /**
109994
+ * Every migration any `runMigrations` call of this process declared, by id. The engine replaces
109995
+ * an owner's catalogue on each declare, so each call carries the union, phased to its own ids.
109996
+ */
109997
+ declaredAll = /* @__PURE__ */ new Map();
109998
+ /** True until `initialize` has run `onInitialize`: more kinds and calls may still declare. */
109999
+ catalogueOpen = true;
110000
+ declaredIncomplete = false;
110001
+ /**
110002
+ * Every switch migration this process added to a declaration so far, by id. The engine replaces
110003
+ * an owner's catalogue on each declare, so a later one (a late kind) carries them all: dropping
110004
+ * an earlier id would read its applied ledger row as a newer database.
110005
+ */
110006
+ switchDeclared = /* @__PURE__ */ new Map();
110007
+ /** The seq each kind's move got, fixed at its first declare so its id and seq never change. */
110008
+ switchSeqs = /* @__PURE__ */ new Map();
110009
+ moveInDeclared = false;
109026
110010
  registrySwitchBound() {
109027
110011
  const api = this.ctx.migrationApi;
109028
110012
  const spec = this.registrySwitchSpec;
@@ -109033,7 +110017,7 @@ var BaseAddon = class {
109033
110017
  return [];
109034
110018
  }
109035
110019
  const date = "2026-11-06";
109036
- const moveIn = spec === null ? [] : migrationSet([registrySwitchToBodyMigration({
110020
+ const moveIn = spec === null || this.moveInDeclared ? [] : migrationSet([registrySwitchToBodyMigration({
109037
110021
  addonId: this.ctx.id,
109038
110022
  date,
109039
110023
  seq: 1e3,
@@ -109043,12 +110027,15 @@ var BaseAddon = class {
109043
110027
  records: switchRecordsOverMigrationApi(a),
109044
110028
  kind: spec.kind
109045
110029
  })).bind(api);
109046
- const moveBack = kinds.flatMap(({ kind }, index) => {
110030
+ if (spec !== null) this.moveInDeclared = true;
110031
+ const moveBack = kinds.flatMap(({ kind }) => {
109047
110032
  this.switchMoved.add(kind.name);
110033
+ const seq = 1001 + this.switchSeqs.size;
110034
+ this.switchSeqs.set(kind.name, seq);
109048
110035
  return migrationSet([bodySwitchToRegistryMigration({
109049
110036
  addonId: this.ctx.id,
109050
110037
  date: "2026-11-19",
109051
- seq: 1001 + index,
110038
+ seq,
109052
110039
  kindName: kind.name,
109053
110040
  ...spec === null ? {} : { followsDate: date }
109054
110041
  })], (a) => bodySwitchPortsOver({
@@ -109074,33 +110061,105 @@ var BaseAddon = class {
109074
110061
  */
109075
110062
  async moveLateInstanceKinds() {
109076
110063
  const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
109077
- if (late.length === 0) return;
110064
+ if (late.length === 0) {
110065
+ if (!this.declaredIncomplete) return;
110066
+ try {
110067
+ await this.runBound([], { only: [] });
110068
+ } catch (err) {
110069
+ if (err instanceof AddonMigrationsBlockedError) throw err;
110070
+ this.ctx.logger.error("the closing migration declare failed", { meta: { error: errMsg$3(err) } });
110071
+ }
110072
+ return;
110073
+ }
109078
110074
  try {
109079
110075
  const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
109080
- await this.runBound(this.lastDeclared, { only });
110076
+ await this.runBound([], { only });
109081
110077
  } catch (err) {
109082
110078
  if (err instanceof AddonMigrationsBlockedError) throw err;
109083
110079
  this.ctx.logger.error("the late instance switch move failed", { meta: { error: errMsg$3(err) } });
109084
110080
  }
109085
110081
  }
110082
+ /** Steps blocked only on another owner's step that has not applied yet (run again when it does). */
110083
+ migrationWaits = new MigrationDependencyWaits();
110084
+ migrationWatch = false;
110085
+ /** Every id announced applied since the subscription: closes the in-flight-run window. */
110086
+ migrationAppliedSeen = /* @__PURE__ */ new Set();
110087
+ migrationRerunTail = Promise.resolve();
110088
+ /**
110089
+ * The engine announces every applied step (`migration.applied`). Subscribed BEFORE the first
110090
+ * declare, so a predecessor that lands between this owner's read and its subscription is not
110091
+ * missed; a step the engine blocked on one runs when that predecessor applies, with no restart.
110092
+ */
110093
+ watchAppliedMigrations() {
110094
+ if (this.migrationWatch) return;
110095
+ this.migrationWatch = true;
110096
+ this.subscribe({ category: EventCategory.MigrationApplied }, (event) => {
110097
+ const ids = appliedIdsOf(event.data);
110098
+ for (const id of ids) this.migrationAppliedSeen.add(id);
110099
+ this.releaseBlockedMigrations(ids);
110100
+ });
110101
+ }
110102
+ /**
110103
+ * Run again the waiting steps whose predecessor is among `applied`. The event is a hint (D8):
110104
+ * a dropped one leaves the step blocked until this addon's next boot, which reads the ledger.
110105
+ */
110106
+ releaseBlockedMigrations(applied) {
110107
+ const freed = this.migrationWaits.releasedBy(applied);
110108
+ if (freed.length === 0) return;
110109
+ this.migrationRerunTail = this.migrationRerunTail.catch(() => void 0).then(async () => {
110110
+ this.ctx.logger.info("a migration predecessor applied — running the blocked steps", { meta: { ids: freed } });
110111
+ await this.runBound([], { only: freed });
110112
+ }).then(() => void 0, (err) => {
110113
+ this.ctx.logger.error("the blocked migration steps could not run again", { meta: {
110114
+ ids: freed,
110115
+ error: errMsg$3(err)
110116
+ } });
110117
+ });
110118
+ }
109086
110119
  async runBound(declared, options) {
109087
- this.lastDeclared = declared;
110120
+ this.watchAppliedMigrations();
110121
+ const priorIds = new Set([...this.declaredAll.keys(), ...this.switchDeclared.keys()]);
109088
110122
  const added = this.registrySwitchBound();
109089
- const migrations = [...declared, ...added];
109090
- const widened = options?.only === void 0 || added.length === 0 ? options : {
110123
+ for (const m of added) this.switchDeclared.set(m.meta.id, m);
110124
+ for (const m of declared) this.declaredAll.set(m.meta.id, m);
110125
+ const migrations = [...this.declaredAll.values(), ...[...this.switchDeclared.values()].filter((m) => !this.declaredAll.has(m.meta.id))];
110126
+ const settledEarlier = [...priorIds].filter((id) => !declared.some((d) => d.meta.id === id));
110127
+ const own = settledEarlier.length === 0 ? options ?? {} : {
109091
110128
  ...options,
109092
- only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
109093
- };
109094
- const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
109095
- ...widened,
109096
- retired: this.retiredMigrationIds
110129
+ ...options?.only === void 0 ? { only: declared.map((m) => m.meta.id) } : {},
110130
+ settledEarlier
110131
+ };
110132
+ const widened = own?.only === void 0 || added.length === 0 ? own : {
110133
+ ...own,
110134
+ only: [...new Set([...own.only, ...added.map((m) => m.meta.id)])]
110135
+ };
110136
+ if (this.catalogueOpen) this.declaredIncomplete = true;
110137
+ const declare = {
110138
+ ...this.retiredMigrationIds.length === 0 ? widened ?? {} : {
110139
+ ...widened,
110140
+ retired: this.retiredMigrationIds
110141
+ },
110142
+ complete: !this.catalogueOpen
109097
110143
  };
109098
110144
  const api = this.ctx.api.migrations;
109099
- const report = await runAddonMigrations({
110145
+ const host = {
109100
110146
  declareOwner: (input) => api.declareOwner.mutate(input),
109101
110147
  startMigration: (input) => api.startMigration.mutate(input),
109102
110148
  finishMigration: (input) => api.finishMigration.mutate(input)
109103
- }, migrations, this.ctx.logger, phased);
110149
+ };
110150
+ const report = await runAddonMigrations(host, migrations, this.ctx.logger, declare);
110151
+ if (declare.complete === false && !this.catalogueOpen) await runAddonMigrations(host, [...new Map([...this.declaredAll, ...this.switchDeclared]).values()], this.ctx.logger, {
110152
+ ...this.retiredMigrationIds.length === 0 ? {} : { retired: this.retiredMigrationIds },
110153
+ only: [],
110154
+ complete: true
110155
+ });
110156
+ this.migrationWaits.record(report, [
110157
+ ...report.applied,
110158
+ ...report.failed,
110159
+ ...report.blocked,
110160
+ ...report.skipped
110161
+ ]);
110162
+ this.releaseBlockedMigrations([...this.migrationAppliedSeen]);
109104
110163
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
109105
110164
  await this.hydrateSwitches();
109106
110165
  await this.adoptUnrowed();
@@ -110256,6 +111315,7 @@ function method(input, output, options) {
110256
111315
  ...options?.caller !== void 0 ? { caller: options.caller } : {},
110257
111316
  ...options?.actions !== void 0 ? { actions: options.actions } : {},
110258
111317
  ...options?.notOperatorFacing !== void 0 ? { notOperatorFacing: options.notOperatorFacing } : {},
111318
+ ...options?.description !== void 0 ? { description: options.description } : {},
110259
111319
  timeoutMs: options?.timeoutMs
110260
111320
  };
110261
111321
  }
@@ -111871,6 +112931,11 @@ var DeviceType = /* @__PURE__ */ function(DeviceType) {
111871
112931
  * water, cooling, solar), its system modes and its power. One main read-only
111872
112932
  * `heat-pump-status` cap carries all of it; `heat-pump-control` sets it (D1026). */
111873
112933
  DeviceType["HeatPump"] = "heat-pump";
112934
+ /** A road vehicle reached through its maker's connected-car account: odometer, range,
112935
+ * openings, tyre warnings and the 12 V battery in one read-only `vehicle` cap; where it
112936
+ * is in `location`; fuel, fluids and service in `consumables`. Its lock and its cabin
112937
+ * climate are accessory children (`lock-vehicle`, `climate-vehicle`). */
112938
+ DeviceType["Vehicle"] = "vehicle";
111874
112939
  /** A home energy installation (any vendor): solar, grid, house, a metered heat pump
111875
112940
  * and the storage as branches of one bus. One read-only `energy-system` cap carries
111876
112941
  * every value; the storage is a field of it, never the `battery` cap (#513, #522). */
@@ -112113,6 +113178,14 @@ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
112113
113178
  /** One heating/cooling circuit of a heat pump: a water loop with comfort /
112114
113179
  * eco setpoints and a heat/cool mode, no room sensor. */
112115
113180
  DeviceRole["ClimateHeatPumpCircuit"] = "climate-heat-pump-circuit";
113181
+ /** A car's cabin: pre-conditioning (start / stop, target temperature) through the
113182
+ * maker's connected-car account. An accessory child of a vehicle. */
113183
+ DeviceRole["ClimateVehicle"] = "climate-vehicle";
113184
+ /** A car's central locking, an accessory child of a vehicle. Slow, cloud-held
113185
+ * commands; exports decide by `isVehicleLock`. */
113186
+ DeviceRole["LockVehicle"] = "lock-vehicle";
113187
+ /** A television: power, volume, channel, source and apps. */
113188
+ DeviceRole["MediaPlayerTv"] = "media-player-tv";
112116
113189
  /** Generic motion / occupancy / moving event source. Distinct from
112117
113190
  * the camera accessory PirSensor role: that one is a camera child;
112118
113191
  * this is a standalone HA / 3rd-party motion sensor. */
@@ -112439,6 +113512,16 @@ var BatteryStatusSchema = /* @__PURE__ */ object({
112439
113512
  */
112440
113513
  lastFullRefreshAt: /* @__PURE__ */ number().optional(),
112441
113514
  /**
113515
+ * The scheduled refresh's attempt bookkeeping for the window it last tried
113516
+ * (window index, attempts spent, ms epoch of the last attempt; `0` = none).
113517
+ * Persisted beside `lastFullRefreshAt` so a restart neither forgets a wake
113518
+ * the window already spent nor repeats it (#666). Written only by the
113519
+ * provider's refresh controller.
113520
+ */
113521
+ refreshAttemptWindow: /* @__PURE__ */ number().optional(),
113522
+ refreshAttempts: /* @__PURE__ */ number().optional(),
113523
+ refreshLastAttemptAt: /* @__PURE__ */ number().optional(),
113524
+ /**
112442
113525
  * True when the source is a BINARY low-battery indicator (HA
112443
113526
  * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
112444
113527
  * charge level — `level` is then a coarse stand-in (100 = normal,
@@ -112687,7 +113770,9 @@ var brightnessCapability = {
112687
113770
  deviceNative: true,
112688
113771
  mode: "singleton",
112689
113772
  deviceTypes: [DeviceType.Light],
112690
- methods: { setBrightness: /* @__PURE__ */ method(/* @__PURE__ */ object({
113773
+ methods: {
113774
+ /** Set the light's brightness level from 0 to 100. */
113775
+ setBrightness: /* @__PURE__ */ method(/* @__PURE__ */ object({
112691
113776
  deviceId: /* @__PURE__ */ number().int().nonnegative(),
112692
113777
  level: /* @__PURE__ */ number().min(0).max(100)
112693
113778
  }), /* @__PURE__ */ _void(), {
@@ -112883,7 +113968,9 @@ var dayNightCapability = {
112883
113968
  tab: "image"
112884
113969
  } },
112885
113970
  methods: {
113971
+ /** The camera's day/night modes and current settings. */
112886
113972
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), DayNightOptionsSchema),
113973
+ /** Change the camera's day/night mode, sensitivity or switch delay. */
112887
113974
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
112888
113975
  deviceId: /* @__PURE__ */ number(),
112889
113976
  settings: DayNightSettingsPatchSchema
@@ -113248,21 +114335,28 @@ var deviceAdoptionCapability = {
113248
114335
  kind: "poll"
113249
114336
  },
113250
114337
  methods: {
114338
+ /** The filters an integration offers to narrow its discovered candidates. */
113251
114339
  listCandidateFilters: /* @__PURE__ */ method(/* @__PURE__ */ object({ integrationId: /* @__PURE__ */ string() }), /* @__PURE__ */ object({ filters: /* @__PURE__ */ array(AdoptionFilterSchema) }), { auth: "admin" }),
114340
+ /** List the devices an integration has discovered and that can be adopted. */
113252
114341
  listCandidates: /* @__PURE__ */ method(ListCandidatesInputSchema, ListCandidatesOutputSchema, { auth: "admin" }),
114342
+ /** Fetch one discovered candidate; null when unknown. */
113253
114343
  getCandidate: /* @__PURE__ */ method(GetCandidateInputSchema, /* @__PURE__ */ DiscoveredChildDeviceSchema.nullable(), { auth: "admin" }),
114344
+ /** Rescan an integration for new candidates and report the adoption status. */
113254
114345
  refresh: /* @__PURE__ */ method(/* @__PURE__ */ object({ integrationId: /* @__PURE__ */ string() }), AdoptionStatusSchema, {
113255
114346
  kind: "mutation",
113256
114347
  auth: "admin"
113257
114348
  }),
114349
+ /** Adopt a discovered candidate as a device. */
113258
114350
  adopt: /* @__PURE__ */ method(AdoptInputSchema, AdoptResultSchema, {
113259
114351
  kind: "mutation",
113260
114352
  auth: "admin"
113261
114353
  }),
114354
+ /** Release an adopted device back to the candidate list. */
113262
114355
  release: /* @__PURE__ */ method(ReleaseInputSchema, /* @__PURE__ */ _void(), {
113263
114356
  kind: "mutation",
113264
114357
  auth: "admin"
113265
114358
  }),
114359
+ /** Re-read an adopted device from the integration and reconcile it. */
113266
114360
  resync: /* @__PURE__ */ method(ResyncInputSchema, ResyncResultSchema, {
113267
114361
  kind: "mutation",
113268
114362
  auth: "admin"
@@ -113626,9 +114720,13 @@ var deviceProviderCapability = {
113626
114720
  scope: "system",
113627
114721
  mode: "collection",
113628
114722
  methods: {
114723
+ /** Start the provider so it begins serving its devices. */
113629
114724
  start: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ _void(), { kind: "mutation" }),
114725
+ /** Stop the provider. */
113630
114726
  stop: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ _void(), { kind: "mutation" }),
114727
+ /** The provider's current status. */
113631
114728
  getStatus: /* @__PURE__ */ method(/* @__PURE__ */ _void(), ProviderStatusSchema),
114729
+ /** List the devices the provider serves. */
113632
114730
  getDevices: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ array(/* @__PURE__ */ object({
113633
114731
  id: /* @__PURE__ */ string(),
113634
114732
  name: /* @__PURE__ */ string(),
@@ -113663,6 +114761,7 @@ var deviceProviderCapability = {
113663
114761
  kind: "mutation",
113664
114762
  timeoutMs: 3 * 6e4
113665
114763
  }),
114764
+ /** Whether the provider can discover devices on the network. */
113666
114765
  supportsDiscovery: /* @__PURE__ */ method(/* @__PURE__ */ object({}), /* @__PURE__ */ boolean()),
113667
114766
  /**
113668
114767
  * Run a network scan. `params` carries optional provider-specific scan
@@ -113708,6 +114807,7 @@ var deviceProviderCapability = {
113708
114807
  getManualCreationType: /* @__PURE__ */ method(/* @__PURE__ */ object({
113709
114808
  /** The integration asked about; a provider whose integrations differ answers per one. */
113710
114809
  integrationId: /* @__PURE__ */ string().optional() }), /* @__PURE__ */ object({ deviceType: /* @__PURE__ */ _enum(DeviceType).nullable() })),
114810
+ /** Adopt a discovered candidate as a device, optionally into an integration instance. */
113711
114811
  adoptDiscoveredDevice: /* @__PURE__ */ method(/* @__PURE__ */ object({
113712
114812
  candidate: DiscoveryCandidateSchema,
113713
114813
  /** The integration the operator adopts into; a provider with several instances needs it. */
@@ -113716,6 +114816,7 @@ integrationId: /* @__PURE__ */ string().optional() }), /* @__PURE__ */ object({
113716
114816
  kind: "mutation",
113717
114817
  auth: "admin"
113718
114818
  }),
114819
+ /** Whether devices can be created by hand through this provider. */
113719
114820
  supportsManualCreation: /* @__PURE__ */ method(/* @__PURE__ */ object({}), /* @__PURE__ */ boolean()),
113720
114821
  /**
113721
114822
  * Fetch the creation form schema for a given DeviceType. Returns
@@ -113728,6 +114829,7 @@ integrationId: /* @__PURE__ */ string().optional() }), /* @__PURE__ */ object({
113728
114829
  /** The integration asked about; a provider whose integrations differ answers per one. */
113729
114830
  integrationId: /* @__PURE__ */ string().optional()
113730
114831
  }), CreationSchemaOutputSchema),
114832
+ /** Create a device of a given type with the given config. */
113731
114833
  createDevice: /* @__PURE__ */ method(/* @__PURE__ */ object({
113732
114834
  type: /* @__PURE__ */ _enum(DeviceType),
113733
114835
  config: /* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ unknown()),
@@ -113837,11 +114939,13 @@ var deviceStateRefreshCapability = {
113837
114939
  deviceNative: true,
113838
114940
  mode: "singleton",
113839
114941
  methods: {
114942
+ /** Re-read a device's state from the source now. */
113840
114943
  refresh: /* @__PURE__ */ method(DeviceStateRefreshInputSchema, DeviceStateRefreshResultSchema, {
113841
114944
  kind: "mutation",
113842
114945
  auth: "admin",
113843
114946
  notOperatorFacing: NOT_OPERATOR_FACING
113844
114947
  }),
114948
+ /** Re-establish a device's live state subscription. */
113845
114949
  resubscribe: /* @__PURE__ */ method(DeviceStateResubscribeInputSchema, DeviceStateRefreshResultSchema, {
113846
114950
  kind: "mutation",
113847
114951
  auth: "admin",
@@ -114054,7 +115158,10 @@ onPressed: {
114054
115158
  };
114055
115159
  //#endregion
114056
115160
  //#region ../types/dist/esm/capabilities/error.cap.mjs
114057
- /** How loudly a fault wants the operator. Both tiers raise the attention event. */
115161
+ /**
115162
+ * How loudly a fault wants the operator. An `error` raises the attention event;
115163
+ * a `warning` is shown on the device and opens a warning alert, nothing more.
115164
+ */
114058
115165
  var DeviceErrorSeveritySchema = /* @__PURE__ */ _enum(["warning", "error"]);
114059
115166
  /** One fault of a device that can raise several at once. */
114060
115167
  var DeviceFaultSchema = /* @__PURE__ */ object({
@@ -114119,7 +115226,13 @@ listFaultTypes: /* @__PURE__ */ method(ListFaultTypesInputSchema, FaultTypesSche
114119
115226
  status: {
114120
115227
  schema: ErrorStatusSchema,
114121
115228
  kind: "push",
114122
- empty: ERROR_STATUS_COLD
115229
+ empty: ERROR_STATUS_COLD,
115230
+ fieldEnums: { code: {
115231
+ from: "method",
115232
+ method: "listFaultTypes",
115233
+ listKey: "types",
115234
+ valueKey: "code"
115235
+ } }
114123
115236
  },
114124
115237
  runtimeState: ErrorStatusSchema,
114125
115238
  /**
@@ -114508,7 +115621,9 @@ var imageSettingsCapability = {
114508
115621
  tab: "image"
114509
115622
  } },
114510
115623
  methods: {
115624
+ /** The camera's picture-adjustment options and current values. */
114511
115625
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), ImageSettingsOptionsSchema),
115626
+ /** Change the camera's picture settings (brightness, contrast, orientation, exposure, ...). */
114512
115627
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
114513
115628
  deviceId: /* @__PURE__ */ number(),
114514
115629
  settings: ImageSettingsPatchSchema
@@ -114798,6 +115913,7 @@ var integrationInstancesCapability = {
114798
115913
  scope: "system",
114799
115914
  mode: "collection",
114800
115915
  methods: {
115916
+ /** What kind of instances this addon's integration holds and how to configure them. */
114801
115917
  describe: /* @__PURE__ */ method(/* @__PURE__ */ _void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
114802
115918
  /** The form; `id: null` is the create form. */
114803
115919
  instanceFormSchema: /* @__PURE__ */ method(/* @__PURE__ */ object({
@@ -114813,10 +115929,12 @@ var integrationInstancesCapability = {
114813
115929
  /** The discovery candidate the wizard was seeded from (`stableId`), if any. */
114814
115930
  candidateStableId: /* @__PURE__ */ string().min(1).optional()
114815
115931
  }), ConfigSchemaPassthrough, { auth: "admin" }),
115932
+ /** List the integration's instances (accounts, relays, destinations). */
114816
115933
  listInstances: /* @__PURE__ */ method(/* @__PURE__ */ looseObject({}), /* @__PURE__ */ array(IntegrationInstanceSchema).readonly(), {
114817
115934
  auth: "protected",
114818
115935
  caller: "scoped"
114819
115936
  }),
115937
+ /** Fetch one integration instance by id; null when absent. */
114820
115938
  getInstance: /* @__PURE__ */ method(/* @__PURE__ */ object({ id: IntegrationInstanceIdSchema }), /* @__PURE__ */ IntegrationInstanceSchema.nullable(), {
114821
115939
  auth: "protected",
114822
115940
  caller: "scoped"
@@ -114856,6 +115974,7 @@ var integrationInstancesCapability = {
114856
115974
  auth: "protected",
114857
115975
  caller: "scoped"
114858
115976
  }),
115977
+ /** Create or change an integration instance. */
114859
115978
  updateInstance: /* @__PURE__ */ method(IntegrationInstancePatchSchema, /* @__PURE__ */ object({ ok: /* @__PURE__ */ literal(true) }), {
114860
115979
  kind: "mutation",
114861
115980
  auth: "protected",
@@ -114884,6 +116003,7 @@ var integrationInstancesCapability = {
114884
116003
  auth: "protected",
114885
116004
  caller: "scoped"
114886
116005
  }),
116006
+ /** Test an instance's connection with the given values before saving. */
114887
116007
  testInstance: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({
114888
116008
  id: /* @__PURE__ */ IntegrationInstanceIdSchema.nullable(),
114889
116009
  values: /* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ unknown()),
@@ -115001,6 +116121,7 @@ var intercomCapability = {
115001
116121
  auth: "protected",
115002
116122
  notOperatorFacing: "live-stream session plumbing driven by a viewer, never a discrete step"
115003
116123
  }),
116124
+ /** Pass the viewer's SDP answer to an open two-way audio session. */
115004
116125
  handleAnswer: /* @__PURE__ */ method(/* @__PURE__ */ object({
115005
116126
  deviceId: /* @__PURE__ */ number(),
115006
116127
  sessionId: /* @__PURE__ */ string(),
@@ -115671,7 +116792,12 @@ DeviceType.Camera;
115671
116792
  * - `pipeline` — the chosen detector plus the operator's detail steps
115672
116793
  * (faces, plates, classifiers, CLIP…), on varied frames from the bench
115673
116794
  * clip: how many parallel sessions the node carries before latency, drops,
115674
- * CPU, RAM or the event loop give out.
116795
+ * CPU, RAM or the event loop give out;
116796
+ * - `decode` — the node, no accelerator of the inference plane: an encoded
116797
+ * camera-like stream (a profile: resolution, rate, codec) served on the
116798
+ * loopback and decoded by the session decode worker a camera gets, with a
116799
+ * motion pass on its frames: how many concurrent streams keep the profile
116800
+ * frame rate inside the same CPU and RAM limits (D1078).
115675
116801
  */
115676
116802
  /** Defaults and bounds, one place. */
115677
116803
  var NODE_BENCHMARK_DEFAULTS = {
@@ -115690,9 +116816,24 @@ var NODE_BENCHMARK_DEFAULTS = {
115690
116816
  /** Candidate models per device in one run. */
115691
116817
  maxModelsPerDevice: 6
115692
116818
  };
116819
+ /**
116820
+ * The camera-like streams the `decode` measurement ramps, heaviest first: a
116821
+ * 4K H.265 main stream and a 1080p H.264 one, at a camera frame rate.
116822
+ */
116823
+ var NODE_BENCH_DECODE_PROFILES = [{
116824
+ width: 3840,
116825
+ height: 2160,
116826
+ fps: 15,
116827
+ codec: "h265"
116828
+ }, {
116829
+ width: 1920,
116830
+ height: 1080,
116831
+ fps: 15,
116832
+ codec: "h264"
116833
+ }];
115693
116834
  NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice;
115694
116835
  NODE_BENCHMARK_DEFAULTS.fpsPerStream, NODE_BENCHMARK_DEFAULTS.budgetMinutes;
115695
- NODE_BENCHMARK_DEFAULTS.settleSec, NODE_BENCHMARK_DEFAULTS.measureSec;
116836
+ [...NODE_BENCH_DECODE_PROFILES], NODE_BENCHMARK_DEFAULTS.settleSec, NODE_BENCHMARK_DEFAULTS.measureSec;
115696
116837
  /**
115697
116838
  * Per-camera tunable ranges + defaults. Single source of truth used
115698
116839
  * by both the Zod data schema (validation + default fallback) and
@@ -116052,7 +117193,9 @@ var motionTriggerCapability = {
116052
117193
  DeviceType.Siren,
116053
117194
  DeviceType.Switch
116054
117195
  ],
116055
- methods: { setMotionTrigger: /* @__PURE__ */ method(/* @__PURE__ */ object({
117196
+ methods: {
117197
+ /** Turn on or off activating the accessory when the camera detects motion. */
117198
+ setMotionTrigger: /* @__PURE__ */ method(/* @__PURE__ */ object({
116056
117199
  deviceId: /* @__PURE__ */ number().int().nonnegative(),
116057
117200
  enabled: /* @__PURE__ */ boolean()
116058
117201
  }), /* @__PURE__ */ _void(), {
@@ -116171,7 +117314,9 @@ var motionZonesCapability = {
116171
117314
  label: "Motion Zones"
116172
117315
  } },
116173
117316
  methods: {
117317
+ /** The camera's onboard motion zone options and current zone. */
116174
117318
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), MotionZoneOptionsSchema),
117319
+ /** Change the camera's onboard motion zone. */
116175
117320
  setZone: /* @__PURE__ */ method(/* @__PURE__ */ object({
116176
117321
  deviceId: /* @__PURE__ */ number(),
116177
117322
  patch: MotionZonePatchSchema
@@ -116299,7 +117444,9 @@ var nativeObjectDetectionCapability = {
116299
117444
  mode: "singleton",
116300
117445
  deviceTypes: [DeviceType.Camera],
116301
117446
  methods: {
117447
+ /** The object classes the camera's onboard detection supports and its current settings. */
116302
117448
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), NativeObjectDetectionOptionsSchema),
117449
+ /** Change the camera's onboard object detection settings. */
116303
117450
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
116304
117451
  deviceId: /* @__PURE__ */ number(),
116305
117452
  settings: NativeObjectDetectionSettingsPatchSchema
@@ -116307,6 +117454,7 @@ var nativeObjectDetectionCapability = {
116307
117454
  kind: "mutation",
116308
117455
  auth: "admin"
116309
117456
  }),
117457
+ /** Turn the camera's onboard object detection on or off. */
116310
117458
  setEnabled: /* @__PURE__ */ method(/* @__PURE__ */ object({
116311
117459
  deviceId: /* @__PURE__ */ number(),
116312
117460
  enabled: /* @__PURE__ */ boolean()
@@ -116742,7 +117890,9 @@ var privacyMaskCapability = {
116742
117890
  label: "Privacy Mask"
116743
117891
  } },
116744
117892
  methods: {
117893
+ /** The camera's privacy mask options and current mask. */
116745
117894
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), PrivacyMaskOptionsSchema),
117895
+ /** Change the camera's privacy mask. */
116746
117896
  setMask: /* @__PURE__ */ method(/* @__PURE__ */ object({
116747
117897
  deviceId: /* @__PURE__ */ number(),
116748
117898
  patch: PrivacyMaskPatchSchema
@@ -117033,10 +118183,12 @@ var ptzCapability = {
117033
118183
  order: 0
117034
118184
  } },
117035
118185
  methods: {
118186
+ /** Nudge the camera by a relative pan, tilt or zoom step. */
117036
118187
  move: /* @__PURE__ */ method(/* @__PURE__ */ PtzMoveCommandSchema.extend({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
117037
118188
  kind: "mutation",
117038
118189
  notOperatorFacing: "a relative nudge from the live-view joystick; a fixed place is a preset"
117039
118190
  }),
118191
+ /** Move the camera continuously until stopped. */
117040
118192
  continuousMove: /* @__PURE__ */ method(/* @__PURE__ */ PtzMoveCommandSchema.extend({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
117041
118193
  kind: "mutation",
117042
118194
  notOperatorFacing: "joystick motion held until released — continuous, not a discrete step"
@@ -117055,7 +118207,9 @@ var ptzCapability = {
117055
118207
  icon: "house"
117056
118208
  }]
117057
118209
  }),
118210
+ /** List the camera's PTZ presets. */
117058
118211
  getPresets: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ array(PtzPresetSchema)),
118212
+ /** Move the camera to a preset. */
117059
118213
  goToPreset: /* @__PURE__ */ method(/* @__PURE__ */ object({
117060
118214
  deviceId: /* @__PURE__ */ number(),
117061
118215
  presetId: /* @__PURE__ */ string()
@@ -117079,6 +118233,7 @@ var ptzCapability = {
117079
118233
  }]
117080
118234
  }]
117081
118235
  }),
118236
+ /** Save the camera's current position as a named preset. */
117082
118237
  savePreset: /* @__PURE__ */ method(/* @__PURE__ */ object({
117083
118238
  deviceId: /* @__PURE__ */ number(),
117084
118239
  presetId: /* @__PURE__ */ string(),
@@ -117108,6 +118263,7 @@ var ptzCapability = {
117108
118263
  }]
117109
118264
  }]
117110
118265
  }),
118266
+ /** Delete a PTZ preset. */
117111
118267
  deletePreset: /* @__PURE__ */ method(/* @__PURE__ */ object({
117112
118268
  deviceId: /* @__PURE__ */ number(),
117113
118269
  presetId: /* @__PURE__ */ string()
@@ -117115,7 +118271,9 @@ var ptzCapability = {
117115
118271
  kind: "mutation",
117116
118272
  auth: "admin"
117117
118273
  }),
118274
+ /** What the camera's PTZ supports (axes, speeds, presets). */
117118
118275
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), PtzOptionsSchema),
118276
+ /** Stop any PTZ movement. */
117119
118277
  stop: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
117120
118278
  kind: "mutation",
117121
118279
  actions: [{
@@ -117476,7 +118634,9 @@ var rebootCapability = {
117476
118634
  DeviceType.Switch,
117477
118635
  DeviceType.Gateway
117478
118636
  ],
117479
- methods: { reboot: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ object({ success: /* @__PURE__ */ literal(true) }), {
118637
+ methods: {
118638
+ /** Reboot the device. */
118639
+ reboot: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ object({ success: /* @__PURE__ */ literal(true) }), {
117480
118640
  kind: "mutation",
117481
118641
  auth: "admin",
117482
118642
  actions: [{
@@ -118193,6 +119353,7 @@ var videoclipsCapability = {
118193
119353
  order: 100
118194
119354
  } },
118195
119355
  methods: {
119356
+ /** List a camera's clips in a time window, from every clip source. */
118196
119357
  listClips: /* @__PURE__ */ method(/* @__PURE__ */ object({
118197
119358
  deviceId: /* @__PURE__ */ number(),
118198
119359
  since: /* @__PURE__ */ number(),
@@ -118251,6 +119412,7 @@ var videoclipsCapability = {
118251
119412
  kind: "query",
118252
119413
  auth: "protected"
118253
119414
  }),
119415
+ /** How to play one clip, at the requested quality. */
118254
119416
  getClipPlayback: /* @__PURE__ */ method(/* @__PURE__ */ object({
118255
119417
  deviceId: /* @__PURE__ */ number(),
118256
119418
  clipId: /* @__PURE__ */ string(),
@@ -118865,7 +120027,9 @@ var recordingOnboardCapability = {
118865
120027
  tab: "recording"
118866
120028
  } },
118867
120029
  methods: {
120030
+ /** The camera's onboard recording options and current settings. */
118868
120031
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), RecordingOnboardOptionsSchema),
120032
+ /** Change the camera's onboard recording settings. */
118869
120033
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
118870
120034
  deviceId: /* @__PURE__ */ number(),
118871
120035
  settings: RecordingOnboardPatchSchema
@@ -119177,6 +120341,7 @@ var snapshotCapability = {
119177
120341
  deviceTypes: [DeviceType.Camera],
119178
120342
  exposesDeviceSettings: true,
119179
120343
  methods: {
120344
+ /** A current snapshot image of a camera, optionally bypassing the cache. */
119180
120345
  getSnapshot: /* @__PURE__ */ method(/* @__PURE__ */ object({
119181
120346
  deviceId: /* @__PURE__ */ number(),
119182
120347
  streamId: /* @__PURE__ */ string().optional(),
@@ -119198,6 +120363,7 @@ var snapshotCapability = {
119198
120363
  */
119199
120364
  force: /* @__PURE__ */ boolean().optional()
119200
120365
  }), /* @__PURE__ */ SnapshotImageSchema.nullable()),
120366
+ /** Drop a camera's cached snapshot. */
119201
120367
  invalidateCache: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
119202
120368
  kind: "mutation",
119203
120369
  auth: "admin"
@@ -119449,7 +120615,9 @@ var streamCatalogCapability = {
119449
120615
  deviceNative: true,
119450
120616
  mode: "singleton",
119451
120617
  deviceTypes: [DeviceType.Camera],
119452
- methods: { getCatalog: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ array(CamStreamDescriptorSchema).readonly()) },
120618
+ methods: {
120619
+ /** List the streams a camera offers. */
120620
+ getCatalog: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ array(CamStreamDescriptorSchema).readonly()) },
119453
120621
  runtimeState: StreamCatalogStateSchema,
119454
120622
  /**
119455
120623
  * Runtime-state durability: **restored** — see the schema doc. A cold
@@ -119581,7 +120749,9 @@ var streamParamsCapability = {
119581
120749
  tab: "streaming"
119582
120750
  } },
119583
120751
  methods: {
120752
+ /** The camera's stream profiles and their encoding options. */
119584
120753
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), StreamParamsOptionsSchema),
120754
+ /** Change the encoding settings of one stream profile. */
119585
120755
  setProfile: /* @__PURE__ */ method(/* @__PURE__ */ object({
119586
120756
  deviceId: /* @__PURE__ */ number(),
119587
120757
  profile: StreamProfileSchema,
@@ -119811,6 +120981,7 @@ var switchCapability = {
119811
120981
  DeviceType.Fan
119812
120982
  ],
119813
120983
  methods: {
120984
+ /** Turn the switch on or off. */
119814
120985
  setState: /* @__PURE__ */ method(/* @__PURE__ */ object({
119815
120986
  deviceId: /* @__PURE__ */ number(),
119816
120987
  on: /* @__PURE__ */ boolean()
@@ -119841,12 +121012,15 @@ var switchCapability = {
119841
121012
  offeredWhen: SWITCH_SETTABLE_GATE
119842
121013
  }]
119843
121014
  }),
121015
+ /** The options the switch supports. */
119844
121016
  getOptions: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), SwitchOptionsSchema, { auth: "protected" }),
121017
+ /** Power-cycle the device the switch powers. */
119845
121018
  powerCycle: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
119846
121019
  kind: "mutation",
119847
121020
  auth: "protected",
119848
121021
  notOperatorFacing: "a power cycle is the forced restart of the device the switch powers (power-source), never a step of its own"
119849
121022
  }),
121023
+ /** Flip the switch to the opposite state. */
119850
121024
  toggle: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
119851
121025
  kind: "mutation",
119852
121026
  auth: "protected",
@@ -121175,6 +122349,10 @@ async function declareDeviceIdentifiers(deps, raw, options = {}) {
121175
122349
  }
121176
122350
  }
121177
122351
  //#endregion
122352
+ //#region ../types/dist/esm/notification/alert-episode.mjs
122353
+ /** The category of the alert a device's `error` cap opens for its fault. */
122354
+ var DEVICE_ERROR_ALERT_CATEGORY = "device.error";
122355
+ //#endregion
121178
122356
  //#region ../types/dist/esm/device/device-error-episode.mjs
121179
122357
  /**
121180
122358
  * The edge between two readings, or `null` for no edge.
@@ -121190,6 +122368,75 @@ function deviceErrorEdge(previous, next) {
121190
122368
  if (next.active === false && previous?.active === true) return "resolve";
121191
122369
  return null;
121192
122370
  }
122371
+ /**
122372
+ * The alert severity of a fault tier. `error` is the cap's top tier and asks
122373
+ * for attention (`critical`); `warning` stays a warning.
122374
+ */
122375
+ function deviceErrorAlertSeverity(severity) {
122376
+ return severity === "error" ? "critical" : "warning";
122377
+ }
122378
+ var DEVICE_ERROR_ALERT_IDLE = {
122379
+ neverOpened: false,
122380
+ pending: null,
122381
+ attempts: 0
122382
+ };
122383
+ /**
122384
+ * The alert write a reading asks for.
122385
+ *
122386
+ * - a START opens; a `warning` fault that becomes an `error` opens again (same
122387
+ * alert id and episode, now critical). An error that eases to a warning
122388
+ * writes nothing: its critical alert stays until the fault resolves;
122389
+ * - a RESOLVE closes, except an alert this process knows was never accepted —
122390
+ * that one has nothing to close, and its failed open is dropped;
122391
+ * - with no edge, a failed write is tried again while the reading still asks
122392
+ * for it. An unknown reading asks for nothing (D49).
122393
+ */
122394
+ function planDeviceErrorAlert(delivery, edge, previous, next) {
122395
+ if (edge === "start") return {
122396
+ write: "open",
122397
+ delivery: {
122398
+ neverOpened: true,
122399
+ pending: "open",
122400
+ attempts: 0
122401
+ }
122402
+ };
122403
+ if (edge === "resolve") {
122404
+ if (delivery.neverOpened) return {
122405
+ write: null,
122406
+ delivery: DEVICE_ERROR_ALERT_IDLE
122407
+ };
122408
+ return {
122409
+ write: "close",
122410
+ delivery: {
122411
+ neverOpened: false,
122412
+ pending: "close",
122413
+ attempts: 0
122414
+ }
122415
+ };
122416
+ }
122417
+ if (next.active === true) {
122418
+ if (previous?.active === true && previous.severity === "warning" && next.severity === "error") return {
122419
+ write: "open",
122420
+ delivery: {
122421
+ ...delivery,
122422
+ pending: "open",
122423
+ attempts: 0
122424
+ }
122425
+ };
122426
+ if (delivery.pending === "open") return {
122427
+ write: "open",
122428
+ delivery
122429
+ };
122430
+ }
122431
+ if (next.active === false && delivery.pending === "close") return {
122432
+ write: "close",
122433
+ delivery
122434
+ };
122435
+ return {
122436
+ write: null,
122437
+ delivery
122438
+ };
122439
+ }
121193
122440
  function deviceErrorAlertId(deviceId) {
121194
122441
  return `device-error:${String(deviceId)}`;
121195
122442
  }
@@ -121214,8 +122461,8 @@ function buildDeviceErrorAlert(deviceId, deviceName, status, now) {
121214
122461
  const alertId = deviceErrorAlertId(deviceId);
121215
122462
  return {
121216
122463
  id: alertId,
121217
- category: "device.error",
121218
- severity: "critical",
122464
+ category: DEVICE_ERROR_ALERT_CATEGORY,
122465
+ severity: deviceErrorAlertSeverity(status.severity),
121219
122466
  title: `${deviceName}: ${label}`,
121220
122467
  message: `${deviceName} reports a fault: ${label}.`,
121221
122468
  action: {
@@ -121292,6 +122539,7 @@ var DEVICE_LOCAL_STATE_CAP_NAMES = {
121292
122539
  intercom: "intercom",
121293
122540
  irTransmitter: "ir-transmitter",
121294
122541
  lawnMowerControl: "lawn-mower-control",
122542
+ location: "location",
121295
122543
  lockControl: "lock-control",
121296
122544
  lowPowerSleep: "low-power-sleep",
121297
122545
  mediaPlayer: "media-player",
@@ -121330,6 +122578,7 @@ var DEVICE_LOCAL_STATE_CAP_NAMES = {
121330
122578
  update: "update",
121331
122579
  vacuumControl: "vacuum-control",
121332
122580
  valve: "valve",
122581
+ vehicle: "vehicle",
121333
122582
  vibration: "vibration",
121334
122583
  waterHeater: "water-heater",
121335
122584
  weather: "weather",
@@ -121349,6 +122598,8 @@ var BaseDevice = class {
121349
122598
  statusIsExternal;
121350
122599
  /** The fault catalog the integration declared; `[]` until it does. */
121351
122600
  faultTypes = [];
122601
+ /** What the alerts cap accepted for this device's fault, and the write still owed to it. */
122602
+ errorAlertDelivery = DEVICE_ERROR_ALERT_IDLE;
121352
122603
  name;
121353
122604
  parentDeviceId;
121354
122605
  role;
@@ -121701,51 +122952,81 @@ var BaseDevice = class {
121701
122952
  /**
121702
122953
  * Publish the device's fault. The slice is written; on an EDGE (a fault
121703
122954
  * starts, or one resolves) an attention episode opens or closes through the
121704
- * alerts cap, which the notification center announces as
121705
- * `device-attention-required` / `-resolved`. An unknown reading is never an
121706
- * edge. No rule exists by default: it notifies when the operator makes one.
122955
+ * alerts cap, at the severity of the fault's tier: an `error` fault is a
122956
+ * critical alert, which the notification center announces as
122957
+ * `device-attention-required` / `-resolved`; a `warning` fault is a warning
122958
+ * alert and announces nothing until it becomes an error. An unknown reading
122959
+ * is never an edge. No rule exists by default: it notifies when the operator
122960
+ * makes one.
122961
+ *
122962
+ * An alert write that fails is tried again on the next reading that still
122963
+ * asks for it, `DEVICE_ERROR_ALERT_MAX_ATTEMPTS` times at most.
121707
122964
  */
121708
122965
  async publishError(reading) {
121709
122966
  const previous = this.getCapSlice(errorCapability);
121710
122967
  if (reading.active === null && previous !== null && previous.active !== null) return;
121711
122968
  const now = Date.now();
121712
122969
  const edge = deviceErrorEdge(previous, reading);
121713
- const next = edge === "start" && reading.since === null ? {
122970
+ const next = this.withErrorSince(previous, reading, edge === "start", now);
122971
+ this.setCapSlice(errorCapability, next);
122972
+ const plan = planDeviceErrorAlert(this.errorAlertDelivery, edge, previous, next);
122973
+ this.errorAlertDelivery = plan.delivery;
122974
+ if (plan.write === null) return;
122975
+ await this.writeErrorAlert(plan.write, next, now);
122976
+ }
122977
+ /** A fault keeps the start it was given: stamped on the start, carried while it lasts. */
122978
+ withErrorSince(previous, reading, starts, now) {
122979
+ if (reading.active !== true || reading.since !== null) return reading;
122980
+ if (starts) return {
121714
122981
  ...reading,
121715
122982
  since: now
121716
- } : reading;
121717
- this.setCapSlice(errorCapability, next);
121718
- if (edge === null) return;
121719
- const alerts = this.ctx.api.alerts;
121720
- if (alerts === void 0) {
121721
- this.ctx.logger.warn("device error: attention event skipped — alerts capability missing", {
121722
- tags: { deviceId: this.id },
121723
- meta: { edge }
121724
- });
121725
- return;
121726
- }
122983
+ };
122984
+ return previous?.since == null ? reading : {
122985
+ ...reading,
122986
+ since: previous.since
122987
+ };
122988
+ }
122989
+ /** One attempt at the alert write the plan asked for; a failure stays owed, under the bound. */
122990
+ async writeErrorAlert(write, status, now) {
122991
+ const attempt = this.errorAlertDelivery.attempts + 1;
121727
122992
  try {
121728
- if (edge === "start") await alerts.emit.mutate(buildDeviceErrorAlert(this.id, this.name, next, now));
121729
- else await alerts.update.mutate({
121730
- alertId: deviceErrorAlertId(this.id),
121731
- patch: {
121732
- status: "completed",
121733
- read: true,
121734
- updatedAt: now
121735
- }
121736
- });
121737
- this.ctx.logger.info(`device error: ${edge === "start" ? "raised" : "resolved"}`, {
122993
+ const alerts = this.ctx.api.alerts;
122994
+ if (alerts === void 0) throw new Error("alerts capability missing");
122995
+ if (write === "open") {
122996
+ await alerts.emit.mutate(buildDeviceErrorAlert(this.id, this.name, status, now));
122997
+ this.errorAlertDelivery = DEVICE_ERROR_ALERT_IDLE;
122998
+ } else {
122999
+ await alerts.update.mutate({
123000
+ alertId: deviceErrorAlertId(this.id),
123001
+ patch: {
123002
+ status: "completed",
123003
+ read: true,
123004
+ updatedAt: now
123005
+ }
123006
+ });
123007
+ this.errorAlertDelivery = DEVICE_ERROR_ALERT_IDLE;
123008
+ }
123009
+ this.ctx.logger.info(`device error: ${write === "open" ? "raised" : "resolved"}`, {
121738
123010
  tags: { deviceId: this.id },
121739
123011
  meta: {
121740
- code: next.code,
121741
- label: next.label
123012
+ code: status.code,
123013
+ label: status.label,
123014
+ severity: status.severity,
123015
+ attempt
121742
123016
  }
121743
123017
  });
121744
123018
  } catch (err) {
121745
- this.ctx.logger.warn("device error: attention event failed", {
123019
+ const givenUp = attempt >= 5;
123020
+ this.errorAlertDelivery = {
123021
+ ...this.errorAlertDelivery,
123022
+ pending: givenUp ? null : write,
123023
+ attempts: givenUp ? 0 : attempt
123024
+ };
123025
+ this.ctx.logger.warn(givenUp ? "device error: attention event given up, the alert is not written" : "device error: attention event failed, retried on the next reading", {
121746
123026
  tags: { deviceId: this.id },
121747
123027
  meta: {
121748
- edge,
123028
+ write,
123029
+ attempt,
121749
123030
  error: errMsg$3(err)
121750
123031
  }
121751
123032
  });
@@ -129613,6 +130894,24 @@ var IntercomFailureReport = class {
129613
130894
  /** The process-wide instance every camera in this addon notes into. */
129614
130895
  var intercomFailureReport = new IntercomFailureReport();
129615
130896
  //#endregion
130897
+ //#region src/stamp-current-features.ts
130898
+ /**
130899
+ * Stamp the camera's CURRENT feature list on every descriptor.
130900
+ *
130901
+ * A descriptor restored from the durable catalog slice carries the
130902
+ * `deviceFeatures` of whichever provider build wrote it (a pre-#459 build wrote
130903
+ * `battery-operated` without `sleeps`). Trusting that list made the broker open
130904
+ * a default prebuffer hold on a battery camera and keep it awake forever. The
130905
+ * features are a property of the camera NOW, never of the stored catalog, so a
130906
+ * stored list is never read.
130907
+ */
130908
+ function stampCurrentFeatures(descriptors, features) {
130909
+ return descriptors.map((d) => ({
130910
+ ...d,
130911
+ deviceFeatures: [...features]
130912
+ }));
130913
+ }
130914
+ //#endregion
129616
130915
  //#region src/baichuan-webhook-shared.ts
129617
130916
  /** The data-plane prefix this addon serves the camera push on: `/addon/<addonId>/webhook/<stableId>`. */
129618
130917
  var BAICHUAN_WEBHOOK_PREFIX = "webhook";
@@ -129718,12 +131017,21 @@ function reportsPowerSource(info) {
129718
131017
  * sleep, or while on mains or a panel, reports `0` as a placeholder — device
129719
131018
  * 3628 sat at 100% on its adapter and raised a low-battery notification on
129720
131019
  * every hourly wake. Those zeros are UNMEASURED: the caller keeps the last real
129721
- * level. A `0` from an awake camera running on its cell alone (or of unknown
129722
- * source) is a genuine empty cell and passes, as does every non-zero level.
131020
+ * level.
131021
+ *
131022
+ * The same placeholder also arrives with NO power source to blame (device 3628,
131023
+ * its own Baichuan read): `batteryPercent: 0, chargeStatus: "none",
131024
+ * adapterStatus: "none", voltage: 0, current: 0, temperature: 0`, awake — an
131025
+ * all-zero payload that raised an empty-battery alert; the next read was 99.
131026
+ * A `0` level with a present `voltage` of 0 carries no cell measurement at all,
131027
+ * so it is UNMEASURED too. A `0` from an awake camera on its cell alone with a
131028
+ * real voltage (or a payload without the field) is a genuine empty cell and
131029
+ * passes, as does every non-zero level.
129723
131030
  */
129724
131031
  function isMeasuredCameraBatteryLevel(level, context) {
129725
131032
  if (level !== 0) return true;
129726
131033
  if (context.sleeping) return false;
131034
+ if (context.voltage === 0) return false;
129727
131035
  return context.charging !== "dc" && context.charging !== "solar";
129728
131036
  }
129729
131037
  /** What the cell is doing, from `chargeStatus`. Absent is `'unknown'`, never `'idle'` (D315). */
@@ -129757,6 +131065,12 @@ var BATTERY_REFRESH_MINUTES_KEY = "batteryRefreshMinutes";
129757
131065
  var BATTERY_REFRESH_TICK_MS = 6e4;
129758
131066
  /** The least time between two attempts in one window. */
129759
131067
  var RETRY_BACKOFF_MS = 10 * 6e4;
131068
+ /**
131069
+ * How old the last full refresh may grow while a stream is open before the
131070
+ * control burst runs under that stream anyway. A camera that streams 24/7
131071
+ * would otherwise never refresh battery, accessories or settings.
131072
+ */
131073
+ var STREAM_DEFER_MAX_AGE_MS = 240 * 6e4;
129760
131074
  /** The one refresh step whose failure does not hold the window open. */
129761
131075
  var SOFT_FAILURE_STEP = "snapshot";
129762
131076
  var MAX_WAKE_LEAD_MS = 5 * 6e4;
@@ -129806,12 +131120,48 @@ function decideBatteryRefresh(input) {
129806
131120
  };
129807
131121
  return { kind: "wake-then-refresh" };
129808
131122
  }
131123
+ /**
131124
+ * A FULL-slice write replaces the slice, so every writer that composes its own
131125
+ * value must carry the scheduled refresh's bookkeeping over from the slice it
131126
+ * replaces. Dropping it makes a restart read "never refreshed" and owe the
131127
+ * camera a wake (#666: the stamp read back `null` after any battery read that
131128
+ * followed it).
131129
+ */
131130
+ function carryRefreshBookkeeping(previous, next) {
131131
+ return {
131132
+ ...next,
131133
+ ...previous.lastFullRefreshAt !== void 0 ? { lastFullRefreshAt: previous.lastFullRefreshAt } : {},
131134
+ ...previous.refreshAttemptWindow !== void 0 ? { refreshAttemptWindow: previous.refreshAttemptWindow } : {},
131135
+ ...previous.refreshAttempts !== void 0 ? { refreshAttempts: previous.refreshAttempts } : {},
131136
+ ...previous.refreshLastAttemptAt !== void 0 ? { refreshLastAttemptAt: previous.refreshLastAttemptAt } : {}
131137
+ };
131138
+ }
131139
+ /** The ledger over the slice's flat fields; `write` receives the patch to persist. */
131140
+ function attemptLedgerOverSlice(readSlice, writeFields) {
131141
+ return {
131142
+ read: () => {
131143
+ const s = readSlice();
131144
+ if (typeof s.refreshAttemptWindow !== "number" || typeof s.refreshAttempts !== "number") return;
131145
+ return {
131146
+ window: s.refreshAttemptWindow,
131147
+ attempts: s.refreshAttempts,
131148
+ lastAttemptAt: s.refreshLastAttemptAt
131149
+ };
131150
+ },
131151
+ write: (r) => writeFields({
131152
+ refreshAttemptWindow: r.window,
131153
+ refreshAttempts: r.attempts,
131154
+ refreshLastAttemptAt: r.lastAttemptAt ?? 0
131155
+ })
131156
+ };
131157
+ }
129809
131158
  var BatteryHourlyRefresh = class {
129810
131159
  deps;
129811
131160
  inFlight = null;
129812
131161
  attemptWindow = Number.NEGATIVE_INFINITY;
129813
131162
  attempts = 0;
129814
131163
  lastAttemptAt;
131164
+ hydrated = false;
129815
131165
  constructor(deps) {
129816
131166
  this.deps = deps;
129817
131167
  }
@@ -129836,6 +131186,7 @@ var BatteryHourlyRefresh = class {
129836
131186
  const intervalMs = this.deps.intervalMs();
129837
131187
  const offsetMs = intervalMs > 0 ? staggerOffsetMs(this.deps.deviceId, intervalMs) : 0;
129838
131188
  const window = intervalMs > 0 ? windowIndex(nowMs, intervalMs, offsetMs) : 0;
131189
+ this.hydrateAttempts();
129839
131190
  if (window !== this.attemptWindow) {
129840
131191
  this.attemptWindow = window;
129841
131192
  this.attempts = 0;
@@ -129854,14 +131205,67 @@ var BatteryHourlyRefresh = class {
129854
131205
  this.logSkip(decision.reason, trigger);
129855
131206
  return false;
129856
131207
  }
131208
+ if (this.shouldDeferForStream()) {
131209
+ this.noteStreamDeferred(trigger);
131210
+ return false;
131211
+ }
131212
+ if (this.deps.isStreaming?.() === true) this.logDeferralBoundReached(trigger);
129857
131213
  this.attempts += 1;
129858
131214
  this.lastAttemptAt = nowMs;
131215
+ this.deps.attemptLedger?.write({
131216
+ window,
131217
+ attempts: this.attempts,
131218
+ lastAttemptAt: nowMs
131219
+ });
129859
131220
  const run = this.run(decision.kind, trigger).finally(() => {
129860
131221
  this.inFlight = null;
129861
131222
  });
129862
131223
  this.inFlight = run;
129863
131224
  return run;
129864
131225
  }
131226
+ /** Once, at the first decision: take the persisted bookkeeping of the window a restart interrupted. */
131227
+ hydrateAttempts() {
131228
+ if (this.hydrated) return;
131229
+ this.hydrated = true;
131230
+ const stored = this.deps.attemptLedger?.read();
131231
+ if (stored === void 0) return;
131232
+ this.attemptWindow = stored.window;
131233
+ this.attempts = stored.attempts;
131234
+ this.lastAttemptAt = typeof stored.lastAttemptAt === "number" && stored.lastAttemptAt > 0 ? stored.lastAttemptAt : void 0;
131235
+ }
131236
+ /**
131237
+ * A stream is open AND the last full refresh is younger than
131238
+ * {@link STREAM_DEFER_MAX_AGE_MS}: the control burst waits. Past that age (or
131239
+ * with no refresh on record) it runs under the stream — the deferral is bounded.
131240
+ */
131241
+ shouldDeferForStream() {
131242
+ if (this.deps.isStreaming?.() !== true) return false;
131243
+ const last = this.deps.lastFullRefreshAt();
131244
+ if (typeof last !== "number" || last <= 0) return false;
131245
+ return this.deps.now() - last < STREAM_DEFER_MAX_AGE_MS;
131246
+ }
131247
+ logDeferralBoundReached(what) {
131248
+ this.deps.logger.info("battery control burst: deferral bound reached — refreshing under an active stream", {
131249
+ tags: { deviceId: this.deps.deviceId },
131250
+ meta: {
131251
+ what,
131252
+ maxAgeMs: STREAM_DEFER_MAX_AGE_MS
131253
+ }
131254
+ });
131255
+ }
131256
+ streamDeferLoggedWindow = Number.NEGATIVE_INFINITY;
131257
+ /** Say once per window that a due control burst was held back for a stream. */
131258
+ noteStreamDeferred(what) {
131259
+ const intervalMs = this.deps.intervalMs();
131260
+ const offsetMs = intervalMs > 0 ? staggerOffsetMs(this.deps.deviceId, intervalMs) : 0;
131261
+ const window = intervalMs > 0 ? windowIndex(this.deps.now(), intervalMs, offsetMs) : 0;
131262
+ if (window === this.streamDeferLoggedWindow) return;
131263
+ this.streamDeferLoggedWindow = window;
131264
+ this.deps.logger.info("battery control burst deferred — a stream is active", {
131265
+ tags: { deviceId: this.deps.deviceId },
131266
+ meta: { what }
131267
+ });
131268
+ }
129865
131269
  async run(kind, trigger) {
129866
131270
  const { logger, deviceId } = this.deps;
129867
131271
  try {
@@ -132032,6 +133436,7 @@ async function connectReolinkHub(connection) {
132032
133436
  transport: connection.transport,
132033
133437
  ...connection.uid ? { uid: connection.uid } : {}
132034
133438
  });
133439
+ api.setGeneralSessionRecycling({ guard: () => true });
132035
133440
  await api.login();
132036
133441
  return api;
132037
133442
  }
@@ -132137,14 +133542,14 @@ function isSummarySourced(source) {
132137
133542
  function decideSleepCommit(input) {
132138
133543
  const { current, next, source, lastFirstHandCommitAt, nowMs, videoFlowing, wired } = input;
132139
133544
  if (current === next) return { kind: "unchanged" };
133545
+ if (next === true && wired) return {
133546
+ kind: "refused",
133547
+ reason: "wired",
133548
+ windowMs: 0,
133549
+ sinceLastChangeMs: nowMs - lastFirstHandCommitAt
133550
+ };
132140
133551
  if (next === true && isSecondHand(source)) {
132141
133552
  const sinceMs = nowMs - lastFirstHandCommitAt;
132142
- if (wired) return {
132143
- kind: "refused",
132144
- reason: "wired",
132145
- windowMs: 0,
132146
- sinceLastChangeMs: sinceMs
132147
- };
132148
133553
  if (videoFlowing) return {
132149
133554
  kind: "refused",
132150
133555
  reason: "video-flowing",
@@ -132176,6 +133581,49 @@ function decideSleepCommit(input) {
132176
133581
  };
132177
133582
  }
132178
133583
  //#endregion
133584
+ //#region src/login-deadline.ts
133585
+ /**
133586
+ * A login the camera abandons must not wedge the provider.
133587
+ *
133588
+ * `ensureApi` is single-flight: every caller joins the pending `loginPromise`.
133589
+ * A camera that accepts the connection and then never answers left that
133590
+ * promise pending forever, so every later demand joined a login that could
133591
+ * not finish and the provider stayed dark until a restart.
133592
+ */
133593
+ /** Longest a Baichuan login may take before it is abandoned (a battery wake included). */
133594
+ var LOGIN_DEADLINE_MS = 6e4;
133595
+ var LoginDeadlineError = class extends Error {
133596
+ deadlineMs;
133597
+ constructor(deadlineMs) {
133598
+ super(`Baichuan login did not finish within ${deadlineMs} ms`);
133599
+ this.deadlineMs = deadlineMs;
133600
+ this.name = "LoginDeadlineError";
133601
+ }
133602
+ };
133603
+ /**
133604
+ * Run `login`, bounded. On expiry `onExpire` closes the pending client, then
133605
+ * the call rejects with {@link LoginDeadlineError}; a late settle of `login` is
133606
+ * swallowed (the client it belonged to is closed).
133607
+ */
133608
+ async function loginWithin(login, deadlineMs, onExpire) {
133609
+ let timer;
133610
+ let didExpire = false;
133611
+ const expired = new Promise((_, reject) => {
133612
+ timer = setTimeout(() => {
133613
+ didExpire = true;
133614
+ Promise.resolve().then(onExpire).catch(() => void 0).then(() => reject(new LoginDeadlineError(deadlineMs)));
133615
+ }, deadlineMs);
133616
+ });
133617
+ const run = login();
133618
+ run.catch(() => void 0);
133619
+ try {
133620
+ await Promise.race([run, expired]);
133621
+ if (didExpire) throw new LoginDeadlineError(deadlineMs);
133622
+ } finally {
133623
+ if (timer !== void 0) clearTimeout(timer);
133624
+ }
133625
+ }
133626
+ //#endregion
132179
133627
  //#region src/session-limit.ts
132180
133628
  /**
132181
133629
  * How long the broker lets a Home Hub child's session run before it re-dials on
@@ -132189,15 +133637,25 @@ function decideSleepCommit(input) {
132189
133637
  */
132190
133638
  var HOME_HUB_SESSION_LIMIT_MS = 27 * 6e4;
132191
133639
  /**
133640
+ * The same cut on a STANDALONE battery camera: four consecutive live sessions
133641
+ * ended at 1799-1806 s (2026-11-23), so the firmware limits a session to about
133642
+ * 30 min there too. Declared two minutes under it so the broker's planned
133643
+ * re-dial wins the race against the camera's cut and the recording rolls over
133644
+ * at a time of our choosing, not as a hole.
133645
+ */
133646
+ var STANDALONE_BATTERY_SESSION_LIMIT_MS = 28 * 6e4;
133647
+ /**
132192
133648
  * Stamp the descriptors with the session limit the broker acts on. Only a
132193
- * battery child of a hub gets one: a standalone camera has no such cut, and
132194
- * declaring one there would re-dial a healthy stream for nothing.
133649
+ * battery camera gets one (a hub child at 27 min, a standalone one at 28 min):
133650
+ * a mains-powered camera or a wired hub child has no such cut, and declaring
133651
+ * one there would re-dial a healthy stream for nothing.
132195
133652
  */
132196
133653
  function withSessionLimit(descriptors, input) {
132197
- if (!input.isHubChild || !input.isBattery) return [...descriptors];
133654
+ if (!input.isBattery) return [...descriptors];
133655
+ const maxSessionMs = input.isHubChild ? HOME_HUB_SESSION_LIMIT_MS : STANDALONE_BATTERY_SESSION_LIMIT_MS;
132198
133656
  return descriptors.map((d) => ({
132199
133657
  ...d,
132200
- maxSessionMs: HOME_HUB_SESSION_LIMIT_MS
133658
+ maxSessionMs
132201
133659
  }));
132202
133660
  }
132203
133661
  //#endregion
@@ -132423,6 +133881,15 @@ var reolinkAccessoryBaseSchema = object({
132423
133881
  channel: number().int().nonnegative().default(0),
132424
133882
  kind: string()
132425
133883
  });
133884
+ /**
133885
+ * True when the parent is a battery camera that is asleep right now. The one
133886
+ * question every accessory probe / revalidation asks BEFORE it reaches
133887
+ * `ensureApi()`: on a sleeping battery camera the login itself is the wake.
133888
+ * It reads the parent's own `isBattery` + `sleeping` (no second copy).
133889
+ */
133890
+ function isParentSleepingBattery(parent) {
133891
+ return parent.isBatteryCam?.() === true && parent.isSleeping?.() === true;
133892
+ }
132426
133893
  //#endregion
132427
133894
  //#region src/accessories/floodlight.ts
132428
133895
  /**
@@ -132472,13 +133939,6 @@ var FloodlightAccessory = class extends BaseDevice {
132472
133939
  * /setMotionTrigger. Read by the parent's align loop via the
132473
133940
  * `ReolinkAccessoryRef.isInCooldown` impl below. */
132474
133941
  lastSetAtMs = 0;
132475
- /** Becomes `true` once both `refreshLightFromFirmware` and
132476
- * `refreshMotionTriggerFromFirmware` have completed at least one
132477
- * successful round-trip. Used by `onProbe` to decide whether the
132478
- * boot-time sleep-gate should force a wake (no cached state) or
132479
- * skip (already-have-state path). Mirrors the Reolink mobile app's
132480
- * one-shot wake-and-fetch on launch. */
132481
- hasFetchedFromFirmware = false;
132482
133942
  constructor(ctx, parent) {
132483
133943
  super(ctx, floodlightAccessorySchema, {
132484
133944
  type: DeviceType.Light,
@@ -132538,7 +133998,6 @@ var FloodlightAccessory = class extends BaseDevice {
132538
133998
  level: brightness,
132539
133999
  lastChangedAt: ts
132540
134000
  });
132541
- this.hasFetchedFromFirmware = true;
132542
134001
  } catch (err) {
132543
134002
  this.ctx.logger.warn("floodlight refresh FAILED — slice stays at cold-start seed", {
132544
134003
  tags: { deviceId: this.id },
@@ -132550,46 +134009,29 @@ var FloodlightAccessory = class extends BaseDevice {
132550
134009
  }
132551
134010
  }
132552
134011
  /**
132553
- * Kernel-driven probe (Phase 4). Runs on every device construction
132554
- * + addon restart. Pulls the actual on/off + brightness +
132555
- * motion-trigger state from the camera so the slices reflect
132556
- * firmware truth instead of the conservative cold-start seeds
132557
- * written in `registerSwitchCap` / `registerBrightnessCap` /
132558
- * `registerMotionTriggerCap`.
132559
- *
132560
- * Sleeping battery cam:
132561
- * 1. **First-time probe (no cached state yet)** — force a one-shot
132562
- * wake + fetch so the operator sees a populated UI at launch.
132563
- * Mirrors the Reolink mobile app: at app launch it wakes the
132564
- * cam once to fetch initial state. Without this, an aggressive
132565
- * sleep timeout (~14s) can return the cam to sleep before the
132566
- * kernel finishes its initial probe pass — the retry chain
132567
- * exhausts and the slices never populate.
132568
- * 2. **Subsequent probes (slices already populated)** — skip. A
132569
- * poll on a sleeping camera returns 400 and drains the
132570
- * battery. The parent's `alignAuxDevicesState('wake')` runs
132571
- * on the next wake transition (simpleEvent push or sleep-poll
132572
- * backstop) and refreshes both slices then.
134012
+ * Kernel-driven probe. On a sleeping battery camera it does nothing: no
134013
+ * login, no wake (the login IS the wake, #666), not even for an accessory
134014
+ * with no cached state. The persisted slices stand in, and the parent's
134015
+ * `alignAuxDevicesState('wake')` (the wake transition, or the scheduled
134016
+ * window's authorised wake) refreshes this accessory the next time the
134017
+ * camera is up for its own reasons.
132573
134018
  */
132574
134019
  async onProbe() {
132575
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
132576
- if (this.hasFetchedFromFirmware) {
132577
- this.ctx.logger.debug("floodlight onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
132578
- return;
132579
- }
132580
- this.ctx.logger.info("floodlight onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
132581
- try {
132582
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
132583
- await sleep(1e3);
132584
- } catch (err) {
132585
- this.ctx.logger.warn("floodlight wake before initial probe failed — proceeding anyway", {
132586
- tags: { deviceId: this.id },
132587
- meta: { error: err instanceof Error ? err.message : String(err) }
132588
- });
132589
- }
134020
+ if (isParentSleepingBattery(this.parent)) {
134021
+ this.ctx.logger.info("floodlight onProbe skipped — parent battery cam is sleeping (serving persisted state)", { tags: { deviceId: this.id } });
134022
+ return;
132590
134023
  }
132591
134024
  await Promise.all([this.refreshLightFromFirmware(), this.refreshMotionTriggerFromFirmware()]);
132592
134025
  }
134026
+ /** The cap read's revalidation: never logs in to a sleeping battery camera
134027
+ * (#666) — the read is served from the persisted slice. */
134028
+ async revalidateMotionTrigger() {
134029
+ if (isParentSleepingBattery(this.parent)) {
134030
+ this.ctx.logger.debug("floodlight motion-trigger revalidation skipped — parent battery cam is sleeping", { tags: { deviceId: this.id } });
134031
+ return;
134032
+ }
134033
+ await this.refreshMotionTriggerFromFirmware();
134034
+ }
132593
134035
  /** Refresh motion-trigger from firmware and write the slice. Also
132594
134036
  * mirrors the camera-current `duration` + `detectType` into config
132595
134037
  * so the Settings form shows firmware truth instead of stale
@@ -132611,7 +134053,6 @@ var FloodlightAccessory = class extends BaseDevice {
132611
134053
  lastChangedAt,
132612
134054
  lastFetchedAt: Date.now()
132613
134055
  });
132614
- this.hasFetchedFromFirmware = true;
132615
134056
  const patch = {};
132616
134057
  if (typeof result?.duration === "number" && result.duration > 0) patch["motionLightDurationS"] = result.duration;
132617
134058
  if (typeof result?.detectType === "string") {
@@ -132707,7 +134148,7 @@ var FloodlightAccessory = class extends BaseDevice {
132707
134148
  runtimeState: this.runtimeState,
132708
134149
  cap: motionTriggerCapability,
132709
134150
  ownDeviceId: this.id,
132710
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134151
+ refresh: () => this.revalidateMotionTrigger(),
132711
134152
  staleMs: STALE_MS$1,
132712
134153
  empty: () => ({
132713
134154
  enabled: false,
@@ -132858,12 +134299,6 @@ var PirAccessory = class extends BaseDevice {
132858
134299
  /** Nothing reported: the kernel derives this device's features from its bound caps (#459). */
132859
134300
  features = [];
132860
134301
  lastSetAtMs = 0;
132861
- /** Becomes `true` after the first successful `refreshFromFirmware`
132862
- * round-trip. Used by `onProbe` to decide whether the boot-time
132863
- * sleep-gate should force a wake (no cached state) or skip
132864
- * (already-have-state path). Mirrors the Reolink mobile app's
132865
- * one-shot wake-and-fetch on launch. */
132866
- hasFetchedFromFirmware = false;
132867
134302
  constructor(ctx, parent) {
132868
134303
  super(ctx, pirAccessorySchema, {
132869
134304
  type: DeviceType.Switch,
@@ -132939,7 +134374,6 @@ var PirAccessory = class extends BaseDevice {
132939
134374
  }
132940
134375
  });
132941
134376
  this.refreshSwitchFromExternal(state);
132942
- this.hasFetchedFromFirmware = true;
132943
134377
  } catch (err) {
132944
134378
  this.ctx.logger.warn("pir refresh FAILED — slice stays at cold-start seed", {
132945
134379
  tags: { deviceId: this.id },
@@ -132951,45 +134385,17 @@ var PirAccessory = class extends BaseDevice {
132951
134385
  }
132952
134386
  }
132953
134387
  /**
132954
- * Kernel-driven probe — runs at device construction (addon boot,
132955
- * device add). For battery cams currently asleep we have two
132956
- * cases:
132957
- *
132958
- * 1. **First-time probe (no cached state yet)** — force a one-shot
132959
- * wake + fetch. Mirrors the Reolink mobile app's launch
132960
- * behaviour: the app wakes the cam once at startup so the
132961
- * operator sees a populated UI. Without this, an aggressive
132962
- * sleep timeout (~14s after boot on Argus / battery doorbell
132963
- * firmwares) can put the cam back to sleep before the
132964
- * kernel's initial probe pass completes — the slice never
132965
- * gets populated, the kernel's retry chain exhausts after 5
132966
- * attempts, and the operator sees an empty PIR switch state
132967
- * until they manually wake the cam.
132968
- * 2. **Subsequent probes (slice already populated)** — skip the
132969
- * fetch. A Baichuan poll on a sleeping camera returns 400,
132970
- * drains the battery, and would clobber the cached value
132971
- * anyway. The parent's `alignAuxDevicesState('wake')` path
132972
- * (simpleEvent `awake` push or sleep-poll backstop)
132973
- * refreshes us when the cam wakes naturally.
132974
- *
132975
- * Wired cams + already-awake battery cams take the normal path.
134388
+ * Kernel-driven probe. On a sleeping battery camera it does nothing: no
134389
+ * login, no wake (the login IS the wake, #666), not even for an accessory
134390
+ * with no cached state. The persisted slices stand in, and the parent's
134391
+ * `alignAuxDevicesState('wake')` (the wake transition, or the scheduled
134392
+ * window's authorised wake) refreshes this accessory the next time the
134393
+ * camera is up for its own reasons.
132976
134394
  */
132977
134395
  async onProbe() {
132978
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
132979
- if (this.hasFetchedFromFirmware) {
132980
- this.ctx.logger.debug("pir onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
132981
- return;
132982
- }
132983
- this.ctx.logger.info("pir onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
132984
- try {
132985
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
132986
- await sleep(1e3);
132987
- } catch (err) {
132988
- this.ctx.logger.warn("pir wake before initial probe failed — proceeding anyway", {
132989
- tags: { deviceId: this.id },
132990
- meta: { error: err instanceof Error ? err.message : String(err) }
132991
- });
132992
- }
134396
+ if (isParentSleepingBattery(this.parent)) {
134397
+ this.ctx.logger.info("pir onProbe skipped — parent battery cam is sleeping (serving persisted state)", { tags: { deviceId: this.id } });
134398
+ return;
132993
134399
  }
132994
134400
  await this.refreshFromFirmware();
132995
134401
  }
@@ -133217,12 +134623,6 @@ var SirenAccessory = class extends BaseDevice {
133217
134623
  lastSetAtMs = 0;
133218
134624
  /** Clears the `siren` slice when a timed activation runs out. */
133219
134625
  sirenTimer = null;
133220
- /** Becomes `true` after the first successful
133221
- * `refreshMotionTriggerFromFirmware` round-trip. Used by `onProbe`
133222
- * to decide whether the boot-time sleep-gate should force a wake
133223
- * (no cached state) or skip (already-have-state path). Mirrors the
133224
- * Reolink mobile app's one-shot wake-and-fetch on launch. */
133225
- hasFetchedFromFirmware = false;
133226
134626
  constructor(ctx, parent) {
133227
134627
  super(ctx, sirenAccessorySchema, {
133228
134628
  type: DeviceType.Siren,
@@ -133259,42 +134659,26 @@ var SirenAccessory = class extends BaseDevice {
133259
134659
  };
133260
134660
  }
133261
134661
  /**
133262
- * Kernel-driven probe (Phase 4). Runs on every device construction
133263
- * + addon restart. Pulls the actual motion-trigger enable state
133264
- * from the camera so the slice reflects firmware truth. The switch
133265
- * (manual fire) cap is intentionally NOT refreshed — Reolink's
133266
- * `getSiren` returns OFF as soon as the audio task ends.
133267
- *
133268
- * Sleeping battery cam:
133269
- * 1. **First-time probe (no cached state yet)** — force a one-shot
133270
- * wake + fetch so the operator sees a populated UI at launch.
133271
- * Mirrors the Reolink mobile app: at app launch it wakes the
133272
- * cam once to fetch initial state. Without this, an aggressive
133273
- * sleep timeout (~14s) can return the cam to sleep before the
133274
- * kernel finishes its initial probe pass — the retry chain
133275
- * exhausts and the slice never populates.
133276
- * 2. **Subsequent probes (slice already populated)** — skip. A
133277
- * poll on a sleeping camera returns 400 and drains the
133278
- * battery. The parent's `alignAuxDevicesState('wake')` path
133279
- * (simpleEvent `awake` push or sleep-poll backstop) refreshes
133280
- * us when the cam wakes naturally.
134662
+ * Kernel-driven probe. On a sleeping battery camera it does nothing: no
134663
+ * login, no wake (the login IS the wake, #666), not even for an accessory
134664
+ * with no cached state. The persisted slices stand in, and the parent's
134665
+ * `alignAuxDevicesState('wake')` (the wake transition, or the scheduled
134666
+ * window's authorised wake) refreshes this accessory the next time the
134667
+ * camera is up for its own reasons.
133281
134668
  */
133282
134669
  async onProbe() {
133283
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
133284
- if (this.hasFetchedFromFirmware) {
133285
- this.ctx.logger.debug("siren onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
133286
- return;
133287
- }
133288
- this.ctx.logger.info("siren onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
133289
- try {
133290
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
133291
- await sleep(1e3);
133292
- } catch (err) {
133293
- this.ctx.logger.warn("siren wake before initial probe failed — proceeding anyway", {
133294
- tags: { deviceId: this.id },
133295
- meta: { error: err instanceof Error ? err.message : String(err) }
133296
- });
133297
- }
134670
+ if (isParentSleepingBattery(this.parent)) {
134671
+ this.ctx.logger.info("siren onProbe skipped — parent battery cam is sleeping (serving persisted state)", { tags: { deviceId: this.id } });
134672
+ return;
134673
+ }
134674
+ await this.refreshMotionTriggerFromFirmware();
134675
+ }
134676
+ /** The cap read's revalidation: never logs in to a sleeping battery camera
134677
+ * (#666) — the read is served from the persisted slice. */
134678
+ async revalidateMotionTrigger() {
134679
+ if (isParentSleepingBattery(this.parent)) {
134680
+ this.ctx.logger.debug("siren motion-trigger revalidation skipped — parent battery cam is sleeping", { tags: { deviceId: this.id } });
134681
+ return;
133298
134682
  }
133299
134683
  await this.refreshMotionTriggerFromFirmware();
133300
134684
  }
@@ -133310,7 +134694,6 @@ var SirenAccessory = class extends BaseDevice {
133310
134694
  lastChangedAt,
133311
134695
  lastFetchedAt: Date.now()
133312
134696
  });
133313
- this.hasFetchedFromFirmware = true;
133314
134697
  const items = audioTask?.typeScheduleList?.item ?? [];
133315
134698
  if (items.length > 0) {
133316
134699
  const recovered = recoverSirenDetectTypeFromItems(items);
@@ -133539,7 +134922,7 @@ var SirenAccessory = class extends BaseDevice {
133539
134922
  runtimeState: this.runtimeState,
133540
134923
  cap: motionTriggerCapability,
133541
134924
  ownDeviceId: this.id,
133542
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134925
+ refresh: () => this.revalidateMotionTrigger(),
133543
134926
  staleMs: STALE_MS,
133544
134927
  empty: () => ({
133545
134928
  enabled: false,
@@ -133863,17 +135246,41 @@ function effectiveProbeFlags(sliceProbed, sliceFlags, deviceCache) {
133863
135246
  ...resolveAccessoryProbeFlags(false, {}, deviceCache)
133864
135247
  };
133865
135248
  }
135249
+ function abilityReadQuality(debug) {
135250
+ return debug?.abilitiesAvailable === true && debug.supportAvailable === true ? "full" : "partial";
135251
+ }
135252
+ /**
135253
+ * Fold one ability read into the flags already known. A `full` read is
135254
+ * authoritative, `false` included. A `partial` read is not evidence of
135255
+ * absence (D49): it may add a flag it positively saw, never retract one —
135256
+ * two degraded probes in a row on camera 3628 pruned its Siren child and the
135257
+ * next full probe re-created it under a new id. Returns a new object.
135258
+ */
135259
+ function mergeAbilityRead(previous, read, quality) {
135260
+ const taken = {};
135261
+ for (const key of FLAG_KEYS) {
135262
+ const value = read[key];
135263
+ if (value === void 0) continue;
135264
+ if (quality === "full" || value) taken[key] = value;
135265
+ }
135266
+ return {
135267
+ ...previous,
135268
+ ...taken
135269
+ };
135270
+ }
133866
135271
  /**
133867
- * The typed answer for `getAccessoryChildren()`. A probe that completed THIS
133868
- * session is a definitive read (`complete`) even while the parent is asleep
133869
- * or offline, so the kernel's reconcile can retire a child whose flag is now
133870
- * false (it still needs a second agreeing probe, D49). Flags restored from
133871
- * `deviceCache` alone, or no probe at all, are `unknown`: they spawn but
135272
+ * The typed answer for `getAccessoryChildren()`. A FULL ability read that
135273
+ * landed THIS session is a definitive read (`complete`) even while the parent
135274
+ * is asleep or offline, so the kernel's reconcile can retire a child whose
135275
+ * flag is now false (it still needs a second agreeing probe, D49). Flags
135276
+ * restored from `deviceCache` alone, a slice rehydrated from an earlier
135277
+ * session, partial reads, or no probe at all, are `unknown`: they spawn but
133872
135278
  * never prune. A legacy bare array was `unknown` whenever the parent was
133873
135279
  * offline, which is how a ghost Floodlight outlived `hasFloodlight:false`.
133874
135280
  */
133875
- function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs) {
135281
+ function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs, fullReadThisSession) {
133876
135282
  if (!sliceProbed) return accessoryChildrenUnknown("no probe completed this session", specs);
135283
+ if (!fullReadThisSession) return accessoryChildrenUnknown("no full ability read this session", specs);
133877
135284
  if (!ACCESSORY_FLAGS.some(([flag]) => typeof sliceFlags[flag] === "boolean")) return accessoryChildrenUnknown("probe carried no ability flags", specs);
133878
135285
  return {
133879
135286
  kind: "complete",
@@ -135197,8 +136604,17 @@ function createKeepAwakeLoop(deps) {
135197
136604
  let handle = null;
135198
136605
  let failing = false;
135199
136606
  const tick = () => {
136607
+ if (deps.videoFlowing?.() === true) {
136608
+ try {
136609
+ deps.onSkip?.();
136610
+ } catch {}
136611
+ return;
136612
+ }
135200
136613
  deps.wake().then(() => {
135201
136614
  failing = false;
136615
+ try {
136616
+ deps.onSuccess?.();
136617
+ } catch {}
135202
136618
  }).catch((err) => {
135203
136619
  const first = !failing;
135204
136620
  failing = true;
@@ -135989,6 +137405,13 @@ var REOLINK_AUDIO_STREAM_KEYS = [
135989
137405
  "thirdStream"
135990
137406
  ];
135991
137407
  /** Generate a short random hex token for per-stream RTSP-style credentials. */
137408
+ /**
137409
+ * The error a login dialled with replaced settings ends with. A caller still
137410
+ * awaiting it retries through `ensureApi`, which dials with the new settings.
137411
+ */
137412
+ function supersededLoginError(cause) {
137413
+ return new Error("Reolink login superseded by a connection settings change", { cause: cause ?? void 0 });
137414
+ }
135992
137415
  function randomToken(bytes) {
135993
137416
  return randomBytes(bytes).toString("hex");
135994
137417
  }
@@ -136106,6 +137529,10 @@ function coerceNumber(value) {
136106
137529
  }
136107
137530
  return null;
136108
137531
  }
137532
+ /** One successful wake in this many is logged at debug. */
137533
+ var KEEP_AWAKE_SUCCESS_LOG_EVERY = 15;
137534
+ /** A joiner of a materialize run older than this is logged (a stuck run reads as silence otherwise). */
137535
+ var MATERIALIZE_JOIN_LOG_AFTER_MS = 2e4;
136109
137536
  /**
136110
137537
  * Baichuan's native PTZ speed scale is 1..63; `runPtz` maps the cap's
136111
137538
  * normalized 0..1 onto it. Named because the autotrack loop has to know the
@@ -136278,6 +137705,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136278
137705
  }
136279
137706
  /** Lazy-connected Baichuan API. Spans the lifetime of every active stream. */
136280
137707
  api = null;
137708
+ /** Why the previous Baichuan session ended; named on the next login's log line. */
137709
+ lastSessionDropReason = null;
137710
+ loginCount = 0;
136281
137711
  /**
136282
137712
  * Stable bound handler for `api.onSimpleEvent` — created ONCE in
136283
137713
  * the class so every `onSimpleEvent` / `offSimpleEvent` call uses
@@ -136377,18 +137807,130 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136377
137807
  tags: { deviceId: this.id },
136378
137808
  meta: { activeStreams }
136379
137809
  }),
137810
+ onSuccess: () => this.noteKeepAwakeResult(true, null),
137811
+ videoFlowing: () => Date.now() - this.lastVideoFlowAt < KEEP_AWAKE_INTERVAL_MS,
137812
+ onSkip: () => this.noteKeepAwakeSkipped(),
136380
137813
  onFailure: (err, first) => {
137814
+ const error = err instanceof Error ? err.message : String(err);
136381
137815
  (first ? this.ctx.logger.info.bind(this.ctx.logger) : this.ctx.logger.debug.bind(this.ctx.logger))("keep-awake: wake failed", {
136382
137816
  tags: { deviceId: this.id },
136383
- meta: { error: err instanceof Error ? err.message : String(err) }
137817
+ meta: { error }
136384
137818
  });
137819
+ this.noteKeepAwakeResult(false, error);
136385
137820
  }
136386
137821
  });
137822
+ /** Wake counters for the current hour, plus the last broker packet count per stream. */
137823
+ keepAwakeStats = {
137824
+ windowStartedAt: 0,
137825
+ issued: 0,
137826
+ succeeded: 0,
137827
+ failed: 0,
137828
+ skipped: 0
137829
+ };
137830
+ keepAwakePacketCount = /* @__PURE__ */ new Map();
137831
+ /** A tick skipped because video was flowing: counted, never logged per tick. */
137832
+ noteKeepAwakeSkipped() {
137833
+ const stats = this.keepAwakeStats;
137834
+ if (stats.windowStartedAt === 0) stats.windowStartedAt = Date.now();
137835
+ stats.skipped += 1;
137836
+ this.flushKeepAwakeSummary(Date.now());
137837
+ }
137838
+ /**
137839
+ * Make the keep-awake loop observable: a sampled debug line for successes, an
137840
+ * hourly info summary, and — on a failure — whether the broker is still
137841
+ * receiving video (a failed wake with flowing video is not a dead camera).
137842
+ */
137843
+ noteKeepAwakeResult(ok, error) {
137844
+ const now = Date.now();
137845
+ const stats = this.keepAwakeStats;
137846
+ if (stats.windowStartedAt === 0) stats.windowStartedAt = now;
137847
+ stats.issued += 1;
137848
+ if (ok) stats.succeeded += 1;
137849
+ else stats.failed += 1;
137850
+ if (ok && stats.succeeded % KEEP_AWAKE_SUCCESS_LOG_EVERY === 1) this.ctx.logger.debug("keep-awake: wake ok", {
137851
+ tags: { deviceId: this.id },
137852
+ meta: {
137853
+ succeeded: stats.succeeded,
137854
+ issued: stats.issued,
137855
+ sampledEvery: KEEP_AWAKE_SUCCESS_LOG_EVERY
137856
+ }
137857
+ });
137858
+ this.flushKeepAwakeSummary(now);
137859
+ if (!ok) this.logVideoFlowAfterWakeFailure(error ?? "unknown");
137860
+ }
137861
+ /** The hourly info summary; resets the window. */
137862
+ flushKeepAwakeSummary(now) {
137863
+ const stats = this.keepAwakeStats;
137864
+ if (now - stats.windowStartedAt < 60 * 6e4) return;
137865
+ this.ctx.logger.info("keep-awake: hourly summary", {
137866
+ tags: { deviceId: this.id },
137867
+ meta: {
137868
+ issued: stats.issued,
137869
+ succeeded: stats.succeeded,
137870
+ failed: stats.failed,
137871
+ skippedVideoFlowing: stats.skipped,
137872
+ windowMs: now - stats.windowStartedAt
137873
+ }
137874
+ });
137875
+ this.keepAwakeStats = {
137876
+ windowStartedAt: now,
137877
+ issued: 0,
137878
+ succeeded: 0,
137879
+ failed: 0,
137880
+ skipped: 0
137881
+ };
137882
+ }
137883
+ async logVideoFlowAfterWakeFailure(error) {
137884
+ for (const camStreamId of [...this.active.keys()]) try {
137885
+ const stats = await this.ctx.api.streamBroker.getBrokerStats.query({ brokerId: `${this.id}/${camStreamId}` });
137886
+ const previous = this.keepAwakePacketCount.get(camStreamId);
137887
+ this.keepAwakePacketCount.set(camStreamId, stats.packetCount);
137888
+ if (previous !== void 0 ? stats.packetCount > previous : stats.inputFps > 0) this.ctx.logger.info("keep-awake: wake failed but the broker still receives video", {
137889
+ tags: {
137890
+ deviceId: this.id,
137891
+ camStreamId
137892
+ },
137893
+ meta: {
137894
+ error,
137895
+ inputFps: stats.inputFps,
137896
+ packetCount: stats.packetCount,
137897
+ packetsSinceLastFailedWake: previous === void 0 ? null : stats.packetCount - previous,
137898
+ brokerStatus: stats.status
137899
+ }
137900
+ });
137901
+ } catch (err) {
137902
+ this.ctx.logger.debug("keep-awake: broker stats unavailable for the video-flow check", {
137903
+ tags: {
137904
+ deviceId: this.id,
137905
+ camStreamId
137906
+ },
137907
+ meta: { error: err instanceof Error ? err.message : String(err) }
137908
+ });
137909
+ }
137910
+ }
136387
137911
  syncKeepAwake() {
136388
137912
  this.keepAwake.sync(this.active.size);
136389
137913
  }
137914
+ /**
137915
+ * A broker stream of this camera is open (a listening rfc4571 server in
137916
+ * `this.active`) — in-memory only, never a read (D49). The scheduled battery
137917
+ * refresh and the wake warm-up use it to keep their control burst off a
137918
+ * session that is carrying video: the firmware pauses video while the
137919
+ * control channel is busy.
137920
+ */
137921
+ hasActiveStream() {
137922
+ return this.active.size > 0;
137923
+ }
136390
137924
  /** Login lock — concurrent demand events must not race the login flow. */
136391
137925
  loginPromise = null;
137926
+ /**
137927
+ * Bumped by `disconnectAll`. A login started under an older generation was
137928
+ * dialled with the OLD settings (e.g. the relay before the operator picked
137929
+ * local-direct): it is closed and discarded instead of becoming `this.api`.
137930
+ */
137931
+ loginGeneration = 0;
137932
+ /** The client a login in flight is dialling, so `disconnectAll` can abort it. */
137933
+ pendingLoginApi = null;
136392
137934
  /** Wall-clock ms of the last video packet the stream server produced; 0 = none yet. */
136393
137935
  lastVideoFlowAt = 0;
136394
137936
  /** True once we've discovered (via getBatteryInfo) that this is a battery cam. */
@@ -136467,6 +138009,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136467
138009
  batteryUpdateTimer = null;
136468
138010
  /** Set by `removeDevice`: nothing may re-arm a timer on a removed camera. */
136469
138011
  removed = false;
138012
+ /**
138013
+ * True once a FULL ability read (SupportInfo and AbilityInfo both answered)
138014
+ * landed this session. Until then the accessory answer is `unknown` and can
138015
+ * never prune a child: a rehydrated slice or a partial read is not a list
138016
+ * (D49). Read defensively — the base constructor may ask before field init.
138017
+ */
138018
+ fullAbilityReadThisSession = false;
136470
138019
  /** Single-flight gate so two interval fires can't overlap. */
136471
138020
  /** Aux accessory references registered by spawned children
136472
138021
  * (siren / floodlight / pir). The parent's centralised align
@@ -137106,9 +138655,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137106
138655
  } catch (err) {
137107
138656
  this.ctx.logger.debug("reolink deviceCache snapshot persist failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137108
138657
  }
137109
- if (slices === void 0 && this.isBattery && this.isEmailPushEligible) await this.refreshCameraEmailConfig().catch((err) => {
137110
- this.ctx.logger.debug("reolink email config probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137111
- });
138658
+ if (slices === void 0 && this.isBattery && this.isEmailPushEligible) {
138659
+ if (this.sleeping) {
138660
+ this.ctx.logger.info("reolink email config read skipped — the camera fell asleep during the refresh", {
138661
+ tags: { deviceId: this.id },
138662
+ meta: { reason }
138663
+ });
138664
+ return;
138665
+ }
138666
+ await this.refreshCameraEmailConfig().catch((err) => {
138667
+ this.ctx.logger.debug("reolink email config probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
138668
+ });
138669
+ }
137112
138670
  }
137113
138671
  /**
137114
138672
  * Admin-only raw-read debug surface (D346): return the library's response
@@ -137222,7 +138780,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137222
138780
  * leave the catalog stale rather than stamping it fresh.
137223
138781
  */
137224
138782
  async wakeForClipCatalogRefresh() {
137225
- if (!await this.wakeIfSleeping()) throw new Error(`ReolinkCamera ${this.id}: the authorised clip-refresh wake did not bring the camera up`);
138783
+ if (!await this.wakeIfSleeping("clip-catalog-refresh")) throw new Error(`ReolinkCamera ${this.id}: the authorised clip-refresh wake did not bring the camera up`);
137226
138784
  }
137227
138785
  /**
137228
138786
  * Wake this camera because the OPERATOR asked for one of its clips — a
@@ -137232,7 +138790,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137232
138790
  * so the service can refuse `wake-timeout` by name.
137233
138791
  */
137234
138792
  async wakeForClipRead(timeoutMs) {
137235
- return this.wakeIfSleeping(timeoutMs);
138793
+ return this.wakeIfSleeping("clip-read", timeoutMs);
137236
138794
  }
137237
138795
  clipTimeZoneWarned = { done: false };
137238
138796
  getClipDeviceRef() {
@@ -137286,7 +138844,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137286
138844
  if (kinds.includes(AccessoryKind.Siren)) push(AccessoryKind.Siren, DeviceType.Siren, ACCESSORY_LABEL[AccessoryKind.Siren]);
137287
138845
  if (kinds.includes(AccessoryKind.Floodlight)) push(AccessoryKind.Floodlight, DeviceType.Light, ACCESSORY_LABEL[AccessoryKind.Floodlight]);
137288
138846
  if (kinds.includes(AccessoryKind.PirSensor)) push(AccessoryKind.PirSensor, DeviceType.Switch, ACCESSORY_LABEL[AccessoryKind.PirSensor]);
137289
- return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out);
138847
+ return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out, this.fullAbilityReadThisSession === true);
137290
138848
  }
137291
138849
  /**
137292
138850
  * Resolver injected by the provider (`setEmailPushParamsResolver`) so
@@ -137322,7 +138880,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137322
138880
  * camera. No-op for non-battery or already-awake cams. Best-effort:
137323
138881
  * returns whether the camera is (now) reachable/awake.
137324
138882
  */
137325
- async wakeIfSleeping(timeoutMs = 15e3) {
138883
+ async wakeIfSleeping(caller, timeoutMs = 15e3) {
137326
138884
  if (!this.isBattery || !this.sleeping) return true;
137327
138885
  let api;
137328
138886
  try {
@@ -137333,7 +138891,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137333
138891
  this.markWakeIssued();
137334
138892
  this.ctx.logger.info("proactive action: waking sleeping battery cam", {
137335
138893
  tags: { deviceId: this.id },
137336
- meta: { timeoutMs }
138894
+ meta: {
138895
+ timeoutMs,
138896
+ caller
138897
+ }
137337
138898
  });
137338
138899
  this.ctx.eventBus.emit(createEvent(EventCategory.BatteryOnWakeStarted, this.eventSource(), { deviceId: this.id }));
137339
138900
  const channel = this.getChannel();
@@ -137353,7 +138914,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137353
138914
  } catch (err) {
137354
138915
  this.ctx.logger.warn("proactive action: wake did not complete in time", {
137355
138916
  tags: { deviceId: this.id },
137356
- meta: { error: err instanceof Error ? err.message : String(err) }
138917
+ meta: {
138918
+ caller,
138919
+ error: err instanceof Error ? err.message : String(err)
138920
+ }
137357
138921
  });
137358
138922
  return false;
137359
138923
  }
@@ -137402,7 +138966,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137402
138966
  "vehicle"
137403
138967
  ];
137404
138968
  const attachmentType = this.config.get("emailPushAttachment") ?? "picture";
137405
- await this.wakeIfSleeping();
138969
+ await this.wakeIfSleeping("auto-configure-email-push");
137406
138970
  const api = await this.ensureApi();
137407
138971
  this.ctx.logger.info("email-push: auto-configuring camera", {
137408
138972
  tags: { deviceId: this.id },
@@ -137452,7 +139016,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137452
139016
  if (!this.baichuanWebhookParamsResolver) throw userError("reolink.webhook-not-wired", void 0, "HaCfg Webhook Server is not wired — restart the Reolink addon");
137453
139017
  const params = await this.baichuanWebhookParamsResolver();
137454
139018
  if (!params) throw new Error("The HaCfg webhook cannot be armed for this camera (it is not a standalone battery camera).");
137455
- await this.wakeIfSleeping();
139019
+ await this.wakeIfSleeping("auto-configure-baichuan-webhook");
137456
139020
  const api = await this.ensureApi();
137457
139021
  const supported = await api.probeBaichuanWebhookSupport();
137458
139022
  this.baichuanWebhookSupportedCached = supported;
@@ -137551,7 +139115,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137551
139115
  * Push tab read.
137552
139116
  */
137553
139117
  async refreshCameraEmailConfig() {
137554
- await this.wakeIfSleeping();
139118
+ await this.wakeIfSleeping("refresh-camera-email-config");
137555
139119
  const api = await this.ensureApi();
137556
139120
  const channel = this.getChannel();
137557
139121
  const [email, task] = await Promise.all([api.getEmail(), api.getEmailTask(channel).catch(() => null)]);
@@ -137668,7 +139232,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137668
139232
  await this.autoConfigureBaichuanWebhook();
137669
139233
  });
137670
139234
  this.registerDeviceAction("refresh-settings", deviceCustomAction(unknown(), RefreshSettingsResultSchema, { kind: "mutation" }), async () => {
137671
- const awake = await this.wakeIfSleeping();
139235
+ const awake = await this.wakeIfSleeping("operator-rehydrate");
137672
139236
  const [snapshot, warm] = await Promise.allSettled([this.refreshParentSettingsSnapshot(void 0, "operator"), this.warmCapSlicesOnWake({ force: true })]);
137673
139237
  const warmed = warm.status === "fulfilled" ? warm.value.warmed : 0;
137674
139238
  const capsTotal = this.capWarmers.size;
@@ -137698,6 +139262,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137698
139262
  this.registerRecordingOnboardCap();
137699
139263
  this.registerStreamCatalogProvider();
137700
139264
  this.registerNativeObjectDetectionCap();
139265
+ this.adoptBatteryFromDeviceCache();
139266
+ }
139267
+ /** Sets `isBattery` from the persisted `deviceCache` and, for a battery
139268
+ * camera, registers its battery cap and arms the refresh timer. Called from
139269
+ * cap registration; `isBatteryCam()` answers from the flag it sets. */
139270
+ adoptBatteryFromDeviceCache() {
137701
139271
  const cache = this.config.get("deviceCache");
137702
139272
  if (cache?.deviceType === "battery-cam" || cache?.hasBattery === true) {
137703
139273
  this.isBattery = true;
@@ -137761,7 +139331,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137761
139331
  const reported = typeof info.batteryPercent === "number" ? Math.max(0, Math.min(100, Math.round(info.batteryPercent))) : void 0;
137762
139332
  const measured = reported !== void 0 && isMeasuredCameraBatteryLevel(reported, {
137763
139333
  sleeping,
137764
- charging
139334
+ charging,
139335
+ voltage: info.voltage
137765
139336
  });
137766
139337
  if (reported === 0) this.ctx.logger.info("battery read reporting 0", {
137767
139338
  tags: { deviceId: this.id },
@@ -137966,6 +139537,26 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137966
139537
  return false;
137967
139538
  }
137968
139539
  }
139540
+ /** A battery camera running on its adapter is wired: it never sleeps. */
139541
+ isOnAdapterPower() {
139542
+ return this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter";
139543
+ }
139544
+ /**
139545
+ * Whether a silent stream source may be a camera gone to sleep. A battery
139546
+ * camera whose power source is not known yet (no snapshot, or `unknown`)
139547
+ * counts as sleeping — refusing one recovery is cheap, waking a sleeper
139548
+ * drains it; a camera with no battery feature is never refused.
139549
+ */
139550
+ streamSourceMaySleep() {
139551
+ return reolinkCameraSleeps(this.featureInputs()) && !this.isOnAdapterPower();
139552
+ }
139553
+ /** Asked by the lib before EVERY recovery of a silent source: read live, never frozen at creation. */
139554
+ streamRecoveryVerdict() {
139555
+ return this.streamSourceMaySleep() ? {
139556
+ allowed: false,
139557
+ reason: "the camera may be asleep: a new session would wake it, so the next consumer decides"
139558
+ } : { allowed: true };
139559
+ }
137969
139560
  /**
137970
139561
  * THE single writer of the `battery.sleeping` slice.
137971
139562
  *
@@ -137995,7 +139586,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137995
139586
  lastFirstHandCommitAt: this.sleepStateChangedAt,
137996
139587
  nowMs: Date.now(),
137997
139588
  videoFlowing: Date.now() - this.lastVideoFlowAt < VIDEO_FLOW_FRESH_MS,
137998
- wired: this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter"
139589
+ wired: this.isOnAdapterPower()
137999
139590
  });
138000
139591
  if (decision.kind === "unchanged") return false;
138001
139592
  if (decision.kind === "refused") {
@@ -138118,10 +139709,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138118
139709
  const now = Date.now();
138119
139710
  const quantised = now - now % ReolinkCamera.CONTACT_WRITE_QUANTUM_MS;
138120
139711
  const previousContact = this.state.battery.lastContactAt ?? 0;
138121
- this.setCapSlice(batteryCapability, {
139712
+ this.setCapSlice(batteryCapability, carryRefreshBookkeeping(this.state.battery, {
138122
139713
  ...mapped,
138123
139714
  lastContactAt: Math.max(previousContact, quantised)
138124
- });
139715
+ }));
138125
139716
  }
138126
139717
  /**
138127
139718
  * Hub-fed battery refresh for an adopted child. The parent's
@@ -138423,7 +140014,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138423
140014
  * changed.
138424
140015
  */
138425
140016
  async applyEmailConfigPatch(fields) {
138426
- await this.wakeIfSleeping();
140017
+ await this.wakeIfSleeping("apply-email-config-patch");
138427
140018
  const api = await this.ensureApi();
138428
140019
  const channel = this.getChannel();
138429
140020
  const patch = {};
@@ -140972,7 +142563,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
140972
142563
  * session or touches the broker.
140973
142564
  */
140974
142565
  async buildStreamCatalog() {
140975
- if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(this.cachedStreamDescriptors);
142566
+ if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(stampCurrentFeatures(this.cachedStreamDescriptors, this.features));
140976
142567
  const restored = this.restoreStreamCatalogFromLedger();
140977
142568
  if (restored) return this.withLiveNativeSdp(restored);
140978
142569
  if (this.buildStreamCatalogInFlight) return this.withLiveNativeSdp(await this.buildStreamCatalogInFlight);
@@ -141256,7 +142847,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141256
142847
  const stored = this.runtimeState.getCapState(streamCatalogCapability.name);
141257
142848
  const descriptors = stored?.descriptors;
141258
142849
  if (!descriptors || descriptors.length === 0) return null;
141259
- this.cachedStreamDescriptors = [...descriptors];
142850
+ this.cachedStreamDescriptors = stampCurrentFeatures(descriptors, this.features);
141260
142851
  this.ctx.logger.info("stream catalog restored from the durable slice (no camera contact)", {
141261
142852
  tags: { deviceId: this.id },
141262
142853
  meta: {
@@ -141304,7 +142895,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141304
142895
  ...entry.codec !== void 0 ? { codec: entry.codec } : {},
141305
142896
  ...entry.metadata ? { metadata: entry.metadata } : {},
141306
142897
  ...entry.maxSessionMs !== void 0 ? { maxSessionMs: entry.maxSessionMs } : {},
141307
- deviceFeatures: entry.deviceFeatures ?? [...this.features],
142898
+ deviceFeatures: [...this.features],
141308
142899
  autoEligible: entry.autoEligible ?? true
141309
142900
  });
141310
142901
  this.publishedStreamIds.add(entry.camStreamId);
@@ -141341,6 +142932,31 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141341
142932
  * listening; if the lib idle-tore-down between calls we recreate.
141342
142933
  */
141343
142934
  async materializeStreamSocket(camStreamId) {
142935
+ const inFlight = this.materializeInFlight.get(camStreamId);
142936
+ if (inFlight) {
142937
+ const ageMs = Date.now() - (this.materializeStartedAt.get(camStreamId) ?? Date.now());
142938
+ if (ageMs >= MATERIALIZE_JOIN_LOG_AFTER_MS) this.ctx.logger.warn("materializeStreamSocket: joining a run still in flight", {
142939
+ tags: {
142940
+ deviceId: this.id,
142941
+ camStreamId
142942
+ },
142943
+ meta: { inFlightMs: ageMs }
142944
+ });
142945
+ return inFlight;
142946
+ }
142947
+ this.materializeStartedAt.set(camStreamId, Date.now());
142948
+ const run = this.runMaterializeStreamSocket(camStreamId).finally(() => {
142949
+ this.materializeStartedAt.delete(camStreamId);
142950
+ if (this.materializeInFlight.get(camStreamId) === run) this.materializeInFlight.delete(camStreamId);
142951
+ });
142952
+ this.materializeInFlight.set(camStreamId, run);
142953
+ return run;
142954
+ }
142955
+ /** In-flight `materializeStreamSocket` runs, per camStreamId. */
142956
+ materializeInFlight = /* @__PURE__ */ new Map();
142957
+ /** When each in-flight run started, to say how long a joiner waited on it. */
142958
+ materializeStartedAt = /* @__PURE__ */ new Map();
142959
+ async runMaterializeStreamSocket(camStreamId) {
141344
142960
  const parts = parseCamStreamId(camStreamId, this.getChannel());
141345
142961
  if (!parts || parts.kind !== "native") return;
141346
142962
  this.ctx.logger.info("broker requested rfc4571 source refresh — materializing on demand", {
@@ -141374,7 +142990,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141374
142990
  deviceId: this.id,
141375
142991
  camStreamId
141376
142992
  },
141377
- meta: { url: `tcp://${server.host}:${server.port}` }
142993
+ meta: {
142994
+ url: `tcp://${server.host}:${server.port}`,
142995
+ republishCause: "broker-source-refresh (materializeStreamSocket)"
142996
+ }
141378
142997
  });
141379
142998
  }
141380
142999
  async removeDevice() {
@@ -141459,7 +143078,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141459
143078
  requireAuth: true,
141460
143079
  deviceId: this.stableId,
141461
143080
  requestedId: camStreamId,
141462
- logger: this.libLoggerAdapter()
143081
+ logger: this.libLoggerAdapter(),
143082
+ resilience: { recoveryGuard: () => this.streamRecoveryVerdict() }
141463
143083
  });
141464
143084
  } catch (err) {
141465
143085
  this.ctx.logger.error("rfc4571: createRfc4571TcpServer failed", {
@@ -141726,17 +143346,21 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141726
143346
  logger: this.ctx.logger,
141727
143347
  now: () => Date.now(),
141728
143348
  isAwake: () => !this.sleeping,
143349
+ isStreaming: () => this.hasActiveStream(),
141729
143350
  intervalMs: () => resolveBatteryRefreshIntervalMs(this.config.get("batteryRefreshMinutes")),
141730
143351
  lastFullRefreshAt: () => this.state.battery.lastFullRefreshAt,
141731
143352
  wake: async () => {
141732
143353
  if (!this.canProactivelyWake("scheduled-refresh")) return false;
141733
143354
  this.markWakeIssued();
141734
- return this.wakeIfSleeping();
143355
+ return this.wakeIfSleeping("scheduled-refresh");
141735
143356
  },
141736
143357
  refreshAll: () => this.refreshEverythingNow(),
141737
143358
  stamp: (at) => {
141738
143359
  this.state.battery.lastFullRefreshAt = at;
141739
- }
143360
+ },
143361
+ attemptLedger: attemptLedgerOverSlice(() => this.state.battery, (fields) => {
143362
+ this.runtimeState.patchCapState(batteryCapability.name, fields);
143363
+ })
141740
143364
  });
141741
143365
  return this.batteryRefresh;
141742
143366
  }
@@ -141930,13 +143554,16 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141930
143554
  });
141931
143555
  }
141932
143556
  else await this.reprobeAccessoriesIfStale(reason);
141933
- if (!(this.isBattery ? await this.getBatteryRefresh().noteAwake().catch(() => false) : false)) {
143557
+ const scheduledRefreshCovered = this.isBattery ? await this.getBatteryRefresh().noteAwake().catch(() => false) : false;
143558
+ const streamingDefer = this.isBattery && this.getBatteryRefresh().shouldDeferForStream();
143559
+ if (streamingDefer) this.getBatteryRefresh().noteStreamDeferred("wake-warm-up");
143560
+ if (!scheduledRefreshCovered && !streamingDefer) {
141934
143561
  await this.warmCapSlicesOnWake();
141935
143562
  await this.warmSnapshotOnWake();
141936
143563
  await this.alignAuxDevicesState("wake");
141937
143564
  await this.refreshParentSettingsSnapshot();
141938
143565
  }
141939
- await this.refreshClipCatalogOnWake();
143566
+ if (!streamingDefer) await this.refreshClipCatalogOnWake();
141940
143567
  }
141941
143568
  static PING_INTERVAL_MS = 3e4;
141942
143569
  static PING_MAX_FAILURES = 3;
@@ -142265,6 +143892,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
142265
143892
  const entries = [...this.active.values()];
142266
143893
  this.active.clear();
142267
143894
  this.keepAwake.stop();
143895
+ this.loginGeneration += 1;
143896
+ this.loginPromise = null;
143897
+ const pending = this.pendingLoginApi;
143898
+ this.pendingLoginApi = null;
143899
+ if (pending) try {
143900
+ await pending.close({ reason: "login-superseded" });
143901
+ } catch {}
142268
143902
  for (const entry of entries) try {
142269
143903
  await entry.server.close("disconnect-all");
142270
143904
  } catch {}
@@ -143340,7 +144974,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143340
144974
  async applySettingsPatch(patch) {
143341
144975
  if (this.isHubChild()) this.refuseHubChildPatch(patch);
143342
144976
  const { emailSmtpServer, emailSmtpPort, emailUserName, emailPassword, emailSsl, emailRecipient1, emailRecipient2, emailRecipient3, emailSendNickname, emailScheduleEnabled, osdChannelEnabled, osdChannelName, osdChannelPosition, osdTimeEnabled, osdTimePosition, osdWatermark, hubName: _hubName, [POWER_SOURCE_SETTING_KEY]: powerSource, ...rest } = patch;
143343
- if ((osdChannelEnabled !== void 0 || osdChannelName !== void 0 || osdChannelPosition !== void 0 || osdTimeEnabled !== void 0 || osdTimePosition !== void 0 || osdWatermark !== void 0 || emailSmtpServer !== void 0 || emailRecipient1 !== void 0 || powerSource !== void 0) && !await this.wakeIfSleeping()) this.ctx.logger.warn("settings write: battery cam did not wake — writing anyway", { tags: { deviceId: this.id } });
144977
+ if ((osdChannelEnabled !== void 0 || osdChannelName !== void 0 || osdChannelPosition !== void 0 || osdTimeEnabled !== void 0 || osdTimePosition !== void 0 || osdWatermark !== void 0 || emailSmtpServer !== void 0 || emailRecipient1 !== void 0 || powerSource !== void 0) && !await this.wakeIfSleeping("settings-write")) this.ctx.logger.warn("settings write: battery cam did not wake — writing anyway", { tags: { deviceId: this.id } });
143344
144978
  const emailFields = {
143345
144979
  emailSmtpServer,
143346
144980
  emailSmtpPort,
@@ -143388,7 +145022,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143388
145022
  if (Object.keys(rest).length === 0 && !hasOsdPatch) return;
143389
145023
  if (Object.keys(rest).length > 0) await this.config.setAll(rest);
143390
145024
  const typedPatch = patch;
143391
- if (typedPatch.host || typedPatch.port || typedPatch.username || typedPatch.password) {
145025
+ if (typedPatch.host || typedPatch.port || typedPatch.username || typedPatch.password || typedPatch.transport || typedPatch.uid || typedPatch.udpDiscoveryMethod) {
143392
145026
  await this.disconnectAll();
143393
145027
  return;
143394
145028
  }
@@ -143800,14 +145434,15 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143800
145434
  * separate auth flow per accessory. `ReolinkAccessory` calls this
143801
145435
  * inside its `applyOn` / `fetchOn` to reach the camera firmware.
143802
145436
  */
143803
- /** Implements `ReolinkAccessoryHost.isBatteryCam` so spawned
143804
- * accessory children skip background polling on a sleeping
143805
- * battery cam (Baichuan polls on a sleeping camera return 400 +
143806
- * drain the battery). Reads from the runtime feature-probe slice
143807
- * populated during `onProbe()`; falls back to false when the probe
143808
- * hasn't completed yet. */
145437
+ /** Implements `ReolinkAccessoryHost.isBatteryCam`: returns `this.isBattery`,
145438
+ * the same flag the parent's own sleep gates read. That flag is set during
145439
+ * cap registration from the persisted `deviceCache`
145440
+ * (`deviceType === 'battery-cam' || hasBattery`) and again at login. It is
145441
+ * NOT read from the `feature-probe` slice: a battery camera asleep at boot
145442
+ * never seeds that slice, so every accessory probed straight through its
145443
+ * sleep gate and woke the camera (#666, device 640). */
143809
145444
  isBatteryCam() {
143810
- return this.runtimeState.getCapState("feature-probe")?.flags?.["hasBattery"] === true;
145445
+ return this.isBattery;
143811
145446
  }
143812
145447
  /** Implements `ReolinkAccessoryHost.isSleeping`. Reads the canonical
143813
145448
  * source of truth — the `battery.sleeping` runtime-state slice — so
@@ -143822,7 +145457,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143822
145457
  /** Implements `ReolinkAccessoryHost.wakeForWrite`: an accessory's operator
143823
145458
  * write (PIR, ...) wakes a sleeping battery camera first. */
143824
145459
  wakeForWrite() {
143825
- return this.wakeIfSleeping();
145460
+ return this.wakeIfSleeping("write");
143826
145461
  }
143827
145462
  /** Implements `ReolinkAccessoryHost.probeAbility`: the effective probe flag
143828
145463
  * (live slice, else the persisted probe); `undefined` = never probed. */
@@ -143858,7 +145493,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143858
145493
  meta: {
143859
145494
  port,
143860
145495
  transport,
143861
- hasUid: Boolean(uid)
145496
+ hasUid: Boolean(uid),
145497
+ loginReason: this.lastSessionDropReason ?? "first-login",
145498
+ loginsSoFar: this.loginCount
143862
145499
  }
143863
145500
  });
143864
145501
  const debugOptions = this.getBaichuanDebugOptions();
@@ -143874,6 +145511,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143874
145511
  debugOptions: debugOptions === void 0 ? null : Object.keys(debugOptions)
143875
145512
  }
143876
145513
  });
145514
+ const generation = this.loginGeneration;
143877
145515
  this.loginPromise = (async () => {
143878
145516
  const api = new ReolinkBaichuanApi({
143879
145517
  host,
@@ -143886,16 +145524,41 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143886
145524
  ...debugOptions ? { debugOptions } : {},
143887
145525
  logger: this.libLoggerAdapter()
143888
145526
  });
145527
+ this.pendingLoginApi = api;
143889
145528
  try {
143890
- await api.login();
145529
+ await loginWithin(() => api.login(), LOGIN_DEADLINE_MS, () => api.close({ reason: "login-deadline" }));
143891
145530
  } catch (err) {
145531
+ if (generation !== this.loginGeneration) throw supersededLoginError(err);
145532
+ if (err instanceof LoginDeadlineError) this.ctx.logger.warn("Baichuan login abandoned — camera did not answer in time", {
145533
+ tags: { deviceId: this.id },
145534
+ meta: { deadlineMs: err.deadlineMs }
145535
+ });
145536
+ this.pendingLoginApi = null;
143892
145537
  this.loginPromise = null;
143893
145538
  if (isConnectivityFailure(err)) this.noteUnreachable(err instanceof Error ? err.message : String(err));
143894
145539
  else if (this.ownsReachability()) this.reachability.noteReachable();
143895
145540
  throw err;
143896
145541
  }
145542
+ if (generation !== this.loginGeneration) {
145543
+ try {
145544
+ await api.close({ reason: "login-superseded" });
145545
+ } catch {}
145546
+ throw supersededLoginError(null);
145547
+ }
145548
+ this.pendingLoginApi = null;
143897
145549
  this.api = api;
143898
145550
  this.loginPromise = null;
145551
+ this.loginCount += 1;
145552
+ if (this.lastSessionDropReason !== null) {
145553
+ this.ctx.logger.info("Baichuan session re-logged-in", {
145554
+ tags: { deviceId: this.id },
145555
+ meta: {
145556
+ reason: this.lastSessionDropReason,
145557
+ loginCount: this.loginCount
145558
+ }
145559
+ });
145560
+ this.lastSessionDropReason = null;
145561
+ }
143899
145562
  this.reconnectAttempts = 0;
143900
145563
  if (this.ownsReachability()) this.reachability.noteReachable();
143901
145564
  const persistedDeviceType = this.config.get("deviceCache")?.deviceType;
@@ -143912,6 +145575,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143912
145575
  this.isBattery = false;
143913
145576
  }
143914
145577
  else this.isBattery = false;
145578
+ if (!this.isBattery) api.setGeneralSessionRecycling({ guard: () => true });
143915
145579
  if (this.isBattery) {
143916
145580
  this.startSleepPoll();
143917
145581
  this.startBatteryUpdatePolling();
@@ -144149,11 +145813,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144149
145813
  let hasPirSensor;
144150
145814
  let hasAutotrack;
144151
145815
  let capabilitiesRead = false;
145816
+ let readQuality = "partial";
144152
145817
  try {
144153
145818
  channelCount = await api.getChannelCount();
144154
145819
  } catch {}
144155
145820
  try {
144156
- const { capabilities } = await api.getDeviceCapabilities(this.getChannel());
145821
+ const { capabilities, debug } = await api.getDeviceCapabilities(this.getChannel());
145822
+ readQuality = abilityReadQuality(debug);
144157
145823
  hasPtz = capabilities.hasPtz;
144158
145824
  hasIntercom = capabilities.hasIntercom;
144159
145825
  hasDoorbell = capabilities.isDoorbell;
@@ -144174,12 +145840,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144174
145840
  return;
144175
145841
  }
144176
145842
  const prev = this.runtimeState.getCapState("feature-probe");
144177
- const prevFlags = prev?.flags ?? {};
145843
+ const prevFlags = this.getProbeFlags();
144178
145844
  const inferredDeviceType = this.config.get("deviceCache")?.deviceType ?? (this.isBattery ? "battery-cam" : null);
144179
145845
  const persistedModel = this.config.get("deviceCache")?.model ?? null;
144180
- const flags = {
144181
- ...prevFlags,
144182
- hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery,
145846
+ const readFlags = {
144183
145847
  ...hasPtz !== void 0 ? { hasPtz } : {},
144184
145848
  ...hasIntercom !== void 0 ? { hasIntercom } : {},
144185
145849
  ...hasDoorbell !== void 0 ? { hasDoorbell } : {},
@@ -144188,6 +145852,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144188
145852
  ...hasPirSensor !== void 0 ? { hasPirSensor } : {},
144189
145853
  ...hasAutotrack !== void 0 ? { hasAutotrack } : {}
144190
145854
  };
145855
+ const flags = {
145856
+ ...mergeAbilityRead(prevFlags, readFlags, readQuality),
145857
+ hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery
145858
+ };
145859
+ const fullRead = capabilitiesRead && readQuality === "full";
145860
+ if (fullRead) this.fullAbilityReadThisSession = true;
144191
145861
  const now = Date.now();
144192
145862
  const next = {
144193
145863
  flags,
@@ -144204,7 +145874,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144204
145874
  ...inferredDeviceType ? { deviceType: inferredDeviceType } : {},
144205
145875
  ...channelCount !== void 0 ? { channelCount } : {}
144206
145876
  };
144207
- await this.config.setAll({ deviceCache: capabilitiesRead ? withPersistedProbe(identity, flags, now) : identity });
145877
+ await this.config.setAll({ deviceCache: fullRead ? withPersistedProbe(identity, flags, now) : identity });
144208
145878
  } catch (err) {
144209
145879
  this.ctx.logger.debug("deviceCache identity persist failed (non-fatal)", {
144210
145880
  tags: { deviceId: this.id },
@@ -144221,7 +145891,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144221
145891
  meta: {
144222
145892
  flags,
144223
145893
  channelCount,
144224
- deviceType: inferredDeviceType
145894
+ deviceType: inferredDeviceType,
145895
+ abilityRead: capabilitiesRead ? readQuality : "failed",
145896
+ ...capabilitiesRead && readQuality === "partial" ? { partialRead: readFlags } : {}
144225
145897
  }
144226
145898
  });
144227
145899
  }
@@ -144282,6 +145954,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144282
145954
  async dropBaichuanSession(reason) {
144283
145955
  const current = this.api;
144284
145956
  this.api = null;
145957
+ if (current) this.lastSessionDropReason = reason;
144285
145958
  if (!current) return;
144286
145959
  try {
144287
145960
  await current.close({ reason });
@@ -144352,6 +146025,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144352
146025
  if (this.reconnectTimer) return;
144353
146026
  if (this.isBattery) {
144354
146027
  this.api = null;
146028
+ this.lastSessionDropReason = `disconnect: ${reason}`;
144355
146029
  this.ctx.logger.debug("Battery cam disconnect — deferring reconnect to next demand", {
144356
146030
  tags: { deviceId: this.id },
144357
146031
  meta: {
@@ -144382,6 +146056,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144382
146056
  }
144383
146057
  });
144384
146058
  this.api = null;
146059
+ this.lastSessionDropReason = `reconnect: ${reason}`;
144385
146060
  if (this.removed) return;
144386
146061
  this.reconnectTimer = setTimeout(() => {
144387
146062
  this.reconnectTimer = null;
@@ -144464,7 +146139,8 @@ var AutodetectCache = class {
144464
146139
  input.username,
144465
146140
  passHash,
144466
146141
  input.uid?.trim() ?? "",
144467
- input.transport
146142
+ input.transport,
146143
+ input.udpDiscoveryMethod ?? ""
144468
146144
  ].join(":");
144469
146145
  }
144470
146146
  /**
@@ -144527,6 +146203,34 @@ var AutodetectCache = class {
144527
146203
  }
144528
146204
  };
144529
146205
  //#endregion
146206
+ //#region src/autodetect-inputs.ts
146207
+ function readString(obj, key) {
146208
+ const v = obj[key];
146209
+ return typeof v === "string" ? v : "";
146210
+ }
146211
+ function readTransportMode(obj) {
146212
+ const v = obj["transport"];
146213
+ return v === "tcp" || v === "udp" || v === "auto" ? v : "auto";
146214
+ }
146215
+ /** `auto` / unknown / absent mean "race every method"; only a real method is kept. */
146216
+ function readDiscoveryMethod(obj) {
146217
+ const parsed = ReolinkUdpDiscoveryMethodSchema.safeParse(obj["udpDiscoveryMethod"]);
146218
+ return parsed.success ? parsed.data : void 0;
146219
+ }
146220
+ function buildAutodetectInputs(form) {
146221
+ const rawUid = readString(form, "uid").trim();
146222
+ const rawPort = form["port"];
146223
+ return {
146224
+ host: readString(form, "host").trim(),
146225
+ username: (readString(form, "username") || "admin").trim(),
146226
+ password: readString(form, "password"),
146227
+ uid: rawUid.length > 0 ? rawUid : void 0,
146228
+ transport: readTransportMode(form),
146229
+ port: typeof rawPort === "number" && Number.isFinite(rawPort) ? rawPort : 9e3,
146230
+ udpDiscoveryMethod: readDiscoveryMethod(form)
146231
+ };
146232
+ }
146233
+ //#endregion
144530
146234
  //#region src/creation-schema.ts
144531
146235
  /**
144532
146236
  * Creation form for Reolink devices.
@@ -144704,6 +146408,28 @@ function buildCreationFormSchema() {
144704
146408
  field: "transport",
144705
146409
  notEquals: "tcp"
144706
146410
  }
146411
+ },
146412
+ {
146413
+ type: "select",
146414
+ key: "udpDiscoveryMethod",
146415
+ label: "UDP discovery",
146416
+ labelKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.label",
146417
+ default: "auto",
146418
+ description: "Auto races every method and may settle on the Reolink relay. \"Local only\" talks straight to the camera IP and never uses Reolink servers.",
146419
+ descriptionKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.description",
146420
+ options: [{
146421
+ value: "auto",
146422
+ label: "Auto (may use the Reolink relay)",
146423
+ labelKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.o_auto.label"
146424
+ }, {
146425
+ value: "local-direct",
146426
+ label: "Local only (direct to the camera IP)",
146427
+ labelKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.o_local.label"
146428
+ }],
146429
+ showWhen: {
146430
+ field: "transport",
146431
+ notEquals: "tcp"
146432
+ }
144707
146433
  }
144708
146434
  ]
144709
146435
  },
@@ -146409,6 +148135,12 @@ function createWebhookHandler(deps) {
146409
148135
  }
146410
148136
  //#endregion
146411
148137
  //#region src/addon.ts
148138
+ /** The broker's source-refresh request; a `reason` it adds is ignored (the library heals a silent source itself). */
148139
+ var sourceRefreshPayload = object({
148140
+ deviceId: number(),
148141
+ camStreamId: string().optional(),
148142
+ reason: string().optional()
148143
+ });
146412
148144
  /**
146413
148145
  * Adapt a camstack scoped logger to the lib's `Logger` shape (just
146414
148146
  * `log(...)`). Lib lines are prefixed with `[AutoDetect]` /
@@ -146435,28 +148167,6 @@ function getString(obj, key) {
146435
148167
  const v = obj[key];
146436
148168
  return typeof v === "string" ? v : "";
146437
148169
  }
146438
- function getNumber(obj, key, fallback) {
146439
- const v = obj[key];
146440
- return typeof v === "number" && Number.isFinite(v) ? v : fallback;
146441
- }
146442
- function getTransportMode(obj) {
146443
- const v = obj["transport"];
146444
- return v === "tcp" || v === "udp" || v === "auto" ? v : "auto";
146445
- }
146446
- function buildAutodetectInputs(form) {
146447
- const host = getString(form, "host").trim();
146448
- const username = (getString(form, "username") || "admin").trim();
146449
- const password = getString(form, "password");
146450
- const rawUid = getString(form, "uid").trim();
146451
- return {
146452
- host,
146453
- username,
146454
- password,
146455
- uid: rawUid.length > 0 ? rawUid : void 0,
146456
- transport: getTransportMode(form),
146457
- port: getNumber(form, "port", 9e3)
146458
- };
146459
- }
146460
148170
  function buildAutodetectLabels(result) {
146461
148171
  const labels = [];
146462
148172
  const model = result.deviceInfo?.type;
@@ -146999,9 +148709,14 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
146999
148709
  provider: { list: () => intercomFailureReport.list() }
147000
148710
  });
147001
148711
  this.subscribe({ category: EventCategory.StreamBrokerOnRequestStreamSourceRefresh }, (event) => {
147002
- const data = event.data;
147003
- const deviceId = typeof data.deviceId === "number" ? data.deviceId : null;
147004
- if (deviceId === null) return;
148712
+ const parsed = sourceRefreshPayload.safeParse(event.data);
148713
+ if (!parsed.success) return;
148714
+ const data = parsed.data;
148715
+ const deviceId = data.deviceId;
148716
+ if (data.reason === "source-silent") this.ctx.logger.debug("stream source refresh reason source-silent is advisory — the library heals a silent source itself", {
148717
+ tags: { deviceId },
148718
+ meta: { camStreamId: data.camStreamId ?? null }
148719
+ });
147005
148720
  this.refreshDeviceStreams(deviceId, data.camStreamId).catch((err) => {
147006
148721
  this.ctx.logger.warn("refresh of Reolink stream failed", {
147007
148722
  tags: { deviceId },
@@ -147450,6 +149165,7 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
147450
149165
  username: inputs.username,
147451
149166
  password: inputs.password,
147452
149167
  ...inputs.uid ? { uid: inputs.uid } : {},
149168
+ ...inputs.udpDiscoveryMethod ? { udpDiscoveryMethod: inputs.udpDiscoveryMethod } : {},
147453
149169
  mode: inputs.transport
147454
149170
  });
147455
149171
  } else this.ctx.logger.info("autodetect cache hit — reusing api", {
@@ -147598,6 +149314,7 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
147598
149314
  username: inputs.username,
147599
149315
  password: inputs.password,
147600
149316
  ...inputs.uid ? { uid: inputs.uid } : {},
149317
+ ...inputs.udpDiscoveryMethod ? { udpDiscoveryMethod: inputs.udpDiscoveryMethod } : {},
147601
149318
  mode: inputs.transport,
147602
149319
  logger: buildAutodetectLibLogger(probeLogger)
147603
149320
  });