forked from Blendman974/faceclaw
Merge branch 'main' of https://github.com/jimrandomh/faceclaw into ring-health-fixes
This commit is contained in:
commit
a2166c6a6c
822 files changed
+79614
-30124
No files matched your search
@@ -0,0 +1,52 @@
|
||||
package com.faceclaw.app;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CompassProtocolTest {
|
||||
private static byte[] hex(String value) {
|
||||
byte[] bytes = new byte[value.length() / 2];
|
||||
for (int i = 0; i < bytes.length; i++) bytes[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
|
||||
return bytes;
|
||||
}
|
||||
private static BleProtocol.CompassEvent parse(byte[] payload) {
|
||||
return parse(payload, BleProtocol.FLAG_NOTIFY);
|
||||
}
|
||||
private static BleProtocol.CompassEvent parse(byte[] payload, int flag) {
|
||||
byte[] frame = BleProtocol.framePb(payload, 8, flag, 15).get(0);
|
||||
return BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame));
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
// Golden packet also checked against the real C encoder in g2flash's host test.
|
||||
byte[] packet = hex("080f1000520308e702a2060c434d010302038c0098badcfe");
|
||||
BleProtocol.CompassEvent event = parse(packet);
|
||||
assert event.headingDegrees == 359 && event.command == 15;
|
||||
assert event.magneticAccuracy == 3 && event.magneticAnomalies == 2;
|
||||
assert event.orientationSource == 3 && event.diagnosticFlags == 0x8c;
|
||||
assert event.sampleTimeMs == 0xfedcba98L; // unsigned 32-bit timestamp through Java long
|
||||
assert parse(packet, BleProtocol.FLAG_NOTIFY_ALT).headingDegrees == 359;
|
||||
assert parse(packet, BleProtocol.FLAG_REQUEST) == null;
|
||||
assert parse(packet, 0) == null;
|
||||
byte[] legacy = Arrays.copyOf(packet, 9);
|
||||
event = parse(legacy);
|
||||
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
|
||||
for (int n = 9; n < packet.length; ++n) {
|
||||
event = parse(Arrays.copyOf(packet, n));
|
||||
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
|
||||
}
|
||||
for (int offset : new int[] {12, 13, 14, 15, 16, 17, 19}) {
|
||||
byte[] invalid = packet.clone(); invalid[offset] = 99;
|
||||
event = parse(invalid);
|
||||
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
|
||||
}
|
||||
packet[15] = packet[16] = (byte)255; packet[17] = 0; packet[18] = 0;
|
||||
event = parse(packet);
|
||||
assert event.magneticAccuracy == -1 && event.magneticAnomalies == -1;
|
||||
assert event.orientationSource == 0 && event.diagnosticFlags == 0;
|
||||
event = parse(hex("08101000"));
|
||||
assert event.command == 16 && event.headingDegrees == -1 && event.diagnosticFlags == -1;
|
||||
event = parse(hex("08111000"));
|
||||
assert event.command == 17 && event.diagnosticFlags == -1;
|
||||
assert parse(hex("080f1000520308e802")) == null; // 360 isn't a heading
|
||||
assert BleProtocol.parseCompassEvent(null) == null;
|
||||
System.out.println("Compass protocol checks passed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.faceclaw.app;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class FaceclawGestureEventTest {
|
||||
private static byte[] hex(String value) {
|
||||
byte[] result = new byte[value.length() / 2];
|
||||
for (int i = 0; i < result.length; ++i)
|
||||
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
|
||||
return result;
|
||||
}
|
||||
private static byte[] pb(byte[] payload) {
|
||||
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
|
||||
return BleProtocol.parseFrame(frame).pb;
|
||||
}
|
||||
/** G2SettingPackage{commandId=3, magic=0, field102=['F','C',1,event,source,0]}: the CFW's wire shape. */
|
||||
private static byte[] packet(int event, int source) {
|
||||
byte[] p = hex("08031000b20606464301000000");
|
||||
p[10] = (byte)event; p[11] = (byte)source;
|
||||
return p;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
// Event codes map to the sys-events a live page would produce.
|
||||
int[][] events = {
|
||||
{2, BleProtocol.EVENT_CLICK},
|
||||
{3, BleProtocol.EVENT_RING_LONG_PRESS},
|
||||
{4, BleProtocol.EVENT_RING_LONG_PRESS_RELEASE},
|
||||
};
|
||||
int[][] sources = {
|
||||
{0, BleProtocol.EVENT_SOURCE_GLASSES_L},
|
||||
{1, BleProtocol.EVENT_SOURCE_GLASSES_R},
|
||||
{4, BleProtocol.EVENT_SOURCE_RING},
|
||||
{7, 0},
|
||||
};
|
||||
for (int[] e : events) for (int[] s : sources) {
|
||||
BleProtocol.FaceclawGestureEvent g = BleProtocol.parseFaceclawGestureEvent(pb(packet(e[0], s[0])));
|
||||
assert g != null && g.eventType == e[1] && g.eventSource == s[1] : e[0] + "/" + s[0];
|
||||
}
|
||||
// The double-tap wake event (1) and unknown codes are not gestures, and the
|
||||
// wake parser does not mistake a gesture for a wake.
|
||||
byte[] wake = packet(1, 0x34); wake[12] = 0x12;
|
||||
assert BleProtocol.parseFaceclawGestureEvent(pb(wake)) == null;
|
||||
assert BleProtocol.parseFaceclawWakeEvent(pb(wake)) == 0x1234;
|
||||
assert BleProtocol.parseFaceclawWakeEventCode(pb(wake)) == 1;
|
||||
// The head-up wake (5) shares the nonce handshake but keeps its own code.
|
||||
byte[] headUp = packet(5, 0x34); headUp[12] = 0x12;
|
||||
assert BleProtocol.parseFaceclawGestureEvent(pb(headUp)) == null;
|
||||
assert BleProtocol.parseFaceclawWakeEvent(pb(headUp)) == 0x1234;
|
||||
assert BleProtocol.parseFaceclawWakeEventCode(pb(headUp)) == BleProtocol.FACECLAW_WAKE_EVENT_HEAD_UP;
|
||||
for (int code : new int[] {2, 3, 4, 6}) {
|
||||
assert BleProtocol.parseFaceclawWakeEvent(pb(packet(code, 1))) == -1;
|
||||
assert BleProtocol.parseFaceclawWakeEventCode(pb(packet(code, 1))) == -1;
|
||||
}
|
||||
for (int code : new int[] {0, 5, 6, 255})
|
||||
assert BleProtocol.parseFaceclawGestureEvent(pb(packet(code, 1))) == null;
|
||||
// Wrong protocol version, wrong magic letters, truncated payloads, plain settings.
|
||||
byte[] bad = packet(2, 1); bad[9] = 2;
|
||||
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
|
||||
bad = packet(2, 1); bad[7] = 'X';
|
||||
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
|
||||
byte[] full = packet(2, 1);
|
||||
for (int n = 0; n < full.length; ++n)
|
||||
assert BleProtocol.parseFaceclawGestureEvent(pb(Arrays.copyOf(full, n))) == null : n;
|
||||
assert BleProtocol.parseFaceclawGestureEvent(pb(hex("08031000"))) == null;
|
||||
assert BleProtocol.parseFaceclawGestureEvent(null) == null;
|
||||
System.out.println("FaceclawGestureEventTest ok");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Android's Java communicator and iOS share the same resource API and wire commands. */
|
||||
public class ResourceCacheProtocolTest {
|
||||
public static void main(String[] args) {
|
||||
ResourceCacheState cache = new ResourceCacheState();
|
||||
CachedResource image = new CachedResource(new byte[]{1, 1, 31});
|
||||
assert cache.prepare(Collections.singletonList(image))[0] == 0;
|
||||
List<byte[]> commands = cache.drainCommands(3600);
|
||||
assert commands.size() == 2 && commands.get(0)[0] == 22;
|
||||
assert Arrays.equals(commands.get(1), new byte[]{21,1,0,0,0,3,0,0,0,0,0,3,0,1,1,31});
|
||||
assert cache.prepare(Collections.singletonList(image))[0] == 0;
|
||||
assert cache.drainCommands(3600).isEmpty();
|
||||
cache.reset();
|
||||
assert cache.prepare(Collections.singletonList(image))[0] == 0;
|
||||
assert cache.drainCommands(3600).get(0)[0] == 22;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.faceclaw.app;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class RingBatteryProtocolTest {
|
||||
private static byte[] hex(String value) {
|
||||
byte[] result = new byte[value.length() / 2];
|
||||
for (int i = 0; i < result.length; ++i)
|
||||
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
|
||||
return result;
|
||||
}
|
||||
private static BleProtocol.RingBatterySnapshot parse(byte[] payload) {
|
||||
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
|
||||
return BleProtocol.parseRingBattery(BleProtocol.parseFrame(frame).pb);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
// Same golden payload as g2flash/tests/ring_battery_test.c.
|
||||
byte[] packet = hex("08031000d206055242010752");
|
||||
BleProtocol.RingBatterySnapshot result = parse(packet);
|
||||
assert result.battery == 82 && result.charging == 1;
|
||||
packet[10] = 3;
|
||||
for (int level = 0; level <= 100; ++level) {
|
||||
packet[11] = (byte)level;
|
||||
result = parse(packet);
|
||||
assert result.battery == level && result.charging == 0;
|
||||
}
|
||||
for (int flags : new int[] {0, 1}) {
|
||||
packet[10] = (byte)flags; packet[11] = (byte)255;
|
||||
result = parse(packet);
|
||||
assert result.battery == -1 && result.charging == -1;
|
||||
}
|
||||
packet = hex("08031000d206055242010752");
|
||||
for (int n = 0; n < packet.length; ++n)
|
||||
assert parse(Arrays.copyOf(packet, n)) == null;
|
||||
for (int offset : new int[] {7, 8, 9, 10, 11}) {
|
||||
byte previous = packet[offset]; packet[offset] = (byte)255;
|
||||
assert parse(packet) == null;
|
||||
packet[offset] = previous;
|
||||
}
|
||||
assert parse(hex("08031000")) == null; // older firmware
|
||||
assert parse(hex("d206055242010252")) == null; // valid without connected
|
||||
assert parse(hex("d206055242010352")).battery == 82;
|
||||
assert parse(hex("d2060552420100ff")).battery == -1;
|
||||
// Invalid unknown value and charging-without-valid must be rejected.
|
||||
assert parse(hex("d206055242010052")) == null;
|
||||
assert parse(hex("d2060552420105ff")) == null;
|
||||
assert parse(hex("d206055242010364")).battery == 100;
|
||||
assert parse(hex("d206055242010365")) == null;
|
||||
assert BleProtocol.parseRingBattery(null) == null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
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();
|
||||
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);
|
||||
expect("trailing garbage rejected", RingProtocol.decodeSteps(dataFrame(5,
|
||||
Arrays.copyOf(activity, activity.length + 4)), 0) == null);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.Collections
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.zip.Inflater
|
||||
import kotlin.test.*
|
||||
|
||||
// Host tests have no Android clock; all other services use the production adapter.
|
||||
internal actual fun testPlatform(): ProtocolPlatform =
|
||||
object : ProtocolPlatform by AndroidProtocolPlatform {
|
||||
override fun elapsedRealtimeMs() = System.nanoTime() / 1_000_000
|
||||
}
|
||||
|
||||
internal actual fun inflateRecords(records: List<ByteArray>): List<ByteArray> {
|
||||
val inflater = Inflater()
|
||||
try {
|
||||
return records.map { record ->
|
||||
if (record[0].toInt() and CfwTransport.RESET_CONTEXT != 0) inflater.reset()
|
||||
val body = record.copyOfRange(5, record.size)
|
||||
if (record[0].toInt() and CfwTransport.COMPRESSED == 0) body
|
||||
else {
|
||||
inflater.setInput(body)
|
||||
val out = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(4096)
|
||||
do {
|
||||
val count = inflater.inflate(buffer)
|
||||
out.write(buffer, 0, count)
|
||||
} while (!inflater.needsInput())
|
||||
out.toByteArray()
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
inflater.end()
|
||||
}
|
||||
}
|
||||
|
||||
class AndroidProtocolTest {
|
||||
@Test
|
||||
fun javaGoldenCorpus() {
|
||||
// SHA-256 of packets emitted by the pre-migration Java implementation.
|
||||
val raw = java.security.MessageDigest.getInstance("SHA-256")
|
||||
val compressed = java.security.MessageDigest.getInstance("SHA-256")
|
||||
val transport = CfwTransport(testPlatform())
|
||||
var state = 123456789
|
||||
try {
|
||||
repeat(120) { i ->
|
||||
val size = intArrayOf(0, 1, 4, 247, 248, 252, 4095, 4096, 8192, 65535)[i % 10]
|
||||
val data =
|
||||
ByteArray(size) {
|
||||
state = state xor (state shl 13)
|
||||
state = state xor (state ushr 17)
|
||||
state = state xor (state shl 5)
|
||||
state.toByte()
|
||||
}
|
||||
if (i % 3 == 0) data.fill((i % 7).toByte())
|
||||
val id = (i * 37) and 255
|
||||
val lenses = 1 + (i / 7) % 3
|
||||
val mtu = intArrayOf(23, 247, 512, 517)[i % 4]
|
||||
if (i % 13 == 0) transport.reset()
|
||||
CfwTransport.frame(data, id, lenses, mtu).forEach { raw.update(it) }
|
||||
transport.encode(data, id, lenses, mtu).forEach { compressed.update(it) }
|
||||
}
|
||||
assertEquals(
|
||||
"d0efdb99ac71763dd29b70fbd0021b80e1cfe514dfc8a60e2a8424892b16c9f5",
|
||||
raw.digest().toHexString(),
|
||||
)
|
||||
assertEquals(
|
||||
"eb5ce0cc6e41b8e84f0d9455f98f3f666b20be0643c3756c5f7aa9d9a66085e2",
|
||||
compressed.digest().toHexString(),
|
||||
)
|
||||
} finally {
|
||||
transport.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writeModeMapping() {
|
||||
assertEquals(
|
||||
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
|
||||
AndroidProtocolPlatform.writeType(GattWriteMode.WITH_RESPONSE),
|
||||
)
|
||||
assertEquals(
|
||||
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,
|
||||
AndroidProtocolPlatform.writeType(ConnectionOptions.WRITE_MODE),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun concurrentAllocationNeverDuplicatesAnInUseId() {
|
||||
val pool = BleMagicPool(testPlatform())
|
||||
val inUse = Collections.synchronizedSet(mutableSetOf<Int>())
|
||||
val executor = Executors.newFixedThreadPool(8)
|
||||
try {
|
||||
val jobs =
|
||||
List(8) {
|
||||
executor.submit {
|
||||
repeat(2000) {
|
||||
val id = pool.allocate()
|
||||
assertTrue(inUse.add(id))
|
||||
Thread.yield()
|
||||
assertTrue(inUse.remove(id))
|
||||
pool.release(1, id, null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs.forEach { it.get(30, TimeUnit.SECONDS) }
|
||||
assertEquals(156, List(156) { pool.allocate() }.toSet().size)
|
||||
} finally {
|
||||
executor.shutdownNow()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal actual fun digest(bytes: ByteArray): String =
|
||||
BinaryEncoding.bytesToHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes))
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import java.util.Locale
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
/** The shared export must match what the Java-era String.format("%+7d") produced. */
|
||||
class FrameTimingsFormatTest {
|
||||
private class FakeClock : ProtocolPlatform by AndroidProtocolPlatform {
|
||||
var nowMs = 5_000L
|
||||
override fun elapsedRealtimeMs(): Long = nowMs
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lineOffsetsMatchJavaFormat() {
|
||||
val clock = FakeClock()
|
||||
val core = FrameTimingsCore(clock, wallClockMs = { 0L }, threadName = { "worker" }, formatWallClock = { "w" }, logInfo = {}, logWarn = {})
|
||||
val offsets = listOf(-1_234_567L, -12L, -1L, 0L, 1L, 42L, 999L, 1_000L, 12_345L, 1_234_567L, 12_345_678L)
|
||||
val root = core.startFrame("input:fmt")
|
||||
for (offset in offsets) {
|
||||
clock.nowMs = 5_000L + offset
|
||||
core.log(root, "o=$offset")
|
||||
}
|
||||
clock.nowMs = 5_000L
|
||||
core.finishFrame(root, "sent")
|
||||
val export = core.buildExport()
|
||||
for (offset in offsets) {
|
||||
val javaLine = String.format(Locale.US, " %+7dms [%s] %s", offset, "worker", "o=$offset")
|
||||
assert(export.contains("\n$javaLine\n")) { "missing <$javaLine> in\n$export" }
|
||||
}
|
||||
assertEquals(2, export.split("\n").count { it.contains("finished: sent") })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.test.Test
|
||||
|
||||
/** Existing wire fixtures also verify the Java API retained by the Kotlin port. */
|
||||
class JavaCompatibilityTest {
|
||||
@Test fun compass() = CompassProtocolTest.main(emptyArray())
|
||||
|
||||
@Test fun ringBattery() = RingBatteryProtocolTest.main(emptyArray())
|
||||
|
||||
@Test fun gestures() = FaceclawGestureEventTest.main(emptyArray())
|
||||
|
||||
@Test fun resourceCache() = ResourceCacheProtocolTest.main(emptyArray())
|
||||
|
||||
@Test fun ringHealthProtocol() = RingProtocolSelfTest.main(emptyArray())
|
||||
}
|
||||
|
||||
class AndroidByteReaderTest {
|
||||
@Test fun repeatedBridgeCrossingsHaveIndependentCursors() {
|
||||
val buffer = java.nio.ByteBuffer.wrap(byteArrayOf(10, 20, 30))
|
||||
val first = AndroidByteReader(buffer)
|
||||
kotlin.test.assertEquals(10, first.get().toInt())
|
||||
kotlin.test.assertEquals(0, buffer.position())
|
||||
val second = AndroidByteReader(buffer)
|
||||
kotlin.test.assertEquals(3, second.remaining())
|
||||
kotlin.test.assertEquals(10, second.get().toInt())
|
||||
kotlin.test.assertEquals(20, first.get().toInt())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user