Add (NOT YET TESTED) firmware flashing/OTA-updating

We're going to extend the Faceclaw app onboarding process to include checking for and installing the custom firmware (currently handled externally with the scripts in ../g2flash). We'll add script scripts/resetOnboarding.sh that uses adb to reset the app on the attached phone to default/pre-onboarding state for testing. The onboarding process will explain that it's only compatible with custom firmware, with options to either skip and try out the app using only the phone-screen preview (instead of pairing with glasses), or proceed with flashing.
If the user proceeds with flashing, we first connect to the glasses (with the existing mechanism), and display an on-glasses confirmation prompt. Because this prompt needs compatibility with stock firmware, it will use a different subset of the BLE protocol than the main app does (in particular, no image containers), so we'll have a separate bluetooth communication class rather than extending FaceclawBleCommunicator. We'll send an init message to start a Hub app, initialize a layout with a text container and a list, populate the text container with a message saying that flashing will void warranty and the list with No and Yes, set up a keepalive/heartbeat message timer, and wait for a menu selection. (Refer to ../g2-kit-unofficial/ble/docs and ../g2-kit-unofficial/ble/gen for protocol details). If the prompt is approved, we go to the flashing screen.
On the flashing screen, we first download the official firmware, apply patches to it, and check that it has the expected result hash. See ../g2flash/build_cfw.sh and ../g2flash/apply_patches.py for details.
Let's implement everything prior to the update itself now, ie, the on-device confirmation prompt, and downloading, patching and verifying the modded firmware.
scripts/resetOnboarding.sh is meant to reset a pref so that Faceclaw reruns its first-run onboarding on next launch, but fails with "No onboarding keys were set. App is already in pre-onboarding state." (And onboarding doesn't trigger on next launch)
Thanks. I tested the on-glasses prompt on real hardware and it worked as expected. Next up, let's port the flashing procedure itself.
One detail of the flashing procedure worth noting: the two lenses get updated separately, and at the end of updating either lens, both lenses get rebooted, creating a brief period when neither is reachable, so the timeout to look for the second lens should not be too short.
This commit is contained in:
James Babcock committed 2026-07-10 12:07:15 -07:00
1 parent 2c04d99dfb
commit cb78841a9d
17 files changed
+2464 -10

No files matched your search

+199
View File
@@ -0,0 +1,199 @@
/**
* Builds the Faceclaw custom firmware on-device: downloads the stock Even
* Realities G2 2.2.4.34 image from Even's CDN, verifies its SHA-256, applies
* the committed byte-patch set (cfw-patches.ts), verifies the patched SHA-256,
* and writes the result to app storage.
*
* This mirrors g2flash/build_cfw.sh + patches/apply_patches.py exactly (same
* URL, same pinned hashes, same offset/old/new patch semantics), so a
* successful run reproduces the reviewed image byte-for-byte. It does NOT flash
* anything — producing and verifying the image is the whole job here.
*/
import { knownFolders } from "@nativescript/core";
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";
export type FirmwareProgress =
| { phase: "downloading" }
| { phase: "verifying-base" }
| { phase: "patching"; applied: number; total: number }
| { phase: "verifying-output" }
| { phase: "writing" }
| { phase: "done"; path: string; bytes: number };
export type BuiltFirmware = {
path: string;
bytes: number;
sha256: string;
};
export class FirmwareBuildError extends Error {}
/**
* Download → verify → patch → verify → persist. Rejects with a
* FirmwareBuildError carrying a human-readable message if any hash check or the
* download fails. `onProgress` is optional and purely for UI.
*/
export async function buildCustomFirmware(
onProgress?: (progress: FirmwareProgress) => void,
): Promise<BuiltFirmware> {
const report = (progress: FirmwareProgress) => {
try {
onProgress?.(progress);
} catch {
// progress reporting must never break the build
}
};
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 patched = applyPatches(new Uint8Array(base), CFW_PATCH_SET.patches, (applied, total) =>
report({ phase: "patching", applied, total }),
);
report({ phase: "verifying-output" });
const outBuffer = tightBuffer(patched);
const outSha = sha256Hex(outBuffer);
if (outSha !== CFW_PATCH_SET.outputSha256) {
throw new FirmwareBuildError(
`Patched firmware failed verification.\nexpected ${CFW_PATCH_SET.outputSha256}\ngot ${outSha}`,
);
}
report({ phase: "writing" });
const path = `${knownFolders.documents().path}/${OUTPUT_FILENAME}`;
writeFile(path, outBuffer);
report({ phase: "done", path, bytes: patched.length });
return { path, bytes: patched.length, sha256: outSha };
}
async function downloadFirmware(): Promise<ArrayBuffer> {
let response: Response;
try {
response = await fetch(FIRMWARE_URL);
} catch (error) {
throw new FirmwareBuildError(`Could not reach Even's firmware CDN: ${(error as Error)?.message ?? error}`);
}
if (!response.ok) {
throw new FirmwareBuildError(`Firmware download failed (HTTP ${response.status}).`);
}
return response.arrayBuffer();
}
/**
* Replay the committed patch set onto `base`, returning the patched bytes. Each
* op writes `new` at `offset` after checking the bytes there equal `old`; an op
* with empty `old` appends at end-of-file (offset must equal current length).
* Idempotent: an op whose target already equals `new` is skipped. Mirrors
* apply_patches.py:apply_ops.
*/
function applyPatches(
base: Uint8Array,
ops: FirmwarePatchOp[],
onStep?: (applied: number, total: number) => void,
): Uint8Array {
let buf = base;
for (let i = 0; i < ops.length; i++) {
const op = ops[i];
const oldBytes = hexToBytes(op.old ?? "");
const newBytes = hexToBytes(op.new);
const off = op.offset;
const tag = `patch #${i} @ 0x${off.toString(16)}${op.desc ? ` (${op.desc})` : ""}`;
if (oldBytes.length > 0) {
const cur = buf.subarray(off, off + oldBytes.length);
if (bytesEqual(cur, newBytes) && !bytesEqual(cur, oldBytes)) {
onStep?.(i + 1, ops.length);
continue; // already applied
}
if (!bytesEqual(cur, oldBytes)) {
throw new FirmwareBuildError(
`${tag}: unexpected bytes in stock image (found ${bytesToHex(cur)}, expected ${op.old}). ` +
`The downloaded image is not the stock base this patch set targets.`,
);
}
buf.set(newBytes, off);
} else {
const end = off + newBytes.length;
if (off <= buf.length && end <= buf.length && bytesEqual(buf.subarray(off, end), newBytes)) {
onStep?.(i + 1, ops.length);
continue; // already applied
}
if (off !== buf.length) {
throw new FirmwareBuildError(
`${tag}: append expects offset 0x${off.toString(16)} to equal current length 0x${buf.length.toString(16)}.`,
);
}
buf = concatBytes(buf, newBytes);
}
onStep?.(i + 1, ops.length);
}
return buf;
}
function hexToBytes(hex: string): Uint8Array {
if (hex.length % 2 !== 0) {
throw new FirmwareBuildError(`odd-length hex string: ${hex}`);
}
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function bytesToHex(bytes: Uint8Array): string {
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += bytes[i].toString(16).padStart(2, "0");
}
return hex;
}
function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
const out = new Uint8Array(a.length + b.length);
out.set(a, 0);
out.set(b, a.length);
return out;
}
/** Return an ArrayBuffer holding exactly `bytes`' contents (no shared slack). */
function tightBuffer(bytes: Uint8Array): ArrayBuffer {
if (bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength) {
return bytes.buffer;
}
return bytes.slice().buffer;
}
/** SHA-256 hex digest of an ArrayBuffer, via Android's MessageDigest. */
function sha256Hex(buffer: ArrayBuffer): string {
return String(com.faceclaw.app.FaceclawFirmwareUtil.sha256Hex(buffer));
}
/** Write an ArrayBuffer's bytes to `path`, via a native FileChannel write. */
function writeFile(path: string, buffer: ArrayBuffer): void {
com.faceclaw.app.FaceclawFirmwareUtil.writeFile(path, buffer);
}
+145
View File
@@ -0,0 +1,145 @@
// AUTO-GENERATED from g2flash/patches/cfw_patches.json — do not edit by hand.
// Regenerate by re-running the generator in the firmware onboarding change.
// Turns the stock G2 2.2.4.34 image into the Faceclaw custom firmware.
export type FirmwarePatchOp = {
offset: number;
old: string;
new: string;
desc?: string;
};
export type FirmwarePatchSet = {
base: string;
baseSha256: string;
outputSha256: string;
patches: FirmwarePatchOp[];
};
export const CFW_PATCH_SET: FirmwarePatchSet = {
"base": "g2_2.2.4.34.bin",
"baseSha256": "f9a93621a7141e0ae54ca6371cd2f1b4afbffa61f302ace096e0656ba25b1754",
"outputSha256": "3b92551cffe297a75e486e036bc0ecc3723fac377ec16fc1f2c1fa81ff4aae22",
"patches": [
{
"offset": 1452514,
"old": "bdf82c10",
"new": "40f24120",
"desc": "container width <= 576"
},
{
"offset": 1452714,
"old": "bdf82e00",
"new": "40f22111",
"desc": "container height movw #0x121"
},
{
"offset": 1452718,
"old": "9128",
"new": "8842",
"desc": "container height cmp r0,r1"
},
{
"offset": 1450756,
"old": "39f72ef9",
"new": "8ef200fc",
"desc": "bl frag_write @ 0x500984"
},
{
"offset": 1451232,
"old": "39f740f8",
"new": "8ef212fb",
"desc": "bl frag_write @ 0x500b60"
},
{
"offset": 1451772,
"old": "38f732ff",
"new": "8ef204fa",
"desc": "bl frag_write @ 0x500d7c"
},
{
"offset": 1451408,
"old": "3bd0",
"new": "3be0",
"desc": "drop per-session CompressMode-consistency guard"
},
{
"offset": 1450884,
"old": "59f772ff",
"new": "8ef2b6fe",
"desc": "bl snapshot_side @ 0x500a04"
},
{
"offset": 1451896,
"old": "59f778fd",
"new": "8ef2bcfc",
"desc": "bl snapshot_side @ 0x500df8"
},
{
"offset": 1114956,
"old": "52f03dfe",
"new": "e0f2d6fe",
"desc": "bl image_deferred (deferred consumer -> FIFO restore + worker, both lenses)"
},
{
"offset": 1137988,
"old": "bff7e2fa",
"new": "ddf27af9",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
"offset": 671534,
"old": "28f049f8",
"new": "4ff305f9",
"desc": "bl evenhub_longpress (replaces force-quit dialog)"
},
{
"offset": 672350,
"old": "1df0cff9",
"new": "4ef389ff",
"desc": "bl ring_release (forward ring release-long-press)"
},
{
"offset": 4131592,
"old": "",
"new": "2de9f04f40f26c63c0f250031b681b6a3bb1930800f0bb80012b37d1002300278be0002a00f0b38002f0030c97084ff0000215d0a2eb870e471c4d1c6ff00306ac19e378ba19d37023790436137163795371a3790eeb060404349371f0d1321dbcf1000f00f093808b5cbcf1010f835400f08d80531ccf5cbcf1020fc75400f086800232895c8154bde8f08f23f0010c01f1010e00236ff0070b4ff0f0086ff00f0900bf0eeb030515f9016c00eb0b0a08ead615770648bf0f358af80850b50609eae577f50648bf0f3700eb830574076f704fea06774fea867409eae77709eae47448bf0f37af70f60718bf0f34ec701ef90340023308ead416670648bf0f362e71a60609eae676e70648bf0f366e71260709eae676670748bf0f36ae71a50709eae575e40718bf0f359c450bf1080b8af80f50b6d10bf10807520758bfbde8f08fc956f02303ead1134c0648bf0f33c3558b066ff00f04ca0604eae3734fea017200f1010648bf0f3304eae272851cf3554b0748bf0f32ea558a0700f1030c04eae272c90718bf0f320cf80720bde8f08f000002fb01f042f66f31c0f24701084700bf084642f6b331c0f24701084770b500284ed001684ef65a62ccf2ff02914218bf70bd90f8fc1090f8fd5049f2597c8d42c0f24e0c2ad205eb8501014491f8012191f8024191f8fee091f8ff3091f8001142ea0424012c4ff0010298bf14466e1c054680f8fd60b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f8fc10bde870406047e047d5f8f80038b148f2eb42c0f244022146bde87040104770bd00bf2de9f04f85b043f6dc76c2f200063568804628466ff3960042f66f34b0f1005fc0f2470407d128684ef65a61ccf2ff01884200f0b8804ff4f870a0470546002800f0b0804ff61060cff6ff70002100bf2a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa1182f8fb1182f8fc1182f8fd1182f8fe1182f8ff1182f8001282f8011282f8021282f8031282f8041282f8051282f8061282f8071282f8081282f8091282f80a1282f80b1282f80c1282f80d1282f80e1282f80f1282f8101282f8111282f8121282f8131282f8141282f8151282f8161282f8171282f8181282f8191282f81a1282f81b1282f81c1282f81d1282f81e1282f81f1282f8201282f8211282f8221282f8231282f8241282f8251282f8261282f8271282f8281282f8291282f82a1282f82b1282f82c1282f82d127ff480af4ef65a60ccf2ff002860012085f8ce004ff0ff30a5f8d400a5f8d600a5f8d800a5f8da00a5f8dc00a5f8de00a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f2003560b8f1000f18bf002d07d14af6ed00c0f2450005b0bde8f04f0047d8f80cb0bbf1000ff2d0d8f820a0baf1000fedd0a94659f8040f00287bd0686900287ad0686a002879d0686b002878d0686c002877d0686d002876d0686e002875d0686f002874d0d5f88400002872d0d5f89400002870d0d5f8a40000286ed0d5f8b40000286cd0d5f8b00029690490d5f8a0002a6b0390d5f8900000260290d5f880002f6f0190286ad5f860e0d5f850c02b6c884238bf014638bf01268a423cbf114602268b423cbf194603268c453cbf614604268e453cbf714605268f423cbf39460626019888423cbf01460726029888423cbf01460826039888423cbf014609260498884238bf0146d5f8c00038bf0a26884238bf0b2609eb0610406804f1440137018847002049f80700012085f8d20016e0002614e0012612e0022610e003260ee004260ce005260ae0062608e0072606e0082604e0092602e00a2600e00b265046a04700283ff451af0af0030c5fea9a034ff0000218d00496a2eb830e431c0bf101066ff00307f119cc78da19d4700c79043714714c79547189790eeb070404349171f0d1049e3a1dbcf1000f10d01bf80230bcf1010f83540ad0531c1bf80370bcf1020fc75403d0911c1bf80120425409eb06114860d5f8c400320149f80280421cc1f808a0c5f8c420c8600de738464146fff732be2de9f04f81b043f6dc7ac2f2000adaf80050044628466ff3960042f66f3916460f46b0f1005fc0f2470907d128684ef65a61ccf2ff01884200f0b8804ff4f870c8470546002800f015814ff61060cff6ff7000212a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa1182f8fb1182f8fc1182f8fd1182f8fe1182f8ff1182f8001282f8011282f8021282f8031282f8041282f8051282f8061282f8071282f8081282f8091282f80a1282f80b1282f80c1282f80d1282f80e1282f80f1282f8101282f8111282f8121282f8131282f8141282f8151282f8161282f8171282f8181282f8191282f81a1282f81b1282f81c1282f81d1282f81e1282f81f1282f8201282f8211282f8221282f8231282f8241282f8251282f8261282f8271282f8281282f8291282f82a1282f82b1282f82c1282f82d127ff480af4ef65a60ccf2ff002860012085f8ce004ff0ff30a5f8d400a5f8d600a5f8d800a5f8da00a5f8dc00a5f8de00a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f200caf8005005f1040a4ff0000b4ff000084ff0ff30002200234ff0ff3105e000bf6032c02a03f1060332d0af187e68a64204d13e6986423cbf194630467e69a64204d13e6a86423cbf591c30467e6aa64204d13e6b86423cbf991c30467e6ba64204d13e6c86423cbfd91c30467e6ca64204d13e6d86423cbf191d30467e6da642ced13f6e87423cbf591d3846c8e700bf002917d40aeb01104768866845f6c3400901c0f250004af801b08047204639463246012300f01af8804609f1440138468847a5e7404601b0bde8f08f45f6c340c0f25000caf800508047204639463246012301b0bde8f04f00e000bf2de9f04fdbb0002918bf002a04d15bb0bde8f04f00f050be0f7807f07f06052e00f06081072e47d0422ef0d0b0f840b0b0f842a0092e00f04682082e40f050820646022a4ff0ff30c0f03983002b00f036830bf10100032303eb500020f0030000fb0af07630824200f235824d78edb188460227b81c904200f22d8208eb070318f807705b7857ea032300f024821f18974200f2208208eb0001304614461a460023fff7adff2246013de3d130465946524600f067fe08e343f6dc74c2f20004236818466ff39600b0f1005f07d118684ef65a67ccf2ff07b84200f0c0800e4642f66f31c0f247014ff4f870154688470346002800f0b0804ff61060cff6ff70002100bf1a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa118Line truncated
"desc": "append injected blobs to main-app payload"
},
{
"offset": 628968,
"old": "a8713500",
"new": "7c983500",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 136,
"old": "28723500",
"new": "fc983500",
"desc": "main-app TOC entry size (ps + 128)"
},
{
"offset": 629088,
"old": "a8713504",
"new": "7c983504",
"desc": "main-app preamble length (low 24 bits)"
},
{
"offset": 629092,
"old": "7a8feaba",
"new": "4ba49032",
"desc": "[4] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 140,
"old": "ee469ded",
"new": "adef18ac",
"desc": "[4] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
"offset": 628972,
"old": "ee469ded",
"new": "adef18ac",
"desc": "[4] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
};
+101
View File
@@ -0,0 +1,101 @@
import { Utils } from "@nativescript/core";
declare const com: any;
export type FlashState = "validating" | "connecting" | "flashing" | "rebooting" | "done" | "error";
export type FlashProgress = {
lens: string;
componentIndex: number;
componentCount: number;
blockIndex: number;
blockCount: number;
};
/**
* TS wrapper around the native FaceclawFirmwareFlasher — streams a verified
* custom-firmware image to both lenses over the stock OTA BLE protocol.
*/
export class FirmwareFlasher {
private readonly flasher: any;
private readonly listenerProxy: any;
private readonly logListeners = new Set<(line: string) => void>();
private readonly progressListeners = new Set<(progress: FlashProgress) => void>();
private readonly stateListeners = new Set<(state: FlashState, detail: string) => void>();
private readonly completeListeners = new Set<(success: boolean, detail: string) => void>();
constructor(addresses: { right: string; left: string }, firmwarePath: string) {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.flasher = new com.faceclaw.app.FaceclawFirmwareFlasher(
context,
addresses.right,
addresses.left,
firmwarePath,
);
this.listenerProxy = new com.faceclaw.app.FaceclawFirmwareFlasherListener({
onLog: (line: string) => this.emit(this.logListeners, String(line)),
onProgress: (
lens: string,
componentIndex: number,
componentCount: number,
blockIndex: number,
blockCount: number,
) =>
this.emit(this.progressListeners, {
lens: String(lens),
componentIndex: Number(componentIndex),
componentCount: Number(componentCount),
blockIndex: Number(blockIndex),
blockCount: Number(blockCount),
}),
onState: (state: string, detail: string) =>
this.emit(this.stateListeners, String(state) as FlashState, String(detail ?? "")),
onComplete: (success: boolean, detail: string) =>
this.emit(this.completeListeners, Boolean(success), String(detail ?? "")),
});
this.flasher.setListener(this.listenerProxy);
}
onLog(listener: (line: string) => void): () => void {
this.logListeners.add(listener);
return () => this.logListeners.delete(listener);
}
onProgress(listener: (progress: FlashProgress) => void): () => void {
this.progressListeners.add(listener);
return () => this.progressListeners.delete(listener);
}
onStateChange(listener: (state: FlashState, detail: string) => void): () => void {
this.stateListeners.add(listener);
return () => this.stateListeners.delete(listener);
}
onComplete(listener: (success: boolean, detail: string) => void): () => void {
this.completeListeners.add(listener);
return () => this.completeListeners.delete(listener);
}
start(): void {
this.flasher.start();
}
cancel(): void {
this.flasher.cancel();
}
close(): void {
this.flasher.close();
}
private emit<A extends unknown[]>(listeners: Set<(...args: A) => void>, ...args: A): void {
const snapshot = Array.from(listeners);
setTimeout(() => {
for (const listener of snapshot) {
listener(...args);
}
}, 0);
}
}
+82
View File
@@ -0,0 +1,82 @@
import { Utils } from "@nativescript/core";
declare const com: any;
export type FlashPromptState =
| "connecting"
| "connected"
| "prompting"
| "result"
| "cancelled"
| "timeout"
| "disconnected"
| "error";
/**
* 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).
*/
export class FlashPromptCommunicator {
private readonly communicator: any;
private readonly listenerProxy: any;
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>();
constructor(addresses: { right: string; left: string }, warningText: string) {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.communicator = new com.faceclaw.app.FaceclawFlashPromptCommunicator(
context,
addresses.right,
addresses.left,
warningText,
);
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 ?? "")),
onResult: (approved: boolean) => this.emit(this.resultListeners, Boolean(approved)),
});
this.communicator.setListener(this.listenerProxy);
}
onLog(listener: (line: string) => void): () => void {
this.logListeners.add(listener);
return () => this.logListeners.delete(listener);
}
onStateChange(listener: (state: FlashPromptState, detail: string) => void): () => void {
this.stateListeners.add(listener);
return () => this.stateListeners.delete(listener);
}
onResult(listener: (approved: boolean) => void): () => void {
this.resultListeners.add(listener);
return () => this.resultListeners.delete(listener);
}
start(): void {
this.communicator.start();
}
cancel(): void {
this.communicator.cancel();
}
close(): void {
this.communicator.close();
}
private emit<A extends unknown[]>(listeners: Set<(...args: A) => void>, ...args: A): void {
const snapshot = Array.from(listeners);
setTimeout(() => {
for (const listener of snapshot) {
listener(...args);
}
}, 0);
}
}
+10
View File
@@ -0,0 +1,10 @@
import { EventData, Page } from "@nativescript/core";
import { OnboardingFlashViewModel } from "./onboarding-flash-view-model";
export function navigatingTo(args: EventData): void {
const page = args.object as Page;
if (!page.bindingContext) {
page.bindingContext = new OnboardingFlashViewModel();
}
}
+18
View File
@@ -0,0 +1,18 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
<GridLayout rows="*,auto" class="p-20">
<ScrollView row="0">
<StackLayout>
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
<ActivityIndicator busy="{{ busy }}" visibility="{{ busyVisibility }}" class="m-t-16" />
<Progress value="{{ progress }}" maxValue="100" visibility="{{ progressVisibility }}" class="m-t-16" />
<Label text="{{ status }}" class="m-t-16 text-center" textWrap="true" />
<Label text="{{ log }}" class="m-t-24" textWrap="true" fontSize="12" visibility="{{ logVisibility }}" />
</StackLayout>
</ScrollView>
<GridLayout row="1" columns="*,*" class="m-t-20">
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" visibility="{{ primaryVisibility }}" class="-primary" />
</GridLayout>
</GridLayout>
</Page>
+519
View File
@@ -0,0 +1,519 @@
import { Frame, Observable } from "@nativescript/core";
import { ensureBlePermissions } from "../g2/android-permissions";
import {
isValidMacAddress,
loadDeviceAddresses,
saveDeviceAddresses,
} from "../g2/device-addresses";
import {
buildCustomFirmware,
FirmwareBuildError,
FirmwareProgress,
} 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 { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
type FlashPhase = "intro" | "prompt" | "building" | "ready" | "flashing" | "flashed" | "error";
// Kept short to fit the glasses' ~50-column text grid.
const GLASSES_WARNING =
"Flashing custom firmware may void your warranty and can brick the glasses. Continue?";
export class OnboardingFlashViewModel extends Observable {
private _phase: FlashPhase = "intro";
private _headline = "Flash Custom Firmware";
private _status = "";
private _log = "";
private _busy = false;
private _progress = 0;
private readonly discovery = new DeviceDiscoveryBridge();
private addresses: { right: string; left: string } | null = null;
private firmwarePath = "";
private prompt: FlashPromptCommunicator | null = null;
private promptUnsubscribers: Array<() => void> = [];
private flasher: FirmwareFlasher | null = null;
private flasherUnsubscribers: Array<() => void> = [];
private retryAction: () => void = () => this.beginPrompt();
// --- observable properties -------------------------------------------------
get phase(): FlashPhase {
return this._phase;
}
get headline(): string {
return this._headline;
}
set headline(value: string) {
if (this._headline !== value) {
this._headline = value;
this.notifyPropertyChange("headline", value);
}
}
get status(): string {
return this._status;
}
set status(value: string) {
if (this._status !== value) {
this._status = value;
this.notifyPropertyChange("status", value);
}
}
get log(): string {
return this._log;
}
set log(value: string) {
if (this._log !== value) {
this._log = value;
this.notifyPropertyChange("log", value);
this.notifyPropertyChange("logVisibility", this.logVisibility);
}
}
get logVisibility(): "visible" | "collapse" {
return this._log ? "visible" : "collapse";
}
get busy(): boolean {
return this._busy;
}
set busy(value: boolean) {
if (this._busy !== value) {
this._busy = value;
this.notifyPropertyChange("busy", value);
this.notifyPropertyChange("busyVisibility", this.busyVisibility);
}
}
get busyVisibility(): "visible" | "collapse" {
return this._busy ? "visible" : "collapse";
}
get progress(): number {
return this._progress;
}
set progress(value: number) {
const clamped = Math.max(0, Math.min(100, Math.round(value)));
if (this._progress !== clamped) {
this._progress = clamped;
this.notifyPropertyChange("progress", clamped);
}
}
get progressVisibility(): "visible" | "collapse" {
return this._phase === "flashing" ? "visible" : "collapse";
}
get primaryLabel(): string {
switch (this._phase) {
case "intro":
return "Connect & Confirm";
case "ready":
return "Flash Now";
case "flashed":
return "Finish";
case "error":
return "Retry";
default:
return "";
}
}
get secondaryLabel(): string {
switch (this._phase) {
case "prompt":
return "Cancel";
case "ready":
return "Not Now";
default:
return "Back";
}
}
get primaryVisibility(): "visible" | "collapse" {
return this.primaryLabel ? "visible" : "collapse";
}
get secondaryVisibility(): "visible" | "collapse" {
// No escape hatch mid-write (building/flashing) or after success (flashed).
return this._phase === "building" || this._phase === "flashing" || this._phase === "flashed"
? "collapse"
: "visible";
}
// --- button handlers -------------------------------------------------------
onPrimaryTap(): void {
switch (this._phase) {
case "intro":
void this.beginPrompt();
return;
case "ready":
this.startFlashing();
return;
case "flashed":
this.finish();
return;
case "error":
this.retryAction();
return;
default:
return;
}
}
onSecondaryTap(): void {
if (this._phase === "prompt") {
this.cancelPrompt();
return;
}
if (this._phase === "building" || this._phase === "flashing" || this._phase === "flashed") {
return;
}
this.leave();
}
// --- prompt flow -----------------------------------------------------------
private async beginPrompt(): Promise<void> {
if (!global.isAndroid) {
this.toError("Flashing is only available on Android.", () => this.beginPrompt());
return;
}
this.setPhase("prompt");
this.headline = "Confirm On Your Glasses";
this.log = "";
this.busy = true;
this.status = "Preparing to connect. Make sure your glasses are on and the Even app is disconnected.";
try {
await ensureBlePermissions();
const addresses = await this.resolveAddresses();
if (!addresses) {
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(),
);
return;
}
this.addresses = addresses;
this.status = "Connecting to your glasses. Watch the lens for a Yes/No prompt.";
this.startCommunicator(addresses);
} catch (error) {
this.busy = false;
this.toError(this.formatError(error), () => this.beginPrompt());
}
}
private startCommunicator(addresses: { right: string; left: string }): void {
this.disposePrompt();
const prompt = new FlashPromptCommunicator(addresses, GLASSES_WARNING);
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.start();
}
private handlePromptState(state: FlashPromptState, detail: string): void {
switch (state) {
case "connecting":
this.status = "Connecting to your glasses...";
break;
case "connected":
this.status = "Connected. Showing the confirmation on the lens...";
break;
case "prompting":
this.status =
"Look at the lens and choose Yes to flash or No to cancel. (Use the ring or a temple tap to select.)";
break;
case "result":
// Handled by onResult.
break;
case "cancelled":
this.busy = false;
this.toError("Cancelled.", () => this.beginPrompt());
break;
case "timeout":
this.busy = false;
this.toError(detail || "No response from the glasses.", () => this.beginPrompt());
break;
case "disconnected":
this.busy = false;
this.toError(detail || "Lost connection to the glasses.", () => this.beginPrompt());
break;
case "error":
this.busy = false;
this.toError(detail || "Connection failed.", () => this.beginPrompt());
break;
}
}
private handlePromptResult(approved: boolean): void {
this.disposePrompt();
if (!approved) {
this.busy = false;
this.toError("You declined on the glasses. No firmware was written.", () => this.beginPrompt());
return;
}
void this.buildFirmware();
}
private cancelPrompt(): void {
this.status = "Cancelling...";
try {
this.prompt?.cancel();
} catch {
// ignore
}
this.disposePrompt();
this.busy = false;
this.toError("Cancelled.", () => this.beginPrompt());
}
// --- firmware build flow ---------------------------------------------------
private async buildFirmware(): Promise<void> {
this.setPhase("building");
this.headline = "Preparing Firmware";
this.busy = true;
this.status = "Confirmed. Downloading the stock firmware...";
try {
const result = await buildCustomFirmware((progress) => this.reportBuildProgress(progress));
this.firmwarePath = result.path;
this.busy = false;
this.setPhase("ready");
this.headline = "Firmware Ready";
this.status =
`Custom firmware prepared and verified (${result.bytes.toLocaleString()} bytes).\n\n` +
"Tap Flash Now to write it to your glasses. Keep both lenses powered on and nearby — " +
"each lens takes a few minutes, and the glasses will reboot when each lens finishes. " +
"Do not close the app during flashing.";
this.appendLog(`saved to ${result.path}`);
} catch (error) {
this.busy = false;
const message =
error instanceof FirmwareBuildError ? error.message : this.formatError(error);
this.toError(message, () => this.buildFirmware());
}
}
private reportBuildProgress(progress: FirmwareProgress): void {
switch (progress.phase) {
case "downloading":
this.status = "Downloading the stock firmware from Even's CDN...";
break;
case "verifying-base":
this.status = "Verifying the downloaded firmware...";
break;
case "patching":
this.status = `Applying patches (${progress.applied}/${progress.total})...`;
break;
case "verifying-output":
this.status = "Verifying the patched firmware...";
break;
case "writing":
this.status = "Saving the prepared firmware...";
break;
case "done":
break;
}
}
// --- flashing flow ---------------------------------------------------------
private startFlashing(): void {
if (!this.addresses || !this.firmwarePath) {
this.toError("Missing glasses addresses or firmware; start over.", () => this.beginPrompt());
return;
}
this.setPhase("flashing");
this.headline = "Flashing Firmware";
this.busy = true;
this.progress = 0;
this.status = "Starting. Do not close the app or power off the glasses.";
this.disposeFlasher();
const flasher = new FirmwareFlasher(this.addresses, this.firmwarePath);
this.flasher = flasher;
this.flasherUnsubscribers.push(
flasher.onLog((line) => this.appendLog(line)),
flasher.onProgress((progress) => this.handleFlashProgress(progress)),
flasher.onStateChange((state, detail) => this.handleFlashState(state, detail)),
flasher.onComplete((success, detail) => this.handleFlashComplete(success, detail)),
);
flasher.start();
}
private handleFlashState(state: FlashState, detail: string): void {
switch (state) {
case "validating":
this.status = "Validating the firmware image...";
break;
case "connecting":
this.status = `Connecting to the ${detail || ""} lens...`.replace(" ", " ");
break;
case "flashing":
this.status = `Flashing the ${detail || ""} lens. Keep the glasses on and nearby.`.replace(" ", " ");
break;
case "rebooting":
this.status = detail || "Lenses rebooting; reconnecting...";
break;
case "done":
case "error":
// Handled by onComplete.
break;
}
}
private handleFlashProgress(progress: FlashProgress): void {
const lensIndex = progress.lens === "right" ? 1 : 0;
const withinLens =
progress.componentCount > 0
? (progress.componentIndex - 1 + (progress.blockCount > 0 ? progress.blockIndex / progress.blockCount : 0)) /
progress.componentCount
: 0;
this.progress = ((lensIndex + withinLens) / 2) * 100;
this.status =
`Flashing ${progress.lens} lens — part ${progress.componentIndex}/${progress.componentCount}, ` +
`block ${progress.blockIndex}/${progress.blockCount}. Keep the glasses on and nearby.`;
}
private handleFlashComplete(success: boolean, detail: string): void {
this.disposeFlasher();
this.busy = false;
if (success) {
this.progress = 100;
this.setPhase("flashed");
this.headline = "All Done";
this.status = detail || "Firmware installed. Your glasses are rebooting into Faceclaw's custom firmware.";
return;
}
this.toError(detail || "Flashing failed.", () => this.startFlashing());
}
// --- helpers ---------------------------------------------------------------
private async resolveAddresses(): Promise<{ right: string; left: string } | null> {
const stored = loadDeviceAddresses();
if (isValidMacAddress(stored.right) && isValidMacAddress(stored.left)) {
return { right: stored.right, left: stored.left };
}
this.status = "Scanning for your glasses...";
const candidates = await this.discovery.scanCandidates(8000);
const found = buildAddressSet(candidates);
if (isValidMacAddress(found.right) && isValidMacAddress(found.left)) {
saveDeviceAddresses({ right: found.right, left: found.left, ring: found.ring || stored.ring });
return { right: found.right, left: found.left };
}
return null;
}
private finish(): void {
setPreviewOnlyMode(false);
setOnboardingCompleted(true);
this.disposePrompt();
this.disposeFlasher();
Frame.topmost()?.navigate({
moduleName: "phone-ui/main-page",
clearHistory: true,
});
}
private leave(): void {
this.disposePrompt();
this.disposeFlasher();
const frame = Frame.topmost();
if (frame?.canGoBack()) {
frame.goBack();
} else {
frame?.navigate({ moduleName: "phone-ui/onboarding-page", clearHistory: true });
}
}
private toError(message: string, retry: () => void): void {
this.retryAction = retry;
this.status = message;
this.setPhase("error");
this.headline = "Something Went Wrong";
}
private setPhase(phase: FlashPhase): void {
if (this._phase !== phase) {
this._phase = phase;
this.notifyPropertyChange("phase", phase);
}
this.notifyPropertyChange("primaryLabel", this.primaryLabel);
this.notifyPropertyChange("secondaryLabel", this.secondaryLabel);
this.notifyPropertyChange("primaryVisibility", this.primaryVisibility);
this.notifyPropertyChange("secondaryVisibility", this.secondaryVisibility);
this.notifyPropertyChange("progressVisibility", this.progressVisibility);
}
private appendLog(line: string): void {
const stamp = new Date().toISOString().slice(11, 19);
this.log = this._log ? `${this._log}\n[${stamp}] ${line}` : `[${stamp}] ${line}`;
}
private disposePrompt(): void {
for (const unsubscribe of this.promptUnsubscribers) {
try {
unsubscribe();
} catch {
// ignore
}
}
this.promptUnsubscribers = [];
if (this.prompt) {
try {
this.prompt.close();
} catch {
// ignore
}
this.prompt = null;
}
}
private disposeFlasher(): void {
for (const unsubscribe of this.flasherUnsubscribers) {
try {
unsubscribe();
} catch {
// ignore
}
}
this.flasherUnsubscribers = [];
if (this.flasher) {
try {
this.flasher.close();
} catch {
// ignore
}
this.flasher = null;
}
}
private formatError(error: unknown): string {
const raw = (error as Error)?.message ?? String(error);
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
}
}
+5 -1
View File
@@ -4,5 +4,9 @@ import { OnboardingViewModel } from "./onboarding-view-model";
export function navigatingTo(args: EventData): void {
const page = args.object as Page;
page.bindingContext = new OnboardingViewModel();
// Preserve the step when returning from the flashing page (back navigation
// re-fires navigatingTo); only build a fresh model on first entry.
if (!page.bindingContext) {
page.bindingContext = new OnboardingViewModel();
}
}
+14
View File
@@ -1,6 +1,7 @@
import { ApplicationSettings } from "@nativescript/core";
const ONBOARDING_COMPLETE_KEY = "onboarding.complete";
const PREVIEW_ONLY_KEY = "onboarding.previewOnly";
export function hasCompletedOnboarding(): boolean {
return ApplicationSettings.getBoolean(ONBOARDING_COMPLETE_KEY, false);
@@ -9,3 +10,16 @@ export function hasCompletedOnboarding(): boolean {
export function setOnboardingCompleted(completed: boolean): void {
ApplicationSettings.setBoolean(ONBOARDING_COMPLETE_KEY, completed);
}
/**
* True when the user chose to skip flashing during onboarding and use only the
* on-phone display preview instead of pairing with glasses. Persisted so the
* app can adapt later; the flashing path clears it.
*/
export function isPreviewOnlyMode(): boolean {
return ApplicationSettings.getBoolean(PREVIEW_ONLY_KEY, false);
}
export function setPreviewOnlyMode(previewOnly: boolean): void {
ApplicationSettings.setBoolean(PREVIEW_ONLY_KEY, previewOnly);
}
+15 -9
View File
@@ -1,6 +1,6 @@
import { Frame, Observable } from "@nativescript/core";
import { setOnboardingCompleted } from "./onboarding-state";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
type OnboardingStep = 1 | 2 | 3;
@@ -38,12 +38,12 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
showSecondary: true,
},
3: {
headline: "Disconnect Even First",
headline: "Custom Firmware Required",
tagline: "",
body:
"You can switch back and forth between Faceclaw and the official Even Realities application at any time. However, they can't both be connected to the headset simultaneously. The Even app will reconnect to the glasses whenever you launch it. To disconnect the official Even app, open it, go to the Home tab, select your glasses, open the Connection submenu, and press Disconnect.",
primaryLabel: "Configure",
secondaryLabel: "Back",
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. This connects to your glasses, asks for confirmation on the lens, then downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
primaryLabel: "Flash Firmware",
secondaryLabel: "Preview Only",
showLogo: false,
showTagline: false,
showSecondary: true,
@@ -67,10 +67,10 @@ export class OnboardingViewModel extends Observable {
this.setStep(3);
return;
}
setOnboardingCompleted(true);
// Step 3 primary: proceed to the flashing flow (connect + on-glasses
// confirmation + firmware download/patch/verify).
Frame.topmost()?.navigate({
moduleName: "phone-ui/config-page",
clearHistory: true,
moduleName: "phone-ui/onboarding-flash-page",
});
}
@@ -80,7 +80,13 @@ export class OnboardingViewModel extends Observable {
return;
}
if (this._step === 3) {
this.setStep(2);
// Step 3 secondary: skip flashing, use the on-phone preview only.
setPreviewOnlyMode(true);
setOnboardingCompleted(true);
Frame.topmost()?.navigate({
moduleName: "phone-ui/main-page",
clearHistory: true,
});
}
}