@camstack/addon-provider-reolink 1.2.260 → 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
  /**
@@ -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,14 @@ 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;
109026
110001
  /**
109027
110002
  * Every switch migration this process added to a declaration so far, by id. The engine replaces
109028
110003
  * an owner's catalogue on each declare, so a later one (a late kind) carries them all: dropping
@@ -109086,34 +110061,105 @@ var BaseAddon = class {
109086
110061
  */
109087
110062
  async moveLateInstanceKinds() {
109088
110063
  const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
109089
- 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
+ }
109090
110074
  try {
109091
110075
  const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
109092
- await this.runBound(this.lastDeclared, { only });
110076
+ await this.runBound([], { only });
109093
110077
  } catch (err) {
109094
110078
  if (err instanceof AddonMigrationsBlockedError) throw err;
109095
110079
  this.ctx.logger.error("the late instance switch move failed", { meta: { error: errMsg$3(err) } });
109096
110080
  }
109097
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
+ }
109098
110119
  async runBound(declared, options) {
109099
- this.lastDeclared = declared;
110120
+ this.watchAppliedMigrations();
110121
+ const priorIds = new Set([...this.declaredAll.keys(), ...this.switchDeclared.keys()]);
109100
110122
  const added = this.registrySwitchBound();
109101
110123
  for (const m of added) this.switchDeclared.set(m.meta.id, m);
109102
- const migrations = [...declared, ...[...this.switchDeclared.values()].filter((m) => !declared.some((d) => d.meta.id === m.meta.id))];
109103
- const widened = options?.only === void 0 || added.length === 0 ? options : {
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 ?? {} : {
109104
110128
  ...options,
109105
- only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
109106
- };
109107
- const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
109108
- ...widened,
109109
- 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
109110
110143
  };
109111
110144
  const api = this.ctx.api.migrations;
109112
- const report = await runAddonMigrations({
110145
+ const host = {
109113
110146
  declareOwner: (input) => api.declareOwner.mutate(input),
109114
110147
  startMigration: (input) => api.startMigration.mutate(input),
109115
110148
  finishMigration: (input) => api.finishMigration.mutate(input)
109116
- }, 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]);
109117
110163
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
109118
110164
  await this.hydrateSwitches();
109119
110165
  await this.adoptUnrowed();
@@ -112466,6 +113512,16 @@ var BatteryStatusSchema = /* @__PURE__ */ object({
112466
113512
  */
112467
113513
  lastFullRefreshAt: /* @__PURE__ */ number().optional(),
112468
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
+ /**
112469
113525
  * True when the source is a BINARY low-battery indicator (HA
112470
113526
  * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
112471
113527
  * charge level — `level` is then a coarse stand-in (100 = normal,
@@ -114170,7 +115226,13 @@ listFaultTypes: /* @__PURE__ */ method(ListFaultTypesInputSchema, FaultTypesSche
114170
115226
  status: {
114171
115227
  schema: ErrorStatusSchema,
114172
115228
  kind: "push",
114173
- 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
+ } }
114174
115236
  },
114175
115237
  runtimeState: ErrorStatusSchema,
114176
115238
  /**
@@ -129832,6 +130894,24 @@ var IntercomFailureReport = class {
129832
130894
  /** The process-wide instance every camera in this addon notes into. */
129833
130895
  var intercomFailureReport = new IntercomFailureReport();
129834
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
129835
130915
  //#region src/baichuan-webhook-shared.ts
129836
130916
  /** The data-plane prefix this addon serves the camera push on: `/addon/<addonId>/webhook/<stableId>`. */
129837
130917
  var BAICHUAN_WEBHOOK_PREFIX = "webhook";
@@ -129985,6 +131065,12 @@ var BATTERY_REFRESH_MINUTES_KEY = "batteryRefreshMinutes";
129985
131065
  var BATTERY_REFRESH_TICK_MS = 6e4;
129986
131066
  /** The least time between two attempts in one window. */
129987
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;
129988
131074
  /** The one refresh step whose failure does not hold the window open. */
129989
131075
  var SOFT_FAILURE_STEP = "snapshot";
129990
131076
  var MAX_WAKE_LEAD_MS = 5 * 6e4;
@@ -130034,12 +131120,48 @@ function decideBatteryRefresh(input) {
130034
131120
  };
130035
131121
  return { kind: "wake-then-refresh" };
130036
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
+ }
130037
131158
  var BatteryHourlyRefresh = class {
130038
131159
  deps;
130039
131160
  inFlight = null;
130040
131161
  attemptWindow = Number.NEGATIVE_INFINITY;
130041
131162
  attempts = 0;
130042
131163
  lastAttemptAt;
131164
+ hydrated = false;
130043
131165
  constructor(deps) {
130044
131166
  this.deps = deps;
130045
131167
  }
@@ -130064,6 +131186,7 @@ var BatteryHourlyRefresh = class {
130064
131186
  const intervalMs = this.deps.intervalMs();
130065
131187
  const offsetMs = intervalMs > 0 ? staggerOffsetMs(this.deps.deviceId, intervalMs) : 0;
130066
131188
  const window = intervalMs > 0 ? windowIndex(nowMs, intervalMs, offsetMs) : 0;
131189
+ this.hydrateAttempts();
130067
131190
  if (window !== this.attemptWindow) {
130068
131191
  this.attemptWindow = window;
130069
131192
  this.attempts = 0;
@@ -130082,14 +131205,67 @@ var BatteryHourlyRefresh = class {
130082
131205
  this.logSkip(decision.reason, trigger);
130083
131206
  return false;
130084
131207
  }
131208
+ if (this.shouldDeferForStream()) {
131209
+ this.noteStreamDeferred(trigger);
131210
+ return false;
131211
+ }
131212
+ if (this.deps.isStreaming?.() === true) this.logDeferralBoundReached(trigger);
130085
131213
  this.attempts += 1;
130086
131214
  this.lastAttemptAt = nowMs;
131215
+ this.deps.attemptLedger?.write({
131216
+ window,
131217
+ attempts: this.attempts,
131218
+ lastAttemptAt: nowMs
131219
+ });
130087
131220
  const run = this.run(decision.kind, trigger).finally(() => {
130088
131221
  this.inFlight = null;
130089
131222
  });
130090
131223
  this.inFlight = run;
130091
131224
  return run;
130092
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
+ }
130093
131269
  async run(kind, trigger) {
130094
131270
  const { logger, deviceId } = this.deps;
130095
131271
  try {
@@ -132260,6 +133436,7 @@ async function connectReolinkHub(connection) {
132260
133436
  transport: connection.transport,
132261
133437
  ...connection.uid ? { uid: connection.uid } : {}
132262
133438
  });
133439
+ api.setGeneralSessionRecycling({ guard: () => true });
132263
133440
  await api.login();
132264
133441
  return api;
132265
133442
  }
@@ -132365,14 +133542,14 @@ function isSummarySourced(source) {
132365
133542
  function decideSleepCommit(input) {
132366
133543
  const { current, next, source, lastFirstHandCommitAt, nowMs, videoFlowing, wired } = input;
132367
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
+ };
132368
133551
  if (next === true && isSecondHand(source)) {
132369
133552
  const sinceMs = nowMs - lastFirstHandCommitAt;
132370
- if (wired) return {
132371
- kind: "refused",
132372
- reason: "wired",
132373
- windowMs: 0,
132374
- sinceLastChangeMs: sinceMs
132375
- };
132376
133553
  if (videoFlowing) return {
132377
133554
  kind: "refused",
132378
133555
  reason: "video-flowing",
@@ -132404,6 +133581,49 @@ function decideSleepCommit(input) {
132404
133581
  };
132405
133582
  }
132406
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
132407
133627
  //#region src/session-limit.ts
132408
133628
  /**
132409
133629
  * How long the broker lets a Home Hub child's session run before it re-dials on
@@ -132417,15 +133637,25 @@ function decideSleepCommit(input) {
132417
133637
  */
132418
133638
  var HOME_HUB_SESSION_LIMIT_MS = 27 * 6e4;
132419
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
+ /**
132420
133648
  * Stamp the descriptors with the session limit the broker acts on. Only a
132421
- * battery child of a hub gets one: a standalone camera has no such cut, and
132422
- * 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.
132423
133652
  */
132424
133653
  function withSessionLimit(descriptors, input) {
132425
- 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;
132426
133656
  return descriptors.map((d) => ({
132427
133657
  ...d,
132428
- maxSessionMs: HOME_HUB_SESSION_LIMIT_MS
133658
+ maxSessionMs
132429
133659
  }));
132430
133660
  }
132431
133661
  //#endregion
@@ -132651,6 +133881,15 @@ var reolinkAccessoryBaseSchema = object({
132651
133881
  channel: number().int().nonnegative().default(0),
132652
133882
  kind: string()
132653
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
+ }
132654
133893
  //#endregion
132655
133894
  //#region src/accessories/floodlight.ts
132656
133895
  /**
@@ -132700,13 +133939,6 @@ var FloodlightAccessory = class extends BaseDevice {
132700
133939
  * /setMotionTrigger. Read by the parent's align loop via the
132701
133940
  * `ReolinkAccessoryRef.isInCooldown` impl below. */
132702
133941
  lastSetAtMs = 0;
132703
- /** Becomes `true` once both `refreshLightFromFirmware` and
132704
- * `refreshMotionTriggerFromFirmware` have completed at least one
132705
- * successful round-trip. Used by `onProbe` to decide whether the
132706
- * boot-time sleep-gate should force a wake (no cached state) or
132707
- * skip (already-have-state path). Mirrors the Reolink mobile app's
132708
- * one-shot wake-and-fetch on launch. */
132709
- hasFetchedFromFirmware = false;
132710
133942
  constructor(ctx, parent) {
132711
133943
  super(ctx, floodlightAccessorySchema, {
132712
133944
  type: DeviceType.Light,
@@ -132766,7 +133998,6 @@ var FloodlightAccessory = class extends BaseDevice {
132766
133998
  level: brightness,
132767
133999
  lastChangedAt: ts
132768
134000
  });
132769
- this.hasFetchedFromFirmware = true;
132770
134001
  } catch (err) {
132771
134002
  this.ctx.logger.warn("floodlight refresh FAILED — slice stays at cold-start seed", {
132772
134003
  tags: { deviceId: this.id },
@@ -132778,46 +134009,29 @@ var FloodlightAccessory = class extends BaseDevice {
132778
134009
  }
132779
134010
  }
132780
134011
  /**
132781
- * Kernel-driven probe (Phase 4). Runs on every device construction
132782
- * + addon restart. Pulls the actual on/off + brightness +
132783
- * motion-trigger state from the camera so the slices reflect
132784
- * firmware truth instead of the conservative cold-start seeds
132785
- * written in `registerSwitchCap` / `registerBrightnessCap` /
132786
- * `registerMotionTriggerCap`.
132787
- *
132788
- * Sleeping battery cam:
132789
- * 1. **First-time probe (no cached state yet)** — force a one-shot
132790
- * wake + fetch so the operator sees a populated UI at launch.
132791
- * Mirrors the Reolink mobile app: at app launch it wakes the
132792
- * cam once to fetch initial state. Without this, an aggressive
132793
- * sleep timeout (~14s) can return the cam to sleep before the
132794
- * kernel finishes its initial probe pass — the retry chain
132795
- * exhausts and the slices never populate.
132796
- * 2. **Subsequent probes (slices already populated)** — skip. A
132797
- * poll on a sleeping camera returns 400 and drains the
132798
- * battery. The parent's `alignAuxDevicesState('wake')` runs
132799
- * on the next wake transition (simpleEvent push or sleep-poll
132800
- * 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.
132801
134018
  */
132802
134019
  async onProbe() {
132803
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
132804
- if (this.hasFetchedFromFirmware) {
132805
- this.ctx.logger.debug("floodlight onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
132806
- return;
132807
- }
132808
- this.ctx.logger.info("floodlight onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
132809
- try {
132810
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
132811
- await sleep(1e3);
132812
- } catch (err) {
132813
- this.ctx.logger.warn("floodlight wake before initial probe failed — proceeding anyway", {
132814
- tags: { deviceId: this.id },
132815
- meta: { error: err instanceof Error ? err.message : String(err) }
132816
- });
132817
- }
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;
132818
134023
  }
132819
134024
  await Promise.all([this.refreshLightFromFirmware(), this.refreshMotionTriggerFromFirmware()]);
132820
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
+ }
132821
134035
  /** Refresh motion-trigger from firmware and write the slice. Also
132822
134036
  * mirrors the camera-current `duration` + `detectType` into config
132823
134037
  * so the Settings form shows firmware truth instead of stale
@@ -132839,7 +134053,6 @@ var FloodlightAccessory = class extends BaseDevice {
132839
134053
  lastChangedAt,
132840
134054
  lastFetchedAt: Date.now()
132841
134055
  });
132842
- this.hasFetchedFromFirmware = true;
132843
134056
  const patch = {};
132844
134057
  if (typeof result?.duration === "number" && result.duration > 0) patch["motionLightDurationS"] = result.duration;
132845
134058
  if (typeof result?.detectType === "string") {
@@ -132935,7 +134148,7 @@ var FloodlightAccessory = class extends BaseDevice {
132935
134148
  runtimeState: this.runtimeState,
132936
134149
  cap: motionTriggerCapability,
132937
134150
  ownDeviceId: this.id,
132938
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134151
+ refresh: () => this.revalidateMotionTrigger(),
132939
134152
  staleMs: STALE_MS$1,
132940
134153
  empty: () => ({
132941
134154
  enabled: false,
@@ -133086,12 +134299,6 @@ var PirAccessory = class extends BaseDevice {
133086
134299
  /** Nothing reported: the kernel derives this device's features from its bound caps (#459). */
133087
134300
  features = [];
133088
134301
  lastSetAtMs = 0;
133089
- /** Becomes `true` after the first successful `refreshFromFirmware`
133090
- * round-trip. Used by `onProbe` to decide whether the boot-time
133091
- * sleep-gate should force a wake (no cached state) or skip
133092
- * (already-have-state path). Mirrors the Reolink mobile app's
133093
- * one-shot wake-and-fetch on launch. */
133094
- hasFetchedFromFirmware = false;
133095
134302
  constructor(ctx, parent) {
133096
134303
  super(ctx, pirAccessorySchema, {
133097
134304
  type: DeviceType.Switch,
@@ -133167,7 +134374,6 @@ var PirAccessory = class extends BaseDevice {
133167
134374
  }
133168
134375
  });
133169
134376
  this.refreshSwitchFromExternal(state);
133170
- this.hasFetchedFromFirmware = true;
133171
134377
  } catch (err) {
133172
134378
  this.ctx.logger.warn("pir refresh FAILED — slice stays at cold-start seed", {
133173
134379
  tags: { deviceId: this.id },
@@ -133179,45 +134385,17 @@ var PirAccessory = class extends BaseDevice {
133179
134385
  }
133180
134386
  }
133181
134387
  /**
133182
- * Kernel-driven probe — runs at device construction (addon boot,
133183
- * device add). For battery cams currently asleep we have two
133184
- * cases:
133185
- *
133186
- * 1. **First-time probe (no cached state yet)** — force a one-shot
133187
- * wake + fetch. Mirrors the Reolink mobile app's launch
133188
- * behaviour: the app wakes the cam once at startup so the
133189
- * operator sees a populated UI. Without this, an aggressive
133190
- * sleep timeout (~14s after boot on Argus / battery doorbell
133191
- * firmwares) can put the cam back to sleep before the
133192
- * kernel's initial probe pass completes — the slice never
133193
- * gets populated, the kernel's retry chain exhausts after 5
133194
- * attempts, and the operator sees an empty PIR switch state
133195
- * until they manually wake the cam.
133196
- * 2. **Subsequent probes (slice already populated)** — skip the
133197
- * fetch. A Baichuan poll on a sleeping camera returns 400,
133198
- * drains the battery, and would clobber the cached value
133199
- * anyway. The parent's `alignAuxDevicesState('wake')` path
133200
- * (simpleEvent `awake` push or sleep-poll backstop)
133201
- * refreshes us when the cam wakes naturally.
133202
- *
133203
- * 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.
133204
134394
  */
133205
134395
  async onProbe() {
133206
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
133207
- if (this.hasFetchedFromFirmware) {
133208
- this.ctx.logger.debug("pir onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
133209
- return;
133210
- }
133211
- this.ctx.logger.info("pir onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
133212
- try {
133213
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
133214
- await sleep(1e3);
133215
- } catch (err) {
133216
- this.ctx.logger.warn("pir wake before initial probe failed — proceeding anyway", {
133217
- tags: { deviceId: this.id },
133218
- meta: { error: err instanceof Error ? err.message : String(err) }
133219
- });
133220
- }
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;
133221
134399
  }
133222
134400
  await this.refreshFromFirmware();
133223
134401
  }
@@ -133445,12 +134623,6 @@ var SirenAccessory = class extends BaseDevice {
133445
134623
  lastSetAtMs = 0;
133446
134624
  /** Clears the `siren` slice when a timed activation runs out. */
133447
134625
  sirenTimer = null;
133448
- /** Becomes `true` after the first successful
133449
- * `refreshMotionTriggerFromFirmware` round-trip. Used by `onProbe`
133450
- * to decide whether the boot-time sleep-gate should force a wake
133451
- * (no cached state) or skip (already-have-state path). Mirrors the
133452
- * Reolink mobile app's one-shot wake-and-fetch on launch. */
133453
- hasFetchedFromFirmware = false;
133454
134626
  constructor(ctx, parent) {
133455
134627
  super(ctx, sirenAccessorySchema, {
133456
134628
  type: DeviceType.Siren,
@@ -133487,42 +134659,26 @@ var SirenAccessory = class extends BaseDevice {
133487
134659
  };
133488
134660
  }
133489
134661
  /**
133490
- * Kernel-driven probe (Phase 4). Runs on every device construction
133491
- * + addon restart. Pulls the actual motion-trigger enable state
133492
- * from the camera so the slice reflects firmware truth. The switch
133493
- * (manual fire) cap is intentionally NOT refreshed — Reolink's
133494
- * `getSiren` returns OFF as soon as the audio task ends.
133495
- *
133496
- * Sleeping battery cam:
133497
- * 1. **First-time probe (no cached state yet)** — force a one-shot
133498
- * wake + fetch so the operator sees a populated UI at launch.
133499
- * Mirrors the Reolink mobile app: at app launch it wakes the
133500
- * cam once to fetch initial state. Without this, an aggressive
133501
- * sleep timeout (~14s) can return the cam to sleep before the
133502
- * kernel finishes its initial probe pass — the retry chain
133503
- * exhausts and the slice never populates.
133504
- * 2. **Subsequent probes (slice already populated)** — skip. A
133505
- * poll on a sleeping camera returns 400 and drains the
133506
- * battery. The parent's `alignAuxDevicesState('wake')` path
133507
- * (simpleEvent `awake` push or sleep-poll backstop) refreshes
133508
- * 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.
133509
134668
  */
133510
134669
  async onProbe() {
133511
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
133512
- if (this.hasFetchedFromFirmware) {
133513
- this.ctx.logger.debug("siren onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
133514
- return;
133515
- }
133516
- this.ctx.logger.info("siren onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
133517
- try {
133518
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
133519
- await sleep(1e3);
133520
- } catch (err) {
133521
- this.ctx.logger.warn("siren wake before initial probe failed — proceeding anyway", {
133522
- tags: { deviceId: this.id },
133523
- meta: { error: err instanceof Error ? err.message : String(err) }
133524
- });
133525
- }
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;
133526
134682
  }
133527
134683
  await this.refreshMotionTriggerFromFirmware();
133528
134684
  }
@@ -133538,7 +134694,6 @@ var SirenAccessory = class extends BaseDevice {
133538
134694
  lastChangedAt,
133539
134695
  lastFetchedAt: Date.now()
133540
134696
  });
133541
- this.hasFetchedFromFirmware = true;
133542
134697
  const items = audioTask?.typeScheduleList?.item ?? [];
133543
134698
  if (items.length > 0) {
133544
134699
  const recovered = recoverSirenDetectTypeFromItems(items);
@@ -133767,7 +134922,7 @@ var SirenAccessory = class extends BaseDevice {
133767
134922
  runtimeState: this.runtimeState,
133768
134923
  cap: motionTriggerCapability,
133769
134924
  ownDeviceId: this.id,
133770
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134925
+ refresh: () => this.revalidateMotionTrigger(),
133771
134926
  staleMs: STALE_MS,
133772
134927
  empty: () => ({
133773
134928
  enabled: false,
@@ -134091,17 +135246,41 @@ function effectiveProbeFlags(sliceProbed, sliceFlags, deviceCache) {
134091
135246
  ...resolveAccessoryProbeFlags(false, {}, deviceCache)
134092
135247
  };
134093
135248
  }
135249
+ function abilityReadQuality(debug) {
135250
+ return debug?.abilitiesAvailable === true && debug.supportAvailable === true ? "full" : "partial";
135251
+ }
134094
135252
  /**
134095
- * The typed answer for `getAccessoryChildren()`. A probe that completed THIS
134096
- * session is a definitive read (`complete`) even while the parent is asleep
134097
- * or offline, so the kernel's reconcile can retire a child whose flag is now
134098
- * false (it still needs a second agreeing probe, D49). Flags restored from
134099
- * `deviceCache` alone, or no probe at all, are `unknown`: they spawn but
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
+ }
135271
+ /**
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
134100
135278
  * never prune. A legacy bare array was `unknown` whenever the parent was
134101
135279
  * offline, which is how a ghost Floodlight outlived `hasFloodlight:false`.
134102
135280
  */
134103
- function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs) {
135281
+ function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs, fullReadThisSession) {
134104
135282
  if (!sliceProbed) return accessoryChildrenUnknown("no probe completed this session", specs);
135283
+ if (!fullReadThisSession) return accessoryChildrenUnknown("no full ability read this session", specs);
134105
135284
  if (!ACCESSORY_FLAGS.some(([flag]) => typeof sliceFlags[flag] === "boolean")) return accessoryChildrenUnknown("probe carried no ability flags", specs);
134106
135285
  return {
134107
135286
  kind: "complete",
@@ -135425,8 +136604,17 @@ function createKeepAwakeLoop(deps) {
135425
136604
  let handle = null;
135426
136605
  let failing = false;
135427
136606
  const tick = () => {
136607
+ if (deps.videoFlowing?.() === true) {
136608
+ try {
136609
+ deps.onSkip?.();
136610
+ } catch {}
136611
+ return;
136612
+ }
135428
136613
  deps.wake().then(() => {
135429
136614
  failing = false;
136615
+ try {
136616
+ deps.onSuccess?.();
136617
+ } catch {}
135430
136618
  }).catch((err) => {
135431
136619
  const first = !failing;
135432
136620
  failing = true;
@@ -136341,6 +137529,10 @@ function coerceNumber(value) {
136341
137529
  }
136342
137530
  return null;
136343
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;
136344
137536
  /**
136345
137537
  * Baichuan's native PTZ speed scale is 1..63; `runPtz` maps the cap's
136346
137538
  * normalized 0..1 onto it. Named because the autotrack loop has to know the
@@ -136513,6 +137705,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136513
137705
  }
136514
137706
  /** Lazy-connected Baichuan API. Spans the lifetime of every active stream. */
136515
137707
  api = null;
137708
+ /** Why the previous Baichuan session ended; named on the next login's log line. */
137709
+ lastSessionDropReason = null;
137710
+ loginCount = 0;
136516
137711
  /**
136517
137712
  * Stable bound handler for `api.onSimpleEvent` — created ONCE in
136518
137713
  * the class so every `onSimpleEvent` / `offSimpleEvent` call uses
@@ -136612,16 +137807,120 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136612
137807
  tags: { deviceId: this.id },
136613
137808
  meta: { activeStreams }
136614
137809
  }),
137810
+ onSuccess: () => this.noteKeepAwakeResult(true, null),
137811
+ videoFlowing: () => Date.now() - this.lastVideoFlowAt < KEEP_AWAKE_INTERVAL_MS,
137812
+ onSkip: () => this.noteKeepAwakeSkipped(),
136615
137813
  onFailure: (err, first) => {
137814
+ const error = err instanceof Error ? err.message : String(err);
136616
137815
  (first ? this.ctx.logger.info.bind(this.ctx.logger) : this.ctx.logger.debug.bind(this.ctx.logger))("keep-awake: wake failed", {
136617
137816
  tags: { deviceId: this.id },
136618
- meta: { error: err instanceof Error ? err.message : String(err) }
137817
+ meta: { error }
136619
137818
  });
137819
+ this.noteKeepAwakeResult(false, error);
136620
137820
  }
136621
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
+ }
136622
137911
  syncKeepAwake() {
136623
137912
  this.keepAwake.sync(this.active.size);
136624
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
+ }
136625
137924
  /** Login lock — concurrent demand events must not race the login flow. */
136626
137925
  loginPromise = null;
136627
137926
  /**
@@ -136710,6 +138009,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136710
138009
  batteryUpdateTimer = null;
136711
138010
  /** Set by `removeDevice`: nothing may re-arm a timer on a removed camera. */
136712
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;
136713
138019
  /** Single-flight gate so two interval fires can't overlap. */
136714
138020
  /** Aux accessory references registered by spawned children
136715
138021
  * (siren / floodlight / pir). The parent's centralised align
@@ -137349,9 +138655,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137349
138655
  } catch (err) {
137350
138656
  this.ctx.logger.debug("reolink deviceCache snapshot persist failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137351
138657
  }
137352
- if (slices === void 0 && this.isBattery && this.isEmailPushEligible) await this.refreshCameraEmailConfig().catch((err) => {
137353
- this.ctx.logger.debug("reolink email config probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137354
- });
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
+ }
137355
138670
  }
137356
138671
  /**
137357
138672
  * Admin-only raw-read debug surface (D346): return the library's response
@@ -137465,7 +138780,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137465
138780
  * leave the catalog stale rather than stamping it fresh.
137466
138781
  */
137467
138782
  async wakeForClipCatalogRefresh() {
137468
- 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`);
137469
138784
  }
137470
138785
  /**
137471
138786
  * Wake this camera because the OPERATOR asked for one of its clips — a
@@ -137475,7 +138790,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137475
138790
  * so the service can refuse `wake-timeout` by name.
137476
138791
  */
137477
138792
  async wakeForClipRead(timeoutMs) {
137478
- return this.wakeIfSleeping(timeoutMs);
138793
+ return this.wakeIfSleeping("clip-read", timeoutMs);
137479
138794
  }
137480
138795
  clipTimeZoneWarned = { done: false };
137481
138796
  getClipDeviceRef() {
@@ -137529,7 +138844,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137529
138844
  if (kinds.includes(AccessoryKind.Siren)) push(AccessoryKind.Siren, DeviceType.Siren, ACCESSORY_LABEL[AccessoryKind.Siren]);
137530
138845
  if (kinds.includes(AccessoryKind.Floodlight)) push(AccessoryKind.Floodlight, DeviceType.Light, ACCESSORY_LABEL[AccessoryKind.Floodlight]);
137531
138846
  if (kinds.includes(AccessoryKind.PirSensor)) push(AccessoryKind.PirSensor, DeviceType.Switch, ACCESSORY_LABEL[AccessoryKind.PirSensor]);
137532
- return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out);
138847
+ return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out, this.fullAbilityReadThisSession === true);
137533
138848
  }
137534
138849
  /**
137535
138850
  * Resolver injected by the provider (`setEmailPushParamsResolver`) so
@@ -137565,7 +138880,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137565
138880
  * camera. No-op for non-battery or already-awake cams. Best-effort:
137566
138881
  * returns whether the camera is (now) reachable/awake.
137567
138882
  */
137568
- async wakeIfSleeping(timeoutMs = 15e3) {
138883
+ async wakeIfSleeping(caller, timeoutMs = 15e3) {
137569
138884
  if (!this.isBattery || !this.sleeping) return true;
137570
138885
  let api;
137571
138886
  try {
@@ -137576,7 +138891,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137576
138891
  this.markWakeIssued();
137577
138892
  this.ctx.logger.info("proactive action: waking sleeping battery cam", {
137578
138893
  tags: { deviceId: this.id },
137579
- meta: { timeoutMs }
138894
+ meta: {
138895
+ timeoutMs,
138896
+ caller
138897
+ }
137580
138898
  });
137581
138899
  this.ctx.eventBus.emit(createEvent(EventCategory.BatteryOnWakeStarted, this.eventSource(), { deviceId: this.id }));
137582
138900
  const channel = this.getChannel();
@@ -137596,7 +138914,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137596
138914
  } catch (err) {
137597
138915
  this.ctx.logger.warn("proactive action: wake did not complete in time", {
137598
138916
  tags: { deviceId: this.id },
137599
- meta: { error: err instanceof Error ? err.message : String(err) }
138917
+ meta: {
138918
+ caller,
138919
+ error: err instanceof Error ? err.message : String(err)
138920
+ }
137600
138921
  });
137601
138922
  return false;
137602
138923
  }
@@ -137645,7 +138966,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137645
138966
  "vehicle"
137646
138967
  ];
137647
138968
  const attachmentType = this.config.get("emailPushAttachment") ?? "picture";
137648
- await this.wakeIfSleeping();
138969
+ await this.wakeIfSleeping("auto-configure-email-push");
137649
138970
  const api = await this.ensureApi();
137650
138971
  this.ctx.logger.info("email-push: auto-configuring camera", {
137651
138972
  tags: { deviceId: this.id },
@@ -137695,7 +139016,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137695
139016
  if (!this.baichuanWebhookParamsResolver) throw userError("reolink.webhook-not-wired", void 0, "HaCfg Webhook Server is not wired — restart the Reolink addon");
137696
139017
  const params = await this.baichuanWebhookParamsResolver();
137697
139018
  if (!params) throw new Error("The HaCfg webhook cannot be armed for this camera (it is not a standalone battery camera).");
137698
- await this.wakeIfSleeping();
139019
+ await this.wakeIfSleeping("auto-configure-baichuan-webhook");
137699
139020
  const api = await this.ensureApi();
137700
139021
  const supported = await api.probeBaichuanWebhookSupport();
137701
139022
  this.baichuanWebhookSupportedCached = supported;
@@ -137794,7 +139115,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137794
139115
  * Push tab read.
137795
139116
  */
137796
139117
  async refreshCameraEmailConfig() {
137797
- await this.wakeIfSleeping();
139118
+ await this.wakeIfSleeping("refresh-camera-email-config");
137798
139119
  const api = await this.ensureApi();
137799
139120
  const channel = this.getChannel();
137800
139121
  const [email, task] = await Promise.all([api.getEmail(), api.getEmailTask(channel).catch(() => null)]);
@@ -137911,7 +139232,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137911
139232
  await this.autoConfigureBaichuanWebhook();
137912
139233
  });
137913
139234
  this.registerDeviceAction("refresh-settings", deviceCustomAction(unknown(), RefreshSettingsResultSchema, { kind: "mutation" }), async () => {
137914
- const awake = await this.wakeIfSleeping();
139235
+ const awake = await this.wakeIfSleeping("operator-rehydrate");
137915
139236
  const [snapshot, warm] = await Promise.allSettled([this.refreshParentSettingsSnapshot(void 0, "operator"), this.warmCapSlicesOnWake({ force: true })]);
137916
139237
  const warmed = warm.status === "fulfilled" ? warm.value.warmed : 0;
137917
139238
  const capsTotal = this.capWarmers.size;
@@ -137941,6 +139262,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137941
139262
  this.registerRecordingOnboardCap();
137942
139263
  this.registerStreamCatalogProvider();
137943
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() {
137944
139271
  const cache = this.config.get("deviceCache");
137945
139272
  if (cache?.deviceType === "battery-cam" || cache?.hasBattery === true) {
137946
139273
  this.isBattery = true;
@@ -138210,6 +139537,26 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138210
139537
  return false;
138211
139538
  }
138212
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
+ }
138213
139560
  /**
138214
139561
  * THE single writer of the `battery.sleeping` slice.
138215
139562
  *
@@ -138239,7 +139586,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138239
139586
  lastFirstHandCommitAt: this.sleepStateChangedAt,
138240
139587
  nowMs: Date.now(),
138241
139588
  videoFlowing: Date.now() - this.lastVideoFlowAt < VIDEO_FLOW_FRESH_MS,
138242
- wired: this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter"
139589
+ wired: this.isOnAdapterPower()
138243
139590
  });
138244
139591
  if (decision.kind === "unchanged") return false;
138245
139592
  if (decision.kind === "refused") {
@@ -138362,10 +139709,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138362
139709
  const now = Date.now();
138363
139710
  const quantised = now - now % ReolinkCamera.CONTACT_WRITE_QUANTUM_MS;
138364
139711
  const previousContact = this.state.battery.lastContactAt ?? 0;
138365
- this.setCapSlice(batteryCapability, {
139712
+ this.setCapSlice(batteryCapability, carryRefreshBookkeeping(this.state.battery, {
138366
139713
  ...mapped,
138367
139714
  lastContactAt: Math.max(previousContact, quantised)
138368
- });
139715
+ }));
138369
139716
  }
138370
139717
  /**
138371
139718
  * Hub-fed battery refresh for an adopted child. The parent's
@@ -138667,7 +140014,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138667
140014
  * changed.
138668
140015
  */
138669
140016
  async applyEmailConfigPatch(fields) {
138670
- await this.wakeIfSleeping();
140017
+ await this.wakeIfSleeping("apply-email-config-patch");
138671
140018
  const api = await this.ensureApi();
138672
140019
  const channel = this.getChannel();
138673
140020
  const patch = {};
@@ -141216,7 +142563,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141216
142563
  * session or touches the broker.
141217
142564
  */
141218
142565
  async buildStreamCatalog() {
141219
- if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(this.cachedStreamDescriptors);
142566
+ if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(stampCurrentFeatures(this.cachedStreamDescriptors, this.features));
141220
142567
  const restored = this.restoreStreamCatalogFromLedger();
141221
142568
  if (restored) return this.withLiveNativeSdp(restored);
141222
142569
  if (this.buildStreamCatalogInFlight) return this.withLiveNativeSdp(await this.buildStreamCatalogInFlight);
@@ -141500,7 +142847,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141500
142847
  const stored = this.runtimeState.getCapState(streamCatalogCapability.name);
141501
142848
  const descriptors = stored?.descriptors;
141502
142849
  if (!descriptors || descriptors.length === 0) return null;
141503
- this.cachedStreamDescriptors = [...descriptors];
142850
+ this.cachedStreamDescriptors = stampCurrentFeatures(descriptors, this.features);
141504
142851
  this.ctx.logger.info("stream catalog restored from the durable slice (no camera contact)", {
141505
142852
  tags: { deviceId: this.id },
141506
142853
  meta: {
@@ -141548,7 +142895,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141548
142895
  ...entry.codec !== void 0 ? { codec: entry.codec } : {},
141549
142896
  ...entry.metadata ? { metadata: entry.metadata } : {},
141550
142897
  ...entry.maxSessionMs !== void 0 ? { maxSessionMs: entry.maxSessionMs } : {},
141551
- deviceFeatures: entry.deviceFeatures ?? [...this.features],
142898
+ deviceFeatures: [...this.features],
141552
142899
  autoEligible: entry.autoEligible ?? true
141553
142900
  });
141554
142901
  this.publishedStreamIds.add(entry.camStreamId);
@@ -141585,6 +142932,31 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141585
142932
  * listening; if the lib idle-tore-down between calls we recreate.
141586
142933
  */
141587
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) {
141588
142960
  const parts = parseCamStreamId(camStreamId, this.getChannel());
141589
142961
  if (!parts || parts.kind !== "native") return;
141590
142962
  this.ctx.logger.info("broker requested rfc4571 source refresh — materializing on demand", {
@@ -141618,7 +142990,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141618
142990
  deviceId: this.id,
141619
142991
  camStreamId
141620
142992
  },
141621
- meta: { url: `tcp://${server.host}:${server.port}` }
142993
+ meta: {
142994
+ url: `tcp://${server.host}:${server.port}`,
142995
+ republishCause: "broker-source-refresh (materializeStreamSocket)"
142996
+ }
141622
142997
  });
141623
142998
  }
141624
142999
  async removeDevice() {
@@ -141703,7 +143078,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141703
143078
  requireAuth: true,
141704
143079
  deviceId: this.stableId,
141705
143080
  requestedId: camStreamId,
141706
- logger: this.libLoggerAdapter()
143081
+ logger: this.libLoggerAdapter(),
143082
+ resilience: { recoveryGuard: () => this.streamRecoveryVerdict() }
141707
143083
  });
141708
143084
  } catch (err) {
141709
143085
  this.ctx.logger.error("rfc4571: createRfc4571TcpServer failed", {
@@ -141970,17 +143346,21 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141970
143346
  logger: this.ctx.logger,
141971
143347
  now: () => Date.now(),
141972
143348
  isAwake: () => !this.sleeping,
143349
+ isStreaming: () => this.hasActiveStream(),
141973
143350
  intervalMs: () => resolveBatteryRefreshIntervalMs(this.config.get("batteryRefreshMinutes")),
141974
143351
  lastFullRefreshAt: () => this.state.battery.lastFullRefreshAt,
141975
143352
  wake: async () => {
141976
143353
  if (!this.canProactivelyWake("scheduled-refresh")) return false;
141977
143354
  this.markWakeIssued();
141978
- return this.wakeIfSleeping();
143355
+ return this.wakeIfSleeping("scheduled-refresh");
141979
143356
  },
141980
143357
  refreshAll: () => this.refreshEverythingNow(),
141981
143358
  stamp: (at) => {
141982
143359
  this.state.battery.lastFullRefreshAt = at;
141983
- }
143360
+ },
143361
+ attemptLedger: attemptLedgerOverSlice(() => this.state.battery, (fields) => {
143362
+ this.runtimeState.patchCapState(batteryCapability.name, fields);
143363
+ })
141984
143364
  });
141985
143365
  return this.batteryRefresh;
141986
143366
  }
@@ -142174,13 +143554,16 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
142174
143554
  });
142175
143555
  }
142176
143556
  else await this.reprobeAccessoriesIfStale(reason);
142177
- 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) {
142178
143561
  await this.warmCapSlicesOnWake();
142179
143562
  await this.warmSnapshotOnWake();
142180
143563
  await this.alignAuxDevicesState("wake");
142181
143564
  await this.refreshParentSettingsSnapshot();
142182
143565
  }
142183
- await this.refreshClipCatalogOnWake();
143566
+ if (!streamingDefer) await this.refreshClipCatalogOnWake();
142184
143567
  }
142185
143568
  static PING_INTERVAL_MS = 3e4;
142186
143569
  static PING_MAX_FAILURES = 3;
@@ -143591,7 +144974,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143591
144974
  async applySettingsPatch(patch) {
143592
144975
  if (this.isHubChild()) this.refuseHubChildPatch(patch);
143593
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;
143594
- 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 } });
143595
144978
  const emailFields = {
143596
144979
  emailSmtpServer,
143597
144980
  emailSmtpPort,
@@ -144051,14 +145434,15 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144051
145434
  * separate auth flow per accessory. `ReolinkAccessory` calls this
144052
145435
  * inside its `applyOn` / `fetchOn` to reach the camera firmware.
144053
145436
  */
144054
- /** Implements `ReolinkAccessoryHost.isBatteryCam` so spawned
144055
- * accessory children skip background polling on a sleeping
144056
- * battery cam (Baichuan polls on a sleeping camera return 400 +
144057
- * drain the battery). Reads from the runtime feature-probe slice
144058
- * populated during `onProbe()`; falls back to false when the probe
144059
- * 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). */
144060
145444
  isBatteryCam() {
144061
- return this.runtimeState.getCapState("feature-probe")?.flags?.["hasBattery"] === true;
145445
+ return this.isBattery;
144062
145446
  }
144063
145447
  /** Implements `ReolinkAccessoryHost.isSleeping`. Reads the canonical
144064
145448
  * source of truth — the `battery.sleeping` runtime-state slice — so
@@ -144073,7 +145457,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144073
145457
  /** Implements `ReolinkAccessoryHost.wakeForWrite`: an accessory's operator
144074
145458
  * write (PIR, ...) wakes a sleeping battery camera first. */
144075
145459
  wakeForWrite() {
144076
- return this.wakeIfSleeping();
145460
+ return this.wakeIfSleeping("write");
144077
145461
  }
144078
145462
  /** Implements `ReolinkAccessoryHost.probeAbility`: the effective probe flag
144079
145463
  * (live slice, else the persisted probe); `undefined` = never probed. */
@@ -144109,7 +145493,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144109
145493
  meta: {
144110
145494
  port,
144111
145495
  transport,
144112
- hasUid: Boolean(uid)
145496
+ hasUid: Boolean(uid),
145497
+ loginReason: this.lastSessionDropReason ?? "first-login",
145498
+ loginsSoFar: this.loginCount
144113
145499
  }
144114
145500
  });
144115
145501
  const debugOptions = this.getBaichuanDebugOptions();
@@ -144140,9 +145526,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144140
145526
  });
144141
145527
  this.pendingLoginApi = api;
144142
145528
  try {
144143
- await api.login();
145529
+ await loginWithin(() => api.login(), LOGIN_DEADLINE_MS, () => api.close({ reason: "login-deadline" }));
144144
145530
  } catch (err) {
144145
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
+ });
144146
145536
  this.pendingLoginApi = null;
144147
145537
  this.loginPromise = null;
144148
145538
  if (isConnectivityFailure(err)) this.noteUnreachable(err instanceof Error ? err.message : String(err));
@@ -144158,6 +145548,17 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144158
145548
  this.pendingLoginApi = null;
144159
145549
  this.api = api;
144160
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
+ }
144161
145562
  this.reconnectAttempts = 0;
144162
145563
  if (this.ownsReachability()) this.reachability.noteReachable();
144163
145564
  const persistedDeviceType = this.config.get("deviceCache")?.deviceType;
@@ -144174,6 +145575,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144174
145575
  this.isBattery = false;
144175
145576
  }
144176
145577
  else this.isBattery = false;
145578
+ if (!this.isBattery) api.setGeneralSessionRecycling({ guard: () => true });
144177
145579
  if (this.isBattery) {
144178
145580
  this.startSleepPoll();
144179
145581
  this.startBatteryUpdatePolling();
@@ -144411,11 +145813,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144411
145813
  let hasPirSensor;
144412
145814
  let hasAutotrack;
144413
145815
  let capabilitiesRead = false;
145816
+ let readQuality = "partial";
144414
145817
  try {
144415
145818
  channelCount = await api.getChannelCount();
144416
145819
  } catch {}
144417
145820
  try {
144418
- const { capabilities } = await api.getDeviceCapabilities(this.getChannel());
145821
+ const { capabilities, debug } = await api.getDeviceCapabilities(this.getChannel());
145822
+ readQuality = abilityReadQuality(debug);
144419
145823
  hasPtz = capabilities.hasPtz;
144420
145824
  hasIntercom = capabilities.hasIntercom;
144421
145825
  hasDoorbell = capabilities.isDoorbell;
@@ -144436,12 +145840,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144436
145840
  return;
144437
145841
  }
144438
145842
  const prev = this.runtimeState.getCapState("feature-probe");
144439
- const prevFlags = prev?.flags ?? {};
145843
+ const prevFlags = this.getProbeFlags();
144440
145844
  const inferredDeviceType = this.config.get("deviceCache")?.deviceType ?? (this.isBattery ? "battery-cam" : null);
144441
145845
  const persistedModel = this.config.get("deviceCache")?.model ?? null;
144442
- const flags = {
144443
- ...prevFlags,
144444
- hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery,
145846
+ const readFlags = {
144445
145847
  ...hasPtz !== void 0 ? { hasPtz } : {},
144446
145848
  ...hasIntercom !== void 0 ? { hasIntercom } : {},
144447
145849
  ...hasDoorbell !== void 0 ? { hasDoorbell } : {},
@@ -144450,6 +145852,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144450
145852
  ...hasPirSensor !== void 0 ? { hasPirSensor } : {},
144451
145853
  ...hasAutotrack !== void 0 ? { hasAutotrack } : {}
144452
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;
144453
145861
  const now = Date.now();
144454
145862
  const next = {
144455
145863
  flags,
@@ -144466,7 +145874,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144466
145874
  ...inferredDeviceType ? { deviceType: inferredDeviceType } : {},
144467
145875
  ...channelCount !== void 0 ? { channelCount } : {}
144468
145876
  };
144469
- await this.config.setAll({ deviceCache: capabilitiesRead ? withPersistedProbe(identity, flags, now) : identity });
145877
+ await this.config.setAll({ deviceCache: fullRead ? withPersistedProbe(identity, flags, now) : identity });
144470
145878
  } catch (err) {
144471
145879
  this.ctx.logger.debug("deviceCache identity persist failed (non-fatal)", {
144472
145880
  tags: { deviceId: this.id },
@@ -144483,7 +145891,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144483
145891
  meta: {
144484
145892
  flags,
144485
145893
  channelCount,
144486
- deviceType: inferredDeviceType
145894
+ deviceType: inferredDeviceType,
145895
+ abilityRead: capabilitiesRead ? readQuality : "failed",
145896
+ ...capabilitiesRead && readQuality === "partial" ? { partialRead: readFlags } : {}
144487
145897
  }
144488
145898
  });
144489
145899
  }
@@ -144544,6 +145954,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144544
145954
  async dropBaichuanSession(reason) {
144545
145955
  const current = this.api;
144546
145956
  this.api = null;
145957
+ if (current) this.lastSessionDropReason = reason;
144547
145958
  if (!current) return;
144548
145959
  try {
144549
145960
  await current.close({ reason });
@@ -144614,6 +146025,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144614
146025
  if (this.reconnectTimer) return;
144615
146026
  if (this.isBattery) {
144616
146027
  this.api = null;
146028
+ this.lastSessionDropReason = `disconnect: ${reason}`;
144617
146029
  this.ctx.logger.debug("Battery cam disconnect — deferring reconnect to next demand", {
144618
146030
  tags: { deviceId: this.id },
144619
146031
  meta: {
@@ -144644,6 +146056,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144644
146056
  }
144645
146057
  });
144646
146058
  this.api = null;
146059
+ this.lastSessionDropReason = `reconnect: ${reason}`;
144647
146060
  if (this.removed) return;
144648
146061
  this.reconnectTimer = setTimeout(() => {
144649
146062
  this.reconnectTimer = null;
@@ -146722,6 +148135,12 @@ function createWebhookHandler(deps) {
146722
148135
  }
146723
148136
  //#endregion
146724
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
+ });
146725
148144
  /**
146726
148145
  * Adapt a camstack scoped logger to the lib's `Logger` shape (just
146727
148146
  * `log(...)`). Lib lines are prefixed with `[AutoDetect]` /
@@ -147290,9 +148709,14 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
147290
148709
  provider: { list: () => intercomFailureReport.list() }
147291
148710
  });
147292
148711
  this.subscribe({ category: EventCategory.StreamBrokerOnRequestStreamSourceRefresh }, (event) => {
147293
- const data = event.data;
147294
- const deviceId = typeof data.deviceId === "number" ? data.deviceId : null;
147295
- 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
+ });
147296
148720
  this.refreshDeviceStreams(deviceId, data.camStreamId).catch((err) => {
147297
148721
  this.ctx.logger.warn("refresh of Reolink stream failed", {
147298
148722
  tags: { deviceId },