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

@@ -126,6 +126,8 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre
fun setListener(listener: FaceclawBleCommunicatorListener?) = core.setListener(listener)
fun setRequiredFirmwareRevision(revision: Int) = core.setRequiredFirmwareRevision(revision)
fun start() {
if (core.start()) {
activeInstance = this
+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',
@@ -791,8 +791,8 @@ class BleProtocol {
* are fields 5/6 of the deviceReceiveRequestFromApp submessage (field 4); Faceclaw's custom
* firmware additionally appends top-level field 100 with its revision ("Faceclaw/<n>";
* older builds sent "EVENCFW/<ver> <tokens>"), which stock firmware never sends. Returns
* null when the ack carries none of it. Compatibility is judged on the TS side
* (app/g2/firmware-compat.ts); Java only needs to know whether the firmware is ours at all.
* null when the ack carries none of it. The session halts when [FirmwareInfo.isCompatible]
* fails; the user-facing classification and messages live in app/g2/firmware-compat.ts.
*/
@JvmStatic
fun parseSettingsFirmwareInfo(pb: ByteArray): FirmwareInfo? {
@@ -1471,11 +1471,34 @@ class BleProtocol {
/**
* True when the glasses run Faceclaw's custom firmware (any revision). Whether the revision
* is the one this app needs is decided on the TS side, which disconnects on a mismatch;
* this only guards the private modes against stock or third-party firmware in the meantime.
* is one this app can run is [isCompatible]; this only guards the private modes against
* stock or third-party firmware.
*/
fun isFaceclawFirmware(): Boolean {
return extension.trim().startsWith(FACECLAW_EXTENSION_PREFIX)
}
/**
* The revision from a "Faceclaw/<n>" extension, or -1 for stock, pre-revision
* ("EVENCFW/...") and third-party firmware. Mirrors parseFirmwareExtension in
* app/g2/firmware-compat.ts.
*/
fun faceclawRevision(): Int {
val text = extension.trim()
if (!text.startsWith(FACECLAW_EXTENSION_PREFIX)) {
return -1
}
val digits = text.substring(FACECLAW_EXTENSION_PREFIX.length).trimStart().takeWhile { it in '0'..'9' }
return digits.toIntOrNull() ?: -1
}
/**
* True when this is Faceclaw's firmware at [requiredRevision] or newer (revisions only add
* to the contract). Mirrors hasCompatibleFirmware in app/g2/firmware-compat.ts.
*/
fun isCompatible(requiredRevision: Int): Boolean {
val revision = faceclawRevision()
return revision >= 0 && revision >= requiredRevision
}
}
}
@@ -359,23 +359,7 @@ internal fun GlassesSessionCore.firstUnpairedArm(): String? {
*/
internal fun GlassesSessionCore.handleUnpairedFailure(address: String) {
logError("Connect failed and $address is not paired; suspending reconnect")
monitor.withLock {
reconnectHalted = true
sessionReady = false
fixedLayoutCreated = false
startupProbePending = false
shutdownRequested = false
chargingMode = false
imageRetryAfterMs = 0
displayedFingerprint = ""
faceclawWakePendingNonce = -1
lastFaceclawWakeLeaseQueuedAtMs = 0
faceclawWakeControlSentCount = 0
clearAllMessagesLocked("arm not paired: $address")
reconnectAfterMs = Long.MAX_VALUE
link.disconnect(rightAddress)
link.disconnect(leftAddress)
}
monitor.withLock { haltReconnectLocked("arm not paired: $address") }
if (!userDisconnectRequested) {
setStateDisplay(
"unpaired",
@@ -386,6 +370,59 @@ internal fun GlassesSessionCore.handleUnpairedFailure(address: String) {
interruptibleSleep.interrupt()
}
/**
* The settings ack reported firmware this app can't run: stock, another
* project's, or an older Faceclaw revision (see
* [BleProtocol.FirmwareInfo.isCompatible]). Everything else this session
* would send is a private-mode message the glasses may misread (stock leaves
* them unacked until the CFW retry limit drops the link), and a redial would
* only find the same firmware, so park the worker loop like
* [handleUnpairedFailure], without any cleanup messages. The firmware info
* was emitted just before this, so the TS side can explain the mismatch and
* offer the custom-firmware install.
*/
internal fun GlassesSessionCore.handleIncompatibleFirmware() {
val info = monitor.withLock {
val pending = incompatibleFirmware
incompatibleFirmware = null
pending
} ?: return
logError("Glasses report incompatible firmware L=" + info.leftVersion + " R=" + info.rightVersion
+ " ext=\"" + info.extension + "\" (need Faceclaw/" + requiredFirmwareRevision + "); suspending reconnect")
monitor.withLock { haltReconnectLocked("incompatible firmware") }
if (!userDisconnectRequested) {
setStateDisplay(
"incompatible-firmware",
"The glasses firmware is not compatible with this version of Faceclaw."
+ " Install the custom firmware, then connect."
)
}
interruptibleSleep.interrupt()
}
/**
* Park the worker loop for good: drop both arms, discard queued traffic and
* stop redialing. Only an explicit connect (start() on a fresh communicator)
* tries again.
*/
internal fun GlassesSessionCore.haltReconnectLocked(reason: String) {
reconnectHalted = true
sessionReady = false
fixedLayoutCreated = false
startupProbePending = false
shutdownRequested = false
chargingMode = false
imageRetryAfterMs = 0
displayedFingerprint = ""
faceclawWakePendingNonce = -1
lastFaceclawWakeLeaseQueuedAtMs = 0
faceclawWakeControlSentCount = 0
clearAllMessagesLocked(reason)
reconnectAfterMs = Long.MAX_VALUE
link.disconnect(rightAddress)
link.disconnect(leftAddress)
}
/**
* Tear the session down and schedule a reconnect. [displayStatus], when given, replaces the
* generic "Reconnecting after <reason>" status line.
@@ -454,6 +491,7 @@ internal fun GlassesSessionCore.resetSessionStateLocked() {
reconnectAfterMs = 0
consecutiveReconnects = 0
reconnectHalted = false
incompatibleFirmware = null
ringReconnectAfterMs = 0
lastAckAtMs = 0
lastIncomingAtMs = 0
@@ -127,10 +127,16 @@ class GlassesSessionCore(
internal val audioMonitorListeners = CopyOnWriteList<FaceclawAudioPacketListener>(platform)
@Volatile internal var running = false
@Volatile internal var userDisconnectRequested = false
// Set when a connect attempt failed while an arm's OS bond is gone:
// retrying is pointless until the user re-pairs, so the worker loop parks
// Set when a connect attempt failed while an arm's OS bond is gone, or the
// glasses reported firmware this app can't run: retrying is pointless until
// the user re-pairs or installs the custom firmware, so the worker loop parks
// instead of redialing. Cleared by start() (a fresh explicit connect).
@Volatile internal var reconnectHalted = false
// The Faceclaw firmware revision this app needs; see setRequiredFirmwareRevision.
@Volatile internal var requiredFirmwareRevision = 0
// Firmware info from a settings ack that failed requiredFirmwareRevision. While
// set, driveSession sends nothing; the worker loop halts on it (handleIncompatibleFirmware).
internal var incompatibleFirmware: BleProtocol.FirmwareInfo? = null
internal var phase = "disconnected"
internal var status = "Disconnected."
@@ -179,9 +185,9 @@ class GlassesSessionCore(
/**
* The last firmware-info read said the glasses run Faceclaw's custom
* firmware. Gates the private modes (cleanup, resource cache, ...) so stock
* or third-party firmware never sees them; the TS side checks the actual
* revision and disconnects on a mismatch, so no per-feature gating is
* needed here.
* or third-party firmware never sees them; a revision mismatch halts the
* session (handleIncompatibleFirmware), so no per-feature gating is needed
* here.
*/
internal var customFirmwareDetected = false
internal val brightnessPolicy = BrightnessPolicy()
@@ -230,7 +236,6 @@ class GlassesSessionCore(
internal var phoneLockState = -1
internal var lastPhoneLockCheckAtMs = 0L
internal var audioCaptureActive = false
internal var firmwareInfoQueried = false
// Glasses are in the charging case: nobody is wearing them, so display
// communication pauses and only battery polls flow (see driveSession).
internal var chargingMode = false
@@ -371,6 +376,15 @@ class GlassesSessionCore(
emitPhoneLockStateIfChanged(true)
}
/**
* The Faceclaw firmware revision this app needs (REQUIRED_FACECLAW_FIRMWARE_VERSION in
* app/g2/firmware-compat.ts; the TS bridges pass it in before start()). A settings ack
* reporting anything else halts the session. 0 accepts any Faceclaw revision.
*/
fun setRequiredFirmwareRevision(revision: Int) {
requiredFirmwareRevision = revision
}
/** Start the worker (through the host); false when it was already running. */
fun start(): Boolean {
monitor.withLock {
@@ -380,6 +394,7 @@ class GlassesSessionCore(
running = true
userDisconnectRequested = false
reconnectHalted = false
incompatibleFirmware = null
shutdownRequested = false
host.startWorker { run() }
return true
@@ -1297,6 +1312,10 @@ class GlassesSessionCore(
break
}
emitPhoneLockStateIfChanged(false)
if (monitor.withLock { incompatibleFirmware != null }) {
handleIncompatibleFirmware()
continue
}
if (!sessionReady) {
if (reconnectHalted) {
interruptibleSleep.sleep(ConnectionOptions.IDLE_SLEEP_MS.toLong())
@@ -1760,16 +1779,16 @@ class GlassesSessionCore(
setStateDisplay("connected", "Connected.")
logLine("session ready")
monitor.withLock {
// Query settings promptly on the first session so firmware
// Query settings at the start of every session so firmware
// version/extension (and battery) arrive without waiting for
// the input-quiet battery poll. The settings response doubles as
// the firmware-compatibility check surfaced during onboarding.
if (!firmwareInfoQueried) {
firmwareInfoQueried = true
lastBatteryRefreshAtMs = now()
pendingMessages.addLast(createBatteryQueryMessageLocked())
logLine("queue settings query for firmware info")
}
// the input-quiet battery poll. The reply is the firmware-
// compatibility check, and the drive loop only creates the
// layout once the queue is empty, so it lands before any
// custom-firmware traffic -- including after a reconnect to
// glasses that were reflashed in the meantime.
lastBatteryRefreshAtMs = now()
pendingMessages.addLast(createBatteryQueryMessageLocked())
logLine("queue settings query for firmware info")
}
tryConnectRing("initial")
} catch (t: Throwable) {
@@ -52,6 +52,10 @@ internal fun GlassesSessionCore.driveSession(): Long {
maybeFinishNoChangeDesiredFrame()
monitor.withLock {
if (incompatibleFirmware != null) {
// Incompatible firmware: hand back to the worker loop to halt.
return 0
}
drainCfwAcknowledgementsLocked()
if (cfwCleanupDelivered) {
/* Successful mode 11 must be the last Faceclaw write. Drop
@@ -1007,6 +1011,13 @@ internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessa
if (firmwareInfo != null) {
customFirmwareDetected = firmwareInfo.isFaceclawFirmware()
emitFirmwareInfo(firmwareInfo)
if (sessionReady && !firmwareInfo.isCompatible(requiredFirmwareRevision)) {
// Halting tears down the link, which belongs on the worker thread
// (this runs on the notification path); until it does, driveSession
// sends nothing more.
incompatibleFirmware = firmwareInfo
interruptibleSleep.interrupt()
}
}
}
message.onTimeout = MessageCallback {
@@ -70,6 +70,8 @@ class IosGlassesSession internal constructor(
fun setListener(listener: FaceclawBleCommunicatorListener?) = core.setListener(listener)
fun setRequiredFirmwareRevision(revision: Int) = core.setRequiredFirmwareRevision(revision)
fun start(): Boolean = core.start()
fun disconnect() = core.disconnect()
+1
View File
@@ -265,6 +265,7 @@ test('background glasses input still composites frames; phone resume preserves t
'../native/nightscout-bridge': { nightscoutBridge: { async start() { pollStarts++; }, async stop() { pollStops++; } } },
'./glance-host': { GlanceHost: class { dismiss() {} reset() {} isVisible() { return false; } } },
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'./firmware-compat': load('app/g2/firmware-compat.ts', {}), './reconnect-policy': load('app/g2/reconnect-policy.ts', {}),
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
'../apps/launcher': { launcherEntries: () => [] },
'../apps/all-apps': { ALL_APPS: [] }, '../ui/dashboard-settings': settings,
+1
View File
@@ -146,6 +146,7 @@ function fixture() {
'./glance-host': { GlanceHost }, './events': events,
'./lock-screen': { LOCK_SCREEN_SURFACE_ID: 'lock-screen', createLockScreenImage: () => new images.GrayImage(640, 480, 123) },
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'./firmware-compat': load('app/g2/firmware-compat.ts', {}), './reconnect-policy': load('app/g2/reconnect-policy.ts', {}),
'../apps/launcher': { launcherEntries: () => [] },
'../apps/evenhub/installed-apps': {}, '../apps/evenhub/manager': {}, '../apps/evenhub/updates': {}, '../apps/evenhub': {},
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
@@ -10,6 +10,7 @@ import kotlin.test.assertTrue
private const val RIGHT = "AA:00:00:00:00:01"
private const val LEFT = "AA:00:00:00:00:02"
private const val STOCK_VERSION = "2.3.0.24"
/** The test platform with a clock the tests can jump forward (the real waits keep real time). */
private class ClockPlatform(private val base: ProtocolPlatform) : ProtocolPlatform by base {
@@ -64,6 +65,12 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
@Volatile var closed = false
/** An address whose connection attempts fail, like an arm that isn't advertising. */
@Volatile var unreachable: String? = null
/**
* The firmware-extension string settings READ acks report alongside [STOCK_VERSION] on both
* arms ("" is stock firmware, which omits the field), or null for an ack without firmware info.
*/
@Volatile var firmwareExtension: String? = null
@Volatile var connects = 0
var seq = 0
val writes: List<Write>
@@ -73,6 +80,7 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
fun cfwMessages(): List<ByteArray> = writes.filter { it.sid == CfwTransport.SID && it.kind == "image" }.mapNotNull { it.message }
override fun connect(address: String, timeoutMs: Int): Boolean {
connects++
if (address == unreachable) return false
lock.withLock { connected.add(address) }
return true
@@ -105,15 +113,22 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
if (sid == CfwTransport.SID) {
for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum))
} else {
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb))
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, inFlight.kind))
}
}
return true
}
private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray {
private fun ackFrame(sid: Int, magic: Int, kind: String?): ByteArray {
val extension = firmwareExtension
val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00)
else if (kind == "battery" && extension != null)
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic) +
BleProtocol.encodeBytesField(4,
BleProtocol.encodeBytesField(5, STOCK_VERSION.encodeToByteArray()) +
BleProtocol.encodeBytesField(6, STOCK_VERSION.encodeToByteArray())) +
(if (extension.isEmpty()) ByteArray(0) else BleProtocol.encodeBytesField(100, extension.encodeToByteArray()))
else
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return BleProtocol.framePb(body, sid, 0x00, seq++)[0]
@@ -207,6 +222,7 @@ private class FakeListener : FaceclawBleCommunicatorListener {
val events = ArrayList<String>()
val finished = ArrayList<String>()
val batteries = ArrayList<String>()
val firmware = ArrayList<String>()
override fun onStateChange(phase: String?, status: String?) {
phases.add(phase ?: "")
@@ -235,7 +251,9 @@ private class FakeListener : FaceclawBleCommunicatorListener {
finished.add("$frameId:$outcome")
}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {
firmware.add("$leftVersion|$rightVersion|$extension")
}
}
private class Session {
@@ -565,4 +583,85 @@ class GlassesSessionCoreTest {
s.core.close()
}
}
@Test
fun stockFirmwareHaltsTheSessionBeforeAnyCustomFirmwareTraffic() {
val s = Session()
s.core.setRequiredFirmwareRevision(36)
s.link.firmwareExtension = ""
try {
assertTrue(s.core.start())
assertTrue(waitUntil(5_000) { s.listener.phases.contains("incompatible-firmware") }, s.host.logs().takeLast(10).toString())
assertEquals(listOf("$STOCK_VERSION|$STOCK_VERSION|"), s.listener.firmware)
assertTrue(s.host.hasLog("incompatible firmware"), s.host.logs().takeLast(10).toString())
// The settings reply precedes the layout, so stock never sees a private-stream message.
assertEquals(0, s.link.writes.count { it.kind == "create-layout" })
assertEquals(0, s.link.writes.count { it.sid == CfwTransport.SID })
assertTrue(s.link.disconnected.containsAll(listOf(RIGHT, LEFT)))
assertFalse(s.core.isSessionReady())
// Parked rather than retrying: no redial even well past the backoff schedule.
val connects = s.link.connects
s.platform.offsetMs += 60_000
s.core.interruptibleSleep.interrupt()
sleepMs(300)
assertEquals(connects, s.link.connects)
assertEquals("incompatible-firmware", s.listener.phases.last())
assertFalse(s.listener.phases.contains("retrying"))
} finally {
s.core.close()
}
}
@Test
fun anOlderFaceclawRevisionAlsoHalts() {
val s = Session()
s.core.setRequiredFirmwareRevision(36)
s.link.firmwareExtension = "Faceclaw/35"
try {
assertTrue(s.core.start())
assertTrue(waitUntil(5_000) { s.listener.phases.contains("incompatible-firmware") }, s.host.logs().takeLast(10).toString())
assertEquals(0, s.link.writes.count { it.kind == "create-layout" })
} finally {
s.core.close()
}
}
@Test
fun compatibleFirmwareIsCheckedAgainOnEverySession() {
val s = Session()
s.core.setRequiredFirmwareRevision(36)
s.link.firmwareExtension = "Faceclaw/36"
try {
s.startAndAwaitLayout()
assertTrue(s.core.monitor.withLock { s.core.customFirmwareDetected })
assertFalse(s.listener.phases.contains("incompatible-firmware"))
// The glasses come back on stock firmware (reflashed while the link was down):
// the new session's own settings query catches it before the layout.
s.link.firmwareExtension = ""
s.core.handleTransportFailure("test drop")
s.platform.offsetMs += 10_000
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5_000) { s.listener.phases.contains("incompatible-firmware") }, s.host.logs().takeLast(10).toString())
assertEquals(2, s.link.writes.count { it.kind == "battery" })
assertEquals(1, s.link.writes.count { it.kind == "create-layout" })
} finally {
s.core.close()
}
}
@Test
fun firmwareCompatibilityFollowsTheRevisionString() {
fun info(extension: String) = BleProtocol.FirmwareInfo(STOCK_VERSION, STOCK_VERSION, extension)
assertEquals(-1, info("").faceclawRevision())
assertEquals(-1, info("EVENCFW/22 img640").faceclawRevision())
assertEquals(-1, info("Faceclaw/abc").faceclawRevision())
assertEquals(-1, info("OtherCFW/36").faceclawRevision())
assertEquals(36, info(" Faceclaw/36 ").faceclawRevision())
assertFalse(info("").isCompatible(36))
assertFalse(info("Faceclaw/35").isCompatible(36))
assertTrue(info("Faceclaw/36").isCompatible(36))
assertTrue(info("Faceclaw/40").isCompatible(36))
assertTrue(info("Faceclaw/1").isCompatible(0))
assertFalse(info("EVENCFW/22").isCompatible(0))
}
}