mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
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.
This commit is contained in:
1 parent
2c04d99dfb
commit
cb78841a9d
17 files changed
+2464
-10
No files matched your search
@@ -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<byte[]> 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<Segment> 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<Segment> 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<byte[]> 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<Segment> 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<Segment> 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<Segment> validate(byte[] img) {
|
||||
List<Segment> 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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+21
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+412
@@ -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<String, CountDownLatch> 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<byte[]> 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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<byte[]> 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<byte[]> 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<byte[]> 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;
|
||||
|
||||
@@ -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<BuiltFirmware> {
|
||||
const report = (progress: FirmwareProgress) => {
|
||||
try {
|
||||
onProgress?.(progress);
|
||||
} catch {
|
||||
// progress reporting must never break the build
|
||||
}
|
||||
};
|
||||
|
||||
report({ phase: "downloading" });
|
||||
const base = await downloadFirmware();
|
||||
|
||||
report({ phase: "verifying-base" });
|
||||
const baseSha = sha256Hex(base);
|
||||
if (baseSha !== CFW_PATCH_SET.baseSha256) {
|
||||
throw new FirmwareBuildError(
|
||||
`Downloaded stock firmware failed verification.\nexpected ${CFW_PATCH_SET.baseSha256}\ngot ${baseSha}`,
|
||||
);
|
||||
}
|
||||
|
||||
const patched = applyPatches(new Uint8Array(base), CFW_PATCH_SET.patches, (applied, total) =>
|
||||
report({ phase: "patching", applied, total }),
|
||||
);
|
||||
|
||||
report({ phase: "verifying-output" });
|
||||
const outBuffer = tightBuffer(patched);
|
||||
const outSha = sha256Hex(outBuffer);
|
||||
if (outSha !== CFW_PATCH_SET.outputSha256) {
|
||||
throw new FirmwareBuildError(
|
||||
`Patched firmware failed verification.\nexpected ${CFW_PATCH_SET.outputSha256}\ngot ${outSha}`,
|
||||
);
|
||||
}
|
||||
|
||||
report({ phase: "writing" });
|
||||
const path = `${knownFolders.documents().path}/${OUTPUT_FILENAME}`;
|
||||
writeFile(path, outBuffer);
|
||||
|
||||
report({ phase: "done", path, bytes: patched.length });
|
||||
return { path, bytes: patched.length, sha256: outSha };
|
||||
}
|
||||
|
||||
async function downloadFirmware(): Promise<ArrayBuffer> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(FIRMWARE_URL);
|
||||
} catch (error) {
|
||||
throw new FirmwareBuildError(`Could not reach Even's firmware CDN: ${(error as Error)?.message ?? error}`);
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new FirmwareBuildError(`Firmware download failed (HTTP ${response.status}).`);
|
||||
}
|
||||
return response.arrayBuffer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Replay the committed patch set onto `base`, returning the patched bytes. Each
|
||||
* op writes `new` at `offset` after checking the bytes there equal `old`; an op
|
||||
* with empty `old` appends at end-of-file (offset must equal current length).
|
||||
* Idempotent: an op whose target already equals `new` is skipped. Mirrors
|
||||
* apply_patches.py:apply_ops.
|
||||
*/
|
||||
function applyPatches(
|
||||
base: Uint8Array,
|
||||
ops: FirmwarePatchOp[],
|
||||
onStep?: (applied: number, total: number) => void,
|
||||
): Uint8Array {
|
||||
let buf = base;
|
||||
for (let i = 0; i < ops.length; i++) {
|
||||
const op = ops[i];
|
||||
const oldBytes = hexToBytes(op.old ?? "");
|
||||
const newBytes = hexToBytes(op.new);
|
||||
const off = op.offset;
|
||||
const tag = `patch #${i} @ 0x${off.toString(16)}${op.desc ? ` (${op.desc})` : ""}`;
|
||||
|
||||
if (oldBytes.length > 0) {
|
||||
const cur = buf.subarray(off, off + oldBytes.length);
|
||||
if (bytesEqual(cur, newBytes) && !bytesEqual(cur, oldBytes)) {
|
||||
onStep?.(i + 1, ops.length);
|
||||
continue; // already applied
|
||||
}
|
||||
if (!bytesEqual(cur, oldBytes)) {
|
||||
throw new FirmwareBuildError(
|
||||
`${tag}: unexpected bytes in stock image (found ${bytesToHex(cur)}, expected ${op.old}). ` +
|
||||
`The downloaded image is not the stock base this patch set targets.`,
|
||||
);
|
||||
}
|
||||
buf.set(newBytes, off);
|
||||
} else {
|
||||
const end = off + newBytes.length;
|
||||
if (off <= buf.length && end <= buf.length && bytesEqual(buf.subarray(off, end), newBytes)) {
|
||||
onStep?.(i + 1, ops.length);
|
||||
continue; // already applied
|
||||
}
|
||||
if (off !== buf.length) {
|
||||
throw new FirmwareBuildError(
|
||||
`${tag}: append expects offset 0x${off.toString(16)} to equal current length 0x${buf.length.toString(16)}.`,
|
||||
);
|
||||
}
|
||||
buf = concatBytes(buf, newBytes);
|
||||
}
|
||||
onStep?.(i + 1, ops.length);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
function hexToBytes(hex: string): Uint8Array {
|
||||
if (hex.length % 2 !== 0) {
|
||||
throw new FirmwareBuildError(`odd-length hex string: ${hex}`);
|
||||
}
|
||||
const out = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function bytesToHex(bytes: Uint8Array): string {
|
||||
let hex = "";
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
hex += bytes[i].toString(16).padStart(2, "0");
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
|
||||
const out = new Uint8Array(a.length + b.length);
|
||||
out.set(a, 0);
|
||||
out.set(b, a.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Return an ArrayBuffer holding exactly `bytes`' contents (no shared slack). */
|
||||
function tightBuffer(bytes: Uint8Array): ArrayBuffer {
|
||||
if (bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength) {
|
||||
return bytes.buffer;
|
||||
}
|
||||
return bytes.slice().buffer;
|
||||
}
|
||||
|
||||
/** SHA-256 hex digest of an ArrayBuffer, via Android's MessageDigest. */
|
||||
function sha256Hex(buffer: ArrayBuffer): string {
|
||||
return String(com.faceclaw.app.FaceclawFirmwareUtil.sha256Hex(buffer));
|
||||
}
|
||||
|
||||
/** Write an ArrayBuffer's bytes to `path`, via a native FileChannel write. */
|
||||
function writeFile(path: string, buffer: ArrayBuffer): void {
|
||||
com.faceclaw.app.FaceclawFirmwareUtil.writeFile(path, buffer);
|
||||
}
|
||||
@@ -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": "2de9f04f40f26c63c0f250031b681b6a3bb1930800f0bb80012b37d1002300278be0002a00f0b38002f0030c97084ff0000215d0a2eb870e471c4d1c6ff00306ac19e378ba19d37023790436137163795371a3790eeb060404349371f0d1321dbcf1000f00f093808b5cbcf1010f835400f08d80531ccf5cbcf1020fc75400f086800232895c8154bde8f08f23f0010c01f1010e00236ff0070b4ff0f0086ff00f0900bf0eeb030515f9016c00eb0b0a08ead615770648bf0f358af80850b50609eae577f50648bf0f3700eb830574076f704fea06774fea867409eae77709eae47448bf0f37af70f60718bf0f34ec701ef90340023308ead416670648bf0f362e71a60609eae676e70648bf0f366e71260709eae676670748bf0f36ae71a50709eae575e40718bf0f359c450bf1080b8af80f50b6d10bf10807520758bfbde8f08fc956f02303ead1134c0648bf0f33c3558b066ff00f04ca0604eae3734fea017200f1010648bf0f3304eae272851cf3554b0748bf0f32ea558a0700f1030c04eae272c90718bf0f320cf80720bde8f08f000002fb01f042f66f31c0f24701084700bf084642f6b331c0f24701084770b500284ed001684ef65a62ccf2ff02914218bf70bd90f8fc1090f8fd5049f2597c8d42c0f24e0c2ad205eb8501014491f8012191f8024191f8fee091f8ff3091f8001142ea0424012c4ff0010298bf14466e1c054680f8fd60b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f8fc10bde870406047e047d5f8f80038b148f2eb42c0f244022146bde87040104770bd00bf2de9f04f85b043f6dc76c2f200063568804628466ff3960042f66f34b0f1005fc0f2470407d128684ef65a61ccf2ff01884200f0b8804ff4f870a0470546002800f0b0804ff61060cff6ff70002100bf2a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa1182f8fb1182f8fc1182f8fd1182f8fe1182f8ff1182f8001282f8011282f8021282f8031282f8041282f8051282f8061282f8071282f8081282f8091282f80a1282f80b1282f80c1282f80d1282f80e1282f80f1282f8101282f8111282f8121282f8131282f8141282f8151282f8161282f8171282f8181282f8191282f81a1282f81b1282f81c1282f81d1282f81e1282f81f1282f8201282f8211282f8221282f8231282f8241282f8251282f8261282f8271282f8281282f8291282f82a1282f82b1282f82c1282f82d127ff480af4ef65a60ccf2ff002860012085f8ce004ff0ff30a5f8d400a5f8d600a5f8d800a5f8da00a5f8dc00a5f8de00a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f2003560b8f1000f18bf002d07d14af6ed00c0f2450005b0bde8f04f0047d8f80cb0bbf1000ff2d0d8f820a0baf1000fedd0a94659f8040f00287bd0686900287ad0686a002879d0686b002878d0686c002877d0686d002876d0686e002875d0686f002874d0d5f88400002872d0d5f89400002870d0d5f8a40000286ed0d5f8b40000286cd0d5f8b00029690490d5f8a0002a6b0390d5f8900000260290d5f880002f6f0190286ad5f860e0d5f850c02b6c884238bf014638bf01268a423cbf114602268b423cbf194603268c453cbf614604268e453cbf714605268f423cbf39460626019888423cbf01460726029888423cbf01460826039888423cbf014609260498884238bf0146d5f8c00038bf0a26884238bf0b2609eb0610406804f1440137018847002049f80700012085f8d20016e0002614e0012612e0022610e003260ee004260ce005260ae0062608e0072606e0082604e0092602e00a2600e00b265046a04700283ff451af0af0030c5fea9a034ff0000218d00496a2eb830e431c0bf101066ff00307f119cc78da19d4700c79043714714c79547189790eeb070404349171f0d1049e3a1dbcf1000f10d01bf80230bcf1010f83540ad0531c1bf80370bcf1020fc75403d0911c1bf80120425409eb06114860d5f8c400320149f80280421cc1f808a0c5f8c420c8600de738464146fff732be2de9f04f81b043f6dc7ac2f2000adaf80050044628466ff3960042f66f3916460f46b0f1005fc0f2470907d128684ef65a61ccf2ff01884200f0b8804ff4f870c8470546002800f015814ff61060cff6ff7000212a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa1182f8fb1182f8fc1182f8fd1182f8fe1182f8ff1182f8001282f8011282f8021282f8031282f8041282f8051282f8061282f8071282f8081282f8091282f80a1282f80b1282f80c1282f80d1282f80e1282f80f1282f8101282f8111282f8121282f8131282f8141282f8151282f8161282f8171282f8181282f8191282f81a1282f81b1282f81c1282f81d1282f81e1282f81f1282f8201282f8211282f8221282f8231282f8241282f8251282f8261282f8271282f8281282f8291282f82a1282f82b1282f82c1282f82d127ff480af4ef65a60ccf2ff002860012085f8ce004ff0ff30a5f8d400a5f8d600a5f8d800a5f8da00a5f8dc00a5f8de00a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f200caf8005005f1040a4ff0000b4ff000084ff0ff30002200234ff0ff3105e000bf6032c02a03f1060332d0af187e68a64204d13e6986423cbf194630467e69a64204d13e6a86423cbf591c30467e6aa64204d13e6b86423cbf991c30467e6ba64204d13e6c86423cbfd91c30467e6ca64204d13e6d86423cbf191d30467e6da642ced13f6e87423cbf591d3846c8e700bf002917d40aeb01104768866845f6c3400901c0f250004af801b08047204639463246012300f01af8804609f1440138468847a5e7404601b0bde8f08f45f6c340c0f25000caf800508047204639463246012301b0bde8f04f00e000bf2de9f04fdbb0002918bf002a04d15bb0bde8f04f00f050be0f7807f07f06052e00f06081072e47d0422ef0d0b0f840b0b0f842a0092e00f04682082e40f050820646022a4ff0ff30c0f03983002b00f036830bf10100032303eb500020f0030000fb0af07630824200f235824d78edb188460227b81c904200f22d8208eb070318f807705b7857ea032300f024821f18974200f2208208eb0001304614461a460023fff7adff2246013de3d130465946524600f067fe08e343f6dc74c2f20004236818466ff39600b0f1005f07d118684ef65a67ccf2ff07b84200f0c0800e4642f66f31c0f247014ff4f870154688470346002800f0b0804ff61060cff6ff70002100bf1a183e3082f8f01182f8f11182f8f21182f8f31182f8f41182f8f51182f8f61182f8f71182f8f81182f8f91182f8fa118Line truncated
|
||||
"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)"
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -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<A extends unknown[]>(listeners: Set<(...args: A) => void>, ...args: A): void {
|
||||
const snapshot = Array.from(listeners);
|
||||
setTimeout(() => {
|
||||
for (const listener of snapshot) {
|
||||
listener(...args);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
@@ -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<A extends unknown[]>(listeners: Set<(...args: A) => void>, ...args: A): void {
|
||||
const snapshot = Array.from(listeners);
|
||||
setTimeout(() => {
|
||||
for (const listener of snapshot) {
|
||||
listener(...args);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
|
||||
<GridLayout rows="*,auto" class="p-20">
|
||||
<ScrollView row="0">
|
||||
<StackLayout>
|
||||
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
|
||||
<ActivityIndicator busy="{{ busy }}" visibility="{{ busyVisibility }}" class="m-t-16" />
|
||||
<Progress value="{{ progress }}" maxValue="100" visibility="{{ progressVisibility }}" class="m-t-16" />
|
||||
<Label text="{{ status }}" class="m-t-16 text-center" textWrap="true" />
|
||||
<Label text="{{ log }}" class="m-t-24" textWrap="true" fontSize="12" visibility="{{ logVisibility }}" />
|
||||
</StackLayout>
|
||||
</ScrollView>
|
||||
|
||||
<GridLayout row="1" columns="*,*" class="m-t-20">
|
||||
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
|
||||
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" visibility="{{ primaryVisibility }}" class="-primary" />
|
||||
</GridLayout>
|
||||
</GridLayout>
|
||||
</Page>
|
||||
@@ -0,0 +1,519 @@
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
|
||||
import { ensureBlePermissions } from "../g2/android-permissions";
|
||||
import {
|
||||
isValidMacAddress,
|
||||
loadDeviceAddresses,
|
||||
saveDeviceAddresses,
|
||||
} from "../g2/device-addresses";
|
||||
import {
|
||||
buildCustomFirmware,
|
||||
FirmwareBuildError,
|
||||
FirmwareProgress,
|
||||
} from "../g2/firmware-builder";
|
||||
import { buildAddressSet, DeviceDiscoveryBridge } from "../native/device-discovery";
|
||||
import { FirmwareFlasher, FlashProgress, FlashState } from "../native/firmware-flasher";
|
||||
import { FlashPromptCommunicator, FlashPromptState } from "../native/flash-prompt-communicator";
|
||||
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
|
||||
|
||||
type FlashPhase = "intro" | "prompt" | "building" | "ready" | "flashing" | "flashed" | "error";
|
||||
|
||||
// Kept short to fit the glasses' ~50-column text grid.
|
||||
const GLASSES_WARNING =
|
||||
"Flashing custom firmware may void your warranty and can brick the glasses. Continue?";
|
||||
|
||||
export class OnboardingFlashViewModel extends Observable {
|
||||
private _phase: FlashPhase = "intro";
|
||||
private _headline = "Flash Custom Firmware";
|
||||
private _status = "";
|
||||
private _log = "";
|
||||
private _busy = false;
|
||||
private _progress = 0;
|
||||
|
||||
private readonly discovery = new DeviceDiscoveryBridge();
|
||||
private addresses: { right: string; left: string } | null = null;
|
||||
private firmwarePath = "";
|
||||
|
||||
private prompt: FlashPromptCommunicator | null = null;
|
||||
private promptUnsubscribers: Array<() => void> = [];
|
||||
private flasher: FirmwareFlasher | null = null;
|
||||
private flasherUnsubscribers: Array<() => void> = [];
|
||||
private retryAction: () => void = () => this.beginPrompt();
|
||||
|
||||
// --- observable properties -------------------------------------------------
|
||||
|
||||
get phase(): FlashPhase {
|
||||
return this._phase;
|
||||
}
|
||||
|
||||
get headline(): string {
|
||||
return this._headline;
|
||||
}
|
||||
|
||||
set headline(value: string) {
|
||||
if (this._headline !== value) {
|
||||
this._headline = value;
|
||||
this.notifyPropertyChange("headline", value);
|
||||
}
|
||||
}
|
||||
|
||||
get status(): string {
|
||||
return this._status;
|
||||
}
|
||||
|
||||
set status(value: string) {
|
||||
if (this._status !== value) {
|
||||
this._status = value;
|
||||
this.notifyPropertyChange("status", value);
|
||||
}
|
||||
}
|
||||
|
||||
get log(): string {
|
||||
return this._log;
|
||||
}
|
||||
|
||||
set log(value: string) {
|
||||
if (this._log !== value) {
|
||||
this._log = value;
|
||||
this.notifyPropertyChange("log", value);
|
||||
this.notifyPropertyChange("logVisibility", this.logVisibility);
|
||||
}
|
||||
}
|
||||
|
||||
get logVisibility(): "visible" | "collapse" {
|
||||
return this._log ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get busy(): boolean {
|
||||
return this._busy;
|
||||
}
|
||||
|
||||
set busy(value: boolean) {
|
||||
if (this._busy !== value) {
|
||||
this._busy = value;
|
||||
this.notifyPropertyChange("busy", value);
|
||||
this.notifyPropertyChange("busyVisibility", this.busyVisibility);
|
||||
}
|
||||
}
|
||||
|
||||
get busyVisibility(): "visible" | "collapse" {
|
||||
return this._busy ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get progress(): number {
|
||||
return this._progress;
|
||||
}
|
||||
|
||||
set progress(value: number) {
|
||||
const clamped = Math.max(0, Math.min(100, Math.round(value)));
|
||||
if (this._progress !== clamped) {
|
||||
this._progress = clamped;
|
||||
this.notifyPropertyChange("progress", clamped);
|
||||
}
|
||||
}
|
||||
|
||||
get progressVisibility(): "visible" | "collapse" {
|
||||
return this._phase === "flashing" ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get primaryLabel(): string {
|
||||
switch (this._phase) {
|
||||
case "intro":
|
||||
return "Connect & Confirm";
|
||||
case "ready":
|
||||
return "Flash Now";
|
||||
case "flashed":
|
||||
return "Finish";
|
||||
case "error":
|
||||
return "Retry";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
get secondaryLabel(): string {
|
||||
switch (this._phase) {
|
||||
case "prompt":
|
||||
return "Cancel";
|
||||
case "ready":
|
||||
return "Not Now";
|
||||
default:
|
||||
return "Back";
|
||||
}
|
||||
}
|
||||
|
||||
get primaryVisibility(): "visible" | "collapse" {
|
||||
return this.primaryLabel ? "visible" : "collapse";
|
||||
}
|
||||
|
||||
get secondaryVisibility(): "visible" | "collapse" {
|
||||
// No escape hatch mid-write (building/flashing) or after success (flashed).
|
||||
return this._phase === "building" || this._phase === "flashing" || this._phase === "flashed"
|
||||
? "collapse"
|
||||
: "visible";
|
||||
}
|
||||
|
||||
// --- button handlers -------------------------------------------------------
|
||||
|
||||
onPrimaryTap(): void {
|
||||
switch (this._phase) {
|
||||
case "intro":
|
||||
void this.beginPrompt();
|
||||
return;
|
||||
case "ready":
|
||||
this.startFlashing();
|
||||
return;
|
||||
case "flashed":
|
||||
this.finish();
|
||||
return;
|
||||
case "error":
|
||||
this.retryAction();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
onSecondaryTap(): void {
|
||||
if (this._phase === "prompt") {
|
||||
this.cancelPrompt();
|
||||
return;
|
||||
}
|
||||
if (this._phase === "building" || this._phase === "flashing" || this._phase === "flashed") {
|
||||
return;
|
||||
}
|
||||
this.leave();
|
||||
}
|
||||
|
||||
// --- prompt flow -----------------------------------------------------------
|
||||
|
||||
private async beginPrompt(): Promise<void> {
|
||||
if (!global.isAndroid) {
|
||||
this.toError("Flashing is only available on Android.", () => this.beginPrompt());
|
||||
return;
|
||||
}
|
||||
this.setPhase("prompt");
|
||||
this.headline = "Confirm On Your Glasses";
|
||||
this.log = "";
|
||||
this.busy = true;
|
||||
this.status = "Preparing to connect. Make sure your glasses are on and the Even app is disconnected.";
|
||||
|
||||
try {
|
||||
await ensureBlePermissions();
|
||||
const addresses = await this.resolveAddresses();
|
||||
if (!addresses) {
|
||||
this.busy = false;
|
||||
this.toError(
|
||||
"Couldn't find both glasses arms. Make sure the glasses are powered on and the Even app is disconnected, then retry.",
|
||||
() => this.beginPrompt(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.addresses = addresses;
|
||||
|
||||
this.status = "Connecting to your glasses. Watch the lens for a Yes/No prompt.";
|
||||
this.startCommunicator(addresses);
|
||||
} catch (error) {
|
||||
this.busy = false;
|
||||
this.toError(this.formatError(error), () => this.beginPrompt());
|
||||
}
|
||||
}
|
||||
|
||||
private startCommunicator(addresses: { right: string; left: string }): void {
|
||||
this.disposePrompt();
|
||||
const prompt = new FlashPromptCommunicator(addresses, GLASSES_WARNING);
|
||||
this.prompt = prompt;
|
||||
|
||||
this.promptUnsubscribers.push(
|
||||
prompt.onLog((line) => this.appendLog(line)),
|
||||
prompt.onStateChange((state, detail) => this.handlePromptState(state, detail)),
|
||||
prompt.onResult((approved) => this.handlePromptResult(approved)),
|
||||
);
|
||||
prompt.start();
|
||||
}
|
||||
|
||||
private handlePromptState(state: FlashPromptState, detail: string): void {
|
||||
switch (state) {
|
||||
case "connecting":
|
||||
this.status = "Connecting to your glasses...";
|
||||
break;
|
||||
case "connected":
|
||||
this.status = "Connected. Showing the confirmation on the lens...";
|
||||
break;
|
||||
case "prompting":
|
||||
this.status =
|
||||
"Look at the lens and choose Yes to flash or No to cancel. (Use the ring or a temple tap to select.)";
|
||||
break;
|
||||
case "result":
|
||||
// Handled by onResult.
|
||||
break;
|
||||
case "cancelled":
|
||||
this.busy = false;
|
||||
this.toError("Cancelled.", () => this.beginPrompt());
|
||||
break;
|
||||
case "timeout":
|
||||
this.busy = false;
|
||||
this.toError(detail || "No response from the glasses.", () => this.beginPrompt());
|
||||
break;
|
||||
case "disconnected":
|
||||
this.busy = false;
|
||||
this.toError(detail || "Lost connection to the glasses.", () => this.beginPrompt());
|
||||
break;
|
||||
case "error":
|
||||
this.busy = false;
|
||||
this.toError(detail || "Connection failed.", () => this.beginPrompt());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private handlePromptResult(approved: boolean): void {
|
||||
this.disposePrompt();
|
||||
if (!approved) {
|
||||
this.busy = false;
|
||||
this.toError("You declined on the glasses. No firmware was written.", () => this.beginPrompt());
|
||||
return;
|
||||
}
|
||||
void this.buildFirmware();
|
||||
}
|
||||
|
||||
private cancelPrompt(): void {
|
||||
this.status = "Cancelling...";
|
||||
try {
|
||||
this.prompt?.cancel();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.disposePrompt();
|
||||
this.busy = false;
|
||||
this.toError("Cancelled.", () => this.beginPrompt());
|
||||
}
|
||||
|
||||
// --- firmware build flow ---------------------------------------------------
|
||||
|
||||
private async buildFirmware(): Promise<void> {
|
||||
this.setPhase("building");
|
||||
this.headline = "Preparing Firmware";
|
||||
this.busy = true;
|
||||
this.status = "Confirmed. Downloading the stock firmware...";
|
||||
|
||||
try {
|
||||
const result = await buildCustomFirmware((progress) => this.reportBuildProgress(progress));
|
||||
this.firmwarePath = result.path;
|
||||
this.busy = false;
|
||||
this.setPhase("ready");
|
||||
this.headline = "Firmware Ready";
|
||||
this.status =
|
||||
`Custom firmware prepared and verified (${result.bytes.toLocaleString()} bytes).\n\n` +
|
||||
"Tap Flash Now to write it to your glasses. Keep both lenses powered on and nearby — " +
|
||||
"each lens takes a few minutes, and the glasses will reboot when each lens finishes. " +
|
||||
"Do not close the app during flashing.";
|
||||
this.appendLog(`saved to ${result.path}`);
|
||||
} catch (error) {
|
||||
this.busy = false;
|
||||
const message =
|
||||
error instanceof FirmwareBuildError ? error.message : this.formatError(error);
|
||||
this.toError(message, () => this.buildFirmware());
|
||||
}
|
||||
}
|
||||
|
||||
private reportBuildProgress(progress: FirmwareProgress): void {
|
||||
switch (progress.phase) {
|
||||
case "downloading":
|
||||
this.status = "Downloading the stock firmware from Even's CDN...";
|
||||
break;
|
||||
case "verifying-base":
|
||||
this.status = "Verifying the downloaded firmware...";
|
||||
break;
|
||||
case "patching":
|
||||
this.status = `Applying patches (${progress.applied}/${progress.total})...`;
|
||||
break;
|
||||
case "verifying-output":
|
||||
this.status = "Verifying the patched firmware...";
|
||||
break;
|
||||
case "writing":
|
||||
this.status = "Saving the prepared firmware...";
|
||||
break;
|
||||
case "done":
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// --- flashing flow ---------------------------------------------------------
|
||||
|
||||
private startFlashing(): void {
|
||||
if (!this.addresses || !this.firmwarePath) {
|
||||
this.toError("Missing glasses addresses or firmware; start over.", () => this.beginPrompt());
|
||||
return;
|
||||
}
|
||||
this.setPhase("flashing");
|
||||
this.headline = "Flashing Firmware";
|
||||
this.busy = true;
|
||||
this.progress = 0;
|
||||
this.status = "Starting. Do not close the app or power off the glasses.";
|
||||
|
||||
this.disposeFlasher();
|
||||
const flasher = new FirmwareFlasher(this.addresses, this.firmwarePath);
|
||||
this.flasher = flasher;
|
||||
this.flasherUnsubscribers.push(
|
||||
flasher.onLog((line) => this.appendLog(line)),
|
||||
flasher.onProgress((progress) => this.handleFlashProgress(progress)),
|
||||
flasher.onStateChange((state, detail) => this.handleFlashState(state, detail)),
|
||||
flasher.onComplete((success, detail) => this.handleFlashComplete(success, detail)),
|
||||
);
|
||||
flasher.start();
|
||||
}
|
||||
|
||||
private handleFlashState(state: FlashState, detail: string): void {
|
||||
switch (state) {
|
||||
case "validating":
|
||||
this.status = "Validating the firmware image...";
|
||||
break;
|
||||
case "connecting":
|
||||
this.status = `Connecting to the ${detail || ""} lens...`.replace(" ", " ");
|
||||
break;
|
||||
case "flashing":
|
||||
this.status = `Flashing the ${detail || ""} lens. Keep the glasses on and nearby.`.replace(" ", " ");
|
||||
break;
|
||||
case "rebooting":
|
||||
this.status = detail || "Lenses rebooting; reconnecting...";
|
||||
break;
|
||||
case "done":
|
||||
case "error":
|
||||
// Handled by onComplete.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private handleFlashProgress(progress: FlashProgress): void {
|
||||
const lensIndex = progress.lens === "right" ? 1 : 0;
|
||||
const withinLens =
|
||||
progress.componentCount > 0
|
||||
? (progress.componentIndex - 1 + (progress.blockCount > 0 ? progress.blockIndex / progress.blockCount : 0)) /
|
||||
progress.componentCount
|
||||
: 0;
|
||||
this.progress = ((lensIndex + withinLens) / 2) * 100;
|
||||
this.status =
|
||||
`Flashing ${progress.lens} lens — part ${progress.componentIndex}/${progress.componentCount}, ` +
|
||||
`block ${progress.blockIndex}/${progress.blockCount}. Keep the glasses on and nearby.`;
|
||||
}
|
||||
|
||||
private handleFlashComplete(success: boolean, detail: string): void {
|
||||
this.disposeFlasher();
|
||||
this.busy = false;
|
||||
if (success) {
|
||||
this.progress = 100;
|
||||
this.setPhase("flashed");
|
||||
this.headline = "All Done";
|
||||
this.status = detail || "Firmware installed. Your glasses are rebooting into Faceclaw's custom firmware.";
|
||||
return;
|
||||
}
|
||||
this.toError(detail || "Flashing failed.", () => this.startFlashing());
|
||||
}
|
||||
|
||||
// --- helpers ---------------------------------------------------------------
|
||||
|
||||
private async resolveAddresses(): Promise<{ right: string; left: string } | null> {
|
||||
const stored = loadDeviceAddresses();
|
||||
if (isValidMacAddress(stored.right) && isValidMacAddress(stored.left)) {
|
||||
return { right: stored.right, left: stored.left };
|
||||
}
|
||||
|
||||
this.status = "Scanning for your glasses...";
|
||||
const candidates = await this.discovery.scanCandidates(8000);
|
||||
const found = buildAddressSet(candidates);
|
||||
if (isValidMacAddress(found.right) && isValidMacAddress(found.left)) {
|
||||
saveDeviceAddresses({ right: found.right, left: found.left, ring: found.ring || stored.ring });
|
||||
return { right: found.right, left: found.left };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private finish(): void {
|
||||
setPreviewOnlyMode(false);
|
||||
setOnboardingCompleted(true);
|
||||
this.disposePrompt();
|
||||
this.disposeFlasher();
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
}
|
||||
|
||||
private leave(): void {
|
||||
this.disposePrompt();
|
||||
this.disposeFlasher();
|
||||
const frame = Frame.topmost();
|
||||
if (frame?.canGoBack()) {
|
||||
frame.goBack();
|
||||
} else {
|
||||
frame?.navigate({ moduleName: "phone-ui/onboarding-page", clearHistory: true });
|
||||
}
|
||||
}
|
||||
|
||||
private toError(message: string, retry: () => void): void {
|
||||
this.retryAction = retry;
|
||||
this.status = message;
|
||||
this.setPhase("error");
|
||||
this.headline = "Something Went Wrong";
|
||||
}
|
||||
|
||||
private setPhase(phase: FlashPhase): void {
|
||||
if (this._phase !== phase) {
|
||||
this._phase = phase;
|
||||
this.notifyPropertyChange("phase", phase);
|
||||
}
|
||||
this.notifyPropertyChange("primaryLabel", this.primaryLabel);
|
||||
this.notifyPropertyChange("secondaryLabel", this.secondaryLabel);
|
||||
this.notifyPropertyChange("primaryVisibility", this.primaryVisibility);
|
||||
this.notifyPropertyChange("secondaryVisibility", this.secondaryVisibility);
|
||||
this.notifyPropertyChange("progressVisibility", this.progressVisibility);
|
||||
}
|
||||
|
||||
private appendLog(line: string): void {
|
||||
const stamp = new Date().toISOString().slice(11, 19);
|
||||
this.log = this._log ? `${this._log}\n[${stamp}] ${line}` : `[${stamp}] ${line}`;
|
||||
}
|
||||
|
||||
private disposePrompt(): void {
|
||||
for (const unsubscribe of this.promptUnsubscribers) {
|
||||
try {
|
||||
unsubscribe();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
this.promptUnsubscribers = [];
|
||||
if (this.prompt) {
|
||||
try {
|
||||
this.prompt.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.prompt = null;
|
||||
}
|
||||
}
|
||||
|
||||
private disposeFlasher(): void {
|
||||
for (const unsubscribe of this.flasherUnsubscribers) {
|
||||
try {
|
||||
unsubscribe();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
this.flasherUnsubscribers = [];
|
||||
if (this.flasher) {
|
||||
try {
|
||||
this.flasher.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.flasher = null;
|
||||
}
|
||||
}
|
||||
|
||||
private formatError(error: unknown): string {
|
||||
const raw = (error as Error)?.message ?? String(error);
|
||||
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
}
|
||||
@@ -4,5 +4,9 @@ import { OnboardingViewModel } from "./onboarding-view-model";
|
||||
|
||||
export function navigatingTo(args: EventData): void {
|
||||
const page = args.object as Page;
|
||||
page.bindingContext = new OnboardingViewModel();
|
||||
// Preserve the step when returning from the flashing page (back navigation
|
||||
// re-fires navigatingTo); only build a fresh model on first entry.
|
||||
if (!page.bindingContext) {
|
||||
page.bindingContext = new OnboardingViewModel();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ApplicationSettings } from "@nativescript/core";
|
||||
|
||||
const ONBOARDING_COMPLETE_KEY = "onboarding.complete";
|
||||
const PREVIEW_ONLY_KEY = "onboarding.previewOnly";
|
||||
|
||||
export function hasCompletedOnboarding(): boolean {
|
||||
return ApplicationSettings.getBoolean(ONBOARDING_COMPLETE_KEY, false);
|
||||
@@ -9,3 +10,16 @@ export function hasCompletedOnboarding(): boolean {
|
||||
export function setOnboardingCompleted(completed: boolean): void {
|
||||
ApplicationSettings.setBoolean(ONBOARDING_COMPLETE_KEY, completed);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the user chose to skip flashing during onboarding and use only the
|
||||
* on-phone display preview instead of pairing with glasses. Persisted so the
|
||||
* app can adapt later; the flashing path clears it.
|
||||
*/
|
||||
export function isPreviewOnlyMode(): boolean {
|
||||
return ApplicationSettings.getBoolean(PREVIEW_ONLY_KEY, false);
|
||||
}
|
||||
|
||||
export function setPreviewOnlyMode(previewOnly: boolean): void {
|
||||
ApplicationSettings.setBoolean(PREVIEW_ONLY_KEY, previewOnly);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Frame, Observable } from "@nativescript/core";
|
||||
|
||||
import { setOnboardingCompleted } from "./onboarding-state";
|
||||
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
|
||||
|
||||
type OnboardingStep = 1 | 2 | 3;
|
||||
|
||||
@@ -38,12 +38,12 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
|
||||
showSecondary: true,
|
||||
},
|
||||
3: {
|
||||
headline: "Disconnect Even First",
|
||||
headline: "Custom Firmware Required",
|
||||
tagline: "",
|
||||
body:
|
||||
"You can switch back and forth between Faceclaw and the official Even Realities application at any time. However, they can't both be connected to the headset simultaneously. The Even app will reconnect to the glasses whenever you launch it. To disconnect the official Even app, open it, go to the Home tab, select your glasses, open the Connection submenu, and press Disconnect.",
|
||||
primaryLabel: "Configure",
|
||||
secondaryLabel: "Back",
|
||||
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. This connects to your glasses, asks for confirmation on the lens, then downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
|
||||
primaryLabel: "Flash Firmware",
|
||||
secondaryLabel: "Preview Only",
|
||||
showLogo: false,
|
||||
showTagline: false,
|
||||
showSecondary: true,
|
||||
@@ -67,10 +67,10 @@ export class OnboardingViewModel extends Observable {
|
||||
this.setStep(3);
|
||||
return;
|
||||
}
|
||||
setOnboardingCompleted(true);
|
||||
// Step 3 primary: proceed to the flashing flow (connect + on-glasses
|
||||
// confirmation + firmware download/patch/verify).
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/config-page",
|
||||
clearHistory: true,
|
||||
moduleName: "phone-ui/onboarding-flash-page",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -80,7 +80,13 @@ export class OnboardingViewModel extends Observable {
|
||||
return;
|
||||
}
|
||||
if (this._step === 3) {
|
||||
this.setStep(2);
|
||||
// Step 3 secondary: skip flashing, use the on-phone preview only.
|
||||
setPreviewOnlyMode(true);
|
||||
setOnboardingCompleted(true);
|
||||
Frame.topmost()?.navigate({
|
||||
moduleName: "phone-ui/main-page",
|
||||
clearHistory: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# resetOnboarding.sh — reset Faceclaw on an attached phone back to its
|
||||
# pre-onboarding state, for testing the onboarding flow repeatedly.
|
||||
#
|
||||
# By default this only clears the onboarding-related preference keys
|
||||
# (onboarding.complete, onboarding.previewOnly, ...) and leaves everything
|
||||
# else — notably the saved glasses/ring MAC addresses — intact, so you don't
|
||||
# have to re-scan devices on every test pass. Pass --all to wipe ALL app data
|
||||
# (a true fresh-install state, addresses included).
|
||||
#
|
||||
# Usage:
|
||||
# scripts/resetOnboarding.sh # reset onboarding flags only
|
||||
# scripts/resetOnboarding.sh --all # full `pm clear` (wipes everything)
|
||||
# scripts/resetOnboarding.sh -s <device-id> # target a specific adb device
|
||||
#
|
||||
# The device id defaults to $FACECLAW_DEVICE_ID, then to the id used by
|
||||
# build_and_run.sh. adb is located the same way build.sh finds its tools.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PACKAGE="com.faceclaw.app"
|
||||
PREF_KEY_PREFIX="onboarding."
|
||||
DEVICE_ID="${FACECLAW_DEVICE_ID:-3A101JEHN12330}"
|
||||
WIPE_ALL=0
|
||||
|
||||
# Match build.sh's tool locations so adb is on PATH even from a bare shell.
|
||||
export ANDROID_HOME="${ANDROID_HOME:-/Users/jbabcock/Library/Android/sdk}"
|
||||
export PATH="$ANDROID_HOME/platform-tools:$PATH"
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--all) WIPE_ALL=1; shift ;;
|
||||
-s|--device) DEVICE_ID="$2"; shift 2 ;;
|
||||
-h|--help)
|
||||
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
|
||||
exit 0 ;;
|
||||
*)
|
||||
echo "unknown option: $1 (try --help)" >&2
|
||||
exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
command -v adb >/dev/null 2>&1 || { echo "error: adb not found on PATH" >&2; exit 1; }
|
||||
|
||||
ADB="adb -s $DEVICE_ID"
|
||||
|
||||
# Confirm the device is actually there before doing anything.
|
||||
if ! $ADB get-state >/dev/null 2>&1; then
|
||||
echo "error: adb device '$DEVICE_ID' not connected." >&2
|
||||
echo " Connected devices:" >&2
|
||||
adb devices -l | sed '1d' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$WIPE_ALL" -eq 1 ]; then
|
||||
echo "Wiping ALL app data for $PACKAGE (fresh-install state)..."
|
||||
$ADB shell pm clear "$PACKAGE"
|
||||
echo "Done. The next launch starts from a clean onboarding."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Surgical reset: strip only the onboarding.* keys from the app's
|
||||
# SharedPreferences XML, preserving saved device addresses and other settings.
|
||||
# This needs run-as, which works for debuggable (sideloaded/dev) builds.
|
||||
if ! $ADB shell run-as "$PACKAGE" true >/dev/null 2>&1; then
|
||||
echo "run-as is unavailable for $PACKAGE (release build?)." >&2
|
||||
echo "Falling back to a full data wipe; re-run with --all to silence this." >&2
|
||||
$ADB shell pm clear "$PACKAGE"
|
||||
echo "Done (full wipe)."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Clearing onboarding preference keys ($PREF_KEY_PREFIX*) for $PACKAGE..."
|
||||
|
||||
# Force-stop first so the running app can't flush its in-memory preferences
|
||||
# back over the files after we edit them.
|
||||
$ADB shell am force-stop "$PACKAGE"
|
||||
|
||||
# List the shared_prefs XML files, then strip matching <... name="onboarding...">
|
||||
# entries from each. toybox sed (present on modern Android) supports -i.
|
||||
# Note: each remote command is passed to `adb shell` as ONE quoted string --
|
||||
# adb joins multiple args with spaces without re-quoting, so inner quoting
|
||||
# (e.g. sh -c '...') gets flattened and re-tokenized by the device shell.
|
||||
FILES="$($ADB shell "run-as $PACKAGE ls shared_prefs 2>/dev/null" | tr -d '\r' || true)"
|
||||
if [ -z "$FILES" ]; then
|
||||
echo "No shared_prefs found; the app may not have run yet. Nothing to do."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
CHANGED=0
|
||||
for f in $FILES; do
|
||||
case "$f" in
|
||||
*.xml) ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
if $ADB shell "run-as $PACKAGE grep -q 'name=\"$PREF_KEY_PREFIX' shared_prefs/$f" >/dev/null 2>&1; then
|
||||
$ADB shell "run-as $PACKAGE sed -i '/name=\"$PREF_KEY_PREFIX/d' shared_prefs/$f"
|
||||
echo " cleared onboarding keys in shared_prefs/$f"
|
||||
CHANGED=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$CHANGED" -eq 1 ]; then
|
||||
echo "Done. Relaunch Faceclaw to go through onboarding again."
|
||||
else
|
||||
echo "No onboarding keys were set. App is already in pre-onboarding state."
|
||||
fi
|
||||
Reference in new issue
Block a user