Modern Apps git

← Modern-Apps.git

weather: sync over the watch conduit client

Commit
4678e6a64e8a615cf0892b019a0726db94dad924
Author
Vayun Mathur <[email protected]>
When
2026-12-04 19:44 UTC (1 day ago)
Parents
836f31d
Migrate the weather phone<->watch sync from direct RFCOMM
WearLinkNode to the Watch conduit client (WearLinkClientNode),
following the already-migrated clock pair exactly. The Watch apps
are the sole Bluetooth holders; this app owns no RFCOMM link for
this channel any more.

What changed:
- weather sync/WearWeatherSync.kt (phone): WearLinkNode replaced
  with WearLinkClientNode registered under the conduit appId
  "weather" (ConduitProtocol.routeKey of /weather/snapshot), not
  the old RFCOMM handshake capability. Presence derives from
  WearLinkState.Connected, snapshots republish on the Connected
  edge and on forecast refresh, watch-state data items still land
  in WearSyncState, and request-sync messages still trigger
  publishSnapshot(). With the Watch app absent the node reports
  NotInstalled/Unavailable and sends return false.
- weather sync/WearLinkBridge.kt (watch): same swap; get() now
  returns WearLinkClientNode. Snapshot -> WearWeatherStore,
  watch-state putData and requestSync sendMessage call sites are
  unchanged.
- weather MainActivity: Bluetooth prompting removed
  (WearLinkPermissions.requestIfNeeded deleted); only the Watch
  apps prompt now.
- Wire protocol unchanged: library.wearlink.weather types and the
  golden-JSON tests are untouched.

Docs: weather/AGENTS.md wear sections now describe the
conduit-client transport in present tense.

Verified in the worktree on devvm21958:
- ./gradlew :weather:lint :weather:lintVitalRelease
  :weather:testDevUnitTest --max-workers=128
  -Dorg.gradle.jvmargs=-Xmx64g: BUILD SUCCESSFUL.

Diff

