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:
James Babcock committed 2026-07-10 12:07:15 -07:00
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);
}
});
}
}
@@ -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);
}
}
}
@@ -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;