Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
4a6ea0a
Stop retrying a key the strap turned down
sayed0am Nov 6, 2026
54792d3
App shell: launch extras read once, phone alerts re-checked on resume…
sayed0am Nov 6, 2026
84da456
Permissions gates and Health Connect: one answer runs every waiter, a…
sayed0am Nov 6, 2026
0f7be02
Sync: one worker for the queue, kept Sync now, ordered widget refreshes
sayed0am Nov 6, 2026
ce55823
App update and firmware: reconcile install state, guard firmware steps
sayed0am Nov 6, 2026
484a394
Workout core: atomic discard, safer start and restore, no stray readi…
sayed0am Nov 6, 2026
302c82e
Small screens: alarms edits, share photo, sleep undo, backup lock, re…
sayed0am Nov 6, 2026
d6202c2
Merge branch 'refs/heads/fix/sm-workout' into fix/state-machines
sayed0am Nov 6, 2026
5f87e2e
Merge branch 'refs/heads/fix/sm-sync' into fix/state-machines
sayed0am Nov 6, 2026
977e606
Merge branch 'refs/heads/fix/sm-shell' into fix/state-machines
sayed0am Nov 6, 2026
2e5e6c7
Merge branch 'refs/heads/fix/sm-permissions' into fix/state-machines
sayed0am Nov 6, 2026
8e52ffc
Merge branch 'refs/heads/fix/sm-update' into fix/state-machines
sayed0am Nov 6, 2026
13e9588
Merge branch 'refs/heads/fix/sm-screens' into fix/state-machines
sayed0am Nov 6, 2026
47a7aa4
Connection state machine: race-free hold, one live HR coroutine, per-…
sayed0am Nov 6, 2026
b04e7da
Merge branch 'refs/heads/fix/sm-connection' into fix/state-machines
sayed0am Nov 6, 2026
975a757
Fix what the merged state machine groups broke
sayed0am Nov 6, 2026
d394a7c
Merge develop into fix/state-machines
sayed0am Nov 9, 2026
4313517
Workout resend to the strap only on a new login, as Zepp
sayed0am Nov 10, 2026
55414cb
A history type cut off part way fails the sync, as Zepp
sayed0am Nov 10, 2026
c8237d4
Permissions: settings dialog for location and notifications turned do…
sayed0am Nov 10, 2026
cb0c0e9
Permissions test: pin the notifications test to Android 14
sayed0am Nov 10, 2026
5a65921
Workout: a failed End shows Not saved yet with Try again, saves track…
sayed0am Nov 10, 2026
66e9fb1
One day state: a swipe shows a placeholder until the day loads, and t…
sayed0am Nov 10, 2026
200f3e6
Workout notifications follow the session, End confirm stays, sticky a…
sayed0am Nov 10, 2026
fb2ff1f
Sync status kept once and read by the app and widgets, Bluetooth off …
sayed0am Nov 10, 2026
beaa458
Merge fix/sm2-workout into fix/sm-wave2
sayed0am Nov 10, 2026
11ce910
Merge fix/sm2-notify into fix/sm-wave2
sayed0am Nov 10, 2026
d4a510f
Merge fix/sm2-status into fix/sm-wave2
sayed0am Nov 10, 2026
dc57cad
Merge fix/sm2-day into fix/sm-wave2
sayed0am Nov 10, 2026
79f5977
Merge fix/sm2-perms into fix/sm-wave2
sayed0am Nov 10, 2026
fea50f5
Fix what the merged wave 2 groups broke
sayed0am Nov 10, 2026
ed63308
Merge wave 2 (fix/sm-wave2) into fix/state-machines
sayed0am Nov 10, 2026
dcfae72
Step notify goes off on a background step push, as Zepp
sayed0am Nov 10, 2026
c6148e4
A restarted workout keeps its added rest time and live kcal
sayed0am Nov 10, 2026
a7e8af9
Merge main (3.0.4) into fix/state-machines
sayed0am Nov 10, 2026
fa56192
A day switch holds the last day for 300 ms, dimmed, then shows the pl…
sayed0am Nov 10, 2026
edd4ace
Health Connect: breathing rate, VO2 max and strap workouts, and every…
sayed0am Nov 11, 2026
6876752
Vitals show the actual readings, and one number on every screen
sayed0am Nov 11, 2026
fb03a89
A lost workout end goes on the next connect, and You and Strap no lon…
sayed0am Nov 11, 2026
b30ad71
Skin temperature syncs again, and blood oxygen keeps 80 to 100 as Zep…
sayed0am Nov 11, 2026
d7cdf3d
Blood oxygen and stress lead with the latest reading, each judged by …
sayed0am Nov 11, 2026
4413a3f
Merge pull request #63 from sayed0am/fix/state-machines
sayed0am Nov 11, 2026
97f03fd
Merge develop into fix/vitals-actual-values
sayed0am Nov 11, 2026
f169906
Skin temperature tests read numbers in the test's locale, and wrap a …
sayed0am Nov 11, 2026
189ef61
Merge pull request #64 from sayed0am/fix/vitals-actual-values
sayed0am Nov 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,11 @@
<uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE" />
<uses-permission android:name="android.permission.health.WRITE_EXERCISE" />
<uses-permission android:name="android.permission.health.WRITE_DISTANCE" />
<!-- Asked for with the rest, but a write without them still goes, the calories left out. -->
<!-- Asked for with the rest, but a write without them still goes, those records left out. -->
<uses-permission android:name="android.permission.health.WRITE_ACTIVE_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.WRITE_TOTAL_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.WRITE_RESPIRATORY_RATE" />
<uses-permission android:name="android.permission.health.WRITE_VO2_MAX" />
<!-- Reading back what unstrap exported, to restore it (Import from Health Connect). -->
<uses-permission android:name="android.permission.health.READ_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_STEPS" />
Expand Down
15 changes: 13 additions & 2 deletions app/src/main/kotlin/org/openstrap/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ class MainActivity : ComponentActivity() {
)
val container = (application as OpenStrapApp).container
showLiveWorkoutWhenLocked(container)
// Only a fresh launch asks for something. A restored activity (process death, then back from Recents) is
// handed its original launch intent again, extras intact, and nav is restored too: replaying them would
// pile the old request on top of where the user had got to.
if (savedInstanceState == null && !launchedFromHistory(intent)) showWorkoutFromIntent()
setContent {
OpenStrapTheme {
AppRoot(container, navRequests, previews, pendingStrap)
Expand Down Expand Up @@ -170,8 +174,10 @@ class MainActivity : ComponentActivity() {
(application as OpenStrapApp).container.workout.inFront()
// The association or battery setting may have changed in system settings meanwhile.
(application as OpenStrapApp).container.companion.refresh()
// Call and notification access may have been granted in system settings meanwhile.
(application as OpenStrapApp).container.phoneAlerts.refresh()
// Debug extras only: the real launch extras are read once, in onCreate and onNewIntent.
handleDebugIntent(previews)
showWorkoutFromIntent()
}

override fun onNewIntent(intent: Intent) {
Expand All @@ -181,6 +187,10 @@ class MainActivity : ComponentActivity() {
showWorkoutFromIntent()
}

/** A launch from the Recents list: its intent is the original one, not a new request. */
private fun launchedFromHistory(intent: Intent?): Boolean =
intent != null && intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0

/**
* The workout notification opens the live screen, even if it was tucked away. A shortcut or the tile opens the
* ready screen, an auto-detected workout's notification that workout, and a health alert or body-signal
Expand Down Expand Up @@ -351,7 +361,7 @@ private fun AppRoot(
day, previewed.recovery, previewed.recoveryFailure, running != null, forced, workoutsVm, onNewDay = dayVm::select,
)
val strap = rememberStrapHeader(strapFacts, day, preview)
val shown = rememberShownDay(previewed, dayVm, rootVm, today.clockDate, strap.now, preview, dataPreview)
val shown = rememberShownDay(previewed, rootVm, today.clockDate, strap.now, preview, dataPreview)
val histories = remember(container) {
Histories { m, from, to -> container.health.daily(m, from, to) }
}
Expand Down Expand Up @@ -396,6 +406,7 @@ private fun AppRoot(
strapOpened = { growFrom = growOrigin.take() },
showWorkout = { container.workout.minimized.value = false },
),
container.workout.state,
)
// Starting a workout closes Ready and Choose. [saved] is what Ready opens on next time for the sport, and Choose's
// Start on your usual saves nothing new.
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ class AppContainer(val app: Application) {
app, database.healthDao(), settings, strap, maxHeartRates, callRinging = { phoneAlerts.callRinging }, onSaved = autoHealthConnect::workoutSaved,
scope = appScope,
)
/** Saved and the Keep recording notice, from the session's state, on the app scope (audit S10). */
val workoutNotifier = org.openstrap.app.device.WorkoutNotifier(
app, workout.state, { database.healthDao().appWorkoutOnce(it) }, appScope,
)
val updater = org.openstrap.app.update.AppUpdater(
app, settings, recording = { workout.state.value is org.openstrap.app.device.WorkoutState.Recording }, scope = appScope,
)
Expand Down Expand Up @@ -81,6 +85,7 @@ class AppContainer(val app: Application) {
workoutState = { workout.state.value },
location = { org.openstrap.app.device.locationAvailable(app) },
placed = { org.openstrap.app.widget.placedWidgets(app) },
bluetoothOff = { strap.connection.value == org.openstrap.app.device.ConnectionState.BluetoothOff },
)

/** The moment as the Moment widget reads it, for the strap's notification: its name, lead and Today's sentence. */
Expand Down Expand Up @@ -112,6 +117,7 @@ class OpenStrapApp : Application(), androidx.work.Configuration.Provider {
container.companion.refresh()
// A workout still recording when the process died carries on (the service restarts it too).
container.workout.restore()
container.workoutNotifier.start()
// Android restarts the process on its own (companion presence, a reboot): reconnect without the screen.
// A no-op when nothing is paired, a connection is already up, or the user tapped Disconnect.
if (BlePermissions.granted(this)) container.strap.backgroundConnect()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ class HealthRepository(
DailyMetric.HeartRate -> dao.dailyHeartRate(a, b)
DailyMetric.Steps -> dao.dailySteps(a, b)
DailyMetric.Hrv -> dao.dailyHrv(a, b)
DailyMetric.SleepHrv -> dao.dailySleepHrv(a, b)
DailyMetric.HrvSdnn -> dao.dailyHrvSdnn(a, b)
DailyMetric.Spo2 -> dao.dailySpo2(a, b)
DailyMetric.SleepSpo2 -> dao.dailySleepSpo2(a, b)
Expand Down Expand Up @@ -366,7 +367,7 @@ class HealthRepository(
}

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

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

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

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

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

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

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

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

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

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

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

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

/** Resting heart rate: the night's lowest 30-minute average against baseline; lower is better. */
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/kotlin/org/openstrap/app/data/RecoveryEngine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,7 @@ class RecoveryEngine(private val dao: HealthDao) {
val inSleep = { t: Long -> t in s.start..s.end }
val sleepHr = hr.filter { inSleep(it.first) && it.second in Recovery.HR_MIN_BPM..Recovery.HR_MAX_BPM }
val sleepBpm = sleepHr.map { it.second.toFloat() }
val rmssd = hrv.filter { inSleep(it.timestamp) && it.milliseconds in Recovery.HRV_MIN_MS..Recovery.HRV_MAX_MS }.map { it.milliseconds.toFloat() }
val rmssd = NightMetrics.sleepHrvReadings(hrv, s.start, s.end)
val asleep = asleepMinutes(s)
val skinValues = skin.filter { inSleep(it.timestamp) }.map { it.celsius }
val spo2Values = spo2.filter { inSleep(it.timestamp) }.map { it.percent.toFloat() }
Expand All @@ -760,7 +760,7 @@ class RecoveryEngine(private val dao: HealthDao) {
deepMinutes = s.deepMinutes,
remMinutes = s.remMinutes,
strapScore = s.score,
hrv = rmssd.mean(),
hrv = NightMetrics.hrvMean(rmssd),
restingHr = Recovery.lowestAverage(sleepHr, 30, Recovery.RHR_WINDOW_MIN_MINUTES)?.second,
rhrMeanSleep = sleepBpm.mean(),
rhrP10 = Recovery.percentile(sleepBpm, 0.10f),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class RoomDayRepository(
SleepNight(
date = d,
session = s,
hrv = during(hrv, { it.timestamp }, { it.milliseconds.toFloat() }),
hrv = s?.let { NightMetrics.sleepHrv(hrv, it.start, it.end) },
skinTemperature = during(skin, { it.timestamp }, { it.celsius }),
spo2 = during(spo2, { it.timestamp }, { it.percent.toFloat() }),
breathing = during(breath, { it.timestamp }, { it.perMinute.toFloat() }),
Expand Down
34 changes: 34 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,27 @@ interface HealthDao : RangedReads {
deleteAppWorkoutRow(start)
}

/**
* Discards the phone workout [start] whole: the workout, the strap's own records of it
* ([org.openstrap.app.data.Workouts.strapTwins]) and its time as "Not a workout", in one transaction. Its time range
* is read before anything is deleted, and a failure undoes all of it, so a retry finds the workout still there and
* does the twin cleanup too. [now] is when it happens. Returns the workout as it was, null if it was gone already.
*/
@androidx.room.Transaction
suspend fun discardAppWorkout(start: Long, now: Long): AppWorkout? {
val w = appWorkoutOnce(start)
val range = w?.takeIf { it.end != null }?.let { org.openstrap.app.data.Workouts.phoneRange(it, now) }
val twins = range?.let { org.openstrap.app.data.Workouts.strapTwins(workoutsOnce(it.first, it.last), it) }.orEmpty()
// Gone before its twins: a start trimmed into a twin would make it another owner of the strap's effect, and the
// effect would stay, its recovery carried into the next workout.
deleteAppWorkout(start)
twins.forEach { deleteStrapWorkout(it.start, now) }
// The strap's copy usually syncs after the summary shows: its time is remembered, and the sync leaves out a
// strap workout over it.
range?.let { insertDismissedWorkouts(listOf(DismissedWorkout(it.first, it.last))) }
return w
}

@Query("SELECT * FROM sport_effect WHERE `end` BETWEEN :from AND :to ORDER BY `end`")
suspend fun sportEffectsOnce(from: Long, to: Long): List<SportEffectRow>

Expand Down Expand Up @@ -695,6 +716,19 @@ interface HealthDao : RangedReads {
@Query("SELECT date(timestamp, 'unixepoch', 'localtime') AS day, AVG(milliseconds) AS value, MIN(milliseconds) AS min, MAX(milliseconds) AS max, COUNT(*) AS count FROM hrv WHERE timestamp BETWEEN :from AND :to GROUP BY day ORDER BY day")
fun dailyHrv(from: Long, to: Long): Flow<List<DailyAggregate>>

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

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

Expand Down
Loading