Modern Apps git

← Modern-Apps.git

findfamily: UWB Precision Finding screen

Commit
1ba6a72dccd06a53c11b14cf327e3b37375ddfc8
Author
Vayun Mathur <[email protected]>
When
2026-05-30 00:48 UTC (6 months ago)
Parents
374412c
Adds a 'Find with Precision' affordance on the per-user pane that opens a
full-screen UWB ranging view backed by Android 15+'s public
android.ranging.RangingManager API (no GMS dependency — works on
GrapheneOS).

Architecture:
- UwbSessionManager (process-global, owned by LocationTrackingService) hosts
  the session so we can auto-accept incoming REQUESTs in the background
  without needing UWB_PRIVILEGED.
- Networking publishes/receives small encrypted handshake envelopes via two
  new endpoints (/api/uwb/publish, /api/uwb/receive) — the same E2E pattern
  as the existing location channel. Ranging samples themselves never touch
  the server.
- A dedicated 3s UWB-only poll loop in LocationTrackingService picks up
  REQUESTs much faster than the 30s location heartbeat.
- UwbController wraps android.ranging with tier-fallback session config
  (DIRECTIONAL antenna + IMU sensor fusion first; degrades on
  REASON_UNSUPPORTED). Each device caches its winning tier.
- Per-axis confidence filtering drops CONFIDENCE_LOW measurements; folds
  back-hemisphere azimuth readings into [-90°,+90°] to work around the
  2-antenna front/back ambiguity.

Scaffolding for cross-platform Android↔iOS ranging via Apple's third-party
accessory protocol (UwbAccessoryProtocol) is in place but the FiRa byte
parsing is stubbed and needs implementing against the spec.

Diff

