Merge remote-tracking branch 'origin/main' into g2-case-battery

# Conflicts:
#	native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt
This commit is contained in:
Om Alve committed 2026-11-02 12:02:53 +05:30
commit 046454e8c0
67 files changed
+11373 -155

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { drawHealthCard } = require("../.test-build/app/health/health-card.js");
const { dailySummary } = require("../.test-build/app/health/health-derive.js");
function render(data) {
const draws = [];
const font = { lineHeight: 21, measureText: (text) => text.length * 10 };
const image = { width: 288, height: 144, drawText(font, x, y, text) {
assert.ok(x >= 0 && x + font.measureText(text) <= 288, `horizontal overflow: ${text}`);
assert.ok(y >= 0 && y + font.lineHeight <= 144, `vertical overflow: ${text}`);
draws.push(text);
} };
drawHealthCard(image, data, font, font);
return draws;
}
test("health card distinguishes an observed zero from missing metrics", () => {
const summary = dailySummary([], [], 0);
const text = render({ kind: "live", summary, hasSteps: true, hasCalories: false });
assert.equal(text.filter((value) => value === "0").length, 1);
assert.equal(text.filter((value) => value === "--").length, 5);
});
test("health card prominently labels fixtures without displaying sample measurements", () => {
const text = render({ kind: "fixture" });
assert.ok(text.includes("Sample data"));
assert.ok(!text.includes("HR avg"));
for (const kind of ["empty", "error"]) render({ kind });
});
+212
View File
@@ -0,0 +1,212 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
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({ ringProtocol } = {}) {
const files = new Map();
const cache = new Map();
const faults = { append: null, remove: null, write: null };
const today = new Date();
today.setHours(0, 0, 0, 0);
const start = today.getTime();
let consumed = false;
const record = {
cmdHi: 1,
anchorUnixSeconds: (start + today.getTimezoneOffset() * 60000) / 1000,
groups: [{ hourIndex: 0, min: 40, max: 50, avg: 45 }],
};
const communicator = {
takeRingHealthBatch: () => ({
getWatermark: () => 1,
getRecords: () => ({ size: () => consumed ? 0 : 1, get: () => record }),
}),
clearRingHealthRecordsBelow: () => { consumed = true; return 1; },
};
const native = {
File: {
exists: (name) => files.has(name),
fromPath: (name) => ({
readTextSync: () => files.get(name),
appendTextSync: (text, onError) => {
if (faults.append) return onError(faults.append);
files.set(name, (files.get(name) ?? "") + text);
},
writeTextSync: (text, onError) => {
if (faults.write) return onError(faults.write);
files.set(name, text);
},
removeSync: (onError) => {
if (faults.remove) return onError(faults.remove);
files.delete(name);
},
}),
},
knownFolders: { documents: () => ({ getFolder: () => ({
path: "/health",
getEntitiesSync: () => [...files.keys()].map((name) => ({ path: name, name: path.basename(name) })),
}) }) },
};
function load(filename) {
if (!filename.endsWith(".ts")) filename += ".ts";
if (cache.has(filename)) return cache.get(filename).exports;
const module = { exports: {} };
cache.set(filename, module);
const code = ts.transpileModule(fs.readFileSync(filename, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
vm.runInNewContext(code, {
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 }, RingProtocol: ringProtocol } } },
}, { filename });
return module.exports;
}
return {
files, faults, start, record, consumed: () => consumed,
load: (name) => load(path.join(__dirname, "../app/health", name)),
};
}
test("first live sync removes fixture samples, sleep and rollups from memory and disk", () => {
const env = liveEnvironment();
const seed = env.load("health-seed");
const store = env.load("health-store-files").healthStore();
assert.equal(seed.seedFixturesIfNeeded(2), true);
assert.ok(store.sleepSessions().length > 0);
assert.ok(store.samplesInRange(env.start, env.start + 86400000).length > 1);
env.load("health-live").syncLiveRecords();
assert.equal(seed.isFixtureData(), false);
assert.equal(env.consumed(), true);
assert.equal(store.sleepSessions().length, 0);
const samples = store.samplesInRange(env.start, env.start + 86400000);
assert.equal(samples.length, 1);
assert.equal(samples[0].avg, 45);
const rollups = JSON.parse(env.files.get("/health/rollups.json"));
assert.equal(Object.keys(rollups.days).length, 1);
const day = Object.values(rollups.days)[0];
assert.deepEqual(Object.keys(day), ["heartRate"]);
assert.equal(day.heartRate.count, 1);
});
test("a failed fixture purge retains the badge and ring batch until retry succeeds", () => {
const env = liveEnvironment();
const seed = env.load("health-seed");
seed.seedFixturesIfNeeded(2);
const live = env.load("health-live");
env.faults.remove = new Error("delete failed");
assert.throws(() => live.syncLiveRecords(), /delete failed/);
assert.equal(env.consumed(), false);
assert.equal(seed.isFixtureData(), true);
env.faults.remove = null;
live.syncLiveRecords();
assert.equal(env.consumed(), true);
assert.equal(seed.isFixtureData(), false);
});
test("NativeScript append callback failures retain the batch and retry persists it", () => {
const env = liveEnvironment();
const live = env.load("health-live");
env.faults.append = { message: "disk full" };
assert.throws(() => live.syncLiveRecords(), /disk full/);
assert.equal(env.consumed(), false);
assert.equal([...env.files.keys()].filter((name) => name.includes("samples-")).length, 0);
env.faults.append = null;
assert.equal(live.syncLiveRecords().samplesWritten, 1);
assert.equal(env.consumed(), true);
assert.equal([...env.files.keys()].filter((name) => name.includes("samples-")).length, 1);
});
test("NativeScript rollup write callback failures propagate without consuming the batch", () => {
const env = liveEnvironment();
env.faults.write = { message: "write failed" };
assert.throws(() => env.load("health-live").syncLiveRecords(), /write failed/);
assert.equal(env.consumed(), false);
env.faults.write = null;
assert.equal(env.load("health-live").syncLiveRecords().samplesWritten, 0);
assert.equal(env.consumed(), true);
assert.equal(env.files.has("/health/rollups.json"), true);
assert.equal(env.load("health-seed").hasLiveData(), true);
assert.equal(env.load("health-seed").seedFixturesIfNeeded(), false);
});
test("a failed fixture append stays labelled and is purged before live ingest", () => {
const env = liveEnvironment();
const seed = env.load("health-seed");
env.faults.append = new Error("disk full");
assert.equal(seed.seedFixturesIfNeeded(2), false);
assert.equal(seed.isFixtureData(), true);
env.faults.append = null;
env.load("health-live").syncLiveRecords();
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");
});
+189
View File
@@ -0,0 +1,189 @@
// The 2026-09-10 design revisions, pinned where getting them wrong would be
// silent.
//
// These are not tests of "does it draw" - a chart's appearance is checked by
// rendering it (tools/health-preview.cjs writes a PNG of every surface without
// an emulator). What is worth a test here is the handful of places where the
// revision put a SPECIFIC rule in the code that a later reader would plausibly
// undo:
//
// 1. The two sleep stage orders, which differ ON PURPOSE and therefore look
// exactly like a typo to anyone who meets one without the other.
// 2. The nightly sleep series, which the diverging chart plots - a gap has to
// stay at its own position or every later night shifts a column.
// 3. The stat rows, where "Buckets" was removed because it was an
// implementation detail on screen.
//
// Everything runs on generated fixtures. No real health data is read.
const test = require("node:test");
const assert = require("node:assert/strict");
const { buildFixtures } = require("../.test-build/app/health/health-fixtures.js");
const {
dailySummary,
dailyHypnogram,
sleepNights,
sleepSummary,
stageSeconds,
} = require("../.test-build/app/health/health-derive.js");
const {
SLEEP_LANE_ORDER,
SLEEP_STACK_ORDER,
rangeAverageText,
} = require("../.test-build/app/health/health-chart.js");
const { GLANCE_PAGES } = require("../.test-build/app/health/health-glance.js");
const { startOfLocalDay, DAY_MS, SAMPLE_METRICS } = require("../.test-build/app/health/health-types.js");
test("the two sleep stage orders are stated in opposite directions but agree on screen", () => {
// Week/month/quarter: stacked upward from zero, deep at the bottom.
assert.deepEqual([...SLEEP_STACK_ORDER], ["deep", "rem", "light"]);
// One night: lanes listed downward, awake at the top.
assert.deepEqual([...SLEEP_LANE_ORDER], ["wake", "light", "rem", "deep"]);
// The point worth pinning. The two orders were given in opposite directions
// (one bottom-to-top, one top-to-bottom) and therefore READ as contradictory,
// which is why the brief called the difference out as deliberate. Resolve
// both to the same direction and the three sleep stages land in the SAME
// vertical order: light highest, deep lowest. The only real difference is
// where awake goes - a lane above the others, or a bar below the zero line.
const stackTopToBottom = [...SLEEP_STACK_ORDER].reverse();
const lanesTopToBottomWithoutWake = SLEEP_LANE_ORDER.filter((stage) => stage !== "wake");
assert.deepEqual(
stackTopToBottom,
[...lanesTopToBottomWithoutWake],
"deep sits at the bottom in both views - do not 'fix' one to disagree with the other",
);
// Awake is in the lanes and NOT in the upward stack - it diverges downward.
assert.ok(!SLEEP_STACK_ORDER.includes("wake"));
assert.ok(SLEEP_LANE_ORDER.includes("wake"));
});
test("the nightly sleep series keeps gaps in position", () => {
const now = Date.now();
const today = startOfLocalDay(now);
const startMs = today - 6 * DAY_MS;
const { sleep } = buildFixtures({ days: 7, nowMs: now });
const all = sleepNights(sleep, startMs, today + DAY_MS);
assert.equal(all.length, 7, "one entry per day in the window, filled or not");
// Drop the middle night and check the later ones do not slide left.
const middleDay = all[3].startMs;
const thinned = sleep.filter((session) => session.dayStartMs !== middleDay);
const withGap = sleepNights(thinned, startMs, today + DAY_MS);
assert.equal(withGap.length, 7);
assert.equal(withGap[3].hasData, false, "the removed night is a gap, not a shift");
assert.equal(withGap[3].startMs, middleDay);
assert.deepEqual(
withGap.map((night) => night.startMs),
all.map((night) => night.startMs),
"every night keeps its own day on the axis",
);
});
test("two sessions on one day are summed, not deduped to the longest", () => {
const today = startOfLocalDay(Date.now());
const night = (totalSec, wakeSec) => ({
dayStartMs: today,
startMs: today,
endMs: today,
totalSec,
wakeSec,
remSec: totalSec * 0.2,
lightSec: totalSec * 0.6,
deepSec: totalSec * 0.2,
segments: [],
timeResolved: true,
});
const nights = sleepNights([night(3600, 300), night(1800, 60)], today, today + DAY_MS);
assert.equal(nights.length, 1);
assert.equal(nights[0].wakeSec, 360, "a nap's wake time counts too");
assert.ok(
Math.abs(nights[0].lightSec - (3600 + 1800) * 0.6) < 1e-6,
"stage totals add across both sessions",
);
const summary = dailySummary([], [night(3600, 300), night(1800, 60)], today).sleep;
assert.equal(summary.totalSec, 5400);
assert.equal(summary.wakeSec, 360);
assert.equal(summary.efficiencyPercent, 5400 / 5760 * 100);
assert.equal(dailySummary([], [], today).sleep, null);
});
test("split-night detail includes both blocks and leaves the gap unknown", () => {
const today = startOfLocalDay(Date.now());
const block = (hour, stageId) => ({
dayStartMs: today, startMs: today + hour * 3600000,
endMs: today + (hour + 1) * 3600000,
totalSec: 3600, wakeSec: 0, remSec: 0, lightSec: 3600, deepSec: 0,
segments: [{ stageId, halfMinutes: 120 }], timeResolved: true,
});
const first = block(1, 1), second = block(3, 2);
const bands = dailyHypnogram([second, first, { ...block(1, 3), dayStartMs: today - DAY_MS }], today);
assert.equal(bands.length, 3);
assert.deepEqual(bands[1], { stage: null, seconds: 3600 });
assert.equal(bands[0].seconds, 3600);
assert.equal(bands[2].seconds, 3600);
assert.notEqual(bands[0].stage, bands[2].stage);
assert.equal(dailySummary([], [first, second], today).sleep.totalSec, 7200,
"an unrecorded gap is not counted as sleep");
assert.deepEqual(dailyHypnogram([{ ...first, segments: [] }], today),
[{ stage: null, seconds: 3600 }]);
});
test("a stage's lane duration comes from the named totals", () => {
const now = Date.now();
const { sleep } = buildFixtures({ days: 2, nowMs: now });
const summary = sleepSummary(sleep[0]);
// The four lanes must account for the whole time in bed, which is exactly
// the property that does NOT depend on the raw stage-id mapping.
const summed = SLEEP_LANE_ORDER.reduce(
(total, stage) => total + stageSeconds(stage, summary),
0,
);
assert.ok(
Math.abs(summed - (summary.totalSec + summary.wakeSec)) < 1,
`lanes should sum to time in bed, got ${summed}`,
);
assert.equal(stageSeconds("wake", summary), summary.wakeSec);
});
test("the glance line reads as a range and an average", () => {
assert.equal(
rangeAverageText({ min: 60, max: 98, avg: 72.6, hasData: true }, "bpm"),
"60-98 bpm, avg 73",
);
assert.equal(
rangeAverageText({ min: 0, max: 0, avg: 0, hasData: false }, "bpm"),
"--",
"no data shows a dash, never a zero",
);
// ASCII hyphen only: Terminus has no en dash and would render the default
// char, putting a "?" in the middle of the number.
const text = rangeAverageText({ min: 40, max: 62, avg: 51, hasData: true }, "ms");
for (const char of text) {
assert.ok(char.codePointAt(0) < 128, `"${char}" is outside ASCII`);
}
});
test("HRV reached the daily summary", () => {
const now = Date.now();
const today = startOfLocalDay(now);
const { samples, sleep } = buildFixtures({ days: 2, nowMs: now });
const summary = dailySummary(samples, sleep, today);
assert.ok(summary.hrv, "HRV is on the glance now - Chris revised the spec");
assert.ok(summary.hrv.hasData);
assert.ok(summary.hrv.max >= summary.hrv.min);
});
test("the glasses cursor walks the summary, every parameter, then sleep", () => {
assert.equal(GLANCE_PAGES[0].kind, "overview", "the glance is where it opens");
assert.equal(GLANCE_PAGES[GLANCE_PAGES.length - 1].kind, "sleep");
const walked = GLANCE_PAGES.filter((page) => page.kind === "metric").map((page) => page.metric);
assert.deepEqual(
[...walked].sort(),
[...SAMPLE_METRICS].sort(),
"every measured parameter is reachable by scrolling",
);
});
+490
View File
@@ -0,0 +1,490 @@
// The health feature's logic, pinned where getting it wrong would be silent.
//
// The three things worth a test here are not the arithmetic - they are the
// places where a bug would quietly produce a plausible wrong answer:
//
// 1. The STORE's durability contract. A health record may be the only copy
// that will ever exist (the ring appears to discard backlog it thinks it
// delivered), so "an append never rewrites a file that already holds
// records" and "a re-sync of the same hour corrects rather than
// duplicates" are the properties the whole feature rests on.
// 2. The INGEST rules that decline to guess - an unanchored hourly page is
// dropped, and step buckets do not get invented timestamps.
// 3. SLEEP, where the percentages must come from the named totals (which
// need no stage-id mapping) while only the hypnogram depends on the ids.
//
// Everything runs on generated fixtures. No real health data is read.
const test = require("node:test");
const assert = require("node:assert/strict");
const { HealthStore } = require("../.test-build/app/health/health-store.js");
const { buildFixtures } = require("../.test-build/app/health/health-fixtures.js");
const {
dailySummary,
sleepSummary,
hypnogram,
rollupSeries,
bandIsMeaningful,
formatDuration,
} = require("../.test-build/app/health/health-derive.js");
const { convertRecords, sleepIdentityHolds } = require("../.test-build/app/health/health-ingest.js");
const {
STAGE_NAME_BY_ID,
STAGE_MAPPING_CONFIRMED,
stageNameForId,
} = require("../.test-build/app/health/sleep-stages.js");
const {
startOfLocalDay,
DAY_MS,
HOUR_MS,
TEN_MINUTES_MS,
} = require("../.test-build/app/health/health-types.js");
/** An in-memory backend that also records how each file was touched. */
function memoryBackend() {
const files = new Map();
const ops = [];
return {
ops,
files,
exists: (name) => files.has(name),
read: (name) => files.get(name) ?? null,
append(name, text) {
ops.push({ op: "append", name });
files.set(name, (files.get(name) ?? "") + text);
},
write(name, text) {
ops.push({ op: "write", name });
files.set(name, text);
},
list: () => [...files.keys()],
};
}
const HOUR = 3600000;
function sample(metric, startMs, min, max, avg, total) {
return { metric, startMs, spanMs: HOUR, min, max, avg, total: total ?? avg };
}
// ---------------------------------------------------------------------------
// Storage
test("a stored sample survives a fresh store over the same files", () => {
const backend = memoryBackend();
const first = new HealthStore(backend);
const start = startOfLocalDay(Date.now());
first.ingestSamples([sample("heartRate", start, 55, 90, 70)]);
const second = new HealthStore(backend);
const held = second.samplesInRange(start, start + DAY_MS);
assert.equal(held.length, 1);
assert.equal(held[0].avg, 70);
});
test("a sample file is only ever appended to, never rewritten", () => {
const backend = memoryBackend();
const store = new HealthStore(backend);
const start = startOfLocalDay(Date.now());
for (let hour = 0; hour < 6; hour += 1) {
store.ingestSamples([sample("heartRate", start + hour * HOUR, 50 + hour, 90, 70 + hour)]);
}
const sampleWrites = backend.ops.filter(
(entry) => entry.op === "write" && entry.name.startsWith("samples-"),
);
// The rollup cache is rewritten freely - it is derived. The shards are not.
assert.equal(sampleWrites.length, 0);
assert.ok(backend.ops.some((entry) => entry.op === "append"));
});
test("re-storing an unchanged bucket writes nothing; a changed one corrects it", () => {
const backend = memoryBackend();
const store = new HealthStore(backend);
const start = startOfLocalDay(Date.now());
assert.equal(store.ingestSamples([sample("heartRate", start, 55, 90, 70)]), 1);
// The live poller re-reads the same capped list every 30 minutes; a no-op
// here is what stops that appending a duplicate line forever.
assert.equal(store.ingestSamples([sample("heartRate", start, 55, 90, 70)]), 0);
// The current hour genuinely changes as it fills up. Later line wins.
assert.equal(store.ingestSamples([sample("heartRate", start, 55, 104, 74)]), 1);
const reloaded = new HealthStore(backend);
const held = reloaded.samplesInRange(start, start + DAY_MS);
assert.equal(held.length, 1);
assert.equal(held[0].max, 104);
});
test("a corrupt rollup cache is rebuilt from the shards rather than trusted", () => {
const backend = memoryBackend();
const store = new HealthStore(backend);
const start = startOfLocalDay(Date.now());
store.ingestSamples([sample("heartRate", start, 55, 90, 70), sample("heartRate", start + HOUR, 60, 100, 80)]);
backend.files.set("rollups.json", "{ not json");
const recovered = new HealthStore(backend);
const rollups = recovered.dailyRollups("heartRate", start, start + DAY_MS);
const day = rollups.get(start);
assert.ok(day, "the day should be recovered from the raw shards");
assert.equal(day.min, 55);
assert.equal(day.max, 100);
assert.equal(day.count, 2);
});
test("a single unreadable line does not cost the rest of the file", () => {
const backend = memoryBackend();
const store = new HealthStore(backend);
const start = startOfLocalDay(Date.now());
store.ingestSamples([sample("heartRate", start, 55, 90, 70)]);
const name = [...backend.files.keys()].find((key) => key.startsWith("samples-"));
backend.files.set(name, `${backend.files.get(name)}{ truncated\n`);
store.ingestSamples([sample("heartRate", start + HOUR, 60, 100, 80)]);
const reloaded = new HealthStore(backend);
assert.equal(reloaded.samplesInRange(start, start + DAY_MS).length, 2);
});
// ---------------------------------------------------------------------------
// Ingest: the rules that decline to guess
test("failed sample corrections stay retryable, including a partially stored batch", () => {
const backend = memoryBackend();
const store = new HealthStore(backend);
const first = new Date(2026, 7, 31).getTime();
const second = new Date(2026, 8, 1).getTime();
const original = sample("heartRate", second, 50, 80, 60);
store.ingestSamples([original]);
const append = backend.append;
backend.append = (name, text) => {
if (name === "samples-2026-09.jsonl") throw new Error("disk full");
append(name, text);
};
const batch = [sample("heartRate", first, 50, 90, 70), sample("heartRate", second, 50, 100, 80)];
assert.throws(() => store.ingestSamples(batch), /disk full/);
assert.equal(store.samplesInRange(second, second + DAY_MS)[0].avg, 60);
backend.append = append;
assert.equal(store.ingestSamples(batch), 1, "only the failed shard should need retry");
const reloaded = new HealthStore(backend);
assert.equal(reloaded.samplesInRange(first, second + DAY_MS).length, 2);
assert.equal(reloaded.samplesInRange(second, second + DAY_MS)[0].avg, 80);
});
test("failed sleep appends and corrections do not poison deduplication", () => {
const backend = memoryBackend();
const store = new HealthStore(backend);
const session = buildFixtures({ days: 1, nowMs: Date.now() }).sleep[0];
assert.ok(session);
const append = backend.append;
backend.append = () => { throw new Error("disk full"); };
assert.throws(() => store.ingestSleep([session]), /disk full/);
assert.equal(store.sleepSessions().length, 0);
backend.append = append;
assert.equal(store.ingestSleep([session]), 1);
const correction = { ...session, totalSec: session.totalSec + 60 };
backend.append = () => { throw new Error("disk full"); };
assert.throws(() => store.ingestSleep([correction]), /disk full/);
assert.equal(store.sleepSessions()[0].totalSec, session.totalSec);
backend.append = append;
assert.equal(store.ingestSleep([correction]), 1);
assert.equal(new HealthStore(backend).sleepSessions()[0].totalSec, correction.totalSec);
});
test("retry after a partial append preserves the first sample and sleep record", () => {
const backend = memoryBackend();
const store = new HealthStore(backend);
const start = startOfLocalDay(Date.now());
const row = sample("heartRate", start, 50, 90, 70);
const session = buildFixtures({ days: 1, nowMs: Date.now() }).sleep[0];
const append = backend.append;
backend.append = (name, text) => {
append(name, text.slice(0, 12));
throw new Error("partial append");
};
assert.throws(() => store.ingestSamples([row]), /partial append/);
assert.throws(() => store.ingestSleep([session]), /partial append/);
backend.append = append;
assert.equal(store.ingestSamples([row]), 1);
assert.equal(store.ingestSleep([session]), 1);
const recovered = new HealthStore(backend);
assert.equal(recovered.samplesInRange(start, start + DAY_MS)[0].avg, 70);
assert.equal(recovered.sleepSessions()[0].totalSec, session.totalSec);
});
test("an unanchored hourly page is dropped, not dated", () => {
const result = convertRecords([
{
kind: "hourly",
metric: "heartRate",
anchorMs: null,
groups: [{ hourIndex: 0, avg: 70, max: 90, min: 55 }],
},
]);
assert.equal(result.samples.length, 0);
assert.equal(result.skipped.length, 1);
assert.match(result.skipped[0].why, /anchor/);
});
test("an anchored hourly page dates each group from the anchor", () => {
const anchor = startOfLocalDay(Date.now());
const result = convertRecords([
{
kind: "hourly",
metric: "hrv",
anchorMs: anchor,
groups: [
{ hourIndex: 0, avg: 40, max: 40, min: 40 },
{ hourIndex: 5, avg: 52, max: 55, min: 50 },
],
},
]);
assert.equal(result.samples.length, 2);
assert.equal(result.samples[0].startMs, anchor);
assert.equal(result.samples[1].startMs, anchor + 5 * HOUR_MS);
});
// The index is cracked (2026-09-12): bucket i starts at anchor + i * 10 minutes.
// This test previously asserted the opposite - one day-span total, buckets
// deliberately discarded - which was the honest call while the index was only
// trusted as an identity. It is now the placement contract.
test("steps place each bucket at anchor + index * ten minutes", () => {
const anchor = startOfLocalDay(Date.now());
const result = convertRecords([
{
kind: "steps",
anchorMs: anchor,
buckets: [
{ index: 0, steps: 100, activeCalories: 4, totalCalories: 15 },
{ index: 130, steps: 260, activeCalories: 9, totalCalories: 21 },
],
},
]);
const steps = result.samples.filter((entry) => entry.metric === "steps");
assert.equal(steps.length, 2, "one sample per bucket, not one day total");
assert.equal(steps[0].startMs, anchor);
assert.equal(steps[0].total, 100);
assert.equal(steps[0].spanMs, TEN_MINUTES_MS);
assert.equal(steps[1].startMs, anchor + 130 * TEN_MINUTES_MS);
assert.equal(steps[1].total, 260);
// The day total is now `sum` and ONLY `sum` - `max`/`avg` are per-bucket.
// Every reader was checked against this on 2026-09-12.
assert.equal(
steps.reduce((acc, entry) => acc + entry.total, 0),
360,
);
const calories = result.samples.filter((entry) => entry.metric === "calories");
assert.equal(calories.length, 2);
assert.equal(calories[1].startMs, anchor + 130 * TEN_MINUTES_MS);
assert.equal(calories[1].total, 21);
// Nothing is declined any more - the buckets are placed, not discarded.
assert.equal(result.skipped.length, 0);
});
test("a sleep session is stored with its time marked unresolved", () => {
const result = convertRecords([
{
kind: "sleep",
startTs: 90000,
endTs: 90000 + 21600,
totalSec: 20400,
wakeSec: 1200,
remSec: 3600,
lightSec: 12000,
deepSec: 4800,
segments: [{ stageId: 2, halfMinutes: 720 }],
receivedAtMs: Date.now(),
},
]);
assert.equal(result.sleep.length, 1);
assert.equal(result.sleep[0].timeResolved, false);
assert.equal(result.sleep[0].dayStartMs, startOfLocalDay(Date.now()));
});
// The first real sleep record off the hardware, 2026-09-12, verbatim from
// `files/health/sleep.jsonl` under com.faceclaw.app. It is here as a FROZEN
// known-good: the -8h correction was derived from Chris confirming the window
// two independent ways, and a future change that quietly makes it -4h again
// (or 0h, which is what shipped first) should fail a test rather than wait to
// be noticed in a chart.
const REAL_SLEEP_RECORD = {
kind: "sleep",
startTs: 1789222861,
endTs: 1789233931,
totalSec: 10440,
wakeSec: 630,
remSec: 1620,
lightSec: 5880,
deepSec: 2940,
segments: [
{ stageId: 0, halfMinutes: 21 },
{ stageId: 2, halfMinutes: 42 },
{ stageId: 3, halfMinutes: 36 },
{ stageId: 2, halfMinutes: 40 },
{ stageId: 1, halfMinutes: 36 },
{ stageId: 2, halfMinutes: 42 },
{ stageId: 3, halfMinutes: 62 },
{ stageId: 2, halfMinutes: 46 },
{ stageId: 1, halfMinutes: 18 },
{ stageId: 2, halfMinutes: 26 },
],
receivedAtMs: 1789234000000,
};
test("a clock correction promotes a sleep session to a real placement", () => {
const rawStartMs = REAL_SLEEP_RECORD.startTs * 1000;
// Twice the hourly ring-clock offset, computed the way health-live.ts
// computes it - so this says what the RULE is rather than restating a
// constant that would rot at the November DST change.
const correction = 2 * new Date(rawStartMs).getTimezoneOffset() * 60 * 1000;
const result = convertRecords([{ ...REAL_SLEEP_RECORD, clockCorrectionMs: correction }]);
assert.equal(result.sleep.length, 1);
const night = result.sleep[0];
assert.equal(night.timeResolved, true, "a corrected session is placed, not unresolved");
assert.equal(night.startMs, rawStartMs - correction);
assert.equal(night.endMs, REAL_SLEEP_RECORD.endTs * 1000 - correction);
// The wake-up day, not the day it happened to be received on.
assert.equal(night.dayStartMs, startOfLocalDay(night.endMs));
// The correction must move where the night sits, never how long it was.
assert.equal(night.endMs - night.startMs, 11070 * 1000);
assert.equal(night.totalSec, 10440);
});
test("the real 2026-09-12 record decodes to the window Chris confirmed", (t) => {
// EDT only: the known-good is a wall-clock reading and the assertion is
// meaningless in another zone. Skipped rather than weakened elsewhere.
if (new Date(REAL_SLEEP_RECORD.startTs * 1000).getTimezoneOffset() !== 240) {
t.skip("not EDT");
return;
}
const result = convertRecords([{ ...REAL_SLEEP_RECORD, clockCorrectionMs: 8 * 3600 * 1000 }]);
const night = result.sleep[0];
const local = (ms) => new Date(ms).toLocaleString("sv-SE", { timeZone: "America/New_York" });
assert.equal(local(night.startMs), "2026-09-12 02:21:01");
assert.equal(local(night.endMs), "2026-09-12 05:25:31");
});
// ---------------------------------------------------------------------------
// Sleep
test("stage percentages come from the named totals, not from the stage ids", () => {
const session = {
dayStartMs: startOfLocalDay(Date.now()),
startMs: 0,
endMs: 0,
totalSec: 20000,
wakeSec: 1000,
remSec: 4000,
lightSec: 12000,
deepSec: 4000,
// Deliberately unmappable ids: the percentages must not care.
segments: [{ stageId: 9, halfMinutes: 700 }],
timeResolved: true,
};
const summary = sleepSummary(session);
assert.equal(Math.round(summary.remPercent), 20);
assert.equal(Math.round(summary.lightPercent), 60);
assert.equal(Math.round(summary.deepPercent), 20);
// total / (total + wake) = 20000 / 21000
assert.equal(Math.round(summary.efficiencyPercent), 95);
// ...while the hypnogram, which does depend on the ids, says so.
assert.equal(hypnogram(session)[0].stage, null);
});
test("the stage-id mapping is the one named place, and it is the derived one", () => {
assert.equal(stageNameForId(0), "wake");
assert.equal(stageNameForId(1), "rem");
assert.equal(stageNameForId(2), "light");
assert.equal(stageNameForId(3), "deep");
assert.equal(stageNameForId(4), null);
assert.equal(Object.keys(STAGE_NAME_BY_ID).length, 4);
// Pinned deliberately: flipping this is the confirmation step, and it should
// be a decision someone makes, not something that drifts.
assert.equal(STAGE_MAPPING_CONFIRMED, false);
});
test("no sleep-quality composite is exposed", () => {
const summary = sleepSummary({
dayStartMs: 0, startMs: 0, endMs: 0,
totalSec: 20000, wakeSec: 1000, remSec: 4000, lightSec: 12000, deepSec: 4000,
segments: [], timeResolved: true,
});
const invented = Object.keys(summary).filter((key) => /quality|score/i.test(key));
assert.deepEqual(invented, []);
});
// ---------------------------------------------------------------------------
// Series and fixtures
test("a range with no data comes back as gaps at the right positions", () => {
const start = startOfLocalDay(Date.now());
const points = rollupSeries([sample("heartRate", start + 3 * HOUR, 55, 90, 70)], {
metric: "heartRate",
granularity: "hour",
startMs: start,
endMs: start + DAY_MS,
});
assert.equal(points.length, 24);
assert.equal(points[0].count, 0);
assert.equal(points[3].count, 1);
assert.equal(points[3].avg, 70);
});
test("the band is drawn for heart rate and dropped for a collapsed metric", () => {
const start = startOfLocalDay(Date.now());
const spread = [];
const flat = [];
for (let hour = 0; hour < 12; hour += 1) {
spread.push({ startMs: start + hour * HOUR, spanMs: HOUR, min: 60, max: 92, avg: 74, sum: 74, count: 1 });
flat.push({ startMs: start + hour * HOUR, spanMs: HOUR, min: 97, max: 97, avg: 97, sum: 97, count: 1 });
}
assert.equal(bandIsMeaningful(spread), true);
assert.equal(bandIsMeaningful(flat), false);
});
test("the fixtures reproduce the shapes the real export has", () => {
const now = Date.now();
const { samples, sleep } = buildFixtures({ days: 7, nowMs: now });
const hourly = samples.filter((entry) => entry.metric === "heartRate");
assert.ok(hourly.every((entry) => entry.spanMs === HOUR_MS), "heart rate is hourly");
const stepBuckets = samples.filter((entry) => entry.metric === "steps");
assert.ok(stepBuckets.every((entry) => entry.spanMs === 600000), "steps are ten-minute");
// Heart rate has a real spread; SpO2 mostly does not. Both were measured off
// the export before the generator was written.
const hrSpread = hourly.filter((entry) => entry.max > entry.min).length / hourly.length;
const spo2 = samples.filter((entry) => entry.metric === "spo2");
const spo2Spread = spo2.filter((entry) => entry.max > entry.min).length / spo2.length;
assert.ok(hrSpread > 0.9, `heart rate should nearly always have spread, got ${hrSpread}`);
assert.ok(spo2Spread < 0.15, `SpO2 should rarely have spread, got ${spo2Spread}`);
// Every generated night satisfies the same identity real records satisfy.
for (const night of sleep) {
assert.ok(
sleepIdentityHolds(night),
"segment run must account for exactly the time in bed",
);
}
});
test("the daily summary picks last night and today's own buckets", () => {
const now = Date.now();
const today = startOfLocalDay(now);
const { samples, sleep } = buildFixtures({ days: 3, nowMs: now });
const summary = dailySummary(samples, sleep, today);
assert.equal(summary.dayStartMs, today);
assert.ok(summary.heartRate.hasData);
assert.ok(summary.sleep, "there should be a night attributed to today");
assert.ok(summary.steps >= 0);
});
test("durations format the way the glance prints them", () => {
assert.equal(formatDuration(0), "--");
assert.equal(formatDuration(6 * 3600 + 12 * 60), "6h 12m");
assert.equal(formatDuration(45 * 60), "45m");
});
@@ -0,0 +1,620 @@
package com.faceclaw.app;
import java.util.Arrays;
import java.util.List;
/**
* Standalone self-test for {@link RingProtocol}. No Android APIs and no
* hardware: every byte-manipulation path is exercised against either frames
* copied from the reference capture or synthetic bodies built from the spec's
* field layout.
*
* <p>Run through JavaCompatibilityTest ({@code npm run test:kotlin}), which
* also checks that the Kotlin port keeps the Java-facing API the TypeScript
* health ingest reads.
*
* <p>The captured frames reproduced below are requests and page-ACKs only.
* Those carry a nonce, a command id and a sequence number — no biometric
* values. No captured DATA page appears here, deliberately.
*/
public final class RingProtocolSelfTest {
private static int checks;
private static int failures;
public static void main(String[] args) {
testCrcAndRequestRoundTrip();
testFiveHealthRequests();
testPageAckAgainstCapture();
testParseRejectsGarbage();
testFragmentReassembly();
testHourlyDecode();
testStepsDecode();
testSleepDecodeAndIdentities();
testDailyWireLayouts();
testFirmware23Trailer();
testFrameJournalReplay();
testDeviceStatus();
System.out.println();
System.out.println(failures == 0
? "PASS: all " + checks + " checks"
: "FAIL: " + failures + " of " + checks + " checks");
if (failures != 0) {
throw new AssertionError(failures + " of " + checks + " ring protocol checks failed");
}
}
// ------------------------------------------------------------------
/**
* Rebuild captured request pkt 9166 from its decoded fields alone. If the
* CRC-32C parameters or the header layout are wrong by even one bit this
* cannot reproduce the captured bytes.
*/
private static void testCrcAndRequestRoundTrip() {
section("CRC + request round-trip (captured pkt 9166)");
byte[] built = RingProtocol.buildRequest(
RingProtocol.CHAN_HEALTH,
RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH,
0x06,
0x08ca);
expectHex("pkt 9166", "00db64265a64026406000001010c00ca08", built);
RingProtocol.Frame frame = RingProtocol.parse(built);
expect("parses back", frame != null && frame.crcOk);
expect("chan", frame.chan == RingProtocol.CHAN_HEALTH);
expect("kind REQ", frame.kind == RingProtocol.KIND_REQ);
expect("seq", frame.seq == 0x06);
expect("cmd 01:01", frame.cmdHi == 0x01 && frame.cmdLo == 0x01);
expect("payload is the 2-byte nonce", frame.payload.length == 2);
// A single flipped payload bit must invalidate the CRC.
byte[] tampered = built.clone();
tampered[15] ^= 0x01;
RingProtocol.Frame bad = RingProtocol.parse(tampered);
expect("tampered frame fails CRC", bad != null && !bad.crcOk);
}
/** The five ready-to-send health requests, seq=1, nonce=0. */
private static void testFiveHealthRequests() {
section("five health requests (spec section 9)");
String[][] expected = {
{"heart rate", "00450fe48f64026401000001010c000000"},
{"SpO2", "000d3fd33364026401000002010c000000"},
{"HRV", "00dc30615564026401000004010c000000"},
{"steps", "00e4208c3e64026401000005010c000000"},
{"sleep", "00ac10bb8264026401000006010c000000"},
};
int[] commands = {
RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_HI_SPO2,
RingProtocol.CMD_HI_HRV,
RingProtocol.CMD_HI_STEPS,
RingProtocol.CMD_HI_SLEEP,
};
for (int i = 0; i < commands.length; i++) {
byte[] built = RingProtocol.buildHealthRequest(commands[i], 0x01, 0x0000);
expectHex(expected[i][0], expected[i][1], built);
}
// The convenience burst builder must produce the same first frame and
// then advance the shared sequence counter by one per frame.
List<byte[]> burst = RingProtocol.buildHealthRequestBurst(0x01, 0x0000);
expect("burst has five frames", burst.size() == 5);
expectHex("burst[0] == heart rate", expected[0][1], burst.get(0));
boolean seqRuns = true;
for (int i = 0; i < burst.size(); i++) {
RingProtocol.Frame f = RingProtocol.parse(burst.get(i));
if (f == null || !f.crcOk || f.seq != 0x01 + i) {
seqRuns = false;
}
}
expect("burst sequence numbers run 1..5 and all CRCs are valid", seqRuns);
}
/**
* Rebuild real captured page-ACKs. This is what pins down the two things
* the prose spec got wrong: the payload begins with the usual nonce (so the
* echoed page seq is at offset 6, not 4), and the frame's own SEQ is the
* phone's shared counter rather than the echoed page seq.
*/
private static void testPageAckAgainstCapture() {
section("page ACK 00:7E rebuilt from captured frames");
// seq, nonce, ackedCmdHi, ackedCmdLo, pageSeq, expected hex
Object[][] cases = {
{0x0d, 0x5f49, 0x01, 0x01, 0x03, "005e55d80b6401640d0001007e1600495f02010100030000000000"},
{0x13, 0xdc10, 0x04, 0x01, 0x07, "00a2bae3c4640164130001007e160010dc02040100070000000000"},
{0x17, 0x86e9, 0x02, 0x01, 0x09, "002c006c61640164170001007e1600e98602020100090000000000"},
{0x23, 0x634c, 0x06, 0x01, 0x13, "00b96c8823640164230001007e16004c6302060100130000000000"},
{0x25, 0x46f2, 0x05, 0x01, 0x14, "00474ee8b8640164250001007e1600f24602050100140000000000"},
{0x14, 0x7bc3, 0x05, 0x01, 0x3b, "00f3a5a917640164140001007e1600c37b020501003b0000000000"},
};
for (Object[] c : cases) {
byte[] built = RingProtocol.buildPageAck(
(Integer) c[0], (Integer) c[1], (Integer) c[2], (Integer) c[3], (Integer) c[4]);
expectHex("ack for cmd " + hex2((Integer) c[2]) + ":" + hex2((Integer) c[3])
+ " page seq " + hex2((Integer) c[4]), (String) c[5], built);
}
RingProtocol.Frame f = RingProtocol.parse(RingProtocol.buildPageAck(0x0d, 0x5f49, 0x01, 0x01, 0x03));
expect("ack rides the DEVICE channel", f.chan == RingProtocol.CHAN_DEVICE);
expect("ack kind is ACK", f.kind == RingProtocol.KIND_ACK);
expect("ack command is 00:7e", f.cmdHi == 0x00 && f.cmdLo == 0x7e);
expect("ack header seq differs from echoed page seq", f.seq != (f.payload[6] & 0xff));
expect("echoed page seq is at payload[6]", (f.payload[6] & 0xff) == 0x03);
}
private static void testParseRejectsGarbage() {
section("parser rejects non-frames");
expect("null", RingProtocol.parse(null) == null);
expect("too short", RingProtocol.parse(new byte[8]) == null);
expect("no magic", RingProtocol.parse(new byte[20]) == null);
// A 3-byte ring gesture frame must not look like a header.
expect("gesture frame is not a header",
!RingProtocol.looksLikeHeader(new byte[] {(byte) 0xff, 0x04, 0x01}));
// A frame whose PLEN disagrees with its actual length is rejected.
byte[] frame = RingProtocol.buildHealthRequest(RingProtocol.CMD_HI_HRV, 1, 0);
byte[] truncated = Arrays.copyOf(frame, frame.length - 1);
expect("length/PLEN mismatch rejected", RingProtocol.parse(truncated) == null);
}
/**
* Fragmentation, reproducing the shape the capture actually shows: an
* oversized frame split into a 244-byte FLAG=0x01 head and a headerless
* continuation, with an unrelated complete frame arriving in between.
*/
private static void testFragmentReassembly() {
section("fragment reassembly");
// Build a 252-byte steps-shaped frame: 15 header + 237 payload.
byte[] payload = new byte[237];
for (int i = 0; i < payload.length; i++) {
payload[i] = (byte) (i * 7 + 3);
}
byte[] whole = RingProtocol.buildFrame(
RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA,
RingProtocol.CMD_HI_STEPS, RingProtocol.CMD_LO_HEALTH, 0x15, payload);
expect("test frame is 252 bytes", whole.length == 252);
byte[] head = Arrays.copyOf(whole, 244);
head[0] = (byte) RingProtocol.FLAG_FRAGMENTED;
byte[] continuation = new byte[RingProtocol.CONTINUATION_PREFIX_LEN + (whole.length - 244)];
System.arraycopy(whole, 244, continuation, RingProtocol.CONTINUATION_PREFIX_LEN, whole.length - 244);
expect("continuation is 5 + remaining bytes", continuation.length == 13);
byte[] interleaved = RingProtocol.buildFrame(
RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x01, 0x16, new byte[9]);
RingProtocol.Reassembler reassembler = new RingProtocol.Reassembler();
RingProtocol.Intake first = reassembler.accept(head);
expect("head consumed", first.consumed && first.frame == null);
expect("fragment outstanding", reassembler.hasPending());
RingProtocol.Intake middle = reassembler.accept(interleaved);
expect("interleaved frame still parses while a fragment is pending",
middle.consumed && middle.frame != null && middle.frame.crcOk);
expect("fragment survives the interleaved frame", reassembler.hasPending());
RingProtocol.Intake done = reassembler.accept(continuation);
expect("continuation completes the frame", done.consumed && done.frame != null);
expect("reassembled frame passes CRC", done.frame.crcOk);
expect("reassembled bytes are exact",
Arrays.equals(done.frame.raw, headJoined(head, whole)));
expect("no fragment left outstanding", !reassembler.hasPending());
expect("reassembled payload is intact", Arrays.equals(done.frame.payload, payload));
// Non-protocol traffic must pass straight through untouched.
RingProtocol.Intake gesture = reassembler.accept(new byte[] {(byte) 0xff, 0x04, 0x01});
expect("gesture frame is not consumed", !gesture.consumed);
}
private static byte[] headJoined(byte[] head, byte[] whole) {
byte[] expected = whole.clone();
expected[0] = head[0];
return expected;
}
// ------------------------------------------------------------------
// Synthetic record bodies, built directly from the spec's field layout.
// ------------------------------------------------------------------
private static void testHourlyDecode() {
section("hourly decode (heart rate W=1, HRV W=2, backlog page)");
// Anchored heart-rate page, W=1, three groups.
long anchor = 1788926400L; // 2026-09-09 00:00 local, the capture's anchor
int[][] groups = {{0, 61, 88, 55}, {1, 58, 71, 52}, {2, 63, 90, 57}};
byte[] body = hourlyBody(3, anchor, 12345L, 64, 1, groups);
RingProtocol.Frame frame = dataFrame(RingProtocol.CMD_HI_HEART_RATE, body);
RingProtocol.HourlyRecord hr = RingProtocol.decodeHourly(frame, 0L);
expect("HR decodes", hr != null);
expect("HR width resolved to 1", hr.valueWidth == 1);
expect("HR group count", hr.groups.length == 3);
expect("HR anchor", hr.anchorUnixSeconds == anchor);
expect("HR not backlog", !hr.isBacklog());
expect("HR current", hr.current == 64);
boolean values = true;
for (int i = 0; i < groups.length; i++) {
RingProtocol.HourlyGroup g = hr.groups[i];
values &= g.hourIndex == groups[i][0] && g.avg == groups[i][1]
&& g.max == groups[i][2] && g.min == groups[i][3]
&& g.unixSeconds == anchor + groups[i][0] * 3600L;
}
expect("HR values and hour timestamps round-trip", values);
// HRV uses two-byte values; the width must be resolved, not assumed.
int[][] hrvGroups = {{8, 300, 420, 210}, {9, 275, 380, 190}, {10, 512, 640, 400}};
byte[] hrvBody = hourlyBody(3, anchor, 22222L, 333, 2, hrvGroups);
RingProtocol.HourlyRecord hrv =
RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HRV, hrvBody), 0L);
expect("HRV decodes", hrv != null);
expect("HRV width resolved to 2", hrv.valueWidth == 2);
expect("HRV current", hrv.current == 333);
expect("HRV holds values above 255", hrv.groups[2].max == 640);
// Backlog page: anchor absent. The hour index must survive; the absolute
// time must NOT be invented.
byte[] backlogBody = hourlyBody(3, RingProtocol.UNKNOWN_TIME, 77777L, 60, 1, groups);
RingProtocol.HourlyRecord backlog =
RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HEART_RATE, backlogBody), 0L);
expect("backlog decodes", backlog != null);
expect("backlog flagged", backlog.isBacklog());
expect("backlog anchor unknown", backlog.anchorUnixSeconds == RingProtocol.UNKNOWN_TIME);
boolean noInventedTime = true;
for (RingProtocol.HourlyGroup g : backlog.groups) {
noInventedTime &= g.unixSeconds == RingProtocol.UNKNOWN_TIME;
}
expect("backlog groups carry no invented absolute time", noInventedTime);
expect("backlog keeps raw hour indices",
backlog.groups[0].hourIndex == 0 && backlog.groups[2].hourIndex == 2);
expect("backlog still decodes values", backlog.groups[1].avg == 58);
}
private static void testStepsDecode() {
section("steps decode");
long anchor = 1788926400L;
int[][] buckets = {{0, 120, 4, 16}, {3, 0, 0, 12}, {130, 45, 2, 14}};
byte[] body = stepsBody(anchor, buckets);
RingProtocol.StepsRecord steps =
RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, body), 0L);
expect("steps decode", steps != null);
expect("bucket count", steps.buckets.length == 3);
expect("total steps", steps.totalSteps() == 165);
expect("raw index preserved, including the 130+ jump",
steps.buckets[2].index == 130);
expect("v2/v3 kept as unconfirmed calorie-shaped fields",
steps.buckets[0].calorieLike2 == 4 && steps.buckets[0].calorieLike3 == 16);
expect("steps anchor", steps.anchorUnixSeconds == anchor);
// Length must be exact: a truncated body is a decode failure, not a guess.
byte[] shortBody = Arrays.copyOf(body, body.length - 1);
expect("truncated steps body rejected",
RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, shortBody), 0L) == null);
}
private static void testSleepDecodeAndIdentities() {
section("sleep decode + the spec's arithmetic identities");
// segments: (stage, halfMinutes). Stage sums: 0->10, 1->20, 2->70, 3->25.
int[][] segments = {{0, 4}, {1, 20}, {2, 40}, {0, 6}, {2, 30}, {3, 25}};
int totalHalfMinutes = 125;
int seconds = totalHalfMinutes * 30; // 3750
int wake = 10 * 30; // 300, stage 0
int rem = 20 * 30; // 600, stage 1
int light = 70 * 30; // 2100, stage 2
int deep = 25 * 30; // 750, stage 3
int total = seconds - wake; // 3450
long start = 100000L;
long end = start + seconds;
byte[] body = sleepBody(1, start, end, total, wake, rem, light, deep, segments);
RingProtocol.SleepRecord sleep =
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, body), 0L);
expect("sleep decodes", sleep != null);
expect("real record", sleep.isRealRecord());
expect("segment count", sleep.segments.length == segments.length);
expect("segment stages and durations round-trip",
sleep.segments[2].stage == 2 && sleep.segments[2].halfMinutes == 40);
expect("identity: sum(half_minutes) x 30 == total_time + wake_time",
sleep.totalHalfMinutes() * 30 == sleep.totalTime + sleep.wakeTime);
expect("identity: sum(half_minutes) x 30 == end_ts - start_ts",
sleep.totalHalfMinutes() * 30 == (int) (sleep.endTs - sleep.startTs));
expect("identity: per-stage sums match the four stage totals",
sleep.halfMinutesForStage(0) * 30 == wake
&& sleep.halfMinutesForStage(1) * 30 == rem
&& sleep.halfMinutesForStage(2) * 30 == light
&& sleep.halfMinutesForStage(3) * 30 == deep);
expect("identitiesHold() agrees", sleep.identitiesHold());
expect("uncracked 6-byte field stored raw, not interpreted",
sleep.unknownPrefix.length == 6);
expect("relative timestamps kept as sent",
sleep.startTs == start && sleep.endTs == end);
// The empty end-of-list marker must decode without inventing a session.
byte[] marker = new byte[] {0x11, 0x22, 0x02};
RingProtocol.SleepRecord empty =
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, marker), 0L);
expect("RECSTATE=2 marker decodes", empty != null && !empty.isRealRecord());
expect("marker has no segments", empty.segments.length == 0);
// A declared segment count that does not fill the body is a parse failure.
byte[] broken = body.clone();
broken[32] = (byte) (segments.length + 1);
expect("segment-count mismatch rejected",
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, broken), 0L) == null);
}
// ------------------------------------------------------------------
private static void testDailyWireLayouts() {
section("footer-free daily layouts and timezone anchors");
long anchor = 1789700400L;
byte[] hr = hourlyBody(2, anchor, anchor + 3600, 70, 1,
new int[][] {{0, 70, 80, 60}, {1, 72, 82, 62}});
expect("two-hour HR frame is 37 bytes", dataFrame(1, hr).raw.length == 37);
for (int timezone : new int[] {-420, -240, 0, 330, 840}) {
putLe(hr, 3, timezone, 2);
RingProtocol.HourlyRecord decoded = RingProtocol.decodeHourly(dataFrame(1, hr), 0);
expect("anchor works at timezone " + timezone,
decoded != null && decoded.anchorUnixSeconds == anchor && decoded.groups.length == 2);
}
byte[] spo2 = hourlyBody(1, anchor, anchor, 98, 1, new int[][] {{0, 98, 99, 97}});
expect("one-hour SpO2 frame is 33 bytes", dataFrame(2, spo2).raw.length == 33);
expect("SpO2 decodes without footer", RingProtocol.decodeHourly(dataFrame(2, spo2), 0).groups[0].avg == 98);
byte[] hrv = hourlyBody(1, anchor, anchor, 51, 2, new int[][] {{3, 51, 300, 40}});
RingProtocol.HourlyRecord variability = RingProtocol.decodeHourly(dataFrame(4, hrv), 0);
expect("one-hour HRV retains two-byte values", variability.valueWidth == 2
&& variability.groups[0].hourIndex == 3 && variability.groups[0].max == 300);
// Offline daily pages omit the five-byte latest-reading prefix.
byte[] offline = new byte[9 + 8];
System.arraycopy(hr, 0, offline, 0, 9);
System.arraycopy(hr, 14, offline, 9, 8);
RingProtocol.HourlyRecord past = RingProtocol.decodeHourly(dataFrame(1, offline), 0);
expect("daily page without latest sample decodes", past != null
&& past.current == -1 && past.groups[1].avg == 72);
putLe(offline, 5, 0, 4);
expect("zero day remains unresolved", RingProtocol.anchorUnixSeconds(offline) == RingProtocol.UNKNOWN_TIME);
int[][] buckets = new int[8][4];
for (int i = 0; i < buckets.length; i++) buckets[i] = new int[] {i, i * 10, 1, 2};
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);
// 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() {
section("direct device status battery");
byte[] payload = {0x11, 0x22, 82, 2, 1, 0, 0, 0, 0};
for (int charge = 0; charge <= 3; charge++) {
payload[3] = (byte) charge;
RingProtocol.Frame frame = RingProtocol.parse(RingProtocol.buildFrame(
RingProtocol.CHAN_DEVICE, RingProtocol.KIND_RSP, 0, 1, 1, payload));
RingProtocol.DeviceStatus status = RingProtocol.decodeDeviceStatus(frame);
expect("battery and charge enum " + charge, status != null && status.battery == 82
&& status.charging == (charge == 0 ? -1 : charge == 2 ? 0 : 1));
}
payload[2] = (byte) 255;
expect("invalid battery rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse(
RingProtocol.buildFrame(1, 3, 0, 1, 1, payload))) == null);
expect("wrong channel rejected", RingProtocol.decodeDeviceStatus(dataFrame(1, payload)) == null);
expect("short response rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse(
RingProtocol.buildFrame(1, 3, 0, 1, 1, new byte[2]))) == null);
}
// Synthetic body builders matching the recovered R1 serializers.
// ------------------------------------------------------------------
private static byte[] hourlyBody(int count, long anchor, long tag, int current,
int width, int[][] groups) {
byte[] body = new byte[13 + width + count * (1 + 3 * width)];
body[0] = 0x11;
body[1] = 0x22;
body[2] = (byte) count;
writeAnchor(body, anchor);
putLe(body, 9, tag, 4);
putLe(body, 13, current, width);
int offset = 13 + width;
for (int[] g : groups) {
body[offset++] = (byte) g[0];
putLe(body, offset, g[1], width);
offset += width;
putLe(body, offset, g[2], width);
offset += width;
putLe(body, offset, g[3], width);
offset += width;
}
return body;
}
private static byte[] stepsBody(long anchor, int[][] buckets) {
byte[] body = new byte[9 + buckets.length * 7];
body[0] = 0x33;
body[1] = 0x44;
body[2] = (byte) buckets.length;
writeAnchor(body, anchor);
int offset = 9;
for (int[] b : buckets) {
body[offset] = (byte) b[0];
putLe(body, offset + 1, b[1], 2);
putLe(body, offset + 3, b[2], 2);
putLe(body, offset + 5, b[3], 2);
offset += 7;
}
return body;
}
private static byte[] sleepBody(int recordState, long start, long end, int total, int wake,
int rem, int light, int deep, int[][] segments) {
byte[] body = new byte[34 + segments.length * 3];
body[0] = 0x55;
body[1] = 0x66;
body[2] = (byte) recordState;
for (int i = 3; i < 9; i++) {
body[i] = (byte) (0xA0 + i); // the uncracked 6-byte field
}
putLe(body, 9, 90210L, 4); // the uncracked u32 tag
body[13] = 0x00;
putLe(body, 14, start, 4);
putLe(body, 18, end, 4);
putLe(body, 22, total, 2);
putLe(body, 24, wake, 2);
putLe(body, 26, rem, 2);
putLe(body, 28, light, 2);
putLe(body, 30, deep, 2);
body[32] = (byte) segments.length;
body[33] = 0x00;
int offset = 34;
for (int[] s : segments) {
body[offset] = (byte) s[0];
putLe(body, offset + 1, s[1], 2);
offset += 3;
}
return body;
}
private static void writeAnchor(byte[] body, long anchor) {
if (anchor == RingProtocol.UNKNOWN_TIME) {
return; // six zero bytes = backlog page
}
body[3] = 0x10;
body[4] = (byte) 0xFF;
putLe(body, 5, anchor, 4);
}
private static void putLe(byte[] out, int offset, long value, int width) {
for (int i = 0; i < width; i++) {
out[offset + i] = (byte) ((value >>> (8 * i)) & 0xff);
}
}
private static RingProtocol.Frame dataFrame(int cmdHi, byte[] body) {
byte[] frame = RingProtocol.buildFrame(
RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi,
RingProtocol.CMD_LO_HEALTH, 0x20, body);
return RingProtocol.parse(frame);
}
// ------------------------------------------------------------------
private static void section(String name) {
System.out.println();
System.out.println("-- " + name);
}
private static void expect(String what, boolean ok) {
checks++;
if (!ok) {
failures++;
}
System.out.println(" " + (ok ? "ok " : "FAIL") + " " + what);
}
private static void expectHex(String what, String expectedHex, byte[] actual) {
String actualHex = RingProtocol.hex(actual);
boolean ok = expectedHex.equals(actualHex);
checks++;
if (!ok) {
failures++;
System.out.println(" FAIL " + what);
System.out.println(" expected " + expectedHex);
System.out.println(" actual " + actualHex);
return;
}
System.out.println(" ok " + what + " " + actualHex);
}
private static String hex2(int value) {
return String.format(java.util.Locale.US, "%02x", value & 0xff);
}
}
@@ -11,6 +11,8 @@ class JavaCompatibilityTest {
@Test fun gestures() = FaceclawGestureEventTest.main(emptyArray())
@Test fun resourceCache() = ResourceCacheProtocolTest.main(emptyArray())
@Test fun ringHealthProtocol() = RingProtocolSelfTest.main(emptyArray())
}
class AndroidByteReaderTest {
@@ -0,0 +1,125 @@
package com.faceclaw.app
import kotlin.test.*
class GlassesRingLinkTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun toHex(bytes: ByteArray) = bytes.joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
private val mac = hex("b16a9f2f43dc")
@Test fun macWireBytesAreLeastSignificantFirst() {
assertEquals("b16a9f2f43dc", toHex(assertNotNull(macWireBytes("DC:43:2F:9F:6A:B1"))))
assertNull(macWireBytes(""))
assertNull(macWireBytes("DC:43:2F:9F:6A"))
assertNull(macWireBytes("DC:43:2F:9F:6A:ZZ"))
}
@Test fun disconnectRequestWireShape() {
// commandId=8 magic=0x21 disconnectInfo(7){dev=0, ringMac}
assertEquals("080810213a0a08001206b16a9f2f43dc", toHex(BleProtocol.buildRingDisconnectRequest(0x21, mac)))
}
@Test fun connectRequestWireShape() {
// commandId=6 magic=0x21 ringInfo(5){connectRing=[01], ringMac, ringName="R1"}
assertEquals("08061021" + "2a" + "0f" + "0a0101" + "1206b16a9f2f43dc" + "1a025231",
toHex(BleProtocol.buildRingConnectRequest(0x21, true, mac, "R1".encodeToByteArray())))
}
@Test fun parsesGlassesReportsThroughFraming() {
// A RING_CONNECT_INFO notification: ringInfo{connectRing, ringMac, ringName, connRet=0}.
val info = hex("0a0101") + hex("1206") + mac + hex("1a025231") + hex("2000")
val pb = hex("0806") + hex("1005") + byteArrayOf(0x2a, info.size.toByte()) + info
val frame = BleProtocol.parseFrame(BleProtocol.framePb(pb, BleProtocol.SID_SECURITY_AUTH, 1, 1).single())
val report = assertNotNull(BleProtocol.parseRingConnectInfo(frame.pb))
assertEquals("b16a9f2f43dc", toHex(assertNotNull(report.ringMac)))
assertEquals("R1", report.ringName)
assertEquals(0, report.code)
// even-g2-protocol's captured sid-0x91 "Device Identity": {1:1, 2:19, 3:{1:mac, 2:1}}
val event = hex("08011013" + "1a0a" + "0a06b16a9f2f43dc" + "1001")
val eventFrame = BleProtocol.parseFrame(BleProtocol.framePb(event, BleProtocol.SID_RING_DATA, 1, 1).single())
val ringEvent = assertNotNull(BleProtocol.parseRingDataEvent(eventFrame.pb))
assertEquals("b16a9f2f43dc", toHex(assertNotNull(ringEvent.ringMac)))
assertEquals(1, ringEvent.code)
assertNull(BleProtocol.parseRingConnectInfo(BleProtocol.buildAuthenticationRequest(3)))
}
@Test fun unpairRequestWireShape() {
// commandId=9 magic=0x21 unpairInfo(8){dev=RING(0), ringMac}
assertEquals("0809" + "1021" + "420a" + "0800" + "1206b16a9f2f43dc", toHex(BleProtocol.buildRingUnpairRequest(0x21, mac)))
}
@Test fun ringChecksumMatchesCapturedEvenFrames() {
// Frames from HCI snoops of Even's app (g2-kit-unofficial examples/ring-direct.ts).
assertEquals("00971953f964016401000000080d003f0101", toHex(RingProtocol.buildPairAuth(1)))
assertEquals("00f979f7b164016404000000020c001b64",
toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x02, 4, ByteArray(0))))
assertEquals("002d946c0164026405000001010c002ac6",
toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_REQ, 0x01, 0x01, 5, ByteArray(0))))
assertEquals("00d4c9ba7064016403000200051200807710ff3348bb69",
toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x05, 3, hex("10ff3348bb69"))))
}
@Test fun advStartCarriesBothTargetsLeastSignificantFirst() {
val right = assertNotNull(macWireBytes("EC:D7:82:69:3C:CB"))
val left = assertNotNull(macWireBytes("C4:5A:23:3D:F5:F8"))
val frame = RingProtocol.buildAdvStart(9, right, left)
assertValidRingFrame(frame)
assertEquals("00" + "000a", toHex(frame.copyOfRange(10, 13)))
assertEquals("cb3c6982d7ec" + "f8f53d235ac4", toHex(frame.copyOfRange(17, frame.size)))
assertEquals("ffffffffffff".repeat(2),
toHex(RingProtocol.buildAdvStart(9, ByteArray(6) { 0xff.toByte() }, ByteArray(6) { 0xff.toByte() }).copyOfRange(17, 29)))
}
@Test fun touchSwitchAndRemoveRingAreSets() {
val on = RingProtocol.buildTouchSwitch(2, RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, true)
assertValidRingFrame(on)
assertEquals("02" + "0007", toHex(on.copyOfRange(10, 13)))
assertEquals("0201", toHex(on.copyOfRange(17, on.size)))
assertEquals("0200", toHex(RingProtocol.buildTouchSwitch(2, 2, false).copyOfRange(17, 19)))
val remove = RingProtocol.buildRemoveRingNotify(3)
assertValidRingFrame(remove)
assertEquals("02" + "0082" + "01", toHex(remove.copyOfRange(10, 13)) + toHex(remove.copyOfRange(17, remove.size)))
}
@Test fun legacyGlassesChannelFrames() {
// Bytes from g2-firmware-emulator: the stock G2's pair-auth, the R1's battery
// report (67%, then charging) and its non-target rejection.
assertEquals("00358800", toHex(RingProtocol.LEGACY_GLASSES_PAIR_AUTH))
val idle = assertNotNull(RingProtocol.parseLegacyBattery(hex("00098b004300")))
assertEquals(67, idle.battery)
assertEquals(0, idle.charging)
assertEquals(1, assertNotNull(RingProtocol.parseLegacyBattery(hex("00098b004301"))).charging)
assertNull(RingProtocol.parseLegacyBattery(hex("00098b006500"))) // 101%
assertNull(RingProtocol.parseLegacyBattery(hex("00098b0043")))
assertNull(RingProtocol.parseLegacyBattery(hex("000961000a000013cb0000")))
assertTrue(RingProtocol.isLegacyTargetRejected(hex("00019600")))
assertFalse(RingProtocol.isLegacyTargetRejected(hex("0001960000")))
// Neither is mistaken for input.
assertNull(FaceclawRingEventDecoder.decode(hex("00098b004300")))
assertNull(FaceclawRingEventDecoder.decode(hex("00019600")))
}
@Test fun ringResponseStatusDecodes() {
assertEquals("ok", RingProtocol.responseResult(0x03))
assertEquals("error", RingProtocol.responseResult(0x07))
assertEquals("refused", RingProtocol.responseResult(0x0b))
assertEquals("unsupported", RingProtocol.responseResult(0x0f))
assertNull(RingProtocol.responseResult(0x00))
assertNull(RingProtocol.responseResult(0x02))
}
/** Outer CRC-32C and inner phone checksum both match the bytes. */
private fun assertValidRingFrame(frame: ByteArray) {
val crc32 = (frame[1].toInt() and 0xff) or ((frame[2].toInt() and 0xff) shl 8) or
((frame[3].toInt() and 0xff) shl 16) or ((frame[4].toInt() and 0xff) shl 24)
assertEquals(RingProtocol.crc32(frame, 5, frame.size), crc32)
val args = frame.copyOfRange(17, frame.size)
val checksum = RingProtocol.phoneChecksum(frame[6].toInt(), frame[8].toInt() and 0xff,
frame[10].toInt(), frame[11].toInt(), frame[12].toInt() and 0xff, args)
assertEquals(checksum, (frame[15].toInt() and 0xff) or ((frame[16].toInt() and 0xff) shl 8))
assertEquals(frame.size - 5, (frame[13].toInt() and 0xff) or ((frame[14].toInt() and 0xff) shl 8))
}
}
@@ -0,0 +1,375 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private const val RING = "CC:00:00:00:00:03"
/**
* A ring that answers health requests through the session's real notification
* path: each REQ gets DATA page `cmd*10+1`, then its RSP; the ACK for a page
* ending in 1 triggers page `+1`, so the transfer is ACK-paced like the real
* ring's backlog.
*/
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
@Volatile var requestStarted = false
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) =
deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi,
RingProtocol.CMD_LO_HEALTH, pageSeq, byteArrayOf(0, 0)))
private fun rsp(cmdHi: Int) =
deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_RSP, cmdHi,
RingProtocol.CMD_LO_HEALTH, 0, byteArrayOf(0, 0)))
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
assertEquals(RING, address)
assertEquals(BleProtocol.R1_WRITE_CHAR_UUID, characteristicUuid)
val frame = RingProtocol.parse(frames.single())!!
if (frame.kind == RingProtocol.KIND_ACK) {
if (failAck) return false
val pageSeq = frame.payload[6].toInt() and 0xff
val cmdHi = frame.payload[3].toInt() and 0xff
lock.withLock { writesList.add("ack:$pageSeq") }
// A write longer than the idle timeout: page two arrives only
// after page one's ACK has actually completed.
sleepMs(130)
if (pageSeq % 10 == 1) {
startThread("ring-page", true) {
sleepMs(5)
page(cmdHi, pageSeq + 1)
}
}
} else if (frame.chan == RingProtocol.CHAN_HEALTH && frame.kind == RingProtocol.KIND_REQ) {
requestStarted = true
lock.withLock { writesList.add("req:" + frame.cmdHi) }
if (answer) {
page(frame.cmdHi, frame.cmdHi * 10 + 1)
if (delayRsp) {
startThread("ring-rsp", true) {
sleepMs(20)
rsp(frame.cmdHi)
}
} else {
rsp(frame.cmdHi)
}
}
}
// Device-channel pings between health types are not answered.
return true
}
override fun connect(address: String, timeoutMs: Int): Boolean = true
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 247
override fun discoverServices(address: String, 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) {
disconnects++
}
override fun close() {}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private class RingHost : SessionHost {
@Volatile var journalFails = false
val journal = ArrayList<String>()
override fun postToMain(action: () -> Unit) = action()
override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() }
override fun isPhoneLocked(): Boolean = false
override fun setScreenWakeLock(on: Boolean) {}
override fun isEvenAppActive(): Boolean = false
override fun startWorker(body: () -> Unit) {}
override fun joinWorker(timeoutMs: Long) {}
override fun supportsRingHealth(): Boolean = true
override fun appendRingFrameJournal(line: String) {
if (journalFails) throw IllegalStateException("disk full")
synchronizedAdd(line)
}
private val lock = testPlatform().createLock()
private fun synchronizedAdd(line: String) = lock.withLock { journal.add(line) }
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {}
}
/** A core whose ring link is up, without running the glasses worker. */
private class RingSession {
val platform = testPlatform()
val link = FakeRingLink(platform)
val host = RingHost()
val core = GlassesSessionCore(link, host, FrameTimingsCore(platform), platform,
"AA:00:00:00:00:01", "AA:00:00:00:00:02", RING)
init {
link.core = core
core.ringHealthRspTimeoutMs = 500
core.ringHealthDataIdleMs = 100
core.monitor.withLock {
core.running = true
core.ringConnected = true
core.ringNotificationsReady = true
}
}
fun outboundSize(): Int = core.monitor.withLock { core.ringOutbound.size }
}
class RingHealthTransferTest {
@Test fun shutdownCancelsAnRspWait() {
val s = RingSession()
s.link.answer = false
s.core.ringHealthRspTimeoutMs = 10_000
val done = Latch(1, s.platform)
startThread("ring-pull", true) {
s.core.requestRingHealth()
done.countDown()
}
val deadline = s.platform.elapsedRealtimeMs() + 1000
while (!s.link.requestStarted && s.platform.elapsedRealtimeMs() < deadline) sleepMs(5)
assertTrue(s.link.requestStarted, "no request")
val start = s.platform.elapsedRealtimeMs()
s.core.monitor.withLock {
s.core.running = false
s.core.monitor.signalAll()
}
assertTrue(done.await(300), "ring pull did not stop")
assertTrue(s.platform.elapsedRealtimeMs() - start < 300, "session lock blocked")
}
@Test fun ackPacedPagesDrainBeforeTheNextType() {
val s = RingSession()
s.link.delayRsp = true
assertTrue(s.core.requestRingHealth(), "pull failed")
val expected = RingProtocol.HEALTH_COMMANDS.flatMap { command ->
listOf("req:$command", "ack:" + (command * 10 + 1), "ack:" + (command * 10 + 2))
}
assertEquals(expected, s.link.writes, "premature next type")
// Every intact frame (each page and each RSP) was journaled.
assertEquals(expected.count { it.startsWith("ack:") } + RingProtocol.HEALTH_COMMANDS.size, s.host.journal.size)
}
@Test fun failedAckAbortsAndStaysQueuedForRetry() {
val s = RingSession()
s.link.failAck = true
assertFalse(s.core.requestRingHealth(), "failed ACK completed pull")
assertEquals(1, s.link.writes.size, "advanced after failed ACK")
assertEquals(1, s.outboundSize(), "failed ACK was discarded")
s.link.failAck = false
// The failure paused ring writes; the retry must not touch the link yet.
assertEquals(-1, s.core.flushRingOutbound(), "retried inside the write backoff")
assertEquals(1, s.outboundSize(), "backoff dropped the queued ACK")
s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L }
assertTrue(s.core.awaitRingHealthDataIdle(s.core.ringHealthDataIdleMs), "retry failed")
assertEquals(0, s.outboundSize(), "retry did not drain ACKs")
}
@Test fun writeBackoffGrowsAndResetsOnSuccess() {
val s = RingSession()
s.link.failAck = true
s.core.queueRingPageAck(RingProtocol.parse(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH,
RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE, RingProtocol.CMD_LO_HEALTH, 1, byteArrayOf(0, 0)))!!)
fun pausedForMs() = s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs - s.core.now() }
assertEquals(-1, s.core.flushRingOutbound())
val first = pausedForMs()
s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L }
assertEquals(-1, s.core.flushRingOutbound())
assertTrue(pausedForMs() > first, "backoff did not grow")
s.link.failAck = false
s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L }
assertEquals(1, s.core.flushRingOutbound())
assertEquals(0, s.core.monitor.withLock { s.core.ringWriteFailures }, "success did not reset the backoff")
}
@Test fun missingRspAbortsWithoutAdvancing() {
val s = RingSession()
s.link.answer = false
assertFalse(s.core.requestRingHealth(), "missing RSP completed pull")
assertEquals(1, s.link.writes.size, "advanced without RSP")
}
@Test fun disconnectFailsTheDataWait() {
val s = RingSession()
s.core.monitor.withLock { s.core.ringConnected = false }
assertFalse(s.core.awaitRingHealthDataIdle(100), "disconnect completed transfer")
}
@Test fun unjournaledPageIsNotAcknowledged() {
val s = RingSession()
s.host.journalFails = true
s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID,
RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH, 7, byteArrayOf(0, 0)))
assertEquals(0, s.outboundSize())
}
@Test fun batchWatermarkOnlyClearsWhatWasTaken() {
val s = RingSession()
// A decodable one-group heart-rate page: count 1, tz 0, anchor 1000, then [hour][avg][max][min].
val payload = byteArrayOf(0, 0, 1, 0, 0, 0xe8.toByte(), 0x03, 0, 0, 2, 60, 70, 50)
fun deliver(seq: Int) = s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID,
RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH, seq, payload))
deliver(1)
deliver(2)
val batch = s.core.takeRingHealthBatch()
assertEquals(2, batch.records.size)
assertEquals(2L, batch.watermark)
deliver(3)
assertEquals(2, s.core.clearRingHealthRecordsBelow(batch.watermark))
val rest = s.core.getRingHealthRecords()
assertEquals(1, rest.size)
val record = rest.single() as RingProtocol.HourlyRecord
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")
}
}
@@ -22,6 +22,34 @@ class RingInputTest {
assertEquals(decoded.ringTick, native.ringTick)
}
@Test fun directReportsMapLikeTheGlassesRelay() {
// Frames captured on the direct link (bae80011), 2026-10-06.
val down = assertNotNull(FaceclawRingEventDecoder.decode(hex("000961000a000013cb0000"))).event
assertEquals(BleProtocol.EVENT_RING_PRESS, down.eventType)
assertEquals(BleProtocol.EVENT_SOURCE_RING, down.eventSource)
assertEquals(10, down.ringType)
assertEquals(0xcb13L, down.ringTick)
val tapHold = assertNotNull(FaceclawRingEventDecoder.decode(hex("0009610009020055d60200"))).event
assertEquals(BleProtocol.EVENT_SHORT_THEN_LONG_PRESS, tapHold.eventType)
assertEquals(2, tapHold.ringAux)
assertEquals(0x02d655L, tapHold.ringTick)
val swipe = assertNotNull(FaceclawRingEventDecoder.decode(hex("0009610004350009cc0000"))).event
assertEquals(BleProtocol.EVENT_SCROLL_TOP, swipe.eventType)
assertEquals(0x35, swipe.ringAux)
assertEquals(0x00, swipe.ringSpeed)
// Same mapping as the CFW relay for every wire type (gesture_fwd.c).
val relayed = mapOf(0 to 9, 1 to 0, 2 to 3, 4 to 1, 5 to 2, 8 to 10, 9 to 11, 10 to 14, 3 to 127, 0xff to 127)
for ((wire, sysEvent) in relayed) {
val frame = hex("0009610000abcdefcdab89").also { it[4] = wire.toByte() }
val event = assertNotNull(FaceclawRingEventDecoder.decode(frame)).event
assertEquals(sysEvent, event.eventType, "wire type $wire")
assertEquals(0x89abcdefL, event.ringTick)
}
}
@Test fun legacyAndInvalidExtensionsNeverInventATimestamp() {
assertEquals(-1L, assertNotNull(G2Event.decodePayload(224, hex("08026a041a02080e"))).ringTick)
for (offset in listOf(9,13,14,15,16,20)) {
+10
View File
@@ -58,6 +58,16 @@
"../app/apps/teleprompter/script-tracker.ts",
"../app/apps/nightscout/nightscout-alerts.ts",
"../app/apps/nightscout/missed-bolus-detector.ts",
"../app/health/health-types.ts",
"../app/health/health-derive.ts",
"../app/health/health-store.ts",
"../app/health/health-ingest.ts",
"../app/health/health-fixtures.ts",
"../app/health/sleep-stages.ts",
"../app/health/health-chart.ts",
"../app/health/health-glance.ts",
"../app/health/health-card.ts",
"../app/health/health-phone-chart.ts",
"../app/g2/brightness-curve.ts",
"../app/g2/events.ts",
"../app/apps/t3code/t3-rpc.ts",