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

@@ -269,6 +269,13 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre
fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean =
core.setGlassesRingLink(action, fallbackAddress, fallbackName)
/** See [GlassesSessionCore.sendRingConfigCommand]. */
fun sendRingConfigCommand(action: String, fallbackAddress: String?, fallbackName: String?): String =
core.sendRingConfigCommand(action, fallbackAddress, fallbackName)
/** See [GlassesSessionCore.setDirectRingRole]. */
fun setDirectRingRole(role: String?) = core.setDirectRingRole(role)
fun addImuListener(listener: FaceclawImuListener?) = core.addImuListener(listener)
fun removeImuListener(listener: FaceclawImuListener?) = core.removeImuListener(listener)
+113 -33
View File
@@ -3,13 +3,17 @@ 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 { MenuLayer, type MenuItem } from "../../ui/menu";
import { ringConnectionModeSetting, ringDirectRoleSetting } from "../../ui/dashboard-settings";
import { loadDeviceAddresses } from "../../g2/device-addresses";
import {
getRingSessionStatus,
getRingSystemBluetoothState,
sendRingConfigCommand,
setDirectRingRole,
setGlassesRingLink,
type GlassesRingLinkAction,
type RingConfigAction,
type RingSessionStatus,
type RingSystemBluetoothState,
} from "../../native/ring-status";
@@ -20,26 +24,46 @@ const VALUE_X = 130;
const BUTTON_GAP = 8;
type Row = { label: string; value: string; dim?: boolean };
type Button = { label: string; action: GlassesRingLinkAction | "mode" };
type Button = "glasses" | "ring" | "mode" | "role";
const BUTTONS: readonly Button[] = [
{ label: "Disconnect", action: "disconnect" },
{ label: "Release", action: "release" },
{ label: "Reconnect", action: "connect" },
{ label: "Mode", action: "mode" },
const BUTTONS: readonly Button[] = ["glasses", "ring", "mode", "role"];
/** Glasses-side commands (sid 0x80 pair manager). */
const GLASSES_ACTIONS: readonly { label: string; action: GlassesRingLinkAction }[] = [
{ label: "Disconnect ring", action: "disconnect" },
{ label: "Release ring", action: "release" },
{ label: "Unpair ring", action: "unpair" },
{ label: "Connect ring", action: "connect" },
];
/** Ring-side commands over the direct link, and the combined flows. */
const RING_ACTIONS: readonly { label: string; action: RingConfigAction }[] = [
{ label: "Bind to these glasses", action: "bind" },
{ label: "Unbind from glasses", action: "unbind" },
{ label: "Targets: these glasses", action: "targets-glasses" },
{ label: "Targets: clear (any)", action: "targets-clear" },
{ label: "Remove ring notify", action: "remove-ring" },
{ label: "Touch source on", action: "touch-on" },
{ label: "Touch source off", action: "touch-off" },
{ label: "Pair auth (phone role)", action: "pair-auth" },
];
const ACTION_MENU_LAYOUT = { x: "center" as const, y: 8, width: 300, dimUnderneath: 0.35 };
/**
* 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.
* versus relayed by the glasses. The ring sends gestures only to whichever
* link holds its glasses role, 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.
* Everything below is EXPERIMENTAL (see GlassesSessionRing.kt and
* notes/ring-link-control.md). "Glasses..." sends sid 0x80 ring-link commands
* to the glasses; "Ring..." sends binding commands to the ring over the
* direct link (Mode must be direct and the link up), including Bind/Unbind,
* which do both halves in the official app's order. Mode flips the Developer
* "Ring connection" setting (applies on the next glasses connection); Role
* cycles which ring role the direct link claims and applies immediately.
*/
export class RingStatusLayer implements Layer {
private session: RingSessionStatus | null = null;
@@ -101,9 +125,7 @@ export class RingStatusLayer implements Layer {
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;
const text = buttonLabel(button);
image.drawText(font, x + Math.max(0, Math.floor((buttonWidth - font.measureText(text)) / 2)),
buttonTop + 4, text, selected ? 255 : 170);
});
@@ -132,11 +154,17 @@ export class RingStatusLayer implements Layer {
: "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 link",
value: `${state}${since}, role ${s.directRole}, ${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) });
if (s.lastDirectRaw) {
rows.push({ label: "Direct raw", value: `${formatAge(s.lastDirectRawAgeMs)} ago: ${s.lastDirectRaw}` });
}
}
rows.push({ label: "Glasses input", value: describeInput(s.lastGlassesInputAgeMs, s.lastGlassesInput) });
rows.push({
@@ -148,27 +176,66 @@ export class RingStatusLayer implements Layer {
if (s.lastGlassesReport) {
rows.push({ label: "Glasses said", value: `${s.lastGlassesReport} (${formatAge(s.lastGlassesReportAgeMs)} ago)` });
}
if (s.lastRingCommand) {
rows.push({
label: "Ring cmd",
value: `${s.lastRingCommand} ${formatAge(s.lastRingCommandAgeMs)} ago: ${s.lastRingCommandResult}`,
});
}
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}` });
rows.push({ label: "Glasses cmd", value: `${s.lastCommand} ${formatAge(s.lastCommandAgeMs)} ago` });
rows.push({ label: "Glasses ack", 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;
private activate(ctx: LayerContext): void {
switch (BUTTONS[this.selected]!) {
case "glasses":
ctx.stack.push(this.actionMenu("Glasses ring link", GLASSES_ACTIONS.map(({ label, action }) => ({
label,
onSelect: (menuCtx) => {
this.runGlassesAction(label, action);
menuCtx.stack.pop();
},
}))));
return;
case "ring":
ctx.stack.push(this.actionMenu("Ring binding", RING_ACTIONS.map(({ label, action }) => ({
label,
onSelect: (menuCtx) => {
this.notice = `${label}: ${sendRingConfigCommand(action, this.ringAddress(), this.system?.name ?? "")}`;
this.poll();
menuCtx.stack.pop();
},
}))));
return;
case "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;
}
case "role": {
const next = ringDirectRoleSetting.set(ringDirectRoleSetting.next());
setDirectRingRole(next);
this.notice = this.session?.directEnabled
? `Direct ring role: ${ringDirectRoleSetting.displayValue(next)}; reconnecting the direct link`
: `Direct ring role: ${ringDirectRoleSetting.displayValue(next)}; used once Mode is direct`;
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)`;
}
private actionMenu(title: string, items: MenuItem[]): MenuLayer {
return new MenuLayer(title, items, ACTION_MENU_LAYOUT);
}
private runGlassesAction(label: string, action: GlassesRingLinkAction): void {
this.notice = setGlassesRingLink(action, this.ringAddress(), this.system?.name ?? "")
? `${label} sent (experimental)`
: `${label} not sent (no session or no ring address)`;
this.poll();
}
@@ -181,7 +248,7 @@ export class RingStatusLayer implements Layer {
this.selected = (this.selected + 1) % BUTTONS.length;
return;
case "click":
this.activate();
this.activate(ctx);
return;
case "double-click":
ctx.stack.pop();
@@ -192,6 +259,19 @@ export class RingStatusLayer implements Layer {
}
}
function buttonLabel(button: Button): string {
switch (button) {
case "glasses":
return "Glasses...";
case "ring":
return "Ring...";
case "mode":
return ringConnectionModeSetting.get() === "direct" ? "Mode: direct" : "Mode: glasses";
case "role":
return `Role: ${ringDirectRoleSetting.get()}`;
}
}
function describeSystem(sys: RingSystemBluetoothState | null): string {
if (!sys) return "unknown";
if (sys.error) return `error: ${sys.error}`;
+2 -1
View File
@@ -72,7 +72,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
import { appViewportRect, isOnSwitcherEdge, sidebarStripVisible, type WindowHeightMode } from "../ui/shell/geometry";
import { type LayerActions, type TextSettingsEditToggle } from "../ui/layers";
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayModeSetting, navigateDisplayModeSetting, navigateVerticalPositionSetting, terminalDisplayModeSetting, terminalVerticalPositionSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayModeSetting, navigateDisplayModeSetting, navigateVerticalPositionSetting, terminalDisplayModeSetting, terminalVerticalPositionSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, ringDirectRoleSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import {
getInstalledEvenHubAppById,
@@ -1446,6 +1446,7 @@ class DashboardController {
right: addresses.right,
left: addresses.left,
ring: ringAddress,
ringRole: ringDirectRoleSetting.get(),
});
this.communicator = communicator;
// Size the compositor before anything else is awaited: windows opened
+5 -1
View File
@@ -199,7 +199,7 @@ export class FaceclawCommunicatorBridge {
private microphoneWork: Promise<void> = Promise.resolve();
private microphoneToken = 0;
constructor(addresses: { right: string; left: string; ring?: string }) {
constructor(addresses: { right: string; left: string; ring?: string; ringRole?: string }) {
this.communicator = FaceclawKitIosGlassesSession.alloc().initWithRightAddressLeftAddressRingAddress(
String(addresses.right ?? "").toUpperCase(),
String(addresses.left ?? "").toUpperCase(),
@@ -207,6 +207,10 @@ export class FaceclawCommunicatorBridge {
);
// The shared session halts on any other firmware ("incompatible-firmware").
this.communicator.setRequiredFirmwareRevisionRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION);
// Guarded: an older framework build may not export it yet.
if (addresses.ringRole && typeof this.communicator.setDirectRingRoleRole === "function") {
this.communicator.setDirectRingRoleRole(addresses.ringRole);
}
this.listenerProxy = SessionListener.new() as SessionListener;
this.listenerProxy.bridge = this;
this.communicator.setListenerListener(this.listenerProxy);
+3 -1
View File
@@ -161,7 +161,7 @@ export class FaceclawCommunicatorBridge {
private readonly firmwareInfoListeners = new Set<(info: FirmwareInfo) => void>();
private readonly previewAnimationListeners = new Set<() => void>();
constructor(addresses: { right: string; left: string; ring?: string }) {
constructor(addresses: { right: string; left: string; ring?: string; ringRole?: string }) {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
@@ -173,6 +173,8 @@ export class FaceclawCommunicatorBridge {
);
// The shared session halts on any other firmware ("incompatible-firmware").
this.communicator.setRequiredFirmwareRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION);
// Which R1 role the direct ring link claims; only matters with a ring address.
if (addresses.ringRole) this.communicator.setDirectRingRole(addresses.ringRole);
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
onStateChange: (phase: string, status: string) => {
const state = {
+49 -2
View File
@@ -37,14 +37,38 @@ export type RingSessionStatus = {
lastCommandAgeMs: number;
lastCommandResultR: string;
lastCommandResultL: string;
/** Which ring role the direct link claims: "both", "phone" or "glasses". */
directRole: string;
lastRingCommand: string;
lastRingCommandAgeMs: number;
lastRingCommandResult: string;
/** Last direct-link notification nothing decoded: characteristic prefix and hex. */
lastDirectRaw: string;
lastDirectRawAgeMs: number;
};
/**
* 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.
* connect mode (may hold off auto-reconnect), "unpair" makes them forget the
* ring, "connect" hands the ring back.
*/
export type GlassesRingLinkAction = "disconnect" | "release" | "connect";
export type GlassesRingLinkAction = "disconnect" | "release" | "unpair" | "connect";
/**
* EXPERIMENTAL ring-side binding commands over the direct link (see
* GlassesSessionCore.sendRingConfigCommand). "bind" and "unbind" combine the
* ring and glasses halves in the official app's order.
*/
export type RingConfigAction =
| "bind"
| "unbind"
| "pair-auth"
| "targets-glasses"
| "targets-clear"
| "touch-on"
| "touch-off"
| "remove-ring";
export type RingSystemBluetoothState = {
address: string;
@@ -100,3 +124,26 @@ export function setGlassesRingLink(action: GlassesRingLinkAction, fallbackAddres
return false;
}
}
/** A one-line outcome for the UI. */
export function sendRingConfigCommand(action: RingConfigAction, fallbackAddress: string, fallbackName: string): string {
const active = activeCommunicator();
if (!active) return "not sent: no glasses session";
try {
return String(active.sendRingConfigCommand(action, fallbackAddress, fallbackName));
} catch (error) {
console.warn(`sendRingConfigCommand failed: ${error}`);
return `failed: ${error}`;
}
}
/** Apply a direct ring role to the running session (reconnects the direct link if it is up). */
export function setDirectRingRole(role: string): void {
const active = activeCommunicator();
if (!active) return;
try {
active.setDirectRingRole(role);
} catch (error) {
console.warn(`setDirectRingRole failed: ${error}`);
}
}
+14
View File
@@ -715,6 +715,20 @@ export const ringConnectionModeSetting = new ConfigSettingEnum<RingConnectionMod
"How R1 ring input reaches the phone. Only via glasses: the ring's own link to the glasses carries its gestures, and the phone never opens a Bluetooth connection to the ring. Direct: also connect to the ring from the phone (currently unreliable). Takes effect on the next connection to the glasses.",
});
/** Which of the R1's two roles the direct link claims; see GlassesSessionCore.setDirectRingRole. */
export type RingDirectRole = "both" | "phone" | "glasses";
export const ringDirectRoleSetting = new ConfigSettingEnum<RingDirectRole>({
id: "ring-direct-role",
label: "Direct ring role",
storageKey: "developer.ringDirectRole",
defaultValue: "both",
values: ["both", "phone", "glasses"],
formatValue: (value) => (value === "phone" ? "Phone" : value === "glasses" ? "Glasses" : "Both"),
description:
"EXPERIMENTAL, only used when Ring connection is Direct. The ring has a phone role (health sync) and a glasses role (gestures). Phone: claim only the phone role, like Even's app. Glasses: claim the glasses role so ring gestures come straight to the phone; works only while the glasses are not holding the ring, and disables ring health sync. Both: the old behavior, which asks for both roles on one link.",
});
// "whisper" (no "onboard-" prefix) is OpenAI's CLOUD realtime model
// (gpt-realtime-whisper); "onboard-whisper" is the on-device sherpa-onnx
// Whisper backend. Same underlying model family, two different places it
+2
View File
@@ -57,6 +57,7 @@ import {
previewColorSetting,
phoneRotationSetting,
ringConnectionModeSetting,
ringDirectRoleSetting,
sonioxApiKeySetting,
screenFadeSetting,
enumSettingMenuItem,
@@ -184,6 +185,7 @@ function settingsSections(): SettingsSection[] {
// Whether the phone opens its own BLE link to the R1 ring; the
// glasses relay ring gestures either way. Applied at connect time.
enumSettingMenuItem(ringConnectionModeSetting),
enumSettingMenuItem(ringDirectRoleSetting),
toggleSettingMenuItem(saveVoiceRecordingsSetting),
toggleSettingMenuItem(firmwareDebugFlagsSetting),
toggleSettingMenuItem(suspendEvenHubWhenScreenOffSetting),
@@ -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)
@@ -7,11 +7,11 @@ class GlassesRingLinkTest {
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 macWireBytesAreLeastSignificantFirst() {
assertEquals("b16a9f2f43dc", toHex(assertNotNull(macWireBytes("DC:43:2F:9F:6A:B1"))))
assertNull(macWireBytes(""))
assertNull(macWireBytes("DC:43:2F:9F:6A"))
assertNull(macWireBytes("DC:43:2F:9F:6A:ZZ"))
}
@Test fun disconnectRequestWireShape() {
@@ -44,4 +44,64 @@ class GlassesRingLinkTest {
assertNull(BleProtocol.parseRingConnectInfo(BleProtocol.buildAuthenticationRequest(3)))
}
@Test fun unpairRequestWireShape() {
// commandId=9 magic=0x21 unpairInfo(8){dev=RING(0), ringMac}
assertEquals("0809" + "1021" + "420a" + "0800" + "1206b16a9f2f43dc", toHex(BleProtocol.buildRingUnpairRequest(0x21, mac)))
}
@Test fun ringChecksumMatchesCapturedEvenFrames() {
// Frames from HCI snoops of Even's app (g2-kit-unofficial examples/ring-direct.ts).
assertEquals("00971953f964016401000000080d003f0101", toHex(RingProtocol.buildPairAuth(1)))
assertEquals("00f979f7b164016404000000020c001b64",
toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_REQ, 0x00, 0x02, 4, ByteArray(0))))
assertEquals("002d946c0164026405000001010c002ac6",
toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_REQ, 0x01, 0x01, 5, ByteArray(0))))
assertEquals("00d4c9ba7064016403000200051200807710ff3348bb69",
toHex(RingProtocol.buildCheckedFrame(RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x05, 3, hex("10ff3348bb69"))))
}
@Test fun advStartCarriesBothTargetsLeastSignificantFirst() {
val right = assertNotNull(macWireBytes("EC:D7:82:69:3C:CB"))
val left = assertNotNull(macWireBytes("C4:5A:23:3D:F5:F8"))
val frame = RingProtocol.buildAdvStart(9, right, left)
assertValidRingFrame(frame)
assertEquals("00" + "000a", toHex(frame.copyOfRange(10, 13)))
assertEquals("cb3c6982d7ec" + "f8f53d235ac4", toHex(frame.copyOfRange(17, frame.size)))
assertEquals("ffffffffffff".repeat(2),
toHex(RingProtocol.buildAdvStart(9, ByteArray(6) { 0xff.toByte() }, ByteArray(6) { 0xff.toByte() }).copyOfRange(17, 29)))
}
@Test fun touchSwitchAndRemoveRingAreSets() {
val on = RingProtocol.buildTouchSwitch(2, RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, true)
assertValidRingFrame(on)
assertEquals("02" + "0007", toHex(on.copyOfRange(10, 13)))
assertEquals("0201", toHex(on.copyOfRange(17, on.size)))
assertEquals("0200", toHex(RingProtocol.buildTouchSwitch(2, 2, false).copyOfRange(17, 19)))
val remove = RingProtocol.buildRemoveRingNotify(3)
assertValidRingFrame(remove)
assertEquals("02" + "0082" + "01", toHex(remove.copyOfRange(10, 13)) + toHex(remove.copyOfRange(17, remove.size)))
}
@Test fun ringResponseStatusDecodes() {
assertEquals("ok", RingProtocol.responseResult(0x03))
assertEquals("error", RingProtocol.responseResult(0x07))
assertEquals("refused", RingProtocol.responseResult(0x0b))
assertEquals("unsupported", RingProtocol.responseResult(0x0f))
assertNull(RingProtocol.responseResult(0x00))
assertNull(RingProtocol.responseResult(0x02))
}
/** Outer CRC-32C and inner phone checksum both match the bytes. */
private fun assertValidRingFrame(frame: ByteArray) {
val crc32 = (frame[1].toInt() and 0xff) or ((frame[2].toInt() and 0xff) shl 8) or
((frame[3].toInt() and 0xff) shl 16) or ((frame[4].toInt() and 0xff) shl 24)
assertEquals(RingProtocol.crc32(frame, 5, frame.size), crc32)
val args = frame.copyOfRange(17, frame.size)
val checksum = RingProtocol.phoneChecksum(frame[6].toInt(), frame[8].toInt() and 0xff,
frame[10].toInt(), frame[11].toInt(), frame[12].toInt() and 0xff, args)
assertEquals(checksum, (frame[15].toInt() and 0xff) or ((frame[16].toInt() and 0xff) shl 8))
assertEquals(frame.size - 5, (frame[13].toInt() and 0xff) or ((frame[14].toInt() and 0xff) shl 8))
}
}
@@ -22,6 +22,34 @@ class RingInputTest {
assertEquals(decoded.ringTick, native.ringTick)
}
@Test fun directReportsMapLikeTheGlassesRelay() {
// Frames captured on the direct link (bae80011), 2026-10-06.
val down = assertNotNull(FaceclawRingEventDecoder.decode(hex("000961000a000013cb0000"))).event
assertEquals(BleProtocol.EVENT_RING_PRESS, down.eventType)
assertEquals(BleProtocol.EVENT_SOURCE_RING, down.eventSource)
assertEquals(10, down.ringType)
assertEquals(0xcb13L, down.ringTick)
val tapHold = assertNotNull(FaceclawRingEventDecoder.decode(hex("0009610009020055d60200"))).event
assertEquals(BleProtocol.EVENT_SHORT_THEN_LONG_PRESS, tapHold.eventType)
assertEquals(2, tapHold.ringAux)
assertEquals(0x02d655L, tapHold.ringTick)
val swipe = assertNotNull(FaceclawRingEventDecoder.decode(hex("0009610004350009cc0000"))).event
assertEquals(BleProtocol.EVENT_SCROLL_TOP, swipe.eventType)
assertEquals(0x35, swipe.ringAux)
assertEquals(0x00, swipe.ringSpeed)
// Same mapping as the CFW relay for every wire type (gesture_fwd.c).
val relayed = mapOf(0 to 9, 1 to 0, 2 to 3, 4 to 1, 5 to 2, 8 to 10, 9 to 11, 10 to 14, 3 to 127, 0xff to 127)
for ((wire, sysEvent) in relayed) {
val frame = hex("0009610000abcdefcdab89").also { it[4] = wire.toByte() }
val event = assertNotNull(FaceclawRingEventDecoder.decode(frame)).event
assertEquals(sysEvent, event.eventType, "wire type $wire")
assertEquals(0x89abcdefL, event.ringTick)
}
}
@Test fun legacyAndInvalidExtensionsNeverInventATimestamp() {
assertEquals(-1L, assertNotNull(G2Event.decodePayload(224, hex("08026a041a02080e"))).ringTick)
for (offset in listOf(9,13,14,15,16,20)) {