Add ANCS support to G1

This commit is contained in:
James Babcock committed 2026-11-06 21:47:23 -08:00
1 parent 0cc263c5d2
commit 6e4515afa5
12 files changed
+199 -19

No files matched your search

+11
View File
@@ -32,6 +32,17 @@ test('receives fragmented UTF-8 notifications; pre-existing and modified items d
x.source(8,0,4);x.feed(3,[]);x.details(8);x.feed(3,[]);x.metadata(8);assert.equal(x.changed.at(-1)[1],false)
assert.ok(x.sent.every(p=>p.length<=20))
})
test('a phone that is not sharing ANCS says so and is asked again, and an unknown status restarts',t=>{
const x=setup(t);x.client.stop()
const sent=[],c=new AncsClient(async b=>sent.push([...b]),()=>{})
t.after(()=>c.stop());c.start(5,20)
c.receive(new Uint8Array([65,78,1,0,...le(5),0,0,3,0]))
c.receive(new Uint8Array([65,78,1,0,...le(5),1,0,3,3]))
assert.equal(c.state,'unavailable');assert.match(c.statusMessage,/Share System Notifications/)
const d=new AncsClient(async()=>{},()=>{});t.after(()=>d.stop());d.start(6,20)
d.receive(new Uint8Array([65,78,1,0,...le(6),0,0,3,4]))
assert.equal(d.state,'unavailable');assert.doesNotMatch(d.statusMessage,/Share System Notifications/)
})
test('removal during retrieval cannot resurrect notification',t=>{
const x=setup(t);x.source(7);x.source(7,2);x.details(7);x.feed(3,[])
assert.deepEqual(x.client.read(),[])
+28 -4
View File
@@ -22,6 +22,7 @@ const timings = load('app/native/frame-timings.ts', {});
const LAUNCHER_GRAY = 75;
function fixture() {
const relay = { available: true, starts: 0, client: null, message: undefined };
const observers = new Map(), phoneState = { protectedDataAvailable: true };
let settingsChanged, remoteHost, controller, bridge = null;
let now = 1000, nextTask = 0, screenOn = true, shellOptions;
@@ -107,9 +108,9 @@ function fixture() {
constructor() { super(); bridge = this; }
on(kind, fn) { this.listeners[kind] = fn; return () => { if (this.listeners[kind] === fn) delete this.listeners[kind]; }; }
onStateChange(fn) { return this.on('state', fn); } onRingEvent(fn) { return this.on('ring', fn); }
onWearState(fn) { return this.on('wear', fn); } onBatteryState(fn) { return this.on('battery', fn); } onCaseState(fn) { return this.on('case', fn); } onFirmwareInfo() { return noop(); }
onWearState(fn) { return this.on('wear', fn); } onBatteryState(fn) { return this.on('battery', fn); } onCaseState(fn) { return this.on('case', fn); } onFirmwareInfo(fn) { return this.on('firmware', fn); }
onFrameMetrics() { return noop(); } onPreviewAnimationFrame() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
onAncsAuthorization() { return noop(); } setRequiresAncs() {} ancsRelayAvailable() { return relay.available; } rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {} async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
emitState(phase, status = phase) { if (phase === 'connected' || phase === 'disconnected') this.phase = phase; this.listeners.state?.({ phase, status }); }
emitRing(input) { this.listeners.ring?.(input); }
@@ -148,7 +149,10 @@ function fixture() {
'../ui/shell/voice-activity': { voiceActivity: { setActive() {}, isActive: () => false, subscribe: () => () => {} } },
'../native/faceclaw-communicator.ios': { FaceclawCommunicatorBridge, resolveIosPeripherals: async addresses => addresses },
'../native/preview-display.ios': { PreviewDisplayTarget },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; start() {} stop() {} stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../g1/firmware/g1v0-image': { G1V0_IMAGE: { version: '0.5.65' } },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; constructor() { relay.client = this; }
start() { this.state = 'starting'; relay.starts++; } stop(message) { this.state = 'disconnected'; relay.message = message; }
stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../native/nightscout-bridge': { nightscoutBridge: { async start() {}, async stop() {} } },
'../native/weather': { weatherBridge: { setSessionActive() {} } },
'./glance-host': { GlanceHost }, './events': events,
@@ -214,10 +218,30 @@ function fixture() {
}
async function phone(type, origin = 'ring') { controller.gesture(type, origin); await render(); }
async function connect() { await controller.connect(); await render(); }
return { controller, shell, battery, remoteHost, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers,
return { relay, controller, shell, battery, remoteHost, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers,
get shellOptions() { return shellOptions; }, registered, inProcessApps,
get bridge() { return bridge; }, connect, wear: wearing => bridge.emitWear(wearing), settingsChanged: () => settingsChanged(), sent, previews, received, boardStats, hardware, phone, advance, render };
}
test('a link that comes back asks for the notification relay again; a G1 without one is told to update', async () => {
const f = fixture();
await f.connect();
const firmware = { leftVersion: 'g1v0 0.5.65', rightVersion: 'g1v0 0.5.65', extension: 'Faceclaw/38' };
f.bridge.listeners.firmware(firmware);
assert.equal(f.relay.starts, 1);
// Connected and running: nothing to do.
f.bridge.emitState('connected');
assert.equal(f.relay.starts, 1);
// The firmware's relay ended with the link, so the client must not go on thinking it's ready.
f.bridge.emitState('retrying', 'Reconnecting');
assert.equal(f.relay.client.state, 'disconnected');
f.bridge.emitState('connected');
assert.equal(f.relay.starts, 2);
f.bridge.emitState('retrying', 'Reconnecting');
f.relay.available = false;
f.bridge.emitState('connected');
assert.equal(f.relay.starts, 2);
assert.match(f.relay.message, /firmware 0\.5\.65/);
});
const assertBlank = pixels => assert.ok(pixels.every(p => p === 0));
const assertBoard = pixels => {
assert.equal(pixels[48 * 640 + 270], 200);
@@ -132,6 +132,11 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
val leftArm = FakeG1Arm(true)
val rightArm = FakeG1Arm(false)
@Volatile var hasDisplayPath = true
/** HELLO's bit for the notification relay, the characteristic behind it, and what reaches it. */
@Volatile var hasAncsRelay = false
@Volatile var ancsCharacteristicMissing = false
val ancsSubscribed = ArrayList<String>()
val ancsWrites = ArrayList<Pair<String, ByteArray>>()
/** Out of the case, or the OS said no: no bond can be made. */
@Volatile var pairingRefused = false
private val out = ArrayList<Pair<String, ByteArray>>()
@@ -176,8 +181,13 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean =
characteristicUuid == G1Ble.EVT_CHAR_UUID
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean {
if (characteristicUuid == G1Ble.ANCS_CHAR_UUID && !ancsCharacteristicMissing) {
lock.withLock { ancsSubscribed.add(address) }
return true
}
return characteristicUuid == G1Ble.EVT_CHAR_UUID
}
override fun requestBond(address: String) {
if (!pairingRefused) lock.withLock { arm(address).bonded = true }
@@ -200,6 +210,10 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
assertTrue(frames.all { it.size <= 182 }, "writes must fit the MTU")
for (f in frames) packet(address, a, f)
}
G1Ble.ANCS_CHAR_UUID -> {
assertEquals(GattWriteMode.WITH_RESPONSE, mode, "the arm's refusals come back as ATT errors")
lock.withLock { for (f in frames) ancsWrites.add(address to f) }
}
else -> throw AssertionError("write to $characteristicUuid")
}
return true
@@ -220,7 +234,7 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
body[3] = 63
body[4] = (if (a.left) 1 else 0).toByte()
body[5] = (2 or 64).toByte()
body[6] = (if (a.left) 0 else 4).toByte()
body[6] = ((if (a.left) 0 else 4) or (if (hasAncsRelay) 8 else 0)).toByte()
reply(address, op, tag, 0, body)
}
G1Protocol.OP_FC_INFO -> if (hasDisplayPath) {
@@ -488,6 +502,79 @@ class G1SessionTest {
}
}
@Test
fun aRelayFirmwareIsListenedToOnTheRightArmOnly() {
val s = G1Session()
val frames = ArrayList<ByteArray>()
val lock = testPlatform().createLock()
s.glasses.hasAncsRelay = true
s.core.setRawFrameTap { frame -> lock.withLock { frames.add(frame) } }
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.ready() }, s.tail())
assertTrue(s.core.ancsRelayAvailable())
assertEquals(listOf(RIGHT), s.glasses.lock.withLock { s.glasses.ancsSubscribed.toList() })
// A command goes to the relay's characteristic; a G2's would go to its command characteristic.
val start = byteArrayOf(0x41, 0x4e, 1, 0, 9, 0, 0, 0)
assertTrue(s.core.writeRawPacket("R", start))
val written = s.glasses.lock.withLock { s.glasses.ancsWrites.single() }
assertEquals(RIGHT, written.first)
assertTrue(written.second.contentEquals(start))
// A frame reaches the client untouched, and isn't taken for an event; a stray one doesn't reach it.
val frame = byteArrayOf(0x41, 0x4e, 1, 0, 9, 0, 0, 0, 0, 0, 3, 1)
s.core.onNotification(RIGHT, G1Ble.ANCS_CHAR_UUID, frame)
s.core.onNotification(LEFT, G1Ble.ANCS_CHAR_UUID, frame)
s.core.onNotification(RIGHT, G1Ble.ANCS_CHAR_UUID, byteArrayOf(1, 2, 3))
s.core.onNotification(RIGHT, G1Ble.EVT_CHAR_UUID.uppercase(), byteArrayOf(0x41, 0x4e, 1, 0, 9, 0, 0, 0, 0, 0, 3))
lock.withLock {
assertEquals(1, frames.size, "only the right arm's relay frames")
assertTrue(frames[0].contentEquals(frame))
}
} finally {
s.core.disconnect()
}
}
@Test
fun theRelayIsAvailableOnlyWithFirmwareAHostThatListensAndTheCharacteristic() {
// Android: no client, so nothing to subscribe for, whatever the firmware has.
val android = G1Session()
android.glasses.hasAncsRelay = true
try {
assertTrue(android.core.start())
assertTrue(awaitTrue(5_000) { android.ready() }, android.tail())
assertFalse(android.core.ancsRelayAvailable())
assertEquals(emptyList(), android.glasses.lock.withLock { android.glasses.ancsSubscribed.toList() })
} finally {
android.core.disconnect()
}
// Firmware before the relay still runs Faceclaw, and doesn't get a subscription it can't answer.
val old = G1Session()
old.core.setRawFrameTap { }
try {
assertTrue(old.core.start())
assertTrue(awaitTrue(5_000) { old.ready() }, old.tail())
assertFalse(old.core.ancsRelayAvailable())
assertEquals(emptyList(), old.glasses.lock.withLock { old.glasses.ancsSubscribed.toList() })
} finally {
old.core.disconnect()
}
// The OS still has the layout from before the update: the session goes on without it.
val stale = G1Session()
stale.glasses.hasAncsRelay = true
stale.glasses.ancsCharacteristicMissing = true
stale.core.setRawFrameTap { }
try {
assertTrue(stale.core.start())
assertTrue(awaitTrue(5_000) { stale.ready() }, stale.tail())
assertFalse(stale.core.ancsRelayAvailable())
} finally {
stale.core.disconnect()
}
}
@Test
fun aSecondFrameIsADeltaThatCostsLittle() {
val s = G1Session()
@@ -921,7 +1008,11 @@ class G1ProtocolTest {
val hello = assertNotNull(G1Protocol.parseHello(body))
assertEquals("0.5.62", hello.version)
assertTrue(hello.mic)
assertFalse(hello.ancs, "firmware before the relay")
assertTrue(hello.leftArm && hello.panelOk && hello.encrypted && hello.inCase)
body[6] = 8
assertTrue(assertNotNull(G1Protocol.parseHello(body)).ancs)
assertFalse(assertNotNull(G1Protocol.parseHello(body)).mic)
assertFalse(hello.safeMode)
body[0] = 4
assertNull(G1Protocol.parseHello(body), "protocol 4 is not this firmware")