Files
corescope-rx/src/monitor.js
T
Erwin FitenandClaude Opus 5 ec55d31bfe fix: the debug log announced a healthy BLE link once a second
noteLinkState's guard was inverted. `state.linkQuiet` holds the INVERSE of
the link being up, so the steady state is `linkQuiet !== linkUp` and an edge
is `linkQuiet === linkUp`. The guard returned on the edge and fell through in
the steady state — the exact opposite of both.

Per-second monitorTick therefore wrote "companion link back" on every tick of
a perfectly healthy link, and swallowed the real transition: linkQuiet never
flipped off its `false` initial value, so "companion link down" could never be
reached at all. A field log from this morning shows 157 of 200 buffered lines
spent on the spam, the whole 200-line ring buffer covering 2m36s, and not one
"link down" line — defeating cc710a3, which added the pair so that a dropped
link would stop reading like an app that had crashed.

The edge decision moves to monitor.js as the pure `linkTransition`, next to
the other per-tick monitor helpers, since app.js cannot be imported under
node --test. Five regression tests cover both steady states, both edges, and a
full drop/return cycle driven tick by tick.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 09:48:06 +02:00

90 lines
4.9 KiB
JavaScript

// Pure monitoring/state helpers for the Home monitor + auto-discover.
// No DOM, no timers, no network — caller passes `now` (ms epoch). Unit-testable.
// --- Auto-discover scheduling -------------------------------------------------
// Discover runs automatically while connected. It backs off whenever organic mesh
// traffic is arriving (we already see those packets, so polling is wasteful and adds
// airtime), and only sweeps after a quiet gap. Standstill pauses it entirely.
export const DISCOVER_INTERVAL_MS = 30000; // base cadence when the channel is quiet
export const DISCOVER_BACKOFF_MS = 15000; // silence required after organic traffic
// discoverDecision decides, on each tick, whether to fire a discover sweep now and
// what status to surface. `lastHeardAt` = ms of the last ORGANIC reception (an
// overheard forwarder/advert — NOT our own discover response); null if none yet.
// `lastFireAt` = ms of the last sweep (0 = never). `linkUp` is whether the BLE link is
// actually up. Returns:
// { fire, state: 'link-down'|'paused'|'backoff'|'active', secs }
// where `secs` is the backoff seconds remaining (backoff) or seconds until the next
// sweep (active). On fire the caller sets lastFireAt = now.
//
// link-down comes FIRST because a sweep while the companion is gone is not a sweep: the
// write throws on a dead characteristic. A field log (2026-09-13, 01:57 onward) shows
// 2.5 minutes of "discover send failed: GATT Server is disconnected" every 30 seconds,
// one per tick, with nothing else able to happen anyway. lastFireAt is deliberately not
// advanced while down, so the first tick after the link returns sweeps immediately.
export function discoverDecision(now, lastHeardAt, lastFireAt, paused, linkUp = true, opts = {}) {
const interval = opts.intervalMs ?? DISCOVER_INTERVAL_MS;
const backoff = opts.backoffMs ?? DISCOVER_BACKOFF_MS;
if (!linkUp) return { fire: false, state: 'link-down', secs: 0 };
if (paused) return { fire: false, state: 'paused', secs: 0 };
if (lastHeardAt != null && now - lastHeardAt < backoff) {
return { fire: false, state: 'backoff', secs: Math.ceil((backoff - (now - lastHeardAt)) / 1000) };
}
const dueIn = interval - (now - lastFireAt);
if (lastFireAt === 0 || dueIn <= 0) return { fire: true, state: 'active', secs: 0 };
return { fire: false, state: 'active', secs: Math.ceil(dueIn / 1000) };
}
// isOrganicHeard reports whether an attributed reception (deriveHeardKey result)
// counts as organic mesh traffic for the backoff: anything we heard that is NOT a
// reply to our own discover poll (those are 8-byte 'discover' prefixes). A 2-byte
// path-hash forwarder ('rxlog') or a 0-hop advert means we're in an active area.
export function isOrganicHeard(hk) {
return !!hk && hk.src !== 'discover';
}
// --- SNR volume meter ---------------------------------------------------------
// Maps an SNR (dB) to a 0..100 bar fill over a fixed display range, with a
// peak-hold marker that decays back toward the live bar.
export const SNR_MIN_DB = -20;
export const SNR_MAX_DB = 10;
export const PEAK_DECAY_PCT_PER_S = 25; // how fast the peak marker sinks back
export function snrToPct(snr) {
if (snr == null) return 0;
const f = (snr - SNR_MIN_DB) / (SNR_MAX_DB - SNR_MIN_DB);
return Math.max(0, Math.min(1, f)) * 100;
}
// decayPeak moves the peak marker toward `targetPct` by PEAK_DECAY_PCT_PER_S, never
// below the target (the live bar pushes it up, decay only lowers a stale peak).
export function decayPeak(peakPct, targetPct, dtMs, opts = {}) {
const rate = opts.ratePctPerS ?? PEAK_DECAY_PCT_PER_S;
const decayed = peakPct - rate * (dtMs / 1000);
return Math.max(targetPct, decayed);
}
// --- Capture rate (rolling window) -------------------------------------------
// pruneTimestamps drops entries older than windowMs. With the default 60 s window the
// surviving length is the packets-per-minute rate.
export function pruneTimestamps(times, now, windowMs = 60000) {
const cutoff = now - windowMs;
return times.filter((t) => t >= cutoff);
}
// --- Companion link edges -----------------------------------------------------
// linkTransition decides what the per-second tick should ANNOUNCE about the BLE link:
// 'down', 'back', or null while nothing changed. `prevQuiet` is the caller's stored
// flag, which holds the INVERSE of the link being up — so the steady state is
// `prevQuiet !== linkUp`, and an edge is exactly `prevQuiet === linkUp`.
//
// Getting that comparison the wrong way round is not a cosmetic bug: it announces on
// every steady tick and swallows the real edge. A field log (2026-09-14, 08:47 onward)
// shows "companion link back" once a second for three minutes, filling the 200-line
// debug buffer so that the heard/asks/regions lines rolled out of it — and no "link
// down" line anywhere, because the flag never flipped.
export function linkTransition(prevQuiet, linkUp) {
if (prevQuiet !== linkUp) return null; // steady: the flag already holds the inverse
return linkUp ? 'back' : 'down';
}