Merge branch 'bluetooth-pairing-improvements'

This commit is contained in:
James Babcock committed 2026-08-24 12:59:33 -07:00
commit ca183e5aed
54 files changed
+1115 -474

No files matched your search

@@ -1397,6 +1397,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
if (!sleepDuringConnectSettling(800)) {
return;
}
authenticateArms();
sendPrelude();
synchronized (lock) {
@@ -1577,6 +1578,55 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
}
}
/**
* Complete the sid-0x80 security-auth exchange on both freshly opened arm
* connections. Firmware 2.2.9 answers no queries until it completes over an
* encrypted link and closes unauthenticated links after ~30 s (see
* ../notes/ble-connections-2.2.9.md); on an unbonded phone the exchange is
* also what triggers SMP pairing. Deliberately soft: on timeout we log and
* continue rather than fail the connect — the custom firmware's response
* behavior is not yet hardware-verified, and on stock firmware an
* unanswered auth just means the prelude fails exactly as it did before.
* A pairing prompt accepted after our window still bonds at the OS level,
* so the next reconnect attempt authenticates promptly.
*/
private void authenticateArms() throws InterruptedException {
OutboundMessage right = messageBuilder.securityAuth(false);
OutboundMessage left = messageBuilder.securityAuth(true);
long now = SystemClock.elapsedRealtime();
for (OutboundMessage message : new OutboundMessage[] {right, left}) {
message.onAck = () -> {
};
message.onTimeout = () -> {
};
message.sentAtMs = now;
writeMessage(message);
}
long deadline = SystemClock.elapsedRealtime() + ConnectionOptions.SECURITY_AUTH_SOFT_TIMEOUT_MS;
while (running && !userDisconnectRequested && !inFlightMessages.isEmpty()) {
synchronized (lock) {
if (!running || userDisconnectRequested || inFlightMessages.isEmpty()) {
break;
}
}
long remaining = deadline - SystemClock.elapsedRealtime();
if (remaining <= 0) {
break;
}
interruptibleSleep.sleep(Math.min(remaining, 100));
}
synchronized (lock) {
if (!inFlightMessages.isEmpty()) {
clearInFlightMessagesLocked("security auth timeout");
logLine("security auth not acknowledged; continuing (2.2.9 stock requires it; older/custom firmware may not answer)");
return;
}
}
boolean rightOk = BleProtocol.isAuthenticationSuccess(right.ackPayload, right.magic);
boolean leftOk = BleProtocol.isAuthenticationSuccess(left.ackPayload, left.magic);
logLine("security auth R=" + (rightOk ? "ok" : "unconfirmed") + " L=" + (leftOk ? "ok" : "unconfirmed"));
}
private void sendPrelude() throws InterruptedException {
sendPrelude(false);
}
@@ -31,11 +31,12 @@ import java.util.Set;
* its company identifier restored so the "ER"+serial+MAC layout survives
* intact, RSSI, advertised TX power, and connectability.
*
* Admission is deliberately loose — a name containing G2 or R1, or the Even
* "ER" manufacturer signature — because renamed custom firmware may drop the
* stock name. Side, serial, and pair matching are decided in TypeScript
* (app/g2/even-advertisement.ts, app/g2/pairing-candidates.ts) where they can
* be unit-tested.
* Admission is deliberately loose — a name containing G2, the stock
* "EVEN R1…" ring prefix, or the Even "ER" manufacturer signature — because
* renamed custom firmware may drop the stock name. Side, serial, and pair
* matching are decided in TypeScript (app/g2/even-advertisement.ts,
* app/g2/pairing-candidates.ts) where they can be unit-tested; this filter
* must stay a superset of the TS classifier's admission.
*
* Ported from the discovery path of SybilSight's Bluetooth SDK (G2.didDiscover
* and R1's advertisement snapshot), reduced to what Android exposes.
@@ -288,7 +289,7 @@ public class FaceclawDeviceDiscovery {
Integer rssiValue = (rssi == 127 || rssi == 0) ? null : rssi;
boolean bonded = device.getBondState() == BluetoothDevice.BOND_BONDED;
return buildJson(
device.getAddress(), name, toHex(manufacturerData), rssiValue, txPower,
device.getAddress(), name, FaceclawFirmwareUtil.bytesToHex(manufacturerData), rssiValue, txPower,
connectable, bonded, "scan", System.currentTimeMillis());
}
@@ -332,7 +333,9 @@ public class FaceclawDeviceDiscovery {
return false;
}
String upper = name.toUpperCase();
return upper.contains("G2") || upper.contains("R1");
// A bare "R1" substring also matches unrelated hardware ("Oppo Enco
// R1"), and TS only classifies rings from the stock name prefix.
return upper.contains("G2") || upper.startsWith("EVEN R1");
}
private static JSONObject buildJson(
@@ -358,17 +361,6 @@ public class FaceclawDeviceDiscovery {
}
}
private static String toHex(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02X", b & 0xff));
}
return sb.toString();
}
private static String describeScanError(int errorCode) {
switch (errorCode) {
case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
@@ -23,6 +23,7 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
private final Context context;
private final String rightAddress;
private final String leftAddress;
private final FaceclawBleManager bleManager;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
@@ -35,13 +36,21 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
private byte[] awaitPb = null;
private CountDownLatch awaitLatch = null;
/**
* A sid-0x09 frame that carried firmware versions without matching the
* awaited magic — some firmware pushes the settings snapshot on a magic it
* picked itself instead of (or in addition to) acking the read.
*/
private volatile byte[] unsolicitedSettingsPb;
private volatile FaceclawDeviceInfoProbeListener listener;
private volatile Thread worker;
private volatile boolean cancelled = false;
public FaceclawDeviceInfoProbe(Context context, String rightAddress) {
public FaceclawDeviceInfoProbe(Context context, String rightAddress, String leftAddress) {
this.context = context.getApplicationContext();
this.rightAddress = rightAddress == null ? "" : rightAddress;
this.leftAddress = leftAddress == null ? "" : leftAddress;
this.bleManager = new FaceclawBleManager(this.context);
this.bleManager.setListener(this);
}
@@ -83,27 +92,28 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
return;
}
emitState("connecting", "");
connectArm(rightAddress);
byte[] ack = probeArm(rightAddress, "right");
// The right lens is the documented control endpoint, but a silent
// right lens has been observed on stock 2.2.9 even after a
// successful security auth — run the same probe against the left
// lens rather than giving up, and log which lens answered.
if (ack == null && !cancelled && !leftAddress.trim().isEmpty()
&& !leftAddress.equalsIgnoreCase(rightAddress)) {
emitLog("right lens did not answer the settings query; probing the left lens");
try {
ack = probeArm(leftAddress, "left");
} catch (Exception e) {
emitLog("left-lens probe failed: " + (e.getMessage() == null ? e.toString() : e.getMessage()));
}
}
if (cancelled) {
emitError("Cancelled.");
return;
}
emitState("querying", "");
// Session prelude, then a settings/device-info read (both arms'
// versions and the CFW capability string ride back in one response).
if (writeAndAwaitAck(rightAddress, BleProtocol.PRELUDE_ACK_SID, BleProtocol.FLAG_REQUEST,
BleProtocol.PRELUDE_ACK_MAGIC, BleProtocol.PRELUDE_F5872_PAYLOAD,
ConnectionOptions.PRELUDE_TIMEOUT_MS) == null) {
throw new IllegalStateException("session prelude not acked");
}
int magic = allocMagic();
byte[] ack = writeAndAwaitAck(rightAddress, BleProtocol.SID_UI_SETTING, BleProtocol.FLAG_REQUEST,
magic, BleProtocol.buildSettingsQuery(magic), QUERY_TIMEOUT_MS);
if (ack == null) {
throw new IllegalStateException("no response to the device-info query");
throw new IllegalStateException(
"no response to the device-info query on either lens — check `adb logcat -s "
+ TAG + "` for the frame trace");
}
BleProtocol.FirmwareInfo info = BleProtocol.parseSettingsFirmwareInfo(ack);
@@ -123,6 +133,73 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
}
}
/**
* Connect + authenticate + prelude + settings read on one lens. Returns the
* settings ack protobuf, an unsolicited settings push that carried firmware
* versions, or null when the lens never answered the read. Throws on
* connect or prelude failure; the caller wraps the fallback lens's attempt
* so its failure cannot mask the primary lens's outcome.
*/
private byte[] probeArm(String address, String label) throws InterruptedException {
emitState("connecting", label);
connectArm(address);
if (cancelled) {
return null;
}
// Firmware 2.2.9 answers no queries until the security-auth exchange
// completes over an encrypted link; on a phone with no existing bond
// this is also what triggers SMP pairing (and its OS prompt), so it
// must come before the prelude and query. Soft: this probe also runs
// against the custom firmware, whose response to the exchange is not
// yet hardware-verified, so an unconfirmed auth falls through.
emitState("authenticating", label);
boolean authenticated = authenticate(address);
if (cancelled) {
return null;
}
emitState("querying", label);
// Session prelude, then a settings/device-info read (both arms'
// versions and the CFW capability string ride back in one response).
if (writeAndAwaitAck(address, BleProtocol.PRELUDE_ACK_SID, BleProtocol.FLAG_REQUEST,
BleProtocol.PRELUDE_ACK_MAGIC, BleProtocol.PRELUDE_F5872_PAYLOAD,
ConnectionOptions.PRELUDE_TIMEOUT_MS) == null) {
throw new IllegalStateException("session prelude not acked (" + label + " lens)"
+ (authenticated ? "" : "; authentication did not complete —"
+ " if Android shows a Bluetooth pairing request, accept it and try again"));
}
// Two attempts: the first read straight after a fresh pairing has been
// seen to go unanswered while a later one succeeds.
for (int attempt = 0; attempt < 2 && !cancelled; attempt++) {
int magic = allocMagic();
byte[] ack = writeAndAwaitAck(address, BleProtocol.SID_UI_SETTING, BleProtocol.FLAG_REQUEST,
magic, BleProtocol.buildSettingsQuery(magic), QUERY_TIMEOUT_MS);
if (ack != null) {
return ack;
}
// A push with the firmware versions on the device's own magic is
// as good as the ack we asked for.
byte[] pushed = unsolicitedSettingsPb;
if (pushed != null) {
emitLog("using unsolicited settings push instead of the read ack (" + label + " lens)");
return pushed;
}
emitLog("settings query attempt " + (attempt + 1) + " unanswered (" + label + " lens)");
}
return null;
}
private boolean authenticate(String address) throws InterruptedException {
int magic = allocMagic();
byte[] ack = writeAndAwaitAck(address, BleProtocol.SID_SECURITY_AUTH, BleProtocol.FLAG_SECURITY_AUTH,
magic, BleProtocol.buildAuthenticationRequest(magic), ConnectionOptions.SECURITY_AUTH_TIMEOUT_MS);
boolean success = ack != null && BleProtocol.isAuthenticationSuccess(ack, magic);
emitLog(success ? "security auth complete: " + address : "security auth unconfirmed: " + address);
return success;
}
private void connectArm(String address) {
if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) {
throw new IllegalStateException("connect failed");
@@ -150,10 +227,13 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
synchronized (lock) {
seq = nextSeq++ & 0xff;
}
emitLog(String.format("tx %s sid=0x%02x flag=0x%02x magic=%d seq=0x%02x len=%d",
address, sid, flag, magic, seq, payload.length));
List<byte[]> frames = BleProtocol.framePb(payload, sid, flag, seq);
boolean written = bleManager.writeFrames(
address, BleProtocol.WRITE_CHAR_UUID, frames, ConnectionOptions.WRITE_TYPE, ConnectionOptions.WRITE_TIMEOUT_MS);
if (!written) {
emitLog("tx write FAILED sid=0x" + Integer.toHexString(sid));
synchronized (lock) {
awaitLatch = null;
}
@@ -171,10 +251,38 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
if (!BleProtocol.NOTIFY_CHAR_UUID.equalsIgnoreCase(characteristicUuid)) {
return;
}
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data);
// One notification value can carry several envelope frames back to
// back; reading only the first would silently drop the rest.
List<byte[]> frames = BleProtocol.splitFrames(data);
if (frames.size() > 1) {
emitLog("rx " + address + " value carries " + frames.size() + " frames (raw " + data.length + " bytes)");
}
for (byte[] buf : frames) {
handleFrame(address, buf, data.length);
}
}
private void handleFrame(String address, byte[] buf, int rawValueLength) {
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(buf);
if (!frame.ok) {
emitLog("rx " + address + " unparseable frame len=" + buf.length + " (raw value " + rawValueLength + ")"
+ " head=" + FaceclawFirmwareUtil.bytesToHex(java.util.Arrays.copyOf(buf, Math.min(16, buf.length))));
return;
}
// Log every control frame while diagnosing 2.2.9: sid/flag/type/magic
// plus a payload prefix is enough to reconstruct what the lens said.
int declared = buf.length > 3 ? buf[3] & 0xff : 0;
String truncated = buf.length < 8 + declared ? " TRUNCATED(declared=" + declared + ")" : "";
emitLog(String.format("rx %s sid=0x%02x flag=0x%02x type=%d magic=%d frag=%d/%d len=%d%s pb=%s",
address, frame.sid, frame.flag, frame.msgType, frame.msgSeq,
buf.length > 5 ? buf[5] & 0xff : 0, buf.length > 4 ? buf[4] & 0xff : 0, frame.pb.length, truncated,
FaceclawFirmwareUtil.bytesToHex(java.util.Arrays.copyOf(frame.pb, Math.min(48, frame.pb.length)))));
if (frame.sid == BleProtocol.SID_UI_SETTING
&& BleProtocol.parseSettingsFirmwareInfo(frame.pb) != null) {
// Any settings frame carrying firmware versions answers the probe's
// question, whether or not it matches the magic we asked with.
unsolicitedSettingsPb = frame.pb;
}
if (frame.flag == BleProtocol.FLAG_NOTIFY || frame.flag == BleProtocol.FLAG_NOTIFY_ALT) {
return; // async event, not an ack
}
@@ -14,17 +14,23 @@ 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.CountDownLatch;
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.
* aa21 envelope (BleProtocol.framePb) and the c0/c1 control/data protocol.
*
* Each lens connection completes the sid-0x80 security-auth exchange before
* OTA BEGIN — firmware 2.2.9 closes unauthenticated links ~30 s in, killing
* the transfer mid-component. No control-channel traffic is injected during
* the transfer itself: official OTA captures show none between BEGIN and the
* final END, heartbeats demonstrably do not satisfy the 2.2.9 deadline, and a
* concurrent control writer would interleave with the marker/data
* transactions. (See ../notes/ble-connections-2.2.9.md.)
*
* 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
@@ -40,7 +46,6 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
// 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;
@@ -52,9 +57,6 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
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.
@@ -89,10 +91,12 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
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;
private int nextAuthMagic = 0x60;
private int pendingAuthMagic = -1;
private CountDownLatch authLatch;
private byte[] authAckPb;
public FaceclawFirmwareFlasher(Context context, String rightAddress, String leftAddress, String firmwarePath) {
this.context = context.getApplicationContext();
@@ -127,7 +131,6 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
public void close() {
cancel();
stopHeartbeat();
try {
bleManager.close();
} catch (Exception ignored) {
@@ -172,27 +175,34 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
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();
// Fresh envelope counter for the OTA stream (the auth exchange during
// bring-up used its own); mirrors the stock sequence.
resetSeq();
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");
int beginStatus = sendCtrlAndWait(address, OP_BEGIN, EMPTY, CTRL_ACK_TIMEOUT_MS);
if (!isEndOk(beginStatus)) {
emitLog("warning: unexpected begin status " + beginStatus + "; continuing");
}
// Progress is reported in bytes across the whole image: the segments
// are one large firmware blob plus several small ones, so a bar
// stepped per segment would sit still through the big one and then
// sprint through the rest.
long totalBytes = 0;
for (Segment seg : segs) {
totalBytes += seg.ps;
}
long bytesBefore = 0;
for (int i = 0; i < segs.size(); i++) {
if (cancelled) {
throw new IllegalStateException("Cancelled.");
}
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();
flashComponentWithRetry(lens, address, i, segs.size(), segs.get(i), img, bytesBefore, totalBytes);
bytesBefore += segs.get(i).ps;
}
emitLog(lens + " lens: all components verified");
try {
@@ -201,14 +211,15 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
}
}
private void flashComponentWithRetry(String lens, String address, int index, int count, Segment seg, byte[] img) {
private void flashComponentWithRetry(String lens, String address, int index, int count, Segment seg, byte[] img,
long bytesBefore, long totalBytes) {
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);
endStatus = flashComponent(lens, address, index, count, seg, img, bytesBefore, totalBytes);
} catch (TimeoutException | RuntimeException e) {
emitLog(seg.name + ": block phase failed: " + e.getMessage());
endStatus = -1;
@@ -226,8 +237,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
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 {
private int flashComponent(String lens, String address, int index, int count, Segment seg, byte[] img,
long bytesBefore, long totalBytes) throws TimeoutException {
byte[] sub = Arrays.copyOfRange(img, seg.off, seg.off + 128);
int ps = seg.ps;
int payloadStart = seg.off + 128;
@@ -260,7 +271,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
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);
long bytesSent = bytesBefore + Math.min((long) (b + 1) * BLOCK_SIZE, (long) ps);
emitProgress(lens, index + 1, count, b + 1, blockCount, bytesSent, totalBytes);
}
}
emitLog(seg.name + ": data phase done; sending END");
@@ -356,50 +368,64 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
if (!bleManager.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) {
return false;
}
// Control-channel notify carries the auth response; mandatory.
if (!bleManager.enableNotifications(address, BleProtocol.NOTIFY_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_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);
if (!authenticate(address)) {
throw new IllegalStateException(
"security auth not acknowledged — if Android shows a Bluetooth pairing request, accept it");
}
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;
/**
* Complete the sid-0x80 security-auth exchange on this connection. On an
* unbonded phone this triggers SMP pairing (possibly with an OS prompt),
* so the wait is generous. Must succeed before any OTA traffic.
*/
private boolean authenticate(String address) {
int magic;
CountDownLatch latch = new CountDownLatch(1);
synchronized (lock) {
magic = nextAuthMagic;
nextAuthMagic = nextAuthMagic >= 0x7f ? 0x60 : nextAuthMagic + 1;
pendingAuthMagic = magic;
authAckPb = null;
authLatch = latch;
}
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();
if (!writeOta(address, BleProtocol.WRITE_CHAR_UUID, BleProtocol.SID_SECURITY_AUTH,
BleProtocol.buildAuthenticationRequest(magic), nextSeq())) {
emitLog("auth write failed: " + address);
return false;
}
boolean signalled;
try {
signalled = latch.await(ConnectionOptions.SECURITY_AUTH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
byte[] pb;
synchronized (lock) {
pb = authAckPb;
}
if (!signalled || !BleProtocol.isAuthenticationSuccess(pb, magic)) {
emitLog("security auth not acknowledged (" + address
+ ") — if Android shows a Bluetooth pairing request, accept it");
return false;
}
emitLog("security auth complete: " + address);
return true;
} finally {
synchronized (lock) {
pendingAuthMagic = -1;
authLatch = null;
}
}
}
@@ -497,8 +523,25 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
@Override
public void onNotification(String address, String characteristicUuid, byte[] data) {
if (BleProtocol.NOTIFY_CHAR_UUID.equalsIgnoreCase(characteristicUuid)) {
// Control channel: only the security-auth response is awaited here.
// A value can carry several envelope frames back to back (e.g. the
// response packed with one of the lens's own sid-0x80 notifies).
for (byte[] buf : BleProtocol.splitFrames(data)) {
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(buf);
if (frame.ok && frame.sid == BleProtocol.SID_SECURITY_AUTH) {
synchronized (lock) {
if (authLatch != null && frame.msgSeq == pendingAuthMagic) {
authAckPb = frame.pb;
authLatch.countDown();
}
}
}
}
return;
}
if (!BleProtocol.OTA_DATA_NOTIFY_UUID.equalsIgnoreCase(characteristicUuid)) {
return; // acks arrive on the data-notify char; ignore heartbeat responses
return; // OTA acks arrive on the data-notify char
}
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data);
if (!frame.ok || frame.pb.length < 2) {
@@ -517,7 +560,6 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
// ---- helpers -------------------------------------------------------------
private void teardown() {
stopHeartbeat();
try {
bleManager.close();
} catch (Exception ignored) {
@@ -621,11 +663,12 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
});
}
private void emitProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount) {
private void emitProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount,
long bytesSent, long bytesTotal) {
mainHandler.post(() -> {
FaceclawFirmwareFlasherListener current = listener;
if (current != null) {
current.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount);
current.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount, bytesSent, bytesTotal);
}
});
}
@@ -6,9 +6,12 @@ public interface FaceclawFirmwareFlasherListener {
/**
* Fine-grained progress for the UI bar. `lens` is "left"/"right";
* component/block indices are 1-based against their counts.
* component/block indices are 1-based against their counts. `bytesSent` /
* `bytesTotal` cover the whole lens image, so a bar driven by them moves
* evenly even though the components differ wildly in size.
*/
void onProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount);
void onProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount,
long bytesSent, long bytesTotal);
/**
* Coarse lifecycle. `state` is one of: validating, connecting, flashing,
@@ -11,24 +11,32 @@ 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).
* ~4 MB firmware image (and with no overload ambiguity). Also home of the one
* shared byte→hex encoder for com.faceclaw.app.
*/
public final class FaceclawFirmwareUtil {
private FaceclawFirmwareUtil() {}
/** Lowercase hex of the bytes. The TS-side decoder is case-insensitive. */
public static String bytesToHex(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
int v = b & 0xff;
sb.append(Character.forDigit(v >>> 4, 16));
sb.append(Character.forDigit(v & 0x0f, 16));
}
return sb.toString();
}
/** 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();
return bytesToHex(md.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256 unavailable", e);
}
@@ -50,6 +50,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
private final Object lock = new Object();
private final ConcurrentHashMap<String, CountDownLatch> pendingAcks = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, byte[]> ackPayloads = new ConcurrentHashMap<>();
private final CountDownLatch selectionLatch = new CountDownLatch(1);
private volatile FaceclawFlashPromptListener listener;
@@ -197,38 +198,71 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
}
private void bringUpArm(String address) throws InterruptedException {
// 1. Mandatory session prelude on sid=0x01 (app-launch).
if (!writeAndAwaitAck(
// 1. Security-auth exchange on sid=0x80: firmware 2.2.9 will not run a
// session (and closes the link after ~30 s) without it, and on an
// unbonded phone this is what triggers SMP pairing, so it may sit
// waiting on an OS pairing prompt.
int authMagic = allocMagic();
byte[] authAck = writeAndAwaitAck(
address,
BleProtocol.SID_SECURITY_AUTH,
BleProtocol.FLAG_SECURITY_AUTH,
authMagic,
BleProtocol.buildAuthenticationRequest(authMagic),
ConnectionOptions.SECURITY_AUTH_TIMEOUT_MS);
if (authAck == null || !BleProtocol.isAuthenticationSuccess(authAck, authMagic)) {
throw new IllegalStateException(
"could not authenticate with the glasses (" + address
+ ") — if Android shows a Bluetooth pairing request, accept it and try again");
}
// 2. 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)) {
ConnectionOptions.PRELUDE_TIMEOUT_MS) == null) {
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)) {
// 3. Create the prompt page (warning text + No/Yes list) on sid=0xe0 Cmd=0.
// Two attempts: on 2.2.9 the first request sent right after the
// prelude can be dropped while the lens emits its own sid-0x80
// notifications (observed with the device-info settings read).
byte[] pageAck = null;
for (int attempt = 0; attempt < 2 && pageAck == null && !cancelled; attempt++) {
int magic = allocMagic();
byte[] page = BleProtocol.buildCreatePromptPage(
magic, TEXT_NAME, TEXT_CONTAINER_ID, warningText, LIST_NAME, LIST_CONTAINER_ID, ITEMS);
pageAck = writeAndAwaitAck(address, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, magic, page, CREATE_ACK_TIMEOUT_MS);
if (pageAck == null) {
emitLog("prompt page attempt " + (attempt + 1) + " unacked: " + address);
}
}
if (pageAck == null) {
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)
/** Write and wait for the matching ack; returns the ack's protobuf (may be empty), or null on timeout/write failure. */
private byte[] 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 null;
}
return latch.await(timeoutMs, TimeUnit.MILLISECONDS);
if (!latch.await(timeoutMs, TimeUnit.MILLISECONDS)) {
return null;
}
byte[] pb = ackPayloads.get(key);
return pb == null ? new byte[0] : pb;
} finally {
pendingAcks.remove(key, latch);
ackPayloads.remove(key);
}
}
@@ -309,7 +343,14 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
if (!BleProtocol.NOTIFY_CHAR_UUID.equalsIgnoreCase(characteristicUuid)) {
return;
}
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data);
// A value can carry several envelope frames back to back.
for (byte[] buf : BleProtocol.splitFrames(data)) {
handleFrame(address, buf);
}
}
private void handleFrame(String address, byte[] buf) {
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(buf);
if (!frame.ok) {
return;
}
@@ -321,8 +362,10 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
return;
}
if (frame.msgSeq >= 0) {
CountDownLatch latch = pendingAcks.get(ackKey(frame.sid, frame.msgSeq));
String key = ackKey(frame.sid, frame.msgSeq);
CountDownLatch latch = pendingAcks.get(key);
if (latch != null) {
ackPayloads.put(key, frame.pb);
latch.countDown();
}
}
@@ -144,7 +144,7 @@ public class FaceclawModelDownloader {
+ expectedTotalBytes + " bytes); try again to resume");
return;
}
String actualSha = toHex(digest.digest());
String actualSha = FaceclawFirmwareUtil.bytesToHex(digest.digest());
if (!expectedSha256.isEmpty() && !actualSha.equals(expectedSha256)) {
partFile.delete();
postError("Model download was corrupted (checksum mismatch); download it again");
@@ -177,12 +177,6 @@ public class FaceclawModelDownloader {
return hashed;
}
private static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) sb.append(String.format("%02x", b));
return sb.toString();
}
private void post(Runnable runnable) {
callbackHandler.post(runnable);
}
@@ -28,6 +28,16 @@ public class BleProtocol {
public static final int PRELUDE_ACK_SID = 0x01;
public static final int PRELUDE_ACK_MAGIC = 156;
/**
* DEVICE_SETTINGS security-auth channel. Firmware 2.2.9 enforces completing
* this exchange shortly after a GATT connection opens (a ~30 s deadline
* closes unauthenticated links) and gates query responses on it; the
* message itself exists back to the 2.2.4 era, so sending it is safe on all
* stock versions. See ../notes/ble-connections-2.2.9.md.
*/
public static final int SID_SECURITY_AUTH = 0x80;
public static final int FLAG_SECURITY_AUTH = 0x00;
private static final int SECURITY_AUTH_CMD = 4;
public static final int SID_APP_LAUNCH = 0x01;
public static final int SID_EVENHUB = 0xe0;
public static final int SID_UI_SETTING = 0x09;
@@ -323,6 +333,48 @@ public class BleProtocol {
));
}
/**
* The application authentication request: DEVICE_SETTINGS/AUTHENTICATION(4)
* on sid 0x80, flag 0x00. Carries no key material — it arms the firmware's
* "security auth" flag; the firmware sends the success notification once
* the flag is set AND the BLE link is encrypted (SMP pairing/bond
* restoration, handled by the OS below GATT, possibly after a pairing
* prompt). Protobuf: f1=4 (command), f2=magic, f3={f1=1, f2=4}.
*/
public static byte[] buildAuthenticationRequest(int magic) {
byte[] auth = concat(CollectionUtils.listOf(
encodeVarintField(1, 1),
encodeVarintField(2, SECURITY_AUTH_CMD)
));
return concat(CollectionUtils.listOf(
encodeVarintField(1, SECURITY_AUTH_CMD),
encodeVarintField(2, magic),
encodeMessageField(3, auth)
));
}
/**
* True when `pb` (trailing CRC still attached) is the success notification
* for the authentication request sent with `magic`: command 4, the same
* magic, and an EMPTY field-3 result message (`1a 00` — the omitted result
* code defaults to zero). A GATT write completing is NOT success; only this
* notification is.
*/
public static boolean isAuthenticationSuccess(byte[] pb, int magic) {
if (pb == null) {
return false;
}
byte[] root = stripTrailingCrc(pb);
if (readVarintFieldValue(root, 1, -1) != SECURITY_AUTH_CMD) {
return false;
}
if (readVarintFieldValue(root, 2, -1) != magic) {
return false;
}
byte[] result = readFieldBytes(root, 3);
return result != null && result.length == 0;
}
public static byte[] buildSettingsQuery(int magic) {
byte[] request = encodeVarintField(1, 1);
return concat(CollectionUtils.listOf(
@@ -552,6 +604,35 @@ public class BleProtocol {
}
/**
* Split one notification value into individual `aa21`/`aa12` envelope
* frames. A value normally holds exactly one frame, but the firmware can
* pack several (each self-describing via the length byte at offset 3), and
* a frame that only reads the first would silently drop the rest. A value
* that does not start with an envelope, or a trailing partial frame
* (truncated by the stack — observed on a Samsung tablet for values over
* 64 bytes), is returned as-is so the caller can log it.
*/
public static List<byte[]> splitFrames(byte[] value) {
List<byte[]> out = new ArrayList<>();
if (value == null || value.length == 0) {
return out;
}
int offset = 0;
while (offset + 8 <= value.length
&& value[offset] == (byte) 0xaa
&& (value[offset + 1] == 0x21 || value[offset + 1] == 0x12)) {
int len = value[offset + 3] & 0xff;
int end = Math.min(value.length, offset + 8 + len);
out.add(Arrays.copyOfRange(value, offset, end));
offset = end;
}
if (offset < value.length) {
out.add(Arrays.copyOfRange(value, offset, value.length));
}
return out;
}
public static ParsedFrame parseFrame(byte[] buf) {
if (buf == null || buf.length < 10 || buf[0] != (byte) 0xaa || (buf[1] != 0x21 && buf[1] != 0x12)) {
return new ParsedFrame(false, 0, 0, new byte[0], -1, -1);
@@ -12,6 +12,14 @@ public class ConnectionOptions {
public static final int RING_RECONNECT_DELAY_MS = 2_000;
public static final int WRITE_TIMEOUT_MS = 2_000;
public static final int PRELUDE_TIMEOUT_MS = 2_000;
// Application security-auth exchange (sid 0x80). The success notification
// only arrives once the BLE link is encrypted, which on a first-time
// connection means SMP pairing — possibly with an OS dialog the user has
// to accept — so the stock-firmware paths wait generously.
public static final int SECURITY_AUTH_TIMEOUT_MS = 30_000;
// The main communicator's wait is soft (it proceeds on timeout so firmware
// that never answers can't stall every reconnect), so it is kept short.
public static final int SECURITY_AUTH_SOFT_TIMEOUT_MS = 6_000;
public static final int ACK_TIMEOUT_MS = 3_500;
public static final int HEARTBEAT_FAILURE_DEADLINE_MS = 10_000;
public static final int HEARTBEAT_READY_MS = 4_000;
@@ -23,6 +23,22 @@ public class MessageBuilder {
);
}
/** The per-connection sid-0x80 security-auth request (one per arm). */
public OutboundMessage securityAuth(boolean leftArm) {
int magic = magicPool.allocate();
return new OutboundMessage(
"security-auth",
"security auth " + (leftArm ? "L" : "R"),
BleProtocol.SID_SECURITY_AUTH,
BleProtocol.FLAG_SECURITY_AUTH,
magic,
BleProtocol.buildAuthenticationRequest(magic),
ConnectionOptions.SECURITY_AUTH_SOFT_TIMEOUT_MS,
-1,
leftArm
);
}
public OutboundMessage shutdown(int exitMode) {
int magic = magicPool.allocate();
return new OutboundMessage(