findfamily: UWB precision finding between own phone and watch
- Commit
c69a6c364df93d2684008874affbe87e48796784- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 16:14 UTC (44 minutes ago)
- Parents
018affb
Own devices can find each other over UWB, as a device-only feature beside Ring: 'Find watch' on the phone device card (Route.DeviceFindWatch, live distance with an azimuth arrow when the hardware reports it) and 'Find phone' on the watch people screen. Member/person surfaces never offer it. Session coordination rides the conduit as messages (/findfamily/device-uwb, WearDeviceUwbMessage): the finder (controller) sends session id/channel/preamble/key and its address, the found device replies with its address, and ranging then runs locally between the two devices with no backend involvement. DeviceUwbCoordinator implements both roles on both sides, so finding is symmetric. Ranging sits behind the DeviceUwbRanger seam over the existing API-36 UwbController stack. Availability is UwbSessionManager.isAvailable (SDK 36 + FEATURE_UWB, the already-declared RANGING permission); a pair without UWB - including a watch without it - degrades to an honest 'UWB not available on this pair' state while location and ring keep working. Where azimuth is absent the UI is distance-only by design. The ranging UI state (median-of-last-5 smoothing, 5-second stale labelling) is pure in domain/DeviceUwbFinding and tested with fake samples; the conduit session-param types round-trip in DeviceUwbFindingTest, and DeviceFindContent renders the ranging and unavailable states. A new 15-device-find-watch listing preview covers the route; findfamily metadata was regenerated (renders 18 images; untracked intermediate listing PNGs are not committed, per repo convention). Verified on the stack: :findfamily:lint, :findfamily:lintVitalRelease, :findfamily:testDevUnitTest, :library:wearlink:lint and :library:wearlink:testDevUnitTest all pass.
Diff
findfamily/AGENTS.md
diff --git a/findfamily/AGENTS.md b/findfamily/AGENTS.mdindex 5a05e7286c..d5c267debf 100644--- a/findfamily/AGENTS.md+++ b/findfamily/AGENTS.md@@ -66,6 +66,24 @@ location sharing never starts there. (`wear-findfamily-snapshot.json`); presentation helpers live in `domain/WearRelative.kt`; the watch sync side is `sync/WearLinkBridge.kt`.+- Own-device companion features (device surfaces only, never member/person+ surfaces): the paired watch is presented on the phone as "Your watch"+ (device card in the family list and on the self sheet, plus a distinct+ watch map marker), fed by the watch's conduit fix at+ `/findfamily/watch-location` (`sync/WatchLocationPublisher`, cadence in+ `domain/WatchLocationCadence`: first fix, then 5 min / 100 m / 15 min,+ via app-open + `sync/WatchLocationWorker`). That fix is own-device+ awareness only: the member location published to other members is+ always the phone's position and the watch fix never enters it. Ring is+ device-only: phone rings watch / watch rings phone as conduit messages+ at `/findfamily/ring` (`platform/RingController`, alarm-stream ringtone+ + vibration, 60 s TTL on receive and 60 s auto-stop, notification Stop).+ UWB precision finding is device-only: "Find watch" (`Route.DeviceFindWatch`+ -> `ui/DeviceFindScreen`) / watch "Find phone", session params exchanged+ over `/findfamily/device-uwb` (`sync/DeviceUwbCoordinator`,+ `platform/DeviceUwbFinder` seam over the API-36 `UwbController`;+ distance always, azimuth arrow when present; unavailable pairs degrade+ honestly). Person/member panels never offer ring or UWB finding. - Watch listing screenshots are the `group = "wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt`, collected by `:findfamily:metadata` into `metadata_data/photos/findfamily/wear/`;@@ -94,6 +112,17 @@ location sharing never starts there. - com/vayunmathur/findfamily/domain/NoShowPolicy.kt - com/vayunmathur/findfamily/domain/MovementDetector.kt — sender moving/still state machine (acceleration + fix speed + displacement) - com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt — when a "still" sender forces a one-off fix+### device/ companion features (in sync/ + platform/ + domain/)+- com/vayunmathur/findfamily/sync/WatchLocationPublisher.kt — watch-location acquisition (LocationManager, permission-gated, cadence-gated)+- com/vayunmathur/findfamily/sync/WatchLocationWorker.kt — 15-min periodic watch-location publish (watch only)+- com/vayunmathur/findfamily/data/WatchDeviceLocationStore.kt — phone-side latest watch-companion fix (local only)+- com/vayunmathur/findfamily/platform/RingController.kt — ring audio seam (`RingAudioPlayer`) + Android alarm-stream player, auto-stop, Stop notification+- com/vayunmathur/findfamily/platform/DeviceUwbFinder.kt — UWB capability/ranging seam (`DeviceUwbRanger`)+- com/vayunmathur/findfamily/sync/DeviceUwbCoordinator.kt — conduit session-param exchange + local ranging collection+- com/vayunmathur/findfamily/domain/WatchLocationCadence.kt — watch cadence + `RingPolicy`; `domain/DeviceUwbFinding.kt` — smoothing/stale state+- com/vayunmathur/findfamily/ui/WatchDeviceCard.kt — "Your watch" device card (Ring/Find device actions only)+- com/vayunmathur/findfamily/ui/DeviceFindScreen.kt — live UWB find view for the paired watch+ ### sync/ — wear companion (both sides in this APK) - com/vayunmathur/findfamily/sync/WearFindFamilySync.kt — phone conduit client node; all-people snapshot publish from decrypted Room state, watch-state receive, request-sync + op handling - com/vayunmathur/findfamily/sync/WearLinkBridge.kt — watch conduit client node; snapshot receive into `data/WearFindFamilyStore`, watch-state publish, stop-sharing/refresh/request-sync messages to the phone
findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.ktindex d4fd88b05a..428f8ad4cf 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt@@ -10,6 +10,7 @@ import com.vayunmathur.findfamily.ui.FirstRunSheet import com.vayunmathur.findfamily.ui.MainPage import com.vayunmathur.findfamily.ui.PersonHistoryPage import com.vayunmathur.findfamily.ui.UwbRangingScreen+import com.vayunmathur.findfamily.ui.DeviceFindScreen import com.vayunmathur.findfamily.ui.dialogs.AddLinkDialog import com.vayunmathur.findfamily.ui.dialogs.AddPersonDialog import com.vayunmathur.findfamily.ui.dialogs.AddTrackerDialog@@ -142,6 +143,9 @@ fun Navigation( entry<Route.UwbRangingPage> { UwbRangingScreen(backStack, ffViewModel, it.userId) }+ entry<Route.DeviceFindWatch> {+ DeviceFindScreen(backStack)+ } entry<Route.NoShowAlertDialog>(metadata = DialogPage()) { val users by ffViewModel.users.collectAsState() val waypoints by ffViewModel.waypoints.collectAsState()
findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/Route.ktindex a8bc609d86..dacfda718d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt@@ -51,6 +51,10 @@ sealed interface Route: NavKey { @Serializable data class UwbRangingPage(val userId: Long): Route + @Serializable+ /** Full-screen UWB precision finding of the owner's paired watch (device-only, never a member). */+ data object DeviceFindWatch: Route+ @Serializable /** Dialog for setting a no-show watch for the given person. */ data class NoShowAlertDialog(val userId: Long): Route
findfamily/src/main/java/com/vayunmathur/findfamily/domain/DeviceUwbFinding.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/DeviceUwbFinding.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/DeviceUwbFinding.ktnew file mode 100644index 0000000000..e047f520bd--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/DeviceUwbFinding.kt@@ -0,0 +1,39 @@+package com.vayunmathur.findfamily.domain++/** One UWB ranging sample for an own-device find session. */+data class DeviceUwbSample(+ val distanceMeters: Double?,+ val azimuthDeg: Double?,+ val atMillis: Long,+)++/** UI state for finding an own device (phone <-> watch) over UWB. Device-only, never a member feature. */+sealed interface DeviceUwbState {+ data object Unavailable : DeviceUwbState+ data object Searching : DeviceUwbState+ data class Ranging(val distanceMeters: Double, val azimuthDeg: Double?, val stale: Boolean = false) : DeviceUwbState+}++/** Distance smoothing (median of the last samples) and stale handling for the ranging UI. */+object DeviceUwbSmoothing {+ const val STALE_AFTER_MS = 5_000L+ const val WINDOW = 5++ fun smoothedDistance(samples: List<DeviceUwbSample>): Double? {+ val distances = samples.mapNotNull { it.distanceMeters }.takeLast(WINDOW).sorted()+ if (distances.isEmpty()) return null+ return distances[distances.size / 2]+ }++ fun state(samples: List<DeviceUwbSample>, nowMillis: Long, available: Boolean): DeviceUwbState {+ if (!available) return DeviceUwbState.Unavailable+ val last = samples.lastOrNull { it.distanceMeters != null } ?: return DeviceUwbState.Searching+ val distance = smoothedDistance(samples) ?: return DeviceUwbState.Searching+ val azimuth = samples.lastOrNull { it.azimuthDeg != null }?.azimuthDeg+ return DeviceUwbState.Ranging(+ distanceMeters = distance,+ azimuthDeg = azimuth,+ stale = nowMillis - last.atMillis > STALE_AFTER_MS,+ )+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/DeviceUwbFinder.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/DeviceUwbFinder.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/DeviceUwbFinder.ktnew file mode 100644index 0000000000..9c6d8d8290--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/DeviceUwbFinder.kt@@ -0,0 +1,89 @@+package com.vayunmathur.findfamily.platform++import android.content.Context+import android.os.Build+import com.vayunmathur.findfamily.domain.DeviceUwbSample+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.emptyFlow+import kotlinx.coroutines.flow.map++/** Capability + ranging seam for own-device UWB finding, so UI/state logic is testable with a fake. */+interface DeviceUwbRanger {+ fun isAvailable(context: Context): Boolean+ fun controllerParams(context: Context): ControllerParams?+ fun controleeAddress(context: Context): ByteArray?+ fun range(+ context: Context,+ role: Role,+ localAddress: ByteArray,+ peerAddress: ByteArray,+ sessionId: Int,+ sessionKey: ByteArray,+ channel: Int,+ preamble: Int,+ ): Flow<DeviceUwbSample>++ enum class Role { Controller, Controlee }++ data class ControllerParams(+ val localAddress: ByteArray,+ val sessionId: Int,+ val sessionKey: ByteArray,+ val channel: Int,+ val preamble: Int,+ )+}++/**+ * Android ranger over the existing API-36 [UwbController] stack. Availability+ * is [UwbSessionManager.isAvailable] (SDK 36+ and FEATURE_UWB); on any pair+ * without it (including watches without UWB) finding degrades to+ * "UWB not available on this pair" and location/ring keep working.+ */+object AndroidDeviceUwbRanger : DeviceUwbRanger {+ override fun isAvailable(context: Context): Boolean = UwbSessionManager.isAvailable(context)++ override fun controllerParams(context: Context): DeviceUwbRanger.ControllerParams? {+ if (!isAvailable(context) || Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) return null+ val info = UwbController(context).openController().getOrNull() ?: return null+ return DeviceUwbRanger.ControllerParams(+ localAddress = info.localAddress,+ sessionId = info.sessionId,+ sessionKey = info.sessionKey,+ channel = info.channelNumber,+ preamble = info.preambleIndex,+ )+ }++ override fun controleeAddress(context: Context): ByteArray? {+ if (!isAvailable(context) || Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) return null+ return UwbController(context).openControlee().getOrNull()+ }++ override fun range(+ context: Context,+ role: DeviceUwbRanger.Role,+ localAddress: ByteArray,+ peerAddress: ByteArray,+ sessionId: Int,+ sessionKey: ByteArray,+ channel: Int,+ preamble: Int,+ ): Flow<DeviceUwbSample> {+ if (!isAvailable(context) || Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) return emptyFlow()+ val controller = UwbController(context)+ val uwbRole = if (role == DeviceUwbRanger.Role.Controller) {+ UwbController.Role.Initiator+ } else {+ UwbController.Role.Responder+ }+ return controller.stream(uwbRole, localAddress, peerAddress, sessionId, sessionKey, channel, preamble)+ .map { sample ->+ DeviceUwbSample(+ distanceMeters = sample.distanceMeters?.toDouble(),+ azimuthDeg = sample.azimuthDeg?.toDouble(),+ atMillis = System.currentTimeMillis(),+ )+ }+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/sync/DeviceUwbCoordinator.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/sync/DeviceUwbCoordinator.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/DeviceUwbCoordinator.ktnew file mode 100644index 0000000000..b50a9d7471--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/DeviceUwbCoordinator.kt@@ -0,0 +1,118 @@+package com.vayunmathur.findfamily.sync++import android.content.Context+import com.vayunmathur.findfamily.domain.DeviceUwbSample+import com.vayunmathur.findfamily.platform.AndroidDeviceUwbRanger+import com.vayunmathur.findfamily.platform.DeviceUwbRanger+import com.vayunmathur.library.wearlink.findfamily.WearDeviceUwbKind+import com.vayunmathur.library.wearlink.findfamily.WearDeviceUwbMessage+import kotlin.io.encoding.Base64+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.launch++/**+ * Coordinates an own-device UWB find session over the conduit: session+ * params/address exchange as conduit messages, ranging locally via+ * [DeviceUwbRanger]. No backend involvement. Either side can be controller+ * (finder) or controlee (found device), so phone->watch and watch->phone+ * finding are symmetric.+ */+object DeviceUwbCoordinator {+ var ranger: DeviceUwbRanger = AndroidDeviceUwbRanger+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private var rangingJob: Job? = null+ private var pendingController: DeviceUwbRanger.ControllerParams? = null++ private val _samples = MutableStateFlow<List<DeviceUwbSample>>(emptyList())+ val samples: StateFlow<List<DeviceUwbSample>> = _samples.asStateFlow()++ private val _active = MutableStateFlow(false)+ val active: StateFlow<Boolean> = _active.asStateFlow()++ fun isAvailable(context: Context): Boolean = ranger.isAvailable(context)++ /** Start finding the paired device: become controller and send the session params. */+ suspend fun startFinding(context: Context, send: suspend (WearDeviceUwbMessage) -> Boolean): Boolean {+ val params = ranger.controllerParams(context) ?: return false+ pendingController = params+ _samples.value = emptyList()+ return send(+ WearDeviceUwbMessage(+ kind = WearDeviceUwbKind.FIND_REQUEST,+ sessionId = params.sessionId,+ channel = params.channel,+ preamble = params.preamble,+ sessionKeyB64 = Base64.encode(params.sessionKey),+ localAddressB64 = Base64.encode(params.localAddress),+ requestedAtMillis = System.currentTimeMillis(),+ ),+ )+ }++ suspend fun stopFinding(send: suspend (WearDeviceUwbMessage) -> Boolean) {+ send(WearDeviceUwbMessage(kind = WearDeviceUwbKind.FIND_STOP, requestedAtMillis = System.currentTimeMillis()))+ stopLocal()+ }++ fun stopLocal() {+ rangingJob?.cancel()+ rangingJob = null+ pendingController = null+ _active.value = false+ }++ /** Handle one conduit UWB message on either side. */+ fun handleMessage(context: Context, message: WearDeviceUwbMessage, send: suspend (WearDeviceUwbMessage) -> Boolean) {+ when (message.kind) {+ WearDeviceUwbKind.FIND_STOP -> stopLocal()+ WearDeviceUwbKind.FIND_REQUEST -> {+ val address = ranger.controleeAddress(context) ?: return+ scope.launch {+ send(+ WearDeviceUwbMessage(+ kind = WearDeviceUwbKind.FIND_ACCEPT,+ sessionId = message.sessionId,+ channel = message.channel,+ preamble = message.preamble,+ sessionKeyB64 = message.sessionKeyB64,+ localAddressB64 = Base64.encode(address),+ requestedAtMillis = System.currentTimeMillis(),+ ),+ )+ val peer = runCatching { Base64.decode(message.localAddressB64) }.getOrNull() ?: return@launch+ val key = runCatching { Base64.decode(message.sessionKeyB64) }.getOrNull() ?: return@launch+ startRanging(context, DeviceUwbRanger.Role.Controlee, address, peer, message.sessionId, key, message.channel, message.preamble)+ }+ }+ WearDeviceUwbKind.FIND_ACCEPT -> {+ val params = pendingController ?: return+ val peer = runCatching { Base64.decode(message.localAddressB64) }.getOrNull() ?: return+ startRanging(context, DeviceUwbRanger.Role.Controller, params.localAddress, peer, params.sessionId, params.sessionKey, params.channel, params.preamble)+ }+ }+ }++ private fun startRanging(+ context: Context,+ role: DeviceUwbRanger.Role,+ local: ByteArray,+ peer: ByteArray,+ sessionId: Int,+ key: ByteArray,+ channel: Int,+ preamble: Int,+ ) {+ rangingJob?.cancel()+ _active.value = true+ rangingJob = scope.launch {+ ranger.range(context.applicationContext, role, local, peer, sessionId, key, channel, preamble)+ .collect { sample -> _samples.value = (_samples.value + sample).takeLast(20) }+ }+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindContent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindContent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindContent.ktnew file mode 100644index 0000000000..9d1b4ccfe1--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindContent.kt@@ -0,0 +1,69 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.foundation.layout.Arrangement+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.runtime.Composable+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.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 com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.domain.DeviceUwbState+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconNavigationArrow+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/** Stateless device-find layout for previews/tests. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DeviceFindContent(state: DeviceUwbState, onBack: () -> Unit) {+ AppScaffold(title = stringResource(R.string.find_watch), onNavigateBack = onBack) { padding ->+ Column(+ Modifier.fillMaxSize().padding(padding).padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ when (state) {+ DeviceUwbState.Unavailable -> Text(+ stringResource(R.string.uwb_unavailable_pair),+ textAlign = TextAlign.Center,+ )+ DeviceUwbState.Searching -> Text(+ stringResource(R.string.searching_device),+ style = MaterialTheme.typography.titleMedium,+ textAlign = TextAlign.Center,+ )+ is DeviceUwbState.Ranging -> {+ if (state.azimuthDeg != null) {+ IconNavigationArrow(+ modifier = Modifier.size(72.dp).graphicsLayer { rotationZ = state.azimuthDeg.toFloat() }+ .alpha(if (state.stale) 0.4f else 1f),+ )+ Spacer(Modifier.height(16.dp))+ }+ Text(+ "%.1f m".format(state.distanceMeters),+ fontSize = 48.sp,+ fontWeight = FontWeight.Bold,+ modifier = Modifier.alpha(if (state.stale) 0.4f else 1f),+ )+ if (state.stale) {+ Text(stringResource(R.string.device_signal_stale), textAlign = TextAlign.Center)+ }+ }+ }+ }+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindScreen.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindScreen.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindScreen.ktnew file mode 100644index 0000000000..cfd679e182--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/DeviceFindScreen.kt@@ -0,0 +1,56 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.foundation.layout.Arrangement+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.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.rememberCoroutineScope+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 com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.Route+import com.vayunmathur.findfamily.domain.DeviceUwbSmoothing+import com.vayunmathur.findfamily.domain.DeviceUwbState+import com.vayunmathur.findfamily.sync.DeviceUwbCoordinator+import com.vayunmathur.findfamily.sync.WearFindFamilySync+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconNavigationArrow+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.launch++/** Live UWB finding of the owner's paired watch. Device-only; no member is ever ranged from here. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DeviceFindScreen(backStack: NavBackStack<Route>) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val samples by DeviceUwbCoordinator.samples.collectAsState()+ val available = DeviceUwbCoordinator.isAvailable(context)+ LaunchedEffect(Unit) {+ scope.launch { WearFindFamilySync.get(context).startFindingWatch() }+ }+ DisposableEffect(Unit) {+ onDispose { DeviceUwbCoordinator.stopLocal() }+ }+ val state = DeviceUwbSmoothing.state(samples, System.currentTimeMillis(), available)+ DeviceFindContent(state = state, onBack = { backStack.pop() })+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageActions.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageActions.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageActions.ktindex 7675d059d5..ad833fb60b 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageActions.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageActions.kt@@ -166,6 +166,8 @@ internal fun rememberMainPageActions( // it already implements; the ones needing the nav stack or the clipboard go here. // Selection actions push the sheet destinations: the back stack is the // single place selection lives.+ val ringContext = LocalContext.current+ val ringScope = rememberCoroutineScope() val familyActions = remember(ffViewModel, backStack, platform) { object : FamilyListActions by ffViewModel { override fun selectUser(userId: Long) {@@ -186,6 +188,18 @@ internal fun rememberMainPageActions( backStack.add(Route.AddPersonDialog(userId)) } + override fun ringWatch() {+ ringScope.launch { WearFindFamilySync.get(ringContext).ringWatch() }+ }++ override fun stopRinging() {+ RingController.stop(ringContext)+ }++ override fun findWatch() {+ backStack.add(com.vayunmathur.findfamily.Route.DeviceFindWatch)+ }+ override fun copyLink(link: TemporaryLink) { // The fragment carries the link's secret and never hits the server. New links // send just the 32-byte ML-KEM seed (`#s=`) with a Base26 id, which fits in an
findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.ktindex e51dce3a33..5cce942734 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt@@ -56,6 +56,10 @@ fun PersonSheet( val globalSharingEnabled by ffViewModel.globalSharingEnabled.collectAsState() val crowdFindingEnabled by ffViewModel.crowdFindingEnabled.collectAsState() val connectedUsers by ffViewModel.connectedUsers.collectAsState()+ val watchLocationState by WatchDeviceLocationStore.get(LocalContext.current).latest.collectAsState()+ val isRingingState by RingController.ringing.collectAsState()+ val personScope = rememberCoroutineScope()+ val personContext = LocalContext.current val requestPickContact = platform.requestPickContact { name, photo -> ffViewModel.updateContactNamePhoto(userId, name, photo)@@ -77,6 +81,18 @@ fun PersonSheet( } val personActions = remember(ffViewModel, ensureLocationSharing, ensureNotifications) { object : PersonActions by ffViewModel {+ override fun ringWatch() {+ personScope.launch { WearFindFamilySync.get(personContext).ringWatch() }+ }++ override fun stopRinging() {+ RingController.stop(personContext)+ }++ override fun findWatch() {+ backStack.add(Route.DeviceFindWatch)+ }+ override fun changeConnectedContact() = requestPickContact() override fun setUserSharing(user: com.vayunmathur.findfamily.data.User, enabled: Boolean) {@@ -116,6 +132,8 @@ fun PersonSheet( globalSharingEnabled, crowdFindingEnabled, connectedUsers,+ watchLocationState,+ isRingingState, ), personActions, onShowNoShowAlert = { backStack.add(Route.NoShowAlertDialog(userId)) },
findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt
diff --git a/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt b/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.ktindex 61edaa0381..d5796fcb80 100644--- a/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt+++ b/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt@@ -39,6 +39,7 @@ import com.vayunmathur.library.ui.rememberHistoryScrubberState import androidx.compose.runtime.CompositionLocalProvider import com.vayunmathur.findfamily.Route import com.vayunmathur.findfamily.domain.FirstRunStage+import com.vayunmathur.findfamily.domain.DeviceUwbState import com.vayunmathur.findfamily.ui.dialogs.AddLinkContent import com.vayunmathur.findfamily.ui.dialogs.AddPersonContent import com.vayunmathur.findfamily.ui.dialogs.AddTrackerContent@@ -452,6 +453,15 @@ class MetadataPreviews { } } + @PreviewTest+ @Preview(name = "15-device-find-watch", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview15DeviceFindWatch() {+ DynamicTheme(darkTheme = true) {+ DeviceFindContent(state = DeviceUwbState.Ranging(2.5, 20.0), onBack = {})+ }+ }+ @PreviewTest @Preview(name = "14-permission-upgrade-dialog", device = PHONE, group = "phone", showSystemUi = true) @Composable
findfamily/src/test/java/com/vayunmathur/findfamily/domain/DeviceUwbFindingTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/DeviceUwbFindingTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/DeviceUwbFindingTest.ktnew file mode 100644index 0000000000..2513e0948e--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/DeviceUwbFindingTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.findfamily.domain++import com.vayunmathur.library.wearlink.findfamily.WearDeviceUwbKind+import com.vayunmathur.library.wearlink.findfamily.WearDeviceUwbMessage+import com.vayunmathur.library.wearlink.findfamily.WearFindFamilyProtocol+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class DeviceUwbFindingTest {++ @Test+ fun sessionParamsRoundTripOverConduitType() {+ val request = WearDeviceUwbMessage(+ kind = WearDeviceUwbKind.FIND_REQUEST,+ sessionId = 42,+ channel = 9,+ preamble = 10,+ sessionKeyB64 = "a2V5",+ localAddressB64 = "AQI=",+ requestedAtMillis = 1_000L,+ )+ val json = WearFindFamilyProtocol.json.encodeToString(request)+ assertEquals(request, WearFindFamilyProtocol.json.decodeFromString<WearDeviceUwbMessage>(json))+ val accept = request.copy(kind = WearDeviceUwbKind.FIND_ACCEPT, localAddressB64 = "AwQ=")+ assertEquals(+ accept,+ WearFindFamilyProtocol.json.decodeFromString<WearDeviceUwbMessage>(WearFindFamilyProtocol.json.encodeToString(accept)),+ )+ }++ @Test+ fun unavailablePairDegradesHonestly() {+ val state = DeviceUwbSmoothing.state(emptyList(), nowMillis = 10_000L, available = false)+ assertEquals(DeviceUwbState.Unavailable, state)+ }++ @Test+ fun searchingUntilFirstDistance() {+ assertEquals(+ DeviceUwbState.Searching,+ DeviceUwbSmoothing.state(emptyList(), nowMillis = 10_000L, available = true),+ )+ }++ @Test+ fun smoothingUsesMedianAndDropsNulls() {+ val samples = listOf(+ DeviceUwbSample(10.0, null, 1_000L),+ DeviceUwbSample(null, 20.0, 2_000L),+ DeviceUwbSample(2.0, null, 3_000L),+ DeviceUwbSample(3.0, 15.0, 4_000L),+ )+ assertEquals(3.0, DeviceUwbSmoothing.smoothedDistance(samples))+ val state = DeviceUwbSmoothing.state(samples, nowMillis = 4_500L, available = true) as DeviceUwbState.Ranging+ assertEquals(3.0, state.distanceMeters)+ assertEquals(15.0, state.azimuthDeg)+ assertFalse(state.stale)+ }++ @Test+ fun staleAfterFiveSecondsWithoutSample() {+ val samples = listOf(DeviceUwbSample(2.0, null, 1_000L))+ val state = DeviceUwbSmoothing.state(+ samples,+ nowMillis = 1_000L + DeviceUwbSmoothing.STALE_AFTER_MS + 1L,+ available = true,+ ) as DeviceUwbState.Ranging+ assertTrue(state.stale)+ }++ @Test+ fun distanceOnlyWhenAzimuthAbsent() {+ val samples = listOf(DeviceUwbSample(1.5, null, 5_000L))+ val state = DeviceUwbSmoothing.state(samples, nowMillis = 5_500L, available = true) as DeviceUwbState.Ranging+ assertEquals(1.5, state.distanceMeters)+ assertEquals(null, state.azimuthDeg)+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/DeviceFindContentTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/DeviceFindContentTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/DeviceFindContentTest.ktnew file mode 100644index 0000000000..20d39311d8--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/DeviceFindContentTest.kt@@ -0,0 +1,29 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.domain.DeviceUwbState+import kotlin.test.Test+import org.junit.Rule+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class DeviceFindContentTest {++ @get:Rule+ val rule = createComposeRule()++ @Test+ fun rangingShowsBigDistance() {+ rule.setContent { DeviceFindContent(DeviceUwbState.Ranging(2.5, null), onBack = {}) }+ rule.onNodeWithText("2.5 m").assertIsDisplayed()+ }++ @Test+ fun unavailableStatesHonestMessage() {+ rule.setContent { DeviceFindContent(DeviceUwbState.Unavailable, onBack = {}) }+ rule.onNodeWithText("UWB is not available", substring = true).assertIsDisplayed()+ }+}