mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Implement the 2.2.9 security-auth exchange on every stock-facing BLE connection
Firmware 2.2.9 requires the sid-0x80 DEVICE_SETTINGS/AUTHENTICATION(4) exchange shortly after each GATT connection: it gates query responses on completing it over an encrypted link, and closes unauthenticated links after ~30 s. On a phone with no existing bond (no inherited stock-app pairing) the exchange is also what triggers SMP pairing. This is why the onboarding firmware check failed with "no response to the device-info query" on a fresh device: the probe connected, the prelude was acked, but the settings query was never answered and no pairing ever happened. (See ../notes/ble-connections-2.2.9.md, validated by g2flash on hardware.) - BleProtocol: buildAuthenticationRequest / isAuthenticationSuccess (strict: command 4, matching magic, empty result message), SID_SECURITY_AUTH. - Device-info probe: authenticates before the prelude with a 30 s window (the user may need to accept an OS pairing prompt; the check page says so). Soft on non-response since the probe also runs against the custom firmware — but a query timeout after unconfirmed auth now names the pairing problem. - Flash-prompt communicator: authenticates each arm before the prelude (mandatory — it only ever talks to stock firmware). - Firmware flasher: control-channel notifications are now mandatory, each lens authenticates before OTA BEGIN, and the OTA-time heartbeat is gone — official captures show no control traffic during a transfer, heartbeats demonstrably do not satisfy the 2.2.9 deadline, and a concurrent control writer interleaves with the marker/data transactions. The OTA envelope counter now resets after bring-up, mirroring the stock sequence. - Main communicator: authenticates both arms after connecting, before the prelude, with a short soft wait (logs and continues on timeout so firmware that never answers cannot stall reconnects). Hardware test pending: fresh-device onboarding against stock 2.2.9 (check, prompt, flash), and a regression pass on custom-firmware connect + probe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016ZqzwmRQ3HQxasBz5rYyZV
This commit is contained in:
1 parent
17182532f4
commit
1bde70aa45
9 files changed
+281
-74
No files matched your search
@@ -1384,6 +1384,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
if (!sleepDuringConnectSettling(800)) {
|
||||
return;
|
||||
}
|
||||
authenticateArms();
|
||||
sendPrelude();
|
||||
|
||||
synchronized (lock) {
|
||||
@@ -1559,6 +1560,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);
|
||||
}
|
||||
|
||||
@@ -90,6 +90,20 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 to the query and only enriches its error.
|
||||
emitState("authenticating", "");
|
||||
boolean authenticated = authenticate(rightAddress);
|
||||
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).
|
||||
@@ -103,7 +117,10 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
|
||||
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(authenticated
|
||||
? "no response to the device-info query"
|
||||
: "no response to the device-info query — authentication with the glasses did not complete;"
|
||||
+ " if Android shows a Bluetooth pairing request, accept it and try again");
|
||||
}
|
||||
|
||||
BleProtocol.FirmwareInfo info = BleProtocol.parseSettingsFirmwareInfo(ack);
|
||||
@@ -123,6 +140,15 @@ public class FaceclawDeviceInfoProbe implements FaceclawBleListener {
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
|
||||
@@ -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,24 @@ 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");
|
||||
}
|
||||
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);
|
||||
}
|
||||
emitLog(lens + " lens: all components verified");
|
||||
try {
|
||||
@@ -356,50 +356,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 +511,21 @@ 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.
|
||||
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data);
|
||||
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 +544,6 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener {
|
||||
// ---- helpers -------------------------------------------------------------
|
||||
|
||||
private void teardown() {
|
||||
stopHeartbeat();
|
||||
try {
|
||||
bleManager.close();
|
||||
} catch (Exception ignored) {
|
||||
|
||||
+35
-9
@@ -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,61 @@ 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.
|
||||
// 3. 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)) {
|
||||
if (writeAndAwaitAck(address, BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, magic, page, CREATE_ACK_TIMEOUT_MS) == 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,8 +345,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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -8,7 +8,7 @@ export type DeviceInfo = {
|
||||
capabilities: string;
|
||||
};
|
||||
|
||||
export type DeviceInfoState = "connecting" | "querying";
|
||||
export type DeviceInfoState = "connecting" | "authenticating" | "querying";
|
||||
|
||||
/**
|
||||
* TS wrapper around the native FaceclawDeviceInfoProbe — a one-shot,
|
||||
|
||||
@@ -163,6 +163,9 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
|
||||
private reportProbeState(state: DeviceInfoState): void {
|
||||
if (state === "connecting") {
|
||||
this.status = "Connecting to your glasses...";
|
||||
} else if (state === "authenticating") {
|
||||
// First-time connections pair here; the OS may show a Bluetooth dialog.
|
||||
this.status = "Authenticating with your glasses... If Android asks to pair, tap Pair.";
|
||||
} else if (state === "querying") {
|
||||
this.status = "Reading the firmware version...";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user