From c119883ca0a1802b5eccfc65df8c196103e14202 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Sun, 27 Sep 2026 15:32:49 -0700 Subject: [PATCH] Add ring debug; change GATT locking --- .../faceclaw/app/FaceclawBleCommunicator.kt | 44 ++++ .../com/faceclaw/app/FaceclawBleManager.kt | 183 +++++++++------ app/apps/developer/developer-app.ts | 9 + app/apps/developer/ring-status.ts | 220 ++++++++++++++++++ app/native/ring-status.ts | 102 ++++++++ .../faceclaw/app/g2protocol/BleProtocol.kt | 84 +++++++ .../app/g2protocol/ConnectionOptions.kt | 2 + .../faceclaw/app/g2protocol/MessageBuilder.kt | 16 ++ .../g2protocol/session/GlassesSessionCore.kt | 124 +++++++++- .../g2protocol/session/GlassesSessionRing.kt | 141 ++++++++++- .../com/faceclaw/app/ble/IosGlassesSession.kt | 3 + .../com/faceclaw/app/GlassesRingLinkTest.kt | 47 ++++ .../faceclaw/app/RingHealthTransferTest.kt | 21 ++ 13 files changed, 915 insertions(+), 81 deletions(-) create mode 100644 app/apps/developer/ring-status.ts create mode 100644 app/native/ring-status.ts create mode 100644 tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt index 6d774926..8c853e88 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt @@ -2,6 +2,9 @@ package com.faceclaw.app import android.annotation.SuppressLint import android.app.KeyguardManager +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile import android.content.BroadcastReceiver import android.content.Context import android.content.Intent @@ -34,6 +37,40 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre fun getActive(): FaceclawBleCommunicator? { return activeInstance } + + /** + * The phone's own Bluetooth view of the ring, independent of whether a + * session is running or configured to talk to the ring: bond state, + * whether any app on the phone holds a GATT link, and the (hidden-API, + * best-effort) ACL connection. JSON; fields are null when unknown. + */ + @JvmStatic + fun getSystemBluetoothStateJson(context: Context, address: String?): String { + val result = org.json.JSONObject() + val trimmed = address?.trim()?.uppercase() ?: "" + result.put("address", trimmed) + try { + val manager = context.applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager? + val adapter = manager?.adapter + if (manager == null || adapter == null || trimmed.isEmpty() || !android.bluetooth.BluetoothAdapter.checkBluetoothAddress(trimmed)) { + return result.toString() + } + val device = adapter.getRemoteDevice(trimmed) + result.put("bonded", device.bondState == BluetoothDevice.BOND_BONDED) + result.put("gattConnected", + manager.getConnectionState(device, BluetoothProfile.GATT) == BluetoothProfile.STATE_CONNECTED) + try { + val isConnected = BluetoothDevice::class.java.getMethod("isConnected") + result.put("aclConnected", isConnected.invoke(device) as Boolean) + } catch (_: Throwable) { + // Hidden API unavailable; leave unknown. + } + result.put("name", device.name ?: org.json.JSONObject.NULL) + } catch (t: Throwable) { + result.put("error", t.message ?: t.toString()) + } + return result.toString() + } } private val appContext: Context = context.applicationContext @@ -223,6 +260,13 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre /** Status/results of the current or most recent benchmark run, as JSON. */ fun getBandwidthBenchmarkStatus(): String = core.getBandwidthBenchmarkStatus() + /** See [GlassesSessionCore.getRingStatus]. */ + fun getRingStatus(): String = core.getRingStatus() + + /** See [GlassesSessionCore.setGlassesRingLink]. */ + fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean = + core.setGlassesRingLink(action, fallbackAddress, fallbackName) + fun addImuListener(listener: FaceclawImuListener?) = core.addImuListener(listener) fun removeImuListener(listener: FaceclawImuListener?) = core.removeImuListener(listener) diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt index a2d7f718..7ef99d9d 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.kt @@ -54,6 +54,7 @@ class FaceclawBleManager(context: Context) { private val gattClients = ConcurrentHashMap() private val bluetoothApiLock = Any() + private val messageLocks = ConcurrentHashMap() private val connectLatches = ConcurrentHashMap() private val connectResults = ConcurrentHashMap() @@ -144,59 +145,58 @@ class FaceclawBleManager(context: Context) { * reconnect, not an immediate attempt), so this needs its own longer * timeout - do not reuse CONNECT_TIMEOUT_MS/awaitLatch's short window for * it, that would just trade one spurious failure for another. + * + * Only the connectGatt call and the timeout cleanup run under the global + * API lock; the wait for the link does not. A pending connection is not a + * GATT operation in flight, and holding the lock across it let an + * unreachable ring (20s autoConnect timeout, retried every 2s) starve every + * glasses write. */ fun connect(address: String?, timeoutMs: Int, autoConnect: Boolean): Boolean { if (address == null || address.trim().isEmpty()) { throw IllegalArgumentException("address is required") } val latch = CountDownLatch(1) - connectLatches[address] = latch - connectResults.remove(address) - - val gattLock = gattLock(address) - synchronized(gattLock) { - val existing = gattClients[address] - if (existing != null) { - connectLatches.remove(address) + val gatt: BluetoothGatt + synchronized(gattLock(address)) { + if (gattClients[address] != null) { return true } val device = bluetoothAdapter.getRemoteDevice(address) - if (device == null) { - connectLatches.remove(address) - throw IllegalArgumentException("remote device not found: $address") - } + ?: throw IllegalArgumentException("remote device not found: $address") - val gatt: BluetoothGatt? = device.connectGatt( + connectLatches[address] = latch + connectResults.remove(address) + gatt = device.connectGatt( context, autoConnect, gattCallback, BluetoothDevice.TRANSPORT_LE, BluetoothDevice.PHY_LE_2M or BluetoothDevice.PHY_LE_1M - ) - if (gatt != null) { - gattClients[address] = gatt - } - - if (gatt == null) { - connectLatches.remove(address) + ) ?: run { + connectLatches.remove(address, latch) return false } + gattClients[address] = gatt + } - if (!awaitLatch(latch, timeoutMs)) { - connectLatches.remove(address) - connectResults.remove(address) - gattClients.remove(address, gatt) + val completed = awaitLatch(latch, timeoutMs) + connectLatches.remove(address, latch) + val connected = connectResults.remove(address) == true + if (completed && connected && gattClients[address] === gatt) { + return true + } + // Timed out, or failed. Whoever removed the client from gattClients + // (the disconnect callback, or disconnect()) also closes it. + synchronized(gattLock(address)) { + if (gattClients.remove(address, gatt)) { negotiatedMtus.remove(address) gatt.disconnect() gatt.close() - return false } - - val connected = connectResults.remove(address) - connectLatches.remove(address) - return connected == true } + return false } fun requestConnectionPriority(address: String, priority: Int): Boolean { @@ -316,6 +316,14 @@ class FaceclawBleManager(context: Context) { } } + /** + * Writes [frames] in order. The global API lock is held for each frame's + * write-and-callback (one GATT operation in flight process-wide), but not + * across the whole message or during retry backoff, so a slow or failing + * link (the direct ring) can't hold the glasses off the air for a whole + * retry cycle. The per-address lock keeps concurrent messages to the same + * device from interleaving their frames. + */ fun writeFrames( address: String, characteristicUuid: String, @@ -328,9 +336,13 @@ class FaceclawBleManager(context: Context) { } val startMs = System.currentTimeMillis() - synchronized(gattLock(address)) { - val gatt = requireGatt(address) - val characteristic = requireCharacteristic(gatt, characteristicUuid) + synchronized(messageLock(address)) { + val gatt: BluetoothGatt + val characteristic: BluetoothGattCharacteristic + synchronized(gattLock(address)) { + gatt = requireGatt(address) + characteristic = requireCharacteristic(gatt, characteristicUuid) + } for (i in frames.indices) { val frame = frames[i] @@ -356,46 +368,44 @@ class FaceclawBleManager(context: Context) { ): Boolean { var retryCount = 0 while (true) { - val latch = CountDownLatch(1) - writeLatches[address] = latch - writeStatuses.remove(address) - - val currentTime = System.currentTimeMillis() - val result = gatt.writeCharacteristic(characteristic, data!!, writeType) - val timeAsleep = System.currentTimeMillis() - currentTime - //Log.i(TAG, "writeCharacteristic: spent " + timeAsleep + "ms"); - - if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) { - writeLatches.remove(address, latch) - writeStatuses.remove(address) - if (!sleepBeforeWriteRetry(address, "busy", retryCount++)) { + val retryReason: String + synchronized(gattLock(address)) { + if (gattClients[address] !== gatt) { + // Disconnected (and closed) since the write started. + Log.w(TAG, "writeCharacteristic abandoned: address=$address no longer connected") return false } - continue - } else { - //Log.i(TAG, "writeCharacteristic with writeType=" + writeType + " result=" + result + " retryCount=" + retryCount); - if (result != android.bluetooth.BluetoothStatusCodes.SUCCESS) { + val latch = CountDownLatch(1) + writeLatches[address] = latch + writeStatuses.remove(address) + + val result = gatt.writeCharacteristic(characteristic, data!!, writeType) + if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) { writeLatches.remove(address, latch) writeStatuses.remove(address) - if (!sleepBeforeWriteRetry(address, "start result=$result", retryCount++)) { + retryReason = "busy" + } else if (result != android.bluetooth.BluetoothStatusCodes.SUCCESS) { + writeLatches.remove(address, latch) + writeStatuses.remove(address) + retryReason = "start result=$result" + } else { + if (!awaitLatch(latch, timeoutMs)) { + writeLatches.remove(address, latch) + writeStatuses.remove(address) return false } - continue - } - if (!awaitLatch(latch, timeoutMs)) { + val status = writeStatuses.remove(address) writeLatches.remove(address, latch) - writeStatuses.remove(address) - return false - } - val status = writeStatuses.remove(address) - writeLatches.remove(address) - if (status != null && status == BluetoothGatt.GATT_SUCCESS) { - return true - } - if (!sleepBeforeWriteRetry(address, "callback status=$status", retryCount++)) { - return false + if (status != null && status == BluetoothGatt.GATT_SUCCESS) { + return true + } + retryReason = "callback status=$status" } } + // Back off outside the lock so other devices' operations proceed. + if (!sleepBeforeWriteRetry(address, retryReason, retryCount++)) { + return false + } } } @@ -416,13 +426,18 @@ class FaceclawBleManager(context: Context) { } fun disconnect(address: String?) { - val gattLock = gattLock(address) - synchronized(gattLock) { - val gatt = if (address != null) gattClients.remove(address) else null - if (address != null) negotiatedMtus.remove(address) - if (gatt == null) { - return - } + if (address == null) { + return + } + val gatt = gattClients.remove(address) + negotiatedMtus.remove(address) + // Wake anything waiting on this device first: a closed client never + // calls back, and the waiter may be holding the lock close() needs. + releasePendingOperations(address) + if (gatt == null) { + return + } + synchronized(gattLock(address)) { gatt.disconnect() gatt.close() } @@ -465,9 +480,28 @@ class FaceclawBleManager(context: Context) { private fun gattLock(address: String?): Any { // Android's Bluetooth stack has process-wide command-pipeline constraints on some devices. // Keep every BluetoothGatt API call serialized globally, even for different MAC addresses. + // Never hold it across anything unbounded or slow that isn't a GATT operation in flight + // (connection waits, retry sleeps): every glasses frame write needs it. return bluetoothApiLock } + /** Serializes whole multi-frame messages per device; taken before [gattLock], never after. */ + private fun messageLock(address: String): Any { + return messageLocks.getOrPut(address) { Any() } + } + + /** + * Fail every operation still waiting on a callback from [address]. They see no status and + * return false, instead of holding the global lock until their timeouts expire. + */ + private fun releasePendingOperations(address: String) { + connectLatches.remove(address)?.countDown() + servicesLatches.remove(address)?.countDown() + mtuLatches.remove(address)?.countDown() + descriptorLatches.remove(address)?.countDown() + writeLatches.remove(address)?.countDown() + } + private val gattCallback: BluetoothGattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { Log.i(TAG, "onConnectionStateChange: status=$status newState=$newState") @@ -485,10 +519,13 @@ class FaceclawBleManager(context: Context) { connectResults[address] = false val latch = connectLatches.remove(address) latch?.countDown() - val gattLock = gattLock(address) - synchronized(gattLock) { - gattClients.remove(address, gatt) + // Unpublish and wake this client's waiters before taking the lock: one of them + // may hold it, waiting for a callback that will now never come. + if (gattClients.remove(address, gatt)) { negotiatedMtus.remove(address) + releasePendingOperations(address) + } + synchronized(gattLock(address)) { gatt.close() } dispatchConnectionState(address, false) diff --git a/app/apps/developer/developer-app.ts b/app/apps/developer/developer-app.ts index 8a8366da..1f1c831c 100644 --- a/app/apps/developer/developer-app.ts +++ b/app/apps/developer/developer-app.ts @@ -7,6 +7,7 @@ import { AccelerometerDemoLayer } from "./accelerometer-demo"; import { BandwidthBenchmarkLayer } from "./bandwidth-benchmark"; import { LightSensorDemoLayer } from "./light-sensor-demo"; import { ResourceUsageLayer } from "./resource-usage"; +import { RingStatusLayer } from "./ring-status"; import { LoadAppFromQrLayer, LoadAppFromUrlLayer } from "./load-app"; import { unicodeTestMenu } from "./unicode-test"; import { type AppContext } from "../app-definition"; @@ -85,6 +86,14 @@ function debugTestsMenu(openInputEvents: (ctx: Parameters[ ctx.stack.push(new LightSensorDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender)); }, }, + { + label: "Ring status", + disabled: global.isIOS, + description: global.isIOS ? "Not available on iOS yet." : undefined, + onSelect: (ctx) => { + ctx.stack.push(new RingStatusLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender)); + }, + }, { label: "BLE bandwidth", onSelect: (ctx) => { diff --git a/app/apps/developer/ring-status.ts b/app/apps/developer/ring-status.ts new file mode 100644 index 00000000..f20cbb3e --- /dev/null +++ b/app/apps/developer/ring-status.ts @@ -0,0 +1,220 @@ +import { getDefaultSmallFont } from "../../graphics/ui-fonts"; +import { GrayImage } from "../../graphics/image"; +import { type InputEvent } from "../../ui/gestures"; +import { Layer, type LayerContext } from "../../ui/layers"; +import { shell } from "../../ui/shell/shell"; +import { ringConnectionModeSetting } from "../../ui/dashboard-settings"; +import { loadDeviceAddresses } from "../../g2/device-addresses"; +import { + getRingSessionStatus, + getRingSystemBluetoothState, + setGlassesRingLink, + type GlassesRingLinkAction, + type RingSessionStatus, + type RingSystemBluetoothState, +} from "../../native/ring-status"; + +const POLL_INTERVAL_MS = 1_000; +const LEFT_X = 16; +const VALUE_X = 130; +const BUTTON_GAP = 8; + +type Row = { label: string; value: string; dim?: boolean }; +type Button = { label: string; action: GlassesRingLinkAction | "mode" }; + +const BUTTONS: readonly Button[] = [ + { label: "Disconnect", action: "disconnect" }, + { label: "Release", action: "release" }, + { label: "Reconnect", action: "connect" }, + { label: "Mode", action: "mode" }, +]; + +/** + * Where R1 ring input is coming from: the phone's own Bluetooth link to the + * ring, the direct-link session state, and when input last arrived directly + * versus relayed by the glasses. A ring connected to the glasses does not + * also report gestures to a phone that connects to it directly, so the two + * "input" rows are the quickest way to see which path is live. + * + * The buttons are EXPERIMENTAL glasses-side ring link commands (sid 0x80, + * see GlassesSessionRing.kt): Disconnect / Release ask the glasses to let go + * of the ring, Reconnect hands it back, and Mode flips the Developer "Ring + * connection" setting, which applies on the next glasses connection. + */ +export class RingStatusLayer implements Layer { + private session: RingSessionStatus | null = null; + private system: RingSystemBluetoothState | null = null; + private timer: ReturnType | null = null; + private selected = 0; + private notice = ""; + + constructor( + private readonly windowId: string, + private readonly requestRender: () => void, + ) { + this.poll(); + this.timer = setInterval(() => { + this.poll(); + if (shell.isWindowVisible(this.windowId)) this.requestRender(); + }, POLL_INTERVAL_MS); + } + + onRemoved(): void { + if (this.timer !== null) { + clearInterval(this.timer); + this.timer = null; + } + } + + private ringAddress(): string { + return this.session?.ringAddress || loadDeviceAddresses().ring; + } + + private poll(): void { + this.session = getRingSessionStatus(); + const address = this.ringAddress(); + this.system = address ? getRingSystemBluetoothState(address) : null; + } + + paint(ctx: LayerContext): GrayImage { + const font = getDefaultSmallFont(); + const { width, height } = ctx.stack.getBaseSize(); + const image = new GrayImage(width, height, 0); + const lineStep = font.lineHeight + 2; + const buttonHeight = font.lineHeight + 8; + const buttonTop = height - buttonHeight - 6; + + image.drawText(font, 18, 10, "Ring status", 230); + let y = 10 + lineStep + 4; + const rows = this.rows(); + if (this.notice) rows.push({ label: "", value: this.notice }); + for (const row of rows) { + if (y + font.lineHeight > buttonTop - 4) break; + image.drawText(font, LEFT_X, y, row.label, row.dim ? 100 : 150); + image.drawText(font, VALUE_X, y, row.value, row.dim ? 120 : 220); + y += lineStep; + } + + const buttonWidth = Math.floor((width - 2 * LEFT_X - BUTTON_GAP * (BUTTONS.length - 1)) / BUTTONS.length); + BUTTONS.forEach((button, index) => { + const x = LEFT_X + index * (buttonWidth + BUTTON_GAP); + const selected = index === this.selected; + if (selected) image.fillRoundedRect(x, buttonTop, buttonWidth, buttonHeight, 40, 4); + image.drawRoundedRect(x, buttonTop, buttonWidth, buttonHeight, selected ? 200 : 70, 4); + const text = button.action === "mode" + ? (ringConnectionModeSetting.get() === "direct" ? "Mode: direct" : "Mode: glasses") + : button.label; + image.drawText(font, x + Math.max(0, Math.floor((buttonWidth - font.measureText(text)) / 2)), + buttonTop + 4, text, selected ? 255 : 170); + }); + return image; + } + + private rows(): Row[] { + const s = this.session; + const address = this.ringAddress(); + const rows: Row[] = [ + { label: "Ring", value: address || "none paired" }, + { label: "Phone BT", value: describeSystem(this.system) }, + ]; + + if (!s) { + rows.push({ label: "Session", value: "not connected to glasses", dim: true }); + return rows; + } + + if (!s.directEnabled) { + const pending = ringConnectionModeSetting.get() === "direct"; + rows.push({ label: "Direct link", value: pending ? "on after glasses reconnect" : "off (mode: glasses)", dim: true }); + } else { + const state = s.directNotificationsReady ? "subscribed" + : s.directConnected ? "connected, subscribing" + : "not connected"; + const since = s.directStateAgeMs >= 0 ? ` ${formatAge(s.directStateAgeMs)}` : ""; + const battery = s.directBattery >= 0 ? `, ${s.directBattery}%` : ""; + rows.push({ label: "Direct link", value: `${state}${since}, ${s.directConnectCount} connects${battery}` }); + } + rows.push({ label: "Direct input", value: describeInput(s.lastDirectInputAgeMs, s.lastDirectInput) }); + if (s.directEnabled) { + rows.push({ label: "Direct pkts", value: describeAge(s.lastDirectNotifyAgeMs) }); + } + rows.push({ label: "Glasses input", value: describeInput(s.lastGlassesInputAgeMs, s.lastGlassesInput) }); + rows.push({ + label: "Glasses ring", + value: (s.glassesRingBatteryAgeMs < 0 ? "battery not reported" + : `${s.glassesRingBattery >= 0 ? `battery ${s.glassesRingBattery}%` : "no battery"} ${formatAge(s.glassesRingBatteryAgeMs)} ago`) + + (s.glassesRingMac ? `, mac ${s.glassesRingMac}` : ""), + }); + if (s.lastGlassesReport) { + rows.push({ label: "Glasses said", value: `${s.lastGlassesReport} (${formatAge(s.lastGlassesReportAgeMs)} ago)` }); + } + if (s.lastCommand) { + rows.push({ label: "Sent", value: `${s.lastCommand} ${formatAge(s.lastCommandAgeMs)} ago` }); + rows.push({ label: "Result", value: `R ${s.lastCommandResultR}; L ${s.lastCommandResultL}` }); + } + if (s.lastDirectError) rows.push({ label: "Direct error", value: s.lastDirectError, dim: true }); + return rows; + } + + private activate(): void { + const button = BUTTONS[this.selected]!; + if (button.action === "mode") { + const next = ringConnectionModeSetting.get() === "direct" ? "glasses" : "direct"; + ringConnectionModeSetting.set(next); + this.notice = `Ring connection set to ${ringConnectionModeSetting.displayValue(next)}; applies on next glasses connection`; + return; + } + const address = this.ringAddress(); + const name = this.system?.name ?? ""; + this.notice = setGlassesRingLink(button.action, address, name) + ? `${button.label} sent (experimental)` + : `${button.label} not sent (no session or no ring address)`; + this.poll(); + } + + handleInput(event: InputEvent, ctx: LayerContext): void { + switch (event.type) { + case "scroll-up": + this.selected = (this.selected + BUTTONS.length - 1) % BUTTONS.length; + return; + case "scroll-down": + this.selected = (this.selected + 1) % BUTTONS.length; + return; + case "click": + this.activate(); + return; + case "double-click": + ctx.stack.pop(); + return; + default: + return; + } + } +} + +function describeSystem(sys: RingSystemBluetoothState | null): string { + if (!sys) return "unknown"; + if (sys.error) return `error: ${sys.error}`; + if (sys.bonded === undefined) return "unknown"; + const parts = [sys.bonded ? "bonded" : "not bonded"]; + if (sys.gattConnected !== undefined) parts.push(sys.gattConnected ? "GATT up" : "no GATT"); + if (sys.aclConnected !== undefined) parts.push(sys.aclConnected ? "link up" : "no link"); + return parts.join(", "); +} + +function describeInput(ageMs: number, label: string): string { + if (ageMs < 0) return "never"; + return label ? `${formatAge(ageMs)} ago: ${label}` : `${formatAge(ageMs)} ago`; +} + +function describeAge(ageMs: number): string { + return ageMs < 0 ? "never" : `${formatAge(ageMs)} ago`; +} + +function formatAge(ageMs: number): string { + const seconds = Math.floor(ageMs / 1000); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}m ${seconds % 60}s`; + return `${Math.floor(minutes / 60)}h ${minutes % 60}m`; +} diff --git a/app/native/ring-status.ts b/app/native/ring-status.ts new file mode 100644 index 00000000..81d6257a --- /dev/null +++ b/app/native/ring-status.ts @@ -0,0 +1,102 @@ +import { Utils } from "@nativescript/core"; + +declare const com: any; + +/** + * R1 ring diagnostics (Developer > Debug tests > Ring status). Session-side + * state comes from the active communicator; the phone's own Bluetooth view of + * the ring (bond, GATT/ACL link) is queried separately so it is available + * even with no session or with the direct ring link disabled. + */ + +/** GlassesSessionCore.getRingStatus. Ages are ms before now, -1 = never. */ +export type RingSessionStatus = { + directEnabled: boolean; + ringAddress: string; + glassesConnected: boolean; + sessionReady: boolean; + directConnected: boolean; + directNotificationsReady: boolean; + directConnectCount: number; + directStateAgeMs: number; + directBattery: number; + lastDirectNotifyAgeMs: number; + lastDirectInputAgeMs: number; + lastDirectInput: string; + glassesRingBattery: number; + glassesRingBatteryAgeMs: number; + lastGlassesInputAgeMs: number; + lastGlassesInput: string; + lastDirectError: string; + /** Ring MAC as the glasses reported it (wire byte order, hex), "" if not yet seen. */ + glassesRingMac: string; + glassesRingName: string; + lastGlassesReport: string; + lastGlassesReportAgeMs: number; + lastCommand: string; + lastCommandAgeMs: number; + lastCommandResultR: string; + lastCommandResultL: string; +}; + +/** + * EXPERIMENTAL glasses-side ring link control (sid 0x80 pair manager): + * "disconnect" drops the glasses' ring link, "release" also clears their + * connect mode (may hold off auto-reconnect), "connect" hands the ring back. + */ +export type GlassesRingLinkAction = "disconnect" | "release" | "connect"; + +export type RingSystemBluetoothState = { + address: string; + bonded?: boolean; + gattConnected?: boolean; + aclConnected?: boolean; + name?: string | null; + error?: string; +}; + +function activeCommunicator(): any { + if (!global.isAndroid) return null; + try { + return com.faceclaw.app.FaceclawBleCommunicator.getActive(); + } catch { + return null; + } +} + +/** Null when there is no active glasses session (or on iOS). */ +export function getRingSessionStatus(): RingSessionStatus | null { + const active = activeCommunicator(); + if (!active) return null; + try { + return JSON.parse(String(active.getRingStatus())) as RingSessionStatus; + } catch (error) { + console.warn(`getRingStatus failed: ${error}`); + return null; + } +} + +/** Null on iOS or when the query itself fails. */ +export function getRingSystemBluetoothState(address: string): RingSystemBluetoothState | null { + if (!global.isAndroid) return null; + try { + const json = com.faceclaw.app.FaceclawBleCommunicator.getSystemBluetoothStateJson( + Utils.android.getApplicationContext(), address); + return JSON.parse(String(json)) as RingSystemBluetoothState; + } catch (error) { + console.warn(`getSystemBluetoothStateJson failed: ${error}`); + return null; + } +} + +/** False when there is no session or the command could not be queued. */ +export function setGlassesRingLink(action: GlassesRingLinkAction, fallbackAddress: string, fallbackName: string): boolean { + const active = activeCommunicator(); + if (!active) return false; + try { + return Boolean(active.setGlassesRingLink(action, fallbackAddress, fallbackName)); + } catch (error) { + console.warn(`setGlassesRingLink failed: ${error}`); + return false; + } +} diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt index 2aa00b08..85faf5ce 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt @@ -62,6 +62,17 @@ class BleProtocol { private const val SECURITY_AUTH_CMD: Int = 4 + // DevCfgDataPackage ring commands on sid 0x80 (dev_config_protocol / + // dev_pair_manager). Wire shapes from g2-kit-unofficial's generated + // protos; handler behavior only from openCFW's decompilation + // (pb_service_pair_mgr.c) - not captured from the Even app and not + // hardware-verified. + private const val DEV_CFG_RING_CONNECT_INFO_CMD: Int = 6 + private const val DEV_CFG_DISCONNECT_INFO_CMD: Int = 8 + + /** sid 0x91 RingDataPackage: glasses-side ring events (g2.ring). */ + const val SID_RING_DATA: Int = 0x91 + const val SID_APP_LAUNCH: Int = 0x01 const val SID_EVENHUB: Int = 0xe0 @@ -502,6 +513,79 @@ class BleProtocol { ) } + /** + * DISCONNECT_INFO(8) with DisconnectInfo{dev=RING(0), ringMac}: ask the glasses to drop + * their link to the ring. In openCFW's decompilation the handler ignores the payload, + * resets the ring retry counter and posts the ring-disconnect event, leaving the stored + * ring target alone (unlike RING_CONNECT_INFO, which overwrites it). + */ + @JvmStatic + fun buildRingDisconnectRequest(magic: Int, ringMac: ByteArray): ByteArray { + return concat( + CollectionUtils.listOf( + encodeVarintField(1, DEV_CFG_DISCONNECT_INFO_CMD), + encodeVarintField(2, magic), + encodeMessageField(7, concat(CollectionUtils.listOf( + encodeVarintField(1, 0), + encodeBytesField(2, ringMac), + ))), + ) + ) + } + + /** + * RING_CONNECT_INFO(6) with RingInfo{connectRing, ringMac, ringName}. connectRing is + * declared `bytes` but read by the firmware as one byte. Every call overwrites the glasses' + * ring target with ringMac/ringName, so pass the target the glasses themselves reported + * when one is known. Only the ring-owning temple acts on connect=true; the firmware + * ignores connect requests closer than ~20 s apart. + */ + @JvmStatic + fun buildRingConnectRequest(magic: Int, connect: Boolean, ringMac: ByteArray, ringName: ByteArray): ByteArray { + return concat( + CollectionUtils.listOf( + encodeVarintField(1, DEV_CFG_RING_CONNECT_INFO_CMD), + encodeVarintField(2, magic), + encodeMessageField(5, concat(CollectionUtils.listOf( + encodeBytesField(1, byteArrayOf(if (connect) 1 else 0)), + encodeBytesField(2, ringMac), + encodeBytesField(3, ringName), + ))), + ) + ) + } + + /** A RingInfo (from RING_CONNECT_INFO) or RingEvent (from sid 0x91) the glasses sent. */ + class GlassesRingReport( + @JvmField val source: String, + @JvmField val ringMac: ByteArray?, + @JvmField val ringName: String, + /** connRet for RingInfo (0 = connected, 90 = timeout), eventId for RingEvent; -1 absent. */ + @JvmField val code: Int, + ) + + /** Decode a sid-0x80 RING_CONNECT_INFO frame (notification or ack), else null. */ + @JvmStatic + fun parseRingConnectInfo(pb: ByteArray?): GlassesRingReport? { + if (pb == null) return null + val root = stripTrailingCrc(pb) + if (readVarintFieldValue(root, 1, -1) != DEV_CFG_RING_CONNECT_INFO_CMD) return null + val info = readFieldBytes(root, 5) ?: return null + val name = readFieldBytes(info, 3) + return GlassesRingReport("connect-info", readFieldBytes(info, 2), + if (name == null) "" else name.decodeToString(), readVarintFieldValue(info, 4, -1)) + } + + /** Decode a sid-0x91 RingDataPackage EVENT(1) frame, else null. */ + @JvmStatic + fun parseRingDataEvent(pb: ByteArray?): GlassesRingReport? { + if (pb == null) return null + val root = stripTrailingCrc(pb) + if (readVarintFieldValue(root, 1, -1) != 1) return null + val event = readFieldBytes(root, 3) ?: return null + return GlassesRingReport("ring-event", readFieldBytes(event, 1), "", readVarintFieldValue(event, 2, -1)) + } + /** * True when `pb` (trailing CRC still attached) is the success notification for the * authentication request sent with `magic`: command 4, the same magic, and an EMPTY field-3 diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt index de0950cb..54c38425 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/ConnectionOptions.kt @@ -12,6 +12,8 @@ class ConnectionOptions { const val DESCRIPTOR_TIMEOUT_MS = 5_000 const val RING_DESIRED_MTU = 247 const val RING_RECONNECT_DELAY_MS = 2_000 + // Cap for the exponential backoff on repeated direct-ring connect failures. + const val RING_RECONNECT_MAX_DELAY_MS = 60_000L // The ring connects with autoConnect=true (see SessionLink.connect's // 3-arg overload) - Android manages that as a background reconnect rather // than an immediate attempt, so it needs far more room than the glasses' diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt index 218c7d4c..e18ad0ee 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/MessageBuilder.kt @@ -43,6 +43,22 @@ class MessageBuilder { ) } + /** A sid-0x80 DevCfgDataPackage ring command (see BleProtocol.buildRingConnectRequest). */ + fun ringLinkCommand(label: String, leftArm: Boolean, build: (Int) -> ByteArray): OutboundMessage { + var magic: Int = magicPool.allocate() + return OutboundMessage( + "ring-link", + (label + (if (leftArm) " L" else " R")), + BleProtocol.SID_SECURITY_AUTH, + BleProtocol.FLAG_SECURITY_AUTH, + magic, + build(magic), + ACK_TIMEOUT_MS, + -1, + leftArm, + ) + } + fun shutdown(exitMode: Int): OutboundMessage { var magic: Int = magicPool.allocate() return OutboundMessage( diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt index 9fa9f4d5..ecc87c8d 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt @@ -150,6 +150,17 @@ class GlassesSessionCore( // write timeout. The ring worker drains the queue instead. internal val ringReassembler = RingProtocol.Reassembler() internal val ringOutbound = ArrayDeque() + /** + * Ring-write backoff after a failed write (see writeRingFrame). Every ring + * write shares the platform's GATT pipeline with the glasses, and a failing + * one can hold it for the whole write timeout, so failures must not be + * retried at ring-worker tick rate. Reset on each ring connect. Guarded by + * `monitor`. + */ + internal var ringWriteBlockedUntilMs = 0L + internal var ringWriteFailures = 0 + /** Consecutive failed direct-ring connect attempts; stretches the retry delay. Guarded by `monitor`. */ + internal var ringConnectFailures = 0 internal val ringHealthRecords = ArrayList() /** * Total records ever appended to [ringHealthRecords], including every @@ -311,6 +322,28 @@ class GlassesSessionCore( // over the glasses-relayed ringBattery while the ring is connected. internal var directRingBattery = -1 internal var directRingCharging = -1 + // Ring diagnostics for the Developer > Ring status page (now() clock, 0 = never). + internal var lastDirectRingNotifyAtMs = 0L + internal var lastDirectRingInputAtMs = 0L + internal var lastDirectRingInputLabel = "" + internal var lastGlassesRingInputAtMs = 0L + internal var lastGlassesRingInputLabel = "" + internal var lastGlassesRingBatteryAtMs = 0L + internal var ringConnectedChangedAtMs = 0L + internal var ringConnectCount = 0 + internal var lastDirectRingError = "" + // What the glasses themselves said about their ring link (sid 0x80 + // RING_CONNECT_INFO / sid 0x91 ring events). The MAC is kept in wire byte + // order so a reconnect can echo it back without guessing the order. + internal var glassesRingMac: ByteArray? = null + internal var glassesRingName = "" + internal var lastGlassesRingReport = "" + internal var lastGlassesRingReportAtMs = 0L + // The last glasses ring-link command we sent, and how each temple answered. + internal var lastRingLinkCommand = "" + internal var lastRingLinkCommandAtMs = 0L + internal var lastRingLinkResultR = "" + internal var lastRingLinkResultL = "" // Silent mode: 1 = on, 0 = off, -1 = not yet known. See updateSilentModeLocked. internal var silentMode = -1 internal var wearState = -1 @@ -901,6 +934,65 @@ class GlassesSessionCore( interruptibleSleep.interrupt() } + /** + * Ring connection/input diagnostics as JSON. Times are reported as ages + * in ms (-1 = never) so the caller needs no access to this clock. + */ + fun getRingStatus(): String { + monitor.withLock { + val now = now() + fun age(atMs: Long): Long = if (atMs == 0L) -1L else maxOf(0L, now - atMs) + val status = linkedMapOf() + status["directEnabled"] = hasRingAddress() + status["ringAddress"] = ringAddress + status["glassesConnected"] = rightConnected && leftConnected + status["sessionReady"] = sessionReady + status["directConnected"] = ringConnected + status["directNotificationsReady"] = ringNotificationsReady + status["directConnectCount"] = ringConnectCount + status["directStateAgeMs"] = age(ringConnectedChangedAtMs) + status["directBattery"] = directRingBattery + status["lastDirectNotifyAgeMs"] = age(lastDirectRingNotifyAtMs) + status["lastDirectInputAgeMs"] = age(lastDirectRingInputAtMs) + status["lastDirectInput"] = lastDirectRingInputLabel + status["glassesRingBattery"] = ringBattery + status["glassesRingBatteryAgeMs"] = age(lastGlassesRingBatteryAtMs) + status["lastGlassesInputAgeMs"] = age(lastGlassesRingInputAtMs) + status["lastGlassesInput"] = lastGlassesRingInputLabel + status["lastDirectError"] = lastDirectRingError + status["glassesRingMac"] = glassesRingMac?.let { hex(it) } ?: "" + status["glassesRingName"] = glassesRingName + status["lastGlassesReport"] = lastGlassesRingReport + status["lastGlassesReportAgeMs"] = age(lastGlassesRingReportAtMs) + status["lastCommand"] = lastRingLinkCommand + status["lastCommandAgeMs"] = age(lastRingLinkCommandAtMs) + status["lastCommandResultR"] = lastRingLinkResultR + status["lastCommandResultL"] = lastRingLinkResultL + return try { Json.write(status) } catch (e: Exception) { "{}" } + } + } + + /** + * EXPERIMENTAL: ask the glasses to drop or re-establish their own link to + * the ring, so the phone can take the ring over directly and later hand + * it back. `action` is "disconnect", "release" or "connect"; see + * [queueGlassesRingLinkCommandLocked]. `fallbackAddress` ("AA:BB:..") and + * `fallbackName` are used only when the glasses have not reported their + * ring target this session. False when no session is up. + */ + fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean { + monitor.withLock { + if (!running || !sessionReady) { + logLine("skip glasses ring link command; session not ready") + return false + } + val ok = queueGlassesRingLinkCommandLocked(action, fallbackAddress ?: "", fallbackName ?: "") + if (!ok) return false + } + interruptibleSleep.interrupt() + return true + } + /** Status/results of the current or most recent benchmark run, as JSON. */ fun getBandwidthBenchmarkStatus(): String { monitor.withLock { @@ -1552,6 +1644,10 @@ class GlassesSessionCore( wearState = decodedWearState emitWearState = true } + if (frame.ok + && (frame.sid == BleProtocol.SID_SECURITY_AUTH || frame.sid == BleProtocol.SID_RING_DATA)) { + recordGlassesRingReportLocked(frame, address) + } var faceclawWakeNotification = false if (shutdownRequested && frame.ok @@ -1631,6 +1727,7 @@ class GlassesSessionCore( if (ring != null) { ringBattery = ring.battery ringCharging = ring.charging + lastGlassesRingBatteryAtMs = now() emitBatteryState(headsetBattery, headsetCharging) } } @@ -1696,6 +1793,10 @@ class GlassesSessionCore( && decoded.eventType == BleProtocol.EVENT_IMU_DATA_REPORT if (!pureImuSample) { lastConnectionOrInputAtMs = lastIncomingAtMs + if (decoded.eventSource == BleProtocol.EVENT_SOURCE_RING) { + lastGlassesRingInputAtMs = lastIncomingAtMs + lastGlassesRingInputLabel = decoded.kind + " type=" + decoded.eventType + } } if ("list-click" == decoded.kind || "text-click" == decoded.kind) { // Container-routed touchpad input reached us, so the @@ -1744,6 +1845,7 @@ class GlassesSessionCore( } internal fun handleDirectRingNotification(characteristicUuid: String, data: ByteArray) { + monitor.withLock { lastDirectRingNotifyAtMs = now() } if (handleRingHealthNotification(characteristicUuid, data)) { return } @@ -1758,6 +1860,8 @@ class GlassesSessionCore( monitor.withLock { lastIncomingAtMs = arrivalMs lastConnectionOrInputAtMs = arrivalMs + lastDirectRingInputAtMs = arrivalMs + lastDirectRingInputLabel = decoded.label + " " + decoded.detail } logLine("direct ring " + decoded.label + " " + decoded.detail + " raw=" + hex(data)) val frameId = frameTimings.startFrame("input:ring:" + decoded.label) @@ -1790,6 +1894,8 @@ class GlassesSessionCore( return } if (isConfiguredRingAddress(address)) { + if (connected != ringConnected) ringConnectedChangedAtMs = now() + if (connected && !ringConnected) ringConnectCount++ ringConnected = connected ringNotificationsReady = false if (!connected) { @@ -1979,12 +2085,21 @@ class GlassesSessionCore( try { connectRing() } catch (t: Throwable) { - monitor.withLock { + // Back off exponentially: each attempt's setup steps hold the + // GATT pipeline the glasses share, and an unreachable ring (e.g. + // held by the glasses) fails the same way every time. + val retryDelayMs = monitor.withLock { + val delay = minOf(ConnectionOptions.RING_RECONNECT_MAX_DELAY_MS, + ConnectionOptions.RING_RECONNECT_DELAY_MS.toLong() shl minOf(ringConnectFailures, 5)) + ringConnectFailures++ ringConnected = false ringNotificationsReady = false - ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS + ringReconnectAfterMs = now() + delay + lastDirectRingError = "connect failed: " + safeMessage(t) + delay } - logLine("direct ring connect failed (" + reason + "): " + safeMessage(t)) + logLine("direct ring connect failed (" + reason + "): " + safeMessage(t) + + "; retry in " + (retryDelayMs / 1000) + "s") } } @@ -2042,6 +2157,9 @@ class GlassesSessionCore( ringNonce = 0 ringReassembler.reset() ringOutbound.clear() + ringWriteBlockedUntilMs = 0L + ringWriteFailures = 0 + ringConnectFailures = 0 } logLine("direct ring ready phoneNotify=$phoneNotify dataNotify=$dataNotify") diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt index 7ad71f4d..f4a3879f 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt @@ -87,6 +87,10 @@ private const val RING_HEALTH_ABORTED_RETRY_LIMIT = 2 */ private const val RING_HEALTH_ABORTED_RETRY_GAP_MS = 60L * 1000L +/** First pause after a failed ring write; doubles per consecutive failure. See [writeRingFrame]. */ +private const val RING_WRITE_BACKOFF_MS = 1_000L +private const val RING_WRITE_BACKOFF_MAX_MS = 15_000L + /** * Device-channel commands Even's real app fires in the gaps between * health requests - identity (0x0a), battery (0x01), firmware version @@ -142,6 +146,7 @@ internal fun GlassesSessionCore.runRingWorker() { ringConnected = false ringNotificationsReady = false ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS + lastDirectRingError = "worker error: " + GlassesSessionCore.safeMessage(t) } link.disconnect(ringAddress) } @@ -690,24 +695,47 @@ internal fun GlassesSessionCore.sendRingDevicePing(cmdLo: Int) { writeRingFrame(frame, "device ping 0x" + cmdLo.toString(16)) } -/** Write one already-built ring frame. Ring worker only (blocking). */ +/** + * Write one already-built ring frame. Ring worker only (blocking). + * + * After a failure, further writes fail immediately (without touching the + * link) until an exponential backoff expires. The ring worker otherwise + * retries a queued ACK every 100ms tick, and each failing attempt can occupy + * the GATT pipeline the glasses' display writes need for up to the write + * timeout. + */ internal fun GlassesSessionCore.writeRingFrame(frame: ByteArray, what: String): Boolean { - return try { - val ok = link.writeFrames( + val blockedForMs = monitor.withLock { ringWriteBlockedUntilMs - now() } + if (blockedForMs > 0) { + return false + } + val ok = try { + val written = link.writeFrames( ringAddress, BleProtocol.R1_WRITE_CHAR_UUID, listOf(frame), ConnectionOptions.WRITE_MODE, ConnectionOptions.WRITE_TIMEOUT_MS ) - if (!ok) { + if (!written) { logLine("ring $what write failed") } - ok + written } catch (t: Throwable) { logLine("ring " + what + " write error: " + GlassesSessionCore.safeMessage(t)) false } + monitor.withLock { + if (ok) { + ringWriteFailures = 0 + } else { + val backoffMs = minOf(RING_WRITE_BACKOFF_MAX_MS, RING_WRITE_BACKOFF_MS shl minOf(ringWriteFailures, 4)) + ringWriteFailures++ + ringWriteBlockedUntilMs = now() + backoffMs + logLine("ring writes paused for " + backoffMs + "ms after " + ringWriteFailures + " consecutive failure(s)") + } + } + return ok } /** @@ -744,3 +772,106 @@ internal fun GlassesSessionCore.nextRingNonceLocked(): Int { ringNonce = (ringNonce + 1) and 0xffff return ringNonce } + +// --------------------------------------------------------------------------- +// The glasses' own link to the ring (sid 0x80 pair-manager commands) +// +// While the glasses hold the ring, it reports gestures only to them, so a +// direct phone link sees nothing. These ask the glasses to let go of it and +// to take it back. Shapes and handler behavior come from g2-kit-unofficial's +// protos and openCFW's decompilation of pb_service_pair_mgr.c; none of it has +// been captured from the Even app or verified on hardware. Deliberately no +// UNPAIR_INFO: that wipes the glasses' stored ring pairing. + +/** + * Parse "AA:BB:CC:DD:EE:FF" into wire order, least-significant byte first. + * Inferred, not verified: the one captured glasses-sent ring MAC + * (even-g2-protocol's "Device Identity", b1:6a:9f:2f:43:dc on sid 0x91) is + * only a valid random static address (top two bits set) read backwards. + */ +internal fun ringMacWireBytes(address: String): ByteArray? { + val parts = address.trim().split(':') + if (parts.size != 6) return null + val bytes = ByteArray(6) + for (i in 0 until 6) { + val value = parts[i].toIntOrNull(16) ?: return null + bytes[5 - i] = value.toByte() + } + return bytes +} + +/** + * Queue one ring-link command to both temples (only the ring-owning temple + * acts on a connect; either may hold the link). Actions: + * - "disconnect": DISCONNECT_INFO. Drops the link and resets the retry + * counter without touching the stored ring target; the glasses' own + * reconnect policy may take the ring back later. + * - "release": RING_CONNECT_INFO connect=0. Also cancels pending connect + * timeouts and clears the connect mode, so it may hold off auto-reconnect. + * - "connect": RING_CONNECT_INFO connect=1 with the ring's MAC and name. + * Both RING_CONNECT_INFO forms overwrite the stored target, so they echo the + * target the glasses reported when there is one. + */ +internal fun GlassesSessionCore.queueGlassesRingLinkCommandLocked( + action: String, fallbackAddress: String, fallbackName: String, +): Boolean { + val reported = glassesRingMac + val mac = reported ?: ringMacWireBytes(fallbackAddress) + if (mac == null) { + logLine("glasses ring $action skipped: no ring address") + return false + } + val name = (if (reported != null && glassesRingName.isNotEmpty()) glassesRingName else fallbackName) + .encodeToByteArray() + val macSource = if (reported != null) "glasses-reported" else "configured" + lastRingLinkCommand = "$action mac=${GlassesSessionCore.hex(mac)} ($macSource)" + lastRingLinkCommandAtMs = now() + lastRingLinkResultR = "sent" + lastRingLinkResultL = "sent" + for (leftArm in booleanArrayOf(false, true)) { + val message = messageBuilder.ringLinkCommand("glasses ring $action", leftArm) { magic -> + when (action) { + "disconnect" -> BleProtocol.buildRingDisconnectRequest(magic, mac) + "release" -> BleProtocol.buildRingConnectRequest(magic, false, mac, name) + else -> BleProtocol.buildRingConnectRequest(magic, true, mac, name) + } + } + message.onAck = MessageCallback { + val result = "ack " + GlassesSessionCore.hex(message.ackPayload) + if (leftArm) lastRingLinkResultL = result else lastRingLinkResultR = result + logLine("glasses ring $action ${if (leftArm) "L" else "R"} $result") + } + message.onTimeout = MessageCallback { + if (leftArm) lastRingLinkResultL = "no ack" else lastRingLinkResultR = "no ack" + logLine("glasses ring $action ${if (leftArm) "L" else "R"} ack timeout") + } + pendingMessages.addLast(message) + } + logLine("queue glasses ring $action mac=${GlassesSessionCore.hex(mac)} ($macSource) name=${name.decodeToString()}") + return true +} + +/** + * Note ring-link reports from the glasses: RING_CONNECT_INFO notifications + * (connRet 0 = connected, 90 = connect timeout) and sid-0x91 ring events, + * both carrying the ring MAC in the glasses' byte order. Acks to our own + * commands are skipped for the MAC so it never just echoes our guess. + */ +internal fun GlassesSessionCore.recordGlassesRingReportLocked(frame: BleProtocol.ParsedFrame, address: String) { + val report = if (frame.sid == BleProtocol.SID_RING_DATA) BleProtocol.parseRingDataEvent(frame.pb) + else BleProtocol.parseRingConnectInfo(frame.pb) + if (report == null) return + val arm = if (address.equals(leftAddress, ignoreCase = true)) "L" else "R" + val ownAck = inFlightMessages.any { it.sid == frame.sid && it.magic == frame.msgSeq } + val mac = report.ringMac + lastGlassesRingReport = report.source + " " + arm + " code=" + report.code + + (if (mac != null) " mac=" + GlassesSessionCore.hex(mac) else "") + + (if (report.ringName.isNotEmpty()) " name=" + report.ringName else "") + + (if (ownAck) " (ack)" else "") + lastGlassesRingReportAtMs = now() + if (!ownAck && mac != null && mac.size == 6 && mac.any { it.toInt() != 0 }) { + glassesRingMac = mac.copyOf() + if (report.ringName.isNotEmpty()) glassesRingName = report.ringName + } + logLine("glasses ring report: $lastGlassesRingReport") +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt index cc84dac9..1fdcbcdc 100644 --- a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt @@ -161,6 +161,9 @@ class IosGlassesSession internal constructor( fun cancelBandwidthBenchmark() = core.cancelBandwidthBenchmark() fun getBandwidthBenchmarkStatus(): String = core.getBandwidthBenchmarkStatus() + fun getRingStatus(): String = core.getRingStatus() + fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean = + core.setGlassesRingLink(action, fallbackAddress, fallbackName) fun addImuListener(listener: FaceclawImuListener?) = core.addImuListener(listener) diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt new file mode 100644 index 00000000..313b06af --- /dev/null +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt @@ -0,0 +1,47 @@ +package com.faceclaw.app + +import kotlin.test.* + +class GlassesRingLinkTest { + private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + private fun toHex(bytes: ByteArray) = bytes.joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') } + private val mac = hex("b16a9f2f43dc") + + @Test fun ringMacWireBytesAreLeastSignificantFirst() { + assertEquals("b16a9f2f43dc", toHex(assertNotNull(ringMacWireBytes("DC:43:2F:9F:6A:B1")))) + assertNull(ringMacWireBytes("")) + assertNull(ringMacWireBytes("DC:43:2F:9F:6A")) + assertNull(ringMacWireBytes("DC:43:2F:9F:6A:ZZ")) + } + + @Test fun disconnectRequestWireShape() { + // commandId=8 magic=0x21 disconnectInfo(7){dev=0, ringMac} + assertEquals("080810213a0a08001206b16a9f2f43dc", toHex(BleProtocol.buildRingDisconnectRequest(0x21, mac))) + } + + @Test fun connectRequestWireShape() { + // commandId=6 magic=0x21 ringInfo(5){connectRing=[01], ringMac, ringName="R1"} + assertEquals("08061021" + "2a" + "0f" + "0a0101" + "1206b16a9f2f43dc" + "1a025231", + toHex(BleProtocol.buildRingConnectRequest(0x21, true, mac, "R1".encodeToByteArray()))) + } + + @Test fun parsesGlassesReportsThroughFraming() { + // A RING_CONNECT_INFO notification: ringInfo{connectRing, ringMac, ringName, connRet=0}. + val info = hex("0a0101") + hex("1206") + mac + hex("1a025231") + hex("2000") + val pb = hex("0806") + hex("1005") + byteArrayOf(0x2a, info.size.toByte()) + info + val frame = BleProtocol.parseFrame(BleProtocol.framePb(pb, BleProtocol.SID_SECURITY_AUTH, 1, 1).single()) + val report = assertNotNull(BleProtocol.parseRingConnectInfo(frame.pb)) + assertEquals("b16a9f2f43dc", toHex(assertNotNull(report.ringMac))) + assertEquals("R1", report.ringName) + assertEquals(0, report.code) + + // even-g2-protocol's captured sid-0x91 "Device Identity": {1:1, 2:19, 3:{1:mac, 2:1}} + val event = hex("08011013" + "1a0a" + "0a06b16a9f2f43dc" + "1001") + val eventFrame = BleProtocol.parseFrame(BleProtocol.framePb(event, BleProtocol.SID_RING_DATA, 1, 1).single()) + val ringEvent = assertNotNull(BleProtocol.parseRingDataEvent(eventFrame.pb)) + assertEquals("b16a9f2f43dc", toHex(assertNotNull(ringEvent.ringMac))) + assertEquals(1, ringEvent.code) + + assertNull(BleProtocol.parseRingConnectInfo(BleProtocol.buildAuthenticationRequest(3))) + } +} diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingHealthTransferTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingHealthTransferTest.kt index 06814dad..5161b52d 100644 --- a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingHealthTransferTest.kt +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/RingHealthTransferTest.kt @@ -191,10 +191,31 @@ class RingHealthTransferTest { assertEquals(1, s.link.writes.size, "advanced after failed ACK") assertEquals(1, s.outboundSize(), "failed ACK was discarded") s.link.failAck = false + // The failure paused ring writes; the retry must not touch the link yet. + assertEquals(-1, s.core.flushRingOutbound(), "retried inside the write backoff") + assertEquals(1, s.outboundSize(), "backoff dropped the queued ACK") + s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L } assertTrue(s.core.awaitRingHealthDataIdle(s.core.ringHealthDataIdleMs), "retry failed") assertEquals(0, s.outboundSize(), "retry did not drain ACKs") } + @Test fun writeBackoffGrowsAndResetsOnSuccess() { + val s = RingSession() + s.link.failAck = true + s.core.queueRingPageAck(RingProtocol.parse(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, + RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE, RingProtocol.CMD_LO_HEALTH, 1, byteArrayOf(0, 0)))!!) + fun pausedForMs() = s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs - s.core.now() } + assertEquals(-1, s.core.flushRingOutbound()) + val first = pausedForMs() + s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L } + assertEquals(-1, s.core.flushRingOutbound()) + assertTrue(pausedForMs() > first, "backoff did not grow") + s.link.failAck = false + s.core.monitor.withLock { s.core.ringWriteBlockedUntilMs = 0L } + assertEquals(1, s.core.flushRingOutbound()) + assertEquals(0, s.core.monitor.withLock { s.core.ringWriteFailures }, "success did not reset the backoff") + } + @Test fun missingRspAbortsWithoutAdvancing() { val s = RingSession() s.link.answer = false