Modern Apps git

← Modern-Apps.git

watch: extract shared module for session DTO and BLE contract

Commit
de52918d51f27c4c50eb22e36fd7fd1d204efdc4
Author
Vayun Mathur <[email protected]>
When
2026-07-06 17:31 UTC (5 months ago)
Parents
2221597

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 42c805fa04..5980dfe602 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -54,6 +54,8 @@ pdfViewer = "1.0.0-alpha19" glance = "1.1.1" connectClient = "1.2.0-alpha04" healthServicesClient = "1.1.0-alpha05"+wearTiles = "1.4.1"+wearProtolayout = "1.2.1" cryptographyCore = "0.6.0" libphonenumber = "9.0.32" material3AdaptiveNavigationSuite = "1.4.0"@@ -168,6 +170,13 @@ androidx-connect-client = { module = "androidx.health.connect:connect-client", v # Wear OS Health Services — direct, OEM-calibrated on-watch measurements. Not # Google Play / GMS; safe to keep isolated to the watch module. androidx-health-services-client = { module = "androidx.health:health-services-client", version.ref = "healthServicesClient" }+# Wear OS Tiles + ProtoLayout — quick-glance workout controls surface. Wear-only+# platform components; no Google Play / GMS.+androidx-wear-tiles = { module = "androidx.wear.tiles:tiles", version.ref = "wearTiles" }+androidx-wear-protolayout = { module = "androidx.wear.protolayout:protolayout", version.ref = "wearProtolayout" }+androidx-wear-protolayout-material = { module = "androidx.wear.protolayout:protolayout-material", version.ref = "wearProtolayout" }+androidx-wear-protolayout-expression = { module = "androidx.wear.protolayout:protolayout-expression", version.ref = "wearProtolayout" }+androidx-concurrent-futures = { module = "androidx.concurrent:concurrent-futures", version = "1.2.0" } cryptography-core = { module = "dev.whyoleg.cryptography:cryptography-core", version.ref = "cryptographyCore" } cryptography-provider-jdk = { module = "dev.whyoleg.cryptography:cryptography-provider-jdk", version.ref = "cryptographyCore" } jaudiotagger = { module = "net.jthink:jaudiotagger", version.ref = "jaudiotagger" }
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 1147dfc8f5..66aac574d0 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -66,5 +66,6 @@ include(":launcher") include(":things") include(":office") include(":tools:holidaygen")+include(":watch:shared") include(":watch:watch") include(":watch:phone")
watch/phone/build.gradle.kts
diff --git a/watch/phone/build.gradle.kts b/watch/phone/build.gradle.ktsindex c473231191..d4e141930b 100644--- a/watch/phone/build.gradle.kts+++ b/watch/phone/build.gradle.kts@@ -11,6 +11,7 @@ android { }  dependencies {+    implementation(project(":watch:shared"))     implementation(libs.androidx.connect.client)     implementation(libs.androidx.work.runtime.ktx)     implementRoom(libs)
watch/phone/src/main/AndroidManifest.xml
diff --git a/watch/phone/src/main/AndroidManifest.xml b/watch/phone/src/main/AndroidManifest.xmlindex 3b73e46f3f..265e07163b 100644--- a/watch/phone/src/main/AndroidManifest.xml+++ b/watch/phone/src/main/AndroidManifest.xml@@ -21,6 +21,11 @@     <uses-permission android:name="android.permission.health.WRITE_TOTAL_CALORIES_BURNED" />     <uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE" />     <uses-permission android:name="android.permission.health.WRITE_SLEEP" />+    <!-- Active exercise session records (session-unique metrics only). -->+    <uses-permission android:name="android.permission.health.WRITE_EXERCISE" />+    <uses-permission android:name="android.permission.health.WRITE_EXERCISE_ROUTE" />+    <uses-permission android:name="android.permission.health.WRITE_SPEED" />+    <uses-permission android:name="android.permission.health.WRITE_VO2_MAX" />      <queries>         <package android:name="com.google.android.apps.healthdata" />
watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.ktdeleted file mode 100644index 6321b67a44..0000000000--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.kt+++ /dev/null@@ -1,19 +0,0 @@-package com.vayunmathur.watch.phone.ble--import java.util.UUID--/**- * Shared BLE contract between the watch (GATT server) and phone (GATT client).- * These UUIDs and opcodes are duplicated verbatim from the :watch:watch module.- */-object BleConstants {-    val SERVICE_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-567812345678")-    val DATA_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-567812345679")-    val CONTROL_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-56781234567a")-    val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")--    const val OPCODE_ACK: Byte = 0x01-    const val OPCODE_CLEAR: Byte = 0x02--    val EOT_MARKER: ByteArray = byteArrayOf(0x04)-}
watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.ktindex ccb384f8da..21d3ae3e2c 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt@@ -15,6 +15,7 @@ import android.bluetooth.le.ScanSettings import android.content.Context import android.os.ParcelUuid import android.util.Log+import com.vayunmathur.watch.shared.ble.BleConstants import com.vayunmathur.watch.phone.data.WatchBatch import com.vayunmathur.watch.phone.data.WatchRecord import java.io.ByteArrayOutputStream
watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.ktindex db73fdd260..ef4728f4fb 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.kt@@ -11,6 +11,9 @@ data class WatchRecord(     val value: Double,     val delta: Double,     val stationary: Boolean = false,+    // Present only for type == "ExerciseSession": the serialized session summary+    // (com.vayunmathur.watch.shared.data.ExerciseSessionSummary JSON).+    val session: String? = null, )  @Serializable
watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.ktindex 728b1fa3d0..353c217a2a 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt@@ -6,17 +6,26 @@ import androidx.health.connect.client.HealthConnectClient import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.DistanceRecord import androidx.health.connect.client.records.ElevationGainedRecord+import androidx.health.connect.client.records.ExerciseRoute+import androidx.health.connect.client.records.ExerciseSegment+import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.FloorsClimbedRecord import androidx.health.connect.client.records.HeartRateRecord import androidx.health.connect.client.records.Record import androidx.health.connect.client.records.RestingHeartRateRecord import androidx.health.connect.client.records.SleepSessionRecord+import androidx.health.connect.client.records.SpeedRecord+import androidx.health.connect.client.records.StepsCadenceRecord import androidx.health.connect.client.records.StepsRecord import androidx.health.connect.client.records.TotalCaloriesBurnedRecord+import androidx.health.connect.client.records.Vo2MaxRecord import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Energy import androidx.health.connect.client.units.Length+import androidx.health.connect.client.units.Velocity+import com.vayunmathur.watch.shared.data.ExerciseSessionSummary import com.vayunmathur.watch.phone.data.WatchRecord+import kotlinx.serialization.json.Json import java.time.Instant import java.time.LocalDate import java.time.ZoneId@@ -38,8 +47,16 @@ class HealthConnectManager(private val context: Context) {         HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class),         HealthPermission.getWritePermission(RestingHeartRateRecord::class),         HealthPermission.getWritePermission(SleepSessionRecord::class),+        // Active exercise session records (session-unique metrics only).+        HealthPermission.getWritePermission(ExerciseSessionRecord::class),+        HealthPermission.getWritePermission(SpeedRecord::class),+        HealthPermission.getWritePermission(StepsCadenceRecord::class),+        HealthPermission.getWritePermission(Vo2MaxRecord::class),+        HealthPermission.PERMISSION_WRITE_EXERCISE_ROUTE,     ) +    private val json = Json { ignoreUnknownKeys = true }+     fun sdkStatus(): Int = HealthConnectClient.getSdkStatus(context)      fun isAvailable(): Boolean = sdkStatus() == HealthConnectClient.SDK_AVAILABLE@@ -52,7 +69,13 @@ class HealthConnectManager(private val context: Context) {     suspend fun insert(records: List<WatchRecord>) {         if (records.isEmpty()) return         val zone = ZoneId.systemDefault()-        val hcRecords = records.mapNotNull { record ->++        // Exercise sessions carry a JSON summary and map to a family of session+        // records; handle them separately from the scalar per-sample/daily types.+        val (sessions, scalars) = records.partition { it.type == "ExerciseSession" }+        sessions.forEach { insertExerciseSession(it, zone) }++        val hcRecords = scalars.mapNotNull { record ->             val time = Instant.ofEpochMilli(record.timestamp)             val offset = zone.rules.getOffset(time)             when (record.type) {@@ -148,6 +171,133 @@ class HealthConnectManager(private val context: Context) {         return build(start, day)     } +    /**+     * Parses the session JSON and writes the session envelope plus ONLY the+     * session-unique records (Speed, StepsCadence, Vo2Max) and route/segments.+     *+     * Deliberately NOT written here: Distance, Floors, Elevation, Calories, Steps+     * and HeartRate. Those already flow into Health Connect via the passive+     * daily-total pipeline and the watch's SensorManager per-sample pipeline while+     * the workout is happening. Writing session-scoped copies for the same app+     * origin would sum on top of those and double-count. The live values shown on+     * the watch come from ExerciseUpdate and are carried here only as display-only+     * aggregates — never re-written as records.+     */+    private suspend fun insertExerciseSession(record: WatchRecord, zone: ZoneId) {+        val jsonStr = record.session ?: return+        val summary = try {+            json.decodeFromString<ExerciseSessionSummary>(jsonStr)+        } catch (e: Exception) {+            Log.e(TAG, "parse ExerciseSessionSummary failed", e)+            return+        }++        val start = Instant.ofEpochMilli(summary.startTime)+        var end = Instant.ofEpochMilli(summary.endTime)+        if (!end.isAfter(start)) end = start.plusSeconds(1)+        val startOffset = zone.rules.getOffset(start)+        val endOffset = zone.rules.getOffset(end)+        val key = summary.startTime++        val toInsert = mutableListOf<Record>()++        val route = summary.route?.takeIf { it.isNotEmpty() }?.let { points ->+            ExerciseRoute(+                points.map { p ->+                    ExerciseRoute.Location(+                        time = Instant.ofEpochMilli(p.time),+                        latitude = p.lat,+                        longitude = p.lng,+                        altitude = p.altitude?.let { Length.meters(it) },+                    )+                },+            )+        }++        val segments = summary.segments.orEmpty().map { seg ->+            ExerciseSegment(+                startTime = Instant.ofEpochMilli(seg.start),+                endTime = Instant.ofEpochMilli(seg.end).let {+                    if (it.isAfter(Instant.ofEpochMilli(seg.start))) it+                    else Instant.ofEpochMilli(seg.start).plusSeconds(1)+                },+                segmentType = seg.type,+                repetitions = seg.reps.toInt(),+            )+        }++        toInsert += ExerciseSessionRecord(+            startTime = start,+            startZoneOffset = startOffset,+            endTime = end,+            endZoneOffset = endOffset,+            exerciseType = healthConnectExerciseType(summary.exerciseType),+            title = null,+            segments = segments,+            laps = emptyList(),+            exerciseRoute = route,+            metadata = Metadata.manualEntry(clientRecordId = "exercise-$key"),+        )++        // Speed: only avg/max were reported (no time series), so emit avg at the+        // start and max at the end of the window.+        summary.avgSpeedMps?.let { avg ->+            val samples = buildList {+                add(SpeedRecord.Sample(time = start, speed = Velocity.metersPerSecond(avg)))+                summary.maxSpeedMps?.let {+                    add(SpeedRecord.Sample(time = end, speed = Velocity.metersPerSecond(it)))+                }+            }+            toInsert += SpeedRecord(+                startTime = start,+                startZoneOffset = startOffset,+                endTime = end,+                endZoneOffset = endOffset,+                samples = samples,+                metadata = Metadata.manualEntry(clientRecordId = "exercise-speed-$key"),+            )+        }++        summary.avgCadenceSpm?.let { cadence ->+            toInsert += StepsCadenceRecord(+                startTime = start,+                startZoneOffset = startOffset,+                endTime = end,+                endZoneOffset = endOffset,+                samples = listOf(StepsCadenceRecord.Sample(time = start, rate = cadence)),+                metadata = Metadata.manualEntry(clientRecordId = "exercise-cadence-$key"),+            )+        }++        summary.vo2Max?.let { vo2 ->+            toInsert += Vo2MaxRecord(+                time = end,+                zoneOffset = endOffset,+                vo2MillilitersPerMinuteKilogram = vo2,+                measurementMethod = Vo2MaxRecord.MEASUREMENT_METHOD_OTHER,+                metadata = Metadata.manualEntry(clientRecordId = "exercise-vo2-$key"),+            )+        }++        try {+            client().insertRecords(toInsert)+        } catch (e: Exception) {+            Log.e(TAG, "insert exercise session failed", e)+        }+    }++    // Health Services ExerciseType.name -> Health Connect EXERCISE_TYPE_* int.+    // The two enum systems differ, so the mapping is explicit.+    private fun healthConnectExerciseType(hsName: String): Int = when (hsName) {+        "WALKING" -> ExerciseSessionRecord.EXERCISE_TYPE_WALKING+        "RUNNING" -> ExerciseSessionRecord.EXERCISE_TYPE_RUNNING+        "BIKING" -> ExerciseSessionRecord.EXERCISE_TYPE_BIKING+        "HIKING" -> ExerciseSessionRecord.EXERCISE_TYPE_HIKING+        "SWIMMING_POOL" -> ExerciseSessionRecord.EXERCISE_TYPE_SWIMMING_POOL+        "STRENGTH_TRAINING" -> ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING+        else -> ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT+    }+     /** Batch-inserts derivation output; clientRecordIds make this idempotent. */     suspend fun insertDerived(records: List<Record>) {         if (records.isEmpty()) return
watch/shared/build.gradle.kts
diff --git a/watch/shared/build.gradle.kts b/watch/shared/build.gradle.ktsnew file mode 100644index 0000000000..38d22979f1--- /dev/null+++ b/watch/shared/build.gradle.kts@@ -0,0 +1,20 @@+plugins {+    // Applied directly (not common-conventions-library) to keep this module free+    // of Compose: it is the phone-safe contract layer, kotlinx.serialization only.+    alias(libs.plugins.android.library)+    alias(libs.plugins.kotlin.serialization)+}++android {+    namespace = "com.vayunmathur.watch.shared"+    compileSdk {+        version = release(37)+    }+    defaultConfig {+        minSdk = 30+    }+}++dependencies {+    implementation(libs.kotlinx.serialization.json)+}
watch/shared/src/main/java/com/vayunmathur/watch/shared/ble/BleConstants.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/BleConstants.kt b/watch/shared/src/main/java/com/vayunmathur/watch/shared/ble/BleConstants.ktsimilarity index 63%rename from watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/BleConstants.ktrename to watch/shared/src/main/java/com/vayunmathur/watch/shared/ble/BleConstants.ktindex 1b7fc60020..5d3cc0a239 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/BleConstants.kt+++ b/watch/shared/src/main/java/com/vayunmathur/watch/shared/ble/BleConstants.kt@@ -1,10 +1,10 @@-package com.vayunmathur.watch.watch.ble+package com.vayunmathur.watch.shared.ble  import java.util.UUID  /**- * Shared BLE contract between the watch (GATT server) and phone (GATT client).- * These UUIDs and opcodes are duplicated verbatim in the :watch:phone module.+ * Single source of truth for the BLE contract between the watch (GATT server) and+ * phone (GATT client). Shared by both apps so the UUIDs/opcodes cannot drift.  */ object BleConstants {     val SERVICE_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-567812345678")@@ -15,6 +15,11 @@ object BleConstants {     // WRITE: phone sends control opcodes (ACK / CLEAR) back to the watch.     val CONTROL_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-56781234567a") +    // READ + WRITE + NOTIFY: the current Do-Not-Disturb interruption filter as a+    // single byte (1=ALL, 2=PRIORITY, 3=NONE, 4=ALARMS). Either side can write it+    // and both get notified; the watch holds the authoritative value.+    val DND_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-56781234567b")+     // Client Characteristic Configuration Descriptor (standard 0x2902).     val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") 
watch/shared/src/main/java/com/vayunmathur/watch/shared/data/ExerciseSessionSummary.kt
diff --git a/watch/shared/src/main/java/com/vayunmathur/watch/shared/data/ExerciseSessionSummary.kt b/watch/shared/src/main/java/com/vayunmathur/watch/shared/data/ExerciseSessionSummary.ktnew file mode 100644index 0000000000..c281c25483--- /dev/null+++ b/watch/shared/src/main/java/com/vayunmathur/watch/shared/data/ExerciseSessionSummary.kt@@ -0,0 +1,77 @@+package com.vayunmathur.watch.shared.data++import kotlinx.serialization.Serializable++/**+ * Serializable summary of one active exercise session captured on the watch via+ * Health Services `ExerciseClient`. It is stored as a JSON blob in the watch's+ * `SensorRecord.session`, shipped to the phone over the existing BLE pipeline,+ * and parsed there into Health Connect records.+ *+ * This is the single source of truth for the DTO, shared by both apps. All metric+ * fields are nullable and capability-gated: only the values the watch actually+ * reported for the chosen exercise type are populated. Only session-unique data+ * lives here — distance, calories, steps and HR keep flowing through the passive/+ * SensorManager pipelines and must NOT be re-derived from this summary (see the+ * phone's HealthConnectManager.insertExerciseSession).+ */+@Serializable+data class ExerciseSessionSummary(+    // Health Services ExerciseType.name (e.g. "RUNNING"). Mapped to the Health+    // Connect exercise-type int on the phone.+    val exerciseType: String,+    val startTime: Long,+    val endTime: Long,+    val activeDurationMs: Long,+    // Session-unique metrics (no daily/passive equivalent).+    val avgSpeedMps: Double? = null,+    val maxSpeedMps: Double? = null,+    val avgCadenceSpm: Double? = null,+    val vo2Max: Double? = null,+    val route: List<RoutePoint>? = null,+    // Display-only lap count aggregate; the real per-lap markers ride in [laps].+    val lapCount: Long? = null,+    val laps: List<LapMarker>? = null,+    // Throttled speed time-series; the phone prefers this over the avg/max+    // approximation when building the SpeedRecord.+    val speedSamples: List<SpeedSample>? = null,+    val segments: List<RepSegment>? = null,+    // Human-readable terminal reason (e.g. "Ended by user", "Auto-paused"). Display-only.+    val endReason: String? = null,+    // Display-only aggregates for debugging/UI. The phone does NOT write these as+    // records (they already flow through the daily/passive pipelines).+    val distanceMeters: Double? = null,+    val totalCalories: Double? = null,+    val avgHr: Double? = null,+)++@Serializable+data class RoutePoint(+    val lat: Double,+    val lng: Double,+    val altitude: Double? = null,+    val time: Long,+)++@Serializable+data class RepSegment(+    // A Health Connect ExerciseSegment type constant (int).+    val type: Int,+    val reps: Long,+    val start: Long,+    val end: Long,+)++/** One swimming lap, mapped to a Health Connect [androidx.health.connect.client.records.ExerciseLap]. */+@Serializable+data class LapMarker(+    val start: Long,+    val end: Long,+)++/** One throttled speed sample, mapped to a Health Connect SpeedRecord.Sample. */+@Serializable+data class SpeedSample(+    val timeMs: Long,+    val mps: Double,+)
watch/watch/build.gradle.kts
diff --git a/watch/watch/build.gradle.kts b/watch/watch/build.gradle.ktsindex 57cddce380..612225b3cc 100644--- a/watch/watch/build.gradle.kts+++ b/watch/watch/build.gradle.kts@@ -10,6 +10,12 @@ android { }  dependencies {+    implementation(project(":watch:shared"))     implementation(libs.androidx.health.services.client)+    implementation(libs.androidx.wear.tiles)+    implementation(libs.androidx.wear.protolayout)+    implementation(libs.androidx.wear.protolayout.material)+    implementation(libs.androidx.wear.protolayout.expression)+    implementation(libs.androidx.concurrent.futures)     implementRoom(libs) }
watch/watch/src/main/AndroidManifest.xml
diff --git a/watch/watch/src/main/AndroidManifest.xml b/watch/watch/src/main/AndroidManifest.xmlindex 28d0de4052..f5cbce3d83 100644--- a/watch/watch/src/main/AndroidManifest.xml+++ b/watch/watch/src/main/AndroidManifest.xml@@ -6,14 +6,19 @@     <uses-feature         android:name="android.hardware.bluetooth_le"         android:required="true" />+    <uses-feature+        android:name="android.hardware.location.gps"+        android:required="false" />      <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />     <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />     <uses-permission android:name="android.permission.BODY_SENSORS" />     <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />     <uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_HEALTH" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />     <uses-permission android:name="android.permission.WAKE_LOCK" /> @@ -44,6 +49,31 @@             android:exported="false"             android:foregroundServiceType="health|connectedDevice" /> +        <service+            android:name=".service.ExerciseService"+            android:exported="false"+            android:foregroundServiceType="health|location" />++        <activity+            android:name=".ui.ExerciseControlActivity"+            android:exported="false"+            android:excludeFromRecents="true"+            android:taskAffinity=""+            android:theme="@style/Theme.NoDisplay" />++        <service+            android:name=".tile.ExerciseTileService"+            android:exported="true"+            android:label="@string/exercise_title"+            android:permission="com.google.android.wearable.permission.BIND_TILE_PROVIDER">+            <intent-filter>+                <action android:name="androidx.wear.tiles.action.BIND_TILE_PROVIDER" />+            </intent-filter>+            <meta-data+                android:name="androidx.wear.tiles.PREVIEW"+                android:resource="@drawable/ic_launcher_foreground" />+        </service>+     </application>  </manifest>
watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.ktindex 0c1279b616..3d4757d4a5 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt@@ -1,6 +1,7 @@ package com.vayunmathur.watch.watch  import android.Manifest+import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity@@ -9,8 +10,12 @@ import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -26,46 +31,126 @@ import androidx.wear.compose.material.Button import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.Text import com.vayunmathur.watch.watch.data.SensorDatabase+import com.vayunmathur.watch.watch.data.WorkoutType+import com.vayunmathur.watch.watch.service.ExerciseService import com.vayunmathur.watch.watch.service.SensorBackgroundService  class MainActivity : ComponentActivity() { +    private var openPickerFromTile by mutableStateOf(false)+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        handleIntent(intent)         setContent {             MaterialTheme {-                CollectorScreen()+                RootScreen(openPickerRequested = openPickerFromTile, onPickerConsumed = {+                    openPickerFromTile = false+                })             }         }     } +    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        handleIntent(intent)+    }++    private fun handleIntent(intent: Intent?) {+        if (intent?.getStringExtra(EXTRA_OPEN_PICKER) != null) {+            openPickerFromTile = true+        }+    }++    private enum class Screen { Home, Picker, Live }+     @Composable-    private fun CollectorScreen() {+    private fun RootScreen(openPickerRequested: Boolean, onPickerConsumed: () -> Unit) {         val context = this-        val dao = remember { SensorDatabase.get(context).sensorDao() }-        val rowCount by dao.countFlow().collectAsState(0)+        var screen by remember { mutableStateOf(Screen.Home) } -        var hasPermissions by remember { mutableStateOf(false) }-        var collecting by remember { mutableStateOf(false) }+        val exerciseState by ExerciseService.uiStateFlow.collectAsState()++        var hasCollectorPerms by remember { mutableStateOf(false) }+        var hasExercisePerms by remember { mutableStateOf(false) } -        val requestPermissions = rememberLauncherForActivityResult(+        val requestCollectorPerms = rememberLauncherForActivityResult(             contract = ActivityResultContracts.RequestMultiplePermissions(),-            onResult = { result -> hasPermissions = result.values.all { it } },+            onResult = { result -> hasCollectorPerms = result.values.all { it } },+        )+        val requestExercisePerms = rememberLauncherForActivityResult(+            contract = ActivityResultContracts.RequestMultiplePermissions(),+            onResult = { result -> hasExercisePerms = result.values.all { it } },         )          LaunchedEffect(Unit) {-            hasPermissions = requiredPermissions().all {-                checkSelfPermission(it) == android.content.pm.PackageManager.PERMISSION_GRANTED+            hasCollectorPerms = collectorPermissions().all { granted(it) }+            hasExercisePerms = exercisePermissions().all { granted(it) }+        }++        // Route to the picker when launched from the Tile.+        LaunchedEffect(openPickerRequested) {+            if (openPickerRequested) {+                screen = Screen.Picker+                onPickerConsumed()+            }+        }++        // Follow the session: show live metrics whenever a workout is running.+        LaunchedEffect(exerciseState) {+            when (exerciseState) {+                ExerciseService.UiState.Preparing,+                ExerciseService.UiState.Active,+                ExerciseService.UiState.Paused,+                -> screen = Screen.Live+                ExerciseService.UiState.Ended -> if (screen == Screen.Live) screen = Screen.Home+                ExerciseService.UiState.Idle -> Unit             }         } +        when (screen) {+            Screen.Home -> HomeScreen(+                hasCollectorPerms = hasCollectorPerms,+                onGrantCollector = { requestCollectorPerms.launch(collectorPermissions()) },+                onOpenPicker = {+                    if (hasExercisePerms) screen = Screen.Picker+                    else requestExercisePerms.launch(exercisePermissions())+                },+            )+            Screen.Picker -> PickerScreen(+                onPick = { workout ->+                    ExerciseService.start(context, workout)+                    screen = Screen.Live+                },+                onBack = { screen = Screen.Home },+            )+            Screen.Live -> LiveScreen(+                state = exerciseState,+                onPause = { ExerciseService.pause(context) },+                onResume = { ExerciseService.resume(context) },+                onStop = { ExerciseService.stop(context) },+            )+        }+    }++    @Composable+    private fun HomeScreen(+        hasCollectorPerms: Boolean,+        onGrantCollector: () -> Unit,+        onOpenPicker: () -> Unit,+    ) {+        val context = this+        val dao = remember { SensorDatabase.get(context).sensorDao() }+        val rowCount by dao.countFlow().collectAsState(0)+        var collecting by remember { mutableStateOf(false) }+         Column(-            modifier = Modifier.fillMaxSize().padding(16.dp),+            modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),             horizontalAlignment = Alignment.CenterHorizontally,             verticalArrangement = Arrangement.Center,         ) {-            if (!hasPermissions) {-                Button(onClick = { requestPermissions.launch(requiredPermissions()) }) {+            if (!hasCollectorPerms) {+                Button(onClick = onGrantCollector) {                     Text(stringResource(R.string.grant_permissions))                 }                 return@Column@@ -91,10 +176,83 @@ class MainActivity : ComponentActivity() {                     else stringResource(R.string.action_start),                 )             }+            Button(onClick = onOpenPicker, modifier = Modifier.padding(top = 8.dp)) {+                Text(stringResource(R.string.exercise_start_workout))+            }         }     } -    private fun requiredPermissions(): Array<String> {+    @Composable+    private fun PickerScreen(onPick: (WorkoutType) -> Unit, onBack: () -> Unit) {+        Column(+            modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(6.dp),+        ) {+            Text(stringResource(R.string.exercise_pick_type))+            WorkoutType.entries.forEach { workout ->+                Button(+                    onClick = { onPick(workout) },+                    modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp),+                ) {+                    Text(workout.label)+                }+            }+            Button(onClick = onBack, modifier = Modifier.padding(top = 4.dp)) {+                Text(stringResource(R.string.exercise_back))+            }+        }+    }++    @Composable+    private fun LiveScreen(+        state: ExerciseService.UiState,+        onPause: () -> Unit,+        onResume: () -> Unit,+        onStop: () -> Unit,+    ) {+        val durationMs by ExerciseService.activeDurationFlow.collectAsState()+        val hr by ExerciseService.heartRateFlow.collectAsState()+        val calories by ExerciseService.caloriesFlow.collectAsState()+        val distance by ExerciseService.distanceFlow.collectAsState()+        val label by ExerciseService.activeWorkoutLabelFlow.collectAsState()+        val dash = stringResource(R.string.exercise_dash)++        Column(+            modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.Center,+        ) {+            Text(label ?: stringResource(R.string.exercise_title))+            Text(stringResource(R.string.exercise_state, state.name))+            Text(stringResource(R.string.exercise_duration, formatDuration(durationMs)))+            Text(stringResource(R.string.exercise_hr, hr?.toInt()?.toString() ?: dash))+            Text(stringResource(R.string.exercise_calories, calories?.toInt()?.toString() ?: dash))+            Text(stringResource(R.string.exercise_distance, distance?.toInt()?.toString() ?: dash))++            Row(+                modifier = Modifier.padding(top = 8.dp),+                horizontalArrangement = Arrangement.spacedBy(8.dp),+            ) {+                if (state == ExerciseService.UiState.Paused) {+                    Button(onClick = onResume) { Text(stringResource(R.string.exercise_resume)) }+                } else {+                    Button(onClick = onPause) { Text(stringResource(R.string.exercise_pause)) }+                }+                Button(onClick = onStop) { Text(stringResource(R.string.exercise_stop)) }+            }+        }+    }++    private fun formatDuration(ms: Long): String {+        val totalSeconds = ms / 1000+        return "%d:%02d".format(totalSeconds / 60, totalSeconds % 60)+    }++    private fun granted(permission: String): Boolean =+        checkSelfPermission(permission) == android.content.pm.PackageManager.PERMISSION_GRANTED++    private fun collectorPermissions(): Array<String> {         val perms = mutableListOf(             Manifest.permission.BLUETOOTH_ADVERTISE,             Manifest.permission.BLUETOOTH_CONNECT,@@ -106,4 +264,22 @@ class MainActivity : ComponentActivity() {         }         return perms.toTypedArray()     }++    // Active exercise needs body sensors + activity recognition (HR/steps) and,+    // for outdoor GPS routes, fine location.+    private fun exercisePermissions(): Array<String> {+        val perms = mutableListOf(+            Manifest.permission.BODY_SENSORS,+            Manifest.permission.ACTIVITY_RECOGNITION,+            Manifest.permission.ACCESS_FINE_LOCATION,+        )+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+            perms += Manifest.permission.POST_NOTIFICATIONS+        }+        return perms.toTypedArray()+    }++    companion object {+        const val EXTRA_OPEN_PICKER = "open_picker"+    } }
watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.ktindex 354c3bb754..46cdd0f261 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt@@ -15,6 +15,7 @@ import android.bluetooth.le.BluetoothLeAdvertiser import android.content.Context import android.os.ParcelUuid import android.util.Log+import com.vayunmathur.watch.shared.ble.BleConstants import com.vayunmathur.watch.watch.data.SensorDao import com.vayunmathur.watch.watch.data.SensorRecord import kotlinx.coroutines.CoroutineScope@@ -34,6 +35,7 @@ private data class WireRecord(     val value: Double,     val delta: Double,     val stationary: Boolean = false,+    val session: String? = null, )  @Serializable@@ -230,7 +232,7 @@ class GattServerManager(         scope.launch(Dispatchers.IO) {             val rows: List<SensorRecord> = dao.getAll()             val batch = WireBatch(rows.map {-                WireRecord(it.id, it.type.name, it.timestamp, it.value, it.delta, it.stationary)+                WireRecord(it.id, it.type.name, it.timestamp, it.value, it.delta, it.stationary, it.session)             })             pendingAck[device.address] = rows.map { it.id } 
watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.ktindex c577ea8a56..c7b08bda6e 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt@@ -9,6 +9,8 @@ import androidx.room.PrimaryKey import androidx.room.Query import androidx.room.Room import androidx.room.RoomDatabase+import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabase import kotlinx.coroutines.flow.Flow  enum class MetricType {@@ -20,6 +22,9 @@ enum class MetricType {     Floors,     Elevation,     Calories,+    // An active workout captured via Health Services ExerciseClient. The whole+    // session summary rides in [SensorRecord.session] as a JSON blob.+    ExerciseSession, }  @Entity@@ -35,6 +40,9 @@ data class SensorRecord(     val delta: Double = 0.0,     // For HeartRate: whether the wearer was stationary when sampled.     val stationary: Boolean = false,+    // For ExerciseSession: the serialized ExerciseSessionSummary JSON. Null for+    // every scalar metric type.+    val session: String? = null, )  @Dao@@ -55,7 +63,15 @@ interface SensorDao {     suspend fun deleteByIds(ids: List<Long>) } -@Database(entities = [SensorRecord::class], version = 1, exportSchema = false)+// Adds the nullable session column. Non-destructive so unsent rows survive the+// upgrade; existing rows get session = NULL.+val MIGRATION_1_2 = object : Migration(1, 2) {+    override fun migrate(db: SupportSQLiteDatabase) {+        db.execSQL("ALTER TABLE SensorRecord ADD COLUMN session TEXT DEFAULT NULL")+    }+}++@Database(entities = [SensorRecord::class], version = 2, exportSchema = false) abstract class SensorDatabase : RoomDatabase() {     abstract fun sensorDao(): SensorDao @@ -69,7 +85,7 @@ abstract class SensorDatabase : RoomDatabase() {                     context.applicationContext,                     SensorDatabase::class.java,                     "sensor.db",-                ).build().also { INSTANCE = it }+                ).addMigrations(MIGRATION_1_2).build().also { INSTANCE = it }             }     } }
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.ktnew file mode 100644index 0000000000..f7695700c9--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/ExerciseController.kt@@ -0,0 +1,361 @@+package com.vayunmathur.watch.watch.service++import android.content.Context+import android.util.Log+import androidx.health.services.client.ExerciseClient+import androidx.health.services.client.ExerciseUpdateCallback+import androidx.health.services.client.HealthServices+import androidx.health.services.client.data.Availability+import androidx.health.services.client.data.DataPointContainer+import androidx.health.services.client.data.DataType+import androidx.health.services.client.data.ExerciseConfig+import androidx.health.services.client.data.ExerciseLapSummary+import androidx.health.services.client.data.ExerciseState+import androidx.health.services.client.data.ExerciseTrackedStatus+import androidx.health.services.client.data.ExerciseUpdate+import androidx.health.services.client.data.LocationData+import androidx.health.services.client.data.WarmUpConfig+import com.vayunmathur.watch.shared.data.ExerciseSessionSummary+import com.vayunmathur.watch.shared.data.LapMarker+import com.vayunmathur.watch.shared.data.RepSegment+import com.vayunmathur.watch.shared.data.RoutePoint+import com.vayunmathur.watch.shared.data.SpeedSample+import com.vayunmathur.watch.watch.data.MetricType+import com.vayunmathur.watch.watch.data.SensorDao+import com.vayunmathur.watch.watch.data.SensorRecord+import com.vayunmathur.watch.watch.data.WorkoutType+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import java.util.concurrent.Executor++/**+ * Wraps Health Services' active [ExerciseClient] to run one workout at a time.+ * Mirrors [HealthServicesCollector]'s future handling (addListener + a direct+ * executor, no kotlinx-coroutines-guava). It capability-gates the requested data+ * types per exercise type, drives the prepare → start → pause/resume → end+ * lifecycle, pushes live values out through callbacks, and on ENDED builds an+ * [ExerciseSessionSummary] and persists it as a single [SensorRecord] for the+ * BLE pipeline to ship.+ */+class ExerciseController(+    context: Context,+    private val dao: SensorDao,+    private val scope: CoroutineScope,+    // Live callbacks for the UI/Tile, invoked on the direct executor thread.+    private val onState: (ExerciseState) -> Unit,+    private val onMetrics: (LiveMetrics) -> Unit,+    private val onMessage: (String) -> Unit,+) {+    data class LiveMetrics(+        val activeDurationMs: Long = 0,+        val heartRateBpm: Double? = null,+        val calories: Double? = null,+        val distanceMeters: Double? = null,+    )++    private val appContext = context.applicationContext+    private val client: ExerciseClient =+        HealthServices.getClient(appContext).exerciseClient++    private val json = Json { ignoreUnknownKeys = true }+    private val directExecutor = Executor { it.run() }++    @Volatile private var activeWorkout: WorkoutType? = null+    @Volatile private var startedAtMs: Long = 0L++    // Accumulated across updates for the final summary.+    private val routePoints = mutableListOf<RoutePoint>()+    @Volatile private var lastRouteAtMs = 0L+    @Volatile private var latestActiveDurationMs = 0L+    @Volatile private var latestHr: Double? = null+    @Volatile private var latestCalories: Double? = null+    @Volatile private var latestDistance: Double? = null+    @Volatile private var latestAvgSpeed: Double? = null+    @Volatile private var latestMaxSpeed: Double? = null+    @Volatile private var latestAvgCadence: Double? = null+    @Volatile private var latestVo2Max: Double? = null+    @Volatile private var latestLapCount: Long? = null+    @Volatile private var latestRepCount: Long? = null++    /**+     * Warms up sensors, then starts the workout once we confirm no other app owns+     * an exercise. If our own app already owns an in-progress exercise, we simply+     * re-attach the update callback (orphan recovery) instead of starting again.+     */+    fun start(workout: WorkoutType) {+        val infoFuture = client.getCurrentExerciseInfoAsync()+        infoFuture.addListener({+            val status = try {+                infoFuture.get().exerciseTrackedStatus+            } catch (e: Exception) {+                Log.e(TAG, "getCurrentExerciseInfo failed", e)+                ExerciseTrackedStatus.UNKNOWN+            }+            when (status) {+                ExerciseTrackedStatus.OTHER_APP_IN_PROGRESS -> {+                    onMessage("Another app is tracking a workout")+                }+                ExerciseTrackedStatus.OWNED_EXERCISE_IN_PROGRESS -> {+                    // Recover: rebind to the in-progress session.+                    activeWorkout = workout+                    client.setUpdateCallback(directExecutor, updateCallback)+                }+                else -> beginNewExercise(workout)+            }+        }, directExecutor)+    }++    private fun beginNewExercise(workout: WorkoutType) {+        activeWorkout = workout+        resetAccumulators()+        client.setUpdateCallback(directExecutor, updateCallback)++        val capsFuture = client.getCapabilitiesAsync()+        capsFuture.addListener({+            val supported: Set<DataType<*, *>> = try {+                capsFuture.get().getExerciseTypeCapabilities(workout.healthServicesType)+                    .supportedDataTypes+            } catch (e: Exception) {+                Log.e(TAG, "getCapabilities failed", e)+                emptySet()+            }+            val dataTypes = desiredDataTypes(workout).filter { it in supported }.toSet()+            warmUpThenStart(workout, dataTypes, supported)+        }, directExecutor)+    }++    private fun warmUpThenStart(+        workout: WorkoutType,+        dataTypes: Set<DataType<*, *>>,+        supported: Set<DataType<*, *>>,+    ) {+        // Warm-up only accepts delta (non-aggregate) types.+        val warmUpTypes = dataTypes.filterIsInstance<+            androidx.health.services.client.data.DeltaDataType<*, *>>().toSet()+        if (warmUpTypes.isNotEmpty()) {+            val prepFuture = client.prepareExerciseAsync(+                WarmUpConfig(workout.healthServicesType, warmUpTypes),+            )+            prepFuture.addListener({+                try {+                    prepFuture.get()+                } catch (e: Exception) {+                    Log.w(TAG, "prepareExercise failed; starting anyway", e)+                }+                startExercise(workout, dataTypes, supported)+            }, directExecutor)+        } else {+            startExercise(workout, dataTypes, supported)+        }+    }++    private fun startExercise(+        workout: WorkoutType,+        dataTypes: Set<DataType<*, *>>,+        supported: Set<DataType<*, *>>,+    ) {+        val gps = workout.isGpsBased && DataType.LOCATION in supported+        val config = ExerciseConfig.builder(workout.healthServicesType)+            .setDataTypes(dataTypes)+            .setIsAutoPauseAndResumeEnabled(false)+            .setIsGpsEnabled(gps)+            .build()+        startedAtMs = System.currentTimeMillis()+        val future = client.startExerciseAsync(config)+        future.addListener({+            try {+                future.get()+            } catch (e: Exception) {+                Log.e(TAG, "startExercise failed", e)+                onMessage("Could not start workout")+            }+        }, directExecutor)+    }++    fun pause() = fireAndForget(client.pauseExerciseAsync(), "pause")+    fun resume() = fireAndForget(client.resumeExerciseAsync(), "resume")+    fun stop() = fireAndForget(client.endExerciseAsync(), "end")++    private fun fireAndForget(+        future: com.google.common.util.concurrent.ListenableFuture<Void>,+        op: String,+    ) {+        future.addListener({+            try {+                future.get()+            } catch (e: Exception) {+                Log.e(TAG, "$op failed", e)+            }+        }, directExecutor)+    }++    private val updateCallback = object : ExerciseUpdateCallback {+        override fun onRegistered() {}++        override fun onRegistrationFailed(throwable: Throwable) {+            Log.e(TAG, "update callback registration failed", throwable)+        }++        override fun onExerciseUpdateReceived(update: ExerciseUpdate) {+            val metrics = update.latestMetrics+            captureLive(update, metrics)+            val state = update.exerciseStateInfo.state+            onState(state)+            if (state.isEnded) {+                finishSession(update)+            }+        }++        override fun onLapSummaryReceived(lapSummary: ExerciseLapSummary) {}++        override fun onAvailabilityChanged(dataType: DataType<*, *>, availability: Availability) {}+    }++    private fun captureLive(update: ExerciseUpdate, metrics: DataPointContainer) {+        update.activeDurationCheckpoint?.let {+            latestActiveDurationMs = it.activeDuration.toMillis()+        }+        metrics.getData(DataType.HEART_RATE_BPM).lastOrNull()?.let { latestHr = it.value }+        metrics.getData(DataType.CALORIES_TOTAL)?.let { latestCalories = it.total }+        metrics.getData(DataType.DISTANCE_TOTAL)?.let { latestDistance = it.total }+        metrics.getData(DataType.SPEED_STATS)?.let {+            latestAvgSpeed = it.average+            latestMaxSpeed = it.max+        }+        metrics.getData(DataType.STEPS_PER_MINUTE_STATS)?.let {+            latestAvgCadence = it.average.toDouble()+        }+        metrics.getData(DataType.VO2_MAX_STATS)?.let { latestVo2Max = it.average }+        metrics.getData(DataType.SWIMMING_LAP_COUNT_TOTAL)?.let { latestLapCount = it.total }+        metrics.getData(DataType.REP_COUNT_TOTAL)?.let { latestRepCount = it.total }++        // Throttle route points to at most one every few seconds. Route point+        // timestamps use capture time (near-real-time given the throttle) to+        // avoid resolving the device boot instant for sample-relative durations.+        metrics.getData(DataType.LOCATION).forEach { sample ->+            val now = System.currentTimeMillis()+            if (now - lastRouteAtMs >= ROUTE_MIN_INTERVAL_MS) {+                lastRouteAtMs = now+                val loc: LocationData = sample.value+                routePoints += RoutePoint(+                    lat = loc.latitude,+                    lng = loc.longitude,+                    // Health Services reports Double.MAX_VALUE when altitude is+                    // unavailable (LocationData.ALTITUDE_UNAVAILABLE, whose+                    // companion is internal, so the sentinel is inlined here).+                    altitude = loc.altitude.takeIf { it.isFinite() && it != Double.MAX_VALUE },+                    time = now,+                )+            }+        }++        onMetrics(+            LiveMetrics(+                activeDurationMs = latestActiveDurationMs,+                heartRateBpm = latestHr,+                calories = latestCalories,+                distanceMeters = latestDistance,+            ),+        )+    }++    private fun finishSession(update: ExerciseUpdate) {+        val workout = activeWorkout ?: return+        activeWorkout = null+        val endTime = System.currentTimeMillis()+        val startTime = update.startTime?.toEpochMilli() ?: startedAtMs++        val summary = ExerciseSessionSummary(+            exerciseType = workout.healthServicesType.name,+            startTime = startTime,+            endTime = endTime,+            activeDurationMs = latestActiveDurationMs,+            avgSpeedMps = latestAvgSpeed,+            maxSpeedMps = latestMaxSpeed,+            avgCadenceSpm = latestAvgCadence,+            vo2Max = latestVo2Max,+            route = routePoints.toList().takeIf { it.isNotEmpty() },+            lapCount = latestLapCount,+            segments = buildSegments(workout, startTime, endTime),+            distanceMeters = latestDistance,+            totalCalories = latestCalories,+            avgHr = latestHr,+        )+        persist(summary)+        clearCallback()+    }++    // Rep-based workouts report a running REP_COUNT_TOTAL; we emit it as a single+    // whole-session segment. Fine-grained per-set segmentation is not available+    // from a plain rep counter, so the segment type is UNKNOWN (0).+    private fun buildSegments(workout: WorkoutType, start: Long, end: Long): List<RepSegment>? {+        if (!workout.isRepBased) return null+        val reps = latestRepCount?.takeIf { it > 0 } ?: return null+        return listOf(RepSegment(type = SEGMENT_TYPE_UNKNOWN, reps = reps, start = start, end = end))+    }++    private fun persist(summary: ExerciseSessionSummary) {+        val record = SensorRecord(+            type = MetricType.ExerciseSession,+            timestamp = summary.endTime,+            value = 0.0,+            session = json.encodeToString(summary),+        )+        scope.launch(Dispatchers.IO) {+            try {+                dao.insert(record)+            } catch (e: Exception) {+                Log.e(TAG, "insert session failed", e)+            }+        }+    }++    private fun clearCallback() {+        try {+            client.clearUpdateCallbackAsync(updateCallback)+        } catch (e: Exception) {+            Log.e(TAG, "clearUpdateCallback failed", e)+        }+    }++    private fun resetAccumulators() {+        routePoints.clear()+        lastRouteAtMs = 0L+        latestActiveDurationMs = 0L+        latestHr = null+        latestCalories = null+        latestDistance = null+        latestAvgSpeed = null+        latestMaxSpeed = null+        latestAvgCadence = null+        latestVo2Max = null+        latestLapCount = null+        latestRepCount = null+    }++    private fun desiredDataTypes(workout: WorkoutType): Set<DataType<*, *>> {+        val types = mutableSetOf<DataType<*, *>>(+            DataType.HEART_RATE_BPM,+            DataType.CALORIES_TOTAL,+            DataType.DISTANCE_TOTAL,+            DataType.SPEED,+            DataType.SPEED_STATS,+            DataType.STEPS_PER_MINUTE_STATS,+            DataType.VO2_MAX_STATS,+        )+        if (workout.isGpsBased) types += DataType.LOCATION+        if (workout.isSwimming) types += DataType.SWIMMING_LAP_COUNT_TOTAL+        if (workout.isRepBased) types += DataType.REP_COUNT_TOTAL+        return types+    }++    companion object {+        private const val TAG = "ExerciseController"+        private const val ROUTE_MIN_INTERVAL_MS = 3_000L+        // Health Connect ExerciseSegment.EXERCISE_SEGMENT_TYPE_UNKNOWN.+        private const val SEGMENT_TYPE_UNKNOWN = 0+    }+}
watch/watch/src/main/res/values/strings.xml
diff --git a/watch/watch/src/main/res/values/strings.xml b/watch/watch/src/main/res/values/strings.xmlindex e9bb044d5a..8fdb8532f3 100644--- a/watch/watch/src/main/res/values/strings.xml+++ b/watch/watch/src/main/res/values/strings.xml@@ -11,4 +11,22 @@     <string name="notification_channel_name">Sensor Collection</string>     <string name="notification_title">Collecting health data</string>     <string name="notification_text">Reading sensors and serving over BLE</string>++    <!-- Exercise session -->+    <string name="exercise_notification_channel">Workout Tracking</string>+    <string name="exercise_notification_title">Workout in progress</string>+    <string name="exercise_notification_text">Tracking your active exercise session</string>+    <string name="exercise_title">Workout</string>+    <string name="exercise_pick_type">Pick a workout</string>+    <string name="exercise_start_workout">Start workout</string>+    <string name="exercise_pause">Pause</string>+    <string name="exercise_resume">Resume</string>+    <string name="exercise_stop">Stop</string>+    <string name="exercise_back">Back</string>+    <string name="exercise_state">State: %1$s</string>+    <string name="exercise_duration">Duration: %1$s</string>+    <string name="exercise_hr">HR: %1$s</string>+    <string name="exercise_calories">Calories: %1$s</string>+    <string name="exercise_distance">Distance: %1$s m</string>+    <string name="exercise_dash">--</string> </resources>
watch/watch/src/main/res/values/themes.xml
diff --git a/watch/watch/src/main/res/values/themes.xml b/watch/watch/src/main/res/values/themes.xmlindex 33bc3e6ca0..1e692cfa39 100644--- a/watch/watch/src/main/res/values/themes.xml+++ b/watch/watch/src/main/res/values/themes.xml@@ -1,4 +1,11 @@ <?xml version="1.0" encoding="utf-8"?> <resources>     <style name="AppTheme" parent="@android:style/Theme.DeviceDefault" />+    <style name="Theme.NoDisplay" parent="@android:style/Theme.Translucent.NoTitleBar">+        <item name="android:windowBackground">@android:color/transparent</item>+        <item name="android:windowIsTranslucent">true</item>+        <item name="android:windowContentOverlay">@null</item>+        <item name="android:windowAnimationStyle">@null</item>+        <item name="android:backgroundDimEnabled">false</item>+    </style> </resources>