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

+5
View File
@@ -13,6 +13,11 @@ and others who contributed to documenting the G2's bluetooth protocol and firmwa
G2 microphone LC3 decoding uses Google's liblc3: https://github.com/google/liblc3 G2 microphone LC3 decoding uses Google's liblc3: https://github.com/google/liblc3
Even G1 support builds on ScouterKit (MIT License), by the ScouterKit authors:
https://github.com/mafik/scouter_kit. The firmware Faceclaw installs on a G1 is a
modified build of its g1v0, using the Zephyr RTOS and Nordic's nRF Connect SDK; the
parts of it that are Even Realities' own are downloaded from Even, not shipped here.
RayNeo iO support builds on the Glassly SDK and custom firmware by Tetramo, Inc. RayNeo iO support builds on the Glassly SDK and custom firmware by Tetramo, Inc.
and Mentra Labs, Inc. (MIT License): https://github.com/tetramo-labs/glassly and and Mentra Labs, Inc. (MIT License): https://github.com/tetramo-labs/glassly and
https://github.com/tetramo-labs/glassly-rayneo-cfw. The iO wire codecs in https://github.com/tetramo-labs/glassly-rayneo-cfw. The iO wire codecs in
@@ -48,6 +48,10 @@ class AndroidStockLink(context: Context) : StockLink, FaceclawBleListener {
else -> BondState.UNKNOWN else -> BondState.UNKNOWN
} }
override fun negotiatedMtu(address: String): Int = bleManager.getNegotiatedMtu(address)
override fun requestBond(address: String) = bleManager.requestBond(address)
override fun disconnect(address: String) = bleManager.disconnect(address) override fun disconnect(address: String) = bleManager.disconnect(address)
override fun close() = bleManager.close() override fun close() = bleManager.close()
@@ -0,0 +1,87 @@
package com.faceclaw.app
import android.content.Context
import android.os.Handler
import android.os.Looper
/**
* Android host for the shared [G1ArmFlashFlow]: owns the GATT link and the worker thread for one G1 arm's install, or a
* question about what it runs, and delivers listener callbacks on the main thread. For app/native/g1-flasher.ts.
*/
class FaceclawG1Flasher(context: Context, address: String?, side: String?, firmwarePath: String?, mode: String?, connectWindowMs: Int) {
private val link = AndroidStockLink(context.applicationContext)
private val mainHandler = Handler(Looper.getMainLooper())
private val lock = Any()
@Volatile
private var listener: FaceclawFirmwareFlasherListener? = null
@Volatile
private var worker: Thread? = null
private val flow =
G1ArmFlashFlow(
link,
address ?: "",
side ?: "",
firmwarePath ?: "",
G1ArmFlashFlow.mode(mode ?: ""),
connectWindowMs,
object : FaceclawFirmwareFlasherListener {
override fun onLog(line: String?) {
android.util.Log.i(G1ArmFlashFlow.TAG, line ?: "")
post { it.onLog(line) }
}
override fun onProgress(
lens: String?,
componentIndex: Int,
componentCount: Int,
blockIndex: Int,
blockCount: Int,
bytesSent: Long,
bytesTotal: Long,
) = post { it.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount, bytesSent, bytesTotal) }
override fun onState(state: String?, detail: String?) = post { it.onState(state, detail ?: "") }
override fun onComplete(success: Boolean, detail: String?) = post { it.onComplete(success, detail ?: "") }
},
)
fun setListener(listener: FaceclawFirmwareFlasherListener?) {
this.listener = listener
}
fun start() {
synchronized(lock) {
if (worker != null) {
return
}
val w = Thread({ flow.run() }, "faceclaw-g1-flash")
worker = w
w.start()
}
}
fun cancel() {
flow.cancel()
}
fun close() {
cancel()
try {
link.close()
} catch (ignored: Exception) {
}
}
private fun post(action: (FaceclawFirmwareFlasherListener) -> Unit) {
mainHandler.post {
val current = listener
if (current != null) {
action(current)
}
}
}
}
+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+MC4X7qHbjXmo9mFLag0syboZ1Fm/uJhLS3UjjLB7JraygvWZkAH7j8RjpR49Nc6MrIv+gF9Zr3AR8i0ZDbcC4mGAtpBRzU48xmQdckF/BIYoGXgPXrCXArfu6kZIBLlq5l60EC7kovRPGi8RpuKwCyg7HE0V+mS3VPYXEfd2EknSvZQkWaazcB1bGvdvvmrv7CqI+Cj3fx0zd3XN0ruoCESIji4sQPEFqyI+AkyA1fdYe8pqskZBODOVXdpcj7fX87u+czuKG1sdaUebHwAWgplDaybiRId39KMAVnGBC3J8Pvwd8f7iL/gZlyi8gY+oFxFXw3/N05/ddpJ5udhbH6EXGNMix3JATS59jWdxjpZzFsTfisv9Xiet5+hvyhuvNbS0D+mJUAUXZMaqU16nimP+gBsv7LV1c8XPs8yzDMv8zin2cTWGR0cx94nrWsj+0um/mubIW4AaFubbN/JJ5Uojqt3YrlRXdo2bv2a9XfhQe5OPD6q+YMApCuvWVmYZzPWrGL9xOn3xlJnluj5+UGYt298ipN/cfCA9G4sPpucow4oq6qaJdluRzE1OUfiGXPrnLQp7b6yepiUXjUq3dMvPYltNmpM+z19rbL3HritnvfYtZv29LmzWN0OK29+3XKK/jk/GgCdammdXQNuAz0SebZor4EG6b+Y+2ZQHc9j8ss661/Y9rbf+SZu1G5g4f7jHurQb0EvcYt7jZvG8/ZW2J4VGlKHGrhd2osHGm7lzNUKuNQ61mFr3RwxA79w+VTsStWrsJ6+uW+BiF2fTJ12OtEsaiC2kYz1afnf3ZV80G4P0m9Pawb41Fem50K9Iy7NO+f3ahzqDvQGhN4IXWNRbi1GMzmbMf95C0vYeiCM2r7FgoV+PLZ0O4ZDnvOwF2sc0cH5Jd0YWUA5NCSv8Rc7pVA5bysLmiO7mUsN4cWjt4IBzk5WG1KU7JhOND0Hfrjpnmcz/j8YPe7IiNH9IDDxXU+v1DpXOh7GBhN1X415kTz1XjssDDv8bKUtoizME3euKJXWGyqXDmN6yVJU9JvbNm0ieJ/NYeMt7RQ1No0j88h3riyeoeiiDATutCsv6gubybooD67Fd8ZvZTn5U951PxhDGRJwqILIN7hyXg8aQ6iykWUowUBJQV9OJ4kgiHvepUIt9ZzB1a3/zgLLTvDL8k+xVHIkcQqV7zVco8dYye+z5Is8hg5tpcdY5jjrS6ha0S/2nq1KV9t5KcnDx16Y+bj1365VY0Meg1ck8Ekbawj0K43idD9V53NTiqZp93nOQJdJKXqKh/qlkjZw9q2cI+Qiy5d6jkBrGFBXXP8k7Ngsa3+Mc0qSue5ZdrDvAyzVv84/CWmN7inzQZuUKxNinW3iTWXub9lqc7vuOVmrnphTl5rNpxl4PJpY5vtYxnA147tDghmAF2BZed593GbzDtkKafnmirGFhbFa4m9caStmoZzI1TuIPRbfzTpoXSytMTIHe1mKu/lvtW9FFuJJ3XKdOar+aa9VxyUAoYEadZJdMqTQXco4OPcjRFOVX6Dp40r11e5KSX69hjzmw2Vv42oHZPKwG1syF2hY/VJlYRYu37BnUsLonztGK/Dns07Ljb21muvUmDNCot0txaKUcDHTS6B95IawFuy/wMqefkYnmft83R9L+4/TavZS3Ar1jJAZELJ70fOX52HOAJzYv7S1vO1U1peYuntefrElmp34Cmc7yggZrP88AN+2hOI1V7SaD6YaBsh1gfcX93kSLVV6KEXstSTtaZw8ZKHBNLvAF8ftU0VpZ0BtOZPtT6ITFvq/cwjPUpaP0UjOqnXfl6I/cnaOus6W5polg+a6j8a2L5lQMN+3CNhSAdmmwjZ+YZKEMgPTdXzL/Pw4i07IPRO6sy95H6RM4MszClJ9lGWbnbyk1EVk6JNkq38edMMG9yZpTEyRO28X8zgc8xgOwUJ6W+keEcFZIaGUjrcCLtFO7DiJZFulhbfx6iZfI+LCPQk8QmacZpb2thn2SIWnaoxLh9kJv9kcPWGuMx5u2OxpySRHY6ZwPOZnEXBQb4SZh1XJ9As5tbH+UcNONDmf3erGtyZ7gmdzURkCua/y3Wy2m4lyaSPScrdqe+4e1CBMytVWNLpnB2kVqMV8+hIVp+eJ9gp46pENu6KtgPjLJh3FjyVdfwT4lM4cjBWPl/vp/B/SDE4I739dwWSG/7bV8/cm1uhJWdC/wZkMNdEFYNyaIK0t8EuMHxMPudY0PzQZ4wUcaX3ZYya+kcXq9ayp6qrhhAteaSpLVm29EuCWHhVTMqBpKq7gCaw2Eor3mPJbMO8pSpxEsZ2bNTynC9h9kNzcN1J0Pd7P+oeyvU/T78Hrt4xd9XUMYm96Syg7ys8jQvRw+xzze/5MYY9KVL2aNdstswhov83o6tz2ZgHJ8c7ZJXVgzUVmFcYwBPa/gtts6RxSULSFtxlQTLp+PswAN1S6rtQV9iaauvzpEy6xgeS7BBn5iyOGFwG7wXylZeWbRPy1aI1lLHsQLTorLN9tUNyWoHlOwerPQhtydJjv5WJkefAZ9ocCAx3zog7UeIN8NbBmnjq+QI63kFvIOQDn5GxVTbs82neFq/RRZ3Bt5aSwvSgX5pJ5dBLDvJQeQm2XNnoXF72IoB1223VoAdzJWG6GAK+KK3eAj9bvMF68RS76U/biXB8/3k0u8J4MUlXPXqQnT/BRl1erxtLj/OdKxFwxZwgnAL9yBfwWnIP/oT16zuH9no7n/0BaaHTv+ui3y3cubynjhCcXJNf6KYrpqc3CJpBl/jBWLcMR/SnOlCI1+/PKLBYB9RQm19/jLZQG7p4Eu2YswnBWrncD2U+aOH3LGQRVvmsI3FF4A3w+tHVElUHvbRGsaBNHvhba4iKvH6EPtbt1wmN9Ls65dLN5bNXtsMNFJA47o1QzSe5vnKTa2klr7S6JzOvRNFBqsX6TddRhunsORW+orrseklJq5h8CffaT6iMTq2WY7zvIlxH+cjptO8KtvKkdRxePc49GC/rRxB9diXOdYNUWxgm4qHWlw/3GKP4xWZniPIlNPddoxBP4Rh/VCdC5K9p02cLvq2j76y9gmkI7QG0P0nBGTgvS0+E7RDQRvI0OlBE46wHh70ynDeY3EQ7DZLnJdwbG99zJFtX21B3uV2sHbvmriz/BT2MIxdnOcsjzRmNoHdzP7im2J/zLHawrifsvf4LGy/D+vpMD9dl2iNaqxEo+pVTc3lkEV1CHNR6iU07b+TG9svqcyTuT+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 versionsText = `L=${info.leftVersion || "unknown"} R=${info.rightVersion || "unknown"}`;
const required = `Faceclaw firmware revision ${REQUIRED_FACECLAW_FIRMWARE_VERSION}`; 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) { switch (extension.kind) {
case "faceclaw": case "faceclaw":
if (extension.version >= REQUIRED_FACECLAW_FIRMWARE_VERSION) return null; 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); if (pair.mismatchWarning) warnings.push(pair.mismatchWarning);
let armsSummary: string; let armsSummary: string;
let canSelect = false; let canSelect = false;
if (pair.g1Firmware === "stock") { if (pair.completeness !== "complete") {
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") {
armsSummary = pair.completeness === "left-only" armsSummary = pair.completeness === "left-only"
? "Only the left arm has been seen — waiting for the right" ? "Only the left arm has been seen — waiting for the right"
: "Only the right arm has been seen — waiting for the left"; : "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 { } else {
armsSummary = "Left + right arms found. To pair, keep them in the case with the lid open"; armsSummary = "Left + right arms found. To pair, keep them in the case with the lid open";
canSelect = true; 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 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) } forget(address: string): void { ApplicationSettings.remove(`ios.ble.peripheral.${address}`); this.devices.delete(address) }
} }
let instance: IosBluetooth | null = null 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="Conversations" tap="{{ onConversationsTap }}" android.position="popup" />
<ActionItem text="Take screenshot" tap="{{ onTakeScreenshotTap }}" android.position="popup" /> <ActionItem text="Take screenshot" tap="{{ onTakeScreenshotTap }}" android.position="popup" />
<ActionItem text="Record screen" tap="{{ onRecordScreenTap }}" 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" /> <ActionItem text="Uninstall custom firmware" tap="{{ onUninstallFirmwareTap }}" isEnabled="{{ canRun }}" visibility="{{ glassesMenuItemsVisibility }}" android.position="popup" />
</ActionBar> </ActionBar>
+11 -2
View File
@@ -662,6 +662,14 @@ export class MainViewModel extends RemoteControlsViewModel {
* auto-reconnect suppression right away. * auto-reconnect suppression right away.
*/ */
async onPrepareFontsTap(): Promise<void> { async onPrepareFontsTap(): Promise<void> {
await this.openFirmwareCheck();
}
async onCheckFirmwareTap(): Promise<void> {
await this.openFirmwareCheck();
}
private async openFirmwareCheck(): Promise<void> {
this.setWarningsModalVisible(false); this.setWarningsModalVisible(false);
if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") { if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") {
try { try {
@@ -909,8 +917,9 @@ export class MainViewModel extends RemoteControlsViewModel {
} }
private async openFlashPage(mode: "install" | "uninstall"): Promise<void> { private async openFlashPage(mode: "install" | "uninstall"): Promise<void> {
// The flasher needs the glasses to itself, so drop the main connection first. // The flasher needs the glasses to itself, so drop the main connection first. That includes a session
if (this.phase === "connected" || this.phase === "charging") { // still retrying: an install brings arms back at the addresses it is dialling.
if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") {
try { try {
await dashboardController.disconnect(); await dashboardController.disconnect();
} catch { } catch {
@@ -18,11 +18,21 @@ import {
type OnboardingFirmwareKind, type OnboardingFirmwareKind,
} from "../g2/firmware-compat"; } from "../g2/firmware-compat";
import { DeviceInfoProbe, DeviceInfoState } from "../native/device-info-probe"; 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 { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
import { formatErrorMessage } from "../util/format-error"; import { formatErrorMessage } from "../util/format-error";
type CheckPhase = "checking" | "fonts" | "custom" | "flashable" | "newer-validated" | "newer" | "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 { export class OnboardingFirmwareCheckViewModel extends Observable {
private _phase: CheckPhase = "checking"; private _phase: CheckPhase = "checking";
private _headline = "Checking Firmware"; private _headline = "Checking Firmware";
@@ -31,7 +41,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
private generation = 0; private generation = 0;
private probeInstance: DeviceInfoProbe | null = null; private probeInstance: { close(): void } | null = null;
constructor() { constructor() {
super(); super();
@@ -175,6 +185,10 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
try { try {
await ensureBlePermissions(); await ensureBlePermissions();
if (generation !== this.generation) return; if (generation !== this.generation) return;
if (glassesTypeSetting.get() === "g1") {
await this.checkG1(generation);
return;
}
const stored = loadDeviceAddresses(); const stored = loadDeviceAddresses();
if (!isValidMacAddress(stored.right)) { if (!isValidMacAddress(stored.right)) {
this.toError("No glasses address is configured. Go back and set the device addresses."); 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); this.applyClassification(kind, version, extension);
} catch (error) { } catch (error) {
if (generation !== this.generation) return; if (generation !== this.generation) return;
this.probeInstance = null;
this.toError(this.formatError(error)); 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 { private reportProbeState(state: DeviceInfoState, detail: string): void {
// The probe brings up the right lens, then the left, and pairs with each // The probe brings up the right lens, then the left, and pairs with each
// in turn (they are separate Bluetooth devices with separate bonds). // in turn (they are separate Bluetooth devices with separate bonds).
@@ -326,7 +401,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
this.busy = false; this.busy = false;
this.setPhase("custom"); this.setPhase("custom");
this.headline = extractedFonts ? "Fonts Ready" : "Custom Firmware Detected"; this.headline = extractedFonts ? "Fonts Ready" : "Custom Firmware Detected";
const details = [ const details = glassesTypeSetting.get() === "g1" ? [version].filter(Boolean) : [
extension.kind === "faceclaw" ? `revision ${extension.version}` : "", extension.kind === "faceclaw" ? `revision ${extension.version}` : "",
version ? `based on stock ${version}` : "", version ? `based on stock ${version}` : "",
].filter(Boolean); ].filter(Boolean);
+6 -3
View File
@@ -1,5 +1,7 @@
import { NavigatedData, Page } from "@nativescript/core"; 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"; import { FlashMode, OnboardingFlashViewModel } from "./onboarding-flash-view-model";
export function navigatingTo(args: NavigatedData): void { export function navigatingTo(args: NavigatedData): void {
@@ -7,16 +9,17 @@ export function navigatingTo(args: NavigatedData): void {
if (!page.bindingContext) { if (!page.bindingContext) {
const context = const context =
(args.context as { mode?: FlashMode; fromOnboarding?: boolean; autoStart?: boolean } | undefined) ?? undefined; (args.context as { mode?: FlashMode; fromOnboarding?: boolean; autoStart?: boolean } | undefined) ?? undefined;
page.bindingContext = new OnboardingFlashViewModel({ const options = {
mode: context?.mode ?? "install", mode: context?.mode ?? "install",
fromOnboarding: context?.fromOnboarding ?? true, fromOnboarding: context?.fromOnboarding ?? true,
autoStart: context?.autoStart ?? false, autoStart: context?.autoStart ?? false,
}); };
page.bindingContext = glassesTypeSetting.get() === "g1" ? new G1FlashViewModel(options) : new OnboardingFlashViewModel(options);
} }
} }
export function navigatingFrom(args: NavigatedData): void { export function navigatingFrom(args: NavigatedData): void {
const page = args.object as Page; const page = args.object as Page;
(page.bindingContext as OnboardingFlashViewModel | undefined)?.dispose(); (page.bindingContext as OnboardingFlashViewModel | G1FlashViewModel | undefined)?.dispose();
page.bindingContext = null; page.bindingContext = null;
} }
+2 -2
View File
@@ -30,7 +30,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
2: { 2: {
headline: "Before You Continue", headline: "Before You Continue",
tagline: "", 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 : ""), (global.isIOS ? "\n\niOS / TestFlight privacy\n\n" + IOS_PRIVACY_NOTICE : ""),
primaryLabel: "Agree", primaryLabel: "Agree",
secondaryLabel: "Back", secondaryLabel: "Back",
@@ -40,7 +40,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
3: { 3: {
headline: "Custom Firmware Required", headline: "Custom Firmware Required",
tagline: "", 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", primaryLabel: "Flash Firmware",
secondaryLabel: "Preview Only", secondaryLabel: "Preview Only",
splash: false, splash: false,
+1 -8
View File
@@ -358,8 +358,7 @@ export class PairingViewModel extends Observable {
ring: ringAddress, ring: ringAddress,
}; };
saveDeviceAddresses(addresses); saveDeviceAddresses(addresses);
const g1 = !!pair?.g1Firmware; if (pair) glassesTypeSetting.set(pair.g1Firmware ? "g1" : "g2");
if (pair) glassesTypeSetting.set(g1 ? "g1" : "g2");
if (pair) { if (pair) {
savePairedGlassesIdentity({ savePairedGlassesIdentity({
serial: pair.serial ?? "", serial: pair.serial ?? "",
@@ -386,12 +385,6 @@ export class PairingViewModel extends Observable {
this.dispose(); this.dispose();
if (this.onboarding) { if (this.onboarding) {
setPreviewOnlyMode(false); 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. // Continue the onboarding chain: check the glasses' firmware next.
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" }); Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" });
return; return;
@@ -0,0 +1,467 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.jvm.JvmField
class G1FlashTimings(
@JvmField val connectTimeoutMs: Int = ConnectionOptions.CONNECT_TIMEOUT_MS,
@JvmField val servicesTimeoutMs: Int = ConnectionOptions.SERVICES_TIMEOUT_MS,
@JvmField val descriptorTimeoutMs: Int = ConnectionOptions.DESCRIPTOR_TIMEOUT_MS,
@JvmField val writeTimeoutMs: Int = ConnectionOptions.WRITE_TIMEOUT_MS,
/** The OS may be showing its pairing dialog. */
@JvmField val pairingMs: Int = 60_000,
@JvmField val retryDelayMs: Int = 2_000,
@JvmField val controlReplyMs: Int = 1_500,
@JvmField val controlTries: Int = 4,
/** The first chunk of an upload waits for the arm to erase its slot. */
@JvmField val uploadReplyMs: Int = 30_000,
@JvmField val smpReplyMs: Int = 20_000,
/** The arm may go down before its reply leaves. */
@JvmField val resetReplyMs: Int = 5_000,
@JvmField val heartbeatMs: Int = 8_000,
@JvmField val pollMs: Int = 200,
@JvmField val uploadRetries: Int = 40,
)
/**
* Installs an MCUboot image on one G1 arm through MCUmgr SMP, or asks an arm what it runs; a port of scouter_kit's
* g1_firmware/flash.py. The caller handles one arm at a time, left first, and looks for the arm again afterwards: it
* restarts, and coming off Even's firmware it has a new address.
*
* Nothing changes on the arm until the confirm, which comes only after the arm's image list shows that its second slot
* holds exactly this image. MCUboot then overwrites the running firmware with no way back. [run] blocks; the worker thread
* is the host's.
*/
class G1ArmFlashFlow(
private val link: StockLink,
private val address: String,
private val side: String,
private val firmwarePath: String,
private val mode: Mode,
/** How long to keep trying to reach the arm and pair with it. */
private val connectWindowMs: Int,
private val listener: FaceclawFirmwareFlasherListener,
private val timings: G1FlashTimings = G1FlashTimings(),
platform: ProtocolPlatform = protocolPlatform(),
private val readImage: (String) -> ByteArray = ::readFileData,
) : StockLinkListener {
enum class Mode {
/** The arm runs Even's firmware. */
STOCK,
/** The arm runs g1v0: it answers what it runs, and an arm that already has this version is left alone. */
UPDATE,
/** Only say what the arm runs, and pair with it. */
PROBE,
}
companion object {
const val TAG = "FaceclawG1Flash"
private const val MIN_BATTERY_PERCENT = 30
fun mode(name: String): Mode = when (name) {
"stock" -> Mode.STOCK
"update" -> Mode.UPDATE
"probe" -> Mode.PROBE
else -> throw IllegalArgumentException("unknown mode $name")
}
}
private class LinkLostException(message: String) : Exception(message)
/** The arm has no g1v0 service. */
private class NotG1v0Exception : Exception("this arm doesn't run g1v0")
private val platform = platform
private val lock = platform.createLock()
private val sleeper = InterruptibleSleep(platform)
private val assembler = G1Smp.Assembler()
private var smpSeq = -1
private var smpReply: Map<*, *>? = null
private var smpLatch: Latch? = null
private var nextSmpSeq = 0
private var controlTag = -1
private var controlReply: G1Protocol.Reply? = null
private var controlLatch: Latch? = null
private var nextControlTag = 0
private var linkLost = false
private var heartbeats = 0
private var nextHeartbeatAtMs = 0L
@Volatile
private var cancelled = false
fun cancel() {
cancelled = true
lock.withLock {
smpLatch?.countDown()
controlLatch?.countDown()
}
sleeper.interrupt()
}
fun run() {
link.setListener(this)
try {
if (mode == Mode.PROBE) probe() else install()
} catch (e: Exception) {
val message = if (cancelled) "Cancelled." else StockLinkSession.messageOf(e)
log("failed: $message")
listener.onState("error", message)
listener.onComplete(false, message)
} finally {
quietly { link.disconnect(address) }
}
}
private fun probe() {
listener.onState("connecting", side)
try {
bringUp()
} catch (e: NotG1v0Exception) {
listener.onComplete(true, """{"firmware":"stock"}""")
return
}
listener.onState("checking", side)
val hello = hello()
listener.onComplete(true, """{"firmware":"g1v0","version":"${hello.version}","safeMode":${hello.safeMode},"inCase":${hello.inCase},"battery":${batteryPercent()}}""")
}
private fun install() {
listener.onState("validating", side)
val image = try {
readImage(firmwarePath)
} catch (e: Exception) {
throw IllegalStateException("could not read the firmware: " + StockLinkSession.messageOf(e), e)
}
val version = G1Smp.imageVersion(image)
val hash = G1Smp.imageHash(image)
log("image $version, ${image.size} bytes, hash ${BinaryEncoding.bytesToHex(hash.copyOf(8))}")
listener.onState("connecting", side)
bringUp()
if (mode == Mode.UPDATE) {
listener.onState("checking", side)
val hello = hello()
log("runs g1v0 ${hello.version}, safe mode ${hello.safeMode}, in the case ${hello.inCase}, encrypted ${hello.encrypted}")
if (hello.version == version && !hello.safeMode) {
listener.onComplete(true, """{"flashed":false,"version":"$version"}""")
return
}
val battery = batteryPercent()
if (battery != null && battery < MIN_BATTERY_PERCENT) {
throw IllegalStateException("The $side arm's battery is at $battery%, too low to install safely. " +
"Charge both arms to at least $MIN_BATTERY_PERCENT% in the case, then try again.")
}
}
val slots = retrying { images() }
for (slot in slots) log(slot.toString())
listener.onState("flashing", side)
if (holdsImage(slots, hash)) {
log("the second slot already holds this image")
listener.onProgress(side, 1, 1, image.size, image.size, image.size.toLong(), image.size.toLong())
} else {
val startedAt = now()
upload(image)
log("uploaded in ${(now() - startedAt) / 1000} s")
}
if (!holdsImage(retrying { images() }, hash)) {
throw IllegalStateException("The $side arm's second slot doesn't hold the image after the upload. Nothing was installed.")
}
throwIfCancelled()
listener.onState("committing", side)
val confirm = smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(hash), timings.smpReplyMs)
val code = G1Smp.replyCode(confirm)
if (code != 0) throw IllegalStateException("The $side arm refused the image (error $code). Nothing was installed.")
log("confirmed: MCUboot installs it at the next boot")
try {
smp(G1Smp.OP_WRITE, G1Smp.GROUP_OS, G1Smp.CMD_OS_RESET, emptyMap(), timings.resetReplyMs)
} catch (e: StockTimeoutException) {
log("no answer to the reset")
} catch (e: LinkLostException) {
log("the link went down with the reset")
}
listener.onState("rebooting", side)
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
}
private fun holdsImage(slots: List<G1Smp.Slot>, hash: ByteArray): Boolean =
slots.any { it.image == 0 && it.slot == 1 && it.hash.contentEquals(hash) }
private fun images(): List<G1Smp.Slot> =
G1Smp.parseSlots(smp(G1Smp.OP_READ, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, emptyMap(), timings.smpReplyMs))
/** MCUmgr answers each chunk with the offset it wants next, so an upload resumes after a lost link. */
private fun upload(image: ByteArray) {
val fileSha = sha256(image)
var offset = 0
var failures = 0
while (offset < image.size) {
throwIfCancelled()
val reply = try {
smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_UPLOAD, G1Smp.uploadRequest(image, offset, fileSha), timings.uploadReplyMs)
} catch (e: Exception) {
if (e !is StockTimeoutException && e !is LinkLostException) throw e
failures++
if (failures > timings.uploadRetries) throw e
log("chunk at $offset failed (${e.message}), trying again")
reconnectIfNeeded()
continue
}
val code = G1Smp.replyCode(reply)
val next = G1Smp.replyOffset(reply)
if (code != 0 || next == null || next < 0 || next > image.size) {
throw IllegalStateException("The $side arm refused the upload at $offset (error $code). Nothing was installed.")
}
offset = next
listener.onProgress(side, 1, 1, offset, image.size, offset.toLong(), image.size.toLong())
}
}
private fun <T> retrying(request: () -> T): T {
var attempt = 0
while (true) {
try {
return request()
} catch (e: Exception) {
if (e !is StockTimeoutException && e !is LinkLostException) throw e
attempt++
if (attempt >= 10) throw e
log("request failed (${e.message}), trying again")
reconnectIfNeeded()
}
}
}
private fun reconnectIfNeeded() {
throwIfCancelled()
lock.withLock { assembler.reset() }
if (!link.isConnected(address)) bringUp()
}
// ---- the link ------------------------------------------------------------
private fun bringUp() {
val deadline = now() + connectWindowMs
var attempt = 0
while (true) {
throwIfCancelled()
attempt++
val failure = try {
connectOnce()
log("connected (attempt $attempt)")
return
} catch (e: NotG1v0Exception) {
throw e
} catch (e: Exception) {
StockLinkSession.messageOf(e)
}
log("connect attempt $attempt failed: $failure")
quietly { link.disconnect(address) }
if (now() >= deadline) {
throw IllegalStateException("Couldn't reach the $side arm: $failure." + if (mode == Mode.STOCK) {
" If this phone was paired with these glasses before, remove them from its Bluetooth settings and try again."
} else {
""
})
}
sleeper.sleep(timings.retryDelayMs.toLong())
}
}
private fun connectOnce() {
if (!link.connect(address, timings.connectTimeoutMs)) throw IllegalStateException("connect failed")
lock.withLock {
linkLost = false
assembler.reset()
}
link.prepareLink(address, G1Ble.REQUESTED_MTU, timings.connectTimeoutMs)
if (!link.discoverServices(address, timings.servicesTimeoutMs)) throw IllegalStateException("service discovery failed")
if (mode == Mode.STOCK) {
// Even's firmware serves its own service only on an encrypted link, and the heartbeat goes there.
settleBond()
if (!link.enableNotifications(address, G1Smp.NUS_TX_UUID, timings.descriptorTimeoutMs)) {
throw IllegalStateException("no link to Even's service")
}
heartbeats = 0
nextHeartbeatAtMs = 0
} else {
if (!link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, timings.descriptorTimeoutMs)) {
if (!link.isConnected(address)) throw LinkLostException("the link went down")
throw NotG1v0Exception()
}
// Out of the case the arm obeys only an encrypted link.
settleBond()
val paired = try {
link.writeFrames(address, G1Ble.PAIR_CHAR_UUID, listOf(byteArrayOf(1)), GattWriteMode.WITH_RESPONSE, timings.pairingMs)
} catch (e: IllegalStateException) {
false
}
if (!paired) throw IllegalStateException("no encrypted link: an arm pairs only in its case")
}
if (mode != Mode.PROBE && !link.enableNotifications(address, G1Smp.SMP_CHAR_UUID, timings.descriptorTimeoutMs)) {
throw IllegalStateException("no update service")
}
}
/** Asks the OS to pair if it hasn't, and waits for that to end; a platform that doesn't say pairs by itself. */
private fun settleBond() {
if (link.bondState(address) == BondState.NONE) {
listener.onState("pairing", side)
link.requestBond(address)
}
val deadline = now() + timings.pairingMs
var sawBonding = false
while (true) {
throwIfCancelled()
when (link.bondState(address)) {
BondState.BONDED, BondState.UNKNOWN -> return
BondState.BONDING -> sawBonding = true
BondState.NONE -> if (sawBonding) throw IllegalStateException("pairing was refused")
}
if (!link.isConnected(address)) throw LinkLostException("the link went down while pairing")
if (now() >= deadline) throw IllegalStateException("pairing took too long")
sleeper.sleep(timings.pollMs.toLong())
}
}
private fun heartbeatIfDue() {
if (mode != Mode.STOCK || now() < nextHeartbeatAtMs) return
val seq = heartbeats % 0xff
heartbeats++
nextHeartbeatAtMs = now() + timings.heartbeatMs
try {
link.writeFrames(address, G1Smp.NUS_RX_UUID, listOf(G1Smp.stockHeartbeat(seq)), GattWriteMode.WITHOUT_RESPONSE, timings.writeTimeoutMs)
} catch (e: IllegalStateException) {
// The request waiting now finds out.
}
}
private fun smp(op: Int, group: Int, cmd: Int, payload: Map<String, Any?>, timeoutMs: Int): Map<*, *> {
val seq = nextSmpSeq
nextSmpSeq = (nextSmpSeq + 1) and 0xff
val latch = Latch(1, platform)
lock.withLock {
smpSeq = seq
smpReply = null
smpLatch = latch
}
try {
heartbeatIfDue()
val frames = G1Smp.split(G1Smp.frame(op, group, seq, cmd, payload), link.negotiatedMtu(address))
val written = try {
link.writeFrames(address, G1Smp.SMP_CHAR_UUID, frames, GattWriteMode.WITHOUT_RESPONSE, timings.writeTimeoutMs)
} catch (e: IllegalStateException) {
false
}
if (!written) throw LinkLostException("write failed")
val deadline = now() + timeoutMs
while (true) {
throwIfCancelled()
heartbeatIfDue()
val remaining = deadline - now()
if (remaining <= 0) throw StockTimeoutException("no answer from the $side arm within $timeoutMs ms")
latch.await(minOf(remaining, timings.pollMs.toLong()))
val (reply, lost) = lock.withLock { smpReply to linkLost }
if (reply != null) return reply
if (lost) throw LinkLostException("the link went down")
}
} finally {
lock.withLock {
if (smpLatch === latch) smpLatch = null
}
}
}
private fun control(op: Int, body: ByteArray = ByteArray(0)): G1Protocol.Reply {
repeat(timings.controlTries) {
val tag = nextControlTag % 255 + 1
nextControlTag = tag
val latch = Latch(1, platform)
lock.withLock {
controlTag = tag
controlReply = null
controlLatch = latch
}
val written = try {
link.writeFrames(address, G1Ble.CTRL_CHAR_UUID, listOf(G1Protocol.control(op, tag, body)), GattWriteMode.WITHOUT_RESPONSE, timings.writeTimeoutMs)
} catch (e: IllegalStateException) {
false
}
if (!written) throw LinkLostException("write failed")
latch.await(timings.controlReplyMs.toLong())
throwIfCancelled()
val (reply, lost) = lock.withLock {
controlLatch = null
controlReply to linkLost
}
if (reply != null) return reply
if (lost) throw LinkLostException("the link went down")
}
throw StockTimeoutException("no answer to request $op from the $side arm")
}
private fun hello(): G1Protocol.Hello {
val reply = control(G1Protocol.OP_HELLO)
return G1Protocol.parseHello(reply.body) ?: throw IllegalStateException("The $side arm's firmware isn't one this app knows.")
}
/** Null when the arm doesn't know yet, or a firmware doesn't say. */
private fun batteryPercent(): Int? {
val reply = control(G1Protocol.OP_PROPS, byteArrayOf(G1Protocol.PROP_BATT_PCT.toByte()))
if (reply.status != 0) return null
val value = G1Protocol.parseProps(reply.body, 1)?.get(0) ?: return null
return if (value in 0..100) value else null
}
private fun throwIfCancelled() {
if (cancelled) throw IllegalStateException("Cancelled.")
}
private fun now(): Long = platform.elapsedRealtimeMs()
private fun log(line: String) = listener.onLog("$side arm: $line")
private inline fun quietly(action: () -> Unit) {
try {
action()
} catch (ignored: Exception) {
}
}
// ---- inbound -------------------------------------------------------------
override fun onNotification(address: String, characteristicUuid: String, data: ByteArray) {
if (characteristicUuid.equals(G1Smp.SMP_CHAR_UUID, ignoreCase = true)) {
lock.withLock {
for ((seq, body) in assembler.feed(data)) {
if (seq == smpSeq) {
smpReply = body
smpLatch?.countDown()
}
}
}
} else if (characteristicUuid.equals(G1Ble.EVT_CHAR_UUID, ignoreCase = true)) {
val reply = G1Protocol.parseReply(data) ?: return
lock.withLock {
if (reply.tag == controlTag) {
controlReply = reply
controlLatch?.countDown()
}
}
}
}
override fun onConnectionStateChange(address: String, connected: Boolean) {
if (connected) return
lock.withLock {
linkLost = true
smpLatch?.countDown()
controlLatch?.countDown()
}
}
}
@@ -11,6 +11,19 @@ object G1Ble {
/** Faceclaw's records (VM.md §6.11). */ /** Faceclaw's records (VM.md §6.11). */
const val FC_CHAR_UUID = "f3da4d59-277a-4fc9-a1ed-41c9c22d4405" const val FC_CHAR_UUID = "f3da4d59-277a-4fc9-a1ed-41c9c22d4405"
const val REQUESTED_MTU = 247 const val REQUESTED_MTU = 247
/** The oldest firmware this app works with: `PROP_SET` came in here. */
const val REQUIRED_FIRMWARE = "0.5.63"
/** Dotted versions, component by component. */
fun firmwareAtLeast(version: String, required: String = REQUIRED_FIRMWARE): Boolean {
val have = version.split(".").map { it.toIntOrNull() ?: 0 }
val want = required.split(".").map { it.toIntOrNull() ?: 0 }
for (i in 0 until maxOf(have.size, want.size)) {
val delta = have.getOrElse(i) { 0 } - want.getOrElse(i) { 0 }
if (delta != 0) return delta > 0
}
return true
}
} }
/** /**
@@ -0,0 +1,291 @@
package com.faceclaw.app
import kotlin.jvm.JvmField
/** The part of CBOR that MCUmgr uses: integers, byte and text strings, arrays, maps, booleans and null. */
object G1Cbor {
fun encode(value: Any?): ByteArray {
val out = Output()
write(out, value)
return out.toByteArray()
}
fun decode(data: ByteArray, start: Int = 0): Any? = Reader(data, start).value()
private class Output {
private var bytes = ByteArray(256)
private var size = 0
private fun reserve(extra: Int) {
if (size + extra > bytes.size) bytes = bytes.copyOf(maxOf(bytes.size * 2, size + extra))
}
fun add(byte: Int) {
reserve(1)
bytes[size++] = byte.toByte()
}
fun add(data: ByteArray) {
reserve(data.size)
data.copyInto(bytes, size)
size += data.size
}
fun toByteArray(): ByteArray = bytes.copyOf(size)
}
private fun head(out: Output, major: Int, n: Long) {
val first = major shl 5
val width = when {
n < 24 -> {
out.add(first or n.toInt())
return
}
n < 0x100L -> 1
n < 0x10000L -> 2
n < 0x100000000L -> 4
else -> 8
}
out.add(first or (24 + width.countTrailingZeroBits()))
for (i in width - 1 downTo 0) out.add(((n ushr (8 * i)) and 0xff).toInt())
}
private fun write(out: Output, value: Any?) {
when (value) {
null -> out.add(0xf6)
is Boolean -> out.add(if (value) 0xf5 else 0xf4)
is Int -> write(out, value.toLong())
is Long -> if (value >= 0) head(out, 0, value) else head(out, 1, -1 - value)
is ByteArray -> {
head(out, 2, value.size.toLong())
out.add(value)
}
is String -> {
val text = value.encodeToByteArray()
head(out, 3, text.size.toLong())
out.add(text)
}
is List<*> -> {
head(out, 4, value.size.toLong())
for (item in value) write(out, item)
}
is Map<*, *> -> {
head(out, 5, value.size.toLong())
for ((key, item) in value) {
write(out, key)
write(out, item)
}
}
else -> throw IllegalArgumentException("not CBOR: $value")
}
}
private class Reader(private val data: ByteArray, private var at: Int) {
private fun u8(): Int {
if (at >= data.size) throw IllegalArgumentException("CBOR cut short")
return data[at++].toInt() and 0xff
}
fun value(): Any? {
val first = u8()
val major = first ushr 5
val info = first and 31
val n: Long? = when {
info < 24 -> info.toLong()
info in 24..27 -> {
var v = 0L
repeat(1 shl (info - 24)) { v = (v shl 8) or u8().toLong() }
v
}
info == 31 -> null
else -> throw IllegalArgumentException("bad CBOR header $first")
}
return when (major) {
0 -> n ?: throw IllegalArgumentException("bad CBOR integer")
1 -> -1 - (n ?: throw IllegalArgumentException("bad CBOR integer"))
2, 3 -> {
val size = (n ?: throw IllegalArgumentException("indefinite CBOR string")).toInt()
if (size < 0 || at + size > data.size) throw IllegalArgumentException("CBOR cut short")
val bytes = data.copyOfRange(at, at + size)
at += size
if (major == 2) bytes else bytes.decodeToString()
}
4 -> {
val items = ArrayList<Any?>()
while (more(n, items.size)) items.add(value())
if (n == null) at++
items
}
5 -> {
val items = LinkedHashMap<Any?, Any?>()
while (more(n, items.size)) {
val key = value()
items[key] = value()
}
if (n == null) at++
items
}
7 -> when (info) {
20 -> false
21 -> true
22 -> null
else -> throw IllegalArgumentException("unsupported CBOR simple value $info")
}
else -> throw IllegalArgumentException("unsupported CBOR major type $major")
}
}
/** An indefinite-length array or map (what Zephyr's image list uses) ends at a 0xFF. */
private fun more(n: Long?, count: Int): Boolean {
if (n != null) return count < n
if (at >= data.size) throw IllegalArgumentException("CBOR cut short")
return (data[at].toInt() and 0xff) != 0xff
}
}
}
/**
* MCUmgr SMP, the update service of both Even's firmware and g1v0: as much of it as installing an image takes, and what
* an MCUboot image says about itself. The same requests as scouter_kit's tools/g1host.py (class Smp), which was proven on
* real arms first.
*/
object G1Smp {
const val SMP_CHAR_UUID = "da2e7828-fbce-4e01-ae9e-261174997c48"
const val NUS_RX_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
const val NUS_TX_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
const val OP_READ = 0
const val OP_WRITE = 2
const val GROUP_OS = 0
const val GROUP_IMAGE = 1
const val CMD_IMAGE_STATE = 0
const val CMD_IMAGE_UPLOAD = 1
const val CMD_OS_RESET = 5
const val UPLOAD_CHUNK = 2048
private const val HEADER = 8
/** Even's firmware drops a link it hears no heartbeat on. */
fun stockHeartbeat(seq: Int): ByteArray =
byteArrayOf(0x25, 0x06, 0x00, seq.toByte(), 0x04, seq.toByte())
fun frame(op: Int, group: Int, seq: Int, cmd: Int, payload: Map<String, Any?>): ByteArray {
val body = G1Cbor.encode(payload)
val out = ByteArray(HEADER + body.size)
out[0] = op.toByte()
out[2] = (body.size ushr 8).toByte()
out[3] = body.size.toByte()
out[4] = (group ushr 8).toByte()
out[5] = group.toByte()
out[6] = seq.toByte()
out[7] = cmd.toByte()
body.copyInto(out, HEADER)
return out
}
/** One ATT write at most [mtu] - 3 bytes long; MCUmgr joins them again. */
fun split(frame: ByteArray, mtu: Int): List<ByteArray> {
val size = maxOf(mtu - 3, 20)
return (frame.indices step size).map { frame.copyOfRange(it, minOf(it + size, frame.size)) }
}
/** The first chunk also says what is coming, which lets the arm resume an upload of the same file. */
fun uploadRequest(image: ByteArray, offset: Int, fileSha256: ByteArray): Map<String, Any?> {
val data = image.copyOfRange(offset, minOf(offset + UPLOAD_CHUNK, image.size))
return if (offset == 0) {
mapOf("image" to 0, "len" to image.size, "off" to 0, "sha" to fileSha256, "data" to data, "upgrade" to false)
} else {
mapOf("off" to offset, "data" to data)
}
}
fun confirmRequest(imageHash: ByteArray): Map<String, Any?> = mapOf("hash" to imageHash, "confirm" to true)
/** Joins notifications into replies; [feed] gives each complete one as sequence number and body. */
class Assembler {
private var pending = ByteArray(0)
fun reset() {
pending = ByteArray(0)
}
fun feed(data: ByteArray): List<Pair<Int, Map<*, *>>> {
pending += data
val replies = ArrayList<Pair<Int, Map<*, *>>>()
while (pending.size >= HEADER) {
val size = ((pending[2].toInt() and 0xff) shl 8) or (pending[3].toInt() and 0xff)
if (pending.size < HEADER + size) break
val seq = pending[6].toInt() and 0xff
val body = try {
if (size == 0) emptyMap<Any?, Any?>() else G1Cbor.decode(pending, HEADER) as? Map<*, *>
} catch (e: IllegalArgumentException) {
null
}
if (body == null) {
// A frame cut by a lost link: the request is sent again.
pending = ByteArray(0)
break
}
pending = pending.copyOfRange(HEADER + size, pending.size)
replies.add(seq to body)
}
return replies
}
}
class Slot(
@JvmField val image: Int,
@JvmField val slot: Int,
@JvmField val version: String,
@JvmField val hash: ByteArray,
@JvmField val flags: List<String>,
) {
override fun toString(): String =
"image $image slot $slot: $version ${BinaryEncoding.bytesToHex(hash.copyOf(minOf(8, hash.size)))} ${flags.joinToString(" ")}".trim()
}
fun parseSlots(reply: Map<*, *>): List<Slot> {
val images = reply["images"] as? List<*> ?: return emptyList()
return images.mapNotNull { item ->
val entry = item as? Map<*, *> ?: return@mapNotNull null
val hash = entry["hash"] as? ByteArray ?: return@mapNotNull null
Slot((entry["image"] as? Long ?: 0L).toInt(), (entry["slot"] as? Long ?: -1L).toInt(), entry["version"] as? String ?: "?", hash,
listOf("bootable", "pending", "confirmed", "active", "permanent").filter { entry[it] == true })
}
}
fun replyCode(reply: Map<*, *>): Int = (reply["rc"] as? Long ?: 0L).toInt()
fun replyOffset(reply: Map<*, *>): Int? = (reply["off"] as? Long)?.toInt()
/** The dotted version in an MCUboot header. */
fun imageVersion(image: ByteArray): String {
requireImage(image)
val revision = (image[22].toInt() and 0xff) or ((image[23].toInt() and 0xff) shl 8)
return "${image[20].toInt() and 0xff}.${image[21].toInt() and 0xff}.$revision"
}
/** The SHA-256 TLV: how MCUmgr names an image. */
fun imageHash(image: ByteArray): ByteArray {
requireImage(image)
var at = u16(image, 8) + u32(image, 12)
require(at + 4 <= image.size && u16(image, at) == 0x6907) { "the image has no TLV area" }
val end = at + u16(image, at + 2)
require(end <= image.size) { "the image's TLV area is cut short" }
at += 4
while (at + 4 <= end) {
val type = u16(image, at)
val size = u16(image, at + 2)
if (type == 0x10 && size == 32 && at + 4 + size <= end) return image.copyOfRange(at + 4, at + 4 + size)
at += 4 + size
}
throw IllegalArgumentException("the image has no SHA-256 TLV")
}
private fun requireImage(image: ByteArray) {
require(image.size > 32 && u32(image, 0) == 0x96f3b83d.toInt()) { "not an MCUboot image" }
}
private fun u16(data: ByteArray, at: Int): Int = (data[at].toInt() and 0xff) or ((data[at + 1].toInt() and 0xff) shl 8)
private fun u32(data: ByteArray, at: Int): Int = u16(data, at) or (u16(data, at + 2) shl 16)
}
@@ -48,6 +48,12 @@ interface StockLink {
fun bondState(address: String): BondState fun bondState(address: String): BondState
/** The ATT MTU agreed on this link. */
fun negotiatedMtu(address: String): Int = 23
/** Ask the OS to pair with a connected device; a platform that pairs by itself on demand does nothing. */
fun requestBond(address: String) {}
fun disconnect(address: String) fun disconnect(address: String)
fun close() fun close()
@@ -94,6 +94,8 @@ internal object G1Timings {
const val LENS_RIGHT = 2 const val LENS_RIGHT = 2
} }
/** What the Install prompt says an arm runs when it isn't g1v0. */
private const val G1_OTHER_FIRMWARE = "Even's firmware"
private val G1_PROPS = intArrayOf(G1Protocol.PROP_BATT_PCT, G1Protocol.PROP_CHARGE, G1Protocol.PROP_IN_CASE, G1Protocol.PROP_WORN) private val G1_PROPS = intArrayOf(G1Protocol.PROP_BATT_PCT, G1Protocol.PROP_CHARGE, G1Protocol.PROP_IN_CASE, G1Protocol.PROP_WORN)
private val G1_LIGHT = intArrayOf(G1Protocol.PROP_LIGHT) private val G1_LIGHT = intArrayOf(G1Protocol.PROP_LIGHT)
private val G1_IMU = intArrayOf(G1Protocol.PROP_ACC_X, G1Protocol.PROP_ACC_Y, G1Protocol.PROP_ACC_Z) private val G1_IMU = intArrayOf(G1Protocol.PROP_ACC_X, G1Protocol.PROP_ACC_Y, G1Protocol.PROP_ACC_Z)
@@ -421,6 +423,9 @@ internal fun GlassesSessionCore.g1HideBeforeDisconnect() {
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// Connect (worker thread) // Connect (worker thread)
/** The arm has no g1v0 service: it runs Even's firmware. */
private class G1OtherFirmwareException : Exception("not g1v0 firmware")
private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) { private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) {
val address = g1ArmAddress(arm) val address = g1ArmAddress(arm)
val timeoutMs = maxOf(deadlineMs - now(), ConnectionOptions.CONNECT_TIMEOUT_MS.toLong()) val timeoutMs = maxOf(deadlineMs - now(), ConnectionOptions.CONNECT_TIMEOUT_MS.toLong())
@@ -433,7 +438,8 @@ private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) {
throw IllegalStateException("discoverServices failed: $address") throw IllegalStateException("discoverServices failed: $address")
} }
if (!link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) { if (!link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) {
throw IllegalStateException("no event characteristic on $address: not g1v0 firmware?") if (!link.isConnected(address)) throw IllegalStateException("link lost: $address")
throw G1OtherFirmwareException()
} }
link.requestLe2mPhy(address) link.requestLe2mPhy(address)
monitor.withLock { monitor.withLock {
@@ -495,9 +501,9 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
logLine("G1 " + (if (arm == 0) "left" else "right") + " arm: " + versions[arm] logLine("G1 " + (if (arm == 0) "left" else "right") + " arm: " + versions[arm]
+ " display path " + fcVersion + " encrypted=" + hello.encrypted + " inCase=" + hello.inCase + " display path " + fcVersion + " encrypted=" + hello.encrypted + " inCase=" + hello.inCase
+ " panelOk=" + hello.panelOk + " phy=" + link.describePhy(g1ArmAddress(arm))) + " panelOk=" + hello.panelOk + " phy=" + link.describePhy(g1ArmAddress(arm)))
compatible = compatible && fcVersion >= 1 compatible = compatible && fcVersion >= 1 && G1Ble.firmwareAtLeast(hello.version)
} }
// The firmware's own number, not the G2 custom firmware's: the path has one version so far, and TS compares this. // Not the G2 custom firmware's revision: this firmware has its own version, compared here, and TS compares this.
val firmware = BleProtocol.FirmwareInfo(versions[0], versions[1], val firmware = BleProtocol.FirmwareInfo(versions[0], versions[1],
if (compatible) BleProtocol.FirmwareInfo.FACECLAW_EXTENSION_PREFIX + requiredFirmwareRevision else "") if (compatible) BleProtocol.FirmwareInfo.FACECLAW_EXTENSION_PREFIX + requiredFirmwareRevision else "")
emitFirmwareInfo(firmware) emitFirmwareInfo(firmware)
@@ -533,6 +539,11 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
} }
setStateDisplay("connected", "Connected.") setStateDisplay("connected", "Connected.")
interruptibleSleep.interrupt() interruptibleSleep.interrupt()
} catch (t: G1OtherFirmwareException) {
logLine("G1: an arm runs Even's firmware")
val firmware = BleProtocol.FirmwareInfo(G1_OTHER_FIRMWARE, G1_OTHER_FIRMWARE, "")
emitFirmwareInfo(firmware)
monitor.withLock { incompatibleFirmware = firmware }
} catch (t: Throwable) { } catch (t: Throwable) {
logLine("G1 connect failed: " + safeMessage(t)) logLine("G1 connect failed: " + safeMessage(t))
val unpaired = firstUnpairedArm() val unpaired = firstUnpairedArm()
@@ -461,6 +461,9 @@ class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform
override fun isBonded(address: String): Boolean = true override fun isBonded(address: String): Boolean = true
/** CoreBluetooth pairs by itself when an attribute needs it. */
override fun requestBond(address: String) {}
override fun prepareBenchmarkLink(address: String, mode: Int) {} override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() { override fun recordDisplayFrameSent() {
@@ -171,3 +171,56 @@ class IosFirmwareFlasher(rightAddress: String, leftAddress: String, firmwarePath
lock.withLock { listener }?.let(action) lock.withLock { listener }?.let(action)
} }
} }
/** iOS host for the shared [G1ArmFlashFlow]: one G1 arm's install, or a question about what it runs. */
class IosG1Flasher(address: String, side: String, firmwarePath: String, mode: String, connectWindowMs: Int) {
private val link = IosBleCentral()
private val lock = IosProtocolPlatform.createLock()
private var started = false
private var listener: FaceclawFirmwareFlasherListener? = null
private val flow = G1ArmFlashFlow(
link,
address,
side,
firmwarePath,
G1ArmFlashFlow.mode(mode),
connectWindowMs,
object : FaceclawFirmwareFlasherListener {
override fun onLog(line: String?) {
PlatformLog.i(G1ArmFlashFlow.TAG, line ?: "")
post { it.onLog(line) }
}
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) =
post { it.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount, bytesSent, bytesTotal) }
override fun onState(state: String?, detail: String?) = post { it.onState(state, detail ?: "") }
override fun onComplete(success: Boolean, detail: String?) = post { it.onComplete(success, detail ?: "") }
},
)
fun setListener(listener: FaceclawFirmwareFlasherListener?) {
lock.withLock { this.listener = listener }
}
fun start() {
lock.withLock {
if (started) return
started = true
}
runOnThread("faceclaw-g1-flash") { flow.run() }
}
fun cancel() = flow.cancel()
fun close() {
cancel()
runCatching { link.close() }
}
private fun post(action: (FaceclawFirmwareFlasherListener) -> Unit) = main {
lock.withLock { listener }?.let(action)
}
}
+14
View File
@@ -74,3 +74,17 @@ test("reportedFirmwareVersion picks the higher arm", () => {
assert.equal(compat.reportedFirmwareVersion(info("", "", "2.2.9.22")), "2.2.9.22"); assert.equal(compat.reportedFirmwareVersion(info("", "", "2.2.9.22")), "2.2.9.22");
assert.equal(compat.reportedFirmwareVersion(info("", "", "")), ""); assert.equal(compat.reportedFirmwareVersion(info("", "", "")), "");
}); });
test("a G1's report names what the arms run and offers the install, stock or too old", () => {
const stock = compat.firmwareIncompatibilityMessage(info("", "Even's firmware", "Even's firmware"));
assert.match(stock, /G1/);
assert.match(stock, /Even's firmware/);
assert.match(stock, /install/);
assert.doesNotMatch(stock, /revision/);
const older = compat.firmwareIncompatibilityMessage(info("", "g1v0 0.5.62", "g1v0 0.5.63"));
assert.match(older, /L=g1v0 0\.5\.62 R=g1v0 0\.5\.63/);
assert.match(older, /install/);
// A compatible G1 reports the extension, and a G2's stock report is unchanged.
assert.equal(compat.firmwareIncompatibilityMessage(info(`Faceclaw/${REQUIRED}`, "g1v0 0.5.63", "g1v0 0.5.63")), null);
assert.match(compat.firmwareIncompatibilityMessage(info("")), /stock firmware/);
});
+169
View File
@@ -0,0 +1,169 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const zlib = require('node:zlib');
const { readZipEntry, assembleG1Image, decodeG1OwnBytes, G1FirmwareError } = require('../.test-build/app/g1/firmware-image.js');
const plan = require('../.test-build/app/g1/flash-plan.js');
const { G1V0_IMAGE } = require('../.test-build/app/g1/firmware/g1v0-image.js');
const { G1V0_OWN_BYTES_BASE64 } = require('../.test-build/app/g1/firmware/g1v0-own-bytes.js');
const sha = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
const noise = (length, seed) => Uint8Array.from({ length }, (_, i) => (i * 31 + seed * 17 + (i >> 3)) & 0xff);
const fromBase64 = (text) => new Uint8Array(Buffer.from(text, 'base64'));
/** A zip the way Even's are made: one entry stored, the others deflated, under a folder. */
function zipOf(entries) {
const locals = [];
const directory = [];
let offset = 0;
for (const { name, data, deflate } of entries) {
const packed = deflate ? zlib.deflateRawSync(data) : Buffer.from(data);
const nameBytes = Buffer.from(name);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(deflate ? 8 : 0, 8);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(nameBytes.length, 26);
const central = Buffer.alloc(46);
central.writeUInt32LE(0x02014b50, 0);
central.writeUInt16LE(deflate ? 8 : 0, 10);
central.writeUInt32LE(packed.length, 20);
central.writeUInt32LE(data.length, 24);
central.writeUInt16LE(nameBytes.length, 28);
central.writeUInt32LE(offset, 42);
locals.push(local, nameBytes, packed);
directory.push(central, nameBytes);
offset += local.length + nameBytes.length + packed.length;
}
const centralBytes = Buffer.concat(directory);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(entries.length, 8);
end.writeUInt16LE(entries.length, 10);
end.writeUInt32LE(centralBytes.length, 12);
end.writeUInt32LE(offset, 16);
return new Uint8Array(Buffer.concat([...locals, centralBytes, end]));
}
function fixture() {
const net = noise(5000, 1);
const app = noise(9000, 2);
const image = noise(20000, 3);
const table = app.subarray(4000, 4352);
image.set(net, 3000);
image.set(table, 12000);
const parts = [
{ offset: 3000, length: net.length, file: 'net.bin', fileOffset: 0, sha256: sha(net) },
{ offset: 12000, length: table.length, file: 'app.bin', fileOffset: 4000, sha256: sha(table) },
];
const own = Buffer.concat([image.subarray(0, 3000), image.subarray(8000, 12000), image.subarray(12352)]);
const manifest = { version: '0.0.1', sha256: sha(image), size: image.length, source: 't', stockVersion: 's', stockZipUrl: 'u', stockZipSha256: 'z', parts };
return { net, app, image, own: new Uint8Array(own), manifest };
}
test('a zip entry is found, deflated or stored, also under a folder', () => {
const stored = noise(300, 4);
const packed = noise(70000, 5);
const zip = zipOf([{ name: 'manifest.json', data: stored }, { name: 'firmware/app.bin', data: packed, deflate: true }]);
assert.deepEqual(readZipEntry(zip, 'manifest.json'), stored);
assert.deepEqual(Buffer.from(readZipEntry(zip, 'app.bin')), Buffer.from(packed));
assert.throws(() => readZipEntry(zip, 'missing.bin'), /no missing\.bin/);
assert.throws(() => readZipEntry(noise(100, 6), 'x'), /not a zip/);
});
test('the parts go back where they were, byte for byte', () => {
const { net, app, image, own, manifest } = fixture();
const files = { 'net.bin': net, 'app.bin': app };
const out = assembleG1Image(manifest, own, (name) => files[name], sha);
assert.deepEqual(Buffer.from(out), Buffer.from(image));
});
test('a part that is not the one it was built with is refused', () => {
const { net, app, own, manifest } = fixture();
const bad = net.slice();
bad[100] ^= 1;
const files = { 'net.bin': bad, 'app.bin': app };
assert.throws(() => assembleG1Image(manifest, own, (name) => files[name], sha), G1FirmwareError);
const short = { 'net.bin': net.subarray(0, 100), 'app.bin': app };
assert.throws(() => assembleG1Image(manifest, own, (name) => short[name], sha), /not the one/);
});
test('damaged bundled bytes never pass as an image', () => {
const { net, app, own, manifest } = fixture();
const files = { 'net.bin': net, 'app.bin': app };
const flipped = own.slice();
flipped[10] ^= 1;
assert.throws(() => assembleG1Image(manifest, flipped, (name) => files[name], sha), /failed verification/);
assert.throws(() => assembleG1Image(manifest, own.subarray(0, own.length - 1), (name) => files[name], sha), G1FirmwareError);
});
test('the bundled firmware is whole and carries none of Even\'s bytes in its manifest ranges', () => {
const own = decodeG1OwnBytes(G1V0_OWN_BYTES_BASE64, fromBase64);
const taken = G1V0_IMAGE.parts.reduce((sum, part) => sum + part.length, 0);
assert.equal(own.length + taken, G1V0_IMAGE.size);
// MCUboot's magic and the version in its header, ahead of the first part.
assert.equal(Buffer.from(own.subarray(0, 4)).toString('hex'), '3db8f396');
assert.equal(`${own[20]}.${own[21]}.${own[22] | (own[23] << 8)}`, G1V0_IMAGE.version);
assert.match(G1V0_IMAGE.stockZipUrl, /^https:\/\/cdn\.evenreal\.co\//);
assert.match(G1V0_IMAGE.sha256, /^[0-9a-f]{64}$/);
const sorted = [...G1V0_IMAGE.parts].sort((a, b) => a.offset - b.offset);
assert.ok(sorted[0].offset > 512 && sorted.at(-1).offset + sorted.at(-1).length < G1V0_IMAGE.size);
assert.doesNotMatch(G1V0_IMAGE.source, /uncommitted/, 'ship only a firmware that was committed');
});
test('versions compare by number, not by text', () => {
assert.ok(plan.compareG1Versions('0.5.100', '0.5.63') > 0);
assert.ok(plan.compareG1Versions('0.5.9', '0.5.63') < 0);
assert.equal(plan.compareG1Versions('0.5.63', '0.5.63'), 0);
assert.equal(plan.compareG1Versions('0.5', '0.5.0'), 0);
assert.ok(plan.compareG1Versions('', '0.5.63') < 0);
});
test('a pair is chosen by serial, then address, and never guessed between two', () => {
const g1 = (serial, left, right) => ({ g1Firmware: 'g1v0', serial, left: left && { address: left }, right: right && { address: right } });
const ours = g1('S1', 'L1', 'R1');
const theirs = g1('S2', 'L2', 'R2');
assert.equal(plan.pickG1Pair([theirs, ours], { serial: 's1' }), ours);
assert.equal(plan.pickG1Pair([theirs, ours], { left: 'L1' }), ours);
assert.equal(plan.pickG1Pair([theirs, ours], { right: 'R2' }), theirs);
assert.equal(plan.pickG1Pair([theirs, ours], {}), null);
assert.equal(plan.pickG1Pair([ours], {}), ours);
// A flash changed the addresses: the serial still finds it.
assert.equal(plan.pickG1Pair([g1('S1', 'NEW', 'NEW2'), theirs], { serial: 'S1', left: 'OLD', right: 'OLD2' }).left.address, 'NEW');
// Our serial with one arm heard so far: wait, even if another pair is complete.
assert.equal(plan.pickG1Pair([g1('S1', 'L1', null), theirs], { serial: 'S1' }), null);
// The wanted glasses weren't heard: another pair is never a stand-in, even the only one around.
assert.equal(plan.pickG1Pair([theirs], { serial: 'S1' }), null);
assert.equal(plan.pickG1Pair([theirs], { left: 'L1', right: 'R1' }), null);
// A wanted address on one side doesn't match a pair for lacking the other.
assert.equal(plan.pickG1Pair([g1('S2', 'L2', null)], { left: 'L1' }), null);
// G2 pairs don't count.
assert.equal(plan.pickG1Pair([{ serial: 'S9', left: { address: 'a' }, right: { address: 'b' } }], {}), null);
});
test('the state of the two arms is that of the arm that needs the most', () => {
const on = (version, extra = {}) => ({ firmware: 'g1v0', version, safeMode: false, ...extra });
const state = (...arms) => plan.g1FirmwareState(arms, '0.5.63');
assert.equal(state(on('0.5.63'), on('0.5.63')), 'current');
assert.equal(state(on('0.5.64'), on('0.5.63')), 'current');
assert.equal(state(on('0.5.62'), on('0.5.63')), 'older');
assert.equal(state(on('0.5.63', { safeMode: true }), on('0.5.62')), 'safe-mode');
assert.equal(state({ firmware: 'stock' }, on('0.5.63', { safeMode: true })), 'stock');
});
test('the native flow\'s answer is read, and nonsense is no answer', () => {
assert.deepEqual(plan.parseG1FlashResult('{"flashed":true,"version":"0.5.64"}'), { flashed: true, version: '0.5.64' });
assert.deepEqual(plan.parseG1FlashResult('nonsense'), {});
assert.deepEqual(plan.parseG1FlashResult(''), {});
assert.deepEqual(plan.parseG1FlashResult('null'), {});
});
test('each arm counts for half of the bar', () => {
assert.equal(plan.g1FlashPercent('left', 0, 100), 0);
assert.equal(plan.g1FlashPercent('left', 100, 100), 50);
assert.equal(plan.g1FlashPercent('right', 0, 100), 50);
assert.equal(plan.g1FlashPercent('right', 100, 100), 100);
assert.equal(plan.g1FlashPercent('right', 5, 0), 50);
});
@@ -0,0 +1,551 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
private const val ARM = "F4:27:E9:CA:E8:3F"
private fun hex(text: String): ByteArray = ByteArray(text.length / 2) { text.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
/** An image the way MCUboot lays one out: header, payload, then a TLV area with its SHA-256. */
private fun testImage(version: Triple<Int, Int, Int> = Triple(0, 5, 64), payloadSize: Int = 5000): ByteArray {
val headerSize = 512
val hash = ByteArray(32) { (it * 3 + version.third).toByte() }
val image = ByteArray(headerSize + payloadSize + 4 + 4 + 32)
fun put16(at: Int, value: Int) {
image[at] = value.toByte()
image[at + 1] = (value ushr 8).toByte()
}
fun put32(at: Int, value: Int) {
put16(at, value and 0xffff)
put16(at + 2, value ushr 16)
}
put32(0, 0x96f3b83d.toInt())
put16(8, headerSize)
put32(12, payloadSize)
image[20] = version.first.toByte()
image[21] = version.second.toByte()
put16(22, version.third)
for (i in 0 until payloadSize) image[headerSize + i] = (i * 7).toByte()
val tlv = headerSize + payloadSize
put16(tlv, 0x6907)
put16(tlv + 2, 4 + 4 + 32)
put16(tlv + 4, 0x10)
put16(tlv + 6, 32)
hash.copyInto(image, tlv + 8)
return image
}
/**
* One arm behind the StockLink port: MCUmgr's image and OS groups as flash.py meets them on real arms, and g1v0's HELLO
* and PROPS. Requests are answered synchronously, from the write.
*/
private class FakeArm(private val image: ByteArray, var stock: Boolean = false) : StockLink {
var inbound: StockLinkListener? = null
var connected = false
var bond = BondState.BONDED
var bondRequests = 0
var bondResult = BondState.BONDED
val subscribed = ArrayList<String>()
val heartbeats = ArrayList<ByteArray>()
val calls = ArrayList<String>()
var runningVersion = "0.5.63"
var safeMode = false
var battery = 80
var slot1Hash: ByteArray? = null
var uploaded = ByteArray(0)
var uploadOffset = 0
var uploadRefusal = 0
/** After the upload the list shows this instead of the image's hash. */
var corruptAfterUpload = false
var confirmRefusal = 0
var dropAtOffset = -1
var silentRequests = 0
/** The chunk at this offset gets no answer, once. */
var silentAtOffset = -1
var onChunk: (() -> Unit)? = null
var connects = 0
val wantHash = G1Smp.imageHash(image)
override fun setListener(listener: StockLinkListener?) { inbound = listener }
override fun connect(address: String, timeoutMs: Int): Boolean {
connects++
connected = true
return true
}
override fun prepareLink(address: String, desiredMtu: Int, timeoutMs: Int) {}
override fun discoverServices(address: String, timeoutMs: Int): Boolean = connected
override fun enableNotifications(address: String, characteristicUuid: String, timeoutMs: Int): Boolean {
if (!connected) return false
if (stock && characteristicUuid == G1Ble.EVT_CHAR_UUID) return false
if (!stock && characteristicUuid == G1Smp.NUS_TX_UUID) return false
subscribed.add(characteristicUuid)
return true
}
override fun isConnected(address: String): Boolean = connected
override fun bondState(address: String): BondState = bond
override fun requestBond(address: String) {
bondRequests++
bond = bondResult
}
override fun negotiatedMtu(address: String): Int = 100
override fun disconnect(address: String) { connected = false }
override fun close() { connected = false }
fun drop() {
connected = false
inbound?.onConnectionStateChange(ARM, false)
}
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
if (!connected) throw IllegalStateException("Not connected")
when (characteristicUuid) {
G1Smp.NUS_RX_UUID -> heartbeats.add(frames.single())
G1Ble.PAIR_CHAR_UUID -> return bond == BondState.BONDED
G1Ble.CTRL_CHAR_UUID -> control(frames.single())
G1Smp.SMP_CHAR_UUID -> {
for (frame in frames) assertTrue(frame.size <= 97, "a write longer than the MTU allows")
smp(frames.reduce { a, b -> a + b })
}
else -> throw IllegalStateException("write to $characteristicUuid")
}
return true
}
private fun control(request: ByteArray) {
val op = request[0].toInt() and 0xff
val tag = request[1]
val body = when (op) {
G1Protocol.OP_HELLO -> {
val parts = runningVersion.split(".").map { it.toInt().toByte() }
val flags = (if (safeMode) 1 else 0) or 2 or 64
byteArrayOf(5, parts[0], parts[1], parts[2], 1, flags.toByte(), 0)
}
G1Protocol.OP_PROPS -> byteArrayOf(battery.toByte(), 0, 0, 0)
else -> ByteArray(0)
}
val event = ByteArray(9) + byteArrayOf(tag, 0) + body
event[0] = (0x80 or op).toByte()
inbound?.onNotification(ARM, G1Ble.EVT_CHAR_UUID, event)
}
private fun smp(frame: ByteArray) {
val op = frame[0].toInt()
val group = frame[5].toInt()
val seq = frame[6].toInt() and 0xff
val cmd = frame[7].toInt()
val body = G1Cbor.decode(frame, 8) as Map<*, *>
if (silentRequests > 0) {
silentRequests--
return
}
when {
group == 1 && cmd == 1 -> {
calls.add("upload")
val off = (body["off"] as Long).toInt()
onChunk?.invoke()
if (off == silentAtOffset) {
silentAtOffset = -1
return
}
if (uploadRefusal != 0) return reply(op, group, seq, cmd, mapOf("rc" to uploadRefusal))
if (off == uploadOffset) {
val data = body["data"] as ByteArray
if (off == 0) {
assertEquals(image.size.toLong(), body["len"])
assertContentEquals(sha256(image), body["sha"] as ByteArray)
assertEquals(0L, body["image"])
uploaded = ByteArray(0)
}
uploaded += data
uploadOffset += data.size
if (uploadOffset == image.size) slot1Hash = if (corruptAfterUpload) ByteArray(32) else G1Smp.imageHash(uploaded)
}
if (uploadOffset >= dropAtOffset && dropAtOffset >= 0) {
dropAtOffset = -1
drop()
return
}
reply(op, group, seq, cmd, mapOf("rc" to 0, "off" to uploadOffset))
}
group == 1 && cmd == 0 && op == G1Smp.OP_READ -> {
calls.add("list")
val images = ArrayList<Map<String, Any?>>()
images.add(mapOf("image" to 0, "slot" to 0, "version" to runningVersion, "hash" to ByteArray(32), "active" to true, "confirmed" to true, "bootable" to true))
slot1Hash?.let { images.add(mapOf("image" to 0, "slot" to 1, "version" to "0.5.64", "hash" to it, "bootable" to true)) }
reply(op, group, seq, cmd, mapOf("images" to images))
}
group == 1 && cmd == 0 -> {
calls.add("confirm")
assertEquals(true, body["confirm"])
assertContentEquals(wantHash, body["hash"] as ByteArray)
reply(op, group, seq, cmd, mapOf("rc" to confirmRefusal))
}
group == 0 && cmd == 5 -> {
calls.add("reset")
reply(op, group, seq, cmd, emptyMap())
drop()
}
else -> throw IllegalStateException("SMP $group/$cmd")
}
}
/** The reply comes in pieces, as notifications do. */
private fun reply(op: Int, group: Int, seq: Int, cmd: Int, body: Map<String, Any?>) {
val frame = G1Smp.frame(op or 1, group, seq, cmd, body)
for (piece in G1Smp.split(frame, 23)) inbound?.onNotification(ARM, G1Smp.SMP_CHAR_UUID, piece)
}
}
private class Recorder : FaceclawFirmwareFlasherListener {
val states = ArrayList<String>()
val logs = ArrayList<String>()
var progress = 0L
var total = 0L
var success: Boolean? = null
var detail = ""
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) {
progress = bytesSent
total = bytesTotal
}
override fun onState(state: String?, detail: String?) { states.add(state ?: "") }
override fun onComplete(success: Boolean, detail: String?) {
this.success = success
this.detail = detail ?: ""
}
}
private val FAST = G1FlashTimings(
connectTimeoutMs = 50, servicesTimeoutMs = 50, descriptorTimeoutMs = 50, writeTimeoutMs = 50, pairingMs = 200, retryDelayMs = 1,
controlReplyMs = 20, controlTries = 2, uploadReplyMs = 150, smpReplyMs = 150, resetReplyMs = 50, heartbeatMs = 30, pollMs = 5, uploadRetries = 5,
)
class G1SmpTest {
private val sha = ByteArray(32) { it.toByte() }
/** The expected bytes come from scouter_kit's tools/g1host.py, whose requests were proven on real arms. */
@Test
fun requestsMatchTheProvenPythonTool() {
val image = ByteArray(574408)
image[0] = 1
image[1] = 2
image[2] = 3
val first = G1Smp.uploadRequest(image, 0, sha).toMutableMap()
first["data"] = byteArrayOf(1, 2, 3)
assertEquals(
"0200004e00010001a665696d61676500636c656e1a0008c3c8636f666600637368615820000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f6464617461430102036775706772616465f4",
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 0, G1Smp.CMD_IMAGE_UPLOAD, first)),
)
assertEquals(
"0200001100010101a2636f6666190800646461746143010203",
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 1, G1Smp.CMD_IMAGE_UPLOAD, mapOf("off" to 2048, "data" to byteArrayOf(1, 2, 3)))),
)
assertEquals(
"0200003100010500a264686173685820000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f67636f6e6669726df5",
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 5, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(sha))),
)
assertEquals("0000000100010700a0", BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_READ, G1Smp.GROUP_IMAGE, 7, G1Smp.CMD_IMAGE_STATE, emptyMap())))
assertEquals("020000010000ff05a0", BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_OS, 255, G1Smp.CMD_OS_RESET, emptyMap())))
}
@Test
fun cborMatchesPythonAndRoundTrips() {
val value = mapOf("n" to -5, "big" to 70000, "huge" to 5000000000L, "t" to true, "s" to "ab")
val encoded = G1Cbor.encode(value)
assertEquals("a5616e24636269671a0001117064687567651b000000012a05f2006174f56173626162", BinaryEncoding.bytesToHex(encoded))
val decoded = G1Cbor.decode(encoded) as Map<*, *>
assertEquals(-5L, decoded["n"])
assertEquals(70000L, decoded["big"])
assertEquals(5000000000L, decoded["huge"])
assertEquals(true, decoded["t"])
assertEquals("ab", decoded["s"])
}
@Test
fun cborReadsTheIndefiniteLengthsOfAnImageList() {
// {"images": [{"slot": 1, "active": true}]}, each container of indefinite length.
val data = hex("bf66696d616765739fbf64736c6f74016661637469766" + "5f5ffffff")
val slots = (G1Cbor.decode(data) as Map<*, *>)["images"] as List<*>
val slot = slots.single() as Map<*, *>
assertEquals(1L, slot["slot"])
assertEquals(true, slot["active"])
}
@Test
fun malformedCborIsAnErrorNotAWrongValue() {
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(hex("5820")) }
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(hex("bf")) }
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(ByteArray(0)) }
}
@Test
fun repliesAreJoinedAcrossNotifications() {
val assembler = G1Smp.Assembler()
val one = G1Smp.frame(3, 1, 7, 1, mapOf("off" to 2048, "rc" to 0))
val two = G1Smp.frame(3, 1, 8, 0, emptyMap())
val all = one + two
val replies = ArrayList<Pair<Int, Map<*, *>>>()
for (start in all.indices step 5) replies += assembler.feed(all.copyOfRange(start, minOf(start + 5, all.size)))
assertEquals(listOf(7, 8), replies.map { it.first })
assertEquals(2048, G1Smp.replyOffset(replies[0].second))
assertEquals(0, G1Smp.replyCode(replies[1].second))
}
@Test
fun anImageSaysWhatItIs() {
val image = testImage(Triple(0, 5, 300))
assertEquals("0.5.300", G1Smp.imageVersion(image))
assertContentEquals(ByteArray(32) { (it * 3 + 300).toByte() }, G1Smp.imageHash(image))
assertFailsWith<IllegalArgumentException> { G1Smp.imageVersion(ByteArray(100)) }
val cut = image.copyOf(image.size - 20)
assertFailsWith<IllegalArgumentException> { G1Smp.imageHash(cut) }
}
@Test
fun writesFitTheMtu() {
val pieces = G1Smp.split(ByteArray(1000), 247)
assertTrue(pieces.all { it.size <= 244 })
assertEquals(1000, pieces.sumOf { it.size })
}
}
class G1ArmFlashFlowTest {
private val image = testImage()
private fun flow(arm: FakeArm, listener: Recorder, mode: G1ArmFlashFlow.Mode, window: Int = 100) =
G1ArmFlashFlow(arm, ARM, "left", "image.bin", mode, window, listener, FAST, testPlatform(), { image })
private fun run(arm: FakeArm, mode: G1ArmFlashFlow.Mode, window: Int = 100): Recorder {
val listener = Recorder()
flow(arm, listener, mode, window).run()
assertNotNull(listener.success, "the flow must always finish")
return listener
}
private fun confirmIsLast(arm: FakeArm) {
assertEquals(listOf("confirm", "reset"), arm.calls.takeLast(2))
assertEquals(1, arm.calls.count { it == "confirm" })
}
@Test
fun anUpdateUploadsChecksThenConfirmsAndResets() {
val arm = FakeArm(image)
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertEquals("""{"flashed":true,"version":"0.5.64"}""", result.detail)
assertContentEquals(image, arm.uploaded)
assertEquals(image.size.toLong(), result.progress)
assertEquals(image.size.toLong(), result.total)
confirmIsLast(arm)
// The list before the confirm is what proves the slot holds this image.
assertEquals("list", arm.calls[arm.calls.indexOf("confirm") - 1])
assertTrue(arm.heartbeats.isEmpty(), "g1v0 has no heartbeat")
assertTrue("rebooting" in result.states)
}
@Test
fun anArmAlreadyOnThisVersionIsLeftAlone() {
val arm = FakeArm(image)
arm.runningVersion = "0.5.64"
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success)
assertEquals("""{"flashed":false,"version":"0.5.64"}""", result.detail)
assertTrue(arm.calls.isEmpty(), "nothing goes to the update service")
}
@Test
fun anArmInSafeModeOnThisVersionIsInstalledAgain() {
val arm = FakeArm(image)
arm.runningVersion = "0.5.64"
arm.safeMode = true
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals("""{"flashed":true,"version":"0.5.64"}""", result.detail)
confirmIsLast(arm)
}
@Test
fun aSlotThatDoesNotHoldTheImageIsNeverConfirmed() {
val arm = FakeArm(image)
arm.corruptAfterUpload = true
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("confirm" in arm.calls)
assertFalse("reset" in arm.calls)
assertTrue("Nothing was installed" in result.detail, result.detail)
}
@Test
fun aRefusedUploadIsNeverConfirmed() {
val arm = FakeArm(image)
arm.uploadRefusal = 9
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("confirm" in arm.calls)
assertTrue("error 9" in result.detail, result.detail)
}
@Test
fun aRefusedConfirmIsNotAReset() {
val arm = FakeArm(image)
arm.confirmRefusal = 2
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("reset" in arm.calls)
}
@Test
fun aLowBatteryStopsAnUpdateBeforeAnyUpload() {
val arm = FakeArm(image)
arm.battery = 12
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertTrue("12%" in result.detail, result.detail)
assertTrue(arm.calls.isEmpty())
}
@Test
fun aDamagedImageFailsBeforeTheLinkIsTouched() {
val listener = Recorder()
val arm = FakeArm(image)
G1ArmFlashFlow(arm, ARM, "left", "image.bin", G1ArmFlashFlow.Mode.UPDATE, 100, listener, FAST, testPlatform(), { ByteArray(100) }).run()
assertEquals(false, listener.success)
assertEquals(0, arm.connects)
}
@Test
fun anUnreadableImageIsAClearFailure() {
val listener = Recorder()
val arm = FakeArm(image)
G1ArmFlashFlow(arm, ARM, "left", "image.bin", G1ArmFlashFlow.Mode.STOCK, 100, listener, FAST, testPlatform(), { throw IllegalStateException("gone") }).run()
assertEquals(false, listener.success)
assertTrue("could not read the firmware" in listener.detail, listener.detail)
}
@Test
fun aLostLinkResumesTheUpload() {
val arm = FakeArm(image)
arm.dropAtOffset = 2048
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertContentEquals(image, arm.uploaded)
assertTrue(arm.connects >= 2, "it connected again")
confirmIsLast(arm)
}
@Test
fun aChunkThatGetsNoAnswerIsSentAgain() {
val arm = FakeArm(image)
arm.silentAtOffset = 2048
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertContentEquals(image, arm.uploaded)
confirmIsLast(arm)
}
@Test
fun anUploadThatNeverGetsAnswersGivesUpWithoutConfirming() {
val arm = FakeArm(image)
arm.silentRequests = 1000
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("confirm" in arm.calls)
}
@Test
fun aSlotAlreadyHoldingTheImageSkipsTheUpload() {
val arm = FakeArm(image)
arm.slot1Hash = arm.wantHash
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertFalse("upload" in arm.calls)
confirmIsLast(arm)
}
@Test
fun stockGetsAHeartbeatEvenWhileAChunkWaits() {
val arm = FakeArm(image, stock = true)
// A chunk can wait a long time, as the first does while the arm erases its slot: the heartbeat has to keep going.
arm.silentAtOffset = 2048
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertTrue(arm.heartbeats.size >= 3, "heartbeats: ${arm.heartbeats.size}")
assertTrue(G1Smp.NUS_TX_UUID in arm.subscribed)
assertEquals(0x25, arm.heartbeats[0][0].toInt())
assertEquals(arm.heartbeats[1][3], 1.toByte())
assertEquals(arm.heartbeats[1][5], 1.toByte())
confirmIsLast(arm)
}
@Test
fun stockIsPairedWithFirst() {
val arm = FakeArm(image, stock = true)
arm.bond = BondState.NONE
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.bondRequests)
assertTrue("pairing" in result.states)
}
@Test
fun aRefusedBondIsRetriedThenReported() {
val arm = FakeArm(image)
arm.bond = BondState.NONE
arm.bondResult = BondState.NONE
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE, window = 1)
assertEquals(false, result.success)
assertTrue(arm.calls.isEmpty())
assertTrue("Couldn't reach the left arm" in result.detail, result.detail)
}
@Test
fun aPlatformThatCannotSeeBondsReliesOnTheEncryptedWrite() {
val arm = FakeArm(image)
arm.bond = BondState.UNKNOWN
val listener = Recorder()
// The write to PAIR fails on an unknown bond in this fake, as on an arm out of the case: no encrypted link.
flow(arm, listener, G1ArmFlashFlow.Mode.PROBE, 1).run()
assertEquals(false, listener.success)
assertEquals(0, arm.bondRequests)
assertTrue("an arm pairs only in its case" in listener.detail, listener.detail)
}
@Test
fun aProbeSaysWhatAnArmRuns() {
val arm = FakeArm(image)
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
assertEquals(true, result.success, result.detail)
assertEquals("""{"firmware":"g1v0","version":"0.5.63","safeMode":false,"inCase":false,"battery":80}""", result.detail)
assertTrue(arm.calls.isEmpty())
}
@Test
fun aProbeOfEvensFirmwareNeedsNoPairing() {
val arm = FakeArm(image, stock = true)
arm.bond = BondState.NONE
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
assertEquals("""{"firmware":"stock"}""", result.detail)
assertEquals(0, arm.bondRequests)
}
@Test
fun cancellingDuringTheUploadStopsBeforeTheConfirm() {
val arm = FakeArm(image)
val listener = Recorder()
val flow = flow(arm, listener, G1ArmFlashFlow.Mode.UPDATE)
arm.onChunk = { flow.cancel() }
flow.run()
assertEquals(false, listener.success)
assertEquals("Cancelled.", listener.detail)
assertFalse("confirm" in arm.calls)
}
}
@@ -217,7 +217,7 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
body[0] = 5 body[0] = 5
body[1] = 0 body[1] = 0
body[2] = 5 body[2] = 5
body[3] = 62 body[3] = 63
body[4] = (if (a.left) 1 else 0).toByte() body[4] = (if (a.left) 1 else 0).toByte()
body[5] = (2 or 64).toByte() body[5] = (2 or 64).toByte()
body[6] = (if (a.left) 0 else 4).toByte() body[6] = (if (a.left) 0 else 4).toByte()
@@ -472,7 +472,7 @@ class G1SessionTest {
assertEquals(G1Protocol.EVENTS_MASK, s.glasses.leftArm.eventsMask) assertEquals(G1Protocol.EVENTS_MASK, s.glasses.leftArm.eventsMask)
assertEquals(G1Protocol.EVENTS_MASK, s.glasses.rightArm.eventsMask) assertEquals(G1Protocol.EVENTS_MASK, s.glasses.rightArm.eventsMask)
assertEquals(1, s.glasses.leftArm.healthOk, "the boot is confirmed healthy") assertEquals(1, s.glasses.leftArm.healthOk, "the boot is confirmed healthy")
assertTrue(s.listener.firmware.single().startsWith("g1v0 0.5.62|g1v0 0.5.62|Faceclaw/"), s.listener.firmware.toString()) assertTrue(s.listener.firmware.single().startsWith("g1v0 0.5.63|g1v0 0.5.63|Faceclaw/"), s.listener.firmware.toString())
s.submit(1, 1) s.submit(1, 1)
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() }, "frame never displayed:\n" + s.tail()) assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() }, "frame never displayed:\n" + s.tail())
+13 -4
View File
@@ -332,7 +332,7 @@ test("G1 arms on g1v0 join on the frame serial and can be selected", () => {
assert.match(row.armsSummary, /case/); assert.match(row.armsSummary, /case/);
}); });
test("G1 arms on Even's firmware show up but can't be selected", () => { test("G1 arms on Even's firmware can be selected, to install on", () => {
const aggregator = new DiscoveryAggregator(); const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("Even G1_70_L_EF50E5", "C0:66:16:EF:50:E5", "02" + ascii(G1_SERIAL))); aggregator.ingest(g1Arm("Even G1_70_L_EF50E5", "C0:66:16:EF:50:E5", "02" + ascii(G1_SERIAL)));
aggregator.ingest(g1Arm("Even G1_70_R_CBE689", "E4:46:BA:CB:E6:89", "01" + ascii(G1_SERIAL))); aggregator.ingest(g1Arm("Even G1_70_R_CBE689", "E4:46:BA:CB:E6:89", "01" + ascii(G1_SERIAL)));
@@ -340,16 +340,25 @@ test("G1 arms on Even's firmware show up but can't be selected", () => {
assert.equal(pair.g1Firmware, "stock"); assert.equal(pair.g1Firmware, "stock");
assert.equal(pair.completeness, "complete"); assert.equal(pair.completeness, "complete");
const row = glassesRow(pair); const row = glassesRow(pair);
assert.equal(row.canSelect, false); assert.equal(row.canSelect, true);
assert.match(row.armsSummary, /computer/); assert.match(row.armsSummary, /install/);
}); });
test("a G1 pair with one arm in safe mode can't be selected", () => { test("a G1 pair with one arm in safe mode can be selected, to install again", () => {
const aggregator = new DiscoveryAggregator(); const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1v0Arm("L", "F4:27:E9:CA:E8:3F")); aggregator.ingest(g1v0Arm("L", "F4:27:E9:CA:E8:3F"));
aggregator.ingest(g1Arm("G1v0S_R", "CD:EB:89:BF:E9:EC", "ffff0104" + ascii(G1_SERIAL))); aggregator.ingest(g1Arm("G1v0S_R", "CD:EB:89:BF:E9:EC", "ffff0104" + ascii(G1_SERIAL)));
const [pair] = aggregator.pairs(); const [pair] = aggregator.pairs();
assert.equal(pair.g1Firmware, "g1v0-safe"); assert.equal(pair.g1Firmware, "g1v0-safe");
assert.equal(glassesRow(pair).canSelect, true);
});
test("a G1 pair needs both arms heard, whatever it runs", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("Even G1_70_L_EF50E5", "C0:66:16:EF:50:E5", "02" + ascii(G1_SERIAL)));
const [pair] = aggregator.pairs();
assert.equal(pair.g1Firmware, "stock");
assert.equal(pair.completeness, "left-only");
assert.equal(glassesRow(pair).canSelect, false); assert.equal(glassesRow(pair).canSelect, false);
}); });
+5
View File
@@ -41,6 +41,11 @@
"../app/apps/glanceboard/layout.ts", "../app/apps/glanceboard/layout.ts",
"../app/apps/files/video-layout.ts", "../app/apps/files/video-layout.ts",
"../app/g2/pairing-candidates.ts", "../app/g2/pairing-candidates.ts",
"../app/g1/pako.d.ts",
"../app/g1/firmware-image.ts",
"../app/g1/flash-plan.ts",
"../app/g1/firmware/g1v0-image.ts",
"../app/g1/firmware/g1v0-own-bytes.ts",
"../app/apps/calculator/math/*.ts", "../app/apps/calculator/math/*.ts",
"../app/apps/microphones/mic-protocol.ts", "../app/apps/microphones/mic-protocol.ts",
"../app/apps/calculator/calculator-commands.ts", "../app/apps/calculator/calculator-commands.ts",
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Turns a built g1v0 image into what the app ships: app/g1/firmware/g1v0-image.ts and g1v0-own-bytes.ts.
A built image embeds two of Even's files (scouter_kit g1_firmware/README.md, "Build the image"), which must not be
published: its network-core image and its TouchBar table. Those bytes are cut out here, and the phone puts them back
from Even's own download (app/g1/firmware-builder.ts). The result has the same SHA-256 as the build, so the MCUboot
signature made at build time stays valid.
tools/g1_firmware_bundle.py WORK/build/g1v0-v0563/zephyr/app_update.bin --firmware-dir ~/src/scouter_kit/g1_firmware
--firmware-dir holds stock_images.txt and, under work/firmware/1.6.6/, Even's unpacked files (scripts/fetch_stock.sh).
"""
import argparse
import base64
import hashlib
import json
import struct
import subprocess
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "app" / "g1" / "firmware"
STOCK_VERSION = "1.6.6"
TABLE = "aw9320x_table"
def sha(data):
return hashlib.sha256(data).hexdigest()
def stock_pins(firmware_dir):
rows = [line.split() for line in (firmware_dir / "stock_images.txt").read_text().splitlines()
if line.strip() and not line.startswith("#")]
return {row[1]: row[2:] for row in rows if row[0] == STOCK_VERSION}
def only_place(image, part, label):
at = image.find(part)
if at < 0:
raise SystemExit(f"{label} is not in the image: was it built with Even's {STOCK_VERSION}?")
if image.find(part, at + 1) >= 0:
raise SystemExit(f"{label} is in the image twice")
return at
def image_version(image):
if image[:4] != bytes.fromhex("3db8f396"):
raise SystemExit("not an MCUboot image")
major, minor, revision = struct.unpack_from("<BBH", image, 20)
return f"{major}.{minor}.{revision}"
def source_commit(firmware_dir):
def git(*args):
return subprocess.run(["git", "-C", str(firmware_dir), *args], capture_output=True, text=True).stdout.strip()
return git("rev-parse", "--short=12", "HEAD") + ("+uncommitted" if git("status", "--porcelain", "--", "firmware", "../src/vm") else "")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("image", type=Path)
ap.add_argument("--firmware-dir", type=Path, required=True)
args = ap.parse_args()
image = args.image.read_bytes()
pins = stock_pins(args.firmware_dir)
stock = args.firmware_dir / "work" / "firmware" / STOCK_VERSION
net = (stock / "net_core_app_update.bin").read_bytes()
app = (stock / "app_update.bin").read_bytes()
if sha(net) != pins["net_core_app_update.bin"][0] or sha(app) != pins["app_update.bin"][0]:
raise SystemExit(f"Even's files in {stock} don't match stock_images.txt")
table_hash, table_where = pins[TABLE]
table_offset, table_length = table_where.split("@")[1].split("+")
table_offset, table_length = int(table_offset, 16), int(table_length)
table = app[table_offset:table_offset + table_length]
if sha(table) != table_hash:
raise SystemExit("the TouchBar table isn't where stock_images.txt says")
parts = sorted([
{"offset": only_place(image, net, "the net-core image"), "length": len(net), "file": "net_core_app_update.bin",
"fileOffset": 0, "sha256": sha(net)},
{"offset": only_place(image, table, "the TouchBar table"), "length": len(table), "file": "app_update.bin",
"fileOffset": table_offset, "sha256": table_hash},
], key=lambda part: part["offset"])
own = bytearray()
position = 0
for part in parts:
own += image[position:part["offset"]]
position = part["offset"] + part["length"]
own += image[position:]
for label, part in (("net-core image", net), ("TouchBar table", table)):
if bytes(part[:64]) in own:
raise SystemExit(f"the bytes left over still hold Even's {label}")
manifest = {
"version": image_version(image),
"sha256": sha(image),
"size": len(image),
"source": source_commit(args.firmware_dir),
"stockVersion": STOCK_VERSION,
"stockZipUrl": pins["zip"][1],
"stockZipSha256": pins["zip"][0],
"parts": parts,
}
OUT.mkdir(parents=True, exist_ok=True)
(OUT / "g1v0-image.ts").write_text(
"// AUTO-GENERATED by tools/g1_firmware_bundle.py -- do not edit by hand.\n"
"// What the app installs on a G1, and the parts of it that come from Even's own download.\n\n"
"export type G1FirmwarePart = { offset: number; length: number; file: string; fileOffset: number; sha256: string };\n\n"
"export type G1FirmwareImage = {\n"
" version: string;\n sha256: string;\n size: number;\n source: string;\n stockVersion: string;\n"
" stockZipUrl: string;\n stockZipSha256: string;\n parts: G1FirmwarePart[];\n};\n\n"
f"export const G1V0_IMAGE: G1FirmwareImage = {json.dumps(manifest, indent=2)};\n")
packed = zlib.compress(bytes(own), 9)
(OUT / "g1v0-own-bytes.ts").write_text(
"// AUTO-GENERATED by tools/g1_firmware_bundle.py -- do not edit by hand.\n"
"// The built g1v0 image without Even's parts (g1v0-image.ts), deflated.\n\n"
f'export const G1V0_OWN_BYTES_BASE64 = "{base64.b64encode(packed).decode()}";\n')
print(f"g1v0 {manifest['version']}: {len(image)} B, {len(own)} B of its own, {len(packed)} B deflated; "
f"parts at {[part['offset'] for part in parts]}")
if __name__ == "__main__":
main()