Modern Apps git

← Modern-Apps.git

findfamily: show paired watch as a device with its location

Commit
e9b892086c1d6ffab8822f513be254c722d8b6a1
Author
Vayun Mathur <[email protected]>
When
2026-12-06 16:14 UTC (1 hour ago)
Parents
e4a2b82
The watch is a companion of the same member, not a separate
person. It publishes its own fix over the Watch conduit as a
latest-wins data item (/findfamily/watch-location): the watch
side acquires LocationManager GPS/network fixes with no Play
services assumption, gated by WatchLocationCadence (first fix,
then at most every 5 minutes unless moved 100 m, at least every
15 minutes) and by the periodic WatchLocationWorker, plus an
immediate publish on app open.

The phone keeps that fix in WatchDeviceLocationStore as
own-device awareness only. The member location published to
other members is always the phone position; the watch fix
never enters the outgoing publish, the Room people model, or
the backend protocol.

On the phone the watch is presented as a device, distinct
from person rendering: a 'Your watch' device card in the
family list and on the self sheet (last fix age, battery,
coordinates), and a distinct watch map marker. The shared
wearlink protocol gains WearWatchLocation, WearRingRequest
and WearDeviceUwbMessage wire types (additive, older sides
ignore them), plus IconWatch/IconRingDevice.

