forked from Blendman974/faceclaw
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
@@ -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