diff --git a/app/apps/developer/ring-status.ts b/app/apps/developer/ring-status.ts index 2b8aac97..de0eaa2e 100644 --- a/app/apps/developer/ring-status.ts +++ b/app/apps/developer/ring-status.ts @@ -4,13 +4,12 @@ import { type InputEvent } from "../../ui/gestures"; import { Layer, type LayerContext } from "../../ui/layers"; import { shell } from "../../ui/shell/shell"; import { MenuLayer, type MenuItem } from "../../ui/menu"; -import { ringConnectionModeSetting, ringDirectRoleSetting } from "../../ui/dashboard-settings"; +import { ringConnectionModeSetting } from "../../ui/dashboard-settings"; import { loadDeviceAddresses } from "../../g2/device-addresses"; import { getRingSessionStatus, getRingSystemBluetoothState, sendRingConfigCommand, - setDirectRingRole, setGlassesRingLink, type GlassesRingLinkAction, type RingConfigAction, @@ -24,9 +23,9 @@ const VALUE_X = 130; const BUTTON_GAP = 8; type Row = { label: string; value: string; dim?: boolean }; -type Button = "glasses" | "ring" | "mode" | "role"; +type Button = "glasses" | "ring" | "mode"; -const BUTTONS: readonly Button[] = ["glasses", "ring", "mode", "role"]; +const BUTTONS: readonly Button[] = ["glasses", "ring", "mode"]; /** Glasses-side commands (sid 0x80 pair manager). */ const GLASSES_ACTIONS: readonly { label: string; action: GlassesRingLinkAction }[] = [ @@ -62,8 +61,9 @@ const ACTION_MENU_LAYOUT = { x: "center" as const, y: 8, width: 300, dimUndernea * 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. + * "Ring connection" setting (applies on the next glasses connection). In + * Direct mode the session does the setup on its own (see + * GlassesSessionRing.runRingGlassesSetup); the menus are for experiments. */ export class RingStatusLayer implements Layer { private session: RingSessionStatus | null = null; @@ -146,8 +146,8 @@ export class RingStatusLayer implements Layer { } if (!s.directEnabled) { - const pending = ringConnectionModeSetting.get() === "direct"; - rows.push({ label: "Direct link", value: pending ? "on after glasses reconnect" : "off (mode: glasses)", dim: true }); + const pending = ringConnectionModeSetting.get() !== "glasses"; + rows.push({ label: "Direct link", value: pending ? "on after glasses reconnect" : "off (only via glasses)", dim: true }); } else { const state = s.directNotificationsReady ? "subscribed" : s.directConnected ? "connected, subscribing" @@ -159,6 +159,12 @@ export class RingStatusLayer implements Layer { value: `${state}${since}, role ${s.directRole}, ${s.directConnectCount} connects${battery}`, }); } + if (s.directEnabled && s.directRole === "glasses") { + rows.push({ + label: "Direct auth", + value: s.directGlassesAuth ? `${s.directGlassesAuth} ${formatAge(s.directGlassesAuthAgeMs)} ago` : "not sent yet", + }); + } rows.push({ label: "Direct input", value: describeInput(s.lastDirectInputAgeMs, s.lastDirectInput) }); if (s.directEnabled) { rows.push({ label: "Direct pkts", value: describeAge(s.lastDirectNotifyAgeMs) }); @@ -212,19 +218,10 @@ export class RingStatusLayer implements Layer { })))); return; case "mode": { - const next = ringConnectionModeSetting.get() === "direct" ? "glasses" : "direct"; - ringConnectionModeSetting.set(next); + const next = ringConnectionModeSetting.set(ringConnectionModeSetting.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; - } } } @@ -266,9 +263,7 @@ function buttonLabel(button: Button): string { case "ring": return "Ring..."; case "mode": - return ringConnectionModeSetting.get() === "direct" ? "Mode: direct" : "Mode: glasses"; - case "role": - return `Role: ${ringDirectRoleSetting.get()}`; + return `Mode: ${ringConnectionModeSetting.get()}`; } } diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 65b3fcb9..30966522 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -18,6 +18,8 @@ import { weatherBridge } from "../native/weather"; import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, readActiveNotifications } from "../native/notification-icons"; import { shouldShowNotificationOnGlasses } from "../native/notification-sources"; import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict"; +import { defaultRingName, setGlassesRingLink } from "../native/ring-status"; +import { getBooleanSetting, setBooleanSetting } from "../native/settings-store"; import { grayImageToPreviewSource } from "../native/gray-image-preview"; import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from "./firmware-compat"; import { hasExtractedEvenHubFonts } from "./firmware-builder"; @@ -72,7 +74,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, ringDirectRoleSetting, 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, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings"; import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization"; import { getInstalledEvenHubAppById, @@ -238,6 +240,9 @@ function sourceName(eventSource: number): string { return EventSourceTypeName[eventSource] ?? `SOURCE_${eventSource}`; } +/** Set while a Direct ring session may have taken the R1 from the glasses; see handRingBackToGlassesIfNeeded. */ +const RING_TAKEN_FROM_GLASSES_KEY = "developer.ringTakenFromGlasses"; + class DashboardController { private phase: ConnectionPhase = "disconnected"; private status = "Disconnected."; @@ -315,6 +320,8 @@ class DashboardController { /** Faceclaw's firmware at the required revision reported in; its extensions can be used. */ private customFirmwareConfirmed = false; private faceclawWakeLeaseState: boolean | null = null; + /** Ring connection mode the current session was started with (it applies per connection). */ + private ringModeAtConnect: RingConnectionMode = "glasses"; private glassesWorn: boolean | null = null; /** Put on while charging: Java reconnects on that, and the wake waits for the new session. */ private wakeAfterChargingReconnect = false; @@ -991,6 +998,25 @@ class DashboardController { this.evenHubSuspendTimer = null; } + /** + * A Direct-mode session may have unpaired the R1 from the glasses (see + * GlassesSessionRing.releaseRingFromGlassesLocked). The first session in + * another mode asks the glasses to connect to it again; the ring's own + * glasses targets were cleared, so it accepts them. Called on connect. + */ + private handRingBackToGlassesIfNeeded(): void { + if (this.ringModeAtConnect === "direct" || !getBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false)) return; + const ring = loadDeviceAddresses().ring; + if (!ring) { + setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false); + return; + } + if (setGlassesRingLink("connect", ring, defaultRingName(ring))) { + setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false); + this.appendLog(`Handing the R1 ring ${ring} back to the glasses`); + } + } + private pushFirmwareDebugFlags(): void { if (!this.communicator) return; void this.communicator @@ -1423,10 +1449,14 @@ class DashboardController { this.setPhase("connecting"); this.setStatus("Connecting to the glasses..."); // "Only via glasses" (the default) means the phone never opens its own - // link to the ring: the glasses relay its gestures to us anyway, and the - // direct link is currently unreliable. An empty address disables every - // direct-ring code path in the communicator. - const ringAddress = ringConnectionModeSetting.get() === "direct" ? addresses.ring : ""; + // link to the ring: the glasses relay its gestures to us anyway. An empty + // address disables every direct-ring code path in the communicator. + const ringMode = ringConnectionModeSetting.get(); + this.ringModeAtConnect = ringMode; + const ringAddress = ringMode !== "glasses" ? addresses.ring : ""; + // Direct mode may unpair the ring from the glasses; remember to hand it + // back once a later session runs in another mode. + if (ringMode === "direct" && ringAddress) setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, true); this.appendLog( `Using configured arms: R=${addresses.right} L=${addresses.left}${ringAddress ? ` ring=${ringAddress}` : ""}`, ); @@ -1446,7 +1476,9 @@ class DashboardController { right: addresses.right, left: addresses.left, ring: ringAddress, - ringRole: ringDirectRoleSetting.get(), + // Direct mode acts as the ring's glasses (gestures, battery); health + // sync needs the phone role instead. + ringRole: ringMode === "direct" ? "glasses" : "phone", }); this.communicator = communicator; // Size the compositor before anything else is awaited: windows opened @@ -1493,6 +1525,7 @@ class DashboardController { // mode-7 control message once the dashboard container is warmed up. this.pushFirmwareDebugFlags(); this.pushBrightness(true); + this.handRingBackToGlassesIfNeeded(); } if (mappedPhase !== "connected" && mappedPhase !== "charging") { // A wear snapshot is session-scoped. CFW reports a fresh value when diff --git a/app/native/ring-status.ts b/app/native/ring-status.ts index 73334a6f..f176ca89 100644 --- a/app/native/ring-status.ts +++ b/app/native/ring-status.ts @@ -37,8 +37,11 @@ export type RingSessionStatus = { lastCommandAgeMs: number; lastCommandResultR: string; lastCommandResultL: string; - /** Which ring role the direct link claims: "both", "phone" or "glasses". */ + /** Which ring role the direct link claims: "phone" or "glasses". */ directRole: string; + /** Glasses role only: what the ring made of our legacy pair-auth this connection ("" = not sent). */ + directGlassesAuth: string; + directGlassesAuthAgeMs: number; lastRingCommand: string; lastRingCommandAgeMs: number; lastRingCommandResult: string; @@ -137,13 +140,12 @@ export function sendRingConfigCommand(action: RingConfigAction, fallbackAddress: } } -/** 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}`); - } +/** + * The R1's advertised name, "EVEN R1_" plus the last three address bytes + * (e.g. FF:AA:F1:F6:7E:28 -> "EVEN R1_F67E28"). The glasses store it with the + * ring's MAC when told to connect. + */ +export function defaultRingName(address: string): string { + const hex = address.replace(/[^0-9a-fA-F]/g, "").toUpperCase(); + return hex.length === 12 ? `EVEN R1_${hex.slice(6)}` : ""; } diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index c68a1094..01b51749 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -702,31 +702,24 @@ export const showBleBandwidthSetting = new ConfigSettingBoolean({ "Show Bluetooth messages and bytes sent, throughput, acknowledged display fps, and bytes per frame at the bottom of the phone screen. Rates use a five-second window; bytes include control traffic and protocol framing.", }); -export type RingConnectionMode = "glasses" | "direct"; +/** + * How the phone talks to the R1. The ring has one phone role (health sync) and + * one glasses role (gestures, battery pushes), so "health" and "direct" are + * the two ways a phone link can be useful; see + * GlassesSessionCore.setDirectRingRole and notes/ring-link-control.md. + */ +export type RingConnectionMode = "glasses" | "health" | "direct"; export const ringConnectionModeSetting = new ConfigSettingEnum({ id: "ring-connection-mode", label: "Ring connection", storageKey: "developer.ringConnectionMode", defaultValue: "glasses", - values: ["glasses", "direct"], - formatValue: (value) => (value === "direct" ? "Direct" : "Only via glasses"), + values: ["glasses", "health", "direct"], + formatValue: (value) => + value === "direct" ? "Direct to phone" : value === "health" ? "Via glasses + health sync" : "Only via glasses", description: - "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({ - 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.", + "How the R1 ring reaches the phone. Only via glasses: the glasses relay the ring's gestures and the phone never connects to it. Via glasses + health sync: the same, plus the phone connects to the ring to sync health data. Direct to phone (experimental): the phone takes the ring over from the glasses and gets its gestures and battery itself; the glasses lose ring input and ring health sync is off. Leaving Direct hands the ring back to the glasses. Takes effect on the next connection to the glasses.", }); // "whisper" (no "onboard-" prefix) is OpenAI's CLOUD realtime model diff --git a/app/ui/dashboard/settings-menus.ts b/app/ui/dashboard/settings-menus.ts index 2d652554..9e36b6fa 100644 --- a/app/ui/dashboard/settings-menus.ts +++ b/app/ui/dashboard/settings-menus.ts @@ -57,7 +57,6 @@ import { previewColorSetting, phoneRotationSetting, ringConnectionModeSetting, - ringDirectRoleSetting, sonioxApiKeySetting, screenFadeSetting, enumSettingMenuItem, @@ -182,10 +181,9 @@ function settingsSections(): SettingsSection[] { { label: "Developer", items: [ - // Whether the phone opens its own BLE link to the R1 ring; the - // glasses relay ring gestures either way. Applied at connect time. + // Whether and how the phone opens its own BLE link to the R1 ring. + // Applied at connect time. enumSettingMenuItem(ringConnectionModeSetting), - enumSettingMenuItem(ringDirectRoleSetting), toggleSettingMenuItem(saveVoiceRecordingsSetting), toggleSettingMenuItem(firmwareDebugFlagsSetting), toggleSettingMenuItem(suspendEvenHubWhenScreenOffSetting), diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt index 28ee4a32..f6c912fe 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/BleProtocol.kt @@ -25,8 +25,14 @@ class BleProtocol { // R1 ring, vendor service bae80001-4f05-4503-8e65-3af1f7329d1f. The service // holds two write/notify pairs: bae80010 (write) + bae80011 (notify), and // bae80012 (write) + bae80013 (notify). The health-data protocol - // (RingProtocol) rides the SECOND pair. - const val R1_PHONE_NOTIFY_CHAR_UUID: String = "bae80011-4f05-4503-8e65-3af1f7329d1f" + // (RingProtocol) rides the SECOND pair. The first is the legacy channel + // the glasses use: enabling its CCCD gives a link the ring's glasses + // role, and the ring sends gestures and battery there (RingProtocol's + // legacy-channel section). + const val R1_LEGACY_NOTIFY_CHAR_UUID: String = "bae80011-4f05-4503-8e65-3af1f7329d1f" + + /** Legacy-channel writes (write without response), e.g. the glasses' 00 35 88 00. */ + const val R1_LEGACY_WRITE_CHAR_UUID: String = "bae80010-4f05-4503-8e65-3af1f7329d1f" const val R1_NOTIFY_CHAR_UUID: String = "bae80013-4f05-4503-8e65-3af1f7329d1f" diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt index 3d692261..aa2e92a1 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/RingProtocol.kt @@ -311,6 +311,46 @@ class RingProtocol private constructor() { } } + // ------------------------------------------------------------------ + // Legacy (glasses-role) channel: bae80010 write / bae80011 notify + // + // Raw frames with the opcode in byte 2, not the 0x64 models above. What + // the G2 sends and what the ring answers come from g2-firmware-emulator + // (docs/r1-command88-native.md, r1-cccd-frontier.md) running the stock + // firmwares; the gesture report shape is in FaceclawRingEventDecoder. + // ------------------------------------------------------------------ + + /** + * The G2's legacy pair-auth, opcode 0x88, captured from the stock glasses + * firmware writing it right after enabling the bae80011 CCCD. The ring + * marks the link as its glasses peer and checks it against the advStart + * targets: accepted (a target matches, or none are set) answers with a + * battery report; rejected answers [LEGACY_TARGET_REJECTED] and drops the + * link about 20 s later. + */ + @JvmField val LEGACY_GLASSES_PAIR_AUTH: ByteArray = byteArrayOf(0x00, 0x35, 0x88.toByte(), 0x00) + + /** The ring's "non-target glasses connected" notice, opcode 0x96. */ + @JvmField val LEGACY_TARGET_REJECTED: ByteArray = byteArrayOf(0x00, 0x01, 0x96.toByte(), 0x00) + + /** + * The ring's battery report to its glasses peer, `00 09 8B 00 + * `: sent when a glasses pair-auth is accepted and whenever the + * percentage changes. Null for anything else. + */ + @JvmStatic + fun parseLegacyBattery(raw: ByteArray?): DeviceStatus? { + if (raw == null || raw.size != 6 || raw[0].toInt() != 0x00 || raw[1].toInt() != 0x09 || + (raw[2].toInt() and 0xff) != 0x8B || raw[3].toInt() != 0x00) return null + val battery = raw[4].toInt() and 0xff + if (battery > 100) return null + return DeviceStatus(battery, if (raw[5].toInt() != 0) 1 else 0) + } + + @JvmStatic + fun isLegacyTargetRejected(raw: ByteArray?): Boolean = + raw != null && raw.contentEquals(LEGACY_TARGET_REJECTED) + private fun nonceBytes(nonce: Int): ByteArray { return byteArrayOf((nonce and 0xff).toByte(), ((nonce ushr 8) and 0xff).toByte()) } diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt index a86d0c44..be926d60 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt @@ -354,8 +354,17 @@ class GlassesSessionCore( internal var lastRingLinkResultR = "" internal var lastRingLinkResultL = "" // Which of the ring's two roles the direct link claims; see setDirectRingRole. - internal var directRingRole = DIRECT_RING_ROLE_BOTH + internal var directRingRole = DIRECT_RING_ROLE_PHONE internal var ringRoleReconnectPending = false + // Glasses-role direct link: the per-connection setup (legacy pair-auth + + // touch source on) still to be written, what the ring made of the + // pair-auth, and the once-per-connection target clear after a rejection. + internal var ringGlassesSetupPending = false + internal var directGlassesAuth = "" + internal var directGlassesAuthAtMs = 0L + internal var directGlassesAuthRetried = false + // Last time we asked the glasses to unpair the ring for the direct link. + internal var lastRingReleaseAtMs = 0L // Ring-side binding commands (system channel) waiting for the ring worker, // the one written and not yet answered, and the last one's outcome. internal val ringConfigQueue = ArrayDeque() @@ -1010,6 +1019,8 @@ class GlassesSessionCore( status["lastCommandResultR"] = lastRingLinkResultR status["lastCommandResultL"] = lastRingLinkResultL status["directRole"] = directRingRole + status["directGlassesAuth"] = directGlassesAuth + status["directGlassesAuthAgeMs"] = age(directGlassesAuthAtMs) status["lastRingCommand"] = lastRingConfigCommand status["lastRingCommandAgeMs"] = age(lastRingConfigCommandAtMs) status["lastRingCommandResult"] = lastRingConfigResult @@ -1021,24 +1032,20 @@ class GlassesSessionCore( /** * Which ring role the direct link claims. The R1 holds one phone role and - * one glasses role at a time and sends gestures only to the glasses role - * (openCFW R1 decompilation): - * - "phone": pairAuth on the system channel, health sync; only the data - * CCCD (what Even's app does). - * - "glasses": enable the legacy-channel CCCD, which appears to be what - * assigns a link the glasses role, and skip pairAuth and health. Only works while the - * glasses themselves do not hold that role. - * - "both": the long-standing default, both CCCDs plus pairAuth. If the - * glasses role is free this probably asks for both roles on one link; - * the decompiled stock role setter hits a fatal assertion on that. - * A change while the direct link is up reconnects it. + * one glasses role, on separate links, and sends gestures and battery + * pushes only to the glasses role: + * - "phone" (default): pairAuth on the system channel and health sync, + * with only the data CCCD, like Even's app. The glasses keep the ring. + * - "glasses": act as the ring's glasses (legacy CCCD, legacy pair-auth, + * touch source on; see runRingGlassesSetup) and take the ring over from + * the glasses when they still hold it. No health sync: the ring answers + * system requests only on a phone-role link. + * Asking for both on one link (the old behavior) made the ring drop the + * link every ~6 s while the glasses held it. A change while the direct + * link is up reconnects it. */ fun setDirectRingRole(role: String?) { - val normalized = when (role) { - DIRECT_RING_ROLE_PHONE -> DIRECT_RING_ROLE_PHONE - DIRECT_RING_ROLE_GLASSES -> DIRECT_RING_ROLE_GLASSES - else -> DIRECT_RING_ROLE_BOTH - } + val normalized = if (role == DIRECT_RING_ROLE_GLASSES) DIRECT_RING_ROLE_GLASSES else DIRECT_RING_ROLE_PHONE monitor.withLock { if (normalized == directRingRole) return directRingRole = normalized @@ -1872,6 +1879,7 @@ class GlassesSessionCore( ringCharging = ring.charging lastGlassesRingBatteryAtMs = now() emitBatteryState(headsetBattery, headsetCharging) + if (ring.battery >= 0) releaseRingFromGlassesLocked("glasses report the ring connected") } } // CFW mic status (field 104) rides both standalone pushes and @@ -1939,6 +1947,7 @@ class GlassesSessionCore( if (decoded.eventSource == BleProtocol.EVENT_SOURCE_RING) { lastGlassesRingInputAtMs = lastIncomingAtMs lastGlassesRingInputLabel = decoded.kind + " type=" + decoded.eventType + releaseRingFromGlassesLocked("ring input relayed by the glasses") } } if ("list-click" == decoded.kind || "text-click" == decoded.kind) { @@ -2010,6 +2019,9 @@ class GlassesSessionCore( if (handleRingHealthNotification(characteristicUuid, data)) { return } + if (handleRingLegacyControl(data)) { + return + } val decoded = FaceclawRingEventDecoder.decode(data) if (decoded == null) { monitor.withLock { @@ -2362,10 +2374,10 @@ class GlassesSessionCore( // only to that role. The direct ring // role setting decides which CCCDs we enable; see setDirectRingRole. val role = monitor.withLock { directRingRole } - val phoneNotify = role != DIRECT_RING_ROLE_PHONE - && enableRingNotification(BleProtocol.R1_PHONE_NOTIFY_CHAR_UUID) + val legacyNotify = role == DIRECT_RING_ROLE_GLASSES + && enableRingNotification(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID) val dataNotify = enableRingNotification(BleProtocol.R1_NOTIFY_CHAR_UUID) - if (!phoneNotify && !dataNotify) { + if (!legacyNotify && !dataNotify) { throw IllegalStateException("no R1 notify characteristic subscribed") } @@ -2381,12 +2393,18 @@ class GlassesSessionCore( ringWriteBlockedUntilMs = 0L ringWriteFailures = 0 ringConnectFailures = 0 + // The ring forgets touch-source state with the link, so every + // glasses-role connection repeats the setup (runRingGlassesSetup). + ringGlassesSetupPending = role == DIRECT_RING_ROLE_GLASSES + directGlassesAuth = "" + directGlassesAuthAtMs = 0L + directGlassesAuthRetried = false } - logLine("direct ring ready role=$role phoneNotify=$phoneNotify dataNotify=$dataNotify") + logLine("direct ring ready role=$role legacyNotify=$legacyNotify dataNotify=$dataNotify") - // Claiming the glasses role means no pairAuth (it would ask for the - // phone role on the same link) and therefore no health sync. - if (dataNotify && host.supportsRingHealth() && role != DIRECT_RING_ROLE_GLASSES) { + // The glasses role means no pairAuth (it would ask for the phone role + // on the same link) and therefore no health sync. + if (dataNotify && host.supportsRingHealth() && role == DIRECT_RING_ROLE_PHONE) { onRingDataChannelReady() } } @@ -2528,7 +2546,7 @@ class GlassesSessionCore( if (!isConfiguredRingAddress(address) || characteristicUuid == null) { return false } - return BleProtocol.R1_PHONE_NOTIFY_CHAR_UUID == characteristicUuid + return BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID == characteristicUuid || BleProtocol.R1_NOTIFY_CHAR_UUID == characteristicUuid } diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt index 6e147ba5..bdbf05af 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionRing.kt @@ -134,6 +134,7 @@ internal fun GlassesSessionCore.runRingWorker() { if (shouldAttemptRingConnect()) tryConnectRing("ring worker") if (!running) break flushRingConfigCommands() + runRingGlassesSetup() flushRingOutbound() runRequestedRingHealthPull() resumeAbortedRingHealthPull() @@ -695,7 +696,9 @@ internal fun GlassesSessionCore.sendRingDevicePing(cmdLo: Int) { * the GATT pipeline the glasses' display writes need for up to the write * timeout. */ -internal fun GlassesSessionCore.writeRingFrame(frame: ByteArray, what: String): Boolean { +internal fun GlassesSessionCore.writeRingFrame( + frame: ByteArray, what: String, characteristicUuid: String = BleProtocol.R1_WRITE_CHAR_UUID, +): Boolean { val blockedForMs = monitor.withLock { ringWriteBlockedUntilMs - now() } if (blockedForMs > 0) { return false @@ -703,7 +706,7 @@ internal fun GlassesSessionCore.writeRingFrame(frame: ByteArray, what: String): val ok = try { val written = link.writeFrames( ringAddress, - BleProtocol.R1_WRITE_CHAR_UUID, + characteristicUuid, listOf(frame), ConnectionOptions.WRITE_MODE, ConnectionOptions.WRITE_TIMEOUT_MS @@ -870,6 +873,9 @@ internal fun GlassesSessionCore.recordGlassesRingReportLocked(frame: BleProtocol if (report.ringName.isNotEmpty()) glassesRingName = report.ringName } logLine("glasses ring report: $lastGlassesRingReport") + if (!ownAck && frame.sid != BleProtocol.SID_RING_DATA && report.code == 0) { + releaseRingFromGlassesLocked("glasses connected the ring") + } } // --------------------------------------------------------------------------- @@ -883,7 +889,6 @@ internal fun GlassesSessionCore.recordGlassesRingReportLocked(frame: BleProtocol // (advStart, then RING_CONNECT_INFO to the glasses) is from its decompiled // EvConnect.startRingAdvForCurrentGlasses. Not verified on hardware. -internal const val DIRECT_RING_ROLE_BOTH = "both" internal const val DIRECT_RING_ROLE_PHONE = "phone" internal const val DIRECT_RING_ROLE_GLASSES = "glasses" @@ -1043,3 +1048,99 @@ internal fun GlassesSessionCore.restartRingLinkForRoleChange() { logLine("direct ring: reconnecting to take the $role role") link.disconnect(ringAddress) } + +// --------------------------------------------------------------------------- +// Acting as the ring's glasses (direct ring role "glasses") +// +// Mirrors what the stock G2 does on connecting to its ring +// (g2-firmware-emulator docs/r1-cccd-frontier.md, r1-command88-native.md): +// enable the legacy CCCD (connectRing), then write the legacy pair-auth. We +// add touchSwitch "glasses source on", without which a link gets no +// gestures (hardware, 2026-10-06). The ring keeps its targets and the +// glasses keep their unpairing across connections, so those are sent only +// when the ring or the glasses show they are still bound to each other. + +/** Floor between automatic glasses unpair requests, so a fight with something re-binding the ring stays slow. */ +private const val RING_RELEASE_MIN_INTERVAL_MS = 2L * 60L * 1000L + +/** + * The per-connection glasses-role setup. Ring worker only; a failed write + * leaves it pending for the next tick (after writeRingFrame's backoff). + */ +internal fun GlassesSessionCore.runRingGlassesSetup() { + monitor.withLock { + if (!ringGlassesSetupPending || !ringNotificationsReady) return + // Before the write: the ring answers within milliseconds. + directGlassesAuth = "sent" + directGlassesAuthAtMs = now() + } + if (!writeRingFrame(RingProtocol.LEGACY_GLASSES_PAIR_AUTH, "glasses pair-auth", BleProtocol.R1_LEGACY_WRITE_CHAR_UUID)) { + return + } + val touch = monitor.withLock { + RingProtocol.buildTouchSwitch(nextRingSeqLocked(), RingProtocol.TOUCH_SWITCH_SELECTOR_GLASSES, true) + } + if (!writeRingFrame(touch, "touch source on")) { + return + } + monitor.withLock { ringGlassesSetupPending = false } + logLine("direct ring: sent glasses pair-auth and touch source on") +} + +/** + * Legacy-channel control frames that are not input: the battery report and + * the target rejection. Returns true when consumed. GATT callback thread. + */ +internal fun GlassesSessionCore.handleRingLegacyControl(data: ByteArray): Boolean { + val battery = RingProtocol.parseLegacyBattery(data) + if (battery != null) { + monitor.withLock { + directRingBattery = battery.battery + directRingCharging = battery.charging + // Only the accepted glasses peer gets these. + directGlassesAuth = "accepted" + directGlassesAuthAtMs = now() + emitBatteryState(headsetBattery, headsetCharging) + } + logLine("direct ring battery " + battery.battery + "% charging=" + battery.charging + " (legacy report)") + return true + } + if (!RingProtocol.isLegacyTargetRejected(data)) { + return false + } + // The ring's advStart targets name other glasses (normally ours, from the + // Even app's pairing), so it drops this link in ~20 s. Clear them once per + // connection, then repeat the pair-auth so it is checked again. + val clearing = monitor.withLock { + directGlassesAuthAtMs = now() + if (directGlassesAuthRetried) { + directGlassesAuth = "rejected again: ring is bound to other glasses" + false + } else { + directGlassesAuthRetried = true + directGlassesAuth = "rejected: clearing the ring's glasses targets" + queueRingConfigCommandLocked("remove-ring", null, "", "") + ringGlassesSetupPending = true + true + } + } + logLine("direct ring: glasses pair-auth rejected (ring bound to other glasses)" + + if (clearing) "; clearing its targets and retrying" else "; giving up for this connection") + return true +} + +/** + * The glasses still hold the ring while the direct link wants its glasses + * role: ask them to unpair it (UNPAIR_INFO), which they remember until + * something re-pairs them. Rate-limited. Caller holds `monitor`. + */ +internal fun GlassesSessionCore.releaseRingFromGlassesLocked(reason: String) { + if (!hasRingAddress() || directRingRole != DIRECT_RING_ROLE_GLASSES || !running || !sessionReady) return + val now = now() + if (lastRingReleaseAtMs != 0L && now - lastRingReleaseAtMs < RING_RELEASE_MIN_INTERVAL_MS) return + lastRingReleaseAtMs = now + logLine("direct ring: the glasses still hold the ring ($reason); asking them to unpair it") + if (queueGlassesRingLinkCommandLocked("unpair", ringAddress, glassesRingName)) { + interruptibleSleep.interrupt() + } +} diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt index 58a99ffe..b4611639 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt @@ -1033,6 +1033,7 @@ internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessa // Old firmware and missing/malformed extensions must clear any prior reading. ringBattery = if (ring == null) -1 else ring.battery ringCharging = if (ring == null) -1 else ring.charging + if (ringBattery >= 0) releaseRingFromGlassesLocked("glasses report the ring connected") val snapshot = BleProtocol.parseSettingsBattery(message.ackPayload) if (snapshot != null) { headsetBattery = snapshot.battery diff --git a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt index bb24ea5e..d6c91649 100644 --- a/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt +++ b/tests/kotlin/src/commonTest/kotlin/com/faceclaw/app/GlassesRingLinkTest.kt @@ -84,6 +84,24 @@ class GlassesRingLinkTest { assertEquals("02" + "0082" + "01", toHex(remove.copyOfRange(10, 13)) + toHex(remove.copyOfRange(17, remove.size))) } + @Test fun legacyGlassesChannelFrames() { + // Bytes from g2-firmware-emulator: the stock G2's pair-auth, the R1's battery + // report (67%, then charging) and its non-target rejection. + assertEquals("00358800", toHex(RingProtocol.LEGACY_GLASSES_PAIR_AUTH)) + val idle = assertNotNull(RingProtocol.parseLegacyBattery(hex("00098b004300"))) + assertEquals(67, idle.battery) + assertEquals(0, idle.charging) + assertEquals(1, assertNotNull(RingProtocol.parseLegacyBattery(hex("00098b004301"))).charging) + assertNull(RingProtocol.parseLegacyBattery(hex("00098b006500"))) // 101% + assertNull(RingProtocol.parseLegacyBattery(hex("00098b0043"))) + assertNull(RingProtocol.parseLegacyBattery(hex("000961000a000013cb0000"))) + assertTrue(RingProtocol.isLegacyTargetRejected(hex("00019600"))) + assertFalse(RingProtocol.isLegacyTargetRejected(hex("0001960000"))) + // Neither is mistaken for input. + assertNull(FaceclawRingEventDecoder.decode(hex("00098b004300"))) + assertNull(FaceclawRingEventDecoder.decode(hex("00019600"))) + } + @Test fun ringResponseStatusDecodes() { assertEquals("ok", RingProtocol.responseResult(0x03)) assertEquals("error", RingProtocol.responseResult(0x07))