G1 support: Flashing within the Android app

This commit is contained in:
James Babcock committed 2026-11-06 12:55:24 -08:00
1 parent 345ba36c33
commit 38c52ebc31
37 files changed
+2819 -32

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
/** Keeping what's saved about a G1 current as an install changes its arms' addresses. */
import {
loadDeviceAddresses,
loadPairedGlassesIdentity,
saveDeviceAddresses,
savePairedGlassesIdentity,
} from "../g2/device-addresses";
import type { EvenAdvertisement } from "../g2/even-advertisement";
import type { GlassesPairCandidate } from "../g2/pairing-candidates";
import type { G1Side } from "./flash-plan";
export function saveG1Pair(pair: GlassesPairCandidate): void {
const stored = loadDeviceAddresses();
saveDeviceAddresses({ left: pair.left!.address, right: pair.right!.address, ring: stored.ring });
const identity = loadPairedGlassesIdentity();
savePairedGlassesIdentity({
serial: pair.serial ?? identity?.serial ?? "",
leftName: pair.left!.name,
rightName: pair.right!.name,
leftAddress: pair.left!.address,
rightAddress: pair.right!.address,
ringName: identity?.ringName ?? "",
ringAddress: stored.ring,
pairedAtMs: identity?.pairedAtMs ?? Date.now(),
});
}
/** Saved as soon as it's known: if anything stops the install after this, the next try and the session still find this arm. */
export function saveG1Arm(side: G1Side, arm: EvenAdvertisement): void {
saveDeviceAddresses({ ...loadDeviceAddresses(), [side]: arm.address });
const identity = loadPairedGlassesIdentity();
if (identity) {
savePairedGlassesIdentity(side === "left"
? { ...identity, leftName: arm.name, leftAddress: arm.address }
: { ...identity, rightName: arm.name, rightAddress: arm.address });
}
}
+75
View File
@@ -0,0 +1,75 @@
/**
* Finding a G1's arms by listening for them. That's how an install knows what each arm runs before connecting to it,
* and how it finds an arm again afterwards: an arm coming off Even's firmware has a new address.
*/
import { classifyAdvertisement, type EvenAdvertisement } from "../g2/even-advertisement";
import { DiscoveryAggregator, type GlassesPairCandidate } from "../g2/pairing-candidates";
import { DeviceDiscoveryBridge } from "../native/device-discovery";
import { pickG1Pair, sameG1Serial, type G1Side, type G1Wanted } from "./flash-plan";
/** A serial should tell which arm is ours, but an arm that is the only one of its side around is good enough after this. */
const ACCEPT_ANY_SERIAL_AFTER_MS = 45_000;
export class G1ArmScanner {
private discovery: DeviceDiscoveryBridge | null = null;
private finish: (() => void) | null = null;
/** Resolves with the wanted pair once both arms have been heard, or null after [timeoutMs]. */
waitForPair(wanted: G1Wanted, timeoutMs: number): Promise<GlassesPairCandidate | null> {
const aggregator = new DiscoveryAggregator();
return this.listen<GlassesPairCandidate>(timeoutMs, (raw, done) => {
if (aggregator.ingest(raw)) {
const pair = pickG1Pair(aggregator.pairs(), wanted);
if (pair) done(pair);
}
});
}
/** Resolves when an arm of this side on g1v0 is heard, or null after [timeoutMs]. */
waitForG1v0Arm(side: G1Side, serial: string | null | undefined, timeoutMs: number): Promise<EvenAdvertisement | null> {
const startedAt = Date.now();
const others = new Map<string, EvenAdvertisement>();
return this.listen<EvenAdvertisement>(timeoutMs, (raw, done) => {
const arm = classifyAdvertisement(raw);
if (!arm || arm.role !== side || !arm.g1Firmware || arm.g1Firmware === "stock") return;
if (!serial || sameG1Serial(arm.serial, serial)) {
done(arm);
return;
}
others.set(arm.address, arm);
if (others.size === 1 && Date.now() - startedAt >= ACCEPT_ANY_SERIAL_AFTER_MS) done(arm);
});
}
stop(): void {
this.finish?.();
}
private listen<T>(timeoutMs: number, onRaw: (raw: Parameters<DiscoveryAggregator["ingest"]>[0], done: (value: T) => void) => void): Promise<T | null> {
return new Promise((resolve, reject) => {
this.discovery ??= new DeviceDiscoveryBridge();
const discovery = this.discovery;
if (!discovery.bluetoothEnabled) {
reject(new Error("Bluetooth is off. Turn it on, then try again."));
return;
}
let settled = false;
const settle = (value: T | null, error?: Error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
this.finish = null;
discovery.stopScan();
if (error) reject(error);
else resolve(value);
};
const timer = setTimeout(() => settle(null), timeoutMs);
this.finish = () => settle(null);
const started = discovery.startScan({
onAdvertisement: (raw) => onRaw(raw, (value) => settle(value)),
onScanFailed: (_code, message) => settle(null, new Error(`The Bluetooth scan failed: ${message}`)),
});
if (!started) settle(null, new Error("Could not start the Bluetooth scan. Check that Bluetooth is on."));
});
}
}
+52
View File
@@ -0,0 +1,52 @@
/**
* Prepares the g1v0 image on the phone, as app/g2/firmware-builder.ts does for a G2: downloads Even's public firmware,
* checks it, and puts the parts this firmware embeds back into what the app ships. The result is byte for byte the
* image that was built, tested and signed, and it is checked to be. It does not touch the glasses.
*/
import { knownFolders } from "@nativescript/core";
import { firmwareSha256, writeFirmwareFile } from "../native/firmware-files";
import { decodeBase64 } from "../util/base64";
import { fetchWithUserAgent } from "../util/http";
import { G1V0_IMAGE } from "./firmware/g1v0-image";
import { G1V0_OWN_BYTES_BASE64 } from "./firmware/g1v0-own-bytes";
import { assembleG1Image, decodeG1OwnBytes, G1FirmwareError, readZipEntry } from "./firmware-image";
export type G1BuildProgress = "downloading" | "verifying" | "assembling" | "writing";
export type BuiltG1Firmware = { path: string; bytes: number; version: string };
function sha256(bytes: Uint8Array): string {
return firmwareSha256(bytes.slice().buffer);
}
async function downloadStockZip(): Promise<Uint8Array> {
let response: Response;
try {
response = await fetchWithUserAgent(G1V0_IMAGE.stockZipUrl);
} catch (error) {
throw new G1FirmwareError(`Could not reach Even's firmware server: ${(error as Error)?.message ?? error}`);
}
if (!response.ok) throw new G1FirmwareError(`The firmware download failed (HTTP ${response.status}).`);
return new Uint8Array(await response.arrayBuffer());
}
export async function buildG1Firmware(onProgress?: (progress: G1BuildProgress) => void): Promise<BuiltG1Firmware> {
onProgress?.("downloading");
const zip = await downloadStockZip();
onProgress?.("verifying");
const zipHash = sha256(zip);
if (zipHash !== G1V0_IMAGE.stockZipSha256) {
throw new G1FirmwareError(`Even's firmware download failed verification.\nexpected ${G1V0_IMAGE.stockZipSha256}\ngot ${zipHash}`);
}
onProgress?.("assembling");
const own = decodeG1OwnBytes(G1V0_OWN_BYTES_BASE64, decodeBase64);
const image = assembleG1Image(G1V0_IMAGE, own, (name) => readZipEntry(zip, name), sha256);
onProgress?.("writing");
const path = `${knownFolders.documents().path}/g1v0_${G1V0_IMAGE.version}.bin`;
writeFirmwareFile(path, image.slice().buffer);
return { path, bytes: image.length, version: G1V0_IMAGE.version };
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Rebuilding the g1v0 image from what the app ships and Even's public firmware download. No I/O, so tests can run it
* on real or made-up files. tools/g1_firmware_bundle.py is the other half.
*/
import { inflate, inflateRaw } from "pako";
import type { G1FirmwareImage } from "./firmware/g1v0-image";
export class G1FirmwareError extends Error {}
/** One file from a zip; throws when it's absent or in a form a firmware zip doesn't use. */
export function readZipEntry(zip: Uint8Array, name: string): Uint8Array {
const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
const END_OF_DIRECTORY = 0x06054b50;
const DIRECTORY_ENTRY = 0x02014b50;
const LOCAL_HEADER = 0x04034b50;
let end = zip.length - 22;
while (end >= 0 && view.getUint32(end, true) !== END_OF_DIRECTORY) end--;
if (end < 0) throw new G1FirmwareError("The firmware download is not a zip file.");
const count = view.getUint16(end + 10, true);
let at = view.getUint32(end + 16, true);
for (let i = 0; i < count; i++) {
if (at + 46 > zip.length || view.getUint32(at, true) !== DIRECTORY_ENTRY) break;
const method = view.getUint16(at + 10, true);
const packedSize = view.getUint32(at + 20, true);
const nameLength = view.getUint16(at + 28, true);
const extraLength = view.getUint16(at + 30, true);
const commentLength = view.getUint16(at + 32, true);
const headerAt = view.getUint32(at + 42, true);
const entryName = String.fromCharCode(...zip.subarray(at + 46, at + 46 + nameLength));
if (entryName === name || entryName.endsWith(`/${name}`)) {
if (view.getUint32(headerAt, true) !== LOCAL_HEADER) throw new G1FirmwareError(`Bad zip entry for ${name}.`);
const dataAt = headerAt + 30 + view.getUint16(headerAt + 26, true) + view.getUint16(headerAt + 28, true);
const packed = zip.subarray(dataAt, dataAt + packedSize);
if (method === 0) return packed.slice();
if (method === 8) return inflateRaw(packed);
throw new G1FirmwareError(`${name} uses zip method ${method}.`);
}
at += 46 + nameLength + extraLength + commentLength;
}
throw new G1FirmwareError(`The firmware download has no ${name}.`);
}
export function decodeG1OwnBytes(base64: string, decode: (text: string) => Uint8Array): Uint8Array {
return inflate(decode(base64));
}
/**
* The finished image. [fileBytes] gives one of Even's unpacked files by name, [sha256] a lowercase hex digest. Each part
* and the result are checked, so a success is byte for byte the image that was built and signed.
*/
export function assembleG1Image(
manifest: G1FirmwareImage,
own: Uint8Array,
fileBytes: (name: string) => Uint8Array,
sha256: (bytes: Uint8Array) => string,
): Uint8Array {
const image = new Uint8Array(manifest.size);
let position = 0;
let ownAt = 0;
for (const part of [...manifest.parts].sort((a, b) => a.offset - b.offset)) {
const before = part.offset - position;
image.set(own.subarray(ownAt, ownAt + before), position);
ownAt += before;
const bytes = fileBytes(part.file).subarray(part.fileOffset, part.fileOffset + part.length);
if (bytes.length !== part.length || sha256(bytes) !== part.sha256) {
throw new G1FirmwareError(`${part.file} in Even's download is not the one this firmware was built with.`);
}
image.set(bytes, part.offset);
position = part.offset + part.length;
}
image.set(own.subarray(ownAt), position);
if (ownAt + (manifest.size - position) !== own.length) {
throw new G1FirmwareError("The firmware bundled with this app is damaged.");
}
const digest = sha256(image);
if (digest !== manifest.sha256) {
throw new G1FirmwareError(`The assembled firmware failed verification.\nexpected ${manifest.sha256}\ngot ${digest}`);
}
return image;
}
+41
View File
@@ -0,0 +1,41 @@
// AUTO-GENERATED by tools/g1_firmware_bundle.py -- do not edit by hand.
// What the app installs on a G1, and the parts of it that come from Even's own download.
export type G1FirmwarePart = { offset: number; length: number; file: string; fileOffset: number; sha256: string };
export type G1FirmwareImage = {
version: string;
sha256: string;
size: number;
source: string;
stockVersion: string;
stockZipUrl: string;
stockZipSha256: string;
parts: G1FirmwarePart[];
};
export const G1V0_IMAGE: G1FirmwareImage = {
"version": "0.5.64",
"sha256": "25e759efbe17093390386ac286865515d1f3f47efa8e40b5f054685fc7b2d6b6",
"size": 574408,
"source": "51596992c1f1",
"stockVersion": "1.6.6",
"stockZipUrl": "https://cdn.evenreal.co/firmware/dcfa510c090e476c10a6f6c348a22415.zip",
"stockZipSha256": "748836f2d9d092b0783cbb7672fdccec4f730051cad27f095bbb156ac3e5d316",
"parts": [
{
"offset": 263344,
"length": 226020,
"file": "net_core_app_update.bin",
"fileOffset": 0,
"sha256": "c277749be97a2763742db399afeb10ca6916059abd60d41bbc05c8892c002c77"
},
{
"offset": 489392,
"length": 352,
"file": "app_update.bin",
"fileOffset": 531288,
"sha256": "92e73a6dd92da734bc21e8184d94d69e9a49e23056e378670b24334a305a953d"
}
]
};
+4
View File
@@ -0,0 +1,4 @@
// AUTO-GENERATED by tools/g1_firmware_bundle.py -- do not edit by hand.
// The built g1v0 image without Even's parts (g1v0-image.ts), deflated.
export const G1V0_OWN_BYTES_BASE64 = "eNrsfIl/U1X2+H1Lkpc0tCktmC5gFgppg5guaKEgaVJelxTagswguKSAmoJLsC6ldSQsSgEZEUQq6FccdAYVpWVRSq2pgIP7JCwji0pdQ1upL20hL1vf79yXFpj5/v6C3+fXfu57527nnnvuOeeeu7xMP9z/MsJ/JEJ1HYwIIokZDf8J///v/+k/9bsSTcBEoz/fR6OMb8j/FW782/TP62neT2PwthP/P/x3wHyt6C4k9/s7rePcB66g9O/8g3ePOEdwqLyiu4Ms76507vejCnPPGsS4NRyBnMWJnKtC603y5z/2kRvKmZ3FhQOuxIruOXOO+tXkUb9GqQop+zUhklO7zVCjovsTfUX3KT0VUkbM3UqkD5H9Fd1W6ivfyu5Fc2Xeym4id6y7ghs0mwfMgB/jNIsxBDHkdkGc7ETuVRwqtKCb3fd1F1JbuqmEld26h1Z26x9a6qnoHrnoZE/S4k/cJ9WF5hJzofmwe6ElxdjodharOKAeMGm4lWagx5II8cIBRGi5lYVqd6kFY5rh+ZufIAtDVETVo0TH/BqKCFF+xCEreabUYu8xo+YrKCHpVLPftVJ6ysxUdGcTJNQYzKo62SJy52hljDvmbgpoLkXmHoSIqQY3rnf5ZHPIFdnrZ5T7e5QkCim5d9wIasyxqK0fuT1mtdVZvIVDCauAKqnbBbQSOUTBIR+MC4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TuT+OIKPk/PX4lSMH/EKF9IKpF21o7i1R4BxVO6w7E+ylbe6Ll+31j3JqEunsvRPqD7tv6t08NdCL6r8bdax/NLVyWkpRchExgMjV3DNz6B7vnZQ/gUi1ynpVWXPKFObbex/csL/tUK95g79XFUrwoomIe94l691c9vrlcgWEer7XVz+h17VB1rtug9tXKNo2IbCS/wDagHIKWe9n9Y5eBspMqE9uze8t3rDXh+tfvDxtKa4r6/2t/vbekg2vX55SfxPgeM3HQc3XL9+24OLl28puK6uDeqlFx678Oamxd8JSXJO6oqtNskLdpRcvm+qR8YFe6YKM3rcA0wSoM7F+Zq8M6hsXAEUQz6ov7p0ArWXWF/Wuq38QwszejPrU7zF9Big5AWh7Ssx5DuiD/tbv9b1+edRSFuI4hmm7eHlk/ejef2yo8NVBSqxkPnCmGEoq6tneE1Dqsw09EEvcMF0cz3ni35kZmnAZVodyTliJvIGbbnctz56RkTv1jsy/Lr7DdPe/hO2NN92RUbrljnffyZpR4Um/4+uvvroDV+AOJdoSy9IdL1lob+HV/jvvcbxloc6l2sGSdBE6SJmHxhMTiKJGkDaufYHjzvS77eBHfplatNeymld2NLqh3IN/+NBPUk12cUU5UXI71/kxch8vYBBRMpb7y+EYrNDh2B2HMaw6RJVP02rY27hfQp2LVe2oU6rhDsVXSNlvu4g7k1smsoVXB+YhDTzvHmPPK1qT8q6FOLlZpECvPhCODCrDY3MLitIa4u4kTLG2+UMVXKX+FI/unFh+DJ7G2XrHAUuuZ5oOaTNL7uDS+PF2gy2zLMXxYqynVfMdjTf0VF8+Tqwh8XwHNXRQg4QaKbYFDiIH8jMI3YJapNtRe76hr4XQpdlSnUiXaDtf236JNwuBl924P75lt3ENoXWW497FDYRR4tU3CMbjHiJXX/uJbzekfAx2h/elNUiM5DlSp7B95yONZ8+e9+H+m/6UXUzDe5iP6EepJmc+pMH7c Line truncated
+88
View File
@@ -0,0 +1,88 @@
/** What installing firmware on a G1 has to decide. No I/O. */
import type { GlassesPairCandidate } from "../g2/pairing-candidates";
export type G1Side = "left" | "right";
/** Left first: a right arm on g1v0 next to a left arm on Even's firmware would leave the left eye dark. */
export const G1_SIDES: readonly G1Side[] = ["left", "right"];
export const G1_CASE_INSTRUCTIONS =
"Put the glasses in their charging case with the lid open, and plug the case in. Stay nearby, and leave Faceclaw open.";
export const G1_INSTALL_NOTICE =
"This replaces the firmware on both arms, about two minutes each. Going back to Even's firmware later takes a computer, and " +
"may not be the version you have now. Installing custom firmware is not covered by warranty.";
/** What the native flow says when it finishes (G1ArmFlashFlow). */
export type G1FlashResult = {
flashed?: boolean;
firmware?: "g1v0" | "stock";
version?: string;
safeMode?: boolean;
inCase?: boolean;
battery?: number | null;
};
export function parseG1FlashResult(detail: string): G1FlashResult {
try {
const parsed = JSON.parse(detail);
return parsed && typeof parsed === "object" ? (parsed as G1FlashResult) : {};
} catch {
return {};
}
}
/** Dotted versions, component by component; a missing component counts as 0. */
export function compareG1Versions(a: string, b: string): number {
const parts = (version: string) => version.split(".").map((part) => parseInt(part, 10) || 0);
const left = parts(a);
const right = parts(b);
for (let i = 0; i < Math.max(left.length, right.length); i++) {
const delta = (left[i] ?? 0) - (right[i] ?? 0);
if (delta !== 0) return delta;
}
return 0;
}
export type G1Wanted = { serial?: string | null; left?: string; right?: string };
const serialOf = (serial: string | null | undefined) => (serial ?? "").trim().toUpperCase();
export function sameG1Serial(a: string | null | undefined, b: string | null | undefined): boolean {
return serialOf(a) !== "" && serialOf(a) === serialOf(b);
}
/**
* The pair being installed on, among those heard, once both arms have been. Its serial decides, as a flash changes an arm's
* address; an address it was saved under also tells. Only with neither known does the only G1 around count: firmware
* must never go to someone else's glasses because the wanted ones weren't heard.
*/
export function pickG1Pair(pairs: readonly GlassesPairCandidate[], wanted: G1Wanted): GlassesPairCandidate | null {
const g1 = pairs.filter((pair) => pair.g1Firmware);
const complete = (pair: GlassesPairCandidate | undefined) => (pair?.left && pair.right ? pair : null);
const bySerial = g1.find((pair) => sameG1Serial(pair.serial, wanted.serial));
if (bySerial) return complete(bySerial);
const byAddress = g1.find((pair) =>
(!!wanted.left && pair.left?.address === wanted.left) || (!!wanted.right && pair.right?.address === wanted.right));
if (byAddress) return complete(byAddress);
if (serialOf(wanted.serial) || wanted.left || wanted.right) return null;
return g1.length === 1 ? complete(g1[0]) : null;
}
/**
* What a check of the two arms found: "stock", Even's firmware on an arm; "safe-mode", g1v0 restarted repeatedly and only
* updates work; "older", older than the app ships; "current", nothing to do.
*/
export type G1FirmwareState = "stock" | "safe-mode" | "older" | "current";
export function g1FirmwareState(arms: readonly G1FlashResult[], shipped: string): G1FirmwareState {
if (arms.some((arm) => arm.firmware === "stock")) return "stock";
if (arms.some((arm) => arm.safeMode)) return "safe-mode";
return arms.some((arm) => compareG1Versions(arm.version ?? "", shipped) < 0) ? "older" : "current";
}
/** Each arm counts for half of the bar. */
export function g1FlashPercent(side: G1Side, bytesSent: number, bytesTotal: number): number {
const within = bytesTotal > 0 ? Math.min(1, bytesSent / bytesTotal) : 0;
return ((side === "right" ? 1 + within : within) / 2) * 100;
}
+4
View File
@@ -0,0 +1,4 @@
declare module "pako" {
export function inflate(data: Uint8Array): Uint8Array;
export function inflateRaw(data: Uint8Array): Uint8Array;
}
+5
View File
@@ -117,6 +117,11 @@ export function firmwareIncompatibilityMessage(info: FirmwareInfo): string | nul
const versionsText = `L=${info.leftVersion || "unknown"} R=${info.rightVersion || "unknown"}`;
const required = `Faceclaw firmware revision ${REQUIRED_FACECLAW_FIRMWARE_VERSION}`;
// A G1's session names what the arms run instead of a revision (GlassesSessionG1.kt).
if (extension.kind === "none" && reportedVersions.some((version) => /^(g1v0|Even's firmware)/.test(version))) {
return `These G1 glasses run ${versionsText}. This version of Faceclaw needs the firmware it comes with: install it to continue.`;
}
switch (extension.kind) {
case "faceclaw":
if (extension.version >= REQUIRED_FACECLAW_FIRMWARE_VERSION) return null;
+7 -5
View File
@@ -386,14 +386,16 @@ export function g1Row(pair: GlassesPairCandidate, context: RowContext = {}): Pai
if (pair.mismatchWarning) warnings.push(pair.mismatchWarning);
let armsSummary: string;
let canSelect = false;
if (pair.g1Firmware === "stock") {
armsSummary = "Needs the Faceclaw firmware for the G1, which is installed from a computer";
} else if (pair.g1Firmware === "g1v0-safe") {
armsSummary = "In safe mode: the firmware restarted repeatedly. Reinstall it from a computer";
} else if (pair.completeness !== "complete") {
if (pair.completeness !== "complete") {
armsSummary = pair.completeness === "left-only"
? "Only the left arm has been seen — waiting for the right"
: "Only the right arm has been seen — waiting for the left";
} else if (pair.g1Firmware === "stock") {
armsSummary = "Runs Even's firmware. Faceclaw will install its own, with the glasses in the case";
canSelect = true;
} else if (pair.g1Firmware === "g1v0-safe") {
armsSummary = "In safe mode: the firmware restarted repeatedly. Faceclaw can install it again, with the glasses in the case";
canSelect = true;
} else {
armsSummary = "Left + right arms found. To pair, keep them in the case with the lid open";
canSelect = true;
+75
View File
@@ -0,0 +1,75 @@
import { Application } from '@nativescript/core'
import { parseG1FlashResult, type G1FlashResult } from '../g1/flash-plan'
import { iosBluetooth } from './ios-bluetooth'
import { kotlinListener } from './kotlin-listener.ios'
import type { G1FlasherOptions } from './g1-flasher'
export type { G1FlashMode, G1FlasherOptions } from './g1-flasher'
declare const FaceclawKitIosG1Flasher: any, FaceclawKitFaceclawFirmwareFlasherListener: any
/**
* iOS twin of the Android G1Flasher: the shared Kotlin G1ArmFlashFlow over a CoreBluetooth central. As with the G2's
* flasher, the phone must stay in the foreground with the screen awake, and addresses are mapped to peripheral
* identifiers first.
*/
export class G1Flasher {
private flasher: any = null
private listenerProxy: object | null = null
private logListener: ((line: string) => void) | null = null
private progressListener: ((bytesSent: number, bytesTotal: number) => void) | null = null
private stateListener: ((state: string) => void) | null = null
private previousIdle = false
private cancelled = false
private foregroundError = ''
constructor(private readonly options: G1FlasherOptions) {}
onLog(listener: (line: string) => void): void { this.logListener = listener }
onProgress(listener: (bytesSent: number, bytesTotal: number) => void): void { this.progressListener = listener }
onState(listener: (state: string) => void): void { this.stateListener = listener }
private readonly backgrounded = () => {
this.foregroundError = 'The install stopped because Faceclaw left the foreground. Return to Faceclaw and try again.'
this.cancel()
}
run(): Promise<G1FlashResult> {
this.previousIdle = UIApplication.sharedApplication.idleTimerDisabled
UIApplication.sharedApplication.idleTimerDisabled = true
Application.on(Application.suspendEvent, this.backgrounded)
const restore = () => {
Application.off(Application.suspendEvent, this.backgrounded)
UIApplication.sharedApplication.idleTimerDisabled = this.previousIdle
}
return new Promise<G1FlashResult>((resolve, reject) => {
const identifier = iosBluetooth().peripheralIdentifier(this.options.address, this.options.side)
if (!identifier) throw new Error(`Could not find the ${this.options.side} arm. Keep the glasses in the case with the lid open.`)
this.flasher = FaceclawKitIosG1Flasher.alloc().initWithAddressSideFirmwarePathModeConnectWindowMs(
identifier, this.options.side, this.options.firmwarePath, this.options.mode, this.options.connectWindowMs)
this.listenerProxy = kotlinListener(FaceclawKitFaceclawFirmwareFlasherListener, {
onLogLine: (line: string) => this.logListener?.(String(line ?? '')),
onProgressLensComponentIndexComponentCountBlockIndexBlockCountBytesSentBytesTotal: (
_lens: string, _componentIndex: number, _componentCount: number, _blockIndex: number, _blockCount: number, sent: number, total: number,
) => this.progressListener?.(Number(sent), Number(total)),
onStateStateDetail: (state: string) => this.stateListener?.(String(state)),
onCompleteSuccessDetail: (success: boolean, detail: string) => {
if (success) resolve(parseG1FlashResult(String(detail ?? '')))
else reject(new Error(this.foregroundError || String(detail ?? '') || 'The install failed.'))
},
})
this.flasher.setListenerListener(this.listenerProxy)
if (this.cancelled) this.flasher.cancel()
this.flasher.start()
}).finally(restore)
}
cancel(): void {
this.cancelled = true
try { this.flasher?.cancel() } catch { /* ignore */ }
}
close(): void {
this.cancel()
try { this.flasher?.close() } catch { /* ignore */ }
}
}
+73
View File
@@ -0,0 +1,73 @@
import { Utils } from "@nativescript/core";
import { parseG1FlashResult, type G1FlashResult, type G1Side } from "../g1/flash-plan";
declare const com: any;
export type G1FlashMode = "stock" | "update" | "probe";
export type G1FlasherOptions = {
address: string;
side: G1Side;
firmwarePath: string;
mode: G1FlashMode;
/** How long to keep trying to reach the arm and pair with it. */
connectWindowMs: number;
};
/** TS wrapper around FaceclawG1Flasher: one arm's install, or a question about what it runs. */
export class G1Flasher {
private readonly flasher: any;
private readonly listenerProxy: any;
private logListener: ((line: string) => void) | null = null;
private progressListener: ((bytesSent: number, bytesTotal: number) => void) | null = null;
private stateListener: ((state: string) => void) | null = null;
private completion: ((success: boolean, detail: string) => void) | null = null;
constructor(options: G1FlasherOptions) {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.flasher = new com.faceclaw.app.FaceclawG1Flasher(
context, options.address, options.side, options.firmwarePath, options.mode, options.connectWindowMs,
);
this.listenerProxy = new com.faceclaw.app.FaceclawFirmwareFlasherListener({
onLog: (line: string) => this.logListener?.(String(line)),
onProgress: (_lens: string, _component: number, _components: number, _block: number, _blocks: number, sent: number, total: number) =>
this.progressListener?.(Number(sent), Number(total)),
onState: (state: string) => this.stateListener?.(String(state)),
onComplete: (success: boolean, detail: string) => this.completion?.(Boolean(success), String(detail ?? "")),
});
this.flasher.setListener(this.listenerProxy);
}
onLog(listener: (line: string) => void): void {
this.logListener = listener;
}
onProgress(listener: (bytesSent: number, bytesTotal: number) => void): void {
this.progressListener = listener;
}
onState(listener: (state: string) => void): void {
this.stateListener = listener;
}
run(): Promise<G1FlashResult> {
return new Promise((resolve, reject) => {
this.completion = (success, detail) => {
this.completion = null;
if (success) resolve(parseG1FlashResult(detail));
else reject(new Error(detail || "The install failed."));
};
this.flasher.start();
});
}
cancel(): void {
this.flasher.cancel();
}
close(): void {
this.flasher.close();
}
}
+9
View File
@@ -129,6 +129,15 @@ export class IosBluetooth {
})
return result
}
/** The peripheral last heard at this address, if it was on this side. */
peripheralIdentifier(address: string, role: string): string | null {
try {
const saved = JSON.parse(ApplicationSettings.getString(`ios.ble.peripheral.${address}`, '{}'))
return saved.role === role && typeof saved.identifier === 'string' ? saved.identifier : null
} catch {
return null
}
}
forget(address: string): void { ApplicationSettings.remove(`ios.ble.peripheral.${address}`); this.devices.delete(address) }
}
let instance: IosBluetooth | null = null
+345
View File
@@ -0,0 +1,345 @@
import { Frame, Observable } from "@nativescript/core";
import { G1ArmScanner } from "../g1/arm-scanner";
import { G1V0_IMAGE } from "../g1/firmware/g1v0-image";
import { buildG1Firmware, type BuiltG1Firmware, type G1BuildProgress } from "../g1/firmware-builder";
import { saveG1Arm, saveG1Pair } from "../g1/addresses";
import { G1_CASE_INSTRUCTIONS, G1_INSTALL_NOTICE, G1_SIDES, g1FlashPercent, type G1FlashResult, type G1Side } from "../g1/flash-plan";
import { loadDeviceAddresses, loadPairedGlassesIdentity } from "../g2/device-addresses";
import { downloadAndExtractEvenHubFonts, hasExtractedEvenHubFonts } from "../g2/firmware-builder";
import { type GlassesPairCandidate } from "../g2/pairing-candidates";
import { resumeAutoReconnect, suppressAutoReconnect } from "../g2/reconnect-policy";
import { ensureBlePermissions } from "../native/ble-permissions";
import { G1Flasher, type G1FlasherOptions } from "../native/g1-flasher";
import { formatErrorMessage } from "../util/format-error";
import { finishOnboardingNavigation } from "./onboarding-navigation";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
type Phase = "intro" | "preparing" | "flashing" | "flashed" | "error" | "unavailable";
const LOCATE_MS = 45_000;
/** An arm takes about 20 s to copy the image, and a hung boot resets itself within two minutes. */
const RETURN_MS = 240_000;
const CONNECT_MS = 60_000;
/** A new arm pairs only once it knows it's in the case, which a full case can take a while to tell it. */
const FIRST_PAIRING_MS = 120_000;
/**
* The install page on a G1, in place of OnboardingFlashViewModel. The two arms are separate devices that each take the
* image over MCUmgr (G1ArmFlashFlow), left first. There is nothing on the lens to confirm with before g1v0 is on the arm,
* so the confirmation is on the phone: the page before, or this one's intro.
*
* Every run starts by listening for what each arm runs now, so a retry picks up wherever the last one stopped. An arm's
* new address is saved as soon as it's known.
*/
export class G1FlashViewModel extends Observable {
private phase: Phase = "intro";
private readonly fromOnboarding: boolean;
private readonly scanner = new G1ArmScanner();
private image: BuiltG1Firmware | null = null;
private flasher: G1Flasher | null = null;
private generation = 0;
private disposed = false;
private unpairedArm = false;
headline = "Install Faceclaw's Firmware";
status = "";
log = "";
busy = false;
progress = 0;
constructor(options?: { mode?: "install" | "uninstall"; fromOnboarding?: boolean; autoStart?: boolean }) {
super();
this.fromOnboarding = options?.fromOnboarding ?? true;
if (options?.mode === "uninstall") {
// Restoring Even's firmware has never been run on a real arm, and an arm whose network core is older than the
// image may not come back, so the phone doesn't offer it yet.
this.phase = "unavailable";
this.headline = "Back to Even's Firmware";
this.status = "Faceclaw can't restore Even's firmware on a G1 yet. It takes a computer: see \"Restore Even's firmware\" in " +
"the ScouterKit firmware's README.";
return;
}
suppressAutoReconnect();
this.status = `${G1_CASE_INSTRUCTIONS}\n\n${G1_INSTALL_NOTICE}`;
if (options?.autoStart) void this.run();
}
// --- what the page binds --------------------------------------------------
get logVisibility(): "visible" | "collapse" {
return this.log ? "visible" : "collapse";
}
get busyVisibility(): "visible" | "collapse" {
return this.busy ? "visible" : "collapse";
}
get progressVisibility(): "visible" | "collapse" {
return this.phase === "flashing" ? "visible" : "collapse";
}
get primaryLabel(): string {
switch (this.phase) {
case "intro":
return "Install";
case "flashed":
return "Finish";
case "error":
return "Retry";
default:
return "";
}
}
get primaryVisibility(): "visible" | "collapse" {
return this.primaryLabel ? "visible" : "collapse";
}
get secondaryLabel(): string {
return "Back";
}
get secondaryVisibility(): "visible" | "collapse" {
// No way out mid-install, or after one.
return this.phase === "preparing" || this.phase === "flashing" || this.phase === "flashed" ? "collapse" : "visible";
}
onPrimaryTap(): void {
if (this.phase === "intro" || this.phase === "error") void this.run();
else if (this.phase === "flashed") this.finish();
}
onSecondaryTap(): void {
if (this.phase === "intro" || this.phase === "error" || this.phase === "unavailable") this.leave();
}
// --- the install ----------------------------------------------------------
private async run(): Promise<void> {
const generation = ++this.generation;
const live = () => !this.disposed && generation === this.generation;
this.setPhase("preparing");
this.setBusy(true);
this.setText("Preparing Firmware", "Getting the firmware ready...");
try {
await ensureBlePermissions();
if (!live()) return;
if (!this.image) {
this.image = await buildG1Firmware((progress) => {
if (live()) this.setStatus(describeBuild(progress));
});
this.appendLog(`firmware ${this.image.version} prepared and verified (${this.image.bytes.toLocaleString()} bytes)`);
}
await this.prepareFonts(live);
if (!live()) return;
this.setPhase("flashing");
this.setText("Installing Firmware", "Listening for your glasses...");
const identity = loadPairedGlassesIdentity();
const stored = loadDeviceAddresses();
const pair = await this.scanner.waitForPair({ serial: identity?.serial, left: stored.left, right: stored.right }, LOCATE_MS);
if (!live()) return;
if (!pair) {
throw new Error("Couldn't hear both arms of your glasses. Make sure they're in the case with the lid open, and that no other app " +
"or phone is connected to them, then retry.");
}
saveG1Pair(pair);
this.unpairedArm = false;
for (const side of G1_SIDES) {
await this.installArm(side, pair, live);
if (!live()) return;
}
this.finished();
} catch (error) {
if (live()) this.failed(formatErrorMessage(error));
}
}
private async installArm(side: G1Side, pair: GlassesPairCandidate, live: () => boolean): Promise<void> {
const arm = pair[side]!;
const fromStock = arm.g1Firmware === "stock";
this.setProgress(g1FlashPercent(side, 0, 1));
this.setStatus(`Connecting to the ${side} arm...`);
const installed = await this.flash({
address: arm.address,
side,
firmwarePath: this.image!.path,
mode: fromStock ? "stock" : "update",
connectWindowMs: CONNECT_MS,
}, (state) => {
if (state === "pairing") this.setStatus(`Pairing with the ${side} arm. If your phone asks, accept it.`);
else if (state === "checking") this.setStatus(`Checking the ${side} arm...`);
else if (state === "flashing") this.setStatus(`Sending the firmware to the ${side} arm. Nothing has changed yet.`);
else if (state === "committing") this.setStatus(`Installing on the ${side} arm. Keep the glasses in the case.`);
}, (sent, total) => this.setProgress(g1FlashPercent(side, sent, total)));
if (!live()) return;
this.setProgress(g1FlashPercent(side, 1, 1));
if (!installed.flashed) {
this.appendLog(`${side} arm already runs ${installed.version}`);
return;
}
this.setStatus(`The ${side} arm is restarting into the new firmware. This takes about 20 seconds; keep it in the case.`);
const identity = loadPairedGlassesIdentity();
const back = await this.scanner.waitForG1v0Arm(side, identity?.serial ?? pair.serial, RETURN_MS);
if (!live()) return;
if (!back) {
throw new Error(`The ${side} arm hasn't come back yet. Leave the glasses in the plugged-in case for a few minutes, with the lid ` +
"open: an interrupted install finishes by itself. Then retry.");
}
saveG1Arm(side, back);
if (back.g1Firmware === "g1v0-safe") {
throw new Error(`The ${side} arm came back in safe mode: the new firmware restarted repeatedly. Retry to install it again.`);
}
this.setStatus(`Pairing with the ${side} arm. If your phone asks, accept it.`);
let running: G1FlashResult;
try {
running = await this.flash({
address: back.address,
side,
firmwarePath: "",
mode: "probe",
connectWindowMs: fromStock ? FIRST_PAIRING_MS : RETURN_MS,
});
} catch (error) {
if (!fromStock || !live()) throw error;
// Installed, as its advertising shows; it just won't pair yet. The next connection pairs it.
this.appendLog(`${side} arm not paired yet: ${formatErrorMessage(error)}`);
this.unpairedArm = true;
return;
}
if (!live()) return;
if (running.version !== installed.version) {
throw new Error(`The ${side} arm runs ${running.version}, not ${installed.version}: it didn't take the new firmware. Retry to try again.`);
}
this.appendLog(`${side} arm runs ${running.version}`);
}
private async flash(
options: G1FlasherOptions,
onState?: (state: string) => void,
onProgress?: (sent: number, total: number) => void,
) {
const flasher = new G1Flasher(options);
this.flasher = flasher;
flasher.onLog((line) => this.appendLog(line));
if (onState) flasher.onState(onState);
if (onProgress) flasher.onProgress(onProgress);
try {
return await flasher.run();
} finally {
if (this.flasher === flasher) this.flasher = null;
flasher.close();
}
}
/** A G2's install gets these from the same download; Faceclaw's fonts are a phone-side matter, so a failure here is no reason to stop. */
private async prepareFonts(live: () => boolean): Promise<void> {
if (hasExtractedEvenHubFonts()) return;
if (live()) this.setStatus("Preparing fonts...");
try {
await downloadAndExtractEvenHubFonts();
} catch (error) {
this.appendLog(`fonts not prepared: ${formatErrorMessage(error)}`);
}
}
private finished(): void {
// The glasses are ready for the main page to connect to.
resumeAutoReconnect();
this.setBusy(false);
this.setProgress(100);
this.setPhase("flashed");
this.setText("All Done", `Both arms run Faceclaw's firmware ${G1V0_IMAGE.version}.` + (this.unpairedArm
? " Keep the glasses in the case with the lid open until Faceclaw has connected: they only pair in the case."
: ""));
}
private failed(message: string): void {
this.setBusy(false);
this.setPhase("error");
this.setText("Something Went Wrong", message);
}
private finish(): void {
setPreviewOnlyMode(false);
setOnboardingCompleted(true);
this.teardown();
finishOnboardingNavigation();
}
private leave(): void {
this.teardown();
const frame = Frame.topmost();
if (this.fromOnboarding && frame?.canGoBack()) {
frame.goBack();
return;
}
if (!this.fromOnboarding) {
finishOnboardingNavigation();
return;
}
frame?.navigate({ moduleName: "phone-ui/onboarding-page", clearHistory: true });
}
dispose(): void {
this.disposed = true;
this.teardown();
}
private teardown(): void {
++this.generation;
this.scanner.stop();
this.flasher?.close();
this.flasher = null;
}
// --- page state -----------------------------------------------------------
private setText(headline: string, status: string): void {
this.set("headline", headline);
this.set("status", status);
}
private setStatus(status: string): void {
this.set("status", status);
}
private setBusy(busy: boolean): void {
this.set("busy", busy);
this.notifyPropertyChange("busyVisibility", this.busyVisibility);
}
private setProgress(percent: number): void {
this.set("progress", Math.max(0, Math.min(100, Math.round(percent))));
}
private setPhase(phase: Phase): void {
this.phase = phase;
for (const property of ["primaryLabel", "primaryVisibility", "secondaryVisibility", "progressVisibility"] as const) {
this.notifyPropertyChange(property, this[property]);
}
}
private appendLog(line: string): void {
const stamp = new Date().toISOString().slice(11, 19);
this.set("log", this.log ? `${this.log}\n[${stamp}] ${line}` : `[${stamp}] ${line}`);
this.notifyPropertyChange("logVisibility", this.logVisibility);
}
}
function describeBuild(progress: G1BuildProgress): string {
switch (progress) {
case "downloading":
return "Downloading the parts it needs from Even's firmware server...";
case "verifying":
return "Verifying the download...";
case "assembling":
return "Assembling the firmware...";
default:
return "Saving the firmware...";
}
}
+1
View File
@@ -15,6 +15,7 @@
<ActionItem text="Conversations" tap="{{ onConversationsTap }}" android.position="popup" />
<ActionItem text="Take screenshot" tap="{{ onTakeScreenshotTap }}" android.position="popup" />
<ActionItem text="Record screen" tap="{{ onRecordScreenTap }}" android.position="popup" />
<ActionItem text="Check firmware" tap="{{ onCheckFirmwareTap }}" isEnabled="{{ canRun }}" visibility="{{ glassesMenuItemsVisibility }}" android.position="popup" />
<ActionItem text="Uninstall custom firmware" tap="{{ onUninstallFirmwareTap }}" isEnabled="{{ canRun }}" visibility="{{ glassesMenuItemsVisibility }}" android.position="popup" />
</ActionBar>
+11 -2
View File
@@ -662,6 +662,14 @@ export class MainViewModel extends RemoteControlsViewModel {
* auto-reconnect suppression right away.
*/
async onPrepareFontsTap(): Promise<void> {
await this.openFirmwareCheck();
}
async onCheckFirmwareTap(): Promise<void> {
await this.openFirmwareCheck();
}
private async openFirmwareCheck(): Promise<void> {
this.setWarningsModalVisible(false);
if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") {
try {
@@ -909,8 +917,9 @@ export class MainViewModel extends RemoteControlsViewModel {
}
private async openFlashPage(mode: "install" | "uninstall"): Promise<void> {
// The flasher needs the glasses to itself, so drop the main connection first.
if (this.phase === "connected" || this.phase === "charging") {
// The flasher needs the glasses to itself, so drop the main connection first. That includes a session
// still retrying: an install brings arms back at the addresses it is dialling.
if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") {
try {
await dashboardController.disconnect();
} catch {
@@ -18,11 +18,21 @@ import {
type OnboardingFirmwareKind,
} from "../g2/firmware-compat";
import { DeviceInfoProbe, DeviceInfoState } from "../native/device-info-probe";
import { G1Flasher } from "../native/g1-flasher";
import { saveG1Pair } from "../g1/addresses";
import { G1ArmScanner } from "../g1/arm-scanner";
import { G1V0_IMAGE } from "../g1/firmware/g1v0-image";
import { G1_CASE_INSTRUCTIONS, G1_INSTALL_NOTICE, g1FirmwareState, type G1FlashResult, type G1Side } from "../g1/flash-plan";
import { loadPairedGlassesIdentity } from "../g2/device-addresses";
import { glassesTypeSetting } from "../ui/dashboard-settings";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
import { formatErrorMessage } from "../util/format-error";
type CheckPhase = "checking" | "fonts" | "custom" | "flashable" | "newer-validated" | "newer" | "error";
const G1_LOCATE_MS = 30_000;
const G1_CHECK_CONNECT_MS = 45_000;
export class OnboardingFirmwareCheckViewModel extends Observable {
private _phase: CheckPhase = "checking";
private _headline = "Checking Firmware";
@@ -31,7 +41,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
private generation = 0;
private probeInstance: DeviceInfoProbe | null = null;
private probeInstance: { close(): void } | null = null;
constructor() {
super();
@@ -175,6 +185,10 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
try {
await ensureBlePermissions();
if (generation !== this.generation) return;
if (glassesTypeSetting.get() === "g1") {
await this.checkG1(generation);
return;
}
const stored = loadDeviceAddresses();
if (!isValidMacAddress(stored.right)) {
this.toError("No glasses address is configured. Go back and set the device addresses.");
@@ -194,11 +208,72 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
this.applyClassification(kind, version, extension);
} catch (error) {
if (generation !== this.generation) return;
this.probeInstance = null;
this.toError(this.formatError(error));
}
}
/**
* What each arm's name says first, as that needs no connection: Even's firmware can't be asked in the same way, and an
* arm that is about to be replaced shouldn't have to pair. Only arms on g1v0 are asked which version they run.
*/
private async checkG1(generation: number): Promise<void> {
this.status = "Listening for your glasses...";
const scanner = new G1ArmScanner();
this.probeInstance = { close: () => scanner.stop() };
const stored = loadDeviceAddresses();
const pair = await scanner.waitForPair({ serial: loadPairedGlassesIdentity()?.serial, left: stored.left, right: stored.right }, G1_LOCATE_MS);
if (generation !== this.generation) return;
this.probeInstance = null;
if (!pair) {
this.toError(`Couldn't hear both arms of your glasses. ${G1_CASE_INSTRUCTIONS} Make sure no other app or phone is connected to them, then retry.`);
return;
}
saveG1Pair(pair);
const named = [pair.left!.g1Firmware, pair.right!.g1Firmware];
if (named.includes("stock")) {
this.showG1Install({ firmware: "stock" });
return;
}
if (named.includes("g1v0-safe")) {
this.showG1Install({ safeMode: true });
return;
}
const arms: G1FlashResult[] = [];
for (const side of ["left", "right"] as G1Side[]) {
const flasher = new G1Flasher({ address: pair[side]!.address, side, firmwarePath: "", mode: "probe", connectWindowMs: G1_CHECK_CONNECT_MS });
this.probeInstance = flasher;
flasher.onState((state) => {
if (generation !== this.generation) return;
if (state === "pairing") {
this.status = `Pairing with the ${side} arm. If your phone asks, accept it. A G1 pairs only in its case, with the lid open.`;
} else {
this.status = `Checking the ${side} arm...`;
}
});
arms.push(await flasher.run());
if (generation !== this.generation) return;
this.disposeProbe();
}
const state = g1FirmwareState(arms, G1V0_IMAGE.version);
if (state === "current") this.applyClassification("custom", arms[0]!.version ?? "", { kind: "none" });
else this.showG1Install(state === "stock" ? { firmware: "stock" } : state === "safe-mode" ? { safeMode: true } : arms.find((arm) => arm.version) ?? {});
}
private showG1Install(found: G1FlashResult): void {
this.busy = false;
this.setPhase("flashable");
if (found.firmware === "stock") {
this.headline = "Ready to Install";
this.status = `Your glasses run Even's firmware.\n\n${G1_CASE_INSTRUCTIONS}\n\n${G1_INSTALL_NOTICE}`;
} else if (found.safeMode) {
this.headline = "Firmware Needs Reinstalling";
this.status = `An arm of your glasses is in safe mode: its firmware restarted repeatedly. Installing it again usually fixes this.\n\n${G1_CASE_INSTRUCTIONS}`;
} else {
this.headline = "Firmware Update Available";
this.status = `Your glasses run Faceclaw's firmware ${found.version ?? ""}, and this version of Faceclaw comes with ${G1V0_IMAGE.version}.\n\n${G1_CASE_INSTRUCTIONS}`;
}
}
private reportProbeState(state: DeviceInfoState, detail: string): void {
// The probe brings up the right lens, then the left, and pairs with each
// in turn (they are separate Bluetooth devices with separate bonds).
@@ -326,7 +401,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
this.busy = false;
this.setPhase("custom");
this.headline = extractedFonts ? "Fonts Ready" : "Custom Firmware Detected";
const details = [
const details = glassesTypeSetting.get() === "g1" ? [version].filter(Boolean) : [
extension.kind === "faceclaw" ? `revision ${extension.version}` : "",
version ? `based on stock ${version}` : "",
].filter(Boolean);
+6 -3
View File
@@ -1,5 +1,7 @@
import { NavigatedData, Page } from "@nativescript/core";
import { glassesTypeSetting } from "../ui/dashboard-settings";
import { G1FlashViewModel } from "./g1-flash-view-model";
import { FlashMode, OnboardingFlashViewModel } from "./onboarding-flash-view-model";
export function navigatingTo(args: NavigatedData): void {
@@ -7,16 +9,17 @@ export function navigatingTo(args: NavigatedData): void {
if (!page.bindingContext) {
const context =
(args.context as { mode?: FlashMode; fromOnboarding?: boolean; autoStart?: boolean } | undefined) ?? undefined;
page.bindingContext = new OnboardingFlashViewModel({
const options = {
mode: context?.mode ?? "install",
fromOnboarding: context?.fromOnboarding ?? true,
autoStart: context?.autoStart ?? false,
});
};
page.bindingContext = glassesTypeSetting.get() === "g1" ? new G1FlashViewModel(options) : new OnboardingFlashViewModel(options);
}
}
export function navigatingFrom(args: NavigatedData): void {
const page = args.object as Page;
(page.bindingContext as OnboardingFlashViewModel | undefined)?.dispose();
(page.bindingContext as OnboardingFlashViewModel | G1FlashViewModel | undefined)?.dispose();
page.bindingContext = null;
}
+2 -2
View File
@@ -30,7 +30,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
2: {
headline: "Before You Continue",
tagline: "",
body: "This software provides a custom user interface and functionality for the Even Realities G2 smart glasses. It is not created or supported by Even Realities. If this software somehow breaks your headset, this is not Even's fault and is not covered by the hardware's warranty. If this software doesn't break you headset, using this software may void the hardware's warranty anyways, at the sole discretion of Even Realities. This software is beta; don't rely on it for anything critically important." +
body: "This software provides a custom user interface and functionality for the Even Realities G2 and G1 smart glasses. It is not created or supported by Even Realities. If this software somehow breaks your headset, this is not Even's fault and is not covered by the hardware's warranty. If this software doesn't break you headset, using this software may void the hardware's warranty anyways, at the sole discretion of Even Realities. This software is beta; don't rely on it for anything critically important." +
(global.isIOS ? "\n\niOS / TestFlight privacy\n\n" + IOS_PRIVACY_NOTICE : ""),
primaryLabel: "Agree",
secondaryLabel: "Back",
@@ -40,7 +40,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
3: {
headline: "Custom Firmware Required",
tagline: "",
body: "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.\n\nFlashing replaces the official firmware. You can uninstall and return to the official firmware later, by reconnecting the official Even Realities app. Installing custom firmware is not covered by warranty.",
body: "Faceclaw only runs on Even Realities G2 or G1 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.\n\nFlashing replaces the official firmware. On a G2 you can uninstall and return to the official firmware later, by reconnecting the official Even Realities app; on a G1 that takes a computer. Installing custom firmware is not covered by warranty.",
primaryLabel: "Flash Firmware",
secondaryLabel: "Preview Only",
splash: false,
+1 -8
View File
@@ -358,8 +358,7 @@ export class PairingViewModel extends Observable {
ring: ringAddress,
};
saveDeviceAddresses(addresses);
const g1 = !!pair?.g1Firmware;
if (pair) glassesTypeSetting.set(g1 ? "g1" : "g2");
if (pair) glassesTypeSetting.set(pair.g1Firmware ? "g1" : "g2");
if (pair) {
savePairedGlassesIdentity({
serial: pair.serial ?? "",
@@ -386,12 +385,6 @@ export class PairingViewModel extends Observable {
this.dispose();
if (this.onboarding) {
setPreviewOnlyMode(false);
if (g1) {
// The G2 firmware check and flash pages don't apply: a G1's firmware is installed from a
// computer, and the session reports incompatible firmware if it lacks the display path.
finishOnboardingNavigation();
return;
}
// Continue the onboarding chain: check the glasses' firmware next.
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" });
return;