diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbe.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbe.java new file mode 100644 index 00000000..f89fa8b0 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbe.java @@ -0,0 +1,242 @@ +package com.faceclaw.app; + +import android.bluetooth.BluetoothGatt; +import android.content.Context; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Connects to the glasses (stock-firmware compatible), reads the device-info / + * settings response, and reports the firmware versions plus the CFW capability + * string (empty on stock firmware). Used by onboarding to decide whether to + * flash. Reuses FaceclawBleManager + BleProtocol; owns its own connection and + * runs on a single worker thread. Shows nothing on the lens. + */ +public class FaceclawDeviceInfoProbe implements FaceclawBleListener { + private static final String TAG = "FaceclawDeviceInfo"; + private static final int QUERY_TIMEOUT_MS = 4_000; + + private final Context context; + private final String rightAddress; + private final FaceclawBleManager bleManager; + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + + private final Object lock = new Object(); + private int nextSeq = 0x40; + private int nextMagic = 100; + + private int awaitSid = -1; + private int awaitMagic = -1; + private byte[] awaitPb = null; + private CountDownLatch awaitLatch = null; + + private volatile FaceclawDeviceInfoProbeListener listener; + private volatile Thread worker; + private volatile boolean cancelled = false; + + public FaceclawDeviceInfoProbe(Context context, String rightAddress) { + this.context = context.getApplicationContext(); + this.rightAddress = rightAddress == null ? "" : rightAddress; + this.bleManager = new FaceclawBleManager(this.context); + this.bleManager.setListener(this); + } + + public void setListener(FaceclawDeviceInfoProbeListener listener) { + this.listener = listener; + } + + public void start() { + synchronized (lock) { + if (worker != null) { + return; + } + worker = new Thread(this::run, "faceclaw-device-info"); + worker.start(); + } + } + + public void cancel() { + cancelled = true; + Thread w = worker; + if (w != null) { + w.interrupt(); + } + } + + public void close() { + cancel(); + try { + bleManager.close(); + } catch (Exception ignored) { + } + } + + private void run() { + try { + if (rightAddress.trim().isEmpty()) { + emitError("No right-arm address configured."); + return; + } + + emitState("connecting", ""); + connectArm(rightAddress); + if (cancelled) { + emitError("Cancelled."); + return; + } + + emitState("querying", ""); + // Session prelude, then a settings/device-info read (both arms' + // versions and the CFW capability string ride back in one response). + if (writeAndAwaitAck(rightAddress, BleProtocol.PRELUDE_ACK_SID, BleProtocol.FLAG_REQUEST, + BleProtocol.PRELUDE_ACK_MAGIC, BleProtocol.PRELUDE_F5872_PAYLOAD, + ConnectionOptions.PRELUDE_TIMEOUT_MS) == null) { + throw new IllegalStateException("session prelude not acked"); + } + + int magic = allocMagic(); + byte[] ack = writeAndAwaitAck(rightAddress, BleProtocol.SID_UI_SETTING, BleProtocol.FLAG_REQUEST, + magic, BleProtocol.buildSettingsQuery(magic), QUERY_TIMEOUT_MS); + if (ack == null) { + throw new IllegalStateException("no response to the device-info query"); + } + + BleProtocol.FirmwareInfo info = BleProtocol.parseSettingsFirmwareInfo(ack); + String left = info == null ? "" : info.leftVersion; + String right = info == null ? "" : info.rightVersion; + String caps = info == null ? "" : info.capabilities; + emitLog("device-info: L=" + left + " R=" + right + " caps=[" + caps + "]"); + emitResult(left, right, caps); + } catch (Exception e) { + String message = cancelled ? "Cancelled." : (e.getMessage() == null ? e.toString() : e.getMessage()); + emitError(message); + } finally { + try { + bleManager.close(); + } catch (Exception ignored) { + } + } + } + + private void connectArm(String address) { + if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { + throw new IllegalStateException("connect failed"); + } + 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("service discovery failed"); + } + if (!bleManager.enableNotifications(address, BleProtocol.NOTIFY_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) { + throw new IllegalStateException("could not subscribe to notifications"); + } + } + + private byte[] writeAndAwaitAck(String address, int sid, int flag, int magic, byte[] payload, int timeoutMs) + throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + synchronized (lock) { + awaitSid = sid; + awaitMagic = magic; + awaitPb = null; + awaitLatch = latch; + } + int seq; + synchronized (lock) { + seq = nextSeq++ & 0xff; + } + List frames = BleProtocol.framePb(payload, sid, flag, seq); + boolean written = bleManager.writeFrames( + address, BleProtocol.WRITE_CHAR_UUID, frames, ConnectionOptions.WRITE_TYPE, ConnectionOptions.WRITE_TIMEOUT_MS); + if (!written) { + synchronized (lock) { + awaitLatch = null; + } + return null; + } + boolean acked = latch.await(timeoutMs, TimeUnit.MILLISECONDS); + synchronized (lock) { + awaitLatch = null; + return acked ? awaitPb : null; + } + } + + @Override + public void onNotification(String address, String characteristicUuid, byte[] data) { + if (!BleProtocol.NOTIFY_CHAR_UUID.equalsIgnoreCase(characteristicUuid)) { + return; + } + BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data); + if (!frame.ok) { + return; + } + if (frame.flag == BleProtocol.FLAG_NOTIFY || frame.flag == BleProtocol.FLAG_NOTIFY_ALT) { + return; // async event, not an ack + } + synchronized (lock) { + if (awaitLatch != null && frame.sid == awaitSid && frame.msgSeq == awaitMagic) { + awaitPb = frame.pb; + awaitLatch.countDown(); + } + } + } + + @Override + public void onConnectionStateChange(String address, boolean connected) { + if (!connected) { + Log.i(TAG, "disconnected: " + address); + } + } + + private int allocMagic() { + synchronized (lock) { + int magic = nextMagic; + nextMagic = nextMagic >= 255 ? 100 : nextMagic + 1; + return magic; + } + } + + private void emitLog(String line) { + Log.i(TAG, line); + mainHandler.post(() -> { + FaceclawDeviceInfoProbeListener current = listener; + if (current != null) { + current.onLog(line); + } + }); + } + + private void emitState(String state, String detail) { + final String safeDetail = detail == null ? "" : detail; + mainHandler.post(() -> { + FaceclawDeviceInfoProbeListener current = listener; + if (current != null) { + current.onState(state, safeDetail); + } + }); + } + + private void emitResult(String left, String right, String caps) { + mainHandler.post(() -> { + FaceclawDeviceInfoProbeListener current = listener; + if (current != null) { + current.onResult(left, right, caps); + } + }); + } + + private void emitError(String message) { + final String safeMessage = message == null ? "" : message; + mainHandler.post(() -> { + FaceclawDeviceInfoProbeListener current = listener; + if (current != null) { + current.onError(safeMessage); + } + }); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbeListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbeListener.java new file mode 100644 index 00000000..0288df31 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbeListener.java @@ -0,0 +1,15 @@ +package com.faceclaw.app; + +/** Callbacks from FaceclawDeviceInfoProbe to the TypeScript layer. */ +public interface FaceclawDeviceInfoProbeListener { + void onLog(String line); + + /** Lifecycle: connecting, querying. */ + void onState(String state, String detail); + + /** Terminal success: firmware versions and the CFW capability string (may be empty). */ + void onResult(String leftVersion, String rightVersion, String capabilities); + + /** Terminal failure (couldn't connect or read the version). */ + void onError(String message); +} diff --git a/README b/README index 085bc734..efe3bcb3 100644 --- a/README +++ b/README @@ -4,10 +4,10 @@ This is an unofficial user interface for the Even Realities G2 smart glasses. It is entirely unofficial, and comes with no support or warranty from Even Realities or from anyone. -To use it, you uninstall or unpair the official Even Realities app, then -install the custom firmware from from https://github.com/jimrandomh/g2flash, -then install this app on the same phone. Faceclaw is not compatible with the -stock firmware due to limitations in how the stock firmware handles images. +This app runs on Android, and requires installing custom firmware on the +glasses. The Android app itself can install and uninstall the custom firmware; +it downloads the stock firmware from Even and applies patches generated from +https://github.com/jimrandomh/g2flash. THIS IS AN UNFINISHED DEVELOPMENT PROTOTYPE; IF YOU DON'T HAVE ANY PROGRAMMING EXPERIENCE, OR YOU AREN'T COMFORTABLE EDITING, COMPILING, AND SIDELOADING AN diff --git a/app/g2/firmware-builder.ts b/app/g2/firmware-builder.ts index adc1d501..337aa636 100644 --- a/app/g2/firmware-builder.ts +++ b/app/g2/firmware-builder.ts @@ -16,7 +16,8 @@ import { CFW_PATCH_SET, FirmwarePatchOp } from "./firmware/cfw-patches"; declare const com: any; const FIRMWARE_URL = "https://cdn.evenreal.co/firmware/a6966d807634cc97aec641a0dcca358b.bin"; -const OUTPUT_FILENAME = "g2_2.2.4.34_cfw.bin"; +const CFW_OUTPUT_FILENAME = "g2_2.2.4.34_cfw.bin"; +const STOCK_OUTPUT_FILENAME = "g2_2.2.4.34.bin"; export type FirmwareProgress = | { phase: "downloading" } @@ -50,16 +51,7 @@ export async function buildCustomFirmware( } }; - report({ phase: "downloading" }); - const base = await downloadFirmware(); - - report({ phase: "verifying-base" }); - const baseSha = sha256Hex(base); - if (baseSha !== CFW_PATCH_SET.baseSha256) { - throw new FirmwareBuildError( - `Downloaded stock firmware failed verification.\nexpected ${CFW_PATCH_SET.baseSha256}\ngot ${baseSha}`, - ); - } + const base = await downloadAndVerifyBase(report); const patched = applyPatches(new Uint8Array(base), CFW_PATCH_SET.patches, (applied, total) => report({ phase: "patching", applied, total }), @@ -75,13 +67,53 @@ export async function buildCustomFirmware( } report({ phase: "writing" }); - const path = `${knownFolders.documents().path}/${OUTPUT_FILENAME}`; + const path = `${knownFolders.documents().path}/${CFW_OUTPUT_FILENAME}`; writeFile(path, outBuffer); report({ phase: "done", path, bytes: patched.length }); return { path, bytes: patched.length, sha256: outSha }; } +/** + * Download and verify the unmodified stock firmware (no patches applied) and + * persist it. Used to un-install the custom firmware by reflashing the original + * image the CFW was built from. + */ +export async function buildStockFirmware( + onProgress?: (progress: FirmwareProgress) => void, +): Promise { + const report = (progress: FirmwareProgress) => { + try { + onProgress?.(progress); + } catch { + // progress reporting must never break the build + } + }; + + const base = await downloadAndVerifyBase(report); + + report({ phase: "writing" }); + const path = `${knownFolders.documents().path}/${STOCK_OUTPUT_FILENAME}`; + writeFile(path, base); + + report({ phase: "done", path, bytes: base.byteLength }); + return { path, bytes: base.byteLength, sha256: CFW_PATCH_SET.baseSha256 }; +} + +async function downloadAndVerifyBase(report: (progress: FirmwareProgress) => void): Promise { + report({ phase: "downloading" }); + const base = await downloadFirmware(); + + report({ phase: "verifying-base" }); + const baseSha = sha256Hex(base); + if (baseSha !== CFW_PATCH_SET.baseSha256) { + throw new FirmwareBuildError( + `Downloaded stock firmware failed verification.\nexpected ${CFW_PATCH_SET.baseSha256}\ngot ${baseSha}`, + ); + } + return base; +} + async function downloadFirmware(): Promise { let response: Response; try { diff --git a/app/g2/firmware-compat.ts b/app/g2/firmware-compat.ts index 9ff24130..72e75b21 100644 --- a/app/g2/firmware-compat.ts +++ b/app/g2/firmware-compat.ts @@ -10,6 +10,12 @@ import { type FirmwareInfo } from "../native/faceclaw-communicator"; const MIN_FIRMWARE_VERSION = [2, 2, 4, 34]; const REQUIRED_FIRMWARE_EXTENSION = "imgz"; +// The stock firmware release Faceclaw's custom image is built from. Stock at or +// below this can be flashed with our patched image; a newer stock version is +// unrecognized (its layout may differ from what our patch set targets). +export const FLASHABLE_STOCK_VERSION = [2, 2, 4, 34]; +export const FLASHABLE_STOCK_VERSION_TEXT = FLASHABLE_STOCK_VERSION.join("."); + function parseDottedVersion(version: string): number[] { return version .trim() @@ -60,3 +66,41 @@ export function firmwareIncompatibilityMessage(info: FirmwareInfo): string | nul return null; } + +/** True when the glasses advertise Faceclaw's custom-firmware image extension. */ +export function hasCustomFirmware(info: FirmwareInfo): boolean { + return info.capabilities.trim().split(/\s+/).includes(REQUIRED_FIRMWARE_EXTENSION); +} + +/** The higher of the two arms' reported versions, or "" if none reported. */ +export function reportedFirmwareVersion(info: FirmwareInfo): string { + const versions = [info.leftVersion, info.rightVersion].map((v) => v.trim()).filter(Boolean); + if (versions.length === 0) return ""; + return versions.reduce((highest, current) => + compareVersions(parseDottedVersion(current), parseDottedVersion(highest)) > 0 ? current : highest, + ); +} + +/** + * How the pre-flash firmware check should treat the connected glasses: + * - "custom": Faceclaw's firmware is already installed — nothing to flash. + * - "flashable-stock": stock firmware at or below the version we build from. + * - "newer-stock": stock firmware newer than we recognize — flash only on override. + * - "unknown": no version could be read (treated as a probe/connection failure). + */ +export type OnboardingFirmwareKind = "custom" | "flashable-stock" | "newer-stock" | "unknown"; + +export function classifyOnboardingFirmware(info: FirmwareInfo): { + kind: OnboardingFirmwareKind; + version: string; +} { + if (hasCustomFirmware(info)) { + return { kind: "custom", version: reportedFirmwareVersion(info) }; + } + const version = reportedFirmwareVersion(info); + if (!version) { + return { kind: "unknown", version: "" }; + } + const comparison = compareVersions(parseDottedVersion(version), FLASHABLE_STOCK_VERSION); + return { kind: comparison <= 0 ? "flashable-stock" : "newer-stock", version }; +} diff --git a/app/native/device-info-probe.ts b/app/native/device-info-probe.ts new file mode 100644 index 00000000..0e892fca --- /dev/null +++ b/app/native/device-info-probe.ts @@ -0,0 +1,101 @@ +import { Utils } from "@nativescript/core"; + +declare const com: any; + +export type DeviceInfo = { + leftVersion: string; + rightVersion: string; + capabilities: string; +}; + +export type DeviceInfoState = "connecting" | "querying"; + +/** + * TS wrapper around the native FaceclawDeviceInfoProbe — a one-shot, + * stock-compatible connect + firmware/device-info read. `run()` resolves with + * the firmware versions and CFW capability string, or rejects on failure. + */ +export class DeviceInfoProbe { + private readonly probe: any; + private readonly listenerProxy: any; + private readonly logListeners = new Set<(line: string) => void>(); + private readonly stateListeners = new Set<(state: DeviceInfoState, detail: string) => void>(); + + private settled = false; + private resolveFn: ((info: DeviceInfo) => void) | null = null; + private rejectFn: ((error: Error) => void) | null = null; + + constructor(rightAddress: string) { + const context = Utils.android.getApplicationContext(); + if (!context) throw new Error("Android application context unavailable"); + + this.probe = new com.faceclaw.app.FaceclawDeviceInfoProbe(context, rightAddress); + this.listenerProxy = new com.faceclaw.app.FaceclawDeviceInfoProbeListener({ + onLog: (line: string) => this.emit(this.logListeners, String(line)), + onState: (state: string, detail: string) => + this.emit(this.stateListeners, String(state) as DeviceInfoState, String(detail ?? "")), + onResult: (leftVersion: string, rightVersion: string, capabilities: string) => + this.settle(null, { + leftVersion: String(leftVersion), + rightVersion: String(rightVersion), + capabilities: String(capabilities), + }), + onError: (message: string) => this.settle(new Error(String(message)), null), + }); + this.probe.setListener(this.listenerProxy); + } + + onLog(listener: (line: string) => void): () => void { + this.logListeners.add(listener); + return () => this.logListeners.delete(listener); + } + + onStateChange(listener: (state: DeviceInfoState, detail: string) => void): () => void { + this.stateListeners.add(listener); + return () => this.stateListeners.delete(listener); + } + + run(): Promise { + return new Promise((resolve, reject) => { + this.resolveFn = resolve; + this.rejectFn = reject; + this.probe.start(); + }); + } + + cancel(): void { + try { + this.probe.cancel(); + } catch { + // ignore + } + } + + close(): void { + try { + this.probe.close(); + } catch { + // ignore + } + } + + private settle(error: Error | null, info: DeviceInfo | null): void { + if (this.settled) return; + this.settled = true; + this.close(); + if (error) { + this.rejectFn?.(error); + } else if (info) { + this.resolveFn?.(info); + } + } + + private emit(listeners: Set<(...args: A) => void>, ...args: A): void { + const snapshot = Array.from(listeners); + setTimeout(() => { + for (const listener of snapshot) { + listener(...args); + } + }, 0); + } +} diff --git a/app/phone-ui/config-page.ts b/app/phone-ui/config-page.ts index 3fdf928b..9b9e3edc 100644 --- a/app/phone-ui/config-page.ts +++ b/app/phone-ui/config-page.ts @@ -1,8 +1,13 @@ -import { EventData, Page } from "@nativescript/core"; +import { NavigatedData, Page } from "@nativescript/core"; import { ConfigViewModel } from "./config-view-model"; -export function navigatingTo(args: EventData): void { +export function navigatingTo(args: NavigatedData): void { const page = args.object as Page; - page.bindingContext = new ConfigViewModel(); + // Preserve the model across back-navigation (returning from the unpair page) + // so the onboarding "Continue" flow isn't lost. + if (!page.bindingContext) { + const context = (args.context as { onboarding?: boolean } | undefined) ?? undefined; + page.bindingContext = new ConfigViewModel({ onboarding: context?.onboarding ?? false }); + } } diff --git a/app/phone-ui/config-page.xml b/app/phone-ui/config-page.xml index f180828d..5048e69c 100644 --- a/app/phone-ui/config-page.xml +++ b/app/phone-ui/config-page.xml @@ -27,7 +27,7 @@