Refactor Java to shared kotlin

This commit is contained in:
James Babcock committed 2026-09-18 22:48:20 -07:00
1 parent bc8e80c533
commit 68810197a8
173 files changed
+9855 -6252

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,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,58 @@
package com.faceclaw.app;
import java.lang.reflect.*;
import java.util.*;
public class TextureCacheProtocolTest {
static int u16(byte[] b, int p) { return (b[p]&255) | (b[p+1]&255)<<8; }
static int u32(byte[] b, int p) { return u16(b,p) | u16(b,p+2)<<16; }
public static void main(String[] args) throws Exception {
TextureCacheState cache = new TextureCacheState();
byte[] pixels = new byte[255*255];
for (int i=0;i<pixels.length;i++) pixels[i]=(byte)(i%15+1);
ImageAtlas.Entry big = new ImageAtlas.Entry(255,255,pixels);
for (int i=0;i<3;i++) assert cache.ensureImage(i,big)>=0;
ImageAtlas.Entry tiny = new ImageAtlas.Entry(1,1,new byte[]{15});
int imageOffset = cache.ensureImage(100,tiny);
assert imageOffset>65535;
GlyphAtlas.Glyph glyph = new GlyphAtlas.Glyph(1,1,0,1,0,null,new byte[]{15});
int glyphOffset = cache.ensureGlyph(42,'A',glyph);
int table = cache.fontTableOffset(42);
assert table>65535 && glyphOffset==table+96*4;
byte[] memory = new byte[262144];
for (byte[] upload: cache.drainUploadPayloads(3600)) {
assert upload[0]==18;
int pos=1;
while (pos<upload.length) {
int offset=u32(upload,pos), n=u16(upload,pos+4);
System.arraycopy(upload,pos+6,memory,offset,n); pos+=6+n;
}
assert pos==upload.length;
}
assert memory[imageOffset]==1 && memory[imageOffset+2]==0x1f;
assert u32(memory,table+('A'-32)*4)==glyphOffset;
assert !cache.hasPendingUploads();
// Exercise the production planner encoders with offsets above 64 KiB.
Class<?> selected=Class.forName("com.faceclaw.app.TexturePlanner$Selected");
Constructor<?> ctor=selected.getDeclaredConstructors()[0]; ctor.setAccessible(true);
Object image=ctor.newInstance(SurfaceCompositor.ScreenDraw.image(100,321,123),null,tiny,321,15);
Method encode=TexturePlanner.class.getDeclaredMethod("encodeImageDraw",TextureCacheState.class,selected);
encode.setAccessible(true);
byte[] draw=(byte[])encode.invoke(null,cache,image);
assert draw.length==10 && draw[0]==19 && u32(draw,1)==imageOffset;
assert u16(draw,5)==321 && u16(draw,7)==123 && draw[9]==31;
Object letter=ctor.newInstance(SurfaceCompositor.ScreenDraw.glyph(42,'A',321,123,255),glyph,null,321,15);
Method runs=TexturePlanner.class.getDeclaredMethod("buildRuns",TextureCacheState.class,List.class,List.class);
runs.setAccessible(true); List<byte[]> out=new ArrayList<>();
runs.invoke(null,cache,Collections.singletonList(letter),out);
byte[] run=out.get(0);
assert run.length==12 && run[0]==20 && u32(run,1)==table;
assert u16(run,5)==321 && u16(run,7)==123 && run[9]==31 && run[10]==1 && run[11]=='A';
int id=200;
while (cache.ensureImage(id++,big)>=0) {}
int before=cache.usedBytes();
assert cache.ensureImage(id,big)==-1 && cache.usedBytes()==before;
cache.reset(); assert cache.usedBytes()==0 && !cache.hasPendingUploads();
assert cache.ensureImage(id,tiny)==0;
}
}
@@ -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,27 @@
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 textureCache() = TextureCacheProtocolTest.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())
}
}