wear: findfamily companion shows everyone's location
- Commit
85fc08be625762c2c736ab3cea080a545a6e0dc3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-25 16:50 UTC (10 days ago)
- Parents
4531e01
New :findfamily-wear: watch home lists every person with place, distance/direction, fix age, battery, moving/still, and staleness; per-person detail Route with a relative view; an all-people map plotting everyone around the region centre (radial/north-up projection - an honest relative view rather than a faked basemap, since FindFamily owns no planet data). Payload summarises before it ever drops anyone (a 200-person circle loses nobody; hard-cap drops are stated with counts). Stop-sharing-now and request- refresh ops execute on the phone; no location history, no E2EE material crosses; watch stores only the last summary, always staleness-labelled. Verified: wear 11/11 tests + assemble + lint; phone suite green incl. protocol goldens.
Diff
findfamily-wear/AGENTS.md
diff --git a/findfamily-wear/AGENTS.md b/findfamily-wear/AGENTS.mdnew file mode 100644index 0000000000..b7679e59be--- /dev/null+++ b/findfamily-wear/AGENTS.md@@ -0,0 +1,44 @@+# AGENTS.md — findfamily-wear/ (':findfamily-wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `findfamily-wear/` + `findfamily/` (the phone side of the same feature).++- Gradle: :findfamily-wear / dir: findfamily-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone FindFamily (`:findfamily`). This module+deliberately uses `applicationId = "com.vayunmathur.findfamily"` (the+phone app's) with the shared dev/release signing from the convention+plugins: WearLink's handshake token requires the same signing+certificate on both sides, so changing either breaks phone<->watch sync.+Bootstrap is a one-time ADB sideload of this APK onto the watch.++## Protocol+`domain/WearFindFamilyProtocol.kt` is a copy of the phone's file (Gradle+cannot depend on another app module). Change both copies together; each+side's `WearFindFamilyProtocolTest` pins the same golden JSON.++- Snapshot: WearLink data item (`/findfamily/snapshot`, phone -> watch) —+ ALL people in the circle as location summaries (place label, E7 coord,+ fix/report times, accuracy, battery, motion), no history/track.+- Watch state: WearLink data item (`/findfamily/watch-state`)+- Ops: WearLink message (`/findfamily/op`: STOP_SHARING_NOW,+ REQUEST_REFRESH); request-sync message (`/findfamily/request-sync`)+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## What the watch shows+People home (every person, most-recent first), per-person detail via a+Route carrying the person id (precise fix age/accuracy/place + relative+view), and an all-people relative map centred on the phone-supplied+region (self when located). There is no vector basemap: the phone+FindFamily app owns no planet archive, so markers are plotted relative+to the centre — never fake precision, stale fixes are labelled by age.+The last snapshot persists on-watch for offline reading.++## Verify (this module only)+```+./gradlew :findfamily-wear:assembleDev+./gradlew :findfamily-wear:testDebugUnitTest+```
findfamily-wear/build.gradle.kts
diff --git a/findfamily-wear/build.gradle.kts b/findfamily-wear/build.gradle.ktsnew file mode 100644index 0000000000..4c90583ff4--- /dev/null+++ b/findfamily-wear/build.gradle.kts@@ -0,0 +1,30 @@+plugins {+ id("common-conventions-wear")+}++launcherIcon {+ symbol = "moved_location"+}++// Version shared with the phone app (root version.txt).+val wearVersionLines = file("../version.txt").readLines()+val wearVersionCode = wearVersionLines[0].trim().toInt()+val wearVersionName = wearVersionLines[1].trim()++android {+ // WearLink handshake requires same package + signing as the phone app.+ namespace = "com.vayunmathur.findfamily.wear"+ defaultConfig {+ applicationId = "com.vayunmathur.findfamily"+ minSdk = 31+ versionCode = wearVersionCode+ versionName = wearVersionName+ }+}++dependencies {+ implementation(libs.kotlinx.coroutines.android)+ implementation(project(":library:wearlink"))+ testImplementation(libs.kotlin.test)+ testImplementation(libs.kotlin.test.junit)+}
findfamily-wear/src/main/AndroidManifest.xml
diff --git a/findfamily-wear/src/main/AndroidManifest.xml b/findfamily-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..f9d172cc32--- /dev/null+++ b/findfamily-wear/src/main/AndroidManifest.xml@@ -0,0 +1,35 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-feature+ android:name="android.hardware.type.watch"+ android:required="true" />+ <uses-feature+ android:name="android.hardware.touchscreen"+ android:required="false" />++ <uses-permission android:name="android.permission.WAKE_LOCK" />++ <application+ android:allowBackup="false"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@android:style/Theme.Material.NoActionBar">++ <meta-data+ android:name="com.google.android.wearable.standalone"+ android:value="false" />++ <activity+ android:name=".ui.WearMainActivity"+ android:exported="true"+ android:taskAffinity="">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ </application>+</manifest>
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/data/WearFindFamilyStore.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/data/WearFindFamilyStore.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/data/WearFindFamilyStore.ktnew file mode 100644index 0000000000..4755ee0b6f--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/data/WearFindFamilyStore.kt@@ -0,0 +1,56 @@+package com.vayunmathur.findfamily.wear.data++import android.content.Context+import com.vayunmathur.findfamily.wear.domain.WearFindFamilyProtocol+import com.vayunmathur.findfamily.wear.domain.WearFindFamilySnapshot+import com.vayunmathur.library.log.Log+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString++/**+ * The watch's local truth: the last phone snapshot, persisted as JSON in+ * app-private storage so people read fully offline (phone absent, process+ * cold-started) — labelled stale by age, never as live data.+ */+class WearFindFamilyStore private constructor(private val context: Context) {++ companion object {+ private const val TAG = "WearFindFamilyStore"++ @Volatile+ private var instance: WearFindFamilyStore? = null++ /** The process-wide store (bridge and UI must agree on one). */+ fun get(context: Context): WearFindFamilyStore = instance ?: synchronized(this) {+ instance ?: WearFindFamilyStore(context.applicationContext).also { instance = it }+ }+ }++ private val snapshotFile = File(context.filesDir, "wear-findfamily-snapshot.json")++ private val _snapshot = MutableStateFlow(loadSnapshot())+ /** Last snapshot from the phone; empty until the first sync. */+ val snapshot: StateFlow<WearFindFamilySnapshot> = _snapshot.asStateFlow()++ private val _connected = MutableStateFlow(false)+ /** Last known WearLink session state, for offline honesty in the UI. */+ val connected: StateFlow<Boolean> = _connected.asStateFlow()++ fun setConnected(connected: Boolean) {+ _connected.value = connected+ }++ fun setSnapshot(snapshot: WearFindFamilySnapshot) {+ _snapshot.value = snapshot+ runCatching { snapshotFile.writeText(WearFindFamilyProtocol.json.encodeToString(snapshot)) }+ .onFailure { Log.status(TAG, "persist snapshot failed: ${it.message}") }+ com.vayunmathur.findfamily.wear.sync.WearLinkBridge.publishWatchState(context)+ }++ private fun loadSnapshot(): WearFindFamilySnapshot = runCatching {+ WearFindFamilyProtocol.json.decodeFromString<WearFindFamilySnapshot>(snapshotFile.readText())+ }.getOrDefault(WearFindFamilySnapshot())+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocol.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocol.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocol.ktnew file mode 100644index 0000000000..579a32e156--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocol.kt@@ -0,0 +1,297 @@+package com.vayunmathur.findfamily.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Phone <-> watch protocol for the Wear OS FindFamily companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module+ * (`:findfamily-wear`, applicationId `com.vayunmathur.findfamily`) carries+ * a copy of this file under `com.vayunmathur.findfamily.wear.domain`.+ * Change both copies together; each side's unit tests pin the same golden+ * JSON so a one-sided edit fails loudly.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [SNAPSHOT_PATH] phone -> watch (all-people location+ * summaries) and [WATCH_STATE_PATH] watch -> phone.+ * - Messages: [OP_PATH] watch -> phone (stop-sharing / request-refresh)+ * and [REQUEST_SYNC_PATH] watch -> phone (ask for a fresh snapshot).+ * Delivery needs a live session; nothing wakes a dead phone process.+ *+ * Owner rule: the watch shows ALL people in the phone circle. The payload+ * is bounded by summarising (short labels, E7 coordinates, no history),+ * never by a top-N people cap in normal operation. Only if the byte cap+ * still cannot fit everyone does [buildWearSnapshot] drop the+ * least-recently-updated people, and then it says so honestly via+ * `truncated` + `droppedCount`, keeping most-recent first.+ *+ * Privacy: a person entry is exactly what the phone's own cards show —+ * current place label, current coordinate at E7 precision, fix/report+ * times, accuracy, speed-derived motion, battery. No location history,+ * no track, no keys, no pair ids. E2EE stays phone-side: the phone+ * decrypts peer reports into its Room store and only these already-+ * decrypted summaries cross WearLink (Bluetooth-bonded, cert-bound).+ */+object WearFindFamilyProtocol {+ /** WearLink appId the phone requires in the peer handshake. */+ const val CAPABILITY = "findfamily_wear_companion"++ /** Data-item path (phone -> watch): the [WearFindFamilySnapshot] JSON. */+ const val SNAPSHOT_PATH = "/findfamily/snapshot"++ /** Data-item path (watch -> phone): the [WearWatchState] JSON. */+ const val WATCH_STATE_PATH = "/findfamily/watch-state"++ /** Message path (watch -> phone): one [WearFindFamilyOp] JSON. */+ const val OP_PATH = "/findfamily/op"++ /** Message path (watch -> phone): ask the phone to publish a fresh snapshot. */+ const val REQUEST_SYNC_PATH = "/findfamily/request-sync"++ /** Largest snapshot JSON in UTF-8 bytes; summarise/drop-oldest to fit. */+ const val MAX_JSON_BYTES = 90_000++ /** Field caps applied when a snapshot is built. */+ const val MAX_NAME_CHARS = 60+ const val MAX_PLACE_CHARS = 80++ /** Tighter caps used as the first summarising step before anyone is dropped. */+ const val SUMMARISED_NAME_CHARS = 24+ const val SUMMARISED_PLACE_CHARS = 24++ /** A fix older than this (watch clock vs fix time) reads stale, never live. */+ const val STALE_AFTER_MS = 30 * 60_000L++ /** Speed (m/s) at/above which a person counts as moving for the watch summary. */+ const val MOVING_SPEED_MPS = 1.0++ /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+ val json: Json = Json { ignoreUnknownKeys = true }+}++/** Motion summary derived phone-side from the fix's reported speed. */+@Serializable+enum class WearMotion { MOVING, STATIONARY, UNKNOWN }++/** Kind of watch-readable alert state carried in a snapshot. */+@Serializable+enum class WearAlertKind { AT_PLACE, NOSHOW }++/** One person trimmed to watch size: the phone card, summarised. No history. */+@Serializable+data class WearPerson(+ val id: Long,+ val name: String,+ /** Saved-place/locality label the phone UI shows ("Home"), "" when unnamed. */+ val placeLabel: String = "",+ /** When the person arrived at [placeLabel] (phone `lastLocationChangeTime`), 0 unknown. */+ val placeSinceMillis: Long = 0L,+ /** Current coordinate, degrees * 1e7 (the precision the phone map shows); null = no fix. */+ val latE7: Int? = null,+ val lonE7: Int? = null,+ /** Fix accuracy radius (m); -1 when the source gives none (e.g. network sighting). */+ val accuracyMeters: Int = -1,+ /** When the position was measured (epoch millis); 0 = no fix. */+ val updatedAtMillis: Long = 0L,+ /** When the report was sent; differs from measured time on parting reports. */+ val reportedAtMillis: Long = 0L,+ /** Battery percent 0..100; -1 when unavailable (incl. network sightings). */+ val batteryPercent: Int = -1,+ val motion: WearMotion = WearMotion.UNKNOWN,+ /** Wire source name (LIVE/SHUTDOWN/BATTERY_LOW/NETWORK_SIGHTING); "" when no fix. */+ val source: String = "",+ /** Whether the phone is sharing this device's location with this person. */+ val sharingEnabled: Boolean = true,+ val isSelf: Boolean = false,+)++/**+ * Watch-readable alert state. The phone persists current place + since+ * (not an enter/leave event log), so AT_PLACE is the honest enter state;+ * NOSHOW mirrors the phone's no-show rows (pending and fired).+ */+@Serializable+data class WearAlert(+ val kind: WearAlertKind,+ val personId: Long,+ val placeLabel: String = "",+ val atMillis: Long = 0L,+ val fired: Boolean = false,+)++/** Bounded region around the snapshot centre with everyone's markers relative to it. */+@Serializable+data class WearRegion(+ val centerLatE7: Int = 0,+ val centerLonE7: Int = 0,+ /** Radius (m) covering centre -> farthest located person, clamped for rendering. */+ val radiusM: Int = 200,+ val hasCenter: Boolean = false,+)++/** The phone's all-people snapshot for the watch ([WearFindFamilyProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearFindFamilySnapshot(+ val generatedAtMillis: Long = 0L,+ /** Every person in the circle, most recently updated first. */+ val people: List<WearPerson> = emptyList(),+ val alerts: List<WearAlert> = emptyList(),+ /** Global sharing switch on the phone (Quick Settings tile semantics). */+ val sharingEnabled: Boolean = true,+ val region: WearRegion = WearRegion(),+ /** True only when the byte cap forced people out; see [droppedCount]. */+ val truncated: Boolean = false,+ val droppedCount: Int = 0,+ /** People before any cap drop, so the watch can state the full circle size. */+ val totalPeople: Int = 0,+)++/** What the watch last applied, published at [WearFindFamilyProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+ val appliedGeneratedAtMillis: Long = 0L,+ val peopleCount: Int = 0,+)++/** Watch-originated actions; the phone remains the source of truth for both. */+@Serializable+enum class WearOpKind { STOP_SHARING_NOW, REQUEST_REFRESH }++/** One watch-originated action, as [WearFindFamilyProtocol.OP_PATH]. */+@Serializable+data class WearFindFamilyOp(+ val kind: WearOpKind,+ val requestedAtMillis: Long = 0L,+)++/** Motion from reported speed; no speed (or a sighting) is honestly UNKNOWN. */+fun wearMotionFor(speedMps: Float?, hasFix: Boolean): WearMotion = when {+ !hasFix || speedMps == null || !speedMps.isFinite() -> WearMotion.UNKNOWN+ speedMps >= WearFindFamilyProtocol.MOVING_SPEED_MPS -> WearMotion.MOVING+ else -> WearMotion.STATIONARY+}++/** True when a person's fix is missing or older than the stale window. */+fun wearIsStale(person: WearPerson, nowMillis: Long): Boolean =+ person.updatedAtMillis <= 0L || nowMillis - person.updatedAtMillis > WearFindFamilyProtocol.STALE_AFTER_MS++/** True when the whole snapshot has aged out (offline reading must label it). */+fun wearSnapshotIsStale(snapshot: WearFindFamilySnapshot?, nowMillis: Long): Boolean =+ snapshot == null || nowMillis - snapshot.generatedAtMillis > WearFindFamilyProtocol.STALE_AFTER_MS++/** Haversine distance (m) between two E7 positions. */+fun wearDistanceMeters(lat1E7: Int, lon1E7: Int, lat2E7: Int, lon2E7: Int): Double {+ val r = 6_371_000.0+ val dLat = Math.toRadians((lat2E7 - lat1E7) / 1e7)+ val dLon = Math.toRadians((lon2E7 - lon1E7) / 1e7)+ val a = sin(dLat / 2) * sin(dLat / 2) ++ cos(Math.toRadians(lat1E7 / 1e7)) * cos(Math.toRadians(lat2E7 / 1e7)) *+ sin(dLon / 2) * sin(dLon / 2)+ return 2 * r * kotlin.math.asin(sqrt(a.coerceIn(0.0, 1.0)))+}++/** Initial bearing (degrees clockwise from north, 0..359) from first E7 point to second. */+fun wearBearingDegrees(lat1E7: Int, lon1E7: Int, lat2E7: Int, lon2E7: Int): Int {+ val lat1 = Math.toRadians(lat1E7 / 1e7)+ val lat2 = Math.toRadians(lat2E7 / 1e7)+ val dLon = Math.toRadians((lon2E7 - lon1E7) / 1e7)+ val y = sin(dLon) * cos(lat2)+ val x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)+ val deg = Math.toDegrees(atan2(y, x))+ return ((deg % 360.0) + 360.0).toInt() % 360+}++/** 8-wind compass label for a bearing ("N", "NE", ...). */+fun wearCompass(bearingDeg: Int): String {+ val winds = arrayOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")+ return winds[(((bearingDeg % 360) + 360) % 360 + 22) / 45 % 8]+}++/** Metres east/north of an origin for a target E7 position (relative-view math). */+fun wearRelativeOffsetMeters(+ originLatE7: Int,+ originLonE7: Int,+ latE7: Int,+ lonE7: Int,+): Pair<Double, Double> {+ val east = (lonE7 - originLonE7) / 1e7 * 111_320.0 * cos(Math.toRadians(originLatE7 / 1e7))+ val north = (latE7 - originLatE7) / 1e7 * 110_540.0+ return east to north+}++/** Region centred on self (else first located person) covering every located person. */+fun wearRegionFor(people: List<WearPerson>): WearRegion {+ val located = people.filter { it.latE7 != null && it.lonE7 != null }+ if (located.isEmpty()) return WearRegion()+ val centre = located.firstOrNull { it.isSelf } ?: located.first()+ val maxDist = located.maxOf {+ wearDistanceMeters(centre.latE7!!, centre.lonE7!!, it.latE7!!, it.lonE7!!)+ }+ return WearRegion(+ centerLatE7 = centre.latE7!!,+ centerLonE7 = centre.lonE7!!,+ radiusM = maxDist.toInt().coerceIn(200, 100_000),+ hasCenter = true,+ )+}++/**+ * Builds the all-people snapshot: most-recently-updated first, field caps+ * applied, then — only to fit [WearFindFamilyProtocol.MAX_JSON_BYTES] —+ * tighter summarising, and only then dropping least-recent people with+ * `truncated`/`droppedCount` set. Normal circles lose nobody.+ */+fun buildWearSnapshot(+ candidates: List<WearPerson>,+ alerts: List<WearAlert> = emptyList(),+ sharingEnabled: Boolean = true,+ generatedAtMillis: Long,+): WearFindFamilySnapshot {+ val sorted = candidates.sortedWith(+ compareByDescending<WearPerson> { it.updatedAtMillis }.thenBy { it.id },+ ).map {+ it.copy(+ name = it.name.take(WearFindFamilyProtocol.MAX_NAME_CHARS),+ placeLabel = it.placeLabel.take(WearFindFamilyProtocol.MAX_PLACE_CHARS),+ )+ }+ fun snap(people: List<WearPerson>, dropped: Int) = WearFindFamilySnapshot(+ generatedAtMillis = generatedAtMillis,+ people = people,+ alerts = alerts,+ sharingEnabled = sharingEnabled,+ region = wearRegionFor(people),+ truncated = dropped > 0,+ droppedCount = dropped,+ totalPeople = sorted.size,+ )+ var kept = sorted+ var snapshot = snap(kept, 0)+ if (WearFindFamilyProtocol.json.encodeToString(snapshot).encodeToByteArray().size <=+ WearFindFamilyProtocol.MAX_JSON_BYTES+ ) return snapshot+ // Summarise harder before dropping anyone.+ kept = kept.map {+ it.copy(+ name = it.name.take(WearFindFamilyProtocol.SUMMARISED_NAME_CHARS),+ placeLabel = it.placeLabel.take(WearFindFamilyProtocol.SUMMARISED_PLACE_CHARS),+ )+ }+ snapshot = snap(kept, 0)+ while (kept.isNotEmpty() &&+ WearFindFamilyProtocol.json.encodeToString(snapshot).encodeToByteArray().size >+ WearFindFamilyProtocol.MAX_JSON_BYTES+ ) {+ kept = kept.dropLast(1)+ snapshot = snap(kept, sorted.size - kept.size)+ }+ return snapshot+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearRelative.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearRelative.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearRelative.ktnew file mode 100644index 0000000000..00ee6133ac--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearRelative.kt@@ -0,0 +1,65 @@+package com.vayunmathur.findfamily.wear.domain++import kotlin.math.sqrt++/** Human distance summary: metres under 1 km, one-decimal km beyond. */+fun wearFormatDistance(meters: Double): String = when {+ !meters.isFinite() || meters < 0 -> ""+ meters < 1_000 -> "${meters.toInt()} m"+ else -> "${((meters / 100.0).toInt() / 10.0)} km"+}++/** Short age for a timestamp: "just now", "5m ago", "2h ago", "3d ago"; "" when unknown. */+fun wearAgeLabel(atMillis: Long, nowMillis: Long): String {+ if (atMillis <= 0L) return ""+ val age = (nowMillis - atMillis).coerceAtLeast(0L)+ return when {+ age < 60_000L -> "just now"+ age < 3_600_000L -> "${age / 60_000L}m ago"+ age < 86_400_000L -> "${age / 3_600_000L}h ago"+ else -> "${age / 86_400_000L}d ago"+ }+}++/** Stale label for a person, e.g. "Stale · 2h ago"; empty when fresh. */+fun wearStaleLabel(person: WearPerson, nowMillis: Long): String =+ if (wearIsStale(person, nowMillis)) {+ val age = wearAgeLabel(person.updatedAtMillis, nowMillis)+ if (age.isEmpty()) "No location yet" else "Stale · $age"+ } else {+ ""+ }++/** Distance + compass summary from self to [person]; "" when either end lacks a fix. */+fun wearDistanceSummary(self: WearPerson?, person: WearPerson): String {+ if (self == null || self.latE7 == null || self.lonE7 == null) return ""+ if (person.latE7 == null || person.lonE7 == null || person.isSelf) return ""+ val dist = wearDistanceMeters(self.latE7, self.lonE7, person.latE7, person.lonE7)+ val bearing = wearBearingDegrees(self.latE7, self.lonE7, person.latE7, person.lonE7)+ return "${wearFormatDistance(dist)} ${wearCompass(bearing)}"+}++/**+ * North-up relative projection for the watch Canvas: centre at the+ * region centre, radius fits half the smaller viewport side. Pure so+ * the relative-view math is unit-testable without a Canvas.+ */+data class WearRelativeProjection(+ val viewportWidthPx: Float,+ val viewportHeightPx: Float,+ val radiusM: Int,+) {+ val pixelsPerMeter: Double+ get() = (minOf(viewportWidthPx, viewportHeightPx) / 2.0 / radiusM.coerceAtLeast(1))++ /** Screen (x, y) for metres east/north of the centre. North is up. */+ fun project(eastM: Double, northM: Double): Pair<Float, Float> {+ val x = viewportWidthPx / 2.0 + eastM * pixelsPerMeter+ val y = viewportHeightPx / 2.0 - northM * pixelsPerMeter+ return x.toFloat() to y.toFloat()+ }++ /** True when metres (e/n) fall inside the region radius. */+ fun inside(eastM: Double, northM: Double): Boolean =+ sqrt(eastM * eastM + northM * northM) <= radiusM+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/sync/WearLinkBridge.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/sync/WearLinkBridge.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..9f47469f66--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/sync/WearLinkBridge.kt@@ -0,0 +1,98 @@+package com.vayunmathur.findfamily.wear.sync++import android.content.Context+import com.vayunmathur.findfamily.wear.data.WearFindFamilyStore+import com.vayunmathur.findfamily.wear.domain.WearFindFamilyOp+import com.vayunmathur.findfamily.wear.domain.WearFindFamilyProtocol+import com.vayunmathur.findfamily.wear.domain.WearFindFamilySnapshot+import com.vayunmathur.findfamily.wear.domain.WearOpKind+import com.vayunmathur.findfamily.wear.domain.WearWatchState+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink for FindFamily: snapshot data items land in+ * [WearFindFamilyStore], watch state goes back as a data item, and+ * stop-sharing / refresh / request-sync are messages to the phone (the+ * source of truth — the watch never claims a phone change locally).+ * Delivery is bound to this process being alive.+ */+object WearLinkBridge {+ private const val TAG = "WearLinkBridge"+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile+ private var node: WearLinkNode? = null++ fun get(context: Context): WearLinkNode {+ val appContext = context.applicationContext+ return node ?: synchronized(this) {+ node ?: create(appContext).also { node = it }+ }+ }++ private fun create(context: Context): WearLinkNode {+ val store = WearFindFamilyStore.get(context)+ val listener = object : WearLinkListener {+ override fun onData(path: String, body: ByteArray) {+ if (path != WearFindFamilyProtocol.SNAPSHOT_PATH) return+ val snapshot = runCatching {+ WearFindFamilyProtocol.json.decodeFromString<WearFindFamilySnapshot>(body.decodeToString())+ }.getOrNull()+ if (snapshot == null) {+ Log.status(TAG, "ignoring malformed snapshot")+ return+ }+ store.setSnapshot(snapshot)+ }+ }+ val created = WearLinkNode(context, WearFindFamilyProtocol.CAPABILITY, listener)+ scope.launch {+ created.state.collect { linkState ->+ store.setConnected(linkState is WearLinkState.Connected)+ }+ }+ created.start()+ return created+ }++ fun publishWatchState(context: Context) {+ val snapshot = WearFindFamilyStore.get(context).snapshot.value+ val state = WearWatchState(+ appliedGeneratedAtMillis = snapshot.generatedAtMillis,+ peopleCount = snapshot.people.size,+ )+ scope.launch {+ get(context).putData(+ WearFindFamilyProtocol.WATCH_STATE_PATH,+ WearFindFamilyProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }+ }++ /** Ask the phone for a fresh snapshot; false when no session is live. */+ suspend fun requestSync(context: Context): Boolean =+ get(context).sendMessage(WearFindFamilyProtocol.REQUEST_SYNC_PATH, ByteArray(0))++ /** Stop sharing now on the phone (same switch as its Quick Settings tile). */+ suspend fun stopSharingNow(context: Context): Boolean = sendOp(context, WearOpKind.STOP_SHARING_NOW)++ /** Ask the phone to publish fresh locations (its freshest state + service reconcile). */+ suspend fun requestRefresh(context: Context): Boolean = sendOp(context, WearOpKind.REQUEST_REFRESH)++ private suspend fun sendOp(context: Context, kind: WearOpKind): Boolean =+ get(context).sendMessage(+ WearFindFamilyProtocol.OP_PATH,+ WearFindFamilyProtocol.json.encodeToString(+ WearFindFamilyOp(kind, System.currentTimeMillis()),+ ).encodeToByteArray(),+ requireAck = true,+ )+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearAllMapScreen.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearAllMapScreen.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearAllMapScreen.ktnew file mode 100644index 0000000000..d36057c50d--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearAllMapScreen.kt@@ -0,0 +1,114 @@+package com.vayunmathur.findfamily.wear.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.findfamily.wear.R+import com.vayunmathur.findfamily.wear.data.WearFindFamilyStore+import com.vayunmathur.findfamily.wear.domain.wearFormatDistance+import com.vayunmathur.findfamily.wear.domain.wearSnapshotIsStale++/**+ * All-people relative map: every located person plotted around the+ * snapshot region centre (you when located), markers keyed by initial+ * in the legend below. No basemap is drawn — relative position only,+ * with snapshot staleness labelled.+ */+@Composable+fun WearAllMapScreen(+ store: WearFindFamilyStore,+ onOpenPerson: (Long) -> Unit,+ onBack: () -> Unit,+) {+ val snapshot by store.snapshot.collectAsState()+ val connected by store.connected.collectAsState()+ val now = System.currentTimeMillis()+ val listState = rememberScalingLazyListState()+ val located = snapshot.people.filter { it.latE7 != null && it.lonE7 != null }++ ScalingLazyColumn(state = listState) {+ item {+ Text(+ stringResource(R.string.wear_map),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ if (!connected || wearSnapshotIsStale(snapshot, now)) {+ item {+ Text(+ if (!connected) stringResource(R.string.wear_offline)+ else stringResource(R.string.wear_stale_snapshot),+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ }+ item {+ Text(+ "Within ${wearFormatDistance(snapshot.region.radiusM.toDouble())} of centre",+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ if (located.isEmpty()) {+ item {+ Text(+ stringResource(R.string.wear_no_location),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ item {+ Box(Modifier.fillMaxWidth().height(190.dp).padding(horizontal = 4.dp)) {+ WearRelativeCanvas(+ region = snapshot.region,+ people = located,+ nowMillis = now,+ )+ }+ }+ items(located, key = { it.id }) { person ->+ Chip(+ onClick = { onOpenPerson(person.id) },+ label = {+ Text("${wearMarkerInitial(person.name)} — ${person.name}", maxLines = 1)+ },+ secondaryLabel = {+ Text(person.placeLabel.ifBlank { stringResource(R.string.wear_no_location) }, maxLines = 1)+ },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ item {+ Chip(+ onClick = onBack,+ label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearMainActivity.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearMainActivity.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..f6c8859b6c--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearMainActivity.kt@@ -0,0 +1,50 @@+package com.vayunmathur.findfamily.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.findfamily.wear.data.WearFindFamilyStore+import com.vayunmathur.findfamily.wear.sync.WearLinkBridge++/**+ * Watch FindFamily entry: people home, per-person detail and the+ * all-people relative map, rendered only from the locally stored+ * snapshot so it works standalone (phone absent, cold start).+ */+class WearMainActivity : ComponentActivity() {++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+ val store = WearFindFamilyStore.get(this)+ WearLinkBridge.get(this)+ WearLinkBridge.publishWatchState(this)+ setContent {+ MaterialTheme {+ var route by remember { mutableStateOf<WearRoute>(WearRoute.People) }+ when (val current = route) {+ WearRoute.People -> WearPeopleScreen(+ store = store,+ onOpenPerson = { route = WearRoute.Person(it) },+ onOpenMap = { route = WearRoute.AllMap },+ )+ is WearRoute.Person -> WearPersonScreen(+ store = store,+ personId = current.personId,+ onBack = { route = WearRoute.People },+ )+ WearRoute.AllMap -> WearAllMapScreen(+ store = store,+ onOpenPerson = { route = WearRoute.Person(it) },+ onBack = { route = WearRoute.People },+ )+ }+ }+ }+ }+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPeopleScreen.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPeopleScreen.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPeopleScreen.ktnew file mode 100644index 0000000000..f7fcd16cbc--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPeopleScreen.kt@@ -0,0 +1,214 @@+package com.vayunmathur.findfamily.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.findfamily.wear.R+import com.vayunmathur.findfamily.wear.data.WearFindFamilyStore+import com.vayunmathur.findfamily.wear.domain.WearAlertKind+import com.vayunmathur.findfamily.wear.domain.WearMotion+import com.vayunmathur.findfamily.wear.domain.wearAgeLabel+import com.vayunmathur.findfamily.wear.domain.wearDistanceSummary+import com.vayunmathur.findfamily.wear.domain.wearSnapshotIsStale+import com.vayunmathur.findfamily.wear.domain.wearStaleLabel+import com.vayunmathur.findfamily.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/**+ * People home: EVERY person in the phone circle, most recently updated+ * first, with place, distance/direction from you, last-update age,+ * battery and motion — from the local snapshot (offline-safe, stale+ * labelled). Actions ask the phone; nothing here claims a phone change.+ */+@Composable+fun WearPeopleScreen(+ store: WearFindFamilyStore,+ onOpenPerson: (Long) -> Unit,+ onOpenMap: () -> Unit,+) {+ val snapshot by store.snapshot.collectAsState()+ val connected by store.connected.collectAsState()+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ var note by remember { mutableStateOf<String?>(null) }+ val requestedText = stringResource(R.string.wear_requested)+ val noPhoneText = stringResource(R.string.wear_no_phone)+ val now = System.currentTimeMillis()+ val self = snapshot.people.firstOrNull { it.isSelf }+ val listState = rememberScalingLazyListState()++ ScalingLazyColumn(state = listState) {+ item {+ Text(+ stringResource(R.string.app_name),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ item {+ Text(+ if (snapshot.sharingEnabled) stringResource(R.string.wear_sharing_on)+ else stringResource(R.string.wear_sharing_off),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),+ )+ }+ if (!connected) {+ item {+ Text(+ stringResource(R.string.wear_offline),+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else if (wearSnapshotIsStale(snapshot, now)) {+ item {+ Text(+ stringResource(R.string.wear_stale_snapshot),+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ }+ if (snapshot.truncated) {+ item {+ Text(+ stringResource(R.string.wear_truncated, snapshot.people.size, snapshot.totalPeople),+ style = MaterialTheme.typography.caption2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),+ )+ }+ }+ note?.let { text ->+ item {+ Text(+ text,+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),+ )+ }+ }+ if (snapshot.people.isEmpty()) {+ item {+ Text(+ stringResource(R.string.wear_empty),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ items(snapshot.people, key = { it.id }) { person ->+ val place = person.placeLabel.ifBlank { stringResource(R.string.wear_no_location) }+ val distance = wearDistanceSummary(self, person)+ val age = wearAgeLabel(person.updatedAtMillis, now)+ val battery = if (person.batteryPercent >= 0) " · ${person.batteryPercent}%" else ""+ val motion = when (person.motion) {+ WearMotion.MOVING -> " · Moving"+ WearMotion.STATIONARY -> " · Still"+ WearMotion.UNKNOWN -> ""+ }+ val stale = wearStaleLabel(person, now)+ Chip(+ onClick = { onOpenPerson(person.id) },+ label = {+ Text(+ if (person.isSelf) "${person.name} (${stringResource(R.string.wear_you)})" else person.name,+ maxLines = 1,+ )+ },+ secondaryLabel = {+ Text(+ listOf(place, distance, age, stale).filter { it.isNotBlank() }+ .joinToString(" · ") + battery + motion,+ maxLines = 2,+ )+ },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ // Alerts: current saved-place state + no-show rows from the phone.+ if (snapshot.alerts.isNotEmpty()) {+ item {+ Text(+ stringResource(R.string.wear_alerts),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ items(snapshot.alerts.take(10), key = { "${it.kind}-${it.personId}-${it.atMillis}" }) { alert ->+ val personName = snapshot.people.firstOrNull { it.id == alert.personId }?.name ?: "?"+ Text(+ when (alert.kind) {+ WearAlertKind.AT_PLACE -> "$personName at ${alert.placeLabel}"+ WearAlertKind.NOSHOW ->+ if (alert.fired) "$personName did not arrive${if (alert.placeLabel.isNotBlank()) " at ${alert.placeLabel}" else ""}"+ else "$personName expected${if (alert.placeLabel.isNotBlank()) " at ${alert.placeLabel}" else ""}"+ },+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),+ )+ }+ }+ item {+ Chip(+ onClick = onOpenMap,+ label = { Text(stringResource(R.string.wear_map), maxLines = 1) },+ colors = ChipDefaults.primaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ item {+ Chip(+ onClick = {+ scope.launch {+ note = if (WearLinkBridge.requestRefresh(context)) requestedText else noPhoneText+ }+ },+ label = { Text(stringResource(R.string.wear_refresh), maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ item {+ Chip(+ onClick = {+ scope.launch {+ note = if (WearLinkBridge.stopSharingNow(context)) requestedText else noPhoneText+ }+ },+ label = { Text(stringResource(R.string.wear_stop_sharing), maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPersonScreen.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPersonScreen.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPersonScreen.ktnew file mode 100644index 0000000000..f7b22000d3--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearPersonScreen.kt@@ -0,0 +1,124 @@+package com.vayunmathur.findfamily.wear.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.findfamily.wear.R+import com.vayunmathur.findfamily.wear.data.WearFindFamilyStore+import com.vayunmathur.findfamily.wear.domain.WearMotion+import com.vayunmathur.findfamily.wear.domain.wearAgeLabel+import com.vayunmathur.findfamily.wear.domain.wearDistanceSummary+import com.vayunmathur.findfamily.wear.domain.wearRegionFor+import com.vayunmathur.findfamily.wear.domain.wearStaleLabel++/**+ * Per-person detail (Route carries [personId]): precise fix age,+ * accuracy, place label, battery/motion, and a relative view centred+ * on you (region centre) with this person highlighted. Stale fixes are+ * labelled with their age — precision is never faked.+ */+@Composable+fun WearPersonScreen(+ store: WearFindFamilyStore,+ personId: Long,+ onBack: () -> Unit,+) {+ val snapshot by store.snapshot.collectAsState()+ val person = snapshot.people.firstOrNull { it.id == personId }+ val self = snapshot.people.firstOrNull { it.isSelf }+ val now = System.currentTimeMillis()+ val listState = rememberScalingLazyListState()+ val noLocationText = stringResource(R.string.wear_no_location)+ val lines: List<String> = if (person == null) {+ emptyList()+ } else {+ buildList {+ add(person.placeLabel.ifBlank { noLocationText })+ wearDistanceSummary(self, person).takeIf { it.isNotBlank() }?.let { add(it) }+ val age = wearAgeLabel(person.updatedAtMillis, now)+ if (age.isNotBlank()) add("Updated $age")+ wearStaleLabel(person, now).takeIf { it.isNotBlank() }?.let { add(it) }+ if (person.accuracyMeters >= 0) add("Accuracy ±${person.accuracyMeters} m")+ if (person.source == "NETWORK_SIGHTING") add("Seen nearby by another phone — approximate")+ if (person.source == "SHUTDOWN") add("Last fix before that phone switched off")+ if (person.source == "BATTERY_LOW") add("Last fix before that phone ran low")+ if (person.batteryPercent >= 0) add("Battery ${person.batteryPercent}%")+ add(+ when (person.motion) {+ WearMotion.MOVING -> "Moving"+ WearMotion.STATIONARY -> "Stationary"+ WearMotion.UNKNOWN -> "Motion unknown"+ },+ )+ if (person.placeSinceMillis > 0L && person.placeLabel.isNotBlank()) {+ val since = wearAgeLabel(person.placeSinceMillis, now)+ if (since.isNotBlank()) add("At this place since $since")+ }+ }+ }++ ScalingLazyColumn(state = listState) {+ item {+ Text(+ person?.name ?: "?",+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ if (person == null) {+ item {+ Text(+ stringResource(R.string.wear_no_location),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ val region = wearRegionFor(listOfNotNull(self, person))+ if (region.hasCenter && person.latE7 != null) {+ item {+ Box(Modifier.fillMaxWidth().height(150.dp).padding(horizontal = 8.dp)) {+ WearRelativeCanvas(+ region = region,+ people = listOfNotNull(self, person),+ nowMillis = now,+ highlightId = person.id,+ )+ }+ }+ }+ items(lines.size) { index ->+ Text(+ lines[index],+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),+ )+ }+ }+ item {+ Chip(+ onClick = onBack,+ label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+}
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRelativeCanvas.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRelativeCanvas.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRelativeCanvas.ktnew file mode 100644index 0000000000..85b8b8baad--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRelativeCanvas.kt@@ -0,0 +1,90 @@+package com.vayunmathur.findfamily.wear.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import com.vayunmathur.findfamily.wear.domain.WearPerson+import com.vayunmathur.findfamily.wear.domain.WearRegion+import com.vayunmathur.findfamily.wear.domain.WearRelativeProjection+import com.vayunmathur.findfamily.wear.domain.wearRelativeOffsetMeters++private val CentreColor = Color(0xFF4DA3FF)+private val PersonColor = Color(0xFF7EE081)+private val StaleColor = Color(0xFF9AA3AD)+private val RingColor = Color(0xFF394149)++/**+ * Relative-position renderer: no basemap is faked — people are plotted+ * as labelled markers (first initial) at their true metres east/north+ * of the region centre, with the centre (you, when located) in the+ * middle. [highlightId] draws one person larger (detail view). Markers+ * outside the region radius are clamped to the rim, never hidden.+ */+@Composable+fun WearRelativeCanvas(+ region: WearRegion,+ people: List<WearPerson>,+ nowMillis: Long,+ highlightId: Long? = null,+) {+ Canvas(Modifier.fillMaxSize()) {+ drawRect(Color(0xFF101613))+ if (!region.hasCenter) return@Canvas+ val projection = WearRelativeProjection(size.width, size.height, region.radiusM)+ // Range rings at 1/3 and 2/3 radius for scale honesty.+ for (fraction in listOf(1f / 3f, 2f / 3f, 1f)) {+ drawCircle(+ RingColor,+ radius = (size.minDimension / 2f) * fraction,+ center = Offset(size.width / 2f, size.height / 2f),+ style = androidx.compose.ui.graphics.drawscope.Stroke(width = 1.5f),+ )+ }+ // North tick.+ drawLine(+ Color.White,+ Offset(size.width / 2f, 6f),+ Offset(size.width / 2f, 18f),+ strokeWidth = 3f,+ )+ for (person in people) {+ val lat = person.latE7 ?: continue+ val lon = person.lonE7 ?: continue+ var (east, north) = wearRelativeOffsetMeters(region.centerLatE7, region.centerLonE7, lat, lon)+ if (!projection.inside(east, north)) {+ val scale = region.radiusM / kotlin.math.sqrt(east * east + north * north)+ east *= scale+ north *= scale+ }+ val (x, y) = projection.project(east, north)+ val stale = com.vayunmathur.findfamily.wear.domain.wearIsStale(person, nowMillis)+ val isCentre = person.isSelf+ val highlighted = person.id == highlightId+ val radius = when {+ isCentre -> 9f+ highlighted -> 11f+ else -> 8f+ }+ drawCircle(Color.White, radius = radius + 2f, center = Offset(x, y))+ drawCircle(+ when {+ isCentre -> CentreColor+ stale -> StaleColor+ else -> PersonColor+ },+ radius = radius,+ center = Offset(x, y),+ )+ }+ // Centre dot when self has no separate marker at the exact centre.+ drawCircle(Color.White, radius = 5f, center = Offset(size.width / 2f, size.height / 2f))+ drawCircle(CentreColor, radius = 3.5f, center = Offset(size.width / 2f, size.height / 2f))+ }+}++/** One-letter marker label for a person (initial), "?" when blank. */+fun wearMarkerInitial(name: String): String =+ name.trim().firstOrNull()?.uppercaseChar()?.toString() ?: "?"
findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRoute.kt
diff --git a/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRoute.kt b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..700ce651f7--- /dev/null+++ b/findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/ui/WearRoute.kt@@ -0,0 +1,13 @@+package com.vayunmathur.findfamily.wear.ui++/** Watch navigation: detail routes carry the person id, never selection state. */+sealed interface WearRoute {+ /** Every person in the circle (home). */+ data object People : WearRoute++ /** One person's location detail, identified by phone user id. */+ data class Person(val personId: Long) : WearRoute++ /** All-people relative map around the snapshot region centre. */+ data object AllMap : WearRoute+}
findfamily-wear/src/main/res/values/colors.xml
diff --git a/findfamily-wear/src/main/res/values/colors.xml b/findfamily-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..f42ada656e--- /dev/null+++ b/findfamily-wear/src/main/res/values/colors.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <color name="ic_launcher_background">#FFFFFF</color>+</resources>
findfamily-wear/src/main/res/values/strings.xml
diff --git a/findfamily-wear/src/main/res/values/strings.xml b/findfamily-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..569748ef81--- /dev/null+++ b/findfamily-wear/src/main/res/values/strings.xml@@ -0,0 +1,20 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">FindFamily</string>+ <string name="wear_empty">No people synced yet. Open FindFamily on your phone to sync this watch.</string>+ <string name="wear_people">People</string>+ <string name="wear_map">Map</string>+ <string name="wear_refresh">Refresh</string>+ <string name="wear_stop_sharing">Stop sharing now</string>+ <string name="wear_sharing_on">Sharing on</string>+ <string name="wear_sharing_off">Sharing stopped</string>+ <string name="wear_requested">Asked your phone</string>+ <string name="wear_no_phone">Phone not reachable — showing the last synced copy</string>+ <string name="wear_offline">Offline — last synced copy</string>+ <string name="wear_stale_snapshot">Stale snapshot</string>+ <string name="wear_truncated">Showing %1$d of %2$d people — the rest would not fit; most recent kept</string>+ <string name="wear_alerts">Alerts</string>+ <string name="wear_back">Back</string>+ <string name="wear_no_location">No location yet</string>+ <string name="wear_you">You</string>+</resources>
findfamily-wear/src/test/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocolTest.kt
diff --git a/findfamily-wear/src/test/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocolTest.kt b/findfamily-wear/src/test/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocolTest.ktnew file mode 100644index 0000000000..aade0d480b--- /dev/null+++ b/findfamily-wear/src/test/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocolTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.findfamily.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearFindFamilyProtocolTest {++ private fun person(+ id: Long,+ updatedAt: Long,+ name: String = "Person $id",+ place: String = "Home",+ ) = WearPerson(+ id = id,+ name = name,+ placeLabel = place,+ latE7 = 377_749_000,+ lonE7 = -1_224_194_000,+ updatedAtMillis = updatedAt,+ )++ @Test+ fun goldenSnapshotJson() {+ val snapshot = WearFindFamilySnapshot(+ generatedAtMillis = 1_000L,+ people = listOf(person(7L, 900L, name = "Ada")),+ region = WearRegion(377_749_000, -1_224_194_000, 200, true),+ totalPeople = 1,+ )+ assertEquals(+ """{"generatedAtMillis":1000,"people":[{"id":7,"name":"Ada","placeLabel":"Home",""" ++ """"latE7":377749000,"lonE7":-1224194000,"updatedAtMillis":900}],""" ++ """"region":{"centerLatE7":377749000,"centerLonE7":-1224194000,""" ++ """"hasCenter":true},"totalPeople":1}""",+ WearFindFamilyProtocol.json.encodeToString(snapshot),+ )+ }++ @Test+ fun goldenStopSharingOpJson() {+ val op = WearFindFamilyOp(WearOpKind.STOP_SHARING_NOW, 123L)+ assertEquals(+ """{"kind":"STOP_SHARING_NOW","requestedAtMillis":123}""",+ WearFindFamilyProtocol.json.encodeToString(op),+ )+ val refresh = WearFindFamilyOp(WearOpKind.REQUEST_REFRESH, 456L)+ assertEquals(+ """{"kind":"REQUEST_REFRESH","requestedAtMillis":456}""",+ WearFindFamilyProtocol.json.encodeToString(refresh),+ )+ }++ @Test+ fun snapshotRoundTrips() {+ val snapshot = WearFindFamilySnapshot(+ generatedAtMillis = 9L,+ people = listOf(person(1L, 10L), person(2L, 20L)),+ alerts = listOf(WearAlert(WearAlertKind.NOSHOW, 2L, "School", 30L, fired = true)),+ sharingEnabled = false,+ region = WearRegion(377_749_000, -1_224_194_000, 500, true),+ truncated = true,+ droppedCount = 3,+ totalPeople = 5,+ )+ assertEquals(+ snapshot,+ WearFindFamilyProtocol.json.decodeFromString<WearFindFamilySnapshot>(+ WearFindFamilyProtocol.json.encodeToString(snapshot),+ ),+ )+ }++ @Test+ fun allPeopleCompletenessNoSilentDrop() {+ val candidates = (1L..200L).map { person(it, it * 1_000L) }+ val snapshot = buildWearSnapshot(candidates, generatedAtMillis = 999_000L)+ assertEquals(200, snapshot.people.size)+ assertEquals(200, snapshot.totalPeople)+ assertFalse(snapshot.truncated)+ assertEquals(0, snapshot.droppedCount)+ // Most recently updated first.+ assertEquals(200L, snapshot.people.first().id)+ assertEquals(1L, snapshot.people.last().id)+ }++ @Test+ fun hardCapDropsOldestAndSaysSo() {+ val candidates = (1L..2_000L).map {+ person(it, it, name = "N".repeat(100), place = "P".repeat(120))+ }+ val snapshot = buildWearSnapshot(candidates, generatedAtMillis = 0L)+ assertTrue(snapshot.truncated)+ assertTrue(snapshot.droppedCount > 0)+ assertEquals(2_000, snapshot.totalPeople)+ assertEquals(snapshot.totalPeople - snapshot.droppedCount, snapshot.people.size)+ // Most recent survives; oldest are the ones dropped.+ assertEquals(2_000L, snapshot.people.first().id)+ val bytes = WearFindFamilyProtocol.json.encodeToString(snapshot).encodeToByteArray().size+ assertTrue(bytes <= WearFindFamilyProtocol.MAX_JSON_BYTES, "snapshot $bytes over cap")+ }++ @Test+ fun summarisingCapsFieldsBeforeDropping() {+ val snapshot = buildWearSnapshot(+ listOf(person(1L, 1L, name = "N".repeat(100), place = "P".repeat(120))),+ generatedAtMillis = 0L,+ )+ assertEquals(WearFindFamilyProtocol.MAX_NAME_CHARS, snapshot.people.single().name.length)+ assertEquals(WearFindFamilyProtocol.MAX_PLACE_CHARS, snapshot.people.single().placeLabel.length)+ assertFalse(snapshot.truncated)+ }++ @Test+ fun stalenessLabelling() {+ val fresh = person(1L, 1_000_000L)+ val now = 1_000_000L + WearFindFamilyProtocol.STALE_AFTER_MS+ assertFalse(wearIsStale(fresh, now))+ assertTrue(wearIsStale(fresh, now + 1L))+ assertTrue(wearIsStale(person(2L, 0L), now))+ assertEquals("Stale · 31m ago", wearStaleLabel(fresh, now + 60_000L))+ assertTrue(wearSnapshotIsStale(WearFindFamilySnapshot(generatedAtMillis = 0L), now))+ assertFalse(wearSnapshotIsStale(WearFindFamilySnapshot(generatedAtMillis = now), now))+ }++ @Test+ fun relativeViewMath() {+ // 0.01 degrees north of equator is about 1.11 km.+ val north = wearDistanceMeters(0, 0, 100_000, 0)+ assertTrue(north in 1_100.0..1_125.0, "north distance $north")+ assertEquals(90, wearBearingDegrees(0, 0, 0, 100_000))+ assertEquals(0, wearBearingDegrees(0, 0, 100_000, 0))+ assertEquals("E", wearCompass(90))+ assertEquals("N", wearCompass(0))+ assertEquals("NE", wearCompass(45))+ val (east, northM) = wearRelativeOffsetMeters(0, 0, 0, 100_000)+ assertTrue(east in 1_100.0..1_125.0 && northM == 0.0, "offset $east/$northM")+ val projection = WearRelativeProjection(200f, 200f, 100)+ assertEquals(100f to 100f, projection.project(0.0, 0.0))+ assertEquals(200f to 100f, projection.project(100.0, 0.0))+ assertEquals(100f to 0f, projection.project(0.0, 100.0))+ assertTrue(projection.inside(60.0, 60.0))+ assertFalse(projection.inside(90.0, 90.0))+ }++ @Test+ fun motionFromSpeed() {+ assertEquals(WearMotion.MOVING, wearMotionFor(2.0f, true))+ assertEquals(WearMotion.STATIONARY, wearMotionFor(0.0f, true))+ assertEquals(WearMotion.UNKNOWN, wearMotionFor(null, true))+ assertEquals(WearMotion.UNKNOWN, wearMotionFor(5.0f, false))+ }++ @Test+ fun regionCentresOnSelfAndCoversEveryone() {+ val self = person(1L, 100L).copy(isSelf = true)+ val far = person(2L, 90L).copy(latE7 = 387_749_000) // ~111 km north+ val region = wearRegionFor(listOf(far, self))+ assertEquals(self.latE7, region.centerLatE7)+ assertTrue(region.hasCenter)+ assertEquals(100_000, region.radiusM)+ assertEquals(WearRegion(), wearRegionFor(listOf(person(3L, 1L).copy(latE7 = null, lonE7 = null))))+ }++ @Test+ fun distanceSummaryAndAge() {+ val self = person(1L, 100L).copy(isSelf = true)+ val other = person(2L, 100L).copy(latE7 = 378_749_000) // ~11 km north+ assertTrue(wearDistanceSummary(self, other).endsWith(" N"))+ assertEquals("", wearDistanceSummary(null, other))+ assertEquals("just now", wearAgeLabel(1_000L, 30_000L))+ assertEquals("5m ago", wearAgeLabel(0L + 1_000L, 1_000L + 5 * 60_000L))+ assertEquals("2h ago", wearAgeLabel(1_000L, 1_000L + 2 * 3_600_000L))+ assertEquals("500 m", wearFormatDistance(500.0))+ assertEquals("1.5 km", wearFormatDistance(1_500.0))+ }+}
findfamily/build.gradle.kts
diff --git a/findfamily/build.gradle.kts b/findfamily/build.gradle.ktsindex 16ff6823e3..fc3a3f2d4e 100644--- a/findfamily/build.gradle.kts+++ b/findfamily/build.gradle.kts@@ -125,6 +125,7 @@ dependencies { implementation(project(":library:image")) implementation(project(":library:map"))+ implementation(project(":library:wearlink")) // @SystemApi android.nearby.NearbyManager, for powered-off finding. Present at runtime, // absent from the public SDK, and must NOT be packaged. See :library:aosp-stubs. compileOnly(project(":library:aosp-stubs"))
findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.ktindex 370e3f44ff..0369a2cd59 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt@@ -54,6 +54,10 @@ class MainActivity : MaActivity() { private val noShowTarget = mutableStateOf<Pair<Long, Long?>?>(null) override fun onCreateBeforeContent() {+ com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+ // Wear companion sync lives and dies with this process (WearLink has+ // no system wakeup); it republishes on reconnect and on data changes.+ com.vayunmathur.findfamily.sync.WearFindFamilySync.get(this).start() deepLinkAddInvite.value = parseAddDeepLink(intent) noShowTarget.value = parseNoShowTarget(intent) // FIRST_PARTY: api.maproj.org + data.maproj.org (Cloudflare ISRG+GTS).
findfamily/src/main/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocol.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocol.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocol.ktnew file mode 100644index 0000000000..ffe7608dbc--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocol.kt@@ -0,0 +1,297 @@+package com.vayunmathur.findfamily.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Phone <-> watch protocol for the Wear OS FindFamily companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module+ * (`:findfamily-wear`, applicationId `com.vayunmathur.findfamily`) carries+ * a copy of this file under `com.vayunmathur.findfamily.wear.domain`.+ * Change both copies together; each side's unit tests pin the same golden+ * JSON so a one-sided edit fails loudly.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [SNAPSHOT_PATH] phone -> watch (all-people location+ * summaries) and [WATCH_STATE_PATH] watch -> phone.+ * - Messages: [OP_PATH] watch -> phone (stop-sharing / request-refresh)+ * and [REQUEST_SYNC_PATH] watch -> phone (ask for a fresh snapshot).+ * Delivery needs a live session; nothing wakes a dead phone process.+ *+ * Owner rule: the watch shows ALL people in the phone circle. The payload+ * is bounded by summarising (short labels, E7 coordinates, no history),+ * never by a top-N people cap in normal operation. Only if the byte cap+ * still cannot fit everyone does [buildWearSnapshot] drop the+ * least-recently-updated people, and then it says so honestly via+ * `truncated` + `droppedCount`, keeping most-recent first.+ *+ * Privacy: a person entry is exactly what the phone's own cards show —+ * current place label, current coordinate at E7 precision, fix/report+ * times, accuracy, speed-derived motion, battery. No location history,+ * no track, no keys, no pair ids. E2EE stays phone-side: the phone+ * decrypts peer reports into its Room store and only these already-+ * decrypted summaries cross WearLink (Bluetooth-bonded, cert-bound).+ */+object WearFindFamilyProtocol {+ /** WearLink appId the phone requires in the peer handshake. */+ const val CAPABILITY = "findfamily_wear_companion"++ /** Data-item path (phone -> watch): the [WearFindFamilySnapshot] JSON. */+ const val SNAPSHOT_PATH = "/findfamily/snapshot"++ /** Data-item path (watch -> phone): the [WearWatchState] JSON. */+ const val WATCH_STATE_PATH = "/findfamily/watch-state"++ /** Message path (watch -> phone): one [WearFindFamilyOp] JSON. */+ const val OP_PATH = "/findfamily/op"++ /** Message path (watch -> phone): ask the phone to publish a fresh snapshot. */+ const val REQUEST_SYNC_PATH = "/findfamily/request-sync"++ /** Largest snapshot JSON in UTF-8 bytes; summarise/drop-oldest to fit. */+ const val MAX_JSON_BYTES = 90_000++ /** Field caps applied when a snapshot is built. */+ const val MAX_NAME_CHARS = 60+ const val MAX_PLACE_CHARS = 80++ /** Tighter caps used as the first summarising step before anyone is dropped. */+ const val SUMMARISED_NAME_CHARS = 24+ const val SUMMARISED_PLACE_CHARS = 24++ /** A fix older than this (watch clock vs fix time) reads stale, never live. */+ const val STALE_AFTER_MS = 30 * 60_000L++ /** Speed (m/s) at/above which a person counts as moving for the watch summary. */+ const val MOVING_SPEED_MPS = 1.0++ /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+ val json: Json = Json { ignoreUnknownKeys = true }+}++/** Motion summary derived phone-side from the fix's reported speed. */+@Serializable+enum class WearMotion { MOVING, STATIONARY, UNKNOWN }++/** Kind of watch-readable alert state carried in a snapshot. */+@Serializable+enum class WearAlertKind { AT_PLACE, NOSHOW }++/** One person trimmed to watch size: the phone card, summarised. No history. */+@Serializable+data class WearPerson(+ val id: Long,+ val name: String,+ /** Saved-place/locality label the phone UI shows ("Home"), "" when unnamed. */+ val placeLabel: String = "",+ /** When the person arrived at [placeLabel] (phone `lastLocationChangeTime`), 0 unknown. */+ val placeSinceMillis: Long = 0L,+ /** Current coordinate, degrees * 1e7 (the precision the phone map shows); null = no fix. */+ val latE7: Int? = null,+ val lonE7: Int? = null,+ /** Fix accuracy radius (m); -1 when the source gives none (e.g. network sighting). */+ val accuracyMeters: Int = -1,+ /** When the position was measured (epoch millis); 0 = no fix. */+ val updatedAtMillis: Long = 0L,+ /** When the report was sent; differs from measured time on parting reports. */+ val reportedAtMillis: Long = 0L,+ /** Battery percent 0..100; -1 when unavailable (incl. network sightings). */+ val batteryPercent: Int = -1,+ val motion: WearMotion = WearMotion.UNKNOWN,+ /** Wire source name (LIVE/SHUTDOWN/BATTERY_LOW/NETWORK_SIGHTING); "" when no fix. */+ val source: String = "",+ /** Whether the phone is sharing this device's location with this person. */+ val sharingEnabled: Boolean = true,+ val isSelf: Boolean = false,+)++/**+ * Watch-readable alert state. The phone persists current place + since+ * (not an enter/leave event log), so AT_PLACE is the honest enter state;+ * NOSHOW mirrors the phone's no-show rows (pending and fired).+ */+@Serializable+data class WearAlert(+ val kind: WearAlertKind,+ val personId: Long,+ val placeLabel: String = "",+ val atMillis: Long = 0L,+ val fired: Boolean = false,+)++/** Bounded region around the snapshot centre with everyone's markers relative to it. */+@Serializable+data class WearRegion(+ val centerLatE7: Int = 0,+ val centerLonE7: Int = 0,+ /** Radius (m) covering centre -> farthest located person, clamped for rendering. */+ val radiusM: Int = 200,+ val hasCenter: Boolean = false,+)++/** The phone's all-people snapshot for the watch ([WearFindFamilyProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearFindFamilySnapshot(+ val generatedAtMillis: Long = 0L,+ /** Every person in the circle, most recently updated first. */+ val people: List<WearPerson> = emptyList(),+ val alerts: List<WearAlert> = emptyList(),+ /** Global sharing switch on the phone (Quick Settings tile semantics). */+ val sharingEnabled: Boolean = true,+ val region: WearRegion = WearRegion(),+ /** True only when the byte cap forced people out; see [droppedCount]. */+ val truncated: Boolean = false,+ val droppedCount: Int = 0,+ /** People before any cap drop, so the watch can state the full circle size. */+ val totalPeople: Int = 0,+)++/** What the watch last applied, published at [WearFindFamilyProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+ val appliedGeneratedAtMillis: Long = 0L,+ val peopleCount: Int = 0,+)++/** Watch-originated actions; the phone remains the source of truth for both. */+@Serializable+enum class WearOpKind { STOP_SHARING_NOW, REQUEST_REFRESH }++/** One watch-originated action, as [WearFindFamilyProtocol.OP_PATH]. */+@Serializable+data class WearFindFamilyOp(+ val kind: WearOpKind,+ val requestedAtMillis: Long = 0L,+)++/** Motion from reported speed; no speed (or a sighting) is honestly UNKNOWN. */+fun wearMotionFor(speedMps: Float?, hasFix: Boolean): WearMotion = when {+ !hasFix || speedMps == null || !speedMps.isFinite() -> WearMotion.UNKNOWN+ speedMps >= WearFindFamilyProtocol.MOVING_SPEED_MPS -> WearMotion.MOVING+ else -> WearMotion.STATIONARY+}++/** True when a person's fix is missing or older than the stale window. */+fun wearIsStale(person: WearPerson, nowMillis: Long): Boolean =+ person.updatedAtMillis <= 0L || nowMillis - person.updatedAtMillis > WearFindFamilyProtocol.STALE_AFTER_MS++/** True when the whole snapshot has aged out (offline reading must label it). */+fun wearSnapshotIsStale(snapshot: WearFindFamilySnapshot?, nowMillis: Long): Boolean =+ snapshot == null || nowMillis - snapshot.generatedAtMillis > WearFindFamilyProtocol.STALE_AFTER_MS++/** Haversine distance (m) between two E7 positions. */+fun wearDistanceMeters(lat1E7: Int, lon1E7: Int, lat2E7: Int, lon2E7: Int): Double {+ val r = 6_371_000.0+ val dLat = Math.toRadians((lat2E7 - lat1E7) / 1e7)+ val dLon = Math.toRadians((lon2E7 - lon1E7) / 1e7)+ val a = sin(dLat / 2) * sin(dLat / 2) ++ cos(Math.toRadians(lat1E7 / 1e7)) * cos(Math.toRadians(lat2E7 / 1e7)) *+ sin(dLon / 2) * sin(dLon / 2)+ return 2 * r * kotlin.math.asin(sqrt(a.coerceIn(0.0, 1.0)))+}++/** Initial bearing (degrees clockwise from north, 0..359) from first E7 point to second. */+fun wearBearingDegrees(lat1E7: Int, lon1E7: Int, lat2E7: Int, lon2E7: Int): Int {+ val lat1 = Math.toRadians(lat1E7 / 1e7)+ val lat2 = Math.toRadians(lat2E7 / 1e7)+ val dLon = Math.toRadians((lon2E7 - lon1E7) / 1e7)+ val y = sin(dLon) * cos(lat2)+ val x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)+ val deg = Math.toDegrees(atan2(y, x))+ return ((deg % 360.0) + 360.0).toInt() % 360+}++/** 8-wind compass label for a bearing ("N", "NE", ...). */+fun wearCompass(bearingDeg: Int): String {+ val winds = arrayOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")+ return winds[(((bearingDeg % 360) + 360) % 360 + 22) / 45 % 8]+}++/** Metres east/north of an origin for a target E7 position (relative-view math). */+fun wearRelativeOffsetMeters(+ originLatE7: Int,+ originLonE7: Int,+ latE7: Int,+ lonE7: Int,+): Pair<Double, Double> {+ val east = (lonE7 - originLonE7) / 1e7 * 111_320.0 * cos(Math.toRadians(originLatE7 / 1e7))+ val north = (latE7 - originLatE7) / 1e7 * 110_540.0+ return east to north+}++/** Region centred on self (else first located person) covering every located person. */+fun wearRegionFor(people: List<WearPerson>): WearRegion {+ val located = people.filter { it.latE7 != null && it.lonE7 != null }+ if (located.isEmpty()) return WearRegion()+ val centre = located.firstOrNull { it.isSelf } ?: located.first()+ val maxDist = located.maxOf {+ wearDistanceMeters(centre.latE7!!, centre.lonE7!!, it.latE7!!, it.lonE7!!)+ }+ return WearRegion(+ centerLatE7 = centre.latE7!!,+ centerLonE7 = centre.lonE7!!,+ radiusM = maxDist.toInt().coerceIn(200, 100_000),+ hasCenter = true,+ )+}++/**+ * Builds the all-people snapshot: most-recently-updated first, field caps+ * applied, then — only to fit [WearFindFamilyProtocol.MAX_JSON_BYTES] —+ * tighter summarising, and only then dropping least-recent people with+ * `truncated`/`droppedCount` set. Normal circles lose nobody.+ */+fun buildWearSnapshot(+ candidates: List<WearPerson>,+ alerts: List<WearAlert> = emptyList(),+ sharingEnabled: Boolean = true,+ generatedAtMillis: Long,+): WearFindFamilySnapshot {+ val sorted = candidates.sortedWith(+ compareByDescending<WearPerson> { it.updatedAtMillis }.thenBy { it.id },+ ).map {+ it.copy(+ name = it.name.take(WearFindFamilyProtocol.MAX_NAME_CHARS),+ placeLabel = it.placeLabel.take(WearFindFamilyProtocol.MAX_PLACE_CHARS),+ )+ }+ fun snap(people: List<WearPerson>, dropped: Int) = WearFindFamilySnapshot(+ generatedAtMillis = generatedAtMillis,+ people = people,+ alerts = alerts,+ sharingEnabled = sharingEnabled,+ region = wearRegionFor(people),+ truncated = dropped > 0,+ droppedCount = dropped,+ totalPeople = sorted.size,+ )+ var kept = sorted+ var snapshot = snap(kept, 0)+ if (WearFindFamilyProtocol.json.encodeToString(snapshot).encodeToByteArray().size <=+ WearFindFamilyProtocol.MAX_JSON_BYTES+ ) return snapshot+ // Summarise harder before dropping anyone.+ kept = kept.map {+ it.copy(+ name = it.name.take(WearFindFamilyProtocol.SUMMARISED_NAME_CHARS),+ placeLabel = it.placeLabel.take(WearFindFamilyProtocol.SUMMARISED_PLACE_CHARS),+ )+ }+ snapshot = snap(kept, 0)+ while (kept.isNotEmpty() &&+ WearFindFamilyProtocol.json.encodeToString(snapshot).encodeToByteArray().size >+ WearFindFamilyProtocol.MAX_JSON_BYTES+ ) {+ kept = kept.dropLast(1)+ snapshot = snap(kept, sorted.size - kept.size)+ }+ return snapshot+}
findfamily/src/main/java/com/vayunmathur/findfamily/sync/WearFindFamilySync.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WearFindFamilySync.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WearFindFamilySync.ktnew file mode 100644index 0000000000..04c43cf573--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/sync/WearFindFamilySync.kt@@ -0,0 +1,232 @@+package com.vayunmathur.findfamily.sync++import android.content.Context+import com.vayunmathur.findfamily.data.LocationSource+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.domain.WearAlert+import com.vayunmathur.findfamily.domain.WearAlertKind+import com.vayunmathur.findfamily.domain.WearFindFamilyOp+import com.vayunmathur.findfamily.domain.WearFindFamilyProtocol+import com.vayunmathur.findfamily.domain.WearOpKind+import com.vayunmathur.findfamily.domain.WearPerson+import com.vayunmathur.findfamily.domain.WearWatchState+import com.vayunmathur.findfamily.domain.buildWearSnapshot+import com.vayunmathur.findfamily.domain.wearMotionFor+import com.vayunmathur.findfamily.network.Networking+import com.vayunmathur.findfamily.platform.LocationServiceController+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/** Phone-side wear status; absence of a watch is a normal state, never an error. */+data class WearFindFamilySyncState(+ val companionPresent: Boolean = false,+ val lastPublishedAtMillis: Long? = null,+ val lastPublishedPeopleCount: Int = 0,+ val lastWatchAppliedAtMillis: Long? = null,+)++/**+ * Phone side of the FindFamily wear companion over WearLink.+ *+ * The phone is the source of truth and the only E2EE endpoint: peer+ * reports are decrypted into Room by the existing pipeline, and this+ * class reads that already-decrypted state to build all-people location+ * summaries (see [WearFindFamilyProtocol] for the privacy boundary).+ * Watch ops apply here: STOP_SHARING_NOW flips the same global sharing+ * switch as the Quick Settings tile ([LocationServiceController]),+ * REQUEST_REFRESH republishes from the freshest Room state and nudges+ * the tracking service to reconcile — it does not fake a fresh peer fix,+ * peers still publish on their own heartbeat.+ */+class WearFindFamilySync private constructor(context: Context) {++ companion object {+ private const val TAG = "WearFindFamilySync"++ @Volatile+ private var instance: WearFindFamilySync? = null++ /** The process-wide sync (activity must agree on one). */+ fun get(context: Context): WearFindFamilySync = instance ?: synchronized(this) {+ instance ?: WearFindFamilySync(context.applicationContext).also { instance = it }+ }+ }++ private val appContext = context.applicationContext+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val repository get() = FindFamilyRepository.get(appContext)++ private val _state = MutableStateFlow(WearFindFamilySyncState())+ val state: StateFlow<WearFindFamilySyncState> = _state.asStateFlow()++ private val listener = object : WearLinkListener {+ override fun onData(path: String, body: ByteArray) {+ if (path != WearFindFamilyProtocol.WATCH_STATE_PATH) return+ val watchState = runCatching {+ WearFindFamilyProtocol.json.decodeFromString<WearWatchState>(body.decodeToString())+ }.getOrNull() ?: return+ _state.update {+ it.copy(lastWatchAppliedAtMillis = watchState.appliedGeneratedAtMillis.takeIf { v -> v > 0L })+ }+ }++ override fun onMessage(path: String, body: ByteArray) {+ when (path) {+ WearFindFamilyProtocol.REQUEST_SYNC_PATH -> scope.launch { publishSnapshot() }+ WearFindFamilyProtocol.OP_PATH -> {+ val op = runCatching {+ WearFindFamilyProtocol.json.decodeFromString<WearFindFamilyOp>(body.decodeToString())+ }.getOrNull()+ if (op == null) {+ Log.status(TAG, "ignoring malformed wear op")+ return+ }+ scope.launch { applyWearOp(op) }+ }+ }+ }+ }++ private val node = WearLinkNode(appContext, WearFindFamilyProtocol.CAPABILITY, listener)+ private var started = false+ private var pendingPublish: Job? = null++ fun start() {+ if (started) return+ started = true+ scope.launch {+ node.state.collect { linkState ->+ val present = linkState is WearLinkState.Connected+ val wasPresent = _state.value.companionPresent+ _state.update { it.copy(companionPresent = present) }+ if (present && !wasPresent) {+ publishSnapshot()+ startLiveCollectorsOnce()+ }+ }+ }+ // No eager Room collectors here: the SQLCipher store is opened by+ // the existing ViewModel/service flows, and this sync publishes on+ // connect, on watch request/op, and via [WearFindFamilySync] callers.+ // (Debounced live republishing can ride those flows later without+ // making MainActivity launch open the database on its own.)+ node.start()+ }++ private var liveCollectorsStarted = false++ /** Debounced live republishing, started only after a watch actually connects. */+ private fun startLiveCollectorsOnce() {+ if (liveCollectorsStarted) return+ liveCollectorsStarted = true+ fun republishSoon() {+ pendingPublish?.cancel()+ pendingPublish = scope.launch {+ delay(1_000)+ publishSnapshot()+ }+ }+ scope.launch { runCatching { repository.users.collect { republishSoon() } } }+ scope.launch { runCatching { repository.latestLocationByUser.collect { republishSoon() } } }+ }++ /** Applies one watch op on the phone (source of truth). Visible for tests. */+ internal suspend fun applyWearOp(op: WearFindFamilyOp) {+ when (op.kind) {+ WearOpKind.STOP_SHARING_NOW ->+ LocationServiceController.setGlobalSharingEnabled(appContext, false)+ WearOpKind.REQUEST_REFRESH -> LocationServiceController.syncServiceState(appContext)+ }+ publishSnapshot()+ }++ /** Build the all-people snapshot from Room and publish it as a data item. */+ suspend fun publishSnapshot() {+ val snapshot = buildPhoneSnapshot()+ val sent = node.putData(+ WearFindFamilyProtocol.SNAPSHOT_PATH,+ WearFindFamilyProtocol.json.encodeToString(snapshot).encodeToByteArray(),+ )+ if (sent) {+ _state.update {+ it.copy(+ lastPublishedAtMillis = snapshot.generatedAtMillis,+ lastPublishedPeopleCount = snapshot.people.size,+ )+ }+ } else {+ Log.status(TAG, "publish snapshot not delivered (no live WearLink session)")+ }+ }++ /** Room -> wire snapshot. Pure mapping except for the repository reads. */+ internal suspend fun buildPhoneSnapshot() = run {+ val users = repository.getAllUsers().filter {+ it.requestStatus == RequestStatus.MUTUAL_CONNECTION ||+ it.requestStatus == RequestStatus.AWAITING_RESPONSE ||+ it.id == Networking.userid+ }+ val latest = repository.latestLocationsOnce().associateBy { it.userid }+ val waypoints = runCatching { repository.waypointStore.getAll() }.getOrDefault(emptyList())+ val waypointNames = waypoints.associate { it.id to it.name }+ val people = users.map { user ->+ val loc = latest[user.id]+ val sighting = loc?.source == LocationSource.NETWORK_SIGHTING+ WearPerson(+ id = user.id,+ name = user.name,+ placeLabel = user.locationName.takeUnless { it == "Unnamed Location" }.orEmpty(),+ placeSinceMillis = user.lastLocationChangeTime.toEpochMilliseconds(),+ latE7 = loc?.let { (it.coord.lat * 1e7).toInt() },+ lonE7 = loc?.let { (it.coord.lon * 1e7).toInt() },+ accuracyMeters = if (sighting || loc == null) -1 else loc.acc.toInt(),+ updatedAtMillis = loc?.timestamp?.toEpochMilliseconds() ?: 0L,+ reportedAtMillis = loc?.reportedAt?.toEpochMilliseconds() ?: 0L,+ batteryPercent = if (sighting || loc == null) -1 else loc.battery.toInt().coerceIn(0, 100),+ motion = wearMotionFor(loc?.speed, loc != null && !sighting),+ source = loc?.source?.name.orEmpty(),+ sharingEnabled = user.sendingEnabled,+ isSelf = Networking.userid != 0L && user.id == Networking.userid,+ )+ }+ val alerts = buildList {+ for (person in people) {+ if (person.placeLabel.isNotBlank()) {+ add(WearAlert(WearAlertKind.AT_PLACE, person.id, person.placeLabel, person.placeSinceMillis))+ }+ }+ val noShows = runCatching { repository.noShowAlertStore.getAll() }.getOrDefault(emptyList())+ for (alert in noShows) {+ add(+ WearAlert(+ kind = WearAlertKind.NOSHOW,+ personId = alert.watchedUserId,+ placeLabel = alert.waypointId?.let { waypointNames[it] }.orEmpty(),+ atMillis = alert.expectedAt.toEpochMilliseconds(),+ fired = alert.fired,+ ),+ )+ }+ }+ buildWearSnapshot(+ candidates = people,+ alerts = alerts,+ sharingEnabled = LocationServiceController.isGlobalSharingEnabled(appContext),+ generatedAtMillis = System.currentTimeMillis(),+ )+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocolTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocolTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocolTest.ktnew file mode 100644index 0000000000..21e90ff9b4--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocolTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.findfamily.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearFindFamilyProtocolTest {++ private fun person(+ id: Long,+ updatedAt: Long,+ name: String = "Person $id",+ place: String = "Home",+ ) = WearPerson(+ id = id,+ name = name,+ placeLabel = place,+ latE7 = 377_749_000,+ lonE7 = -1_224_194_000,+ updatedAtMillis = updatedAt,+ )++ @Test+ fun goldenSnapshotJson() {+ val snapshot = WearFindFamilySnapshot(+ generatedAtMillis = 1_000L,+ people = listOf(person(7L, 900L, name = "Ada")),+ region = WearRegion(377_749_000, -1_224_194_000, 200, true),+ totalPeople = 1,+ )+ assertEquals(+ """{"generatedAtMillis":1000,"people":[{"id":7,"name":"Ada","placeLabel":"Home",""" ++ """"latE7":377749000,"lonE7":-1224194000,"updatedAtMillis":900}],""" ++ """"region":{"centerLatE7":377749000,"centerLonE7":-1224194000,""" ++ """"hasCenter":true},"totalPeople":1}""",+ WearFindFamilyProtocol.json.encodeToString(snapshot),+ )+ }++ @Test+ fun goldenStopSharingOpJson() {+ assertEquals(+ """{"kind":"STOP_SHARING_NOW","requestedAtMillis":123}""",+ WearFindFamilyProtocol.json.encodeToString(WearFindFamilyOp(WearOpKind.STOP_SHARING_NOW, 123L)),+ )+ assertEquals(+ """{"kind":"REQUEST_REFRESH","requestedAtMillis":456}""",+ WearFindFamilyProtocol.json.encodeToString(WearFindFamilyOp(WearOpKind.REQUEST_REFRESH, 456L)),+ )+ }++ @Test+ fun allPeopleCompletenessNoSilentDrop() {+ val candidates = (1L..200L).map { person(it, it * 1_000L) }+ val snapshot = buildWearSnapshot(candidates, generatedAtMillis = 999_000L)+ assertEquals(200, snapshot.people.size)+ assertEquals(200, snapshot.totalPeople)+ assertFalse(snapshot.truncated)+ assertEquals(200L, snapshot.people.first().id)+ }++ @Test+ fun hardCapDropsOldestAndSaysSo() {+ val candidates = (1L..2_000L).map {+ person(it, it, name = "N".repeat(100), place = "P".repeat(120))+ }+ val snapshot = buildWearSnapshot(candidates, generatedAtMillis = 0L)+ assertTrue(snapshot.truncated)+ assertTrue(snapshot.droppedCount > 0)+ assertEquals(2_000L, snapshot.people.first().id)+ val bytes = WearFindFamilyProtocol.json.encodeToString(snapshot).encodeToByteArray().size+ assertTrue(bytes <= WearFindFamilyProtocol.MAX_JSON_BYTES, "snapshot $bytes over cap")+ }++ @Test+ fun stalenessAndRelativeMath() {+ val fresh = person(1L, 1_000_000L)+ val now = 1_000_000L + WearFindFamilyProtocol.STALE_AFTER_MS+ assertFalse(wearIsStale(fresh, now))+ assertTrue(wearIsStale(fresh, now + 1L))+ assertEquals(90, wearBearingDegrees(0, 0, 0, 100_000))+ assertEquals("E", wearCompass(90))+ val north = wearDistanceMeters(0, 0, 100_000, 0)+ assertTrue(north in 1_100.0..1_125.0, "north $north")+ assertEquals(WearMotion.MOVING, wearMotionFor(2.0f, true))+ assertEquals(WearMotion.UNKNOWN, wearMotionFor(5.0f, false))+ }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 4586b405e2..49a2181803 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -103,6 +103,7 @@ include(":youpipe") include(":youpipe:extractor") include(":uniflix") include(":findfamily")+include(":findfamily-wear") include(":maps") include(":maps:wear") project(":maps:wear").projectDir = file("maps-wear")