Modern Apps git

← Modern-Apps.git

health: sync to local db first

Commit
74d509796e3d7534459c5d666db88a1905a09be5
Author
Vayun Mathur <[email protected]>
When
2026-02-11 06:59 UTC (9 months ago)
Parents
60f51d9

Diff

health/build.gradle.kts
diff --git a/health/build.gradle.kts b/health/build.gradle.ktsindex 13d4190f4d..aa23121dee 100644--- a/health/build.gradle.kts+++ b/health/build.gradle.kts@@ -17,6 +17,7 @@ dependencies {     // room     implementation(libs.androidx.room.runtime)     implementation(libs.androidx.room.ktx)+    implementation(libs.androidx.work.runtime.ktx)     ksp(libs.androidx.room.compiler)      // Navigation 3
health/src/main/java/com/vayunmathur/health/HealthAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/HealthAPI.kt b/health/src/main/java/com/vayunmathur/health/HealthAPI.ktindex 367f69be49..490493a634 100644--- a/health/src/main/java/com/vayunmathur/health/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/HealthAPI.kt@@ -2,103 +2,108 @@ package com.vayunmathur.health  import android.content.Context import android.content.SharedPreferences+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember import androidx.health.connect.client.HealthConnectClient import androidx.health.connect.client.aggregate.AggregateMetric import androidx.health.connect.client.aggregate.AggregationResult import androidx.health.connect.client.aggregate.AggregationResultGroupedByDuration import androidx.health.connect.client.aggregate.AggregationResultGroupedByPeriod import androidx.health.connect.client.feature.ExperimentalPersonalHealthRecordApi-import androidx.health.connect.client.records.HeartRateRecord import androidx.health.connect.client.records.MedicalResource-import androidx.health.connect.client.records.Record-import androidx.health.connect.client.records.SleepSessionRecord import androidx.health.connect.client.request.AggregateGroupByDurationRequest import androidx.health.connect.client.request.AggregateGroupByPeriodRequest import androidx.health.connect.client.request.AggregateRequest import androidx.health.connect.client.request.ReadMedicalResourcesInitialRequest import androidx.health.connect.client.request.ReadMedicalResourcesPageRequest-import androidx.health.connect.client.request.ReadRecordsRequest import androidx.health.connect.client.time.TimeRangeFilter-import java.time.Duration-import java.time.Instant-import java.time.LocalDate-import java.time.LocalDateTime-import java.time.LocalTime-import java.time.Period-import java.time.temporal.ChronoUnit-import java.time.temporal.TemporalAdjusters+import com.vayunmathur.health.database.HealthDatabase+import com.vayunmathur.health.database.Record+import com.vayunmathur.health.database.RecordType+import kotlinx.coroutines.flow.Flow+import kotlinx.datetime.DateTimeUnit+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atTime+import kotlinx.datetime.plus+import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Duration.Companion.hours+import kotlin.time.Instant  object HealthAPI {     lateinit var healthConnectClient: HealthConnectClient+    lateinit var db: HealthDatabase     lateinit var preferences: SharedPreferences -    fun init(healthConnectClient: HealthConnectClient, context: Context) {+    fun init(healthConnectClient: HealthConnectClient, context: Context, db: HealthDatabase) {         this.healthConnectClient = healthConnectClient+        this.db = db         preferences = context.getSharedPreferences("sync", Context.MODE_PRIVATE)     } -    suspend fun aggregates(timeRangeFilter: TimeRangeFilter, vararg metrics: AggregateMetric<*>): AggregationResult {-        return healthConnectClient.aggregate(-            AggregateRequest(metrics.toSet(), timeRangeFilter)-        )+    @Composable+    fun sumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {+        return remember { db.healthDao().sumInRange(recordType, startTime, endTime) }     } -    suspend inline fun <reified T : Record> lastRecord(): T? {-        val records = healthConnectClient.readRecords(ReadRecordsRequest(T::class, TimeRangeFilter.before(-            Instant.now().plus(1, ChronoUnit.DAYS)), ascendingOrder = false, pageSize = 1))-        return records.records.lastOrNull()+    @Composable+    fun maxInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {+        return remember { db.healthDao().maxInRange(recordType, startTime, endTime) }     } -    fun timeRangeToday(anchor: LocalDate = LocalDate.now()): TimeRangeFilter {-        val startOfDay = anchor.atStartOfDay()-        val endOfDay = anchor.atTime(LocalTime.MAX)-        return TimeRangeFilter.between(startOfDay, endOfDay)+    @Composable+    fun minInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {+        return remember { db.healthDao().minInRange(recordType, startTime, endTime) }     } -    fun timeRangeThisWeek(anchor: LocalDate = LocalDate.now()): TimeRangeFilter {-        val startOfWeek = anchor.with(java.time.DayOfWeek.MONDAY).atStartOfDay()-        val endOfWeek = startOfWeek.plusDays(6).toLocalDate().atTime(LocalTime.MAX)-        return TimeRangeFilter.between(startOfWeek, endOfWeek)+    suspend inline fun lastRecord(recordType: RecordType): Record? {+        return db.healthDao().getLastRecord(recordType)     } -    fun timeRangeThisMonth(anchor: LocalDate = LocalDate.now()): TimeRangeFilter {-        val startOfMonth = anchor.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay()-        val endOfMonth = anchor.with(TemporalAdjusters.lastDayOfMonth()).atTime(LocalTime.MAX)-        return TimeRangeFilter.between(startOfMonth, endOfMonth)+    enum class PeriodType {+        Hourly, Daily, Weekly     } -    fun timeRangeThisYear(anchor: LocalDate = LocalDate.now()): TimeRangeFilter {-        val startOfYear = anchor.with(TemporalAdjusters.firstDayOfYear()).atStartOfDay()-        val endOfYear = anchor.with(TemporalAdjusters.lastDayOfYear()).atTime(LocalTime.MAX)-        return TimeRangeFilter.between(startOfYear, endOfYear)-    }+    suspend fun getListOfSums(+        recordType: RecordType,+        startTime: Instant,+        endTime: Instant,+        period: PeriodType+    ): List<Double> {+        val tz = TimeZone.currentSystemDefault()+        val sums = mutableListOf<Double>() -    suspend fun aggregateByPeriod(-        timeRangeFilter: TimeRangeFilter,-        period: Period,-        metrics: Set<AggregateMetric<*>>-    ): List<AggregationResultGroupedByPeriod> {-        return healthConnectClient.aggregateGroupByPeriod(-            AggregateGroupByPeriodRequest(-                metrics = metrics,-                timeRangeFilter = timeRangeFilter,-                timeRangeSlicer = period-            )-        )-    }+        var currentStart = startTime++        while (currentStart < endTime) {+            val nextStart = when (period) {+                PeriodType.Hourly -> {+                    currentStart.plus(1.hours)+                }+                PeriodType.Daily -> {+                    // Shift to local time, add a day, shift back to Instant+                    val localDateTime = currentStart.toLocalDateTime(tz)+                    val nextLocalDate = localDateTime.date.plus(1, DateTimeUnit.DAY)+                    nextLocalDate.atTime(localDateTime.hour, localDateTime.minute).toInstant(tz)+                }+                PeriodType.Weekly -> {+                    val localDateTime = currentStart.toLocalDateTime(tz)+                    val nextLocalDate = localDateTime.date.plus(1, DateTimeUnit.WEEK)+                    nextLocalDate.atTime(localDateTime.hour, localDateTime.minute).toInstant(tz)+                }+            }++            // Clamp the end range to the requested endTime+            val currentEnd = if (nextStart > endTime) endTime else nextStart++            // Fetch sum from DAO+            val sum = db.healthDao().sumInRangeGet(recordType, currentStart, currentEnd)+            sums.add(sum)++            currentStart = nextStart+        } -    suspend fun aggregateByDuration(-        timeRangeFilter: TimeRangeFilter,-        duration: Duration,-        metrics: Set<AggregateMetric<*>>-    ): List<AggregationResultGroupedByDuration> {-        return healthConnectClient.aggregateGroupByDuration(-            AggregateGroupByDurationRequest(-                metrics = metrics,-                timeRangeFilter = timeRangeFilter,-                timeRangeSlicer = duration-            )-        )+        return sums     }      @OptIn(ExperimentalPersonalHealthRecordApi::class)
health/src/main/java/com/vayunmathur/health/HealthSyncWorker.kt
diff --git a/health/src/main/java/com/vayunmathur/health/HealthSyncWorker.kt b/health/src/main/java/com/vayunmathur/health/HealthSyncWorker.ktnew file mode 100644index 0000000000..842d4660e3--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/HealthSyncWorker.kt@@ -0,0 +1,150 @@+package com.vayunmathur.health++import android.content.Context+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.changes.DeletionChange+import androidx.health.connect.client.changes.UpsertionChange+import androidx.health.connect.client.impl.platform.records.toPlatformRecord+import androidx.health.connect.client.records.HeartRateRecord+import androidx.health.connect.client.records.*+import androidx.health.connect.client.request.ChangesTokenRequest+import androidx.health.connect.client.request.ReadRecordsRequest+import androidx.health.connect.client.time.TimeRangeFilter+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.health.database.HealthDatabase+import com.vayunmathur.health.database.Record+import com.vayunmathur.health.database.RecordType+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.buildDatabase+import java.time.Duration+import java.time.Instant+import java.util.concurrent.TimeUnit++/**+ * Worker that ensures local Room DB is in sync with Health Connect.+ */+class HealthSyncWorker(+    appContext: Context,+    workerParams: WorkerParameters+) : CoroutineWorker(appContext, workerParams) {++    override suspend fun doWork(): Result {+        val healthConnectClient = HealthConnectClient.getOrCreate(applicationContext)+        val db = applicationContext.buildDatabase<HealthDatabase>()+        val ds = DataStoreUtils.getInstance(applicationContext)+        var token = ds.getString("hc_token")+        if (token == null) {+            // 2. If no token exists, initialize one for the data types you care about+            CLASSES.forEach {+                var pageToken: String? = null+                do {+                    val records = healthConnectClient.readRecords(ReadRecordsRequest(it, TimeRangeFilter.after(Instant.EPOCH), pageSize = 5000, pageToken = pageToken))+                    db.healthDao().upsert(records.records.map { it.toRecord() }.flatten())+                    pageToken = records.pageToken+                } while (pageToken != null)+                println("Completed inserting ${it.simpleName}")+            }+            token = healthConnectClient.getChangesToken(+                ChangesTokenRequest(+                    recordTypes = CLASSES+                )+            )+            ds.setString("hc_token", token)+        }+        do {+            val response = healthConnectClient.getChanges(token!!)++            // Handle new/updated records+            val upsertedRecords = response.changes.filterIsInstance<UpsertionChange>().map { it.record }++            val newRecords = upsertedRecords.map {+                it.toRecord()+            }.flatten()+            db.healthDao().upsert(newRecords)+            println("Upserted ${newRecords.size} records")++            // Handle deleted records+            val deletedIds = response.changes.filterIsInstance<DeletionChange>().map { it.recordId }+            db.healthDao().deleteByIds(deletedIds)++            // Update token for the next iteration/sync+            token = response.nextChangesToken+            ds.setString("hc_token", token)++            println("Deleted ${deletedIds.size} records")++        } while (response.hasMore)+        return Result.success()+    }++    companion object {+        fun enqueue(context: Context) {+            val constraints = Constraints.Builder()+                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)+                .build()++            val syncRequest = PeriodicWorkRequestBuilder<HealthSyncWorker>(1, TimeUnit.HOURS)+                .setConstraints(constraints)+                .build()++            val syncRequestNow = OneTimeWorkRequestBuilder<HealthSyncWorker>()+                .setConstraints(constraints)+                .build()++            WorkManager.getInstance(context).enqueueUniquePeriodicWork(+                "HealthSyncWork",+                ExistingPeriodicWorkPolicy.KEEP,+                syncRequest+            )+            WorkManager.getInstance(context).enqueueUniqueWork("HealthSyncWork_now", ExistingWorkPolicy.KEEP, syncRequestNow)+        }+    }+}++fun androidx.health.connect.client.records.Record.toRecord(): List<Record> =+    when (this) {+        // --- Activity ---+        is StepsRecord -> listOf(Record(this.metadata.id, 0, RecordType.Steps, this.startTime, this.endTime, this.count.toDouble()))+        is WheelchairPushesRecord -> listOf(Record(this.metadata.id, 0, RecordType.Wheelchair, this.startTime, this.endTime, this.count.toDouble()))+        is DistanceRecord -> listOf(Record(this.metadata.id, 0, RecordType.Distance, this.startTime, this.endTime, this.distance.inKilometers))+        is TotalCaloriesBurnedRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesTotal, this.startTime, this.endTime, this.energy.inKilocalories))+        is ActiveCaloriesBurnedRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesActive, this.startTime, this.endTime, this.energy.inKilocalories))+        is BasalMetabolicRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesBasal, this.time, this.time, this.basalMetabolicRate.inKilocaloriesPerDay))+        is FloorsClimbedRecord -> listOf(Record(this.metadata.id, 0, RecordType.Floors, this.startTime, this.endTime, this.floors))+        is ElevationGainedRecord -> listOf(Record(this.metadata.id, 0, RecordType.Elevation, this.startTime, this.endTime, this.elevation.inMeters))++        // --- Vitals ---+        is HeartRateRecord -> this.samples.mapIndexed { idx, sample -> Record(this.metadata.id, idx, RecordType.HeartRate, sample.time, sample.time, sample.beatsPerMinute.toDouble()) }+        is RestingHeartRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.RestingHeartRate, this.time, this.time, this.beatsPerMinute.toDouble()))+        is HeartRateVariabilityRmssdRecord -> listOf(Record(this.metadata.id, 0, RecordType.HeartRateVariabilityRmssd, this.time, this.time, this.heartRateVariabilityMillis))+        is RespiratoryRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.RespiratoryRate, this.time, this.time, this.rate))+        is OxygenSaturationRecord -> listOf(Record(this.metadata.id, 0, RecordType.OxygenSaturation, this.time, this.time, this.percentage.value))+        is BloodPressureRecord -> listOf(Record(this.metadata.id, 0, RecordType.BloodPressure, this.time, this.time, this.systolic.inMillimetersOfMercury, this.diastolic.inMillimetersOfMercury))+        is BloodGlucoseRecord -> listOf(Record(this.metadata.id, 0, RecordType.BloodGlucose, this.time, this.time, this.level.inMilligramsPerDeciliter))+        is Vo2MaxRecord -> listOf(Record(this.metadata.id, 0, RecordType.Vo2Max, this.time, this.time, this.vo2MillilitersPerMinuteKilogram))+        is SkinTemperatureRecord -> this.deltas.mapIndexed { idx, delta -> Record(this.metadata.id, idx, RecordType.SkinTemperature, delta.time, delta.time, delta.delta.inCelsius) }++        // --- Body Composthision ---+        is WeightRecord -> listOf(Record(this.metadata.id, 0, RecordType.Weight, this.time, this.time, this.weight.inKilograms))+        is HeightRecord -> listOf(Record(this.metadata.id, 0, RecordType.Height, this.time, this.time, this.height.inMeters))+        is BodyFatRecord -> listOf(Record(this.metadata.id, 0, RecordType.BodyFat, this.time, this.time, this.percentage.value))+        is LeanBodyMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.LeanBodyMass, this.time, this.time, this.mass.inKilograms))+        is BoneMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.BoneMass, this.time, this.time, this.mass.inKilograms))+        is BodyWaterMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.BodyWaterMass, this.time, this.time, this.mass.inKilograms))++        // --- Lifestyle ---+//                    is SleepSessionRecord -> listOf(Record(this.metadata.id, 0, "Sleep", this.startTime, this.endTime, this))+        is MindfulnessSessionRecord -> listOf(Record(this.metadata.id, 0, RecordType.Mindfulness, this.startTime, this.endTime, Duration.between(this.startTime, this.endTime).toMillis().toDouble() / 1000.0 / 60.0))+        is HydrationRecord -> listOf(Record(this.metadata.id, 0, RecordType.Hydration, this.startTime, this.endTime, this.volume.inMilliliters))+//                    is NutritionRecord -> listOf(Record(it.metadata.id, 0, "Nutrition", it.startTime, it.endTime, it))++        else -> throw IllegalArgumentException("Unsupported record type")+    }\ No newline at end of file
health/src/main/java/com/vayunmathur/health/MainActivity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/MainActivity.kt b/health/src/main/java/com/vayunmathur/health/MainActivity.ktindex 167c6327bc..500c8dccc8 100644--- a/health/src/main/java/com/vayunmathur/health/MainActivity.kt+++ b/health/src/main/java/com/vayunmathur/health/MainActivity.kt@@ -26,51 +26,34 @@ import androidx.health.connect.client.PermissionController import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.* import androidx.navigation3.runtime.NavKey+import com.vayunmathur.health.database.HealthDatabase import com.vayunmathur.health.ui.BarChartDetails import com.vayunmathur.health.ui.HealthMetricConfig import com.vayunmathur.health.ui.MainPage import com.vayunmathur.health.ui.MedicalRecordsPage import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.rememberNavBackStack import kotlinx.serialization.Serializable -val PERMISSIONS = setOf(+val CLASSES = setOf(     // Activity & Energy-    HealthPermission.getReadPermission(StepsRecord::class),-    HealthPermission.getReadPermission(WheelchairPushesRecord::class),-    HealthPermission.getReadPermission(DistanceRecord::class),-    HealthPermission.getReadPermission(TotalCaloriesBurnedRecord::class),-    HealthPermission.getReadPermission(ActiveCaloriesBurnedRecord::class),-    HealthPermission.getReadPermission(BasalMetabolicRateRecord::class),-    HealthPermission.getReadPermission(FloorsClimbedRecord::class),-    HealthPermission.getReadPermission(ElevationGainedRecord::class),+    StepsRecord::class, WheelchairPushesRecord::class, DistanceRecord::class, TotalCaloriesBurnedRecord::class,+    ActiveCaloriesBurnedRecord::class, BasalMetabolicRateRecord::class, FloorsClimbedRecord::class, ElevationGainedRecord::class,      // Vitals & Clinical-    HealthPermission.getReadPermission(HeartRateRecord::class),-    HealthPermission.getReadPermission(RestingHeartRateRecord::class),-    HealthPermission.getReadPermission(HeartRateVariabilityRmssdRecord::class),-    HealthPermission.getReadPermission(RespiratoryRateRecord::class),-    HealthPermission.getReadPermission(OxygenSaturationRecord::class),-    HealthPermission.getReadPermission(BloodPressureRecord::class),-    HealthPermission.getReadPermission(BloodGlucoseRecord::class),-    HealthPermission.getReadPermission(Vo2MaxRecord::class),-    HealthPermission.getReadPermission(SkinTemperatureRecord::class),+    HeartRateRecord::class, RestingHeartRateRecord::class, HeartRateVariabilityRmssdRecord::class, RespiratoryRateRecord::class,+    OxygenSaturationRecord::class, BloodPressureRecord::class, BloodGlucoseRecord::class, Vo2MaxRecord::class, SkinTemperatureRecord::class,      // Body Composition-    HealthPermission.getReadPermission(WeightRecord::class),-    HealthPermission.getReadPermission(HeightRecord::class),-    HealthPermission.getReadPermission(BodyFatRecord::class),-    HealthPermission.getReadPermission(LeanBodyMassRecord::class),-    HealthPermission.getReadPermission(BoneMassRecord::class),-    HealthPermission.getReadPermission(BodyWaterMassRecord::class),+    WeightRecord::class, HeightRecord::class, BodyFatRecord::class, LeanBodyMassRecord::class, BoneMassRecord::class, BodyWaterMassRecord::class,      // Lifestyle & Nutrition-    HealthPermission.getReadPermission(SleepSessionRecord::class),-    HealthPermission.getReadPermission(MindfulnessSessionRecord::class),-    HealthPermission.getReadPermission(HydrationRecord::class),-    HealthPermission.getReadPermission(NutritionRecord::class),-) + if (SdkExtensions.getExtensionVersion(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) >= 16) {setOf(+    MindfulnessSessionRecord::class, HydrationRecord::class, // TODO: readd these: NutritionRecord::class, SleepSessionRecord::class+)++val PERMISSIONS = CLASSES.map { HealthPermission.getReadPermission(it) }.toSet() + if (SdkExtensions.getExtensionVersion(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) >= 16) {setOf(     HealthPermissions.READ_MEDICAL_DATA_ALLERGIES_INTOLERANCES,     HealthPermissions.READ_MEDICAL_DATA_CONDITIONS,     HealthPermissions.READ_MEDICAL_DATA_LABORATORY_RESULTS,@@ -91,7 +74,8 @@ class MainActivity : ComponentActivity() {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         val healthConnectClient = HealthConnectClient.getOrCreate(this)-        HealthAPI.init(healthConnectClient, this)+        val db = buildDatabase<HealthDatabase>()+        HealthAPI.init(healthConnectClient, this, db)         setContent {             DynamicTheme {                 var hasPermissions by remember { mutableStateOf(false) }@@ -108,7 +92,10 @@ class MainActivity : ComponentActivity() {                 }                  if (hasPermissions) {-                    Navigation()+                    LaunchedEffect(Unit) {+                        HealthSyncWorker.enqueue(this@MainActivity)+                    }+                    Navigation(db)                 } else {                     Box(                         modifier = Modifier.fillMaxSize(),@@ -137,7 +124,7 @@ sealed interface Route: NavKey { }  @Composable-fun Navigation() {+fun Navigation(db: HealthDatabase) {     val backStack = rememberNavBackStack<Route>(Route.MainPage)     MainNavigation(backStack) {         entry<Route.MainPage> {
health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt b/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.ktnew file mode 100644index 0000000000..3192fef073--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt@@ -0,0 +1,78 @@+package com.vayunmathur.health.database++import androidx.room.*+import kotlinx.coroutines.flow.Flow+import java.time.Instant+import java.time.Period+import java.time.ZoneOffset++enum class RecordType {+    Steps, Wheelchair, Distance, CaloriesTotal, CaloriesActive, CaloriesBasal, Floors, Elevation,+    HeartRate, RestingHeartRate, HeartRateVariabilityRmssd, RespiratoryRate, OxygenSaturation,+    BloodPressure, BloodGlucose, Vo2Max, SkinTemperature,+    Weight, Height, BodyFat, LeanBodyMass, BoneMass, BodyWaterMass,+    Sleep, Mindfulness, Hydration, Nutrition+}++@Entity+data class Record(+    val id: String,+    val index : Int, // for multisample records+    val type: RecordType,+    val startTime: Instant,+    val endTime: Instant,+    val value: Double,+    val secondaryValue: Double = 0.0,+    @PrimaryKey val primaryKey: String = "$id-$index",+)++@Dao+interface HealthDao {+    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun upsert(records: List<Record>)++    @Query("DELETE FROM Record WHERE primaryKey IN (:ids)")+    suspend fun deleteByIds(ids: List<String>)++    @Query("SELECT * FROM Record WHERE type = :type ORDER BY startTime DESC")+    suspend fun getRecords(type: RecordType): List<Record>++    @Query("SELECT * FROM Record WHERE primaryKey = :id")+    suspend fun getRecord(id: String): Record?++    @Query("SELECT * FROM Record WHERE type = :type ORDER BY startTime DESC LIMIT 1")+    suspend fun getLastRecord(type: RecordType): Record?++    @Query("SELECT SUM(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    fun sumInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double>+    @Query("SELECT SUM(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    suspend fun sumInRangeGet(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Double+    @Query("SELECT MIN(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    fun minInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double>+    @Query("SELECT MAX(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    fun maxInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double>+}++@Database(+    entities = [Record::class],+    version = 1,+    exportSchema = false+)+@TypeConverters(Converters::class)+abstract class HealthDatabase : RoomDatabase() {+    abstract fun healthDao(): HealthDao+}++class Converters {+    @TypeConverter+    fun fromTimestamp(value: Long?): Instant? = value?.let { Instant.ofEpochMilli(it) }++    @TypeConverter+    fun dateToTimestamp(date: Instant?): Long? = date?.toEpochMilli()++    @TypeConverter+    fun toTS(date: kotlin.time.Instant): Long = date.toEpochMilliseconds()++    @TypeConverter+    fun fromTS(timestamp: Long): kotlin.time.Instant = kotlin.time.Instant.fromEpochMilliseconds(timestamp)+}\ No newline at end of file
health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.ktindex a095799f03..ff81d2fd16 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -25,16 +25,19 @@ import androidx.navigation3.runtime.NavBackStack import com.vayunmathur.health.HealthAPI import com.vayunmathur.health.Route import com.vayunmathur.library.ui.IconNavigation-import kotlinx.coroutines.launch-import java.time.LocalDate-import java.time.Period-import java.time.format.DateTimeFormatter-import java.time.format.TextStyle-import java.util.* import com.vayunmathur.health.R-import java.time.Duration-import java.time.ZoneId-import java.time.temporal.ChronoUnit+import com.vayunmathur.health.database.RecordType+import kotlinx.datetime.DateTimeUnit+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn+import kotlinx.datetime.atTime+import kotlinx.datetime.minus+import kotlinx.datetime.plus+import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime+import kotlinx.datetime.todayIn+import kotlin.time.Clock  /**  * Configuration for different health metrics to make the UI reusable.@@ -42,74 +45,18 @@ import java.time.temporal.ChronoUnit  */ enum class HealthMetricConfig(     val title: String,-    val metric: AggregateMetric<*>,+    val recordType: RecordType,     val unit: String,-    val dailyGoal: Long,-    val getValue: (AggregationResult) -> Long+    val dailyGoal: Long ) {-    ENERGY(-        title = "Energy Burned",-        metric = TotalCaloriesBurnedRecord.ENERGY_TOTAL,-        unit = "cal",-        dailyGoal = 2470,-        getValue = { it[TotalCaloriesBurnedRecord.ENERGY_TOTAL]?.inKilocalories?.toLong() ?: 0L }-    ),--    ACTIVE_CALORIES(-        title = "Active Calories",-        metric = ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL,-        unit = "cal",-        dailyGoal = 500,-        getValue = { it[ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL]?.inKilocalories?.toLong() ?: 0L }-    ),--    BASAL_METABOLIC_RATE(-        title = "Basal Metabolic Rate",-        metric = BasalMetabolicRateRecord.BASAL_CALORIES_TOTAL,-        unit = "cal",-        dailyGoal = 1800,-        getValue = { it[BasalMetabolicRateRecord.BASAL_CALORIES_TOTAL]?.inKilocalories?.toLong() ?: 0L }-    ),--    STEPS(-        title = "Steps",-        metric = StepsRecord.COUNT_TOTAL,-        unit = "steps",-        dailyGoal = 10000,-        getValue = { it[StepsRecord.COUNT_TOTAL] ?: 0L }-    ),--    WHEELCHAIR_PUSHES(-        title = "Wheelchair Pushes",-        metric = WheelchairPushesRecord.COUNT_TOTAL,-        unit = "pushes",-        dailyGoal = 3000,-        getValue = { it[WheelchairPushesRecord.COUNT_TOTAL] ?: 0L }-    ),--    DISTANCE(-        title = "Distance",-        metric = DistanceRecord.DISTANCE_TOTAL,-        unit = "km",-        dailyGoal = 5,-        getValue = { it[DistanceRecord.DISTANCE_TOTAL]?.inKilometers?.toLong() ?: 0L }-    ),--    ELEVATION(-        title = "Elevation Gained",-        metric = ElevationGainedRecord.ELEVATION_GAINED_TOTAL,-        unit = "m",-        dailyGoal = 50,-        getValue = { it[ElevationGainedRecord.ELEVATION_GAINED_TOTAL]?.inMeters?.toLong() ?: 0L }-    ),--    FLOORS(-        title = "Floors Climbed",-        metric = FloorsClimbedRecord.FLOORS_CLIMBED_TOTAL,-        unit = "floors",-        dailyGoal = 10,-        getValue = { it[FloorsClimbedRecord.FLOORS_CLIMBED_TOTAL]?.toInt()?.toLong() ?: 0L }-    )+    ENERGY("Energy Burned", RecordType.CaloriesTotal, "cal", 2470),+    ACTIVE_CALORIES("Active Calories", RecordType.CaloriesActive, "cal", 500),+    BASAL_METABOLIC_RATE("Basal Metabolic Rate", RecordType.CaloriesBasal, "cal", 1800),+    STEPS("Steps", RecordType.Steps, "steps", 10000),+    WHEELCHAIR_PUSHES("Wheelchair Pushes", RecordType.Wheelchair, "pushes", 3000),+    DISTANCE("Distance", RecordType.Distance, "km", 5),+    ELEVATION("Elevation Gained", RecordType.Elevation, "m", 50),+    FLOORS("Floors Climbed", RecordType.Floors, "floors", 10) }  data class MetricDashboardData(@@ -133,105 +80,70 @@ fun BarChartDetails(     backStack: NavBackStack<Route>,     config: HealthMetricConfig ) {-    var selectedTab by remember { mutableStateOf(2) } // 0:Day, 1:Week, 2:Month, 3:Year+    var selectedTab by remember { mutableIntStateOf(2) }     val tabs = listOf("Day", "Week", "Month", "Year")-    var anchorDate by remember { mutableStateOf(LocalDate.now()) }-    var dataState by remember { mutableStateOf(MetricDashboardData()) }-    val scope = rememberCoroutineScope()--    LaunchedEffect(selectedTab, anchorDate, config) {-        scope.launch {-            try {-                val metrics = setOf(config.metric)-                val filter = when (selectedTab) {-                    0 -> HealthAPI.timeRangeToday(anchorDate)-                    1 -> HealthAPI.timeRangeThisWeek(anchorDate)-                    2 -> HealthAPI.timeRangeThisMonth(anchorDate)-                    else -> HealthAPI.timeRangeThisYear(anchorDate)-                }--                val mappedChart: List<Pair<String, Long>>-                val history: List<HistoryItem>-                val totalValue: Long-                val barCount: Int--                if (selectedTab == 0) {-                    barCount = 24-                    val hourlyData = HealthAPI.aggregateByDuration(filter, Duration.ofHours(1), metrics)-                    totalValue = hourlyData.sumOf { config.getValue(it.result) } -                    mappedChart = hourlyData.map { group ->-                        val value = config.getValue(group.result)-                        val label = group.startTime.atZone(ZoneId.systemDefault()).hour.toString()-                        label to value-                    }-                    history = hourlyData.map { group ->-                        val value = config.getValue(group.result)-                        val hour = group.startTime.atZone(ZoneId.systemDefault()).hour-                        HistoryItem("Hour $hour", value, config.unit, false)-                    }.filter { it.value > 0 }.reversed()-                } else {-                    val period = if (selectedTab == 3) Period.ofMonths(1) else Period.ofDays(1)-                    barCount = when (selectedTab) {-                        1 -> 7-                        2 -> anchorDate.lengthOfMonth()-                        else -> 12-                    }--                    val grouped = HealthAPI.aggregateByPeriod(filter, period, metrics)-                    totalValue = grouped.sumOf { config.getValue(it.result) }--                    mappedChart = grouped.map { group ->-                        val totalMonthValue = config.getValue(group.result)--                        val displayValue = if (selectedTab == 3) {-                            val daysInMonth = ChronoUnit.DAYS.between(group.startTime, group.endTime).coerceAtLeast(1)-                            totalMonthValue / daysInMonth-                        } else totalMonthValue--                        val label = when (selectedTab) {-                            3 -> group.startTime.month.getDisplayName(TextStyle.SHORT, Locale.getDefault())-                            else -> group.startTime.dayOfMonth.toString()-                        }-                        label to displayValue-                    }--                    history = grouped.map { group ->-                        val totalMonthValue = config.getValue(group.result)+    // Switch to kotlinx-datetime+    var anchorDate by remember { mutableStateOf(Clock.System.todayIn(TimeZone.currentSystemDefault())) }+    var dataState by remember { mutableStateOf(MetricDashboardData()) } -                        val displayValue = if (selectedTab == 3) {-                            val daysInMonth = ChronoUnit.DAYS.between(group.startTime, group.endTime).coerceAtLeast(1)-                            totalMonthValue / daysInMonth-                        } else totalMonthValue+    val tz = TimeZone.currentSystemDefault() -                        val label = when (selectedTab) {-                            1 -> group.startTime.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault())-                            2 -> group.startTime.format(DateTimeFormatter.ofPattern("MMM d"))-                            else -> group.startTime.month.getDisplayName(TextStyle.FULL, Locale.getDefault())-                        }-                        HistoryItem(label, displayValue, config.unit, displayValue >= config.dailyGoal)-                    }.filter { it.value > 0 }.reversed()-                }+    LaunchedEffect(selectedTab, anchorDate, config) {+        val (startTime, endTime, periodType) = when (selectedTab) {+            0 -> Triple(+                anchorDate.atStartOfDayIn(tz),+                anchorDate.atTime(23, 59, 59).toInstant(tz),+                HealthAPI.PeriodType.Hourly+            )+            1 -> {+                val start = anchorDate.minus(anchorDate.dayOfWeek.ordinal, DateTimeUnit.DAY)+                Triple(start.atStartOfDayIn(tz), start.plus(7, DateTimeUnit.DAY).atStartOfDayIn(tz), HealthAPI.PeriodType.Daily)+            }+            2 -> {+                val start = LocalDate(anchorDate.year, anchorDate.month, 1)+                val end = start.plus(1, DateTimeUnit.MONTH)+                Triple(start.atStartOfDayIn(tz), end.atStartOfDayIn(tz), HealthAPI.PeriodType.Daily)+            }+            else -> {+                val start = LocalDate(anchorDate.year, 1, 1)+                val end = start.plus(1, DateTimeUnit.YEAR)+                Triple(start.atStartOfDayIn(tz), end.atStartOfDayIn(tz), HealthAPI.PeriodType.Weekly) // Or Monthly if you add it+            }+        } -                val daysInRange = when (selectedTab) {-                    0 -> 1L-                    1 -> 7L-                    2 -> anchorDate.lengthOfMonth().toLong()-                    else -> if (anchorDate.isLeapYear) 366L else 365L-                }-                val dailyAvg = totalValue / daysInRange+        val rawSums = HealthAPI.getListOfSums(config.recordType, startTime, endTime, periodType) -                dataState = MetricDashboardData(-                    totalValue = totalValue,-                    dailyAverage = dailyAvg,-                    chartData = mappedChart,-                    historyItems = history,-                    totalBarCount = barCount-                )-            } catch (e: Exception) {-                e.printStackTrace()+        // Transform the raw sums into Chart and History data+        val mappedChart = rawSums.mapIndexed { index, value ->+            val label = when (selectedTab) {+                0 -> index.toString()+                1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.take(3)+                else -> (index + 1).toString()             }+            label to value.toLong()         }++        val history = rawSums.mapIndexed { index, value ->+            val label = when (selectedTab) {+                0 -> "Hour $index"+                1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.lowercase().capitalize()+                2 -> "Day ${index + 1}"+                else -> "Week ${index + 1}"+            }+            HistoryItem(label, value.toLong(), config.unit, value >= config.dailyGoal)+        }.filter { it.value > 0 }.reversed()++        val totalValue = rawSums.sum().toLong()+        val daysInRange = rawSums.size.coerceAtLeast(1)++        dataState = MetricDashboardData(+            totalValue = totalValue,+            dailyAverage = if (selectedTab == 0) totalValue else totalValue / daysInRange,+            chartData = mappedChart,+            historyItems = history,+            totalBarCount = rawSums.size+        )     }      Scaffold(@@ -248,12 +160,7 @@ fun BarChartDetails(                     Tab(                         selected = selectedTab == index,                         onClick = { selectedTab = index },-                        text = {-                            Text(-                                text = title,-                                fontWeight = if (selectedTab == index) FontWeight.Bold else FontWeight.Normal-                            )-                        }+                        text = { Text(title, fontWeight = if (selectedTab == index) FontWeight.Bold else FontWeight.Normal) }                     )                 }             }@@ -263,10 +170,11 @@ fun BarChartDetails(                 contentPadding = PaddingValues(top = 16.dp, bottom = 24.dp)             ) {                 item {+                    // Header Date Display                     val headerLabel = when (selectedTab) {-                        0 -> anchorDate.format(DateTimeFormatter.ofPattern("MMMM d, yyyy"))-                        1 -> "Week of ${anchorDate.with(java.time.DayOfWeek.MONDAY).format(DateTimeFormatter.ofPattern("MMM d"))}"-                        2 -> anchorDate.format(DateTimeFormatter.ofPattern("MMMM yyyy"))+                        0 -> "${anchorDate.month.name} ${anchorDate.dayOfMonth}, ${anchorDate.year}"+                        1 -> "Week of ${anchorDate.minus(anchorDate.dayOfWeek.ordinal, DateTimeUnit.DAY)}"+                        2 -> "${anchorDate.month.name} ${anchorDate.year}"                         else -> anchorDate.year.toString()                     } @@ -276,32 +184,27 @@ fun BarChartDetails(                         horizontalArrangement = Arrangement.Center                     ) {                         IconButton(onClick = {-                            anchorDate = when (selectedTab) {-                                0 -> anchorDate.minusDays(1)-                                1 -> anchorDate.minusWeeks(1)-                                2 -> anchorDate.minusMonths(1)-                                else -> anchorDate.minusYears(1)+                            anchorDate = when(selectedTab) {+                                0 -> anchorDate.minus(1, DateTimeUnit.DAY)+                                1 -> anchorDate.minus(1, DateTimeUnit.WEEK)+                                2 -> anchorDate.minus(1, DateTimeUnit.MONTH)+                                else -> anchorDate.minus(1, DateTimeUnit.YEAR)                             }                         }) {-                            Icon(painterResource(R.drawable.baseline_arrow_back_24), contentDescription = "Prev")+                            Icon(painterResource(R.drawable.baseline_arrow_back_24), "Prev")                         } -                        Text(-                            text = headerLabel,-                            style = MaterialTheme.typography.titleMedium,-                            modifier = Modifier.widthIn(min = 140.dp),-                            textAlign = TextAlign.Center-                        )+                        Text(headerLabel, style = MaterialTheme.typography.titleMedium, modifier = Modifier.widthIn(min = 140.dp), textAlign = TextAlign.Center)                          IconButton(onClick = {-                            anchorDate = when (selectedTab) {-                                0 -> anchorDate.plusDays(1)-                                1 -> anchorDate.plusWeeks(1)-                                2 -> anchorDate.plusMonths(1)-                                else -> anchorDate.plusYears(1)+                            anchorDate = when(selectedTab) {+                                0 -> anchorDate.plus(1, DateTimeUnit.DAY)+                                1 -> anchorDate.plus(1, DateTimeUnit.WEEK)+                                2 -> anchorDate.plus(1, DateTimeUnit.MONTH)+                                else -> anchorDate.plus(1, DateTimeUnit.YEAR)                             }                         }) {-                            Icon(painterResource(R.drawable.outline_arrow_forward_24), contentDescription = "Next")+                            Icon(painterResource(R.drawable.outline_arrow_forward_24), "Next")                         }                     } @@ -314,48 +217,25 @@ fun BarChartDetails(                             fontWeight = FontWeight.Light                         )                         Text(-                            text = " ${config.unit} per day (avg)",+                            text = " ${config.unit}${if (selectedTab != 0) " per day (avg)" else ""}",                             style = MaterialTheme.typography.bodyLarge,                             modifier = Modifier.padding(bottom = 12.dp, start = 4.dp),                             color = LocalContentColor.current.copy(alpha = 0.6f)                         )                     }-                    Text(-                        text = "Total ${config.title.lowercase()}: ${String.format("%,d", dataState.totalValue)} ${config.unit}",-                        style = MaterialTheme.typography.bodyMedium,-                        color = LocalContentColor.current.copy(alpha = 0.6f),-                        modifier = Modifier.padding(top = 8.dp)-                    )                 }                  item {                     Spacer(Modifier.height(32.dp))-                    val colorScheme = MaterialTheme.colorScheme                     GenericBarChart(                         data = dataState.chartData,                         totalBarCount = dataState.totalBarCount,                         goalValue = config.dailyGoal,-                        barColor = colorScheme.primary,-                        goalColor = colorScheme.secondary+                        barColor = MaterialTheme.colorScheme.primary,+                        goalColor = MaterialTheme.colorScheme.secondary                     )                 } -                item {-                    Spacer(Modifier.height(32.dp))-                    Row(-                        modifier = Modifier.fillMaxWidth(),-                        horizontalArrangement = Arrangement.SpaceBetween-                    ) {-                        Text("History", fontWeight = FontWeight.Bold)-                        Text(-                            if (selectedTab == 0) config.unit.replaceFirstChar { it.uppercase() } else "Daily average",-                            style = MaterialTheme.typography.bodySmall,-                            color = LocalContentColor.current.copy(alpha = 0.6f)-                        )-                    }-                    Spacer(Modifier.height(16.dp))-                }-                 items(dataState.historyItems) { item ->                     HistoryCard(item)                     Spacer(Modifier.height(8.dp))
health/src/main/java/com/vayunmathur/health/ui/MainPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt b/health/src/main/java/com/vayunmathur/health/ui/MainPage.ktindex 95229caea7..9fa7a00da4 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt@@ -25,6 +25,7 @@ import androidx.compose.material3.Scaffold import androidx.compose.material3.Text 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@@ -44,14 +45,19 @@ import androidx.navigation3.runtime.NavBackStack import com.vayunmathur.health.HealthAPI import com.vayunmathur.health.R import com.vayunmathur.health.Route+import com.vayunmathur.health.database.RecordType import com.vayunmathur.health.fhir.Patient import com.vayunmathur.library.ui.invisibleClickable import com.vayunmathur.library.util.round import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock+import kotlin.time.Duration.Companion.hours+import kotlin.time.Instant import kotlin.time.toKotlinDuration  val JSON = kotlinx.serialization.json.Json {@@ -63,7 +69,6 @@ val JSON = kotlinx.serialization.json.Json { @Composable fun MainPage(backStack: NavBackStack<Route>) {     val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())-    var aggregates: AggregationResult? by remember { mutableStateOf(null) }      // Health Metrics States (Point-in-time)     var br by remember { mutableStateOf<Double?>(null) }@@ -82,50 +87,49 @@ fun MainPage(backStack: NavBackStack<Route>) {     var boneMass by remember { mutableStateOf<Double?>(null) }     var leanBodyMass by remember { mutableStateOf<Double?>(null) }     var bodyWaterMass by remember { mutableStateOf<Double?>(null) }+    +    val dayStart = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date.atStartOfDayIn(TimeZone.currentSystemDefault())+    val dayEnd = dayStart.plus(24.hours)++    val totalCaloriesBurnedToday by HealthAPI.sumInRange(RecordType.CaloriesTotal, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)+    val activeCaloriesBurnedToday by HealthAPI.sumInRange(RecordType.CaloriesActive, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)+    val basalCaloriesBurnedToday by HealthAPI.sumInRange(RecordType.CaloriesBasal, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)+    val stepsToday by HealthAPI.sumInRange(RecordType.Steps, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)+    val wheelchairPushesToday by HealthAPI.sumInRange(RecordType.Wheelchair, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)+    val mindfulnessToday by HealthAPI.sumInRange(RecordType.Mindfulness, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)+    val distanceToday by HealthAPI.sumInRange(RecordType.Distance, dayStart, dayEnd).collectAsState(0.0)+    val floorsClimbedToday by HealthAPI.sumInRange(RecordType.Floors, dayStart, dayEnd).collectAsState(0.0)+    val elevationGainedToday by HealthAPI.sumInRange(RecordType.Elevation, dayStart, dayEnd).collectAsState(0.0)+    val hydrationToday by HealthAPI.sumInRange(RecordType.Hydration, dayStart, dayEnd).collectAsState(0.0) // Liters+//    val caloriesConsumedToday by HealthAPI.sumInRange(RecordType.NutritionEnergy, dayStart, dayEnd).collectAsState(0.0)+//    val proteinToday by HealthAPI.sumInRange(RecordType.Protein, dayStart, dayEnd).collectAsState(0.0) // Grams+//    val carbsToday by HealthAPI.sumInRange(RecordType.Carbohydrates, dayStart, dayEnd).collectAsState(0.0)+//    val fatToday by HealthAPI.sumInRange(RecordType.Fat, dayStart, dayEnd).collectAsState(0.0)++    val heartRateMaxToday by HealthAPI.maxInRange(RecordType.HeartRate, dayStart, dayEnd).map{it.toLong()}.collectAsState(0L)+    val heartRateMinToday by HealthAPI.minInRange(RecordType.HeartRate, dayStart, dayEnd).map{it.toLong()}.collectAsState(0L)++//    val sleepDurationToday by HealthAPI.sumInRange(RecordType.Sleep, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)      LaunchedEffect(now.date) {-        // 1. Fetch Aggregates (Cumulative time-series data)-        aggregates = withContext(Dispatchers.IO) {-            HealthAPI.aggregates(-                HealthAPI.timeRangeToday(),-                TotalCaloriesBurnedRecord.ENERGY_TOTAL,-                ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL,-                BasalMetabolicRateRecord.BASAL_CALORIES_TOTAL,-                StepsRecord.COUNT_TOTAL,-                WheelchairPushesRecord.COUNT_TOTAL, // New-                // MindfulnessSessionRecord.MINDFULNESS_DURATION_TOTAL, TODO: add back when supported-                DistanceRecord.DISTANCE_TOTAL,-                FloorsClimbedRecord.FLOORS_CLIMBED_TOTAL,-                ElevationGainedRecord.ELEVATION_GAINED_TOTAL,-                HydrationRecord.VOLUME_TOTAL,-                NutritionRecord.ENERGY_TOTAL,-                NutritionRecord.PROTEIN_TOTAL,-                NutritionRecord.TOTAL_CARBOHYDRATE_TOTAL,-                NutritionRecord.TOTAL_FAT_TOTAL,-                HeartRateRecord.BPM_MAX,-                HeartRateRecord.BPM_MIN,-                SleepSessionRecord.SLEEP_DURATION_TOTAL,-            )-        }-         // 2. Fetch Latest Records (Point-in-time metrics)         withContext(Dispatchers.IO) {-            spo2 = HealthAPI.lastRecord<OxygenSaturationRecord>()?.percentage?.value-            br = HealthAPI.lastRecord<RespiratoryRateRecord>()?.rate-            hrv = HealthAPI.lastRecord<HeartRateVariabilityRmssdRecord>()?.heartRateVariabilityMillis-            rhr = HealthAPI.lastRecord<RestingHeartRateRecord>()?.beatsPerMinute-            skinTemp = HealthAPI.lastRecord<SkinTemperatureRecord>()?.deltas?.lastOrNull()?.delta?.inCelsius-            vo2Max = HealthAPI.lastRecord<Vo2MaxRecord>()?.vo2MillilitersPerMinuteKilogram-            bloodGlucose = HealthAPI.lastRecord<BloodGlucoseRecord>()?.level?.inMilligramsPerDeciliter-            bloodPressure = HealthAPI.lastRecord<BloodPressureRecord>()?.let {-                it.systolic.inMillimetersOfMercury to it.diastolic.inMillimetersOfMercury+            spo2 = HealthAPI.lastRecord(RecordType.OxygenSaturation)?.value+            br = HealthAPI.lastRecord(RecordType.RespiratoryRate)?.value+            hrv = HealthAPI.lastRecord(RecordType.HeartRateVariabilityRmssd)?.value+            rhr = HealthAPI.lastRecord(RecordType.RestingHeartRate)?.value?.toLong()+            skinTemp = HealthAPI.lastRecord(RecordType.SkinTemperature)?.value+            vo2Max = HealthAPI.lastRecord(RecordType.Vo2Max)?.value+            bloodGlucose = HealthAPI.lastRecord(RecordType.BloodGlucose)?.value+            bloodPressure = HealthAPI.lastRecord(RecordType.BloodPressure)?.let {+                it.value to it.secondaryValue             }-            height = HealthAPI.lastRecord<HeightRecord>()?.height?.inMeters-            weight = HealthAPI.lastRecord<WeightRecord>()?.weight?.inKilograms-            bodyFat = HealthAPI.lastRecord<BodyFatRecord>()?.percentage?.value-            boneMass = HealthAPI.lastRecord<BoneMassRecord>()?.mass?.inKilograms-            leanBodyMass = HealthAPI.lastRecord<LeanBodyMassRecord>()?.mass?.inKilograms-            bodyWaterMass = HealthAPI.lastRecord<BodyWaterMassRecord>()?.mass?.inKilograms+            height = HealthAPI.lastRecord(RecordType.Height)?.value+            weight = HealthAPI.lastRecord(RecordType.Weight)?.value+            bodyFat = HealthAPI.lastRecord(RecordType.BodyFat)?.value+            boneMass = HealthAPI.lastRecord(RecordType.BoneMass)?.value+            leanBodyMass = HealthAPI.lastRecord(RecordType.LeanBodyMass)?.value+            bodyWaterMass = HealthAPI.lastRecord(RecordType.BodyWaterMass)?.value         }     } @@ -150,39 +154,39 @@ fun MainPage(backStack: NavBackStack<Route>) {              // 4. Activity & Energy             Text("Activity", style = MaterialTheme.typography.labelLarge)-            EnergyBurned(backStack, aggregates?.get(TotalCaloriesBurnedRecord.ENERGY_TOTAL)?.inKilocalories ?: 0.0)+            EnergyBurned(backStack, totalCaloriesBurnedToday)              Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {                 Box(Modifier.weight(1f)) {-                    MiniMetricCard("Active", (aggregates?.get(ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL)?.inKilocalories ?: 0.0).round(0).toInt().toString(), "cal", onClick = {+                    MiniMetricCard("Active", activeCaloriesBurnedToday.toString(), "cal", onClick = {                         backStack.add(Route.BarChartDetails(HealthMetricConfig.ACTIVE_CALORIES))                     })                 }                 Box(Modifier.weight(1f)) {-                    MiniMetricCard("Basal", (aggregates?.get(BasalMetabolicRateRecord.BASAL_CALORIES_TOTAL)?.inKilocalories ?: 0.0).round(0).toInt().toString(), "cal", onClick = {+                    MiniMetricCard("Basal", basalCaloriesBurnedToday.toString(), "cal", onClick = {                         backStack.add(Route.BarChartDetails(HealthMetricConfig.BASAL_METABOLIC_RATE))                     })                 }             }              // High priority Activity Metrics-            Steps(backStack, aggregates?.get(StepsRecord.COUNT_TOTAL) ?: 0)+            Steps(backStack, stepsToday) -            val pushes = aggregates?.get(WheelchairPushesRecord.COUNT_TOTAL) ?: 0-            if (pushes > 0) {-                WheelchairPushes(backStack, pushes)+            if (wheelchairPushesToday > 0) {+                WheelchairPushes(backStack, wheelchairPushesToday)             } -            // Mindfulness(aggregates?.get(MindfulnessSessionRecord.MINDFULNESS_DURATION_TOTAL)?.toKotlinDuration()?.inWholeMinutes ?: 0)+            Mindfulness(mindfulnessToday)              Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                Box(Modifier.weight(1f)) { ElevationGained(backStack, aggregates?.get(ElevationGainedRecord.ELEVATION_GAINED_TOTAL)?.inMeters ?: 0.0) }-                Box(Modifier.weight(1f)) { FloorsClimbed(backStack, aggregates?.get(FloorsClimbedRecord.FLOORS_CLIMBED_TOTAL) ?: 0.0) }+                Box(Modifier.weight(1f)) { ElevationGained(backStack, elevationGainedToday) }+                Box(Modifier.weight(1f)) { FloorsClimbed(backStack, floorsClimbedToday) }             } -            Distance(backStack,aggregates?.get(DistanceRecord.DISTANCE_TOTAL)?.inKilometers ?: 0.0)-            HeartRate(aggregates?.get(HeartRateRecord.BPM_MAX) ?: 0, aggregates?.get(HeartRateRecord.BPM_MIN) ?: 0)-            Sleep(aggregates?.get(SleepSessionRecord.SLEEP_DURATION_TOTAL)?.toKotlinDuration()?.inWholeMinutes ?: 0)+            Distance(backStack,distanceToday)+            HeartRate(heartRateMaxToday, heartRateMinToday)+            // TODO: add this back+            //Sleep(aggregates?.get(SleepSessionRecord.SLEEP_DURATION_TOTAL)?.toKotlinDuration()?.inWholeMinutes ?: 0)               // 1. Vitals & Clinical Metrics@@ -191,8 +195,9 @@ fun MainPage(backStack: NavBackStack<Route>) {              // 2. Nutrition Summary             Text("Nutrition (Today)", style = MaterialTheme.typography.labelLarge)-            NutritionSummaryCard(aggregates)-            Hydration(aggregates?.get(HydrationRecord.VOLUME_TOTAL)?.inMilliliters ?: 0.0)+            // TODO: add this back+            //NutritionSummaryCard(aggregates)+            Hydration(hydrationToday)              // 3. Body Composition             Text("Body Composition", style = MaterialTheme.typography.labelLarge)@@ -383,8 +388,8 @@ fun Mindfulness(min: Long) { }  @Composable-fun EnergyBurned(backStack: NavBackStack<Route>, kcal: Double) {-    GenericCard("Energy", null, "cal", kcal.round(0).toInt().toString(), "Today", onClick = {+fun EnergyBurned(backStack: NavBackStack<Route>, kcal: Long) {+    GenericCard("Energy", null, "cal", kcal.toString(), "Today", onClick = {         backStack.add(Route.BarChartDetails(HealthMetricConfig.ENERGY))     }) {         ProgressBarGraphic(R.drawable.baseline_local_fire_department_24, kcal.toFloat(), 2500f, Color(0xFF00E676))
library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex 0d82966a7e..c0e10d26c1 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -81,6 +81,17 @@ class DataStoreUtils private constructor(context: Context) {         }     } +    fun getString(string: String): String? {+        return stateMap[stringPreferencesKey(string)] as String?+    }++    suspend fun setString(string: String, value: String, onlyIfAbsent: Boolean = false) {+        dataStore.edit {+            if (onlyIfAbsent && it.contains(stringPreferencesKey(string))) return@edit+            it[stringPreferencesKey(string)]+        }+    }+     companion object {         @Volatile         private var instance: DataStoreUtils? = null