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

@@ -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()