R1 ring: Debug health-data sync
This commit is contained in:
1 parent
fcea0b369a
commit
7289496c09
14 files changed
+705
-194
No files matched your search
@@ -2,6 +2,8 @@
|
||||
|
||||
## 0.8.6 - Future
|
||||
|
||||
* Connect directly to the R1 ring rather than indirectly via the glasses
|
||||
* Add a Health app and glanceboard card for viewing R1 ring data
|
||||
* Add a distance unit option
|
||||
* Make BLE benchmark work on iOS
|
||||
* Ensure connection is re-set to 2M on reconnect
|
||||
@@ -12,6 +14,7 @@
|
||||
* Android: Optionally sign in to Spotify's Web API for library browsing and other features
|
||||
* Mark stock firmware 2.4.0 as validated for installing custom firmware over
|
||||
|
||||
|
||||
## 0.8.5 - 2026-10-25
|
||||
|
||||
### Features
|
||||
|
||||
@@ -165,6 +165,13 @@ export class RingStatusLayer implements Layer {
|
||||
value: s.directGlassesAuth ? `${s.directGlassesAuth} ${formatAge(s.directGlassesAuthAgeMs)} ago` : "not sent yet",
|
||||
});
|
||||
}
|
||||
if (s.directEnabled) {
|
||||
const pull = s.healthWindowActive ? "pulling now (phone role)"
|
||||
: s.lastHealthPull ? `${s.lastHealthPull} ${formatAge(s.lastHealthPullAgeMs)} ago`
|
||||
: "no pull yet";
|
||||
const held = s.heldHealthRecords > 0 ? `, ${s.heldHealthRecords} records unstored` : "";
|
||||
rows.push({ label: "Health sync", value: pull + held });
|
||||
}
|
||||
rows.push({ label: "Direct input", value: describeInput(s.lastDirectInputAgeMs, s.lastDirectInput) });
|
||||
if (s.directEnabled) {
|
||||
rows.push({ label: "Direct pkts", value: describeAge(s.lastDirectNotifyAgeMs) });
|
||||
|
||||
@@ -1502,8 +1502,9 @@ class DashboardController {
|
||||
right: addresses.right,
|
||||
left: addresses.left,
|
||||
ring: ringAddress,
|
||||
// Direct mode acts as the ring's glasses (gestures, battery); health
|
||||
// sync needs the phone role instead.
|
||||
// Direct mode acts as the ring's glasses (gestures, battery). Health
|
||||
// sync needs the phone role, which the session borrows briefly for
|
||||
// each pull (GlassesSessionRing.beginRingHealthWindowLocked).
|
||||
ringRole: ringMode === "direct" ? "glasses" : "phone",
|
||||
});
|
||||
this.communicator = communicator;
|
||||
|
||||
+125
-26
@@ -45,7 +45,7 @@ import {
|
||||
type WireStepsRecord,
|
||||
} from "./health-ingest";
|
||||
import { markLiveData, purgeFixtureData } from "./health-seed";
|
||||
import { healthStore } from "./health-store-files";
|
||||
import { checkedFileOperation, healthStore } from "./health-store-files";
|
||||
import { startOfLocalDay, type SleepSegment } from "./health-types";
|
||||
import { File, knownFolders } from "@nativescript/core";
|
||||
|
||||
@@ -381,7 +381,128 @@ function consumeUpTo(communicator: any, watermark: number): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** The communicator's `java.util.List` of `RingProtocol.HealthRecord`s. */
|
||||
type JavaRecordList = { size(): number; get(index: number): any };
|
||||
|
||||
type StoreResult = Omit<LiveSyncResult, "seen">;
|
||||
|
||||
/**
|
||||
* Convert decoded records and store them durably. Throws if a store write
|
||||
* fails, so the caller keeps whatever it would otherwise mark as consumed.
|
||||
* Shared by the live batch and the journal replay.
|
||||
*/
|
||||
function storeRecords(records: JavaRecordList): StoreResult {
|
||||
const wire: WireRecord[] = [];
|
||||
const size = records.size();
|
||||
for (let i = 0; i < size; i++) {
|
||||
try {
|
||||
const converted = toWire(records.get(i));
|
||||
if (converted) wire.push(converted);
|
||||
} catch (error) {
|
||||
console.warn("health live: skipped an undecodable record", error);
|
||||
}
|
||||
}
|
||||
if (wire.length === 0) return { samplesWritten: 0, sleepWritten: 0, skipped: [] };
|
||||
|
||||
const { samples, sleep, skipped } = convertRecords(wire);
|
||||
if (samples.length === 0 && sleep.length === 0) {
|
||||
return { samplesWritten: 0, sleepWritten: 0, skipped };
|
||||
}
|
||||
|
||||
// First real data wins the store outright — see the header.
|
||||
purgeFixtureData();
|
||||
|
||||
const store = healthStore();
|
||||
const samplesWritten = store.ingestSamples(samples);
|
||||
const sleepWritten = store.ingestSleep(sleep);
|
||||
// Also mark on a retry whose samples were already appended before a later
|
||||
// write failed. Otherwise opening Health could seed fixtures over real data.
|
||||
markLiveData();
|
||||
return { samplesWritten, sleepWritten, skipped };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bump when the Kotlin decoders learn a layout they used to reject. The
|
||||
* replay cursor records the version it ran under, and a cursor from an older
|
||||
* decoder replays the whole journal: the frames it skipped are only on disk.
|
||||
*
|
||||
* 2: R1 firmware 2.3.x's four-byte page trailer (2026-11-01). Before it,
|
||||
* every page that firmware sent was journaled, acknowledged and dropped.
|
||||
*/
|
||||
const JOURNAL_DECODER_VERSION = 2;
|
||||
|
||||
type ReplayCursor = { version: number; throughReceivedAtMs: number };
|
||||
|
||||
function healthFilePath(name: string): string {
|
||||
return `${knownFolders.documents().getFolder("health").path}/${name}`;
|
||||
}
|
||||
|
||||
function readReplayCursor(): ReplayCursor | null {
|
||||
try {
|
||||
const path = healthFilePath("journal-replay.json");
|
||||
if (!File.exists(path)) return null;
|
||||
const parsed = JSON.parse(File.fromPath(path).readTextSync()) as ReplayCursor;
|
||||
return typeof parsed?.version === "number" && typeof parsed.throughReceivedAtMs === "number" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let journalReplayed = false;
|
||||
|
||||
/**
|
||||
* Store the health pages in the communicator's frame journal
|
||||
* (`ring-frames.jsonl`, written before each page is acknowledged) that have
|
||||
* not been replayed under the current decoder. Once per process, before any
|
||||
* live batch, so pages land oldest first and a newer live value is never
|
||||
* overwritten by an older replayed one.
|
||||
*
|
||||
* The ring counts an acknowledged page as synced and does not send it again,
|
||||
* so a page the decoder could not read at the time exists nowhere else. The
|
||||
* store and the steps ledger are idempotent, so re-storing a page that was
|
||||
* already ingested live is a no-op.
|
||||
*/
|
||||
function replayFrameJournalOnce(): void {
|
||||
if (journalReplayed) return;
|
||||
let ringProtocol: any;
|
||||
try {
|
||||
ringProtocol = (com as any).faceclaw.app.RingProtocol;
|
||||
} catch {
|
||||
ringProtocol = null;
|
||||
}
|
||||
const journalPath = healthFilePath("ring-frames.jsonl");
|
||||
if (!ringProtocol || !File.exists(journalPath)) {
|
||||
journalReplayed = true;
|
||||
return;
|
||||
}
|
||||
const cursor = readReplayCursor();
|
||||
const after = cursor?.version === JOURNAL_DECODER_VERSION ? cursor.throughReceivedAtMs : 0;
|
||||
const records: JavaRecordList = ringProtocol.decodeFrameJournal(File.fromPath(journalPath).readTextSync(), after);
|
||||
const size = records.size();
|
||||
if (size > 0) {
|
||||
const result = storeRecords(records);
|
||||
let through = after;
|
||||
for (let i = 0; i < size; i++) through = Math.max(through, Number(records.get(i).receivedAtMs));
|
||||
const next: ReplayCursor = { version: JOURNAL_DECODER_VERSION, throughReceivedAtMs: through };
|
||||
checkedFileOperation((onError) =>
|
||||
File.fromPath(healthFilePath("journal-replay.json")).writeTextSync(JSON.stringify(next), onError),
|
||||
);
|
||||
console.log(
|
||||
`health live: replayed ${size} journaled pages -> ${result.samplesWritten} samples, ` +
|
||||
`${result.sleepWritten} sleep` + (result.skipped.length ? `, ${result.skipped.length} skipped` : ""),
|
||||
);
|
||||
}
|
||||
journalReplayed = true;
|
||||
}
|
||||
|
||||
export function syncLiveRecords(): LiveSyncResult {
|
||||
try {
|
||||
replayFrameJournalOnce();
|
||||
} catch (error) {
|
||||
// Not marked done: the next sync retries it, ahead of the live batch.
|
||||
console.warn("health live: frame journal replay failed", error);
|
||||
}
|
||||
|
||||
const communicator = activeCommunicator();
|
||||
if (!communicator) return EMPTY;
|
||||
|
||||
@@ -399,33 +520,9 @@ export function syncLiveRecords(): LiveSyncResult {
|
||||
// what keeps a page landing mid-ingest from being dropped.
|
||||
const watermark = Number(batch.getWatermark());
|
||||
if (!records || !records.size || records.size() === 0) return EMPTY;
|
||||
|
||||
const wire: WireRecord[] = [];
|
||||
const size = records.size();
|
||||
for (let i = 0; i < size; i++) {
|
||||
try {
|
||||
const converted = toWire(records.get(i));
|
||||
if (converted) wire.push(converted);
|
||||
} catch (error) {
|
||||
console.warn("health live: skipped an undecodable record", error);
|
||||
}
|
||||
}
|
||||
if (wire.length === 0) return { ...EMPTY, seen: size };
|
||||
|
||||
const { samples, sleep, skipped } = convertRecords(wire);
|
||||
if (samples.length === 0 && sleep.length === 0) {
|
||||
return { seen: size, samplesWritten: 0, sleepWritten: 0, skipped };
|
||||
}
|
||||
|
||||
// First real data wins the store outright — see the header.
|
||||
purgeFixtureData();
|
||||
|
||||
const store = healthStore();
|
||||
const samplesWritten = store.ingestSamples(samples);
|
||||
const sleepWritten = store.ingestSleep(sleep);
|
||||
// Also mark on a retry whose samples were already appended before a later
|
||||
// write failed. Otherwise opening Health could seed fixtures over real data.
|
||||
markLiveData();
|
||||
const { samplesWritten, sleepWritten, skipped } = storeRecords(records);
|
||||
|
||||
// ONLY here. Both store writes have returned, so the records are durable.
|
||||
// If either threw, or the process died above this line, nothing is cleared
|
||||
@@ -433,6 +530,8 @@ export function syncLiveRecords(): LiveSyncResult {
|
||||
// ingest (a no-op, the store refuses identical re-writes) instead of losing
|
||||
// a night. Note `samplesWritten === 0` is NOT a failure: it means the store
|
||||
// already held all of it, which is the steady state this change creates.
|
||||
// Records that converted to nothing are consumed too: holding them would
|
||||
// only re-run the same conversion every tick.
|
||||
consumeUpTo(communicator, watermark);
|
||||
|
||||
console.log(
|
||||
|
||||
@@ -39,6 +39,13 @@ export type RingSessionStatus = {
|
||||
lastCommandResultL: string;
|
||||
/** Which ring role the direct link claims: "phone" or "glasses". */
|
||||
directRole: string;
|
||||
/** Glasses role only: the link is temporarily in the phone role for a health pull. */
|
||||
healthWindowActive: boolean;
|
||||
/** Outcome of the last health pull ("completed, 12 pages", "aborted, 0 pages", ...), "" if none. */
|
||||
lastHealthPull: string;
|
||||
lastHealthPullAgeMs: number;
|
||||
/** Decoded health records not yet stored by the TypeScript ingest. */
|
||||
heldHealthRecords: number;
|
||||
/** Glasses role only: what the ring made of our legacy pair-auth this connection ("" = not sent). */
|
||||
directGlassesAuth: string;
|
||||
directGlassesAuthAgeMs: number;
|
||||
|
||||
@@ -851,7 +851,7 @@ export const ringConnectionModeSetting = new ConfigSettingEnum<RingConnectionMod
|
||||
formatValue: (value) =>
|
||||
value === "direct" ? "Direct to phone" : value === "health" ? "Via glasses + health sync" : "Only via glasses",
|
||||
description:
|
||||
"How the R1 ring reaches the phone. Only via glasses: the glasses relay the ring's gestures and the phone never connects to it. Via glasses + health sync: the same, plus the phone connects to the ring to sync health data. Direct to phone (experimental): the phone takes the ring over from the glasses and gets its gestures and battery itself; the glasses lose ring input and ring health sync is off. Leaving Direct hands the ring back to the glasses. Takes effect on the next connection to the glasses.",
|
||||
"How the R1 ring reaches the phone. Only via glasses: the glasses relay the ring's gestures and the phone never connects to it. Via glasses + health sync: the same, plus the phone connects to the ring to sync health data. Direct to phone (experimental): the phone takes the ring over from the glasses and gets its gestures and battery itself; the glasses lose ring input. Health still syncs, but each sync (on opening Health, and at :01 and :31) pauses ring gestures for up to a minute while the phone briefly reconnects to the ring in its health role. Leaving Direct hands the ring back to the glasses. Takes effect on the next connection to the glasses.",
|
||||
});
|
||||
|
||||
// "whisper" (no "onboard-" prefix) is OpenAI's CLOUD realtime model
|
||||
|
||||
+56
-6
@@ -107,6 +107,20 @@ class RingProtocol private constructor() {
|
||||
/** Returned by anchor/timestamp accessors when the value is not known. */
|
||||
const val UNKNOWN_TIME: Long = -1L
|
||||
|
||||
/**
|
||||
* Bytes R1 firmware 2.3.x appends to every health DATA page, after the
|
||||
* last group/bucket. Seen on 2.3.0.0005 and 2.3.2.0008: every one of
|
||||
* the 30 hourly and activity pages journaled 2026-10-06..11-01 carries
|
||||
* it (values `6e050000`, `00000000`, `ad5e0000`; meaning unknown).
|
||||
* Firmware 2.0.7.0003 sent none (notes/ring-health-live-validation.md),
|
||||
* so the decoders accept a page with or without it. The group or
|
||||
* bucket count is explicit, so the two lengths cannot be confused.
|
||||
*/
|
||||
const val HEALTH_PAGE_TRAILER_LEN: Int = 4
|
||||
|
||||
private val JOURNAL_RECEIVED_AT = Regex("\"receivedAtMs\":(\\d+)")
|
||||
private val JOURNAL_RAW = Regex("\"raw\":\"([0-9a-fA-F]+)\"")
|
||||
|
||||
private val EMPTY = ByteArray(0)
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -432,14 +446,42 @@ class RingProtocol private constructor() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the health DATA pages in a ring frame journal - the JSON lines
|
||||
* `{"receivedAtMs":N,"raw":"<hex>"}` the session writes before
|
||||
* acknowledging each frame - received after [afterReceivedAtMs], in
|
||||
* file order. Anything that is not a decodable health DATA page is
|
||||
* skipped. Lets pages the ring will never send again (it counts an
|
||||
* acknowledged page as synced) be stored after a decoder fix.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun decodeFrameJournal(text: String, afterReceivedAtMs: Long): List<HealthRecord> {
|
||||
val records = ArrayList<HealthRecord>()
|
||||
for (line in text.lineSequence()) {
|
||||
val receivedAtMs = JOURNAL_RECEIVED_AT.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: continue
|
||||
if (receivedAtMs <= afterReceivedAtMs) continue
|
||||
val raw = JOURNAL_RAW.find(line)?.groupValues?.get(1) ?: continue
|
||||
if (raw.length % 2 != 0) continue
|
||||
val bytes = ByteArray(raw.length / 2) { raw.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
|
||||
val record = try {
|
||||
decode(parse(bytes), receivedAtMs)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: continue
|
||||
records.add(record)
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
/**
|
||||
* Heart rate / SpO2 / HRV: an hourly `[index][avg][max][min]` series.
|
||||
*
|
||||
* Layout follows openR1 r1_health_encode_daily_u8/u16 in r1_health.c:
|
||||
* count, signed timezone minutes, day start, optional latest timestamp/value,
|
||||
* then count groups. There is no footer. HR/SpO2 values are one byte; HRV
|
||||
* values are two. Subtracting a supposed four-byte footer misdecoded a
|
||||
* one-group HRV page as one-byte values and rejected real HR/SpO2 pages.
|
||||
* then count groups, then (firmware 2.3.x only) [HEALTH_PAGE_TRAILER_LEN]
|
||||
* trailing bytes. HR/SpO2 values are one byte; HRV values are two; the
|
||||
* width comes from the command, never from the length, which is what
|
||||
* once misdecoded a one-group HRV page as one-byte values.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun decodeHourly(frame: Frame, receivedAtMs: Long): HourlyRecord? {
|
||||
@@ -451,7 +493,11 @@ class RingProtocol private constructor() {
|
||||
val anchor = anchorUnixSeconds(pay)
|
||||
val width = if (frame.cmdHi == CMD_HI_HRV) 2 else 1
|
||||
val groupBytes = count * (1 + 3 * width)
|
||||
val prefixLength = pay.size - groupBytes
|
||||
val nonGroupBytes = pay.size - groupBytes
|
||||
// 9 or 13+width without the trailer; 13 or 17+width with it. All distinct.
|
||||
val trailer = if (nonGroupBytes == 9 + HEALTH_PAGE_TRAILER_LEN
|
||||
|| nonGroupBytes == 13 + width + HEALTH_PAGE_TRAILER_LEN) HEALTH_PAGE_TRAILER_LEN else 0
|
||||
val prefixLength = nonGroupBytes - trailer
|
||||
val hasLatest = prefixLength == 13 + width
|
||||
if (count > 24 || (!hasLatest && prefixLength != 9)) return null
|
||||
val tag = if (hasLatest) readUInt32Le(pay, 9) else UNKNOWN_TIME
|
||||
@@ -488,7 +534,8 @@ class RingProtocol private constructor() {
|
||||
return null
|
||||
}
|
||||
val count = pay[2].toInt() and 0xff
|
||||
if (count > 144 || pay.size != 9 + count * 7) {
|
||||
val bucketsEnd = 9 + count * 7
|
||||
if (count > 144 || (pay.size != bucketsEnd && pay.size != bucketsEnd + HEALTH_PAGE_TRAILER_LEN)) {
|
||||
return null
|
||||
}
|
||||
val anchor = anchorUnixSeconds(pay)
|
||||
@@ -539,7 +586,10 @@ class RingProtocol private constructor() {
|
||||
val lightTime = readUInt16Le(pay, 28)
|
||||
val deepTime = readUInt16Le(pay, 30)
|
||||
val segmentCount = readUInt16Le(pay, 32)
|
||||
if (pay.size != 34 + segmentCount * 3) {
|
||||
// The 2.3.x trailer is assumed here too: no sleep DATA page has been
|
||||
// seen from that firmware yet.
|
||||
val segmentsEnd = 34 + segmentCount * 3
|
||||
if (pay.size != segmentsEnd && pay.size != segmentsEnd + HEALTH_PAGE_TRAILER_LEN) {
|
||||
return null
|
||||
}
|
||||
var offset = 34
|
||||
|
||||
+32
-5
@@ -226,6 +226,18 @@ class GlassesSessionCore(
|
||||
* sequence. Guarded by `monitor`. See RING_HEALTH_ABORTED_RETRY_LIMIT.
|
||||
*/
|
||||
internal var ringHealthAbortedRetries = 0
|
||||
/**
|
||||
* Direct mode (configured role "glasses") only: the direct link has been
|
||||
* handed to the phone role for one health pull, and returns to the glasses
|
||||
* role when that pull ends, or at [ringHealthWindowDeadlineMs] if the
|
||||
* phone-role link never comes up. See beginRingHealthWindowLocked.
|
||||
* Guarded by `monitor`.
|
||||
*/
|
||||
internal var ringHealthWindowActive = false
|
||||
internal var ringHealthWindowDeadlineMs = 0L
|
||||
/** Outcome of the last health pull, for the Ring status page. Guarded by `monitor`. */
|
||||
internal var lastRingHealthPullResult = ""
|
||||
internal var lastRingHealthPullAtMs = 0L
|
||||
/**
|
||||
* Timeout waiting for a health REQ's own RSP. In the reference capture
|
||||
* (a real successful Even sync) RSPs land within ~150ms; this only needs
|
||||
@@ -1021,6 +1033,10 @@ class GlassesSessionCore(
|
||||
status["lastCommandResultR"] = lastRingLinkResultR
|
||||
status["lastCommandResultL"] = lastRingLinkResultL
|
||||
status["directRole"] = directRingRole
|
||||
status["healthWindowActive"] = ringHealthWindowActive
|
||||
status["lastHealthPull"] = lastRingHealthPullResult
|
||||
status["lastHealthPullAgeMs"] = age(lastRingHealthPullAtMs)
|
||||
status["heldHealthRecords"] = ringHealthRecords.size
|
||||
status["directGlassesAuth"] = directGlassesAuth
|
||||
status["directGlassesAuthAgeMs"] = age(directGlassesAuthAtMs)
|
||||
status["lastRingCommand"] = lastRingConfigCommand
|
||||
@@ -1040,8 +1056,10 @@ class GlassesSessionCore(
|
||||
* with only the data CCCD, like Even's app. The glasses keep the ring.
|
||||
* - "glasses": act as the ring's glasses (legacy CCCD, legacy pair-auth,
|
||||
* touch source on; see runRingGlassesSetup) and take the ring over from
|
||||
* the glasses when they still hold it. No health sync: the ring answers
|
||||
* system requests only on a phone-role link.
|
||||
* the glasses when they still hold it. The ring answers system requests
|
||||
* (health included) only on a phone-role link, so each health pull
|
||||
* briefly reconnects the link in the phone role and then returns it
|
||||
* (see beginRingHealthWindowLocked).
|
||||
* Asking for both on one link (the old behavior) made the ring drop the
|
||||
* link every ~6 s while the glasses held it. A change while the direct
|
||||
* link is up reconnects it.
|
||||
@@ -1051,6 +1069,8 @@ class GlassesSessionCore(
|
||||
monitor.withLock {
|
||||
if (normalized == directRingRole) return
|
||||
directRingRole = normalized
|
||||
// A health window only exists to borrow the phone role from the glasses role.
|
||||
ringHealthWindowActive = false
|
||||
if (ringConnected || ringNotificationsReady) {
|
||||
ringRoleReconnectPending = true
|
||||
monitor.signalAll()
|
||||
@@ -2406,7 +2426,11 @@ class GlassesSessionCore(
|
||||
// service events 6/7), and the ring sends gestures (00 09 61 00 ...)
|
||||
// only to that role. The direct ring
|
||||
// role setting decides which CCCDs we enable; see setDirectRingRole.
|
||||
val role = monitor.withLock { directRingRole }
|
||||
val configuredRole: String
|
||||
val role = monitor.withLock {
|
||||
configuredRole = directRingRole
|
||||
effectiveRingRoleLocked()
|
||||
}
|
||||
val legacyNotify = role == DIRECT_RING_ROLE_GLASSES
|
||||
&& enableRingNotification(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID)
|
||||
val dataNotify = enableRingNotification(BleProtocol.R1_NOTIFY_CHAR_UUID)
|
||||
@@ -2433,10 +2457,13 @@ class GlassesSessionCore(
|
||||
directGlassesAuthAtMs = 0L
|
||||
directGlassesAuthRetried = false
|
||||
}
|
||||
logLine("direct ring ready role=$role legacyNotify=$legacyNotify dataNotify=$dataNotify")
|
||||
logLine("direct ring ready role=$role legacyNotify=$legacyNotify dataNotify=$dataNotify"
|
||||
+ (if (role != configuredRole) " (health window; configured role $configuredRole)" else ""))
|
||||
|
||||
// The glasses role means no pairAuth (it would ask for the phone role
|
||||
// on the same link) and therefore no health sync.
|
||||
// on the same link) and therefore no health sync. Direct mode gets its
|
||||
// health through a temporary phone-role connection instead (see
|
||||
// beginRingHealthWindowLocked), which takes this branch.
|
||||
if (dataNotify && host.supportsRingHealth() && role == DIRECT_RING_ROLE_PHONE) {
|
||||
onRingDataChannelReady()
|
||||
}
|
||||
|
||||
+189
-26
@@ -87,6 +87,39 @@ private const val RING_HEALTH_ABORTED_RETRY_LIMIT = 2
|
||||
*/
|
||||
private const val RING_HEALTH_ABORTED_RETRY_GAP_MS = 60L * 1000L
|
||||
|
||||
/**
|
||||
* Direct mode: floor between health windows (see beginRingHealthWindowLocked).
|
||||
* A window costs the user ring gestures for the length of two reconnects and a
|
||||
* pull, so opening and closing the Health app must not keep bouncing the link.
|
||||
* The aligned :01/:31 pulls are well outside it.
|
||||
*/
|
||||
private const val RING_HEALTH_WINDOW_MIN_INTERVAL_MS = 5L * 60L * 1000L
|
||||
|
||||
/**
|
||||
* Direct mode: how long a health window waits for its phone-role link to be
|
||||
* up before giving up and handing the link back to the glasses role. Bounds
|
||||
* only the connect; a pull that has started runs to completion on the ring
|
||||
* worker before the deadline is looked at again.
|
||||
*/
|
||||
private const val RING_HEALTH_WINDOW_CONNECT_TIMEOUT_MS = 60_000L
|
||||
|
||||
/**
|
||||
* Direct mode: a requested health window waits until the ring has been idle
|
||||
* this long, so it does not take the ring away in the middle of a gesture
|
||||
* sequence. The request stays pending meanwhile.
|
||||
*/
|
||||
private const val RING_HEALTH_WINDOW_INPUT_IDLE_MS = 5_000L
|
||||
|
||||
/**
|
||||
* Pause between dropping the direct link and reconnecting it in another role.
|
||||
* The ring frees a role when the connection ends, but Android keeps the LE
|
||||
* link up for a moment after the last client closes, and a new client
|
||||
* registered in that moment reuses it - the ring would then see the old
|
||||
* role's handle ask for the other role, which stock firmware treats as a
|
||||
* fatal assertion (openCFW CONNECTION-ROLE-ASSIGNMENT-CORRELATION.md).
|
||||
*/
|
||||
private const val RING_ROLE_SWITCH_SETTLE_MS = 3_000L
|
||||
|
||||
/** First pause after a failed ring write; doubles per consecutive failure. See [writeRingFrame]. */
|
||||
private const val RING_WRITE_BACKOFF_MS = 1_000L
|
||||
private const val RING_WRITE_BACKOFF_MAX_MS = 15_000L
|
||||
@@ -130,6 +163,7 @@ class RingHealthBatch internal constructor(
|
||||
internal fun GlassesSessionCore.runRingWorker() {
|
||||
while (running) {
|
||||
try {
|
||||
expireRingHealthWindow()
|
||||
restartRingLinkForRoleChange()
|
||||
if (shouldAttemptRingConnect()) tryConnectRing("ring worker")
|
||||
if (!running) break
|
||||
@@ -314,27 +348,143 @@ internal fun GlassesSessionCore.journalRingFrame(frame: RingProtocol.Frame): Boo
|
||||
* Ring worker only (blocking).
|
||||
*/
|
||||
internal fun GlassesSessionCore.onRingDataChannelReady() {
|
||||
// The handshake mirrors what Even's own app repeats on every one
|
||||
// of its sync bursts (confirmed in the reference capture), so
|
||||
// sending it on every reconnect matches known-working behavior.
|
||||
// The actual health pull is throttled separately below - see
|
||||
// ringHealthLastRequestedAtMs and requestRingHealth()'s own
|
||||
// race-condition warning for why.
|
||||
sendRingHandshake()
|
||||
val now = now()
|
||||
val dueForHealthPull: Boolean
|
||||
val lastRequestedAtMs: Long
|
||||
monitor.withLock {
|
||||
lastRequestedAtMs = ringHealthLastRequestedAtMs
|
||||
dueForHealthPull = ringHealthPullDueLocked(now)
|
||||
if (dueForHealthPull) {
|
||||
ringHealthLastRequestedAtMs = now
|
||||
try {
|
||||
// The handshake mirrors what Even's own app repeats on every one
|
||||
// of its sync bursts (confirmed in the reference capture), so
|
||||
// sending it on every reconnect matches known-working behavior.
|
||||
// The actual health pull is throttled separately below - see
|
||||
// ringHealthLastRequestedAtMs and requestRingHealth()'s own
|
||||
// race-condition warning for why.
|
||||
sendRingHandshake()
|
||||
val now = now()
|
||||
val dueForHealthPull: Boolean
|
||||
val lastRequestedAtMs: Long
|
||||
monitor.withLock {
|
||||
lastRequestedAtMs = ringHealthLastRequestedAtMs
|
||||
// A health window was opened for exactly this pull, and its own
|
||||
// floor was applied when it opened.
|
||||
dueForHealthPull = ringHealthWindowActive || ringHealthPullDueLocked(now)
|
||||
if (dueForHealthPull) {
|
||||
ringHealthLastRequestedAtMs = now
|
||||
}
|
||||
}
|
||||
if (dueForHealthPull) {
|
||||
runRingHealthPull()
|
||||
} else {
|
||||
logLine("ring health: pull skipped, last one was " + ((now - lastRequestedAtMs) / 1000) + "s ago")
|
||||
}
|
||||
} finally {
|
||||
// Completed, aborted or threw: either way the link goes back to the
|
||||
// glasses role, so a failed pull never costs the user gestures for
|
||||
// longer than the attempt.
|
||||
monitor.withLock { endRingHealthWindowLocked("pull finished") }
|
||||
}
|
||||
if (dueForHealthPull) {
|
||||
runRingHealthPull()
|
||||
} else {
|
||||
logLine("ring health: pull skipped, last one was " + ((now - lastRequestedAtMs) / 1000) + "s ago")
|
||||
}
|
||||
|
||||
/**
|
||||
* The direct link's role for its next setup: the configured one, except the
|
||||
* phone role while a health window is open. Caller holds `monitor`.
|
||||
*/
|
||||
internal fun GlassesSessionCore.effectiveRingRoleLocked(): String =
|
||||
if (ringHealthWindowActive) DIRECT_RING_ROLE_PHONE else directRingRole
|
||||
|
||||
/**
|
||||
* Direct mode's health sync. Caller holds `monitor`.
|
||||
*
|
||||
* In Direct mode the direct link holds the ring's glasses role (gestures,
|
||||
* battery), and the ring answers system requests - health included - only to
|
||||
* its phone role. One link cannot hold both: the stock role setter treats the
|
||||
* same connection asking for the second role as a fatal assertion, and live
|
||||
* "both" links died every ~6 s (notes/ring-link-control.md). So a pull borrows
|
||||
* the phone role: drop the link, reconnect it with only the data CCCD (the
|
||||
* health-mode setup, which runs the handshake and the pull), then drop it
|
||||
* again and reconnect in the glasses role. Ring gestures stop for that long,
|
||||
* typically well under a minute; the glasses' own touch input is unaffected.
|
||||
*
|
||||
* Every exit returns the link to the glasses role: the pull finishing
|
||||
* ([onRingDataChannelReady]), the connect deadline ([expireRingHealthWindow]),
|
||||
* or a role change ([GlassesSessionCore.setDirectRingRole]).
|
||||
*
|
||||
* Not yet hardware-tested: whether the ring restores the bonded peer's legacy
|
||||
* CCCD on the phone-role reconnect and assigns the glasses role from it. If it
|
||||
* does, the phone-role pairAuth would be refused or the link dropped, the pull
|
||||
* would abort, and the window would close; look for "health window" in the log.
|
||||
*/
|
||||
internal fun GlassesSessionCore.beginRingHealthWindowLocked(now: Long, reason: String) {
|
||||
ringHealthWindowActive = true
|
||||
ringHealthWindowDeadlineMs = now + RING_HEALTH_WINDOW_CONNECT_TIMEOUT_MS
|
||||
// Counts as the attempt for the window floor whether or not it succeeds,
|
||||
// so a ring that never comes up in the phone role is retried at most
|
||||
// once per floor.
|
||||
ringHealthLastRequestedAtMs = now
|
||||
// A link already set up in the glasses role has to be dropped. One that
|
||||
// is still connecting sets up in the phone role when it lands.
|
||||
if (ringNotificationsReady) {
|
||||
ringRoleReconnectPending = true
|
||||
}
|
||||
monitor.signalAll()
|
||||
logLine("ring health: opening a health window ($reason): direct link to the phone role for one pull")
|
||||
}
|
||||
|
||||
/** Close a health window and put the link back in the glasses role. Caller holds `monitor`. */
|
||||
internal fun GlassesSessionCore.endRingHealthWindowLocked(reason: String) {
|
||||
if (!ringHealthWindowActive) return
|
||||
ringHealthWindowActive = false
|
||||
ringHealthWindowDeadlineMs = 0L
|
||||
// Only a link that finished its phone-role setup has to be dropped; one
|
||||
// still connecting picks up the glasses role when it sets up.
|
||||
if (directRingRole == DIRECT_RING_ROLE_GLASSES && ringNotificationsReady) {
|
||||
ringRoleReconnectPending = true
|
||||
}
|
||||
monitor.signalAll()
|
||||
logLine("ring health: closing the health window ($reason); direct link back to the glasses role")
|
||||
}
|
||||
|
||||
/** Ring-worker tick: give up on a health window whose phone-role link never came up. */
|
||||
internal fun GlassesSessionCore.expireRingHealthWindow() {
|
||||
monitor.withLock {
|
||||
if (!ringHealthWindowActive || now() < ringHealthWindowDeadlineMs) return
|
||||
lastRingHealthPullResult = "not run: phone-role link did not come up"
|
||||
lastRingHealthPullAtMs = now()
|
||||
endRingHealthWindowLocked("phone-role link not up after "
|
||||
+ (RING_HEALTH_WINDOW_CONNECT_TIMEOUT_MS / 1000L) + "s")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Direct mode's on-demand pull: open a health window for an explicit request
|
||||
* (Health app opened, aligned :01/:31 tick), and once per session without one
|
||||
* so the first pull does not wait for the next aligned tick. Ring worker only.
|
||||
*/
|
||||
private fun GlassesSessionCore.startRequestedRingHealthWindow() {
|
||||
val now = now()
|
||||
monitor.withLock {
|
||||
if (!host.supportsRingHealth()) {
|
||||
ringHealthPullRequested = false
|
||||
return
|
||||
}
|
||||
if (ringHealthWindowActive) {
|
||||
// The open window pulls as soon as its link is up.
|
||||
ringHealthPullRequested = false
|
||||
return
|
||||
}
|
||||
val firstThisSession = ringHealthLastRequestedAtMs == 0L
|
||||
if (!ringHealthPullRequested && !firstThisSession) return
|
||||
// The ring is only dialed once the glasses session is up
|
||||
// (shouldAttemptRingConnect); opening sooner would spend the
|
||||
// window's connect deadline waiting on the glasses.
|
||||
if (!running || !sessionReady) return
|
||||
if (!firstThisSession && now - ringHealthLastRequestedAtMs < RING_HEALTH_WINDOW_MIN_INTERVAL_MS) {
|
||||
ringHealthPullRequested = false
|
||||
logLine("ring health: health window skipped, last pull attempt was "
|
||||
+ ((now - ringHealthLastRequestedAtMs) / 1000) + "s ago")
|
||||
return
|
||||
}
|
||||
if (lastDirectRingInputAtMs != 0L && now - lastDirectRingInputAtMs < RING_HEALTH_WINDOW_INPUT_IDLE_MS) {
|
||||
return // the ring is in use; try again on a later tick
|
||||
}
|
||||
ringHealthPullRequested = false
|
||||
beginRingHealthWindowLocked(now, if (firstThisSession) "first pull this session" else "requested")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,8 +512,12 @@ internal fun GlassesSessionCore.ringHealthPullDueLocked(now: Long): Boolean {
|
||||
* definition of "aborted".
|
||||
*/
|
||||
internal fun GlassesSessionCore.runRingHealthPull() {
|
||||
val pagesBefore = monitor.withLock { ringHealthPageCounter }
|
||||
val completed = requestRingHealth()
|
||||
monitor.withLock {
|
||||
val pages = ringHealthPageCounter - pagesBefore
|
||||
lastRingHealthPullResult = (if (completed) "completed" else "aborted") + ", $pages pages"
|
||||
lastRingHealthPullAtMs = now()
|
||||
if (completed) {
|
||||
ringHealthAbortedRetries = 0
|
||||
} else if (ringHealthAbortedRetries < RING_HEALTH_ABORTED_RETRY_LIMIT) {
|
||||
@@ -393,6 +547,8 @@ internal fun GlassesSessionCore.resumeAbortedRingHealthPull() {
|
||||
if (ringHealthAbortedRetries == 0) {
|
||||
return
|
||||
}
|
||||
// Direct mode does not resume here: a retry would mean another pair
|
||||
// of role switches, so the next requested or aligned window retries.
|
||||
if (!ringConnected || !ringNotificationsReady || directRingRole == DIRECT_RING_ROLE_GLASSES) {
|
||||
return
|
||||
}
|
||||
@@ -407,6 +563,12 @@ internal fun GlassesSessionCore.resumeAbortedRingHealthPull() {
|
||||
|
||||
/** Ring-worker side of [GlassesSessionCore.requestRingHealthNow]. */
|
||||
internal fun GlassesSessionCore.runRequestedRingHealthPull() {
|
||||
if (monitor.withLock { directRingRole == DIRECT_RING_ROLE_GLASSES }) {
|
||||
// Direct mode used to drop every request here, so the Health app
|
||||
// never got data; the pull has to borrow the phone role instead.
|
||||
startRequestedRingHealthWindow()
|
||||
return
|
||||
}
|
||||
val now = now()
|
||||
monitor.withLock {
|
||||
if (!ringHealthPullRequested) {
|
||||
@@ -417,10 +579,6 @@ internal fun GlassesSessionCore.runRequestedRingHealthPull() {
|
||||
logLine("ring health: on-demand pull skipped, ring not ready")
|
||||
return
|
||||
}
|
||||
if (directRingRole == DIRECT_RING_ROLE_GLASSES) {
|
||||
logLine("ring health: on-demand pull skipped, direct link holds the glasses role")
|
||||
return
|
||||
}
|
||||
if (ringHealthLastRequestedAtMs != 0L
|
||||
&& now - ringHealthLastRequestedAtMs < RING_HEALTH_ON_DEMAND_MIN_INTERVAL_MS) {
|
||||
logLine("ring health: on-demand pull skipped, last one was "
|
||||
@@ -1033,17 +1191,22 @@ internal fun GlassesSessionCore.recordRingConfigResponse(frame: RingProtocol.Fra
|
||||
logLine("ring command $label answered: $result " + frame.describe())
|
||||
}
|
||||
|
||||
/** Apply a [GlassesSessionCore.setDirectRingRole] change by reconnecting the direct link. Ring worker only. */
|
||||
/**
|
||||
* Apply a role change (a [GlassesSessionCore.setDirectRingRole] change, or a
|
||||
* health window opening or closing) by reconnecting the direct link. Ring
|
||||
* worker only.
|
||||
*/
|
||||
internal fun GlassesSessionCore.restartRingLinkForRoleChange() {
|
||||
val role = monitor.withLock {
|
||||
if (!ringRoleReconnectPending) return
|
||||
ringRoleReconnectPending = false
|
||||
ringConnected = false
|
||||
ringNotificationsReady = false
|
||||
ringReconnectAfterMs = 0
|
||||
// Let the old connection end before dialing again; see RING_ROLE_SWITCH_SETTLE_MS.
|
||||
ringReconnectAfterMs = now() + RING_ROLE_SWITCH_SETTLE_MS
|
||||
ringOutbound.clear()
|
||||
dropRingConfigCommandsLocked("role change")
|
||||
directRingRole
|
||||
effectiveRingRoleLocked()
|
||||
}
|
||||
logLine("direct ring: reconnecting to take the $role role")
|
||||
link.disconnect(ringAddress)
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
# R1 live sync, 2026-09-17
|
||||
|
||||
Validated on the connected Pixel 7a and an R1 reporting firmware `2.0.7.0003`.
|
||||
|
||||
## Connection and decoding
|
||||
|
||||
Direct mode was effective. The first connection attempt timed out after 20 seconds;
|
||||
the retry connected, subscribed to both notify characteristics, completed the
|
||||
handshake, and received responses to all five health requests. Pairing was not the
|
||||
reason health measurements were absent.
|
||||
|
||||
The incoming daily records do not have the four-byte footer assumed by PR #26.
|
||||
The rejected HR, SpO2 and activity frame lengths were respectively 37, 33 and 80
|
||||
bytes, matching two one-byte hourly groups, one one-byte hourly group, and eight
|
||||
activity buckets without a footer. Subtracting four bytes also made a one-group
|
||||
HRV page appear to contain one-byte values instead of the actual two-byte values.
|
||||
|
||||
Payload bytes 3–4 are a signed timezone offset in minutes. `10 ff` is EDT's
|
||||
offset of -240; it is not a magic marker. This R1 reports `5c fe`, or -420.
|
||||
The handshake's timezone field now also uses the phone's actual offset.
|
||||
|
||||
The corrected serializers are corroborated by the sibling openCFW checkout at
|
||||
commit `fc1040f1`, particularly `r1_health_encode_daily_u8`,
|
||||
`r1_health_encode_daily_u16`, `r1_activity_encode_daily`, and `r1_sleep_encode`
|
||||
in `r1/src/r1_health.c`. Regression tests use synthetic records matching those
|
||||
layouts rather than checking private biometric captures into the repository.
|
||||
|
||||
After installing the fixes, a live sync decoded four pages and stored 31 samples
|
||||
across heart rate, HRV, SpO2, steps and calories. The fixture files and marker were
|
||||
removed, and `live-marker.json` was present. There was no sleep DATA page in that
|
||||
sync; sleep has not been validated on this ring.
|
||||
|
||||
## Battery
|
||||
|
||||
Device-channel `00:01` returns seven status bytes after the two-byte prefix.
|
||||
The first is battery percentage; the next is the charge-state enum. This matches
|
||||
openCFW's `get_device_status` and `r1_charge_state`. The captured percentage was
|
||||
85%, independently confirmed by the user in the Even app.
|
||||
|
||||
Faceclaw now uses the direct status while the ring link is connected, falling
|
||||
back to the glasses report on disconnect. This does not repair the separate
|
||||
stock ring-to-glasses connection or its cached battery reading.
|
||||
|
||||
## Clock investigation (follow-up)
|
||||
|
||||
Successful decoding does not establish correct chart timestamps. This ring's
|
||||
reported day anchor had nonzero hour/minute/second components; the inherited
|
||||
`anchor + index * interval - clock correction` conversion produced hourly bucket
|
||||
starts at `:47:44`. The relationship between that anchor, current ring time, and
|
||||
the clock changes made by Faceclaw and Even remains unverified. Do not normalize
|
||||
these to midnight or change the clock corrections without further evidence.
|
||||
|
||||
CRC-valid frames are now retained before acknowledgement in the app-private
|
||||
`files/health/ring-frames.jsonl`, with reception time and original bytes. This
|
||||
preserves evidence and permits later reprocessing; it is not yet an automatic
|
||||
replay/import path. The earlier rejected pages were not journaled by the old
|
||||
build, and re-delivery of them is not guaranteed.
|
||||
|
||||
`python3 tools/ring-clock-audit.py <journal.jsonl>` reports the relevant time
|
||||
fields without emitting measurement values. It reads the journal without
|
||||
modifying it. All instants below are UTC, avoiding local display ambiguity.
|
||||
|
||||
| Field | Observed value |
|
||||
| --- | --- |
|
||||
| Phone reception of fresh HR page | Sep 18 04:07:28.792 |
|
||||
| Latest HR timestamp in that page | Sep 18 11:07:25 |
|
||||
| Difference | +25,196.208 seconds (seven hours minus 3.792 seconds) |
|
||||
| Daily anchor, shared across metric pages | Sep 17 12:47:44 |
|
||||
| Timezone in those pages | -420 minutes |
|
||||
| Anchor's local time | 05:47:44, not midnight |
|
||||
| Latest HRV / SpO2 timestamps | Sep 18 03:39:03 / 03:38:51 |
|
||||
|
||||
The handshake explicitly sends `phone Unix seconds - UTC offset`, or UTC +7h
|
||||
in PDT. The fresh HR timestamp is consistent with that incorrect initialization.
|
||||
The older HRV/SpO2 timestamps precede reception and cannot be assumed to have
|
||||
the same error. The unchanged bucket index 20 and non-midnight anchor also
|
||||
indicate that a clock change did not rebuild all existing daily metadata.
|
||||
We cannot infer trustworthy dates for those buckets from the latest HR time.
|
||||
|
||||
The sibling openCFW checkout's `r1/docs/correlation/CLOCK-PRODUCTION-CORRELATION.md`
|
||||
and recovered RTC evidence describe command `00:05` as UTC epoch seconds plus a
|
||||
separate signed timezone offset. The clock applies that offset for local-calendar
|
||||
bucketing. Command `00:0e` is a health-recording setting, not a second clock setter.
|
||||
The inherited comments claiming that UTC+offset and double sleep correction were
|
||||
protocol requirements have therefore been replaced with explicit migration TODOs.
|
||||
|
||||
**Do not silently rewind the live ring.**
|
||||
`r1/docs/correlation/TIME-HEALTH-ROLLOVER-CORRELATION.md` and
|
||||
`r1_health_plan_time_transition` document stock behavior: a backward jump of at
|
||||
least 3,600 seconds requests health-database formatting and synchronization cursor
|
||||
reset. A seven-hour correction can erase history still held only by the ring.
|
||||
The local phone-store backup is `/tmp/faceclaw-health-before-clock.tar`; it
|
||||
preserves received frames and derived records, not every possible unreceived page.
|
||||
No clock correction or historical timestamp rewrite was performed in this follow-up.
|
||||
|
||||
The next controlled test is to finish a health pull, preserve its raw pages, then
|
||||
set `00:05` to actual UTC seconds with the phone's offset still in its separate
|
||||
field. Remove the matching display corrections for new records and keep old
|
||||
ambiguous records archived separately. Verify the command response, fresh HR time
|
||||
against receipt time, and a new daily anchor against local midnight. This test
|
||||
requires permission for the firmware's possible history reset. Sleep clock and
|
||||
duration units still require a real sleep DATA page; no sleep has been observed
|
||||
on this new ring.
|
||||
|
||||
## Remaining initial-review fixes
|
||||
|
||||
- Ring connection, handshake, health waits and page ACKs now run on one dedicated
|
||||
ring worker. GATT locking is per address, so the glasses sender continues while
|
||||
the ring connects or waits for pages. Shutdown interrupts and joins both workers.
|
||||
- Daily sleep totals include all sessions attributed to the wake-up day. The
|
||||
detail view orders their stage blocks chronologically and leaves unrecorded
|
||||
intervals unknown instead of counting them as sleep.
|
||||
- Startup registers the share-intent handler and native user agent once.
|
||||
|
||||
Validation: Android build and full TypeScript check passed; focused health and
|
||||
ring tests passed (36 passed, one pre-existing timezone-specific skip). Installed
|
||||
on the Pixel 7a. The 21:19:58–21:20:08 local-time pull answered all five health
|
||||
requests on the ring worker while the glasses sender delivered and received
|
||||
ACKs for images roughly every 0.8 seconds throughout that interval. Battery
|
||||
remained 85%. The historical timestamp heuristics are still unchanged.
|
||||
@@ -62,7 +62,14 @@ async function buildKotlin(platform, configuration = 'debug') {
|
||||
if (files.length !== 1) throw new Error(`Expected one Kotlin AAR, found: ${files.join(', ')}`);
|
||||
const source = path.join(output, files[0]);
|
||||
const aar = path.join(destination, 'faceclaw-shared.aar');
|
||||
if (!sameContents(source, aar)) cpSync(source, aar);
|
||||
if (!sameContents(source, aar)) {
|
||||
cpSync(source, aar);
|
||||
// NativeScript's buildMetadata task tracks dependency jars by path, not
|
||||
// contents, so a new AAR at the same path leaves the JS metadata stale:
|
||||
// a method added in Kotlin is then "not a function" at runtime. Removing
|
||||
// the task's outputs makes Gradle run it again.
|
||||
rmSync(path.join(root, 'platforms/android/app/src/main/assets/metadata'), { recursive: true, force: true });
|
||||
}
|
||||
} else {
|
||||
const framework = path.join(destination, 'FaceclawKit.xcframework');
|
||||
const source = path.join(kotlin, `shared/build/XCFrameworks/${configuration}/FaceclawKit.xcframework`);
|
||||
|
||||
@@ -7,7 +7,7 @@ const ts = require("typescript");
|
||||
|
||||
// Run the actual live ingest, seed and file-backend modules with NativeScript
|
||||
// files and the Java communicator replaced at their platform boundaries.
|
||||
function liveEnvironment() {
|
||||
function liveEnvironment({ ringProtocol } = {}) {
|
||||
const files = new Map();
|
||||
const cache = new Map();
|
||||
const faults = { append: null, remove: null, write: null };
|
||||
@@ -63,12 +63,12 @@ function liveEnvironment() {
|
||||
module, exports: module.exports, Date,
|
||||
require: (name) => name === "@nativescript/core" ? native : load(path.resolve(path.dirname(filename), name)),
|
||||
console: { log() {}, warn() {} },
|
||||
com: { faceclaw: { app: { FaceclawBleCommunicator: { getActive: () => communicator } } } },
|
||||
com: { faceclaw: { app: { FaceclawBleCommunicator: { getActive: () => communicator }, RingProtocol: ringProtocol } } },
|
||||
}, { filename });
|
||||
return module.exports;
|
||||
}
|
||||
return {
|
||||
files, faults, start, consumed: () => consumed,
|
||||
files, faults, start, record, consumed: () => consumed,
|
||||
load: (name) => load(path.join(__dirname, "../app/health", name)),
|
||||
};
|
||||
}
|
||||
@@ -147,3 +147,66 @@ test("a failed fixture append stays labelled and is purged before live ingest",
|
||||
assert.equal(seed.isFixtureData(), false);
|
||||
assert.equal(env.load("health-store-files").healthStore().sleepSessions().length, 0);
|
||||
});
|
||||
|
||||
test("journaled pages are replayed once, before the live batch, and again after a decoder upgrade", () => {
|
||||
const calls = [];
|
||||
let journalRecords = [];
|
||||
const ringProtocol = {
|
||||
decodeFrameJournal: (text, after) => {
|
||||
calls.push({ text, after });
|
||||
const list = journalRecords.filter((r) => r.receivedAtMs > after);
|
||||
return { size: () => list.length, get: (i) => list[i] };
|
||||
},
|
||||
};
|
||||
const env = liveEnvironment({ ringProtocol });
|
||||
const seed = env.load("health-seed");
|
||||
seed.seedFixturesIfNeeded(2);
|
||||
env.files.set("/health/ring-frames.jsonl", "journal text");
|
||||
// A page the ring sent an hour earlier, never decoded at the time.
|
||||
journalRecords = [{ ...env.record, groups: [{ hourIndex: 1, min: 50, max: 60, avg: 55 }], receivedAtMs: 1000 }];
|
||||
const live = env.load("health-live");
|
||||
const store = env.load("health-store-files").healthStore();
|
||||
|
||||
live.syncLiveRecords();
|
||||
assert.deepEqual(calls.map((c) => [c.text, c.after]), [["journal text", 0]]);
|
||||
assert.equal(seed.isFixtureData(), false);
|
||||
// A wide range: on a DST-change day the fixture record's hour 0 falls before local midnight.
|
||||
const avgs = Array.from(store.samplesInRange(env.start - 86400000, env.start + 2 * 86400000), (s) => s.avg).sort();
|
||||
assert.deepEqual(avgs, [45, 55]);
|
||||
assert.deepEqual(JSON.parse(env.files.get("/health/journal-replay.json")),
|
||||
{ version: 2, throughReceivedAtMs: 1000 });
|
||||
|
||||
// Once per process.
|
||||
live.syncLiveRecords();
|
||||
assert.equal(calls.length, 1);
|
||||
|
||||
// The next process resumes after the cursor...
|
||||
const next = liveEnvironment({ ringProtocol });
|
||||
for (const [name, text] of env.files) next.files.set(name, text);
|
||||
next.load("health-live").syncLiveRecords();
|
||||
assert.equal(calls.at(-1).after, 1000);
|
||||
|
||||
// ...unless the cursor came from an older decoder, which may have skipped pages.
|
||||
const upgraded = liveEnvironment({ ringProtocol });
|
||||
for (const [name, text] of env.files) upgraded.files.set(name, text);
|
||||
upgraded.files.set("/health/journal-replay.json", JSON.stringify({ version: 1, throughReceivedAtMs: 1000 }));
|
||||
upgraded.load("health-live").syncLiveRecords();
|
||||
assert.equal(calls.at(-1).after, 0);
|
||||
});
|
||||
|
||||
test("a failed journal replay is retried on the next sync and never blocks the live batch", () => {
|
||||
let failures = 1;
|
||||
const ringProtocol = {
|
||||
decodeFrameJournal: () => {
|
||||
if (failures-- > 0) throw new Error("decode blew up");
|
||||
return { size: () => 0, get: () => null };
|
||||
},
|
||||
};
|
||||
const env = liveEnvironment({ ringProtocol });
|
||||
env.files.set("/health/ring-frames.jsonl", "journal text");
|
||||
const live = env.load("health-live");
|
||||
assert.equal(live.syncLiveRecords().samplesWritten, 1);
|
||||
assert.equal(env.consumed(), true);
|
||||
live.syncLiveRecords();
|
||||
assert.equal(failures, -1, "replay was not retried");
|
||||
});
|
||||
@@ -31,6 +31,8 @@ public final class RingProtocolSelfTest {
|
||||
testStepsDecode();
|
||||
testSleepDecodeAndIdentities();
|
||||
testDailyWireLayouts();
|
||||
testFirmware23Trailer();
|
||||
testFrameJournalReplay();
|
||||
testDeviceStatus();
|
||||
|
||||
System.out.println();
|
||||
@@ -379,8 +381,96 @@ public final class RingProtocolSelfTest {
|
||||
byte[] activity = stepsBody(anchor, buckets);
|
||||
expect("eight-bucket activity frame is 80 bytes", dataFrame(5, activity).raw.length == 80);
|
||||
expect("activity decodes without footer", RingProtocol.decodeSteps(dataFrame(5, activity), 0).buckets.length == 8);
|
||||
expect("trailing garbage rejected", RingProtocol.decodeSteps(dataFrame(5,
|
||||
Arrays.copyOf(activity, activity.length + 4)), 0) == null);
|
||||
// Four extra bytes are firmware 2.3.x's trailer (testFirmware23Trailer); other lengths are garbage.
|
||||
for (int extra : new int[] {1, 3, 5, 7}) {
|
||||
expect("activity with " + extra + " trailing bytes rejected", RingProtocol.decodeSteps(dataFrame(5,
|
||||
Arrays.copyOf(activity, activity.length + extra)), 0) == null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Firmware 2.3.x appends four bytes to every health page; 2.0.7 did not. */
|
||||
private static void testFirmware23Trailer() {
|
||||
section("firmware 2.3.x four-byte page trailer");
|
||||
long anchor = 1793520000L; // 2026-11-01 00:00 PST, the anchor 2.3.2.0008 sent
|
||||
byte[] trailer = {(byte) 0xad, 0x5e, 0x00, 0x00};
|
||||
|
||||
byte[] hr = withTrailer(hourlyBody(2, anchor, 24037L, 77, 1,
|
||||
new int[][] {{13, 74, 80, 69}, {14, 74, 81, 68}}), trailer);
|
||||
expect("two-hour HR page with trailer is 41 bytes", dataFrame(1, hr).raw.length == 41);
|
||||
RingProtocol.HourlyRecord heart = RingProtocol.decodeHourly(dataFrame(1, hr), 0);
|
||||
expect("HR with trailer decodes", heart != null && heart.groups.length == 2
|
||||
&& heart.current == 77 && heart.anchorUnixSeconds == anchor
|
||||
&& heart.groups[1].hourIndex == 14 && heart.groups[1].max == 81 && heart.groups[1].min == 68);
|
||||
|
||||
byte[] hrv = withTrailer(hourlyBody(2, anchor, 21676L, 54, 2,
|
||||
new int[][] {{13, 65, 65, 65}, {14, 54, 300, 54}}), trailer);
|
||||
expect("two-hour HRV page with trailer is 48 bytes", dataFrame(4, hrv).raw.length == 48);
|
||||
RingProtocol.HourlyRecord variability = RingProtocol.decodeHourly(dataFrame(4, hrv), 0);
|
||||
expect("HRV with trailer keeps two-byte values", variability != null && variability.valueWidth == 2
|
||||
&& variability.current == 54 && variability.groups[1].max == 300);
|
||||
|
||||
byte[] spo2 = withTrailer(hourlyBody(1, anchor, anchor + 70344L, 97, 1,
|
||||
new int[][] {{19, 97, 97, 97}}), trailer);
|
||||
expect("one-hour SpO2 page with trailer is 37 bytes", dataFrame(2, spo2).raw.length == 37);
|
||||
RingProtocol.HourlyRecord oxygen = RingProtocol.decodeHourly(dataFrame(2, spo2), 0);
|
||||
expect("SpO2 with trailer decodes", oxygen != null && oxygen.groups[0].hourIndex == 19 && oxygen.groups[0].avg == 97);
|
||||
|
||||
// No latest-reading prefix, plus the trailer: 9 + 4 bytes around the groups.
|
||||
byte[] offline = new byte[9 + 4 + 4];
|
||||
System.arraycopy(spo2, 0, offline, 0, 9);
|
||||
System.arraycopy(spo2, 14, offline, 9, 4);
|
||||
System.arraycopy(trailer, 0, offline, 13, 4);
|
||||
RingProtocol.HourlyRecord past = RingProtocol.decodeHourly(dataFrame(2, offline), 0);
|
||||
expect("page without latest reading, with trailer, decodes", past != null
|
||||
&& past.current == -1 && past.groups[0].hourIndex == 19);
|
||||
expect("HR with one stray byte rejected",
|
||||
RingProtocol.decodeHourly(dataFrame(1, Arrays.copyOf(hr, hr.length + 1)), 0) == null);
|
||||
|
||||
int[][] buckets = new int[8][4];
|
||||
for (int i = 0; i < buckets.length; i++) buckets[i] = new int[] {80 + i, i * 11, i, 2 * i};
|
||||
byte[] activity = withTrailer(stepsBody(anchor, buckets), trailer);
|
||||
expect("eight-bucket activity page with trailer is 84 bytes", dataFrame(5, activity).raw.length == 84);
|
||||
RingProtocol.StepsRecord steps = RingProtocol.decodeSteps(dataFrame(5, activity), 0);
|
||||
expect("activity with trailer decodes", steps != null && steps.buckets.length == 8
|
||||
&& steps.buckets[7].index == 87 && steps.buckets[7].steps == 77);
|
||||
|
||||
byte[] sleep = withTrailer(sleepBody(1, 1000L, 1000L + 120, 60, 60, 0, 60, 0,
|
||||
new int[][] {{0, 2}, {2, 2}}), trailer);
|
||||
RingProtocol.SleepRecord night = RingProtocol.decodeSleep(dataFrame(6, sleep), 0);
|
||||
expect("sleep with trailer decodes", night != null && night.isRealRecord() && night.segments.length == 2);
|
||||
}
|
||||
|
||||
private static void testFrameJournalReplay() {
|
||||
section("frame journal replay");
|
||||
long anchor = 1793520000L;
|
||||
byte[] hr = withTrailer(hourlyBody(1, anchor, 1L, 70, 1, new int[][] {{13, 70, 75, 65}}),
|
||||
new byte[] {0, 0, 0, 0});
|
||||
byte[] page = dataFrame(1, hr).raw;
|
||||
byte[] rsp = RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_RSP, 1,
|
||||
RingProtocol.CMD_LO_HEALTH, 3, new byte[] {0, 0});
|
||||
byte[] battery = RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_RSP, 0, 1, 4,
|
||||
new byte[] {0x11, 0x22, 82, 2, 1, 0, 0, 0, 0});
|
||||
// The writer's own shape: a blank line, the record, a newline.
|
||||
String journal = "\n{\"receivedAtMs\":100,\"raw\":\"" + RingProtocol.hex(page) + "\"}\n"
|
||||
+ "\n{\"receivedAtMs\":200,\"raw\":\"" + RingProtocol.hex(rsp) + "\"}\n"
|
||||
+ "\n{\"receivedAtMs\":300,\"raw\":\"" + RingProtocol.hex(battery) + "\"}\n"
|
||||
+ "{\"receivedAtMs\":350,\"raw\":\"zz\"}\n"
|
||||
+ "half a line from a failed app{\"receivedAtMs\":\n"
|
||||
+ "\n{\"receivedAtMs\":400,\"raw\":\"" + RingProtocol.hex(page) + "\"}\n";
|
||||
List<RingProtocol.HealthRecord> all = RingProtocol.decodeFrameJournal(journal, 0L);
|
||||
expect("only health DATA pages come back", all.size() == 2);
|
||||
expect("each keeps its journaled receive time",
|
||||
all.get(0).receivedAtMs == 100L && all.get(1).receivedAtMs == 400L);
|
||||
expect("decoded as heart rate", all.get(0) instanceof RingProtocol.HourlyRecord
|
||||
&& ((RingProtocol.HourlyRecord) all.get(0)).groups[0].avg == 70);
|
||||
List<RingProtocol.HealthRecord> later = RingProtocol.decodeFrameJournal(journal, 100L);
|
||||
expect("cursor skips what was already replayed", later.size() == 1 && later.get(0).receivedAtMs == 400L);
|
||||
}
|
||||
|
||||
private static byte[] withTrailer(byte[] body, byte[] trailer) {
|
||||
byte[] out = Arrays.copyOf(body, body.length + trailer.length);
|
||||
System.arraycopy(trailer, 0, out, body.length, trailer.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void testDeviceStatus() {
|
||||
|
||||
@@ -18,6 +18,7 @@ private class FakeRingLink(private val platform: ProtocolPlatform) : SessionLink
|
||||
lateinit var core: GlassesSessionCore
|
||||
private val lock = platform.createLock()
|
||||
private val writesList = ArrayList<String>()
|
||||
private val subscribedList = ArrayList<String>()
|
||||
@Volatile var failAck = false
|
||||
@Volatile var answer = true
|
||||
@Volatile var delayRsp = false
|
||||
@@ -26,6 +27,12 @@ private class FakeRingLink(private val platform: ProtocolPlatform) : SessionLink
|
||||
val writes: List<String>
|
||||
get() = lock.withLock { writesList.toList() }
|
||||
|
||||
/** Every CCCD enabled, in order, across connections. */
|
||||
val subscribed: List<String>
|
||||
get() = lock.withLock { subscribedList.toList() }
|
||||
|
||||
@Volatile var disconnects = 0
|
||||
|
||||
private fun deliver(frame: ByteArray) = core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID, frame)
|
||||
|
||||
private fun page(cmdHi: Int, pageSeq: Int) =
|
||||
@@ -83,9 +90,14 @@ private class FakeRingLink(private val platform: ProtocolPlatform) : SessionLink
|
||||
|
||||
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
|
||||
|
||||
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true
|
||||
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean {
|
||||
lock.withLock { subscribedList.add(characteristicUuid) }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun disconnect(address: String) {}
|
||||
override fun disconnect(address: String) {
|
||||
disconnects++
|
||||
}
|
||||
|
||||
override fun close() {}
|
||||
|
||||
@@ -258,4 +270,106 @@ class RingHealthTransferTest {
|
||||
assertEquals(60, record.groups.single().avg)
|
||||
assertEquals(1000L + 2 * 3600L, record.groups.single().unixSeconds)
|
||||
}
|
||||
/** A Direct-mode (glasses-role) session whose direct link is up. */
|
||||
private fun directSession(): RingSession {
|
||||
val s = RingSession()
|
||||
s.core.monitor.withLock {
|
||||
s.core.directRingRole = DIRECT_RING_ROLE_GLASSES
|
||||
s.core.sessionReady = true
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@Test fun directModePullBorrowsThePhoneRoleAndHandsItBack() {
|
||||
val s = directSession()
|
||||
// Not the first pull this session, so only the request opens the window.
|
||||
s.core.monitor.withLock { s.core.ringHealthLastRequestedAtMs = s.core.now() - 10 * 60_000L }
|
||||
s.core.runRequestedRingHealthPull()
|
||||
assertFalse(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "opened without a request")
|
||||
|
||||
s.core.requestRingHealthNow()
|
||||
s.core.runRequestedRingHealthPull()
|
||||
s.core.monitor.withLock {
|
||||
assertTrue(s.core.ringHealthWindowActive, "request did not open a health window")
|
||||
assertTrue(s.core.ringRoleReconnectPending, "glasses-role link was not dropped")
|
||||
assertEquals(DIRECT_RING_ROLE_PHONE, s.core.effectiveRingRoleLocked())
|
||||
}
|
||||
s.core.restartRingLinkForRoleChange()
|
||||
assertEquals(1, s.link.disconnects)
|
||||
s.core.monitor.withLock {
|
||||
assertFalse(s.core.ringNotificationsReady)
|
||||
assertTrue(s.core.ringReconnectAfterMs > s.core.now(), "redialed before the old link could end")
|
||||
}
|
||||
|
||||
// Phone-role setup: data CCCD only, then the handshake and the pull.
|
||||
s.core.connectRing()
|
||||
assertEquals(listOf(BleProtocol.R1_NOTIFY_CHAR_UUID), s.link.subscribed, "phone role took the legacy CCCD")
|
||||
val requests = RingProtocol.HEALTH_COMMANDS.map { "req:$it" }
|
||||
assertEquals(requests, s.link.writes.filter { it.startsWith("req:") }, "pull did not run")
|
||||
s.core.monitor.withLock {
|
||||
assertFalse(s.core.ringHealthWindowActive, "window left open after the pull")
|
||||
assertTrue(s.core.ringRoleReconnectPending, "link not handed back to the glasses role")
|
||||
assertTrue(s.core.lastRingHealthPullResult.startsWith("completed"), s.core.lastRingHealthPullResult)
|
||||
}
|
||||
// Back in the glasses role: legacy CCCD again, and no further health traffic.
|
||||
s.core.restartRingLinkForRoleChange()
|
||||
s.core.connectRing()
|
||||
assertEquals(listOf(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, BleProtocol.R1_NOTIFY_CHAR_UUID),
|
||||
s.link.subscribed.drop(1), "glasses role not restored")
|
||||
assertEquals(requests, s.link.writes.filter { it.startsWith("req:") }, "glasses-role link pulled")
|
||||
}
|
||||
|
||||
@Test fun directModeWindowWaitsForAnIdleRingAndRespectsItsFloor() {
|
||||
val s = directSession()
|
||||
s.core.monitor.withLock {
|
||||
s.core.ringHealthLastRequestedAtMs = s.core.now() - 10 * 60_000L
|
||||
s.core.lastDirectRingInputAtMs = s.core.now()
|
||||
}
|
||||
s.core.requestRingHealthNow()
|
||||
s.core.runRequestedRingHealthPull()
|
||||
s.core.monitor.withLock {
|
||||
assertFalse(s.core.ringHealthWindowActive, "took the ring away mid-gesture")
|
||||
assertTrue(s.core.ringHealthPullRequested, "deferred request was dropped")
|
||||
s.core.lastDirectRingInputAtMs = s.core.now() - 60_000L
|
||||
}
|
||||
s.core.runRequestedRingHealthPull()
|
||||
assertTrue(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "idle ring did not open a window")
|
||||
|
||||
// A second request inside the floor is dropped rather than bouncing the link again.
|
||||
s.core.monitor.withLock { s.core.endRingHealthWindowLocked("test") }
|
||||
s.core.requestRingHealthNow()
|
||||
s.core.runRequestedRingHealthPull()
|
||||
s.core.monitor.withLock {
|
||||
assertFalse(s.core.ringHealthWindowActive, "window floor ignored")
|
||||
assertFalse(s.core.ringHealthPullRequested, "request inside the floor stayed pending")
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun directModeFirstPullWaitsForTheGlassesAndGivesUpOnAnUnreachableRing() {
|
||||
val s = directSession()
|
||||
s.core.monitor.withLock {
|
||||
s.core.ringConnected = false
|
||||
s.core.ringNotificationsReady = false
|
||||
s.core.sessionReady = false
|
||||
}
|
||||
s.core.runRequestedRingHealthPull()
|
||||
assertFalse(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "opened before the glasses session")
|
||||
s.core.monitor.withLock { s.core.sessionReady = true }
|
||||
s.core.runRequestedRingHealthPull()
|
||||
s.core.monitor.withLock {
|
||||
assertTrue(s.core.ringHealthWindowActive, "no first pull this session")
|
||||
// Nothing set up to drop: the next connection sets up in the phone role.
|
||||
assertFalse(s.core.ringRoleReconnectPending)
|
||||
s.core.ringHealthWindowDeadlineMs = s.core.now() - 1
|
||||
}
|
||||
s.core.expireRingHealthWindow()
|
||||
s.core.monitor.withLock {
|
||||
assertFalse(s.core.ringHealthWindowActive, "window outlived its deadline")
|
||||
assertEquals(DIRECT_RING_ROLE_GLASSES, s.core.effectiveRingRoleLocked())
|
||||
assertTrue(s.core.lastRingHealthPullResult.startsWith("not run"), s.core.lastRingHealthPullResult)
|
||||
}
|
||||
// Not retried until something asks for it.
|
||||
s.core.runRequestedRingHealthPull()
|
||||
assertFalse(s.core.monitor.withLock { s.core.ringHealthWindowActive }, "retried without a request")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user