Build out Ring Status debug tool; fix some aspects of ring direct communication

This commit is contained in:
James Babcock committed 2026-10-06 19:53:43 -07:00
1 parent e12cfaaf38
commit f38595422c
16 files changed
+812 -173

No files matched your search

@@ -69,6 +69,7 @@ class BleProtocol {
// hardware-verified.
private const val DEV_CFG_RING_CONNECT_INFO_CMD: Int = 6
private const val DEV_CFG_DISCONNECT_INFO_CMD: Int = 8
private const val DEV_CFG_UNPAIR_INFO_CMD: Int = 9
/** sid 0x91 RingDataPackage: glasses-side ring events (g2.ring). */
const val SID_RING_DATA: Int = 0x91
@@ -195,6 +196,12 @@ class BleProtocol {
const val EVENT_HEAD_UP: Int = 12
/** Faceclaw/18: R1 touch-down, before the gesture is known (R1 2.3.0+, wire type 10). */
const val EVENT_RING_PRESS: Int = 14
/** CFW's SysEvent for an R1 wire type it has no mapping for; diagnostics only. */
const val EVENT_RING_UNKNOWN: Int = 127
const val EVENT_SOURCE_GLASSES_R: Int = 1
const val EVENT_SOURCE_RING: Int = 2
@@ -533,6 +540,26 @@ class BleProtocol {
)
}
/**
* UNPAIR_INFO(9) with UnpairInfo{dev=RING(0), ringMac}: the glasses forget their stored ring
* pairing. Never dev=RING_GLASSES(2): openCFW's decompilation shows that also enters OTA
* mode and unpairs the phone from the glasses. The handler uses the MAC only when it is
* exactly 6 bytes; whether it compares it against the stored ring is unknown.
*/
@JvmStatic
fun buildRingUnpairRequest(magic: Int, ringMac: ByteArray): ByteArray {
return concat(
CollectionUtils.listOf(
encodeVarintField(1, DEV_CFG_UNPAIR_INFO_CMD),
encodeVarintField(2, magic),
encodeMessageField(8, 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'
@@ -10,57 +10,50 @@ class FaceclawRingEventDecoder {
if (((raw == null) || (raw.size == 0))) {
return null
}
var chargerGesture: DirectRingEvent? = decodeChargerGesture(raw)
if ((chargerGesture != null)) {
return chargerGesture
var report: DirectRingEvent? = decodeRingReport(raw)
if ((report != null)) {
return report
}
return decodeDirectGesture(raw)
}
private fun decodeChargerGesture(raw: ByteArray): DirectRingEvent? {
if ((raw.size != 11)) {
/**
* The R1's standard input report, `00 09 61 00 TYPE AUX SPEED TICK_LE32`: the same
* 11 bytes the ring sends the glasses, which CFW's gesture_fwd.c forwards as an EvenHub
* SysEvent. TYPE maps exactly as CFW maps it, and the raw fields ride along as ring
* metadata, so direct and glasses-relayed input look the same to the TypeScript side
* (including RingInputFilter's 100-tick suppression). Unmapped types become
* EVENT_RING_UNKNOWN, which is kept for diagnostics but never routed as a gesture.
*/
private fun decodeRingReport(raw: ByteArray): DirectRingEvent? {
if (raw.size != 11 || u8(raw[0]) != 0x00 || u8(raw[1]) != 0x09 ||
u8(raw[2]) != 0x61 || u8(raw[3]) != 0x00) {
return null
}
if (
((((u8(raw[0]) != 0x00) || (u8(raw[1]) != 0x09)) || (u8(raw[2]) != 0x61)) ||
(u8(raw[3]) != 0x00))
) {
return null
val type = u8(raw[4])
val aux = u8(raw[5])
val speed = u8(raw[6])
val tick = (u8(raw[7]) or (u8(raw[8]) shl 8) or (u8(raw[9]) shl 16) or (u8(raw[10]) shl 24))
.toLong() and 0xffffffffL
val label = ringReportTypeName(type)
val eventType = when (type) {
0x00 -> BleProtocol.EVENT_RING_LONG_PRESS
0x01 -> BleProtocol.EVENT_CLICK
0x02 -> BleProtocol.EVENT_DOUBLE_CLICK
0x04 -> BleProtocol.EVENT_SCROLL_TOP
0x05 -> BleProtocol.EVENT_SCROLL_BOTTOM
0x08 -> BleProtocol.EVENT_RING_LONG_PRESS_RELEASE
0x09 -> BleProtocol.EVENT_SHORT_THEN_LONG_PRESS
0x0a -> BleProtocol.EVENT_RING_PRESS
else -> BleProtocol.EVENT_RING_UNKNOWN
}
var code: Int = u8(raw[4])
var param: Int = (u8(raw[5]) or (u8(raw[6]) shl 8))
var tick: Long =
((((u8(raw[7]) or (u8(raw[8]) shl 8)) or (u8(raw[9]) shl 16)) or
(u8(raw[10]) shl 24))
.toLong() and 0xffffffffL)
var detail: String =
"code=0x${code.toString(16).padStart(2, '0')}(${chargerCodeName(code)}) param=0x${param.toString(16).padStart(4, '0')} tick=$tick"
when (code) {
0x00 -> {
return event(BleProtocol.EVENT_RING_LONG_PRESS, "LONG_PRESS", detail)
}
0x01 -> {
return event(BleProtocol.EVENT_CLICK, "TAP", detail)
}
0x02 -> {
return event(BleProtocol.EVENT_DOUBLE_CLICK, "DOUBLE_TAP", detail)
}
0x04 -> {
return event(BleProtocol.EVENT_SCROLL_TOP, "SWIPE_UP", detail)
}
0x05 -> {
return event(BleProtocol.EVENT_SCROLL_BOTTOM, "SWIPE_DOWN", detail)
}
0x08 -> {
return event(
BleProtocol.EVENT_RING_LONG_PRESS_RELEASE,
"LONG_PRESS_RELEASE",
detail,
)
}
else -> {
return null
}
val detail = "type=0x${type.toString(16).padStart(2, '0')}($label) " +
"aux=0x${aux.toString(16).padStart(2, '0')} speed=0x${speed.toString(16).padStart(2, '0')} tick=$tick"
return event(eventType, label, detail).also {
it.event.ringTick = tick
it.event.ringType = type
it.event.ringAux = aux
it.event.ringSpeed = speed
}
}
@@ -96,29 +89,17 @@ class FaceclawRingEventDecoder {
return DirectRingEvent(event, label, detail)
}
private fun chargerCodeName(code: Int): String {
when (code) {
0x00 -> {
return "LONG_PRESS"
}
0x01 -> {
return "TAP"
}
0x02 -> {
return "DOUBLE_TAP"
}
0x04 -> {
return "SWIPE_UP"
}
0x05 -> {
return "SWIPE_DOWN"
}
0x08 -> {
return "LONG_PRESS_RELEASE"
}
else -> {
return "unknown"
}
private fun ringReportTypeName(type: Int): String {
return when (type) {
0x00 -> "LONG_PRESS"
0x01 -> "TAP"
0x02 -> "DOUBLE_TAP"
0x04 -> "SWIPE_UP"
0x05 -> "SWIPE_DOWN"
0x08 -> "LONG_PRESS_RELEASE"
0x09 -> "TAP_THEN_HOLD"
0x0a -> "TOUCH_DOWN"
else -> "UNKNOWN"
}
}
@@ -73,6 +73,21 @@ class RingProtocol private constructor() {
const val CMD_HI_DEVICE: Int = 0x00
const val CMD_LO_PAGE_ACK: Int = 0x7E
/**
* System-channel (00:xx) commands that configure the ring's binding.
* Subcommand numbers and handler behavior are from openCFW's R1
* decompilation (r1/src/r1_dispatch.c, r1/docs/correlation/
* CONNECTION-CONTROL-CORRELATION.md); g2-kit-unofficial's ring.ts names
* the same table. Only pairAuth and advStart have been seen in a capture
* of Even's app.
*/
const val CMD_LO_TOUCH_SWITCH: Int = 0x07
const val CMD_LO_PAIR_AUTH: Int = 0x08
const val CMD_LO_ADV_START: Int = 0x0A
const val CMD_LO_REMOVE_RING_NOTIFY: Int = 0x82
/** touchSwitch selector for the glasses touch source; selector 1 (phone) is diagnostic-only. */
const val TOUCH_SWITCH_SELECTOR_GLASSES: Int = 2
/**
* The five health pulls, in the order Even's own app issues them:
* heart rate, HRV, SpO2, sleep, steps. That order is identical in all four
@@ -202,6 +217,100 @@ class RingProtocol private constructor() {
return buildFrame(CHAN_DEVICE, KIND_ACK, CMD_HI_DEVICE, CMD_LO_PAGE_ACK, seq, payload)
}
/**
* The ring's phone-direction model checksum: the two bytes that sit
* where [buildFrame]'s callers put a "nonce". It is a CRC-16 (Nordic
* crc16_compute, init 0xFFFF) over header bytes 5-8 and 10-14 (skipping
* the high byte of the 16-bit serial) and then the arguments. Verified
* against five captured Even-app frames; see GlassesRingLinkTest.
*
* Most of our frames still carry a counter there instead and the ring
* answers them anyway, so the ring does not seem to enforce it; the
* binding commands below compute it so they do not depend on that.
*/
@JvmStatic
fun phoneChecksum(chan: Int, seq: Int, kind: Int, cmdHi: Int, cmdLo: Int, args: ByteArray): Int {
val plen = HEADER_LEN + 2 + args.size - 5
val header = byteArrayOf(
MAGIC.toByte(), chan.toByte(), MAGIC.toByte(), seq.toByte(),
kind.toByte(), cmdHi.toByte(), cmdLo.toByte(), plen.toByte(), (plen ushr 8).toByte(),
)
var crc = 0xffff
for (b in header + args) {
crc = ((crc ushr 8) or (crc shl 8)) and 0xffff
crc = crc xor (b.toInt() and 0xff)
crc = crc xor ((crc and 0xff) ushr 4)
crc = crc xor ((crc shl 12) and 0xffff)
crc = crc xor (((crc and 0xff) shl 5) and 0xffff)
}
return crc
}
/** A frame whose two leading payload bytes are the [phoneChecksum] of `args`. */
@JvmStatic
fun buildCheckedFrame(chan: Int, kind: Int, cmdHi: Int, cmdLo: Int, seq: Int, args: ByteArray): ByteArray {
val crc = phoneChecksum(chan, seq, kind, cmdHi, cmdLo, args)
return buildFrame(chan, kind, cmdHi, cmdLo, seq, nonceBytes(crc) + args)
}
/**
* pairAuth (00:08) with role byte 1: claims the ring's phone role, after
* which the ring asks for link security (bonding) and starts answering
* requests. For seq 1 this is byte-identical to Even's captured frame.
*/
@JvmStatic
fun buildPairAuth(seq: Int): ByteArray =
buildCheckedFrame(CHAN_DEVICE, KIND_REQ, CMD_HI_DEVICE, CMD_LO_PAIR_AUTH, seq, byteArrayOf(0x01))
/**
* advStart (00:0A): the two glasses addresses the ring will accept as
* its glasses peer, each in wire order (least-significant byte first).
* The ring persists them, disconnects a connected glasses peer that
* matches neither (after ~20 s), and treats a slot of all 00 or all FF
* as unset; with both unset it accepts any glasses peer. Sent with the
* REQ status byte because that is what Even's captured frames use.
*/
@JvmStatic
fun buildAdvStart(seq: Int, first: ByteArray, second: ByteArray): ByteArray {
require(first.size == 6 && second.size == 6) { "advStart targets must be 6 bytes each" }
return buildCheckedFrame(CHAN_DEVICE, KIND_REQ, CMD_HI_DEVICE, CMD_LO_ADV_START, seq, first + second)
}
/**
* touchSwitch (00:07) SET: [selector, value]. Selector 2 opens (value 1)
* or closes (value 0) the glasses touch source; the phone selector does
* nothing in the decompiled handler.
*/
@JvmStatic
fun buildTouchSwitch(seq: Int, selector: Int, on: Boolean): ByteArray =
buildCheckedFrame(CHAN_DEVICE, KIND_DATA, CMD_HI_DEVICE, CMD_LO_TOUCH_SWITCH, seq,
byteArrayOf(selector.toByte(), if (on) 1 else 0))
/**
* removeRingNotify (00:82) SET, one byte: the ring clears its
* glasses-connected flag and erases both advStart targets. The retail
* handler acts on any nonempty payload; 1 is our choice.
*/
@JvmStatic
fun buildRemoveRingNotify(seq: Int): ByteArray =
buildCheckedFrame(CHAN_DEVICE, KIND_DATA, CMD_HI_DEVICE, CMD_LO_REMOVE_RING_NOTIFY, seq, byteArrayOf(0x01))
/**
* The outcome a ring response's status byte carries: `0x03 | code << 2`
* with code 0 ok, 1 error, 2 refused, 3 unsupported. Null when `kind` is
* not a response.
*/
@JvmStatic
fun responseResult(kind: Int): String? {
if ((kind and 0x03) != KIND_RSP) return null
return when ((kind ushr 2) and 0x03) {
0 -> "ok"
1 -> "error"
2 -> "refused"
else -> "unsupported"
}
}
private fun nonceBytes(nonce: Int): ByteArray {
return byteArrayOf((nonce and 0xff).toByte(), ((nonce ushr 8) and 0xff).toByte())
}
@@ -353,6 +353,20 @@ class GlassesSessionCore(
internal var lastRingLinkCommandAtMs = 0L
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 ringRoleReconnectPending = false
// 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>()
internal var ringConfigAwaiting: RingConfigCommand? = null
internal var lastRingConfigCommand = ""
internal var lastRingConfigCommandAtMs = 0L
internal var lastRingConfigResult = ""
// Last direct-link notification nothing decoded (e.g. legacy-channel
// frames while claiming the glasses role).
internal var lastDirectRingRaw = ""
internal var lastDirectRingRawAtMs = 0L
// Silent mode: 1 = on, 0 = off, -1 = not yet known. See updateSilentModeLocked.
internal var silentMode = -1
internal var wearState = -1
@@ -995,14 +1009,90 @@ class GlassesSessionCore(
status["lastCommandAgeMs"] = age(lastRingLinkCommandAtMs)
status["lastCommandResultR"] = lastRingLinkResultR
status["lastCommandResultL"] = lastRingLinkResultL
status["directRole"] = directRingRole
status["lastRingCommand"] = lastRingConfigCommand
status["lastRingCommandAgeMs"] = age(lastRingConfigCommandAtMs)
status["lastRingCommandResult"] = lastRingConfigResult
status["lastDirectRaw"] = lastDirectRingRaw
status["lastDirectRawAgeMs"] = age(lastDirectRingRawAtMs)
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
* 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.
*/
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
}
monitor.withLock {
if (normalized == directRingRole) return
directRingRole = normalized
if (ringConnected || ringNotificationsReady) {
ringRoleReconnectPending = true
monitor.signalAll()
}
}
logLine("direct ring role set to $normalized")
}
/**
* EXPERIMENTAL: ring-side binding commands over the direct link, plus the
* two combined flows. Returns a one-line outcome for the UI. Actions:
* "pair-auth", "targets-glasses", "targets-clear", "touch-on",
* "touch-off", "remove-ring" (see [queueRingConfigCommandLocked]);
* "bind" = advStart(our glasses), then after the ring answers the glasses
* RING_CONNECT_INFO connect=1 (the official app's order); "unbind" = the
* glasses' UNPAIR_INFO, then removeRingNotify to the ring.
* `fallbackAddress`/`fallbackName` are the ring's, for the glasses side.
*/
fun sendRingConfigCommand(action: String, fallbackAddress: String?, fallbackName: String?): String {
val outcome = monitor.withLock {
if (!running || !sessionReady) return "not sent: no glasses session"
val directReady = ringNotificationsReady
when (action) {
"bind" -> {
if (!directReady) return "not sent: direct ring link not ready"
queueRingConfigCommandLocked("targets-glasses", "connect", fallbackAddress ?: "", fallbackName ?: "")
}
"unbind" -> {
val glasses = queueGlassesRingLinkCommandLocked("unpair", fallbackAddress ?: "", fallbackName ?: "")
val ring = directReady && queueRingConfigCommandLocked("remove-ring", null, "", "") == null
when {
glasses && ring -> null
glasses -> "glasses unpair sent; ring part skipped (direct link not ready)"
ring -> "ring part sent; glasses unpair skipped (no ring address)"
else -> "not sent: no ring address and no direct link"
}
}
else -> {
if (!directReady) return "not sent: direct ring link not ready"
queueRingConfigCommandLocked(action, null, "", "")
}
}
}
interruptibleSleep.interrupt()
return outcome ?: "sent"
}
/**
* EXPERIMENTAL: ask the glasses to drop, forget 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", "unpair" 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.
@@ -1922,6 +2012,10 @@ class GlassesSessionCore(
}
val decoded = FaceclawRingEventDecoder.decode(data)
if (decoded == null) {
monitor.withLock {
lastDirectRingRaw = characteristicUuid.take(8) + " " + hex(data.copyOf(minOf(data.size, 24)))
lastDirectRingRawAtMs = now()
}
logDebug("direct ring notify ignored: characteristicUuid=" + characteristicUuid + " raw=" + hex(data))
return
}
@@ -1979,6 +2073,7 @@ class GlassesSessionCore(
// link; the sequence counter restarts on the next connect.
ringReassembler.reset()
ringOutbound.clear()
dropRingConfigCommandsLocked("direct link dropped")
directRingBattery = -1
directRingCharging = -1
emitBatteryState(headsetBattery, headsetCharging)
@@ -2259,7 +2354,16 @@ class GlassesSessionCore(
// channel is plausibly what carries ring-as-remote gesture events,
// which are a daily-driver feature; matching Even byte-for-byte here
// buys nothing and risks breaking them.
val phoneNotify = enableRingNotification(BleProtocol.R1_PHONE_NOTIFY_CHAR_UUID)
//
// Per openCFW's R1 decompilation, the "phone-notify" characteristic
// (bae80011) is really the legacy channel the glasses use. Enabling its
// CCCD appears to be what assigns a link the ring's glasses role (BAE8
// service events 6/7), and the ring sends gestures (00 09 61 00 ...)
// 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 dataNotify = enableRingNotification(BleProtocol.R1_NOTIFY_CHAR_UUID)
if (!phoneNotify && !dataNotify) {
throw IllegalStateException("no R1 notify characteristic subscribed")
@@ -2278,9 +2382,11 @@ class GlassesSessionCore(
ringWriteFailures = 0
ringConnectFailures = 0
}
logLine("direct ring ready phoneNotify=$phoneNotify dataNotify=$dataNotify")
logLine("direct ring ready role=$role phoneNotify=$phoneNotify dataNotify=$dataNotify")
if (dataNotify && host.supportsRingHealth()) {
// 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) {
onRingDataChannelReady()
}
}
@@ -93,20 +93,23 @@ 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
* (0x02), device id (0x0b) - found by extracting the literal wire order
* of a real successful sync (same capture as ringHealthRspTimeoutMs; two
* health requests - battery (0x01), firmware version (0x02), device id
* (0x0b) - found by extracting the literal wire order of a real
* successful sync (same capture as ringHealthRspTimeoutMs; two
* independent syncs in it agree). Rotated one-per-health-type here rather
* than replicated exactly (Even's real cadence isn't perfectly regular
* either - compare the two syncs in the capture), since which of these,
* if any, is actually load-bearing for the ring answering has never
* been isolated. This is matching cadence, not a confirmed protocol
* requirement.
*
* Even's sync also sends 0x0a, which used to be replayed here with the
* capture's "opaque blob". 0x0a is advStart: the blob was the capturing
* phone's two glasses MACs, which the ring persists as the only glasses it
* accepts. It is now sent only on request (queueRingConfigCommandLocked),
* with our own glasses' addresses.
*/
private val RING_DEVICE_PING_CMD_LO = intArrayOf(0x0a, 0x01, 0x02, 0x0b)
/** The opaque blob Even sends with every device-channel 0x0a request (f8f53d235ac4ceaa073885cc). */
private val RING_IDENTITY_BLOB: ByteArray = "f8f53d235ac4ceaa073885cc".chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private val RING_DEVICE_PING_CMD_LO = intArrayOf(0x01, 0x02, 0x0b)
/**
* A snapshot of the health buffer together with the watermark identifying
@@ -127,8 +130,10 @@ class RingHealthBatch internal constructor(
internal fun GlassesSessionCore.runRingWorker() {
while (running) {
try {
restartRingLinkForRoleChange()
if (shouldAttemptRingConnect()) tryConnectRing("ring worker")
if (!running) break
flushRingConfigCommands()
flushRingOutbound()
runRequestedRingHealthPull()
resumeAbortedRingHealthPull()
@@ -221,6 +226,7 @@ internal fun GlassesSessionCore.handleRingHealthNotification(characteristicUuid:
}
logLine("direct ring battery " + status.battery + "% charging=" + status.charging)
}
recordRingConfigResponse(frame)
logDebug("ring device frame " + frame.describe())
return true
}
@@ -386,7 +392,7 @@ internal fun GlassesSessionCore.resumeAbortedRingHealthPull() {
if (ringHealthAbortedRetries == 0) {
return
}
if (!ringConnected || !ringNotificationsReady) {
if (!ringConnected || !ringNotificationsReady || directRingRole == DIRECT_RING_ROLE_GLASSES) {
return
}
if (now - ringHealthLastRequestedAtMs < RING_HEALTH_ABORTED_RETRY_GAP_MS) {
@@ -410,6 +416,10 @@ internal fun GlassesSessionCore.runRequestedRingHealthPull() {
logLine("ring health: on-demand pull skipped, ring not ready")
return
}
if (directRingRole == DIRECT_RING_ROLE_GLASSES) {
logLine("ring health: on-demand pull skipped, direct link holds the glasses role")
return
}
if (ringHealthLastRequestedAtMs != 0L
&& now - ringHealthLastRequestedAtMs < RING_HEALTH_ON_DEMAND_MIN_INTERVAL_MS) {
logLine("ring health: on-demand pull skipped, last one was "
@@ -446,37 +456,29 @@ internal fun GlassesSessionCore.sendRingHandshake() {
+ " (tz " + localTimeZoneId() + ")")
val clock = le32(liveClockSeconds)
val seqs = IntArray(7)
val nonces = IntArray(7)
val seqs = IntArray(6)
val nonces = IntArray(6)
monitor.withLock {
for (i in 0 until 7) {
for (i in 0 until 6) {
seqs[i] = nextRingSeqLocked()
nonces[i] = nextRingNonceLocked()
}
}
val frames = arrayOf(
RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x08, seqs[0],
// NO nonce prefix on this one frame - payload is exactly the
// three bytes 3f 01 01. Every other request on both channels
// starts with the 2-byte nonce; 00:08 does not, and the ring
// silently drops the whole frame if you add one, then ignores
// everything that follows on the connection.
//
// Measured 2026-09-11 across all four btsnoop captures, 46
// real 00:08 writes, zero exceptions:
// payload 3f0101 (3 bytes) -> 3 writes, ALL answered (12-21 notifications each)
// payload 01003f0101 (5 bytes) -> 43 writes, ALL silent (zero notifications)
// The 5-byte form is the more common one in the captures only
// because it is ours, failing and retrying all night. Do not
// "fix" this back to the nonce form by pattern-matching the
// other frames or by counting which variant appears more.
//
// This also explains 2026-09-10: the handshake worked when it
// was raw bytes replayed from the capture, and stopped working
// the moment it was rebuilt "properly" through buildFrame(),
// which is what introduced the nonce prefix.
byteArrayOf(0x3f, 0x01, 0x01)),
// pairAuth. Its bytes after the header must be exactly 3f 01 01:
// measured 2026-09-11 across all four btsnoop captures, 46 real
// 00:08 writes, zero exceptions:
// 3f0101 (3 bytes) -> 3 writes, ALL answered (12-21 notifications each)
// 01003f0101 (5 bytes) -> 43 writes, ALL silent (zero notifications)
// The 5-byte form was ours, failing and retrying all night. The
// first two bytes are not a nonce: they are the frame's phone
// checksum (3f01 is its value at seq 1), and the role byte 01 must
// follow it directly. A nonce in front shifted the role byte, so the
// ring never assigned us the phone role and ignored everything after.
// buildPairAuth computes the checksum; at seq 1 it is the captured
// frame byte for byte (see GlassesRingLinkTest).
RingProtocol.buildPairAuth(seqs[0]),
RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x0e, seqs[1],
le16(nonces[1]) + clock + byteArrayOf(0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)),
RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x05, seqs[2],
@@ -489,8 +491,8 @@ internal fun GlassesSessionCore.sendRingHandshake() {
le16(nonces[4])),
RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x0b, seqs[5],
le16(nonces[5])),
RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x0a, seqs[6],
le16(nonces[6]) + RING_IDENTITY_BLOB),
// Even's handshake ends with advStart (00:0A) naming its glasses; it is
// not replayed here (see RING_DEVICE_PING_CMD_LO).
)
for (frame in frames) {
if (!writeRingFrame(frame, "handshake")) {
@@ -679,18 +681,7 @@ internal fun GlassesSessionCore.awaitRingHealthDataIdle(idleMs: Long): Boolean {
*/
internal fun GlassesSessionCore.sendRingDevicePing(cmdLo: Int) {
val frame = monitor.withLock {
val seq = nextRingSeqLocked()
val nonce = nextRingNonceLocked()
if (cmdLo == 0x0a) {
// The only one of these four that isn't a bare nonce - it
// carries the same opaque constant blob as the handshake's
// own 0x0a frame (confirmed byte-identical across two
// different nights, see sendRingHandshake()'s comments).
RingProtocol.buildFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x0a, seq,
le16(nonce) + RING_IDENTITY_BLOB)
} else {
RingProtocol.buildRequest(RingProtocol.CHAN_DEVICE, 0x00, cmdLo, seq, nonce)
}
RingProtocol.buildRequest(RingProtocol.CHAN_DEVICE, 0x00, cmdLo, nextRingSeqLocked(), nextRingNonceLocked())
}
writeRingFrame(frame, "device ping 0x" + cmdLo.toString(16))
}
@@ -777,19 +768,21 @@ internal fun GlassesSessionCore.nextRingNonceLocked(): Int {
// 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.
// direct phone link sees nothing. These ask the glasses to let go of it, to
// forget 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; the connect form also matches the official app's
// decompiled builder. None of it has been verified on hardware. UNPAIR_INFO
// wipes the glasses' stored ring pairing; the Even app can re-pair.
/**
* 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.
* Parse "AA:BB:CC:DD:EE:FF" into wire order, least-significant byte first,
* for both ring and glasses addresses. The official app's
* StringExt.macToBytes reverses the same way for RING_CONNECT_INFO, and the
* R1 (a Nordic part) compares advStart targets against its little-endian
* peer addresses.
*/
internal fun ringMacWireBytes(address: String): ByteArray? {
internal fun macWireBytes(address: String): ByteArray? {
val parts = address.trim().split(':')
if (parts.size != 6) return null
val bytes = ByteArray(6)
@@ -809,6 +802,8 @@ internal fun ringMacWireBytes(address: String): ByteArray? {
* - "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.
* - "unpair": UNPAIR_INFO dev=RING. The glasses forget the ring, so they
* stop reconnecting to it until something sends "connect" again.
* Both RING_CONNECT_INFO forms overwrite the stored target, so they echo the
* target the glasses reported when there is one.
*/
@@ -816,7 +811,7 @@ internal fun GlassesSessionCore.queueGlassesRingLinkCommandLocked(
action: String, fallbackAddress: String, fallbackName: String,
): Boolean {
val reported = glassesRingMac
val mac = reported ?: ringMacWireBytes(fallbackAddress)
val mac = reported ?: macWireBytes(fallbackAddress)
if (mac == null) {
logLine("glasses ring $action skipped: no ring address")
return false
@@ -832,6 +827,7 @@ internal fun GlassesSessionCore.queueGlassesRingLinkCommandLocked(
val message = messageBuilder.ringLinkCommand("glasses ring $action", leftArm) { magic ->
when (action) {
"disconnect" -> BleProtocol.buildRingDisconnectRequest(magic, mac)
"unpair" -> BleProtocol.buildRingUnpairRequest(magic, mac)
"release" -> BleProtocol.buildRingConnectRequest(magic, false, mac, name)
else -> BleProtocol.buildRingConnectRequest(magic, true, mac, name)
}
@@ -875,3 +871,175 @@ internal fun GlassesSessionCore.recordGlassesRingReportLocked(frame: BleProtocol
}
logLine("glasses ring report: $lastGlassesRingReport")
}
// ---------------------------------------------------------------------------
// The ring's own binding state (system-channel commands over the direct link)
//
// The R1 keeps one phone role and one glasses role, and a pair of glasses
// addresses (advStart targets) it will accept in the glasses role; gestures go
// only to the glasses role. Behavior is from openCFW's R1 decompilation
// (r1/docs/correlation/CONNECTION-CONTROL-CORRELATION.md and
// ADV-START-TOUCH-SWITCH-HANDLERS-CORRELATION.md); the official app's order
// (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"
/** How long a command with a follow-up waits for the ring's answer before running it anyway. */
private const val RING_CONFIG_RESPONSE_TIMEOUT_MS = 3_000L
/** Six 0xFF bytes: an unset advStart target, the value removeRingNotify writes. */
private val RING_TARGET_UNSET = ByteArray(6) { 0xff.toByte() }
/**
* One queued ring command. `followUp` is a glasses ring-link action (see
* [queueGlassesRingLinkCommandLocked]) to queue once the ring has answered.
*/
internal class RingConfigCommand(
val label: String,
val frame: ByteArray,
val cmdLo: Int,
val followUp: String?,
val followUpAddress: String,
val followUpName: String,
)
/**
* Queue one ring-side command for the ring worker. Actions:
* - "pair-auth": pairAuth, claiming the phone role (the handshake already does).
* - "targets-glasses": advStart with this session's right and left arms.
* - "targets-clear": advStart with both targets unset (any glasses accepted).
* - "touch-on" / "touch-off": touchSwitch on the glasses touch source.
* - "remove-ring": removeRingNotify (clears both targets and the
* glasses-connected flag).
* Returns null when queued, else why not.
*/
internal fun GlassesSessionCore.queueRingConfigCommandLocked(
action: String, followUp: String?, followUpAddress: String, followUpName: String,
): String? {
val seq = nextRingSeqLocked()
val label: String
val frame: ByteArray
when (action) {
"pair-auth" -> {
label = "pairAuth"
frame = RingProtocol.buildPairAuth(seq)
}
"targets-glasses" -> {
val right = macWireBytes(rightAddress)
val left = macWireBytes(leftAddress)
if (right == null || left == null) return "not sent: glasses addresses unparseable"
label = "advStart R=$rightAddress L=$leftAddress"
frame = RingProtocol.buildAdvStart(seq, right, left)
}
"targets-clear" -> {
label = "advStart cleared"
frame = RingProtocol.buildAdvStart(seq, RING_TARGET_UNSET, RING_TARGET_UNSET)
}
"touch-on", "touch-off" -> {
label = "touchSwitch glasses " + (if (action == "touch-on") "on" else "off")
frame = RingProtocol.buildTouchSwitch(seq, RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, action == "touch-on")
}
"remove-ring" -> {
label = "removeRingNotify"
frame = RingProtocol.buildRemoveRingNotify(seq)
}
else -> return "not sent: unknown ring action $action"
}
val cmdLo = frame[12].toInt() and 0xff
ringConfigQueue.addLast(RingConfigCommand(label, frame, cmdLo, followUp, followUpAddress, followUpName))
lastRingConfigCommand = label + (if (followUp != null) " then glasses $followUp" else "")
lastRingConfigCommandAtMs = now()
lastRingConfigResult = "queued"
logLine("queue ring command $label seq=$seq" + (if (followUp != null) " then glasses $followUp" else ""))
monitor.signalAll()
return null
}
/** The direct link went away: queued commands (and their follow-ups) are not sent. */
internal fun GlassesSessionCore.dropRingConfigCommandsLocked(reason: String) {
lastRingConfigResult = when {
ringConfigQueue.isNotEmpty() -> "dropped: $reason"
ringConfigAwaiting != null -> "no answer: $reason"
else -> return
}
ringConfigQueue.clear()
ringConfigAwaiting = null
monitor.signalAll()
}
/**
* Write queued ring commands. Ring worker only. A command with a follow-up
* waits for the ring's answer (or a timeout), then queues the glasses half.
* A failed write leaves the command queued for the next tick.
*/
internal fun GlassesSessionCore.flushRingConfigCommands() {
while (true) {
val command = monitor.withLock {
if (!ringNotificationsReady) return
ringConfigQueue.firstOrNull() ?: return
}
if (!writeRingFrame(command.frame, command.label)) return
monitor.withLock {
val index = ringConfigQueue.indexOfFirst { it === command }
if (index >= 0) ringConfigQueue.removeAt(index)
ringConfigAwaiting = command
lastRingConfigResult = "sent, awaiting ring"
}
logLine("ring command ${command.label} written: " + GlassesSessionCore.hex(command.frame))
val followUp = command.followUp ?: continue
val answered = awaitRingConfigResponse(command)
val queued = monitor.withLock {
if (!running || !sessionReady) false
else queueGlassesRingLinkCommandLocked(followUp, command.followUpAddress, command.followUpName)
}
logLine("ring command ${command.label}: " + (if (answered) "answered" else "no answer")
+ "; glasses $followUp " + (if (queued) "queued" else "not sent"))
interruptibleSleep.interrupt()
}
}
private fun GlassesSessionCore.awaitRingConfigResponse(command: RingConfigCommand): Boolean {
val deadline = now() + RING_CONFIG_RESPONSE_TIMEOUT_MS
monitor.withLock {
while (running && ringConfigAwaiting === command) {
val remaining = deadline - now()
if (remaining <= 0) break
monitor.awaitMs(remaining)
}
return ringConfigAwaiting !== command
}
}
/** Match a system-channel response to the command awaiting one. GATT callback thread. */
internal fun GlassesSessionCore.recordRingConfigResponse(frame: RingProtocol.Frame) {
if (frame.cmdHi != RingProtocol.CMD_HI_DEVICE) return
val result = RingProtocol.responseResult(frame.kind) ?: return
val label = monitor.withLock {
val awaiting = ringConfigAwaiting
if (awaiting == null || awaiting.cmdLo != frame.cmdLo) return
ringConfigAwaiting = null
lastRingConfigResult = result + " (status " + RingProtocol.hex2(frame.kind) + ")"
monitor.signalAll()
awaiting.label
}
logLine("ring command $label answered: $result " + frame.describe())
}
/** Apply a [GlassesSessionCore.setDirectRingRole] change by reconnecting the direct link. Ring worker only. */
internal fun GlassesSessionCore.restartRingLinkForRoleChange() {
val role = monitor.withLock {
if (!ringRoleReconnectPending) return
ringRoleReconnectPending = false
ringConnected = false
ringNotificationsReady = false
ringReconnectAfterMs = 0
ringOutbound.clear()
dropRingConfigCommandsLocked("role change")
directRingRole
}
logLine("direct ring: reconnecting to take the $role role")
link.disconnect(ringAddress)
}
@@ -166,6 +166,9 @@ class IosGlassesSession internal constructor(
fun getRingStatus(): String = core.getRingStatus()
fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean =
core.setGlassesRingLink(action, fallbackAddress, fallbackName)
fun sendRingConfigCommand(action: String, fallbackAddress: String?, fallbackName: String?): String =
core.sendRingConfigCommand(action, fallbackAddress, fallbackName)
fun setDirectRingRole(role: String?) = core.setDirectRingRole(role)
fun addImuListener(listener: FaceclawImuListener?) = core.addImuListener(listener)