watch: derive expanded health metrics on phone and write to Health Connect
- Commit
b4e335178e59cbd1dd67f1ba88bcf49c9368f71a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-06 02:21 UTC (5 months ago)
- Parents
9e5182e
Diff
watch/phone/build.gradle.kts
diff --git a/watch/phone/build.gradle.kts b/watch/phone/build.gradle.ktsindex 76ea340d34..c473231191 100644--- a/watch/phone/build.gradle.kts+++ b/watch/phone/build.gradle.kts@@ -13,4 +13,5 @@ android { dependencies { 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 b78040a015..3cf6eb127f 100644--- a/watch/phone/src/main/AndroidManifest.xml+++ b/watch/phone/src/main/AndroidManifest.xml@@ -15,6 +15,15 @@ <!-- Health Connect --> <uses-permission android:name="android.permission.health.WRITE_HEART_RATE" /> <uses-permission android:name="android.permission.health.WRITE_STEPS" />+ <uses-permission android:name="android.permission.health.WRITE_DISTANCE" />+ <uses-permission android:name="android.permission.health.WRITE_FLOORS_CLIMBED" />+ <uses-permission android:name="android.permission.health.WRITE_ELEVATION_GAINED" />+ <uses-permission android:name="android.permission.health.WRITE_ACTIVE_CALORIES_BURNED" />+ <uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE" />+ <uses-permission android:name="android.permission.health.WRITE_SLEEP" />+ <uses-permission android:name="android.permission.health.READ_WEIGHT" />+ <uses-permission android:name="android.permission.health.WRITE_WEIGHT" />+ <uses-permission android:name="android.permission.health.READ_HEIGHT" /> <queries> <package android:name="com.google.android.apps.healthdata" />
watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.ktindex 49a22f979a..953afdd157 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt@@ -13,16 +13,20 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding+import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text+import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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.Alignment import androidx.compose.ui.Modifier@@ -32,6 +36,7 @@ import androidx.health.connect.client.PermissionController import com.vayunmathur.watch.phone.ble.ConnectionState import com.vayunmathur.watch.phone.health.HealthConnectManager import com.vayunmathur.watch.phone.sync.SyncForegroundService+import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { @@ -50,6 +55,7 @@ class MainActivity : ComponentActivity() { private fun SyncScreen(modifier: Modifier) { val context = this val health = remember { HealthConnectManager(context) }+ val coroutineScope = rememberCoroutineScope() val connection by SyncForegroundService.connectionStateFlow.collectAsState() val synced by SyncForegroundService.syncedCountFlow.collectAsState()@@ -57,6 +63,7 @@ class MainActivity : ComponentActivity() { var hasBlePerms by remember { mutableStateOf(false) } var hasHcPerms by remember { mutableStateOf(false) } var hcAvailable by remember { mutableStateOf(true) }+ var needsWeight by remember { mutableStateOf(false) } val blePermsLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestMultiplePermissions(),@@ -76,6 +83,24 @@ class MainActivity : ComponentActivity() { if (hcAvailable) hasHcPerms = health.hasAllPermissions() } + // Once HC permissions are granted, prompt for weight if none is recorded.+ LaunchedEffect(hasHcPerms) {+ if (hasHcPerms) {+ needsWeight = health.latestWeightKg() == null+ }+ }++ if (needsWeight) {+ WeightPromptDialog(+ onSubmit = { kg ->+ coroutineScope.launch {+ health.writeWeight(kg)+ needsWeight = false+ }+ },+ )+ }+ Column( modifier = modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,@@ -106,6 +131,35 @@ class MainActivity : ComponentActivity() { } } + @Composable+ private fun WeightPromptDialog(onSubmit: (Double) -> Unit) {+ var text by remember { mutableStateOf("") }+ val kg = text.toDoubleOrNull()+ AlertDialog(+ onDismissRequest = {},+ title = { Text(stringResource(R.string.weight_prompt_title)) },+ text = {+ Column {+ Text(stringResource(R.string.weight_prompt_body))+ OutlinedTextField(+ value = text,+ onValueChange = { text = it },+ label = { Text(stringResource(R.string.weight_prompt_hint)) },+ singleLine = true,+ )+ }+ },+ confirmButton = {+ TextButton(+ onClick = { kg?.let(onSubmit) },+ enabled = kg != null && kg > 0.0,+ ) {+ Text(stringResource(R.string.weight_prompt_save))+ }+ },+ )+ }+ @Composable private fun ConnectionState.label(): String = when (this) { ConnectionState.Disconnected -> stringResource(R.string.state_disconnected)
watch/phone/src/main/java/com/vayunmathur/watch/phone/data/ReceivedRecord.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/ReceivedRecord.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/ReceivedRecord.ktnew file mode 100644index 0000000000..b4d837742f--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/ReceivedRecord.kt@@ -0,0 +1,75 @@+package com.vayunmathur.watch.phone.data++import android.content.Context+import androidx.room.Dao+import androidx.room.Database+import androidx.room.Entity+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.PrimaryKey+import androidx.room.Query+import androidx.room.Room+import androidx.room.RoomDatabase++/**+ * Phone-side rolling buffer of raw records received from the watch. The watch+ * deletes rows after the phone ACKs, so the phone keeps its own copy here to+ * recompute daily/overnight derivations as more data streams in.+ */+@Entity+data class ReceivedRecord(+ // Composite of the watch row id and its type: watch ids restart on reinstall,+ // so pairing with type keeps the buffer key stable and de-duplicated.+ @PrimaryKey val key: String,+ val type: String,+ val timestamp: Long,+ val value: Double,+ val delta: Double,+ val stationary: Boolean,+)++@Dao+interface ReceivedDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun insertAll(records: List<ReceivedRecord>)++ @Query(+ "SELECT * FROM ReceivedRecord WHERE type = :type AND timestamp >= :startMs " ++ "AND timestamp < :endMs ORDER BY timestamp ASC",+ )+ suspend fun getByTypeInRange(type: String, startMs: Long, endMs: Long): List<ReceivedRecord>++ @Query("SELECT * FROM ReceivedRecord WHERE type = :type ORDER BY timestamp ASC")+ suspend fun getByType(type: String): List<ReceivedRecord>++ @Query(+ "SELECT * FROM ReceivedRecord WHERE timestamp >= :startMs AND timestamp < :endMs " ++ "ORDER BY timestamp ASC",+ )+ suspend fun getInRange(startMs: Long, endMs: Long): List<ReceivedRecord>++ @Query("SELECT MIN(timestamp) FROM ReceivedRecord")+ suspend fun earliestTimestamp(): Long?++ @Query("DELETE FROM ReceivedRecord WHERE timestamp < :cutoffMs")+ suspend fun deleteOlderThan(cutoffMs: Long)+}++@Database(entities = [ReceivedRecord::class], version = 1, exportSchema = false)+abstract class ReceivedDatabase : RoomDatabase() {+ abstract fun receivedDao(): ReceivedDao++ companion object {+ @Volatile+ private var INSTANCE: ReceivedDatabase? = null++ fun get(context: Context): ReceivedDatabase =+ INSTANCE ?: synchronized(this) {+ INSTANCE ?: Room.databaseBuilder(+ context.applicationContext,+ ReceivedDatabase::class.java,+ "received.db",+ ).build().also { INSTANCE = it }+ }+ }+}
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 4ccf35d3a1..acd950c827 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@@ -4,9 +4,21 @@ import android.content.Context import android.util.Log import androidx.health.connect.client.HealthConnectClient import androidx.health.connect.client.permission.HealthPermission+import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord+import androidx.health.connect.client.records.DistanceRecord+import androidx.health.connect.client.records.ElevationGainedRecord+import androidx.health.connect.client.records.FloorsClimbedRecord import androidx.health.connect.client.records.HeartRateRecord+import androidx.health.connect.client.records.HeightRecord+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.StepsRecord+import androidx.health.connect.client.records.WeightRecord import androidx.health.connect.client.records.metadata.Metadata+import androidx.health.connect.client.request.ReadRecordsRequest+import androidx.health.connect.client.time.TimeRangeFilter+import androidx.health.connect.client.units.Mass import com.vayunmathur.watch.phone.data.WatchRecord import java.time.Instant import java.time.ZoneId@@ -20,6 +32,15 @@ class HealthConnectManager(private val context: Context) { val permissions: Set<String> = setOf( HealthPermission.getWritePermission(HeartRateRecord::class), HealthPermission.getWritePermission(StepsRecord::class),+ HealthPermission.getWritePermission(DistanceRecord::class),+ HealthPermission.getWritePermission(FloorsClimbedRecord::class),+ HealthPermission.getWritePermission(ElevationGainedRecord::class),+ HealthPermission.getWritePermission(ActiveCaloriesBurnedRecord::class),+ HealthPermission.getWritePermission(RestingHeartRateRecord::class),+ HealthPermission.getWritePermission(SleepSessionRecord::class),+ HealthPermission.getReadPermission(WeightRecord::class),+ HealthPermission.getWritePermission(WeightRecord::class),+ HealthPermission.getReadPermission(HeightRecord::class), ) fun sdkStatus(): Int = HealthConnectClient.getSdkStatus(context)@@ -75,6 +96,66 @@ class HealthConnectManager(private val context: Context) { } } + /** Batch-inserts derivation output; clientRecordIds make this idempotent. */+ suspend fun insertDerived(records: List<Record>) {+ if (records.isEmpty()) return+ try {+ client().insertRecords(records)+ } catch (e: Exception) {+ Log.e(TAG, "insertDerived failed", e)+ }+ }++ /** Most recent body weight in kilograms, or null if none recorded. */+ suspend fun latestWeightKg(): Double? = try {+ client().readRecords(+ ReadRecordsRequest(+ recordType = WeightRecord::class,+ timeRangeFilter = TimeRangeFilter.before(Instant.now()),+ ascendingOrder = false,+ pageSize = 1,+ ),+ ).records.firstOrNull()?.weight?.inKilograms+ } catch (e: Exception) {+ Log.e(TAG, "latestWeightKg failed", e)+ null+ }++ /** Most recent body height in meters, or null if none recorded. */+ suspend fun latestHeightMeters(): Double? = try {+ client().readRecords(+ ReadRecordsRequest(+ recordType = HeightRecord::class,+ timeRangeFilter = TimeRangeFilter.before(Instant.now()),+ ascendingOrder = false,+ pageSize = 1,+ ),+ ).records.firstOrNull()?.height?.inMeters+ } catch (e: Exception) {+ Log.e(TAG, "latestHeightMeters failed", e)+ null+ }++ suspend fun writeWeight(kg: Double) {+ if (kg <= 0.0) return+ val time = Instant.now()+ val offset = ZoneId.systemDefault().rules.getOffset(time)+ try {+ client().insertRecords(+ listOf(+ WeightRecord(+ time = time,+ zoneOffset = offset,+ weight = Mass.kilograms(kg),+ metadata = Metadata.manualEntry(),+ ),+ ),+ )+ } catch (e: Exception) {+ Log.e(TAG, "writeWeight failed", e)+ }+ }+ companion object { private const val TAG = "HealthConnectManager" private const val STEP_WINDOW_SECONDS = 60L
watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthDerivations.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthDerivations.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthDerivations.ktnew file mode 100644index 0000000000..f949638856--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthDerivations.kt@@ -0,0 +1,255 @@+package com.vayunmathur.watch.phone.health++import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord+import androidx.health.connect.client.records.DistanceRecord+import androidx.health.connect.client.records.ElevationGainedRecord+import androidx.health.connect.client.records.FloorsClimbedRecord+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.metadata.Metadata+import androidx.health.connect.client.units.Energy+import androidx.health.connect.client.units.Length+import com.vayunmathur.watch.phone.data.ReceivedRecord+import java.time.Instant+import java.time.LocalDate+import java.time.LocalTime+import java.time.ZoneId+import kotlin.math.pow++/**+ * Pure, side-effect-free derivations run over the phone-side record buffer.+ *+ * Everything here is heuristic/approximate by design: the watch only streams raw+ * HR, steps, barometric pressure and coarse motion state, so resting HR, active+ * calories, floors/elevation and sleep are all estimates. All outputs carry a+ * day-keyed clientRecordId so recomputing on later syncs upserts instead of+ * duplicating in Health Connect.+ */+class HealthDerivations(+ private val zone: ZoneId = ZoneId.systemDefault(),+) {++ /**+ * @param records the full buffered window of received raw records.+ * @param weightKg body weight for the calorie estimate, or null if unknown.+ * @param heightMeters body height for the stride estimate, or null.+ */+ fun derive(+ records: List<ReceivedRecord>,+ weightKg: Double?,+ heightMeters: Double?,+ ): List<Record> {+ if (records.isEmpty()) return emptyList()+ val out = mutableListOf<Record>()++ val byType = records.groupBy { it.type }+ val hr = byType["HeartRate"].orEmpty().sortedBy { it.timestamp }+ val steps = byType["Steps"].orEmpty().sortedBy { it.timestamp }+ val pressure = byType["Pressure"].orEmpty().sortedBy { it.timestamp }++ out += distanceRecords(steps, heightMeters)+ out += elevationAndFloors(pressure)+ out += restingHeartRate(hr)+ out += activeCalories(hr, weightKg)+ out += sleepSessions(hr)+ return out+ }++ // Distance = Σ step deltas × stride, summed per calendar day.+ private fun distanceRecords(steps: List<ReceivedRecord>, heightMeters: Double?): List<Record> {+ val stride = heightMeters?.let { it * STRIDE_HEIGHT_FACTOR } ?: DEFAULT_STRIDE_METERS+ return steps.groupBy { dateOf(it.timestamp) }.mapNotNull { (day, rows) ->+ val meters = rows.sumOf { it.delta } * stride+ if (meters <= 0.0) return@mapNotNull null+ val (start, end) = dayBounds(day, rows)+ DistanceRecord(+ startTime = start,+ startZoneOffset = offset(start),+ endTime = end,+ endZoneOffset = offset(end),+ distance = Length.meters(meters),+ metadata = Metadata.manualEntry(clientRecordId = "distance-$day"),+ )+ }+ }++ // Consecutive pressure readings -> altitude deltas; net positive gain per day.+ private fun elevationAndFloors(pressure: List<ReceivedRecord>): List<Record> {+ if (pressure.size < 2) return emptyList()+ val gainByDay = mutableMapOf<LocalDate, Double>()+ for (i in 1 until pressure.size) {+ val prev = pressure[i - 1]+ val cur = pressure[i]+ val delta = altitudeMeters(cur.value) - altitudeMeters(prev.value)+ if (delta > ELEVATION_NOISE_METERS) {+ val day = dateOf(cur.timestamp)+ gainByDay[day] = (gainByDay[day] ?: 0.0) + delta+ }+ }+ val out = mutableListOf<Record>()+ for ((day, gain) in gainByDay) {+ if (gain <= 0.0) continue+ val rows = pressure.filter { dateOf(it.timestamp) == day }+ val (start, end) = dayBounds(day, rows)+ out += ElevationGainedRecord(+ startTime = start,+ startZoneOffset = offset(start),+ endTime = end,+ endZoneOffset = offset(end),+ elevation = Length.meters(gain),+ metadata = Metadata.manualEntry(clientRecordId = "elevation-$day"),+ )+ out += FloorsClimbedRecord(+ startTime = start,+ startZoneOffset = offset(start),+ endTime = end,+ endZoneOffset = offset(end),+ floors = gain / METERS_PER_FLOOR,+ metadata = Metadata.manualEntry(clientRecordId = "floors-$day"),+ )+ }+ return out+ }++ // Resting HR = low-quantile of stationary HR readings per day.+ private fun restingHeartRate(hr: List<ReceivedRecord>): List<Record> {+ return hr.filter { it.stationary && it.value > 0.0 }+ .groupBy { dateOf(it.timestamp) }+ .mapNotNull { (day, rows) ->+ if (rows.size < MIN_RESTING_SAMPLES) return@mapNotNull null+ val sorted = rows.map { it.value }.sorted()+ val idx = ((sorted.size - 1) * RESTING_QUANTILE).toInt()+ val bpm = sorted[idx].toLong()+ if (bpm <= 0L) return@mapNotNull null+ val time = Instant.ofEpochMilli(rows.minOf { it.timestamp })+ RestingHeartRateRecord(+ time = time,+ zoneOffset = offset(time),+ beatsPerMinute = bpm,+ metadata = Metadata.manualEntry(clientRecordId = "resting-$day"),+ )+ }+ }++ // Active calories via a Keytel-style HR estimate, summed per day.+ private fun activeCalories(hr: List<ReceivedRecord>, weightKg: Double?): List<Record> {+ if (weightKg == null || weightKg <= 0.0) return emptyList()+ val kcalByDay = mutableMapOf<LocalDate, Double>()+ for (i in 1 until hr.size) {+ val prev = hr[i - 1]+ val cur = hr[i]+ val minutes = (cur.timestamp - prev.timestamp) / 60_000.0+ if (minutes <= 0.0 || minutes > MAX_SAMPLE_GAP_MIN) continue+ val perMin = keytelKcalPerMin(cur.value, weightKg)+ if (perMin <= 0.0) continue+ val day = dateOf(cur.timestamp)+ kcalByDay[day] = (kcalByDay[day] ?: 0.0) + perMin * minutes+ }+ return kcalByDay.mapNotNull { (day, kcal) ->+ if (kcal <= 0.0) return@mapNotNull null+ val rows = hr.filter { dateOf(it.timestamp) == day }+ val (start, end) = dayBounds(day, rows)+ ActiveCaloriesBurnedRecord(+ startTime = start,+ startZoneOffset = offset(start),+ endTime = end,+ endZoneOffset = offset(end),+ energy = Energy.kilocalories(kcal),+ metadata = Metadata.manualEntry(clientRecordId = "calories-$day"),+ )+ }+ }++ // Sleep = contiguous night-time spans of stationary + low HR, >= min duration.+ private fun sleepSessions(hr: List<ReceivedRecord>): List<Record> {+ val nightly = hr.filter {+ it.stationary && it.value in 1.0..SLEEP_HR_THRESHOLD && isNightTime(it.timestamp)+ }.sortedBy { it.timestamp }+ if (nightly.isEmpty()) return emptyList()++ val out = mutableListOf<Record>()+ var runStart = nightly.first()+ var prev = nightly.first()+ fun flush(last: ReceivedRecord) {+ val durationMs = last.timestamp - runStart.timestamp+ if (durationMs < MIN_SLEEP_DURATION_MS) return+ val start = Instant.ofEpochMilli(runStart.timestamp)+ val end = Instant.ofEpochMilli(last.timestamp)+ // Key by the wake date so a single overnight sleep upserts on later syncs.+ val day = dateOf(last.timestamp)+ out += SleepSessionRecord(+ startTime = start,+ startZoneOffset = offset(start),+ endTime = end,+ endZoneOffset = offset(end),+ stages = listOf(+ SleepSessionRecord.Stage(+ startTime = start,+ endTime = end,+ stage = SleepSessionRecord.STAGE_TYPE_SLEEPING,+ ),+ ),+ metadata = Metadata.manualEntry(clientRecordId = "sleep-$day"),+ )+ }+ for (i in 1 until nightly.size) {+ val cur = nightly[i]+ if (cur.timestamp - prev.timestamp > SLEEP_GAP_MS) {+ flush(prev)+ runStart = cur+ }+ prev = cur+ }+ flush(prev)+ return out+ }++ // --- helpers ---++ private fun keytelKcalPerMin(bpm: Double, weightKg: Double): Double {+ // Keytel et al. (2005), sex/age-agnostic simplification with default age.+ val kcal = (-55.0969 + 0.6309 * bpm + 0.1988 * weightKg + 0.2017 * DEFAULT_AGE) / 4.184+ return kcal.coerceAtLeast(0.0)+ }++ // Standard barometric (hypsometric) altitude from station pressure in hPa.+ private fun altitudeMeters(hpa: Double): Double =+ 44_330.0 * (1.0 - (hpa / SEA_LEVEL_HPA).pow(0.190_294))++ private fun dateOf(ms: Long): LocalDate =+ Instant.ofEpochMilli(ms).atZone(zone).toLocalDate()++ private fun offset(instant: Instant) = zone.rules.getOffset(instant)++ // Span the actual first..last row of the day (clamped so end > start).+ private fun dayBounds(day: LocalDate, rows: List<ReceivedRecord>): Pair<Instant, Instant> {+ val start = Instant.ofEpochMilli(rows.minOf { it.timestamp })+ var end = Instant.ofEpochMilli(rows.maxOf { it.timestamp })+ if (!end.isAfter(start)) end = start.plusSeconds(1)+ return start to end+ }++ private fun isNightTime(ms: Long): Boolean {+ val t = Instant.ofEpochMilli(ms).atZone(zone).toLocalTime()+ // Overnight window wraps midnight: [20:00, 24:00) ∪ [00:00, 10:00).+ return t >= NIGHT_START || t < NIGHT_END+ }++ companion object {+ private const val STRIDE_HEIGHT_FACTOR = 0.415+ private const val DEFAULT_STRIDE_METERS = 0.762+ private const val SEA_LEVEL_HPA = 1_013.25+ private const val METERS_PER_FLOOR = 3.0+ private const val ELEVATION_NOISE_METERS = 0.5+ private const val RESTING_QUANTILE = 0.05+ private const val MIN_RESTING_SAMPLES = 3+ private const val DEFAULT_AGE = 30.0+ private const val MAX_SAMPLE_GAP_MIN = 5.0+ private const val SLEEP_HR_THRESHOLD = 60.0+ private const val MIN_SLEEP_DURATION_MS = 3 * 60 * 60 * 1000L+ private const val SLEEP_GAP_MS = 30 * 60 * 1000L+ private val NIGHT_START: LocalTime = LocalTime.of(20, 0)+ private val NIGHT_END: LocalTime = LocalTime.of(10, 0)+ }+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.ktindex a7103ce739..928bb04484 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt@@ -10,7 +10,11 @@ import android.os.IBinder import com.vayunmathur.watch.phone.R import com.vayunmathur.watch.phone.ble.ConnectionState import com.vayunmathur.watch.phone.ble.GattClientManager+import com.vayunmathur.watch.phone.data.ReceivedDatabase+import com.vayunmathur.watch.phone.data.ReceivedRecord+import com.vayunmathur.watch.phone.data.WatchRecord import com.vayunmathur.watch.phone.health.HealthConnectManager+import com.vayunmathur.watch.phone.health.HealthDerivations import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob@@ -30,11 +34,18 @@ class SyncForegroundService : Service() { private lateinit var client: GattClientManager private lateinit var health: HealthConnectManager+ private lateinit var buffer: ReceivedDatabase+ private val derivations = HealthDerivations()++ // Cached body metrics from Health Connect, refreshed on each batch.+ @Volatile private var weightKg: Double? = null+ @Volatile private var heightMeters: Double? = null override fun onCreate() { super.onCreate() client = GattClientManager(this) health = HealthConnectManager(this)+ buffer = ReceivedDatabase.get(this) scope.launch { client.state.collect { state ->@@ -48,12 +59,44 @@ class SyncForegroundService : Service() { scope.launch { client.batches.collect { records ->- health.insert(records)+ processBatch(records) syncedCount.value += records.size } } } + private suspend fun processBatch(records: List<WatchRecord>) {+ // 1. Write raw HR/Steps directly (existing behavior).+ health.insert(records)++ // 2. Persist the batch into the rolling phone-side buffer.+ buffer.receivedDao().insertAll(+ records.map {+ ReceivedRecord(+ key = "${it.type}-${it.id}",+ type = it.type,+ timestamp = it.timestamp,+ value = it.value,+ delta = it.delta,+ stationary = it.stationary,+ )+ },+ )++ // 3. Refresh cached body metrics for the estimators.+ weightKg = health.latestWeightKg() ?: weightKg+ heightMeters = health.latestHeightMeters() ?: heightMeters++ // 4. Run derivations over the buffered window and upsert into HC.+ val cutoff = System.currentTimeMillis() - BUFFER_WINDOW_MS+ val buffered = buffer.receivedDao().getInRange(cutoff, Long.MAX_VALUE)+ val derived = derivations.derive(buffered, weightKg, heightMeters)+ health.insertDerived(derived)++ // 5. Prune buffer rows outside the rolling window.+ buffer.receivedDao().deleteOlderThan(cutoff)+ }+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startForeground(NOTIFICATION_ID, buildNotification()) client.startScan()@@ -88,6 +131,8 @@ class SyncForegroundService : Service() { companion object { private const val CHANNEL_ID = "watch_sync" private const val NOTIFICATION_ID = 1+ // Rolling buffer window (~3 days) used for daily/overnight derivations.+ private const val BUFFER_WINDOW_MS = 3L * 24 * 60 * 60 * 1000 val connectionState = MutableStateFlow(ConnectionState.Disconnected) val syncedCount = MutableStateFlow(0)
watch/phone/src/main/res/values/strings.xml
diff --git a/watch/phone/src/main/res/values/strings.xml b/watch/phone/src/main/res/values/strings.xmlindex 7cee3744a4..51cec476d7 100644--- a/watch/phone/src/main/res/values/strings.xml+++ b/watch/phone/src/main/res/values/strings.xml@@ -13,6 +13,10 @@ <string name="state_connected">Connected</string> <string name="rationale_title">Health Connect Permissions</string> <string name="rationale_body">This app writes heart rate and step data collected from your watch into Health Connect.</string>+ <string name="weight_prompt_title">Enter your weight</string>+ <string name="weight_prompt_body">Your weight is used to estimate active calories from your watch data. It is saved to Health Connect.</string>+ <string name="weight_prompt_hint">Weight (kg)</string>+ <string name="weight_prompt_save">Save</string> <string name="notification_channel_name">Watch Sync</string> <string name="notification_title">Syncing watch health data</string> <string name="notification_text">Maintaining BLE link and writing to Health Connect</string>