weather/AGENTS.md
diff --git a/weather/AGENTS.md b/weather/AGENTS.mdindex 7990136e15..c69063565d 100644--- a/weather/AGENTS.md+++ b/weather/AGENTS.md@@ -36,9 +36,9 @@ receivers are a phone-only surface and early-return on a watch.  ## Wear sync (Watch conduit client) **Protocol:** shared wire types live in `:library:wearlink` at `com.vayunmathur.library.wearlink.weather.WearWeatherProtocol`; the golden-JSON tests in this module pin the shared code's wire format.-- Snapshot + watch-state sync: WearLink data items (`/weather/snapshot` phone -> watch, `/weather/watch-state` watch -> phone)-- Sync request: WearLink message (`/weather/request-sync`), watch -> phone only-- **Transport: WearLink RFCOMM nodes** — phone side `sync/WearWeatherSync.kt` publishes the snapshot from cached forecasts, watch side `sync/WearLinkBridge.kt` receives it into `data/WearWeatherStore`; the watch renders the locally stored snapshot offline and holds no network path of its own. Protocol values stay Celsius / km/h; rendering converts to the watch's system regional preferences (`platform/WearSystemUnits`, formatting in `domain/WearWeatherFormatting`).+- Snapshot + watch-state sync: conduit data items (`/weather/snapshot` phone -> watch, `/weather/watch-state` watch -> phone)+- Sync request: conduit message (`/weather/request-sync`), watch -> phone only+- **Transport: Watch conduit client** — phone side `sync/WearWeatherSync.kt` and watch side `sync/WearLinkBridge.kt` both use `WearLinkClientNode` (Messenger to the Watch app's `watch_conduit` service, appId `weather`); this app owns no RFCOMM link and holds no Bluetooth permission for this channel, so neither entry activity prompts for Bluetooth. With the Watch app absent the node reports `NotInstalled`/`Unavailable` and the sync stays idle; snapshots republish on conduit `Connected` and on forecast refresh. The watch renders the locally stored snapshot offline and holds no network path of its own. Protocol values stay Celsius / km/h; rendering converts to the watch's system regional preferences (`platform/WearSystemUnits`, formatting in `domain/WearWeatherFormatting`).  ## Watch experience (in this module) - `ui/WearMainActivity` (a `WearShellActivity`) routes `ui/WearRoute` over locations (`ui/WearLocationsScreen`) and one location's current/hourly/daily detail (`ui/WearLocationScreen`), with a sync-now action that messages the phone side.@@ -131,8 +131,8 @@ receivers are a phone-only surface and early-return on a watch. - com/vayunmathur/weather/ui/components/blocks/SunBlock.kt - com/vayunmathur/weather/ui/components/blocks/MoonBlock.kt ### sync/ — wear companion sync-- com/vayunmathur/weather/sync/WearWeatherSync.kt — phone WearLink node; snapshot publish from cached forecasts, watch-state receive, request-sync handling-- com/vayunmathur/weather/sync/WearLinkBridge.kt — watch WearLink node; snapshot receive into the watch store, watch-state publish, sync request+- com/vayunmathur/weather/sync/WearWeatherSync.kt — phone conduit client node; snapshot publish from cached forecasts, watch-state receive, request-sync handling+- com/vayunmathur/weather/sync/WearLinkBridge.kt — watch conduit client node; snapshot receive into the watch store, watch-state publish, sync request ### Watch experience (ui/ + platform/ + data/ + domain/) - com/vayunmathur/weather/ui/WearMainActivity.kt — watch entry (WearShellActivity) - com/vayunmathur/weather/ui/WearRoute.kt, WearLocationsScreen.kt, WearLocationScreen.kt
weather/src/main/java/com/vayunmathur/weather/MainActivity.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt b/weather/src/main/java/com/vayunmathur/weather/MainActivity.ktindex 5477276677..ed1c41fc39 100644--- a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -46,7 +46,10 @@ class MainActivity : MaActivity() {      override fun onCreateBeforeContent() {         if (routedToWear) return-        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        // No Bluetooth prompt here: the Watch app owns the conduit link+        // and its permission. Wear sync runs over WearLinkClientNode via+        // WeatherViewModel; with the Watch app absent it reports+        // NotInstalled/Unavailable and the weather keeps working locally.         // FIRST_PARTY covers static.maproj.org (static weather packs on         // R2, the app's only weather origin) and, for the flagged         // no-land-tile fallback only, api.maproj.org; place search is a
weather/src/main/java/com/vayunmathur/weather/sync/WearLinkBridge.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/sync/WearLinkBridge.kt b/weather/src/main/java/com/vayunmathur/weather/sync/WearLinkBridge.ktindex 5fe4d3daec..9cff4496bd 100644--- a/weather/src/main/java/com/vayunmathur/weather/sync/WearLinkBridge.kt+++ b/weather/src/main/java/com/vayunmathur/weather/sync/WearLinkBridge.kt@@ -2,7 +2,8 @@ package com.vayunmathur.weather.sync import android.content.Context import com.vayunmathur.library.log.Log import com.vayunmathur.library.wearlink.WearLinkListener-import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode import com.vayunmathur.weather.data.WearWeatherStore import com.vayunmathur.library.wearlink.weather.WearWeatherProtocol import com.vayunmathur.library.wearlink.weather.WearWeatherSnapshot@@ -12,17 +13,39 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.serialization.encodeToString+/**+ * Watch side of the Watch conduit client for Weather: snapshot data items+ * land in [WearWeatherStore], watch state goes back as a data item, and+ * request-sync is a message. Transport is `WearLinkClientNode` (Messenger+ * to the Watch app's conduit service); this app owns no RFCOMM link.+ * Delivery is bound to this process being alive; there is no+ * Play-services listener service. With the Watch app absent the node+ * reports NotInstalled/Unavailable and the watch keeps rendering the+ * locally stored snapshot.+ */ object WearLinkBridge {     private const val TAG="WearLinkBridge"; private val scope=CoroutineScope(SupervisorJob()+Dispatchers.IO)-    @Volatile private var node:WearLinkNode?=null-    fun get(c:Context):WearLinkNode{ val a=c.applicationContext; return node?:synchronized(this){node?:create(a).also{node=it}} }-    private fun create(c:Context):WearLinkNode{+    @Volatile private var node:WearLinkClientNode?=null+    fun get(c:Context):WearLinkClientNode{ val a=c.applicationContext; return node?:synchronized(this){node?:create(a).also{node=it}} }+    private fun create(c:Context):WearLinkClientNode{         val l=object:WearLinkListener{ override fun onData(path:String,body:ByteArray){ if(path!=WearWeatherProtocol.SNAPSHOT_PATH)return             val s=runCatching{WearWeatherProtocol.json.decodeFromString<WearWeatherSnapshot>(body.decodeToString())}.getOrNull()?:run{Log.status(TAG,"malformed snapshot");return}             WearWeatherStore.get(c).setSnapshot(s) } }-        return WearLinkNode(c,WearWeatherProtocol.CAPABILITY,l).also{it.start()}+        // Conduit appId = first path segment of the weather paths (the+        // ConduitProtocol route key), not the RFCOMM handshake capability.+        return WearLinkClientNode(+            c,+            ConduitProtocol.routeKey(WearWeatherProtocol.SNAPSHOT_PATH),+            l,+        ).also{it.start()}     }     fun publishWatchState(c:Context,s:WearWeatherSnapshot){ scope.launch{ get(c).putData(WearWeatherProtocol.WATCH_STATE_PATH, WearWeatherProtocol.json.encodeToString(WearWatchState(s.generatedAtMillis,s.locations.size)).encodeToByteArray()) } }     suspend fun requestSync(c:Context):Boolean=get(c).sendMessage(WearWeatherProtocol.REQUEST_SYNC_PATH,ByteArray(0)) }+/**+ * Asks the phone for a fresh snapshot over the conduit. Returns false when+ * the conduit link is not connected — the watch keeps rendering its last+ * synced copy, and the UI says exactly that instead of pretending a sync+ * happened.+ */ suspend fun requestWearSync(c:Context):Boolean=WearLinkBridge.requestSync(c)
weather/src/main/java/com/vayunmathur/weather/sync/WearWeatherSync.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/sync/WearWeatherSync.kt b/weather/src/main/java/com/vayunmathur/weather/sync/WearWeatherSync.ktindex e0dc775bbf..7bb3f9c7e8 100644--- a/weather/src/main/java/com/vayunmathur/weather/sync/WearWeatherSync.kt+++ b/weather/src/main/java/com/vayunmathur/weather/sync/WearWeatherSync.kt@@ -2,8 +2,9 @@ package com.vayunmathur.weather.sync import android.content.Context 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 com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode import com.vayunmathur.weather.data.WeatherRepository import com.vayunmathur.weather.data.weatherJson import com.vayunmathur.library.wearlink.weather.WearWeatherCurrent@@ -16,7 +17,6 @@ import com.vayunmathur.library.wearlink.weather.WearWatchState import com.vayunmathur.library.wearlink.weather.buildWearWeatherSnapshot import com.vayunmathur.weather.domain.roundCoord import com.vayunmathur.weather.domain.todayIndex-import com.vayunmathur.library.wearlink.weather.wearCompanionPresent import com.vayunmathur.weather.network.Daily import com.vayunmathur.weather.network.ForecastResponse import kotlinx.coroutines.CoroutineScope@@ -31,7 +31,19 @@ import kotlinx.serialization.encodeToString  data class WearSyncState(val companionPresent:Boolean=false, val lastPublishedAtMillis:Long?=null, val lastWatchAppliedAtMillis:Long?=null, val lastPublishedLocationCount:Int=0) -/** Phone side over WearLink: publish on forecast refresh + on watch request; presence = handshake. Absence is normal. */+/**+ * Phone side of the wear sync over the Watch conduit client+ * (:library:wearlink `WearLinkClientNode`: a Messenger binding to the+ * Watch app's conduit service, not an RFCOMM link this app owns):+ * presence is the peer-link Connected state the conduit reports, the+ * weather snapshot is a data item, and the watch's request-sync is a+ * message handled here while this process lives. There is no+ * Play-services listener service: a request arriving while the phone app+ * is dead waits until it next runs, and the snapshot republishes on+ * reconnect and on every forecast refresh. Absence of a watch (or of+ * the Watch app, reported as NotInstalled/Unavailable) is a normal+ * state, never an error.+ */ class WearWeatherSync private constructor(context:Context){  companion object{ private const val TAG="WearWeatherSync"; @Volatile private var i:WearWeatherSync?=null   fun get(c:Context):WearWeatherSync=i?:synchronized(this){i?:WearWeatherSync(c.applicationContext).also{i=it}} }@@ -43,12 +55,18 @@ class WearWeatherSync private constructor(context:Context){    _state.update{it.copy(lastWatchAppliedAtMillis=ws.appliedGeneratedAtMillis.takeIf{a->a>0L})} }   override fun onMessage(path:String,body:ByteArray){ if(path==WearWeatherProtocol.REQUEST_SYNC_PATH) scope.launch{publishSnapshot()} }  }- private val node=WearLinkNode(appContext,WearWeatherProtocol.CAPABILITY,listener); private var started=false- fun start(){ if(started)return; started=true; scope.launch{ node.state.collect{ ls-> val p=ls is WearLinkState.Connected; val was=_state.value.companionPresent; _state.update{it.copy(companionPresent=wearCompanionPresent(if(p)listOf("peer")else emptyList()))}; if(p&&!was) publishSnapshot() } }; node.start() }+ // Conduit appId = first path segment of the weather paths (the+ // ConduitProtocol route key), not the RFCOMM handshake capability.+ private val node=WearLinkClientNode(+  appContext,+  ConduitProtocol.routeKey(WearWeatherProtocol.SNAPSHOT_PATH),+  listener,+ ); private var started=false+ fun start(){ if(started)return; started=true; scope.launch{ node.state.collect{ ls-> val p=ls is WearLinkState.Connected; val was=_state.value.companionPresent; _state.update{it.copy(companionPresent=p)}; if(p&&!was) publishSnapshot() } }; node.start() }  fun onForecastRefreshed(){ scope.launch{publishSnapshot()} }  fun syncNow(){ scope.launch{publishSnapshot()} }  suspend fun publishSnapshot(){ val s=buildSnapshot()?:return; val sent=node.putData(WearWeatherProtocol.SNAPSHOT_PATH, WearWeatherProtocol.json.encodeToString(s).encodeToByteArray())-  if(sent) _state.update{it.copy(lastPublishedAtMillis=s.generatedAtMillis,lastPublishedLocationCount=s.locations.size)} else Log.status(TAG,"publish not delivered (no live session)") }+  if(sent) _state.update{it.copy(lastPublishedAtMillis=s.generatedAtMillis,lastPublishedLocationCount=s.locations.size)} else Log.status(TAG,"publish snapshot not delivered (conduit link not connected)") }  private suspend fun buildSnapshot():WearWeatherSnapshot?=runCatching{   val repo=WeatherRepository.get(appContext); val locs=repo.getLocations().sortedWith(compareByDescending<com.vayunmathur.weather.data.SavedLocation>{it.isCurrent}.thenBy{it.displayOrder})   val candidates=locs.mapNotNull{ loc-> val cache=repo.getCache(roundCoord(loc.latitude),roundCoord(loc.longitude))?:return@mapNotNull null