Firmware uninstall/revert-to-stock for G1s

This commit is contained in:
James Babcock committed 2026-11-08 00:11:13 -08:00
1 parent e103b89510
commit 479308f4a6
17 files changed
+1014 -98

No files matched your search

@@ -5,10 +5,18 @@ 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.
* Android host for the shared [G1ArmFlashFlow]: owns the GATT link and the worker thread for one G1 arm's install, its
* restore to Even's firmware, 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) {
class FaceclawG1Flasher(
context: Context,
address: String?,
side: String?,
firmwarePath: String?,
netCorePath: String?,
mode: String?,
connectWindowMs: Int,
) {
private val link = AndroidStockLink(context.applicationContext)
private val mainHandler = Handler(Looper.getMainLooper())
private val lock = Any()
@@ -25,6 +33,7 @@ class FaceclawG1Flasher(context: Context, address: String?, side: String?, firmw
address ?: "",
side ?: "",
firmwarePath ?: "",
netCorePath ?: "",
G1ArmFlashFlow.mode(mode ?: ""),
connectWindowMs,
object : FaceclawFirmwareFlasherListener {
+13 -2
View File
@@ -1,6 +1,7 @@
/**
* 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.
* and how it finds an arm again afterwards, when it advertises what it runs now (and, coming from g1v0 before 0.5.66, at
* a new address).
*/
import { classifyAdvertisement, type EvenAdvertisement } from "../g2/even-advertisement";
import { DiscoveryAggregator, type GlassesPairCandidate } from "../g2/pairing-candidates";
@@ -27,11 +28,21 @@ export class G1ArmScanner {
/** 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> {
return this.waitForArm(side, serial, timeoutMs, (arm) => arm.g1Firmware !== "stock");
}
/** Resolves when an arm of this side is heard that [accept] takes, on any firmware, or null after [timeoutMs]. */
waitForArm(
side: G1Side,
serial: string | null | undefined,
timeoutMs: number,
accept: (arm: EvenAdvertisement) => boolean,
): 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 (!arm || arm.role !== side || !arm.g1Firmware || !accept(arm)) return;
if (!serial || sameG1Serial(arm.serial, serial)) {
done(arm);
return;
+21
View File
@@ -0,0 +1,21 @@
/**
* Even's official G1 firmware, which an uninstall puts back: both images of one public release, the application core's
* and the network core's (the Bluetooth controller), as Even's own update installs them, so the two always match.
* From Even's CDN, checked against these SHA-256 sums (scouter_kit g1_firmware/stock_images.txt). Every public image
* says 0.0.0 in its MCUboot header, so the hashes are the only way to tell releases apart.
*/
export type EvenG1Release = {
version: string;
zipUrl: string;
zipSha256: string;
appSha256: string;
netCoreSha256: string;
};
export const EVEN_G1_RESTORE: EvenG1Release = {
version: "1.6.6",
zipUrl: "https://cdn.evenreal.co/firmware/dcfa510c090e476c10a6f6c348a22415.zip",
zipSha256: "748836f2d9d092b0783cbb7672fdccec4f730051cad27f095bbb156ac3e5d316",
appSha256: "ae032838e27037156da98e19de90df78f5406715751f3b38adf50498db3010c1",
netCoreSha256: "c277749be97a2763742db399afeb10ca6916059abd60d41bbc05c8892c002c77",
};
+26 -5
View File
@@ -1,29 +1,34 @@
/**
* 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.
* image that was built, tested and signed, and it is checked to be. Also prepares Even's own images for an uninstall.
* 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 { EVEN_G1_RESTORE } from "./even-firmware";
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";
import { assembleG1Image, decodeG1OwnBytes, extractEvenG1Images, G1FirmwareError, readZipEntry } from "./firmware-image";
export type G1BuildProgress = "downloading" | "verifying" | "assembling" | "writing";
export type BuiltG1Firmware = { path: string; bytes: number; version: string };
/** Even's release for an uninstall: the application core's image and the network core's. */
export type BuiltEvenG1Firmware = { appPath: string; netCorePath: string; bytes: number; version: string };
function sha256(bytes: Uint8Array): string {
return firmwareSha256(bytes.slice().buffer);
}
async function downloadStockZip(): Promise<Uint8Array> {
async function downloadStockZip(url: string): Promise<Uint8Array> {
let response: Response;
try {
response = await fetchWithUserAgent(G1V0_IMAGE.stockZipUrl);
response = await fetchWithUserAgent(url);
} catch (error) {
throw new G1FirmwareError(`Could not reach Even's firmware server: ${(error as Error)?.message ?? error}`);
}
@@ -33,7 +38,7 @@ async function downloadStockZip(): Promise<Uint8Array> {
export async function buildG1Firmware(onProgress?: (progress: G1BuildProgress) => void): Promise<BuiltG1Firmware> {
onProgress?.("downloading");
const zip = await downloadStockZip();
const zip = await downloadStockZip(G1V0_IMAGE.stockZipUrl);
onProgress?.("verifying");
const zipHash = sha256(zip);
@@ -50,3 +55,19 @@ export async function buildG1Firmware(onProgress?: (progress: G1BuildProgress) =
writeFirmwareFile(path, image.slice().buffer);
return { path, bytes: image.length, version: G1V0_IMAGE.version };
}
export async function buildEvenG1Firmware(onProgress?: (progress: G1BuildProgress) => void): Promise<BuiltEvenG1Firmware> {
onProgress?.("downloading");
const zip = await downloadStockZip(EVEN_G1_RESTORE.zipUrl);
onProgress?.("verifying");
const { app, netCore } = extractEvenG1Images(zip, EVEN_G1_RESTORE, sha256);
onProgress?.("writing");
const folder = knownFolders.documents().path;
const appPath = `${folder}/even_g1_${EVEN_G1_RESTORE.version}_app.bin`;
const netCorePath = `${folder}/even_g1_${EVEN_G1_RESTORE.version}_net.bin`;
writeFirmwareFile(appPath, app.slice().buffer);
writeFirmwareFile(netCorePath, netCore.slice().buffer);
return { appPath, netCorePath, bytes: app.length + netCore.length, version: EVEN_G1_RESTORE.version };
}
+26
View File
@@ -4,6 +4,7 @@
*/
import { inflate, inflateRaw } from "pako";
import type { EvenG1Release } from "./even-firmware";
import type { G1FirmwareImage } from "./firmware/g1v0-image";
export class G1FirmwareError extends Error {}
@@ -41,6 +42,31 @@ export function readZipEntry(zip: Uint8Array, name: string): Uint8Array {
throw new G1FirmwareError(`The firmware download has no ${name}.`);
}
/**
* The two images of Even's release from its download, each checked by its own SHA-256 as well as the zip's, so what
* goes to the arms is byte for byte what Even published.
*/
export function extractEvenG1Images(
zip: Uint8Array,
release: EvenG1Release,
sha256: (bytes: Uint8Array) => string,
): { app: Uint8Array; netCore: Uint8Array } {
const zipHash = sha256(zip);
if (zipHash !== release.zipSha256) {
throw new G1FirmwareError(`Even's firmware download failed verification.\nexpected ${release.zipSha256}\ngot ${zipHash}`);
}
const checked = (name: string, want: string) => {
const bytes = readZipEntry(zip, name);
const got = sha256(bytes);
if (got !== want) throw new G1FirmwareError(`${name} in Even's download failed verification.\nexpected ${want}\ngot ${got}`);
return bytes;
};
return {
app: checked("app_update.bin", release.appSha256),
netCore: checked("net_core_app_update.bin", release.netCoreSha256),
};
}
export function decodeG1OwnBytes(base64: string, decode: (text: string) => Uint8Array): Uint8Array {
return inflate(decode(base64));
}
+16 -5
View File
@@ -1,11 +1,15 @@
/** What installing firmware on a G1 has to decide. No I/O. */
import type { GlassesPairCandidate } from "../g2/pairing-candidates";
import { EVEN_G1_RESTORE } from "./even-firmware";
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"];
/** Going back, right first, for the same reason: halfway, the pair is as halfway through an install. */
export const G1_UNINSTALL_SIDES: readonly G1Side[] = ["right", "left"];
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.";
@@ -14,13 +18,20 @@ export const G1_CASE_DELAY_HINT =
"A fully charged arm can take up to 5 minutes to notice it's in the case, so this may take a while.";
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.";
"This replaces the firmware on both arms, about two minutes each. Faceclaw can put Even's firmware back later, but as version " +
`${EVEN_G1_RESTORE.version}, which may not be the version you have now. Installing custom firmware is not covered by warranty.`;
export const G1_UNINSTALL_NOTICE =
`This puts Even's official firmware ${EVEN_G1_RESTORE.version} back on both arms, Bluetooth controller included, a few minutes ` +
"each. It may not be the version they came with. Afterwards they work with Even's app again, and not with Faceclaw until you " +
"install its firmware again.";
/** What the native flow says when it finishes (G1ArmFlashFlow). */
export type G1FlashResult = {
flashed?: boolean;
firmware?: "g1v0" | "stock";
/** A restore erased g1v0's asset store, where Even's fonts and pictures were. */
wiped?: boolean;
version?: string;
safeMode?: boolean;
inCase?: boolean;
@@ -102,8 +113,8 @@ export function g1StateFromAdvertising(
return { state: compareG1Versions(lowest, shipped) < 0 ? "older" : "current", version: lowest };
}
/** Each arm counts for half of the bar. */
export function g1FlashPercent(side: G1Side, bytesSent: number, bytesTotal: number): number {
/** Each arm counts for half of the bar, in the order they're done. */
export function g1FlashPercent(side: G1Side, bytesSent: number, bytesTotal: number, order: readonly G1Side[] = G1_SIDES): number {
const within = bytesTotal > 0 ? Math.min(1, bytesSent / bytesTotal) : 0;
return ((side === "right" ? 1 + within : within) / 2) * 100;
return ((order.indexOf(side) + within) / 2) * 100;
}
+6 -4
View File
@@ -7,8 +7,10 @@ export type { G1FlashMode, G1FlasherOptions } from './g1-flasher'
declare const FaceclawKitIosG1Flasher: any, FaceclawKitFaceclawFirmwareFlasherListener: any
/** CoreBluetooth has no way to remove a pairing; iOS Settings does it, and a stale one does no harm. */
export function forgetG1Pairing(_address: string): void {}
/** CoreBluetooth has no way to remove a pairing; iOS Settings does it. */
export function forgetG1Pairing(_address: string): boolean {
return false
}
/**
* iOS twin of the Android G1Flasher: the shared Kotlin G1ArmFlashFlow over a CoreBluetooth central. As with the G2's
@@ -47,8 +49,8 @@ export class G1Flasher {
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.flasher = FaceclawKitIosG1Flasher.alloc().initWithAddressSideFirmwarePathNetCorePathModeConnectWindowMs(
identifier, this.options.side, this.options.firmwarePath, this.options.netCorePath ?? '', this.options.mode, this.options.connectWindowMs)
this.listenerProxy = kotlinListener(FaceclawKitFaceclawFirmwareFlasherListener, {
onLogLine: (line: string) => this.logListener?.(String(line ?? '')),
onProgressLensComponentIndexComponentCountBlockIndexBlockCountBytesSentBytesTotal: (
+12 -6
View File
@@ -4,24 +4,30 @@ import { parseG1FlashResult, type G1FlashResult, type G1Side } from "../g1/flash
declare const com: any;
export type G1FlashMode = "stock" | "update" | "probe";
/** "restore": Even's firmware back on an arm running g1v0, both of its images. */
export type G1FlashMode = "stock" | "update" | "probe" | "restore";
export type G1FlasherOptions = {
address: string;
side: G1Side;
/** The application core's image. */
firmwarePath: string;
/** A restore's network-core image. */
netCorePath?: string;
mode: G1FlashMode;
/** How long to keep trying to reach the arm and pair with it. */
connectWindowMs: number;
};
/** Removes the phone's pairing with an address the glasses no longer use. */
export function forgetG1Pairing(address: string): void {
/** Removes the phone's pairing with an address, which the glasses no longer use or no longer share. False: this phone can't. */
export function forgetG1Pairing(address: string): boolean {
const context = Utils.android.getApplicationContext();
if (context) com.faceclaw.app.FaceclawG1Flasher.forgetPairing(context, address);
if (!context) return false;
com.faceclaw.app.FaceclawG1Flasher.forgetPairing(context, address);
return true;
}
/** TS wrapper around FaceclawG1Flasher: one arm's install, or a question about what it runs. */
/** TS wrapper around FaceclawG1Flasher: one arm's install, its restore to Even's firmware, or a question about what it runs. */
export class G1Flasher {
private readonly flasher: any;
private readonly listenerProxy: any;
@@ -34,7 +40,7 @@ export class G1Flasher {
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,
context, options.address, options.side, options.firmwarePath, options.netCorePath ?? "", options.mode, options.connectWindowMs,
);
this.listenerProxy = new com.faceclaw.app.FaceclawFirmwareFlasherListener({
onLog: (line: string) => this.logListener?.(String(line)),
+158 -27
View File
@@ -1,14 +1,23 @@
import { Frame, Observable } from "@nativescript/core";
import { G1ArmScanner } from "../g1/arm-scanner";
import { EVEN_G1_RESTORE } from "../g1/even-firmware";
import { G1V0_IMAGE } from "../g1/firmware/g1v0-image";
import { buildG1Firmware, type BuiltG1Firmware, type G1BuildProgress } from "../g1/firmware-builder";
import {
buildEvenG1Firmware,
buildG1Firmware,
type BuiltEvenG1Firmware,
type BuiltG1Firmware,
type G1BuildProgress,
} from "../g1/firmware-builder";
import { saveG1Arm, saveG1Pair } from "../g1/addresses";
import {
G1_CASE_DELAY_HINT,
G1_CASE_INSTRUCTIONS,
G1_INSTALL_NOTICE,
G1_SIDES,
G1_UNINSTALL_NOTICE,
G1_UNINSTALL_SIDES,
g1FlashPercent,
type G1FlashResult,
type G1Side,
@@ -23,19 +32,27 @@ 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";
type Phase = "intro" | "preparing" | "flashing" | "flashed" | "error";
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;
/** Even's image is larger than g1v0, and MCUboot first installs the network core's. */
const RESTORE_RETURN_MS = 300_000;
/**
* Just after its reset an arm may still be heard on g1v0. Later than this, one heard on g1v0 has booted it again:
* MCUboot didn't take Even's firmware.
*/
const OLD_FIRMWARE_GRACE_MS = 15_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.
* The install and uninstall page on a G1, in place of OnboardingFlashViewModel. The two arms are separate devices that
* each take the image over MCUmgr (G1ArmFlashFlow), left first; an uninstall goes right first and puts back both of
* Even's images, the network core's too. There is nothing on the lens to confirm with while an arm runs Even's
* firmware, 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.
@@ -43,12 +60,18 @@ const FIRST_PAIRING_MS = 120_000;
export class G1FlashViewModel extends Observable {
private phase: Phase = "intro";
private readonly fromOnboarding: boolean;
private readonly uninstalling: boolean;
private readonly scanner = new G1ArmScanner();
private image: BuiltG1Firmware | null = null;
private evenImage: BuiltEvenG1Firmware | null = null;
private flasher: G1Flasher | null = null;
private generation = 0;
private disposed = false;
private unpairedArm = false;
/** An uninstall's outcome, for the last page: an arm's store erased, a pairing this phone couldn't remove, an arm done. */
private wiped = false;
private pairingLeft = false;
private restoredArm = false;
headline = "Install Faceclaw's Firmware";
status = "";
@@ -59,17 +82,14 @@ export class G1FlashViewModel extends Observable {
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;
}
this.uninstalling = options?.mode === "uninstall";
suppressAutoReconnect();
this.status = `${G1_CASE_INSTRUCTIONS}\n\n${G1_INSTALL_NOTICE}`;
if (this.uninstalling) {
this.headline = "Back to Even's Firmware";
this.status = `${G1_CASE_INSTRUCTIONS}\n\n${G1_UNINSTALL_NOTICE}`;
} else {
this.status = `${G1_CASE_INSTRUCTIONS}\n\n${G1_INSTALL_NOTICE}`;
}
if (options?.autoStart) void this.run();
}
@@ -90,7 +110,7 @@ export class G1FlashViewModel extends Observable {
get primaryLabel(): string {
switch (this.phase) {
case "intro":
return "Install";
return this.uninstalling ? "Uninstall" : "Install";
case "flashed":
return "Finish";
case "error":
@@ -119,7 +139,7 @@ export class G1FlashViewModel extends Observable {
}
onSecondaryTap(): void {
if (this.phase === "intro" || this.phase === "error" || this.phase === "unavailable") this.leave();
if (this.phase === "intro" || this.phase === "error") this.leave();
}
// --- the install ----------------------------------------------------------
@@ -129,21 +149,30 @@ export class G1FlashViewModel extends Observable {
const live = () => !this.disposed && generation === this.generation;
this.setPhase("preparing");
this.setBusy(true);
this.setText("Preparing Firmware", "Getting the firmware ready...");
this.setText("Preparing Firmware", this.uninstalling ? "Getting Even's firmware ready..." : "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)`);
if (this.uninstalling) {
if (!this.evenImage) {
this.evenImage = await buildEvenG1Firmware((progress) => {
if (live()) this.setStatus(describeEvenBuild(progress));
});
this.appendLog(`Even's firmware ${this.evenImage.version} downloaded and verified (${this.evenImage.bytes.toLocaleString()} bytes)`);
}
} else {
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);
}
await this.prepareFonts(live);
if (!live()) return;
this.setPhase("flashing");
this.setText("Installing Firmware", "Listening for your glasses...");
this.setText(this.uninstalling ? "Restoring Even's Firmware" : "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);
@@ -154,6 +183,14 @@ export class G1FlashViewModel extends Observable {
}
saveG1Pair(pair);
if (this.uninstalling) {
for (const side of G1_UNINSTALL_SIDES) {
await this.restoreArm(side, pair, live);
if (!live()) return;
}
this.restored();
return;
}
this.unpairedArm = false;
for (const side of G1_SIDES) {
await this.installArm(side, pair, live);
@@ -231,6 +268,65 @@ export class G1FlashViewModel extends Observable {
this.appendLog(`${side} arm runs ${running.version}`);
}
/**
* Even's firmware back on one arm, then a wait for it to advertise as Even's. An arm already on Even's firmware is
* left alone: a retry goes on from there.
*/
private async restoreArm(side: G1Side, pair: GlassesPairCandidate, live: () => boolean): Promise<void> {
const arm = pair[side]!;
if (arm.g1Firmware === "stock") {
this.appendLog(`${side} arm already runs Even's firmware`);
this.setProgress(g1FlashPercent(side, 1, 1, G1_UNINSTALL_SIDES));
return;
}
const even = this.evenImage!;
this.setProgress(g1FlashPercent(side, 0, 1, G1_UNINSTALL_SIDES));
this.setStatus(`Connecting to the ${side} arm...`);
const result = await this.flash({
address: arm.address,
side,
firmwarePath: even.appPath,
netCorePath: even.netCorePath,
mode: "restore",
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 === "wiping") {
this.setStatus(`Erasing Faceclaw's storage on the ${side} arm, where Even's fonts were. This can take several minutes; keep the ` +
"glasses in the case. Nothing else has changed yet.");
} else if (state === "flashing") this.setStatus(`Sending Even's firmware to the ${side} arm. Its firmware hasn't 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, G1_UNINSTALL_SIDES)));
if (!live()) return;
if (result.wiped) this.wiped = true;
this.setProgress(g1FlashPercent(side, 1, 1, G1_UNINSTALL_SIDES));
this.setStatus(`The ${side} arm is restarting into Even's firmware. This takes a minute or two; keep it in the case.`);
const resetAt = Date.now();
const identity = loadPairedGlassesIdentity();
const back = await this.scanner.waitForArm(side, identity?.serial ?? pair.serial, RESTORE_RETURN_MS,
(heard) => heard.g1Firmware === "stock" || Date.now() - resetAt >= OLD_FIRMWARE_GRACE_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.");
}
if (back.g1Firmware !== "stock") {
throw new Error(`The ${side} arm came back on Faceclaw's firmware: it didn't take Even's. Retry to try again.`);
}
saveG1Arm(side, back);
this.restoredArm = true;
// Even's app makes its own pairing with Even's firmware; the one this phone made with g1v0 would only be in its way.
this.forgetPairing(back.address);
if (back.address !== arm.address) this.forgetPairing(arm.address);
this.appendLog(`${side} arm runs Even's firmware`);
}
private forgetPairing(address: string): void {
if (!forgetG1Pairing(address)) this.pairingLeft = true;
}
private async flash(
options: G1FlasherOptions,
onState?: (state: string) => void,
@@ -271,6 +367,28 @@ export class G1FlashViewModel extends Observable {
: ""));
}
private restored(): void {
// Stays manually disconnected: Faceclaw would only find firmware it can't run.
this.setBusy(false);
this.setProgress(100);
this.setPhase("flashed");
if (!this.restoredArm) {
this.setText("All Done", "Both arms already run Even's firmware.");
return;
}
const steps = [`Both arms run Even's firmware ${EVEN_G1_RESTORE.version}.`];
if (this.pairingLeft) {
steps.push("Before pairing them in Even's app, remove both arms in this phone's Bluetooth settings (\"Forget This Device\"): " +
"Faceclaw's firmware made that pairing, and Even's firmware makes its own.");
} else {
steps.push("To use them, pair them in Even's app.");
}
if (this.wiped) {
steps.push("Even's Chinese, Japanese and Korean text and its demo pictures were erased with Faceclaw's storage, and don't come back.");
}
this.setText("All Done", steps.join("\n\n"));
}
private failed(message: string): void {
this.setBusy(false);
this.setPhase("error");
@@ -278,8 +396,10 @@ export class G1FlashViewModel extends Observable {
}
private finish(): void {
setPreviewOnlyMode(false);
setOnboardingCompleted(true);
if (!this.uninstalling) {
setPreviewOnlyMode(false);
setOnboardingCompleted(true);
}
this.teardown();
finishOnboardingNavigation();
}
@@ -344,6 +464,17 @@ export class G1FlashViewModel extends Observable {
}
}
function describeEvenBuild(progress: G1BuildProgress): string {
switch (progress) {
case "downloading":
return "Downloading Even's firmware from Even's firmware server...";
case "verifying":
return "Verifying the download...";
default:
return "Saving the firmware...";
}
}
function describeBuild(progress: G1BuildProgress): string {
switch (progress) {
case "downloading":
+2 -1
View File
@@ -1,4 +1,5 @@
import { Frame, Observable, Screen } from "@nativescript/core";
import { EVEN_G1_RESTORE } from "../g1/even-firmware";
import { glassesTypeSetting, type GlassesType } from "../ui/dashboard-settings";
import { isPreviewOnlyMode } from "./onboarding-state";
@@ -38,7 +39,7 @@ function firmwareBody(glasses: GlassesType): string {
return `Faceclaw only runs on a RayNeo iO that has Faceclaw's custom firmware installed. This app can't install it on an iO, so that has to be done separately before you pair your glasses. ${WARRANTY_NOTE}\n\n${PREVIEW_HINT}`;
}
const restore = glasses === "g1"
? "Returning to the official firmware later takes a computer."
? `You can return to the official firmware later from Faceclaw, as version ${EVEN_G1_RESTORE.version}.`
: "You can uninstall and return to the official firmware later, by reconnecting the official Even Realities app.";
return `Faceclaw only runs on ${GLASSES_MAKER[glasses].product} glasses that have Faceclaw's custom firmware installed. Next, Faceclaw will pair with your glasses, check their firmware, and install the custom firmware if it isn't there yet.\n\nFlashing replaces the official firmware. ${restore} ${WARRANTY_NOTE}\n\n${PREVIEW_HINT}`;
}
@@ -21,22 +21,31 @@ class G1FlashTimings(
@JvmField val heartbeatMs: Int = 8_000,
@JvmField val pollMs: Int = 200,
@JvmField val uploadRetries: Int = 40,
/** How often a store job's state is asked for while its notice hasn't come. */
@JvmField val storePollMs: Int = 2_000,
/** Erasing the store over Even's old fonts and pictures takes minutes. */
@JvmField val wipeMs: Int = 1_800_000,
@JvmField val crcMs: Int = 30_000,
)
/**
* 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.
* g1_firmware/flash.py. The caller handles one arm at a time and looks for the arm again afterwards: it restarts, and
* coming off firmware older than g1v0 0.5.66 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.
*
* [Mode.RESTORE] puts Even's firmware back on an arm running g1v0: both of a release's images, the application core's
* ([firmwarePath]) and the network core's ([netCorePath]), as Even's own update does, so the two always match.
*/
class G1ArmFlashFlow(
private val link: StockLink,
private val address: String,
private val side: String,
private val firmwarePath: String,
private val netCorePath: String,
private val mode: Mode,
/** How long to keep trying to reach the arm and pair with it. */
private val connectWindowMs: Int,
@@ -52,20 +61,30 @@ class G1ArmFlashFlow(
UPDATE,
/** Only say what the arm runs, and pair with it. */
PROBE,
/** The arm runs g1v0 and gets Even's firmware back. */
RESTORE,
}
companion object {
const val TAG = "FaceclawG1Flash"
private const val MIN_BATTERY_PERCENT = 30
private const val ANY_STORE_JOB = -1
private const val STORE_JOB_INTERRUPTED = -1
fun mode(name: String): Mode = when (name) {
"stock" -> Mode.STOCK
"update" -> Mode.UPDATE
"probe" -> Mode.PROBE
"restore" -> Mode.RESTORE
else -> throw IllegalArgumentException("unknown mode $name")
}
}
/** One image of an install: MCUboot's number for it, its bytes and the hash its slot is checked against. */
private class Part(val imageIndex: Int, val bytes: ByteArray, val label: String) {
val hash: ByteArray = G1Smp.imageHash(bytes)
}
private class LinkLostException(message: String) : Exception(message)
/** The arm has no g1v0 service. */
@@ -89,6 +108,9 @@ class G1ArmFlashFlow(
private var stockBattery: Int? = null
private var stockBatteryLatch: Latch? = null
/** `NOTICE` 8s since the store job now waited for was asked for. */
private val storeNotices = ArrayList<G1Protocol.StoreNotice>()
/** The OS's half of a stale pairing goes once per run: a second failure isn't that. */
private var bondRemoved = false
@@ -111,7 +133,11 @@ class G1ArmFlashFlow(
fun run() {
link.setListener(this)
try {
if (mode == Mode.PROBE) probe() else install()
when (mode) {
Mode.PROBE -> probe()
Mode.RESTORE -> restore()
else -> install()
}
} catch (e: Exception) {
val message = if (cancelled) "Cancelled." else StockLinkSession.messageOf(e)
log("failed: $message")
@@ -135,13 +161,15 @@ class G1ArmFlashFlow(
listener.onComplete(true, """{"firmware":"g1v0","version":"${hello.version}","safeMode":${hello.safeMode},"inCase":${hello.inCase},"battery":${batteryPercent()}}""")
}
private fun readFirmware(path: String): ByteArray = try {
readImage(path)
} catch (e: Exception) {
throw IllegalStateException("could not read the firmware: " + StockLinkSession.messageOf(e), e)
}
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 image = readFirmware(firmwarePath)
val version = G1Smp.imageVersion(image)
val hash = G1Smp.imageHash(image)
log("image $version, ${image.size} bytes, hash ${BinaryEncoding.bytesToHex(hash.copyOf(8))}")
@@ -166,15 +194,15 @@ class G1ArmFlashFlow(
val slots = retrying { images() }
for (slot in slots) log(slot.toString())
listener.onState("flashing", side)
if (holdsImage(slots, hash)) {
if (holdsImage(slots, G1Smp.IMAGE_APP, 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)
upload(image, G1Smp.IMAGE_APP)
log("uploaded in ${(now() - startedAt) / 1000} s")
}
if (!holdsImage(retrying { images() }, hash)) {
if (!holdsImage(retrying { images() }, G1Smp.IMAGE_APP, hash)) {
throw IllegalStateException("The $side arm's second slot doesn't hold the image after the upload. Nothing was installed.")
}
throwIfCancelled()
@@ -184,6 +212,82 @@ class G1ArmFlashFlow(
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")
reset()
listener.onState("rebooting", side)
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
}
/**
* Even's firmware back on an arm running g1v0: the store cleared if g1v0 ever wrote to it, then both images uploaded
* and checked, and only then marked for MCUboot, the network core first. MCUboot installs both at the reset, the
* network core through its own path to that core, as at every update from Even.
*/
private fun restore() {
listener.onState("validating", side)
val parts = listOf(
Part(G1Smp.IMAGE_NET_CORE, readFirmware(netCorePath), "network core"),
Part(G1Smp.IMAGE_APP, readFirmware(firmwarePath), "application"),
)
for (part in parts) log("${part.label} image: ${part.bytes.size} bytes, hash ${BinaryEncoding.bytesToHex(part.hash.copyOf(8))}")
listener.onState("connecting", side)
bringUp()
listener.onState("checking", side)
val hello = hello()
log("runs g1v0 ${hello.version}, safe mode ${hello.safeMode}, in the case ${hello.inCase}, encrypted ${hello.encrypted}")
requireBattery(batteryPercent())
val wiped = clearStore(hello)
val slots = retrying { images() }
for (slot in slots) log(slot.toString())
listener.onState("flashing", side)
val total = parts.sumOf { it.bytes.size }
var before = 0
for ((index, part) in parts.withIndex()) {
if (holdsImage(slots, part.imageIndex, part.hash)) {
log("the ${part.label}'s second slot already holds Even's image")
listener.onProgress(side, index + 1, parts.size, part.bytes.size, part.bytes.size, (before + part.bytes.size).toLong(), total.toLong())
} else {
val startedAt = now()
upload(part.bytes, part.imageIndex, index + 1, parts.size, before, total)
log("${part.label} uploaded in ${(now() - startedAt) / 1000} s")
}
before += part.bytes.size
}
val uploaded = retrying { images() }
for (part in parts) {
if (!holdsImage(uploaded, part.imageIndex, part.hash)) {
throw IllegalStateException("The $side arm's slot for its ${part.label} doesn't hold Even's image after the upload. Nothing was installed.")
}
}
throwIfCancelled()
listener.onState("committing", side)
// The network core first. If the second request fails, what's left pending is Even's network core under g1v0,
// which g1v0 works with (its fallback installs this very image); Even's application over the older network core
// is the combination that has never been tried.
for (part in parts) {
val permanent = part.imageIndex == G1Smp.IMAGE_APP
val reply = smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(part.hash, permanent), timings.smpReplyMs)
val code = G1Smp.replyCode(reply)
if (code != 0) {
throw IllegalStateException("The $side arm refused Even's ${part.label} image (error $code). The arm wasn't restarted; retry to try again.")
}
}
val marked = retrying { images() }
for (slot in marked) log(slot.toString())
for (part in parts) {
if (!marked.any { it.image == part.imageIndex && it.slot == 1 && it.hash.contentEquals(part.hash) && "pending" in it.flags }) {
throw IllegalStateException("The $side arm didn't mark Even's ${part.label} image for installing. The arm wasn't restarted; retry to try again.")
}
}
log("both images marked: MCUboot installs them at the next boot")
reset()
listener.onState("rebooting", side)
listener.onComplete(true, """{"flashed":true,"firmware":"stock","wiped":$wiped}""")
}
private fun reset() {
try {
smp(G1Smp.OP_WRITE, G1Smp.GROUP_OS, G1Smp.CMD_OS_RESET, emptyMap(), timings.resetReplyMs)
} catch (e: StockTimeoutException) {
@@ -191,8 +295,144 @@ class G1ArmFlashFlow(
} catch (e: LinkLostException) {
log("the link went down with the reset")
}
listener.onState("rebooting", side)
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
}
// ---- the asset store ---------------------------------------------------------
/**
* Before Even's firmware goes back: g1v0's asset store took the flash where Even's fonts and pictures were, so if it
* ever wrote there, Even's firmware must meet erased flash (flash.py's `wipe_store`). A store that was never written
* is left alone, and Even's data with it. True when it was erased.
*/
private fun clearStore(hello: G1Protocol.Hello): Boolean {
repeat(3) {
val info = assetInfo()
if (info == null) {
log("no asset store: this firmware never wrote where Even's data is")
return false
}
if (!info.available) {
log("the asset store is unavailable, so nothing was written to it")
return false
}
if (info.running) {
// A retried request can find its own job running, as can a retry after a link lost during a wipe.
log("a storage job is running: waiting for it to end")
clearStoreNotices()
waitStoreJob(ANY_STORE_JOB, timings.wipeMs.toLong())
return@repeat
}
if (!storeWritten(info, hello)) {
log("the asset store was never written: Even's fonts and pictures stay as they are")
return false
}
if (hello.safeMode) throw IllegalStateException(safeModeMessage())
listener.onState("wiping", side)
log("erasing the asset store (${info.assets} assets, commit ${info.seq})")
val startedAt = now()
clearStoreNotices()
when (val status = control(G1Protocol.OP_ASSET_FORMAT, G1Protocol.assetFormatRequest(wipe = true)).status) {
0 -> {
val result = waitStoreJob(G1Protocol.STORE_JOB_FORMAT, timings.wipeMs.toLong())
if (result == STORE_JOB_INTERRUPTED) {
throw IllegalStateException("The $side arm restarted while erasing Faceclaw's storage. Nothing was installed; retry to finish it.")
}
if (result != 0) {
throw IllegalStateException("The $side arm couldn't erase Faceclaw's storage (error $result). Nothing was installed.")
}
log("asset store erased in ${(now() - startedAt) / 1000} s")
return true
}
G1Protocol.STATUS_SAFE_MODE -> throw IllegalStateException(safeModeMessage())
// A job runs: the next round waits for it.
G1Protocol.STATUS_ASSET -> {}
else -> throw IllegalStateException("The $side arm refused to erase Faceclaw's storage (error $status). Nothing was installed.")
}
}
throw IllegalStateException("The $side arm's storage couldn't be erased. Nothing was installed.")
}
private fun safeModeMessage(): String =
"The $side arm is in safe mode (its firmware restarted repeatedly), where it can't erase Faceclaw's storage, and that has to " +
"happen before Even's firmware goes back. Install Faceclaw's firmware again, then uninstall it. Nothing was installed."
/**
* Whether g1v0 ever wrote to the store. It only reads it at boot, so with no assets and no commit nothing was written,
* unless a format erased the directory's two sectors (a format resets the commit count), which their fingerprint shows.
*/
private fun storeWritten(info: G1Protocol.AssetInfo, hello: G1Protocol.Hello): Boolean {
if (info.assets > 0 || info.seq != 0L) return true
if (hello.safeMode) {
log("safe mode: the directory can't be checked")
return true
}
val nonErased = flashNonErased(G1Protocol.STORE_ADDRESS, G1Protocol.STORE_DIRECTORY_BYTES)
log("the store's directory sectors: ${nonErased ?: "unknown"} bytes not erased")
return nonErased == null || nonErased == 0L
}
/** How many bytes of flash [from]…[from] + [n] - 1 aren't 0xFF, or null when the arm didn't say. */
private fun flashNonErased(from: Int, n: Int): Long? {
clearStoreNotices()
val status = try {
control(G1Protocol.OP_FLASH_CRC, G1Protocol.flashCrcRequest(from, n)).status
} catch (e: StockTimeoutException) {
return null
}
// 13: a crc job runs, which a retried request finds when the first one's reply was lost; its notice says the same.
if (status != 0 && status != G1Protocol.STATUS_ASSET) return null
val deadline = now() + timings.crcMs
while (now() < deadline) {
throwIfCancelled()
val notice = lock.withLock {
storeNotices.firstOrNull { it.job == G1Protocol.STORE_JOB_CRC && it.address == from && it.n == n }
}
if (notice != null) return if (notice.result == 0) notice.nonErased else null
if (!link.isConnected(address)) return null
sleeper.sleep(timings.pollMs.toLong())
}
return null
}
private fun assetInfo(): G1Protocol.AssetInfo? {
val reply = control(G1Protocol.OP_ASSET_INFO)
return if (reply.status == 0) G1Protocol.parseAssetInfo(reply.body) else null
}
private fun clearStoreNotices() = lock.withLock { storeNotices.clear() }
/**
* The result of the store job running now: its `NOTICE` 8, or `ASSET_INFO`'s state once it has ended (a notice is lost
* with the link, and the job goes on without it). [STORE_JOB_INTERRUPTED] when the arm restarted meanwhile, which ends
* a job unfinished.
*/
private fun waitStoreJob(job: Int, timeoutMs: Long): Int {
val deadline = now() + timeoutMs
var askAt = now() + timings.storePollMs
while (true) {
throwIfCancelled()
val notice = lock.withLock { storeNotices.firstOrNull { job == ANY_STORE_JOB || it.job == job } }
if (notice != null) return notice.result
if (now() >= deadline) throw StockTimeoutException("the $side arm's storage job didn't end within ${timeoutMs / 60_000} minutes")
if (now() >= askAt) {
askAt = now() + timings.storePollMs
val info = try {
assetInfo()
} catch (e: Exception) {
if (e !is StockTimeoutException && e !is LinkLostException) throw e
log("no answer while the storage job runs (${e.message})")
reconnectIfNeeded()
null
}
when (info?.state) {
G1Protocol.STORE_DONE -> return info.lastError
G1Protocol.STORE_FAILED -> return if (info.lastError != 0) info.lastError else G1Protocol.STATUS_ASSET
// A job leaves the state at done or failed until the next boot.
G1Protocol.STORE_IDLE -> return STORE_JOB_INTERRUPTED
}
}
sleeper.sleep(timings.pollMs.toLong())
}
}
private fun requireBattery(percent: Int?) {
@@ -202,21 +442,24 @@ class G1ArmFlashFlow(
}
}
private fun holdsImage(slots: List<G1Smp.Slot>, hash: ByteArray): Boolean =
slots.any { it.image == 0 && it.slot == 1 && it.hash.contentEquals(hash) }
private fun holdsImage(slots: List<G1Smp.Slot>, imageIndex: Int, hash: ByteArray): Boolean =
slots.any { it.image == imageIndex && 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) {
/**
* MCUmgr answers each chunk with the offset it wants next, so an upload resumes after a lost link. Progress counts
* [before] bytes of earlier parts out of [total].
*/
private fun upload(image: ByteArray, imageIndex: Int, part: Int = 1, parts: Int = 1, before: Int = 0, total: Int = image.size) {
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)
smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_UPLOAD, G1Smp.uploadRequest(image, offset, fileSha, imageIndex), timings.uploadReplyMs)
} catch (e: Exception) {
if (e !is StockTimeoutException && e !is LinkLostException) throw e
failures++
@@ -231,7 +474,7 @@ class G1ArmFlashFlow(
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())
listener.onProgress(side, part, parts, offset, image.size, (before + offset).toLong(), total.toLong())
}
}
@@ -525,6 +768,11 @@ class G1ArmFlashFlow(
stockBatteryLatch?.countDown()
}
} else if (characteristicUuid.equals(G1Ble.EVT_CHAR_UUID, ignoreCase = true)) {
val notice = G1Protocol.parseStoreNotice(data)
if (notice != null) {
lock.withLock { storeNotices.add(notice) }
return
}
val reply = G1Protocol.parseReply(data) ?: return
lock.withLock {
if (reply.tag == controlTag) {
@@ -39,9 +39,17 @@ object G1Protocol {
const val OP_PROPS = 0x0A
const val OP_MIC = 0x13
const val OP_EVENTS = 0x14
const val OP_ASSET_INFO = 0x17
const val OP_ASSET_FORMAT = 0x1B
const val OP_FLASH_CRC = 0x1C
const val OP_FC_INFO = 0x1D
const val OP_PROP_SET = 0x1E
/** Control statuses (VM.md §1). */
const val STATUS_SAFE_MODE = 7
/** A store request: a job runs, no space, no store. */
const val STATUS_ASSET = 13
const val EV_NOTICE = 0x05
const val EV_MIC_DATA = 0x06
const val EV_INPUT = 0x07
@@ -65,6 +73,18 @@ object G1Protocol {
const val NOTICE_MIC_STOPPED = 5
const val MIC_STOPPED_LEASE = 3
const val NOTICE_GUARD = 7
/** A store job ended (VM.md §6.10). */
const val NOTICE_STORE_JOB = 8
const val STORE_JOB_FORMAT = 3
const val STORE_JOB_CRC = 4
/** `ASSET_INFO`'s job states. */
const val STORE_IDLE = 0
const val STORE_DONE = 4
const val STORE_FAILED = 5
/** The asset store's partition in the arm's QSPI flash, where Even's fonts and pictures were; its first two sectors hold its directory. */
const val STORE_ADDRESS = 0x140000
const val STORE_DIRECTORY_BYTES = 2 * 4096
const val PROP_BATT_PCT = 0x11
const val PROP_CHARGE = 0x12
@@ -156,6 +176,50 @@ object G1Protocol {
return Notice(data[EVENT_HEADER].toInt() and 255, data.copyOfRange(EVENT_HEADER + 1, data.size))
}
/** `ASSET_FORMAT` frees the whole store; with [wipe] it also erases every sector that isn't erased already. */
fun assetFormatRequest(wipe: Boolean): ByteArray =
le32(0x534B4153) + if (wipe) le32(0x50570000) else ByteArray(0)
/** `FLASH_CRC`: a read-only fingerprint of flash bytes address…address + n - 1, given in `NOTICE` 8. */
fun flashCrcRequest(address: Int, n: Int): ByteArray = le32(address) + le32(n)
class AssetInfo(
@JvmField val assets: Int,
@JvmField val state: Int,
@JvmField val lastError: Int,
/** Without a usable flash there is no store, and nothing was ever written to it. */
@JvmField val available: Boolean,
/** The directory's commit count: 0 for a store that is empty and never was written, or was formatted since. */
@JvmField val seq: Long,
) {
val running: Boolean get() = state in 1..3
}
fun parseAssetInfo(body: ByteArray): AssetInfo? {
if (body.size < 20) return null
return AssetInfo(body[12].toInt() and 255, body[13].toInt() and 255, body[14].toInt() and 255, body[15].toInt() and 1 != 0,
u32(body, 16).toLong() and 0xffffffffL)
}
class StoreNotice(
@JvmField val job: Int,
@JvmField val result: Int,
/** A crc job's range, crc32 and how many of its bytes are not 0xFF; 0 for the other jobs. */
@JvmField val address: Int,
@JvmField val n: Int,
@JvmField val nonErased: Long,
)
fun parseStoreNotice(data: ByteArray): StoreNotice? {
val notice = parseNotice(data) ?: return null
val body = notice.body
if (notice.kind != NOTICE_STORE_JOB || body.size < 18) return null
return StoreNotice(body[0].toInt() and 255, body[1].toInt() and 255, u32(body, 2), u32(body, 6), u32(body, 14).toLong() and 0xffffffffL)
}
private fun le32(value: Int): ByteArray =
byteArrayOf(value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte())
/**
* What the arm's light reading looks like to [BrightnessPolicy] and the Developer app: a live passive poll in the
* G2 custom firmware's report (settings field 105), whose value counts tenths of a lux.
@@ -197,17 +197,28 @@ object G1Smp {
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?> {
/** MCUboot's image numbers on an nRF5340: the application core, and the network core (the Bluetooth controller). */
const val IMAGE_APP = 0
const val IMAGE_NET_CORE = 1
/**
* The first chunk also says what is coming, which lets the arm resume an upload of the same file, and which image it
* is: each has its own second slot.
*/
fun uploadRequest(image: ByteArray, offset: Int, fileSha256: ByteArray, imageIndex: Int = IMAGE_APP): 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)
mapOf("image" to imageIndex, "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)
/**
* Marks the image with this hash for MCUboot's next boot. [permanent] false is a test install, which is what Even's app
* and g1v0's own network-core fallback ask for on image 1; the network core has no copy to go back to either way.
*/
fun confirmRequest(imageHash: ByteArray, permanent: Boolean = true): Map<String, Any?> = mapOf("hash" to imageHash, "confirm" to permanent)
/** Joins notifications into replies; [feed] gives each complete one as sequence number and body. */
class Assembler {
@@ -172,8 +172,8 @@ class IosFirmwareFlasher(rightAddress: String, leftAddress: String, firmwarePath
}
}
/** 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) {
/** iOS host for the shared [G1ArmFlashFlow]: one G1 arm's install, its restore to Even's firmware, or a question about what it runs. */
class IosG1Flasher(address: String, side: String, firmwarePath: String, netCorePath: String, mode: String, connectWindowMs: Int) {
private val link = IosBleCentral()
private val lock = IosProtocolPlatform.createLock()
private var started = false
@@ -184,6 +184,7 @@ class IosG1Flasher(address: String, side: String, firmwarePath: String, mode: St
address,
side,
firmwarePath,
netCorePath,
G1ArmFlashFlow.mode(mode),
connectWindowMs,
object : FaceclawFirmwareFlasherListener {
+34 -1
View File
@@ -3,7 +3,8 @@ 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 { readZipEntry, assembleG1Image, decodeG1OwnBytes, extractEvenG1Images, G1FirmwareError } = require('../.test-build/app/g1/firmware-image.js');
const { EVEN_G1_RESTORE } = require('../.test-build/app/g1/even-firmware.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');
@@ -178,6 +179,38 @@ test('the native flow\'s answer is read, and nonsense is no answer', () => {
assert.deepEqual(plan.parseG1FlashResult('null'), {});
});
test('an uninstall goes right first, and its bar follows that order', () => {
assert.deepEqual([...plan.G1_UNINSTALL_SIDES], ['right', 'left']);
assert.equal(plan.g1FlashPercent('right', 0, 100, plan.G1_UNINSTALL_SIDES), 0);
assert.equal(plan.g1FlashPercent('right', 100, 100, plan.G1_UNINSTALL_SIDES), 50);
assert.equal(plan.g1FlashPercent('left', 50, 100, plan.G1_UNINSTALL_SIDES), 75);
});
test('Even\'s two images come out of its download only when each is the one published', () => {
const app = noise(9000, 7);
const netCore = noise(4000, 8);
const zip = zipOf([
{ name: 'app_update.bin', data: app },
{ name: 'net_core_app_update.bin', data: netCore, deflate: true },
{ name: 'manifest.json', data: noise(100, 9) },
]);
const release = { version: '9.9.9', zipUrl: 'u', zipSha256: sha(zip), appSha256: sha(app), netCoreSha256: sha(netCore) };
const out = extractEvenG1Images(zip, release, sha);
assert.deepEqual(Buffer.from(out.app), Buffer.from(app));
assert.deepEqual(Buffer.from(out.netCore), Buffer.from(netCore));
assert.throws(() => extractEvenG1Images(zip, { ...release, zipSha256: sha(app) }, sha), (e) => e instanceof G1FirmwareError && /download failed/.test(e.message));
assert.throws(() => extractEvenG1Images(zip, { ...release, netCoreSha256: sha(app) }, sha), /net_core_app_update\.bin in Even's download/);
});
test('the release an uninstall puts back is the one the bundled firmware was built from', () => {
// g1v0 embeds Even's network core from this same download, which the bundle's manifest checks by hash.
assert.equal(EVEN_G1_RESTORE.version, G1V0_IMAGE.stockVersion);
assert.equal(EVEN_G1_RESTORE.zipUrl, G1V0_IMAGE.stockZipUrl);
assert.equal(EVEN_G1_RESTORE.zipSha256, G1V0_IMAGE.stockZipSha256);
const net = G1V0_IMAGE.parts.find((part) => part.file === 'net_core_app_update.bin' && part.fileOffset === 0);
assert.equal(net?.sha256, EVEN_G1_RESTORE.netCoreSha256);
});
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);
@@ -42,10 +42,11 @@ private fun testImage(version: Triple<Int, Int, Int> = Triple(0, 5, 64), payload
}
/**
* 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.
* One arm behind the StockLink port: MCUmgr's image and OS groups as flash.py meets them on real arms, and g1v0's HELLO,
* PROPS and asset store. Requests are answered synchronously, from the write. [netImage] is what a restore puts in image
* 1's slot.
*/
private class FakeArm(private val image: ByteArray, var stock: Boolean = false) : StockLink {
private class FakeArm(private val image: ByteArray, var stock: Boolean = false, private val netImage: ByteArray? = null) : StockLink {
var inbound: StockLinkListener? = null
var connected = false
var bond = BondState.BONDED
@@ -59,13 +60,44 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
var safeMode = false
var battery = 80
var slot1Hash: ByteArray? = null
/** The hash in each image's second slot. */
val slotHashes = HashMap<Int, ByteArray>()
var slot1Hash: ByteArray?
get() = slotHashes[0]
set(value) {
if (value == null) slotHashes.remove(0) else slotHashes[0] = value
}
/** Images marked for the next boot, and whether permanently. */
val pending = HashMap<Int, Boolean>()
val confirms = ArrayList<Pair<Int, Boolean>>()
/** The image of the upload in progress, and what each image's last whole upload was. */
var uploadImage = -1
val uploads = HashMap<Int, ByteArray>()
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
/** Only this image's confirm is refused; -1: any. */
var confirmRefusalImage = -1
/** This image's confirm is answered, and the list doesn't show it pending. */
var unmarkedImage = -1
/** No `ASSET_INFO`, as before 0.5.56. */
var storeSupported = true
var storeAvailable = true
var storeAssets = 0
var storeSeq = 0L
var storeState = 0
var storeError = 0
/** Bytes that aren't 0xFF in the store's directory sectors: Even's data, until a format. */
var directoryNonErased = 4096L
/** The format's NOTICE 8 never comes. */
var loseStoreNotice = false
/** The arm restarts during the wipe: no notice, and the job state back to idle. */
var wipeInterrupted = false
val formats = ArrayList<Boolean>()
var dropAtOffset = -1
var silentRequests = 0
/** The chunk at this offset gets no answer, once. */
@@ -157,6 +189,9 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
private fun control(request: ByteArray) {
val op = request[0].toInt() and 0xff
val tag = request[1]
val args = request.copyOfRange(2, request.size)
var status = 0
var after: (() -> Unit)? = null
val body = when (op) {
G1Protocol.OP_HELLO -> {
val parts = runningVersion.split(".").map { it.toInt().toByte() }
@@ -164,11 +199,67 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
byteArrayOf(5, parts[0], parts[1], parts[2], 1, flags.toByte(), 0)
}
G1Protocol.OP_PROPS -> byteArrayOf(battery.toByte(), 0, 0, 0)
G1Protocol.OP_ASSET_INFO -> {
if (!storeSupported) {
status = 2
ByteArray(0)
} else {
ByteArray(12) + byteArrayOf(storeAssets.toByte(), storeState.toByte(), storeError.toByte(), if (storeAvailable) 1 else 0) +
le32(storeSeq.toInt())
}
}
G1Protocol.OP_FLASH_CRC -> {
calls.add("crc")
assertContentEquals(G1Protocol.flashCrcRequest(G1Protocol.STORE_ADDRESS, G1Protocol.STORE_DIRECTORY_BYTES), args)
if (safeMode) {
status = 7
} else {
after = { storeNotice(G1Protocol.STORE_JOB_CRC, 0, args + le32(0x1234) + le32(directoryNonErased.toInt())) }
}
ByteArray(0)
}
G1Protocol.OP_ASSET_FORMAT -> {
calls.add("format")
assertContentEquals(G1Protocol.assetFormatRequest(wipe = true), args)
when {
safeMode -> status = 7
storeState in 1..3 -> status = 13
else -> {
formats.add(true)
storeAssets = 0
storeSeq = 0
directoryNonErased = 0
if (wipeInterrupted) {
storeState = 0
} else {
storeState = 4
storeError = 0
if (!loseStoreNotice) after = { storeNotice(G1Protocol.STORE_JOB_FORMAT, 0, ByteArray(16)) }
}
}
}
ByteArray(0)
}
else -> ByteArray(0)
}
val event = ByteArray(9) + byteArrayOf(tag, 0) + body
val event = ByteArray(9) + byteArrayOf(tag, status.toByte()) + body
event[0] = (0x80 or op).toByte()
inbound?.onNotification(ARM, G1Ble.EVT_CHAR_UUID, event)
after?.invoke()
}
private fun storeNotice(job: Int, result: Int, detail: ByteArray) {
val event = ByteArray(9) + byteArrayOf(G1Protocol.NOTICE_STORE_JOB.toByte(), job.toByte(), result.toByte()) + detail
event[0] = G1Protocol.EV_NOTICE.toByte()
inbound?.onNotification(ARM, G1Ble.EVT_CHAR_UUID, event)
}
private fun le32(value: Int): ByteArray = byteArrayOf(value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte())
private fun imageOf(index: Int): ByteArray = when (index) {
0 -> image
1 -> netImage ?: throw AssertionError("an upload to image 1")
else -> throw AssertionError("an upload to image $index")
}
private fun smp(frame: ByteArray) {
@@ -191,17 +282,26 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
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"])
if (off == 0) {
// A first chunk names the image; the same file again resumes where it stopped, as MCUmgr does.
val index = (body["image"] as Long).toInt()
val expected = imageOf(index)
assertEquals(expected.size.toLong(), body["len"])
assertContentEquals(sha256(expected), body["sha"] as ByteArray)
if (index != uploadImage || uploadOffset >= expected.size) {
uploadImage = index
uploadOffset = 0
uploaded = ByteArray(0)
}
}
if (off == uploadOffset) {
val data = body["data"] as ByteArray
uploaded += data
uploadOffset += data.size
if (uploadOffset == image.size) slot1Hash = if (corruptAfterUpload) ByteArray(32) else G1Smp.imageHash(uploaded)
if (uploadOffset == imageOf(uploadImage).size) {
uploads[uploadImage] = uploaded
slotHashes[uploadImage] = if (corruptAfterUpload) ByteArray(32) else G1Smp.imageHash(uploaded)
}
}
if (uploadOffset >= dropAtOffset && dropAtOffset >= 0) {
dropAtOffset = -1
@@ -214,14 +314,31 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
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)) }
for ((index, hash) in slotHashes.toSortedMap()) {
val marked = pending[index]
val entry = mutableMapOf<String, Any?>("image" to index, "slot" to 1, "version" to "0.5.64", "hash" to hash, "bootable" to true)
if (marked != null && index != unmarkedImage) {
entry["pending"] = true
if (marked) entry["permanent"] = true
}
images.add(entry)
}
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))
val hash = body["hash"] as ByteArray
val index = slotHashes.entries.firstOrNull { it.value.contentEquals(hash) }?.key
assertNotNull(index, "a confirm for a hash no slot holds")
if (index == 0 && netImage == null) {
assertEquals(true, body["confirm"])
assertContentEquals(wantHash, hash)
}
val permanent = body["confirm"] as Boolean
confirms.add(index to permanent)
val refused = if (confirmRefusalImage < 0 || confirmRefusalImage == index) confirmRefusal else 0
if (refused == 0) pending[index] = permanent
reply(op, group, seq, cmd, mapOf("rc" to refused))
}
group == 0 && cmd == 5 -> {
calls.add("reset")
@@ -262,6 +379,7 @@ private class Recorder : FaceclawFirmwareFlasherListener {
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,
storePollMs = 10, wipeMs = 2_000, crcMs = 200,
)
class G1SmpStockTest {
@@ -370,7 +488,7 @@ 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 })
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()
@@ -464,7 +582,7 @@ class G1ArmFlashFlowTest {
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()
G1ArmFlashFlow(arm, ARM, "left", "image.bin", "", G1ArmFlashFlow.Mode.UPDATE, 100, listener, FAST, testPlatform(), { ByteArray(100) }).run()
assertEquals(false, listener.success)
assertEquals(0, arm.connects)
}
@@ -473,7 +591,7 @@ class G1ArmFlashFlowTest {
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()
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)
}
@@ -653,6 +771,169 @@ class G1ArmFlashFlowTest {
assertEquals(0, arm.bondRequests)
}
// ---- back to Even's firmware ----
private val evenApp = testImage(Triple(0, 0, 0), payloadSize = 7000)
private val evenNet = testImage(Triple(0, 0, 1), payloadSize = 3000)
private fun restoreArm(): FakeArm = FakeArm(evenApp, netImage = evenNet).also { it.runningVersion = "0.5.66" }
private fun restore(arm: FakeArm, window: Int = 100): Recorder {
val listener = Recorder()
G1ArmFlashFlow(arm, ARM, "right", "app.bin", "net.bin", G1ArmFlashFlow.Mode.RESTORE, window, listener, FAST, testPlatform(), { path ->
when (path) {
"app.bin" -> evenApp
"net.bin" -> evenNet
else -> throw IllegalStateException("no $path")
}
}).run()
assertNotNull(listener.success, "the flow must always finish")
return listener
}
@Test
fun aRestoreUploadsBothImagesThenMarksTheNetworkCoreFirst() {
val arm = restoreArm()
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals("""{"flashed":true,"firmware":"stock","wiped":false}""", result.detail)
assertContentEquals(evenNet, arm.uploads[1])
assertContentEquals(evenApp, arm.uploads[0])
// Image 1 as a test install, as Even's app and g1v0's fallback do; the application for good.
assertEquals(listOf(1 to false, 0 to true), arm.confirms)
assertEquals(listOf("confirm", "confirm", "list", "reset"), arm.calls.takeLast(4))
assertEquals((evenApp.size + evenNet.size).toLong(), result.total)
assertEquals(result.total, result.progress)
assertTrue("rebooting" in result.states)
}
@Test
fun aStoreNeverWrittenKeepsEvensData() {
val arm = restoreArm()
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals(listOf("crc"), arm.calls.filter { it == "crc" || it == "format" })
assertTrue(arm.formats.isEmpty())
assertFalse("wiping" in result.states)
}
@Test
fun aStoreThatHoldsAssetsIsWipedBeforeAnyUpload() {
val arm = restoreArm()
arm.storeAssets = 2
arm.storeSeq = 5
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals("""{"flashed":true,"firmware":"stock","wiped":true}""", result.detail)
assertEquals(listOf(true), arm.formats)
assertTrue(arm.calls.indexOf("format") < arm.calls.indexOf("upload"))
assertFalse("crc" in arm.calls, "a store with assets needs no fingerprint")
assertTrue("wiping" in result.states)
}
@Test
fun anEmptyStoreWhoseDirectoryWasErasedIsWiped() {
// A format resets the commit count, and erased the two directory sectors over Even's data.
val arm = restoreArm()
arm.directoryNonErased = 0
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals(listOf("crc", "format"), arm.calls.filter { it == "crc" || it == "format" })
}
@Test
fun firmwareWithoutTheStoreIsNotWiped() {
val arm = restoreArm()
arm.storeSupported = false
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertFalse("crc" in arm.calls)
assertFalse("format" in arm.calls)
}
@Test
fun aLostWipeNoticeIsReadFromTheStoreState() {
val arm = restoreArm()
arm.storeAssets = 1
arm.storeSeq = 1
arm.loseStoreNotice = true
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertTrue("\"wiped\":true" in result.detail, result.detail)
}
@Test
fun anArmThatRestartsDuringTheWipeGetsNothingInstalled() {
val arm = restoreArm()
arm.storeAssets = 1
arm.storeSeq = 1
arm.wipeInterrupted = true
val result = restore(arm)
assertEquals(false, result.success)
assertTrue("restarted while erasing" in result.detail, result.detail)
assertFalse("upload" in arm.calls)
assertFalse("confirm" in arm.calls)
}
@Test
fun safeModeWithAWrittenStoreInstallsNothing() {
val arm = restoreArm()
arm.safeMode = true
arm.storeAssets = 1
arm.storeSeq = 1
val result = restore(arm)
assertEquals(false, result.success)
assertTrue("safe mode" in result.detail, result.detail)
assertFalse("format" in arm.calls)
assertFalse("upload" in arm.calls)
}
@Test
fun aLowBatteryStopsARestoreBeforeTheWipe() {
val arm = restoreArm()
arm.battery = 12
arm.storeAssets = 1
arm.storeSeq = 1
val result = restore(arm)
assertEquals(false, result.success)
assertTrue("12%" in result.detail, result.detail)
assertFalse("format" in arm.calls)
assertFalse("upload" in arm.calls)
}
@Test
fun aRefusedNetworkCoreNeverLeavesTheApplicationMarked() {
val arm = restoreArm()
arm.confirmRefusal = 3
arm.confirmRefusalImage = 1
val result = restore(arm)
assertEquals(false, result.success)
assertEquals(listOf(1 to false), arm.confirms)
assertFalse(0 in arm.pending)
assertFalse("reset" in arm.calls)
assertTrue("network core" in result.detail, result.detail)
}
@Test
fun anImageTheArmDidNotMarkIsNoReset() {
val arm = restoreArm()
arm.unmarkedImage = 0
val result = restore(arm)
assertEquals(false, result.success)
assertFalse("reset" in arm.calls)
assertTrue("didn't mark" in result.detail, result.detail)
}
@Test
fun aLostLinkResumesARestoreUpload() {
val arm = restoreArm()
arm.dropAtOffset = 2048
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertContentEquals(evenNet, arm.uploads[1])
assertContentEquals(evenApp, arm.uploads[0])
}
@Test
fun cancellingDuringTheUploadStopsBeforeTheConfirm() {
val arm = FakeArm(image)
@@ -665,3 +946,41 @@ class G1ArmFlashFlowTest {
assertFalse("confirm" in arm.calls)
}
}
class G1StoreProtocolTest {
/** The bytes of scouter_kit's tools/g1host.py: `struct.pack("<II", FORMAT_MAGIC, WIPE_MAGIC)`. */
@Test
fun requestsMatchThePythonTool() {
assertEquals("53414b5300005750", BinaryEncoding.bytesToHex(G1Protocol.assetFormatRequest(wipe = true)))
assertEquals("53414b53", BinaryEncoding.bytesToHex(G1Protocol.assetFormatRequest(wipe = false)))
assertEquals("0000140000200000", BinaryEncoding.bytesToHex(G1Protocol.flashCrcRequest(0x140000, 8192)))
}
@Test
fun assetInfoIsRead() {
// data 10, free 20, largest 30, 2 assets, state 4, error 0, flags 1, seq 0x01020304
val info = G1Protocol.parseAssetInfo(hex("0a000000140000001e00000002040001" + "04030201"))
assertNotNull(info)
assertEquals(2, info.assets)
assertEquals(4, info.state)
assertTrue(info.available)
assertFalse(info.running)
assertEquals(0x01020304L, info.seq)
assertEquals(null, G1Protocol.parseAssetInfo(ByteArray(19)))
}
@Test
fun aStoreJobsNoticeIsRead() {
val crc = hex("05" + "0000000000000000" + "08" + "0400" + "00001400" + "00200000" + "78563412" + "00100000")
val notice = G1Protocol.parseStoreNotice(crc)
assertNotNull(notice)
assertEquals(G1Protocol.STORE_JOB_CRC, notice.job)
assertEquals(0, notice.result)
assertEquals(0x140000, notice.address)
assertEquals(8192, notice.n)
assertEquals(4096L, notice.nonErased)
// Another notice kind, or a short one, is none.
assertEquals(null, G1Protocol.parseStoreNotice(hex("05" + "0000000000000000" + "07" + "2a2a")))
assertEquals(null, G1Protocol.parseStoreNotice(hex("05" + "0000000000000000" + "08" + "0300")))
}
}
+1
View File
@@ -46,6 +46,7 @@
"../app/g1/pako.d.ts",
"../app/g1/firmware-image.ts",
"../app/g1/flash-plan.ts",
"../app/g1/even-firmware.ts",
"../app/g1/firmware/g1v0-image.ts",
"../app/g1/firmware/g1v0-own-bytes.ts",
"../app/apps/calculator/math/*.ts",