diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 8867175c..b0c80bc5 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -56,9 +56,11 @@
-
+
+
+
diff --git a/app/src/main/kotlin/org/openstrap/app/data/HealthRepository.kt b/app/src/main/kotlin/org/openstrap/app/data/HealthRepository.kt
index cd93be46..918f5351 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/HealthRepository.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/HealthRepository.kt
@@ -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)
@@ -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) {
diff --git a/app/src/main/kotlin/org/openstrap/app/data/HeartReadings.kt b/app/src/main/kotlin/org/openstrap/app/data/HeartReadings.kt
new file mode 100644
index 00000000..919ffe67
--- /dev/null
+++ b/app/src/main/kotlin/org/openstrap/app/data/HeartReadings.kt
@@ -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>, from: Long, to: Long): List> =
+ 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? = series.minByOrNull { it.second }
+
+ /** The mean of [series]' readings, to the nearest bpm; null without readings. */
+ fun mean(series: List>): 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>, strapMax: Int?): Pair? {
+ 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)
+ }
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/data/NightMetrics.kt b/app/src/main/kotlin/org/openstrap/app/data/NightMetrics.kt
index 7e4a5e8d..378c9fdd 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/NightMetrics.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/NightMetrics.kt
@@ -1,5 +1,6 @@
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
@@ -7,6 +8,23 @@ 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, start: Long, end: Long): List =
+ 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): 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, 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) }
diff --git a/app/src/main/kotlin/org/openstrap/app/data/ReadinessModel.kt b/app/src/main/kotlin/org/openstrap/app/data/ReadinessModel.kt
index 5629ecb6..46c5c348 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/ReadinessModel.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/ReadinessModel.kt
@@ -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. */
diff --git a/app/src/main/kotlin/org/openstrap/app/data/RecoveryEngine.kt b/app/src/main/kotlin/org/openstrap/app/data/RecoveryEngine.kt
index d260ce1f..ce319c14 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/RecoveryEngine.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/RecoveryEngine.kt
@@ -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() }
@@ -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),
diff --git a/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt b/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt
index 14c4898b..cea1ae26 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt
@@ -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() }),
diff --git a/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt b/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt
index bdd8e7fc..6df15fba 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt
@@ -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>
+ /**
+ * 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>
+
@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>
diff --git a/app/src/main/kotlin/org/openstrap/app/device/ZeppJobs.kt b/app/src/main/kotlin/org/openstrap/app/device/ZeppJobs.kt
index 475290f0..32ced568 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/ZeppJobs.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/ZeppJobs.kt
@@ -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 {
/**
@@ -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. */
diff --git a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt
index 9d7d2f79..f8c05881 100644
--- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt
+++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt
@@ -27,9 +27,11 @@ import androidx.health.connect.client.records.HeartRateRecord
import androidx.health.connect.client.records.HeartRateVariabilityRmssdRecord
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.RestingHeartRateRecord
import androidx.health.connect.client.records.SleepSessionRecord
import androidx.health.connect.client.records.StepsRecord
+import androidx.health.connect.client.records.Vo2MaxRecord
import androidx.health.connect.client.records.metadata.Device
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.time.TimeRangeFilter
@@ -96,16 +98,18 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
)
/**
- * Asked for with [permissions], but not needed: without them everything else is still written and the calories
- * are left out, so a grant from before calories, or one turned off, keeps working.
+ * Asked for with [permissions], but not needed: without them everything else is still written and those records
+ * (calories, breathing rate, VO2 max) are left out, so a grant from before them, or one turned off, keeps working.
*/
- val caloriePermissions = setOf(
+ val optionalPermissions = setOf(
HealthPermission.getWritePermission(ActiveCaloriesBurnedRecord::class),
HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class),
+ HealthPermission.getWritePermission(RespiratoryRateRecord::class),
+ HealthPermission.getWritePermission(Vo2MaxRecord::class),
)
- /** What a write asks Health Connect for: the needed ones with the optional calories, so they are offered in the same screen. */
- val requestedPermissions: Set get() = permissions + caloriePermissions
+ /** What a write asks Health Connect for: the needed ones with the optional ones, so they are offered in the same screen. */
+ val requestedPermissions: Set get() = permissions + optionalPermissions
/** Reading back what was exported; history is the permission to read further back than 30 days. */
val readPermissions: Set
@@ -131,9 +135,9 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
suspend fun hasPermissions(): Boolean =
client.permissionController.getGrantedPermissions().containsAll(permissions)
- /** Whether the optional calorie permissions are granted, for the Health Connect page's offer to ask again. */
- suspend fun hasCaloriePermissions(): Boolean =
- client.permissionController.getGrantedPermissions().containsAll(caloriePermissions)
+ /** Whether the optional permissions are granted, for the Health Connect page's offer to ask again. */
+ suspend fun hasOptionalPermissions(): Boolean =
+ client.permissionController.getGrantedPermissions().containsAll(optionalPermissions)
/** The record reads the user has granted (any of them is enough to import that kind). */
suspend fun hasReadPermissions(): Boolean =
@@ -173,18 +177,22 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
records += heartRate(from, to)
records += steps(from, to)
records += workouts(dao.appWorkoutsOnce(from, to))
+ val strapSessions = strapWorkouts(from, to)
+ records += strapSessions
val (kcal, kcalRanges) = calories(from, to, now)
records += kcal
records += sleep(from, to, now)
+ records += bloodOxygen(from, to)
- for (o in dao.spo2Once(from, to)) {
- if (o.percent !in 70..100) continue
- records += OxygenSaturationRecord(
- time = Instant.ofEpochSecond(o.timestamp), zoneOffset = offset(o.timestamp),
- percentage = Percentage(o.percent.toDouble()),
- metadata = meta("spo2:${o.timestamp}"),
- )
+ // Each only with its permission granted, as the calories are.
+ val granted = client.permissionController.getGrantedPermissions()
+ val replaced = mutableListOf, TimeRangeFilter>>()
+ if (HealthPermission.getWritePermission(RespiratoryRateRecord::class) in granted) records += breathing(from, to)
+ if (HealthPermission.getWritePermission(Vo2MaxRecord::class) in granted) {
+ // Time is the workout's end, so the range to replace is the one the records are looked up by.
+ replaced += Vo2MaxRecord::class to TimeRangeFilter.between(Instant.ofEpochSecond(from), Instant.ofEpochSecond(to))
+ records += vo2max(from, to)
}
for (h in dao.hrvOnce(from, to)) {
@@ -199,8 +207,9 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
val resting = restingHr(from, to, ZoneId.systemDefault())
records += resting
- store.writeSerially(writeLock, records, kcalRanges + (SleepSessionRecord::class to sleepRange(from, to))) {
+ store.writeSerially(writeLock, records, kcalRanges + replaced + (SleepSessionRecord::class to sleepRange(from, to))) {
dropMovedRestingHr(resting)
+ dropStaleStrapWorkouts(from, to, strapSessions)
}
return records.size
}
@@ -290,7 +299,9 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
val (from, to) = AutoHealthConnect.workoutRange(w.from, end, now)
val (kcal, kcalRanges) = calories(w.from, end, now)
val records = heartRate(from, to) + steps(from, to) + workouts(listOf(w)) + kcal
- store.writeSerially(writeLock, records, kcalRanges)
+ // A strap workout this one now overlaps was written before it was known; its record goes.
+ val strap = strapWorkouts(w.from, end)
+ store.writeSerially(writeLock, records, kcalRanges) { dropStaleStrapWorkouts(w.from, end, strap) }
return records.size
}
@@ -365,6 +376,71 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
)
}
+ /**
+ * One blood oxygen record per stored reading, the percent as the strap sent it. Only 80 to 100, the range Zepp
+ * keeps and so the one stored ([org.openstrap.protocol.history.SpO2Reading.isPlausible]).
+ */
+ internal suspend fun bloodOxygen(from: Long, to: Long): List = dao.spo2Once(from, to)
+ .filter { it.percent in SPO2_KEPT }
+ .map { o ->
+ OxygenSaturationRecord(
+ time = Instant.ofEpochSecond(o.timestamp), zoneOffset = offset(o.timestamp),
+ percentage = Percentage(o.percent.toDouble()),
+ metadata = meta("spo2:${o.timestamp}"),
+ )
+ }
+
+ /** Breathing rate: one record per stored sample, the value as the strap sent it. */
+ internal suspend fun breathing(from: Long, to: Long): List = dao.breathRateOnce(from, to).map { b ->
+ RespiratoryRateRecord(
+ time = Instant.ofEpochSecond(b.timestamp), zoneOffset = offset(b.timestamp),
+ rate = b.perMinute.toDouble(),
+ metadata = meta("breath:${b.timestamp}"),
+ )
+ }
+
+ /**
+ * The strap's own VO2 max, one record per strap workout that has a figure of 1 to 100 (the workout's, else its
+ * sport effect's, as the app shows it), at the workout's end, [Workouts.endOf] with its effect. Only the records
+ * with that time in [from, to] are returned, so a replaced range matches them. OpenStrap's own estimates aren't sent.
+ */
+ internal suspend fun vo2max(from: Long, to: Long): List {
+ val reach = org.openstrap.app.data.Workouts.EFFECT_WINDOW_S
+ val effects = dao.sportEffectsOnce(from, to + reach)
+ return dao.workoutsOnce(from - reach, to).mapNotNull { w ->
+ val effect = org.openstrap.app.data.Workouts.effectOf(w, effects)
+ val value = (w.vo2max ?: effect?.vo2max?.let(Math::round))?.takeIf { it in 1..100 } ?: return@mapNotNull null
+ val time = effect?.end ?: w.end
+ if (time !in from..to) return@mapNotNull null
+ Vo2MaxRecord(
+ time = Instant.ofEpochSecond(time), zoneOffset = offset(time),
+ vo2MillilitersPerMinuteKilogram = value.toDouble(),
+ measurementMethod = Vo2MaxRecord.MEASUREMENT_METHOD_OTHER,
+ metadata = meta("vo2max:${w.start}"),
+ )
+ }
+ }
+
+ /**
+ * Workouts the strap recorded, as exercise sessions. The strap also records its own session for a workout started
+ * on the phone, so one overlapping a phone workout is left out (that one goes out as [workouts]). No calories: they
+ * go out by the hour and day.
+ */
+ internal suspend fun strapWorkouts(from: Long, to: Long): List {
+ val strap = dao.workoutsOnce(from, to).filter { it.end > it.start }
+ if (strap.isEmpty()) return emptyList()
+ val phone = dao.appWorkoutsOnce(strap.minOf { it.start }, strap.maxOf { it.end })
+ return strap.filter { w -> phone.none { it.from < w.end && (it.end ?: Long.MAX_VALUE) > w.start } }.map { w ->
+ androidx.health.connect.client.records.ExerciseSessionRecord(
+ startTime = Instant.ofEpochSecond(w.start), startZoneOffset = offset(w.start),
+ endTime = Instant.ofEpochSecond(w.end), endZoneOffset = offset(w.end),
+ exerciseType = exerciseType(w.sportType),
+ title = org.openstrap.app.data.Workouts.sportName(w.sportType),
+ metadata = meta("strapworkout:${w.start}"),
+ )
+ }
+ }
+
/** Workouts recorded on the phone, as exercise sessions; GPS distance with them (a step estimate stays here). */
private fun workouts(list: List): List {
val records = mutableListOf()
@@ -572,5 +648,28 @@ internal suspend fun RecordStore.dropMovedRestingHr(written: List) {
+ val own = ownRecords(
+ androidx.health.connect.client.records.ExerciseSessionRecord::class,
+ TimeRangeFilter.between(Instant.ofEpochSecond(from), Instant.ofEpochSecond(to)),
+ ) ?: return
+ val keep = written.mapTo(HashSet()) { it.metadata.clientRecordId }
+ val stale = own.filter { r ->
+ r.metadata.clientRecordId?.startsWith(STRAP_WORKOUT_PREFIX) == true && r.metadata.clientRecordId !in keep
+ }.map { it.metadata.id }
+ stale.chunked(HC_BATCH).forEach { deleteIds(androidx.health.connect.client.records.ExerciseSessionRecord::class, it) }
+}
+
+/** The blood oxygen percents that are kept, and so exported: Zepp's range. */
+private val SPO2_KEPT = 80..100
+
+/** The start of a strap workout session's clientRecordId. */
+private const val STRAP_WORKOUT_PREFIX = "openstrap:strapworkout:"
+
/** A resting heart rate record's date where it was written, by its own offset, or null without one. */
private fun dateOf(r: RestingHeartRateRecord): java.time.LocalDate? = r.zoneOffset?.let { r.time.atOffset(it).toLocalDate() }
diff --git a/app/src/main/kotlin/org/openstrap/app/presentation/DataCopy.kt b/app/src/main/kotlin/org/openstrap/app/presentation/DataCopy.kt
index d36b289c..02dcee0e 100644
--- a/app/src/main/kotlin/org/openstrap/app/presentation/DataCopy.kt
+++ b/app/src/main/kotlin/org/openstrap/app/presentation/DataCopy.kt
@@ -30,7 +30,7 @@ object RecoveryCopy {
is Recovery.Detail.Breathing -> strings.format(R.string.core_data_recovery_breathing, Signed.of(d.vsUsual, 1, locale))
is Recovery.Detail.BloodOxygen -> strings.format(
R.string.core_data_recovery_blood_oxygen,
- String.format(locale, "%.1f", d.percent),
+ whole(Math.round(d.percent), locale),
Signed.of(d.vsUsual, 1, locale),
)
is Recovery.Detail.Load -> strings.format(R.string.core_data_recovery_load, whole(d.yesterday, locale), whole(d.usual, locale))
diff --git a/app/src/main/kotlin/org/openstrap/app/presentation/DetailCopy.kt b/app/src/main/kotlin/org/openstrap/app/presentation/DetailCopy.kt
index 2d350955..e8e677e0 100644
--- a/app/src/main/kotlin/org/openstrap/app/presentation/DetailCopy.kt
+++ b/app/src/main/kotlin/org/openstrap/app/presentation/DetailCopy.kt
@@ -22,6 +22,25 @@ internal object DetailCopy {
else -> strings.get(R.string.core_detail_status_usual)
}
+ /**
+ * How far a skin temperature is from your normal, signed and with its unit, on the cards and rows that have room for
+ * no more: "+0.3 °C", "\u22120.2 °C". [change] is the level minus your normal's mean; none reads "+0.0 °C".
+ */
+ fun changeWithUnit(metric: Metric, change: Float): String = "${metric.formatChange(change)} ${metric.unit}"
+
+ /**
+ * The status line under a skin temperature's level on a day's detail: its signed [change] from your normal with the
+ * unit, then which side of it [status] (History.status's 1, -1 or 0) puts it on: "-0.7 °C, below your normal".
+ */
+ fun skinChangeWord(metric: Metric, change: Float, status: Int, strings: Strings = Strings.app): String = strings.format(
+ when (status) {
+ 1 -> R.string.core_detail_skin_above
+ -1 -> R.string.core_detail_skin_below
+ else -> R.string.core_detail_skin_within
+ },
+ changeWithUnit(metric, change),
+ )
+
/** Where a chart's point sits against your normal: inside it stays dim, above or below it gets the full colour. */
enum class Level { Inside, Above, Below }
@@ -86,20 +105,48 @@ internal object DetailCopy {
private fun counted(n: Int, nightly: Boolean, strings: Strings): String =
strings.plural(if (nightly) R.plurals.core_detail_nights else R.plurals.core_detail_days, n, numberWord(n, strings))
+ /**
+ * The day's latest reading of blood oxygen or stress: the clock time [at] it was taken, for blood oxygen whether it was
+ * taken [asleep] (in the sleep window), for stress its [level].
+ */
+ data class Latest(val at: String, val asleep: Boolean = false, val level: StressLevel? = null)
+
+ /**
+ * "%, daytime, latest at 14:05" or "%, while asleep, latest at 05:10", or "High, latest at 14:05" for a metric with
+ * no [unit] (stress, whose level leads); null without a [latest], or a level for a metric with no unit.
+ */
+ private fun latestLabel(unit: String, latest: Latest?, strings: Strings): String? = when {
+ latest == null -> null
+ unit.isEmpty() -> latest.level?.let { strings.format(R.string.core_detail_label_stress_latest_at, it.word(strings), latest.at) }
+ else -> strings.format(
+ if (latest.asleep) R.string.core_detail_label_unit_asleep_latest_at else R.string.core_detail_label_unit_daytime_latest_at,
+ unit, latest.at,
+ )
+ }
+
/**
* The label under the value: what the number is for the range. "bpm now", "ms, day average", "steps, average of
- * the last 7 days". [live] is heart rate read live this minute.
+ * the last 7 days". [live] is heart rate read live this minute, [estimated] a resting heart rate unstrap worked out itself,
+ * [latest] the day's latest reading of blood oxygen or stress, which their day says instead of an average.
*/
- fun valueLabel(metric: Metric, range: Range, live: Boolean = false, today: Boolean = true, strings: Strings = Strings.app): String {
+ fun valueLabel(
+ metric: Metric, range: Range, live: Boolean = false, today: Boolean = true, estimated: Boolean = false,
+ latest: Latest? = null, strings: Strings = Strings.app,
+ ): String {
val unit = metric.unit
// One string with the unit and one without, so a translator writes the capital rather than the code adding it.
fun with(bare: Int, withUnit: Int) = if (unit.isEmpty()) strings.get(bare) else strings.format(withUnit, unit)
return when (range) {
Range.Day -> when (metric) {
Metric.HeartRate -> strings.get(if (live) R.string.core_detail_label_bpm_now else R.string.core_detail_label_bpm_latest)
- Metric.RestingHr -> strings.get(R.string.core_detail_label_bpm_resting)
+ Metric.RestingHr -> strings.get(
+ if (estimated) R.string.core_detail_label_bpm_resting_estimated else R.string.core_detail_label_bpm_resting,
+ )
Metric.Steps -> strings.get(if (today) R.string.core_detail_label_steps_today else R.string.core_detail_label_steps)
Metric.Breathing -> strings.get(R.string.core_detail_label_breathing)
+ // Blood oxygen's and stress's day is their latest reading, with the time it was taken ([latest]).
+ Metric.Spo2, Metric.Stress -> latestLabel(unit, latest, strings)
+ ?: with(R.string.core_detail_label_day_average, R.string.core_detail_label_unit_day_average)
else -> with(R.string.core_detail_label_day_average, R.string.core_detail_label_unit_day_average)
}
Range.Week -> if (metric == Metric.Steps) strings.get(R.string.core_detail_label_steps_week)
diff --git a/app/src/main/kotlin/org/openstrap/app/presentation/MetricCopy.kt b/app/src/main/kotlin/org/openstrap/app/presentation/MetricCopy.kt
index 22642114..53eb1ef2 100644
--- a/app/src/main/kotlin/org/openstrap/app/presentation/MetricCopy.kt
+++ b/app/src/main/kotlin/org/openstrap/app/presentation/MetricCopy.kt
@@ -14,7 +14,7 @@ import java.util.Locale
enum class Metric(@StringRes private val titleId: Int, @StringRes private val unitId: Int, val decimals: Int, val daily: DailyMetric) {
HeartRate(R.string.core_metric_heart_rate, R.string.core_unit_bpm, 0, DailyMetric.HeartRate),
RestingHr(R.string.core_metric_resting_hr, R.string.core_unit_bpm, 0, DailyMetric.RestingHr),
- Hrv(R.string.core_metric_hrv, R.string.core_unit_ms, 0, DailyMetric.Hrv),
+ Hrv(R.string.core_metric_hrv, R.string.core_unit_ms, 0, DailyMetric.SleepHrv),
Spo2(R.string.core_metric_spo2, 0, 0, DailyMetric.Spo2),
Stress(R.string.core_metric_stress, 0, 0, DailyMetric.Stress),
SkinTemperature(R.string.core_metric_skin_temperature, R.string.core_unit_celsius, 1, DailyMetric.SkinTemperature),
diff --git a/app/src/main/kotlin/org/openstrap/app/presentation/StressLevel.kt b/app/src/main/kotlin/org/openstrap/app/presentation/StressLevel.kt
new file mode 100644
index 00000000..20f5123b
--- /dev/null
+++ b/app/src/main/kotlin/org/openstrap/app/presentation/StressLevel.kt
@@ -0,0 +1,39 @@
+package org.openstrap.app.presentation
+
+import androidx.annotation.StringRes
+import kotlin.math.roundToInt
+import org.openstrap.app.R
+import org.openstrap.app.i18n.Strings
+
+/**
+ * How stressed a stress reading is, in Zepp's bands: relaxed 0 to 39, normal 40 to 59, medium 60 to 79, high 80 to 100
+ * (the same bands [org.openstrap.app.data.Recovery.STRESS_FROM] documents). A reading is judged by the level of the
+ * number shown, not against your usual.
+ */
+enum class StressLevel(@StringRes private val id: Int) {
+ Relaxed(R.string.glow_stress_relaxed),
+ Normal(R.string.glow_stress_normal),
+ Medium(R.string.glow_stress_medium),
+ High(R.string.glow_stress_high),
+ ;
+
+ /** The level's name: "Relaxed", "Normal", "Medium" or "High". */
+ fun word(strings: Strings = Strings.app): String = strings.get(id)
+
+ companion object {
+ private const val NORMAL_FROM = 40
+ private const val MEDIUM_FROM = 60
+ private const val HIGH_FROM = 80
+
+ /** The level of a stress [value], read as the whole number it is shown as, so the word agrees with the digits. */
+ fun of(value: Float): StressLevel {
+ val shown = value.roundToInt()
+ return when {
+ shown >= HIGH_FROM -> High
+ shown >= MEDIUM_FROM -> Medium
+ shown >= NORMAL_FROM -> Normal
+ else -> Relaxed
+ }
+ }
+ }
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DataStates.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DataStates.kt
index 8d225c03..eb17de63 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DataStates.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DataStates.kt
@@ -183,7 +183,8 @@ fun DayUiState.previewed(preview: DataPreview?): DayUiState = when (preview) {
private fun DayUiState.withoutNight() = copy(
sleep = null, previousSleepScore = null, sleepStages = emptyList(), sleepBreakdown = null, sleepSpo2 = emptyList(),
- osaResult = null, osaEvents = emptyList(), sleepHeartRate = emptyList(), sleepHrv = emptyList(), sleepSkinTemperature = emptyList(),
+ osaResult = null, osaEvents = emptyList(), sleepHeartRate = emptyList(), sleepHeartMinutes = emptyList(), sleepHrv = emptyList(),
+ sleepSkinTemperature = emptyList(),
)
/**
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt
index f67ffd9e..11ac284e 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt
@@ -32,6 +32,7 @@ import org.openstrap.app.data.DayValue
import org.openstrap.app.data.RecoveryResult
import org.openstrap.app.data.SleepEdits
import org.openstrap.app.data.SleepHistory
+import org.openstrap.app.data.HeartReadings
import org.openstrap.app.data.Summaries
import org.openstrap.app.data.Today
import org.openstrap.app.data.catching
@@ -69,6 +70,11 @@ data class DayUiState(
val hourlySteps: List = List(24) { 0f },
val activeHours: Int = 0,
val heartRate: List = emptyList(),
+ /**
+ * The day's stored heart rate readings, one a minute (time, bpm): what its lowest and
+ * highest come from, not [heartRate]'s averages.
+ */
+ val heartMinutes: List> = emptyList(),
val latestHeartRate: Int? = null,
val restingHeartRate: Int? = null,
/** True when [restingHeartRate] is our own estimate rather than the strap's value. */
@@ -123,6 +129,8 @@ data class DayUiState(
val nights: List = emptyList(),
/** Heart rate across the night window (5-minute averages), so sleep before midnight is included. */
val sleepHeartRate: List = emptyList(),
+ /** The night window's stored heart rate readings, one a minute (time, bpm), for the night's lowest. */
+ val sleepHeartMinutes: List> = emptyList(),
/** HRV and skin temperature read during the night's main sleep, before midnight too, for the night-scoped details. */
val sleepHrv: List = emptyList(),
val sleepSkinTemperature: List = emptyList(),
@@ -139,6 +147,20 @@ data class DayUiState(
) {
/** From the stages, else the session's own count: a night without stages has its awake minutes out. */
val asleepSeconds: Long? get() = sleepBreakdown?.asleepSeconds ?: sleep?.let(org.openstrap.app.data.SleepHistory::asleepSeconds)
+
+ /**
+ * True when the Sleep score shown isn't the strap's own: the user moved the sleep's times 15 minutes or more, so
+ * unstrap adjusted the strap's score ([SleepEdits.anchored]).
+ */
+ val sleepScoreAdjusted: Boolean
+ get() = sleep != null && sleepAsDetected != null && sleep.score != null &&
+ !SleepEdits.keepsScore(sleepAsDetected, sleep.start, sleep.end)
+
+ /**
+ * The day's lowest and highest heart rate from the stored readings, the high the strap's own maximum when higher
+ * ([HeartReadings.heartRange]).
+ */
+ val heartRateRange: Pair? get() = HeartReadings.heartRange(heartMinutes, dailyMaxHeartRate)
}
/** The day's Recovery couldn't be worked out. [yesterday] is yesterday's score, shown dimmed in its place, when known. */
@@ -460,6 +482,7 @@ class DayViewModel(
val sleep = data.sleep
val series = Summaries.heartRateSeries(data.heartRate, data.minutes)
val hourly = Summaries.hourlySteps(data.minutes, data.day.from)
+ val nightSeries = Summaries.heartRateSeries(data.nightHeartRate, emptyList())
return DayUiState(
loaded = true,
date = data.date,
@@ -468,6 +491,7 @@ class DayViewModel(
hourlySteps = hourly,
activeHours = Summaries.activeHours(hourly),
heartRate = Summaries.bucketAverage(series).map { ChartPoint(it.first, it.second.toFloat()) },
+ heartMinutes = series,
latestHeartRate = series.lastOrNull()?.second,
restingHeartRate = data.restingTrend.lastOrNull()?.value?.toInt(),
restingEstimated = data.restingEstimated.lastOrNull() ?: false,
@@ -501,9 +525,10 @@ class DayViewModel(
activeCalories = data.activeCalories,
alerts = data.alerts,
nights = data.nights,
- sleepHeartRate = Summaries.bucketAverage(Summaries.heartRateSeries(data.nightHeartRate, emptyList())).map {
+ sleepHeartRate = Summaries.bucketAverage(nightSeries).map {
ChartPoint(it.first, it.second.toFloat())
},
+ sleepHeartMinutes = nightSeries,
sleepHrv = data.sleepHrv.map { ChartPoint(it.timestamp, it.milliseconds.toFloat()) },
sleepSkinTemperature = data.sleepSkin.map { ChartPoint(it.timestamp, it.celsius) },
dayStart = data.day.from,
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt
index caa3039b..0f692d7a 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt
@@ -358,7 +358,7 @@ object InfoCopy {
if (strapScore != null) add(strings.format(R.string.day_info_recovery_note_strap, strapScore))
ready ?: return@buildList
if (ready.capped) add(strings.get(R.string.day_info_recovery_note_capped))
- ready.fallbackHrv?.let { add(strings.format(R.string.day_info_recovery_note_hrv, it.toInt())) }
+ ready.fallbackHrv?.let { add(strings.format(R.string.day_info_recovery_note_hrv, Math.round(it))) }
ready.fallbackRestingHr?.let { add(strings.format(R.string.day_info_recovery_note_resting_hr, it.toInt())) }
if (ready.hrvWeekThin) add(strings.format(R.string.day_info_recovery_note_week_thin, ready.hrvWeekNights))
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/LatestReading.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/LatestReading.kt
new file mode 100644
index 00000000..4bb40d01
--- /dev/null
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/LatestReading.kt
@@ -0,0 +1,94 @@
+package org.openstrap.app.ui.dashboard
+
+import org.openstrap.app.R
+import org.openstrap.app.i18n.Strings
+import org.openstrap.app.presentation.ChartPoint
+import org.openstrap.app.presentation.StressLevel
+
+/**
+ * Blood oxygen and stress on Today, All metrics, the Recovery tab and the details opened from them: the day's latest
+ * reading and when it was taken, as heart rate leads with its latest. The strap reads blood oxygen day and night, so a
+ * night's average is only on the Sleep and Recovery tabs ([SleepCopy.nightValue]). Stress is judged by the level of the
+ * reading shown ([StressLevel]): its line says the level, and only a High reading gets a tag and a rim ([stressTag]).
+ * The sentence under its chart still reads the day's average against your usual.
+ */
+internal object LatestReading {
+ /** The newest of the day's blood oxygen readings, day or night; null before the day has one. */
+ fun spo2(state: DayUiState): ChartPoint? = state.spo2.maxByOrNull { it.x }
+
+ /** The newest of the day's stress readings, those during and after a workout already left out; null before the day has one. */
+ fun stress(state: DayUiState): ChartPoint? = state.stress.maxByOrNull { it.x }
+
+ /** The metrics whose day leads with their latest reading. */
+ val METRICS: Set = setOf(
+ org.openstrap.app.presentation.Metric.Spo2, org.openstrap.app.presentation.Metric.Stress,
+ )
+
+ /** [metric]'s latest reading of the day, null for a metric that doesn't lead with one or before it has one. */
+ fun of(metric: org.openstrap.app.presentation.Metric, state: DayUiState): ChartPoint? = when (metric) {
+ org.openstrap.app.presentation.Metric.Spo2 -> spo2(state)
+ org.openstrap.app.presentation.Metric.Stress -> stress(state)
+ else -> null
+ }
+
+ /** How old a reading may be, in seconds, before cards and rows say when it was taken. */
+ const val STALE_AFTER_S = 60 * 60L
+
+ /** Whether a reading taken at [at] is more than an hour before [now] (epoch seconds); every reading of a past day is. */
+ fun isStale(at: Long, now: Long): Boolean = now - at > STALE_AFTER_S
+
+ /** The day's sleep window, the main sleep's start to its end, null on a day without one. */
+ fun sleepWindow(state: DayUiState): LongRange? = state.sleep?.let { it.start..it.end }
+
+ /** Whether a reading at [at] falls inside the sleep [window]; without a window every reading counts as daytime. */
+ fun isAsleep(at: Long, window: LongRange?): Boolean = window != null && at in window
+
+ /**
+ * The indices of a chart's [count] readings, one every [slot] seconds from the start of [day], that fall inside the
+ * sleep [window]; null without a window, or when it doesn't touch the day.
+ */
+ fun shadeIndices(window: LongRange?, day: LongRange, slot: Long, count: Int): IntRange? {
+ val touches = window != null && window.first <= day.last && window.last >= day.first
+ if (window == null || count < 2 || !touches) return null
+ val from = ((window.first - day.first).coerceAtLeast(0) / slot).toInt()
+ val to = ((window.last - day.first) / slot).toInt().coerceAtMost(count - 1)
+ return (from..to).takeIf { from < to }
+ }
+
+ /** Whether the day's latest blood oxygen reading was taken inside the sleep window; false without a reading. */
+ fun spo2Asleep(state: DayUiState): Boolean = spo2(state)?.let { isAsleep(it.x, sleepWindow(state)) } == true
+
+ /**
+ * The line under a blood oxygen reading taken at [at]: "Daytime" or "While asleep", with the time ("Daytime, 12:50")
+ * once the reading is stale at [now]. [time] writes an epoch second as a clock time.
+ */
+ fun spo2Line(at: Long, window: LongRange?, now: Long, strings: Strings = Strings.app, time: (Long) -> String): String {
+ val asleep = isAsleep(at, window)
+ return if (isStale(at, now)) {
+ strings.format(if (asleep) R.string.glow_today_spo2_asleep_at else R.string.glow_today_spo2_daytime_at, time(at))
+ } else {
+ strings.get(if (asleep) R.string.glow_today_spo2_asleep else R.string.glow_today_spo2_daytime)
+ }
+ }
+
+ /** The stress tag: "High" when the reading's [level] is High, null for the other levels, which have no tag and no rim. */
+ fun stressTag(level: StressLevel, strings: Strings = Strings.app): NewsTag? =
+ if (level == StressLevel.High) NewsTag(level.word(strings), goal = false) else null
+
+ /**
+ * The line under a stress reading of [value] taken at [at]: its level word ("Normal"), with the time ("Normal,
+ * 12:50") once the reading is stale at [now]. Where the High tag shows ([tagged]) the tag says the level already, so
+ * the line is null when fresh and "Latest at 12:50" when stale.
+ */
+ fun stressLine(
+ at: Long, value: Float, now: Long, tagged: Boolean, strings: Strings = Strings.app, time: (Long) -> String,
+ ): String? {
+ val level = StressLevel.of(value)
+ val stale = isStale(at, now)
+ return when {
+ tagged && level == StressLevel.High -> if (stale) strings.format(R.string.glow_today_latest_at, time(at)) else null
+ stale -> strings.format(R.string.glow_today_stress_level_at, level.word(strings), time(at))
+ else -> level.word(strings)
+ }
+ }
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt
index 0badc45e..85dfd6fa 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt
@@ -4,7 +4,6 @@ import org.openstrap.app.data.DayStat
import org.openstrap.app.data.Healthspan
import org.openstrap.app.data.History
import org.openstrap.app.data.RecoveryResult
-import org.openstrap.app.presentation.ChartPoint
import org.openstrap.app.presentation.LoadBand
import org.openstrap.app.presentation.LoadBands
import java.time.Instant
@@ -91,9 +90,3 @@ fun habitAgeOffStatus(outcome: Healthspan.Outcome?): OffStatus {
else -> OffStatus.Usual
}
}
-
-/** The day's mean stress from its [samples], null without any: the value Stress' daily history keeps. */
-fun stressMean(samples: List): Float? = samples.takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.toFloat()
-
-/** The day's stress ([stressMean] of [samples]) against your normal (`rememberNormal(Metric.Stress)`). */
-fun stressOffStatus(samples: List, normal: History.Normal?): OffStatus = offStatus(stressMean(samples), normal)
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt
index cd06d4ff..f7a09778 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt
@@ -8,6 +8,7 @@ import org.openstrap.app.data.History
import org.openstrap.app.data.SleepEdits
import org.openstrap.app.data.SleepHistory
import org.openstrap.app.data.SleepRegularity
+import org.openstrap.app.data.HeartReadings
import org.openstrap.app.i18n.Strings
import org.openstrap.app.presentation.ChartPoint
import org.openstrap.app.presentation.Ranges
@@ -47,23 +48,32 @@ internal object SleepCopy {
else -> null
}
- /** The night's heart rate readings while asleep (5-minute averages). */
+ /** The night's heart rate readings while asleep (5-minute averages), for its line. */
fun sleepHeart(state: DayUiState): List =
state.sleep?.let { s -> state.sleepHeartRate.filter { it.x in s.start..s.end } }.orEmpty()
- /** The lowest heart rate while asleep, and when. */
- fun lowestHeart(state: DayUiState): ChartPoint? = sleepHeart(state).minByOrNull { it.y }
+ /** The night's stored heart rate readings while asleep, one a minute, for its lowest and mean. */
+ private fun sleepMinutes(state: DayUiState): List> =
+ state.sleep?.let { s -> HeartReadings.within(state.sleepHeartMinutes, s.start, s.end) }.orEmpty()
- /** The average heart rate while asleep: the strap's for the night, else the average of the readings. */
- fun averageHeart(state: DayUiState): Int? =
- state.sleep?.averageHeartRate ?: sleepHeart(state).takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.roundToInt()
+ /** The lowest heart rate while asleep, and when: the lowest stored reading, not the lowest 5-minute average. */
+ fun lowestHeart(state: DayUiState): ChartPoint? =
+ HeartReadings.lowest(sleepMinutes(state))?.let { (t, bpm) -> ChartPoint(t, bpm.toFloat()) }
+
+ /** The average heart rate while asleep: the strap's for the night, else the mean of the stored readings. */
+ fun averageHeart(state: DayUiState): Int? = state.sleep?.averageHeartRate ?: HeartReadings.mean(sleepMinutes(state))
/**
- * The signals the strap reads in your sleep. Wherever one shows, on any tab, in its detail or a related row, it's
+ * The signals the strap reads only in your sleep. Wherever one shows, on any tab, in its detail or a related row, it's
* the night's average ([nightValue]) against the nights before ([nightNormal]), so they all say the same. The
* calendar day would split the night at midnight and judge it against whole days, hours off the wrist included.
+ * Blood oxygen is not one: the strap reads it all day too, so only the Sleep and Recovery tabs show its night
+ * ([NIGHT_FIGURES]), and Today and All metrics lead with its latest reading ([LatestReading]).
*/
- val NIGHT_SIGNALS: Set = setOf(Metric.Hrv, Metric.Breathing, Metric.Spo2, Metric.SkinTemperature)
+ val NIGHT_SIGNALS: Set = setOf(Metric.Hrv, Metric.Breathing, Metric.SkinTemperature)
+
+ /** The metrics whose figure on the Sleep and Recovery tabs is the night's, so their details open scoped to the night. */
+ val NIGHT_FIGURES: Set = NIGHT_SIGNALS + Metric.Spo2
/**
* What a night signal says while its normal is still forming: "Learning, 5 of 7 nights". The same words on every
@@ -123,8 +133,8 @@ internal object SleepCopy {
*/
fun nightDaily(metric: Metric): DailyMetric = if (metric == Metric.Spo2) DailyMetric.SleepSpo2 else metric.daily
- /** Whether [nightDaily] comes only from sleep (breathing rate, night blood oxygen), so Month and Year are nights too. */
- fun dailyIsNightly(metric: Metric): Boolean = metric == Metric.Spo2 || metric == Metric.Breathing
+ /** Whether [nightDaily] comes only from sleep (breathing rate, night blood oxygen, HRV), so Month and Year are nights too. */
+ fun dailyIsNightly(metric: Metric): Boolean = metric == Metric.Spo2 || metric == Metric.Breathing || metric == Metric.Hrv
/**
* The label under a night-scoped value: "ms, average asleep", "ms, average of the last 7 nights". Month and Year say
@@ -176,8 +186,10 @@ internal object SleepCopy {
/* -------------------------------------------- Sleep score ------------------------------------------- */
/** The label under the score. */
- fun scoreLabel(today: Boolean, strings: Strings = Strings.app): String =
- strings.get(if (today) R.string.day_sleep_score_label_last_night else R.string.day_sleep_score_label_that_night)
+ fun scoreLabel(today: Boolean, adjusted: Boolean = false, strings: Strings = Strings.app): String {
+ val label = strings.get(if (today) R.string.day_sleep_score_label_last_night else R.string.day_sleep_score_label_that_night)
+ return if (adjusted) strings.format(R.string.day_sleep_score_label_adjusted, label) else label
+ }
/** The Sleep score's state with no score: no sleep at all, or a night the strap didn't score. */
fun noScore(hasSleep: Boolean, today: Boolean, strings: Strings = Strings.app): Pair = when {
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt
index d26c0d6d..febd400f 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt
@@ -34,6 +34,7 @@ import java.time.format.TextStyle as DayStyle
import java.util.Locale
import kotlin.math.roundToInt
import org.openstrap.app.presentation.AFTER_FIRST_NIGHT
+import org.openstrap.app.presentation.DetailCopy
import org.openstrap.app.presentation.Metric
import org.openstrap.app.presentation.TodayCopy
@@ -52,8 +53,10 @@ internal class NightVital(
/**
* The six night vitals the Sleep tab lists (spec 5.2), always all six, in order: lowest heart rate, HRV, breathing
- * rate, blood oxygen, skin temperature (as its change from your normal once there is one) and average heart rate.
+ * rate, blood oxygen, skin temperature (its level, with the signed change from your normal under it once there is one) and
+ * average heart rate.
* HRV, breathing, blood oxygen and skin temperature are read against your previous nights once there are a week of them.
+ * Blood oxygen's line says it is the night average, and skin temperature's its change from your normal.
*/
internal fun nightVitals(state: DayUiState, firstNights: Boolean = false, strings: Strings = Strings.app): List {
val session = state.sleep
@@ -63,11 +66,14 @@ internal fun nightVitals(state: DayUiState, firstNights: Boolean = false, string
else -> strings.get(R.string.day_sleep_vital_no_reading)
}
// The same value and normal the night-scoped detail shows ([SleepCopy]).
- fun against(metric: Metric, label: String, color: Color, show: (Float, History.Normal?) -> String): NightVital {
+ fun against(
+ metric: Metric, label: String, color: Color, second: (Float, History.Normal?) -> String? = { _, _ -> null },
+ show: (Float, History.Normal?) -> String,
+ ): NightVital {
val v = SleepCopy.nightValue(state, metric) ?: return NightVital(metric, label, color, null, missing)
val n = SleepCopy.nightNormal(state, metric)
val direction = History.status(v, n)
- val status = SleepCopy.learning(state, metric, strings) ?: TodayCopy.normalWord(direction)
+ val status = second(v, n) ?: SleepCopy.learning(state, metric, strings) ?: TodayCopy.normalWord(direction)
return NightVital(metric, label, color, show(v, n), status, direction.takeIf { n != null })
}
val lowest = SleepCopy.lowestHeart(state)
@@ -81,11 +87,16 @@ internal fun nightVitals(state: DayUiState, firstNights: Boolean = false, string
against(Metric.Breathing, strings.get(R.string.day_info_breathing_name), MetricColors.sleepLight) { v, _ ->
Metric.Breathing.format(v)
},
- against(Metric.Spo2, strings.get(R.string.day_info_spo2_name), MetricColors.spo2) { v, _ -> "${v.roundToInt()}%" },
- // Skin temperature means little on its own; once there's a normal, show how far off it is.
- against(Metric.SkinTemperature, strings.get(R.string.day_info_skin_temp_name), MetricColors.temperature) { v, n ->
- n?.let { Metric.SkinTemperature.formatChange(v - it.mean) } ?: Metric.SkinTemperature.format(v)
- },
+ // Blood oxygen is read all day too, so its row says this is the night's average.
+ against(
+ Metric.Spo2, strings.get(R.string.day_info_spo2_name), MetricColors.spo2,
+ second = { _, _ -> strings.get(R.string.glow_today_spo2_night_average) },
+ ) { v, _ -> "${v.roundToInt()}%" },
+ // The night's average level, with how far it is from your normal under it once there is one.
+ against(
+ Metric.SkinTemperature, strings.get(R.string.day_info_skin_temp_name), MetricColors.temperature,
+ second = { v, n -> n?.let { DetailCopy.changeWithUnit(Metric.SkinTemperature, v - it.mean) } },
+ ) { v, _ -> Metric.SkinTemperature.format(v) },
NightVital(
Metric.HeartRate, strings.get(R.string.day_sleep_vital_average_heart), MetricColors.heart, average?.toString(),
if (average != null) strings.get(R.string.day_sleep_vital_while_asleep) else missing,
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt
index dfd5e759..e1c8ad42 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt
@@ -92,7 +92,7 @@ enum class OffWords {
/** Blood oxygen: only Below normal is news. */
LowOnly,
- /** Recovery, Stress, Load: Above or Below usual. */
+ /** Recovery, Load: Above or Below usual. */
Usual,
/** Last night: Long or Short. */
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt
index 1054b510..7a09c35b 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt
@@ -279,9 +279,8 @@ class FirmwareViewModel(
const val MIN_BATTERY = 30
/**
- * Off for now: since firmware 3.27.0.1 the strap's own sleep result is empty or wrong on nights it was worn
- * (2026-11-07), so no more strap updates until that is understood. The Strap page shows the version without
- * opening this page, and [install] refuses.
+ * Off for now (since 2026-11-07). The Strap page shows the version without opening this page, and [install]
+ * refuses.
*/
const val UPDATES_ENABLED = false
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt
index 453a20fe..9dca56a5 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt
@@ -15,7 +15,9 @@ import org.openstrap.app.data.RecoveryResult
import org.openstrap.app.data.WorkoutAnalysis
import org.openstrap.app.ui.dashboard.DayUiState
import org.openstrap.app.ui.dashboard.Detail
+import org.openstrap.app.presentation.DetailCopy
import org.openstrap.app.presentation.Metric
+import org.openstrap.app.ui.dashboard.LatestReading
import org.openstrap.app.ui.dashboard.SleepCopy
import org.openstrap.app.ui.dashboard.avg
import org.openstrap.app.ui.theme.MetricColors
@@ -97,6 +99,8 @@ fun metricIndex(
today: LocalDate = LocalDate.now(),
/** The strap's own Recovery for the day, shown as its estimate while OpenStrap's score is withheld, as on Today. */
strapScore: Int? = null,
+ /** The time as epoch seconds, which says whether a latest reading is old enough to show when it was taken. */
+ now: Long = java.time.Instant.now().epochSecond,
strings: Strings = Strings.app,
): List {
val rec = recovery
@@ -143,7 +147,7 @@ fun metricIndex(
),
),
),
- ) + signalGroups(state, strings) + listOf(
+ ) + signalGroups(state, now, strings) + listOf(
IndexGroup(
strings.get(R.string.glow_metrics_group_activity),
listOf(
@@ -173,10 +177,30 @@ private fun metric(
value: Float?,
@StringRes status: Int = R.string.glow_metrics_day_average,
suffix: String = "",
-) = row(strings.get(name), color, value?.let { m.format(it) + suffix }, strings.get(status), IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS)))
+ /** The status as already worded, for a latest reading whose line depends on its time. */
+ line: String? = null,
+) = row(strings.get(name), color, value?.let { m.format(it) + suffix }, line ?: strings.get(status), IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS)))
+
+/**
+ * Skin temperature's row: the night's average level, with its change from your normal in the status line once there's
+ * a normal, as the Sleep tab says it; before that, "Average asleep".
+ */
+private fun skinTemperatureRow(state: DayUiState, strings: Strings): IndexRow {
+ val m = Metric.SkinTemperature
+ val v = SleepCopy.nightValue(state, m)
+ val normal = SleepCopy.nightNormal(state, m)
+ val name = strings.get(R.string.glow_metrics_skin_temperature)
+ val target = IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS))
+ val status = if (v != null && normal != null) {
+ DetailCopy.changeWithUnit(m, v - normal.mean)
+ } else {
+ strings.get(R.string.glow_metrics_night_average)
+ }
+ return row(name, MetricColors.temperature, v?.let { m.format(it) }, status, target)
+}
/** The index's Heart and Body signals groups, a row for each of their metrics. */
-private fun signalGroups(state: DayUiState, strings: Strings): List = listOf(
+private fun signalGroups(state: DayUiState, now: Long, strings: Strings): List = listOf(
IndexGroup(
strings.get(R.string.glow_metrics_group_heart),
listOf(
@@ -184,9 +208,10 @@ private fun signalGroups(state: DayUiState, strings: Strings): List
strings, Metric.HeartRate, R.string.glow_metrics_heart_rate, MetricColors.heart, state.latestHeartRate?.toFloat(),
R.string.glow_metrics_latest_reading,
),
+ // Our own estimate says so when the strap sent none for the day.
metric(
- strings, Metric.RestingHr, R.string.glow_metrics_resting_heart_rate, MetricColors.heart,
- state.restingHeartRate?.toFloat(), R.string.glow_metrics_for_the_day,
+ strings, Metric.RestingHr, R.string.glow_metrics_resting_heart_rate, MetricColors.heart, state.restingHeartRate?.toFloat(),
+ if (state.restingEstimated) R.string.glow_metrics_for_the_day_estimated else R.string.glow_metrics_for_the_day,
),
metric(
strings, Metric.Hrv, R.string.glow_metrics_hrv, MetricColors.hrv, SleepCopy.nightValue(state, Metric.Hrv),
@@ -197,20 +222,23 @@ private fun signalGroups(state: DayUiState, strings: Strings): List
IndexGroup(
strings.get(R.string.glow_metrics_group_body),
listOf(
- // Night signals: last night's, as every tab and detail shows them (SleepCopy.NIGHT_SIGNALS).
+ // Blood oxygen leads with the day's latest reading, as heart rate does, and opens the day's detail. The line says
+ // whether it was taken awake or asleep, and when once it is an hour old.
metric(
- strings, Metric.Spo2, R.string.glow_metrics_blood_oxygen, MetricColors.spo2, SleepCopy.nightValue(state, Metric.Spo2),
- R.string.glow_metrics_night_average, suffix = "%",
- ),
- metric(
- strings, Metric.SkinTemperature, R.string.glow_metrics_skin_temperature, MetricColors.temperature,
- SleepCopy.nightValue(state, Metric.SkinTemperature), R.string.glow_metrics_night_average,
+ strings, Metric.Spo2, R.string.glow_metrics_blood_oxygen, MetricColors.spo2, LatestReading.spo2(state)?.y,
+ suffix = "%", line = latestLine(Metric.Spo2, state, now, strings, time = ::clock),
),
+ // Night signals: last night's, as every tab and detail shows them (SleepCopy.NIGHT_SIGNALS).
+ skinTemperatureRow(state, strings),
metric(
strings, Metric.Breathing, R.string.glow_metrics_breathing_rate, MetricColors.sleepLight,
SleepCopy.nightValue(state, Metric.Breathing), R.string.glow_metrics_night_average,
),
- metric(strings, Metric.Stress, R.string.glow_metrics_stress, MetricColors.stress, state.stress.avg()?.toFloat()),
+ // The latest reading, as on Today; its High tag and rim are on the Today and Recovery cards, so the line says the level.
+ metric(
+ strings, Metric.Stress, R.string.glow_metrics_stress, MetricColors.stress, LatestReading.stress(state)?.y,
+ line = latestLine(Metric.Stress, state, now, strings, time = ::clock),
+ ),
),
),
)
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt
index 41753093..04e9fed0 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt
@@ -215,7 +215,7 @@ fun GlowActivityScreen(
}
ActivityCard.Load -> DayLoadCard(r) { open(Score.Load) }
ActivityCard.HeartRate -> HeartRateCard(
- state, live, restingRange, rememberNormal(Metric.HeartRate, state.date, history),
+ state, live, restingRange,
) { onOpenMetric(Metric.HeartRate) }
ActivityCard.Facts -> DayFactsList(state, r, workouts, isToday, onEditProfile, open, partial)
ActivityCard.Workouts -> WorkoutsList(
@@ -393,12 +393,11 @@ private val LevelFillHeight = 28.dp
/**
* Heart rate (spec 5.3, 6): the day's line through your [resting] range as a dim band ([DayLine]), the number under it
- * following the finger while you hold the line. When the latest reading is off your heart rate [normal] the rim lights
- * at the line's end, over the top when above and the foot when below, with "Above normal" or "Below normal" after the
- * number (spec 2.5). Opens the heart rate detail.
+ * following the finger while you hold the line. A reading moves all day, so there is no tag and no rim (resting heart
+ * rate carries its own). Opens the heart rate detail.
*/
@Composable
-private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal?, normal: History.Normal?, onClick: () -> Unit) {
+private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal?, onClick: () -> Unit) {
val step = HEART_STEP_SECONDS
val values = remember(state.heartRate, state.dayStart) { bucket(state.heartRate, state.dayStart..state.dayEnd, step) }
var picked by remember(values) { mutableStateOf(null) }
@@ -406,12 +405,9 @@ private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal
val pad = with(LocalDensity.current) { LinePad.toPx() }
val scrubbed = picked?.let { i -> values.getOrNull(i)?.let { it.roundToInt() to state.dayStart + i * step } }
val now = scrubbed?.first ?: live ?: state.latestHeartRate
- val status = bodyOffStatus(state.latestHeartRate?.toFloat(), normal)
- val tag = offTag(OffWords.Normal, status)
- val rim = if (tag != null) dayLineRim(values, status == OffStatus.Above, PictureSize.Wide) else null
- PictureCard(MetricColors.heart, Modifier.fillMaxWidth().gridSize(CardSize.Wide), rim = rim, onClick = onClick) {
+ PictureCard(MetricColors.heart, Modifier.fillMaxWidth().gridSize(CardSize.Wide), onClick = onClick) {
EdgeTitle(
- stringResource(R.string.glow_today_heart_rate), state.restingHeartRate?.let { stringResource(R.string.glow_today_resting, it) },
+ stringResource(R.string.glow_today_heart_rate), restingNote(state),
)
if (state.heartRate.size >= 2) {
Spacer(Modifier.height(GlowLayout.TitleGap))
@@ -424,17 +420,21 @@ private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal
.scrub(values) { x -> picked = x?.let { nearestReading(values, it, width.toFloat(), pad) } },
)
}
- // The tag is about now, so a scrubbed point leaves it out.
TaggedNumber(
- now?.toString(), stringResource(R.string.glow_unit_bpm), tag.takeIf { scrubbed == null }, Modifier.padding(top = 14.dp),
+ now?.toString(), stringResource(R.string.glow_unit_bpm), null, Modifier.padding(top = 14.dp),
)
val at = scrubbed?.second ?: state.heartRate.lastOrNull()?.x
- StatusLine(TodayCopy.heartAt(live != null && scrubbed == null, at?.let(::clock)))
+ // A held point is the average of a 10-minute stretch, not one reading.
+ StatusLine(
+ if (scrubbed != null) stringResource(R.string.core_today_heart_average_from, step / SECONDS_PER_MINUTE, clock(scrubbed.second))
+ else TodayCopy.heartAt(live != null, at?.let(::clock)),
+ )
}
}
/** The heart rate line's buckets: 10 minutes each. */
private const val HEART_STEP_SECONDS = 10 * 60L
+private const val SECONDS_PER_MINUTE = 60L
/** The line's height on the card and the inset [DayLine] draws inside its edges. */
private val DayLineHeight = 70.dp
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt
index 76efc80d..9eadbbfb 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt
@@ -169,6 +169,8 @@ fun GlowLineChart(
yRange: ClosedFloatingPointRange? = null,
/** A usual range drawn as a band of the colour at 12%, no edge lines (e.g. your normal). */
band: ClosedFloatingPointRange? = null,
+ /** The readings, by index, to shade lightly behind the line (e.g. the hours asleep); null for none. */
+ shade: IntRange? = null,
/** How the average label prints a value. */
format: (Float) -> String = { it.roundToInt().toString() },
/**
@@ -212,6 +214,11 @@ fun GlowLineChart(
val axisLabels = m.measureAll(labels)
val h = g.plotBottom
onDrawBehind {
+ if (shade != null) {
+ val x0 = g.xOf(shade.first)
+ val box = Size(g.xOf(shade.last) - x0, g.plotBottom - g.top)
+ drawRect(Color.White.copy(alpha = SHADE_ALPHA), Offset(x0, g.top), box)
+ }
drawLineChartBody(g, paths, color)
if (average != null) {
@@ -242,6 +249,9 @@ fun GlowLineChart(
)
}
+/** The hours shaded behind a line chart, in white. */
+private const val SHADE_ALPHA = 0.07f
+
/** Your normal behind a chart: a band of the ink at 12% (spec 2.7). */
private const val NormalBandAlpha = ChartInk.NORMAL_BAND_ALPHA
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt
index 23826943..36e1dd17 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt
@@ -129,7 +129,7 @@ private fun ListNote(note: String, onNote: (() -> Unit)?) {
* A row in a [ListPanel]: the metric's [icon] in its ink [color] (or in [iconTint], as a workout's sport in white), the
* [name] with its [status] under it, the [value] in dot-matrix digits in its own column on the right, and the tap caret
* when [onClick] opens something (spec 2.5, Grouped list). Name and value stay white, the status Secondary. Off your
- * normal, [tag] takes the status's place as a news tag ([NewsPill]), and a row has no rim. A null [value] is a waiting row: a dim dash, the icon at 30%, and [status] says what it waits for ("After
+ * normal, [tag] sits after the [status] on its line as a news tag ([NewsPill]), and a row has no rim. A null [value] is a waiting row: a dim dash, the icon at 30%, and [status] says what it waits for ("After
* your first night"). A row that isn't a metric passes no icon. [divider] draws the hairline above the row.
*/
@Composable
@@ -139,7 +139,7 @@ fun ListRow(
value: String?,
status: String?,
modifier: Modifier = Modifier,
- /** Off your normal: the off tag in place of [status] (spec 2.5, Tags). */
+ /** Off your normal: the off tag after [status] on its line, the line giving way to it (spec 2.5, Tags). */
tag: org.openstrap.app.ui.dashboard.NewsTag? = null,
onClick: (() -> Unit)? = null,
divider: Boolean = true,
@@ -176,12 +176,7 @@ fun ListRow(
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
RowName(name)
- if (tag != null && !waiting) NewsPill(tag)
- else if (status != null) Text(
- status,
- color = if (waiting) Color.White.copy(alpha = 0.45f) else Color.White.copy(alpha = 0.6f),
- style = GlowType.secondary,
- )
+ RowLine(status, tag.takeIf { !waiting }, waiting)
}
Spacer(Modifier.width(12.dp))
if (value != null) CompositionLocalProvider(LocalCardNumbers provides opening?.numbers) {
@@ -195,6 +190,25 @@ fun ListRow(
}
}
+/** A row's second line: the [status], then the off [tag] after it, which keeps its place while the status gives way. */
+@Composable
+private fun RowLine(status: String?, tag: org.openstrap.app.ui.dashboard.NewsTag?, waiting: Boolean) {
+ if (status == null && tag == null) return
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ if (status != null) Text(
+ status,
+ Modifier.weight(1f, fill = false),
+ color = if (waiting) Color.White.copy(alpha = 0.45f) else Color.White.copy(alpha = 0.6f),
+ style = GlowType.secondary,
+ // Beside a tag the line stays on one row, the tag keeping its place.
+ maxLines = if (tag != null) 1 else Int.MAX_VALUE,
+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
+ )
+ if (status != null && tag != null) Spacer(Modifier.width(8.dp))
+ if (tag != null) NewsPill(tag)
+ }
+}
+
/** A row's icon, and the gap after it, as on the You and Strap pages. */
internal val RowIcon = 20.dp
internal val RowIconGap = 14.dp
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt
index 59209844..081d9372 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt
@@ -89,9 +89,11 @@ import org.openstrap.app.presentation.Metric
import org.openstrap.app.ui.dashboard.NIGHTLY
import org.openstrap.app.ui.dashboard.RELATED
import org.openstrap.app.presentation.Range
+import org.openstrap.app.presentation.StressLevel
import org.openstrap.app.ui.dashboard.ScreenList
import org.openstrap.app.ui.dashboard.avg
import org.openstrap.app.ui.dashboard.colorOf
+import org.openstrap.app.ui.dashboard.LatestReading
import org.openstrap.app.ui.dashboard.SleepCopy
import org.openstrap.app.ui.dashboard.siblingsOf
import java.time.LocalDate
@@ -493,14 +495,19 @@ internal fun DetailEmpty(text: String) {
private val HOURS = listOf("00", "06", "12", "18", "24")
-/** A day's value of [metric]: the live or latest heart rate, the strap's resting heart rate, the day's steps, else the average of its readings. */
+/**
+ * A day's value of [metric]: the live or latest heart rate, the resting heart rate, the day's steps, HRV from the night's
+ * readings, else the average of the day's readings.
+ */
internal fun dayValue(metric: Metric, state: DayUiState, live: Int? = null): Float? = when (metric) {
Metric.HeartRate -> (live ?: state.latestHeartRate)?.toFloat()
Metric.RestingHr -> state.restingHeartRate?.toFloat()
Metric.Steps -> state.steps.toFloat().takeIf { it > 0f }
- Metric.Hrv -> state.hrv.avg()?.toFloat()
- Metric.Spo2 -> state.spo2.avg()?.toFloat()
- Metric.Stress -> state.stress.avg()?.toFloat()
+ // The night's average, the one HRV figure on every screen ([NightMetrics.sleepHrv]).
+ Metric.Hrv -> SleepCopy.nightValue(state, Metric.Hrv)
+ // The latest reading, as heart rate: blood oxygen's night average is only on the Sleep and Recovery tabs
+ // ([SleepCopy.nightValue]); stress is judged by that reading's level ([StressLevel]).
+ Metric.Spo2, Metric.Stress -> LatestReading.of(metric, state)?.y
Metric.SkinTemperature -> state.skinTemperature.takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.toFloat()
Metric.Breathing -> state.breathRate.takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.toFloat()
}
@@ -565,15 +572,39 @@ fun GlowMetricDetailScreen(
range == Range.Day -> dayValue(metric, state, live)
else -> summary?.average
}
- // Heart rate's normal is a daily average, not a reading, so the day's reading gets no word; nor does a night's.
+ // Heart rate's normal is a daily average, not a reading, so the day's reading gets no word; nor does a night's,
+ // nor a latest reading (blood oxygen, stress), which has no baseline of its own.
+ val latestReading = !night && range == Range.Day && metric in LatestReading.METRICS
val status = when {
fromNight -> History.status(value, nightNormal)
- range == Range.Year || (range == Range.Day && metric == Metric.HeartRate) -> null
+ range == Range.Year || (range == Range.Day && metric == Metric.HeartRate) || latestReading -> null
else -> History.status(value, normal)
}
- val label = if (night) SleepCopy.nightLabel(metric, range) else DetailCopy.valueLabel(metric, range, live = live != null, today = isToday)
+ val label = if (night) SleepCopy.nightLabel(metric, range) else DetailCopy.valueLabel(
+ metric, range, live = live != null, today = isToday, estimated = metric == Metric.RestingHr && state.restingEstimated,
+ latest = LatestReading.of(metric, state)?.let {
+ DetailCopy.Latest(
+ clock(it.x), asleep = metric == Metric.Spo2 && LatestReading.spo2Asleep(state),
+ level = if (metric == Metric.Stress) StressLevel.of(it.y) else null,
+ )
+ },
+ )
+ // What the day is read against your usual with: the status of its value, or for stress, whose headline is the latest
+ // reading, of the day's average, the figure the sentence under its chart reads.
+ val dayStatus = if (latestReading && metric == Metric.Stress) History.status(state.stress.avg()?.toFloat(), normal) else status
+ // The normal the value is read against, for skin temperature's change from it, which its label says after what the
+ // number is. A day's only: a longer range's value is an average over days, not a level to place against one night.
+ val headNormal = (if (fromNight) nightNormal else normal).takeIf { range == Range.Day }
val headline = when {
- value != null -> DetailHeadline(metric.format(value, Units.DOT_LOCALE), label, DetailCopy.statusWord(status))
+ value != null -> DetailHeadline(
+ metric.format(value, Units.DOT_LOCALE), label,
+ // Skin temperature's day says how far it is from your normal, and which side, in place of the plain word.
+ if (metric == Metric.SkinTemperature && headNormal != null && status != null) {
+ DetailCopy.skinChangeWord(metric, value - headNormal.mean, status)
+ } else {
+ DetailCopy.statusWord(status)
+ },
+ )
night && range == Range.Day -> SleepCopy.nightNoValue(state.sleep != null, isToday).let { (word, why) -> DetailHeadline.none(word, why) }
night && range == Range.Week ->
DetailHeadline.none(stringResource(R.string.glow_no_reading), stringResource(R.string.glow_metrics_last_7_nights))
@@ -600,7 +631,7 @@ fun GlowMetricDetailScreen(
val sentence = when {
value == null -> null
metric == Metric.HeartRate -> SleepCopy.lowestHeart(state).let { low ->
- SleepCopy.nightHeart(low?.y?.toInt(), low?.x?.let(::clock), Math.round(value), isToday)
+ SleepCopy.nightHeart(low?.y?.let(Math::round), low?.x?.let(::clock), Math.round(value), isToday)
}
else -> DetailCopy.day(status, org.openstrap.app.presentation.DaySource.Night, isToday, nightDays)
}
@@ -634,11 +665,11 @@ fun GlowMetricDetailScreen(
} else if (range == Range.Day) {
item { DayChart(metric, state, color, value != null, normalOf = { m -> rememberNormal(m, end, history) }) { scrub = it } }
val sentence = when {
- value == null -> null
- metric == Metric.HeartRate -> state.heartRate.takeIf { it.isNotEmpty() }?.let { s ->
- DetailCopy.heartDay(s.minOf { it.y }.toInt(), s.maxOf { it.y }.toInt(), isToday)
- }
- else -> DetailCopy.day(status, org.openstrap.app.presentation.daySource(metric), isToday, normalDays)
+ // Blood oxygen's latest reading has no sentence; stress's is the day's average against your usual.
+ value == null || (latestReading && metric == Metric.Spo2) -> null
+ // The day's stored lowest and highest readings, the strap's own maximum when higher, not the chart's averages.
+ metric == Metric.HeartRate -> state.heartRateRange?.let { (low, high) -> DetailCopy.heartDay(low, high, isToday) }
+ else -> DetailCopy.day(dayStatus, org.openstrap.app.presentation.daySource(metric), isToday, normalDays)
}
if (sentence != null) item { DetailSentence(sentence) }
} else {
@@ -664,7 +695,7 @@ fun GlowMetricDetailScreen(
if (sentence != null) item { DetailSentence(sentence) }
}
val related = RELATED[metric].orEmpty()
- if (related.isNotEmpty() || night) item { RelatedList(related, state, history, onOpen, sleepRow = night) }
+ if (related.isNotEmpty() || night) item { RelatedList(related, state, history, onOpen, night = night) }
}
if (info) {
@@ -672,6 +703,7 @@ fun GlowMetricDetailScreen(
val sheetStatus = when {
night -> History.status(SleepCopy.nightValue(state, metric), nightNormal)
range == Range.Year -> null
+ latestReading -> dayStatus
else -> History.status(value, normal)
}
InfoSheet(
@@ -711,24 +743,30 @@ private fun NightChart(metric: Metric, state: DayUiState, color: Color, onScrub:
Column(Modifier.padding(top = 8.dp)) {
GlowLineChart(
values, height = 220.dp, labels = listOf(clock(window.first), clock(window.last)), color = color, showAverage = false, format = metric::format,
+ yRange = SPO2_AXIS.takeIf { metric == Metric.Spo2 },
onScrub = { i ->
- onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot) })
+ onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot, slot) })
},
)
}
}
-/** A scrubbed reading of [metric] in the headline: its value and the time it was taken, "bpm at 22:30". */
-private fun scrubAt(metric: Metric, v: Float, at: Long, strings: Strings = Strings.app) = DetailHeadline(
+/**
+ * A scrubbed point of [metric]'s line in the headline: its value and the time it starts. The line is made of averages
+ * over [slot] seconds, so it says so: "bpm, 5 min average from 22:30".
+ */
+private fun scrubAt(metric: Metric, v: Float, at: Long, slot: Long, strings: Strings = Strings.app) = DetailHeadline(
metric.format(v, Units.DOT_LOCALE),
if (metric.unit.isBlank()) {
- strings.format(R.string.glow_metrics_at_time, clock(at))
+ strings.format(R.string.glow_metrics_average_from_time, slot / SECONDS_PER_MINUTE, clock(at))
} else {
- strings.format(R.string.glow_metrics_unit_at_time, metric.unit, clock(at))
+ strings.format(R.string.glow_metrics_unit_average_from_time, metric.unit, slot / SECONDS_PER_MINUTE, clock(at))
},
null,
)
+private const val SECONDS_PER_MINUTE = 60L
+
/** A held hour's steps in the headline: "steps, 09:00 to 10:00". */
private fun hourSteps(hour: Int, steps: Float, strings: Strings = Strings.app): DetailHeadline {
val (from, to) = TimeOfDay.minutes(hour * MINUTES_PER_HOUR) to TimeOfDay.minutes((hour + 1) * MINUTES_PER_HOUR)
@@ -739,6 +777,9 @@ private fun hourSteps(hour: Int, steps: Float, strings: Strings = Strings.app):
private const val MINUTES_PER_HOUR = 60
+/** Blood oxygen's chart scale, so the lowest reading doesn't sit on the bottom edge: a fixed 80 to 100 %. */
+private val SPO2_AXIS = 80f..100f
+
/**
* The selected day's own chart: steps by the hour, the week of resting heart rates, or the day's readings as a line
* to scrub, which moves the headline ([onScrub], null on release). Heart rate's line has your resting range behind it.
@@ -781,10 +822,15 @@ private fun DayChart(metric: Metric, state: DayUiState, color: Color, hasValue:
val values = remember(series, window) { bucket(series, window, slot) }
val labels = if (window == day) HOURS else listOf(clock(window.first), clock(window.last))
val band = if (metric == Metric.HeartRate) normalOf(Metric.RestingHr)?.let { it.low..it.high } else null
+ // Blood oxygen's hours inside the sleep window are shaded, so a night reading shows as one.
+ val sleep = LatestReading.sleepWindow(state)
+ val shade = if (metric == Metric.Spo2) LatestReading.shadeIndices(sleep, window, slot, values.size) else null
GlowLineChart(
- values, height = 220.dp, labels = labels, color = color, showAverage = false, band = band, format = metric::format,
+ values, height = 220.dp, labels = labels, color = color, showAverage = false, band = band, shade = shade,
+ yRange = SPO2_AXIS.takeIf { metric == Metric.Spo2 },
+ format = metric::format,
onScrub = { i ->
- onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot) })
+ onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot, slot) })
},
)
}
@@ -858,10 +904,10 @@ internal fun series(
* [sleepRow], as a night-scoped detail has, the night's Sleep score leads.
*/
@Composable
-private fun RelatedList(related: List, state: DayUiState, history: DailyHistory, onOpen: (Detail) -> Unit, sleepRow: Boolean = false) {
+private fun RelatedList(related: List, state: DayUiState, history: DailyHistory, onOpen: (Detail) -> Unit, night: Boolean = false) {
RelatedPanel {
- if (sleepRow) SleepScoreRow(state, divider = false, onOpen)
- related.forEachIndexed { i, m -> RelatedMetricRow(m, state, history, divider = i > 0 || sleepRow, onOpen) }
+ if (night) SleepScoreRow(state, divider = false, onOpen)
+ related.forEachIndexed { i, m -> RelatedMetricRow(m, state, history, divider = i > 0 || night, onOpen, nightScoped = night) }
}
}
@@ -893,26 +939,57 @@ internal fun RecoveryScoreRow(ready: org.openstrap.app.data.Recovery.Readiness?,
ready?.score?.let { org.openstrap.app.presentation.TodayCopy.recoveryWord(it, ready.strainAlert) } ?: NO_VALUE, divider, onOpen,
)
-/** A body signal as a related row: the day's value and its word against your normal, marked when it's off normal. */
+/**
+ * A body signal as a related row: the day's value and its word against your normal, marked when it's off normal. On a
+ * page scoped to the night ([nightScoped]) blood oxygen is the night's average, elsewhere its latest reading, as
+ * stress's is; stress's High tag judges that reading's level.
+ */
@Composable
-internal fun RelatedMetricRow(m: Metric, state: DayUiState, history: DailyHistory, divider: Boolean, onOpen: (Detail) -> Unit) {
+internal fun RelatedMetricRow(
+ m: Metric, state: DayUiState, history: DailyHistory, divider: Boolean, onOpen: (Detail) -> Unit, nightScoped: Boolean = false,
+) {
// A night signal reads as everywhere else: last night's against the nights before (SleepCopy.NIGHT_SIGNALS).
- val night = m in SleepCopy.NIGHT_SIGNALS
+ val night = m in SleepCopy.NIGHT_SIGNALS || (m == Metric.Spo2 && nightScoped)
+ // Blood oxygen and stress on a day-scoped page are their latest reading, which has no normal to be read against.
+ val latest = m in LatestReading.METRICS && !night
val dayNormal = rememberNormal(m, state.date, history)
val normal = if (night) SleepCopy.nightNormal(state, m) else dayNormal
val v = if (night) SleepCopy.nightValue(state, m) else dayValue(m, state)
- // The heart rate moves all day, so it has no word against a normal.
- val status = if (m == Metric.HeartRate) null else History.status(v, normal)
+ // The heart rate moves all day, so it has no word against a normal; nor has a latest reading.
+ val status = if (m == Metric.HeartRate || latest) null else History.status(v, normal)
// A percent stays on its number, as on Recovery ("99%"): the line under it is the word, not the unit.
+ val tag = relatedTag(m, v, status)
ListRow(
m.title, colorOf(m), v?.let { if (m == Metric.Spo2) "${m.format(it)}%" else m.format(it) },
when {
v == null -> NO_VALUE
+ // Blood oxygen on a night page is the night's average.
+ night && m == Metric.Spo2 -> stringResource(R.string.glow_today_spo2_night_average)
// A night signal whose normal is still forming says so, with the count, as on every tab.
night && normal == null -> SleepCopy.learning(state, m)
+ // The time shows once the reading is an hour old or more.
+ latest -> latestLine(m, state, java.time.Instant.now().epochSecond, tagged = tag != null, time = ::clock)
+ // The tag already says which way it is off.
+ tag != null -> null
else -> DetailCopy.statusWord(status) ?: m.unit.ifEmpty { null }
},
- tag = org.openstrap.app.ui.dashboard.bodyTag(m, status), onClick = { onOpen(Detail.OfMetric(m, night)) }, divider = divider,
+ tag = tag, onClick = { onOpen(Detail.OfMetric(m, night)) }, divider = divider,
icon = m.rowIcon(),
)
}
+
+/** A related row's tag: stress is judged by the level of its reading [v] (High is tagged), the rest by [status] against their normal. */
+private fun relatedTag(m: Metric, v: Float?, status: Int?): org.openstrap.app.ui.dashboard.NewsTag? =
+ if (m == Metric.Stress) v?.let { LatestReading.stressTag(StressLevel.of(it)) } else org.openstrap.app.ui.dashboard.bodyTag(m, status)
+
+/**
+ * The line under [m]'s latest reading of the day in [state] (blood oxygen or stress) at [now]; null without a reading,
+ * or for a stress reading whose High [tagged] tag says it already and is fresh.
+ */
+internal fun latestLine(
+ m: Metric, state: DayUiState, now: Long, strings: Strings = Strings.app, tagged: Boolean = false, time: (Long) -> String,
+): String? {
+ val at = LatestReading.of(m, state) ?: return null
+ return if (m == Metric.Spo2) LatestReading.spo2Line(at.x, LatestReading.sleepWindow(state), now, strings, time)
+ else LatestReading.stressLine(at.x, at.y, now, tagged, strings, time)
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt
index f2654ff0..0ca206ed 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt
@@ -11,6 +11,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.Alignment
import androidx.compose.ui.text.style.TextOverflow
import kotlin.math.roundToInt
+import org.openstrap.app.presentation.StressLevel
import org.openstrap.app.presentation.Units
import org.openstrap.app.ui.components.cardNumber
import org.openstrap.app.ui.dashboard.SleepCopy
@@ -20,8 +21,7 @@ import org.openstrap.app.ui.dashboard.OffWords
import org.openstrap.app.ui.dashboard.bodyOffStatus
import org.openstrap.app.ui.dashboard.bodyTag
import org.openstrap.app.ui.dashboard.offTag
-import org.openstrap.app.ui.dashboard.stressMean
-import org.openstrap.app.ui.dashboard.stressOffStatus
+import org.openstrap.app.ui.dashboard.LatestReading
import org.openstrap.app.ui.glow.pictures.PictureSize
import org.openstrap.app.ui.glow.pictures.RangeFill
import org.openstrap.app.ui.glow.pictures.SplitBar
@@ -53,13 +53,13 @@ import org.openstrap.app.data.History
import org.openstrap.app.data.Recovery
import org.openstrap.app.data.RecoveryResult
import org.openstrap.app.presentation.AFTER_FIRST_NIGHT
-import org.openstrap.app.ui.dashboard.DailyHistory
import org.openstrap.app.ui.dashboard.FIRST_SCORE
import org.openstrap.app.ui.dashboard.PARTIAL_DAY
import org.openstrap.app.ui.dashboard.Wear
import org.openstrap.app.ui.dashboard.DayUiState
import org.openstrap.app.ui.dashboard.InfoCopy
import org.openstrap.app.ui.dashboard.Score
+import org.openstrap.app.presentation.DetailCopy
import org.openstrap.app.presentation.Metric
import org.openstrap.app.ui.dashboard.FAILED_SHORT
import org.openstrap.app.ui.dashboard.RECOVERY_FAILED
@@ -90,7 +90,6 @@ import org.openstrap.app.ui.glow.draw.DotSize
fun GlowRecoveryScreen(
state: DayUiState,
recovery: RecoveryResult?,
- history: DailyHistory,
/** The tab's header, or a back header when the screen is opened from a card on another tab. */
header: @Composable () -> Unit,
contentPadding: PaddingValues,
@@ -117,7 +116,7 @@ fun GlowRecoveryScreen(
firstScore: Boolean = false,
) {
val list = rememberLazyListState()
- val signals = rememberSignals(state, history)
+ val signals = rememberSignals(state)
val r = recovery
val failure = recoveryFailure?.takeIf { r == null }
val learning = r?.readiness?.calibrating == true
@@ -415,9 +414,10 @@ private fun ChargeSmall(c: Recovery.ChargeDay?, recharged: Boolean, modifier: Mo
private const val DIAL_SHARE = 0.44f
/**
- * Skin temperature as a short Wide (spec 5.1): the change from your normal in dots with °C and its off tag at the
- * left, the dial at the right centred on your normal. Off your normal the rim lights at the dial's top when above, its
- * foot when below. Before there's a normal it waits for one. Opens the skin temperature detail.
+ * Skin temperature as a short Wide (spec 5.1): last night's average in dots with °C and its off tag at the left, the
+ * dial at the right centred on your normal with the change from it written in the arc. Off your normal the rim lights at the
+ * dial's top when above, its foot when below. Before there's a normal the line says how far along it is. Opens the skin
+ * temperature detail.
*/
@Composable
private fun SkinTempCard(
@@ -438,12 +438,10 @@ private fun SkinTempCard(
Column(Modifier.weight(1f)) {
CardTitle(stringResource(R.string.glow_recovery_skin_temperature))
Spacer(Modifier.height(12.dp))
- // Off your normal the tag says which way, and nothing under the number repeats it.
+ // Last night's average, as the Sleep tab shows it; the change from your normal is read in the dial.
NumberWithTag(tag) {
androidx.compose.foundation.layout.Row(verticalAlignment = Alignment.Bottom) {
- // Against your normal once there is one; until then last night's reading, as the Sleep tab shows it.
- val shown = deviation?.let { Metric.SkinTemperature.formatChange(it, Units.DOT_LOCALE) }
- ?: today?.let { Metric.SkinTemperature.format(it, Units.DOT_LOCALE) }
+ val shown = today?.let { Metric.SkinTemperature.format(it, Units.DOT_LOCALE) }
if (shown != null) DotMatrixText(shown, Modifier.cardNumber(shown), dot = DotSize.Edge)
else WaitingDash(Modifier.padding(vertical = 8.dp))
if (shown != null) Text(
@@ -452,11 +450,11 @@ private fun SkinTempCard(
)
}
}
+ // The change from your normal is the dial's reading; the line under the number is for when there is none.
val line = when {
today == null -> waiting
normal == null || deviation == null -> learning ?: TodayCopy.normalWord(null)
- tag != null -> null
- else -> stringResource(R.string.glow_recovery_skin_close)
+ else -> null
}
if (line != null) Text(
line,
@@ -464,7 +462,10 @@ private fun SkinTempCard(
modifier = Modifier.padding(top = 6.dp), maxLines = 2, overflow = TextOverflow.Ellipsis,
)
}
- TempDial(deviation, band, MetricColors.temperature, PictureSize.Wide, Modifier.fillMaxWidth(DIAL_SHARE).height(84.dp))
+ TempDial(
+ deviation, band, MetricColors.temperature, PictureSize.Wide, Modifier.fillMaxWidth(DIAL_SHARE).height(84.dp),
+ reading = deviation?.let { DetailCopy.changeWithUnit(Metric.SkinTemperature, it) },
+ )
}
}
}
@@ -481,31 +482,37 @@ private class BodySignal(
val tag: NewsTag?,
/** What the row says while its normal is forming, "Learning, 5 of 7 nights"; null for the plain word. */
val learning: String? = null,
+ /** What the row says instead of a word against your normal: the night average, or when the day's latest reading was taken. */
+ val line: String? = null,
)
/** The Recovery tab's body signals: the rows of the list and skin temperature for its own card. */
private class Signals(val rows: List, val skin: Float?, val skinNormal: History.Normal?, val skinLearning: String?)
/**
- * Loads the last 30 days of each body signal, enough for its normal ([rememberNormal], keyed on the day and the
- * history, each normal worked out once per load), and the signals once per day state (audit K8). Breathing rate,
+ * The body signals once per day state (audit K8), each night signal against its normal. Breathing rate,
* blood oxygen and stress make the list (spec 5.1): HRV and resting heart rate are in What drove it already.
*/
@Composable
-private fun rememberSignals(state: DayUiState, history: DailyHistory): Signals {
- val stress = rememberNormal(Metric.Stress, state.date, history)
+private fun rememberSignals(state: DayUiState): Signals {
val breathName = stringResource(R.string.glow_recovery_breathing_rate)
val spo2Name = stringResource(R.string.glow_recovery_blood_oxygen)
val stressName = stringResource(R.string.glow_recovery_stress)
- return remember(state, stress) {
- fun body(metric: Metric, name: String, accent: Color, today: Float?, normal: History.Normal?, unit: String = ""): BodySignal {
+ val nightAverage = stringResource(R.string.glow_today_spo2_night_average)
+ return remember(state) {
+ fun body(
+ metric: Metric, name: String, accent: Color, today: Float?, normal: History.Normal?, unit: String = "", line: String? = null,
+ ): BodySignal {
val direction = History.status(today, normal)
return BodySignal(
metric, name, accent, today?.let { metric.format(it) + unit }, direction, bodyTag(metric, direction),
- SleepCopy.learning(state, metric),
+ SleepCopy.learning(state, metric), line,
)
}
- val stressToday = stressMean(state.stress)
+ // The row's number is the latest reading; its word is that reading's level, and only a High one is tagged.
+ val stressLatest = LatestReading.stress(state)
+ val stressTag = stressLatest?.let { LatestReading.stressTag(StressLevel.of(it.y)) }
+ val now = java.time.Instant.now().epochSecond
Signals(
listOf(
// Night signals: last night's against the nights before, as the Sleep tab and their details read them.
@@ -515,11 +522,12 @@ private fun rememberSignals(state: DayUiState, history: DailyHistory): Signals {
),
body(
Metric.Spo2, spo2Name, MetricColors.spo2, SleepCopy.nightValue(state, Metric.Spo2),
- SleepCopy.nightNormal(state, Metric.Spo2), unit = "%",
+ SleepCopy.nightNormal(state, Metric.Spo2), unit = "%", line = nightAverage,
),
BodySignal(
- Metric.Stress, stressName, MetricColors.stress, stressToday?.let { Metric.Stress.format(it) },
- History.status(stressToday, stress), offTag(OffWords.Usual, stressOffStatus(state.stress, stress)),
+ Metric.Stress, stressName, MetricColors.stress, stressLatest?.let { Metric.Stress.format(it.y) },
+ null, stressTag,
+ line = stressLatest?.let { LatestReading.stressLine(it.x, it.y, now, tagged = stressTag != null, time = ::clock) },
),
),
// Tonight's against the nights before (spec 2.7, Dial): the day's mean counts hours off the wrist, which
@@ -531,16 +539,19 @@ private fun rememberSignals(state: DayUiState, history: DailyHistory): Signals {
}
}
-/** Body signals against your normal, each opening its metric, its off tag in place of its word. [waiting] is what a row with no reading says. */
+/** Body signals against your normal, each opening its metric, its off tag after its line. [waiting] is what a row with no reading says. */
@Composable
private fun SignalsList(signals: List, waiting: String, onOpen: (Metric) -> Unit) {
ListPanel(title = stringResource(R.string.glow_recovery_body_signals), note = stringResource(R.string.glow_recovery_against_normal)) {
signals.forEachIndexed { i, s ->
ListRow(
s.label, s.accent, s.value,
+ // The tag already says which way it is off, so the word against your normal gives way to it.
when {
s.value == null -> waiting
+ s.line != null -> s.line
s.learning != null -> s.learning
+ s.tag != null -> null
else -> TodayCopy.normalWord(s.direction)
},
tag = s.tag, onClick = { onOpen(s.metric) }, divider = i > 0, icon = s.metric.rowIcon(),
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt
index 2fa2246f..dddde6ab 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt
@@ -181,7 +181,9 @@ private fun NightHero(state: DayUiState, firstNights: Boolean, onRestore: (org.o
HeroNumber(
score?.toString(),
listOfNotNull(
- TabCopy.sleepScoreLine(score),
+ TabCopy.sleepScoreLine(score).let {
+ if (state.sleepScoreAdjusted) stringResource(R.string.glow_sleep_score_adjusted, it) else it
+ },
TabCopy.woke(session.wakeCount),
),
)
@@ -260,9 +262,12 @@ internal val SleepRowColors: List = DayViewModel.SLEEP_STAGE_ROWS.let { r
private fun VitalsList(state: DayUiState, firstNights: Boolean, onOpen: (Metric) -> Unit) {
ListPanel(title = stringResource(R.string.glow_sleep_vitals_title), note = stringResource(R.string.glow_sleep_vitals_note)) {
nightVitals(state, firstNights).forEachIndexed { i, v ->
+ val tag = org.openstrap.app.ui.dashboard.bodyTag(v.metric, v.direction)
ListRow(
- v.label, v.color, v.value, v.status,
- tag = org.openstrap.app.ui.dashboard.bodyTag(v.metric, v.direction), onClick = { onOpen(v.metric) }, divider = i > 0,
+ v.label, v.color, v.value,
+ // The tag already says which way it is off, so the plain word against your normal gives way to it.
+ v.status.takeUnless { tag != null && it == org.openstrap.app.presentation.TodayCopy.normalWord(v.direction) },
+ tag = tag, onClick = { onOpen(v.metric) }, divider = i > 0,
icon = v.metric.rowIcon(),
)
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt
index 4d5ca2bc..2ae656af 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt
@@ -50,6 +50,7 @@ import org.openstrap.app.ui.components.HapticEvent
import org.openstrap.app.ui.components.rememberHaptics
import org.openstrap.app.ui.dashboard.DailyHistory
import org.openstrap.app.ui.dashboard.DayUiState
+import org.openstrap.app.ui.dashboard.LatestReading
import org.openstrap.app.ui.dashboard.SleepCopy
import org.openstrap.app.ui.dashboard.Tier
import org.openstrap.app.ui.dashboard.lookOr
@@ -785,16 +786,25 @@ private fun TodayRow(
BodyRow(
stringResource(R.string.glow_today_resting_hr), MetricColors.heart, s.restingHeartRate?.toFloat(),
normal(Metric.RestingHr), "", Metric.RestingHr,
+ source = if (s.restingEstimated) BodyValue.Estimated else BodyValue.Plain,
),
// Night signals: last night's against the nights before, as the Sleep tab and their details read them.
BodyRow(
stringResource(R.string.glow_today_hrv), MetricColors.hrv, SleepCopy.nightValue(s, Metric.Hrv),
SleepCopy.nightNormal(s, Metric.Hrv), "", Metric.Hrv, SleepCopy.learning(s, Metric.Hrv),
),
- BodyRow(
- stringResource(R.string.glow_today_blood_oxygen), MetricColors.spo2, SleepCopy.nightValue(s, Metric.Spo2),
- SleepCopy.nightNormal(s, Metric.Spo2), "%", Metric.Spo2, SleepCopy.learning(s, Metric.Spo2),
- ),
+ // Blood oxygen leads with the day's latest reading, said as daytime or asleep, with its time once an hour
+ // old. A single reading has no normal, so the row has no tag; the night's average, with its tag, is
+ // on the Sleep and Recovery tabs.
+ LatestReading.spo2(s).let { latest ->
+ BodyRow(
+ stringResource(R.string.glow_today_blood_oxygen), MetricColors.spo2, latest?.y,
+ null, "%", Metric.Spo2,
+ source = BodyValue.Latest(
+ latest?.let { LatestReading.spo2Line(it.x, LatestReading.sleepWindow(s), ctx.now, time = ::clock) }.orEmpty(),
+ ),
+ )
+ },
BodyRow(
stringResource(R.string.glow_today_breathing_rate), MetricColors.sleepLight, SleepCopy.nightValue(s, Metric.Breathing),
SleepCopy.nightNormal(s, Metric.Breathing), "", Metric.Breathing, SleepCopy.learning(s, Metric.Breathing),
@@ -807,12 +817,11 @@ private fun TodayRow(
else LastNightCard(s, ctx.firstNights, onOpenSleep, modifier, stuck = ctx.stuck, size = size)
// A live reading is never stale.
TodayCard.HeartRate -> HeartDayCard(
- s, ctx.live, size, { onOpenMetric(Metric.HeartRate) }, modifier, restingRange = ctx.restingRange, normal = normal(Metric.HeartRate),
+ s, ctx.live, size, { onOpenMetric(Metric.HeartRate) }, modifier, restingRange = ctx.restingRange,
upTo = if (ctx.live == null) ctx.upTo(s.heartRate.lastOrNull()?.x) else null,
)
TodayCard.Stress -> StressDayCard(
- s, size, normal(Metric.Stress), ctx.waiting, { onOpenMetric(Metric.Stress) }, modifier,
- upTo = ctx.upTo(s.stress.lastOrNull()?.x),
+ s, size, ctx.waiting, { onOpenMetric(Metric.Stress) }, modifier, now = ctx.now,
)
// Steps come in the same records as the rest of the day, so the day's newest reading is how far they go. The
// count stays in dots in the evening too, under the hero's: the goal tag needs a number to sit by (spec 2.5).
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt
index 20735678..b375ad29 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt
@@ -391,7 +391,7 @@ private fun ScoreRelated(score: Score, state: DayUiState, r: RecoveryResult?, hi
stringResource(if (asleep == null) R.string.glow_recovery_no_sleep else R.string.glow_recovery_asleep),
onClick = { onOpen(Detail.OfScore(Score.Sleep)) }, icon = Score.Sleep.rowIcon(),
)
- metrics.forEach { m -> RelatedMetricRow(m, state, history, divider = true, onOpen) }
+ metrics.forEach { m -> RelatedMetricRow(m, state, history, divider = true, onOpen, nightScoped = true) }
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt
index ee12fc92..6903c5d2 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt
@@ -52,6 +52,7 @@ import org.openstrap.app.data.Recovery
import org.openstrap.app.data.RecoveryResult
import org.openstrap.app.data.SleepEdits
import org.openstrap.app.data.SleepHistory
+import org.openstrap.app.data.HeartReadings
import org.openstrap.app.data.Summaries
import org.openstrap.app.data.db.SleepSession
import org.openstrap.app.data.wasoMinutes
@@ -170,7 +171,9 @@ internal fun SleepScoreDetail(
DetailHeadline(Math.round(known.average()).toString(), stringResource(R.string.glow_sleep_week_average), null)
range == Range.Week ->
DetailHeadline.none(stringResource(R.string.glow_sleep_no_scores), stringResource(R.string.glow_sleep_in_last_7_nights))
- score != null -> DetailHeadline(score.toString(), SleepCopy.scoreLabel(isToday), TabCopy.sleepScoreWord(score))
+ score != null -> DetailHeadline(
+ score.toString(), SleepCopy.scoreLabel(isToday, state.sleepScoreAdjusted), TabCopy.sleepScoreWord(score),
+ )
session == null && state.deletedSleep != null ->
DetailHeadline.none(stringResource(R.string.glow_sleep_no_score), SleepCopy.noScoreDeleted(isToday))
// The day's rows haven't arrived: nothing yet, not "No score".
@@ -451,7 +454,12 @@ private fun NightLines(state: DayUiState, window: LongRange, onScrub: (DetailHea
if (hr.isNotEmpty()) {
ChartTitle(
stringResource(R.string.glow_sleep_heart_rate),
- stringResource(R.string.glow_sleep_heart_note, hr.minOf { it.y }.toInt(), hr.map { it.y }.average().toInt()),
+ // The lowest stored reading and the night's average, as the Sleep tab says them; not the line's 5-minute averages.
+ stringResource(
+ R.string.glow_sleep_heart_note,
+ SleepCopy.lowestHeart(state)?.y?.let(Math::round) ?: Math.round(hr.minOf { it.y }),
+ SleepCopy.averageHeart(state) ?: Math.round(hr.map { it.y }.average()).toInt(),
+ ),
scrubbed = hrAt,
)
ScrubLine(hr, window, 130.dp, labels, MetricColors.heart, stringResource(R.string.glow_unit_bpm)) { hrAt = it; onScrub(it) }
@@ -649,6 +657,9 @@ internal fun NapsDetail(
// The strap sends no average for a nap, so its heart rate is the day's readings in its window.
val window = nap.start..nap.end
val hr = remember(state.heartRate, window) { state.heartRate.filter { it.x in window } }
+ val minutes = remember(state.heartMinutes, window) {
+ HeartReadings.within(state.heartMinutes, window.first, window.last)
+ }
if (hr.isNotEmpty()) {
Box(Modifier.padding(top = 16.dp)) {
ScrubLine(
@@ -656,7 +667,12 @@ internal fun NapsDetail(
stringResource(R.string.glow_unit_bpm),
) { scrub = it }
}
- Caption(SleepCopy.napHeart(hr.minOf { it.y }.toInt(), hr.map { it.y }.average().toInt()), Modifier.padding(top = 6.dp, bottom = 8.dp))
+ // The nap's lowest and average from the stored readings, not the line's averages.
+ val low = HeartReadings.lowest(minutes)?.second
+ val average = HeartReadings.mean(minutes)
+ if (low != null && average != null) {
+ Caption(SleepCopy.napHeart(low, average), Modifier.padding(top = 6.dp, bottom = 8.dp))
+ }
}
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt
index 24f854a5..866b0487 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt
@@ -7,6 +7,7 @@ import androidx.compose.ui.res.pluralStringResource
import org.openstrap.app.i18n.Strings
import org.openstrap.app.presentation.DayWords
import org.openstrap.app.presentation.Ranges
+import org.openstrap.app.presentation.StressLevel
import org.openstrap.app.presentation.Units
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
@@ -471,12 +472,15 @@ internal fun HeartCard(
MetricColors.heart, modifier.fillMaxWidth().gridSize(CardSize.Wide), onClick = onClick,
) {
EdgeTitle(
- stringResource(R.string.glow_today_heart_rate), state.restingHeartRate?.let { stringResource(R.string.glow_today_resting, it) },
+ stringResource(R.string.glow_today_heart_rate), restingNote(state),
marker = upTo,
)
val at = scrubbed?.second ?: state.heartRate.lastOrNull()?.x
EdgeValue(
- now?.toString(), stringResource(R.string.glow_unit_bpm), TodayCopy.heartAt(live != null && scrubbed == null, at?.let(::clock)),
+ now?.toString(), stringResource(R.string.glow_unit_bpm),
+ // A held point is the average of a 10-minute stretch, not one reading.
+ if (scrubbed != null) stringResource(R.string.core_today_heart_average_from, step / SECONDS_PER_MINUTE, clock(scrubbed.second))
+ else TodayCopy.heartAt(live != null, at?.let(::clock)),
)
if (state.heartRate.size >= 2) {
Spacer(Modifier.height(10.dp))
@@ -494,60 +498,60 @@ internal fun HeartCard(
/**
* Heart rate on Today (spec 4.2): the day's line through your resting range ([restingRange], your normal resting
- * heart rate) as a dim band, the latest reading or the [live] one in dots. Off your [normal] heart rate for a day, the
- * day so far running high or low, the card rims at the line's end and says Above or Below normal. One high reading
- * isn't news, a day running high is. No scrub here: that lives on Activity's Wide and in the detail.
+ * heart rate) as a dim band, the latest reading or the [live] one in dots. A reading moves all day, so the card has no
+ * tag and no rim; resting heart rate carries its own. No scrub here: that lives on Activity's Wide and in the detail.
*/
@Composable
internal fun HeartDayCard(
state: DayUiState, live: Int?, size: PictureSize, onClick: () -> Unit, modifier: Modifier = Modifier,
- restingRange: org.openstrap.app.data.History.Normal? = null, normal: org.openstrap.app.data.History.Normal? = null,
- upTo: String? = null,
+ restingRange: org.openstrap.app.data.History.Normal? = null, upTo: String? = null,
) {
val values = remember(state.heartRate, state.dayStart, state.dayEnd) { bucket(state.heartRate, state.dayStart..state.dayEnd, HEART_STEP) }
- val mean = remember(values) { values.filterNotNull().takeIf { it.isNotEmpty() }?.average()?.toFloat() }
val now = live ?: state.latestHeartRate
- val off = bodyOffStatus(mean, normal)
val at = TodayCopy.heartAt(live != null, state.heartRate.lastOrNull()?.x?.let(::clock))
TodayPictureCard(
MetricColors.heart, stringResource(R.string.glow_today_heart_rate), size, now?.toString(), stringResource(R.string.glow_unit_bpm),
- offTag(OffWords.Normal, off),
- // A Small says where the day sits against your normal once there is one, a Wide when the reading was taken.
- if (size == PictureSize.Small && normal != null && mean != null && !off.off) TodayCopy.normalWord(0) else at,
- modifier, note = state.restingHeartRate?.let { stringResource(R.string.glow_today_resting, it) },
- rim = if (rimLit(OffWords.Normal, off)) dayLineRim(values, off == OffStatus.Above, size) else null,
+ // The "Up to" marker already says when the line ends.
+ null, at.takeIf { upTo == null },
+ modifier, note = restingNote(state),
onClick = onClick, marker = upTo,
picture = if (state.heartRate.size < 2) null else { m -> DayLine(values, restingRange?.let { it.low..it.high }, MetricColors.heart, size, m) },
)
}
+/** The heart rate cards' note on the title row: the day's resting heart rate, marked as an estimate when the strap sent none. */
+@Composable
+@ReadOnlyComposable
+internal fun restingNote(state: DayUiState): String? = state.restingHeartRate?.let {
+ stringResource(if (state.restingEstimated) R.string.glow_today_resting_estimated else R.string.glow_today_resting, it)
+}
+
/** Heart rate's line on Today: a point every ten minutes. */
private const val HEART_STEP = 10 * 60L
+private const val SECONDS_PER_MINUTE = 60L
/**
* Stress on Today (spec 4.2): the day as one strip, calm to high ([DayStrip], [DayUiState.stressStrip]), the latest
- * reading in dots. The day so far against your [normal] stress says Above or Below usual, with the rim over the
- * stretch that's off.
+ * reading in dots with its level under it ([StressLevel]). Only a High latest reading tags the card "High", with the
+ * rim over the strip's latest stretch; the other levels carry neither.
*/
@Composable
internal fun StressDayCard(
- state: DayUiState, size: PictureSize, normal: org.openstrap.app.data.History.Normal?, waiting: String, onClick: () -> Unit,
- modifier: Modifier = Modifier, upTo: String? = null,
+ state: DayUiState, size: PictureSize, waiting: String, onClick: () -> Unit,
+ modifier: Modifier = Modifier, now: Long = java.time.Instant.now().epochSecond,
) {
- val off = org.openstrap.app.ui.dashboard.stressOffStatus(state.stress, normal)
val levels = state.stressStrip
- val now = state.stress.lastOrNull()
+ val latest = org.openstrap.app.ui.dashboard.LatestReading.stress(state)
+ val tag = latest?.let { org.openstrap.app.ui.dashboard.LatestReading.stressTag(StressLevel.of(it.y)) }
TodayPictureCard(
- MetricColors.stress, stringResource(R.string.glow_today_stress), size, now?.y?.roundToInt()?.toString(), null,
- offTag(OffWords.Usual, off),
+ MetricColors.stress, stringResource(R.string.glow_today_stress), size, latest?.y?.roundToInt()?.toString(), null,
+ tag,
when {
- now == null -> waiting
- // Off, the tag says how it's going and the line when it was read.
- off.off -> TodayCopy.heartAt(false, clock(now.x))
- normal == null -> TodayCopy.normalWord(null)
- else -> TodayCopy.normalWord(0)
+ latest == null -> waiting
+ // The number is the latest reading, whenever it was taken: its level, with the time once it is an hour old.
+ else -> org.openstrap.app.ui.dashboard.LatestReading.stressLine(latest.x, latest.y, now, tagged = tag != null, time = ::clock)
},
- modifier, rim = if (rimLit(OffWords.Usual, off)) dayStripRim(levels, size) else null, onClick = onClick, marker = upTo,
+ modifier, rim = if (tag != null) dayStripRim(levels, size) else null, onClick = onClick,
picture = if (levels.none { it != null }) null else { m -> DayStrip(levels, MetricColors.stress, size, m) },
)
}
@@ -868,8 +872,25 @@ internal class BodyRow(
val name: String, val color: Color, val value: Float?, val normal: org.openstrap.app.data.History.Normal?, val unit: String, val metric: Metric,
/** What the row says while its normal is forming, "Learning, 5 of 7 nights"; null for the plain word. */
val learning: String? = null,
+ /** Where [value] comes from, when it isn't a plain figure read against [normal]. */
+ val source: BodyValue = BodyValue.Plain,
)
+/** What a [BodyRow]'s value is. */
+internal sealed interface BodyValue {
+ /** The day's figure, read against your normal. */
+ data object Plain : BodyValue
+
+ /** unstrap's own estimate, which the row says. */
+ data object Estimated : BodyValue
+
+ /**
+ * The day's latest reading: the row says [line] (when it was taken, awake or asleep) instead of a word against your
+ * normal, and it has no tag or direction, since a single reading has no baseline of its own.
+ */
+ data class Latest(val line: String) : BodyValue
+}
+
/**
* Body values against your normal, each opening its metric, read and rounded as the Recovery tab's body signals are.
* [waiting] is what an empty row says.
@@ -880,15 +901,23 @@ internal fun BodyList(
) {
ListPanel(modifier, title = title, note = stringResource(R.string.glow_today_against_normal), marker = upTo) {
rows.forEachIndexed { i, r ->
- val direction = org.openstrap.app.data.History.status(r.value, r.normal)
+ val source = r.source
+ val direction = if (source is BodyValue.Latest) null else org.openstrap.app.data.History.status(r.value, r.normal)
+ val tag = org.openstrap.app.ui.dashboard.bodyTag(r.metric, direction)
ListRow(
r.name, r.color, r.value?.let { r.metric.format(it) + r.unit },
+ // The tag already says which way it is off, so the word against your normal gives way to it.
when {
r.value == null -> waiting
+ source is BodyValue.Latest -> source.line
r.normal == null && r.learning != null -> r.learning
+ source == BodyValue.Estimated ->
+ if (tag != null) stringResource(R.string.glow_today_estimated)
+ else stringResource(R.string.glow_today_body_estimated, TodayCopy.normalWord(direction))
+ tag != null -> null
else -> TodayCopy.normalWord(direction)
},
- tag = org.openstrap.app.ui.dashboard.bodyTag(r.metric, direction), onClick = { onOpenMetric(r.metric) }, divider = i > 0,
+ tag = tag, onClick = { onOpenMetric(r.metric) }, divider = i > 0,
icon = r.metric.rowIcon(),
)
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt
index 8009b514..a9243975 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt
@@ -15,9 +15,12 @@ import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath
+import androidx.compose.ui.text.drawText
+import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import org.openstrap.app.presentation.StageSpan
+import org.openstrap.app.ui.glow.GlowType
import org.openstrap.app.ui.glow.Rim
import org.openstrap.app.ui.glow.draw.ChartInk
import org.openstrap.app.ui.glow.draw.stageColor
@@ -31,9 +34,9 @@ import kotlin.math.sin
/*
* The line-like pictures (spec 2.7): Heart rate's day line through your resting band, Stress's day strip, Skin
* temperature's dial, Sleep regularity's bed and wake bars and the day with the naps on it. Each draws in its metric's
- * ink to fill its modifier, solid, never dotted or dashed and with no digits, and each but the naps has a rim function
- * saying where on the card the off part sits (spec 2.5). The geometry is in plain functions so it is tested without a
- * screen.
+ * ink to fill its modifier, solid, never dotted or dashed and with no digits (but the dial's reading), and each but the
+ * naps has a rim function saying where on the card the off part sits (spec 2.5). The geometry is in plain functions so it
+ * is tested without a screen.
*/
/* ------------------------------------------------------------------------------------------------ */
@@ -188,7 +191,7 @@ fun DayStrip(levels: List, ink: Color, size: PictureSize, modifier: Modi
}
}
-/** Where Stress's card lights when above usual (spec 2.5): at the strip's end, the latest stretch. Null with none. */
+/** Where Stress's card lights when its latest reading is High (spec 2.5): at the strip's end, the latest stretch. Null with none. */
fun dayStripRim(levels: List, size: PictureSize, slots: Int = levels.size): Rim? {
val last = stripStretches(levels, slots).lastOrNull() ?: return null
return Rim(lineCardX(last.x1, size), lineCardY(0.5f), reachX = 0.6f, reachY = 1.1f)
@@ -227,7 +230,8 @@ internal fun dialPoint(fit: DialFit, angle: Float, inset: Float = 0f): Offset {
* Skin temperature's picture (spec 2.7, Dial): a half dial reaching [DIAL_RANGE] either side of your normal, a white
* track at 8%, your [normal] (a deviation range in °C, like -0.3..0.3) as a band of [ink] at the top, and a needle at
* tonight's [deviation] in the ink. Centred in its modifier: on a Wide the card puts the number left and gives the dial
- * a square-ish box at the right ([WIDE_DIAL_CENTER_X]).
+ * a square-ish box at the right ([WIDE_DIAL_CENTER_X]). The [reading], when given, is the dial's one line of text, at
+ * the foot of the arc inside the needle's reach, in the larger type if it fits there ([dialReadingFits]).
*/
@Composable
fun TempDial(
@@ -236,7 +240,9 @@ fun TempDial(
ink: Color,
size: PictureSize,
modifier: Modifier = Modifier,
+ reading: String? = null,
) {
+ val measurer = rememberTextMeasurer()
Canvas(modifier.pictureArea(size)) {
val track = 4.dp.toPx()
val bandW = 9.dp.toPx()
@@ -257,9 +263,22 @@ fun TempDial(
drawLine(ink, dialPoint(fit, angle, fit.radius * 0.55f), dialPoint(fit, angle, dot), 2.dp.toPx(), StrokeCap.Round)
drawCircle(ink, dot, tip)
}
+ if (reading != null) {
+ val large = measurer.measure(reading, GlowType.secondary.copy(color = Color.White))
+ val text = if (dialReadingFits(large.size.width.toFloat(), large.size.height.toFloat(), fit.radius)) large
+ else measurer.measure(reading, GlowType.caption.copy(color = Color.White))
+ drawText(text, topLeft = Offset(fit.center.x - text.size.width / 2f, fit.center.y - text.size.height))
+ }
}
}
+/** The share of the dial's radius left clear of the needle, which starts 55% of the way out. */
+private const val DIAL_CLEAR_SHARE = 0.55f
+
+/** Whether a [width] by [height] text, centred on the foot of a dial of [radius], stays inside the needle's reach. */
+internal fun dialReadingFits(width: Float, height: Float, radius: Float): Boolean =
+ kotlin.math.hypot(width / 2, height) <= radius * DIAL_CLEAR_SHARE
+
/** Where a Wide's dial sits across the card: in a square-ish box at the right, after the number. */
const val WIDE_DIAL_CENTER_X = 0.78f
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt
index d4ea2a7b..fe84f616 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt
@@ -261,7 +261,7 @@ class AppRootViewModel(
catching { rewards.summary(start, workouts.value, goals.value.workoutsPerWeek) }.getOrNull()
/**
- * The manual copy and auto sync write with these. Only the needed permissions decide: the calorie ones are asked
+ * The manual copy and auto sync write with these. Only the needed permissions decide: the optional ones are asked
* for in the same screen when the needed ones are missing, and never again by themselves.
*/
suspend fun healthConnectWrite(): HcState = HcState.blocked(healthConnect.availability()) ?: when {
@@ -269,10 +269,10 @@ class AppRootViewModel(
else -> HcState.Needs(healthConnect.requestedPermissions)
}
- /** Just the calorie permissions, for the Health Connect page's "Offer calories again". Granted when nothing is left to ask. */
- suspend fun healthConnectCalories(): HcState = HcState.blocked(healthConnect.availability()) ?: when {
- healthConnect.hasCaloriePermissions() -> HcState.Granted
- else -> HcState.Needs(healthConnect.caloriePermissions)
+ /** Just the optional permissions, for the Health Connect page's offer to ask again. Granted when nothing is left to ask. */
+ suspend fun healthConnectOptional(): HcState = HcState.blocked(healthConnect.availability()) ?: when {
+ healthConnect.hasOptionalPermissions() -> HcState.Granted
+ else -> HcState.Needs(healthConnect.optionalPermissions)
}
suspend fun healthConnectRead(): HcState = HcState.blocked(healthConnect.availability()) ?: when {
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt
index c5eadc57..7748f205 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt
@@ -74,7 +74,8 @@ internal fun DetailHost(
val workouts by workoutsVm.workouts.collectAsStateWithLifecycle()
val activity = shown.activity
when (detail) {
- // A night signal's detail is always the night's, as its rows read it (SleepCopy.NIGHT_SIGNALS).
+ // A night signal's detail is always the night's, as its rows read it (SleepCopy.NIGHT_SIGNALS). Blood oxygen's
+ // is the night's only when the Sleep or Recovery tab opened it, so it comes with its own scope.
is Detail.OfMetric -> GlowMetricDetailScreen(
detail.metric, detail.night || detail.metric in SleepCopy.NIGHT_SIGNALS, day, histories.daily, live.bpm, live.canUse,
push, onSwitch, dayVm::select, padding, pop,
@@ -113,9 +114,9 @@ internal fun DetailHost(
Detail.Recovery -> {
BackHandler(onBack = pop)
GlowRecoveryScreen(
- day, shown.recovery, histories.daily,
+ day, shown.recovery,
header = { PageHeader(stringResource(R.string.day_tab_recovery), pop, subtitle = dayName(day.date)) },
- contentPadding = padding, onOpenMetric = { push(Detail.OfMetric(it)) },
+ contentPadding = padding, onOpenMetric = { push(Detail.OfMetric(it, night = it in SleepCopy.NIGHT_FIGURES)) },
onOpenScore = { push(Detail.OfScore(it)) }, strapScore = shown.strapScore,
healthspan = shown.healthspan, onOpenHealthspan = { seeHabitAge(); push(Detail.Healthspan) }, onOpenProfile = onOpenProfile,
recoveryFailure = shown.recoveryFailure, onRetryRecovery = dayVm::retryRecovery,
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt
index d2a34dd7..d937fce2 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt
@@ -50,9 +50,12 @@ internal class HealthConnectActions(
val export: () -> Unit,
/** Auto sync on or off. */
val auto: (Boolean) -> Unit,
- /** True while Health Connect is there and the calorie permissions are not granted: the page offers them again. */
+ /**
+ * True while Health Connect is there and the optional permissions (calories, breathing rate, VO2 max) are not
+ * granted: the page offers them again.
+ */
val caloriesMissing: Boolean,
- /** Asks for just the calorie permissions. */
+ /** Asks for just the optional permissions. */
val offerCalories: () -> Unit,
)
@@ -78,7 +81,7 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De
val scope = rememberCoroutineScope()
var caloriesMissing by remember { mutableStateOf(false) }
val refreshCalories: () -> Unit = {
- scope.launch { caloriesMissing = catching { rootVm.healthConnectCalories() }.getOrNull() is HcState.Needs }
+ scope.launch { caloriesMissing = catching { rootVm.healthConnectOptional() }.getOrNull() is HcState.Needs }
}
// Read again on every return to the app, since the grant can change in Health Connect's own screen.
LifecycleResumeEffect(Unit) {
@@ -90,7 +93,8 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De
val auto = hcForAuto
hcForAuto = false
scope.launch {
- // The needed ones may have been granted before, outside what this screen returns. The calorie ones may stay off.
+ // The needed ones may have been granted before, outside what this screen returns. The optional ones
+ // (calories, breathing rate, VO2 max) may stay off.
when {
!rootVm.healthConnectWriteGranted(granted) -> Toast.makeText(context, HC_NOT_GRANTED, Toast.LENGTH_LONG).show()
auto -> deviceVm.setAutoHealthConnect(true)
@@ -118,7 +122,7 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De
// The manual copy, or turning auto sync on ([forAuto]): with the write permissions, asked for first when missing.
val write: (Boolean) -> Unit = { forAuto ->
scope.launch {
- // The calorie permissions are optional and asked for only along with the needed ones.
+ // The optional permissions (calories, breathing rate, VO2 max) are asked for only along with the needed ones.
when (val hc = rootVm.healthConnectWrite()) {
HcState.Unavailable -> Toast.makeText(context, HC_UNAVAILABLE, Toast.LENGTH_LONG).show()
HcState.Installable -> Toast.makeText(context, HC_INSTALL_FIRST, Toast.LENGTH_LONG).show()
@@ -137,7 +141,7 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De
caloriesMissing = caloriesMissing,
offerCalories = {
scope.launch {
- when (val hc = rootVm.healthConnectCalories()) {
+ when (val hc = rootVm.healthConnectOptional()) {
HcState.Unavailable -> Toast.makeText(context, HC_UNAVAILABLE, Toast.LENGTH_LONG).show()
HcState.Installable -> Toast.makeText(context, HC_INSTALL_FIRST, Toast.LENGTH_LONG).show()
HcState.Granted -> caloriesMissing = false
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt
index 9dd40e7c..09d133df 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt
@@ -53,6 +53,7 @@ import org.openstrap.app.ui.dashboard.Detail
import org.openstrap.app.ui.dashboard.LocalScrollToTop
import org.openstrap.app.ui.dashboard.MomentHeader
import org.openstrap.app.ui.dashboard.RecoveryFailure
+import org.openstrap.app.ui.dashboard.SleepCopy
import org.openstrap.app.ui.dashboard.StrapChip
import org.openstrap.app.ui.dashboard.Wear
import org.openstrap.app.presentation.dayTitle
@@ -305,8 +306,8 @@ private fun TabRoot(
)
}
Tab.Recovery -> GlowRecoveryScreen(
- day, shown.recovery, histories.daily, header = { TabHeader(Tab.Recovery, header) }, contentPadding = padding,
- onOpenMetric = { openStack(Tab.Recovery, Detail.OfMetric(it)) },
+ day, shown.recovery, header = { TabHeader(Tab.Recovery, header) }, contentPadding = padding,
+ onOpenMetric = { openStack(Tab.Recovery, Detail.OfMetric(it, night = it in SleepCopy.NIGHT_FIGURES)) },
onOpenScore = { openStack(Tab.Recovery, Detail.OfScore(it)) },
strapScore = shown.strapScore,
healthspan = shown.healthspan,
diff --git a/app/src/main/res/values-zh-rCN/strings_core_detail.xml b/app/src/main/res/values-zh-rCN/strings_core_detail.xml
index a119cee5..df033d93 100644
--- a/app/src/main/res/values-zh-rCN/strings_core_detail.xml
+++ b/app/src/main/res/values-zh-rCN/strings_core_detail.xml
@@ -35,11 +35,18 @@
当前 bpm
bpm,最近一次
bpm 静息
+ bpm 静息,估算
步,今日目前
步
br/min,睡眠期间
全天平均
%1$s,全天平均
+ %1$s,最新于 %2$s
+ %1$s,高于你的常态
+ %1$s,低于你的常态
+ %1$s,符合你的常态
+ %1$s,白天,最新于 %2$s
+ %1$s,睡眠中,最新于 %2$s
每日步数,最近 7 天
每日步数,最近 30 天
每日步数,最近 12 个月
diff --git a/app/src/main/res/values-zh-rCN/strings_core_today.xml b/app/src/main/res/values-zh-rCN/strings_core_today.xml
index 35f2ed9c..f985dfd9 100644
--- a/app/src/main/res/values-zh-rCN/strings_core_today.xml
+++ b/app/src/main/res/values-zh-rCN/strings_core_today.xml
@@ -119,5 +119,6 @@
按住折线可查看任意时刻数值。
实时监测中
于 %1$s
+ %2$s 起 %1$d 分钟平均
等待手环连接
diff --git a/app/src/main/res/values-zh-rCN/strings_day_info.xml b/app/src/main/res/values-zh-rCN/strings_day_info.xml
index a0952238..bc919348 100644
--- a/app/src/main/res/values-zh-rCN/strings_day_info.xml
+++ b/app/src/main/res/values-zh-rCN/strings_day_info.xml
@@ -30,32 +30,32 @@
手环佩戴偏松、手部冰凉或手臂频繁活动都可能导致读数跳动。实时测量频率更高,因此开启时曲线看起来波动更频繁。
静息心率
你在最平静时的心率。数值越低,通常代表体能越好、心脏休息越充分。
- 手环每天会根据你最平静的一段时间(通常在睡眠中)计算出该数值。当过去 30 天中有 7 天具有有效数据时,其居中水平加减常规波动范围即为你的常态。
+ 通常采用手环当天提供的数值,取自你最平静的一段时间(通常在睡眠中)。若手环当天没有提供,unstrap 会根据全天最平静的半小时进行估算,并会注明。当过去 30 天中有 7 天具有有效数据时,其居中水平加减常规波动范围即为你的常态。
在高强度训练、深夜进食、饮酒、睡眠不佳或身体在抵抗不适时,它会上升;随着体能提升,它会逐渐下降。
夜间手环佩戴偏松或未佩戴会导致参考数据不足。单日的偏高并不能说明太多问题,连续数天的趋势更有参考价值。
HRV
心率变异性,即每次心跳之间微小的时间变化。高于你的常态通常意味着身体恢复良好。
- 手环会在你静止时(主要是睡眠中)测量每次心跳之间的时间间隔,单位为毫秒(ms),当日数值为测量读数的平均值。该数值会与你自己的常态进行对照:即过去 30 天的居中水平加减常规波动范围。
+ 手环会在你静止时(主要是睡眠中)测量每次心跳之间的时间间隔,单位为毫秒(ms)。该数值为整个睡眠期间测量读数的平均值,精确到毫秒。该数值会与你自己的常态进行对照:即过去 30 天的居中水平加减常规波动范围。
良好的睡眠和充分的休息会让它升高;压力、高强度训练和饮酒会使它降低。请将其与你自己的常态对比,而不是与他人比较。
测量期间身体活动、手环佩戴偏松或睡眠时间过短都会减少有效读数。HRV 每天的波动很大,因此连续数天的走势比单日读数更具参考意义。
血氧
你的血液携氧能力占比。大多数人的血氧处于 95 到 100%% 之间。
- 手环通过红光和红外光穿透皮肤,并对比两种光线的反射量。当日数值为所有测量读数的平均值。
+ 手环通过红光和红外光穿透皮肤,并对比两种光线的反射量。手环白天和夜间都会测量,显示的数值是最近一次读数。睡眠页和恢复页显示的是睡眠期间的平均值。
高海拔环境以及睡眠中的呼吸暂停可能会使它降低。
手环佩戴偏松、皮肤冰凉或测量时身体活动都可能导致读数偏低。此读数仅供健康参考,不作为医疗依据。
压力
手环测得的压力水平,范围从 0 到 100。数值越高,表明身体处于更高的警觉状态。
- 手环会在你静止时根据心率及其变异性计算该数值。运动期间及刚结束后的读数会被排除在外,因为运动并不等同于压力。
+ 手环会在你静止时根据心率及其变异性计算该数值。显示的数值是最近一次读数,与你的常态比较的是全天平均值。运动期间及刚结束后的读数会被排除在外,因为运动并不等同于压力。
精神压力、咖啡因和睡眠不足会使它上升;平缓呼吸、充分休息和户外活动能让它降下来。
情绪激动、燥热环境以及生病在手环看来都类似压力;久坐时的微小动作也可能推高读数。
皮肤温度
- 手环下方皮肤的温度。重要的不是绝对数值,而是相对于你常态的变化。
- 手环紧贴皮肤进行测量。绝对温度受佩戴松紧和室温影响,因此 unstrap 会将其显示为相对于过去 30 天常态的变化量。
+ 手环下方皮肤的温度。更值得关注的是相对于你常态的变化,而不是数值本身。
+ 手环紧贴皮肤进行测量。显示的数值是整个睡眠期间的平均值。绝对温度受佩戴松紧和室温影响,因此 unstrap 会同时显示相对于过去 30 天常态的变化量。
它会随饮酒、室内偏暖、高强度训练、生理周期或身体抵抗不适而产生波动。
温暖的被窝、厚重的被子或手环佩戴偏松,都可能在身体本身并无变化的情况下改变读数。
呼吸频率
你在睡眠中每分钟呼吸的次数。对大多数人而言,这一数值十分稳定。
- 手环会在睡眠期间进行测量,因此每晚生成一个数值,并与过去 30 天你的常态进行对比。
+ 手环会在整个睡眠期间进行测量,该数值为这些读数的平均值,并与过去 30 天你的常态进行对比。
在高强度训练之后、处于温暖闷热的房间或身体在抵抗不适时,它可能会高于你的常态。
夜间辗转反侧或部分时间未佩戴手环,都会导致可供参考的读数变少。
步数
@@ -128,7 +128,7 @@
- 有 %1$d 分钟来自心率测量而非步数。
从夜间睡眠中打开时,仅显示你的睡眠数据:从入睡到醒来的心率曲线、睡眠中的最低心率以及手环记录的整夜平均值。“月”与“年”视图则为全天完整数据。
- 从夜间睡眠中打开时,显示手环在睡眠期间的读数(与白天的单次测量分开记录),并与你之前的夜间数据进行对比。
+ 从夜间睡眠中打开时,显示手环在睡眠期间的读数(与白天的读数分开记录),并与你之前的夜间数据进行对比。
从夜间睡眠中打开时,显示当晚的读数,并与你之前的夜间数据进行对比。
从夜间睡眠中打开时,显示你睡眠期间测量读数的平均值,并与你之前的夜间数据进行对比。“月”与“年”视图则为昼夜全天的完整数据。
呼吸紊乱
diff --git a/app/src/main/res/values-zh-rCN/strings_day_sleep.xml b/app/src/main/res/values-zh-rCN/strings_day_sleep.xml
index b04d06bd..7d438bbf 100644
--- a/app/src/main/res/values-zh-rCN/strings_day_sleep.xml
+++ b/app/src/main/res/values-zh-rCN/strings_day_sleep.xml
@@ -20,6 +20,7 @@
过去 7 晚睡眠平均 %1$d bpm,范围 %2$d 至 %3$d。
昨晚
当晚
+ %1$s,已调整
暂无分数
手环未对昨晚睡眠评分
手环未对当晚睡眠评分
diff --git a/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml b/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml
index 35881e47..ddc6299d 100644
--- a/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml
+++ b/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml
@@ -26,6 +26,7 @@
日终值
最新读数
全天值
+ 全天值,估算
全天平均
睡眠平均
最近 7 天
@@ -43,8 +44,8 @@
当天暂无数据。
呼吸频率在睡眠期间测量。
%1$s,%2$s
- %1$s 于 %2$s
- 于 %1$s
+ %1$s,%3$s 起 %2$d 分钟平均
+ %2$s 起 %1$d 分钟平均
步,%1$s
%1$s 当周
相关指标
diff --git a/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml b/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml
index 852a0b54..4d3a72c2 100644
--- a/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml
+++ b/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml
@@ -21,7 +21,6 @@
压力
身体信号
对比你的常态
- 接近你的常态
最近 7 天平均
暂无分数
最近 7 天
diff --git a/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml b/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml
index c698c5f5..9d6bb68c 100644
--- a/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml
+++ b/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml
@@ -2,6 +2,7 @@
呼吸紊乱
昨晚
+ %1$s,已调整
恢复
%1$s,%2$s,%3$d 分钟
夜间体征
diff --git a/app/src/main/res/values-zh-rCN/strings_glow_today.xml b/app/src/main/res/values-zh-rCN/strings_glow_today.xml
index 01314762..0674955d 100644
--- a/app/src/main/res/values-zh-rCN/strings_glow_today.xml
+++ b/app/src/main/res/values-zh-rCN/strings_glow_today.xml
@@ -58,6 +58,20 @@
%1$s,睡眠 %2$s
心率
静息 %1$d
+ 静息 %1$d 估算
+ %1$s,估算
+ 最新于 %1$s
+ 放松
+ 正常
+ 中等
+ 偏高
+ %1$s,%2$s
+ 估算
+ 白天
+ 白天,%1$s
+ 睡眠中
+ 睡眠中,%1$s
+ 夜间平均
步数
目标 %1$s
今晨
diff --git a/app/src/main/res/values-zh-rCN/strings_you_data.xml b/app/src/main/res/values-zh-rCN/strings_you_data.xml
index 03577567..9837c768 100644
--- a/app/src/main/res/values-zh-rCN/strings_you_data.xml
+++ b/app/src/main/res/values-zh-rCN/strings_you_data.xml
@@ -57,8 +57,8 @@
找回 unstrap 曾保存在那里的数据
打开 Health Connect
权限与数据
- 允许后才会复制卡路里。
- 再次请求卡路里权限
+ 允许后才会复制卡路里、呼吸频率和最大摄氧量。
+ 再次请求
安装 Health Connect
在此手机上 Health Connect 是来自 Play 商店的应用。请安装它以便将数据复制到其中。
无法打开 Play 商店。
diff --git a/app/src/main/res/values/strings_core_data.xml b/app/src/main/res/values/strings_core_data.xml
index 0bec06e9..0d190494 100644
--- a/app/src/main/res/values/strings_core_data.xml
+++ b/app/src/main/res/values/strings_core_data.xml
@@ -22,7 +22,7 @@
%1$s/min vs usual
- %1$s%%, %2$s vs usual
+ %1$s%%, %2$s vs usual
Load %1$s, usual %2$s
diff --git a/app/src/main/res/values/strings_core_detail.xml b/app/src/main/res/values/strings_core_detail.xml
index 9d1b94bc..4157339e 100644
--- a/app/src/main/res/values/strings_core_detail.xml
+++ b/app/src/main/res/values/strings_core_detail.xml
@@ -58,6 +58,8 @@
bpm now
bpm, latest
bpm resting
+
+ bpm resting, estimated
steps so far today
steps
@@ -66,6 +68,15 @@
Day average
%1$s, day average
+
+ %1$s, latest at %2$s
+
+ %1$s, above your normal
+ %1$s, below your normal
+ %1$s, within your normal
+
+ %1$s, daytime, latest at %2$s
+ %1$s, while asleep, latest at %2$s
steps a day, last 7 days
steps a day, last 30 days
diff --git a/app/src/main/res/values/strings_core_today.xml b/app/src/main/res/values/strings_core_today.xml
index e7b622b4..c647724c 100644
--- a/app/src/main/res/values/strings_core_today.xml
+++ b/app/src/main/res/values/strings_core_today.xml
@@ -256,6 +256,8 @@
Live now
At %1$s
+
+ %1$d min average from %2$s
Waiting for the strap
diff --git a/app/src/main/res/values/strings_day_info.xml b/app/src/main/res/values/strings_day_info.xml
index 6b446bca..8388d6d7 100644
--- a/app/src/main/res/values/strings_day_info.xml
+++ b/app/src/main/res/values/strings_day_info.xml
@@ -57,42 +57,42 @@
Resting heart rate
Your heart rate at its calmest. Lower usually means a fitter, well rested heart.
- The strap calculates it each day from your calmest stretch, usually in sleep. Your normal is the middle of your last 30 days, give or take a usual spread, once 7 of them have a value.
+ Normally it\'s the strap\'s own figure for the day, from your calmest stretch, usually in sleep. When the strap sent none, unstrap estimates it from the calmest half hour of the day, and says so. Your normal is the middle of your last 30 days, give or take a usual spread, once 7 of them have a value.
It rises after hard training, late meals, alcohol, poor sleep or when your body is fighting something off, and falls as fitness builds.
A night with the strap loose or off gives it less to go on. One high day says less than a few in a row.
HRV
Heart rate variability, the small changes in time between heartbeats. Higher than your normal often means your body is well recovered.
- The strap measures the time between beats, in milliseconds (ms), while you\'re still, mostly in sleep, and the day\'s value is the average of its readings. It\'s read against your own normal: the middle of your last 30 days, give or take a usual spread.
+ The strap measures the time between beats, in milliseconds (ms), while you\'re still, mostly in sleep. The figure is the average of its readings through your sleep, to the nearest ms. It\'s read against your own normal: the middle of your last 30 days, give or take a usual spread.
Good sleep and rest raise it. Stress, hard training and alcohol lower it. Compare it with your own normal, not other people\'s.
Moving during a reading, a loose strap or a short night leave fewer clean readings. HRV swings a lot from day to day, so a few days in a row say more than one.
Blood oxygen
How much of your blood\'s capacity is carrying oxygen. Most people sit at 95 to 100%%.
- The strap shines red and infrared light through the skin and compares how much of each comes back. The day\'s value is the average of its readings.
+ The strap shines red and infrared light through the skin and compares how much of each comes back. It reads through the day and night, and the number is the latest reading. The Sleep and Recovery tabs show the average while you slept.
Altitude and pauses in breathing during sleep can lower it.
A loose strap, cold skin or moving during a reading can give low values. It\'s a wellness reading, not a medical one.
Stress
The strap\'s stress level from 0 to 100. Higher means your body is more on alert.
- The strap calculates it from your heart rate and its variability while you\'re still. Readings during and just after a workout are left out, since exercise isn\'t stress.
+ The strap calculates it from your heart rate and its variability while you\'re still. The number is the latest reading, and the day\'s average is what is compared with your usual. Readings during and just after a workout are left out, since exercise isn\'t stress.
Pressure, caffeine and too little sleep raise it. Calm breathing, rest and time outdoors bring it down.
Excitement, heat and an illness look like stress to the strap. Small movements while sitting can push it up.
Skin temperature
- The temperature of your skin under the strap. What matters is the change from your normal, not the level.
- The strap measures it against your skin. The level depends on fit and the room, so unstrap shows it as a change from your normal of the last 30 days.
+ The temperature of your skin under the strap. What to watch is the change from your normal, more than the level.
+ The strap measures it against your skin. The number is the average through your sleep. The level depends on fit and the room, so unstrap shows the change from your normal of the last 30 days with it.
It moves with alcohol, a warm room, hard training, the menstrual cycle, or when your body is fighting something off.
A warm bed, a heavy duvet or the strap sitting loose all change it without your body changing.
Breathing rate
How many breaths you take a minute while asleep. It stays very steady for most people.
- The strap measures it during sleep, so there\'s one value a night, read against your normal of the last 30 days.
+ The strap measures it through your sleep, and the figure is the average of those readings, read against your normal of the last 30 days.
It can rise above your normal after a hard training day, in a warm, stuffy room, or when your body is fighting something off.
A restless night, or the strap off for part of it, leaves fewer readings to go on.
@@ -215,7 +215,7 @@
Opened from the night, it shows only your sleep: the line from falling asleep to waking, the lowest while asleep and the strap\'s average for the night. Month and Year are whole days.
- Opened from the night, it shows the strap\'s readings in sleep, kept apart from the spot readings in the day, against your earlier nights.
+ Opened from the night, it shows the strap\'s readings in sleep, kept apart from the readings in the day, against your earlier nights.
Opened from the night, it\'s that night\'s readings, against your earlier nights.
diff --git a/app/src/main/res/values/strings_day_sleep.xml b/app/src/main/res/values/strings_day_sleep.xml
index d2b0e254..ed66fecd 100644
--- a/app/src/main/res/values/strings_day_sleep.xml
+++ b/app/src/main/res/values/strings_day_sleep.xml
@@ -48,6 +48,8 @@
last night
that night
+
+ %1$s, adjusted
No score
diff --git a/app/src/main/res/values/strings_glow_metrics.xml b/app/src/main/res/values/strings_glow_metrics.xml
index ecfac6d6..8dc2a934 100644
--- a/app/src/main/res/values/strings_glow_metrics.xml
+++ b/app/src/main/res/values/strings_glow_metrics.xml
@@ -52,6 +52,8 @@
Latest reading
For the day
+
+ For the day, estimated
Day average
Average asleep
@@ -89,10 +91,10 @@
Breathing rate is measured during sleep.
%1$s, %2$s
-
- %1$s at %2$s
-
- at %1$s
+
+ %1$s, %2$d min average from %3$s
+
+ %1$d min average from %2$s
steps, %1$s
diff --git a/app/src/main/res/values/strings_glow_recovery.xml b/app/src/main/res/values/strings_glow_recovery.xml
index 8bced953..1859a527 100644
--- a/app/src/main/res/values/strings_glow_recovery.xml
+++ b/app/src/main/res/values/strings_glow_recovery.xml
@@ -47,8 +47,6 @@
Body signals
Against your normal
-
- Close to your normal
Average of the last 7 days
diff --git a/app/src/main/res/values/strings_glow_sleep.xml b/app/src/main/res/values/strings_glow_sleep.xml
index fbce50b4..442102ce 100644
--- a/app/src/main/res/values/strings_glow_sleep.xml
+++ b/app/src/main/res/values/strings_glow_sleep.xml
@@ -8,6 +8,8 @@
Breathing disturbances
Last night
+
+ %1$s, adjusted
Restore
diff --git a/app/src/main/res/values/strings_glow_today.xml b/app/src/main/res/values/strings_glow_today.xml
index 484f3997..185c1e95 100644
--- a/app/src/main/res/values/strings_glow_today.xml
+++ b/app/src/main/res/values/strings_glow_today.xml
@@ -120,6 +120,28 @@
Heart rate
Resting %1$d
+
+ Resting %1$d est.
+
+ Relaxed
+ Normal
+ Medium
+ High
+
+ %1$s, %2$s
+
+ %1$s, estimated
+
+ Latest at %1$s
+
+ Estimated
+
+ Daytime
+ Daytime, %1$s
+ While asleep
+ While asleep, %1$s
+
+ Night average
Steps
diff --git a/app/src/main/res/values/strings_you_data.xml b/app/src/main/res/values/strings_you_data.xml
index 7274a9d8..bba72357 100644
--- a/app/src/main/res/values/strings_you_data.xml
+++ b/app/src/main/res/values/strings_you_data.xml
@@ -99,9 +99,9 @@
Bring back what unstrap saved there
Open Health Connect
Permissions and data
-
- Calories are left out until you allow them.
- Offer calories again
+
+ Calories, breathing rate and VO2 max are left out until you allow them.
+ Ask again
Install Health Connect
On this phone Health Connect is an app from the Play Store. Install it to copy your data there.
diff --git a/app/src/test/kotlin/org/openstrap/app/data/NightMetricsTest.kt b/app/src/test/kotlin/org/openstrap/app/data/NightMetricsTest.kt
new file mode 100644
index 00000000..113a0824
--- /dev/null
+++ b/app/src/test/kotlin/org/openstrap/app/data/NightMetricsTest.kt
@@ -0,0 +1,42 @@
+package org.openstrap.app.data
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+import org.openstrap.app.data.db.HrvSample
+
+/** The night's HRV: one gate and one rounding for Recovery and for every screen. */
+class NightMetricsTest {
+ private val start = 10_000L
+ private val end = 40_000L
+
+ private fun at(t: Long, ms: Int) = HrvSample(t, ms)
+
+ @Test fun `only readings inside the sleep and from 5 to 200 ms count`() {
+ val readings = listOf(
+ at(start - 1, 60), at(start, 40), at(start + 600, 4), at(start + 1200, 5), at(start + 1800, 200),
+ at(start + 2400, 201), at(end, 60), at(end + 1, 90),
+ )
+ // 40, 5, 200 and 60 are in; 4 and 201 are out of range, and the two outside the sleep are out of it.
+ assertEquals(listOf(40, 5, 200, 60), NightMetrics.sleepHrvReadings(readings, start, end))
+ assertEquals(76.25f, NightMetrics.hrvMean(NightMetrics.sleepHrvReadings(readings, start, end)))
+ }
+
+ @Test fun `the figure shown is the mean to the nearest whole ms`() {
+ // 51.5 goes up and 51.33 down; a cut to a whole number would give 51 for both.
+ assertEquals(52f, NightMetrics.sleepHrv(listOf(at(start, 51), at(start + 60, 52)), start, end))
+ assertEquals(51f, NightMetrics.sleepHrv(listOf(at(start, 51), at(start + 60, 51), at(start + 120, 52)), start, end))
+ }
+
+ @Test fun `a night with no clean reading has no figure`() {
+ assertNull(NightMetrics.sleepHrv(emptyList(), start, end))
+ assertNull(NightMetrics.sleepHrv(listOf(at(start + 10, 3), at(start + 20, 400)), start, end))
+ assertNull(NightMetrics.hrvMean(emptyList()))
+ }
+
+ @Test fun `the screens and Recovery take the same mean`() {
+ val readings = (0 until 20).map { at(start + it * 600L, 30 + it * 3) }
+ val mean = NightMetrics.hrvMean(NightMetrics.sleepHrvReadings(readings, start, end))!!
+ assertEquals(Math.round(mean).toFloat(), NightMetrics.sleepHrv(readings, start, end))
+ }
+}
diff --git a/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt b/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt
index fae0e57d..1525e164 100644
--- a/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt
@@ -61,3 +61,39 @@ class BucketTest {
assertEquals(listOf(0L to 70, 300L to 90), Summaries.bucketAverage(s))
}
}
+
+class HeartRangeTest {
+ // One reading a minute with a single dip and a single spike that 5-minute averages would flatten.
+ private val series = (0 until 10).map { i -> i * 60L to if (i == 3) 44 else if (i == 6) 151 else 70 }
+
+ @Test
+ fun theDayRangeIsTheStoredLowestAndHighest() {
+ assertEquals(44 to 151, HeartReadings.heartRange(series, null))
+ // Averaged into one 5-minute bucket the same minutes read much narrower.
+ assertEquals(listOf(0L to 65, 300L to 86), Summaries.bucketAverage(series))
+ }
+
+ @Test
+ fun theStrapsOwnMaximumLeadsOnlyWhenHigher() {
+ assertEquals(44 to 163, HeartReadings.heartRange(series, 163))
+ assertEquals(44 to 151, HeartReadings.heartRange(series, 120))
+ // A reading outside what a heart can be is not taken as a maximum.
+ assertEquals(44 to 151, HeartReadings.heartRange(series, 255))
+ assertNull(HeartReadings.heartRange(emptyList(), 163))
+ }
+
+ @Test
+ fun lowestIsTheEarliestOfTheLowestAndMeanIsRounded() {
+ assertEquals(60L to 44, HeartReadings.lowest(listOf(0L to 70, 60L to 44, 120L to 44)))
+ assertNull(HeartReadings.lowest(emptyList()))
+ assertEquals(52, HeartReadings.mean(listOf(0L to 51, 60L to 52)))
+ assertEquals(51, HeartReadings.mean(listOf(0L to 51, 60L to 51, 120L to 52)))
+ assertNull(HeartReadings.mean(emptyList()))
+ }
+
+ @Test
+ fun withinKeepsTheReadingsInsideBothEnds() {
+ assertEquals(listOf(60L to 70, 120L to 70), HeartReadings.within(series, 60, 120))
+ assertEquals(listOf(60L to 70, 120L to 70, 180L to 44), HeartReadings.within(series, 60, 180))
+ }
+}
diff --git a/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt b/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt
index 2a753410..4bb98f33 100644
--- a/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt
@@ -30,11 +30,11 @@ class ZeppJobsTest {
}
@Test
- fun theStrapsJobListIsZepps() {
+ fun theStrapsJobListIsZeppsThenSkinTemperature() {
assertEquals(
listOf(
"58", "66", "72", "1", "r08", "5", "r0c", "r06", "73", "19", "18", "37", "38", "39", "59", "pai",
- "56", "57", "70", "61", "74", "76", "87", "88", "78", "44",
+ "56", "57", "70", "61", "74", "76", "87", "88", "78", "44", "46",
),
names(ZeppJobs.list(gates())),
)
@@ -47,8 +47,12 @@ class ZeppJobsTest {
assertTrue("r0c" !in jobs && "44" !in jobs && "pai" !in jobs && "13" in jobs)
// No readiness module, no readiness jobs.
assertTrue(names(ZeppJobs.list(gates(endpoints = emptySet()))).none { it.startsWith("r") || it == "pai" })
- // Never: 2, 46, 43, 86, 7.
- assertTrue(names(ZeppJobs.list(gates())).none { it in setOf("2", "46", "43", "86", "7") })
+ // Never: 2, 43, 86, 7.
+ assertTrue(names(ZeppJobs.list(gates())).none { it in setOf("2", "43", "86", "7") })
+ // Skin temperature (46) is last, after statistics or without them, and only when the strap advertises it.
+ assertEquals("46", names(ZeppJobs.list(gates(statisticsDue = false))).last())
+ val unadvertised = ZeppJobs.Gates(advertised - 46, features, { true }, 3, 5, sleepPlan = true, statisticsDue = true)
+ assertTrue("46" !in names(ZeppJobs.list(unadvertised)))
}
@Test
diff --git a/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt b/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt
index 84b43c7b..9d2c59e1 100644
--- a/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt
@@ -1,9 +1,13 @@
package org.openstrap.app.health
import android.content.Context
+import androidx.health.connect.client.records.ExerciseSessionRecord
import androidx.health.connect.client.records.HeartRateRecord
+import androidx.health.connect.client.records.OxygenSaturationRecord
+import androidx.health.connect.client.records.RespiratoryRateRecord
import androidx.health.connect.client.records.Record
import androidx.health.connect.client.records.SleepSessionRecord
+import androidx.health.connect.client.records.Vo2MaxRecord
import androidx.health.connect.client.records.metadata.Device
import androidx.health.connect.client.records.metadata.Metadata
import androidx.test.core.app.ApplicationProvider
@@ -14,11 +18,16 @@ import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
+import org.openstrap.app.data.db.AppWorkout
+import org.openstrap.app.data.db.BreathRate
import org.openstrap.app.data.db.HeartRateSample
import org.openstrap.app.data.db.OpenStrapDatabase
import org.openstrap.app.data.db.SleepEdit
import org.openstrap.app.data.db.SleepSession
import org.openstrap.app.data.db.SleepStage
+import org.openstrap.app.data.db.Spo2Sample
+import org.openstrap.app.data.db.SportEffectRow
+import org.openstrap.app.data.db.Workout
import org.openstrap.app.testing.inMemoryDb
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@@ -115,4 +124,81 @@ class HealthConnectRoundTripTest {
assertEquals(null, SleepImport.strapStart("openstrap:hr:360000"))
assertEquals(null, SleepImport.strapStart(null))
}
+
+ @Test fun `every breathing rate sample is exported as it was stored`() = runTest {
+ dao.insertBreathRate(listOf(BreathRate(100 * h, 14), BreathRate(100 * h + 60, 9), BreathRate(300 * h, 16)))
+ val records = exporter.breathing(100 * h, 101 * h).map { it as RespiratoryRateRecord }
+ assertEquals(listOf("openstrap:breath:${100 * h}", "openstrap:breath:${100 * h + 60}"), records.map { it.metadata.clientRecordId })
+ assertEquals(listOf(14.0, 9.0), records.map { it.rate })
+ assertEquals(Instant.ofEpochSecond(100 * h), records.first().time)
+ }
+
+ @Test fun `blood oxygen is exported from 80 to 100 only, as it is stored`() = runTest {
+ dao.insertSpo2(listOf(0, 1, 70, 79, 80, 100, 101, 127).mapIndexed { i, p -> Spo2Sample(100 * h + i * 60, p) })
+ val records = exporter.bloodOxygen(100 * h, 101 * h).map { it as OxygenSaturationRecord }
+ assertEquals(listOf(80.0, 100.0), records.map { it.percentage.value })
+ }
+
+ private fun strap(start: Long, end: Long, sport: Int = 1, vo2max: Int? = null) = Workout(
+ start, end, sport, exerciseSeconds = null, calories = null, averageHeartRate = null, maxHeartRate = null, minHeartRate = null,
+ aerobicTrainingEffect = null, anaerobicTrainingEffect = null, trainingLoad = null, vo2max = vo2max, steps = null,
+ )
+
+ private fun effect(end: Long, vo2max: Float?) = SportEffectRow(end, null, vo2max, null, null, null, null, null, null)
+
+ @Test fun `the strap's VO2 max is exported at the workout's end, from the workout or else its effect`() = runTest {
+ // A day apart, so no workout takes another's effect.
+ dao.insertWorkouts(listOf(strap(100 * h, 101 * h, vo2max = 48), strap(130 * h, 131 * h), strap(160 * h, 161 * h, vo2max = 0), strap(190 * h, 191 * h, vo2max = 101)))
+ dao.insertSportEffects(listOf(effect(131 * h + 120, 52.4f), effect(161 * h + 120, 0f)))
+ val records = exporter.vo2max(90 * h, 240 * h).map { it as Vo2MaxRecord }
+ assertEquals(listOf("openstrap:vo2max:${100 * h}", "openstrap:vo2max:${130 * h}"), records.map { it.metadata.clientRecordId })
+ assertEquals(listOf(48.0, 52.0), records.map { it.vo2MillilitersPerMinuteKilogram })
+ assertEquals(listOf(Instant.ofEpochSecond(101 * h), Instant.ofEpochSecond(131 * h + 120)), records.map { it.time })
+ assertTrue(records.all { it.measurementMethod == Vo2MaxRecord.MEASUREMENT_METHOD_OTHER })
+ }
+
+ @Test fun `unstrap's own VO2 max estimate is not exported`() = runTest {
+ dao.insertAppWorkouts(listOf(AppWorkout(start = 100 * h, end = 101 * h, sportType = 1, vo2max = 45f)))
+ assertTrue(exporter.vo2max(90 * h, 140 * h).isEmpty())
+ }
+
+ @Test fun `a strap workout is exported as a session of its own`() = runTest {
+ dao.insertWorkouts(listOf(strap(100 * h, 101 * h, sport = 1), strap(110 * h, 110 * h)))
+ val records = exporter.strapWorkouts(90 * h, 140 * h).map { it as ExerciseSessionRecord }
+ // The empty one is left out: Health Connect rejects a session that doesn't end after it starts.
+ assertEquals(listOf("openstrap:strapworkout:${100 * h}"), records.map { it.metadata.clientRecordId })
+ assertEquals(Instant.ofEpochSecond(100 * h), records.single().startTime)
+ assertEquals(Instant.ofEpochSecond(101 * h), records.single().endTime)
+ assertEquals(ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, records.single().exerciseType)
+ }
+
+ @Test fun `a strap workout overlapping a phone workout is left out`() = runTest {
+ dao.insertAppWorkouts(listOf(AppWorkout(start = 100 * h + 30, end = 101 * h, sportType = 1)))
+ // The strap's own session of it starts a little after, the next one is clear of it.
+ dao.insertWorkouts(listOf(strap(100 * h + 40, 101 * h + 60), strap(102 * h, 103 * h)))
+ assertEquals(listOf("openstrap:strapworkout:${102 * h}"), exporter.strapWorkouts(90 * h, 140 * h).map { it.metadata.clientRecordId })
+ }
+
+ @Test fun `a strap workout a phone workout now overlaps loses its record`() = runTest {
+ val written = ExerciseSessionRecord(
+ startTime = Instant.ofEpochSecond(100 * h), startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochSecond(101 * h), endZoneOffset = ZoneOffset.UTC, exerciseType = ExerciseSessionRecord.EXERCISE_TYPE_RUNNING,
+ metadata = Metadata.autoRecorded(device = band, clientRecordId = "openstrap:strapworkout:${100 * h}"),
+ )
+ val phone = ExerciseSessionRecord(
+ startTime = Instant.ofEpochSecond(100 * h), startZoneOffset = ZoneOffset.UTC,
+ endTime = Instant.ofEpochSecond(101 * h), endZoneOffset = ZoneOffset.UTC, exerciseType = ExerciseSessionRecord.EXERCISE_TYPE_RUNNING,
+ metadata = Metadata.autoRecorded(device = band, clientRecordId = "openstrap:workout:${100 * h}"),
+ )
+ val deleted = mutableListOf()
+ val store = object : RecordStore {
+ override suspend fun insert(records: List) = Unit
+ override suspend fun ownRecords(type: kotlin.reflect.KClass, range: androidx.health.connect.client.time.TimeRangeFilter) = listOf(written, phone)
+ override suspend fun deleteIds(type: kotlin.reflect.KClass, ids: List) { deleted += ids.map { it } }
+ override suspend fun deleteRange(type: kotlin.reflect.KClass, range: androidx.health.connect.client.time.TimeRangeFilter) = Unit
+ }
+ // Nothing of the strap's is written any more: only its own session goes, the phone's stays.
+ store.dropStaleStrapWorkouts(90 * h, 140 * h, emptyList())
+ assertEquals(listOf(written.metadata.id), deleted)
+ }
}
diff --git a/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt
index 0bef6667..32378d0e 100644
--- a/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt
@@ -101,12 +101,14 @@ class DataCopyTest {
assertEquals(
listOf(
"52 ms, −8% vs usual", "54 bpm, +2 vs usual", "7 h 40 asleep", "No sleep debt", "1 h 15 of sleep debt",
- "Lowest heart rate 1 h 35 before waking", "±0,0 °C vs usual", "+0,4/min vs usual", "96,3%, −1,2 vs usual",
+ "Lowest heart rate 1 h 35 before waking", "±0,0 °C vs usual", "+0,4/min vs usual", "96%, −1,2 vs usual",
"Load 140, usual 95",
),
all.map { RecoveryCopy.detail(it) },
)
- assertEquals("96.3%, −1.2 vs usual", RecoveryCopy.detail(Recovery.Detail.BloodOxygen(96.25f, -1.2f), Locale.US))
+ // A whole percent, rounded; the change against usual keeps its decimal.
+ assertEquals("96%, −1.2 vs usual", RecoveryCopy.detail(Recovery.Detail.BloodOxygen(96.25f, -1.2f), Locale.US))
+ assertEquals("97%, −1.2 vs usual", RecoveryCopy.detail(Recovery.Detail.BloodOxygen(96.5f, -1.2f), Locale.US))
assertCleanCopy(all.map { RecoveryCopy.detail(it) } + all.map { RecoveryCopy.detail(it, Locale.US) })
}
}
diff --git a/app/src/test/kotlin/org/openstrap/app/presentation/StressLevelTest.kt b/app/src/test/kotlin/org/openstrap/app/presentation/StressLevelTest.kt
new file mode 100644
index 00000000..6b6252ac
--- /dev/null
+++ b/app/src/test/kotlin/org/openstrap/app/presentation/StressLevelTest.kt
@@ -0,0 +1,28 @@
+package org.openstrap.app.presentation
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/** Zepp's stress bands: relaxed 0 to 39, normal 40 to 59, medium 60 to 79, high 80 to 100. */
+class StressLevelTest {
+ @Test fun `a stress value is judged by Zepp's bands`() {
+ assertEquals(StressLevel.Relaxed, StressLevel.of(0f))
+ assertEquals(StressLevel.Relaxed, StressLevel.of(39f))
+ assertEquals(StressLevel.Normal, StressLevel.of(40f))
+ assertEquals(StressLevel.Normal, StressLevel.of(59f))
+ assertEquals(StressLevel.Medium, StressLevel.of(60f))
+ assertEquals(StressLevel.Medium, StressLevel.of(79f))
+ assertEquals(StressLevel.High, StressLevel.of(80f))
+ assertEquals(StressLevel.High, StressLevel.of(100f))
+ }
+
+ @Test fun `the level agrees with the whole number shown`() {
+ assertEquals(StressLevel.Normal, StressLevel.of(39.6f))
+ assertEquals(StressLevel.Relaxed, StressLevel.of(39.4f))
+ assertEquals(StressLevel.High, StressLevel.of(79.5f))
+ }
+
+ @Test fun `each level has its word`() {
+ assertEquals(listOf("Relaxed", "Normal", "Medium", "High"), StressLevel.entries.map { it.word() })
+ }
+}
diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt
index 93347ff6..4cfcab66 100644
--- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt
@@ -143,6 +143,24 @@ class DayViewModelUiStateTest {
assertEquals(listOf(ChartPoint(at(12), 45f)), s.hrv)
}
+ @Test fun `the day's lowest and highest come from the minutes, the strap's maximum when higher`() {
+ // A one-minute dip and spike inside two 5-minute buckets that average them away.
+ val hr = (0 until 10).map { HeartRateSample(at(10) + it * 60L, if (it == 3) 44 else if (it == 6) 151 else 70) }
+ val s = DayViewModel.toUiState(DayData(date, heartRate = hr))
+ assertEquals(hr.map { it.timestamp to it.bpm }, s.heartMinutes)
+ assertEquals(listOf(65f, 86f), s.heartRate.map { it.y })
+ assertEquals(44 to 151, s.heartRateRange)
+ assertEquals(44 to 163, DayViewModel.toUiState(DayData(date, heartRate = hr, dailyMaxHeartRate = 163)).heartRateRange)
+ assertEquals(44 to 151, DayViewModel.toUiState(DayData(date, heartRate = hr, dailyMaxHeartRate = 120)).heartRateRange)
+ assertNull(DayViewModel.toUiState(DayData(date)).heartRateRange)
+ }
+
+ @Test fun `the night's stored readings are kept for its lowest`() {
+ val night = listOf(HeartRateSample(at(2), 52), HeartRateSample(at(2, 1), 46), HeartRateSample(at(2, 2), 55))
+ val s = DayViewModel.toUiState(DayData(date, nightHeartRate = night))
+ assertEquals(night.map { it.timestamp to it.bpm }, s.sleepHeartMinutes)
+ }
+
@Test fun `the Activity screens get the day's Heart points and energy as state`() = runTest {
val repo = FakeDays()
val clock = FixedClock(Instant.parse("2026-01-15T12:00:00Z"))
diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt
index 773cbb5e..b4753534 100644
--- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt
@@ -5,13 +5,16 @@ import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.openstrap.app.data.History
+import org.openstrap.app.presentation.DetailCopy.Latest
import org.openstrap.app.presentation.DetailCopy.Level
import java.time.LocalDate
import java.util.Locale
+import org.openstrap.app.presentation.localNumber
import org.openstrap.app.presentation.DaySource
import org.openstrap.app.presentation.DetailCopy
import org.openstrap.app.presentation.Metric
import org.openstrap.app.presentation.Range
+import org.openstrap.app.presentation.StressLevel
import org.openstrap.app.presentation.daySource
import org.openstrap.app.presentation.TodayCopy
@@ -110,11 +113,40 @@ class DetailCopyTest {
@Test fun `the label under the value names what it is for the range`() {
assertEquals("bpm now", DetailCopy.valueLabel(Metric.HeartRate, Range.Day, live = true))
assertEquals("ms, day average", DetailCopy.valueLabel(Metric.Hrv, Range.Day))
+ // Blood oxygen's day is its latest reading and when it was taken; its longer ranges stay averages.
+ assertEquals("%, daytime, latest at 14:05", DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("14:05")))
+ assertEquals("%, while asleep, latest at 05:10", DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("05:10", asleep = true)))
+ // Stress is never asleep or awake: its day says the level of its latest reading and when it was taken.
+ assertEquals("High, latest at 14:05", DetailCopy.valueLabel(Metric.Stress, Range.Day, latest = Latest("14:05", asleep = true, level = StressLevel.High)))
+ assertEquals("%, average of the last 30 days", DetailCopy.valueLabel(Metric.Spo2, Range.Month, latest = Latest("14:05")))
assertEquals("Day average", DetailCopy.valueLabel(Metric.Stress, Range.Day))
+ // Stress has no unit: its longer ranges stay averages.
+ assertEquals("Normal, latest at 14:05", DetailCopy.valueLabel(Metric.Stress, Range.Day, latest = Latest("14:05", level = StressLevel.Normal)))
+ assertEquals("Average of the last 30 days", DetailCopy.valueLabel(Metric.Stress, Range.Month, latest = Latest("14:05", level = StressLevel.High)))
+ assertEquals("bpm resting", DetailCopy.valueLabel(Metric.RestingHr, Range.Day))
+ assertEquals("bpm resting, estimated", DetailCopy.valueLabel(Metric.RestingHr, Range.Day, estimated = true))
assertEquals("steps a day, last 7 days", DetailCopy.valueLabel(Metric.Steps, Range.Week))
assertEquals("ms, average of the last 30 days", DetailCopy.valueLabel(Metric.Hrv, Range.Month))
}
+ @Test fun `skin temperature's change on a card is just the signed change and its unit`() {
+ // Numbers as the test's locale writes them: the build also runs these under German.
+ fun n(ascii: String) = localNumber(ascii, Locale.getDefault())
+ assertEquals("+${n("0.3")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, 0.3f))
+ assertEquals("\u2212${n("0.2")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, -0.2f))
+ // No change, or one that rounds to nothing, keeps a plus, never a lone minus.
+ assertEquals("+${n("0.0")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, 0f))
+ assertEquals("+${n("0.0")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, -0.01f))
+ }
+
+ @Test fun `skin temperature's day says its change and which side of your normal it is on`() {
+ val skin = Metric.SkinTemperature
+ fun n(ascii: String) = localNumber(ascii, Locale.getDefault())
+ assertEquals("\u2212${n("0.7")} °C, below your normal", DetailCopy.skinChangeWord(skin, -0.7f, -1))
+ assertEquals("+${n("1.4")} °C, above your normal", DetailCopy.skinChangeWord(skin, 1.4f, 1))
+ assertEquals("+${n("0.1")} °C, within your normal", DetailCopy.skinChangeWord(skin, 0.1f, 0))
+ }
+
@Test fun `the strip ends today while the day shown is in the last week`() {
val today = LocalDate.of(2026, 10, 22)
val strip = DetailCopy.strip(LocalDate.of(2026, 10, 19), today, setOf(LocalDate.of(2026, 10, 20)), Locale.UK)
@@ -130,6 +162,10 @@ class DetailCopyTest {
@Test fun `no detail sentence uses an interpunct, semicolon or em dash`() {
val lines = listOfNotNull(
DetailCopy.day(0, DaySource.Night, true, 30), DetailCopy.heartDay(1, 2, false), DetailCopy.year("1", "2", "ms"),
+ DetailCopy.valueLabel(Metric.RestingHr, Range.Day, estimated = true), DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("14:05")),
+ DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("05:10", asleep = true)),
+ DetailCopy.valueLabel(Metric.Stress, Range.Day, latest = Latest("14:05", level = StressLevel.High)),
+ DetailCopy.skinChangeWord(Metric.SkinTemperature, -0.7f, -1),
DetailCopy.span(Range.Month, listOf(Level.Above, Level.Above), false, true, 30), DetailCopy.scoreWeek(listOf(1, 2)),
DetailCopy.charge(1, 2, 1, true, false, 3), DetailCopy.learningNormal(1, true), DetailCopy.bandLabel(normal) { it.toString() },
) + Metric.entries.flatMap { m -> Range.entries.map { DetailCopy.valueLabel(m, it) } }
diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/LatestReadingTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/LatestReadingTest.kt
new file mode 100644
index 00000000..7410ee2f
--- /dev/null
+++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/LatestReadingTest.kt
@@ -0,0 +1,112 @@
+package org.openstrap.app.ui.dashboard
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.openstrap.app.data.db.SleepSession
+import org.openstrap.app.presentation.ChartPoint
+import org.openstrap.app.presentation.Metric
+import org.openstrap.app.presentation.StressLevel
+
+/** Blood oxygen's latest reading of the day, which Today, All metrics and the details opened from them lead with. */
+class LatestReadingTest {
+ @Test fun `the latest reading is the newest of the day, whatever the order they arrive in`() {
+ val day = DayUiState(spo2 = listOf(ChartPoint(300, 95f), ChartPoint(900, 97f), ChartPoint(600, 94f)))
+ assertEquals(ChartPoint(900, 97f), LatestReading.spo2(day))
+ }
+
+ @Test fun `a day without a reading has no latest one`() {
+ assertNull(LatestReading.spo2(DayUiState()))
+ }
+
+ @Test fun `stress's latest reading is the newest of the day's, whatever the order`() {
+ val day = DayUiState(stress = listOf(ChartPoint(300, 40f), ChartPoint(900, 62f), ChartPoint(600, 55f)))
+ assertEquals(ChartPoint(900, 62f), LatestReading.stress(day))
+ assertNull(LatestReading.stress(DayUiState()))
+ assertEquals(ChartPoint(900, 62f), LatestReading.of(Metric.Stress, day))
+ assertNull(LatestReading.of(Metric.HeartRate, day))
+ }
+
+ @Test fun `a night average is not the latest reading`() {
+ // The night's readings stay in their own series: only the day's series, day and night, counts.
+ val day = DayUiState(sleepSpo2 = listOf(ChartPoint(100, 90f)))
+ assertNull(LatestReading.spo2(day))
+ }
+
+ private val hour = 3600L
+ private fun clock(t: Long) = "t$t"
+
+ @Test fun `a reading is stale once it is more than an hour old`() {
+ assertFalse(LatestReading.isStale(1000, 1000))
+ assertFalse(LatestReading.isStale(1000, 1000 + hour))
+ assertTrue(LatestReading.isStale(1000, 1000 + hour + 1))
+ // A reading taken after now (clock skew) is fresh.
+ assertFalse(LatestReading.isStale(2000, 1000))
+ }
+
+ @Test fun `a reading is asleep inside the sleep window, ends included, and daytime without one`() {
+ val window = 1000L..5000L
+ assertTrue(LatestReading.isAsleep(1000, window))
+ assertTrue(LatestReading.isAsleep(5000, window))
+ assertFalse(LatestReading.isAsleep(999, window))
+ assertFalse(LatestReading.isAsleep(5001, window))
+ assertFalse(LatestReading.isAsleep(3000, null))
+ }
+
+ @Test fun `the sleep window is the main sleep's start to its end`() {
+ assertNull(LatestReading.sleepWindow(DayUiState()))
+ assertEquals(100L..900L, LatestReading.sleepWindow(DayUiState(sleep = SleepSession(start = 100, end = 900))))
+ }
+
+ @Test fun `blood oxygen's line says daytime or asleep, with the time only once the reading is stale`() {
+ val window = 1000L..5000L
+ assertEquals("Daytime", LatestReading.spo2Line(8000, window, 8000 + 60, time = ::clock))
+ assertEquals("Daytime, t8000", LatestReading.spo2Line(8000, window, 8000 + 2 * hour, time = ::clock))
+ assertEquals("While asleep", LatestReading.spo2Line(3000, window, 3000 + 60, time = ::clock))
+ assertEquals("While asleep, t3000", LatestReading.spo2Line(3000, window, 3000 + 2 * hour, time = ::clock))
+ // No sleep window known: daytime.
+ assertEquals("Daytime, t3000", LatestReading.spo2Line(3000, null, 3000 + 2 * hour, time = ::clock))
+ }
+
+ @Test fun `stress's line is the level of the reading, with the time only once it is stale`() {
+ assertEquals("Normal", LatestReading.stressLine(500, 45f, 600, tagged = true, time = ::clock))
+ assertEquals("Normal, t500", LatestReading.stressLine(500, 45f, 500 + 2 * hour, tagged = true, time = ::clock))
+ assertEquals("Relaxed", LatestReading.stressLine(500, 12f, 600, tagged = false, time = ::clock))
+ assertEquals("Medium, t500", LatestReading.stressLine(500, 70f, 500 + 2 * hour, tagged = false, time = ::clock))
+ }
+
+ @Test fun `where the High tag shows the line doesn't repeat it`() {
+ assertNull(LatestReading.stressLine(500, 85f, 600, tagged = true, time = ::clock))
+ assertEquals("Latest at t500", LatestReading.stressLine(500, 85f, 500 + 2 * hour, tagged = true, time = ::clock))
+ // A row with no tag to show says the level itself.
+ assertEquals("High", LatestReading.stressLine(500, 85f, 600, tagged = false, time = ::clock))
+ assertEquals("High, t500", LatestReading.stressLine(500, 85f, 500 + 2 * hour, tagged = false, time = ::clock))
+ }
+
+ @Test fun `only a High stress reading is tagged`() {
+ assertNull(LatestReading.stressTag(StressLevel.Relaxed))
+ assertNull(LatestReading.stressTag(StressLevel.Normal))
+ assertNull(LatestReading.stressTag(StressLevel.Medium))
+ assertEquals(NewsTag("High", goal = false), LatestReading.stressTag(StressLevel.High))
+ }
+
+ @Test fun `the latest blood oxygen reading is asleep by the day's sleep window`() {
+ val sleep = SleepSession(start = 1000, end = 5000)
+ assertTrue(LatestReading.spo2Asleep(DayUiState(sleep = sleep, spo2 = listOf(ChartPoint(900, 95f), ChartPoint(3000, 94f)))))
+ assertFalse(LatestReading.spo2Asleep(DayUiState(sleep = sleep, spo2 = listOf(ChartPoint(3000, 94f), ChartPoint(9000, 96f)))))
+ assertFalse(LatestReading.spo2Asleep(DayUiState(sleep = sleep)))
+ }
+
+ @Test fun `the shaded hours are the readings inside the sleep window, clipped to the day`() {
+ val day = 0L..(24 * hour)
+ val slot = 15 * 60L
+ val count = (24 * hour / slot).toInt() + 1
+ // A night from 23:00 the evening before to 07:00 shades from the start of the day to 07:00.
+ assertEquals(0..28, LatestReading.shadeIndices(-hour..7 * hour, day, slot, count))
+ assertEquals(4..8, LatestReading.shadeIndices(hour..2 * hour, day, slot, count))
+ assertNull(LatestReading.shadeIndices(null, day, slot, count))
+ assertNull(LatestReading.shadeIndices(-10 * hour..-9 * hour, day, slot, count))
+ }
+}
diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt
index 9f691720..929774b1 100644
--- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt
@@ -9,7 +9,6 @@ import org.openstrap.app.data.Recovery
import org.openstrap.app.data.RecoveryResult
import org.openstrap.app.data.db.SleepSession
import org.openstrap.app.data.settings.UserProfile
-import org.openstrap.app.presentation.ChartPoint
import java.time.LocalDate
import java.time.ZoneOffset
@@ -120,12 +119,4 @@ class OffStatusesTest {
assertEquals(OffStatus.Usual, habitAgeOffStatus(Healthspan.Outcome(null, null)))
assertEquals(OffStatus.Usual, habitAgeOffStatus(null))
}
-
- @Test fun `stress is the day's mean against your normal`() {
- val samples = listOf(ChartPoint(0, 60f), ChartPoint(60, 80f))
- assertEquals(70f, stressMean(samples)!!, 0.001f)
- assertNull(stressMean(emptyList()))
- assertEquals(OffStatus.Above, stressOffStatus(samples, History.Normal(40f, 30f, 50f, 20)))
- assertEquals(OffStatus.Usual, stressOffStatus(emptyList(), History.Normal(40f, 30f, 50f, 20)))
- }
}
diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt
index 6446b829..6f24a94a 100644
--- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt
@@ -41,6 +41,11 @@ class SleepCopyTest {
hrv = listOf(ChartPoint(midnight + 14 * 3600, 90f)),
sleepHrv = listOf(ChartPoint(midnight + 3600, 40f), ChartPoint(midnight - 7200, 41f)),
sleepHeartRate = listOf(ChartPoint(midnight - 1800, 60f), ChartPoint(midnight + 3 * 3600, 48f), ChartPoint(midnight + 9 * 3600, 70f)),
+ // The stored readings behind the line's 5-minute averages: one minute dips below the 48 average.
+ sleepHeartMinutes = listOf(
+ midnight - 1800 to 60, midnight + 3 * 3600 to 52, midnight + 3 * 3600 + 60 to 46, midnight + 3 * 3600 + 120 to 48,
+ midnight + 9 * 3600 to 70,
+ ),
)
}
@@ -50,7 +55,9 @@ class SleepCopyTest {
assertEquals(94f, SleepCopy.nightValue(s, Metric.Spo2))
// Heart rate's night value is the strap's average for the night; the lowest is only from readings while asleep.
assertEquals(55f, SleepCopy.nightValue(s, Metric.HeartRate))
- assertEquals(48f, SleepCopy.lowestHeart(s)!!.y)
+ // The lowest is the lowest stored reading and when it was, not the lowest 5-minute average (48).
+ assertEquals(46f, SleepCopy.lowestHeart(s)!!.y)
+ assertEquals(midnight + 3 * 3600 + 60, SleepCopy.lowestHeart(s)!!.x)
// Readings outside the sleep (the 70 after waking) stay out of the night's line.
assertEquals(listOf(60f, 48f), SleepCopy.nightSeries(s, Metric.HeartRate).map { it.y })
assertEquals(listOf(40f), SleepCopy.nightSeries(s, Metric.Hrv).map { it.y })
@@ -58,6 +65,24 @@ class SleepCopyTest {
assertNull(SleepCopy.nightValue(state(sleep = null), Metric.Hrv))
}
+ @Test fun `the average while asleep is the strap's, else the mean of the stored readings`() {
+ assertEquals(55, SleepCopy.averageHeart(state()))
+ // 60, 52, 46 and 48 inside the sleep (the 70 after waking is out): 51.5, rounded up rather than cut to 51.
+ assertEquals(52, SleepCopy.averageHeart(state(sleep = session.copy(averageHeartRate = null))))
+ // Without the 60: 52, 46 and 48 average 48.67, which is 49.
+ assertEquals(49, SleepCopy.averageHeart(state(sleep = session.copy(averageHeartRate = null)).let { it.copy(sleepHeartMinutes = it.sleepHeartMinutes.drop(1)) }))
+ }
+
+ @Test fun `a score the user's times moved says it is adjusted`() {
+ val moved = session.copy(start = session.start + 1800)
+ assertFalse(state().sleepScoreAdjusted)
+ assertFalse(state().copy(sleepAsDetected = session).sleepScoreAdjusted)
+ assertTrue(state(sleep = moved).copy(sleepAsDetected = session).sleepScoreAdjusted)
+ assertEquals("last night, adjusted", SleepCopy.scoreLabel(true, adjusted = true))
+ assertEquals("that night, adjusted", SleepCopy.scoreLabel(false, adjusted = true))
+ assertEquals("last night", SleepCopy.scoreLabel(true))
+ }
+
@Test fun `a night vital reads against the nights before, as the Sleep tab's row does`() {
val s = state()
val normal = SleepCopy.nightNormal(s, Metric.Hrv)!!
@@ -73,6 +98,27 @@ class SleepCopyTest {
assertNull(SleepCopy.nightNormal(s, Metric.HeartRate))
}
+ @Test fun `skin temperature's row is the night's level, its change from your normal under it once there is one`() {
+ fun row(nights: Int): NightVital {
+ // Nights at 35.9 and 36.1 by turns (a normal of 36.0), then tonight at 36.5.
+ val before = (nights.toLong() downTo 1L).map { back ->
+ SleepNight(date.minusDays(back), session, skinTemperature = if (back % 2 == 0L) 35.9f else 36.1f)
+ }
+ return nightVitals(DayUiState(date = date, sleep = session, nights = before + SleepNight(date, session, skinTemperature = 36.5f)))
+ .first { it.metric == Metric.SkinTemperature }
+ }
+ val formed = row(8)
+ fun n(ascii: String) = org.openstrap.app.presentation.localNumber(ascii, java.util.Locale.getDefault())
+ assertEquals(n("36.5"), formed.value)
+ assertEquals("+${n("0.5")} \u00B0C", formed.status)
+ assertEquals(1, formed.direction)
+ // While the normal forms, the level and how far along it is.
+ val forming = row(3)
+ assertEquals(n("36.5"), forming.value)
+ assertTrue(forming.status, forming.status.startsWith("Learning"))
+ assertNull(forming.direction)
+ }
+
@Test fun `the night's week ends on the night shown, with the same value as its Day`() {
val week = SleepCopy.nightWeek(state(), Metric.Hrv)
assertEquals(7, week.size)
@@ -86,17 +132,42 @@ class SleepCopyTest {
assertEquals("Lowest 48 bpm at 03:00 last night, 55 on average while asleep.", SleepCopy.nightHeart(48, "03:00", 55, today = true))
assertEquals("55 bpm on average while asleep that night.", SleepCopy.nightHeart(null, null, 55, today = false))
assertEquals("ms, average asleep", SleepCopy.nightLabel(Metric.Hrv, Range.Day))
+ // Skin temperature's label no longer carries its change from your normal (DetailCopy.skinChangeWord says it).
+ assertEquals("°C, average asleep", SleepCopy.nightLabel(Metric.SkinTemperature, Range.Day))
assertEquals("ms, average of the last 7 nights", SleepCopy.nightLabel(Metric.Hrv, Range.Week))
// Month and Year say when their days aren't only nights.
- assertTrue("day and night" in SleepCopy.nightLabel(Metric.Hrv, Range.Month))
+ assertEquals("ms, last 30 nights", SleepCopy.nightLabel(Metric.Hrv, Range.Month))
+ assertTrue("day and night" in SleepCopy.nightLabel(Metric.SkinTemperature, Range.Month))
assertEquals("%, last 30 nights", SleepCopy.nightLabel(Metric.Spo2, Range.Month))
assertEquals("No sleep" to "None recorded last night", SleepCopy.nightNoValue(hasSleep = false, today = true))
assertEquals("No reading" to "Not measured that night", SleepCopy.nightNoValue(hasSleep = true, today = false))
}
+ @Test fun `blood oxygen is the night's on the Sleep and Recovery tabs only, the day's latest reading elsewhere`() {
+ assertFalse(Metric.Spo2 in SleepCopy.NIGHT_SIGNALS)
+ assertTrue(Metric.Spo2 in SleepCopy.NIGHT_FIGURES)
+ // The other night signals are forced to the night wherever they open.
+ assertTrue(SleepCopy.NIGHT_SIGNALS.containsAll(listOf(Metric.Hrv, Metric.Breathing, Metric.SkinTemperature)))
+ assertTrue(SleepCopy.NIGHT_FIGURES.containsAll(SleepCopy.NIGHT_SIGNALS))
+ assertFalse(Metric.RestingHr in SleepCopy.NIGHT_FIGURES)
+ // The night's average stays what the Sleep tab reads, whatever the day's readings are.
+ val s = state().copy(spo2 = listOf(ChartPoint(midnight + 14 * 3600, 91f)))
+ assertEquals(94f, SleepCopy.nightValue(s, Metric.Spo2))
+ assertEquals(91f, LatestReading.spo2(s)?.y)
+ }
+
+ @Test fun `blood oxygen's row on the Sleep tab says it is the night average, tag or not`() {
+ val row = nightVitals(state()).first { it.metric == Metric.Spo2 }
+ assertEquals("94%", row.value)
+ assertEquals("Night average", row.status)
+ }
+
@Test fun `night blood oxygen draws on its own table`() {
assertEquals(DailyMetric.SleepSpo2, SleepCopy.nightDaily(Metric.Spo2))
- assertEquals(DailyMetric.Hrv, SleepCopy.nightDaily(Metric.Hrv))
+ // HRV is the night's figure on every range, so its Month and Year come from the sleeps too.
+ assertEquals(DailyMetric.SleepHrv, SleepCopy.nightDaily(Metric.Hrv))
+ assertEquals(DailyMetric.SleepHrv, Metric.Hrv.daily)
+ assertTrue(SleepCopy.dailyIsNightly(Metric.Hrv))
assertTrue(SleepCopy.dailyIsNightly(Metric.Breathing))
assertFalse(SleepCopy.dailyIsNightly(Metric.SkinTemperature))
}
@@ -142,7 +213,7 @@ class SleepCopyTest {
val lines = listOf(
SleepCopy.nightHeart(48, "03:00", 55, true), SleepCopy.nightHeart(null, null, 55, false),
SleepCopy.heartWeek(listOf(52, null, 55)), SleepCopy.heartWeek(listOf(52)),
- SleepCopy.scoreLabel(true), SleepCopy.scoreLabel(false),
+ SleepCopy.scoreLabel(true), SleepCopy.scoreLabel(false), SleepCopy.scoreLabel(true, adjusted = true),
SleepCopy.night("Short night", 5 * 3600L, listOf(7 * 3600L, 8 * 3600L, 6 * 3600L)),
SleepCopy.regularityNight(23 * 60, 7 * 60, 23 * 60, true), SleepCopy.noNight(true), SleepCopy.noNight(false),
SleepCopy.napsLabel(true), SleepCopy.naps(3, 3600), SleepCopy.napHeart(58, 64), SleepCopy.NAP_NO_STAGES,
diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt
index 0f7b0a5b..68ce73af 100644
--- a/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt
+++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt
@@ -21,7 +21,7 @@ class AllMetricsTest {
private val empty = DayUiState()
- /** A metric's detail as the index opens it: a night signal's scoped to the night. */
+ /** A metric's detail as the index opens it: a night signal's scoped to the night, blood oxygen's to the day. */
private fun open(m: Metric) = IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS))
@Test fun `every metric detail appears exactly once`() {
@@ -47,23 +47,69 @@ class AllMetricsTest {
assertEquals(NO_VALUE, hrv.status)
}
- @Test fun `values are the day's, night signals last night's, in the metric's format`() {
+ @Test fun `values are the day's, night signals last night's, blood oxygen's latest reading, in the metric's format`() {
val sleep = SleepSession(start = 0, end = 8 * 3600)
val day = empty.copy(
steps = 13860, latestHeartRate = 58,
- // The calendar day's readings differ from the night's: the index shows the night's, as every tab does.
+ // Blood oxygen is the day's latest reading, the other signals the night's, as every tab does.
spo2 = listOf(ChartPoint(0, 90f), ChartPoint(60, 92f)),
skinTemperature = listOf(ChartPoint(0, 31.4f), ChartPoint(60, 31.6f)),
sleep = sleep,
nights = listOf(SleepNight(empty.date, sleep, spo2 = 97f, skinTemperature = 36.5f)),
)
- val rows = metricIndex(day, null, null, emptyList()).flatMap { it.rows }.associateBy { it.target }
+ val rows = metricIndex(day, null, null, emptyList(), now = 120).flatMap { it.rows }.associateBy { it.target }
assertEquals("13,860", rows.getValue(IndexTarget.Open(Detail.OfMetric(Metric.Steps))).value)
assertEquals("58", rows.getValue(IndexTarget.Open(Detail.OfMetric(Metric.HeartRate))).value)
- assertEquals("97%", rows.getValue(open(Metric.Spo2)).value)
+ assertEquals("92%", rows.getValue(open(Metric.Spo2)).value)
+ // Taken inside the night's sleep window a minute ago: no time yet.
+ assertEquals("While asleep", rows.getValue(open(Metric.Spo2)).status)
+ assertEquals(IndexTarget.Open(Detail.OfMetric(Metric.Spo2, night = false)), rows.getValue(open(Metric.Spo2)).target)
assertEquals("36.5", rows.getValue(open(Metric.SkinTemperature)).value)
}
+ @Test fun `blood oxygen's row says daytime without a sleep window, and the time once the reading is old`() {
+ val day = empty.copy(spo2 = listOf(ChartPoint(60, 92f)))
+ fun status(now: Long) = metricIndex(day, null, null, emptyList(), now = now).flatMap { it.rows }.first { it.name == "Blood oxygen" }.status
+ assertEquals("Daytime", status(120))
+ assertTrue(status(120 + 2 * 3600), status(120 + 2 * 3600).startsWith("Daytime, "))
+ }
+
+ @Test fun `a resting heart rate unstrap estimated says so`() {
+ fun status(estimated: Boolean) = metricIndex(empty.copy(restingHeartRate = 54, restingEstimated = estimated), null, null, emptyList())
+ .flatMap { it.rows }.first { it.target == open(Metric.RestingHr) }.status
+ assertEquals("For the day", status(false))
+ assertEquals("For the day, estimated", status(true))
+ }
+
+ @Test fun `stress is the day's latest reading, not its average`() {
+ val day = empty.copy(stress = listOf(ChartPoint(0, 80f), ChartPoint(60, 30f), ChartPoint(120, 40f)))
+ val row = metricIndex(day, null, null, emptyList(), now = 180).flatMap { it.rows }.first { it.name == "Stress" }
+ assertEquals("40", row.value)
+ // The row has no tag, so its line says the level of the reading.
+ assertEquals("Normal", row.status)
+ // An hour on, the row says when.
+ val old = metricIndex(day, null, null, emptyList(), now = 120 + 2 * 3600).flatMap { it.rows }.first { it.name == "Stress" }
+ assertTrue(old.status, old.status.startsWith("Normal, "))
+ val high = metricIndex(day.copy(stress = listOf(ChartPoint(0, 85f))), null, null, emptyList(), now = 60).flatMap { it.rows }.first { it.name == "Stress" }
+ assertEquals("High", high.status)
+ assertEquals(IndexTarget.Open(Detail.OfMetric(Metric.Stress)), row.target)
+ }
+
+ @Test fun `skin temperature leads with its level, its change from your normal under it once there is one`() {
+ val sleep = SleepSession(start = 0, end = 8 * 3600)
+ // Eight nights at 35.9 and 36.1 by turns: a normal of 36.0.
+ val before = (1L..8L).map { SleepNight(empty.date.minusDays(it), SleepSession(0, 1), skinTemperature = if (it % 2 == 0L) 35.9f else 36.1f) }
+ fun row(nights: List) = metricIndex(
+ empty.copy(sleep = sleep, nights = nights + SleepNight(empty.date, sleep, skinTemperature = 36.5f)), null, null, emptyList(),
+ ).flatMap { it.rows }.first { it.target == open(Metric.SkinTemperature) }
+ // Before there's a normal, the night's average says so.
+ assertEquals("36.5", row(emptyList()).value)
+ assertEquals("Average asleep", row(emptyList()).status)
+ val led = row(before)
+ assertEquals("36.5", led.value)
+ assertEquals("+0.5 °C", led.status)
+ }
+
private fun readiness(score: Int?, nights: Int, withheld: Boolean = false) =
org.openstrap.app.data.Recovery.Readiness(score, emptyList(), nights, false, emptyList(), false, withheld = withheld)
diff --git a/docs/releases/v3.0.0.md b/docs/releases/v3.0.0.md
index da3bf946..81992fa0 100644
--- a/docs/releases/v3.0.0.md
+++ b/docs/releases/v3.0.0.md
@@ -44,7 +44,7 @@
- A Keep recording notice when Android won't let a workout run in the background.
- Save a copy and Restore open in Downloads.
- A faster app, from the first launch after an install or update.
-- Strap firmware updates are off for now while I look into a sleep bug in firmware 3.27.0.1.
+- Strap firmware updates are off for now.
## Fixes
diff --git a/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt b/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt
index f6f0fce5..cf9a368d 100644
--- a/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt
+++ b/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt
@@ -159,7 +159,7 @@ data class SpO2Reading(
val isAuto: Boolean,
val history: List?,
) : HistoryRecord {
- /** The app keeps only 80..100 (02 §3.5). */
+ /** Zepp 10.10.5 keeps only 80..100 and drops the rest before storing (`d/eo00.java:158`); 127 is the invalid marker. */
val isPlausible: Boolean get() = spo2 in 80..100
}
diff --git a/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt b/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt
index f521ecb8..24eeb81b 100644
--- a/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt
+++ b/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt
@@ -213,10 +213,12 @@ class RecordParsersTest {
@Test
fun spo2Legacy() {
- val p = w().u32(t0).u8(0x80 or 97).u32(t0 + 60).u8(70).toByteArray()
+ val p = w().u32(t0).u8(0x80 or 97).u32(t0 + 60).u8(70).u32(t0 + 120).u8(127).u32(t0 + 180).u8(0).toByteArray()
val res = ok(HistoryParsers.spo2Single.parse(p, ctx))
assertEquals(97, res.records[0].spo2); assertTrue(res.records[0].isAuto); assertTrue(res.records[0].isPlausible)
+ // Only 80 to 100 is kept, as Zepp does: 70 is out, 127 is the invalid marker and 0 is none.
assertEquals(70, res.records[1].spo2); assertFalse(res.records[1].isAuto); assertFalse(res.records[1].isPlausible)
+ assertFalse(res.records[2].isPlausible); assertFalse(res.records[3].isPlausible)
assertNull(res.records[0].history)
}