Add ring debug; change GATT locking

This commit is contained in:
James Babcock committed 2026-09-27 15:32:49 -07:00
1 parent a8c9ab0a98
commit c119883ca0
13 files changed
+915 -81

No files matched your search

@@ -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
@@ -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'
@@ -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(
@@ -150,6 +150,17 @@ class GlassesSessionCore(
// write timeout. The ring worker drains the queue instead.
internal val ringReassembler = RingProtocol.Reassembler()
internal val ringOutbound = ArrayDeque<ByteArray>()
/**
* 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<RingProtocol.HealthRecord>()
/**
* 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<String, Any?>()
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")
@@ -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")
}
@@ -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)