diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index 73332b8a..801b95b0 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -53,6 +53,7 @@ class PulseLoopApplication : Application() { }, ) WidgetRefreshWorker.schedule(this) + appScope.launch { runCatching { com.pulseloop.service.StepCalibration.sample(this@PulseLoopApplication) } } // Scheduled backups: the daily worker, plus a catch-up on start when one is overdue. com.pulseloop.data.AutoBackup.schedule(this) appScope.launch { diff --git a/app/src/main/java/com/pulseloop/data/DataArchive.kt b/app/src/main/java/com/pulseloop/data/DataArchive.kt index 54daf5d6..8b7a1b51 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchive.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchive.kt @@ -49,6 +49,11 @@ data class PulseArchive( val foodPreferences: List = emptyList(), /** Drinks (v32). */ val drinks: List = emptyList(), + /** Logged periods (v34). */ + val periods: List = emptyList(), + /** Medications and supplements, and answered doses (v35). */ + val meds: List = emptyList(), + val medDoses: List = emptyList(), ) @Serializable data class FoodPreferenceDTO( @@ -58,6 +63,15 @@ data class PulseArchive( val timesAgreed: Int = 1, val createdAt: Long, val updatedAt: Long, ) +@Serializable data class MedDTO( + val id: String, val name: String, val dose: String? = null, val kind: String = "medication", + val timesCsv: String, val active: Boolean = true, val createdAt: Long, +) + +@Serializable data class MedDoseDTO(val id: String, val medId: String, val day: Long, val time: String, val status: String, val at: Long) + +@Serializable data class PeriodDTO(val id: String, val startDay: Long, val endDay: Long? = null, val createdAt: Long) + @Serializable data class DrinkEntryDTO( val id: String, val timestamp: Long, val day: Long, val type: String, val volumeMl: Double, val abvPct: Double, val grams: Double, val kcal: Double, diff --git a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt index 5925ca9a..ba2a5c90 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt @@ -329,6 +329,16 @@ object DataArchiveService { timesAgreed = c.intOrNull("timesAgreed") ?: 1, createdAt = c.long("createdAt"), updatedAt = c.long("updatedAt"), ) }, + meds = collect("meds") { c -> + MedDTO(id = c.str("id"), name = c.str("name"), dose = c.strOrNull("dose"), kind = c.str("kind"), + timesCsv = c.str("timesCsv"), active = (c.intOrNull("active") ?: 1) == 1, createdAt = c.long("createdAt")) + }, + medDoses = collect("med_doses") { c -> + MedDoseDTO(id = c.str("id"), medId = c.str("medId"), day = c.long("day"), time = c.str("time"), status = c.str("status"), at = c.long("at")) + }, + periods = collect("periods") { c -> + PeriodDTO(id = c.str("id"), startDay = c.long("startDay"), endDay = c.longOrNull("endDay"), createdAt = c.long("createdAt")) + }, drinks = collect("drink_entries") { c -> DrinkEntryDTO( id = c.str("id"), timestamp = c.long("timestamp"), day = c.long("day"), type = c.str("type"), @@ -433,6 +443,15 @@ object DataArchiveService { timesAgreed = f.timesAgreed, createdAt = f.createdAt, updatedAt = f.updatedAt, )) } + for (m in archive.meds) { + db.medDao().upsert(MedEntity(id = m.id, name = m.name, dose = m.dose, kind = m.kind, timesCsv = m.timesCsv, active = m.active, createdAt = m.createdAt)) + } + for (d in archive.medDoses) { + db.medDao().upsertDose(MedDoseEntity(id = d.id, medId = d.medId, day = d.day, time = d.time, status = d.status, at = d.at)) + } + for (p in archive.periods) { + db.periodDao().upsert(PeriodEntity(id = p.id, startDay = p.startDay, endDay = p.endDay, createdAt = p.createdAt)) + } for (d in archive.drinks) { db.drinkDao().upsert(DrinkEntryEntity( id = d.id, timestamp = d.timestamp, day = d.day, type = d.type, volumeMl = d.volumeMl, diff --git a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt index 6781c9e2..e75d500c 100644 --- a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt +++ b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt @@ -49,8 +49,11 @@ import com.pulseloop.data.entity.* FoodPreferenceEntity::class, DrinkEntryEntity::class, FindingEntity::class, + PeriodEntity::class, + MedEntity::class, + MedDoseEntity::class, ], - version = 33, + version = 35, exportSchema = false, ) abstract class PulseLoopDatabase : RoomDatabase() { @@ -81,6 +84,10 @@ abstract class PulseLoopDatabase : RoomDatabase() { abstract fun drinkDao(): DrinkDao /** "What changed" findings (v33). */ abstract fun findingDao(): FindingDao + /** Logged periods for cycle tracking (v34). */ + abstract fun periodDao(): PeriodDao + /** Medications and supplements, and answered doses (v35). */ + abstract fun medDao(): MedDao abstract fun coachSummaryDao(): CoachSummaryDao abstract fun wearableLogDao(): WearableLogDao abstract fun rawPacketDao(): RawPacketDao @@ -133,6 +140,8 @@ abstract class PulseLoopDatabase : RoomDatabase() { "food_preferences", "drink_entries", "findings", + "periods", + "meds", "med_doses", ) @Volatile private var INSTANCE: PulseLoopDatabase? = null @@ -613,6 +622,31 @@ abstract class PulseLoopDatabase : RoomDatabase() { } } + /** v33 → v34: logged periods for cycle tracking. */ + private val MIGRATION_33_34 = object : Migration(33, 34) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `periods` (`id` TEXT NOT NULL, `startDay` INTEGER NOT NULL, " + + "`endDay` INTEGER, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))" + ) + } + } + + /** v34 → v35: medications and supplements, and their answered doses. */ + private val MIGRATION_34_35 = object : Migration(34, 35) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `meds` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `dose` TEXT, `kind` TEXT NOT NULL, " + + "`timesCsv` TEXT NOT NULL, `active` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))" + ) + db.execSQL( + "CREATE TABLE IF NOT EXISTS `med_doses` (`id` TEXT NOT NULL, `medId` TEXT NOT NULL, `day` INTEGER NOT NULL, " + + "`time` TEXT NOT NULL, `status` TEXT NOT NULL, `at` INTEGER NOT NULL, PRIMARY KEY(`id`))" + ) + db.execSQL("CREATE INDEX IF NOT EXISTS `index_med_doses_day` ON `med_doses` (`day`)") + } + } + private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) { db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`") db.execSQL( @@ -712,6 +746,8 @@ abstract class PulseLoopDatabase : RoomDatabase() { MIGRATION_30_31, MIGRATION_31_32, MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, ) // Downgrades only (sideloading an older APK). A blanket destructive // fallback would silently wipe every measurement, sleep session, and diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 1a2b889b..947fca8b 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -980,3 +980,54 @@ interface FindingDao { @Upsert suspend fun upsertAll(rows: List) } + +@Dao +interface PeriodDao { + @Query("SELECT * FROM periods ORDER BY startDay DESC") + suspend fun all(): List + + @Query("SELECT * FROM periods ORDER BY startDay DESC") + fun allFlow(): Flow> + + @Upsert + suspend fun upsert(p: PeriodEntity) + + @Query("DELETE FROM periods WHERE id = :id") + suspend fun delete(id: String) +} + +@Dao +interface MedDao { + @Query("SELECT * FROM meds ORDER BY active DESC, name ASC") + fun allFlow(): Flow> + + @Query("SELECT * FROM meds WHERE active = 1") + suspend fun active(): List + + @Query("SELECT * FROM meds") + suspend fun all(): List + + @Upsert + suspend fun upsert(m: MedEntity) + + @Query("DELETE FROM meds WHERE id = :id") + suspend fun delete(id: String) + + @Query("SELECT * FROM med_doses WHERE day >= :fromDay") + fun dosesSinceFlow(fromDay: Long): Flow> + + @Query("SELECT * FROM med_doses WHERE day >= :fromDay") + suspend fun dosesSince(fromDay: Long): List + + @Query("SELECT * FROM med_doses") + suspend fun allDoses(): List + + @Upsert + suspend fun upsertDose(d: MedDoseEntity) + + @Query("DELETE FROM med_doses WHERE id = :id") + suspend fun deleteDose(id: String) + + @Query("DELETE FROM med_doses WHERE medId = :medId") + suspend fun deleteDosesFor(medId: String) +} diff --git a/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt b/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt index 44000752..0720dfbe 100644 --- a/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt +++ b/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt @@ -432,3 +432,40 @@ data class FindingEntity( val algorithmVersion: Int, val createdAt: Long = System.currentTimeMillis(), ) + +/** A logged period (service/Cycle.kt); days are epoch days in the user's calendar. */ +@Entity(tableName = "periods") +data class PeriodEntity( + @PrimaryKey val id: String = java.util.UUID.randomUUID().toString(), + val startDay: Long, + val endDay: Long? = null, + val createdAt: Long = System.currentTimeMillis(), +) + +/** A medication or supplement on a daily schedule (service/Meds.kt). [timesCsv] is "08:00,20:00". */ +@Entity(tableName = "meds") +data class MedEntity( + @PrimaryKey val id: String = java.util.UUID.randomUUID().toString(), + val name: String, + val dose: String? = null, + /** "medication" or "supplement". */ + val kind: String = "medication", + val timesCsv: String, + val active: Boolean = true, + val createdAt: Long = System.currentTimeMillis(), +) + +/** One answered dose: taken or skipped. A past dose with no row is missed; nothing is stored for it. */ +@Entity(tableName = "med_doses", indices = [Index("day")]) +data class MedDoseEntity( + @PrimaryKey val id: String, + val medId: String, + /** Epoch day of the scheduled dose. */ + val day: Long, + val time: String, + /** "taken" or "skipped". */ + val status: String, + val at: Long = System.currentTimeMillis(), +) { + companion object { fun idFor(medId: String, day: Long, time: String) = "$medId:$day:$time" } +} diff --git a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt index d954cdcd..22155672 100644 --- a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt +++ b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt @@ -72,6 +72,12 @@ class GuidancePrefs(context: Context) { internal var lastInactivityAt: Long get() = p.getLong("lastInactivityAt", 0L) set(v) = p.edit().putLong("lastInactivityAt", v).apply() + var medReminders: Boolean + get() = p.getBoolean("medReminders", true) + set(v) = p.edit().putBoolean("medReminders", v).apply() + internal var remindedDoses: Set + get() = p.getStringSet("remindedDoses", emptySet()).orEmpty() + set(v) = p.edit().putStringSet("remindedDoses", v).apply() internal var lastProgressDay: String? get() = p.getString("lastProgressDay", null) set(v) = p.edit().putString("lastProgressDay", v).apply() @@ -102,6 +108,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork val local = Instant.ofEpochMilli(now).atZone(zone) val today = local.toLocalDate() val inputs = runCatching { ReadinessRepository.loadInputs(db, now, zone) }.getOrNull() ?: return Result.success() + runCatching { com.pulseloop.service.StepCalibration.sample(ctx, now, zone) } // Keep the "what changed" log current even when the screen isn't opened. runCatching { com.pulseloop.service.FindingsRepository.refresh(db, now, zone) } @@ -189,6 +196,22 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork } } + // 8. Medication doses: once per dose, from its time until it would count as missed. + runCatching { + val meds = db.medDao().active() + if (meds.isNotEmpty() && prefs.medReminders) { + val answers = db.medDao().dosesSince(today.toEpochDay()) + val due = com.pulseloop.service.Meds.dosesOn(today, meds, answers, local.toLocalDateTime()) + .filter { it.state == com.pulseloop.service.Meds.State.DUE && !local.toLocalTime().isBefore(java.time.LocalTime.parse(it.time)) } + val fresh = due.filter { it.id !in prefs.remindedDoses } + if (fresh.isNotEmpty()) { + val names = fresh.joinToString(", ") { it.med.name + (it.med.dose?.let { d -> " $d" } ?: "") } + notify(ctx, ID_MEDS, "Time for ${fresh.first().med.name}" + if (fresh.size > 1) " and more" else "", + "$names. Open PulseLoop to mark it taken or skipped.") + prefs.remindedDoses = (prefs.remindedDoses + fresh.map { it.id }).toList().takeLast(50).toSet() + } + } + } // 4. Meal reminder — optional, and only while nothing has been logged for that meal. if (prefs.mealReminder && db.userGoalDao().get()?.nutritionEnabled == true) { val meals = db.mealEntryDao().byDay(todayStart).map { it.timestamp } @@ -214,6 +237,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork private const val ID_BATTERY = 3005 private const val ID_INACTIVE = 3006 private const val ID_PROGRESS = 3007 + private const val ID_MEDS = 3008 /** Minutes from [now] until [target] later today or, if already past, tomorrow. */ internal fun minutesUntil(now: LocalTime, target: LocalTime): Int { diff --git a/app/src/main/java/com/pulseloop/service/ActivityDetection.kt b/app/src/main/java/com/pulseloop/service/ActivityDetection.kt new file mode 100644 index 00000000..44dc566f --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/ActivityDetection.kt @@ -0,0 +1,166 @@ +package com.pulseloop.service + +import android.content.Context +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.ring.MeasurementKind +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId + +/** + * Workouts and naps the ring's data suggests, offered as proposals the user confirms, edits or + * discards (OpenStrap Edge's rule): detection never writes a workout on its own, and the user's + * answer always wins over a later re-detection of the same stretch. + */ +object ActivityDetection { + + data class Proposal(val kind: Kind, val startAt: Long, val endAt: Long, val detail: String) { + enum class Kind { WALK, RUN, CARDIO, NAP } + val key: String get() = "${kind.name}:$startAt:$endAt" + val minutes: Int get() = ((endAt - startAt) / 60_000L).toInt() + } + + private const val WINDOW = 15 * 60_000L + const val WALK_STEPS_PER_15 = 1200 // ~80 steps a minute + const val RUN_STEPS_PER_15 = 2100 // ~140 steps a minute + + /** + * Walks and runs: runs of at least two consecutive 15-minute windows of brisk stepping. + * [steps] are (start ms, steps) buckets of any length; they're summed into 15-minute windows. + */ + fun stepSessions(steps: List>): List { + val windows = steps.groupBy { it.first / WINDOW * WINDOW }.mapValues { (_, v) -> v.sumOf { it.second } }.toSortedMap() + val out = mutableListOf() + var runStart: Long? = null; var last = 0L; var total = 0; var fast = 0; var count = 0 + fun close() { + val s = runStart ?: return + if (count >= 2) { + val kind = if (fast * 2 > count) Proposal.Kind.RUN else Proposal.Kind.WALK + out += Proposal(kind, s, last + WINDOW, "%,d steps".format(total)) + } + runStart = null; total = 0; fast = 0; count = 0 + } + for ((start, n) in windows) { + if (n >= WALK_STEPS_PER_15 && (runStart == null || start == last + WINDOW)) { + if (runStart == null) runStart = start + last = start; total += n; count++; if (n >= RUN_STEPS_PER_15) fast++ + } else { + close() + if (n >= WALK_STEPS_PER_15) { runStart = start; last = start; total = n; count = 1; if (n >= RUN_STEPS_PER_15) fast = 1 } + } + } + close() + return out + } + + /** + * Cardio without many steps (cycling, a gym session): at least 20 minutes of readings at 40 % + * or more of heart-rate reserve above the user's quiet level, with gaps of at most 15 minutes. + */ + fun heartSessions(hr: List>, quiet: Double, hrMax: Double): List { + val threshold = quiet + 0.4 * (hrMax - quiet) + val out = mutableListOf() + var start: Long? = null; var last = 0L; var peak = 0.0 + fun close() { + val s = start ?: return + if (last - s >= 20 * 60_000L) out += Proposal(Proposal.Kind.CARDIO, s, last, "Heart rate up to ${peak.toInt()} bpm") + start = null; peak = 0.0 + } + for ((t, bpm) in hr.sortedBy { it.first }) { + if (bpm >= threshold) { + if (start != null && t - last > 15 * 60_000L) close() + if (start == null) start = t + last = t; peak = maxOf(peak, bpm) + } else if (start != null && t - last > 5 * 60_000L) close() + } + close() + return out + } + + /** + * Naps: between 11:00 and 19:00, at least 25 minutes where heart rate stays at or below the + * user's quiet level and the ring counted (almost) no steps. + */ + fun naps(hr: List>, steps: List>, quiet: Double, zone: ZoneId): List { + val out = mutableListOf() + var start: Long? = null; var last = 0L; var n = 0 + fun stepsBetween(a: Long, b: Long) = steps.filter { it.first in a..b }.sumOf { it.second } + fun close() { + val s = start ?: return + if (last - s >= 25 * 60_000L && n >= 4 && stepsBetween(s, last) < 60) { + out += Proposal(Proposal.Kind.NAP, s, last, "Heart rate stayed at your quiet level with no steps") + } + start = null; n = 0 + } + for ((t, bpm) in hr.sortedBy { it.first }) { + val h = Instant.ofEpochMilli(t).atZone(zone).hour + if (h in 11..18 && bpm <= quiet) { + if (start != null && t - last > 15 * 60_000L) close() + if (start == null) start = t + last = t; n++ + } else close() + } + close() + return out + } + + /** Proposals that overlap anything already recorded, or that the user already answered, are dropped. */ + fun open(proposals: List, recorded: List, answered: Set): List = + proposals.filter { p -> p.key !in answered && recorded.none { it.first < p.endAt && p.startAt < it.last } } + + // ── Persistence of answers ─────────────────────────────────────────────────────────────── + + private fun prefs(c: Context) = c.applicationContext.getSharedPreferences("activity_detection", Context.MODE_PRIVATE) + fun answered(c: Context): Set = prefs(c).getStringSet("answered", emptySet()).orEmpty() + fun answer(c: Context, p: Proposal) { + val keep = (answered(c) + p.key).sortedBy { it.substringAfter(':').substringBefore(':').toLongOrNull() ?: 0 }.takeLast(300).toSet() + prefs(c).edit().putStringSet("answered", keep).apply() + } + + /** Open proposals for the last [days] days. */ + suspend fun load(c: Context, db: PulseLoopDatabase, days: Long = 3, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): List { + val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + fun start(d: LocalDate) = d.atStartOfDay(zone).toInstant().toEpochMilli() + val from = start(today.minusDays(days - 1)) + val hr29 = db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, start(today.minusDays(29)), now) + .map { it.timestamp to it.value }.filter { it.second in 30.0..230.0 } + val inputs = ReadinessRepository.loadInputs(db, now, zone) + val nights = (inputs.history + listOfNotNull(inputs.lastNight)).map { it.startAt..it.endAt } + // Quiet level, as cardio load computes it. + val quietDays = hr29.filter { it.first < start(today) } + .groupBy { Instant.ofEpochMilli(it.first).atZone(zone).toLocalDate() } + .mapNotNull { (_, v) -> + CardioLoad.quietOfDay(v.filter { (t, _) -> Instant.ofEpochMilli(t).atZone(zone).hour in 8..21 && nights.none { t in it } }.map { it.second }) + } + val quiet = CardioLoad.quietLevel(quietDays) + val profile = db.userProfileDao().get() + val buckets = (0 until days).flatMap { db.activityBucketDao().byDay(start(today.minusDays(it))) } + .map { it.startEpoch to it.steps } + val recentHr = hr29.filter { it.first >= from && nights.none { n -> it.first in n } } + val proposals = buildList { + addAll(stepSessions(buckets.filter { it.first >= from })) + if (quiet != null) { + addAll(heartSessions(recentHr, quiet, CardioLoad.hrMax(profile?.age))) + addAll(naps(recentHr, buckets, quiet, zone)) + } + } + val sessions = db.activitySessionDao().recent(50).map { it.startedAt..(it.endedAt ?: it.startedAt) } + // A cardio stretch inside a walk or run is the same activity. + val stepRanges = proposals.filter { it.kind == Proposal.Kind.WALK || it.kind == Proposal.Kind.RUN }.map { it.startAt..it.endAt } + val deduped = proposals.filter { p -> p.kind != Proposal.Kind.CARDIO || stepRanges.none { it.first < p.endAt && p.startAt < it.last } } + return open(deduped, sessions + nights, answered(c)).sortedByDescending { it.startAt } + } +} + +/** Accept a proposal: a workout becomes a recorded activity; a nap ticks the day's "Daytime nap" tag. */ +suspend fun ActivityDetection.accept(c: Context, db: PulseLoopDatabase, p: ActivityDetection.Proposal, type: String) { + if (p.kind == ActivityDetection.Proposal.Kind.NAP) { + val zone = ZoneId.systemDefault() + val day = Instant.ofEpochMilli(p.startAt).atZone(zone).toLocalDate().atStartOfDay(zone).toInstant().toEpochMilli() + val tag = JournalInsights.Tag.NAP.key + db.journalDao().upsert(com.pulseloop.data.entity.JournalEntryEntity(com.pulseloop.data.entity.JournalEntryEntity.idFor(day, tag), day, tag)) + } else { + ManualActivityService.create(db, type, p.startAt, p.minutes.toDouble(), notes = "Detected by PulseLoop and confirmed") + } + answer(c, p) +} diff --git a/app/src/main/java/com/pulseloop/service/CardioLoad.kt b/app/src/main/java/com/pulseloop/service/CardioLoad.kt new file mode 100644 index 00000000..7b145e3c --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/CardioLoad.kt @@ -0,0 +1,94 @@ +package com.pulseloop.service + +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import kotlin.math.exp +import kotlin.math.roundToInt + +/** + * A day's cardio load from the ring's all-day heart rate, scored against the user's own quiet + * waking heart rate rather than a population resting value (OpenStrap Edge's "strain"): a fit + * person with a low resting HR gets the same credit for the same effort. Banister's TRIMP over + * heart-rate reserve, with each reading standing for the gap to the next (at most 30 minutes), + * which is what a ring sampling every 5–30 minutes can honestly support. A coarse daily figure, + * labelled as an estimate. + */ +object CardioLoad { + const val MIN_QUIET_DAYS = 3 + private const val MAX_GAP_MIN = 30.0 + + enum class Band(val label: String) { LIGHT("Light"), USUAL("Usual"), HIGH("High"), VERY_HIGH("Very high") } + + data class Result(val load: Int, val quietHr: Int, val usual: Int?, val band: Band?, val elevatedMinutes: Int) + + /** A day's quiet waking HR: the 20th percentile of its daytime readings outside sleep. */ + fun quietOfDay(daytime: List): Double? { + if (daytime.size < 12) return null + val s = daytime.sorted() + return s[(s.size * 0.2).toInt().coerceAtMost(s.size - 1)] + } + + /** The user's quiet level: the median of the last 28 days' daily quiet values, from 3 days on. */ + fun quietLevel(dailyQuiet: List): Double? { + val v = dailyQuiet.takeLast(28) + if (v.size < MIN_QUIET_DAYS) return null + val s = v.sorted(); val m = s.size / 2 + return if (s.size % 2 == 1) s[m] else (s[m - 1] + s[m]) / 2 + } + + fun hrMax(age: Int?): Double = 208 - 0.7 * (age ?: 35).coerceIn(15, 90) + + /** TRIMP-style load of one day's readings (timestamp ms → bpm, sorted), and minutes above quiet + 20 % reserve. */ + fun load(samples: List>, quiet: Double, hrMax: Double): Pair { + if (samples.size < 2 || hrMax <= quiet) return 0.0 to 0 + var trimp = 0.0 + var elevated = 0.0 + samples.zipWithNext().forEach { (a, b) -> + val minutes = ((b.first - a.first) / 60_000.0).coerceIn(0.0, MAX_GAP_MIN) + val reserve = ((a.second - quiet) / (hrMax - quiet)).coerceIn(0.0, 1.0) + if (reserve > 0) trimp += minutes * reserve * 0.64 * exp(1.92 * reserve) + if (reserve >= 0.2) elevated += minutes + } + return trimp to elevated.roundToInt() + } + + fun band(load: Double, usual: Double?): Band? { + if (usual == null || usual <= 0) return null + val r = load / usual + return when { + r < 0.5 -> Band.LIGHT + r <= 1.3 -> Band.USUAL + r <= 2.0 -> Band.HIGH + else -> Band.VERY_HIGH + } + } + + /** + * Today's load from up to 29 days of readings: quiet levels from the days before today, the + * user's usual load from those days too. [asleep] says whether a moment was inside a night. + */ + fun compute( + hr: List>, + asleep: (Long) -> Boolean, + today: LocalDate, + zone: ZoneId, + age: Int?, + ): Result? { + val byDay = hr.filter { it.second in 30.0..230.0 }.groupBy { Instant.ofEpochMilli(it.first).atZone(zone).toLocalDate() } + val days = byDay.keys.filter { it.isBefore(today) }.sorted() + val quietByDay = days.associateWith { d -> + quietOfDay(byDay.getValue(d).filter { (t, _) -> + val h = Instant.ofEpochMilli(t).atZone(zone).hour + h in 8..21 && !asleep(t) + }.map { it.second }) + } + val quiet = quietLevel(quietByDay.values.filterNotNull()) ?: return null + val max = hrMax(age) + val todaySamples = byDay[today].orEmpty().sortedBy { it.first } + val (todayLoad, elevated) = load(todaySamples, quiet, max) + val history = days.takeLast(28).map { load(byDay.getValue(it).sortedBy { s -> s.first }, quiet, max).first }.filter { it > 0 } + val usual = history.takeIf { it.size >= MIN_QUIET_DAYS }?.sorted()?.let { it[it.size / 2] } + return Result(todayLoad.roundToInt(), quiet.roundToInt(), usual?.roundToInt(), band(todayLoad, usual), elevated) + } +} diff --git a/app/src/main/java/com/pulseloop/service/Cycle.kt b/app/src/main/java/com/pulseloop/service/Cycle.kt new file mode 100644 index 00000000..b11b3b5d --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/Cycle.kt @@ -0,0 +1,55 @@ +package com.pulseloop.service + +import java.time.LocalDate +import java.time.temporal.ChronoUnit + +/** + * Cycle phase from the dates the user logs, nothing else (OpenStrap Edge's rule): the day of the + * cycle, whether a period is on, and when the next one is likely from this user's own cycle + * lengths. Deliberately no fertile window: a population-average estimate presented on a health + * screen would be read as a measurement. + */ +object Cycle { + enum class Phase(val label: String, val note: String) { + MENSTRUAL("Period", "Energy and sleep can dip; resting heart rate is often at its lowest."), + FOLLICULAR("Follicular", "After the period, until about two weeks before the next one."), + LUTEAL("Luteal", "The two weeks before a period: skin temperature and resting heart rate often run a little higher."), + LATE("Period later than usual", "Later than your usual cycle length. Log it when it starts."), + UNKNOWN("Cycle", "Log two periods to see phases and an estimate of the next one."), + } + + data class Period(val start: LocalDate, val end: LocalDate?) + + data class Status( + val cycleDay: Int, + val phase: Phase, + val inPeriod: Boolean, + val usualLength: Int?, + val nextStart: LocalDate?, + val daysToNext: Int?, + ) + + /** Cycle lengths between consecutive starts, keeping plausible ones (15–60 days). */ + fun lengths(periods: List): List = + periods.map { it.start }.distinct().sorted().zipWithNext { a, b -> ChronoUnit.DAYS.between(a, b).toInt() } + .filter { it in 15..60 } + + fun status(periods: List, today: LocalDate): Status? { + val past = periods.filter { !it.start.isAfter(today) }.sortedBy { it.start } + val last = past.lastOrNull() ?: return null + val day = ChronoUnit.DAYS.between(last.start, today).toInt() + 1 + // A period with no end logged is taken as on for up to 7 days. + val inPeriod = last.end?.let { !today.isAfter(it) } ?: (day <= 7) + val usual = lengths(past).takeLast(6).sorted().takeIf { it.isNotEmpty() }?.let { it[it.size / 2] } + val next = usual?.let { last.start.plusDays(it.toLong()) } + val toNext = next?.let { ChronoUnit.DAYS.between(today, it).toInt() } + val phase = when { + inPeriod -> Phase.MENSTRUAL + toNext == null -> Phase.UNKNOWN + toNext < 0 -> Phase.LATE + toNext <= 13 -> Phase.LUTEAL + else -> Phase.FOLLICULAR + } + return Status(day, phase, inPeriod, usual, next, toNext) + } +} diff --git a/app/src/main/java/com/pulseloop/service/GpxExport.kt b/app/src/main/java/com/pulseloop/service/GpxExport.kt new file mode 100644 index 00000000..dfabd054 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/GpxExport.kt @@ -0,0 +1,53 @@ +package com.pulseloop.service + +import android.content.Context +import android.net.Uri +import androidx.core.content.FileProvider +import com.pulseloop.data.entity.ActivityGpsPointEntity +import com.pulseloop.data.entity.ActivitySessionEntity +import java.io.File +import java.time.Instant +import java.time.format.DateTimeFormatter + +/** + * GPX 1.1 for a workout's route, so it can go to any map or training app, not only Strava. + * Only accepted points (the recorder's own filter) are written, in time order, with elevation and + * time where known; heart rate rides in the Garmin TrackPointExtension that most apps read. + */ +object GpxExport { + private fun esc(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) + + fun build(session: ActivitySessionEntity, points: List, name: String, heartRate: List> = emptyList()): String? { + val kept = points.filter { it.accepted }.sortedBy { it.timestamp } + if (kept.isEmpty()) return null + val iso = DateTimeFormatter.ISO_INSTANT + val hr = heartRate.sortedBy { it.first } + fun hrAt(t: Long): Int? = hr.lastOrNull { it.first <= t && t - it.first <= 30_000L }?.second?.toInt() + return buildString { + append("""""").append('\n') + append("""""").append('\n') + append(" ").append(esc(name)).append("\n") + append(" ").append(esc(name)).append("").append(esc(session.type)).append("\n") + for (p in kept) { + append(" ") + p.altitude?.let { append("").append("%.1f".format(java.util.Locale.US, it)).append("") } + append("") + hrAt(p.timestamp)?.let { append("").append(it).append("") } + append("\n") + } + append(" \n\n") + } + } + + /** Write the GPX to the cache and return a shareable content URI, or null without a route. */ + fun share(context: Context, session: ActivitySessionEntity, points: List, name: String, heartRate: List>): Uri? { + val text = build(session, points, name, heartRate) ?: return null + val stamp = java.text.SimpleDateFormat("yyyy-MM-dd-HHmm", java.util.Locale.US).format(java.util.Date(session.startedAt)) + val file = File(context.cacheDir, "pulseloop-${session.type}-$stamp.gpx") + file.writeText(text) + return FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file) + } +} diff --git a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt index b1dabe8f..0de90fda 100644 --- a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt +++ b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt @@ -54,6 +54,32 @@ object MindfulSessions { prefs(c).edit().putString("sessions", arr.toString()).apply() } + /** + * What sessions do for HRV, measured honestly: readings in the two hours after a session + * against the two hours before it, never during it (slow breathing raises HRV mechanically + * while it lasts, so in-session readings would flatter every session — OpenStrap Edge's rule). + * Null until three sessions have readings on both sides. + */ + data class Effect(val sessions: Int, val hrvChangePct: Int) + + fun effectFrom(pairs: List, List>>): Effect? { + fun med(v: List) = v.sorted().let { s -> if (s.size % 2 == 1) s[s.size / 2] else (s[s.size / 2 - 1] + s[s.size / 2]) / 2 } + val changes = pairs.filter { (b, a) -> b.isNotEmpty() && a.isNotEmpty() } + .mapNotNull { (b, a) -> med(b).takeIf { it > 0 }?.let { base -> (med(a) - base) / base * 100 } } + if (changes.size < 3) return null + return Effect(changes.size, med(changes).roundToInt()) + } + + suspend fun effect(c: Context, db: PulseLoopDatabase): Effect? { + val window = 2 * 3_600_000L + val pairs = all(c).filter { it.endAt > System.currentTimeMillis() - 60L * 86_400_000L && it.endAt + window < System.currentTimeMillis() }.map { s -> + val before = db.measurementDao().rangeReal(MeasurementKind.HRV.name, s.startAt - window, s.startAt - 1).map { it.value }.filter { it > 0 } + val after = db.measurementDao().rangeReal(MeasurementKind.HRV.name, s.endAt + 1, s.endAt + window).map { it.value }.filter { it > 0 } + before to after + } + return effectFrom(pairs) + } + /** * Saves a finished session with the heart rate the ring recorded during it, and ticks the * day's "Meditation or relaxing" journal tag so its effect on the night shows up. @@ -99,6 +125,8 @@ object HealthInsightsRepository { val hrToday: List, val sleepWindows: List, val workoutWindows: List, + /** Today's cardio load against the user's quiet waking HR; null until 3 days of data. */ + val cardioLoad: CardioLoad.Result? = null, ) private const val DAY = 86_400_000L @@ -214,7 +242,15 @@ object HealthInsightsRepository { .filter { it.statusRaw == "finished" && (it.endedAt ?: 0) >= dayStart - 6 * 3_600_000L } .map { it.startedAt..(it.endedAt ?: it.startedAt) } - return Snapshot(nights, need, debt, radar, todayStress, resilience, bodyClock, cardio, areas, habits, hrToday, sleepWindows, workoutWindows) + // Cardio load: 29 days of all-day HR, sleep excluded from the quiet level. + val hr29 = db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, start(today.minusDays(29)), now) + .map { it.timestamp to it.value } + val nightRanges = nights.map { it.startAt..it.endAt } + val cardioLoad = runCatching { + CardioLoad.compute(hr29, { t -> nightRanges.any { t in it } }, today, zone, profile?.age) + }.getOrNull() + + return Snapshot(nights, need, debt, radar, todayStress, resilience, bodyClock, cardio, areas, habits, hrToday, sleepWindows, workoutWindows, cardioLoad) } // ── Trends ─────────────────────────────────────────────────────────────── diff --git a/app/src/main/java/com/pulseloop/service/Meds.kt b/app/src/main/java/com/pulseloop/service/Meds.kt new file mode 100644 index 00000000..66744888 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/Meds.kt @@ -0,0 +1,54 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.MedDoseEntity +import com.pulseloop.data.entity.MedEntity +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime + +/** + * Medications and supplements: a daily schedule and one answer per dose (OpenStrap Edge's model). + * Only a past dose that was neither taken nor skipped counts as missed, so a skipped dose the + * user decided on is never reported as forgotten. No interaction checking, on purpose: that + * belongs with a pharmacist, not an app that can't see the whole picture. + */ +object Meds { + enum class State(val label: String) { TAKEN("Taken"), SKIPPED("Skipped"), DUE("Due"), MISSED("Missed"), LATER("Later") } + + data class Dose(val med: MedEntity, val day: LocalDate, val time: String, val state: State) { + val id: String get() = MedDoseEntity.idFor(med.id, day.toEpochDay(), time) + } + + /** A dose counts as missed this long after its time with no answer. */ + const val MISSED_AFTER_MIN = 120L + + fun times(m: MedEntity): List = + m.timesCsv.split(',').map { it.trim() }.filter { runCatching { LocalTime.parse(it) }.isSuccess }.distinct().sorted() + + fun dosesOn(day: LocalDate, meds: List, answers: List, now: LocalDateTime): List { + val byId = answers.associateBy { it.id } + return meds.filter { it.active }.flatMap { m -> + times(m).map { t -> + val at = day.atTime(LocalTime.parse(t)) + val answer = byId[MedDoseEntity.idFor(m.id, day.toEpochDay(), t)]?.status + val state = when { + answer == "taken" -> State.TAKEN + answer == "skipped" -> State.SKIPPED + now.isBefore(at.minusMinutes(60)) -> State.LATER + now.isAfter(at.plusMinutes(MISSED_AFTER_MIN)) -> State.MISSED + else -> State.DUE + } + Dose(m, day, t, state) + } + }.sortedBy { it.time } + } + + /** Share of scheduled doses taken over the [days] completed days before [today], or null with none scheduled. */ + fun adherence(m: MedEntity, answers: List, today: LocalDate, days: Int = 7): Int? { + val since = maxOf(today.minusDays(days.toLong()).toEpochDay(), java.time.Instant.ofEpochMilli(m.createdAt).atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay()) + val scheduled = (since until today.toEpochDay()).sumOf { times(m).size.toLong() } + if (scheduled <= 0) return null + val taken = answers.count { it.medId == m.id && it.status == "taken" && it.day in since until today.toEpochDay() } + return (taken * 100 / scheduled).toInt() + } +} diff --git a/app/src/main/java/com/pulseloop/service/ScoresContext.kt b/app/src/main/java/com/pulseloop/service/ScoresContext.kt index d29c95bd..7e485151 100644 --- a/app/src/main/java/com/pulseloop/service/ScoresContext.kt +++ b/app/src/main/java/com/pulseloop/service/ScoresContext.kt @@ -27,6 +27,14 @@ data class ScoresContext( /** Symptom Radar: "No signs", "Minor signs" or "Major signs" of strain, with the flagged signals. */ val symptomRadar: String? = null, val symptomRadarSignals: List = emptyList(), + /** From the periods the user logged, when they track their cycle; no fertility estimate. */ + val cycleDay: Int? = null, + val cyclePhase: String? = null, + /** Today's cardio load against the user's quiet waking heart rate, and its band. */ + val cardioLoad: Int? = null, + val cardioLoadBand: String? = null, + /** Today's scheduled medications and supplements with their state ("Vitamin D 08:00: taken"). */ + val medsToday: List = emptyList(), val note: String = "Scores are PulseLoop estimates from ring data compared with the user's own baseline, not medical measurements.", ) { /** Short stable string for coach-summary regeneration signatures. */ @@ -43,7 +51,21 @@ data class ScoresContext( sleepDebtLevel = h.debt?.level?.label, symptomRadar = h.radar?.level?.label, symptomRadarSignals = h.radar?.signals.orEmpty().filter { it.flagged }.map { it.detail }, - ) + cardioLoad = h.cardioLoad?.load, + cardioLoadBand = h.cardioLoad?.band?.label, + ).let { withLoad -> + val cycle = runCatching { + Cycle.status(db.periodDao().all().map { + Cycle.Period(java.time.LocalDate.ofEpochDay(it.startDay), it.endDay?.let { e -> java.time.LocalDate.ofEpochDay(e) }) + }, java.time.LocalDate.now()) + }.getOrNull() + val meds = runCatching { + val today = java.time.LocalDate.now() + Meds.dosesOn(today, db.medDao().active(), db.medDao().dosesSince(today.toEpochDay()), java.time.LocalDateTime.now()) + .map { "${it.med.name} ${it.time}: ${it.state.label.lowercase()}" } + }.getOrDefault(emptyList()) + withLoad.copy(cycleDay = cycle?.cycleDay, cyclePhase = cycle?.phase?.label, medsToday = meds) + } } private suspend fun buildScores(db: PulseLoopDatabase): ScoresContext? = runCatching { diff --git a/app/src/main/java/com/pulseloop/service/StepCalibration.kt b/app/src/main/java/com/pulseloop/service/StepCalibration.kt new file mode 100644 index 00000000..6cf448a1 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/StepCalibration.kt @@ -0,0 +1,102 @@ +package com.pulseloop.service + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import androidx.core.content.ContextCompat +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import org.json.JSONObject +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import kotlin.coroutines.resume + +/** + * Ring steps against the phone's own step counter (OpenStrap Edge calibrates ring steps per + * device family). Ring step counts are noisy, and a phone carried all day is a fair reference. + * The phone's hardware counter is read whenever the app or its hourly workers run; per-day phone + * totals are kept for 60 days. Shown as a comparison; applied only to Today's tile, and only when + * the user switches it on. + */ +object StepCalibration { + private const val PREFS = "step_calibration" + const val MIN_DAYS = 5 + const val MIN_STEPS = 3000 + + private fun prefs(c: Context) = c.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + + fun isApplied(c: Context) = prefs(c).getBoolean("apply", false) + fun setApplied(c: Context, on: Boolean) = prefs(c).edit().putBoolean("apply", on).apply() + + fun hasPermission(c: Context) = android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q || + ContextCompat.checkSelfPermission(c, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED + + /** Phone steps per day, as recorded so far. */ + fun phoneDays(c: Context): Map = runCatching { + val o = JSONObject(prefs(c).getString("days", "{}") ?: "{}") + o.keys().asSequence().associate { LocalDate.parse(it) to o.getInt(it) } + }.getOrDefault(emptyMap()) + + /** + * Add one counter reading. The counter counts since boot: a reading lower than the last one + * means a reboot, so the new reading itself is the steps since then. + */ + internal fun accumulate(days: Map, lastCounter: Long?, counter: Long, day: LocalDate): Map { + val delta = when { + lastCounter == null -> 0L + counter >= lastCounter -> counter - lastCounter + else -> counter + }.coerceIn(0L, 60_000L) + val out = days.toMutableMap() + out[day] = (out[day] ?: 0) + delta.toInt() + return out.filterKeys { it.isAfter(day.minusDays(60)) } + } + + /** Read the phone's step counter once and fold it into the day totals. Quietly does nothing without permission. */ + suspend fun sample(c: Context, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()) { + if (!hasPermission(c)) return + val sm = c.getSystemService(Context.SENSOR_SERVICE) as? SensorManager ?: return + val sensor = sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) ?: return + val value = withTimeoutOrNull(3_000L) { + suspendCancellableCoroutine { cont -> + val listener = object : SensorEventListener { + override fun onSensorChanged(e: SensorEvent) { + sm.unregisterListener(this) + if (cont.isActive) cont.resume(e.values[0].toLong()) + } + override fun onAccuracyChanged(s: Sensor?, a: Int) {} + } + sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL) + cont.invokeOnCancellation { sm.unregisterListener(listener) } + } + } ?: return + val p = prefs(c) + val last = p.getLong("lastCounter", -1L).takeIf { it >= 0 } + val day = Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + val days = accumulate(phoneDays(c), last, value, day) + val o = JSONObject(); days.forEach { (d, s) -> o.put(d.toString(), s) } + p.edit().putLong("lastCounter", value).putString("days", o.toString()).apply() + } + + data class Result(val factor: Double, val days: Int) + + /** + * Phone ÷ ring over completed days where both counted at least [MIN_STEPS]; the median of + * those ratios once there are [MIN_DAYS]. Null when there aren't, or when the ratio is + * implausible (under 0.6 or over 1.6: the phone wasn't carried, or the ring wasn't worn). + */ + fun factor(phone: Map, ring: Map, today: LocalDate): Result? { + val ratios = phone.filter { (d, p) -> d.isBefore(today) && p >= MIN_STEPS } + .mapNotNull { (d, p) -> ring[d]?.takeIf { it >= MIN_STEPS }?.let { p.toDouble() / it } } + .sorted() + if (ratios.size < MIN_DAYS) return null + val m = ratios[ratios.size / 2] + if (m !in 0.6..1.6) return null + return Result(m, ratios.size) + } +} diff --git a/app/src/main/java/com/pulseloop/service/WeeklyRecap.kt b/app/src/main/java/com/pulseloop/service/WeeklyRecap.kt new file mode 100644 index 00000000..1dcad309 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/WeeklyRecap.kt @@ -0,0 +1,100 @@ +package com.pulseloop.service + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Typeface +import android.net.Uri +import androidx.core.content.FileProvider +import com.pulseloop.data.PulseLoopDatabase +import java.io.File +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import kotlin.math.roundToInt + +/** + * A shareable picture of the last seven days: sleep, steps, resting heart rate and HRV against + * the week before, plus workouts (OpenStrap Edge's shareable weekly recap). Only the user's own + * averages, no scores, so nothing in it reads as a medical claim out of context. + */ +object WeeklyRecap { + + data class Row(val label: String, val value: String, val change: String?) + + data class Recap(val title: String, val rows: List) + + /** The rows, from this week's and last week's summaries. Pure, for testing. */ + fun rows(thisWeek: WeeklyReport.Week, lastWeek: WeeklyReport.Week?, workouts: Int): List = buildList { + thisWeek.avgAsleepMinutes?.let { m -> + val d = lastWeek?.avgAsleepMinutes?.let { m - it } + add(Row("Sleep a night", SleepFormat.duration(m), d?.let { if (kotlin.math.abs(it) < 5) "same as last week" else "${if (it > 0) "+" else "−"}${SleepFormat.duration(kotlin.math.abs(it))}" })) + } + thisWeek.avgSteps?.let { s -> + val d = lastWeek?.avgSteps?.takeIf { it > 0 }?.let { ((s - it) * 100.0 / it).roundToInt() } + add(Row("Steps a day", "%,d".format(s), d?.let { if (kotlin.math.abs(it) < 3) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)}%" })) + } + thisWeek.avgRestingHr?.let { r -> + val d = lastWeek?.avgRestingHr?.let { (r - it).roundToInt() } + add(Row("Resting heart rate", "${r.roundToInt()} bpm", d?.let { if (it == 0) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)} bpm" })) + } + thisWeek.avgHrv?.let { h -> + val d = lastWeek?.avgHrv?.takeIf { it > 0 }?.let { ((h - it) / it * 100).roundToInt() } + add(Row("HRV", "${h.roundToInt()} ms", d?.let { if (kotlin.math.abs(it) < 3) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)}%" })) + } + add(Row("Workouts", "$workouts", null)) + } + + suspend fun load(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): Recap { + val inputs = ReadinessRepository.loadInputs(db, now, zone) + val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + val all = inputs.history + listOfNotNull(inputs.lastNight) + val thisNights = all.filter { it.day.isAfter(today.minusDays(7)) } + val lastNights = all.filter { !it.day.isAfter(today.minusDays(7)) && it.day.isAfter(today.minusDays(14)) } + val days = db.activityDailyDao().recentReal(15) + fun steps(from: LocalDate, to: LocalDate) = days.filter { + val d = Instant.ofEpochMilli(it.date).atZone(zone).toLocalDate() + !d.isBefore(from) && !d.isAfter(to) && it.steps > 0 + }.map { it.steps } + val thisWeek = WeeklyReport.summarize(thisNights, steps(today.minusDays(6), today)) + val lastWeek = WeeklyReport.summarize(lastNights, steps(today.minusDays(13), today.minusDays(7))).takeIf { it.nights >= 3 } + val since = today.minusDays(6).atStartOfDay(zone).toInstant().toEpochMilli() + val workouts = db.activitySessionDao().recent(50).count { it.statusRaw == "finished" && it.startedAt >= since } + val fmt = DateTimeFormatter.ofPattern("d MMM") + return Recap("${today.minusDays(6).format(fmt)} – ${today.format(fmt)}", rows(thisWeek, lastWeek, workouts)) + } + + /** Draw the recap as a 1080×1350 PNG in the app's colours and return a shareable URI. */ + fun share(context: Context, recap: Recap): Uri { + val w = 1080; val h = 1350 + val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) + val c = Canvas(bmp) + c.drawColor(0xFF121214.toInt()) + val mono = Typeface.MONOSPACE + fun paint(color: Long, size: Float, bold: Boolean = false) = Paint(Paint.ANTI_ALIAS_FLAG).apply { + this.color = color.toInt(); textSize = size; typeface = Typeface.create(mono, if (bold) Typeface.BOLD else Typeface.NORMAL) + } + val mint = 0xFF43F3B7; val text = 0xFFF2F2F2; val muted = 0xFF7C7B82; val card = 0xFF1C1B1F + c.drawText("MY WEEK", 80f, 150f, paint(mint, 44f, bold = true)) + c.drawText(recap.title, 80f, 220f, paint(text, 64f, bold = true)) + var y = 300f + val cardPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = card.toInt() } + recap.rows.forEach { r -> + c.drawRoundRect(60f, y, (w - 60).toFloat(), y + 170f, 24f, 24f, cardPaint) + c.drawText(r.label.uppercase(), 100f, y + 55f, paint(muted, 30f)) + c.drawText(r.value, 100f, y + 130f, paint(text, 64f, bold = true)) + r.change?.let { ch -> + val p = paint(if (ch.startsWith("same")) muted else mint, 34f) + c.drawText(ch, w - 100f - p.measureText(ch), y + 125f, p) + } + y += 190f + } + c.drawText("PulseLoop · from my ring, compared with last week", 80f, h - 70f, paint(muted, 28f)) + val file = File(context.cacheDir, "pulseloop-week.png") + file.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) } + bmp.recycle() + return FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index c3d2951e..b207aac1 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -690,8 +690,16 @@ fun PulseLoopApp() { onBack = { navController.popBackStack() }, onBreathe = { navController.navigate("breathe") }, onWhatChanged = { navController.navigate("what_changed") }, + onCycle = { navController.navigate("cycle") }, + onMeds = { navController.navigate("meds") }, ) } + paddedComposable("meds") { + com.pulseloop.ui.screens.MedsScreen(onBack = { navController.popBackStack() }) + } + paddedComposable("cycle") { + com.pulseloop.ui.screens.CycleScreen(onBack = { navController.popBackStack() }) + } paddedComposable("what_changed") { com.pulseloop.ui.screens.WhatChangedScreen(onBack = { navController.popBackStack() }) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt index 8e1fb93c..c5479be6 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -63,6 +63,7 @@ import com.pulseloop.ui.theme.PulseColors import com.pulseloop.ui.viewmodels.ActivityViewModel import com.pulseloop.util.Formats import kotlinx.coroutines.launch +import com.pulseloop.service.accept import java.time.Instant import java.time.LocalDate import java.time.ZoneId @@ -190,6 +191,8 @@ fun ActivityScreen( } } + item { DetectedActivityCard() } + item { Row( Modifier @@ -934,3 +937,75 @@ private fun ActivityRecordsCard( /** How many activity records the list shows before asking (issue #70). */ private const val ACTIVITY_RECORDS_PAGE_SIZE = 50 + + +/** + * Workouts and naps the ring's data suggests, waiting for the user's answer. Nothing is recorded + * until they confirm; a discard is remembered so the same stretch isn't offered again. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun DetectedActivityCard() { + val context = androidx.compose.ui.platform.LocalContext.current + val db = remember { com.pulseloop.data.PulseLoopDatabase.getInstance(context) } + val scope = rememberCoroutineScope() + var tick by remember { mutableIntStateOf(0) } + val proposals by produceState>(emptyList(), tick) { + value = runCatching { com.pulseloop.service.ActivityDetection.load(context, db) }.getOrDefault(emptyList()) + } + if (proposals.isEmpty()) return + val fmt = remember { java.time.format.DateTimeFormatter.ofPattern("EEE HH:mm") } + val zone = remember { java.time.ZoneId.systemDefault() } + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text("DETECTED · REVIEW", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + proposals.forEach { p -> + val defaultType = when (p.kind) { + com.pulseloop.service.ActivityDetection.Proposal.Kind.WALK -> "walk" + com.pulseloop.service.ActivityDetection.Proposal.Kind.RUN -> "run" + else -> "cycle" + } + var type by remember(p.key) { mutableStateOf(defaultType) } + val isNap = p.kind == com.pulseloop.service.ActivityDetection.Proposal.Kind.NAP + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text( + (if (isNap) "Possible nap" else "Possible ${ActivityMeta.label(type).lowercase()}") + " · ${p.minutes} min", + fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, + ) + Text( + "${java.time.Instant.ofEpochMilli(p.startAt).atZone(zone).format(fmt)} · ${p.detail}", + fontSize = 12.sp, color = PulseColors.textMuted, + ) + if (p.kind == com.pulseloop.service.ActivityDetection.Proposal.Kind.CARDIO) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + listOf("cycle", "gym", "sport", "dance", "other").forEach { t -> + val on = t == type + Text( + ActivityMeta.label(t), fontSize = 12.sp, + color = if (on) PulseColors.onAccent else PulseColors.textSecondary, + modifier = Modifier.clip(RoundedCornerShape(16.dp)) + .background(if (on) PulseColors.accent else PulseColors.cardSoft) + .clickable { type = t }.padding(horizontal = 10.dp, vertical = 6.dp), + ) + } + } + } + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Text( + if (isNap) "Yes, a nap" else "Add workout", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, + modifier = Modifier.clickable { + scope.launch { runCatching { com.pulseloop.service.ActivityDetection.accept(context, db, p, type) }; tick++ } + }.padding(vertical = 4.dp), + ) + Text( + "Not this", fontSize = 13.sp, color = PulseColors.textMuted, + modifier = Modifier.clickable { com.pulseloop.service.ActivityDetection.answer(context, p); tick++ }.padding(vertical = 4.dp), + ) + } + } + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt new file mode 100644 index 00000000..725aed24 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt @@ -0,0 +1,152 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.Button +import androidx.compose.material3.DatePicker +import androidx.compose.material3.DatePickerDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberDatePickerState +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.PeriodEntity +import com.pulseloop.service.Cycle +import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.launch +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter + +fun PeriodEntity.toPeriod() = Cycle.Period(LocalDate.ofEpochDay(startDay), endDay?.let { LocalDate.ofEpochDay(it) }) + +/** Cycle tracking: log period dates, see the day and phase, and an estimate of the next one. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CycleScreen(onBack: () -> Unit) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val scope = rememberCoroutineScope() + val periods by remember { db.periodDao().allFlow() }.collectAsState(initial = emptyList()) + val today = remember { LocalDate.now() } + val status = Cycle.status(periods.map { it.toPeriod() }, today) + val fmt = remember { DateTimeFormatter.ofPattern("EEE d MMM") } + var picking by remember { mutableStateOf(null) } // "start" or "end" + var pastStart by remember { mutableStateOf(null) } + + Column(Modifier.fillMaxSize().background(PulseColors.background)) { + Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } + Text("Cycle", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + } + Column( + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + if (status == null) { + Text("Log your period to start", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("PulseLoop shows the day of your cycle and its phase from the dates you log, next to your sleep and recovery.", fontSize = 13.sp, color = PulseColors.textSecondary) + } else { + Text("Day ${status.cycleDay} · ${status.phase.label}", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(status.phase.note, fontSize = 13.sp, color = PulseColors.textSecondary) + status.nextStart?.let { next -> + val d = status.daysToNext ?: 0 + Text( + if (d >= 0) "Next period around ${next.format(fmt)} (in $d day${if (d == 1) "" else "s"}), from your usual ${status.usualLength}-day cycle." + else "Your usual ${status.usualLength}-day cycle would have ended ${-d} day${if (d == -1) "" else "s"} ago.", + fontSize = 13.sp, color = PulseColors.textPrimary, + ) + } + } + } + val open = periods.firstOrNull()?.takeIf { it.endDay == null && status?.inPeriod == true } + if (open != null) { + Button(onClick = { scope.launch { db.periodDao().upsert(open.copy(endDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { + Text("Period ended today") + } + } else { + Button(onClick = { scope.launch { db.periodDao().upsert(PeriodEntity(startDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { + Text("Period started today") + } + } + OutlinedButton(onClick = { picking = "start" }, modifier = Modifier.fillMaxWidth()) { Text("Log a past period") } + + if (periods.isNotEmpty()) { + Text("HISTORY", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + val starts = periods.map { it.startDay }.sorted() + periods.forEach { p -> + val next = starts.firstOrNull { it > p.startDay } + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + val start = LocalDate.ofEpochDay(p.startDay) + Text( + start.format(fmt) + (p.endDay?.let { " – " + LocalDate.ofEpochDay(it).format(fmt) } ?: ""), + fontSize = 14.sp, color = PulseColors.textPrimary, + ) + next?.let { Text("Cycle of ${it - p.startDay} days", fontSize = 12.sp, color = PulseColors.textMuted) } + } + IconButton(onClick = { scope.launch { db.periodDao().delete(p.id) } }) { + Icon(Icons.Filled.Delete, "Delete", tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) + } + } + } + } + Text( + "Phases come only from the dates you log. PulseLoop doesn't predict fertile days, and this isn't contraception or a medical tool.", + fontSize = 11.sp, color = PulseColors.textMuted, + ) + Spacer(Modifier.height(24.dp)) + } + } + + if (picking != null) { + val state = rememberDatePickerState(initialSelectedDateMillis = (pastStart ?: today).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()) + DatePickerDialog( + onDismissRequest = { picking = null; pastStart = null }, + confirmButton = { + TextButton(onClick = { + val chosen = state.selectedDateMillis?.let { Instant.ofEpochMilli(it).atZone(ZoneOffset.UTC).toLocalDate() } + if (chosen != null && !chosen.isAfter(today)) { + if (picking == "start") { pastStart = chosen; picking = "end" } + else { + val s = pastStart ?: chosen + val e = if (chosen.isBefore(s)) s else chosen + scope.launch { db.periodDao().upsert(PeriodEntity(startDay = s.toEpochDay(), endDay = e.toEpochDay())) } + picking = null; pastStart = null + } + } + }) { Text(if (picking == "start") "Next: end date" else "Save") } + }, + dismissButton = { TextButton(onClick = { picking = null; pastStart = null }) { Text("Cancel") } }, + ) { + Text(if (picking == "start") "When did it start?" else "When did it end?", modifier = Modifier.padding(start = 24.dp, top = 16.dp), fontSize = 16.sp, fontWeight = FontWeight.SemiBold) + DatePicker(state = state, showModeToggle = false) + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt new file mode 100644 index 00000000..128df720 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt @@ -0,0 +1,198 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.MedDoseEntity +import com.pulseloop.data.entity.MedEntity +import com.pulseloop.service.Meds +import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.launch +import java.time.LocalDate +import java.time.LocalDateTime + +private val PRESET_TIMES = listOf("07:00", "08:00", "12:00", "18:00", "20:00", "22:00") + +/** Medications and supplements: today's doses to answer, and the list with a week's adherence. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun MedsScreen(onBack: () -> Unit) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val scope = rememberCoroutineScope() + val today = remember { LocalDate.now() } + val meds by remember { db.medDao().allFlow() }.collectAsState(initial = emptyList()) + val answers by remember { db.medDao().dosesSinceFlow(today.minusDays(8).toEpochDay()) }.collectAsState(initial = emptyList()) + var editing by remember { mutableStateOf(null) } + var adding by remember { mutableStateOf(false) } + val doses = Meds.dosesOn(today, meds, answers, LocalDateTime.now()) + + fun answer(d: Meds.Dose, status: String?) = scope.launch { + if (status == null) db.medDao().deleteDose(d.id) + else db.medDao().upsertDose(MedDoseEntity(d.id, d.med.id, d.day.toEpochDay(), d.time, status)) + } + + Column(Modifier.fillMaxSize().background(PulseColors.background)) { + Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } + Text("Medications & supplements", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + } + Column( + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (meds.isEmpty()) { + Text("Add what you take on a schedule. PulseLoop asks once per dose and keeps a week's record, and the coach can see it.", fontSize = 14.sp, color = PulseColors.textSecondary) + } + if (doses.isNotEmpty()) { + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text("TODAY", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + doses.forEach { d -> + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text("${d.time} · ${d.med.name}", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text( + listOfNotNull(d.med.dose, d.state.label).joinToString(" · "), + fontSize = 12.sp, + color = when (d.state) { + Meds.State.TAKEN -> PulseColors.accent + Meds.State.MISSED -> PulseColors.warning + else -> PulseColors.textMuted + }, + ) + } + when (d.state) { + Meds.State.TAKEN, Meds.State.SKIPPED -> + TextButton(onClick = { answer(d, null) }) { Text("Undo") } + else -> { + TextButton(onClick = { answer(d, "skipped") }) { Text("Skip", color = PulseColors.textMuted) } + TextButton(onClick = { answer(d, "taken") }) { Text("Taken") } + } + } + } + } + } + } + meds.forEach { m -> + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable { editing = m }.padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(m.name + (m.dose?.let { " · $it" } ?: ""), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, + color = if (m.active) PulseColors.textPrimary else PulseColors.textMuted) + val adherence = Meds.adherence(m, answers, today) + Text( + (if (m.kind == "supplement") "Supplement" else "Medication") + " · " + Meds.times(m).joinToString(", ") + + (adherence?.let { " · $it% taken this week" } ?: "") + if (!m.active) " · paused" else "", + fontSize = 12.sp, color = PulseColors.textMuted, + ) + } + } + } + Button(onClick = { adding = true }, modifier = Modifier.fillMaxWidth()) { Text("Add medication or supplement") } + Text( + "A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist.", + fontSize = 11.sp, color = PulseColors.textMuted, + ) + Spacer(Modifier.height(24.dp)) + } + } + + if (adding || editing != null) { + val m = editing + MedDialog( + initial = m, + onDismiss = { adding = false; editing = null }, + onSave = { saved -> scope.launch { db.medDao().upsert(saved) }; adding = false; editing = null }, + onDelete = m?.let { med -> { scope.launch { db.medDao().delete(med.id); db.medDao().deleteDosesFor(med.id) }; editing = null } }, + ) + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun MedDialog(initial: MedEntity?, onDismiss: () -> Unit, onSave: (MedEntity) -> Unit, onDelete: (() -> Unit)?) { + var name by remember { mutableStateOf(initial?.name ?: "") } + var dose by remember { mutableStateOf(initial?.dose ?: "") } + var kind by remember { mutableStateOf(initial?.kind ?: "medication") } + var times by remember { mutableStateOf(initial?.let { Meds.times(it).toSet() } ?: setOf("08:00")) } + var active by remember { mutableStateOf(initial?.active ?: true) } + @Composable + fun chip(label: String, on: Boolean, onClick: () -> Unit) { + val shape = RoundedCornerShape(16.dp) + Text( + label, fontSize = 13.sp, + color = if (on) PulseColors.onAccent else PulseColors.textSecondary, + modifier = Modifier.clip(shape).background(if (on) PulseColors.accent else PulseColors.cardSoft) + .border(1.dp, if (on) PulseColors.accent else PulseColors.borderSubtle, shape) + .clickable(onClick = onClick).padding(horizontal = 12.dp, vertical = 8.dp), + ) + } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(if (initial == null) "Add" else "Edit") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + OutlinedTextField(name, { name = it.take(60) }, label = { Text("Name") }, singleLine = true, modifier = Modifier.fillMaxWidth()) + OutlinedTextField(dose, { dose = it.take(40) }, label = { Text("Dose (optional)") }, singleLine = true, modifier = Modifier.fillMaxWidth()) + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + chip("Medication", kind == "medication") { kind = "medication" } + chip("Supplement", kind == "supplement") { kind = "supplement" } + } + Text("Times", fontSize = 13.sp, color = PulseColors.textSecondary) + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + (PRESET_TIMES + times).distinct().sorted().forEach { t -> + chip(t, t in times) { times = if (t in times) times - t else times + t } + } + } + if (initial != null) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Active", fontSize = 14.sp, modifier = Modifier.weight(1f)) + androidx.compose.material3.Switch(checked = active, onCheckedChange = { active = it }) + } + onDelete?.let { del -> TextButton(onClick = del) { + Icon(Icons.Filled.Delete, null, tint = PulseColors.danger, modifier = Modifier.size(16.dp)) + Text(" Delete", color = PulseColors.danger) + } } + } + } + }, + confirmButton = { + TextButton(enabled = name.isNotBlank() && times.isNotEmpty(), onClick = { + onSave((initial ?: MedEntity(name = name.trim(), timesCsv = "")).copy( + name = name.trim(), dose = dose.trim().ifEmpty { null }, kind = kind, + timesCsv = times.sorted().joinToString(","), active = active, + )) + }) { Text("Save") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt index 4bf892ba..c38af3e3 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -24,6 +24,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Share import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -53,6 +54,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.service.BodyClock +import com.pulseloop.service.Cycle import com.pulseloop.service.HealthArea import com.pulseloop.service.HealthInsightsRepository import com.pulseloop.service.HealthInsightsRepository.TrendMetric @@ -126,7 +128,7 @@ private fun Sparkline(values: List, color: Color, modifier: Modifier = M } @Composable -fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () -> Unit = {}) { +fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () -> Unit = {}, onCycle: () -> Unit = {}, onMeds: () -> Unit = {}) { val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } var refresh by remember { mutableIntStateOf(0) } @@ -142,6 +144,24 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } Text("My Health", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + val shareScope = rememberCoroutineScope() + IconButton( + onClick = { + shareScope.launch { + runCatching { + val recap = com.pulseloop.service.WeeklyRecap.load(db) + val uri = com.pulseloop.service.WeeklyRecap.share(context, recap) + val intent = android.content.Intent(android.content.Intent.ACTION_SEND).apply { + type = "image/png" + putExtra(android.content.Intent.EXTRA_STREAM, uri) + addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + context.startActivity(android.content.Intent.createChooser(intent, "Share my week")) + } + } + }, + modifier = Modifier.align(Alignment.CenterEnd), + ) { Icon(androidx.compose.material.icons.Icons.Filled.Share, "Share my week", tint = PulseColors.textSecondary) } } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -165,6 +185,30 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } + val periods by remember { db.periodDao().allFlow() }.collectAsState(initial = emptyList()) + val cycle = Cycle.status(periods.map { it.toPeriod() }, java.time.LocalDate.now()) + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(onClick = onCycle).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(cycle?.let { "Cycle · day ${it.cycleDay} · ${it.phase.label}" } ?: "Cycle", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(cycle?.phase?.note ?: "Log your period to see its phase beside your sleep and recovery", fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("›", fontSize = 22.sp, color = PulseColors.textMuted) + } + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(onClick = onMeds).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text("Medications & supplements", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("Your schedule, today's doses and a week's record", fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("›", fontSize = 22.sp, color = PulseColors.textMuted) + } RadarSection(s.radar, restUntil) { days -> RestMode.set(context, days); restUntil = RestMode.until(context) } @@ -186,6 +230,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () StressSection(s, onBreathe) HeartSection(s) HabitsSection(s.habits) + StepCalibrationCard(db) TrendsSection(db) Text( "Estimates from your ring compared with your own recent normal, not medical measurements.", @@ -274,6 +319,14 @@ private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> val sessions = remember { MindfulSessions.all(context) } val week = sessions.filter { it.startAt >= System.currentTimeMillis() - 7 * 86_400_000L } Fact("Breathing sessions this week", "${week.size} · ${week.sumOf { it.minutes }} min") + val effectDb = remember { PulseLoopDatabase.getInstance(context) } + val effect by produceState(null) { value = runCatching { MindfulSessions.effect(context, effectDb) }.getOrNull() } + effect?.let { e -> + Fact( + "After a session", "HRV ${if (e.hrvChangePct >= 0) "+" else ""}${e.hrvChangePct}%", + "Two hours after against two hours before, over ${e.sessions} sessions. Readings during a session aren't counted: slow breathing raises HRV while it lasts.", + ) + } OutlinedButton(onClick = onBreathe, modifier = Modifier.fillMaxWidth()) { Text("Start a breathing session") } } } @@ -288,6 +341,13 @@ private fun HeartSection(s: HealthInsightsRepository.Snapshot) { Legend(PulseColors.sleep, "Sleep"); Legend(PulseColors.steps, "Workout"); Legend(PulseColors.heartRate, "Day") } } + s.cardioLoad?.let { l -> + Fact( + "Cardio load today", "${l.load}" + (l.band?.let { " · ${it.label}" } ?: ""), + "Heart rate above your quiet waking ${l.quietHr} bpm, ${l.elevatedMinutes} min well above it" + + (l.usual?.let { ". Your usual day: $it" } ?: ""), + ) + } s.cardio?.let { c -> Fact("Cardio capacity (VO₂max)", "%.0f · %s".format(c.vo2max, c.level.label), if (c.fromRing) "Measured by your ring" else "Estimated from resting heart rate and age") @@ -541,3 +601,57 @@ fun MyHealthEntryCard(onClick: () -> Unit) { Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } } + + +/** Ring steps against the phone's own counter, with the option to show calibrated steps on Today. */ +@Composable +private fun StepCalibrationCard(db: PulseLoopDatabase) { + val context = LocalContext.current + var granted by remember { mutableStateOf(com.pulseloop.service.StepCalibration.hasPermission(context)) } + var applied by remember { mutableStateOf(com.pulseloop.service.StepCalibration.isApplied(context)) } + val scope = rememberCoroutineScope() + val launcher = androidx.activity.compose.rememberLauncherForActivityResult( + androidx.activity.result.contract.ActivityResultContracts.RequestPermission() + ) { ok -> + granted = ok + if (ok) scope.launch { com.pulseloop.service.StepCalibration.sample(context) } + } + val result by produceState(null, granted) { + value = runCatching { + val zone = java.time.ZoneId.systemDefault() + val ring = db.activityDailyDao().recentReal(60).associate { java.time.Instant.ofEpochMilli(it.date).atZone(zone).toLocalDate() to it.steps } + com.pulseloop.service.StepCalibration.factor(com.pulseloop.service.StepCalibration.phoneDays(context), ring, java.time.LocalDate.now()) + }.getOrNull() + } + Section("Ring steps vs your phone") { + when { + !granted -> { + Text("Your phone counts steps too. Comparing the two over a few days shows whether your ring over- or under-counts.", fontSize = 13.sp, color = PulseColors.textSecondary) + OutlinedButton(onClick = { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) launcher.launch(android.Manifest.permission.ACTIVITY_RECOGNITION) + }, modifier = Modifier.fillMaxWidth()) { Text("Compare with my phone") } + } + result == null -> Text( + "Collecting: needs ${com.pulseloop.service.StepCalibration.MIN_DAYS} days with at least ${com.pulseloop.service.StepCalibration.MIN_STEPS} steps on both. Carry your phone as usual.", + fontSize = 13.sp, color = PulseColors.textMuted, + ) + else -> { + val r = result!! + val pct = ((r.factor - 1) * 100).roundToInt() + Text( + when { + kotlin.math.abs(pct) < 5 -> "Your ring and phone agree within 5% (${r.days} days)." + pct > 0 -> "Your ring counts about $pct% fewer steps than your phone (${r.days} days)." + else -> "Your ring counts about ${-pct}% more steps than your phone (${r.days} days)." + }, + fontSize = 14.sp, color = PulseColors.textPrimary, + ) + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Show phone-calibrated steps on Today", fontSize = 13.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) + Switch(checked = applied, onCheckedChange = { applied = it; com.pulseloop.service.StepCalibration.setApplied(context, it) }) + } + Text("Goals, scores and Health Connect keep the ring's own count.", fontSize = 11.sp, color = PulseColors.textMuted) + } + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index b81a0f38..d1c8d51c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1093,6 +1093,7 @@ private fun DailyGuidanceSettingsCard() { var battery by remember { mutableStateOf(prefs.bedtimeBattery) } var inactive by remember { mutableStateOf(prefs.inactivityAlerts) } var progress by remember { mutableStateOf(prefs.activityProgress) } + var medsOn by remember { mutableStateOf(prefs.medReminders) } Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { @@ -1137,6 +1138,11 @@ private fun DailyGuidanceSettingsCard() { "Early evening, when you're under 70% of your step goal. Off in Rest Mode.", progress, ) { progress = it; prefs.activityProgress = it } + GuidanceSwitch( + "Medication reminders", + "Once per dose, at its time, for what you add in My Health → Medications & supplements.", + medsOn, + ) { medsOn = it; prefs.medReminders = it } } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt index 46557c55..b677fa94 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -118,6 +118,14 @@ fun TodayScreen( }.getOrNull() } val mealsToday = food?.meals + // Ring steps calibrated against the phone, only when the user applied it in My Health. + val stepFactor by produceState(null, state.lastUpdated) { + value = if (!com.pulseloop.service.StepCalibration.isApplied(context)) null else runCatching { + val zone = java.time.ZoneId.systemDefault() + val ring = db.activityDailyDao().recentReal(60).associate { java.time.Instant.ofEpochMilli(it.date).atZone(zone).toLocalDate() to it.steps } + com.pulseloop.service.StepCalibration.factor(com.pulseloop.service.StepCalibration.phoneDays(context), ring, java.time.LocalDate.now())?.factor + }.getOrNull() + } // Drinks, when the user tracks them: the tile and the morning-after line on Last night. var drinkTick by remember { mutableIntStateOf(0) } val drinks by produceState(null, state.lastUpdated, sleep.lastNight?.id, drinkTick) { @@ -160,7 +168,7 @@ fun TodayScreen( // Dispatch a card id to its tile composable (order/visibility decided above). val todayCardFor: @Composable (DashboardCard, Modifier) -> Unit = { card, m -> when (card) { - DashboardCard.ACTIVITY -> ActivityTileFor(state, units, m) { navController?.navigate("activity") } + DashboardCard.ACTIVITY -> ActivityTileFor(state, units, m, onTap = { navController?.navigate("activity") }, stepFactor = stepFactor) DashboardCard.SLEEP -> SleepTileFor(sleep, m) { navController?.navigate("sleep") } DashboardCard.NUTRITION -> NutritionTile(food, m, onLog = { mealSheet = true }) { navController?.navigate("nutrition") } DashboardCard.DRINKS -> TodayTile(label = "Drinks", color = PulseColors.drinks, modifier = m, onTap = { navController?.navigate("drinks") }) { @@ -379,16 +387,19 @@ private fun ActivityTileFor( units: com.pulseloop.settings.UnitSystem, modifier: Modifier, onTap: () -> Unit, + /** Phone-calibrated step factor, when the user applied one (service/StepCalibration.kt). */ + stepFactor: Double? = null, ) { + val steps = state.steps?.let { s -> stepFactor?.let { (s * it).toInt() } ?: s } val distText = state.distanceMeters?.let { Formats.distance(UnitConverter.distance(it, units)) } ActivityTile( rings = listOf( - ActivityRing(state.steps?.toDouble(), state.stepGoal.toDouble(), PulseColors.steps), + ActivityRing(steps?.toDouble(), state.stepGoal.toDouble(), PulseColors.steps), ActivityRing(state.distanceMeters, state.distanceGoalMeters, PulseColors.distance), ActivityRing(state.calories, state.caloriesGoal.toDouble(), PulseColors.calories), ), values = buildList { - state.steps?.let { add(ActivityTileValue("STEPS", Formats.count(it), PulseColors.steps)) } + steps?.let { add(ActivityTileValue(if (stepFactor != null) "≈ STEPS" else "STEPS", Formats.count(it), PulseColors.steps)) } distText?.let { add(ActivityTileValue(UnitConverter.distanceUnit(units), it, PulseColors.distance)) } state.calories?.let { add(ActivityTileValue("CAL", Formats.count(it.toInt()), PulseColors.calories)) } }, diff --git a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt index 5adb087c..2104ade4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt @@ -14,6 +14,7 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.DirectionsRun import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Check import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button @@ -124,6 +125,24 @@ fun WorkoutSummaryScreen( Row(Modifier.fillMaxWidth()) { CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", tint = PulseColors.textSecondary, onTap = onBack) Spacer(Modifier.weight(1f)) + if (s.useGps && points.any { it.accepted }) { + CircleIconButton(Icons.Filled.Share, "Export route as GPX", tint = PulseColors.textSecondary, onTap = { + scope.launch { + val hr = db.measurementDao().rangeReal( + com.pulseloop.ring.MeasurementKind.HEART_RATE.name, s.startedAt, s.endedAt ?: System.currentTimeMillis(), + ).map { it.timestamp to it.value } + com.pulseloop.service.GpxExport.share(context, s, points, ActivityMeta.label(s.type), hr)?.let { uri -> + val intent = android.content.Intent(android.content.Intent.ACTION_SEND).apply { + type = "application/gpx+xml" + putExtra(android.content.Intent.EXTRA_STREAM, uri) + addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + context.startActivity(android.content.Intent.createChooser(intent, "Export route (GPX)")) + } + } + }) + Spacer(Modifier.width(10.dp)) + } CircleIconButton(Icons.Filled.Edit, "Edit workout", tint = PulseColors.accent, onTap = { editing = true }) Spacer(Modifier.width(10.dp)) CircleIconButton(Icons.Filled.Delete, "Delete workout", tint = PulseColors.danger, onTap = { confirmDelete = true }) diff --git a/app/src/test/java/com/pulseloop/service/ReleaseCTest.kt b/app/src/test/java/com/pulseloop/service/ReleaseCTest.kt new file mode 100644 index 00000000..886ef1bb --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/ReleaseCTest.kt @@ -0,0 +1,94 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test +import java.time.LocalDate + +/** Cardio load, cycle phases, step calibration and the breathing effect. */ +class ReleaseCTest { + + // ── Cardio load ────────────────────────────────────────────────────────────────────────── + + @Test + fun `quiet waking heart rate is the day's 20th percentile, and needs 3 days`() { + assertEquals(54.0, CardioLoad.quietOfDay((50..69).map { it.toDouble() })!!, 0.0) + assertNull(CardioLoad.quietOfDay(listOf(60.0, 61.0))) + assertNull(CardioLoad.quietLevel(listOf(55.0, 56.0))) + assertEquals(56.0, CardioLoad.quietLevel(listOf(55.0, 56.0, 58.0))!!, 0.0) + } + + @Test + fun `load grows with heart-rate reserve and is banded against your usual day`() { + val (load, elevated) = CardioLoad.load(listOf(0L to 120.0, 600_000L to 120.0), quiet = 60.0, hrMax = 180.0) + assertEquals(8.36, load, 0.01) + assertEquals(10, elevated) + assertEquals(0.0, CardioLoad.load(listOf(0L to 55.0, 600_000L to 58.0), 60.0, 180.0).first, 0.0) + assertEquals(CardioLoad.Band.HIGH, CardioLoad.band(100.0, 50.0)) + assertEquals(CardioLoad.Band.USUAL, CardioLoad.band(30.0, 50.0)) + assertNull(CardioLoad.band(30.0, null)) + } + + // ── Cycle ──────────────────────────────────────────────────────────────────────────────── + + private val periods = listOf( + Cycle.Period(LocalDate.of(2026, 8, 4), LocalDate.of(2026, 8, 8)), + Cycle.Period(LocalDate.of(2026, 9, 1), LocalDate.of(2026, 9, 5)), + Cycle.Period(LocalDate.of(2026, 9, 29), null), + ) + + @Test + fun `phase comes from logged dates and the user's own cycle length`() { + assertEquals(Cycle.Phase.MENSTRUAL, Cycle.status(periods, LocalDate.of(2026, 9, 30))!!.phase) + val mid = Cycle.status(periods, LocalDate.of(2026, 10, 10))!! + assertEquals(12, mid.cycleDay) + assertEquals(28, mid.usualLength) + assertEquals(LocalDate.of(2026, 10, 27), mid.nextStart) + assertEquals(Cycle.Phase.FOLLICULAR, mid.phase) + assertEquals(Cycle.Phase.LUTEAL, Cycle.status(periods, LocalDate.of(2026, 10, 20))!!.phase) + assertEquals(Cycle.Phase.LATE, Cycle.status(periods, LocalDate.of(2026, 10, 30))!!.phase) + } + + @Test + fun `one logged period gives the day but no phase estimate`() { + val s = Cycle.status(listOf(Cycle.Period(LocalDate.of(2026, 10, 1), LocalDate.of(2026, 10, 5))), LocalDate.of(2026, 10, 12))!! + assertEquals(12, s.cycleDay) + assertEquals(Cycle.Phase.UNKNOWN, s.phase) + assertNull(s.nextStart) + assertNull(Cycle.status(emptyList(), LocalDate.of(2026, 10, 12))) + } + + // ── Step calibration ───────────────────────────────────────────────────────────────────── + + @Test + fun `phone counter readings add up per day and survive a reboot`() { + val d = LocalDate.of(2026, 10, 20) + var days = StepCalibration.accumulate(emptyMap(), null, 1000, d) + assertEquals(0, days[d]) + days = StepCalibration.accumulate(days, 1000, 1500, d) + days = StepCalibration.accumulate(days, 1500, 200, d) // reboot: 200 since boot + assertEquals(700, days[d]) + } + + @Test + fun `the factor needs five comparable days and a plausible ratio`() { + val today = LocalDate.of(2026, 10, 21) + val phone = (1..5).associate { today.minusDays(it.toLong()) to 5500 } + val ring = (1..5).associate { today.minusDays(it.toLong()) to 5000 } + val r = StepCalibration.factor(phone, ring, today) + assertNotNull(r) + assertEquals(1.1, r!!.factor, 0.001) + assertNull(StepCalibration.factor(phone.entries.take(4).associate { it.key to it.value }, ring, today)) + assertNull(StepCalibration.factor(phone.mapValues { 12000 }, ring, today)) + } + + // ── Breathing effect ───────────────────────────────────────────────────────────────────── + + @Test + fun `breathing effect compares after with before and needs three sessions`() { + val pair = listOf(40.0) to listOf(44.0) + assertEquals(MindfulSessions.Effect(3, 10), MindfulSessions.effectFrom(listOf(pair, pair, pair))) + assertNull(MindfulSessions.effectFrom(listOf(pair, pair, emptyList() to listOf(50.0)))) + } +} diff --git a/app/src/test/java/com/pulseloop/service/ReleaseDTest.kt b/app/src/test/java/com/pulseloop/service/ReleaseDTest.kt new file mode 100644 index 00000000..1cffc067 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/ReleaseDTest.kt @@ -0,0 +1,118 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.ActivityGpsPointEntity +import com.pulseloop.data.entity.ActivitySessionEntity +import com.pulseloop.data.entity.MedDoseEntity +import com.pulseloop.data.entity.MedEntity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneOffset + +/** Detected activity, GPX export, the weekly recap and medications. */ +class ReleaseDTest { + private val min = 60_000L + private val base = LocalDate.of(2026, 10, 20).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli() + + // ── Detection ──────────────────────────────────────────────────────────────────────────── + + @Test + fun `two brisk quarter hours are a walk, faster ones a run, one alone is nothing`() { + val walk = ActivityDetection.stepSessions(listOf(base to 1500, base + 15 * min to 1400, base + 30 * min to 300)) + assertEquals(1, walk.size) + assertEquals(ActivityDetection.Proposal.Kind.WALK, walk[0].kind) + assertEquals(30, walk[0].minutes) + val run = ActivityDetection.stepSessions(listOf(base to 2200, base + 15 * min to 2300)) + assertEquals(ActivityDetection.Proposal.Kind.RUN, run.single().kind) + assertTrue(ActivityDetection.stepSessions(listOf(base to 1500, base + 45 * min to 1500)).isEmpty()) + } + + @Test + fun `twenty minutes well above the quiet level is cardio`() { + val hr = (0..5).map { base + it * 5 * min to 130.0 } + val p = ActivityDetection.heartSessions(hr, quiet = 60.0, hrMax = 180.0) + assertEquals(ActivityDetection.Proposal.Kind.CARDIO, p.single().kind) + assertTrue(ActivityDetection.heartSessions(hr.take(3), 60.0, 180.0).isEmpty()) + } + + @Test + fun `a still afternoon at the quiet level is a possible nap`() { + val afternoon = base + 13 * 60 * min + val hr = (0..6).map { afternoon + it * 5 * min to 55.0 } + val p = ActivityDetection.naps(hr, emptyList(), quiet = 60.0, zone = ZoneOffset.UTC) + assertEquals(ActivityDetection.Proposal.Kind.NAP, p.single().kind) + assertTrue(ActivityDetection.naps(hr, listOf(afternoon + 10 * min to 400), 60.0, ZoneOffset.UTC).isEmpty()) + } + + @Test + fun `recorded or answered stretches are not proposed again`() { + val p = ActivityDetection.Proposal(ActivityDetection.Proposal.Kind.WALK, base, base + 30 * min, "") + assertTrue(ActivityDetection.open(listOf(p), listOf(base + 10 * min..base + 20 * min), emptySet()).isEmpty()) + assertTrue(ActivityDetection.open(listOf(p), emptyList(), setOf(p.key)).isEmpty()) + assertEquals(1, ActivityDetection.open(listOf(p), emptyList(), emptySet()).size) + } + + // ── GPX ────────────────────────────────────────────────────────────────────────────────── + + @Test + fun `gpx carries accepted points in order with heart rate`() { + val s = ActivitySessionEntity(id = "s", type = "run", statusRaw = "finished", startedAt = base, endedAt = base + 10 * min) + val pts = listOf( + ActivityGpsPointEntity(sessionId = "s", latitude = -23.5, longitude = -46.6, timestamp = base + 60_000, altitude = 760.0), + ActivityGpsPointEntity(sessionId = "s", latitude = -23.6, longitude = -46.7, timestamp = base), + ActivityGpsPointEntity(sessionId = "s", latitude = 0.0, longitude = 0.0, timestamp = base + 30_000, accepted = false), + ) + val gpx = GpxExport.build(s, pts, "Running & more", listOf(base to 150.0))!! + assertEquals(2, Regex("150")) + assertTrue(gpx.contains("Running & more")) + assertTrue(gpx.contains("760.0")) + assertNull(GpxExport.build(s, emptyList(), "x")) + } + + // ── Weekly recap ───────────────────────────────────────────────────────────────────────── + + @Test + fun `recap rows compare with last week`() { + val rows = WeeklyRecap.rows( + WeeklyReport.Week(avgAsleepMinutes = 420, avgRestingHr = 56.0, avgHrv = 44.0, avgSteps = 8800, nights = 7), + WeeklyReport.Week(avgAsleepMinutes = 390, avgRestingHr = 58.0, avgHrv = 40.0, avgSteps = 8000, nights = 7), + workouts = 3, + ) + assertEquals(listOf("Sleep a night", "Steps a day", "Resting heart rate", "HRV", "Workouts"), rows.map { it.label }) + assertEquals("+10%", rows[1].change) + assertEquals("−2 bpm", rows[2].change) + assertEquals("+10%", rows[3].change) + assertNull(rows[4].change) + } + + // ── Medications ────────────────────────────────────────────────────────────────────────── + + @Test + fun `only an unanswered past dose is missed`() { + val day = LocalDate.of(2026, 10, 20) + val m = MedEntity(id = "m", name = "Vitamin D", timesCsv = "08:00,20:00", createdAt = 0) + val noon = day.atTime(12, 0) + val doses = Meds.dosesOn(day, listOf(m), emptyList(), noon) + assertEquals(listOf(Meds.State.MISSED, Meds.State.LATER), doses.map { it.state }) + val skipped = MedDoseEntity(MedDoseEntity.idFor("m", day.toEpochDay(), "08:00"), "m", day.toEpochDay(), "08:00", "skipped") + assertEquals(Meds.State.SKIPPED, Meds.dosesOn(day, listOf(m), listOf(skipped), noon).first().state) + assertEquals(Meds.State.DUE, Meds.dosesOn(day, listOf(m), emptyList(), day.atTime(19, 30)).last().state) + } + + @Test + fun `adherence counts taken doses over scheduled ones`() { + val today = LocalDate.of(2026, 10, 20) + val m = MedEntity(id = "m", name = "Iron", timesCsv = "08:00", createdAt = 0) + val taken = (1..5).map { back -> + val d = today.minusDays(back.toLong()).toEpochDay() + MedDoseEntity(MedDoseEntity.idFor("m", d, "08:00"), "m", d, "08:00", "taken") + } + assertEquals(71, Meds.adherence(m, taken, today)) // 5 of 7 + assertEquals(LocalDateTime.of(2026, 1, 1, 0, 0).year, 2026) + } +}