Modern Apps git

← Modern-Apps.git

wear: weather companion on WearLink

Commit
6a16eeb8054830ed02f81b47cff68a9c785c4f96
Author
Vayun Mathur <[email protected]>
When
2026-11-24 18:52 UTC (11 days ago)
Parents
c7d5729
New :weather:wear module (same package/signing):
locations list -> detail Route from a locally persisted
snapshot (current + 24 hourly + 7 daily, primary first
+ up to 3 favourites, 90 KB cap with truncation flag),
offline-capable. Phone publishes on forecast refresh,
hourly worker, WearLink handshake, watch request, or
manual sync - always from the Room cache, never network
on the sync path. Watch state/presence surfaced in the
phone locations drawer; absence is a normal state.

Verified: 227 weather phone tests + 6 wear tests green;
wear assembles with the right package.

Diff

weather-wear/AGENTS.md
diff --git a/weather-wear/AGENTS.md b/weather-wear/AGENTS.mdnew file mode 100644index 0000000000..4fe07db1a4--- /dev/null+++ b/weather-wear/AGENTS.md@@ -0,0 +1,13 @@+# AGENTS.md — weather-wear/ (':weather:wear')+> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `weather-wear/` + `weather/`.+- Gradle: :weather:wear (dir weather-wear/)+- Entry: ui/WearMainActivity.kt+## Why+Wear OS companion of :weather. Same applicationId + signing (WearLink handshake requires same cert). Sideload once via ADB.+## Protocol+`domain/WearWeatherProtocol.kt` is a copy of phone's file. Change both; golden tests pin same JSON.+- Snapshot/watch-state: WearLink data items; request-sync: message watch->phone only.+- Offline: renders locally stored snapshot; no network on watch.+## Verify+./gradlew :weather:wear:assembleDev+./gradlew :weather:wear:testDebugUnitTest
weather-wear/build.gradle.kts
diff --git a/weather-wear/build.gradle.kts b/weather-wear/build.gradle.ktsnew file mode 100644index 0000000000..81fc52d453--- /dev/null+++ b/weather-wear/build.gradle.kts@@ -0,0 +1,15 @@+plugins { id("common-conventions-wear") }+launcherIcon { symbol = "partly_cloudy_day" }+android {+    namespace = "com.vayunmathur.weather.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.weather"+        minSdk = 31+    }+}+dependencies {+    implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
weather-wear/src/main/AndroidManifest.xml
diff --git a/weather-wear/src/main/AndroidManifest.xml b/weather-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..15b8083385--- /dev/null+++ b/weather-wear/src/main/AndroidManifest.xml@@ -0,0 +1,12 @@+<?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>
weather-wear/src/main/java/com/vayunmathur/weather/wear/data/WearWeatherStore.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/data/WearWeatherStore.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/data/WearWeatherStore.ktnew file mode 100644index 0000000000..6eed945b25--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/data/WearWeatherStore.kt@@ -0,0 +1,20 @@+package com.vayunmathur.weather.wear.data+import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.weather.wear.domain.WearWeatherProtocol+import com.vayunmathur.weather.wear.domain.WearWeatherSnapshot+import com.vayunmathur.weather.wear.sync.WearLinkBridge+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString+class WearWeatherStore private constructor(private val context: Context) {+    companion object { private const val TAG="WearWeatherStore"; @Volatile private var i:WearWeatherStore?=null+        fun get(c:Context):WearWeatherStore=i?:synchronized(this){i?:WearWeatherStore(c.applicationContext).also{i=it}} }+    private val file=File(context.filesDir,"wear-weather-snapshot.json")+    private val _s=MutableStateFlow(load()); val snapshot:StateFlow<WearWeatherSnapshot> = _s.asStateFlow()+    fun setSnapshot(s:WearWeatherSnapshot){ _s.value=s; runCatching{file.writeText(WearWeatherProtocol.json.encodeToString(s))}.onFailure{Log.status(TAG,it.message?:"persist failed")}; publishWatchState() }+    fun publishWatchState(){ WearLinkBridge.publishWatchState(context,_s.value) }+    private fun load():WearWeatherSnapshot=runCatching{WearWeatherProtocol.json.decodeFromString<WearWeatherSnapshot>(file.readText())}.getOrDefault(WearWeatherSnapshot())+}
weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherFormatting.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherFormatting.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherFormatting.ktnew file mode 100644index 0000000000..1ad94cc772--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherFormatting.kt@@ -0,0 +1,6 @@+package com.vayunmathur.weather.wear.domain+import kotlin.math.roundToInt+fun wearConditionLabel(code:Int):String=when(code){0->"Clear";1->"Mostly clear";2->"Partly cloudy";3->"Cloudy";45,48->"Fog";51,53,55,56,57->"Drizzle";61,63,65,66,67,80,81,82->"Rain";71,73,75,77,85,86->"Snow";95,96,99->"Thunderstorm";else->"Cloudy"}+fun wearTemp(c:Double):String="${c.roundToInt()}°"+fun wearHourLabel(iso:String):String=iso.substringAfter("T","").take(5).ifBlank{"--:--"}+fun wearDayLabel(iso:String):String=iso.take(10)
weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocol.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocol.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocol.ktnew file mode 100644index 0000000000..f1ebd0a05b--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocol.kt@@ -0,0 +1,119 @@+package com.vayunmathur.weather.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS Weather companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module+ * (`:weather:wear`, applicationId `com.vayunmathur.weather`) carries a copy+ * of this file under `com.vayunmathur.weather.wear.domain`. Change both+ * copies together; each side's unit tests pin the same golden JSON.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [SNAPSHOT_PATH] phone -> watch, [WATCH_STATE_PATH] watch -> phone.+ * - Messages: [REQUEST_SYNC_PATH] watch -> phone (only watch-originated write).+ * Bounded by design: primary location first, then favorites, caps below.+ */+object WearWeatherProtocol {+    const val CAPABILITY = "weather_wear_companion"+    const val SNAPSHOT_PATH = "/weather/snapshot"+    const val WATCH_STATE_PATH = "/weather/watch-state"+    const val REQUEST_SYNC_PATH = "/weather/request-sync"+    const val MAX_LOCATIONS = 4+    const val MAX_HOURLY = 24+    const val MAX_DAILY = 7+    const val MAX_JSON_BYTES = 90_000+    const val MAX_NAME_CHARS = 80+    val json: Json = Json { ignoreUnknownKeys = true }+}++@Serializable+data class WearWeatherCurrent(+    val timeIso: String = "",+    val temperatureC: Double = 0.0,+    val apparentTemperatureC: Double = 0.0,+    val humidityPercent: Int = 0,+    val weatherCode: Int = -1,+    val isDay: Boolean = true,+    val windSpeedKmh: Double = 0.0,+    val windDirectionDegrees: Int = 0,+    val pressureHpa: Double = 0.0,+)++@Serializable+data class WearWeatherHour(+    val timeIso: String = "",+    val temperatureC: Double = 0.0,+    val weatherCode: Int = -1,+    val precipitationProbabilityPercent: Int = 0,+    val isDay: Boolean = true,+)++@Serializable+data class WearWeatherDay(+    val dateIso: String = "",+    val weatherCode: Int = -1,+    val temperatureMaxC: Double = 0.0,+    val temperatureMinC: Double = 0.0,+    val precipitationProbabilityMaxPercent: Int = 0,+)++@Serializable+data class WearWeatherLocation(+    val locationId: Long = 0L,+    val name: String = "",+    val country: String = "",+    val isPrimary: Boolean = false,+    val timezone: String = "UTC",+    val current: WearWeatherCurrent? = null,+    val hourly: List<WearWeatherHour> = emptyList(),+    val daily: List<WearWeatherDay> = emptyList(),+)++@Serializable+data class WearWeatherSnapshot(+    val generatedAtMillis: Long = 0L,+    val locations: List<WearWeatherLocation> = emptyList(),+    val truncated: Boolean = false,+)++@Serializable+data class WearWatchState(+    val appliedGeneratedAtMillis: Long = 0L,+    val locationCount: Int = 0,+)++/** Primary first (stable for equal rank), then field/list caps, then JSON-size cap (drop last locations, then hourly). */+fun buildWearWeatherSnapshot(+    candidates: List<WearWeatherLocation>,+    generatedAtMillis: Long,+): WearWeatherSnapshot {+    val ordered = candidates.sortedByDescending { it.isPrimary }.map { loc ->+        loc.copy(+            name = loc.name.take(WearWeatherProtocol.MAX_NAME_CHARS),+            country = loc.country.take(WearWeatherProtocol.MAX_NAME_CHARS),+            hourly = loc.hourly.take(WearWeatherProtocol.MAX_HOURLY),+            daily = loc.daily.take(WearWeatherProtocol.MAX_DAILY),+        )+    }+    var kept = ordered.take(WearWeatherProtocol.MAX_LOCATIONS)+    var truncated = kept.size < ordered.size+    var snapshot = WearWeatherSnapshot(generatedAtMillis, kept, truncated)+    fun over() = WearWeatherProtocol.json.encodeToString(snapshot).encodeToByteArray().size > WearWeatherProtocol.MAX_JSON_BYTES+    while (over() && kept.size > 1) {+        kept = kept.dropLast(1); truncated = true+        snapshot = WearWeatherSnapshot(generatedAtMillis, kept, true)+    }+    while (over() && kept.firstOrNull()?.hourly?.isNotEmpty() == true) {+        kept = kept.mapIndexed { i, loc -> if (i == 0) loc.copy(hourly = loc.hourly.dropLast(1)) else loc }+        snapshot = WearWeatherSnapshot(generatedAtMillis, kept, true)+    }+    return snapshot+}++/** True when a companion node is present (non-empty handshake set). */+fun wearCompanionPresent(nodeIdsWithCapability: Collection<String>): Boolean = nodeIdsWithCapability.isNotEmpty()
weather-wear/src/main/java/com/vayunmathur/weather/wear/sync/WearLinkBridge.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/sync/WearLinkBridge.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..642e3e0620--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/sync/WearLinkBridge.kt@@ -0,0 +1,28 @@+package com.vayunmathur.weather.wear.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.weather.wear.data.WearWeatherStore+import com.vayunmathur.weather.wear.domain.WearWeatherProtocol+import com.vayunmathur.weather.wear.domain.WearWeatherSnapshot+import com.vayunmathur.weather.wear.domain.WearWatchState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString+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{+        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()}+    }+    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))+}+suspend fun requestWearSync(c:Context):Boolean=WearLinkBridge.requestSync(c)
weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationScreen.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationScreen.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationScreen.ktnew file mode 100644index 0000000000..bd2d6e8cd7--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationScreen.kt@@ -0,0 +1,50 @@+package com.vayunmathur.weather.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.weather.wear.R+import com.vayunmathur.weather.wear.data.WearWeatherStore+import com.vayunmathur.weather.wear.domain.wearConditionLabel+import com.vayunmathur.weather.wear.domain.wearDayLabel+import com.vayunmathur.weather.wear.domain.wearHourLabel+import com.vayunmathur.weather.wear.domain.wearTemp+import com.vayunmathur.weather.wear.sync.requestWearSync+import kotlinx.coroutines.launch+@Composable fun WearLocationScreen(store:WearWeatherStore, locationId:Long, onBack:()->Unit){+ val s by store.snapshot.collectAsState(); val loc=s.locations.firstOrNull{it.locationId==locationId}?:s.locations.firstOrNull()+ val ctx=LocalContext.current; val scope=rememberCoroutineScope(); var note by remember{mutableStateOf<String?>(null)}+ val req=stringResource(R.string.wear_sync_requested); val no=stringResource(R.string.wear_no_phone); val st=rememberScalingLazyListState()+ ScalingLazyColumn(state=st){+  if(loc==null){ item{ Text(stringResource(R.string.wear_empty),textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) } }+  else{+   item{ Text(loc.name.ifBlank{"Location"},style=MaterialTheme.typography.title3,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) }+   loc.current?.let{c-> item{ Text("${wearTemp(c.temperatureC)} ${wearConditionLabel(c.weatherCode)}",style=MaterialTheme.typography.title2,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) }+    item{ Text("Feels ${wearTemp(c.apparentTemperatureC)} · ${c.humidityPercent}% · ${c.windSpeedKmh.toInt()} km/h",style=MaterialTheme.typography.body2,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) } }+   if(loc.hourly.isNotEmpty()){ item{ Text(stringResource(R.string.wear_hourly),style=MaterialTheme.typography.caption1,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) }+    items(loc.hourly){h-> Chip(onClick={},label={Text("${wearHourLabel(h.timeIso)} ${wearTemp(h.temperatureC)}",maxLines=1)},secondaryLabel={Text("${wearConditionLabel(h.weatherCode)} ${h.precipitationProbabilityPercent}%",maxLines=1)},colors=ChipDefaults.secondaryChipColors(),modifier=Modifier.fillMaxWidth().padding(horizontal=8.dp))} }+   if(loc.daily.isNotEmpty()){ item{ Text(stringResource(R.string.wear_daily),style=MaterialTheme.typography.caption1,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) }+    items(loc.daily){d-> Chip(onClick={},label={Text("${wearDayLabel(d.dateIso)} ${wearTemp(d.temperatureMinC)}–${wearTemp(d.temperatureMaxC)}",maxLines=1)},secondaryLabel={Text("${wearConditionLabel(d.weatherCode)} ${d.precipitationProbabilityMaxPercent}%",maxLines=1)},colors=ChipDefaults.secondaryChipColors(),modifier=Modifier.fillMaxWidth().padding(horizontal=8.dp))} }+  }+  note?.let{n-> item{ Text(n,style=MaterialTheme.typography.body2,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) } }+  item{ Chip(onClick={scope.launch{note=if(requestWearSync(ctx))req else no}},label={Text(stringResource(R.string.wear_request_sync),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)) }+ }+}
weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationsScreen.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationsScreen.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationsScreen.ktnew file mode 100644index 0000000000..96d10d15fd--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearLocationsScreen.kt@@ -0,0 +1,33 @@+package com.vayunmathur.weather.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.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.weather.wear.R+import com.vayunmathur.weather.wear.data.WearWeatherStore+import com.vayunmathur.weather.wear.domain.wearConditionLabel+import com.vayunmathur.weather.wear.domain.wearTemp+@Composable fun WearLocationsScreen(store:WearWeatherStore, onOpen:(Long)->Unit){+ val s by store.snapshot.collectAsState(); val st=rememberScalingLazyListState()+ ScalingLazyColumn(state=st){+  item{ Text(stringResource(R.string.app_name),style=MaterialTheme.typography.title3,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) }+  if(s.locations.isEmpty()){ item{ Text(stringResource(R.string.wear_empty),style=MaterialTheme.typography.body2,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) } }+  else { items(s.locations,key={it.locationId}){ loc ->+    Chip(onClick={onOpen(loc.locationId)}, label={Text(loc.name.ifBlank{"Location"},maxLines=1)}, secondaryLabel={Text(loc.current?.let{"${wearTemp(it.temperatureC)} ${wearConditionLabel(it.weatherCode)}"}?:stringResource(R.string.wear_locations),maxLines=1)}, colors=ChipDefaults.secondaryChipColors(), modifier=Modifier.fillMaxWidth().padding(horizontal=8.dp))+  }+   if(s.truncated) item{ Text(stringResource(R.string.wear_truncated),style=MaterialTheme.typography.body2,textAlign=TextAlign.Center,modifier=Modifier.fillMaxWidth().padding(horizontal=12.dp)) }+  }+ }+}
weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearMainActivity.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearMainActivity.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..c2a4ade5d9--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearMainActivity.kt@@ -0,0 +1,18 @@+package com.vayunmathur.weather.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.weather.wear.data.WearWeatherStore+import com.vayunmathur.weather.wear.sync.WearLinkBridge+class WearMainActivity:ComponentActivity(){ override fun onCreate(b:Bundle?){ super.onCreate(b)+ com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+ val store=WearWeatherStore.get(this); WearLinkBridge.get(this); store.publishWatchState()+ setContent{ MaterialTheme{ var route by remember{mutableStateOf<WearRoute>(WearRoute.Locations)}+  when(val cur=route){ WearRoute.Locations->WearLocationsScreen(store){route=WearRoute.Location(it)}+   is WearRoute.Location->WearLocationScreen(store,cur.locationId){route=WearRoute.Locations} } } }+} }
weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearRoute.kt
diff --git a/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearRoute.kt b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..4ebf1096af--- /dev/null+++ b/weather-wear/src/main/java/com/vayunmathur/weather/wear/ui/WearRoute.kt@@ -0,0 +1,2 @@+package com.vayunmathur.weather.wear.ui+sealed interface WearRoute { data object Locations:WearRoute; data class Location(val locationId:Long):WearRoute }
weather-wear/src/main/res/values/colors.xml
diff --git a/weather-wear/src/main/res/values/colors.xml b/weather-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..79503191b9--- /dev/null+++ b/weather-wear/src/main/res/values/colors.xml@@ -0,0 +1 @@+<resources><color name="ic_launcher_background">#FFFFFF</color></resources>
weather-wear/src/main/res/values/strings.xml
diff --git a/weather-wear/src/main/res/values/strings.xml b/weather-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..3adff26ab2--- /dev/null+++ b/weather-wear/src/main/res/values/strings.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+<string name="app_name">Weather</string>+<string name="wear_empty">No weather synced yet. Open Weather on your phone to sync this watch.</string>+<string name="wear_locations">Locations</string>+<string name="wear_hourly">Next hours</string>+<string name="wear_daily">Outlook</string>+<string name="wear_request_sync">Sync now</string>+<string name="wear_sync_requested">Asked your phone for fresh weather</string>+<string name="wear_no_phone">Phone not reachable — showing last synced weather</string>+<string name="wear_truncated">Showing primary locations only</string>+<string name="wear_back">Back</string>+</resources>
weather-wear/src/test/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocolTest.kt
diff --git a/weather-wear/src/test/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocolTest.kt b/weather-wear/src/test/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocolTest.ktnew file mode 100644index 0000000000..56f25c5c45--- /dev/null+++ b/weather-wear/src/test/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocolTest.kt@@ -0,0 +1,16 @@+package com.vayunmathur.weather.wear.domain+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString+class WearWeatherProtocolTest {+ private fun loc(id:Long,primary:Boolean=false)=WearWeatherLocation(locationId=id,name="Loc $id",country="X",isPrimary=primary,timezone="UTC",current=WearWeatherCurrent("2026-11-24T12:00",20.0,19.0,50,1,true,10.0,90,1013.0),hourly=listOf(WearWeatherHour("2026-11-24T13:00",21.0,1,10,true)),daily=listOf(WearWeatherDay("2026-11-24",1,22.0,15.0,10)))+ @Test fun goldenSnapshotJson(){ val s=WearWeatherSnapshot(1000L,listOf(loc(42L,true)),false)+  assertEquals("""{"generatedAtMillis":1000,"locations":[{"locationId":42,"name":"Loc 42","country":"X","isPrimary":true,"current":{"timeIso":"2026-11-24T12:00","temperatureC":20.0,"apparentTemperatureC":19.0,"humidityPercent":50,"weatherCode":1,"windSpeedKmh":10.0,"windDirectionDegrees":90,"pressureHpa":1013.0},"hourly":[{"timeIso":"2026-11-24T13:00","temperatureC":21.0,"weatherCode":1,"precipitationProbabilityPercent":10}],"daily":[{"dateIso":"2026-11-24","weatherCode":1,"temperatureMaxC":22.0,"temperatureMinC":15.0,"precipitationProbabilityMaxPercent":10}]}]}""", WearWeatherProtocol.json.encodeToString(s)) }+ @Test fun roundTrips(){ val s=WearWeatherSnapshot(9L,listOf(loc(1L)),true); assertEquals(s, WearWeatherProtocol.json.decodeFromString<WearWeatherSnapshot>(WearWeatherProtocol.json.encodeToString(s))) }+ @Test fun buildPrimaryFirstAndCapsLocations(){ val s=buildWearWeatherSnapshot((1L..6L).map{loc(it,it==3L)},0L); assertEquals(3L,s.locations.first().locationId); assertEquals(WearWeatherProtocol.MAX_LOCATIONS,s.locations.size); assertTrue(s.truncated) }+ @Test fun buildCapsHourlyDaily(){ val big=loc(1L,true).copy(hourly=(1..40).map{WearWeatherHour("2026-11-24T13:00",1.0,1)},daily=(1..10).map{WearWeatherDay("2026-11-24",1,2.0,1.0)}); val s=buildWearWeatherSnapshot(listOf(big),0L); assertEquals(WearWeatherProtocol.MAX_HOURLY,s.locations[0].hourly.size); assertEquals(WearWeatherProtocol.MAX_DAILY,s.locations[0].daily.size) }+ @Test fun presenceAbsent(){ assertFalse(wearCompanionPresent(emptyList())); assertTrue(wearCompanionPresent(listOf("n"))) }+ @Test fun buildCapsBytes(){ val many=(1L..4L).map{ loc(it).copy(name="x".repeat(200),hourly=(1..24).map{WearWeatherHour("2026-11-24T13:00",1.0,1)}) }; val s=buildWearWeatherSnapshot(many,0L); assertTrue(WearWeatherProtocol.json.encodeToString(s).encodeToByteArray().size<=WearWeatherProtocol.MAX_JSON_BYTES) }+}
weather/build.gradle.kts
diff --git a/weather/build.gradle.kts b/weather/build.gradle.ktsindex 31163ed891..a2a81432eb 100644--- a/weather/build.gradle.kts+++ b/weather/build.gradle.kts@@ -92,6 +92,7 @@ dependencies {     implementation(project(":library:widgets"))     implementation(libs.androidx.datastore.preferences)     implementation(project(":library:map"))+    implementation(project(":library:wearlink"))     implementRoom(libs)     implementation(project(":library:room")) 
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 30e6c57d10..88b8786c13 100644--- a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -22,6 +22,7 @@ class MainActivity : MaActivity() {     }      override fun onCreateBeforeContent() {+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)         // FIRST_PARTY covers api.maproj.org (self-hosted weather bundle         // fallback and tiles proxy) and static.maproj.org (static weather         // tiles, R2 custom domain on the same Cloudflare roots); place
weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.ktindex e83abdb760..a327e4f638 100644--- a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt+++ b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt@@ -44,6 +44,7 @@ class WeatherRefreshWorker(                     Log.status(TAG, "Failed to refresh weather for ${location.name}: ${e.message}")                 }             }+            com.vayunmathur.weather.sync.WearWeatherSync.get(context).onForecastRefreshed()             WeatherGlanceWidget().updateAll(context)             WeatherBlobGlanceWidget().updateAll(context)             Result.success()
weather/src/main/java/com/vayunmathur/weather/domain/WearWeatherProtocol.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/domain/WearWeatherProtocol.kt b/weather/src/main/java/com/vayunmathur/weather/domain/WearWeatherProtocol.ktnew file mode 100644index 0000000000..1c1bed1ee4--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/domain/WearWeatherProtocol.kt@@ -0,0 +1,119 @@+package com.vayunmathur.weather.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS Weather companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module+ * (`:weather:wear`, applicationId `com.vayunmathur.weather`) carries a copy+ * of this file under `com.vayunmathur.weather.wear.domain`. Change both+ * copies together; each side's unit tests pin the same golden JSON.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [SNAPSHOT_PATH] phone -> watch, [WATCH_STATE_PATH] watch -> phone.+ * - Messages: [REQUEST_SYNC_PATH] watch -> phone (only watch-originated write).+ * Bounded by design: primary location first, then favorites, caps below.+ */+object WearWeatherProtocol {+    const val CAPABILITY = "weather_wear_companion"+    const val SNAPSHOT_PATH = "/weather/snapshot"+    const val WATCH_STATE_PATH = "/weather/watch-state"+    const val REQUEST_SYNC_PATH = "/weather/request-sync"+    const val MAX_LOCATIONS = 4+    const val MAX_HOURLY = 24+    const val MAX_DAILY = 7+    const val MAX_JSON_BYTES = 90_000+    const val MAX_NAME_CHARS = 80+    val json: Json = Json { ignoreUnknownKeys = true }+}++@Serializable+data class WearWeatherCurrent(+    val timeIso: String = "",+    val temperatureC: Double = 0.0,+    val apparentTemperatureC: Double = 0.0,+    val humidityPercent: Int = 0,+    val weatherCode: Int = -1,+    val isDay: Boolean = true,+    val windSpeedKmh: Double = 0.0,+    val windDirectionDegrees: Int = 0,+    val pressureHpa: Double = 0.0,+)++@Serializable+data class WearWeatherHour(+    val timeIso: String = "",+    val temperatureC: Double = 0.0,+    val weatherCode: Int = -1,+    val precipitationProbabilityPercent: Int = 0,+    val isDay: Boolean = true,+)++@Serializable+data class WearWeatherDay(+    val dateIso: String = "",+    val weatherCode: Int = -1,+    val temperatureMaxC: Double = 0.0,+    val temperatureMinC: Double = 0.0,+    val precipitationProbabilityMaxPercent: Int = 0,+)++@Serializable+data class WearWeatherLocation(+    val locationId: Long = 0L,+    val name: String = "",+    val country: String = "",+    val isPrimary: Boolean = false,+    val timezone: String = "UTC",+    val current: WearWeatherCurrent? = null,+    val hourly: List<WearWeatherHour> = emptyList(),+    val daily: List<WearWeatherDay> = emptyList(),+)++@Serializable+data class WearWeatherSnapshot(+    val generatedAtMillis: Long = 0L,+    val locations: List<WearWeatherLocation> = emptyList(),+    val truncated: Boolean = false,+)++@Serializable+data class WearWatchState(+    val appliedGeneratedAtMillis: Long = 0L,+    val locationCount: Int = 0,+)++/** Primary first (stable for equal rank), then field/list caps, then JSON-size cap (drop last locations, then hourly). */+fun buildWearWeatherSnapshot(+    candidates: List<WearWeatherLocation>,+    generatedAtMillis: Long,+): WearWeatherSnapshot {+    val ordered = candidates.sortedByDescending { it.isPrimary }.map { loc ->+        loc.copy(+            name = loc.name.take(WearWeatherProtocol.MAX_NAME_CHARS),+            country = loc.country.take(WearWeatherProtocol.MAX_NAME_CHARS),+            hourly = loc.hourly.take(WearWeatherProtocol.MAX_HOURLY),+            daily = loc.daily.take(WearWeatherProtocol.MAX_DAILY),+        )+    }+    var kept = ordered.take(WearWeatherProtocol.MAX_LOCATIONS)+    var truncated = kept.size < ordered.size+    var snapshot = WearWeatherSnapshot(generatedAtMillis, kept, truncated)+    fun over() = WearWeatherProtocol.json.encodeToString(snapshot).encodeToByteArray().size > WearWeatherProtocol.MAX_JSON_BYTES+    while (over() && kept.size > 1) {+        kept = kept.dropLast(1); truncated = true+        snapshot = WearWeatherSnapshot(generatedAtMillis, kept, true)+    }+    while (over() && kept.firstOrNull()?.hourly?.isNotEmpty() == true) {+        kept = kept.mapIndexed { i, loc -> if (i == 0) loc.copy(hourly = loc.hourly.dropLast(1)) else loc }+        snapshot = WearWeatherSnapshot(generatedAtMillis, kept, true)+    }+    return snapshot+}++/** True when a companion node is present (non-empty handshake set). */+fun wearCompanionPresent(nodeIdsWithCapability: Collection<String>): Boolean = nodeIdsWithCapability.isNotEmpty()
weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.ktindex be26271b52..9f27270492 100644--- a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt+++ b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt@@ -55,6 +55,8 @@ class WeatherViewModel(     }, ) : AndroidViewModel(application), WeatherActions { +    val wearSyncState = com.vayunmathur.weather.sync.WearWeatherSync.get(application).state+    fun syncWearNow() = com.vayunmathur.weather.sync.WearWeatherSync.get(getApplication()).syncNow()     val savedLocations: StateFlow<List<SavedLocation>?> = repository.locations         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) @@ -95,6 +97,7 @@ class WeatherViewModel(      init {         WeatherRefreshWorker.scheduleHourlyRefresh(application)+        com.vayunmathur.weather.sync.WearWeatherSync.get(application).start()     }      fun ensureForecast(location: SavedLocation, force: Boolean = false) {@@ -197,6 +200,7 @@ class WeatherViewModel(                     ))                 }                 runCatching { WeatherGlanceWidget().updateAll(getApplication<Application>()) }+                com.vayunmathur.weather.sync.WearWeatherSync.get(getApplication<Application>()).onForecastRefreshed()             }             .onFailure { e ->                 _forecasts.update { current ->
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.ktnew file mode 100644index 0000000000..cf0cd4fc73--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/sync/WearWeatherSync.kt@@ -0,0 +1,63 @@+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.weather.data.WeatherRepository+import com.vayunmathur.weather.data.weatherJson+import com.vayunmathur.weather.domain.WearWeatherCurrent+import com.vayunmathur.weather.domain.WearWeatherDay+import com.vayunmathur.weather.domain.WearWeatherHour+import com.vayunmathur.weather.domain.WearWeatherLocation+import com.vayunmathur.weather.domain.WearWeatherProtocol+import com.vayunmathur.weather.domain.WearWeatherSnapshot+import com.vayunmathur.weather.domain.WearWatchState+import com.vayunmathur.weather.domain.buildWearWeatherSnapshot+import com.vayunmathur.weather.domain.roundCoord+import com.vayunmathur.weather.domain.wearCompanionPresent+import com.vayunmathur.weather.network.ForecastResponse+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+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++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. */+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}} }+ private val appContext=context.applicationContext; private val scope=CoroutineScope(SupervisorJob()+Dispatchers.IO)+ private val _state=MutableStateFlow(WearSyncState()); val state:StateFlow<WearSyncState> = _state.asStateFlow()+ private val listener=object:WearLinkListener{+  override fun onData(path:String,body:ByteArray){ if(path!=WearWeatherProtocol.WATCH_STATE_PATH)return+   val ws=runCatching{WearWeatherProtocol.json.decodeFromString<WearWatchState>(body.decodeToString())}.getOrNull()?:return+   _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() }+ 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)") }+ 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+   val f=runCatching{weatherJson.decodeFromString<ForecastResponse>(cache.forecastJson)}.getOrNull()?:return@mapNotNull null; mapLocation(loc,f) }+  if(candidates.isEmpty()) null else buildWearWeatherSnapshot(candidates, System.currentTimeMillis())+ }.onFailure{Log.status(TAG,"build failed: ${it.message}")}.getOrNull()++ private fun mapLocation(loc:com.vayunmathur.weather.data.SavedLocation, f:ForecastResponse):WearWeatherLocation{+  val cur=f.current; val hourlyDto=f.hourly; val dailyDto=f.daily; val startIdx=if(cur!=null&&hourlyDto!=null) hourlyDto.time.indexOfFirst{it>=cur.time}.let{if(it<0)0 else it} else 0+  val hourly=hourlyDto?.time?.drop(startIdx)?.mapIndexedNotNull{ i, t-> val idx=startIdx+i; WearWeatherHour(t, hourlyDto.temperature.getOrElse(idx){0.0}, hourlyDto.weatherCode.getOrElse(idx){-1}, hourlyDto.precipitationProbability.getOrElse(idx){0}, hourlyDto.isDay.getOrElse(idx){1}==1) }?:emptyList()+  val daily=dailyDto?.time?.mapIndexed{ i,d-> WearWeatherDay(d, dailyDto.weatherCode.getOrElse(i){-1}, dailyDto.temperatureMax.getOrElse(i){0.0}, dailyDto.temperatureMin.getOrElse(i){0.0}, dailyDto.precipitationProbabilityMax.getOrElse(i){0}) }?:emptyList()+  return WearWeatherLocation(loc.id, loc.name, loc.country, loc.isCurrent, f.timezone?:"UTC", cur?.let{WearWeatherCurrent(it.time,it.temperature,it.apparentTemperature,it.relativeHumidity,it.weatherCode,it.isDay==1,it.windSpeed,it.windDirection,it.pressureMsl)}, hourly, daily)+ }+}
weather/src/main/java/com/vayunmathur/weather/ui/LocationsPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/LocationsPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/LocationsPage.ktindex 87460a488a..d8a7d3d5a6 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/LocationsPage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/LocationsPage.kt@@ -102,6 +102,8 @@ fun LocationsPage(         )     } +    val wearState by viewModel.wearSyncState.collectAsState()+    val wearStatusText = if (wearState.companionPresent) "Watch: connected" + (wearState.lastPublishedAtMillis?.let { " · synced" } ?: "") else "Watch: not connected — showing phone weather only"     LocationsScreen(         state = LocationsUiState(             hasLoaded = savedLocations != null,@@ -114,6 +116,7 @@ fun LocationsPage(         onClose = onClose,         onSearchLocation = { backStack.add(Route.SearchLocation) },         onUseDeviceLocation = onAddCurrentLocation,+        wearStatusText = wearStatusText,     ) } 
weather/src/main/java/com/vayunmathur/weather/ui/LocationsScreen.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/LocationsScreen.kt b/weather/src/main/java/com/vayunmathur/weather/ui/LocationsScreen.ktindex 1ed6909f78..31678fcde6 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/LocationsScreen.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/LocationsScreen.kt@@ -79,6 +79,7 @@ fun LocationsScreen(     onClose: () -> Unit = {},     onSearchLocation: () -> Unit = {},     onUseDeviceLocation: () -> Unit = {},+    wearStatusText: String? = null, ) {     var longPressedLocation: SavedLocation? by remember { mutableStateOf(null) }     val sheetState = rememberBottomSheetState(initialValue = SheetValue.Hidden, enabledValues = setOf(SheetValue.Hidden, SheetValue.Expanded))@@ -154,6 +155,7 @@ fun LocationsScreen(             }         },     ) {+        if (wearStatusText != null) { item { Text(wearStatusText, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(horizontal = 4.dp)) } }         val showDeviceLocationCard = localData.none { it.location.isCurrent }         if (showDeviceLocationCard) {             item {
weather/src/test/java/com/vayunmathur/weather/domain/WearWeatherProtocolTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/WearWeatherProtocolTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/WearWeatherProtocolTest.ktnew file mode 100644index 0000000000..6f0e64c022--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/domain/WearWeatherProtocolTest.kt@@ -0,0 +1,16 @@+package com.vayunmathur.weather.domain+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString+class WearWeatherProtocolTest {+ private fun loc(id:Long,primary:Boolean=false)=WearWeatherLocation(locationId=id,name="Loc $id",country="X",isPrimary=primary,timezone="UTC",current=WearWeatherCurrent("2026-11-24T12:00",20.0,19.0,50,1,true,10.0,90,1013.0),hourly=listOf(WearWeatherHour("2026-11-24T13:00",21.0,1,10,true)),daily=listOf(WearWeatherDay("2026-11-24",1,22.0,15.0,10)))+ @Test fun goldenSnapshotJson(){ val s=WearWeatherSnapshot(1000L,listOf(loc(42L,true)),false)+  assertEquals("""{"generatedAtMillis":1000,"locations":[{"locationId":42,"name":"Loc 42","country":"X","isPrimary":true,"current":{"timeIso":"2026-11-24T12:00","temperatureC":20.0,"apparentTemperatureC":19.0,"humidityPercent":50,"weatherCode":1,"windSpeedKmh":10.0,"windDirectionDegrees":90,"pressureHpa":1013.0},"hourly":[{"timeIso":"2026-11-24T13:00","temperatureC":21.0,"weatherCode":1,"precipitationProbabilityPercent":10}],"daily":[{"dateIso":"2026-11-24","weatherCode":1,"temperatureMaxC":22.0,"temperatureMinC":15.0,"precipitationProbabilityMaxPercent":10}]}]}""", WearWeatherProtocol.json.encodeToString(s)) }+ @Test fun roundTrips(){ val s=WearWeatherSnapshot(9L,listOf(loc(1L)),true); assertEquals(s, WearWeatherProtocol.json.decodeFromString<WearWeatherSnapshot>(WearWeatherProtocol.json.encodeToString(s))) }+ @Test fun buildPrimaryFirstAndCapsLocations(){ val s=buildWearWeatherSnapshot((1L..6L).map{loc(it,it==3L)},0L); assertEquals(3L,s.locations.first().locationId); assertEquals(WearWeatherProtocol.MAX_LOCATIONS,s.locations.size); assertTrue(s.truncated) }+ @Test fun buildCapsHourlyDaily(){ val big=loc(1L,true).copy(hourly=(1..40).map{WearWeatherHour("2026-11-24T13:00",1.0,1)},daily=(1..10).map{WearWeatherDay("2026-11-24",1,2.0,1.0)}); val s=buildWearWeatherSnapshot(listOf(big),0L); assertEquals(WearWeatherProtocol.MAX_HOURLY,s.locations[0].hourly.size); assertEquals(WearWeatherProtocol.MAX_DAILY,s.locations[0].daily.size) }+ @Test fun presenceAbsent(){ assertFalse(wearCompanionPresent(emptyList())); assertTrue(wearCompanionPresent(listOf("n"))) }+ @Test fun buildCapsBytes(){ val many=(1L..4L).map{ loc(it).copy(name="x".repeat(200),hourly=(1..24).map{WearWeatherHour("2026-11-24T13:00",1.0,1)}) }; val s=buildWearWeatherSnapshot(many,0L); assertTrue(WearWeatherProtocol.json.encodeToString(s).encodeToByteArray().size<=WearWeatherProtocol.MAX_JSON_BYTES) }+}