Refactor iOS glasses connection handling to shared code, fixing incompatible-version-detection and other error cases

This commit is contained in:
James Babcock committed 2026-10-03 15:08:37 -07:00
1 parent 9b0bf77d79
commit 66ca06f584
16 files changed
+341 -119

No files matched your search

+1
View File
@@ -174,6 +174,7 @@ Page.main-page {
}
.main-page .action-bar-title { font-size: 18; font-weight: bold; color: #ffffff; }
.main-page .action-bar-status { font-size: 14; color: #ffffff; margin-right: 12; }
.main-page .action-bar-warning { font-size: 18; padding: 4 6; }
.main-page .overflow-button {
background-color: transparent;
color: #ffffff;
+25 -60
View File
@@ -20,7 +20,7 @@ import { openEvenAppSettings, readEvenAppNotificationState } from "../native/eve
import { grayImageToPreviewSource } from "../native/gray-image-preview";
import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from "./firmware-compat";
import { hasExtractedEvenHubFonts } from "./firmware-builder";
import { resumeAutoReconnect, suppressAutoReconnect } from "./reconnect-policy";
import { isHaltedSessionPhase, resumeAutoReconnect, suppressAutoReconnect } from "./reconnect-policy";
import { WearRemote, type WearRemoteInputKind } from "./wear-remote";
/** Who a synthetic (non-firmware) input stands for. */
@@ -361,11 +361,10 @@ class DashboardController {
private openAppsRestored = false;
private suppressOpenAppsPersist = false;
// connect() is a long sequence of awaits against this.communicator; the
// incompatible-firmware disconnect must not tear that communicator down
// halted-session disconnect must not tear that communicator down
// underneath it, so it waits for this to clear.
private connectRunning = false;
private incompatibleDisconnectPending = false;
private unpairedDisconnectPending = false;
private haltedDisconnectPending = false;
constructor() {
const sharedActions = {
@@ -1456,12 +1455,12 @@ class DashboardController {
await communicator.configureBrightness(getBrightnessPreferences());
this.offState = communicator.onStateChange((state) => {
if (state.phase !== "connected") resetRingInputFilter();
if (state.phase === "unpaired") {
// Java parked its retry loop: an arm's Android bond is gone, so
// every redial would fail the same way until the user re-pairs.
// Tear down into the manual-disconnected state and keep the
// re-pair instruction as the visible status.
this.scheduleUnpairedDisconnect(state.status);
if (isHaltedSessionPhase(state.phase)) {
// The shared session parked its retry loop (an arm's Android bond
// is gone, or the firmware can't run Faceclaw), so every redial
// would fail the same way. Tear down into the manual-disconnected
// state and keep the session's explanation as the visible status.
this.scheduleHaltedSessionDisconnect(state.status);
return;
}
const mappedPhase =
@@ -1604,6 +1603,8 @@ class DashboardController {
});
this.ensureWearStateTracking();
}
// The shared session halts on incompatible firmware by itself
// ("incompatible-firmware" phase); this only explains why.
if (warning !== this.firmwareWarningMessage) {
this.firmwareWarningMessage = warning;
if (warning) {
@@ -1611,9 +1612,6 @@ class DashboardController {
}
this.emit();
}
if (warning) {
this.scheduleIncompatibleFirmwareDisconnect();
}
});
// The Music and Nightscout apps subscribe to their bridges directly and
// repaint their own windows, so bridge updates need no controller action.
@@ -1711,61 +1709,28 @@ class DashboardController {
}
/**
* Incompatible firmware means every message Faceclaw sends is one the
* glasses may misinterpret, and a live session fights the flash flow's own
* connection. Drop the connection (without the CFW-directed cleanup
* messages) and hold in the manual-disconnected state until the user
* connects explicitly or installs the custom firmware.
* The shared session parked its retry loop (an arm's Android bond is gone,
* or the glasses run firmware Faceclaw can't use; see isHaltedSessionPhase)
* and dropped both arms. Finish the teardown (without the CFW-directed
* cleanup messages, which incompatible firmware would misread) and hold in
* the manual-disconnected state until the user connects explicitly,
* re-pairs or installs the custom firmware, keeping [message] from the
* session as the status the user sees.
*/
private scheduleIncompatibleFirmwareDisconnect(): void {
if (this.incompatibleDisconnectPending) return;
this.incompatibleDisconnectPending = true;
private scheduleHaltedSessionDisconnect(message: string): void {
if (this.haltedDisconnectPending) return;
this.haltedDisconnectPending = true;
const attempt = () => {
// Firmware info can arrive while connect() is still mid-flight; let it
// The halt can be reported while connect() is still mid-flight; let it
// finish so the teardown doesn't race its surface setup.
if (this.connectRunning) {
setTimeout(attempt, 200);
return;
}
this.incompatibleDisconnectPending = false;
this.haltedDisconnectPending = false;
if (this.phase === "disconnected" || this.phase === "disconnecting") {
// The session ended some other way; still stop auto-reconnect from
// re-dialing glasses we know can't run Faceclaw.
suppressAutoReconnect();
return;
}
this.appendLog(
"Disconnecting: the glasses firmware is incompatible. Auto-reconnect is disabled until you connect manually or install the custom firmware.",
);
void this.disconnect({ skipFirmwareCleanup: true })
.then(() => this.setStatus("Disconnected (incompatible firmware)."))
.catch((error) => {
this.appendLog(`incompatible-firmware disconnect failed: ${this.formatError(error)}`);
});
};
setTimeout(attempt, 0);
}
/**
* A connect attempt found an arm whose Android bond is missing, so the Java
* worker stopped retrying. Drop into the manual-disconnected state (no
* auto-reconnect: it would just fail again) and leave the re-pair
* instruction from Java as the status the user sees.
*/
private scheduleUnpairedDisconnect(message: string): void {
if (this.unpairedDisconnectPending) return;
this.unpairedDisconnectPending = true;
const attempt = () => {
// The unpaired report can arrive while connect() is still mid-flight;
// let it finish so the teardown doesn't race its surface setup.
if (this.connectRunning) {
setTimeout(attempt, 200);
return;
}
this.unpairedDisconnectPending = false;
if (this.phase === "disconnected" || this.phase === "disconnecting") {
// The session ended some other way; still stop auto-reconnect from
// re-dialing glasses that are no longer paired.
// re-dialing glasses that would fail the same way.
suppressAutoReconnect();
this.setStatus(message);
return;
@@ -1774,7 +1739,7 @@ class DashboardController {
void this.disconnect({ skipFirmwareCleanup: true })
.then(() => this.setStatus(message))
.catch((error) => {
this.appendLog(`unpaired disconnect failed: ${this.formatError(error)}`);
this.appendLog(`halted-session disconnect failed: ${this.formatError(error)}`);
});
};
setTimeout(attempt, 0);
+42 -16
View File
@@ -24,6 +24,8 @@ import { GlanceHost, type GlanceDisplay } from './glance-host'
import { createLockScreenImage, LOCK_SCREEN_SURFACE_ID } from './lock-screen'
import { OsEventTypeList } from './events'
import { loadDeviceAddresses } from './device-addresses'
import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from './firmware-compat'
import { isHaltedSessionPhase, suppressAutoReconnect } from './reconnect-policy'
import { deviceAddressError } from './ios-peripheral-identity'
import { createLauncherWindow, LAUNCHER_SURFACE_ID } from '../apps/launcher/launcher-app'
import { ALL_APPS } from '../apps/all-apps'
@@ -55,7 +57,9 @@ const FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS = 2000
export type SessionPhase = 'disconnected' | 'connecting' | 'connected' | 'retrying' | 'disconnecting' | 'error'
export type SessionState = { phase: SessionPhase; status: string; battery: number | null; charging: boolean | null;
ring: boolean; frames: number; capabilities: string; leftVersion: string; rightVersion: string }
ring: boolean; frames: number; capabilities: string; leftVersion: string; rightVersion: string;
/** Why the connected firmware can't run Faceclaw (firmware-compat.ts), or '' when it can or is unknown. */
firmwareWarning: string }
function ancsCapable(capabilities: string): boolean {
return /^Faceclaw\/(\d+)/.test(capabilities) && Number(capabilities.split('/')[1]) >= ANCS_FIRMWARE_VERSION
@@ -72,7 +76,7 @@ export class IosPreviewController {
private communicator: FaceclawCommunicatorBridge | null = null
private readonly startedCommunicators = new WeakSet<FaceclawCommunicatorBridge>()
state: SessionState = { phase: 'disconnected', status: 'Preview only', battery: null, charging: null, ring: false,
frames: 0, capabilities: '', leftVersion: '', rightVersion: '' }
frames: 0, capabilities: '', leftVersion: '', rightVersion: '', firmwareWarning: '' }
private notifications: AncsClient | null = null
private readonly sessionOffs: (() => void)[] = []
private stopping: Promise<void> | null = null
@@ -81,6 +85,8 @@ export class IosPreviewController {
private connecting = false
private sessionCreated = false
private wearDetectionRequested = false
/** The last firmware report was Faceclaw's firmware at the required revision. */
private firmwareCompatible = false
private readonly glanceDisplay: GlanceDisplay = {
configureSurface: async (id, options) => { await this.display?.configureSurface(id, options) },
setSurfaceVisible: async (id, visible) => { await this.display?.setSurfaceVisible(id, visible); this.schedulePreviewUpdate() },
@@ -346,7 +352,7 @@ export class IosPreviewController {
if (!enabled) this.setGlassesLocked(false)
else {
if (this.phoneLocked && this.glassesWorn === false) this.setGlassesLocked(true)
if (this.communicator && this.state.phase === 'connected')
if (this.communicator && this.state.phase === 'connected' && this.firmwareCompatible)
void this.communicator.enableWearDetectionAndRequestState().catch(error => this.fail(error))
}
}
@@ -682,7 +688,8 @@ export class IosPreviewController {
this.connecting = true
this.sessionCreated = true
try {
this.state = { ...this.state, capabilities: '', leftVersion: '', rightVersion: '', battery: null, charging: null, ring: false }
this.state = { ...this.state, capabilities: '', leftVersion: '', rightVersion: '', firmwareWarning: '', battery: null, charging: null, ring: false }
this.firmwareCompatible = false
this.update('connecting', 'Finding configured devices…')
let identifiers
try { identifiers = await resolveIosPeripherals(addresses) }
@@ -735,10 +742,19 @@ export class IosPreviewController {
}),
communicator.onFirmwareInfo(info => {
if (this.communicator !== communicator) return
this.logBluetooth(`Firmware: L=${info.leftVersion || '?'} R=${info.rightVersion || '?'}` +
(info.extension ? ` ext="${info.extension}"` : ' (no firmware extension string)'))
// The shared session halts on incompatible firmware by itself ("incompatible-firmware"
// phase, handled in handleSessionState); this only records why, for the warning.
const firmwareWarning = firmwareIncompatibilityMessage(info) ?? ''
if (firmwareWarning && firmwareWarning !== this.state.firmwareWarning) this.logBluetooth(`Firmware compatibility warning: ${firmwareWarning}`)
this.firmwareCompatible = !firmwareWarning && hasCompatibleFirmware(info)
this.state = { ...this.state, leftVersion: info.leftVersion || this.state.leftVersion,
rightVersion: info.rightVersion || this.state.rightVersion, capabilities: info.extension || this.state.capabilities }
rightVersion: info.rightVersion || this.state.rightVersion, capabilities: info.extension || this.state.capabilities,
firmwareWarning }
if (this.active) this.onConnectionState({ ...this.state })
this.syncNotifications(communicator)
this.ensureWearDetection(communicator)
}),
communicator.onFrameMetrics(() => {
if (this.communicator !== communicator) return
@@ -766,21 +782,31 @@ export class IosPreviewController {
// Registering the listener makes the Kotlin session report its current state, which is
// "disconnected" before start(); that must not be mistaken for the session ending.
if (!this.startedCommunicators.has(communicator)) return
const phase: SessionPhase = state.phase === 'charging' ? 'connected' : state.phase === 'unpaired' ? 'error' : state.phase
if (phase === 'connected' && this.state.phase !== 'connected') {
this.state = { ...this.state, frames: this.state.frames }
if (!this.wearDetectionRequested) {
this.wearDetectionRequested = true
void communicator.enableWearDetectionAndRequestState().catch(error => this.logBluetooth(`Wear detection: ${String(error)}`))
}
}
// The shared session parked its retry loop (an arm unpaired, or firmware Faceclaw can't
// run): a redial would fail the same way, so stay down until the user connects explicitly
// (or re-pairs / installs the custom firmware, which lift the suppression).
if (isHaltedSessionPhase(state.phase)) suppressAutoReconnect()
const phase: SessionPhase = state.phase === 'charging' ? 'connected' : isHaltedSessionPhase(state.phase) ? 'error' : state.phase
// Wear state is a per-transport snapshot: ask again on every new session.
if (phase !== 'connected') this.wearDetectionRequested = false
this.update(phase, state.status)
if (phase === 'connected') this.syncNotifications(communicator)
else if ((phase === 'disconnected' || phase === 'error') && !this.stopping) {
// The session ended on its own (retries exhausted, an arm unpaired): release it and go headless.
if (phase === 'connected') {
this.syncNotifications(communicator)
this.ensureWearDetection(communicator)
} else if ((phase === 'disconnected' || phase === 'error') && !this.stopping) {
// The session ended on its own (an arm unpaired, incompatible firmware): release it and go headless.
void this.disconnect(state.status)
}
}
/**
* Wear reports come from the custom firmware, so like Android only ask once the session
* is up and the firmware is confirmed compatible (stock firmware never hears the query).
*/
private ensureWearDetection(communicator: FaceclawCommunicatorBridge): void {
if (this.wearDetectionRequested || !this.firmwareCompatible || this.state.phase !== 'connected') return
this.wearDetectionRequested = true
void communicator.enableWearDetectionAndRequestState().catch(error => this.logBluetooth(`Wear detection: ${String(error)}`))
}
private handleRingEvent(input: RawInputEvent): void {
this.inputQueue = this.inputQueue.then(async () => {
if (this.state.phase !== 'connected') return
+13
View File
@@ -24,3 +24,16 @@ export function resumeAutoReconnect(): void {
export function isAutoReconnectSuppressed(): boolean {
return suppressed;
}
/**
* Communicator phases in which the shared session core has parked its retry
* loop for good: "unpaired" (an arm's OS bond is gone) and
* "incompatible-firmware" (the glasses run firmware this app can't use).
* Redialing would fail the same way, so both platform controllers tear the
* session down into the manual-disconnected state on these.
*/
export type HaltedSessionPhase = "unpaired" | "incompatible-firmware";
export function isHaltedSessionPhase(phase: string): phase is HaltedSessionPhase {
return phase === "unpaired" || phase === "incompatible-firmware";
}
+4 -1
View File
@@ -1,6 +1,6 @@
import type { RingInput } from "../g2/ring-input";
import { File, knownFolders, path, type ImageSource } from "@nativescript/core";
import { type FirmwareInfo } from "../g2/firmware-compat";
import { REQUIRED_FACECLAW_FIRMWARE_VERSION, type FirmwareInfo } from "../g2/firmware-compat";
import { type CompassEvent } from "./compass-types";
import { fromData, toData } from "./kotlin-data";
import { previewPixels } from "./ios-graphics";
@@ -23,6 +23,7 @@ export type CommunicatorPhase =
| "charging"
| "retrying"
| "unpaired"
| "incompatible-firmware"
| "disconnecting";
export type CommunicatorState = {
@@ -203,6 +204,8 @@ export class FaceclawCommunicatorBridge {
String(addresses.left ?? "").toUpperCase(),
String(addresses.ring ?? "").toUpperCase(),
);
// The shared session halts on any other firmware ("incompatible-firmware").
this.communicator.setRequiredFirmwareRevisionRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION);
this.listenerProxy = SessionListener.new() as SessionListener;
this.listenerProxy.bridge = this;
this.communicator.setListenerListener(this.listenerProxy);
+4 -1
View File
@@ -14,6 +14,7 @@ export type CommunicatorPhase =
| "charging"
| "retrying"
| "unpaired"
| "incompatible-firmware"
| "disconnecting";
export type CommunicatorState = {
@@ -34,7 +35,7 @@ export type FrameMetrics = {
tileCount: number;
};
import { type FirmwareInfo } from "../g2/firmware-compat";
import { REQUIRED_FACECLAW_FIRMWARE_VERSION, type FirmwareInfo } from "../g2/firmware-compat";
export type { FirmwareInfo };
@@ -169,6 +170,8 @@ export class FaceclawCommunicatorBridge {
addresses.left,
addresses.ring ?? "",
);
// The shared session halts on any other firmware ("incompatible-firmware").
this.communicator.setRequiredFirmwareRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION);
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
onStateChange: (phase: string, status: string) => {
const state = {
+17 -2
View File
@@ -20,7 +20,7 @@ export function createMainPage(): Page {
root.rows = 'auto,*'
page.content = root
const header = new GridLayout()
header.columns = '*,auto,auto'; header.className = 'main-header'
header.columns = '*,auto,auto,auto'; header.className = 'main-header'
const title = new Label()
title.text = 'Faceclaw'; title.className = 'action-bar-title'
header.addChild(title)
@@ -29,10 +29,17 @@ export function createMainPage(): Page {
state.verticalAlignment = 'middle'
state.on('tap', () => { void openDevices() })
GridLayout.setColumn(state, 1); header.addChild(state)
// Android's warning triangle: shown while the glasses report firmware Faceclaw can't run.
const warning = new Label()
warning.text = '\u26A0\uFE0F'; warning.className = 'action-bar-warning'
warning.accessibilityLabel = 'Attention needed'; warning.verticalAlignment = 'middle'
warning.visibility = 'collapse'
warning.on('tap', () => { void showFirmwareWarning() })
GridLayout.setColumn(warning, 2); header.addChild(warning)
const overflow = new Button()
overflow.text = '⋮'; overflow.accessibilityLabel = 'More options'; overflow.className = 'overflow-button'
overflow.on('tap', () => openMenu())
GridLayout.setColumn(overflow, 2); header.addChild(overflow); root.addChild(header)
GridLayout.setColumn(overflow, 3); header.addChild(overflow); root.addChild(header)
const body = new GridLayout()
GridLayout.setRow(body, 1); root.addChild(body)
const mirror = new Image()
@@ -60,6 +67,7 @@ export function createMainPage(): Page {
}, connection => {
state.text = ({ connected: 'Connected', disconnected: 'Preview', connecting: 'Connecting',
retrying: 'Reconnecting', disconnecting: 'Disconnecting', error: 'Failed' })[connection.phase]
warning.visibility = connection.firmwareWarning ? 'visible' : 'collapse'
}, session => {
keyboardModel.setSession(session)
controls.visibility = session ? 'collapse' : 'visible'
@@ -114,6 +122,13 @@ export function createMainPage(): Page {
}
page.ios.presentViewControllerAnimatedCompletion(menu, true, null)
}
async function showFirmwareWarning(): Promise<void> {
const message = controller.connectionState?.firmwareWarning
if (!message) return
const install = await Dialogs.confirm({ title: 'Attention needed', message,
okButtonText: 'Install custom firmware', cancelButtonText: 'Close' })
if (install) await navigateDevicePage('phone-ui/onboarding-flash-page', { mode: 'install', fromOnboarding: false })
}
async function openDevices(): Promise<void> {
const connected = ['connected', 'connecting', 'retrying'].includes(controller.connectionState?.phase ?? '')
const choice = await Dialogs.action({ title: 'Connection status', message: controller.connectionState?.status ?? 'Preview only', cancelButtonText: 'Cancel',