Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,11 @@
<uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE" />
<uses-permission android:name="android.permission.health.WRITE_EXERCISE" />
<uses-permission android:name="android.permission.health.WRITE_DISTANCE" />
<!-- Asked for with the rest, but a write without them still goes, the calories left out. -->
<!-- Asked for with the rest, but a write without them still goes, those records left out. -->
<uses-permission android:name="android.permission.health.WRITE_ACTIVE_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.WRITE_TOTAL_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.WRITE_RESPIRATORY_RATE" />
<uses-permission android:name="android.permission.health.WRITE_VO2_MAX" />
<!-- Reading back what unstrap exported, to restore it (Import from Health Connect). -->
<uses-permission android:name="android.permission.health.READ_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_STEPS" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ class HealthRepository(
DailyMetric.HeartRate -> dao.dailyHeartRate(a, b)
DailyMetric.Steps -> dao.dailySteps(a, b)
DailyMetric.Hrv -> dao.dailyHrv(a, b)
DailyMetric.SleepHrv -> dao.dailySleepHrv(a, b)
DailyMetric.HrvSdnn -> dao.dailyHrvSdnn(a, b)
DailyMetric.Spo2 -> dao.dailySpo2(a, b)
DailyMetric.SleepSpo2 -> dao.dailySleepSpo2(a, b)
Expand Down Expand Up @@ -366,7 +367,7 @@ class HealthRepository(
}

/** Sampled metrics that have a per-day series. */
enum class DailyMetric { HeartRate, RestingHr, Steps, Hrv, HrvSdnn, Spo2, SleepSpo2, Stress, SkinTemperature, Breathing }
enum class DailyMetric { HeartRate, RestingHr, Steps, Hrv, SleepHrv, HrvSdnn, Spo2, SleepSpo2, Stress, SkinTemperature, Breathing }

/** One local day of a metric: the average (the total, for steps), lowest and highest sample, and how many samples. */
data class DayStat(val date: LocalDate, val value: Float, val min: Float, val max: Float, val count: Int) {
Expand Down
25 changes: 25 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/data/HeartReadings.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.openstrap.app.data

/** Pure helpers over a day's stored heart rate readings (time, bpm); kept free of Android types so they're unit-testable. */
object HeartReadings {
/** The readings of [series] taken from [from] to [to]. */
fun within(series: List<Pair<Long, Int>>, from: Long, to: Long): List<Pair<Long, Int>> =
series.filter { it.first in from..to }

/** The lowest reading of [series], the earliest when several share it, with its time; null without readings. */
fun lowest(series: List<Pair<Long, Int>>): Pair<Long, Int>? = series.minByOrNull { it.second }

/** The mean of [series]' readings, to the nearest bpm; null without readings. */
fun mean(series: List<Pair<Long, Int>>): Int? =
series.takeIf { it.isNotEmpty() }?.let { Math.round(it.map { r -> r.second }.average()).toInt() }

/**
* The day's lowest and highest heart rate from its stored readings ([series], not their 5-minute averages). The
* high is the strap's own daily maximum ([strapMax]) when it has one that is higher. Null without readings.
*/
fun heartRange(series: List<Pair<Long, Int>>, strapMax: Int?): Pair<Int, Int>? {
if (series.isEmpty()) return null
val high = series.maxOf { it.second }
return series.minOf { it.second } to maxOf(high, strapMax?.takeIf { it in HeartRate.VALID } ?: high)
}
}
18 changes: 18 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/data/NightMetrics.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
package org.openstrap.app.data

import org.openstrap.app.data.db.HrvSample
import org.openstrap.app.data.db.NightMetricsRow
import org.openstrap.app.data.db.StrapReadinessRow
import java.time.ZoneId
import kotlin.math.ln

/** OpenStrap's own nightly inputs as logged for the calibration review (evidence-review.md, implementation step 1). */
object NightMetrics {
/**
* The RMSSD readings inside the sleep from [start] to [end] that count: within [Recovery.HRV_MIN_MS] to
* [Recovery.HRV_MAX_MS]. The one gate for every night's HRV, in Recovery and on every screen.
*/
fun sleepHrvReadings(hrv: List<HrvSample>, start: Long, end: Long): List<Int> =
hrv.filter { it.timestamp in start..end && it.milliseconds in Recovery.HRV_MIN_MS..Recovery.HRV_MAX_MS }.map { it.milliseconds }

/** The mean of a night's gated [readings] ([sleepHrvReadings]), as Recovery works with it; null without any. */
fun hrvMean(readings: List<Int>): Float? = readings.takeIf { it.isNotEmpty() }?.average()?.toFloat()

/**
* The night's HRV as every screen shows it: [hrvMean] of the gated readings inside the sleep, to the nearest whole ms.
* Recovery's "what drove it" rounds the same mean the same way, so they cannot differ.
*/
fun sleepHrv(hrv: List<HrvSample>, start: Long, end: Long): Float? =
hrvMean(sleepHrvReadings(hrv, start, end))?.let { Math.round(it).toFloat() }

/** `hrv_n`: ln of the night's mean gated RMSSD; null without one. Never change this inside a baseline. */
fun hrvLn(n: Recovery.Night): Float? = n.hrv?.takeIf { it > 0 }?.let { ln(it) }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ private fun Recovery.hrvBalance(tonight: Night, base: Baseline?, hrv7: Float?):
val zNight = base.z(ln)
val z = if (hrv7 != null) HRV_NIGHT_WEIGHT * zNight + HRV_WEEK_WEIGHT * base.z(hrv7) else zNight
val pct = ((exp(ln - base.centre.toDouble()) - 1) * 100).toInt()
return Contributor(Factor.HrvBalance, scoreFromZ(deadZone(z)), Detail.Hrv(hrv.toInt(), pct))
return Contributor(Factor.HrvBalance, scoreFromZ(deadZone(z)), Detail.Hrv(Math.round(hrv), pct))
}

/** Resting heart rate: the night's lowest 30-minute average against baseline; lower is better. */
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/kotlin/org/openstrap/app/data/RecoveryEngine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,7 @@ class RecoveryEngine(private val dao: HealthDao) {
val inSleep = { t: Long -> t in s.start..s.end }
val sleepHr = hr.filter { inSleep(it.first) && it.second in Recovery.HR_MIN_BPM..Recovery.HR_MAX_BPM }
val sleepBpm = sleepHr.map { it.second.toFloat() }
val rmssd = hrv.filter { inSleep(it.timestamp) && it.milliseconds in Recovery.HRV_MIN_MS..Recovery.HRV_MAX_MS }.map { it.milliseconds.toFloat() }
val rmssd = NightMetrics.sleepHrvReadings(hrv, s.start, s.end)
val asleep = asleepMinutes(s)
val skinValues = skin.filter { inSleep(it.timestamp) }.map { it.celsius }
val spo2Values = spo2.filter { inSleep(it.timestamp) }.map { it.percent.toFloat() }
Expand All @@ -760,7 +760,7 @@ class RecoveryEngine(private val dao: HealthDao) {
deepMinutes = s.deepMinutes,
remMinutes = s.remMinutes,
strapScore = s.score,
hrv = rmssd.mean(),
hrv = NightMetrics.hrvMean(rmssd),
restingHr = Recovery.lowestAverage(sleepHr, 30, Recovery.RHR_WINDOW_MIN_MINUTES)?.second,
rhrMeanSleep = sleepBpm.mean(),
rhrP10 = Recovery.percentile(sleepBpm, 0.10f),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class RoomDayRepository(
SleepNight(
date = d,
session = s,
hrv = during(hrv, { it.timestamp }, { it.milliseconds.toFloat() }),
hrv = s?.let { NightMetrics.sleepHrv(hrv, it.start, it.end) },
skinTemperature = during(skin, { it.timestamp }, { it.celsius }),
spo2 = during(spo2, { it.timestamp }, { it.percent.toFloat() }),
breathing = during(breath, { it.timestamp }, { it.perMinute.toFloat() }),
Expand Down
13 changes: 13 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,19 @@ interface HealthDao : RangedReads {
@Query("SELECT date(timestamp, 'unixepoch', 'localtime') AS day, AVG(milliseconds) AS value, MIN(milliseconds) AS min, MAX(milliseconds) AS max, COUNT(*) AS count FROM hrv WHERE timestamp BETWEEN :from AND :to GROUP BY day ORDER BY day")
fun dailyHrv(from: Long, to: Long): Flow<List<DailyAggregate>>

/**
* HRV while asleep, per night: the readings inside each main sleep from 5 to 200 ms ([Recovery.HRV_MIN_MS] to
* [Recovery.HRV_MAX_MS]), on the day the sleep ended, the mean rounded to a whole ms as the night's figure is
* ([NightMetrics.sleepHrv]).
*/
@Query(
"SELECT date(s.`end`, 'unixepoch', 'localtime') AS day, ROUND(AVG(h.milliseconds)) AS value, " +
"MIN(h.milliseconds) AS min, MAX(h.milliseconds) AS max, COUNT(*) AS count " +
"FROM hrv h JOIN sleep_session s ON s.nap = 0 AND h.timestamp BETWEEN s.start AND s.`end` " +
"WHERE h.timestamp BETWEEN :from AND :to AND h.milliseconds BETWEEN 5 AND 200 GROUP BY day ORDER BY day",
)
fun dailySleepHrv(from: Long, to: Long): Flow<List<DailyAggregate>>

@Query("SELECT date(timestamp, 'unixepoch', 'localtime') AS day, AVG(milliseconds) AS value, MIN(milliseconds) AS min, MAX(milliseconds) AS max, COUNT(*) AS count FROM hrv_sdnn WHERE timestamp BETWEEN :from AND :to GROUP BY day ORDER BY day")
fun dailyHrvSdnn(from: Long, to: Long): Flow<List<DailyAggregate>>

Expand Down
8 changes: 7 additions & 1 deletion app/src/main/kotlin/org/openstrap/app/device/ZeppJobs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ internal sealed interface ZeppJob {
* Helio Strap (firmware 3.27.0.1) it gives 58, 66, 72, 1, readiness `08`, 5→6, `0C`, `06`, 73, 19, 18, 37, 38, 39, 59,
* PAI, 56, 57, 70, 61, 74, 76, 87, 88, 78, 44 (once a day).
*
* Then 46, the one job that isn't Zepp's: skin temperature by the minute, which the strap keeps and Zepp never asks
* for. It's the only source of the temperature itself (readiness has a score, no degrees), so it runs after Zepp's
* whole list, when the strap advertises it.
*
* Not here because they never run on this strap: the AF group (the cloud doesn't allow it), 86 and the dynamic
* readiness score (no handler), BioCharge (no 0x0051), 2 (config flag off), 96 (not advertised), the HLD, BP and
* weight types. Zepp never fetches 46, 43 or 7 from it.
* weight types. Zepp never fetches 43 or 7 from it either.
*/
internal object ZeppJobs {
/**
Expand Down Expand Up @@ -76,6 +80,8 @@ internal object ZeppJobs {
if (g.bit(68, 74)) gdsp(74)
for (code in listOf(76, 87, 88, 78)) if (g.mapped(code)) gdsp(code)
if (g.bit(40, 44) && g.statisticsDue) gdsp(44)
// Not Zepp's: skin temperature, after everything of Zepp's.
if (g.mapped(46)) gdsp(46)
}

/** A sync on demand (a data-available push) runs only the GDSP jobs of [codes], in the same order. */
Expand Down
Loading