diff --git a/AGENTS.md b/AGENTS.md index 501b7c40..c2bcc582 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1012,3 +1012,24 @@ because breaking it fails silently: - **A running check ends the moment a different ring is paired** (`AccuracyRingWatcher`, started from `PulseLoopApplication`). Ring rows carry no device id, so a later sweep could not split the two rings' data. + +## Health Connect as the data source: one app, no ring, nothing back + +**Read this before touching `health/source/` or the export's exclusions.** Full design: +`docs/health-connect-source.md`. + +A user without a PulseLoop ring can pick another device's app (Oura, Samsung Health, Fitbit) and +PulseLoop imports it from Health Connect into the ring's own tables. Three rules hold it together, +and each one fails silently if broken: + +- **Every read carries a `DataOrigin` filter for the chosen package.** Unfiltered, PulseLoop's own + earlier exports come straight back in as "new" data, and two apps' steps sum into the same slot. +- **It goes through `EventPersistenceSubscriber.ingest`, not around it.** That path is what gives an + import deterministic ids, the user's deletions, and the waking-day sleep reconcile. Writing rows + directly would re-create every duplicate and resurrection bug the ring path already fixed. +- **While it is on, the export holds back every type, for all time** (`exportExclusions`, through + `ExportPause`). Exporting would write the source app's own data back to Health Connect under + PulseLoop's name. Don't narrow it to "the types the source writes": a type the source starts + writing next month would then echo. + +It is exclusive with a paired ring: a `DeviceIdentified` turns it off. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d3cd4dd1..c0b754bd 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -86,6 +86,12 @@ + + + + + diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index 4417646a..f2f771de 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -27,6 +27,7 @@ class PulseLoopApplication : Application() { super.onCreate() CrashLogger.install(this) com.pulseloop.service.DrinkPrefs.init(this) + com.pulseloop.health.source.HealthConnectSource.isEnabled(this) // warms [HealthConnectSource.enabledNow] // Application-scoped so capture runs whether or not the Debug screen is open. DiagnosticsSubscriber(PulseLoopDatabase.getInstance(this)).start(appScope) // Accuracy check: a different ring ends a running check at once (it can't be told apart later). diff --git a/app/src/main/java/com/pulseloop/health/HealthConnectExportWorker.kt b/app/src/main/java/com/pulseloop/health/HealthConnectExportWorker.kt index a242ac97..86bb71b6 100644 --- a/app/src/main/java/com/pulseloop/health/HealthConnectExportWorker.kt +++ b/app/src/main/java/com/pulseloop/health/HealthConnectExportWorker.kt @@ -49,6 +49,7 @@ class HealthConnectExportWorker( client = client, db = PulseLoopDatabase.getInstance(applicationContext), store = store, + extraExclusions = com.pulseloop.health.source.HealthConnectSource.exportExclusions(applicationContext), ) // The pass and "Remove PulseLoop data" must never interleave (review pass 5): a pass // still inserting while the removal deletes would re-write records the user asked to diff --git a/app/src/main/java/com/pulseloop/health/HealthConnectExporter.kt b/app/src/main/java/com/pulseloop/health/HealthConnectExporter.kt index 7654b986..1ec53904 100644 --- a/app/src/main/java/com/pulseloop/health/HealthConnectExporter.kt +++ b/app/src/main/java/com/pulseloop/health/HealthConnectExporter.kt @@ -227,6 +227,8 @@ class HealthConnectExporter( private val db: PulseLoopDatabase, private val store: HealthConnectPrefsStore, private val now: () -> Long = { System.currentTimeMillis() }, + /** Held back on top of the accuracy check's, for all time: the Health Connect source mode's. */ + private val extraExclusions: List = emptyList(), ) { /** @@ -306,7 +308,9 @@ class HealthConnectExporter( // advance past them (see [ExportPause]). Read once per pass; the pass runs under // HealthConnectExportWorker.passMutex, which the resume choice also takes, so a choice can't // land halfway through a pass. - val exclusions = ExportPause.exclusions(db.accuracyDao().all(), db.accuracyDao().allPausedUnits()) + // While Health Connect is the data source ([extraExclusions]), nothing it wrote goes back to it. + val exclusions = ExportPause.exclusions(db.accuracyDao().all(), db.accuracyDao().allPausedUnits()) + + extraExclusions fun noteHeldBack(label: String, f: ExportPause.Filtered) { if (f.heldBack > 0) skipped += "$label: ${f.heldBack} record(s) held back by the accuracy check" } diff --git a/app/src/main/java/com/pulseloop/health/exporters/WorkoutExporter.kt b/app/src/main/java/com/pulseloop/health/exporters/WorkoutExporter.kt index d0503b0e..54bbf400 100644 --- a/app/src/main/java/com/pulseloop/health/exporters/WorkoutExporter.kt +++ b/app/src/main/java/com/pulseloop/health/exporters/WorkoutExporter.kt @@ -111,6 +111,8 @@ class WorkoutExporter(private val db: PulseLoopDatabase) { ): PendingWorkouts { val wm = watermark ?: 0L val sessions = db.activitySessionDao().finishedUpdatedSince(wm) + // A workout imported from Health Connect is already there, under its own app. + .filterNot { com.pulseloop.health.source.HealthConnectSource.isImportedWorkout(it.id) } if (sessions.isEmpty()) return PendingWorkouts(emptyList(), emptyList()) // All GPS fixes for the pending sessions in one query — a first-enable backfill can diff --git a/app/src/main/java/com/pulseloop/health/source/HealthConnectSource.kt b/app/src/main/java/com/pulseloop/health/source/HealthConnectSource.kt new file mode 100644 index 00000000..e9e53bf3 --- /dev/null +++ b/app/src/main/java/com/pulseloop/health/source/HealthConnectSource.kt @@ -0,0 +1,226 @@ +package com.pulseloop.health.source + +import android.content.Context +import androidx.health.connect.client.permission.HealthPermission +import androidx.health.connect.client.records.ExerciseSessionRecord +import androidx.health.connect.client.records.MenstruationPeriodRecord +import androidx.health.connect.client.records.RespiratoryRateRecord +import androidx.health.connect.client.records.SleepSessionRecord +import androidx.health.connect.client.records.TotalCaloriesBurnedRecord +import androidx.work.Constraints +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.ExistingWorkPolicy +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import com.pulseloop.health.accuracy.AccuracyCheckPermissions +import com.pulseloop.health.accuracy.ExportExclusion +import com.pulseloop.health.accuracy.ExportUnit +import com.pulseloop.health.accuracy.ReferenceAppLabels +import com.pulseloop.ring.SleepStage +import com.pulseloop.ring.WearableCapability +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import java.util.concurrent.TimeUnit + +/** + * "No ring, Health Connect instead" (docs/health-connect-source.md): the user wears another + * device — an Oura, a Galaxy Ring, a Fitbit — whose app writes to Health Connect, and PulseLoop + * reads that one app's records into the same tables a paired ring fills, so every screen works. + * + * Three rules hold the feature together: + * - **One source app, by package.** Every read carries a `DataOrigin` filter. Reading "everything + * in Health Connect" would pull PulseLoop's own earlier exports back in, and mix two devices' + * steps into one day. + * - **Exclusive with a paired ring.** Both would write the same 15-minute activity slots and the + * same nights; the screen refuses to switch on while a ring is paired. + * - **Nothing goes back.** While this is on, every exported type the source writes is held back + * from the Health Connect export ([exportExclusions]), or the app would echo the source's own + * data to it under PulseLoop's name. Meals and workouts recorded in PulseLoop still export. + */ +object HealthConnectSource { + + /** How far back the first import reads. Health Connect itself only serves 30 days before the first grant. */ + const val FIRST_IMPORT_DAYS = 30L + /** Later passes re-read this much, because source apps write late (a night lands in the morning). */ + const val OVERLAP_DAYS = 3L + + /** Source rows' marker in `activity_daily.source`, so the device's own calorie figure is used. */ + const val ACTIVITY_SOURCE = "health_connect" + /** Prefix of a workout imported from Health Connect; the workout export skips these. */ + const val WORKOUT_ID_PREFIX = "hc-" + + fun isImportedWorkout(id: String): Boolean = id.startsWith(WORKOUT_ID_PREFIX) + + // ── Settings ───────────────────────────────────────────────────────────────────────────── + + private fun prefs(c: Context) = c.applicationContext.getSharedPreferences("hc_source", Context.MODE_PRIVATE) + + @Volatile private var cachedEnabled: Boolean? = null + @Volatile private var active: MutableStateFlow? = null + + /** The source app's package while the mode is on, null while off; for the header and settings. */ + fun activeSource(c: Context): StateFlow = active ?: synchronized(this) { + active ?: MutableStateFlow(if (isEnabled(c)) sourcePackage(c) else null).also { active = it } + } + + /** [isEnabled] for code with no Context (view models); warmed from the Application. */ + val enabledNow: Boolean get() = cachedEnabled == true + + /** What the cards can show while the mode is on: what Oura and its peers write to Health Connect. */ + val CAPABILITIES: Set = setOf( + WearableCapability.HEART_RATE, WearableCapability.SPO2, WearableCapability.STEPS, + WearableCapability.SLEEP, WearableCapability.REM_SLEEP, WearableCapability.HRV, + ) + + fun isEnabled(c: Context): Boolean = cachedEnabled ?: prefs(c).getBoolean("enabled", false).also { cachedEnabled = it } + fun sourcePackage(c: Context): String? = prefs(c).getString("package", null) + fun lastImportAt(c: Context): Long? = prefs(c).getLong("lastImportAt", 0L).takeIf { it > 0 } + fun lastImportCount(c: Context): Int = prefs(c).getInt("lastImportCount", 0) + fun lastError(c: Context): String? = prefs(c).getString("lastError", null) + + fun enable(c: Context, packageName: String) { + val changed = sourcePackage(c) != packageName + prefs(c).edit().putBoolean("enabled", true).putString("package", packageName).apply { + // A different source starts from a full window, not the old one's watermark. + if (changed) remove("lastImportAt").remove("seenWorkouts") + }.apply() + cachedEnabled = true + activeSource(c); active?.value = packageName + schedule(c) + runNow(c) + } + + fun disable(c: Context) { + prefs(c).edit().putBoolean("enabled", false).apply() + cachedEnabled = false + activeSource(c); active?.value = null + WorkManager.getInstance(c).cancelUniqueWork(PERIODIC) + } + + internal fun recordPass(c: Context, at: Long, count: Int, error: String?) { + prefs(c).edit().apply { + if (error == null) putLong("lastImportAt", at).putInt("lastImportCount", count).remove("lastError") + else putString("lastError", error) + }.apply() + } + + /** Workouts already imported once; the user deleting one must not bring it back. */ + internal fun seenWorkouts(c: Context): Set = prefs(c).getStringSet("seenWorkouts", emptySet()).orEmpty() + + internal fun markWorkoutsSeen(c: Context, ids: Collection) { + if (ids.isEmpty()) return + val keep = (seenWorkouts(c) + ids).toList().takeLast(500).toSet() + prefs(c).edit().putStringSet("seenWorkouts", keep).apply() + } + + fun label(c: Context, packageName: String): String = ReferenceAppLabels.label(c, packageName) + + // ── Permissions ────────────────────────────────────────────────────────────────────────── + + /** The accuracy check's reads plus what only this feature uses. Declared in the manifest too. */ + val readPermissions: Set = AccuracyCheckPermissions.all + setOf( + HealthPermission.getReadPermission(TotalCaloriesBurnedRecord::class), + HealthPermission.getReadPermission(ExerciseSessionRecord::class), + HealthPermission.getReadPermission(RespiratoryRateRecord::class), + HealthPermission.getReadPermission(MenstruationPeriodRecord::class), + ) + + /** What the screen asks for: the reads, plus background reading so imports run with the app closed. */ + val request: Set = readPermissions + HealthPermission.PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND + + fun canReadInBackground(granted: Set): Boolean = + HealthPermission.PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND in granted + + // ── Export ─────────────────────────────────────────────────────────────────────────────── + + /** While this is on, every unit the export could echo is held back, for all time. */ + fun exportExclusions(c: Context): List = + if (isEnabled(c)) exportExclusions() else emptyList() + + fun exportExclusions(): List = ExportUnit.entries.map { ExportExclusion(it, Long.MIN_VALUE, null) } + + // ── Scheduling ─────────────────────────────────────────────────────────────────────────── + + private const val PERIODIC = "hc_source_import" + private const val ONE_SHOT = "hc_source_import_now" + + fun schedule(c: Context) { + if (!isEnabled(c)) return + val request = PeriodicWorkRequestBuilder(1, TimeUnit.HOURS) + .setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build()) + .build() + WorkManager.getInstance(c).enqueueUniquePeriodicWork(PERIODIC, ExistingPeriodicWorkPolicy.KEEP, request) + } + + fun runNow(c: Context) { + if (!isEnabled(c)) return + WorkManager.getInstance(c).enqueueUniqueWork( + ONE_SHOT, ExistingWorkPolicy.KEEP, + OneTimeWorkRequestBuilder().build(), + ) + } + + // ── Pure conversions (tested) ──────────────────────────────────────────────────────────── + + /** Health Connect's stage constant as the app's stage. "Sleeping" with no stage is asleep, stage unknown. */ + fun stage(hc: Int): SleepStage = when (hc) { + SleepSessionRecord.STAGE_TYPE_LIGHT -> SleepStage.LIGHT + SleepSessionRecord.STAGE_TYPE_DEEP -> SleepStage.DEEP + SleepSessionRecord.STAGE_TYPE_REM -> SleepStage.REM + SleepSessionRecord.STAGE_TYPE_AWAKE, + SleepSessionRecord.STAGE_TYPE_AWAKE_IN_BED, + SleepSessionRecord.STAGE_TYPE_OUT_OF_BED -> SleepStage.AWAKE + else -> SleepStage.UNKNOWN + } + + data class Stage(val startMs: Long, val endMs: Long, val type: Int) + + /** + * A night as one stage per minute from its start, the shape a ring's sleep record has. A night + * with no stages at all is asleep throughout (stage unknown); with stages, a minute none of them + * covers is awake. Each minute takes the stage covering most of it. Null for an empty or + * over-long session. + */ + fun minuteStages(startMs: Long, endMs: Long, stages: List, maxMinutes: Int = 24 * 60): List? { + val minutes = ((endMs - startMs) / 60_000L).toInt() + if (minutes <= 0 || minutes > maxMinutes) return null + if (stages.isEmpty()) return List(minutes) { SleepStage.UNKNOWN } + val sorted = stages.sortedBy { it.startMs } + return List(minutes) { i -> + val a = startMs + i * 60_000L + val b = a + 60_000L + var best: Stage? = null + var bestOverlap = 0L + for (s in sorted) { + if (s.startMs >= b) break + val o = minOf(b, s.endMs) - maxOf(a, s.startMs) + if (o > bestOverlap) { bestOverlap = o; best = s } + } + best?.let { stage(it.type) } ?: SleepStage.AWAKE + } + } + + /** The app's workout type for a Health Connect exercise type; the inverse of the export's mapping. */ + fun workoutType(exerciseType: Int): String = when (exerciseType) { + ExerciseSessionRecord.EXERCISE_TYPE_WALKING -> "walk" + ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, + ExerciseSessionRecord.EXERCISE_TYPE_RUNNING_TREADMILL -> "run" + ExerciseSessionRecord.EXERCISE_TYPE_BIKING, + ExerciseSessionRecord.EXERCISE_TYPE_BIKING_STATIONARY -> "cycle" + ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING, + ExerciseSessionRecord.EXERCISE_TYPE_WEIGHTLIFTING -> "gym" + ExerciseSessionRecord.EXERCISE_TYPE_SQUASH -> "squash" + ExerciseSessionRecord.EXERCISE_TYPE_YOGA -> "yoga" + ExerciseSessionRecord.EXERCISE_TYPE_DANCING -> "dance" + ExerciseSessionRecord.EXERCISE_TYPE_HIKING -> "hike" + else -> "sport" + } + + /** The window a pass reads: the first one goes back [FIRST_IMPORT_DAYS], later ones overlap the last. */ + fun window(lastImportAt: Long?, now: Long): LongRange { + val from = if (lastImportAt == null) now - FIRST_IMPORT_DAYS * 86_400_000L + else maxOf(now - FIRST_IMPORT_DAYS * 86_400_000L, lastImportAt - OVERLAP_DAYS * 86_400_000L) + return from..now + } +} diff --git a/app/src/main/java/com/pulseloop/health/source/HealthConnectSourceImporter.kt b/app/src/main/java/com/pulseloop/health/source/HealthConnectSourceImporter.kt new file mode 100644 index 00000000..bca59596 --- /dev/null +++ b/app/src/main/java/com/pulseloop/health/source/HealthConnectSourceImporter.kt @@ -0,0 +1,272 @@ +package com.pulseloop.health.source + +import android.content.Context +import android.util.Log +import androidx.health.connect.client.HealthConnectClient +import androidx.health.connect.client.permission.HealthPermission +import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord +import androidx.health.connect.client.records.DistanceRecord +import androidx.health.connect.client.records.ExerciseSessionRecord +import androidx.health.connect.client.records.HeartRateRecord +import androidx.health.connect.client.records.HeartRateVariabilityRmssdRecord +import androidx.health.connect.client.records.MenstruationPeriodRecord +import androidx.health.connect.client.records.OxygenSaturationRecord +import androidx.health.connect.client.records.Record +import androidx.health.connect.client.records.RespiratoryRateRecord +import androidx.health.connect.client.records.SleepSessionRecord +import androidx.health.connect.client.records.StepsRecord +import androidx.health.connect.client.records.TotalCaloriesBurnedRecord +import androidx.health.connect.client.records.metadata.DataOrigin +import androidx.health.connect.client.request.AggregateGroupByDurationRequest +import androidx.health.connect.client.request.AggregateGroupByPeriodRequest +import androidx.health.connect.client.request.ReadRecordsRequest +import androidx.health.connect.client.time.TimeRangeFilter +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import com.pulseloop.AppServices +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.ActivityDailyEntity +import com.pulseloop.data.entity.ActivitySessionEntity +import com.pulseloop.data.entity.PeriodEntity +import com.pulseloop.health.HealthConnectAvailability +import com.pulseloop.health.HealthConnectSdk +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.ring.PulseEvent +import com.pulseloop.service.ActivityAggregates +import com.pulseloop.service.ActivityRollup +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.time.Duration +import java.time.Instant +import java.time.LocalDateTime +import java.time.Period +import java.time.ZoneId +import kotlin.reflect.KClass + +/** + * One import pass from the chosen source app ([HealthConnectSource]). Every reading becomes the + * same [PulseEvent] a ring's history would produce and goes through the persistence subscriber, + * so the import inherits everything that path already gets right: deterministic ids (a re-read + * updates rather than duplicates), the user's deletions, sleep reconciliation by waking day, and + * activity buckets summed per day. + */ +object HealthConnectSourceImporter { + + private const val TAG = "HCSource" + private const val MAX_PAGES = 50 + private val passLock = Mutex() + + sealed interface Outcome { + data object Off : Outcome + data object Unavailable : Outcome + data object NoPermission : Outcome + data class Done(val stored: Int) : Outcome + data class Failed(val message: String) : Outcome + } + + suspend fun run(context: Context, now: Long = System.currentTimeMillis()): Outcome = passLock.withLock { + if (!HealthConnectSource.isEnabled(context)) return Outcome.Off + val pkg = HealthConnectSource.sourcePackage(context) ?: return Outcome.Off + if (HealthConnectSdk.availability(context) != HealthConnectAvailability.AVAILABLE) return Outcome.Unavailable + val client = HealthConnectClient.getOrCreate(context) + val granted = runCatching { client.permissionController.getGrantedPermissions() }.getOrDefault(emptySet()) + if (granted.none { it in HealthConnectSource.readPermissions }) return Outcome.NoPermission + + val services = AppServices.get(context) + val db = services.db + val window = HealthConnectSource.window(HealthConnectSource.lastImportAt(context), now) + val range = TimeRangeFilter.between(Instant.ofEpochMilli(window.first), Instant.ofEpochMilli(window.last)) + val origin = setOf(DataOrigin(pkg)) + val events = mutableListOf() + val failures = mutableListOf() + fun can(type: KClass) = HealthPermission.getReadPermission(type) in granted + suspend fun step(name: String, block: suspend () -> Unit) { + runCatching { block() }.onFailure { + Log.w(TAG, "import $name failed", it) + failures += name + } + } + + step("heart rate") { + if (can(HeartRateRecord::class)) readAll(client, HeartRateRecord::class, range, origin) { r -> + r.samples.forEach { s -> + val bpm = s.beatsPerMinute.toDouble() + if (bpm in 30.0..230.0) events += PulseEvent.HistoryMeasurement(MeasurementKind.HEART_RATE, bpm, s.time) + } + } + } + step("HRV") { + if (can(HeartRateVariabilityRmssdRecord::class)) readAll(client, HeartRateVariabilityRmssdRecord::class, range, origin) { r -> + if (r.heartRateVariabilityMillis in 1.0..250.0) { + events += PulseEvent.HistoryMeasurement(MeasurementKind.HRV, r.heartRateVariabilityMillis, r.time) + } + } + } + step("blood oxygen") { + if (can(OxygenSaturationRecord::class)) readAll(client, OxygenSaturationRecord::class, range, origin) { r -> + val pct = r.percentage.value + if (pct in 70.0..100.0) events += PulseEvent.HistoryMeasurement(MeasurementKind.SPO2, pct, r.time) + } + } + step("respiratory rate") { + if (can(RespiratoryRateRecord::class)) readAll(client, RespiratoryRateRecord::class, range, origin) { r -> + if (r.rate in 4.0..60.0) events += PulseEvent.HistoryMeasurement(MeasurementKind.RESPIRATORY_RATE, r.rate, r.time) + } + } + step("sleep") { + if (can(SleepSessionRecord::class)) readAll(client, SleepSessionRecord::class, range, origin) { r -> + val start = r.startTime.toEpochMilli() / 60_000L * 60_000L + val minutes = HealthConnectSource.minuteStages( + start, r.endTime.toEpochMilli(), + r.stages.map { HealthConnectSource.Stage(it.startTime.toEpochMilli(), it.endTime.toEpochMilli(), it.stage) }, + ) + if (minutes != null) events += PulseEvent.SleepTimeline(Instant.ofEpochMilli(start), minutes, completeSession = true) + } + } + step("steps") { + if (can(StepsRecord::class)) { + val withDistance = can(DistanceRecord::class) + val metrics = buildSet { + add(StepsRecord.COUNT_TOTAL) + if (withDistance) add(DistanceRecord.DISTANCE_TOTAL) + } + // A week per request keeps each response to a few hundred 15-minute groups. + var from = window.first / 900_000L * 900_000L + while (from < window.last) { + val to = minOf(window.last, from + 7 * 86_400_000L) + client.aggregateGroupByDuration( + AggregateGroupByDurationRequest( + metrics = metrics, + timeRangeFilter = TimeRangeFilter.between(Instant.ofEpochMilli(from), Instant.ofEpochMilli(to)), + timeRangeSlicer = Duration.ofMinutes(15), + dataOriginFilter = origin, + ), + ).forEach { g -> + val steps = g.result[StepsRecord.COUNT_TOTAL] ?: 0L + val meters = if (withDistance) g.result[DistanceRecord.DISTANCE_TOTAL]?.inMeters ?: 0.0 else 0.0 + if (steps > 0 || meters > 0) { + events += PulseEvent.ActivityBucket(g.startTime, steps.toInt().coerceAtMost(50_000), meters) + } + } + from = to + } + } + } + + val stored = events.size + services.persistence.ingest(events) + + // After the buckets, so the day rows exist and carry the device's own calorie figure. + step("calories") { + val metric = when { + can(TotalCaloriesBurnedRecord::class) -> TotalCaloriesBurnedRecord.ENERGY_TOTAL + can(ActiveCaloriesBurnedRecord::class) -> ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL + else -> null + } + if (metric != null) { + val zone = ZoneId.systemDefault() + val fromDay = Instant.ofEpochMilli(window.first).atZone(zone).toLocalDate() + val toDay = Instant.ofEpochMilli(window.last).atZone(zone).toLocalDate().plusDays(1) + client.aggregateGroupByPeriod( + AggregateGroupByPeriodRequest( + metrics = setOf(metric), + timeRangeFilter = TimeRangeFilter.between(fromDay.atStartOfDay(), LocalDateTime.of(toDay, java.time.LocalTime.MIDNIGHT)), + timeRangeSlicer = Period.ofDays(1), + dataOriginFilter = origin, + ), + ).forEach { g -> + val kcal = g.result[metric]?.inKilocalories ?: return@forEach + if (kcal <= 0 || kcal > 20_000) return@forEach + val day = g.startTime.toLocalDate().atStartOfDay(zone).toInstant().toEpochMilli() + val existing = db.activityDailyDao().byDay(day) + db.activityDailyDao().upsert( + (existing ?: ActivityDailyEntity(date = day)).copy( + calories = kcal, + source = HealthConnectSource.ACTIVITY_SOURCE, + syncedAt = now, + updatedAt = now, + ), + ) + } + } + } + var workouts = 0 + step("workouts") { + if (can(ExerciseSessionRecord::class)) { + val seen = HealthConnectSource.seenWorkouts(context) + val fresh = mutableListOf() + readAll(client, ExerciseSessionRecord::class, range, origin) { r -> + val id = HealthConnectSource.WORKOUT_ID_PREFIX + r.metadata.id + if (id !in seen) fresh += id + } + if (fresh.isNotEmpty()) { + readAll(client, ExerciseSessionRecord::class, range, origin) { r -> + val id = HealthConnectSource.WORKOUT_ID_PREFIX + r.metadata.id + if (id in fresh && db.activitySessionDao().byId(id) == null && r.endTime > r.startTime) { + val session = ActivitySessionEntity( + id = id, + type = HealthConnectSource.workoutType(r.exerciseType), + statusRaw = "finished", + startedAt = r.startTime.toEpochMilli(), + endedAt = r.endTime.toEpochMilli(), + notes = r.title ?: "From ${HealthConnectSource.label(context, pkg)}", + useGps = false, + ) + val summarized = ActivityAggregates.recompute(db, session) + db.activitySessionDao().upsert(summarized) + ActivityRollup.credit(db, summarized) + workouts++ + } + } + HealthConnectSource.markWorkoutsSeen(context, fresh) + } + } + } + step("periods") { + if (can(MenstruationPeriodRecord::class)) { + val zone = ZoneId.systemDefault() + val known = db.periodDao().all().map { it.startDay }.toSet() + readAll(client, MenstruationPeriodRecord::class, range, origin) { r -> + val start = r.startTime.atZone(zone).toLocalDate().toEpochDay() + // The record's end is exclusive: a period ending at midnight ended the day before. + val end = r.endTime.minusMillis(1).atZone(zone).toLocalDate().toEpochDay().coerceAtLeast(start) + if (known.none { kotlin.math.abs(it - start) <= 2 }) { + db.periodDao().upsert(PeriodEntity(id = "hc-${r.metadata.id}", startDay = start, endDay = end)) + } + } + } + } + + val total = stored + workouts + val error = failures.takeIf { it.size >= 6 }?.let { "Couldn't read ${it.joinToString(", ")}" } + HealthConnectSource.recordPass(context, now, total, error) + return if (error != null) Outcome.Failed(error) else Outcome.Done(total) + } + + private suspend fun readAll( + client: HealthConnectClient, + type: KClass, + range: TimeRangeFilter, + origin: Set, + consume: suspend (T) -> Unit, + ) { + var token: String? = null + var pages = 0 + do { + val response = client.readRecords( + ReadRecordsRequest(type, range, dataOriginFilter = origin, pageSize = 1000, pageToken = token), + ) + response.records.forEach { consume(it) } + token = response.pageToken + pages++ + } while (token != null && pages < MAX_PAGES) + } +} + +class HealthConnectSourceWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { + override suspend fun doWork(): Result { + if (!HealthConnectSource.isEnabled(applicationContext)) return Result.success() + return runCatching { HealthConnectSourceImporter.run(applicationContext) } + .fold({ Result.success() }, { Log.w("HCSource", "pass failed", it); Result.success() }) + } +} diff --git a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt index 474c16bf..7ad3e3d4 100644 --- a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt +++ b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt @@ -9,6 +9,7 @@ import com.pulseloop.health.HealthConnectExportWorker import com.pulseloop.settings.QuietHoursPrefs import com.pulseloop.ring.* import kotlinx.coroutines.* +import kotlinx.coroutines.sync.withLock /** * Ported from [EventPersistenceSubscriber] in PulseEventBus.swift. @@ -61,10 +62,18 @@ class EventPersistenceSubscriber( fun stop() { job?.cancel(); job = null } - private suspend fun persist(event: PulseEvent) { + /** + * Serialises the bus collector with [ingest]: the spot-reading cache and the gate set above are + * only safe from one writer at a time. + */ + private val writeLock = kotlinx.coroutines.sync.Mutex() + + private suspend fun persist(event: PulseEvent) = writeLock.withLock { persistOne(event, notify = true) } + + private suspend fun persistOne(event: PulseEvent, notify: Boolean) { try { persistUnsafe(event) - if (isDataEvent(event)) onDataPersisted?.invoke() + if (notify && isDataEvent(event)) onDataPersisted?.invoke() } catch (e: Exception) { // Swallow individual persistence failures so one bad event // (malformed ring packet, DB constraint, etc.) never crashes the app. @@ -72,6 +81,17 @@ class EventPersistenceSubscriber( } } + /** + * Persist a batch of history events directly, without the bus: the Health Connect source + * import (health/source) hands over a month of readings at once, which a replay-less bus + * could drop under load. Same handlers, same rules; the data-changed callback fires once. + */ + suspend fun ingest(events: List) { + if (events.isEmpty()) return + writeLock.withLock { events.forEach { persistOne(it, notify = false) } } + if (events.any(::isDataEvent)) onDataPersisted?.invoke() + } + /** Events that change what the Today tiles (and therefore the widgets) show. */ private fun isDataEvent(event: PulseEvent): Boolean = when (event) { is PulseEvent.HeartRateSample, @@ -242,6 +262,11 @@ class EventPersistenceSubscriber( )) } is PulseEvent.DeviceIdentified -> { + // A real ring takes over from Health Connect: the two would write the same + // activity slots and nights (health/source/HealthConnectSource.kt). + if (com.pulseloop.health.source.HealthConnectSource.isEnabled(context)) { + com.pulseloop.health.source.HealthConnectSource.disable(context) + } val device = db.deviceDao().currentReal() ?: DeviceEntity() db.deviceDao().upsert(device.copy( deviceTypeRaw = event.deviceType.name, diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index a914269a..464e2873 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -219,6 +219,7 @@ fun PulseLoopApp() { // Daily guidance: unusual-signal alerts, weekly report, wind-down reminder. com.pulseloop.notifications.GuidanceWorker.schedule(context.applicationContext) com.pulseloop.health.HealthConnectBodyImport.schedule(context.applicationContext) + com.pulseloop.health.source.HealthConnectSource.schedule(context.applicationContext) runCatching { com.pulseloop.health.ProfileAging.refresh(db) } // NOTE: demo data is never auto-seeded. A clean install starts empty so the UI @@ -251,6 +252,8 @@ fun PulseLoopApp() { activityVM.refreshCurrentDay() sleepVM.refreshReferenceNight() if (isFirstStart) isFirstStart = false else bleClient.reconnectIfNeeded() + // No ring, Health Connect instead: foreground reads get the larger quota. + com.pulseloop.health.source.HealthConnectSource.runNow(context.applicationContext) } Lifecycle.Event.ON_STOP -> { if (liveWorkout.state.value.activeSession != null) return@LifecycleEventObserver @@ -304,7 +307,8 @@ fun PulseLoopApp() { LaunchedEffect(Unit) { if (!apiKeyStore.onboardingCompleted) { val profileDone = db.userProfileDao().get()?.onboardingCompleted == true - val hasRing = db.deviceDao().current() != null || bleClient.hasLastKnownRing + val hasRing = db.deviceDao().current() != null || bleClient.hasLastKnownRing || + com.pulseloop.health.source.HealthConnectSource.isEnabled(context) if (profileDone || hasRing) { apiKeyStore.onboardingCompleted = true } else { @@ -433,12 +437,15 @@ fun PulseLoopApp() { com.pulseloop.ring.RingConnectionState.RECONNECTING, com.pulseloop.ring.RingConnectionState.SCANNING, ) + val hcSource by remember { com.pulseloop.health.source.HealthConnectSource.activeSource(context) } + .collectAsState() AppHeader( state = if (liveActive) ble.connectionState else storedDevice?.state ?: ble.connectionState, batteryPercent = ble.batteryPercent ?: storedDevice?.batteryPercent, onOpenSettings = { navController.navigate("settings") }, idle = ble.idleSince != null, + sourceLabel = hcSource?.let { com.pulseloop.health.source.HealthConnectSource.label(context, it) + " · Health Connect" }, ) // Thin sync-progress accent under the greeting while history streams in. val syncPct = coordinator.syncProgress.collectAsState().value @@ -628,6 +635,9 @@ fun PulseLoopApp() { paddedComposable("settings/health-connect") { HealthConnectSettingsScreen(onBack = { navController.popBackStack() }) } + paddedComposable("settings/hc-source") { + HealthConnectSourceScreen(onBack = { navController.popBackStack() }) + } paddedComposable("settings/accuracy-check") { AccuracyCheckSettingsScreen(onBack = { navController.popBackStack() }) } diff --git a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt index d80c92ea..93417c26 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -43,6 +43,8 @@ fun AppHeader( onOpenSettings: () -> Unit, /** The ring hung up between syncs on its own (see `IdleLinkPolicy`), not a fault. */ idle: Boolean = false, + /** Set while Health Connect stands in for a ring ("Oura · Health Connect"); replaces the BLE state. */ + sourceLabel: String? = null, ) { Row( modifier = Modifier @@ -74,6 +76,7 @@ fun AppHeader( state = state, batteryPercent = batteryPercent, idle = idle, + sourceLabel = sourceLabel, modifier = Modifier.clickable( onClickLabel = "Open ring settings", role = Role.Button, @@ -98,17 +101,18 @@ fun ConnectionStatusPill( modifier: Modifier = Modifier, /** Disconnected because the ring idled out after a sync — shown neutral, not as an error. */ idle: Boolean = false, + sourceLabel: String? = null, ) { val idleNow = idle && state == RingConnectionState.DISCONNECTED // Holds still under "Remove animations"; the label already says "Connecting…". - val isPulsing = (state == RingConnectionState.CONNECTING || state == RingConnectionState.RECONNECTING) && + val isPulsing = sourceLabel == null && (state == RingConnectionState.CONNECTING || state == RingConnectionState.RECONNECTING) && !rememberReduceMotion() - val dotColor = when (state) { + val dotColor = if (sourceLabel != null) PulseColors.success else when (state) { RingConnectionState.CONNECTED -> PulseColors.success RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> PulseColors.accent else -> if (idleNow) PulseColors.textMuted else PulseColors.danger // scanning/failed/idle/disconnected all read "not connected" } - val label = when (state) { + val label = sourceLabel ?: when (state) { RingConnectionState.CONNECTED -> if (batteryPercent != null && batteryPercent > 0) "Connected · $batteryPercent%" else "Connected" RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> "Connecting…" diff --git a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt new file mode 100644 index 00000000..a62619f4 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt @@ -0,0 +1,237 @@ +package com.pulseloop.ui.screens + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.draw.clip +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +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 androidx.health.connect.client.PermissionController +import com.pulseloop.AppServices +import com.pulseloop.health.HealthConnectAvailability +import com.pulseloop.health.HealthConnectSdk +import com.pulseloop.health.accuracy.ReferenceSourceScanner +import com.pulseloop.health.accuracy.RingIdentity +import com.pulseloop.health.source.HealthConnectSource +import com.pulseloop.health.source.HealthConnectSourceImporter +import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.launch +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +/** Settings → Health Connect as your data source (docs/health-connect-source.md). */ +@Composable +fun HealthConnectSourceScreen(onBack: () -> Unit) { + SettingsSubScreen(title = "Use without a ring", onBack = onBack) { + HealthConnectSourceContent() + } +} + +/** + * Pick the app whose data PulseLoop should use — Oura, Samsung Health, Fitbit — then import. Also + * the onboarding step for people who don't have a PulseLoop ring ([onEnabled] moves it on). + */ +@Composable +fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val services = remember { AppServices.get(context) } + val available = remember { HealthConnectSdk.availability(context) == HealthConnectAvailability.AVAILABLE } + val ring by services.db.deviceDao().currentFlow().collectAsState(initial = null) + val hasRing = ring?.let { it.id != RingIdentity.DEMO_DEVICE_ID } == true || services.bleClient.hasLastKnownRing + var enabled by remember { mutableStateOf(HealthConnectSource.isEnabled(context)) } + var source by remember { mutableStateOf(HealthConnectSource.sourcePackage(context)) } + var granted by remember { mutableStateOf>(emptySet()) } + var scanning by remember { mutableStateOf(false) } + var importing by remember { mutableStateOf(false) } + var scan by remember { mutableStateOf(null) } + var note by remember { mutableStateOf(null) } + var refresh by remember { mutableIntStateOf(0) } + + fun doScan() { + scanning = true + note = null + scope.launch { + when (val r = runCatching { ReferenceSourceScanner.scan(context) }.getOrNull()) { + is ReferenceSourceScanner.Result.Done -> scan = r + ReferenceSourceScanner.Result.Unavailable -> note = "Health Connect isn't available on this phone." + null -> note = "Couldn't read Health Connect. Try again in a moment." + } + scanning = false + } + } + + fun importNow() { + importing = true + note = null + scope.launch { + note = when (val r = runCatching { HealthConnectSourceImporter.run(context) }.getOrNull()) { + is HealthConnectSourceImporter.Outcome.Done -> "Imported ${"%,d".format(r.stored)} readings." + is HealthConnectSourceImporter.Outcome.Failed -> r.message + HealthConnectSourceImporter.Outcome.NoPermission -> "PulseLoop isn't allowed to read Health Connect any more." + HealthConnectSourceImporter.Outcome.Unavailable -> "Health Connect isn't available on this phone." + else -> "The import failed. Try again in a moment." + } + importing = false + refresh++ + } + } + + LaunchedEffect(Unit) { + granted = ReferenceSourceScanner.grantedPermissions(context) + if (granted.any { it in HealthConnectSource.readPermissions } && !enabled) doScan() + } + + val launcher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { got -> + granted = got + if (got.none { it in HealthConnectSource.readPermissions }) { + note = "No access granted. You can allow it in Health Connect's settings." + } else if (!enabled) doScan() + } + val canRead = granted.any { it in HealthConnectSource.readPermissions } + val missing = HealthConnectSource.request - granted + + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + AccuracyCard { + Text("Use the device you already wear", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text( + "No PulseLoop ring? If your Oura, Galaxy Ring, Fitbit or watch app writes to Health Connect, PulseLoop can " + + "read it from there: sleep, heart rate, HRV, blood oxygen, steps, calories, workouts and periods. " + + "Every screen, the coach and your insights then work from that data.", + fontSize = 13.sp, color = PulseColors.textSecondary, + ) + Text( + "PulseLoop reads only the app you choose, and doesn't write that data back to Health Connect.", + fontSize = 12.sp, color = PulseColors.textMuted, + ) + if (!available) { + Text("Health Connect isn't available on this phone.", fontSize = 12.sp, color = PulseColors.danger) + } else if (hasRing && !enabled) { + Text( + "A ring is paired. Forget it in Settings → Wearable first: the two would count the same steps and nights.", + fontSize = 12.sp, color = PulseColors.warning, + ) + } else if (!canRead) { + Button(onClick = { launcher.launch(HealthConnectSource.request) }) { Text("Allow access") } + } + } + + if (enabled && source != null) { + val pkg = source!! + AccuracyCard { + Text("Using ${HealthConnectSource.label(context, pkg)}", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + val last = remember(refresh) { HealthConnectSource.lastImportAt(context) } + val count = remember(refresh) { HealthConnectSource.lastImportCount(context) } + Text( + last?.let { + "Last import " + DateTimeFormatter.ofPattern("EEE d MMM, HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) + + " · ${"%,d".format(count)} readings" + } ?: "Not imported yet", + fontSize = 13.sp, color = PulseColors.textSecondary, + ) + Text( + "PulseLoop checks for new data every hour and whenever you open the app. A night usually appears once " + + "${HealthConnectSource.label(context, pkg)} has synced it in the morning.", + fontSize = 12.sp, color = PulseColors.textMuted, + ) + if (canRead && !HealthConnectSource.canReadInBackground(granted)) { + Text("Allow background access so imports also run while PulseLoop is closed.", fontSize = 12.sp, color = PulseColors.warning) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + Button(onClick = { importNow() }, enabled = !importing && canRead) { Text("Import now") } + if (missing.isNotEmpty()) { + OutlinedButton(onClick = { launcher.launch(HealthConnectSource.request) }) { Text("Allow more") } + } + if (importing) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + } + TextButton(onClick = { + HealthConnectSource.disable(context) + enabled = false + doScan() + }) { Text("Stop using Health Connect", color = PulseColors.danger) } + } + } else if (canRead && !hasRing) { + val r = scan + if (scanning) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + Text("Looking for apps writing to Health Connect…", fontSize = 13.sp, color = PulseColors.textSecondary) + } + } else if (r != null) { + val usable = r.sources.filter { it.echo?.looksLikeEcho != true } + if (usable.isEmpty()) { + AccuracyCard { + Text("No app wrote health data in the last ${ReferenceSourceScanner.LOOKBACK_DAYS} days.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text( + "In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.", + fontSize = 12.sp, color = PulseColors.textMuted, + ) + OutlinedButton(onClick = { doScan() }) { Text("Look again") } + } + } + usable.forEach { src -> + AccuracyCard { + Text(HealthConnectSource.label(context, src.packageName), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(src.metrics.joinToString(", ") { it.metric.label }, fontSize = 13.sp, color = PulseColors.textSecondary) + Button(onClick = { + HealthConnectSource.enable(context, src.packageName) + enabled = true + source = src.packageName + // enable() queues the first import as background work, which outlives this + // screen; onboarding moves on at once, settings shows the pass running here. + if (onEnabled != null) onEnabled() else importNow() + }, modifier = Modifier.fillMaxWidth()) { Text("Use ${HealthConnectSource.label(context, src.packageName)}") } + } + } + } + } + note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } + } +} + +/** Settings' top card while Health Connect stands in for a ring: which app, and when it last imported. */ +@Composable +fun HealthConnectSourceHeroCard(onOpen: () -> Unit) { + val context = LocalContext.current + val pkg = HealthConnectSource.sourcePackage(context) ?: return + val last = HealthConnectSource.lastImportAt(context) + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(PulseColors.card) + .clickable(onClick = onOpen).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text("DATA SOURCE", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text("${HealthConnectSource.label(context, pkg)} via Health Connect", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text( + last?.let { "Last import " + DateTimeFormatter.ofPattern("EEE HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) } + ?: "Waiting for the first import", + fontSize = 13.sp, color = PulseColors.textSecondary, + ) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt index 68a3be92..64b164f9 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt @@ -42,6 +42,7 @@ import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.MonitorHeart import androidx.compose.material.icons.filled.Paid import androidx.compose.material.icons.filled.Verified +import androidx.compose.material.icons.filled.Watch import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text @@ -106,6 +107,8 @@ fun OnboardingScreen( } var path by remember { mutableStateOf(progressStore.loadPath()) } val step = path.lastOrNull() ?: OnboardingStep.WELCOME + // "I wear an Oura…": the RING step becomes the Health Connect source picker instead of pairing. + var useHealthConnect by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(false) } fun push(next: OnboardingStep) { if (path.lastOrNull() == next) return @@ -195,6 +198,7 @@ fun OnboardingScreen( OnboardingStep.WELCOME -> WelcomeStep( getStarted = ::getStarted, exploreWithoutRing = { push(OnboardingStep.PROFILE) }, + useOtherDevice = { useHealthConnect = true; push(OnboardingStep.RING) }, permissionDenied = blePermissionDenied, openAppSettings = { context.startActivity( @@ -204,7 +208,9 @@ fun OnboardingScreen( ) }, ) - OnboardingStep.RING -> PairingScreen( + OnboardingStep.RING -> if (useHealthConnect) HealthConnectSourceStep( + next = { push(OnboardingStep.PROFILE) }, + ) else PairingScreen( bleClient = bleClient, onConnected = { scope.launch { @@ -310,6 +316,7 @@ private data class WelcomeFeature( private fun WelcomeStep( getStarted: () -> Unit, exploreWithoutRing: () -> Unit, + useOtherDevice: () -> Unit = {}, permissionDenied: Boolean = false, openAppSettings: () -> Unit = {}, ) { @@ -341,6 +348,7 @@ private fun WelcomeStep( SecondaryButton("Continue without ring", icon = Icons.Filled.GridView, onClick = exploreWithoutRing) } else { PrimaryButton("Get started", icon = Icons.Filled.ArrowForward, onClick = getStarted) + SecondaryButton("I wear an Oura or another device", icon = Icons.Filled.Watch, onClick = useOtherDevice) SecondaryButton("Explore without ring", icon = Icons.Filled.GridView, onClick = exploreWithoutRing) } } @@ -653,6 +661,23 @@ private fun SetupCompleteEyebrow() { // MARK: - Shared step chrome /** Scrolling step content above a pinned action footer (iOS `OnboardingActionFooter`). */ +/** The RING step for someone without a PulseLoop ring: read their Oura (or other) app from Health Connect. */ +@Composable +private fun HealthConnectSourceStep(next: () -> Unit) { + StepScaffold( + footer = { SecondaryButton("Skip for now", modifier = Modifier.fillMaxWidth(), onClick = next) }, + ) { + Text( + "Use your device's data", + fontSize = 26.sp, + fontWeight = FontWeight.Bold, + color = PulseColors.textPrimary, + textAlign = TextAlign.Center, + ) + HealthConnectSourceContent(onEnabled = next) + } +} + @Composable private fun StepScaffold( footer: @Composable () -> Unit, diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index dc5a17b2..4833cbcf 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -84,7 +84,10 @@ fun SettingsScreen( ) { Text("Settings", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) - DeviceHeroCard( + val hcSource by remember { com.pulseloop.health.source.HealthConnectSource.activeSource(context) }.collectAsState() + if (hcSource != null) { + HealthConnectSourceHeroCard(onOpen = { navigate("settings/hc-source") }) + } else DeviceHeroCard( bleState = bleState, storedDevice = storedDevice, lastSyncAt = coordinator?.lastSyncAt ?: storedDevice?.lastSyncAt, @@ -177,6 +180,9 @@ fun SettingsScreen( add(SettingsRowItem(Icons.Filled.Sync, PulseColors.success, "Health Connect") { navigate("settings/health-connect") }) + add(SettingsRowItem(Icons.Filled.Watch, PulseColors.info, "Use without a ring") { + navigate("settings/hc-source") + }) add(SettingsRowItem(Icons.Filled.Verified, PulseColors.info, "Accuracy check", accuracyTrailing) { navigate("settings/accuracy-check") }) 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 f60a5ba6..9bd83775 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -564,7 +564,9 @@ private data class Hero(val title: String, val summary: String, val chips: List< private fun deriveHero(state: TodayViewModel.TodayState, sleep: SleepViewModel.SleepState): Hero { val steps = state.steps ?: return Hero( title = "Waiting for first sync", - summary = "Sync your ring to start collecting movement, heart rate, blood oxygen, and recovery context.", + summary = if (com.pulseloop.health.source.HealthConnectSource.enabledNow) + "Importing from Health Connect. Your steps, sleep and heart rate appear once your device's app has synced." + else "Sync your ring to start collecting movement, heart rate, blood oxygen, and recovery context.", chips = listOf( ToneChip("Baseline pending", ChipTone.WARN), ToneChip(if (state.heartRate == null) "HR pending" else "HR collected", ChipTone.NEUTRAL), diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index 0658f88f..6232addf 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -728,7 +728,9 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore val now = System.currentTimeMillis() val twentyFourHoursAgo = now - 24 * 3600_000L val device = db.deviceDao().current() - val caps = device?.capabilities ?: setOf( + val caps = device?.capabilities + ?: com.pulseloop.health.source.HealthConnectSource.CAPABILITIES.takeIf { com.pulseloop.health.source.HealthConnectSource.enabledNow } + ?: setOf( com.pulseloop.ring.WearableCapability.HEART_RATE, com.pulseloop.ring.WearableCapability.SPO2, com.pulseloop.ring.WearableCapability.STEPS, diff --git a/app/src/test/java/com/pulseloop/health/source/HealthConnectSourceTest.kt b/app/src/test/java/com/pulseloop/health/source/HealthConnectSourceTest.kt new file mode 100644 index 00000000..183a35f3 --- /dev/null +++ b/app/src/test/java/com/pulseloop/health/source/HealthConnectSourceTest.kt @@ -0,0 +1,84 @@ +package com.pulseloop.health.source + +import androidx.health.connect.client.records.ExerciseSessionRecord +import androidx.health.connect.client.records.SleepSessionRecord +import com.pulseloop.health.accuracy.ExportUnit +import com.pulseloop.ring.SleepStage +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Health Connect as the data source: how its records become the app's (docs/health-connect-source.md). */ +class HealthConnectSourceTest { + + private val t0 = 1_700_000_000_000L / 60_000L * 60_000L + private fun min(n: Int) = t0 + n * 60_000L + + @Test + fun `stages map to the app's, out of bed and awake in bed are awake, plain sleeping is unknown`() { + assertEquals(SleepStage.DEEP, HealthConnectSource.stage(SleepSessionRecord.STAGE_TYPE_DEEP)) + assertEquals(SleepStage.REM, HealthConnectSource.stage(SleepSessionRecord.STAGE_TYPE_REM)) + assertEquals(SleepStage.LIGHT, HealthConnectSource.stage(SleepSessionRecord.STAGE_TYPE_LIGHT)) + assertEquals(SleepStage.AWAKE, HealthConnectSource.stage(SleepSessionRecord.STAGE_TYPE_OUT_OF_BED)) + assertEquals(SleepStage.AWAKE, HealthConnectSource.stage(SleepSessionRecord.STAGE_TYPE_AWAKE_IN_BED)) + assertEquals(SleepStage.UNKNOWN, HealthConnectSource.stage(SleepSessionRecord.STAGE_TYPE_SLEEPING)) + } + + @Test + fun `a night becomes one stage per minute, gaps between stages are awake`() { + val stages = listOf( + HealthConnectSource.Stage(min(0), min(3), SleepSessionRecord.STAGE_TYPE_LIGHT), + HealthConnectSource.Stage(min(5), min(8), SleepSessionRecord.STAGE_TYPE_DEEP), + ) + val m = HealthConnectSource.minuteStages(min(0), min(8), stages)!! + assertEquals(8, m.size) + assertEquals(List(3) { SleepStage.LIGHT } + List(2) { SleepStage.AWAKE } + List(3) { SleepStage.DEEP }, m) + } + + @Test + fun `a minute split between stages takes the one covering most of it`() { + val stages = listOf( + HealthConnectSource.Stage(min(0), min(1) + 40_000, SleepSessionRecord.STAGE_TYPE_REM), + HealthConnectSource.Stage(min(1) + 40_000, min(2), SleepSessionRecord.STAGE_TYPE_LIGHT), + ) + assertEquals(listOf(SleepStage.REM, SleepStage.REM), HealthConnectSource.minuteStages(min(0), min(2), stages)) + } + + @Test + fun `a night with no stages is asleep throughout, an empty or over-long one is dropped`() { + assertEquals(List(90) { SleepStage.UNKNOWN }, HealthConnectSource.minuteStages(min(0), min(90), emptyList())) + assertNull(HealthConnectSource.minuteStages(min(0), min(0), emptyList())) + assertNull(HealthConnectSource.minuteStages(min(0), min(25 * 60), emptyList())) + } + + @Test + fun `workout types map back to the app's`() { + assertEquals("run", HealthConnectSource.workoutType(ExerciseSessionRecord.EXERCISE_TYPE_RUNNING_TREADMILL)) + assertEquals("cycle", HealthConnectSource.workoutType(ExerciseSessionRecord.EXERCISE_TYPE_BIKING)) + assertEquals("walk", HealthConnectSource.workoutType(ExerciseSessionRecord.EXERCISE_TYPE_WALKING)) + assertEquals("sport", HealthConnectSource.workoutType(ExerciseSessionRecord.EXERCISE_TYPE_TENNIS)) + } + + @Test + fun `the first pass reads 30 days, later ones overlap the last by 3`() { + val now = 100L * 86_400_000L + assertEquals(now - 30L * 86_400_000L, HealthConnectSource.window(null, now).first) + assertEquals(now - 4L * 86_400_000L, HealthConnectSource.window(now - 86_400_000L, now).first) + // A long gap never reads further back than Health Connect serves. + assertEquals(now - 30L * 86_400_000L, HealthConnectSource.window(now - 60L * 86_400_000L, now).first) + } + + @Test + fun `while on, every exported type is held back for all time`() { + val ex = HealthConnectSource.exportExclusions() + assertEquals(ExportUnit.entries.toSet(), ex.map { it.unit }.toSet()) + assertTrue(ex.all { it.until == null && it.overlaps(0L, 0L) && it.overlaps(Long.MAX_VALUE - 1, Long.MAX_VALUE) }) + } + + @Test + fun `imported workouts are recognised by id`() { + assertTrue(HealthConnectSource.isImportedWorkout(HealthConnectSource.WORKOUT_ID_PREFIX + "abc")) + assertTrue(!HealthConnectSource.isImportedWorkout("2b8c-uuid")) + } +} diff --git a/docs/health-connect-source.md b/docs/health-connect-source.md new file mode 100644 index 00000000..d1440b62 --- /dev/null +++ b/docs/health-connect-source.md @@ -0,0 +1,58 @@ +# Health Connect as the data source (no ring) + +For people who already wear an Oura, a Galaxy Ring, a Fitbit or a watch: PulseLoop reads that +device's app from Health Connect instead of pairing a ring, and every screen, the coach and the +insights run on that data. + +## How a user gets there + +- Onboarding, welcome step: **"I wear an Oura or another device"**. The ring step then shows the + source picker instead of pairing. +- Settings → Resources → **Use without a ring** (`settings/hc-source`). + +The screen asks for Health Connect read access, lists the apps that wrote health data in the last +week (the accuracy check's `ReferenceSourceScanner`, so PulseLoop's own exports and bridge-app +echoes are already filtered out), and the user picks one. + +## What is imported + +Each pass reads only the chosen package (`DataOrigin` filter) and turns records into the same +`PulseEvent`s a ring's history produces. Those go through `EventPersistenceSubscriber.ingest`, so +ids, tombstones, the sleep reconcile and the bucket sums all behave exactly as for a ring. + +| Health Connect | Becomes | +| --- | --- | +| Heart rate samples | `HistoryMeasurement(HEART_RATE)` | +| HRV (RMSSD) | `HistoryMeasurement(HRV)` | +| Oxygen saturation | `HistoryMeasurement(SPO2)` | +| Respiratory rate | `HistoryMeasurement(RESPIRATORY_RATE)` | +| Sleep session + stages | `SleepTimeline`, one stage per minute, `completeSession = true` | +| Steps + distance | 15-minute aggregates → `ActivityBucket` | +| Total (else active) calories | the day's `activity_daily.calories`, `source = "health_connect"` | +| Exercise sessions | finished `activity_sessions`, id `hc-`, imported once | +| Menstruation periods | `periods`, unless one is logged within 2 days of the start | + +The first pass reads 30 days, the most Health Connect serves before the first grant. Later passes +re-read from 3 days before the last one, because source apps write late (a night lands in the +morning). Passes run hourly in the background (with the background-read permission), and whenever +the app comes to the foreground. + +## Rules + +- **One source app, by package.** Without the filter, PulseLoop's own earlier exports would come + back in, and two devices' steps would land in the same 15-minute slots. +- **Exclusive with a paired ring.** The screen refuses while a ring is paired, and a ring being + identified switches the mode off (`EventPersistenceSubscriber`, `DeviceIdentified`). +- **Nothing goes back.** While the mode is on, `HealthConnectSource.exportExclusions` holds back + every `ExportUnit` for all time, through the same `ExportPause` filter the accuracy check uses, + so watermarks still advance. Imported workouts are skipped by the workout export by id prefix. + Meals and workouts recorded in PulseLoop still export. +- **A deleted import stays deleted.** Measurements and sleep use the ring's tombstones. Workouts are + imported once (the seen-id list), so deleting one doesn't bring it back. + +## Known limits + +- Health Connect has no skin temperature from most of these apps yet, so temperature cards stay + empty, and stress is derived from HRV as for rings without a stress sensor. +- Whatever the source app's own scores are (readiness, sleep score), they don't reach Health + Connect. PulseLoop computes its own from the raw data.