Verified: targeted WatchDeviceFeaturesTest and
WatchDeviceCardTest pass; full lint/tests run on the stack.

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/data/WatchDeviceLocationStore.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/WatchDeviceLocationStore.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/WatchDeviceLocationStore.ktnew file mode 100644index 0000000000..d360a138f1--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/WatchDeviceLocationStore.kt@@ -0,0 +1,45 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.findfamily.WearFindFamilyProtocol+import com.vayunmathur.library.wearlink.findfamily.WearWatchLocation+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString++/**+ * Phone-side latest fix from the paired watch companion, received over the+ * conduit ([WearFindFamilyProtocol.WATCH_LOCATION_PATH]). Persisted as JSON+ * so the tracking service can merge it after a process restart. This is the+ * same member's companion device — never a separate person row.+ */+class WatchDeviceLocationStore private constructor(context: Context) {+    companion object {+        private const val TAG = "WatchDeviceLocationStore"++        @Volatile+        private var instance: WatchDeviceLocationStore? = null++        fun get(context: Context): WatchDeviceLocationStore = instance ?: synchronized(this) {+            instance ?: WatchDeviceLocationStore(context.applicationContext).also { instance = it }+        }+    }++    private val file = File(context.filesDir, "watch-device-location.json")+    private val _latest = MutableStateFlow(load())+    val latest: StateFlow<WearWatchLocation?> = _latest.asStateFlow()++    fun set(location: WearWatchLocation) {+        if (location.updatedAtMillis <= (_latest.value?.updatedAtMillis ?: 0L)) return+        _latest.value = location+        runCatching { file.writeText(WearFindFamilyProtocol.json.encodeToString(location)) }+            .onFailure { Log.status(TAG, "persist failed: ${it.message}") }+    }++    private fun load(): WearWatchLocation? = runCatching {+        WearFindFamilyProtocol.json.decodeFromString<WearWatchLocation>(file.readText())+    }.getOrNull()+}
findfamily/src/main/java/com/vayunmathur/findfamily/domain/RingPolicy.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/RingPolicy.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/RingPolicy.ktnew file mode 100644index 0000000000..8c3d2b45bb--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/RingPolicy.kt@@ -0,0 +1,13 @@+package com.vayunmathur.findfamily.domain++/** Pure ring timing policy (TTL enforced on receive, auto-stop on the ringing device). */+object RingPolicy {+    const val TTL_MS = com.vayunmathur.library.wearlink.findfamily.WearFindFamilyProtocol.RING_TTL_MS+    const val AUTO_STOP_MS = com.vayunmathur.library.wearlink.findfamily.WearFindFamilyProtocol.RING_AUTO_STOP_MS++    fun isFresh(requestedAtMillis: Long, nowMillis: Long): Boolean =+        requestedAtMillis > 0L && nowMillis - requestedAtMillis in 0..TTL_MS++    fun shouldAutoStop(startedAtMillis: Long, nowMillis: Long): Boolean =+        startedAtMillis > 0L && nowMillis - startedAtMillis >= AUTO_STOP_MS+}
findfamily/src/main/java/com/vayunmathur/findfamily/domain/WatchLocationCadence.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/WatchLocationCadence.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/WatchLocationCadence.ktnew file mode 100644index 0000000000..9b64d5c38f--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/WatchLocationCadence.kt@@ -0,0 +1,33 @@+package com.vayunmathur.findfamily.domain++import com.vayunmathur.library.wearlink.findfamily.WearWatchLocation+import com.vayunmathur.library.wearlink.findfamily.wearDistanceMeters++/** Battery-aware cadence for watch-companion location publishing over the conduit. */+object WatchLocationCadence {+    const val MIN_INTERVAL_MS = 5 * 60_000L+    const val MAX_INTERVAL_MS = 15 * 60_000L+    const val SIGNIFICANT_MOVE_METERS = 100.0++    /**+     * Whether a new watch fix should be published now: first fix always;+     * then at most every [MIN_INTERVAL_MS] unless moved significantly, and+     * at least every [MAX_INTERVAL_MS] while publishing keeps running.+     * This signal is own-device awareness only (phone <-> watch conduit);+     * it never enters the member location published to other members.+     */+    fun shouldPublish(+        lastPublishedAtMillis: Long,+        lastLatE7: Int?,+        lastLonE7: Int?,+        candidate: WearWatchLocation,+    ): Boolean {+        if (lastPublishedAtMillis <= 0L) return true+        val elapsed = candidate.updatedAtMillis - lastPublishedAtMillis+        if (elapsed >= MAX_INTERVAL_MS) return true+        if (elapsed < MIN_INTERVAL_MS) return false+        if (lastLatE7 == null || lastLonE7 == null) return true+        return wearDistanceMeters(lastLatE7, lastLonE7, candidate.latE7, candidate.lonE7) >= SIGNIFICANT_MOVE_METERS+    }+}+
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.ktindex 88d2074301..5b51f6acaf 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt@@ -1,6 +1,7 @@ package com.vayunmathur.findfamily.platform  import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.library.wearlink.findfamily.WearWatchLocation import com.vayunmathur.findfamily.data.TemporaryLink import com.vayunmathur.findfamily.data.User import com.vayunmathur.findfamily.data.Waypoint@@ -31,6 +32,9 @@ data class FamilyListUiState(     val locationByUser: Map<Long, LocationValue> = emptyMap(),     /** Names of the people currently at each saved place, keyed by place name. */     val userNamesByLocationName: Map<String, List<String>> = emptyMap(),+    /** Owner's paired watch companion fix (conduit, local only — never published to members). */+    val watchLocation: WearWatchLocation? = null,+    val isRinging: Boolean = false, )  /**@@ -49,6 +53,9 @@ interface FamilyListActions {     fun copyLink(link: TemporaryLink) {}     fun deleteTemporaryLink(link: TemporaryLink) {}     fun beginEditWaypoint(waypoint: Waypoint) {}+    fun ringWatch() {}+    fun stopRinging() {}+    fun findWatch() {}      /** No-op [FamilyListActions] for previews. */     companion object {@@ -72,6 +79,9 @@ data class PersonUiState(      * controls are properties of this device, not of a relationship.      */     val connectedUsers: List<User> = emptyList(),+    /** Owner's watch companion fix, only meaningful on the self sheet. */+    val watchLocation: WearWatchLocation? = null,+    val isRinging: Boolean = false, )  /** Person-sheet callbacks. Same no-op-default arrangement as [FamilyListActions]. */@@ -96,6 +106,9 @@ interface PersonActions {      /** Opt in or out of acting as a finder for other people's powered-off devices. */     fun setCrowdFinding(enabled: Boolean) {}+    fun ringWatch() {}+    fun stopRinging() {}+    fun findWatch() {}      /** No-op [PersonActions] for previews. */     companion object {
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.ktindex c6ddeca1f1..c4754681de 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt@@ -74,6 +74,12 @@ class FindFamilyViewModel(      private val ctx: Context get() = getApplication() +    // Device-only actions are supplied by the sheet hosts (conduit needs a+    // UI context/scope); the ViewModel's default is honestly inert.+    override fun ringWatch() {}+    override fun stopRinging() {}+    override fun findWatch() {}+     // ------------------------------------------------------------------     // DB-backed exposed flows     // ------------------------------------------------------------------
findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationPublisher.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationPublisher.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationPublisher.ktnew file mode 100644index 0000000000..9814233272--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationPublisher.kt@@ -0,0 +1,110 @@+package com.vayunmathur.findfamily.sync++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.location.Location+import android.location.LocationManager+import android.os.BatteryManager+import android.os.Build+import androidx.core.content.ContextCompat+import com.vayunmathur.findfamily.domain.WatchLocationCadence+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.findfamily.WearFindFamilyProtocol+import com.vayunmathur.library.wearlink.findfamily.WearWatchLocation+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.serialization.encodeToString+import kotlin.coroutines.resume++/**+ * Watch-companion location acquisition (watch form factor only). Uses the+ * platform [LocationManager] (GPS/network providers — Wear OS watches may+ * expose either; no Play services assumed). Falls back to publishing+ * nothing when no provider/fix/permission exists: the phone's own position+ * remains the member location, exactly as before.+ *+ * Cadence/battery: publishes on app open and from the periodic worker,+ * gated by [WatchLocationCadence] (min 5 min / significant move 100 m /+ * max 15 min). The fix crosses only the conduit to the paired phone as+ * own-device awareness; it is never published to other members.+ */+object WatchLocationPublisher {+    private const val TAG = "WatchLocationPublisher"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var lastPublished: WearWatchLocation? = null++    fun publishNow(context: Context, force: Boolean = false) {+        scope.launch { publishNowSuspend(context, force) }+    }++    suspend fun publishNowSuspend(context: Context, force: Boolean = false): Boolean {+        val appContext = context.applicationContext+        if (ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&+            ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED+        ) {+            Log.status(TAG, "no location permission on watch; not publishing")+            return false+        }+        val location = currentLocation(appContext) ?: return false+        val candidate = WearWatchLocation(+            latE7 = (location.latitude * 1e7).toInt(),+            lonE7 = (location.longitude * 1e7).toInt(),+            accuracyMeters = if (location.hasAccuracy()) location.accuracy.toInt() else -1,+            updatedAtMillis = if (location.time > 0) location.time else System.currentTimeMillis(),+            batteryPercent = batteryPercent(appContext),+        )+        val last = lastPublished+        if (!force && !WatchLocationCadence.shouldPublish(last?.updatedAtMillis ?: 0L, last?.latE7, last?.lonE7, candidate)) {+            return false+        }+        val sent = WearLinkBridge.get(appContext).putData(+            WearFindFamilyProtocol.WATCH_LOCATION_PATH,+            WearFindFamilyProtocol.json.encodeToString(candidate).encodeToByteArray(),+        )+        if (sent) lastPublished = candidate+        return sent+    }++    private fun batteryPercent(context: Context): Int {+        val bm = context.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager ?: return -1+        return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).coerceIn(0, 100)+    }++    private suspend fun currentLocation(context: Context): Location? {+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null+        val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)+            .filter { runCatching { lm.isProviderEnabled(it) }.getOrDefault(false) }+        if (providers.isEmpty()) return null+        // Prefer a recent last-known fix before paying for an active fix.+        val lastKnown = providers.mapNotNull { provider ->+            runCatching {+                @Suppress("MissingPermission")+                lm.getLastKnownLocation(provider)+            }.getOrNull()+        }.maxByOrNull { it.time }+        if (lastKnown != null && System.currentTimeMillis() - lastKnown.time < WatchLocationCadence.MIN_INTERVAL_MS) {+            return lastKnown+        }+        return suspendCancellableCoroutine { cont ->+            val provider = providers.first()+            try {+                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+                    @Suppress("MissingPermission")+                    lm.getCurrentLocation(provider, null, context.mainExecutor) { loc -> if (cont.isActive) cont.resume(loc) }+                } else {+                    @Suppress("MissingPermission", "DEPRECATION")+                    lm.requestSingleUpdate(provider, { loc: Location -> if (cont.isActive) cont.resume(loc) }, null)+                }+            } catch (e: Exception) {+                Log.status(TAG, "current location failed", e)+                if (cont.isActive) cont.resume(null)+            }+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationWorker.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationWorker.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationWorker.ktnew file mode 100644index 0000000000..15042838a6--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WatchLocationWorker.kt@@ -0,0 +1,30 @@+package com.vayunmathur.findfamily.sync++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.findfamily.platform.FormFactor+import java.util.concurrent.TimeUnit++/** Periodic watch-companion location publish (15 min floor, WorkManager's minimum). Watch form factor only. */+class WatchLocationWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {+    override suspend fun doWork(): Result {+        if (!FormFactor.isWatch(applicationContext)) return Result.success()+        WatchLocationPublisher.publishNowSuspend(applicationContext)+        return Result.success()+    }++    companion object {+        private const val UNIQUE_NAME = "findfamily-watch-location"++        fun enqueue(context: Context) {+            if (!FormFactor.isWatch(context)) return+            val request = PeriodicWorkRequestBuilder<WatchLocationWorker>(15, TimeUnit.MINUTES).build()+            WorkManager.getInstance(context.applicationContext)+                .enqueueUniquePeriodicWork(UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request)+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/FamilyListSheet.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FamilyListSheet.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FamilyListSheet.ktindex 2eab5935ba..38a2b27257 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FamilyListSheet.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FamilyListSheet.kt@@ -45,6 +45,17 @@ fun FamilyListSheet(state: FamilyListUiState, actions: FamilyListActions) {         // Keys are namespaced per section. All four lists live in one LazyColumn but their         // ids come from independent tables, so a user and a waypoint that happen to share an         // id would collide and Compose would throw "Key N was already used".+        if (state.watchLocation != null) {+            item(key = "watch-device") {+                WatchDeviceCard(+                    watchLocation = state.watchLocation,+                    ringing = state.isRinging,+                    onRingWatch = { actions.ringWatch() },+                    onStopRinging = { actions.stopRinging() },+                    onFindWatch = { actions.findWatch() },+                )+            }+        }         items(             state.connectedUsers,             key = { "user-${it.id}" }
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 a2823224a1..1d4168d9fb 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -118,6 +118,8 @@ import com.vayunmathur.findfamily.platform.FindFamilyViewModel import com.vayunmathur.findfamily.platform.MainPageActions import com.vayunmathur.findfamily.platform.MainPageUiState import com.vayunmathur.findfamily.network.Networking+import com.vayunmathur.findfamily.data.WatchDeviceLocationStore+import com.vayunmathur.findfamily.platform.RingController import com.vayunmathur.findfamily.platform.PersonActions import com.vayunmathur.findfamily.platform.PersonUiState import com.vayunmathur.findfamily.platform.Platform@@ -191,6 +193,8 @@ fun MainPage(     val userPositions by ffViewModel.latestLocationByUser.collectAsState()      val context = LocalContext.current+    val watchLocation by WatchDeviceLocationStore.get(context).latest.collectAsState()+    val isRinging by RingController.ringing.collectAsState()      // The selected contact (from the sheet route on top of the stack),     // resolved from the full user list. Drives the map highlight.@@ -217,7 +221,9 @@ fun MainPage(             temporaryLinks = temporaryLinks,             waypoints = waypoints,             locationByUser = userPositions,-            userNamesByLocationName = usersByLocationName+            userNamesByLocationName = usersByLocationName,+            watchLocation = watchLocation,+            isRinging = isRinging         ),     ) 
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.ktindex b73fa07aea..49e5ae71c7 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -44,6 +44,12 @@ import com.vayunmathur.findfamily.data.Waypoint import com.vayunmathur.findfamily.data.radians import com.vayunmathur.findfamily.data.toGeoPoint import com.vayunmathur.findfamily.platform.FindFamilyViewModel+import com.vayunmathur.findfamily.data.WatchDeviceLocationStore+import com.vayunmathur.library.ui.IconWatch+import androidx.compose.ui.platform.LocalContext+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.ui.Alignment as ComposeAlignment import com.vayunmathur.library.ui.invisibleClickable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext@@ -76,6 +82,7 @@ fun MapView(     val users by viewModel.users.collectAsState()     val waypoints by viewModel.waypoints.collectAsState()     val userPositions by viewModel.latestLocationByUser.collectAsState()+    val watchLocation by WatchDeviceLocationStore.get(LocalContext.current).latest.collectAsState()      var initialized by remember { mutableStateOf(false) } @@ -167,6 +174,22 @@ fun MapView(                             }                         }                     }+                    // Owner's watch companion as a device marker — distinct from+                    // person markers, local to this phone only (never published).+                    if (selectedUser == null) {+                        watchLocation?.let { watch ->+                            val watchPosition = GeoPoint(watch.lonE7 / 1e7, watch.latE7 / 1e7)+                            MapMarker(watchPosition) {+                                Column(+                                    horizontalAlignment = ComposeAlignment.CenterHorizontally,+                                    modifier = Modifier.background(MaterialTheme.colorScheme.secondaryContainer, CircleShape).padding(6.dp),+                                ) {+                                    IconWatch()+                                    Text("Your watch", style = MaterialTheme.typography.labelSmall)+                                }+                            }+                        }+                    }                 }             }         }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.ktindex e59eb99f48..82627c8b24 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt@@ -34,6 +34,16 @@ fun PersonDetailSheet(         // No per-person hide/sharing toggle on this page: people cannot be         // hidden or removed from here. Use the Quick Settings tile to pause         // sharing globally.+        if (user.id == Networking.userid) {+            WatchDeviceCard(+                watchLocation = state.watchLocation,+                ringing = state.isRinging,+                onRingWatch = { actions.ringWatch() },+                onStopRinging = { actions.stopRinging() },+                onFindWatch = { actions.findWatch() },+            )+            Spacer(Modifier.height(4.dp))+        }         if (user.id != Networking.userid) {             // No-show watch (issue 702): expected arrival that never happens.             OutlinedButton(
findfamily/src/main/java/com/vayunmathur/findfamily/ui/WatchDeviceCard.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WatchDeviceCard.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WatchDeviceCard.ktnew file mode 100644index 0000000000..904ded2f59--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WatchDeviceCard.kt@@ -0,0 +1,80 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.findfamily.R+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconRingDevice+import com.vayunmathur.library.ui.IconWatch+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.wearlink.findfamily.WearWatchLocation+import androidx.compose.ui.graphics.Color++/**+ * The owner's paired watch as a device — not a person. Shown only on the+ * owner's phone from the conduit watch fix; members never receive this+ * location (they always receive the phone's position).+ */+@Composable+fun WatchDeviceCard(+    watchLocation: WearWatchLocation?,+    ringing: Boolean,+    onRingWatch: () -> Unit,+    onStopRinging: () -> Unit,+    onFindWatch: () -> Unit = {},+) {+    Card(Modifier.fillMaxWidth()) {+        Column(Modifier.padding(horizontal = 12.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+            ListItem(+                leadingContent = { IconWatch() },+                colors = ListItemDefaults.colors(containerColor = Color.Transparent),+                content = { Text(stringResource(R.string.your_watch), style = MaterialTheme.typography.titleMediumEmphasized) },+                supportingContent = {+                    Text(+                        if (watchLocation == null) {+                            stringResource(R.string.watch_device_no_location)+                        } else {+                            val age = watchLocationAgeLabel(watchLocation.updatedAtMillis, System.currentTimeMillis())+                            val battery = if (watchLocation.batteryPercent >= 0) " · ${watchLocation.batteryPercent}%" else ""+                            stringResource(R.string.watch_device_location, age) + battery ++                                " · ${watchLocation.latE7 / 1e7}, ${watchLocation.lonE7 / 1e7}"+                        },+                    )+                },+            )+            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                OutlinedButton(onClick = onRingWatch, modifier = Modifier.weight(1f)) {+                    IconRingDevice()+                    Text(stringResource(R.string.ring_watch))+                }+                OutlinedButton(onClick = onFindWatch, modifier = Modifier.weight(1f)) {+                    IconWatch()+                    Text(stringResource(R.string.find_watch))+                }+                if (ringing) {+                    OutlinedButton(onClick = onStopRinging, modifier = Modifier.weight(1f)) {+                        Text(stringResource(R.string.stop_ringing))+                    }+                }+            }+        }+    }+}++internal fun watchLocationAgeLabel(updatedAtMillis: Long, nowMillis: Long): String = when {+    updatedAtMillis <= 0L -> "not yet received"+    nowMillis - updatedAtMillis < 60_000L -> "just now"+    nowMillis - updatedAtMillis < 3_600_000L -> "${(nowMillis - updatedAtMillis) / 60_000L}m ago"+    else -> "${(nowMillis - updatedAtMillis) / 3_600_000L}h ago"+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/WearMainActivity.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WearMainActivity.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WearMainActivity.ktindex e60a8f5947..33671adfbd 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WearMainActivity.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WearMainActivity.kt@@ -3,6 +3,8 @@ package com.vayunmathur.findfamily.ui import androidx.compose.runtime.Composable import com.vayunmathur.findfamily.data.WearFindFamilyStore import com.vayunmathur.findfamily.sync.WearLinkBridge+import com.vayunmathur.findfamily.sync.WatchLocationPublisher+import com.vayunmathur.findfamily.sync.WatchLocationWorker import com.vayunmathur.library.wearlink.WearShellActivity  /**@@ -15,6 +17,9 @@ class WearMainActivity : WearShellActivity<WearRoute, WearFindFamilyStore>(WearR     override fun createStore() = WearFindFamilyStore.get(this).also {         WearLinkBridge.get(this)         WearLinkBridge.publishWatchState(this)+        // Watch companion location: publish on open (cadence-gated) and periodically via WorkManager.+        WatchLocationPublisher.publishNow(this, force = true)+        WatchLocationWorker.enqueue(this)     }      @Composable
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex f9d5c04e2b..1c0d79772f 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -372,4 +372,21 @@     <string name="noshow_save">Watch</string>     <!-- NoShowAlertDialog: snackbar confirmation after the watch is saved. Sentence -->     <string name="noshow_scheduled">No-show watch set</string>+    <string name="your_watch">Your watch</string>+    <string name="watch_device_location">Watch location %1$s</string>+    <string name="watch_device_no_location">Watch location not yet received</string>+    <string name="watch_device_battery">Watch battery %1$d%%</string>+    <string name="ring_watch">Ring watch</string>+    <string name="ring_phone">Ring phone</string>+    <string name="stop_ringing">Stop ringing</string>+    <string name="ring_notification_title">Find your device</string>+    <string name="ring_notification_text">Your paired device is ringing it</string>+    <string name="ring_stop">Stop</string>+    <string name="ring_sent">Ringing…</string>+    <string name="ring_no_connection">No connection to the other device</string>+    <string name="find_watch">Find watch</string>+    <string name="find_phone">Find phone</string>+    <string name="uwb_unavailable_pair">UWB is not available on this phone/watch pair, so precision finding is off. Location and ringing still work.</string>+    <string name="searching_device">Searching for your device…</string>+    <string name="device_signal_stale">Signal is stale — move a little to refresh it</string> </resources>
findfamily/src/test/java/com/vayunmathur/findfamily/domain/WatchDeviceFeaturesTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/WatchDeviceFeaturesTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/WatchDeviceFeaturesTest.ktnew file mode 100644index 0000000000..a4e3398b63--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/WatchDeviceFeaturesTest.kt@@ -0,0 +1,88 @@+package com.vayunmathur.findfamily.domain++import com.vayunmathur.library.wearlink.findfamily.WearDeviceKind+import com.vayunmathur.library.wearlink.findfamily.WearFindFamilyProtocol+import com.vayunmathur.library.wearlink.findfamily.WearRingRequest+import com.vayunmathur.library.wearlink.findfamily.WearWatchLocation+import com.vayunmathur.library.wearlink.findfamily.wearRingIsFresh+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WatchDeviceFeaturesTest {++    private fun watchFix(at: Long, latE7: Int = 377_749_000, lonE7: Int = -1_224_194_000) = WearWatchLocation(+        latE7 = latE7,+        lonE7 = lonE7,+        accuracyMeters = 12,+        updatedAtMillis = at,+        batteryPercent = 73,+    )++    @Test+    fun watchLocationRoundTrips() {+        val fix = watchFix(123_000L)+        val json = WearFindFamilyProtocol.json.encodeToString(fix)+        assertEquals(fix, WearFindFamilyProtocol.json.decodeFromString<WearWatchLocation>(json))+        assertTrue(json.contains("\"latE7\":377749000"))+    }++    @Test+    fun ringRequestsRoundTripBothDirections() {+        val ringPhone = WearRingRequest(WearDeviceKind.PHONE, 1_000L, "phone-1")+        val ringWatch = WearRingRequest(WearDeviceKind.WATCH, 2_000L, "watch-2")+        assertEquals(+            ringPhone,+            WearFindFamilyProtocol.json.decodeFromString<WearRingRequest>(WearFindFamilyProtocol.json.encodeToString(ringPhone)),+        )+        assertEquals(+            ringWatch,+            WearFindFamilyProtocol.json.decodeFromString<WearRingRequest>(WearFindFamilyProtocol.json.encodeToString(ringWatch)),+        )+    }++    @Test+    fun staleRingIsIgnored() {+        val now = 200_000L+        assertTrue(wearRingIsFresh(WearRingRequest(WearDeviceKind.PHONE, now - 1_000L, "a"), now))+        assertFalse(wearRingIsFresh(WearRingRequest(WearDeviceKind.PHONE, now - RingPolicy.TTL_MS - 1L, "b"), now))+        assertFalse(wearRingIsFresh(WearRingRequest(WearDeviceKind.WATCH, 0L, "c"), now))+        assertTrue(RingPolicy.isFresh(now - 500L, now))+        assertFalse(RingPolicy.isFresh(now - RingPolicy.TTL_MS - 1L, now))+    }++    @Test+    fun ringAutoStopAfterSixtySeconds() {+        assertFalse(RingPolicy.shouldAutoStop(1_000L, 1_000L + RingPolicy.AUTO_STOP_MS - 1L))+        assertTrue(RingPolicy.shouldAutoStop(1_000L, 1_000L + RingPolicy.AUTO_STOP_MS))+    }++    @Test+    fun cadenceFirstFixAlwaysPublishes() {+        assertTrue(WatchLocationCadence.shouldPublish(0L, null, null, watchFix(10_000L)))+    }++    @Test+    fun cadenceCapsFrequencyWithoutMove() {+        val first = watchFix(1_000_000L)+        val soonSamePlace = watchFix(1_000_000L + WatchLocationCadence.MIN_INTERVAL_MS + 1L)+        assertFalse(WatchLocationCadence.shouldPublish(first.updatedAtMillis, first.latE7, first.lonE7, soonSamePlace))+    }++    @Test+    fun cadencePublishesOnSignificantMoveAfterMinInterval() {+        val first = watchFix(1_000_000L)+        // ~1.1 km north after the minimum interval.+        val moved = watchFix(1_000_000L + WatchLocationCadence.MIN_INTERVAL_MS + 1L, latE7 = first.latE7 + 100_000)+        assertTrue(WatchLocationCadence.shouldPublish(first.updatedAtMillis, first.latE7, first.lonE7, moved))+    }++    @Test+    fun cadencePublishesAtMaxIntervalEvenWithoutMove() {+        val first = watchFix(1_000_000L)+        val later = watchFix(1_000_000L + WatchLocationCadence.MAX_INTERVAL_MS)+        assertTrue(WatchLocationCadence.shouldPublish(first.updatedAtMillis, first.latE7, first.lonE7, later))+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/WatchDeviceCardTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/WatchDeviceCardTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/WatchDeviceCardTest.ktnew file mode 100644index 0000000000..6bdfed934a--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/WatchDeviceCardTest.kt@@ -0,0 +1,45 @@+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.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.wearlink.findfamily.WearWatchLocation+import kotlin.test.Test+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class WatchDeviceCardTest {++    @get:Rule+    val rule = createComposeRule()++    @Test+    fun showsYourWatchAsDeviceAndRingsWatch() {+        var rings = 0+        rule.setContent {+            WatchDeviceCard(+                watchLocation = WearWatchLocation(377_749_000, -1_224_194_000, 10, 1_700_000_000_000L, 80),+                ringing = false,+                onRingWatch = { rings++ },+                onStopRinging = {},+            )+        }+        rule.onNodeWithText("Your watch").assertIsDisplayed()+        rule.onNodeWithText("Ring watch").assertIsDisplayed()+        rule.onNodeWithText("Ring watch").performClick()+        assertTrue(rings == 1)+    }++    @Test+    fun noLocationStillShowsDeviceRowWithoutPersonWording() {+        rule.setContent {+            WatchDeviceCard(watchLocation = null, ringing = false, onRingWatch = {}, onStopRinging = {})+        }+        rule.onNodeWithText("Your watch").assertIsDisplayed()+        rule.onNodeWithText("Watch location not yet received").assertIsDisplayed()+    }+}
library/ui/icons.tsv
diff --git a/library/ui/icons.tsv b/library/ui/icons.tsvindex 06f1d14d63..9dcd91a40d 100644--- a/library/ui/icons.tsv+++ b/library/ui/icons.tsv@@ -341,3 +341,5 @@ IconBookmarkBorder	S	Filled.BookmarkBorder	Save for later IconNewspaper	S	Filled.Newspaper	News	 IconOpenInNew	S	Filled.OpenInNew	Open in browser	 IconMobileArrowRight	S	Filled.Smartphone	Open on phone	Open on phone - hand off to the phone app.+IconWatch	S	Filled.Watch	Your watch	Your watch - the paired watch companion device.+IconRingDevice	S	Filled.RingVolume	Ring device	Ring device - make the paired phone or watch ring.
library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdindex ef851bc1d6..09f7c51888 100644--- a/library/wearlink/AGENTS.md+++ b/library/wearlink/AGENTS.md@@ -43,7 +43,7 @@ duplicated per app pair: each migrated protocol lives in `com.vayunmathur.library.wearlink.<app>` and is consumed by both the phone and wear app modules (which may not depend on each other). Golden-JSON tests stay in each app module and pin the shared code's wire format.-Migrated: clock, launcher, calendar, weather, music, notes, maps, appstore, contacts, findfamily, todo, communicate, camera, email, securemail. Remaining pairs are listed in+Migrated: clock, launcher, calendar, weather, music, notes, maps, appstore, contacts, findfamily, todo, communicate, camera, email, securemail. The findfamily protocol also carries own-device companion types: `WearWatchLocation` (watch->phone conduit data), `WearRingRequest` (ring paired own device, TTL-bound message) and `WearDeviceUwbMessage` (UWB session-param exchange; ranging is local). Remaining pairs are listed in `docs/structure/wear-protocol-pairs.tsv`. The contacts protocol (`contacts/WearContactsProtocol`) carries, additively, each contact's joined messenger platforms per action (call/message/video)
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/findfamily/WearFindFamilyProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/findfamily/WearFindFamilyProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/findfamily/WearFindFamilyProtocol.ktindex ddb5306386..b44f5ff930 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/findfamily/WearFindFamilyProtocol.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/findfamily/WearFindFamilyProtocol.kt@@ -53,6 +53,21 @@ object WearFindFamilyProtocol {     /** Message path (watch -> phone): ask the phone to publish a fresh snapshot. */     const val REQUEST_SYNC_PATH = "/findfamily/request-sync" +    /** Data-item path (watch -> phone): the watch companion's own fix ([WearWatchLocation]). Latest-wins. */+    const val WATCH_LOCATION_PATH = "/findfamily/watch-location"++    /** Message path (both directions): ring the paired own device ([WearRingRequest]). Fire-and-forget, TTL-bound. */+    const val RING_PATH = "/findfamily/ring"++    /** Message path (both directions): UWB device-finding session coordination ([WearDeviceUwbMessage]). Ranging itself is local, no backend. */+    const val DEVICE_UWB_PATH = "/findfamily/device-uwb"++    /** A ring request older than this is stale and must be ignored (conduit may replay queued messages). */+    const val RING_TTL_MS = 60_000L++    /** A started ring auto-stops after this long. */+    const val RING_AUTO_STOP_MS = 60_000L+     /** Largest snapshot JSON in UTF-8 bytes; summarise/drop-oldest to fit. */     const val MAX_JSON_BYTES = 90_000 @@ -158,6 +173,66 @@ data class WearWatchState(     val peopleCount: Int = 0, ) +/** Which of the member's own devices supplied / should act. The watch is a companion of the phone, same member. */+@Serializable+enum class WearDeviceKind { PHONE, WATCH }++/**+ * The watch companion's own fix, published at [WearFindFamilyProtocol.WATCH_LOCATION_PATH]+ * as a latest-wins data item. The phone keeps it as own-device awareness only: the member location+ * published to other members is always the phone's position, and this+ * fix never enters that outgoing publish. It never creates a separate person.+ */+@Serializable+data class WearWatchLocation(+    val latE7: Int,+    val lonE7: Int,+    val accuracyMeters: Int = -1,+    val updatedAtMillis: Long = 0L,+    val batteryPercent: Int = -1,+    val deviceKind: WearDeviceKind = WearDeviceKind.WATCH,+    val deviceLabel: String = "Watch",+)++/**+ * Ring the paired own device, sent at [WearFindFamilyProtocol.RING_PATH] as a+ * conduit message (never a persisted data item). [target] is the device that+ * should ring: a watch sends target=PHONE, a phone sends target=WATCH.+ * Receivers ignore requests older than [WearFindFamilyProtocol.RING_TTL_MS].+ */+@Serializable+data class WearRingRequest(+    val target: WearDeviceKind,+    val requestedAtMillis: Long = 0L,+    val ringId: String = "",+)++/** True when a ring request is fresh enough to act on. */+fun wearRingIsFresh(request: WearRingRequest, nowMillis: Long): Boolean =+    request.requestedAtMillis > 0L && nowMillis - request.requestedAtMillis in 0..WearFindFamilyProtocol.RING_TTL_MS++/** UWB device-finding session coordination over the conduit. */+@Serializable+enum class WearDeviceUwbKind { FIND_REQUEST, FIND_ACCEPT, FIND_STOP }++/**+ * Session-parameter exchange for finding the paired own device over UWB.+ * The controller ([WearDeviceUwbKind.FIND_REQUEST] sender) chooses session+ * id/channel/preamble/key and its address; the controlee replies+ * [WearDeviceUwbKind.FIND_ACCEPT] with its address. Addresses/keys are+ * base64. Ranging then happens locally between the two devices.+ */+@Serializable+data class WearDeviceUwbMessage(+    val kind: WearDeviceUwbKind,+    val sessionId: Int = 0,+    val channel: Int = 9,+    val preamble: Int = 10,+    val sessionKeyB64: String = "",+    val localAddressB64: String = "",+    val requestedAtMillis: Long = 0L,+)+ /** Watch-originated actions; the phone remains the source of truth for both. */ @Serializable enum class WearOpKind { STOP_SHARING_NOW, REQUEST_REFRESH }