Autoconfigure ring for direct connection

This commit is contained in:
James Babcock committed 2026-10-06 22:29:03 -07:00
1 parent f38595422c
commit d7a02f25fb
11 files changed
+294 -89

No files matched your search

@@ -25,8 +25,14 @@ class BleProtocol {
// R1 ring, vendor service bae80001-4f05-4503-8e65-3af1f7329d1f. The service
// holds two write/notify pairs: bae80010 (write) + bae80011 (notify), and
// bae80012 (write) + bae80013 (notify). The health-data protocol
// (RingProtocol) rides the SECOND pair.
const val R1_PHONE_NOTIFY_CHAR_UUID: String = "bae80011-4f05-4503-8e65-3af1f7329d1f"
// (RingProtocol) rides the SECOND pair. The first is the legacy channel
// the glasses use: enabling its CCCD gives a link the ring's glasses
// role, and the ring sends gestures and battery there (RingProtocol's
// legacy-channel section).
const val R1_LEGACY_NOTIFY_CHAR_UUID: String = "bae80011-4f05-4503-8e65-3af1f7329d1f"
/** Legacy-channel writes (write without response), e.g. the glasses' 00 35 88 00. */
const val R1_LEGACY_WRITE_CHAR_UUID: String = "bae80010-4f05-4503-8e65-3af1f7329d1f"
const val R1_NOTIFY_CHAR_UUID: String = "bae80013-4f05-4503-8e65-3af1f7329d1f"
@@ -311,6 +311,46 @@ class RingProtocol private constructor() {
}
}
// ------------------------------------------------------------------
// Legacy (glasses-role) channel: bae80010 write / bae80011 notify
//
// Raw frames with the opcode in byte 2, not the 0x64 models above. What
// the G2 sends and what the ring answers come from g2-firmware-emulator
// (docs/r1-command88-native.md, r1-cccd-frontier.md) running the stock
// firmwares; the gesture report shape is in FaceclawRingEventDecoder.
// ------------------------------------------------------------------
/**
* The G2's legacy pair-auth, opcode 0x88, captured from the stock glasses
* firmware writing it right after enabling the bae80011 CCCD. The ring
* marks the link as its glasses peer and checks it against the advStart
* targets: accepted (a target matches, or none are set) answers with a
* battery report; rejected answers [LEGACY_TARGET_REJECTED] and drops the
* link about 20 s later.
*/
@JvmField val LEGACY_GLASSES_PAIR_AUTH: ByteArray = byteArrayOf(0x00, 0x35, 0x88.toByte(), 0x00)
/** The ring's "non-target glasses connected" notice, opcode 0x96. */
@JvmField val LEGACY_TARGET_REJECTED: ByteArray = byteArrayOf(0x00, 0x01, 0x96.toByte(), 0x00)
/**
* The ring's battery report to its glasses peer, `00 09 8B 00 <percent>
* <charging>`: sent when a glasses pair-auth is accepted and whenever the
* percentage changes. Null for anything else.
*/
@JvmStatic
fun parseLegacyBattery(raw: ByteArray?): DeviceStatus? {
if (raw == null || raw.size != 6 || raw[0].toInt() != 0x00 || raw[1].toInt() != 0x09 ||
(raw[2].toInt() and 0xff) != 0x8B || raw[3].toInt() != 0x00) return null
val battery = raw[4].toInt() and 0xff
if (battery > 100) return null
return DeviceStatus(battery, if (raw[5].toInt() != 0) 1 else 0)
}
@JvmStatic
fun isLegacyTargetRejected(raw: ByteArray?): Boolean =
raw != null && raw.contentEquals(LEGACY_TARGET_REJECTED)
private fun nonceBytes(nonce: Int): ByteArray {
return byteArrayOf((nonce and 0xff).toByte(), ((nonce ushr 8) and 0xff).toByte())
}
@@ -354,8 +354,17 @@ class GlassesSessionCore(
internal var lastRingLinkResultR = ""
internal var lastRingLinkResultL = ""
// Which of the ring's two roles the direct link claims; see setDirectRingRole.
internal var directRingRole = DIRECT_RING_ROLE_BOTH
internal var directRingRole = DIRECT_RING_ROLE_PHONE
internal var ringRoleReconnectPending = false
// Glasses-role direct link: the per-connection setup (legacy pair-auth +
// touch source on) still to be written, what the ring made of the
// pair-auth, and the once-per-connection target clear after a rejection.
internal var ringGlassesSetupPending = false
internal var directGlassesAuth = ""
internal var directGlassesAuthAtMs = 0L
internal var directGlassesAuthRetried = false
// Last time we asked the glasses to unpair the ring for the direct link.
internal var lastRingReleaseAtMs = 0L
// Ring-side binding commands (system channel) waiting for the ring worker,
// the one written and not yet answered, and the last one's outcome.
internal val ringConfigQueue = ArrayDeque<RingConfigCommand>()
@@ -1010,6 +1019,8 @@ class GlassesSessionCore(
status["lastCommandResultR"] = lastRingLinkResultR
status["lastCommandResultL"] = lastRingLinkResultL
status["directRole"] = directRingRole
status["directGlassesAuth"] = directGlassesAuth
status["directGlassesAuthAgeMs"] = age(directGlassesAuthAtMs)
status["lastRingCommand"] = lastRingConfigCommand
status["lastRingCommandAgeMs"] = age(lastRingConfigCommandAtMs)
status["lastRingCommandResult"] = lastRingConfigResult
@@ -1021,24 +1032,20 @@ class GlassesSessionCore(
/**
* Which ring role the direct link claims. The R1 holds one phone role and
* one glasses role at a time and sends gestures only to the glasses role
* (openCFW R1 decompilation):
* - "phone": pairAuth on the system channel, health sync; only the data
* CCCD (what Even's app does).
* - "glasses": enable the legacy-channel CCCD, which appears to be what
* assigns a link the glasses role, and skip pairAuth and health. Only works while the
* glasses themselves do not hold that role.
* - "both": the long-standing default, both CCCDs plus pairAuth. If the
* glasses role is free this probably asks for both roles on one link;
* the decompiled stock role setter hits a fatal assertion on that.
* A change while the direct link is up reconnects it.
* one glasses role, on separate links, and sends gestures and battery
* pushes only to the glasses role:
* - "phone" (default): pairAuth on the system channel and health sync,
* with only the data CCCD, like Even's app. The glasses keep the ring.
* - "glasses": act as the ring's glasses (legacy CCCD, legacy pair-auth,
* touch source on; see runRingGlassesSetup) and take the ring over from
* the glasses when they still hold it. No health sync: the ring answers
* system requests only on a phone-role link.
* Asking for both on one link (the old behavior) made the ring drop the
* link every ~6 s while the glasses held it. A change while the direct
* link is up reconnects it.
*/
fun setDirectRingRole(role: String?) {
val normalized = when (role) {
DIRECT_RING_ROLE_PHONE -> DIRECT_RING_ROLE_PHONE
DIRECT_RING_ROLE_GLASSES -> DIRECT_RING_ROLE_GLASSES
else -> DIRECT_RING_ROLE_BOTH
}
val normalized = if (role == DIRECT_RING_ROLE_GLASSES) DIRECT_RING_ROLE_GLASSES else DIRECT_RING_ROLE_PHONE
monitor.withLock {
if (normalized == directRingRole) return
directRingRole = normalized
@@ -1872,6 +1879,7 @@ class GlassesSessionCore(
ringCharging = ring.charging
lastGlassesRingBatteryAtMs = now()
emitBatteryState(headsetBattery, headsetCharging)
if (ring.battery >= 0) releaseRingFromGlassesLocked("glasses report the ring connected")
}
}
// CFW mic status (field 104) rides both standalone pushes and
@@ -1939,6 +1947,7 @@ class GlassesSessionCore(
if (decoded.eventSource == BleProtocol.EVENT_SOURCE_RING) {
lastGlassesRingInputAtMs = lastIncomingAtMs
lastGlassesRingInputLabel = decoded.kind + " type=" + decoded.eventType
releaseRingFromGlassesLocked("ring input relayed by the glasses")
}
}
if ("list-click" == decoded.kind || "text-click" == decoded.kind) {
@@ -2010,6 +2019,9 @@ class GlassesSessionCore(
if (handleRingHealthNotification(characteristicUuid, data)) {
return
}
if (handleRingLegacyControl(data)) {
return
}
val decoded = FaceclawRingEventDecoder.decode(data)
if (decoded == null) {
monitor.withLock {
@@ -2362,10 +2374,10 @@ class GlassesSessionCore(
// only to that role. The direct ring
// role setting decides which CCCDs we enable; see setDirectRingRole.
val role = monitor.withLock { directRingRole }
val phoneNotify = role != DIRECT_RING_ROLE_PHONE
&& enableRingNotification(BleProtocol.R1_PHONE_NOTIFY_CHAR_UUID)
val legacyNotify = role == DIRECT_RING_ROLE_GLASSES
&& enableRingNotification(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID)
val dataNotify = enableRingNotification(BleProtocol.R1_NOTIFY_CHAR_UUID)
if (!phoneNotify && !dataNotify) {
if (!legacyNotify && !dataNotify) {
throw IllegalStateException("no R1 notify characteristic subscribed")
}
@@ -2381,12 +2393,18 @@ class GlassesSessionCore(
ringWriteBlockedUntilMs = 0L
ringWriteFailures = 0
ringConnectFailures = 0
// The ring forgets touch-source state with the link, so every
// glasses-role connection repeats the setup (runRingGlassesSetup).
ringGlassesSetupPending = role == DIRECT_RING_ROLE_GLASSES
directGlassesAuth = ""
directGlassesAuthAtMs = 0L
directGlassesAuthRetried = false
}
logLine("direct ring ready role=$role phoneNotify=$phoneNotify dataNotify=$dataNotify")
logLine("direct ring ready role=$role legacyNotify=$legacyNotify dataNotify=$dataNotify")
// Claiming the glasses role means no pairAuth (it would ask for the
// phone role on the same link) and therefore no health sync.
if (dataNotify && host.supportsRingHealth() && role != DIRECT_RING_ROLE_GLASSES) {
// The glasses role means no pairAuth (it would ask for the phone role
// on the same link) and therefore no health sync.
if (dataNotify && host.supportsRingHealth() && role == DIRECT_RING_ROLE_PHONE) {
onRingDataChannelReady()
}
}
@@ -2528,7 +2546,7 @@ class GlassesSessionCore(
if (!isConfiguredRingAddress(address) || characteristicUuid == null) {
return false
}
return BleProtocol.R1_PHONE_NOTIFY_CHAR_UUID == characteristicUuid
return BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID == characteristicUuid
|| BleProtocol.R1_NOTIFY_CHAR_UUID == characteristicUuid
}
@@ -134,6 +134,7 @@ internal fun GlassesSessionCore.runRingWorker() {
if (shouldAttemptRingConnect()) tryConnectRing("ring worker")
if (!running) break
flushRingConfigCommands()
runRingGlassesSetup()
flushRingOutbound()
runRequestedRingHealthPull()
resumeAbortedRingHealthPull()
@@ -695,7 +696,9 @@ internal fun GlassesSessionCore.sendRingDevicePing(cmdLo: Int) {
* the GATT pipeline the glasses' display writes need for up to the write
* timeout.
*/
internal fun GlassesSessionCore.writeRingFrame(frame: ByteArray, what: String): Boolean {
internal fun GlassesSessionCore.writeRingFrame(
frame: ByteArray, what: String, characteristicUuid: String = BleProtocol.R1_WRITE_CHAR_UUID,
): Boolean {
val blockedForMs = monitor.withLock { ringWriteBlockedUntilMs - now() }
if (blockedForMs > 0) {
return false
@@ -703,7 +706,7 @@ internal fun GlassesSessionCore.writeRingFrame(frame: ByteArray, what: String):
val ok = try {
val written = link.writeFrames(
ringAddress,
BleProtocol.R1_WRITE_CHAR_UUID,
characteristicUuid,
listOf(frame),
ConnectionOptions.WRITE_MODE,
ConnectionOptions.WRITE_TIMEOUT_MS
@@ -870,6 +873,9 @@ internal fun GlassesSessionCore.recordGlassesRingReportLocked(frame: BleProtocol
if (report.ringName.isNotEmpty()) glassesRingName = report.ringName
}
logLine("glasses ring report: $lastGlassesRingReport")
if (!ownAck && frame.sid != BleProtocol.SID_RING_DATA && report.code == 0) {
releaseRingFromGlassesLocked("glasses connected the ring")
}
}
// ---------------------------------------------------------------------------
@@ -883,7 +889,6 @@ internal fun GlassesSessionCore.recordGlassesRingReportLocked(frame: BleProtocol
// (advStart, then RING_CONNECT_INFO to the glasses) is from its decompiled
// EvConnect.startRingAdvForCurrentGlasses. Not verified on hardware.
internal const val DIRECT_RING_ROLE_BOTH = "both"
internal const val DIRECT_RING_ROLE_PHONE = "phone"
internal const val DIRECT_RING_ROLE_GLASSES = "glasses"
@@ -1043,3 +1048,99 @@ internal fun GlassesSessionCore.restartRingLinkForRoleChange() {
logLine("direct ring: reconnecting to take the $role role")
link.disconnect(ringAddress)
}
// ---------------------------------------------------------------------------
// Acting as the ring's glasses (direct ring role "glasses")
//
// Mirrors what the stock G2 does on connecting to its ring
// (g2-firmware-emulator docs/r1-cccd-frontier.md, r1-command88-native.md):
// enable the legacy CCCD (connectRing), then write the legacy pair-auth. We
// add touchSwitch "glasses source on", without which a link gets no
// gestures (hardware, 2026-10-06). The ring keeps its targets and the
// glasses keep their unpairing across connections, so those are sent only
// when the ring or the glasses show they are still bound to each other.
/** Floor between automatic glasses unpair requests, so a fight with something re-binding the ring stays slow. */
private const val RING_RELEASE_MIN_INTERVAL_MS = 2L * 60L * 1000L
/**
* The per-connection glasses-role setup. Ring worker only; a failed write
* leaves it pending for the next tick (after writeRingFrame's backoff).
*/
internal fun GlassesSessionCore.runRingGlassesSetup() {
monitor.withLock {
if (!ringGlassesSetupPending || !ringNotificationsReady) return
// Before the write: the ring answers within milliseconds.
directGlassesAuth = "sent"
directGlassesAuthAtMs = now()
}
if (!writeRingFrame(RingProtocol.LEGACY_GLASSES_PAIR_AUTH, "glasses pair-auth", BleProtocol.R1_LEGACY_WRITE_CHAR_UUID)) {
return
}
val touch = monitor.withLock {
RingProtocol.buildTouchSwitch(nextRingSeqLocked(), RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, true)
}
if (!writeRingFrame(touch, "touch source on")) {
return
}
monitor.withLock { ringGlassesSetupPending = false }
logLine("direct ring: sent glasses pair-auth and touch source on")
}
/**
* Legacy-channel control frames that are not input: the battery report and
* the target rejection. Returns true when consumed. GATT callback thread.
*/
internal fun GlassesSessionCore.handleRingLegacyControl(data: ByteArray): Boolean {
val battery = RingProtocol.parseLegacyBattery(data)
if (battery != null) {
monitor.withLock {
directRingBattery = battery.battery
directRingCharging = battery.charging
// Only the accepted glasses peer gets these.
directGlassesAuth = "accepted"
directGlassesAuthAtMs = now()
emitBatteryState(headsetBattery, headsetCharging)
}
logLine("direct ring battery " + battery.battery + "% charging=" + battery.charging + " (legacy report)")
return true
}
if (!RingProtocol.isLegacyTargetRejected(data)) {
return false
}
// The ring's advStart targets name other glasses (normally ours, from the
// Even app's pairing), so it drops this link in ~20 s. Clear them once per
// connection, then repeat the pair-auth so it is checked again.
val clearing = monitor.withLock {
directGlassesAuthAtMs = now()
if (directGlassesAuthRetried) {
directGlassesAuth = "rejected again: ring is bound to other glasses"
false
} else {
directGlassesAuthRetried = true
directGlassesAuth = "rejected: clearing the ring's glasses targets"
queueRingConfigCommandLocked("remove-ring", null, "", "")
ringGlassesSetupPending = true
true
}
}
logLine("direct ring: glasses pair-auth rejected (ring bound to other glasses)"
+ if (clearing) "; clearing its targets and retrying" else "; giving up for this connection")
return true
}
/**
* The glasses still hold the ring while the direct link wants its glasses
* role: ask them to unpair it (UNPAIR_INFO), which they remember until
* something re-pairs them. Rate-limited. Caller holds `monitor`.
*/
internal fun GlassesSessionCore.releaseRingFromGlassesLocked(reason: String) {
if (!hasRingAddress() || directRingRole != DIRECT_RING_ROLE_GLASSES || !running || !sessionReady) return
val now = now()
if (lastRingReleaseAtMs != 0L && now - lastRingReleaseAtMs < RING_RELEASE_MIN_INTERVAL_MS) return
lastRingReleaseAtMs = now
logLine("direct ring: the glasses still hold the ring ($reason); asking them to unpair it")
if (queueGlassesRingLinkCommandLocked("unpair", ringAddress, glassesRingName)) {
interruptibleSleep.interrupt()
}
}
@@ -1033,6 +1033,7 @@ internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessa
// Old firmware and missing/malformed extensions must clear any prior reading.
ringBattery = if (ring == null) -1 else ring.battery
ringCharging = if (ring == null) -1 else ring.charging
if (ringBattery >= 0) releaseRingFromGlassesLocked("glasses report the ring connected")
val snapshot = BleProtocol.parseSettingsBattery(message.ackPayload)
if (snapshot != null) {
headsetBattery = snapshot.battery