forked from Blendman974/faceclaw
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.
200 lines
6.6 KiB
TypeScript
200 lines
6.6 KiB
TypeScript
/**
|
|
* 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);
|
|
}
|