findfamily/build.gradle.kts
diff --git a/findfamily/build.gradle.kts b/findfamily/build.gradle.ktsindex 7ba62d03f3..155b288bb8 100644--- a/findfamily/build.gradle.kts+++ b/findfamily/build.gradle.kts@@ -25,6 +25,9 @@ dependencies {     implementation(libs.cryptography.core)     implementation(libs.cryptography.provider.jdk) -    // Ultra-Wideband ranging (Precision Finding screen)-    implementation("androidx.core.uwb:uwb:1.0.0-alpha11")+    // Public AOSP ranging API (android.ranging.*) is part of the framework+    // on Android 15+ — no third-party library needed. We intentionally avoid+    // androidx.core.uwb because its only backend is GMS-mediated, which fails+    // on GrapheneOS (sandboxed Play Services can't talk to the platform UWB+    // service). All UWB code paths are gated on Build.VERSION.SDK_INT >= 35. }\ No newline at end of file
findfamily/src/main/AndroidManifest.xml
diff --git a/findfamily/src/main/AndroidManifest.xml b/findfamily/src/main/AndroidManifest.xmlindex 5fbb484274..97c45326ba 100644--- a/findfamily/src/main/AndroidManifest.xml+++ b/findfamily/src/main/AndroidManifest.xml@@ -14,8 +14,11 @@     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> -    <!-- UWB ranging for the Precision Finding screen. Runtime-requested on API 31+. -->-    <uses-permission android:name="android.permission.UWB_RANGING" />+    <!-- Precision Finding screen uses the public android.ranging API+         introduced in Android 15. We do not depend on androidx.core.uwb+         (its only backend is GMS, which is broken on GrapheneOS), and+         consequently do not declare UWB_RANGING. -->+    <uses-permission android:name="android.permission.RANGING" />     <uses-feature android:name="android.hardware.uwb" android:required="false" />      <permission
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex e43f82843e..df0ec63d6b 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -177,10 +177,14 @@ fun MainPage(                     } else if (selectedUserId != null) {                         if (selectedUserId != Networking.userid) {                             val user by ffViewModel.userByIdState(selectedUserId!!)-                            IconButton({-                                backStack.add(Route.UwbRangingPage(selectedUserId!!))-                            }) {-                                IconNavigationArrow()+                            // UWB Precision Finding requires the public android.ranging API+                            // (Android 15+). Hide the entry point on older devices.+                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.VANILLA_ICE_CREAM) {+                                IconButton({+                                    backStack.add(Route.UwbRangingPage(selectedUserId!!))+                                }) {+                                    IconNavigationArrow()+                                }                             }                             IconButton({                                 ffViewModel.deleteUser(user)
findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.ktnew file mode 100644index 0000000000..3464265d36--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt@@ -0,0 +1,242 @@+package com.vayunmathur.findfamily.ui++import android.content.pm.PackageManager+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.core.content.ContextCompat+import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.Route+import com.vayunmathur.findfamily.uwb.RangingSample+import com.vayunmathur.findfamily.util.FindFamilyViewModel+import com.vayunmathur.findfamily.util.UwbSessionManager+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconNavigationArrow+import com.vayunmathur.library.util.NavBackStack++/**+ * Full-screen UWB Precision Finding view. Shows distance + a directional+ * arrow to the selected peer.+ *+ * The screen owns the UWB session lifecycle: it triggers [FindFamilyViewModel.startRanging]+ * on first composition and [FindFamilyViewModel.stopRanging] on dispose.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun UwbRangingScreen(+    backStack: NavBackStack<Route>,+    ffViewModel: FindFamilyViewModel,+    peerUserId: Long+) {+    val context = LocalContext.current++    val peer by ffViewModel.userByIdState(peerUserId)+    val session by ffViewModel.uwbSession.collectAsState()+    val activePeerId by ffViewModel.uwbPeerUserId.collectAsState()++    // Runtime android.permission.RANGING gate (required by the public+    // android.ranging API on Android 15+). UWB_RANGING is the legacy perm+    // for androidx.core.uwb's GMS path — we no longer use that path.+    var hasRangingPermission by remember {+        mutableStateOf(+            ContextCompat.checkSelfPermission(+                context,+                "android.permission.RANGING"+            ) == PackageManager.PERMISSION_GRANTED+        )+    }+    val permLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestPermission()+    ) { granted -> hasRangingPermission = granted }++    LaunchedEffect(hasRangingPermission) {+        if (!hasRangingPermission) {+            permLauncher.launch("android.permission.RANGING")+            return@LaunchedEffect+        }+        // Three cases when the screen opens:+        //  (a) session is Idle           → user wants to find peer; start as initiator.+        //  (b) session is active for THIS peer → service already auto-accepted; just observe.+        //  (c) session is active for ANOTHER peer → busy; show a Failed state (one session at a time).+        when {+            session is UwbSessionManager.UwbSessionState.Idle -> {+                ffViewModel.startRanging(peerUserId)+            }+            activePeerId != null && activePeerId != peerUserId -> {+                // Showing the screen for a different peer than the active session.+                // Don't stomp on the ongoing session — just display its current state+                // (which won't match this peer) so the user understands.+            }+            // else: session is for THIS peer — observe in place.+        }+    }++    DisposableEffect(Unit) {+        onDispose {+            // Only end the session if it's the one this screen was watching.+            if (activePeerId == peerUserId) {+                ffViewModel.stopRanging()+            }+        }+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text(peer.name) },+                navigationIcon = { IconNavigation { backStack.pop() } }+            )+        }+    ) { padding ->+        Column(+            modifier = Modifier+                .fillMaxSize()+                .padding(padding)+                .padding(24.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.SpaceEvenly+        ) {+            when (val s = session) {+                UwbSessionManager.UwbSessionState.Idle,+                UwbSessionManager.UwbSessionState.Starting -> StatusBlock(+                    main = stringResource(R.string.uwb_status_starting),+                    progress = true+                )+                UwbSessionManager.UwbSessionState.WaitingForPeer -> StatusBlock(+                    main = stringResource(R.string.uwb_status_waiting),+                    progress = true+                )+                UwbSessionManager.UwbSessionState.PeerDisconnected -> StatusBlock(+                    main = stringResource(R.string.uwb_status_peer_disconnected),+                    progress = false+                )+                is UwbSessionManager.UwbSessionState.Unsupported -> StatusBlock(+                    main = stringResource(R.string.uwb_status_unsupported),+                    sub = s.reason,+                    progress = false+                )+                is UwbSessionManager.UwbSessionState.Failed -> StatusBlock(+                    main = stringResource(R.string.uwb_status_failed),+                    sub = s.reason,+                    progress = false+                )+                is UwbSessionManager.UwbSessionState.Ranging -> RangingBody(s.sample)+            }+        }+    }+}++@Composable+private fun StatusBlock(main: String, sub: String? = null, progress: Boolean) {+    Column(+        horizontalAlignment = Alignment.CenterHorizontally,+        modifier = Modifier.fillMaxSize(),+        verticalArrangement = Arrangement.Center+    ) {+        if (progress) {+            CircularProgressIndicator()+            Spacer(Modifier.height(16.dp))+        }+        Text(+            main,+            style = MaterialTheme.typography.titleLarge,+            textAlign = TextAlign.Center+        )+        if (sub != null) {+            Spacer(Modifier.height(8.dp))+            Text(+                sub,+                style = MaterialTheme.typography.bodyMedium,+                textAlign = TextAlign.Center,+                color = MaterialTheme.colorScheme.onSurfaceVariant+            )+        }+    }+}++@Composable+private fun RangingBody(sample: RangingSample) {+    val distance = sample.distanceMeters+    val azimuth = sample.azimuthDeg++    Column(+        horizontalAlignment = Alignment.CenterHorizontally,+        verticalArrangement = Arrangement.SpaceEvenly,+        modifier = Modifier.fillMaxSize()+    ) {+        // Distance readout+        Text(+            text = distance?.let { "%.1f m".format(it) } ?: "—",+            fontSize = 96.sp,+            fontWeight = FontWeight.Bold,+            color = MaterialTheme.colorScheme.primary+        )++        // Directional arrow — raw azimuth from the radio (low-confidence+        // samples have already been filtered out in UwbController).+        Box(+            modifier = Modifier.size(220.dp),+            contentAlignment = Alignment.Center+        ) {+            IconNavigationArrow(+                tint = MaterialTheme.colorScheme.primary,+                modifier = Modifier+                    .size(180.dp)+                    .alpha(if (azimuth != null) 1f else 0.25f)+                    .graphicsLayer { rotationZ = azimuth ?: 0f }+            )+        }++        // Debug overlay+        Text(+            text = buildString {+                append("dist: ").append(distance?.let { "%.2f m".format(it) } ?: "—")+                append("   az: ").append(azimuth?.let { "%+.1f°".format(it) } ?: "—")+                append("   el: ").append(sample.elevationDeg?.let { "%+.1f°".format(it) } ?: "—")+            },+            style = MaterialTheme.typography.bodySmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            textAlign = TextAlign.Center+        )++        if (azimuth == null) {+            Text(+                text = "Point the back of your phone toward your contact",+                style = MaterialTheme.typography.bodyMedium,+                textAlign = TextAlign.Center,+                color = MaterialTheme.colorScheme.onSurfaceVariant+            )+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.ktindex 11f12d4e2b..9102232760 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -98,6 +98,7 @@ class LocationTrackingService : Service(), SensorEventListener {     private var lastMovementTime = 0L     private var lastKnownLocation: Location? = null     private var heartbeatJob: Job? = null+    private var uwbPollJob: Job? = null     private var trackingInitialized = false      private val networkListener = LocationListener { location ->@@ -212,19 +213,26 @@ class LocationTrackingService : Service(), SensorEventListener {                 }                 locationValueDao.upsertAll(locations)             }+        }+    } -            // 4. Drain the UWB session-setup channel. Each envelope is published-            //    onto UwbInbox so an open Precision Finding screen can react; if-            //    the envelope is a REQUEST and the screen isn't open, post a-            //    notification offering to launch it.-            Networking.receiveUwbMessages()?.forEach { envelope ->-                UwbInbox.tryEmit(envelope)-                if (envelope.kind == UwbEnvelopeKind.REQUEST) {-                    val senderId = envelope.sender.toLong()-                    val senderName = currentUsers.firstOrNull { it.id == senderId }?.name-                        ?: getString(R.string.uwb_unknown_peer_name)-                    createUwbRequestNotification(senderName, senderId)-                }+    /**+     * Fast-path drain of the UWB session-setup channel, run on a dedicated+     * coroutine every 3s (vs. the 30s heartbeat). Each envelope is forwarded+     * to [UwbInbox] so the manager / open screen can react; REQUEST envelopes+     * also fire a local notification so the user knows ranging is happening.+     */+    private suspend fun drainUwbInbox() {+        val envelopes = Networking.receiveUwbMessages() ?: return+        if (envelopes.isEmpty()) return+        val users = userDao.getAll()+        for (envelope in envelopes) {+            UwbInbox.tryEmit(envelope)+            if (envelope.kind == UwbEnvelopeKind.REQUEST) {+                val senderId = envelope.sender.toLong()+                val senderName = users.firstOrNull { it.id == senderId }?.name+                    ?: getString(R.string.uwb_unknown_peer_name)+                createUwbRequestNotification(senderName, senderId)             }         }     }@@ -314,6 +322,20 @@ class LocationTrackingService : Service(), SensorEventListener {                     delay(30.seconds)                 }             }++            // Separate, faster poll for the UWB session-setup channel. The+            // location heartbeat runs every 30s for battery reasons, but UWB+            // REQUEST envelopes need to be picked up quickly so the responder+            // device auto-accepts within a few seconds. This loop ONLY drains+            // /api/uwb/receive — no location publish/receive, no geocoding,+            // no waypoint logic.+            uwbPollJob?.cancel()+            uwbPollJob = launch {+                while (isActive) {+                    drainUwbInbox()+                    delay(3.seconds)+                }+            }         }     } 
findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.ktindex 19c667c30e..011262af76 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -171,10 +171,21 @@ object Networking {         val cipher = key.encryptor()         val str = json.encodeToString(envelope)         val encryptedData = Base64.encode(cipher.encrypt(str.encodeToByteArray()))-        return makeRequest<Boolean, LocationSharingData>(-            "/api/uwb/publish",-            LocationSharingData(recipientUserId.toULong(), encryptedData)-        ) ?: false+        // We can't reuse `makeRequest<Boolean, ...>` here because the server+        // returns `204 No Content` (no body) on success, and Ktor's content+        // negotiation throws `NoTransformationFoundException` trying to+        // deserialize an empty body into a `Boolean`. `performRequest` returns+        // the raw response and we treat any 2xx status as success.+        val bodyJson = json.encodeToString(LocationSharingData(recipientUserId.toULong(), encryptedData))+        return checkNetworkDown {+            val resp = NetworkClient.performRequest(+                url = "$URL/api/uwb/publish",+                method = "POST",+                headers = mapOf("Content-Type" to "application/json"),+                body = bodyJson+            )+            resp.status in 200..299+        } ?: false     }      /**
findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.ktnew file mode 100644index 0000000000..748251261e--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt@@ -0,0 +1,470 @@+package com.vayunmathur.findfamily.util++import android.content.Context+import android.os.Build+import android.util.Log+import androidx.annotation.RequiresApi+import com.vayunmathur.findfamily.data.UserDao+import com.vayunmathur.findfamily.uwb.RangingSample+import com.vayunmathur.findfamily.uwb.UwbAccessoryProtocol+import com.vayunmathur.findfamily.uwb.UwbBytes+import com.vayunmathur.findfamily.uwb.UwbController+import com.vayunmathur.findfamily.uwb.UwbEnvelope+import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind+import com.vayunmathur.findfamily.uwb.UwbHandshake+import com.vayunmathur.findfamily.uwb.UwbInbox+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull+import java.util.UUID+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Process-global UWB ranging session owner.+ *+ * Built on the public `android.ranging.RangingManager` API (Android 15+).+ * This is the only on-device UWB API that works on GrapheneOS — the legacy+ * `androidx.core.uwb` only ships a GMS-mediated backend that sandboxed Play+ * Services can't fulfil. Accordingly the entire UWB feature requires API 35.+ *+ * Hoisting the session out of the (activity-scoped) ViewModel into a+ * service-scoped singleton lets the existing foreground `LocationTrackingService`+ * auto-accept incoming Precision Finding requests from peers — i.e. range in+ * the background without requiring the user to tap a notification first.+ * This works because the session is owned by the foreground service rather+ * than an Activity, so Android keeps the process eligible for ranging+ * callbacks.+ */+object UwbSessionManager {++    /** UI-facing state machine for the Precision Finding screen. */+    sealed interface UwbSessionState {+        data object Idle : UwbSessionState+        data object Starting : UwbSessionState+        data object WaitingForPeer : UwbSessionState+        data class Ranging(val sample: RangingSample) : UwbSessionState+        data object PeerDisconnected : UwbSessionState+        data class Unsupported(val reason: String) : UwbSessionState+        data class Failed(val reason: String) : UwbSessionState+    }++    private val _state: MutableStateFlow<UwbSessionState> = MutableStateFlow(UwbSessionState.Idle)+    val state: StateFlow<UwbSessionState> = _state.asStateFlow()++    /** The peer userid currently being ranged with (or attempted), if any. */+    private val _peerUserId: MutableStateFlow<Long?> = MutableStateFlow(null)+    val peerUserId: StateFlow<Long?> = _peerUserId.asStateFlow()++    /** True iff this device's API level supports the AOSP ranging API. */+    val isSupportedSdk: Boolean get() =+        Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM++    private const val TAG = "UwbSessionManager"+    private const val TIMEOUT_MS = 60_000L++    private val initialized = AtomicBoolean(false)+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private lateinit var appContext: Context+    private lateinit var userDao: UserDao++    private var controller: UwbController? = null+    private var streamJob: Job? = null+    private var waitJob: Job? = null+    private var currentSessionId: String? = null++    /**+     * Wire up the manager. No-op on devices below API 35. Safe to call+     * multiple times — only the first call has effect.+     */+    fun init(context: Context, userDao: UserDao) {+        if (!isSupportedSdk) { Log.i(TAG, "init: SDK ${Build.VERSION.SDK_INT} < 35, UWB disabled"); return }+        if (!initialized.compareAndSet(false, true)) { Log.i(TAG, "init: already initialized"); return }+        Log.i(TAG, "init: hooking up UwbInbox subscriber")+        appContext = context.applicationContext+        UwbSessionManager.userDao = userDao++        // Subscribe to the global UWB envelope inbox for the whole process+        // lifetime. CANCELs from the peer tear down our local session+        // whether we're idle / waiting / ranging; REQUESTs trigger the+        // responder (auto-accept) path when we're idle.+        scope.launch {+            UwbInbox.flow.collect { env ->+                when (env.kind) {+                    UwbEnvelopeKind.REQUEST -> {+                        if (_state.value is UwbSessionState.Idle) {+                            acceptIncoming(env)+                        }+                        // If already busy, drop — UWB is one-session-at-a-time.+                    }+                    UwbEnvelopeKind.CANCEL -> {+                        if (env.sessionId == currentSessionId) {+                            stopLocal()+                        }+                    }+                    // ACK and CONFIG envelopes are consumed by the waiting+                    // initiator/responder coroutines via UwbInbox.flow.first {...}.+                    else -> {}+                }+            }+        }+    }++    // -----------------------------------------------------------------+    // Initiator path (user tapped "Find with Precision" on the screen)+    // -----------------------------------------------------------------++    fun startAsInitiator(peerUserId: Long) {+        Log.i(TAG, "startAsInitiator(peer=$peerUserId) entered. isSupportedSdk=$isSupportedSdk initialized=${initialized.get()} state=${_state.value}")+        if (!isSupportedSdk) {+            _state.value = UwbSessionState.Unsupported(+                "Precision Finding requires Android 15 or newer."+            )+            return+        }+        if (!initialized.get()) { Log.w(TAG, "startAsInitiator: NOT INITIALIZED — service hasn't called init() yet"); return }+        if (_state.value !is UwbSessionState.Idle) { Log.i(TAG, "startAsInitiator: not idle, skipping"); return }+        _state.value = UwbSessionState.Starting+        val sessionId = UUID.randomUUID().toString()+        currentSessionId = sessionId+        _peerUserId.value = peerUserId++        scope.launch {+            Log.i(TAG, "startAsInitiator: launched coroutine, loading peer from DB")+            val peerUser = userDao.getAll().firstOrNull { it.id == peerUserId }+            Log.i(TAG, "startAsInitiator: peerUser=${peerUser?.name} platform=${peerUser?.platform}")+            if (peerUser == null) {+                _state.value = UwbSessionState.Failed("Unknown peer")+                stopLocal()+                return@launch+            }+            if (peerUser.platform == "ios") {+                beginCrossPlatformInitiateToIos(peerUserId, sessionId)+                return@launch+            }++            val ctrl = UwbController(appContext)+            controller = ctrl+            Log.i(TAG, "startAsInitiator: opening controller")+            val info = ctrl.openController().getOrElse {+                Log.e(TAG, "openController failed", it)+                _state.value = UwbSessionState.Unsupported(it.message ?: "UWB not available on this device")+                return@launch+            }+            Log.i(TAG, "startAsInitiator: controller opened (addr=${info.localAddress.joinToString(":") { "%02x".format(it) }} ch=${info.channelNumber} pi=${info.preambleIndex}); publishing REQUEST")++            val envelope = UwbEnvelope(+                sessionId = sessionId,+                sender = Networking.userid.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.REQUEST,+                payload = UwbHandshake(+                    addressB64 = UwbBytes.b64(info.localAddress),+                    channelNumber = info.channelNumber,+                    preambleIndex = info.preambleIndex,+                    sessionKeyB64 = UwbBytes.b64(info.sessionKey),+                    sessionId = info.sessionId+                )+            )+            val ok = Networking.publishUwbMessage(envelope, peerUserId, peerUser)+            Log.i(TAG, "startAsInitiator: publishUwbMessage returned $ok")+            if (!ok) {+                _state.value = UwbSessionState.Failed("Could not reach peer")+                stopLocal()+                return@launch+            }+            _state.value = UwbSessionState.WaitingForPeer++            waitJob = launch {+                Log.i(TAG, "startAsInitiator: parked waiting for ACK on sessionId=$sessionId")+                val ack = waitForEnvelope(sessionId, TIMEOUT_MS) { env ->+                    env.kind == UwbEnvelopeKind.ACK || env.kind == UwbEnvelopeKind.CANCEL+                }+                if (ack == null) {+                    _state.value = UwbSessionState.Failed("Peer did not respond")+                    stopLocal()+                    return@launch+                }+                if (ack.kind == UwbEnvelopeKind.CANCEL) {+                    _state.value = UwbSessionState.Idle+                    stopLocal()+                    return@launch+                }+                val peerAddress = ack.payload?.addressB64?.let(UwbBytes::from)+                if (peerAddress == null) {+                    _state.value = UwbSessionState.Failed("Invalid peer ack")+                    stopLocal()+                    return@launch+                }+                startRangingStream(+                    ctrl,+                    role = UwbController.Role.Initiator,+                    localAddress = info.localAddress,+                    peerAddress = peerAddress,+                    sessionId = info.sessionId,+                    sessionKey = info.sessionKey,+                    channelNumber = info.channelNumber,+                    preambleIndex = info.preambleIndex+                )+            }+        }+    }++    /**+     * Cross-platform initiator: Android user tapped on an iOS peer. We open+     * controlee, ship accessoryData in the REQUEST, and park waiting for+     * iOS's shareableConfigurationData reply.+     */+    private suspend fun beginCrossPlatformInitiateToIos(peerUserId: Long, sessionId: String) {+        val peerUser = userDao.getAll().firstOrNull { it.id == peerUserId }+        val ctrl = UwbController(appContext)+        controller = ctrl+        val localAddress = ctrl.openControlee().getOrElse {+            _state.value = UwbSessionState.Unsupported(it.message ?: "UWB not available on this device")+            return+        }+        val accessoryData = UwbAccessoryProtocol.encodeAccessoryConfigurationData(localAddress)+        val envelope = UwbEnvelope(+            sessionId = sessionId,+            sender = Networking.userid.toULong(),+            senderPlatform = "android",+            kind = UwbEnvelopeKind.REQUEST,+            payload = UwbHandshake(accessoryConfigDataB64 = UwbBytes.b64(accessoryData))+        )+        val ok = Networking.publishUwbMessage(envelope, peerUserId, peerUser)+        if (!ok) {+            _state.value = UwbSessionState.Failed("Could not reach peer")+            stopLocal()+            return+        }+        _state.value = UwbSessionState.WaitingForPeer+        waitJob = scope.launch {+            val shareable = waitForEnvelope(sessionId, TIMEOUT_MS) { env ->+                env.kind == UwbEnvelopeKind.CONFIG && env.payload?.shareableConfigDataB64 != null+            }+            if (shareable == null) {+                _state.value = UwbSessionState.Failed("iOS peer did not return ranging config")+                stopLocal()+                return@launch+            }+            val parsed = try {+                UwbAccessoryProtocol.parseShareableConfigurationData(+                    UwbBytes.from(shareable.payload!!.shareableConfigDataB64!!)+                )+            } catch (e: Throwable) {+                _state.value = UwbSessionState.Failed(e.message ?: "Could not parse iOS config")+                stopLocal()+                return@launch+            }+            startRangingStream(+                ctrl,+                role = UwbController.Role.Responder,+                localAddress = localAddress,+                peerAddress = parsed.peerAddress,+                sessionId = parsed.sessionId,+                sessionKey = parsed.sessionKey,+                channelNumber = parsed.channelNumber,+                preambleIndex = parsed.preambleIndex+            )+        }+    }++    // -----------------------------------------------------------------+    // Responder path (REQUEST envelope arrived — auto-accept in background)+    // -----------------------------------------------------------------++    private fun acceptIncoming(request: UwbEnvelope) {+        if (!isSupportedSdk) return+        currentSessionId = request.sessionId+        _peerUserId.value = request.sender.toLong()+        _state.value = UwbSessionState.Starting++        scope.launch {+            // Cross-platform: iOS sender (no FiRa payload, only accessoryData).+            if (request.senderPlatform == "ios" || request.payload?.addressB64 == null) {+                beginCrossPlatformAsAccessory(request)+                return@launch+            }+            // After the early return above, payload + addressB64 are both non-null.+            val payload = request.payload+            val peerAddress = UwbBytes.from(payload.addressB64)+            val sessionId = payload.sessionId ?: return@launch+            val sessionKey = payload.sessionKeyB64?.let(UwbBytes::from) ?: return@launch+            val channel = payload.channelNumber ?: return@launch+            val preamble = payload.preambleIndex ?: return@launch++            val ctrl = UwbController(appContext)+            controller = ctrl+            val localAddress = ctrl.openControlee().getOrElse {+                _state.value = UwbSessionState.Unsupported(it.message ?: "UWB not available on this device")+                stopLocal()+                return@launch+            }+            val ack = UwbEnvelope(+                sessionId = request.sessionId,+                sender = Networking.userid.toULong(),+                senderPlatform = "android",+                kind = UwbEnvelopeKind.ACK,+                payload = UwbHandshake(addressB64 = UwbBytes.b64(localAddress))+            )+            val peer = userDao.getAll().firstOrNull { it.id == request.sender.toLong() }+            val ok = Networking.publishUwbMessage(ack, request.sender.toLong(), peer)+            if (!ok) {+                _state.value = UwbSessionState.Failed("Could not reach peer")+                stopLocal()+                return@launch+            }+            startRangingStream(+                ctrl,+                role = UwbController.Role.Responder,+                localAddress = localAddress,+                peerAddress = peerAddress,+                sessionId = sessionId,+                sessionKey = sessionKey,+                channelNumber = channel,+                preambleIndex = preamble+            )+        }+    }++    private suspend fun beginCrossPlatformAsAccessory(request: UwbEnvelope) {+        val ctrl = UwbController(appContext)+        controller = ctrl+        val localAddress = ctrl.openControlee().getOrElse {+            _state.value = UwbSessionState.Unsupported(it.message ?: "UWB not available on this device")+            stopLocal()+            return+        }+        val accessoryData = UwbAccessoryProtocol.encodeAccessoryConfigurationData(localAddress)+        val configEnvelope = UwbEnvelope(+            sessionId = request.sessionId,+            sender = Networking.userid.toULong(),+            senderPlatform = "android",+            kind = UwbEnvelopeKind.CONFIG,+            payload = UwbHandshake(accessoryConfigDataB64 = UwbBytes.b64(accessoryData))+        )+        val peer = userDao.getAll().firstOrNull { it.id == request.sender.toLong() }+        val ok = Networking.publishUwbMessage(configEnvelope, request.sender.toLong(), peer)+        if (!ok) {+            _state.value = UwbSessionState.Failed("Could not reach peer")+            stopLocal()+            return+        }+        _state.value = UwbSessionState.WaitingForPeer+        val shareable = waitForEnvelope(request.sessionId, TIMEOUT_MS) { env ->+            env.kind == UwbEnvelopeKind.CONFIG && env.payload?.shareableConfigDataB64 != null+        }+        if (shareable == null) {+            _state.value = UwbSessionState.Failed("iOS peer did not return ranging config")+            stopLocal()+            return+        }+        val parsed = try {+            UwbAccessoryProtocol.parseShareableConfigurationData(+                UwbBytes.from(shareable.payload!!.shareableConfigDataB64!!)+            )+        } catch (e: Throwable) {+            _state.value = UwbSessionState.Failed(e.message ?: "Could not parse iOS config")+            stopLocal()+            return+        }+        startRangingStream(+            ctrl,+            role = UwbController.Role.Responder,+            localAddress = localAddress,+            peerAddress = parsed.peerAddress,+            sessionId = parsed.sessionId,+            sessionKey = parsed.sessionKey,+            channelNumber = parsed.channelNumber,+            preambleIndex = parsed.preambleIndex+        )+    }++    // -----------------------------------------------------------------+    // Common: drive the RangingResult flow into the state machine+    // -----------------------------------------------------------------++    @RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)+    private fun startRangingStream(+        ctrl: UwbController,+        role: UwbController.Role,+        localAddress: ByteArray,+        peerAddress: ByteArray,+        sessionId: Int,+        sessionKey: ByteArray,+        channelNumber: Int,+        preambleIndex: Int,+    ) {+        streamJob?.cancel()+        streamJob = scope.launch {+            try {+                ctrl.stream(+                    role = role,+                    localAddress = localAddress,+                    peerAddress = peerAddress,+                    sessionId = sessionId,+                    sessionKey = sessionKey,+                    channelNumber = channelNumber,+                    preambleIndex = preambleIndex,+                ).collect { sample ->+                    _state.value = if (sample.peerDisconnected) {+                        UwbSessionState.PeerDisconnected+                    } else {+                        UwbSessionState.Ranging(sample)+                    }+                }+            } catch (e: Exception) {+                _state.value = UwbSessionState.Failed(e.message ?: "Ranging failed")+            }+        }+    }++    /**+     * User-initiated stop. Sends a CANCEL envelope to the peer so its UI can+     * exit too, then tears down the local UWB scope.+     */+    fun stop() {+        val sessionId = currentSessionId+        val peerId = _peerUserId.value+        if (sessionId != null && peerId != null) {+            scope.launch {+                val peer = userDao.getAll().firstOrNull { it.id == peerId }+                Networking.publishUwbMessage(+                    UwbEnvelope(+                        sessionId = sessionId,+                        sender = Networking.userid.toULong(),+                        senderPlatform = "android",+                        kind = UwbEnvelopeKind.CANCEL+                    ),+                    peerId,+                    peer+                )+            }+        }+        stopLocal()+    }++    private fun stopLocal() {+        streamJob?.cancel(); streamJob = null+        waitJob?.cancel(); waitJob = null+        controller?.stop(); controller = null+        currentSessionId = null+        _peerUserId.value = null+        _state.value = UwbSessionState.Idle+    }++    private suspend fun waitForEnvelope(+        sessionId: String,+        timeoutMs: Long,+        predicate: (UwbEnvelope) -> Boolean,+    ): UwbEnvelope? = withTimeoutOrNull(timeoutMs) {+        UwbInbox.flow.first { it.sessionId == sessionId && predicate(it) }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.ktnew file mode 100644index 0000000000..c7e9f7638d--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.kt@@ -0,0 +1,50 @@+package com.vayunmathur.findfamily.uwb++/**+ * Apple's "UWB Specification for Third-Party Accessories" protocol — the bytes+ * that flow between an iPhone (running `NINearbyAccessoryConfiguration`) and a+ * UWB accessory. In the FindFamily cross-platform pairing, the Android device+ * plays the accessory role.+ *+ * The byte format is specified in:+ *   - Apple's PDF "Implementing Spatial Interactions with Third-Party Devices"+ *     (developer.apple.com/nearby-interaction → "Specification")+ *   - FiRa MAC Technical Requirements (TLV-encoded MAC params)+ *+ * The encode/parse functions below are stubbed: filling them in accurately+ * requires both specs in hand and is a multi-day task. The scaffolding+ * around them (transport, envelope routing, controlee session setup via+ * `android.ranging.RangingManager`) is complete.+ */+object UwbAccessoryProtocol {++    /**+     * Generate the "accessory configuration data" blob to send to iOS at+     * session start. Must encode this device's UWB MAC parameters per+     * Apple's accessory spec.+     */+    fun encodeAccessoryConfigurationData(localAddress: ByteArray): ByteArray {+        // TODO(uwb-cross-platform): Implement per Apple's spec.+        // The blob is roughly: [protocol-version u8][profile-id u8][TLV...].+        return byteArrayOf(0x01, 0x00) + localAddress+    }++    /**+     * Parse the "shareableConfigurationData" blob received from iOS into the+     * concrete FiRa parameters this device should use as controlee.+     */+    fun parseShareableConfigurationData(shareableConfigData: ByteArray): Parsed {+        throw NotImplementedError(+            "Apple accessory-protocol byte parsing not yet implemented. " ++                "See UwbAccessoryProtocol.kt and Apple's UWB Third-Party Accessory spec."+        )+    }++    data class Parsed(+        val peerAddress: ByteArray,+        val sessionId: Int,+        val sessionKey: ByteArray,+        val channelNumber: Int,+        val preambleIndex: Int,+    )+}
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.ktnew file mode 100644index 0000000000..05242403f5--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.kt@@ -0,0 +1,417 @@+package com.vayunmathur.findfamily.uwb++import android.content.Context+import android.os.Build+import android.ranging.DataNotificationConfig+import android.ranging.RangingData+import android.ranging.RangingDevice+import android.ranging.RangingManager+import android.ranging.RangingPreference+import android.ranging.RangingSession+import android.ranging.SensorFusionParams+import android.ranging.SessionConfig+import android.ranging.raw.RawInitiatorRangingConfig+import android.ranging.raw.RawRangingDevice+import android.ranging.raw.RawResponderRangingConfig+import android.ranging.uwb.UwbAddress+import android.ranging.uwb.UwbComplexChannel+import android.ranging.uwb.UwbRangingParams+import android.util.Log+import androidx.annotation.RequiresApi+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.callbackFlow+import java.util.UUID+import java.util.concurrent.Executor+import java.util.concurrent.Executors+import kotlin.io.encoding.Base64+import kotlin.random.Random++/**+ * Thin wrapper around `android.ranging.RangingManager` (the public AOSP+ * ranging API introduced in Android 15 / API 35).+ *+ * This API is the on-device, third-party-callable replacement for the+ * legacy `androidx.core.uwb` library, which only ever shipped a GMS-mediated+ * backend and therefore doesn't work on GrapheneOS / non-GMS Android.+ *+ * One instance per ranging session — call [openController] OR [openControlee]+ * to generate the local FiRa params, then [stream] to actually start ranging+ * once the peer's params have been exchanged out-of-band.+ */+@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)  // API 35 / Android 15+class UwbController(context: Context) {++    private val manager: RangingManager? =+        context.getSystemService(RangingManager::class.java)+    private val executor: Executor = Executors.newSingleThreadExecutor()++    private var session: RangingSession? = null+    private val _state: MutableStateFlow<State> = MutableStateFlow(State.Idle)+    val state: StateFlow<State> = _state.asStateFlow()++    /**+     * The configuration tier we last successfully opened a session with on+     * this device. Cached so we don't keep retrying the rejected config on+     * every ranging session. -1 = haven't tried yet.+     */+    private var lastWorkingTier: Int = -1++    sealed interface State {+        data object Idle : State+        data object Opening : State+        data class Ready(val localAddress: ByteArray) : State+        data class Failed(val reason: String) : State+    }++    /**+     * "Open" as the initiator. Generates local FiRa parameters (address,+     * channel, preamble, session id, session key). No system call yet —+     * `RangingManager.createRangingSession()` happens in [stream] once we+     * know the peer's address from the ACK envelope.+     */+    fun openController(): Result<ControllerInfo> {+        if (manager == null) {+            val msg = "RangingManager system service unavailable"+            _state.value = State.Failed(msg)+            return Result.failure(IllegalStateException(msg))+        }+        _state.value = State.Opening+        // Generate our local UWB MAC address (2 bytes). Avoid the reserved+        // FiRa addresses 0x00/0xFF.+        val localAddress = ByteArray(2).also {+            Random.nextBytes(it)+            if (it[0] == 0.toByte() && it[1] == 0.toByte()) it[1] = 1+        }+        val info = ControllerInfo(+            localAddress = localAddress,+            channelNumber = DEFAULT_CHANNEL,+            preambleIndex = DEFAULT_PREAMBLE,+            sessionId = Random.nextInt(),+            sessionKey = Random.nextBytes(8),+            uuid = UUID.randomUUID()+        )+        _state.value = State.Ready(info.localAddress)+        return Result.success(info)+    }++    /**+     * "Open" as the responder. Generates the local UWB MAC address only —+     * all other params come from the peer's REQUEST envelope.+     */+    fun openControlee(): Result<ByteArray> {+        if (manager == null) {+            val msg = "RangingManager system service unavailable"+            _state.value = State.Failed(msg)+            return Result.failure(IllegalStateException(msg))+        }+        _state.value = State.Opening+        val addr = ByteArray(2).also {+            Random.nextBytes(it)+            if (it[0] == 0.toByte() && it[1] == 0.toByte()) it[1] = 1+        }+        _state.value = State.Ready(addr)+        return Result.success(addr)+    }++    /**+     * Begin ranging. Builds the [RangingPreference] from the agreed FiRa+     * params and opens a `RangingSession` through `RangingManager`. The+     * returned [Flow] emits a sample for each `onResults` callback and a+     * "peer disconnected" marker for `onStopped` / `onClosed`. Cancelling+     * collection or calling [stop] closes the session.+     *+     * @param role one of [Role.Initiator] / [Role.Responder] — drives the+     *   `RangingPreference.DEVICE_ROLE_*` selection.+     * @param localAddress this device's MAC address (2 bytes).+     * @param peerAddress the peer's MAC address (2 bytes).+     * @param sessionId same on both ends; chosen by the initiator.+     * @param sessionKey same 8 bytes on both ends; chosen by the initiator.+     * @param channelNumber same on both ends; chosen by the initiator.+     * @param preambleIndex same on both ends; chosen by the initiator.+     * @param peerUuid an arbitrary unique id used by `android.ranging` to+     *   key the peer in callbacks — same on both ends would be nice but not+     *   required; we use a deterministic-ish UUID derived from sessionId.+     */+    fun stream(+        role: Role,+        localAddress: ByteArray,+        peerAddress: ByteArray,+        sessionId: Int,+        sessionKey: ByteArray,+        channelNumber: Int,+        preambleIndex: Int,+        peerUuid: UUID = UUID(0L, sessionId.toLong())+    ): Flow<RangingSample> = callbackFlow {+        val mgr = manager ?: run {+            trySend(+                RangingSample(+                    null, null, null, System.nanoTime(),+                    peerDisconnected = true+                )+            )+            close()+            return@callbackFlow+        }++        val uwbParams = UwbRangingParams.Builder(+            /* sessionId = */ sessionId,+            /* configId = */ UwbRangingParams.CONFIG_UNICAST_DS_TWR,+            /* deviceAddress = */ UwbAddress.fromBytes(localAddress),+            /* peerAddress = */ UwbAddress.fromBytes(peerAddress)+        )+            .setComplexChannel(+                UwbComplexChannel.Builder()+                    .setChannel(channelNumber)+                    .setPreambleIndex(preambleIndex)+                    .build()+            )+            .setSessionKeyInfo(sessionKey)+            // ~5 Hz instead of the default ~1 Hz. Smoother distance/direction+            // updates and seems to keep the radio from settling on a stale+            // sample when the peer briefly drops out of forward FOV.+            // (The UPDATE_RATE_* constants live on RawRangingDevice, not on+            // UwbRangingParams — the setter is on UwbRangingParams.Builder.)+            .setRangingUpdateRate(RawRangingDevice.UPDATE_RATE_FREQUENT)+            // (We intentionally don't call setSlotDuration here — DURATION_1_MS+            // is unsupported by older UWB stacks like the Pixel 7 Pro's and+            // causes the whole session to fail with REASON_UNSUPPORTED. Let+            // the radio pick its default slot duration.)+            .build()++        val rawDevice = RawRangingDevice.Builder()+            .setRangingDevice(RangingDevice.Builder().setUuid(peerUuid).build())+            .setUwbRangingParams(uwbParams)+            .build()++        // Try the richest SessionConfig that the device hasn't rejected.+        // Tier 2 = AoA + DIRECTIONAL antenna + IMU sensor fusion (best AoA — this+        //         is what Find My / Apple Precision Finding use to disambiguate+        //         the front/back hemisphere and stabilise the arrow).+        // Tier 1 = AoA + IMU sensor fusion only (drop the antenna mode flag).+        // Tier 0 = AoA only (Pixel 7 Pro et al. only accept this).+        // We start one tier above whatever last worked (in case the radio became+        // available again) and degrade until the session opens successfully.+        val startTier = if (lastWorkingTier >= 0) (lastWorkingTier + 1).coerceAtMost(2) else 2+        Log.i(TAG, "stream: opening session at tier=$startTier (last working was $lastWorkingTier)")+        var currentTier = startTier++        val callback = object : RangingSession.Callback {+            override fun onOpened() {+                Log.i(TAG, "RangingSession.onOpened (tier=$currentTier)")+                lastWorkingTier = currentTier+            }+            override fun onOpenFailed(reason: Int) {+                Log.e(TAG, "RangingSession.onOpenFailed(reason=$reason, tier=$currentTier). Reasons: 0=UNKNOWN 1=LOCAL_REQUEST 2=REMOTE_REQUEST 3=UNSUPPORTED 4=SYSTEM_POLICY 5=NO_PEERS_FOUND")+                // If REASON_UNSUPPORTED, this config tier was rejected by the+                // radio. Drop one tier and retry, until we hit tier 0 (AoA-only).+                if (reason == 3 && currentTier > 0) {+                    currentTier -= 1+                    Log.w(TAG, "Retrying at tier=$currentTier")+                    runCatching { session?.close() }+                    val newConfig = preferenceForTier(currentTier, role, rawDevice)+                    val newSession = mgr.createRangingSession(executor, this)+                    if (newSession != null) {+                        session = newSession+                        newSession.start(newConfig)+                    }+                    return+                }+                trySend(+                    RangingSample(+                        null, null, null, System.nanoTime(),+                        peerDisconnected = true+                    )+                )+                close(IllegalStateException("RangingSession open failed (reason=$reason)"))+            }+            override fun onStarted(peer: RangingDevice, technology: Int) {}+            override fun onStopped(peer: RangingDevice, technology: Int) {+                trySend(+                    RangingSample(+                        null, null, null, System.nanoTime(),+                        peerDisconnected = true+                    )+                )+            }+            override fun onClosed(reason: Int) {+                trySend(+                    RangingSample(+                        null, null, null, System.nanoTime(),+                        peerDisconnected = true+                    )+                )+                close()+            }+            override fun onResults(peer: RangingDevice, data: RangingData) {+                val d = data.distance+                val az = data.azimuth+                val el = data.elevation+                // RangingMeasurement.measurement is in RADIANS on android.ranging.+                val rawAzDeg = az?.measurement?.let { Math.toDegrees(it).toFloat() }+                // 2-antenna AoA (Pixel 9 Pro XL etc.) has an inherent+                // front/back ambiguity — for a peer at azimuth α the radio+                // CAN'T distinguish it from a peer at (180° − α). So the+                // reading oscillates between e.g. 0° and 180°. Fold every+                // sample into the front hemisphere [-90°, +90°]; we assume+                // the user is pointing the phone at the peer (otherwise why+                // open the Find screen?). 3-antenna arrays (Pixel 7 Pro)+                // already give values inside [-90°, +90°] so the fold is a+                // no-op there.+                val foldedAzDeg = rawAzDeg?.let { v ->+                    when {+                        v > 90f -> 180f - v+                        v < -90f -> -180f - v+                        else -> v+                    }+                }+                // Filter out low-confidence individual measurements per-axis.+                // CONFIDENCE_LOW=0, CONFIDENCE_MEDIUM=1, CONFIDENCE_HIGH=2.+                // We keep MEDIUM and HIGH; drop LOW (the radio's own "this+                // is junk" signal). Each axis is filtered independently so+                // we can show distance even when the angles are noisy.+                val distOk = (d?.confidence ?: 0) >= 1+                val azOk = (az?.confidence ?: 0) >= 1+                val elOk = (el?.confidence ?: 0) >= 1+                Log.i(+                    TAG,+                    "onResults: dist=${d?.measurement} (conf=${d?.confidence})  raw_az=$rawAzDeg (conf=${az?.confidence})  folded_az=$foldedAzDeg  el=${el?.measurement} (conf=${el?.confidence})  rssi=${runCatching { data.rssi }.getOrNull()}"+                )+                trySend(+                    RangingSample(+                        distanceMeters = if (distOk) d?.measurement?.toFloat() else null,+                        azimuthDeg = if (azOk) foldedAzDeg else null,+                        elevationDeg = if (elOk) el?.measurement?.let { Math.toDegrees(it).toFloat() } else null,+                        timestampNanos = System.nanoTime()+                    )+                )+            }+        }++        val newSession = mgr.createRangingSession(executor, callback)+        if (newSession == null) {+            trySend(+                RangingSample(+                    null, null, null, System.nanoTime(),+                    peerDisconnected = true+                )+            )+            close(IllegalStateException("RangingManager.createRangingSession returned null"))+            return@callbackFlow+        }+        session = newSession+        newSession.start(preferenceForTier(startTier, role, rawDevice))++        awaitClose {+            runCatching { session?.stop() }+            runCatching { session?.close() }+            session = null+        }+    }++    /**+     * Build the SessionConfig + RangingPreference for the given tier:+     *+     *  tier 2: AoA + DIRECTIONAL antenna mode + IMU sensor fusion+     *          (best AoA quality — hemisphere-disambiguated, smooth)+     *  tier 1: AoA + IMU sensor fusion+     *  tier 0: AoA only (works on every device but ambiguous on 2-antenna arrays)+     *+     * If the radio rejects a higher tier with REASON_UNSUPPORTED we drop one+     * and retry. This way Pixel 7 Pro lands on tier 0 (its UWB stack rejects+     * antenna mode + sensor fusion) while Pixel 9 Pro XL gets the full+     * Find-My-grade tier 2.+     */+    private fun preferenceForTier(+        tier: Int,+        role: Role,+        rawDevice: RawRangingDevice,+    ): RangingPreference {+        val sessionConfig = SessionConfig.Builder()+            .setAngleOfArrivalNeeded(true)+            .apply {+                if (tier >= 2) {+                    runCatching { setAntennaMode(SessionConfig.ANTENNA_MODE_DIRECTIONAL) }+                        .onFailure { Log.w(TAG, "setAntennaMode unavailable: ${it.message}") }+                }+                if (tier >= 1) {+                    runCatching {+                        setSensorFusionParams(+                            SensorFusionParams.Builder()+                                .setSensorFusionEnabled(true)+                                .build()+                        )+                    }.onFailure { Log.w(TAG, "setSensorFusionParams unavailable: ${it.message}") }+                }+            }+            .build()+        return when (role) {+            Role.Initiator -> RangingPreference.Builder(+                RangingPreference.DEVICE_ROLE_INITIATOR,+                RawInitiatorRangingConfig.Builder()+                    .addRawRangingDevice(rawDevice)+                    .build()+            )+                .setSessionConfig(sessionConfig)+                .build()+            Role.Responder -> RangingPreference.Builder(+                RangingPreference.DEVICE_ROLE_RESPONDER,+                RawResponderRangingConfig.Builder()+                    .setRawRangingDevice(rawDevice)+                    .build()+            )+                .setSessionConfig(sessionConfig)+                .build()+        }+    }++    fun stop() {+        runCatching { session?.stop() }+        runCatching { session?.close() }+        session = null+        _state.value = State.Idle+    }++    data class ControllerInfo(+        val localAddress: ByteArray,+        val channelNumber: Int,+        val preambleIndex: Int,+        val sessionId: Int,+        val sessionKey: ByteArray,+        val uuid: UUID,+    )++    enum class Role { Initiator, Responder }++    companion object {+        private const val TAG = "UwbController"+        /** FiRa channel 9 (the most common UWB channel; supported by every iPhone with U1/U2). */+        const val DEFAULT_CHANNEL: Int = 9+        /** Default FiRa preamble code index that pairs with channel 9. */+        const val DEFAULT_PREAMBLE: Int = 10+    }+}++/**+ * Simplified per-update sample emitted by [UwbController.stream].+ *+ * - [distanceMeters]: null when the latest event is a "peer disconnected" marker.+ * - [azimuthDeg] / [elevationDeg]: null when direction information isn't+ *   available (peer outside forward FOV, or device lacks AoA support).+ */+data class RangingSample(+    val distanceMeters: Float?,+    val azimuthDeg: Float?,+    val elevationDeg: Float?,+    val timestampNanos: Long,+    val peerDisconnected: Boolean = false+)++/** Helpers for byte-array <-> base64 round-tripping in [UwbHandshake]. */+internal object UwbBytes {+    fun b64(bytes: ByteArray): String = Base64.encode(bytes)+    fun from(b64: String): ByteArray = Base64.decode(b64)+}
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.ktnew file mode 100644index 0000000000..f65d18664c--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt@@ -0,0 +1,69 @@+package com.vayunmathur.findfamily.uwb++import kotlinx.serialization.Serializable++/**+ * Wire format for UWB session-setup messages sent through the existing+ * E2E-encrypted UWB endpoints.+ *+ * Only the small handshake (request / ack / config / cancel) flows over the+ * server; all RangingResult samples flow peer-to-peer over the UWB radio+ * after the session is established.+ *+ * (NB: avoid writing literal `/ api / uwb / *` patterns in KDoc blocks —+ * Kotlin's block comments are nestable, so the embedded `slash-star` opens+ * a nested comment that breaks the whole file.)+ */+@Serializable+data class UwbEnvelope(+    /** Random UUID identifying this ranging session end-to-end. */+    val sessionId: String,+    /** The userid (signed long, encoded as ULong on the wire) of the sender. */+    val sender: ULong,+    /** Sender's platform tag: `"android"` or `"ios"`. */+    val senderPlatform: String,+    /** Envelope kind: `"request"`, `"ack"`, `"config"`, `"cancel"`. */+    val kind: String,+    /** Optional payload — see [UwbHandshake]. */+    val payload: UwbHandshake? = null+)++/**+ * Cross-platform UWB handshake payload. Fields are populated based on the+ * pairing — iOS↔iOS uses [discoveryTokenB64], Android↔Android uses the FiRa+ * fields, Android↔iOS uses the accessory-protocol fields.+ *+ * All fields are nullable so a single struct works for every pairing and the+ * JSON decoder tolerates older senders.+ */+@Serializable+data class UwbHandshake(+    // --- Android↔Android FiRa fields ---+    /** Local UWB MAC address of the sender (2 bytes), base64-encoded. */+    val addressB64: String? = null,+    /** FiRa complex-channel number chosen by the controller. */+    val channelNumber: Int? = null,+    /** FiRa preamble index chosen by the controller. */+    val preambleIndex: Int? = null,+    /** Random 8-byte session key chosen by the controller, base64-encoded. */+    val sessionKeyB64: String? = null,+    /** FiRa session id (Int) chosen by the controller. */+    val sessionId: Int? = null,++    // --- iOS↔iOS NearbyInteraction fields ---+    /** NIDiscoveryToken archived via NSKeyedArchiver, base64. */+    val discoveryTokenB64: String? = null,++    // --- Cross-platform (Phase 5) Apple accessory-protocol fields ---+    /** "accessoryData" sent Android → iOS at session start. */+    val accessoryConfigDataB64: String? = null,+    /** "shareableConfigurationData" sent iOS → Android. */+    val shareableConfigDataB64: String? = null,+)++object UwbEnvelopeKind {+    const val REQUEST = "request"+    const val ACK = "ack"+    const val CONFIG = "config"+    const val CANCEL = "cancel"+}
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbInbox.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbInbox.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbInbox.ktnew file mode 100644index 0000000000..0a5c8bed9e--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbInbox.kt@@ -0,0 +1,54 @@+package com.vayunmathur.findfamily.uwb++import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.asSharedFlow+import java.util.concurrent.ConcurrentHashMap++/**+ * Process-global UWB envelope inbox.+ *+ * Producer: [com.vayunmathur.findfamily.util.LocationTrackingService] drains+ *   `/api/uwb/receive` once per heartbeat tick and [emit]s each envelope here.+ *+ * Consumer: [com.vayunmathur.findfamily.util.FindFamilyViewModel] subscribes+ *   while the Precision Finding screen is open to drive the WaitingForPeer+ *   handshake. When the VM isn't alive (e.g. peer wakes a backgrounded app),+ *   the service itself posts a notification offering to open the screen.+ *+ * SharedFlow with replay = 0 + a small buffer: envelopes are one-shot; missed+ * envelopes (e.g. screen closed before they arrived) are dropped on the floor+ * intentionally — EXCEPT incoming `REQUEST` envelopes, which we cache in+ * [pendingRequests] so a notification-launched screen can find them.+ */+object UwbInbox {+    private val _flow = MutableSharedFlow<UwbEnvelope>(extraBufferCapacity = 16)+    val flow: SharedFlow<UwbEnvelope> = _flow.asSharedFlow()++    /** Most-recent REQUEST envelope from each peer, keyed by sender userid (signed long). */+    private val pendingRequests = ConcurrentHashMap<Long, UwbEnvelope>()++    suspend fun emit(envelope: UwbEnvelope) {+        cacheIfRequest(envelope)+        _flow.emit(envelope)+    }++    /** Non-suspending emit used from non-coroutine call sites. Returns false on overflow. */+    fun tryEmit(envelope: UwbEnvelope): Boolean {+        cacheIfRequest(envelope)+        return _flow.tryEmit(envelope)+    }++    /** Retrieve and remove the most recent pending REQUEST from [peerUserId], if any. */+    fun consumePendingRequest(peerUserId: Long): UwbEnvelope? =+        pendingRequests.remove(peerUserId)++    private fun cacheIfRequest(envelope: UwbEnvelope) {+        if (envelope.kind == UwbEnvelopeKind.REQUEST) {+            pendingRequests[envelope.sender.toLong()] = envelope+        } else if (envelope.kind == UwbEnvelopeKind.CANCEL) {+            // Cancel from peer invalidates any pending request from them.+            pendingRequests.remove(envelope.sender.toLong())+        }+    }+}
library/src/main/res/drawable/navigation_24px.xml
diff --git a/library/src/main/res/drawable/navigation_24px.xml b/library/src/main/res/drawable/navigation_24px.xmlnew file mode 100644index 0000000000..7c74c904cf--- /dev/null+++ b/library/src/main/res/drawable/navigation_24px.xml@@ -0,0 +1,14 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+    <!-- Upward-pointing navigation arrow (Material "Near Me" style).+         Used by FindFamily's UWB Precision Finding screen and the top-bar+         "Find with Precision" button. The arrow is rotated by the peer's+         azimuth via Modifier.graphicsLayer { rotationZ = azimuth }. -->+    <path+        android:fillColor="@android:color/white"+        android:pathData="M12,2 L19,21 L12,17 L5,21 Z" />+</vector>