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

@@ -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)) {