diff --git a/.gitignore b/.gitignore index b7c078e4..dc56b331 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,9 @@ npm-debug.log* yarn-debug.log* yarn-error.log* +# npm test compile output (tests/tsconfig.json outDir) +.test-build/ + # General .DS_Store .AppleDouble diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java index 9f6a806d..98074d90 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java @@ -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); } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceDiscovery.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceDiscovery.java index 0452bbda..39223a64 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceDiscovery.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceDiscovery.java @@ -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: diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbe.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbe.java index f89fa8b0..f5c0f51c 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbe.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceInfoProbe.java @@ -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 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 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 } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java index 455d5bff..84d66a4f 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java @@ -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 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); } }); } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java index a111c174..2cd24e20 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasherListener.java @@ -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, diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java index 31a43576..32ce5dc1 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareUtil.java @@ -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); } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java index 16454990..6aba3b3d 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java @@ -50,6 +50,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private final Object lock = new Object(); private final ConcurrentHashMap pendingAcks = new ConcurrentHashMap<>(); + private final ConcurrentHashMap 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(); } } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java index 02f50bb5..c1764d6e 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java @@ -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); } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java index 91c89e73..f1efc7f1 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java @@ -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 splitFrames(byte[] value) { + List 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); diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/ConnectionOptions.java b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/ConnectionOptions.java index 6656f9a6..a358dba9 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/ConnectionOptions.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/ConnectionOptions.java @@ -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; diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/MessageBuilder.java b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/MessageBuilder.java index 14ed0271..eb31a930 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/MessageBuilder.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/MessageBuilder.java @@ -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( diff --git a/App_Resources/Android/src/main/res/drawable-hdpi/background.png b/App_Resources/Android/src/main/res/drawable-hdpi/background.png deleted file mode 100644 index bbefbf42..00000000 Binary files a/App_Resources/Android/src/main/res/drawable-hdpi/background.png and /dev/null differ diff --git a/App_Resources/Android/src/main/res/drawable-hdpi/logo.png b/App_Resources/Android/src/main/res/drawable-hdpi/logo.png index e788deb3..9a212517 100644 Binary files a/App_Resources/Android/src/main/res/drawable-hdpi/logo.png and b/App_Resources/Android/src/main/res/drawable-hdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-ldpi/background.png b/App_Resources/Android/src/main/res/drawable-ldpi/background.png deleted file mode 100644 index f6a08eea..00000000 Binary files a/App_Resources/Android/src/main/res/drawable-ldpi/background.png and /dev/null differ diff --git a/App_Resources/Android/src/main/res/drawable-ldpi/logo.png b/App_Resources/Android/src/main/res/drawable-ldpi/logo.png index e4cac1ad..10758abe 100644 Binary files a/App_Resources/Android/src/main/res/drawable-ldpi/logo.png and b/App_Resources/Android/src/main/res/drawable-ldpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-mdpi/background.png b/App_Resources/Android/src/main/res/drawable-mdpi/background.png deleted file mode 100644 index 0c90f0f7..00000000 Binary files a/App_Resources/Android/src/main/res/drawable-mdpi/background.png and /dev/null differ diff --git a/App_Resources/Android/src/main/res/drawable-mdpi/logo.png b/App_Resources/Android/src/main/res/drawable-mdpi/logo.png index ce3c3a4b..0f4c7204 100644 Binary files a/App_Resources/Android/src/main/res/drawable-mdpi/logo.png and b/App_Resources/Android/src/main/res/drawable-mdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml b/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml index ada77f92..a0acfca1 100644 --- a/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml +++ b/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml @@ -1,8 +1,8 @@ - + - \ No newline at end of file + diff --git a/App_Resources/Android/src/main/res/drawable-xhdpi/background.png b/App_Resources/Android/src/main/res/drawable-xhdpi/background.png deleted file mode 100644 index 3541570c..00000000 Binary files a/App_Resources/Android/src/main/res/drawable-xhdpi/background.png and /dev/null differ diff --git a/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png b/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png index 88267df0..a44364f4 100644 Binary files a/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png and b/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png b/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png deleted file mode 100644 index abb0fc70..00000000 Binary files a/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png and /dev/null differ diff --git a/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png b/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png index 55800c9a..32c4f53f 100644 Binary files a/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png and b/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png b/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png deleted file mode 100644 index 10897752..00000000 Binary files a/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png and /dev/null differ diff --git a/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png b/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png index 0703f90f..bdf0bb04 100644 Binary files a/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png and b/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png differ diff --git a/app/app.css b/app/app.css index dedf8160..673fc5bb 100644 --- a/app/app.css +++ b/app/app.css @@ -20,6 +20,15 @@ TextField { color: #222222; } +/* Without this, the theme's .ns-dark rules recolour the text white while the + * white background above sticks, rendering white-on-white fields. + * Order matters: .system-name-modal TextField must stay after this rule so the + * deliberately light modal wins the equal-specificity tie in dark mode. */ +.ns-dark TextField { + background-color: #2e2e2e; + color: #f0f0f0; +} + .system-name-modal TextField { background-color: #ffffff; color: #222222; @@ -29,6 +38,18 @@ Button.-primary { font-size: 18; } +/* Body/explanatory text in the onboarding flow; the theme default is too + * small to comfortably read paragraphs of legalese, especially on tablets. */ +.body-text { + font-size: 18; +} + +/* The logo art is black-on-transparent; tint it light in dark mode so it + * doesn't vanish into the dark page background. */ +.ns-dark .onboarding-logo { + tint-color: #e6e6e6; +} + /* * Stands in for the lens preview when showing it would be misleading (silent * mode, or a disconnect explained by a flat battery). Sized by the view model @@ -109,6 +130,7 @@ Button.-primary { .pairing-title { font-size: 16; font-weight: bold; + color: #222222; } .pairing-badge { @@ -170,15 +192,88 @@ Button.-primary { padding: 10; } -.pairing-diagnostics { - font-size: 11; - color: #888888; - font-family: monospace; -} - Button.pairing-link { background-color: transparent; color: #2a5bc4; font-size: 14; border-width: 0; } + +/* + * Dark-mode pairing page. The cards keep their light-mode look above; here + * they go dark-gray, and every text colour set above gets a light counterpart + * so nothing renders dark-on-dark (the instructions) or dark-on-a-dark-card. + * Order matters: the -selected/-incomplete rules must follow .pairing-row so + * they win at equal specificity. + */ +.ns-dark .pairing-instructions { + color: #b0b0b0; +} + +.ns-dark .pairing-empty { + color: #999999; +} + +.ns-dark .pairing-row { + background-color: #2e2e2e; + border-color: #4a4a4a; +} + +.ns-dark .pairing-row-selected { + background-color: #333c4c; + border-color: #5b8def; +} + +.ns-dark .pairing-row-incomplete { + background-color: #282828; + border-color: #3c3c3c; +} + +.ns-dark .pairing-title { + color: #f0f0f0; +} + +.ns-dark .pairing-badge { + color: #a8c4f5; + background-color: #2a3b5e; +} + +.ns-dark .pairing-variant { + color: #cccccc; +} + +.ns-dark .pairing-proximity { + color: #a0a0a0; +} + +.ns-dark .pairing-proximity-immediate { + color: #7da7f5; +} + +.ns-dark .pairing-serial { + color: #a0a0a0; +} + +.ns-dark .pairing-arms { + color: #c0c0c0; +} + +.ns-dark .pairing-warning { + color: #e08a66; +} + +.ns-dark .pairing-swatch-label { + color: #aaaaaa; +} + +.ns-dark .pairing-chevron { + color: #bbbbbb; +} + +.ns-dark .pairing-selection { + background-color: #2e2e2e; +} + +.ns-dark Button.pairing-link { + color: #7da7f5; +} diff --git a/app/g2/ble-proximity.ts b/app/g2/ble-proximity.ts index 48e5d3dd..4ca475a6 100644 --- a/app/g2/ble-proximity.ts +++ b/app/g2/ble-proximity.ts @@ -13,8 +13,11 @@ * * `txPower` is the expected signal at one metre and `n` the path loss * exponent — 2.0 in free space, higher indoors where walls and bodies absorb. - * A device that advertises its own TX power gets used as measured; everything - * else falls back to a per-product calibration. + * The reference power always comes from the per-product calibration table. An + * advertised BLE "TX Power Level" is deliberately NOT used: that field is the + * radiated power at the antenna (typically 0…+4 dBm), not an iBeacon-style + * measured power at one metre, and reading it as the latter inflates every + * distance by orders of magnitude. * * ## What this is for, and what it is not * @@ -25,14 +28,15 @@ * absolute numbers metres out. * * It is **not** a measurement. A hand over the temple, a pocket, or a body - * between phone and glasses moves the estimate by metres. Every user-facing - * number is therefore rounded hard, prefixed with "~" when confidence is low, - * and paired with a coarse zone rather than being presented as a distance the - * wearer could act on precisely. + * between phone and glasses moves the estimate by metres. The wearer therefore + * only ever sees a coarse zone (glyph + label), never a number in metres they + * might over-trust; the metres value exists purely to rank and bucket. * * This module is pure (no NativeScript imports) so it can run under node tests. */ +import { clamp } from "../util/numeric-util"; + /** Expected RSSI at one metre, and the path loss exponent, per product. */ export type ProximityCalibration = { readonly txPowerAtOneMeter: number; @@ -66,8 +70,6 @@ export const MAXIMUM_METERS = 100; */ export type ProximityZone = "immediate" | "near" | "far" | "distant"; -const ZONE_ORDER: Record = { immediate: 0, near: 1, far: 2, distant: 3 }; - export function zoneFromMeters(meters: number): ProximityZone { if (meters < 0.5) return "immediate"; if (meters < 3) return "near"; @@ -75,10 +77,6 @@ export function zoneFromMeters(meters: number): ProximityZone { return "distant"; } -export function zoneRank(zone: ProximityZone): number { - return ZONE_ORDER[zone]; -} - export function zoneLabel(zone: ProximityZone): string { switch (zone) { case "immediate": @@ -109,64 +107,37 @@ export function zoneGlyph(zone: ProximityZone): string { /** A distance estimate and how much to trust it. */ export type ProximityEstimate = { readonly meters: number; - /** 0…1. Drops with weak signal and with having to guess the TX power. */ + /** 0…1. Drops with weak signal. */ readonly confidence: number; readonly zone: ProximityZone; }; -/** "0.4 m", "~3 m". The tilde marks an estimate the reader should not lean on. */ -export function formatDistance(estimate: ProximityEstimate): string { - const prefix = estimate.confidence < 0.6 ? "~" : ""; - const meters = estimate.meters; - if (meters < 1) { - return `${prefix}${Math.round(meters * 100)} cm`; - } - if (meters < 10) { - return `${prefix}${meters.toFixed(1)} m`; - } - if (meters < MAXIMUM_METERS) { - return `${prefix}${Math.round(meters)} m`; - } - return `${prefix}>${MAXIMUM_METERS} m`; -} - -/** "In your hand · 0.3 m" — zone first, because the zone is the trustworthy half. */ -export function proximitySummary(estimate: ProximityEstimate): string { - return `${zoneLabel(estimate.zone)} · ${formatDistance(estimate)}`; -} - /** * Estimate distance from a signal sample. Null when there is no RSSI to work * from, so callers can say "signal unknown" rather than render a fabricated * distance. 127 is the Bluetooth "RSSI unavailable" sentinel. */ -export function estimateProximity( - rssi: number | null | undefined, - txPower: number | null | undefined, - calibration: ProximityCalibration, -): ProximityEstimate | null { +export function estimateProximity(rssi: number | null | undefined, calibration: ProximityCalibration): ProximityEstimate | null { if (rssi == null || !Number.isFinite(rssi) || rssi === 127) return null; - const hasTxPower = txPower != null && Number.isFinite(txPower); - const referencePower = hasTxPower ? txPower! : calibration.txPowerAtOneMeter; - const ratio = (referencePower - rssi) / (10 * calibration.pathLossExponent); - const meters = Math.min(Math.max(Math.pow(10, ratio), MINIMUM_METERS), MAXIMUM_METERS); + const ratio = (calibration.txPowerAtOneMeter - rssi) / (10 * calibration.pathLossExponent); + const meters = clamp(Math.pow(10, ratio), MINIMUM_METERS, MAXIMUM_METERS); return { meters, - confidence: proximityConfidence(rssi, hasTxPower), + confidence: proximityConfidence(rssi), zone: zoneFromMeters(meters), }; } /** - * Confidence falls with signal strength, because a weak sample is a noisy one, - * and with having to assume the TX power instead of being told it. + * Confidence falls with signal strength, because a weak sample is a noisy one. + * The 0.85 ceiling reflects that the TX power is always an assumption from the + * calibration table, never a measurement. */ -export function proximityConfidence(rssi: number, hasAdvertisedTxPower: boolean): number { - let confidence = 1.0; +export function proximityConfidence(rssi: number): number { + let confidence = 0.85; if (rssi < -85) confidence *= 0.4; else if (rssi < -75) confidence *= 0.7; else if (rssi < -65) confidence *= 0.85; - confidence *= hasAdvertisedTxPower ? 1.0 : 0.85; return confidence; } diff --git a/app/g2/device-addresses.ts b/app/g2/device-addresses.ts index 90277ddb..b69a67bc 100644 --- a/app/g2/device-addresses.ts +++ b/app/g2/device-addresses.ts @@ -1,5 +1,9 @@ import { ApplicationSettings } from "@nativescript/core"; +import { normalizeMacAddress } from "./even-advertisement"; + +export { normalizeMacAddress }; + export type DeviceAddresses = { right: string; left: string; @@ -32,17 +36,6 @@ export function saveDeviceAddresses(addresses: DeviceAddresses): void { ApplicationSettings.setString(ADDRESS_KEYS.ring, normalizeMacAddress(addresses.ring)); } -export function normalizeMacAddress(value: string | null | undefined): string { - const compact = (value ?? "") - .trim() - .replace(/[^0-9a-fA-F]/g, "") - .toUpperCase(); - if (compact.length !== 12) { - return (value ?? "").trim().toUpperCase(); - } - return compact.match(/.{1,2}/g)?.join(":") ?? compact; -} - export function isValidMacAddress(value: string, allowEmpty = false): boolean { const trimmed = value.trim(); if (!trimmed) { diff --git a/app/g2/even-advertisement.ts b/app/g2/even-advertisement.ts index 0e9b1360..1f4ef724 100644 --- a/app/g2/even-advertisement.ts +++ b/app/g2/even-advertisement.ts @@ -27,28 +27,15 @@ * This module is pure (no NativeScript imports) so it can run under node tests. */ +import { bytesToHex, hexToBytes } from "../util/hex-util"; + +export { bytesToHex, hexToBytes }; + /** Even Realities' manufacturer-data company identifier (`"ER"` read little-endian). */ export const EVEN_COMPANY_IDENTIFIER = 0x5245; export type EvenDeviceRole = "left" | "right" | "ring"; -export function hexToBytes(hex: string | null | undefined): Uint8Array { - const clean = (hex ?? "").replace(/[^0-9a-fA-F]/g, ""); - const out = new Uint8Array(Math.floor(clean.length / 2)); - for (let i = 0; i < out.length; i++) { - out[i] = parseInt(clean.substr(i * 2, 2), 16); - } - return out; -} - -export function bytesToHex(bytes: ArrayLike): string { - let out = ""; - for (let i = 0; i < bytes.length; i++) { - out += (bytes[i]! & 0xff).toString(16).padStart(2, "0").toUpperCase(); - } - return out; -} - /** True when the manufacturer data opens with Even's `"ER"` marker. */ export function hasEvenManufacturerSignature(mfg: Uint8Array): boolean { return mfg.length >= 2 && mfg[0] === 0x45 && mfg[1] === 0x52; @@ -136,7 +123,7 @@ export function ringNameAddressOctets(name: string | null | undefined): number[] const marker = name.indexOf("R1_"); const suffix = (marker >= 0 ? name.slice(marker + 3) : name).trim(); if (suffix.length !== 6 || !/^[0-9a-fA-F]{6}$/.test(suffix)) return null; - return [0, 2, 4].map((i) => parseInt(suffix.substr(i, 2), 16)); + return [0, 2, 4].map((i) => parseInt(suffix.slice(i, i + 2), 16)); } /** @@ -233,20 +220,25 @@ export type EvenAdvertisement = { * Classify a raw advertisement. Returns null for anything that is not an Even * Realities G2 temple or R1 ring. Admission mirrors the SDK: stock names * contain "G2"/"R1", but renamed firmware may not, so the "ER" manufacturer - * signature is an equally strong admission path. + * signature is an equally strong admission path. The ring check is anchored to + * the stock "EVEN R1…" prefix — a bare `R1` substring also matches unrelated + * hardware ("Oppo Enco R1"), and every ring row is selectable, so a loose + * match here saves a stranger's earbuds as the ring. Keep this in sync with + * the Java pre-filter (FaceclawDeviceDiscovery.isAdmissible), which must stay + * a superset of it. */ export function classifyAdvertisement(raw: RawAdvertisement): EvenAdvertisement | null { const mfg = hexToBytes(raw.manufacturerData); const name = raw.name ?? ""; const upper = name.toUpperCase(); const hasSignature = hasEvenManufacturerSignature(mfg); - const looksLikeRing = /\bR1\b|EVEN R1|R1_/.test(upper); + const looksLikeRing = /^EVEN R1([_ ]|$)/.test(upper); const looksLikeG2 = upper.includes("G2"); if (!looksLikeRing && !looksLikeG2 && !hasSignature) return null; const base = { - address: normalizeAddress(raw.address), + address: normalizeMacAddress(raw.address), name, rssi: raw.rssi, txPower: raw.txPower, @@ -295,8 +287,19 @@ export function classifyAdvertisement(raw: RawAdvertisement): EvenAdvertisement }; } -export function normalizeAddress(value: string | null | undefined): string { - const compact = (value ?? "").replace(/[^0-9a-fA-F]/g, "").toUpperCase(); +/** + * Canonical MAC form: uppercase, colon-separated. Anything that does not + * contain exactly 12 hex digits is passed through trimmed and uppercased so + * an obviously-wrong value stays visible instead of being silently mangled. + * The single normalizer for every address comparison in the app — the stored + * side (device-addresses.ts re-exports this) and the scanned side must agree + * byte for byte or "is this the previously-paired device" checks break. + */ +export function normalizeMacAddress(value: string | null | undefined): string { + const compact = (value ?? "") + .trim() + .replace(/[^0-9a-fA-F]/g, "") + .toUpperCase(); if (compact.length !== 12) return (value ?? "").trim().toUpperCase(); return compact.match(/.{2}/g)!.join(":"); } diff --git a/app/g2/firmware-builder.ts b/app/g2/firmware-builder.ts index 01efe859..8465e59e 100644 --- a/app/g2/firmware-builder.ts +++ b/app/g2/firmware-builder.ts @@ -19,6 +19,7 @@ import { isEvenHubFontAsset, } from "./firmware-fonts"; import { fetchWithUserAgent } from "../util/http"; +import { bytesToHex, hexToBytes as hexToBytesLenient } from "../util/hex-util"; declare const com: any; @@ -237,23 +238,12 @@ function applyPatches( return buf; } +/** Patch-op hex is data, not user input: reject malformed strings instead of the shared decoder's silent stripping. */ function hexToBytes(hex: string): Uint8Array { - if (hex.length % 2 !== 0) { - throw new FirmwareBuildError(`odd-length hex string: ${hex}`); + if (hex.length % 2 !== 0 || /[^0-9a-fA-F]/.test(hex)) { + throw new FirmwareBuildError(`invalid hex string: ${hex}`); } - const out = new Uint8Array(hex.length / 2); - for (let i = 0; i < out.length; i++) { - out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); - } - return out; -} - -function bytesToHex(bytes: Uint8Array): string { - let hex = ""; - for (let i = 0; i < bytes.length; i++) { - hex += bytes[i].toString(16).padStart(2, "0"); - } - return hex; + return hexToBytesLenient(hex); } function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { diff --git a/app/g2/glasses-hardware-identity.ts b/app/g2/glasses-hardware-identity.ts index 291963cd..e178012e 100644 --- a/app/g2/glasses-hardware-identity.ts +++ b/app/g2/glasses-hardware-identity.ts @@ -280,16 +280,32 @@ export type GlassesPairSerialVerdict = | { kind: "unknown" } | { kind: "mismatched"; left: string; right: string }; +/** + * Canonical comparison key for a serial-ish string: the decoded serial when it + * decodes (so an `_L_1` arm suffix or casing difference is not read as + * different hardware), else the trimmed uppercase raw value. Null when empty. + * The single definition of serial equality — pair grouping, the pair check, + * and the "Yours" badge must all agree on it. + */ +export function serialKey(value: string | null | undefined): string | null { + const trimmed = nonEmpty(value); + if (!trimmed) return null; + return GlassesHardwareIdentity.decode(trimmed)?.serial ?? trimmed.toUpperCase(); +} + +/** True when both values carry a serial and the serials name the same hardware. */ +export function serialsMatch(a: string | null | undefined, b: string | null | undefined): boolean { + const keyA = serialKey(a); + const keyB = serialKey(b); + return !!keyA && !!keyB && keyA === keyB; +} + export function evaluatePairSerials(left: string | null | undefined, right: string | null | undefined): GlassesPairSerialVerdict { const l = nonEmpty(left); const r = nonEmpty(right); if (!l || !r) return { kind: "unknown" }; - // Compare on the decoded serial when both decode, so an arm suffix or casing - // difference in the reported string is not read as different hardware. - const leftKey = GlassesHardwareIdentity.decode(l)?.serial ?? l.toUpperCase(); - const rightKey = GlassesHardwareIdentity.decode(r)?.serial ?? r.toUpperCase(); - if (leftKey !== rightKey) return { kind: "mismatched", left: l, right: r }; - return { kind: "matched", serial: leftKey }; + if (!serialsMatch(l, r)) return { kind: "mismatched", left: l, right: r }; + return { kind: "matched", serial: serialKey(l)! }; } /** diff --git a/app/g2/pairing-candidates.ts b/app/g2/pairing-candidates.ts index 0c261f19..ce1f4d7e 100644 --- a/app/g2/pairing-candidates.ts +++ b/app/g2/pairing-candidates.ts @@ -14,14 +14,14 @@ import { estimateProximity, GLASSES_CALIBRATION, - proximitySummary, RING_CALIBRATION, sortedByProximity, zoneGlyph, + zoneLabel, type ProximityEstimate, type ProximityZone, } from "./ble-proximity"; -import { classifyAdvertisement, type EvenAdvertisement, type RawAdvertisement } from "./even-advertisement"; +import { classifyAdvertisement, normalizeMacAddress, type EvenAdvertisement, type RawAdvertisement } from "./even-advertisement"; import { glassesImagePath, R1_IMAGE_PATH } from "./glasses-artwork"; import { colorwayDisplayName, @@ -29,6 +29,8 @@ import { evaluatePairSerials, GlassesHardwareIdentity, pairSerialWarning, + serialKey, + serialsMatch, type GlassesColorway, } from "./glasses-hardware-identity"; @@ -45,9 +47,14 @@ export type GlassesPairCandidate = { completeness: PairCompleteness; /** Strongest smoothed signal across the arms that have one. */ rssi: number | null; - txPower: number | null; proximity: ProximityEstimate | null; lastSeenMs: number; + /** + * Set when this lone arm and a lone arm of the other side carry different + * serials — the mixed-pair situation the serial check exists to name. + * Grouping is by serial, so the mismatch can only show up across groups. + */ + mismatchWarning: string | null; }; export type RingCandidate = { @@ -84,10 +91,24 @@ export class DiscoveryAggregator { /** Feed one raw advertisement. Returns the classified record, or null when ignored. */ ingest(raw: RawAdvertisement): EvenAdvertisement | null { - const classified = classifyAdvertisement(raw); + let classified = classifyAdvertisement(raw); if (!classified) { - if (raw.name) this.rejectedNames.add(raw.name); - return null; + // Android sometimes splits an advertisement across reports — an ADV + // report without the scan response's name, or the reverse. If earlier + // traffic from this address already supplied the missing half, retry + // with it filled in rather than dropping the arm. + const remembered = this.byAddress.get(normalizeMacAddress(raw.address)); + if (remembered) { + classified = classifyAdvertisement({ + ...raw, + name: raw.name || remembered.name, + manufacturerData: raw.manufacturerData || remembered.manufacturerData, + }); + } + if (!classified) { + if (raw.name) this.rejectedNames.add(raw.name); + return null; + } } const previous = this.byAddress.get(classified.address); let smoothedRssi: number | null = classified.rssi; @@ -109,6 +130,19 @@ export class DiscoveryAggregator { seenAtMs: Math.max(classified.seenAtMs, previous?.seenAtMs ?? 0), smoothedRssi, }; + if (previous && !classified.manufacturerData && previous.manufacturerData) { + // A record without manufacturer data (a bonded listing, or a split + // report) parses to "serial unknown" notes and a possibly stale cached + // name; those must not overwrite what a fuller advertisement already + // established, or the row shows a serial and claims it is unknown. + merged.note = previous.note; + merged.flag = previous.flag; + merged.embeddedMacMismatch = previous.embeddedMacMismatch; + merged.ringSerialSuffix = previous.ringSerialSuffix; + if (previous.name && (!classified.name || classified.source === "paired")) { + merged.name = previous.name; + } + } this.byAddress.set(merged.address, merged); return merged; } @@ -144,7 +178,8 @@ export class DiscoveryAggregator { const groups = new Map(); for (const record of this.byAddress.values()) { if (record.role === "ring") continue; - const key = record.serial ? `serial:${record.serial}` : `arm:${record.address}`; + const canonical = serialKey(record.serial); + const key = canonical ? `serial:${canonical}` : `arm:${record.address}`; const group = groups.get(key) ?? { left: null, right: null }; const slot = record.role === "left" ? "left" : "right"; const incumbent = group[slot]; @@ -162,20 +197,31 @@ export class DiscoveryAggregator { const samples = [left, right].filter((arm): arm is NonNullable => !!arm && arm.smoothedRssi != null); const strongest = samples.length ? samples.reduce((a, b) => (a.smoothedRssi! >= b.smoothedRssi! ? a : b)) : null; const rssi = strongest ? Math.round(strongest.smoothedRssi!) : null; - const txPower = strongest?.txPower ?? left?.txPower ?? right?.txPower ?? null; pairs.push({ - id: serial ?? `arm:${any.address}`, + id: serialKey(serial) ?? `arm:${any.address}`, serial, identity: GlassesHardwareIdentity.decode(serial), left: left ? stripSmoothing(left) : null, right: right ? stripSmoothing(right) : null, completeness: left && right ? "complete" : left ? "left-only" : "right-only", rssi, - txPower, - proximity: estimateProximity(rssi, txPower, GLASSES_CALIBRATION), + proximity: estimateProximity(rssi, GLASSES_CALIBRATION), lastSeenMs: Math.max(left?.seenAtMs ?? 0, right?.seenAtMs ?? 0), + mismatchWarning: null, }); } + // Grouping on the serial means a group can never hold two different + // serials, so a mixed pair (left temple from A, right from B) surfaces as + // two lone arms, not as one mismatched row. With exactly one lone arm per + // side visible that IS the mixed-arms situation — name it on both rows so + // the wearer isn't left staring at two "waiting for the other" rows. + const loneLeft = pairs.filter((pair) => pair.completeness === "left-only" && pair.serial); + const loneRight = pairs.filter((pair) => pair.completeness === "right-only" && pair.serial); + if (loneLeft.length === 1 && loneRight.length === 1) { + const warning = pairSerialWarning(evaluatePairSerials(loneLeft[0]!.left!.serial, loneRight[0]!.right!.serial)); + loneLeft[0]!.mismatchWarning = warning; + loneRight[0]!.mismatchWarning = warning; + } return sortedByProximity(pairs, (pair) => pair.proximity, (pair) => pair.id); } @@ -189,7 +235,7 @@ export class DiscoveryAggregator { id: record.address, advertisement: stripSmoothing(record), rssi, - proximity: estimateProximity(rssi, record.txPower, RING_CALIBRATION), + proximity: estimateProximity(rssi, RING_CALIBRATION), lastSeenMs: record.seenAtMs, }); } @@ -205,9 +251,11 @@ function stripSmoothing(record: EvenAdvertisement & { smoothedRssi: number | nul /** * The candidate whose signal is strong enough to call "the one you are * holding". `null` when nothing leads clearly, which is the honest answer for - * two pairs sitting on the same table. + * two pairs sitting on the same table — and when the list has a single entry, + * where "closest" has nothing to be closer than. */ export function nearestCandidateId(candidates: ReadonlyArray<{ id: string; rssi: number | null }>): string | null { + if (candidates.length < 2) return null; const ranked = candidates .filter((candidate): candidate is { id: string; rssi: number } => candidate.rssi != null) .slice() @@ -221,19 +269,11 @@ export function nearestCandidateId(candidates: ReadonlyArray<{ id: string; rssi: /** * The saved pair identity is stored as the serial, but historical values may - * carry the `_L_1` arm suffix, so compare on the decoded serial when both - * sides decode and fall back to a containment check when they do not. + * carry the `_L_1` arm suffix; `serialsMatch` compares on the decoded serial + * so the suffix or casing is not read as different hardware. */ export function isPreviouslyPaired(name: string | null | undefined, pairedSerial: string | null | undefined): boolean { - if (!name || !pairedSerial) return false; - const saved = pairedSerial.trim(); - if (!saved) return false; - const left = GlassesHardwareIdentity.decode(name); - const right = GlassesHardwareIdentity.decode(saved); - if (left && right) return left.serial === right.serial; - const a = name.toLowerCase(); - const b = saved.toLowerCase(); - return a.includes(b) || b.includes(a); + return serialsMatch(name, pairedSerial); } // --------------------------------------------------------------------------- @@ -263,15 +303,12 @@ export type PairingRowPresentation = { proximitySummary: string; proximityGlyph: string; zone: ProximityZone | null; - /** "Left + right arms found", "Only the left arm has been seen", … */ + /** "Left + right arms found", "Only the left arm has been seen", …; "" when there is nothing worth a line (an unbonded ring). */ armsSummary: string; /** A problem the wearer should read before tapping, or "" when none. */ warning: string; /** Both arms present (or a ring), so tapping can save addresses. */ canSelect: boolean; - leftAddress: string; - rightAddress: string; - ringAddress: string; }; export type RowContext = { @@ -283,6 +320,29 @@ export type RowContext = { pairedRingAddress?: string | null; }; +/** The presentation fields glasses and ring rows share, so badge and fallback rules cannot drift apart. */ +function presentationBase( + proximity: ProximityEstimate | null, + isNearest: boolean, + isPaired: boolean, + warnings: readonly string[], +): Pick { + return { + isNearest, + isPreviouslyPaired: isPaired, + badge: isPaired ? "Yours" : isNearest ? "Closest" : "", + proximitySummary: proximity ? zoneLabel(proximity.zone) : "Signal unknown", + proximityGlyph: proximity ? zoneGlyph(proximity.zone) : "○○○○", + zone: proximity?.zone ?? null, + warning: warnings.join(" "), + }; +} + +function embeddedMacMismatchWarning(subject: string, ad: EvenAdvertisement | null): string | null { + if (!ad?.embeddedMacMismatch) return null; + return `${subject} advertised address ${ad.embeddedMac} differs from its radio address ${ad.address}.`; +} + export function glassesRow(pair: GlassesPairCandidate, context: RowContext = {}): PairingRowPresentation { const identity = pair.identity; const imagePath = glassesImagePath(identity); @@ -294,20 +354,17 @@ export function glassesRow(pair: GlassesPairCandidate, context: RowContext = {}) const rightNote = pair.right?.note; if (leftNote) warnings.push(`Left arm: ${leftNote}.`); if (rightNote) warnings.push(`Right arm: ${rightNote}.`); - if (pair.left?.embeddedMacMismatch) { - warnings.push(`Left arm's advertised address ${pair.left.embeddedMac} differs from its radio address ${pair.left.address}.`); - } - if (pair.right?.embeddedMacMismatch) { - warnings.push(`Right arm's advertised address ${pair.right.embeddedMac} differs from its radio address ${pair.right.address}.`); - } - const verdict = evaluatePairSerials(pair.left?.serial, pair.right?.serial); - const mismatch = pairSerialWarning(verdict); - if (mismatch) warnings.push(mismatch); + const leftMacWarning = embeddedMacMismatchWarning("Left arm's", pair.left); + if (leftMacWarning) warnings.push(leftMacWarning); + const rightMacWarning = embeddedMacMismatchWarning("Right arm's", pair.right); + if (rightMacWarning) warnings.push(rightMacWarning); + if (pair.mismatchWarning) warnings.push(pair.mismatchWarning); let armsSummary: string; switch (pair.completeness) { case "complete": - armsSummary = verdict.kind === "matched" ? "Left + right arms found · serials match" : "Left + right arms found"; + // Arms are grouped by serial, so a complete pair's serials match by construction. + armsSummary = "Left + right arms found · serials match"; break; case "left-only": armsSummary = "Only the left arm has been seen — waiting for the right"; @@ -328,30 +385,20 @@ export function glassesRow(pair: GlassesPairCandidate, context: RowContext = {}) swatchHex: identity?.colorway ? colorwaySwatchHex(identity.colorway) : null, imagePath, hasVariantImage: !!identity?.imageAssetName, - isNearest, - isPreviouslyPaired: isPreviouslyPairedRow, - badge: isPreviouslyPairedRow ? "Yours" : isNearest ? "Closest" : "", - proximitySummary: pair.proximity ? proximitySummary(pair.proximity) : "Signal unknown", - proximityGlyph: pair.proximity ? zoneGlyph(pair.proximity.zone) : "○○○○", - zone: pair.proximity?.zone ?? null, + ...presentationBase(pair.proximity, isNearest, isPreviouslyPairedRow, warnings), armsSummary, - warning: warnings.join(" "), - canSelect: pair.completeness === "complete" && verdict.kind !== "mismatched", - leftAddress: pair.left?.address ?? "", - rightAddress: pair.right?.address ?? "", - ringAddress: "", + canSelect: pair.completeness === "complete", }; } export function ringRow(ring: RingCandidate, context: RowContext = {}): PairingRowPresentation { const ad = ring.advertisement; - const isPaired = !!context.pairedRingAddress && context.pairedRingAddress.toUpperCase() === ad.address; + const isPaired = !!context.pairedRingAddress && normalizeMacAddress(context.pairedRingAddress) === ad.address; const isNearest = !!context.nearestId && context.nearestId === ring.id; const warnings: string[] = []; if (ad.note) warnings.push(`${ad.note}.`); - if (ad.embeddedMacMismatch) { - warnings.push(`The ring's advertised address ${ad.embeddedMac} differs from its radio address ${ad.address}.`); - } + const macWarning = embeddedMacMismatchWarning("The ring's", ad); + if (macWarning) warnings.push(macWarning); return { id: ring.id, kind: "ring", @@ -362,18 +409,11 @@ export function ringRow(ring: RingCandidate, context: RowContext = {}): PairingR swatchHex: null, imagePath: R1_IMAGE_PATH, hasVariantImage: true, - isNearest, - isPreviouslyPaired: isPaired, - badge: isPaired ? "Yours" : isNearest ? "Closest" : "", - proximitySummary: ring.proximity ? proximitySummary(ring.proximity) : "Signal unknown", - proximityGlyph: ring.proximity ? zoneGlyph(ring.proximity.zone) : "○○○○", - zone: ring.proximity?.zone ?? null, - armsSummary: ad.bonded ? "Paired with this phone" : "Advertising", - warning: warnings.join(" "), + ...presentationBase(ring.proximity, isNearest, isPaired, warnings), + // "Advertising" told the wearer nothing (a listed ring is advertising by + // definition); only the bonded state is worth a line. + armsSummary: ad.bonded ? "Paired with this phone" : "", canSelect: true, - leftAddress: "", - rightAddress: "", - ringAddress: ad.address, }; } diff --git a/app/images/faceclaw-logo.png b/app/images/faceclaw-logo.png new file mode 100644 index 00000000..5356a4e8 Binary files /dev/null and b/app/images/faceclaw-logo.png differ diff --git a/app/native/device-discovery.ts b/app/native/device-discovery.ts index fc5063e6..e35c13c0 100644 --- a/app/native/device-discovery.ts +++ b/app/native/device-discovery.ts @@ -1,6 +1,7 @@ import { Utils } from "@nativescript/core"; -import { classifyAdvertisement, type RawAdvertisement } from "../g2/even-advertisement"; +import { type RawAdvertisement } from "../g2/even-advertisement"; +import { DiscoveryAggregator } from "../g2/pairing-candidates"; declare const com: any; @@ -80,13 +81,16 @@ export class DeviceDiscoveryBridge { /** * Collect advertisements for `timeoutMs` without blocking the UI thread * (scan callbacks are delivered on the main looper, so a blocking sleep - * there would starve them). Latest sample per address wins. + * there would starve them). Every sample is kept: Android can split one + * advertisement across reports (name in one, manufacturer data in another), + * so "latest per address" would drop the informative half — the aggregator + * in `buildAddressSet` merges them instead. */ scanCandidates(timeoutMs = 6000): Promise { return new Promise((resolve, reject) => { - const latest = new Map(); + const samples: RawAdvertisement[] = []; const started = this.startScan({ - onAdvertisement: (raw) => latest.set(raw.address, raw), + onAdvertisement: (raw) => samples.push(raw), onScanFailed: (code, message) => { this.stopScan(); reject(new Error(`Bluetooth scan failed: ${message} (${code})`)); @@ -98,7 +102,7 @@ export class DeviceDiscoveryBridge { } setTimeout(() => { this.stopScan(); - resolve(Array.from(latest.values())); + resolve(samples); }, Math.max(500, timeoutMs)); }); } @@ -106,24 +110,48 @@ export class DeviceDiscoveryBridge { /** * Pick one address per role from a batch of raw advertisements — the manual - * address page's "load" helper. The latest-seen device of each role wins; - * the summary names the serial where one was advertised. + * address page's "load" helper and the flash flow's address resolution. + * + * Runs the batch through the same `DiscoveryAggregator` the pairing page + * uses, so left/right come from ONE serial-joined pair (the closest complete + * one) rather than from whichever arm of whatever pair advertised last — + * "latest per role" silently welded together arms of two different pairs. + * When no arm carries a serial at all (a bonded-device listing has no + * manufacturer data), there is nothing to join on and the latest arm per side + * is used as before. */ export function buildAddressSet(candidates: RawAdvertisement[]): DiscoveredAddressSet { - const classified = candidates.map(classifyAdvertisement).filter((item): item is NonNullable => !!item); - const latestForRole = new Map<"left" | "right" | "ring", (typeof classified)[number]>(); - for (const candidate of classified) { - const incumbent = latestForRole.get(candidate.role); - if (!incumbent || incumbent.seenAtMs <= candidate.seenAtMs) latestForRole.set(candidate.role, candidate); + const aggregator = new DiscoveryAggregator(); + for (const raw of candidates) aggregator.ingest(raw); + const classified = aggregator.advertisements(); + const pairs = aggregator.pairs(); + + let left = ""; + let right = ""; + const completePair = pairs.find((pair) => pair.completeness === "complete"); + if (completePair) { + left = completePair.left!.address; + right = completePair.right!.address; + } else if (classified.every((candidate) => !candidate.serial)) { + for (const role of ["left", "right"] as const) { + const latest = classified + .filter((candidate) => candidate.role === role) + .sort((a, b) => b.seenAtMs - a.seenAtMs)[0]; + if (role === "left") left = latest?.address ?? ""; + else right = latest?.address ?? ""; + } } + // Arms with serials but no complete pair: leave the addresses empty. The + // summary below names what was heard; guessing would defeat the serial join. + const lines = classified.map((candidate) => { const extras = [candidate.serial ? `serial ${candidate.serial}` : null, candidate.rssi != null ? `${candidate.rssi} dBm` : null].filter(Boolean); return `${candidate.role}: ${candidate.name} ${candidate.address}${extras.length ? ` (${extras.join(", ")})` : ""}`; }); return { - left: latestForRole.get("left")?.address ?? "", - right: latestForRole.get("right")?.address ?? "", - ring: latestForRole.get("ring")?.address ?? "", + left, + right, + ring: aggregator.rings()[0]?.advertisement.address ?? "", summary: lines.length ? lines.join("\n") : "No matching devices found.", }; } diff --git a/app/native/device-info-probe.ts b/app/native/device-info-probe.ts index 0e892fca..dec0ab0f 100644 --- a/app/native/device-info-probe.ts +++ b/app/native/device-info-probe.ts @@ -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, @@ -25,11 +25,11 @@ export class DeviceInfoProbe { private resolveFn: ((info: DeviceInfo) => void) | null = null; private rejectFn: ((error: Error) => void) | null = null; - constructor(rightAddress: string) { + constructor(rightAddress: string, leftAddress = "") { const context = Utils.android.getApplicationContext(); if (!context) throw new Error("Android application context unavailable"); - this.probe = new com.faceclaw.app.FaceclawDeviceInfoProbe(context, rightAddress); + this.probe = new com.faceclaw.app.FaceclawDeviceInfoProbe(context, rightAddress, leftAddress); this.listenerProxy = new com.faceclaw.app.FaceclawDeviceInfoProbeListener({ onLog: (line: string) => this.emit(this.logListeners, String(line)), onState: (state: string, detail: string) => diff --git a/app/native/firmware-flasher.ts b/app/native/firmware-flasher.ts index b2cfba7e..cd75d0b7 100644 --- a/app/native/firmware-flasher.ts +++ b/app/native/firmware-flasher.ts @@ -10,6 +10,9 @@ export type FlashProgress = { componentCount: number; blockIndex: number; blockCount: number; + /** Bytes flashed so far across the whole lens image — the size-weighted progress signal. */ + bytesSent: number; + bytesTotal: number; }; /** @@ -42,6 +45,8 @@ export class FirmwareFlasher { componentCount: number, blockIndex: number, blockCount: number, + bytesSent: number, + bytesTotal: number, ) => this.emit(this.progressListeners, { lens: String(lens), @@ -49,6 +54,8 @@ export class FirmwareFlasher { componentCount: Number(componentCount), blockIndex: Number(blockIndex), blockCount: Number(blockCount), + bytesSent: Number(bytesSent), + bytesTotal: Number(bytesTotal), }), onState: (state: string, detail: string) => this.emit(this.stateListeners, String(state) as FlashState, String(detail ?? "")), diff --git a/app/phone-ui/config-page.xml b/app/phone-ui/config-page.xml index 410fda3d..cffe6f9e 100644 --- a/app/phone-ui/config-page.xml +++ b/app/phone-ui/config-page.xml @@ -2,7 +2,7 @@ -