Refactor Kotlin for iOS commonality

This commit is contained in:
James Babcock committed 2026-09-22 19:55:08 -07:00
1 parent 587364e5e6
commit c3a0ba9f56
31 files changed
+2780 -964

No files matched your search

-142
View File
@@ -1,142 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const p = require('../.test-build/app/g2/ble-protocol.js');
const { StockConnection, OTA_WRITE, OTA_NOTIFY, decodeOtaAcks } = require('../.test-build/app/g2/stock-connection.js');
const { firmwareCrc, validateFirmware, flashLensImage } = require('../.test-build/app/g2/firmware-ota.js');
const { createFlashPrompt, flashPromptSelection } = require('../.test-build/app/g2/flash-prompt-protocol.js');
const hex = bytes => Buffer.from(bytes).toString('hex');
function fixture() {
const sizes = [9000, 20, 20, 20, 20], image = new Uint8Array(0x40 + 5 * 16 + sizes.reduce((n, size) => n + size + 128, 0));
const view = new DataView(image.buffer), u32 = (off, value) => view.setUint32(off, value, true);
u32(8, 5); let offset = 0x40 + 5 * 16;
sizes.forEach((size, index) => {
u32(0x40 + index * 16 + 4, offset); u32(offset + 8, size);
image.set(Buffer.from(index ? `ota/part${index}.bin` : 'ota/s200_firmware_ota.bin'), offset + 48);
image.fill(index + 1, offset + 128, offset + 128 + size);
if (!index) { u32(offset + 128, size); u32(offset + 128 + 0x14, 0x00438000); }
const crc = firmwareCrc(image.subarray(offset + 128, offset + 128 + size));
u32(offset + 12, crc); u32(0x40 + index * 16 + 12, crc); offset += size + 128;
});
return image;
}
class Transport {
listeners = new Set(); writes = []; messages = []; chunks = []; seq = 0; held = false; respond = null; closed = [];
onEvent(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
emit(event) { for (const fn of this.listeners) fn(event); }
async resolveDevices() { return { left: 'L', right: 'R' }; }
async connect() { return { characteristics: [p.G2_WRITE, p.G2_NOTIFY, OTA_WRITE, OTA_NOTIFY], maxWrite: 60 }; }
async subscribe() {}
stopScan() {}
disconnect(id) { this.closed.push(id); this.emit({ kind: 'disconnected', identifier: id }); }
notify(id, sid, payload, characteristic = p.G2_NOTIFY, flag = 0) {
this.emit({ kind: 'notification', identifier: id, characteristic, data: hex(p.concat(...p.frameMessage(payload, sid, flag, 10))) });
}
async write(id, characteristic, bytes) {
this.writes.push({ id, characteristic, bytes });
if (bytes[5] === 1) this.chunks = [];
this.chunks.push(bytes.subarray(8));
if (bytes[5] !== bytes[4]) return;
const all = p.concat(...this.chunks), payload = all.slice(0, -2);
assert.equal(p.crc16(payload), all.at(-2) | all.at(-1) << 8);
const message = { id, characteristic, sid: bytes[6], seq: bytes[2], payload };
this.messages.push(message);
if (this.respond) return this.respond(message);
if (this.held) return;
if (characteristic === OTA_WRITE) {
if (message.sid === 0xc0 && payload[0] === 2) { this.seq = message.seq; return; }
if (message.sid === 0xc1) assert.equal(message.seq, this.seq, 'marker/data sequence must match');
this.notify(id, 0xc0, new Uint8Array([message.sid === 0xc1 ? 2 : payload[0], 0]), OTA_NOTIFY);
} else {
this.notify(id, message.sid, p.concat(p.integer(1, p.readInteger(payload, 1)), p.integer(2, p.readInteger(payload, 2)), p.bytes(3, new Uint8Array())));
}
}
}
async function connection(t, transport = new Transport()) {
const link = new StockConnection(transport); t.after(() => link.close());
await link.resolve({ left: 'a', right: 'b', ring: '' }); await link.connect('left', true);
return { link, transport };
}
test('OTA validator checks CRCs, bounds, overlap and the main-app preamble before transfer', () => {
const image = fixture(), segments = validateFirmware(image);
assert.equal(segments.length, 5);
const corrupt = image.slice(); corrupt[segments[0].offset + 200] ^= 1;
assert.throws(() => validateFirmware(corrupt), /CRC32C/);
assert.throws(() => validateFirmware(image.slice(0, -1)), /truncated/);
const bad = image.slice(), view = new DataView(bad.buffer);
view.setUint32(0x44, 0xfffffff0, true); assert.throws(() => validateFirmware(bad), /bounds/);
const overlap = image.slice(); new DataView(overlap.buffer).setUint32(0x54, segments[0].offset, true);
assert.throws(() => validateFirmware(overlap), /overlap/);
const wrongLoad = image.slice(), w = new DataView(wrongLoad.buffer), main = segments[0];
w.setUint32(main.offset + 128 + 0x14, 0, true);
const crc = firmwareCrc(wrongLoad.subarray(main.offset + 128, main.offset + 128 + main.size));
w.setUint32(main.offset + 12, crc, true); w.setUint32(0x4c, crc, true);
assert.throws(() => validateFirmware(wrongLoad), /preamble/);
});
test('OTA framing streams every verified byte in 4KB blocks with shared marker/data sequences', async t => {
const { link, transport } = await connection(t); await link.authenticate('left');
const image = fixture(), segments = validateFirmware(image), progress = [];
await flashLensImage(link, 'left', image, segments, value => progress.push(value), () => {}, async () => {});
const controls = transport.messages.filter(m => m.sid === 0xc0);
assert.equal(controls[0].payload[0], 0);
assert.equal(controls.filter(m => m.payload[0] === 1).length, 5);
assert.equal(controls.filter(m => m.payload[0] === 3).length, 5);
const streamed = p.concat(...transport.messages.filter(m => m.sid === 0xc1).map(m => m.payload));
assert.deepEqual(streamed, p.concat(...segments.map(s => image.slice(s.offset + 128, s.offset + 128 + s.size))));
assert.equal(progress.at(-1).bytesSent, progress.at(-1).bytesTotal);
assert.ok(transport.writes.every(w => w.bytes.length <= 60));
});
test('OTA retries NAKed blocks and failed END verification, but never accepts a rejected FILE_CHECK', async () => {
const image = fixture(), segments = validateFirmware(image); let blockAttempts = 0, endAttempts = 0, checks = 0;
const fake = { check() {}, async exchange(_role, _sid, payload, _match, _timeout, _write, _notify, _flag, _seq, data) {
const op = payload[0]; let status = 0;
if (op === 1) checks++;
if (op === 2 && ++blockAttempts === 1) status = 1;
if (op === 3 && ++endAttempts === 1) status = 2;
return { payload: new Uint8Array([op, status]) };
} };
await flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {});
assert.equal(checks, 6); assert.equal(blockAttempts, 11);
let dataWrites = 0;
fake.exchange = async (_role, _sid, payload, ...args) => { if (args.at(-1)) dataWrites++; return { payload: new Uint8Array([payload[0], payload[0] === 1 ? 4 : 0]) }; };
await assert.rejects(flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {}), /failed after 3 attempts/);
assert.equal(dataWrites, 0);
});
test('onboarding requests ignore wrong peers, magic and pre-encryption authentication failures', async t => {
const { link, transport } = await connection(t); let resolved = false;
transport.respond = message => {
const magic = p.readInteger(message.payload, 2);
const good = p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, new Uint8Array()));
transport.notify('stranger', p.SID.auth, good);
transport.notify('R', p.SID.auth, good);
transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, p.integer(1, 1))));
transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic + 1), p.bytes(3, new Uint8Array())));
setImmediate(() => { assert.equal(resolved, false); transport.notify('L', p.SID.auth, good); });
};
await link.authenticate('left'); resolved = true;
});
test('OTA ACK parsing rejects bad CRC and truncation; cancellation rejects an outstanding transaction', async t => {
const { link, transport } = await connection(t); transport.held = true;
const payload = new Uint8Array([2, 0]), packet = p.frameMessage(payload, 0xc0, 0, 1)[0];
assert.equal(decodeOtaAcks(packet)[0].payload[1], 0);
assert.deepEqual(decodeOtaAcks(packet.slice(0, -1)), []);
packet[8] ^= 1; assert.deepEqual(decodeOtaAcks(packet), []);
const pending = link.exchange('left', 0xc0, new Uint8Array([0]), m => m.command === 0, 8000, OTA_WRITE, OTA_NOTIFY, 0);
link.close(); await assert.rejects(pending, /Cancelled/);
assert.equal(transport.listeners.size, 0);
});
test('stock confirmation keeps No first and accepts only a confirmed flashmenu selection', () => {
const page = createFlashPrompt(42, 'Warning'); const body = p.readBytes(page, 3);
const list = p.readBytes(body, 2), label = p.readBytes(body, 3);
assert.equal(p.readInteger(list, 3), 280); assert.equal(p.readInteger(label, 4), 130);
assert.equal(p.readString(list, 10), 'flashmenu'); assert.equal(p.readString(label, 12), 'Warning');
const event = (index, type = 0, name = 'flashmenu') => ({ sid: 0xe0, flag: 1,
payload: p.bytes(13, p.bytes(1, p.concat(p.bytes(2, new Uint8Array(Buffer.from(name))), p.integer(4, index), p.integer(5, type)))) });
assert.equal(flashPromptSelection(event(0)), false); assert.equal(flashPromptSelection(event(1)), true);
assert.equal(flashPromptSelection(event(1, 1)), null); assert.equal(flashPromptSelection(event(1, 0, 'other')), null);
});
@@ -0,0 +1,314 @@
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.allocPointerTo
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.usePinned
import kotlinx.cinterop.value
import platform.Foundation.NSTemporaryDirectory
import platform.posix.AI_NUMERICHOST
import platform.posix.AI_NUMERICSERV
import platform.posix.SOCK_STREAM
import platform.posix.addrinfo
import platform.posix.close
import platform.posix.connect
import platform.posix.freeaddrinfo
import platform.posix.getaddrinfo
import platform.posix.recv
import platform.posix.send
import platform.posix.socket
private var nextPort = 43000 + (currentTimeMillis() % 9000).toInt()
/** Binds the next free loopback port; returns the listener and its port. */
private fun bindFreePort(): Pair<RemoteInputListener, Int> {
repeat(50) {
val port = nextPort++
val listener = runCatching { IosLocalServerPort.bind("127.0.0.1", port) }.getOrNull() ?: return@repeat
return listener to port
}
error("no free loopback port")
}
/** Blocking POSIX client: connects to loopback, sends [request], reads until the peer closes. */
private fun loopbackExchange(port: Int, request: ByteArray, readTimeoutMs: Int = 8000): ByteArray = memScoped {
val hints = alloc<addrinfo>()
hints.ai_flags = AI_NUMERICHOST or AI_NUMERICSERV
hints.ai_socktype = SOCK_STREAM
val resolved = allocPointerTo<addrinfo>()
check(getaddrinfo("127.0.0.1", port.toString(), hints.ptr, resolved.ptr) == 0)
val info = resolved.value!!.pointed
val fd = socket(info.ai_family, SOCK_STREAM, 0)
check(fd >= 0)
try {
check(connect(fd, info.ai_addr, info.ai_addrlen) == 0) { "connect failed" }
request.usePinned { check(send(fd, it.addressOf(0), request.size.toULong(), 0) == request.size.toLong()) }
val out = ByteSink()
val buffer = ByteArray(4096)
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + readTimeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
val n = buffer.usePinned { recv(fd, it.addressOf(0), buffer.size.toULong(), 0) }
if (n <= 0L) break
out.write(buffer, 0, n.toInt())
if (out.toByteArray().last() == '\n'.code.toByte()) break
}
out.toByteArray()
} finally {
freeaddrinfo(resolved.value)
close(fd)
}
}
/** Minimal loopback HTTP/1.1 server for the NSURLSession facades; one request per connection. */
private class LoopbackHttpServer(private val handler: (path: String, headers: Map<String, String>) -> Reply) {
class Reply(val status: Int, val headers: List<Pair<String, String>>, val pieces: List<ByteArray>, val pieceDelayMs: Long = 0)
private val listener: RemoteInputListener
val port: Int
val requests = ArrayList<Map<String, String>>()
private val lock = IosProtocolPlatform.createLock()
init {
val bound = bindFreePort()
listener = bound.first
port = bound.second
startThread("loopback-http", true) {
while (!listener.isClosed) {
val connection = listener.accept() ?: continue
startThread("loopback-http-conn", true) { serve(connection) }
}
}
}
fun url(path: String) = "http://127.0.0.1:$port$path"
fun close() = listener.close()
fun requestsFor(path: String): List<Map<String, String>> = lock.withLock { requests.filter { it["path"] == path } }
private fun serve(connection: RemoteInputConnection) {
try {
val head = ByteSink()
while (true) {
val b = connection.readByte(5000)
if (b < 0) return
head.write(b)
val bytes = head.toByteArray()
val n = bytes.size
if (n >= 4 && bytes[n - 4] == '\r'.code.toByte() && bytes[n - 3] == '\n'.code.toByte() &&
bytes[n - 2] == '\r'.code.toByte() && bytes[n - 1] == '\n'.code.toByte()) break
}
val lines = head.toByteArray().decodeToString().split("\r\n").filter { it.isNotEmpty() }
val path = lines.first().split(' ')[1]
val headers = lines.drop(1).associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() }
val bodyLength = headers["content-length"]?.toIntOrNull() ?: 0
repeat(bodyLength) { connection.readByte(5000) }
lock.withLock { requests.add(headers + ("path" to path)) }
val reply = handler(path, headers)
val total = reply.pieces.sumOf { it.size }
val response = buildString {
append("HTTP/1.1 ${reply.status} X\r\n")
for ((name, value) in reply.headers) append("$name: $value\r\n")
append("Content-Length: $total\r\nConnection: close\r\n\r\n")
}
connection.write(response.encodeToByteArray())
for (piece in reply.pieces) {
connection.write(piece)
if (reply.pieceDelayMs > 0) sleepMs(reply.pieceDelayMs)
}
} catch (ignored: Exception) {
} finally {
connection.close()
}
}
}
private fun waitUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(20)
}
return condition()
}
private class RecordingSseListener : FaceclawSseListener {
private val lock = IosProtocolPlatform.createLock()
val lines = ArrayList<String>()
var httpError: Pair<Int, String>? = null
var failure: String? = null
var completed = false
val finished: Boolean get() = lock.withLock { completed || httpError != null || failure != null }
override fun onLine(line: String?) { lock.withLock { lines.add(line ?: "") } }
override fun onHttpError(code: Int, body: String?) { lock.withLock { httpError = code to (body ?: "") } }
override fun onComplete() { lock.withLock { completed = true } }
override fun onFailure(message: String?) { lock.withLock { failure = message ?: "" } }
}
private class RecordingDownloadListener : FaceclawModelDownloaderListener {
private val lock = IosProtocolPlatform.createLock()
var progress = 0
var done: String? = null
var error: String? = null
val finished: Boolean get() = lock.withLock { done != null || error != null }
override fun onProgress(bytesDownloaded: Long, totalBytes: Long) { lock.withLock { progress++ } }
override fun onDone(path: String?) { lock.withLock { done = path } }
override fun onError(message: String?) { lock.withLock { error = message } }
}
class IosNetworkingTest {
private val immediate: (() -> Unit) -> Unit = { it() }
/** Like the main queue: never runs on the caller's thread, so the session's lock is not re-entered. */
private val hop: (() -> Unit) -> Unit = { action -> startThread("test-dispatch", true, action) }
@Test
fun remoteInputRoundTripsOverLoopbackAndTimesOut() {
val (probe, port) = bindFreePort()
probe.close()
val remote = IosRemoteInput(hop, requestTimeoutMs = 1200)
val ready = BlockingQueue<String>(IosProtocolPlatform)
remote.setRequestListener { ready.put("ready") }
assertEquals("Invalid local address.", remote.startAddress(port, "example.com"))
assertEquals("Address is not assigned to a local interface.", remote.startAddress(port, "0.0.0.0"))
assertEquals("", remote.startAddress(port, "127.0.0.1"))
try {
val replies = BlockingQueue<ByteArray>(IosProtocolPlatform)
startThread("remote-client", true) { replies.put(loopbackExchange(port, "hello world\n".encodeToByteArray())) }
assertEquals("ready", ready.poll(5000))
val request = Json.parseObject(assertNotNull(remote.nextRequest()))
assertEquals("hello world", request["body"].asString())
assertNull(remote.nextRequest())
remote.complete(request["id"].asLong()!!, "{\"ok\":true}")
assertEquals("{\"ok\":true}\n", assertNotNull(replies.poll(5000)).decodeToString())
startThread("remote-client-2", true) { replies.put(loopbackExchange(port, "later\n".encodeToByteArray())) }
assertEquals("ready", ready.poll(5000))
assertNotNull(remote.nextRequest())
assertEquals(RemoteInputSession.TIMEOUT_RESPONSE + "\n", assertNotNull(replies.poll(8000)).decodeToString())
assertEquals(64, remote.randomSecret().length)
assertEquals(RemoteInputSession.tokenHash("abc"), remote.tokenDigest("abc"))
val all = iosInterfaceAddresses()
assertTrue(all.any { it.loopback && it.address == "127.0.0.1" }, all.toString())
assertTrue(Json.parseArray(remote.interfaces()).none { it.asObject()!!["address"].asString() == "127.0.0.1" })
assertTrue(IosLocalServerPort.isLocalUnicastAddress("::1"))
assertFalse(IosLocalServerPort.isLocalUnicastAddress("224.0.0.1"))
} finally {
remote.stop()
}
}
@Test
fun sseStreamsLinesRefusesRedirectsAndReportsErrors() {
val body = "event: a\r\ndata: one\n\ndata: two\r\n".encodeToByteArray()
val server = LoopbackHttpServer { path, _ ->
when (path) {
"/sse" -> LoopbackHttpServer.Reply(200, listOf("Content-Type" to "text/event-stream"),
listOf(body.copyOfRange(0, 13), body.copyOfRange(13, body.size)), pieceDelayMs = 50)
"/limited" -> LoopbackHttpServer.Reply(429, listOf("Content-Type" to "text/plain"), listOf("slow down".encodeToByteArray()))
else -> LoopbackHttpServer.Reply(302, listOf("Location" to "http://127.0.0.1:1/never"), listOf(ByteArray(0)))
}
}
try {
val ok = RecordingSseListener()
IosSseRequest(server.url("/sse"), "{\"q\":1}", "{\"X-Test\":\"yes\"}", ok, immediate, false)
assertTrue(waitUntil(10_000) { ok.finished }, "sse did not finish: ${ok.failure}")
assertEquals(listOf("event: a", "data: one", "", "data: two"), ok.lines)
assertTrue(ok.completed)
val request = server.requestsFor("/sse").single()
assertEquals("yes", request["x-test"])
assertEquals("text/event-stream", request["accept"])
assertTrue(request["user-agent"]!!.isNotEmpty())
val limited = RecordingSseListener()
IosSseRequest(server.url("/limited"), "{}", null, limited, immediate, false)
assertTrue(waitUntil(10_000) { limited.finished })
assertEquals(429 to "slow down", limited.httpError)
val redirected = RecordingSseListener()
IosSseRequest(server.url("/moved"), "{}", "{}", redirected, immediate, false)
assertTrue(waitUntil(10_000) { redirected.finished })
assertEquals(302, redirected.httpError?.first)
assertTrue(server.requestsFor("/never").isEmpty())
} finally {
server.close()
}
}
@Test
fun downloaderFetchesAndResumesWithRange() {
val payload = ByteArray(200_000) { (it * 31 + it / 977).toByte() }
val sha = sha256Hex(payload)
val server = LoopbackHttpServer { _, headers ->
val range = headers["range"]
if (range != null && range.startsWith("bytes=")) {
val from = range.removePrefix("bytes=").removeSuffix("-").toInt()
LoopbackHttpServer.Reply(206, listOf("Content-Range" to "bytes $from-${payload.size - 1}/${payload.size}"),
listOf(payload.copyOfRange(from, payload.size)))
} else LoopbackHttpServer.Reply(200, emptyList(), listOf(payload.copyOfRange(0, 70_000), payload.copyOfRange(70_000, payload.size)), pieceDelayMs = 30)
}
val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-dl-" + currentTimeMillis()
val dest = "$dir/model.bin"
try {
val first = RecordingDownloadListener()
IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), first, immediate).start()
assertTrue(waitUntil(20_000) { first.finished }, "download did not finish: ${first.error}")
assertEquals(dest, first.done, first.error)
assertContentEquals(payload, readFileData(dest))
assertTrue(first.progress >= 1)
assertNull(server.requestsFor("/model.bin").single()["range"])
deleteFile(dest)
writeFileData("$dest.part", payload.copyOfRange(0, 50_000))
val second = RecordingDownloadListener()
IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), second, immediate).start()
assertTrue(waitUntil(20_000) { second.finished }, "resume did not finish: ${second.error}")
assertEquals(dest, second.done, second.error)
assertContentEquals(payload, readFileData(dest))
assertEquals("bytes=50000-", server.requestsFor("/model.bin").last()["range"])
assertEquals(-1L, fileLength("$dest.part"))
} finally {
server.close()
deleteFile(dest)
deleteFile("$dest.part")
}
}
@Test
fun frameTimingsExportsToAFile() {
val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-ft-" + currentTimeMillis()
platform.Foundation.NSFileManager.defaultManager.createDirectoryAtPath(dir, true, null, null)
val timings = IosFrameTimings(IosProtocolPlatform)
assertNull(timings.exportNow())
timings.startExport(dir)
val frame = timings.startFrame("test:frame")
timings.spanStart(frame, "work")
timings.log(frame, "hello")
timings.spanEnd(frame, "work")
timings.finishFrame(frame, "sent")
val path = assertNotNull(timings.exportNow())
assertEquals("$dir/${IosFrameTimings.EXPORT_FILE_NAME}", path)
val text = readFileData(path).decodeToString()
assertTrue(text.contains("test:frame"), text)
assertTrue(text.contains("hello"), text)
assertNull(timings.exportNow())
assertTrue(timings.statsSummary().isNotEmpty())
deleteFile(path)
}
}
@@ -0,0 +1,228 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import platform.Foundation.NSDate
import platform.Foundation.NSDefaultRunLoopMode
import platform.Foundation.NSRunLoop
import platform.Foundation.NSThread
import platform.Foundation.dateWithTimeIntervalSinceNow
import platform.Foundation.runMode
private const val RIGHT = "11111111-2222-3333-4444-555555555501"
private const val LEFT = "11111111-2222-3333-4444-555555555502"
/** Pump the main run loop (which drains the main dispatch queue) until [condition] or timeout. */
private fun pumpMainUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
NSRunLoop.mainRunLoop.runMode(NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow(0.02))
}
return condition()
}
/** A GATT link that acks EvenHub/settings/auth requests and CFW stream messages like the firmware. */
private class FakeIosLink : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = IosProtocolPlatform.createLock()
val connected = HashSet<String>()
val disconnected = ArrayList<String>()
@Volatile var closed = false
@Volatile var writes = 0
private var seq = 0
override fun connect(address: String, timeoutMs: Int): Boolean {
connected.add(address)
return 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 = true
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
writes++
val sid = frames[0][6].toInt() and 255
val magic = if (sid == CfwTransport.SID) frames[0][2].toInt() and 255 else BleProtocol.parseFrame(frames[0]).msgSeq
val inFlight = core.monitor.withLock { core.inFlightMessages.firstOrNull { it.sid == sid && it.magic == magic && magic != 0 } }
if (inFlight != null) {
if (sid == CfwTransport.SID) {
for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum))
} else {
val joined = frames.flatMap { frame -> frame.slice(8 until 8 + (frame[3].toInt() and 255)) }.toByteArray()
val pb = joined.copyOf(maxOf(0, joined.size - 2))
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb))
}
}
return true
}
private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray {
val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00)
else
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return lock.withLock { BleProtocol.framePb(body, sid, 0x00, seq++)[0] }
}
private fun cfwAck(streamId: Int, lens: Int, size: Int, checksum: Int): ByteArray {
val packet = ByteArray(19)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = 11
packet[4] = 1
packet[5] = 1
packet[6] = CfwTransport.SID.toByte()
packet[8] = 1
packet[9] = streamId.toByte()
packet[12] = lens.toByte()
packet[13] = size.toByte()
packet[14] = (size ushr 8).toByte()
packet[15] = checksum.toByte()
packet[16] = (checksum ushr 8).toByte()
val crc = CfwTransport.crc(packet.copyOfRange(8, 17))
packet[17] = crc.toByte()
packet[18] = (crc ushr 8).toByte()
return packet
}
override fun disconnect(address: String) {
disconnected.add(address)
connected.remove(address)
}
override fun close() {
closed = true
}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private class MainThreadListener : FaceclawBleCommunicatorListener {
val phases = ArrayList<String>()
var offMainCallbacks = 0
private fun record(phase: String) {
if (!NSThread.isMainThread) offMainCallbacks++
phases.add(phase)
}
override fun onStateChange(phase: String?, status: String?) = record(phase ?: "")
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {}
override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) {
if (!NSThread.isMainThread) offMainCallbacks++
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}
override fun onPhoneLockState(locked: Boolean) {}
override fun onEvenAppConflict(message: String?) {}
override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {}
override fun onFrameFinished(frameId: Int, outcome: String?) {}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {}
}
class IosSessionFacadeTest {
@Test
fun facadeSessionConnectsOverAnInjectedLinkAndReportsOnTheMainQueue() {
assertTrue(NSThread.isMainThread, "tests drive the main run loop")
val link = FakeIosLink()
val host = IosSessionHost(threadName = "test-session")
val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform)
link.core = session.coreForTests()
val listener = MainThreadListener()
session.setListener(listener)
assertTrue(session.start())
assertFalse(session.start(), "already running")
assertTrue(pumpMainUntil(5_000) { listener.phases.contains("connected") }, "phases=${listener.phases}")
assertTrue(session.isSessionReady())
assertEquals(0, listener.offMainCallbacks, "listener callbacks must arrive on the main queue")
assertTrue(pumpMainUntil(5_000) { link.writes > 3 }, "auth, prelude, settings and layout writes (saw ${link.writes})")
session.disconnect()
assertTrue(pumpMainUntil(2_000) { listener.phases.lastOrNull() == "disconnected" }, "phases=${listener.phases}")
assertFalse(session.isSessionReady())
assertTrue(link.closed)
assertEquals(listOf(RIGHT, LEFT), link.disconnected.takeLast(2))
assertEquals(0, listener.offMainCallbacks)
}
@Test
fun relayFramesReachTheAncsListenerOnMainAndOtherFramesDoNot() {
val link = FakeIosLink()
val host = IosSessionHost(threadName = "test-session-ancs")
val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform)
val core = session.coreForTests()
link.core = core
val relayed = ArrayList<ByteArray>()
var offMain = 0
session.setAncsListener(object : IosAncsListener {
override fun onAncsAuthorization(authorized: Boolean) {}
override fun onRelayFrame(data: platform.Foundation.NSData) {
if (!NSThread.isMainThread) offMain++
relayed.add(data.byteArray())
}
})
val relay = byteArrayOf(65, 78, 1, 0, 9, 9, 9, 9, 0, 0, 0)
core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay)
core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, relay) // wrong arm: ignored by the tap
assertTrue(pumpMainUntil(2_000) { relayed.size == 1 })
assertEquals(relay.toList(), relayed[0].toList())
assertEquals(0, offMain)
session.setAncsListener(null)
core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay)
assertFalse(pumpMainUntil(200) { relayed.size > 1 })
}
@Test
fun hostDispatchesToTheCallingQueueAndRunsTheWorker() {
val host = IosSessionHost(threadName = "test-host")
var onMain = false
host.currentThreadDispatcher().post { onMain = NSThread.isMainThread }
assertTrue(pumpMainUntil(1_000) { onMain })
var workerThread = ""
host.startWorker { workerThread = NSThread.currentThread.name ?: "" }
host.joinWorker(2_000)
assertEquals("test-host", workerThread)
var posted = false
host.postToMain { posted = NSThread.isMainThread }
assertTrue(pumpMainUntil(1_000) { posted })
assertFalse(host.isEvenAppActive())
}
@Test
fun stockFlowFacadesConstructWithoutBluetooth() {
// No CoreBluetooth on the simulator; construction and cancel/close must still be safe.
val probe = IosDeviceInfoProbe(RIGHT, LEFT)
probe.setListener(null)
probe.close()
val prompt = IosFlashPrompt(RIGHT, LEFT, "warn", true)
prompt.close()
val flasher = IosFirmwareFlasher(RIGHT, LEFT, "/nonexistent.bin")
flasher.close()
assertNotNull(IosFrameTimings.shared.core.buildExport())
}
}