Modern Apps git

← Modern-Apps.git

health: improved line charts & added heart rate graph

Commit
8c666a6e575d789a552a9931a842afb739ad3ce4
Author
Vayun Mathur <[email protected]>
When
2026-03-03 23:41 UTC (9 months ago)
Parents
ea9ef51

Diff

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 3974045f75..6a449a14e6 100644--- a/health/src/main/java/com/vayunmathur/health/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/HealthAPI.kt@@ -67,47 +67,53 @@ object HealthAPI {         startTime: Instant,         endTime: Instant,         period: PeriodType-    ): List<Pair<Double?, Double?>> {-        val tz = TimeZone.currentSystemDefault()-        val avgs = mutableListOf<Pair<Double?, Double?>>()--        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)-                }-                PeriodType.Monthly -> {-                    val localDateTime = currentStart.toLocalDateTime(tz)-                    val nextLocalDate = localDateTime.date.plus(1, DateTimeUnit.MONTH)-                    nextLocalDate.atTime(localDateTime.hour, localDateTime.minute).toInstant(tz)+    ): List<Tuple3<Long, Double, Double>> {+        when(period) {+            PeriodType.Daily -> {+                // yyyy-mm-dd+                val dailySums = db.healthDao().getDailyAvgs(recordType, startTime, endTime).sortedBy { it.day }+                return dailySums.map { Tuple3(LocalDate.parse(it.day).toEpochDays(), it.totalValue, it.totalValue2) }+            }+            PeriodType.Weekly -> {+                val dailySums = db.healthDao().getDailyAvgs(recordType, startTime, endTime).sortedBy { it.day }+                    .groupBy {+                        val date = LocalDate.parse(it.day)+                        val firstDayOfWeek = date.plus((date.dayOfWeek.ordinal+1)%7, DateTimeUnit.DAY)+                        firstDayOfWeek.toEpochDays()+                    }+                    .mapValues { it.value.map { it.totalValue }.average() to it.value.map { it.totalValue2 }.average() }+                    .map { Tuple3(it.key, it.value.first, it.value.second) }+                return dailySums+            }+            PeriodType.Monthly -> {+                val dailySums = db.healthDao().getDailyAvgs(recordType, startTime, endTime).sortedBy { it.day }+                    .groupBy {+                        val date = LocalDate.parse(it.day)+                        val firstDayOfMonth = date.minus(date.day-1, DateTimeUnit.DAY)+                        firstDayOfMonth.toEpochDays()+                    }+                    .mapValues { it.value.map { it.totalValue }.average() to it.value.map { it.totalValue2 }.average() }+                    .map { Tuple3(it.key, it.value.first, it.value.second) }+                return dailySums+            }+            else -> {+                val hourlySums = db.healthDao().getHourlyAvgs(recordType, startTime.toEpochMilliseconds(), endTime.toEpochMilliseconds()).sortedBy { it.hourBlock }+                return hourlySums.map {+                    val date = LocalDateTime.Format {+                        year()+                        chars("-")+                        monthNumber()+                        chars("-")+                        dayOfMonth()+                        chars(" ")+                        hour()+                        chars(":")+                        minute()+                    }.parse(it.hourBlock)+                    Tuple3(date.date.toEpochDays()*24 + date.hour, it.totalValue, it.totalValue2)                 }             }--            // Clamp the end range to the requested endTime-            val currentEnd = if (nextStart > endTime) endTime else nextStart--            // Fetch sum from DAO-            val avg1 = db.healthDao().avgInRangeGet1(recordType, currentStart, currentEnd)-            val avg2 = db.healthDao().avgInRangeGet2(recordType, currentStart, currentEnd)-            avgs.add(Pair(avg1, avg2))--            currentStart = nextStart         }--        return avgs     }      suspend fun getListOfSums(@@ -138,10 +144,10 @@ object HealthAPI {                     .groupBy {                         val date = LocalDate.parse(it.day)                         val firstDayOfMonth = date.minus(date.day-1, DateTimeUnit.DAY)-                        firstDayOfMonth+                        firstDayOfMonth.toEpochDays()                     }                     .mapValues { it.value.map { it.totalValue }.average() to it.value.map { it.totalValue2 }.average() }-                    .map { Tuple3(it.key.toEpochDays(), it.value.first, it.value.second) }+                    .map { Tuple3(it.key, it.value.first, it.value.second) }                 return dailySums             }             else -> {
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.ktindex 8080ba3a3f..9196f35bb0 100644--- a/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt+++ b/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt@@ -103,6 +103,42 @@ interface HealthDao {         endTime: Long     ): List<HourlySum> +    @Query("""+    SELECT +        date(startTime / 1000, 'unixepoch', 'localtime') as day, +        AVG(value) as totalValue,+        AVG(secondaryValue) as totalValue2 +    FROM Record +    WHERE type = :type +      AND startTime >= :startTime +      AND endTime <= :endTime+    GROUP BY day+    ORDER BY day ASC+""")+    suspend fun getDailyAvgs(+        type: RecordType,+        startTime: kotlin.time.Instant,+        endTime: kotlin.time.Instant+    ): List<DailySum>++    @Query("""+    SELECT +        strftime('%Y-%m-%d %H:00', startTime / 1000, 'unixepoch', 'localtime') AS hourBlock, +        AVG(value) AS totalValue,+        AVG(secondaryValue) AS totalValue2+    FROM Record +    WHERE type = :type +      AND startTime >= :startTime +      AND endTime <= :endTime+    GROUP BY hourBlock+    ORDER BY hourBlock ASC+""")+    suspend fun getHourlyAvgs(+        type: RecordType,+        startTime: Long,+        endTime: Long+    ): List<HourlySum>+     // Helper data class to catch the results     data class DailySum(         val day: String, // Format: YYYY-MM-DD
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 2325de0579..c2e24f90ca 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -1,5 +1,6 @@ package com.vayunmathur.health.ui +import android.util.Range import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box@@ -107,6 +108,7 @@ enum class HealthMetricConfig(     RESTING_HEART_RATE("Resting Heart Rate", RecordType.RestingHeartRate, "bpm", 60.0, isLineChart = true),     OXYGEN_SATURATION("Oxygen Saturation", RecordType.OxygenSaturation, "%", 95.0, isLineChart = true, useDecimals = true),     HRV("Heart Rate Variability", RecordType.HeartRateVariabilityRmssd, "ms", 50.0, isLineChart = true, useDecimals = true),+    HEART_RATE("Heart Rate", RecordType.HeartRate, "bpm", 100.0, isLineChart = true),      // Physical Measurements     HEIGHT("Height", RecordType.Height, "cm", 175.0, isLineChart = true, useDecimals = true),@@ -123,6 +125,7 @@ data class MetricDashboardData(     val secondaryAverage: Double? = null,     val chartData: List<Pair<String, Double?>> = emptyList(),     val secondaryChartData: List<Pair<String, Double?>>? = null,+    val primaryRange: ClosedFloatingPointRange<Double>? = null,     val historyItems: List<HistoryItem> = emptyList(),     val totalBarCount: Int = 0 )@@ -142,7 +145,7 @@ fun BarChartDetails(     backStack: NavBackStack<Route>,     config: HealthMetricConfig ) {-    var selectedTab by remember { mutableIntStateOf(1) }+    var selectedTab by remember { mutableIntStateOf(if(config == HealthMetricConfig.HEART_RATE) 0 else 1) }     val tabs = listOf("Day", "Week", "Month", "Year")      var anchorDate by remember { mutableStateOf(Clock.System.todayIn(TimeZone.currentSystemDefault())) }@@ -175,20 +178,12 @@ fun BarChartDetails(          // Both functions now return List<Pair<Double?, Double?>>         val rawPairs = if (config.isLineChart) {-            HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType).mapIndexed { idx, it ->-                Tuple3(-                    idx.toLong(),-                    it.first,-                    it.second-                )-            }+            HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType)         } else {             HealthAPI.getListOfSums(config.recordType, startTime, endTimeNow, periodType)         }         val rawPairsHistory = if (config.isLineChart) {-            HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType2).mapIndexed { idx, it ->-                Tuple3(idx, it.first, it.second)-            }+            HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType2)         } else {             HealthAPI.getListOfSums(config.recordType, startTime, endTimeNow, periodType2)         }@@ -198,20 +193,19 @@ fun BarChartDetails(             rawPairs.mapIndexed { i, p -> i.toString() to p.third }         } else null -        val history = if(selectedTab != 0) rawPairsHistory.mapIndexedNotNull { index, triple ->+        val history = if(selectedTab != 0) rawPairsHistory.mapIndexed { index, triple ->             val label = when (selectedTab) {                 0 -> ""                 1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.lowercase().replaceFirstChar { it.uppercase() }                 2 -> "Day ${index + 1}"                 else -> "Month ${index + 1}"             }-            if(triple.second == null) return@mapIndexedNotNull null             HistoryItem(                 label = label,-                value = triple.second!!,+                value = triple.second,                 secondaryValue = if (config.isDualSeries) triple.third else null,                 unit = config.unit,-                isGoalMet = (triple.second ?: 0.0) >= config.dailyGoal,+                isGoalMet = triple.second >= config.dailyGoal,                 useDecimals = config.useDecimals             )         }.reversed() else listOf()@@ -226,7 +220,8 @@ fun BarChartDetails(             chartData = mappedChart,             secondaryChartData = mappedSecondaryChart,             historyItems = history,-            totalBarCount = rawPairs.size+            totalBarCount = rawPairs.size,+            primaryRange = mappedChart.minOfOrNull { it.second }?.rangeTo(mappedChart.maxOf { it.second })         )     } @@ -239,13 +234,20 @@ fun BarChartDetails(         }     ) { padding ->         Column(modifier = Modifier.padding(padding).fillMaxSize()) {-            SecondaryTabRow(selectedTabIndex = selectedTab, divider = {}) {-                tabs.forEachIndexed { index, title ->-                    Tab(-                        selected = selectedTab == index,-                        onClick = { selectedTab = index },-                        text = { Text(title, fontWeight = if (selectedTab == index) FontWeight.Bold else FontWeight.Normal) }-                    )+            if(config != HealthMetricConfig.HEART_RATE) {+                SecondaryTabRow(selectedTabIndex = selectedTab, divider = {}) {+                    tabs.forEachIndexed { index, title ->+                        Tab(+                            selected = selectedTab == index,+                            onClick = { selectedTab = index },+                            text = {+                                Text(+                                    title,+                                    fontWeight = if (selectedTab == index) FontWeight.Bold else FontWeight.Normal+                                )+                            }+                        )+                    }                 }             } @@ -302,7 +304,9 @@ fun BarChartDetails(                      Row(verticalAlignment = Alignment.Bottom) {                         val formatVal = { v: Double -> if (config.useDecimals) String.format("%.1f", v) else String.format("%,d", v.toLong()) }-                        val avgString = if (dataState.secondaryAverage != null && config.isDualSeries) {+                        val avgString = if(config == HealthMetricConfig.HEART_RATE) {+                            "${formatVal(dataState.primaryRange?.start ?: 0.0)} - ${formatVal(dataState.primaryRange?.endInclusive ?: 0.0)}"+                        } else if (dataState.secondaryAverage != null && config.isDualSeries) {                             "${formatVal(dataState.dailyAverage)}/${formatVal(dataState.secondaryAverage!!)}"                         } else {                             formatVal(dataState.dailyAverage)
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 24749c5f99..004ee6fe53 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt@@ -180,7 +180,7 @@ fun MainPage(backStack: NavBackStack<Route>) {             }              Distance(backStack,distanceToday)-            HeartRate(heartRateMaxToday, heartRateMinToday)+            HeartRate(backStack, heartRateMaxToday, heartRateMinToday)             // TODO: add this back             //Sleep(aggregates?.get(SleepSessionRecord.SLEEP_DURATION_TOTAL)?.toKotlinDuration()?.inWholeMinutes ?: 0) @@ -374,8 +374,10 @@ fun Distance(backStack: NavBackStack<Route>, km: Double) { }  @Composable-fun HeartRate(max: Long, min: Long) {-    GenericCard("Heart rate", null, "bpm", if(max > 0) "$min-$max" else "--", "Today") {+fun HeartRate(backStack: NavBackStack<Route>, max: Long, min: Long) {+    GenericCard("Heart rate", null, "bpm", if(max > 0) "$min-$max" else "--", "Today", onClick = {+        backStack.add(Route.BarChartDetails(HealthMetricConfig.HEART_RATE))+    }) {         ProgressBarGraphic(R.drawable.baseline_favorite_24, max.toFloat(), 200f, Color(0xFFF44336))     } }