From cb78841a9d683c21de541f6ebb7177deb1a53aa5 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Fri, 10 Jul 2026 12:07:15 -0700 Subject: [PATCH] Add (NOT YET TESTED) firmware flashing/OTA-updating We're going to extend the Faceclaw app onboarding process to include checking for and installing the custom firmware (currently handled externally with the scripts in ../g2flash). We'll add script scripts/resetOnboarding.sh that uses adb to reset the app on the attached phone to default/pre-onboarding state for testing. The onboarding process will explain that it's only compatible with custom firmware, with options to either skip and try out the app using only the phone-screen preview (instead of pairing with glasses), or proceed with flashing. If the user proceeds with flashing, we first connect to the glasses (with the existing mechanism), and display an on-glasses confirmation prompt. Because this prompt needs compatibility with stock firmware, it will use a different subset of the BLE protocol than the main app does (in particular, no image containers), so we'll have a separate bluetooth communication class rather than extending FaceclawBleCommunicator. We'll send an init message to start a Hub app, initialize a layout with a text container and a list, populate the text container with a message saying that flashing will void warranty and the list with No and Yes, set up a keepalive/heartbeat message timer, and wait for a menu selection. (Refer to ../g2-kit-unofficial/ble/docs and ../g2-kit-unofficial/ble/gen for protocol details). If the prompt is approved, we go to the flashing screen. On the flashing screen, we first download the official firmware, apply patches to it, and check that it has the expected result hash. See ../g2flash/build_cfw.sh and ../g2flash/apply_patches.py for details. Let's implement everything prior to the update itself now, ie, the on-device confirmation prompt, and downloading, patching and verifying the modded firmware. scripts/resetOnboarding.sh is meant to reset a pref so that Faceclaw reruns its first-run onboarding on next launch, but fails with "No onboarding keys were set. App is already in pre-onboarding state." (And onboarding doesn't trigger on next launch) Thanks. I tested the on-glasses prompt on real hardware and it worked as expected. Next up, let's port the flashing procedure itself. One detail of the flashing procedure worth noting: the two lenses get updated separately, and at the end of updating either lens, both lenses get rebooted, creating a brief period when neither is reachable, so the timeout to look for the second lens should not be too short. --- .../faceclaw/app/FaceclawFirmwareFlasher.java | 649 ++++++++++++++++++ .../app/FaceclawFirmwareFlasherListener.java | 21 + .../faceclaw/app/FaceclawFirmwareUtil.java | 49 ++ .../app/FaceclawFlashPromptCommunicator.java | 412 +++++++++++ .../app/FaceclawFlashPromptListener.java | 16 + .../faceclaw/app/g2protocol/BleProtocol.java | 101 +++ app/g2/firmware-builder.ts | 199 ++++++ app/g2/firmware/cfw-patches.ts | 145 ++++ app/native/firmware-flasher.ts | 101 +++ app/native/flash-prompt-communicator.ts | 82 +++ app/phone-ui/onboarding-flash-page.ts | 10 + app/phone-ui/onboarding-flash-page.xml | 18 + app/phone-ui/onboarding-flash-view-model.ts | 519 ++++++++++++++ app/phone-ui/onboarding-page.ts | 6 +- app/phone-ui/onboarding-state.ts | 14 + app/phone-ui/onboarding-view-model.ts | 24 +- scripts/resetOnboarding.sh | 108 +++ 17 files changed, 2464 insertions(+), 10 deletions(-) create mode 100644 App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java create mode 100644 App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java create mode 100644 App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java create mode 100644 App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java create mode 100644 App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java create mode 100644 app/g2/firmware-builder.ts create mode 100644 app/g2/firmware/cfw-patches.ts create mode 100644 app/native/firmware-flasher.ts create mode 100644 app/native/flash-prompt-communicator.ts create mode 100644 app/phone-ui/onboarding-flash-page.ts create mode 100644 app/phone-ui/onboarding-flash-page.xml create mode 100644 app/phone-ui/onboarding-flash-view-model.ts create mode 100755 scripts/resetOnboarding.sh diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java new file mode 100644 index 00000000..dc57daa8 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java @@ -0,0 +1,649 @@ +package com.faceclaw.app; + +import android.bluetooth.BluetoothGatt; +import android.content.Context; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.util.Log; + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Ports g2flash.py's OTA flash procedure to Android. Streams the EVENOTA + * firmware container to each lens over the firmware-data service using the + * aa21 envelope (BleProtocol.framePb) and the c0/c1 control/data protocol, with + * a heartbeat on the EvenHub control char to keep the session alive. + * + * Lenses are flashed one at a time (left, then right). Finishing either lens + * reboots BOTH lenses, so the second lens is briefly unreachable — the reconnect + * for it uses a generous window rather than failing fast. + * + * Separate from FaceclawBleCommunicator on purpose: this speaks the stock OTA + * protocol and must run before the custom firmware exists. It reuses the GATT + * wrapper (FaceclawBleManager) and framing (BleProtocol). + */ +public class FaceclawFirmwareFlasher implements FaceclawBleListener { + private static final String TAG = "FaceclawFlasher"; + + // OTA message types (envelope sid byte) and control opcodes. + private static final int SID_CTRL = 0xc0; + private static final int SID_DATA = 0xc1; + private static final int SID_HEARTBEAT = 0x80; + private static final int FLAG_OTA = 0x00; + private static final int OP_BEGIN = 0x00; + private static final int OP_FILE_CHECK = 0x01; + private static final int OP_BLOCK = 0x02; + private static final int OP_END = 0x03; + + private static final int BLOCK_SIZE = 4096; + private static final int BLOCK_ACK_TIMEOUT_MS = 4_000; + private static final int CTRL_ACK_TIMEOUT_MS = 8_000; + private static final int BLOCK_NAK_RETRIES = 3; + private static final int COMPONENT_RETRIES = 3; + private static final int HEARTBEAT_INTERVAL_MS = 12_000; + private static final byte[] HEARTBEAT_PAYLOAD = + new byte[] {0x08, 0x0e, 0x10, 0x26, 0x6a, 0x00}; + + // Reconnect windows. The first lens connects from an idle device; the second + // must ride out the post-first-lens reboot of both lenses. + private static final int FIRST_LENS_CONNECT_WINDOW_MS = 30_000; + private static final int SECOND_LENS_CONNECT_WINDOW_MS = 120_000; + private static final int REBOOT_SETTLE_MS = 5_000; + private static final int NOTIFY_SETTLE_MS = 2_500; + private static final int RETRY_DELAY_MS = 2_500; + + // END ack statuses that mean "component accepted": SUCCESS, UPDATING, SYS_RESTART. + private static final int[] END_OK = new int[] {0, 8, 9}; + + // Firmware layout expectations (mirrors g2flash.py). + private static final int EXPECTED_SEGMENTS = 5; + private static final String REQUIRED_SEGMENT = "ota/s200_firmware_ota.bin"; + private static final long APP_LOAD_ADDR = 0x00438000L; + private static final long APP_MAX_END = 0x007F0000L; + private static final int APP_PREAMBLE = 0x20; + + private final Context context; + private final String leftAddress; + private final String rightAddress; + private final String firmwarePath; + private final FaceclawBleManager bleManager; + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + + private final Object lock = new Object(); + private final LinkedBlockingQueue dataAcks = new LinkedBlockingQueue<>(); + + private volatile FaceclawFirmwareFlasherListener listener; + private volatile Thread worker; + private volatile boolean cancelled = false; + private volatile ScheduledExecutorService heartbeatExecutor; + private volatile String heartbeatAddress; + + private int nextSeq = 0; + + public FaceclawFirmwareFlasher(Context context, String rightAddress, String leftAddress, String firmwarePath) { + this.context = context.getApplicationContext(); + this.rightAddress = rightAddress == null ? "" : rightAddress; + this.leftAddress = leftAddress == null ? "" : leftAddress; + this.firmwarePath = firmwarePath == null ? "" : firmwarePath; + this.bleManager = new FaceclawBleManager(this.context); + this.bleManager.setListener(this); + } + + public void setListener(FaceclawFirmwareFlasherListener listener) { + this.listener = listener; + } + + public void start() { + synchronized (lock) { + if (worker != null) { + return; + } + worker = new Thread(this::run, "faceclaw-flasher"); + worker.start(); + } + } + + public void cancel() { + cancelled = true; + Thread w = worker; + if (w != null) { + w.interrupt(); + } + } + + public void close() { + cancel(); + stopHeartbeat(); + try { + bleManager.close(); + } catch (Exception ignored) { + } + } + + private void run() { + try { + if (leftAddress.trim().isEmpty() || rightAddress.trim().isEmpty()) { + throw new IllegalStateException("Both lens addresses are required to flash."); + } + + emitState("validating", ""); + byte[] img = readFile(firmwarePath); + List segs = validate(img); + emitLog("firmware validated: " + segs.size() + " components, " + img.length + " bytes"); + + flashLens("left", leftAddress, img, segs, FIRST_LENS_CONNECT_WINDOW_MS); + if (cancelled) { + emitState("error", "Cancelled."); + emitComplete(false, "Cancelled after the left lens."); + return; + } + + emitState("rebooting", "Left lens done. Both lenses reboot briefly; reconnecting for the right lens."); + sleepInterruptibly(REBOOT_SETTLE_MS); + flashLens("right", rightAddress, img, segs, SECOND_LENS_CONNECT_WINDOW_MS); + + emitState("done", ""); + emitComplete(true, "Both lenses flashed. The glasses are rebooting into the custom firmware."); + } catch (Exception e) { + String message = e.getMessage() == null ? e.toString() : e.getMessage(); + if (cancelled) { + message = "Cancelled."; + } + emitState("error", message); + emitComplete(false, message); + } finally { + teardown(); + } + } + + private void flashLens(String lens, String address, byte[] img, List segs, int connectWindowMs) + throws TimeoutException { + resetSeq(); + emitState("connecting", lens); + connectLensResilient(lens, address, connectWindowMs); + sleepInterruptibly(NOTIFY_SETTLE_MS); + drainAcks(); + + emitState("flashing", lens); + startHeartbeat(address); + try { + int beginStatus = sendCtrlAndWait(address, OP_BEGIN, EMPTY, CTRL_ACK_TIMEOUT_MS); + if (!isEndOk(beginStatus)) { + emitLog("warning: unexpected begin status " + beginStatus + "; continuing"); + } + for (int i = 0; i < segs.size(); i++) { + if (cancelled) { + throw new IllegalStateException("Cancelled."); + } + flashComponentWithRetry(lens, address, i, segs.size(), segs.get(i), img); + } + } finally { + stopHeartbeat(); + } + emitLog(lens + " lens: all components verified"); + try { + bleManager.disconnect(address); + } catch (Exception ignored) { + } + } + + private void flashComponentWithRetry(String lens, String address, int index, int count, Segment seg, byte[] img) { + for (int attempt = 0; attempt < COMPONENT_RETRIES; attempt++) { + if (attempt > 0) { + emitLog(seg.name + ": re-flash attempt " + (attempt + 1) + "/" + COMPONENT_RETRIES); + } + int endStatus; + try { + endStatus = flashComponent(lens, address, index, count, seg, img); + } catch (TimeoutException | RuntimeException e) { + emitLog(seg.name + ": block phase failed: " + e.getMessage()); + endStatus = -1; + } + if (isEndOk(endStatus)) { + emitLog(seg.name + ": END verify OK (status " + endStatus + ")"); + return; + } + if (endStatus >= 0) { + emitLog(seg.name + ": END verify FAILED (status " + endStatus + ")"); + } + drainAcks(); + sleepInterruptibly(1_500); + } + throw new IllegalStateException("component " + seg.name + " failed after " + COMPONENT_RETRIES + " attempts"); + } + + private int flashComponent(String lens, String address, int index, int count, Segment seg, byte[] img) + throws TimeoutException { + byte[] sub = Arrays.copyOfRange(img, seg.off, seg.off + 128); + int ps = seg.ps; + int payloadStart = seg.off + 128; + + int checkStatus = sendCtrlAndWait(address, OP_FILE_CHECK, sub, CTRL_ACK_TIMEOUT_MS); + if (checkStatus != 0) { + throw new IllegalStateException("FILE_CHECK rejected status=" + checkStatus); + } + + int blockCount = (ps + BLOCK_SIZE - 1) / BLOCK_SIZE; + for (int b = 0; b < blockCount; b++) { + if (cancelled) { + throw new IllegalStateException("Cancelled."); + } + int start = payloadStart + b * BLOCK_SIZE; + int end = Math.min(start + BLOCK_SIZE, payloadStart + ps); + byte[] block = Arrays.copyOfRange(img, start, end); + + boolean accepted = false; + for (int tries = 0; tries < BLOCK_NAK_RETRIES; tries++) { + int status = sendBlock(address, block); // throws TimeoutException -> component re-flash + if (status == 0) { + accepted = true; + break; + } + emitLog(seg.name + ": block " + b + "/" + blockCount + " NAK=" + status + + " resend " + (tries + 1) + "/" + BLOCK_NAK_RETRIES); + } + if (!accepted) { + throw new IllegalStateException("block " + b + " NAK'd " + BLOCK_NAK_RETRIES + " times"); + } + if (b % 20 == 0 || b == blockCount - 1) { + emitProgress(lens, index + 1, count, b + 1, blockCount); + } + } + emitLog(seg.name + ": data phase done; sending END"); + return sendCtrlAndWait(address, OP_END, EMPTY, CTRL_ACK_TIMEOUT_MS); + } + + /** Send one 4 KB block as a marker + data pair sharing one envelope seq. */ + private int sendBlock(String address, byte[] block) throws TimeoutException { + int seq = nextSeq(); + drainAcks(); + writeOta(address, BleProtocol.OTA_DATA_WRITE_UUID, SID_CTRL, new byte[] {(byte) OP_BLOCK}, seq); + writeOta(address, BleProtocol.OTA_DATA_WRITE_UUID, SID_DATA, block, seq); + return waitAck(OP_BLOCK, BLOCK_ACK_TIMEOUT_MS); + } + + private int sendCtrlAndWait(String address, int op, byte[] data, int timeoutMs) throws TimeoutException { + int seq = nextSeq(); + drainAcks(); + byte[] payload = new byte[1 + data.length]; + payload[0] = (byte) op; + System.arraycopy(data, 0, payload, 1, data.length); + writeOta(address, BleProtocol.OTA_DATA_WRITE_UUID, SID_CTRL, payload, seq); + return waitAck(op, timeoutMs); + } + + private boolean writeOta(String address, String writeChar, int sid, byte[] payload, int seq) { + List frames = BleProtocol.framePb(payload, sid, FLAG_OTA, seq); + return bleManager.writeFrames( + address, writeChar, frames, ConnectionOptions.WRITE_TYPE, ConnectionOptions.WRITE_TIMEOUT_MS); + } + + private int waitAck(int wantOp, int timeoutMs) throws TimeoutException { + long deadline = SystemClock.elapsedRealtime() + timeoutMs; + while (true) { + long remaining = deadline - SystemClock.elapsedRealtime(); + if (remaining <= 0) { + break; + } + byte[] pb; + try { + pb = dataAcks.poll(remaining, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TimeoutException("interrupted waiting for ack op=" + wantOp); + } + if (pb == null) { + break; + } + if (pb.length >= 2 && (pb[0] & 0xff) == wantOp) { + return pb[1] & 0xff; + } + // Different opcode (e.g. a late ack from a prior stage) — ignore, keep waiting. + } + throw new TimeoutException("no ack op=0x" + Integer.toHexString(wantOp) + " within " + timeoutMs + "ms"); + } + + // ---- connection ---------------------------------------------------------- + + private void connectLensResilient(String lens, String address, int windowMs) { + long deadline = SystemClock.elapsedRealtime() + windowMs; + String lastError = "unknown"; + int attempt = 0; + while (SystemClock.elapsedRealtime() < deadline && !cancelled) { + attempt++; + try { + if (bringUpLens(address)) { + emitLog("connected " + lens + " lens (attempt " + attempt + ")"); + return; + } + lastError = "connect/discover incomplete"; + } catch (Exception e) { + lastError = e.getMessage() == null ? e.toString() : e.getMessage(); + } + emitLog(lens + " connect attempt " + attempt + " failed (" + lastError + "); retrying..."); + try { + bleManager.disconnect(address); + } catch (Exception ignored) { + } + sleepInterruptibly(RETRY_DELAY_MS); + } + if (cancelled) { + throw new IllegalStateException("Cancelled."); + } + throw new IllegalStateException("could not reach " + lens + " lens: " + lastError); + } + + private boolean bringUpLens(String address) { + if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { + return false; + } + bleManager.requestConnectionPriority(address, BluetoothGatt.CONNECTION_PRIORITY_HIGH); + bleManager.requestMtu(address, ConnectionOptions.DESIRED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS); + if (!bleManager.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) { + return false; + } + if (!bleManager.enableNotifications(address, BleProtocol.OTA_DATA_NOTIFY_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) { + return false; + } + // Control-channel notify (heartbeat responses); best-effort. + bleManager.enableNotifications(address, BleProtocol.NOTIFY_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS); + return true; + } + + // ---- heartbeat ----------------------------------------------------------- + + private void startHeartbeat(String address) { + stopHeartbeat(); + heartbeatAddress = address; + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread t = new Thread(runnable, "faceclaw-flash-hb"); + t.setDaemon(true); + return t; + }); + heartbeatExecutor = executor; + executor.scheduleWithFixedDelay( + this::sendHeartbeat, HEARTBEAT_INTERVAL_MS, HEARTBEAT_INTERVAL_MS, TimeUnit.MILLISECONDS); + } + + private void sendHeartbeat() { + if (cancelled) { + return; + } + String address = heartbeatAddress; + if (address == null) { + return; + } + try { + writeOta(address, BleProtocol.WRITE_CHAR_UUID, SID_HEARTBEAT, HEARTBEAT_PAYLOAD, nextSeq()); + } catch (Exception e) { + Log.w(TAG, "heartbeat failed: " + e.getMessage()); + } + } + + private void stopHeartbeat() { + ScheduledExecutorService executor = heartbeatExecutor; + heartbeatExecutor = null; + heartbeatAddress = null; + if (executor != null) { + executor.shutdownNow(); + } + } + + // ---- firmware container parsing / validation ----------------------------- + + private static final byte[] EMPTY = new byte[0]; + + private static final class Segment { + final int off; + final int ps; + final long crc; + final String name; + + Segment(int off, int ps, long crc, String name) { + this.off = off; + this.ps = ps; + this.crc = crc; + this.name = name; + } + } + + private List parseSegments(byte[] img) { + if (img.length < 0x40) { + throw new IllegalStateException("file is too small to be a firmware image"); + } + long n = readU32(img, 8); + if (n <= 0 || n > 64) { + throw new IllegalStateException("implausible component count " + n + " (corrupt image?)"); + } + List segs = new ArrayList<>(); + for (int i = 0; i < n; i++) { + int base = 0x40 + i * 16; + long crc = readU32(img, base + 12); + int off = (int) readU32(img, base + 4); + if (off + 128 > img.length) { + throw new IllegalStateException("segment " + i + " subheader runs past end of file"); + } + int ps = (int) readU32(img, off + 8); + String name = readCString(img, off + 48, 80); + segs.add(new Segment(off, ps, crc, name)); + } + return segs; + } + + private List validate(byte[] img) { + List segs = parseSegments(img); + if (segs.size() != EXPECTED_SEGMENTS) { + throw new IllegalStateException("expected " + EXPECTED_SEGMENTS + " components, found " + segs.size()); + } + Segment main = null; + for (Segment s : segs) { + byte[] payload = Arrays.copyOfRange(img, s.off + 128, s.off + 128 + s.ps); + long calc = crc32cMsb(payload) & 0xffffffffL; + long subCrc = readU32(img, s.off + 12); + if (calc != s.crc || calc != subCrc) { + throw new IllegalStateException("component " + s.name + " CRC32C is stale (image not checksum-fixed)"); + } + if (REQUIRED_SEGMENT.equals(s.name)) { + main = s; + } + } + if (main == null) { + throw new IllegalStateException("required component " + REQUIRED_SEGMENT + " not found"); + } + checkMainAppFitsMram(img, main); + return segs; + } + + private void checkMainAppFitsMram(byte[] img, Segment main) { + if (main.ps < APP_PREAMBLE) { + throw new IllegalStateException("main-app payload is smaller than its preamble"); + } + long loadAddr = readU32(img, main.off + 128 + 0x14); + long preLen = readU32(img, main.off + 128) & 0xFFFFFFL; + if (loadAddr != APP_LOAD_ADDR) { + throw new IllegalStateException( + "main-app preamble load address is 0x" + Long.toHexString(loadAddr) + + ", expected 0x" + Long.toHexString(APP_LOAD_ADDR)); + } + if (preLen != main.ps) { + throw new IllegalStateException( + "main-app preamble length (" + preLen + ") != staged payload size (" + main.ps + ")"); + } + long progEnd = APP_LOAD_ADDR + main.ps - APP_PREAMBLE; + if (progEnd > APP_MAX_END) { + long over = progEnd - APP_MAX_END; + throw new IllegalStateException( + "main-app is too large: programmed region ends at 0x" + Long.toHexString(progEnd) + + ", " + over + " bytes past the safe MRAM ceiling — refusing to flash (brick risk)"); + } + } + + // ---- listener callbacks -------------------------------------------------- + + @Override + public void onNotification(String address, String characteristicUuid, byte[] data) { + if (!BleProtocol.OTA_DATA_NOTIFY_UUID.equalsIgnoreCase(characteristicUuid)) { + return; // acks arrive on the data-notify char; ignore heartbeat responses + } + BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data); + if (!frame.ok || frame.pb.length < 2) { + return; + } + dataAcks.add(Arrays.copyOf(frame.pb, Math.min(frame.pb.length, 2))); + } + + @Override + public void onConnectionStateChange(String address, boolean connected) { + if (!connected) { + Log.i(TAG, "disconnected: " + address); + } + } + + // ---- helpers ------------------------------------------------------------- + + private void teardown() { + stopHeartbeat(); + try { + bleManager.close(); + } catch (Exception ignored) { + } + } + + private void resetSeq() { + synchronized (lock) { + nextSeq = 0; + } + } + + private int nextSeq() { + synchronized (lock) { + nextSeq = (nextSeq + 1) & 0xff; + return nextSeq; + } + } + + private void drainAcks() { + dataAcks.clear(); + } + + private static boolean isEndOk(int status) { + for (int ok : END_OK) { + if (ok == status) { + return true; + } + } + return false; + } + + private void sleepInterruptibly(int ms) { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private static byte[] readFile(String path) { + try (FileInputStream fis = new FileInputStream(path)) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[65536]; + int read; + while ((read = fis.read(buf)) >= 0) { + out.write(buf, 0, read); + } + return out.toByteArray(); + } catch (IOException e) { + throw new IllegalStateException("could not read firmware: " + e.getMessage(), e); + } + } + + private static long readU32(byte[] buf, int offset) { + return (buf[offset] & 0xffL) + | ((buf[offset + 1] & 0xffL) << 8) + | ((buf[offset + 2] & 0xffL) << 16) + | ((buf[offset + 3] & 0xffL) << 24); + } + + private static String readCString(byte[] buf, int offset, int maxLen) { + int end = offset; + int limit = Math.min(buf.length, offset + maxLen); + while (end < limit && buf[end] != 0) { + end++; + } + return new String(buf, offset, end - offset, StandardCharsets.ISO_8859_1); + } + + private static final int[] CRC32C_TABLE = buildCrc32cTable(); + + private static int[] buildCrc32cTable() { + int[] table = new int[256]; + for (int b = 0; b < 256; b++) { + int c = b << 24; + for (int i = 0; i < 8; i++) { + c = (c & 0x80000000) != 0 ? (c << 1) ^ 0x1edc6f41 : c << 1; + } + table[b] = c; + } + return table; + } + + /** CRC-32C, MSB-first, init 0, no final xor (matches g2flash.py crc32c_msb). */ + private static int crc32cMsb(byte[] data) { + int crc = 0; + for (byte value : data) { + crc = (crc << 8) ^ CRC32C_TABLE[((crc >>> 24) ^ (value & 0xff)) & 0xff]; + } + return crc; + } + + private void emitLog(String line) { + Log.i(TAG, line); + mainHandler.post(() -> { + FaceclawFirmwareFlasherListener current = listener; + if (current != null) { + current.onLog(line); + } + }); + } + + private void emitProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount) { + mainHandler.post(() -> { + FaceclawFirmwareFlasherListener current = listener; + if (current != null) { + current.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount); + } + }); + } + + private void emitState(String state, String detail) { + final String safeDetail = detail == null ? "" : detail; + mainHandler.post(() -> { + FaceclawFirmwareFlasherListener current = listener; + if (current != null) { + current.onState(state, safeDetail); + } + }); + } + + private void emitComplete(boolean success, String detail) { + final String safeDetail = detail == null ? "" : detail; + mainHandler.post(() -> { + FaceclawFirmwareFlasherListener current = listener; + if (current != null) { + current.onComplete(success, safeDetail); + } + }); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java new file mode 100644 index 00000000..a111c174 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java @@ -0,0 +1,21 @@ +package com.faceclaw.app; + +/** Callbacks from FaceclawFirmwareFlasher to the TypeScript layer. */ +public interface FaceclawFirmwareFlasherListener { + void onLog(String line); + + /** + * Fine-grained progress for the UI bar. `lens` is "left"/"right"; + * component/block indices are 1-based against their counts. + */ + void onProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount); + + /** + * Coarse lifecycle. `state` is one of: validating, connecting, flashing, + * rebooting, done, error. `detail` carries the lens name or a message. + */ + void onState(String state, String detail); + + /** Terminal callback: success or failure, with an explanatory message. */ + void onComplete(boolean success, String detail); +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java new file mode 100644 index 00000000..31a43576 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java @@ -0,0 +1,49 @@ +package com.faceclaw.app; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * Native helpers for the on-device custom-firmware build: SHA-256 hashing and + * binary file writing. Both take a java.nio.ByteBuffer so NativeScript can + * marshal a JS ArrayBuffer straight across without a per-element copy of the + * ~4 MB firmware image (and with no overload ambiguity). + */ +public final class FaceclawFirmwareUtil { + private FaceclawFirmwareUtil() {} + + /** Lowercase hex SHA-256 of the buffer's remaining bytes. */ + public static String sha256Hex(ByteBuffer data) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(data.duplicate()); + byte[] digest = md.digest(); + StringBuilder sb = new StringBuilder(digest.length * 2); + for (byte b : digest) { + int v = b & 0xff; + sb.append(Character.forDigit(v >>> 4, 16)); + sb.append(Character.forDigit(v & 0x0f, 16)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("SHA-256 unavailable", e); + } + } + + /** Write the buffer's remaining bytes to `path`, overwriting any existing file. */ + public static void writeFile(String path, ByteBuffer data) { + try (FileOutputStream fos = new FileOutputStream(path); + FileChannel channel = fos.getChannel()) { + ByteBuffer view = data.duplicate(); + while (view.hasRemaining()) { + channel.write(view); + } + } catch (IOException e) { + throw new RuntimeException("firmware write failed: " + e.getMessage(), e); + } + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java new file mode 100644 index 00000000..16454990 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java @@ -0,0 +1,412 @@ +package com.faceclaw.app; + +import android.bluetooth.BluetoothGatt; +import android.content.Context; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * A minimal, stock-firmware-compatible BLE communicator used only to show the + * pre-flash confirmation prompt on the glasses and read back the user's Yes/No + * choice. It is deliberately separate from FaceclawBleCommunicator: the main + * app assumes the custom firmware (image containers, compositor, etc.), whereas + * this must work on unmodified glasses, so it speaks only the stock subset — + * session prelude, a text container, a list container, and heartbeats. No + * images. + * + * It reuses the low-level GATT wrapper (FaceclawBleManager) and the framing / + * protobuf helpers (BleProtocol), but owns its own GATT connection and runs its + * whole lifecycle on a single worker thread. It expects the main app to be + * disconnected while it runs (onboarding, before flashing). + */ +public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { + private static final String TAG = "FaceclawFlashPrompt"; + + private static final String TEXT_NAME = "flashwarn"; + private static final String LIST_NAME = "flashmenu"; + private static final int TEXT_CONTAINER_ID = 1; + private static final int LIST_CONTAINER_ID = 2; + // Index 0 = decline, index 1 = approve. Kept short for the ~50-col grid. + private static final String[] ITEMS = new String[] {"No, cancel", "Yes, flash"}; + + private static final int HEARTBEAT_INTERVAL_MS = 4_000; + private static final int SELECTION_TIMEOUT_MS = 120_000; + private static final int CREATE_ACK_TIMEOUT_MS = 3_000; + + private final Context context; + private final String rightAddress; + private final String leftAddress; + private final String warningText; + private final FaceclawBleManager bleManager; + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + + private final Object lock = new Object(); + private final ConcurrentHashMap pendingAcks = new ConcurrentHashMap<>(); + private final CountDownLatch selectionLatch = new CountDownLatch(1); + + private volatile FaceclawFlashPromptListener listener; + private volatile Thread worker; + private volatile boolean cancelled = false; + private volatile boolean finished = false; + private volatile boolean rightConnected = false; + private volatile boolean leftConnected = false; + private volatile boolean rightLost = false; + private volatile Boolean approved = null; + private volatile ScheduledExecutorService heartbeatExecutor; + + private int nextMagic = 100; + private int nextSeq = 0x40; + + public FaceclawFlashPromptCommunicator(Context context, String rightAddress, String leftAddress, String warningText) { + this.context = context.getApplicationContext(); + this.rightAddress = rightAddress == null ? "" : rightAddress; + this.leftAddress = leftAddress == null ? "" : leftAddress; + this.warningText = warningText == null ? "" : warningText; + this.bleManager = new FaceclawBleManager(this.context); + this.bleManager.setListener(this); + } + + public void setListener(FaceclawFlashPromptListener listener) { + this.listener = listener; + } + + public void start() { + synchronized (lock) { + if (worker != null) { + return; + } + worker = new Thread(this::run, "faceclaw-flash-prompt"); + worker.start(); + } + } + + /** Abort the prompt (e.g. the user backed out on the phone). */ + public void cancel() { + cancelled = true; + selectionLatch.countDown(); + Thread w = worker; + if (w != null) { + w.interrupt(); + } + } + + public void close() { + cancel(); + stopHeartbeat(); + try { + bleManager.close(); + } catch (Exception ignored) { + } + } + + private void run() { + try { + if (rightAddress.trim().isEmpty()) { + emitState("error", "No right-arm address configured."); + return; + } + + emitState("connecting", ""); + connectArm(rightAddress, "right"); + rightConnected = true; + + boolean haveLeft = !leftAddress.trim().isEmpty() && !leftAddress.equalsIgnoreCase(rightAddress); + if (haveLeft) { + try { + connectArm(leftAddress, "left"); + leftConnected = true; + } catch (Exception e) { + emitLog("left arm connect failed (continuing on right only): " + e.getMessage()); + } + } + if (cancelled) { + teardown(); + return; + } + + emitState("connected", ""); + bringUpArm(rightAddress); + if (leftConnected) { + try { + bringUpArm(leftAddress); + } catch (Exception e) { + emitLog("left arm prompt failed (continuing on right only): " + e.getMessage()); + leftConnected = false; + } + } + + startHeartbeat(); + emitState("prompting", ""); + + boolean signalled = selectionLatch.await(SELECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); + stopHeartbeat(); + + if (cancelled) { + emitState("cancelled", ""); + teardown(); + return; + } + if (approved != null) { + boolean result = Boolean.TRUE.equals(approved); + try { + sendShutdownBoth(); + } catch (Exception ignored) { + } + emitResult(result); + emitState("result", result ? "approved" : "declined"); + teardown(); + return; + } + if (rightLost) { + emitState("disconnected", "Lost connection to the glasses."); + } else { + emitState("timeout", "No response from the glasses."); + } + teardown(); + } catch (Exception e) { + stopHeartbeat(); + if (!cancelled) { + String message = e.getMessage() == null ? e.toString() : e.getMessage(); + emitState("error", message); + } + teardown(); + } + } + + private void connectArm(String address, String labelForLog) { + if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { + throw new IllegalStateException("connect failed: " + address); + } + bleManager.requestConnectionPriority(address, BluetoothGatt.CONNECTION_PRIORITY_HIGH); + bleManager.requestMtu(address, ConnectionOptions.DESIRED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS); + if (!bleManager.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) { + throw new IllegalStateException("discoverServices failed: " + address); + } + if (!bleManager.enableNotifications(address, BleProtocol.NOTIFY_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) { + throw new IllegalStateException("enableNotifications failed: " + address); + } + emitLog("connected " + labelForLog + " arm"); + } + + private void bringUpArm(String address) throws InterruptedException { + // 1. Mandatory session prelude on sid=0x01 (app-launch). + if (!writeAndAwaitAck( + address, + BleProtocol.PRELUDE_ACK_SID, + BleProtocol.FLAG_REQUEST, + BleProtocol.PRELUDE_ACK_MAGIC, + BleProtocol.PRELUDE_F5872_PAYLOAD, + ConnectionOptions.PRELUDE_TIMEOUT_MS)) { + throw new IllegalStateException("session prelude not acked: " + address); + } + // 2. Create the prompt page (warning text + No/Yes list) on sid=0xe0 Cmd=0. + int magic = allocMagic(); + byte[] page = BleProtocol.buildCreatePromptPage( + magic, TEXT_NAME, TEXT_CONTAINER_ID, warningText, LIST_NAME, LIST_CONTAINER_ID, ITEMS); + if (!writeAndAwaitAck(address, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, magic, page, CREATE_ACK_TIMEOUT_MS)) { + throw new IllegalStateException("prompt page not acked: " + address); + } + emitLog("prompt page shown on " + address); + } + + private boolean writeAndAwaitAck(String address, int sid, int flag, int magic, byte[] payload, int timeoutMs) + throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + String key = ackKey(sid, magic); + pendingAcks.put(key, latch); + try { + if (!writeFrame(address, sid, flag, payload)) { + return false; + } + return latch.await(timeoutMs, TimeUnit.MILLISECONDS); + } finally { + pendingAcks.remove(key, latch); + } + } + + private boolean writeFrame(String address, int sid, int flag, byte[] payload) { + int seq; + synchronized (lock) { + seq = nextSeq++ & 0xff; + } + List frames = BleProtocol.framePb(payload, sid, flag, seq); + return bleManager.writeFrames( + address, + BleProtocol.WRITE_CHAR_UUID, + frames, + ConnectionOptions.WRITE_TYPE, + ConnectionOptions.WRITE_TIMEOUT_MS); + } + + private void startHeartbeat() { + stopHeartbeat(); + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread t = new Thread(runnable, "faceclaw-flash-hb"); + t.setDaemon(true); + return t; + }); + heartbeatExecutor = executor; + executor.scheduleWithFixedDelay( + this::sendHeartbeat, HEARTBEAT_INTERVAL_MS, HEARTBEAT_INTERVAL_MS, TimeUnit.MILLISECONDS); + } + + private void sendHeartbeat() { + if (finished || cancelled) { + return; + } + try { + byte[] heartbeat = BleProtocol.buildHeartbeat(allocMagic()); + if (rightConnected) { + writeFrame(rightAddress, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, heartbeat); + } + if (leftConnected) { + writeFrame(leftAddress, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, heartbeat); + } + } catch (Exception e) { + Log.w(TAG, "heartbeat failed: " + e.getMessage()); + } + } + + private void stopHeartbeat() { + ScheduledExecutorService executor = heartbeatExecutor; + heartbeatExecutor = null; + if (executor != null) { + executor.shutdownNow(); + } + } + + private void sendShutdownBoth() { + byte[] shutdown = BleProtocol.buildShutdown(allocMagic(), 0); + if (rightConnected) { + writeFrame(rightAddress, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, shutdown); + } + if (leftConnected) { + writeFrame(leftAddress, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, shutdown); + } + } + + private void teardown() { + finished = true; + stopHeartbeat(); + try { + bleManager.close(); + } catch (Exception ignored) { + } + rightConnected = false; + leftConnected = false; + } + + @Override + public void onNotification(String address, String characteristicUuid, byte[] data) { + if (!BleProtocol.NOTIFY_CHAR_UUID.equalsIgnoreCase(characteristicUuid)) { + return; + } + BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data); + if (!frame.ok) { + return; + } + if (frame.flag == BleProtocol.FLAG_NOTIFY || frame.flag == BleProtocol.FLAG_NOTIFY_ALT) { + // Async events (taps/selections) only ever come from the right arm. + if (address.equalsIgnoreCase(rightAddress)) { + handleEvent(frame); + } + return; + } + if (frame.msgSeq >= 0) { + CountDownLatch latch = pendingAcks.get(ackKey(frame.sid, frame.msgSeq)); + if (latch != null) { + latch.countDown(); + } + } + } + + private void handleEvent(BleProtocol.ParsedFrame frame) { + BleProtocol.ListSelection selection = BleProtocol.parseListSelection(frame); + if (selection == null || !LIST_NAME.equals(selection.containerName)) { + return; + } + // Only a confirmed click is a decision; scroll/highlight changes are ignored. + if (selection.eventType != BleProtocol.EVENT_CLICK) { + return; + } + boolean yes = selection.itemIndex == 1 + || (selection.itemName != null && selection.itemName.toLowerCase().startsWith("yes")); + synchronized (lock) { + if (finished) { + return; + } + finished = true; + approved = yes; + } + emitLog("selection: " + (yes ? "flash" : "cancel") + " (index " + selection.itemIndex + ")"); + selectionLatch.countDown(); + } + + @Override + public void onConnectionStateChange(String address, boolean connected) { + if (connected) { + return; + } + if (address.equalsIgnoreCase(rightAddress)) { + rightConnected = false; + synchronized (lock) { + if (!finished && !cancelled) { + rightLost = true; + finished = true; + selectionLatch.countDown(); + } + } + } else if (address.equalsIgnoreCase(leftAddress)) { + leftConnected = false; + } + } + + private int allocMagic() { + synchronized (lock) { + int magic = nextMagic; + nextMagic = nextMagic >= 255 ? 100 : nextMagic + 1; + return magic; + } + } + + private static String ackKey(int sid, int magic) { + return sid + ":" + magic; + } + + private void emitLog(String line) { + Log.i(TAG, line); + mainHandler.post(() -> { + FaceclawFlashPromptListener current = listener; + if (current != null) { + current.onLog(line); + } + }); + } + + private void emitState(String state, String detail) { + final String safeDetail = detail == null ? "" : detail; + mainHandler.post(() -> { + FaceclawFlashPromptListener current = listener; + if (current != null) { + current.onState(state, safeDetail); + } + }); + } + + private void emitResult(boolean approvedResult) { + mainHandler.post(() -> { + FaceclawFlashPromptListener current = listener; + if (current != null) { + current.onResult(approvedResult); + } + }); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java new file mode 100644 index 00000000..39a8e322 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptListener.java @@ -0,0 +1,16 @@ +package com.faceclaw.app; + +/** Callbacks from FaceclawFlashPromptCommunicator to the TypeScript layer. */ +public interface FaceclawFlashPromptListener { + void onLog(String line); + + /** + * Lifecycle updates. `state` is one of: connecting, connected, prompting, + * result, cancelled, timeout, disconnected, error. `detail` carries the + * "approved"/"declined" text for result, or an error/explanation message. + */ + void onState(String state, String detail); + + /** Fires once the user picks a menu row: true = flash, false = cancel. */ + void onResult(boolean approved); +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java index 42680670..2cfe7805 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java @@ -17,6 +17,11 @@ import java.util.UUID; public class BleProtocol { public static final String WRITE_CHAR_UUID = "00002760-08c2-11e1-9073-0e8ac72e5401"; public static final String NOTIFY_CHAR_UUID = "00002760-08c2-11e1-9073-0e8ac72e5402"; + // Firmware-data service (svc ...e1001): the OTA transfer channel, distinct + // from the EvenHub write/notify chars above (which the flasher reuses only + // for the keepalive heartbeat). + public static final String OTA_DATA_WRITE_UUID = "00002760-08c2-11e1-9073-0e8ac72e0001"; + public static final String OTA_DATA_NOTIFY_UUID = "00002760-08c2-11e1-9073-0e8ac72e0002"; public static final String RENDER_NOTIFY_UUID = "00002760-08c2-11e1-9073-0e8ac72e6402"; public static final String R1_PHONE_NOTIFY_CHAR_UUID = "bae80011-4f05-4503-8e65-3af1f7329d1f"; public static final String R1_NOTIFY_CHAR_UUID = "bae80013-4f05-4503-8e65-3af1f7329d1f"; @@ -142,6 +147,88 @@ public class BleProtocol { return wrapEvenHub(12, magic, 14, encodeVarintField(1, 0)); } + /** + * Cmd=0 CreateStartUpPage carrying a text container (the message) plus a + * list container (the selectable rows) in one page. Uses stock-firmware-safe + * geometry (each container within the stock ~280x130 container-size cap; the + * CFW is what lifts that to 576x288), so this works before flashing. The + * selected row comes back as an async list event — see parseListSelection. + */ + public static byte[] buildCreatePromptPage( + int magic, + String textName, + int textContainerId, + String warningText, + String listName, + int listContainerId, + String[] items + ) { + List inner = new ArrayList<>(); + inner.add(encodeVarintField(1, 2)); // ContainerTotalNum: 1 text + 1 list + inner.add(encodeMessageField(2, encodeListObject(listName, listContainerId, 0, 150, 280, 120, items, true))); + inner.add(encodeMessageField(3, encodeTextObject(textName, textContainerId, 0, 0, 280, 130, warningText, false))); + inner.add(encodeVarintField(5, 10000)); // widgetId + return wrapEvenHub(0, magic, 3, concat(inner)); + } + + public static byte[] encodeListObject( + String name, + int containerId, + int x, + int y, + int width, + int height, + String[] items, + boolean captureEvents + ) { + List parts = new ArrayList<>(); + parts.add(encodeVarintField(1, x)); + parts.add(encodeVarintField(2, y)); + parts.add(encodeVarintField(3, width)); + parts.add(encodeVarintField(4, height)); + parts.add(encodeVarintField(9, containerId)); + parts.add(encodeStringField(10, name)); + parts.add(encodeMessageField(11, encodeListItemContainer(items))); + if (captureEvents) { + parts.add(encodeVarintField(12, 1)); + } + return concat(parts); + } + + private static byte[] encodeListItemContainer(String[] items) { + List parts = new ArrayList<>(); + parts.add(encodeVarintField(1, items.length)); // ItemCount + parts.add(encodeVarintField(3, 1)); // IsItemSelectBorderEn + for (String item : items) { + parts.add(encodeStringField(4, item)); // repeated ItemName + } + return concat(parts); + } + + /** + * Decode a list-selection async event (sid=0xe0, flag=0x01/0x06). Returns + * null if the frame is not a list event. `itemIndex` is 0-based into the + * ItemName array the list was built with; `eventType` is EVENT_CLICK for a + * confirmed selection (scroll/highlight changes arrive with other types). + */ + public static ListSelection parseListSelection(ParsedFrame frame) { + byte[] pb = stripTrailingCrc(frame.pb); + byte[] deviceEvent = readFieldBytes(pb, 13); + if (deviceEvent == null) { + return null; + } + byte[] listEvent = readFieldBytes(deviceEvent, 1); + if (listEvent == null) { + return null; + } + return new ListSelection( + readStringFieldValue(listEvent, 2), + readStringFieldValue(listEvent, 3), + readVarintFieldValue(listEvent, 4, -1), + readVarintFieldValue(listEvent, 5, EVENT_CLICK) + ); + } + public static byte[] buildAudioControl(int magic, boolean enable) { return wrapEvenHub(CMD_AUDIO_CONTROL, magic, 18, encodeVarintField(1, enable ? 1 : 0)); } @@ -484,6 +571,20 @@ public class BleProtocol { } } + public static final class ListSelection { + public final String containerName; + public final String itemName; + public final int itemIndex; + public final int eventType; + + ListSelection(String containerName, String itemName, int itemIndex, int eventType) { + this.containerName = containerName == null ? "" : containerName; + this.itemName = itemName == null ? "" : itemName; + this.itemIndex = itemIndex; + this.eventType = eventType; + } + } + public static final class ImageTileOptions { final String name; final int containerId; diff --git a/app/g2/firmware-builder.ts b/app/g2/firmware-builder.ts new file mode 100644 index 00000000..adc1d501 --- /dev/null +++ b/app/g2/firmware-builder.ts @@ -0,0 +1,199 @@ +/** + * Builds the Faceclaw custom firmware on-device: downloads the stock Even + * Realities G2 2.2.4.34 image from Even's CDN, verifies its SHA-256, applies + * the committed byte-patch set (cfw-patches.ts), verifies the patched SHA-256, + * and writes the result to app storage. + * + * This mirrors g2flash/build_cfw.sh + patches/apply_patches.py exactly (same + * URL, same pinned hashes, same offset/old/new patch semantics), so a + * successful run reproduces the reviewed image byte-for-byte. It does NOT flash + * anything — producing and verifying the image is the whole job here. + */ +import { knownFolders } from "@nativescript/core"; + +import { CFW_PATCH_SET, FirmwarePatchOp } from "./firmware/cfw-patches"; + +declare const com: any; + +const FIRMWARE_URL = "https://cdn.evenreal.co/firmware/a6966d807634cc97aec641a0dcca358b.bin"; +const OUTPUT_FILENAME = "g2_2.2.4.34_cfw.bin"; + +export type FirmwareProgress = + | { phase: "downloading" } + | { phase: "verifying-base" } + | { phase: "patching"; applied: number; total: number } + | { phase: "verifying-output" } + | { phase: "writing" } + | { phase: "done"; path: string; bytes: number }; + +export type BuiltFirmware = { + path: string; + bytes: number; + sha256: string; +}; + +export class FirmwareBuildError extends Error {} + +/** + * Download → verify → patch → verify → persist. Rejects with a + * FirmwareBuildError carrying a human-readable message if any hash check or the + * download fails. `onProgress` is optional and purely for UI. + */ +export async function buildCustomFirmware( + onProgress?: (progress: FirmwareProgress) => void, +): Promise { + const report = (progress: FirmwareProgress) => { + try { + onProgress?.(progress); + } catch { + // progress reporting must never break the build + } + }; + + report({ phase: "downloading" }); + const base = await downloadFirmware(); + + report({ phase: "verifying-base" }); + const baseSha = sha256Hex(base); + if (baseSha !== CFW_PATCH_SET.baseSha256) { + throw new FirmwareBuildError( + `Downloaded stock firmware failed verification.\nexpected ${CFW_PATCH_SET.baseSha256}\ngot ${baseSha}`, + ); + } + + const patched = applyPatches(new Uint8Array(base), CFW_PATCH_SET.patches, (applied, total) => + report({ phase: "patching", applied, total }), + ); + + report({ phase: "verifying-output" }); + const outBuffer = tightBuffer(patched); + const outSha = sha256Hex(outBuffer); + if (outSha !== CFW_PATCH_SET.outputSha256) { + throw new FirmwareBuildError( + `Patched firmware failed verification.\nexpected ${CFW_PATCH_SET.outputSha256}\ngot ${outSha}`, + ); + } + + report({ phase: "writing" }); + const path = `${knownFolders.documents().path}/${OUTPUT_FILENAME}`; + writeFile(path, outBuffer); + + report({ phase: "done", path, bytes: patched.length }); + return { path, bytes: patched.length, sha256: outSha }; +} + +async function downloadFirmware(): Promise { + let response: Response; + try { + response = await fetch(FIRMWARE_URL); + } catch (error) { + throw new FirmwareBuildError(`Could not reach Even's firmware CDN: ${(error as Error)?.message ?? error}`); + } + if (!response.ok) { + throw new FirmwareBuildError(`Firmware download failed (HTTP ${response.status}).`); + } + return response.arrayBuffer(); +} + +/** + * Replay the committed patch set onto `base`, returning the patched bytes. Each + * op writes `new` at `offset` after checking the bytes there equal `old`; an op + * with empty `old` appends at end-of-file (offset must equal current length). + * Idempotent: an op whose target already equals `new` is skipped. Mirrors + * apply_patches.py:apply_ops. + */ +function applyPatches( + base: Uint8Array, + ops: FirmwarePatchOp[], + onStep?: (applied: number, total: number) => void, +): Uint8Array { + let buf = base; + for (let i = 0; i < ops.length; i++) { + const op = ops[i]; + const oldBytes = hexToBytes(op.old ?? ""); + const newBytes = hexToBytes(op.new); + const off = op.offset; + const tag = `patch #${i} @ 0x${off.toString(16)}${op.desc ? ` (${op.desc})` : ""}`; + + if (oldBytes.length > 0) { + const cur = buf.subarray(off, off + oldBytes.length); + if (bytesEqual(cur, newBytes) && !bytesEqual(cur, oldBytes)) { + onStep?.(i + 1, ops.length); + continue; // already applied + } + if (!bytesEqual(cur, oldBytes)) { + throw new FirmwareBuildError( + `${tag}: unexpected bytes in stock image (found ${bytesToHex(cur)}, expected ${op.old}). ` + + `The downloaded image is not the stock base this patch set targets.`, + ); + } + buf.set(newBytes, off); + } else { + const end = off + newBytes.length; + if (off <= buf.length && end <= buf.length && bytesEqual(buf.subarray(off, end), newBytes)) { + onStep?.(i + 1, ops.length); + continue; // already applied + } + if (off !== buf.length) { + throw new FirmwareBuildError( + `${tag}: append expects offset 0x${off.toString(16)} to equal current length 0x${buf.length.toString(16)}.`, + ); + } + buf = concatBytes(buf, newBytes); + } + onStep?.(i + 1, ops.length); + } + return buf; +} + +function hexToBytes(hex: string): Uint8Array { + if (hex.length % 2 !== 0) { + throw new FirmwareBuildError(`odd-length hex string: ${hex}`); + } + const out = new Uint8Array(hex.length / 2); + for (let i = 0; i < out.length; i++) { + out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); + } + return out; +} + +function bytesToHex(bytes: Uint8Array): string { + let hex = ""; + for (let i = 0; i < bytes.length; i++) { + hex += bytes[i].toString(16).padStart(2, "0"); + } + return hex; +} + +function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +} + +function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array { + const out = new Uint8Array(a.length + b.length); + out.set(a, 0); + out.set(b, a.length); + return out; +} + +/** Return an ArrayBuffer holding exactly `bytes`' contents (no shared slack). */ +function tightBuffer(bytes: Uint8Array): ArrayBuffer { + if (bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength) { + return bytes.buffer; + } + return bytes.slice().buffer; +} + +/** SHA-256 hex digest of an ArrayBuffer, via Android's MessageDigest. */ +function sha256Hex(buffer: ArrayBuffer): string { + return String(com.faceclaw.app.FaceclawFirmwareUtil.sha256Hex(buffer)); +} + +/** Write an ArrayBuffer's bytes to `path`, via a native FileChannel write. */ +function writeFile(path: string, buffer: ArrayBuffer): void { + com.faceclaw.app.FaceclawFirmwareUtil.writeFile(path, buffer); +} diff --git a/app/g2/firmware/cfw-patches.ts b/app/g2/firmware/cfw-patches.ts new file mode 100644 index 00000000..e71693c3 --- /dev/null +++ b/app/g2/firmware/cfw-patches.ts @@ -0,0 +1,145 @@ +// AUTO-GENERATED from g2flash/patches/cfw_patches.json — do not edit by hand. +// Regenerate by re-running the generator in the firmware onboarding change. +// Turns the stock G2 2.2.4.34 image into the Faceclaw custom firmware. + +export type FirmwarePatchOp = { + offset: number; + old: string; + new: string; + desc?: string; +}; + +export type FirmwarePatchSet = { + base: string; + baseSha256: string; + outputSha256: string; + patches: FirmwarePatchOp[]; +}; + +export const CFW_PATCH_SET: FirmwarePatchSet = { + "base": "g2_2.2.4.34.bin", + "baseSha256": "f9a93621a7141e0ae54ca6371cd2f1b4afbffa61f302ace096e0656ba25b1754", + "outputSha256": "3b92551cffe297a75e486e036bc0ecc3723fac377ec16fc1f2c1fa81ff4aae22", + "patches": [ + { + "offset": 1452514, + "old": "bdf82c10", + "new": "40f24120", + "desc": "container width <= 576" + }, + { + "offset": 1452714, + "old": "bdf82e00", + "new": "40f22111", + "desc": "container height movw #0x121" + }, + { + "offset": 1452718, + "old": "9128", + "new": "8842", + "desc": "container height cmp r0,r1" + }, + { + "offset": 1450756, + "old": "39f72ef9", + "new": "8ef200fc", + "desc": "bl frag_write @ 0x500984" + }, + { + "offset": 1451232, + "old": "39f740f8", + "new": "8ef212fb", + "desc": "bl frag_write @ 0x500b60" + }, + { + "offset": 1451772, + "old": "38f732ff", + "new": "8ef204fa", + "desc": "bl frag_write @ 0x500d7c" + }, + { + "offset": 1451408, + "old": "3bd0", + "new": "3be0", + "desc": "drop per-session CompressMode-consistency guard" + }, + { + "offset": 1450884, + "old": "59f772ff", + "new": "8ef2b6fe", + "desc": "bl snapshot_side @ 0x500a04" + }, + { + "offset": 1451896, + "old": "59f778fd", + "new": "8ef2bcfc", + "desc": "bl snapshot_side @ 0x500df8" + }, + { + "offset": 1114956, + "old": "52f03dfe", + "new": "e0f2d6fe", + "desc": "bl image_deferred (deferred consumer -> FIFO restore + worker, both lenses)" + }, + { + "offset": 1137988, + "old": "bff7e2fa", + "new": "ddf27af9", + "desc": "bl settings_send_wrapper (append caps field 100)" + }, + { + "offset": 671534, + "old": "28f049f8", + "new": "4ff305f9", + "desc": "bl evenhub_longpress (replaces force-quit dialog)" + }, + { + "offset": 672350, + "old": "1df0cff9", + "new": "4ef389ff", + "desc": "bl ring_release (forward ring release-long-press)" + }, + { + "offset": 4131592, + "old": "", + "new": "2de9f04f40f26c63c0f250031b681b6a3bb1930800f0bb80012b37d1002300278be0002a00f0b38002f0030c97084ff0000215d0a2eb870e471c4d1c6ff00306ac19e378ba19d37023790436137163795371a3790eeb060404349371f0d1321dbcf1000f00f093808b5cbcf1010f835400f08d80531ccf5cbcf1020fc75400f086800232895c8154bde8f08f23f0010c01f1010e00236ff0070b4ff0f0086ff00f0900bf0eeb030515f9016c00eb0b0a08ead615770648bf0f358af80850b50609eae577f50648bf0f3700eb830574076f704fea06774fea867409eae77709eae47448bf0f37af70f60718bf0f34ec701ef90340023308ead416670648bf0f362e71a60609eae676e70648bf0f366e71260709eae676670748bf0f36ae71a50709eae575e40718bf0f359c450bf1080b8af80f50b6d10bf10807520758bfbde8f08fc956f02303ead1134c0648bf0f33c3558b066ff00f04ca0604eae3734fea017200f1010648bf0f3304eae272851cf3554b0748bf0f32ea558a0700f1030c04eae272c90718bf0f320cf80720bde8f08f000002fb01f042f66f31c0f24701084700bf084642f6b331c0f24701084770b500284ed001684ef65a62ccf2ff02914218bf70bd90f8fc1090f8fd5049f2597c8d42c0f24e0c2ad205eb8501014491f8012191f8024191f8fee091f8ff3091f8001142ea0424012c4ff0010298bf14466e1c054680f8fd60b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f8fc10bde870406047e047d5f8f80038b148f2eb42c0f244022146bde87040104770bd00bf2de9f04f85b043f6dc76c2f200063568804628466ff3960042f66f34b0f1005fc0f2470407d128684ef65a61ccf2ff01884200f0b8804ff4f870a0470546002800f0b0804ff61060cff6ff70002100bf2a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa1182f8fb1182f8fc1182f8fd1182f8fe1182f8ff1182f8001282f8011282f8021282f8031282f8041282f8051282f8061282f8071282f8081282f8091282f80a1282f80b1282f80c1282f80d1282f80e1282f80f1282f8101282f8111282f8121282f8131282f8141282f8151282f8161282f8171282f8181282f8191282f81a1282f81b1282f81c1282f81d1282f81e1282f81f1282f8201282f8211282f8221282f8231282f8241282f8251282f8261282f8271282f8281282f8291282f82a1282f82b1282f82c1282f82d127ff480af4ef65a60ccf2ff002860012085f8ce004ff0ff30a5f8d400a5f8d600a5f8d800a5f8da00a5f8dc00a5f8de00a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f2003560b8f1000f18bf002d07d14af6ed00c0f2450005b0bde8f04f0047d8f80cb0bbf1000ff2d0d8f820a0baf1000fedd0a94659f8040f00287bd0686900287ad0686a002879d0686b002878d0686c002877d0686d002876d0686e002875d0686f002874d0d5f88400002872d0d5f89400002870d0d5f8a40000286ed0d5f8b40000286cd0d5f8b00029690490d5f8a0002a6b0390d5f8900000260290d5f880002f6f0190286ad5f860e0d5f850c02b6c884238bf014638bf01268a423cbf114602268b423cbf194603268c453cbf614604268e453cbf714605268f423cbf39460626019888423cbf01460726029888423cbf01460826039888423cbf014609260498884238bf0146d5f8c00038bf0a26884238bf0b2609eb0610406804f1440137018847002049f80700012085f8d20016e0002614e0012612e0022610e003260ee004260ce005260ae0062608e0072606e0082604e0092602e00a2600e00b265046a04700283ff451af0af0030c5fea9a034ff0000218d00496a2eb830e431c0bf101066ff00307f119cc78da19d4700c79043714714c79547189790eeb070404349171f0d1049e3a1dbcf1000f10d01bf80230bcf1010f83540ad0531c1bf80370bcf1020fc75403d0911c1bf80120425409eb06114860d5f8c400320149f80280421cc1f808a0c5f8c420c8600de738464146fff732be2de9f04f81b043f6dc7ac2f2000adaf80050044628466ff3960042f66f3916460f46b0f1005fc0f2470907d128684ef65a61ccf2ff01884200f0b8804ff4f870c8470546002800f015814ff61060cff6ff7000212a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa1182f8fb1182f8fc1182f8fd1182f8fe1182f8ff1182f8001282f8011282f8021282f8031282f8041282f8051282f8061282f8071282f8081282f8091282f80a1282f80b1282f80c1282f80d1282f80e1282f80f1282f8101282f8111282f8121282f8131282f8141282f8151282f8161282f8171282f8181282f8191282f81a1282f81b1282f81c1282f81d1282f81e1282f81f1282f8201282f8211282f8221282f8231282f8241282f8251282f8261282f8271282f8281282f8291282f82a1282f82b1282f82c1282f82d127ff480af4ef65a60ccf2ff002860012085f8ce004ff0ff30a5f8d400a5f8d600a5f8d800a5f8da00a5f8dc00a5f8de00a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f200caf8005005f1040a4ff0000b4ff000084ff0ff30002200234ff0ff3105e000bf6032c02a03f1060332d0af187e68a64204d13e6986423cbf194630467e69a64204d13e6a86423cbf591c30467e6aa64204d13e6b86423cbf991c30467e6ba64204d13e6c86423cbfd91c30467e6ca64204d13e6d86423cbf191d30467e6da642ced13f6e87423cbf591d3846c8e700bf002917d40aeb01104768866845f6c3400901c0f250004af801b08047204639463246012300f01af8804609f1440138468847a5e7404601b0bde8f08f45f6c340c0f25000caf800508047204639463246012301b0bde8f04f00e000bf2de9f04fdbb0002918bf002a04d15bb0bde8f04f00f050be0f7807f07f06052e00f06081072e47d0422ef0d0b0f840b0b0f842a0092e00f04682082e40f050820646022a4ff0ff30c0f03983002b00f036830bf10100032303eb500020f0030000fb0af07630824200f235824d78edb188460227b81c904200f22d8208eb070318f807705b7857ea032300f024821f18974200f2208208eb0001304614461a460023fff7adff2246013de3d130465946524600f067fe08e343f6dc74c2f20004236818466ff39600b0f1005f07d118684ef65a67ccf2ff07b84200f0c0800e4642f66f31c0f247014ff4f870154688470346002800f0b0804ff61060cff6ff70002100bf1a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa1182f8fb1182f8fc1182f8fd1182f8fe1182f8ff1182f8001282f8011282f8021282f8031282f8041282f8051282f8061282f8071282f8081282f8091282f80a1282f80b1282f80c1282f80d1282f80e1282f80f1282f8101282f8111282f8121282f8131282f8141282f8151282f8161282f8171282f8181282f8191282f81a1282f81b1282f81c1282f81d1282f81e1282f81f1282f8201282f8211282f8221282f8231282f8241282f8251282f8261282f8271282f8281282f8291282f82a1282f82b1282f82c1282f82d127ff480af4ef65a60ccf2ff001860012083f8ce004ff0ff30a3f8d400a3f8d600a3f8d800a3f8da00a3f8dc00a3f8de00a3f8e000a3f8e200a3f8e400a3f8e600a3f8e800a3f8ea00a3f8ec00a3f8ee00a3f8f000a3f8f20031462a462360022a2cbf4978ff21002b00f02f8202294ff0000000f02e82012900f02482002940f01e824ff0ff3183f8d200a3f8d00083f8cf00a3f8cc00c3f8c800a3f8d410a3f8d610a3f8d810a3f8da10a3f8dc10a3f8de10a3f8e010a3f8e210a3f8e410a3f8e610a3f8e810a3f8ea10a3f8ec10a3f8ee10a3f8f010a3f8f21083f8f4005bb0bde8f08f43f6dc78c2f20008022a2cbf4d78ff25d8f8004020466ff39600b0f1005f07d120684ef65a63ccf2ff03984200f0c1800f4642f66f31c0f247014ff4f87016468847002800f0758104464ff61060cff6ff700021324600bf23183e3083f8f01183f8f11183f8f21183f8f31183f8f41183f8f51183f8f61183f8f71183f8f81183f8f91183f8fa1183f8fb1183f8fc1183f8fd1183f8fe1183f8ff1183f8001283f8011283f8021283f8031283f8041283f8051283f8061283f8071283f8081283f8091283f80a1283f80b1283f80c1283f80d1283f80e1283f80f1283f8101283f8111283f8121283f8131283f8141283f8151283f8161283f8171283f8181283f8191283f81a1283f81b1283f81c1283f81d1283f81e1283f81f1283f8201283f8211283f8221283f8231283f8241283f8251283f8261283f8271283f8281283f8291283f82a1283f82b1283f82c1283f82d127ff480af4ef65a60ccf2ff002060012084f8ce004ff0ff303946a4f8d400a4f8d600a4f8d800a4f8da00a4f8dc00a4f8de00a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200c8f8004094f8fc0078b1d4f8f80048b148f2eb43c0f2440340330e46174698473a463146002084f8fc000123032a80f0b180bae03f064ff0210658bf1126b24280f0d4804ff0ff305bb0bde8f08f032afff494adf51f15f1070f7ff68fad00254c1ca2f1010c8df834518df835518df83851cde94d4c4ff21d34c0f2780455941034062e8df83c518df83d518df83e518df83f518df840518df841518df842518df843518df844518df845518df846518df847518df848518df849518df84a518df84b518df84c518df84d518df84e518df84f518df850518df851518df852518df853518df860518df861518df862518df863518df864518df865518df866518df867518df868518df869518df86a518df86b515694579500f0d781032e00f07781012ecdf828a040f0058206460bf10100032101eb50000a9920f00300484342f66f3a00f1b605c0f2470a2846d04700283ff477af4ef20767c0f25b0748f2e4520446cde9500507f13c054da8c0f278020f213823a847002800f035824da8b84746e20023c8f80030002439463246032a0ad34db9887808284dd849f25971c0f24e019631884746e0052a16d3012d14d18f78781e06284ff0000036d8cb78032b33d80a798ab349f25970c0f24e0000f59a7638461946b0472de0022d34d149f25970c0f24e00804725e0002f01f101040ed54af6ed02c0f2450205461e460f469047334601462846022918bf07f1110486462079627950ea02264ff0ff301ebfa279e77952ea072541d15bb0bde8f08f012083f8ce0000205bb0bde8f08f83f8ce005bb0bde8f08f072a77d3032d75d18878cb780a7940ea03204d798e7901284ff0010498bf204644f62061884228bf084649f25971c0f24e01642a28bf642201f5e2731146984744f24040c2f2070000680028cfd045ea062148f2eb42012988bf0c46c0f2440221469047c3e7227b677b42ea07229642b7d1a27be77b42ea07229542b1d12078627840ea0222b01858454ff0ff30a8d8a778e17847ea012c05eb0c015145a0d8217a677a41ea072906eb0901594598d8a17ae47a41ea04242919514591d8def80c0000283ff499ae0bf10101abeb510707fb0a004908cde901461c466346f0460395cdf8009000f04dfe002c3ff47faf40466ee4032a4ff00000fff472af2f1fb7fa87f77f093b403ff46bafd01e4cf6cd42ccf6cc428b78a0fb0202b3eb920f88bf9308302b184628bf3020002b00f0308100eb800303f0030c03f4fe770023ce18f578e21882f8fe503579043382f8ff5075799f4282f80051b67982f80161eed1bcf1000f10d01944ca782344bcf1010f83f8fe2008d00a79bcf1020f83f8ff201cbf497983f8001184f8fc00d4f8f80048f2eb45c0f24405002184f8fd1070b94ff21d30c0f27800a5f1e8071c3022460023b8470028c4f8f80000f0c1810121a84713e73f0600f1a880082afff414aecdf828a0824601274ff0050c4ff0070ecd19ae784ff0ff30002e3ff4f9aeec78002c3ff4f5ae11f8078006eb0807bf005f453ff6edae95f8019067000a9c07eb4905a5423ff6e4ae01eb0c000c92cde906a38a4611f80c104078754641ea002081b2012000f0b3ff00287ff4d7ae0698c468002c3ff4d8ad0aeb05004d900c984ef20761c0f25b01401b48f2e4528a464e9001f13c054da8c0f278020f213823a847002800f06d814da8d047bce5064600200021984600f08afff06800283ff4b3ad0bf10101490801fb0af7abeb010101fb0a004ef20769c0f25b0948f2e452cde9500709f13c044da8c0f278020f213823a04730bb09f585724da80421904701281fd1529c4da8c847bc427ff48cadb8f1000f7ff473ab80e64ef20764c0f25b0448f2e45207930690856804f13c074da8c0f278020f213823b84750b34da8a04771e54da8c8476ee50c2afff46cadcf78ce79b7427ff467ad0f790e7ab7427ff462ad4af6ed04c0f24504cdf828a080461e460d461746a0473a46052729463346c246022808bf01274ff0090c4ff00b0e3de7022e0a9e06fb0bf735d104f585724da80421cde9505790470128c6d1ddf848914da8a047b9457ff435adcce00020a4f8fc005bb0bde8f08f0df59a7907f58572484604219047ddf8488105464846b847012d06d130462146424600f00cf9054601e04ff0ff350af144012046884728465bb0bde8f08f4af6ed00c0f24500cdf814b08047b0f1020818bfb846a5eb0800013009950890002008eb07090c900df1340a04f5857000260b904ff480700b9a51904da80021cdf840a19047ddf840e1beeb0a0c2fd0aaeb0e0111f1040f39d900231cf0030226d09d19454507d34d4505d21af80310a5eb0804099d2955012a19d05d1cac19444507d34c4505d21af80510099da4eb08042955022a0bd09a1c9319434507d34b4505d21af80210a3eb0802099b99546644beeb0a0118bf01214e450c9a28bf01220c9236d2a8bb0029b3d132e008992cf003048d19002303e000bf04339c42bcd0f218424507d34a4505d21af8031005eb030b0bf8011c511c414505d3494503d20aeb03014978e954911c414506d3494504d20aeb03018978ef187970d11c4145dbd34945d9d20aeb0301c978ea189170d3e74ef207614da8c0f25b0188470c98ddf814b0dde9095600283ff467ac079800283ff45dad069829465a46334600f07cff55e549f259700025c0f24e0084f8fc5080473fe70bf101010a9a4fea48004fea5108abeb5101514308fb09f201eb42010844750026180af585740df59a7948460021cde95065a0475199f1b948b9013f4644f4d14ef207614da8c0f25b0188470ae0012811d14ef207614da8c0f25b018847012f7ff421ac079800283ff417ad06980a9a5946fff706ba4ef207614da8c0f25b018847fff710bc00bff0b583b0002958d0362a56d30b78422b53d14b784d2b50d10b7f4f7f43ea0723042b4ad18b7dcf7d0e7e43ea072343ea06434f7e8e7ccd7c53ea076346ea05270e7d4d7d47ea064747ea05641d4648bf5d42b0f84070002b4ff00003c8bf0123bc422ad1b0f84270bd4226d18f7ace7a91f80cc047ea06274e7b47ea0c4747ea0667974219d2621c032606eb5202866822f0030cca19cde901c30746304621462346009500f00cff3846314622462b4600f0d4fe002003b0f0bd41f24b63c0f2500303b0bde8f040184700bfc368002b08bf70472de9f04f9bb00e9080688b46002a1590149200f08a800bf101014fea510eabeb510101fb02f001fb023118441391abf1010116910bf0030117912bf003014f421599a0f102084c1c4ff0000906e000bf09f101095c449145f04466d0bbf1000ff6d01698032801d2002522e06ff00301404600bf10f8023f03f0f00646ea13136618f3700378043103f00f0545ea03133371437803f0f00545ea13137371437803f00f0545ea03137d180435b371e1d10d1d17980028cbd013985feac57a09fb0e034fea55001e5c159806f00f0c08bf4fea161c179909fb0b004cea0c1601294655b5d005f1010c4fea5c069e5d71464fea161ebaf1000f08bf06f00f0e4eea0e168e461799149a022900f80c609fd0a91c4e089b5dbaf1000f03f00f0608bf1e0946ea0613435492e743f6dc77c2f20007386842f66f3501466ff39601b1f1005fc0f2470540f0d88101684ef65a63ccf2ff03994240f0d08190f8ce10002940f08d8290f8d13090f8cf1090f8d07090f8d2008df862300a2a13464ff000028df860108df861708df8630028bf0a2303f00e001792159a41424fea4b00dc070d9406e0179b18320133042b179300f06182179f18abdb5d002b6ff0220308bf3323149f002fedd0179f07eb47074feac70a4af0040513954af0060511950af1080510950af10a050c950af10c0509950af10d0508950af10e050795149d4af00304012d0af10f0506950af1100505950af111054af0010c4af0020e16944af005094af007080af109060af10b0404950af112070af113050295cde90a46cdf83c80cdf8489005d10d9c0025002ca9d0dce000bf03974ff0000917463446019206e000bfa9f102094945074400f0c680da454dd2dc453b704ad2de457b7047d22246169cbb705c45144641d2139dfb705d453dd2129d3b715d4539d2119d7b715d4535d2d845bb7132d2109dfb715d452ed25c453b722bd20c9d7b725d4527d20a9cbb725c45144622d2099dfb725d451ed2089c3b735c45144619d2079d7b735d4515d2069dbb735d4511d2059afb735a450dd2049d3b745d4509d2039d7b745d4505d2029dbb745d4538bffb7400bfda45a7d2dc4507f80b30a3d207eb0b05de456b709ed22246169cab705c45144698d2139eeb705e45bff494af129e2b715e45bff48faf119e6b715e45bff48aafd845ab71bff486af109eddf83c805e45eb71bff47faf5c452b72bff47baf0c9eddf83c800b9c5e456b72bff473af0a9eab725e45bff46eaf099eddf83c800b9c5e45eb72bff466af2246089c2b735c451446bff45faf079eddf83c800b9c5e456b73bff457af069eddf83c800b9c5e45ab73bff44faf059aeb735a45bff44aaf049eddf83c800b9c5e452b74bff442af039e6b745e45bff43daf029eddf83c800b9c5e45ab7438bfeb7433e70d9c039f019ac9f10005002c3ff4ccaeda45bff4c9ae159edc4505fb0b6505f80a30bff4c1aede4505f80c30bff4bcae3e46169f05f80e305f45bff4b5ae139f5f45169feb55bff4afae129f5f45139feb55bff4a9ae119f5f45129feb55bff4a3ae0f9f5f45119feb55bff49dae109f5f450f9feb55bff497ae0b9f5f45109feb55bff491ae0c9f5f450b9feb55bff48bae0a9f5f450c9feb55bff485ae099f5f450a9feb55bff47fae089f5f45099feb55bff479ae079f5f45089feb55bff473ae069f5f45079feb55bff46dae059f5f45069feb55bff467ae049f5f45059feb55bff461ae049f5e45eb55bff45cae029fab555f453cbf029feb5554e64ff4f870a847002800f0b3804ff61061149acff6ff71002600bf43183e3183f8f06183f8f16183f8f26183f8f36183f8f46183f8f56183f8f66183f8f76183f8f86183f8f96183f8fa6183f8fb6183f8fc6183f8fd6183f8fe6183f8ff6183f8006283f8016283f8026283f8036283f8046283f8056283f8066283f8076283f8086283f8096283f80a6283f80b6283f80c6283f80d6283f80e6283f80f6283f8106283f8116283f8126283f8136283f8146283f8156283f8166283f8176283f8186283f8196283f81a6283f81b6283f81c6283f81d6283f81e6283f81f6283f8206283f8216283f8226283f8236283f8246283f8256283f8266283f8276283f8286283f8296283f82a6283f82b6283f82c6283f82d627ff480af4ef65a61ccf2ff010160012180f8ce104ff0ff31a0f8d410a0f8d610a0f8d810a0f8da10a0f8dc10a0f8de10a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210386008e0149a0020386004e0149a42f66f35c0f24705159e02fb0bf405f5836119a8cde91964154688470e9940f2196041f8240f488940f601724bea004088604bea054051f8205c4860c0f24b022846cc600e61904740f2f751c0f24401284688471bb0bde8f04f704700bf2de9f04f8cb0159edde9177b8e4646ea02013943c90740f0c48000eb520500eb56044ff0ff304fea5708012100eb5700b8f1010f88bf7908079001f003000990c7f3410005906ff0010000eb570001906ff0020000eb5700009021f00301601c4f420390681c4ff0000a0a940b950290cdf8108006e000bf0af1010a159eda4500f0c981169854466fea0a01984288bf0beb01040b9de11801fb0e5925180a98964205fb0e0c35d9059c4146b4b10798012c19f800100cf8001001460ed00198022c19f800100cf80010014606d0009819f800100cf80010014600bf07980328cad300bf09eb010414f8016c0ceb010000f8016c14f8026c043900f8026c14f8036c00f8036c14f8044c00f8044ce9d1b2e700bf1798082802d2002126e000bf039801fb0ef605fb0ef1014402981c4600eb06086ff0030308eb0300c67801eb030b8bf80360067904338bf8046046798bf805608079fe1804368bf80600ebd1ddf860b0ddf81080191d2346099800283ff482af099c19f80100012c0cf801003ff47aaf481c099d19f80040022d0cf800403ff471af881c19f800100cf800106ae74ff6fc71394007f003080b91791e00240591cdf828800893cde906e006e0099cdde9070301345c4500f02481169de74321469d42099488bf0beb0701cf1807fb0e092944179f01fb0e0c4ff0000a042fc0f09d80ddf814b000bf50461599964288bf584600eb020500eb01064fea550019f800806ff0010080ea0a000af1010188bf39186ff0020080ea0a000af1020388bf3b186ff003008aea000e0af103004feac57588bf07eb0e0008f00f07002d4fea560508bf4fea18171cf80540f60704f00f0604f0f0043c4408bf46ea07148f180cf805407e08159d19f806602944ff0706f00f054fea510708bf35091cf80760c90706f00f0106f0f0062e4408bf41ea051699180cf807604f08159e19f807703344c90707f00f064fea530108bf3e091cf80170db0707f00f0307f0f007374408bf43ea06170cf801708118159e4b0819f803303044c90703f00f074fea500108bf1f091cf80130c00703f00f0003f0f0033b4408bf40ea07130b98179f0af1040a8245abf1040b0cf801307ff46cafddf818e0ddf860b0ddf82880b8f1000f3ff444af6fea0a005146964288bf3918881843083144c00719f803304fea51001cf8005003f00f0608bf1e0905f00f0305f0f0053544c90708bf43ea06150a99159eddf8288001290cf800503ff41eaf0af10101a7eb0a04964288bfa11e8b185d083144db0719f805504fea51031cf8030005f00f0608bf2e0900f00f0500f0f0003044c90708bf45ea0610ddf82880159eb8f1020f0cf803003ff4f7ae0af10200964288bfe01e81184b083044c90719f803304fea50011cf8016003f00f0508bf1d0906f00f0306f0f0062e44c00708bf43ea0516ddf828800cf80160159ed4e60cb0bde8f08f70b543f6dc76c2f2000632680c4611466ff39601b1f1005f054607d110684ef65a61ccf2ff01884200f0bb8042f66f31c0f247014ff4f8708847002800f0fb8002464ff61060cff6ff70002113183e3083f8f01183f8f11183f8f21183f8f31183f8f41183f8f51183f8f61183f8f71183f8f81183f8f91183f8fa1183f8fb1183f8fc1183f8fd1183f8fe1183f8ff1183f8001283f8011283f8021283f8031283f8041283f8051283f8061283f8071283f8081283f8091283f80a1283f80b1283f80c1283f80d1283f80e1283f80f1283f8101283f8111283f8121283f8131283f8141283f8151283f8161283f8171283f8181283f8191283f81a1283f81b1283f81c1283f81d1283f81e1283f81f1283f8201283f8211283f8221283f8231283f8241283f8251283f8261283f8271283f8281283f8291283f82a1283f82b1283f82c1283f82d127ff480af4ef65a60ccf2ff001060012082f8ce004ff0ff30a2f8d400a2f8d600a2f8d800a2f8da00a2f8dc00a2f8de00a2f8e000a2f8e200a2f8e400a2f8e600a2f8e800a2f8ea00a2f8ec00a2f8ee00a2f8f000a2f8f20032600120002d82f8cc0047d0104630f8d41fa1423bd0b2f8d610a14237d0b2f8d810a14233d0b2f8da10a1422fd0b2f8dc10a1422bd0b2f8de10a14227d0b2f8e010a14223d0b2f8e210a1421fd0b2f8e410a1421bd0b2f8e610a14217d0b2f8e810a14213d0b2f8ea10a1420fd0b2f8ec10a1420bd0b2f8ee10a14207d0b2f8f010a14203d0b2f8f210a1420ad1012082f8d10070bd0020306070bd82f8cd00002070bd92f8cd1081b9b2f8c810611a0bb2b3f1ff3f06dd89b2022924bf012182f8d01002e0012182f8cf10b2f8ca30002182f8cd109c42a2f8c84088bfa2f8ca4092f8f41020f81140481c00f00f0082f8f400002070bd2de9f04182b003fb02f68846cde9001642f6877107466846c0f247011c461546884740f2196047f8240f788940f6017245ea0040b86045ea044057f8204c7860c0f24b0220463946fe60c7f81080904740f2f751c0f244012046884702b0bde8f08100bf2de9f04f83b00c9e0292002e019000f08e80019823f00304471c029803f0030ac4f1000c01384ff00008009005e000bf08f10108b0450f4479d00e98c14600286fea080418bf06eb0409002bf0d0042b06d24ff0000bbaf1000f2ed1e8e700bf0d98b64609fb00f400986ff003050444607800f0f00242ea10107a19d0706078043500f00f0646ea0010107114f8020f00f0f00646ea10105071207800f00f0646ea00100ceb050604369071e0d105f1040b7646baf1000fbad002980d9a4fea5b0509fb0204019814f805e008fb01050ef00f025feacb7908bf4fea1e1242ea0212baf1010f05f80b20a1d00bf1010e4fea5e00205cb9f1000f4fea101208bf00f00f0242ea0210baf1020f05f80e008ed00bf102004208a25cb9f1000f02f00f0408bf140944ea04122a5480e703b0bde8f08f092978d12de9f04102eb030c56248cf804404e248cf8064043248cf8074046248cf8084057248cf809402f248cf80a4031244ff0a20e8cf80b406924352702f803e04ff0060e8cf80d408cf8107037278cf814407a248cf801e04ff0250e67268cf8117036278cf8174078248cf802e04ff0450e6d258cf80f608cf812708cf816608cf8194064266c2761248cf803e08cf805e04ff0200e8cf80e508cf815504ff06f0872258cf81c6065268cf81e7074278cf82040732428338cf80ce08cf813e08cf818e08cf81a808cf81b508cf81d608cf81f708cf821e08cf822408cf823708cf824608cf825508cf826608cf82780bde8f04143f68d1cc0f2470c60474ef23010c2f234000078042818bf704780b582b04ff2332e4ff0000cc0f24f0e0020002100220923cdf804c0cdf800c0f04702b080bd00bff0b583b04ef23013c2f234031b784ff66b44042bc0f2450420d144f20c43c2f207031b680546184616460f46a04703463946324628468bb11b68e02b0ed14ff233260027c0f24f060020002100220a2301970097b047012003b0f0bd04f1160303b0bde8f0401847", + "desc": "append injected blobs to main-app payload" + }, + { + "offset": 628968, + "old": "a8713500", + "new": "7c983500", + "desc": "main-app subheader payload size (ps)" + }, + { + "offset": 136, + "old": "28723500", + "new": "fc983500", + "desc": "main-app TOC entry size (ps + 128)" + }, + { + "offset": 629088, + "old": "a8713504", + "new": "7c983504", + "desc": "main-app preamble length (low 24 bits)" + }, + { + "offset": 629092, + "old": "7a8feaba", + "new": "4ba49032", + "desc": "[4] ota/s200_firmware_ota.bin preamble crc32" + }, + { + "offset": 140, + "old": "ee469ded", + "new": "adef18ac", + "desc": "[4] ota/s200_firmware_ota.bin component crc32c (TOC)" + }, + { + "offset": 628972, + "old": "ee469ded", + "new": "adef18ac", + "desc": "[4] ota/s200_firmware_ota.bin component crc32c (subheader)" + } + ] +}; diff --git a/app/native/firmware-flasher.ts b/app/native/firmware-flasher.ts new file mode 100644 index 00000000..b2cfba7e --- /dev/null +++ b/app/native/firmware-flasher.ts @@ -0,0 +1,101 @@ +import { Utils } from "@nativescript/core"; + +declare const com: any; + +export type FlashState = "validating" | "connecting" | "flashing" | "rebooting" | "done" | "error"; + +export type FlashProgress = { + lens: string; + componentIndex: number; + componentCount: number; + blockIndex: number; + blockCount: number; +}; + +/** + * TS wrapper around the native FaceclawFirmwareFlasher — streams a verified + * custom-firmware image to both lenses over the stock OTA BLE protocol. + */ +export class FirmwareFlasher { + private readonly flasher: any; + private readonly listenerProxy: any; + private readonly logListeners = new Set<(line: string) => void>(); + private readonly progressListeners = new Set<(progress: FlashProgress) => void>(); + private readonly stateListeners = new Set<(state: FlashState, detail: string) => void>(); + private readonly completeListeners = new Set<(success: boolean, detail: string) => void>(); + + constructor(addresses: { right: string; left: string }, firmwarePath: string) { + const context = Utils.android.getApplicationContext(); + if (!context) throw new Error("Android application context unavailable"); + + this.flasher = new com.faceclaw.app.FaceclawFirmwareFlasher( + context, + addresses.right, + addresses.left, + firmwarePath, + ); + this.listenerProxy = new com.faceclaw.app.FaceclawFirmwareFlasherListener({ + onLog: (line: string) => this.emit(this.logListeners, String(line)), + onProgress: ( + lens: string, + componentIndex: number, + componentCount: number, + blockIndex: number, + blockCount: number, + ) => + this.emit(this.progressListeners, { + lens: String(lens), + componentIndex: Number(componentIndex), + componentCount: Number(componentCount), + blockIndex: Number(blockIndex), + blockCount: Number(blockCount), + }), + onState: (state: string, detail: string) => + this.emit(this.stateListeners, String(state) as FlashState, String(detail ?? "")), + onComplete: (success: boolean, detail: string) => + this.emit(this.completeListeners, Boolean(success), String(detail ?? "")), + }); + this.flasher.setListener(this.listenerProxy); + } + + onLog(listener: (line: string) => void): () => void { + this.logListeners.add(listener); + return () => this.logListeners.delete(listener); + } + + onProgress(listener: (progress: FlashProgress) => void): () => void { + this.progressListeners.add(listener); + return () => this.progressListeners.delete(listener); + } + + onStateChange(listener: (state: FlashState, detail: string) => void): () => void { + this.stateListeners.add(listener); + return () => this.stateListeners.delete(listener); + } + + onComplete(listener: (success: boolean, detail: string) => void): () => void { + this.completeListeners.add(listener); + return () => this.completeListeners.delete(listener); + } + + start(): void { + this.flasher.start(); + } + + cancel(): void { + this.flasher.cancel(); + } + + close(): void { + this.flasher.close(); + } + + private emit(listeners: Set<(...args: A) => void>, ...args: A): void { + const snapshot = Array.from(listeners); + setTimeout(() => { + for (const listener of snapshot) { + listener(...args); + } + }, 0); + } +} diff --git a/app/native/flash-prompt-communicator.ts b/app/native/flash-prompt-communicator.ts new file mode 100644 index 00000000..19f08c47 --- /dev/null +++ b/app/native/flash-prompt-communicator.ts @@ -0,0 +1,82 @@ +import { Utils } from "@nativescript/core"; + +declare const com: any; + +export type FlashPromptState = + | "connecting" + | "connected" + | "prompting" + | "result" + | "cancelled" + | "timeout" + | "disconnected" + | "error"; + +/** + * TS wrapper around the native FaceclawFlashPromptCommunicator — the + * stock-firmware-compatible BLE path that shows the pre-flash confirmation on + * the glasses and reports the user's Yes/No choice. Separate from + * FaceclawCommunicatorBridge on purpose (different, minimal protocol subset). + */ +export class FlashPromptCommunicator { + private readonly communicator: any; + private readonly listenerProxy: any; + private readonly logListeners = new Set<(line: string) => void>(); + private readonly stateListeners = new Set<(state: FlashPromptState, detail: string) => void>(); + private readonly resultListeners = new Set<(approved: boolean) => void>(); + + constructor(addresses: { right: string; left: string }, warningText: string) { + const context = Utils.android.getApplicationContext(); + if (!context) throw new Error("Android application context unavailable"); + + this.communicator = new com.faceclaw.app.FaceclawFlashPromptCommunicator( + context, + addresses.right, + addresses.left, + warningText, + ); + this.listenerProxy = new com.faceclaw.app.FaceclawFlashPromptListener({ + onLog: (line: string) => this.emit(this.logListeners, String(line)), + onState: (state: string, detail: string) => + this.emit(this.stateListeners, String(state) as FlashPromptState, String(detail ?? "")), + onResult: (approved: boolean) => this.emit(this.resultListeners, Boolean(approved)), + }); + this.communicator.setListener(this.listenerProxy); + } + + onLog(listener: (line: string) => void): () => void { + this.logListeners.add(listener); + return () => this.logListeners.delete(listener); + } + + onStateChange(listener: (state: FlashPromptState, detail: string) => void): () => void { + this.stateListeners.add(listener); + return () => this.stateListeners.delete(listener); + } + + onResult(listener: (approved: boolean) => void): () => void { + this.resultListeners.add(listener); + return () => this.resultListeners.delete(listener); + } + + start(): void { + this.communicator.start(); + } + + cancel(): void { + this.communicator.cancel(); + } + + close(): void { + this.communicator.close(); + } + + private emit(listeners: Set<(...args: A) => void>, ...args: A): void { + const snapshot = Array.from(listeners); + setTimeout(() => { + for (const listener of snapshot) { + listener(...args); + } + }, 0); + } +} diff --git a/app/phone-ui/onboarding-flash-page.ts b/app/phone-ui/onboarding-flash-page.ts new file mode 100644 index 00000000..5e3b6f46 --- /dev/null +++ b/app/phone-ui/onboarding-flash-page.ts @@ -0,0 +1,10 @@ +import { EventData, Page } from "@nativescript/core"; + +import { OnboardingFlashViewModel } from "./onboarding-flash-view-model"; + +export function navigatingTo(args: EventData): void { + const page = args.object as Page; + if (!page.bindingContext) { + page.bindingContext = new OnboardingFlashViewModel(); + } +} diff --git a/app/phone-ui/onboarding-flash-page.xml b/app/phone-ui/onboarding-flash-page.xml new file mode 100644 index 00000000..7903f2d2 --- /dev/null +++ b/app/phone-ui/onboarding-flash-page.xml @@ -0,0 +1,18 @@ + + + + + + + + +