From 76825f68a7eba2e5de82ccc4d6a3adb1f6fdbecf Mon Sep 17 00:00:00 2001 From: James Babcock Date: Wed, 2 Sep 2026 00:30:50 -0700 Subject: [PATCH] Flashing uses 2.2.9 as base version --- .../app/FaceclawFlashPromptCommunicator.java | 198 ++++++++++++++---- .../app/FaceclawFlashPromptListener.java | 11 +- CHANGELOG | 25 +-- app/apps/evenhub/even-api.ts | 11 +- app/g2/firmware-builder.ts | 15 +- app/g2/firmware-fonts.ts | 12 +- app/native/flash-prompt-communicator.ts | 37 +++- app/phone-ui/onboarding-flash-view-model.ts | 106 ++++++++-- 8 files changed, 324 insertions(+), 91 deletions(-) diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java index e7bce6ca..239e290f 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java @@ -27,9 +27,18 @@ import java.util.concurrent.TimeUnit; * whole lifecycle on a single worker thread. It expects the main app to be * disconnected while it runs (onboarding, before flashing). * - * Only the right arm is used: the lenses relay messages to each other, so - * anything sent to the right arm reaches both, and acks/events only ever come - * from the right arm anyway. + * Both arms are connected and security-authenticated up front, even though the + * prompt itself only needs the right arm (the lenses relay messages to each + * other, and acks/events only ever come from the right arm): on an unbonded + * phone the auth exchange is what raises the OS pairing prompt, and doing both + * here means both prompts appear at the start rather than one popping up half + * way through flashing the second lens. While connected, each arm's battery + * level is read (they are independent batteries) so the caller can refuse to + * flash on a low charge. + * + * With `skipPrompt` the on-glasses confirmation is not shown: the flow is just + * connect + auth + battery read + result(approved). Used to re-check the + * battery after the user has already confirmed once. */ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private static final String TAG = "FaceclawFlashPrompt"; @@ -44,10 +53,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private static final int HEARTBEAT_INTERVAL_MS = 4_000; private static final int SELECTION_TIMEOUT_MS = 120_000; private static final int CREATE_ACK_TIMEOUT_MS = 3_000; + private static final int BATTERY_ACK_TIMEOUT_MS = 3_000; private final Context context; private final String rightAddress; + private final String leftAddress; private final String warningText; + private final boolean skipPrompt; private final FaceclawBleManager bleManager; private final Handler mainHandler = new Handler(Looper.getMainLooper()); @@ -61,6 +73,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private volatile boolean cancelled = false; private volatile boolean finished = false; private volatile boolean rightConnected = false; + private volatile boolean leftConnected = false; private volatile boolean rightLost = false; private volatile Boolean approved = null; private volatile ScheduledExecutorService heartbeatExecutor; @@ -68,10 +81,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private int nextMagic = 100; private int nextSeq = 0x40; - public FaceclawFlashPromptCommunicator(Context context, String rightAddress, String warningText) { + public FaceclawFlashPromptCommunicator( + Context context, String rightAddress, String leftAddress, String warningText, boolean skipPrompt) { this.context = context.getApplicationContext(); this.rightAddress = rightAddress == null ? "" : rightAddress; + this.leftAddress = leftAddress == null ? "" : leftAddress; this.warningText = warningText == null ? "" : warningText; + this.skipPrompt = skipPrompt; this.bleManager = new FaceclawBleManager(this.context); this.bleManager.setListener(this); } @@ -117,43 +133,85 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } emitState("connecting", ""); - connectArm(rightAddress); + connectArm(rightAddress, "right"); rightConnected = true; if (cancelled) { teardown(); return; } + if (!leftAddress.trim().isEmpty()) { + connectArm(leftAddress, "left"); + leftConnected = true; + if (cancelled) { + teardown(); + return; + } + } emitState("connected", ""); - bringUpArm(rightAddress); + // Auth both arms now (pairing prompts, if any, happen here) before + // anything else, so both bonds exist by the time flashing starts. + authenticateArm(rightAddress, "right"); + if (leftConnected) { + authenticateArm(leftAddress, "left"); + } + if (cancelled) { + teardown(); + return; + } + sendPrelude(rightAddress); - startHeartbeat(); - emitState("prompting", ""); + if (!skipPrompt) { + showPrompt(rightAddress); + startHeartbeat(); + emitState("prompting", ""); - boolean signalled = selectionLatch.await(SELECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); - stopHeartbeat(); + selectionLatch.await(SELECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); + stopHeartbeat(); + if (cancelled) { + emitState("cancelled", ""); + teardown(); + return; + } + if (approved == null) { + if (rightLost) { + emitState("disconnected", "Lost connection to the glasses."); + } else { + emitState("timeout", "No response from the glasses."); + } + teardown(); + return; + } + try { + sendShutdown(); + } catch (Exception ignored) { + } + if (!Boolean.TRUE.equals(approved)) { + emitResult(false); + emitState("result", "declined"); + teardown(); + return; + } + } + + // Approved (or prompt skipped): read each arm's battery while the + // links are still up, then report the result. + emitState("battery", ""); + readBatteries(); if (cancelled) { emitState("cancelled", ""); teardown(); return; } - if (approved != null) { - boolean result = Boolean.TRUE.equals(approved); - try { - sendShutdown(); - } catch (Exception ignored) { - } - emitResult(result); - emitState("result", result ? "approved" : "declined"); + if (rightLost) { + emitState("disconnected", "Lost connection to the glasses."); teardown(); return; } - if (rightLost) { - emitState("disconnected", "Lost connection to the glasses."); - } else { - emitState("timeout", "No response from the glasses."); - } + finished = true; + emitResult(true); + emitState("result", "approved"); teardown(); } catch (Exception e) { stopHeartbeat(); @@ -165,26 +223,28 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } } - private void connectArm(String address) { + private void connectArm(String address, String arm) { if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { - throw new IllegalStateException("connect failed: " + address); + throw new IllegalStateException("could not connect to the " + arm + " arm (" + address + ")"); } bleManager.requestConnectionPriority(address, BluetoothGatt.CONNECTION_PRIORITY_HIGH); bleManager.requestMtu(address, ConnectionOptions.DESIRED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS); if (!bleManager.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) { - throw new IllegalStateException("discoverServices failed: " + address); + throw new IllegalStateException("discoverServices failed: " + arm + " arm (" + address + ")"); } if (!bleManager.enableNotifications(address, BleProtocol.NOTIFY_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) { - throw new IllegalStateException("enableNotifications failed: " + address); + throw new IllegalStateException("enableNotifications failed: " + arm + " arm (" + address + ")"); } - emitLog("connected right arm"); + emitLog("connected " + arm + " arm"); } - private void bringUpArm(String address) throws InterruptedException { - // 1. Security-auth exchange on sid=0x80: firmware 2.2.9 will not run a - // session (and closes the link after ~30 s) without it, and on an - // unbonded phone this is what triggers SMP pairing, so it may sit - // waiting on an OS pairing prompt. + /** + * Security-auth exchange on sid=0x80: firmware 2.2.9 will not run a + * session (and closes the link after ~30 s) without it, and on an + * unbonded phone this is what triggers SMP pairing, so it may sit + * waiting on an OS pairing prompt. + */ + private void authenticateArm(String address, String arm) throws InterruptedException { int authMagic = allocMagic(); byte[] authAck = writeAndAwaitAck( address, @@ -195,10 +255,14 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { ConnectionOptions.SECURITY_AUTH_TIMEOUT_MS); if (authAck == null || !BleProtocol.isAuthenticationSuccess(authAck, authMagic)) { throw new IllegalStateException( - "could not authenticate with the glasses (" + address + "could not authenticate with the " + arm + " arm (" + address + ") — if Android shows a Bluetooth pairing request, accept it and try again"); } - // 2. Mandatory session prelude on sid=0x01 (app-launch). + emitLog("security auth complete: " + arm + " arm"); + } + + /** Mandatory session prelude on sid=0x01 (app-launch). Right arm only; it relays. */ + private void sendPrelude(String address) throws InterruptedException { if (writeAndAwaitAck( address, BleProtocol.PRELUDE_ACK_SID, @@ -208,10 +272,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { ConnectionOptions.PRELUDE_TIMEOUT_MS) == null) { throw new IllegalStateException("session prelude not acked: " + address); } - // 3. Create the prompt page (warning text + No/Yes list) on sid=0xe0 Cmd=0. - // Two attempts: on 2.2.9 the first request sent right after the - // prelude can be dropped while the lens emits its own sid-0x80 - // notifications (observed with the device-info settings read). + } + + private void showPrompt(String address) throws InterruptedException { + // Create the prompt page (warning text + No/Yes list) on sid=0xe0 Cmd=0. + // Two attempts: on 2.2.9 the first request sent right after the + // prelude can be dropped while the lens emits its own sid-0x80 + // notifications (observed with the device-info settings read). byte[] pageAck = null; for (int attempt = 0; attempt < 2 && pageAck == null && !cancelled; attempt++) { int magic = allocMagic(); @@ -228,6 +295,42 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { emitLog("prompt page shown on " + address); } + /** + * Read each arm's battery via a sid-0x09 settings read on that arm's own + * link (the arms have independent batteries and each answers with its + * own). An arm that does not answer reports -1; the caller decides what + * to do with a partial reading. + */ + private void readBatteries() throws InterruptedException { + int right = rightConnected ? readBattery(rightAddress, "right") : -1; + int left = leftConnected ? readBattery(leftAddress, "left") : -1; + emitLog("battery R=" + (right < 0 ? "?" : right + "%") + " L=" + (left < 0 ? "?" : left + "%")); + emitBattery(right, left); + } + + private int readBattery(String address, String arm) throws InterruptedException { + for (int attempt = 0; attempt < 2 && !cancelled; attempt++) { + int magic = allocMagic(); + byte[] ack = writeAndAwaitAck( + address, + BleProtocol.SID_UI_SETTING, + BleProtocol.FLAG_REQUEST, + magic, + BleProtocol.buildSettingsQuery(magic), + BATTERY_ACK_TIMEOUT_MS); + if (ack == null) { + emitLog("battery read attempt " + (attempt + 1) + " unacked: " + arm + " arm"); + continue; + } + BleProtocol.BatterySnapshot snapshot = BleProtocol.parseSettingsBattery(ack); + if (snapshot != null) { + return snapshot.battery; + } + emitLog("battery read ack had no battery field: " + arm + " arm"); + } + return -1; + } + /** Write and wait for the matching ack; returns the ack's protobuf (may be empty), or null on timeout/write failure. */ private byte[] writeAndAwaitAck(String address, int sid, int flag, int magic, byte[] payload, int timeoutMs) throws InterruptedException { @@ -312,6 +415,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } catch (Exception ignored) { } rightConnected = false; + leftConnected = false; } @Override @@ -371,6 +475,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { if (connected) { return; } + if (address.equalsIgnoreCase(leftAddress)) { + // The prompt itself only needs the right arm; a dropped left link + // just means no left battery reading. + leftConnected = false; + emitLog("left arm disconnected"); + return; + } if (address.equalsIgnoreCase(rightAddress)) { rightConnected = false; synchronized (lock) { @@ -415,6 +526,15 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { }); } + private void emitBattery(int rightPercent, int leftPercent) { + mainHandler.post(() -> { + FaceclawFlashPromptListener current = listener; + if (current != null) { + current.onBattery(rightPercent, leftPercent); + } + }); + } + private void emitResult(boolean approvedResult) { mainHandler.post(() -> { FaceclawFlashPromptListener current = listener; diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java index 39a8e322..a7ac2da3 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java @@ -6,11 +6,18 @@ public interface FaceclawFlashPromptListener { /** * Lifecycle updates. `state` is one of: connecting, connected, prompting, - * result, cancelled, timeout, disconnected, error. `detail` carries the + * battery, result, cancelled, timeout, disconnected, error. `detail` carries the * "approved"/"declined" text for result, or an error/explanation message. */ void onState(String state, String detail); - /** Fires once the user picks a menu row: true = flash, false = cancel. */ + /** + * Battery percent of each arm, read after the user approved (or right + * after auth when the prompt is skipped); -1 when an arm didn't answer. + * Always fires before onResult(true). + */ + void onBattery(int rightPercent, int leftPercent); + + /** Fires once the user picks a menu row (or, with skipPrompt, once the battery is read): true = flash, false = cancel. */ void onResult(boolean approved); } diff --git a/CHANGELOG b/CHANGELOG index cb893c64..be8e0705 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,23 +1,20 @@ # Changelog -## 0.6.4 - Future +## 0.6.4 - 2026-09-02 * Context menus are centered and include window title * Long-press and short-then-long with a context menu open switches between context menus * Developer speed metrics include bytes/frame - -Compass app: -* Increase sample rate and minimum-change for the compass app -* Compass now handles the distincitn between true north and magnetic north +* The custom firmware uninstaller flashes 2.2.9.22, not 2.2.6.10 +* Compass app: Increase sample rate from 1/s to ~3/s +* Compass app: Handle the distinction between true north and magnetic north * EvenHub compass readings now include calibrated magnetic, declination and true headings - -Files app: -* Viewing image files gamma-corrects and dithers them - -Watch app: -* Ambient mode: the watch no longer blurs when idle -* Fix flicker on waking the watch -* Tapping the idle watch to wake it counts as a tap on the pad -* Remove a number of unfinished prototype features +* Files app: Viewing image files gamma-corrects and dithers them +* Watch app: Uses ambient mode so the watch no longer blurs when idle +* Watch app: Fix flicker on waking the watch +* Watch app: Tapping the idle watch to wake it counts as a tap on the pad +* Watch app: Remove a number of unfinished prototype features +* Firmware flasher checks for glasses battery>30% before starting +* Fix a problem in 0.6.3 where it would abort before starting a custom firmware install with a checksum error ## 0.6.3 - 2026-09-01 * Update custom firmware base version from 2.2.6 to 2.2.9 diff --git a/app/apps/evenhub/even-api.ts b/app/apps/evenhub/even-api.ts index ea8a5ba6..00655752 100644 --- a/app/apps/evenhub/even-api.ts +++ b/app/apps/evenhub/even-api.ts @@ -254,8 +254,15 @@ function buildCommon(version: 1 | 3): string { const fields: Record = { platform: "16", package: "com.even.sg", - versionName: "2.2.6", - build: "114", + // versionName/build must be a real shipped pair of the official Android + // app (versionName/versionCode from its manifest): 2.2.8 = versionCode 122 + // (captures/even-2.2.8-base.apk). Earlier this said 2.2.6 with build 114, + // but 114 was actually 2.2.4's versionCode (see notes/firmware-download.md). + // buildTime is not a literal in the app binary (computed at runtime), so + // it still carries the value from the 2.2.4 capture; the API has accepted + // the mismatch so far. + versionName: "2.2.8", + build: "122", brand: "Google", model: "Pixel 7a", osVersion: "16", diff --git a/app/g2/firmware-builder.ts b/app/g2/firmware-builder.ts index 4d2c4f3a..cd728af0 100644 --- a/app/g2/firmware-builder.ts +++ b/app/g2/firmware-builder.ts @@ -1,6 +1,7 @@ /** * Builds the Faceclaw custom firmware on-device: downloads the stock Even - * Realities G2 2.2.6.10 image from Even's CDN, verifies its SHA-256, applies + * Realities G2 image the patch set was built against (CFW_PATCH_SET.base, + * currently 2.2.9.22) from Even's CDN, verifies its SHA-256, applies * the committed byte-patch set (cfw-patches.ts), extracts the stock EvenHub * fonts for phone-side rendering, verifies the patched SHA-256, and writes the * result to app storage. @@ -24,9 +25,15 @@ import { EvenHubFont } from "../graphics/evenhub-font"; declare const com: any; -const FIRMWARE_URL = "https://cdn.evenreal.co/firmware/e28738432d7b612d625331b00383149b.bin"; -const CFW_OUTPUT_FILENAME = "g2_2.2.6.10_cfw.bin"; -const STOCK_OUTPUT_FILENAME = "g2_2.2.6.10.bin"; +// The CDN names firmware files by MD5. This must be the image whose SHA-256 is +// CFW_PATCH_SET.baseSha256 — keep it in sync with FW_URL in g2flash/build_cfw.sh +// whenever cfw-patches.ts is regenerated against a new stock base. +// (2.2.9.22 = fc250b05…; the older 2.2.6.10 base was e2873843….) +const FIRMWARE_URL = "https://cdn.evenreal.co/firmware/fc250b05e98a9ff998b4b68f5f99f994.bin"; +// Output names follow the patch set's base name (e.g. g2_2.2.9.22.bin → +// g2_2.2.9.22_cfw.bin) so a rebase can't leave stale version numbers here. +const STOCK_OUTPUT_FILENAME = CFW_PATCH_SET.base; +const CFW_OUTPUT_FILENAME = CFW_PATCH_SET.base.replace(/\.bin$/, "") + "_cfw.bin"; export type FirmwareProgress = | { phase: "downloading" } diff --git a/app/g2/firmware-fonts.ts b/app/g2/firmware-fonts.ts index 5da89d1d..58df3769 100644 --- a/app/g2/firmware-fonts.ts +++ b/app/g2/firmware-fonts.ts @@ -21,10 +21,16 @@ type FontSpec = { }; // Priority order is the stock EvenHub fallback chain (before the CJK font). +// These are lv_font_fmt_txt_dsc_t addresses in the stock image the patch set +// is built against (CFW_PATCH_SET.base), so they move on every firmware +// rebase: run scripts/find-firmware-fonts.py against the new stock .bin and +// match rows by cmap count / code-point count (12/8081, 9/9566, 4/11590). +// 2.2.9.22: 0x007a8954, 0x007a8968, 0x007a8878 +// 2.2.6.10: 0x0077f414, 0x0077f428, 0x0077f374 const FONT_SPECS: FontSpec[] = [ - { descriptor: 0x0077f414, lineHeight: 27, baseLine: 5 }, - { descriptor: 0x0077f428, lineHeight: 26, baseLine: 5 }, - { descriptor: 0x0077f374, lineHeight: 20, baseLine: 2 }, + { descriptor: 0x007a8954, lineHeight: 27, baseLine: 5 }, + { descriptor: 0x007a8968, lineHeight: 26, baseLine: 5 }, + { descriptor: 0x007a8878, lineHeight: 20, baseLine: 2 }, ]; type ExtractedGlyph = { diff --git a/app/native/flash-prompt-communicator.ts b/app/native/flash-prompt-communicator.ts index a31cb420..547cd4c5 100644 --- a/app/native/flash-prompt-communicator.ts +++ b/app/native/flash-prompt-communicator.ts @@ -6,20 +6,32 @@ export type FlashPromptState = | "connecting" | "connected" | "prompting" + | "battery" | "result" | "cancelled" | "timeout" | "disconnected" | "error"; +/** Per-arm battery percent; null when that arm didn't answer. */ +export type FlashPromptBattery = { right: number | null; left: number | null }; + +function normalizePercent(value: number): number | null { + const n = Number(value); + return Number.isFinite(n) && n >= 0 ? n : null; +} + /** * TS wrapper around the native FaceclawFlashPromptCommunicator — the * stock-firmware-compatible BLE path that shows the pre-flash confirmation on * the glasses and reports the user's Yes/No choice. Separate from * FaceclawCommunicatorBridge on purpose (different, minimal protocol subset). * - * Talks to the right arm only: the lenses relay messages between themselves, - * and acks/events always come from the right arm. + * Connects and authenticates both arms (so any OS pairing prompts happen up + * front, before flashing), shows the prompt via the right arm (the lenses relay + * messages between themselves, and acks/events always come from the right + * arm), then reads each arm's battery. With `skipPrompt` the on-glasses + * confirmation is omitted and only the battery is read. */ export class FlashPromptCommunicator { private readonly communicator: any; @@ -27,20 +39,32 @@ export class FlashPromptCommunicator { private readonly logListeners = new Set<(line: string) => void>(); private readonly stateListeners = new Set<(state: FlashPromptState, detail: string) => void>(); private readonly resultListeners = new Set<(approved: boolean) => void>(); + private readonly batteryListeners = new Set<(battery: FlashPromptBattery) => void>(); - constructor(rightAddress: string, warningText: string) { + constructor( + addresses: { right: string; left: string }, + warningText: string, + options?: { skipPrompt?: boolean }, + ) { const context = Utils.android.getApplicationContext(); if (!context) throw new Error("Android application context unavailable"); this.communicator = new com.faceclaw.app.FaceclawFlashPromptCommunicator( context, - rightAddress, + addresses.right, + addresses.left, warningText, + Boolean(options?.skipPrompt), ); this.listenerProxy = new com.faceclaw.app.FaceclawFlashPromptListener({ onLog: (line: string) => this.emit(this.logListeners, String(line)), onState: (state: string, detail: string) => this.emit(this.stateListeners, String(state) as FlashPromptState, String(detail ?? "")), + onBattery: (rightPercent: number, leftPercent: number) => + this.emit(this.batteryListeners, { + right: normalizePercent(rightPercent), + left: normalizePercent(leftPercent), + }), onResult: (approved: boolean) => this.emit(this.resultListeners, Boolean(approved)), }); this.communicator.setListener(this.listenerProxy); @@ -56,6 +80,11 @@ export class FlashPromptCommunicator { return () => this.stateListeners.delete(listener); } + onBattery(listener: (battery: FlashPromptBattery) => void): () => void { + this.batteryListeners.add(listener); + return () => this.batteryListeners.delete(listener); + } + onResult(listener: (approved: boolean) => void): () => void { this.resultListeners.add(listener); return () => this.resultListeners.delete(listener); diff --git a/app/phone-ui/onboarding-flash-view-model.ts b/app/phone-ui/onboarding-flash-view-model.ts index 7d29bdf1..2ce56ca2 100644 --- a/app/phone-ui/onboarding-flash-view-model.ts +++ b/app/phone-ui/onboarding-flash-view-model.ts @@ -14,7 +14,11 @@ import { } from "../g2/firmware-builder"; import { buildAddressSet, DeviceDiscoveryBridge } from "../native/device-discovery"; import { FirmwareFlasher, FlashProgress, FlashState } from "../native/firmware-flasher"; -import { FlashPromptCommunicator, FlashPromptState } from "../native/flash-prompt-communicator"; +import { + FlashPromptBattery, + FlashPromptCommunicator, + FlashPromptState, +} from "../native/flash-prompt-communicator"; import { resumeAutoReconnect, suppressAutoReconnect } from "../g2/reconnect-policy"; import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state"; import { formatErrorMessage } from "../util/format-error"; @@ -23,6 +27,10 @@ type FlashPhase = "intro" | "prompt" | "building" | "ready" | "flashing" | "flas export type FlashMode = "install" | "uninstall"; +// Flashing a lens takes minutes and the glasses reboot afterwards; refuse to +// start when either arm is below this so a flat battery can't interrupt it. +const MIN_FLASH_BATTERY_PERCENT = 30; + export class OnboardingFlashViewModel extends Observable { private readonly mode: FlashMode; private readonly fromOnboarding: boolean; @@ -40,6 +48,7 @@ export class OnboardingFlashViewModel extends Observable { private prompt: FlashPromptCommunicator | null = null; private promptUnsubscribers: Array<() => void> = []; + private promptBattery: FlashPromptBattery | null = null; private flasher: FirmwareFlasher | null = null; private flasherUnsubscribers: Array<() => void> = []; private retryAction: () => void = () => this.beginPrompt(); @@ -55,10 +64,10 @@ export class OnboardingFlashViewModel extends Observable { this._headline = this.mode === "uninstall" ? "Uninstall Custom Firmware" : "Flash Custom Firmware"; this._status = this.mode === "uninstall" - ? "This connects to your glasses, asks for confirmation on the lens, then downloads and reflashes the " + - "official firmware — removing Faceclaw's custom features." - : "This connects to your glasses, asks for confirmation on the lens, then downloads, verifies, and flashes " + - "Faceclaw's custom firmware."; + ? "This connects to your glasses, asks for confirmation on the lens, checks the battery, then downloads " + + "and reflashes the official firmware — removing Faceclaw's custom features." + : "This connects to your glasses, asks for confirmation on the lens, checks the battery, then downloads, " + + "verifies, and flashes Faceclaw's custom firmware."; } // Kept short to fit the glasses' ~50-column text grid. @@ -219,15 +228,24 @@ export class OnboardingFlashViewModel extends Observable { // --- prompt flow ----------------------------------------------------------- - private async beginPrompt(): Promise { + /** + * Connect to both arms, authenticate (this is where any Android pairing + * prompts appear), show the Yes/No confirmation on the lens, then read the + * battery. With `skipPrompt` (retrying after a low-battery refusal, when + * the user has already confirmed) the on-glasses confirmation is skipped + * and only the battery is re-checked. + */ + private async beginPrompt(options?: { skipPrompt?: boolean }): Promise { + const skipPrompt = Boolean(options?.skipPrompt); if (!global.isAndroid) { - this.toError("Flashing is only available on Android.", () => this.beginPrompt()); + this.toError("Flashing is only available on Android.", () => this.beginPrompt(options)); return; } this.setPhase("prompt"); - this.headline = "Confirm On Your Glasses"; + this.headline = skipPrompt ? "Checking Battery" : "Confirm On Your Glasses"; this.log = ""; this.busy = true; + this.promptBattery = null; this.status = "Preparing to connect. Make sure your glasses are on and the Even app is disconnected."; try { @@ -237,40 +255,50 @@ export class OnboardingFlashViewModel extends Observable { this.busy = false; this.toError( "Couldn't find both glasses arms. Make sure the glasses are powered on and the Even app is disconnected, then retry.", - () => this.beginPrompt(), + () => this.beginPrompt(options), ); return; } this.addresses = addresses; - this.status = "Connecting to your glasses. Watch the lens for a Yes/No prompt."; - this.startCommunicator(addresses); + this.status = skipPrompt + ? "Connecting to your glasses to re-check the battery..." + : "Connecting to your glasses. Watch the lens for a Yes/No prompt."; + this.startCommunicator(addresses, skipPrompt); } catch (error) { this.busy = false; - this.toError(this.formatError(error), () => this.beginPrompt()); + this.toError(this.formatError(error), () => this.beginPrompt(options)); } } - private startCommunicator(addresses: { right: string; left: string }): void { + private startCommunicator(addresses: { right: string; left: string }, skipPrompt: boolean): void { this.disposePrompt(); - const prompt = new FlashPromptCommunicator(addresses.right, this.glassesWarning); + const prompt = new FlashPromptCommunicator(addresses, this.glassesWarning, { skipPrompt }); this.prompt = prompt; this.promptUnsubscribers.push( prompt.onLog((line) => this.appendLog(line)), - prompt.onStateChange((state, detail) => this.handlePromptState(state, detail)), - prompt.onResult((approved) => this.handlePromptResult(approved)), + prompt.onStateChange((state, detail) => this.handlePromptState(state, detail, skipPrompt)), + prompt.onBattery((battery) => { + this.promptBattery = battery; + }), + prompt.onResult((approved) => this.handlePromptResult(approved, skipPrompt)), ); prompt.start(); } - private handlePromptState(state: FlashPromptState, detail: string): void { + private handlePromptState(state: FlashPromptState, detail: string, skipPrompt: boolean): void { switch (state) { case "connecting": this.status = "Connecting to your glasses..."; break; case "connected": - this.status = "Connected. Showing the confirmation on the lens..."; + this.status = + "Connected. Pairing with both lenses — if Android asks to pair, accept it (once per lens)." + + (skipPrompt ? "" : " Then watch the lens for the confirmation."); + break; + case "battery": + this.status = "Checking the glasses' battery level..."; break; case "prompting": this.status = @@ -289,25 +317,57 @@ export class OnboardingFlashViewModel extends Observable { break; case "disconnected": this.busy = false; - this.toError(detail || "Lost connection to the glasses.", () => this.beginPrompt()); + this.toError(detail || "Lost connection to the glasses.", () => this.beginPrompt({ skipPrompt })); break; case "error": this.busy = false; - this.toError(detail || "Connection failed.", () => this.beginPrompt()); + this.toError(detail || "Connection failed.", () => this.beginPrompt({ skipPrompt })); break; } } - private handlePromptResult(approved: boolean): void { + private handlePromptResult(approved: boolean, skipPrompt: boolean): void { this.disposePrompt(); if (!approved) { this.busy = false; this.toError("You declined on the glasses. No firmware was written.", () => this.beginPrompt()); return; } + const lowBattery = this.describeLowBattery(this.promptBattery); + if (lowBattery) { + this.busy = false; + // The user already confirmed on the lens; a retry only re-checks the battery. + this.toError(lowBattery, () => this.beginPrompt({ skipPrompt: true }), "Charge Your Glasses"); + return; + } + if (!this.promptBattery || (this.promptBattery.right === null && this.promptBattery.left === null)) { + this.appendLog("battery level unknown; proceeding"); + } + this.appendLog(skipPrompt ? "battery ok; confirmed earlier on the lens" : "confirmed on the lens; battery ok"); void this.buildFirmware(); } + /** A "charge first" message when either arm is below the flashing threshold, else null. */ + private describeLowBattery(battery: FlashPromptBattery | null): string | null { + if (!battery) { + return null; + } + const readings = [ + { arm: "right", percent: battery.right }, + { arm: "left", percent: battery.left }, + ].filter((r): r is { arm: string; percent: number } => r.percent !== null); + const low = readings.filter((r) => r.percent < MIN_FLASH_BATTERY_PERCENT); + if (low.length === 0) { + return null; + } + const levels = readings.map((r) => `${r.arm} ${r.percent}%`).join(", "); + return ( + `The glasses' battery is too low to flash safely (${levels}). ` + + `Charge both lenses to at least ${MIN_FLASH_BATTERY_PERCENT}%, then tap Retry to check again. ` + + "You won't need to confirm on the lens a second time." + ); + } + private cancelPrompt(): void { this.status = "Cancelling..."; try { @@ -502,11 +562,11 @@ export class OnboardingFlashViewModel extends Observable { }); } - private toError(message: string, retry: () => void): void { + private toError(message: string, retry: () => void, headline = "Something Went Wrong"): void { this.retryAction = retry; this.status = message; this.setPhase("error"); - this.headline = "Something Went Wrong"; + this.headline = headline; } private setPhase(phase: FlashPhase): void {