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/MainActivity.kt b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt
index 9e1ee33c..01c7441e 100644
--- a/app/src/main/kotlin/org/openstrap/app/MainActivity.kt
+++ b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt
@@ -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)
@@ -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) {
@@ -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
@@ -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) }
}
@@ -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.
diff --git a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt
index a5b1cfd0..b59af8cf 100644
--- a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt
+++ b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt
@@ -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,
)
@@ -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. */
@@ -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()
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 d015370f..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
@@ -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
@@ -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>
+ /**
+ * 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/data/settings/SettingsStore.kt b/app/src/main/kotlin/org/openstrap/app/data/settings/SettingsStore.kt
index a95b01aa..333b6559 100644
--- a/app/src/main/kotlin/org/openstrap/app/data/settings/SettingsStore.kt
+++ b/app/src/main/kotlin/org/openstrap/app/data/settings/SettingsStore.kt
@@ -102,7 +102,14 @@ data class BackupState(
val on get() = folder != null
}
-data class StrapSnapshot(val paired: Boolean, val battery: Int?, val charging: Boolean, val lastSyncDone: Long?)
+data class StrapSnapshot(
+ val paired: Boolean,
+ val battery: Int?,
+ val charging: Boolean,
+ val lastSyncDone: Long?,
+ /** When the syncs began to fail since [lastSyncDone] (epoch seconds), null while they work. */
+ val failingSince: Long? = null,
+)
/**
* Auto sync to Health Connect: [on] or off (off by default), when OpenStrap last wrote there ([lastSynced], epoch
@@ -621,13 +628,17 @@ class SettingsStore private constructor(private val store: DataStore = read { prefs ->
- StrapSnapshot(prefs[address] != null && prefs[authKey] != null, prefs[strapBattery], prefs[strapCharging] == true, prefs[syncDone])
+ StrapSnapshot(
+ prefs[address] != null && prefs[authKey] != null, prefs[strapBattery], prefs[strapCharging] == true, prefs[syncDone],
+ prefs[syncFailingSince],
+ )
}
/** The connected strap's battery and charging, written when either changes. */
@@ -638,9 +649,31 @@ class SettingsStore private constructor(private val store: DataStore
+ @SuppressLint("InlinedApi")
+ get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) listOf(Manifest.permission.POST_NOTIFICATIONS) else emptyList()
+
+ /** Whether notifications may be shown now (always, before Android 13). */
+ fun notificationsGranted(context: Context): Boolean =
+ notifications.all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
+
+ /** Whether a request's [result] turned notifications down. Absent (before Android 13) is not a denial. */
+ @SuppressLint("InlinedApi")
+ fun notificationsDenied(result: Map): Boolean = result[Manifest.permission.POST_NOTIFICATIONS] == false
+
/** Whether the strap may be scanned for and connected to now. */
fun granted(context: Context): Boolean =
bluetooth.all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
diff --git a/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt b/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt
index 9d6199f7..cce873c0 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt
@@ -35,7 +35,7 @@ internal class BuzzCoordinator(
@Volatile private var callHold = false
/** When the last motor pattern ends: one still playing then cuts off a `03` sent meanwhile (seen 2026-10-20). */
@Volatile private var motorBusyUntil = 0L
- private var pulseJob: Job? = null
+ @Volatile private var pulseJob: Job? = null
// Each return is a buzz given way to a call.
@Suppress("ReturnCount")
@@ -154,9 +154,23 @@ internal class BuzzCoordinator(
/** The same `03` … `06` as a ringing call, with Zepp's 60 s limit (03 §3.16). */
suspend fun findStrap() {
- startBuzzing()
- log("find strap: buzzing")
+ // Set before the start goes out, so a stop that lands meanwhile (endFind) is seen below and wins.
findingStrap.value = true
+ var started = false
+ try {
+ startBuzzing()
+ started = true
+ } finally {
+ // Rolled back, whatever ended the start (a refusal, no link, a cancelled caller).
+ if (!started) findingStrap.value = false
+ }
+ if (!findingStrap.value) {
+ // The stop got in first, so its 06 may have gone out before this 03: send another.
+ log("find strap: stopped while starting")
+ catching { stopBuzzing() }
+ return
+ }
+ log("find strap: buzzing")
findJob?.cancel()
findJob = scope.launch {
delay(FindDevice.FIND_TIMEOUT_MS)
@@ -167,6 +181,14 @@ internal class BuzzCoordinator(
}
}
+ /** The link ended: nothing is buzzing, so Find strap, a steady buzz and the pulses stop with it. */
+ fun linkEnded() {
+ findBuzzOn = false
+ pulseJob?.cancel()
+ pulseJob = null
+ endFind()
+ }
+
fun endFind() {
findJob?.cancel()
findJob = null
diff --git a/app/src/main/kotlin/org/openstrap/app/device/CompanionLink.kt b/app/src/main/kotlin/org/openstrap/app/device/CompanionLink.kt
index deb9e143..84a0d57a 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/CompanionLink.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/CompanionLink.kt
@@ -41,6 +41,12 @@ class CompanionLink(private val context: Context, private val settings: Settings
/** True when the paired strap is associated; refreshed by [refresh], on association and on [disassociate]. */
val associated = MutableStateFlow(false)
+ /**
+ * True after the user backed out of Android's prompt: the offer is hidden until the app starts again, and the row
+ * shows the battery setting meanwhile. Not kept: backing out is not a refusal for good.
+ */
+ val offerHidden = MutableStateFlow(false)
+
/** True when the app is already left out of battery optimization, whichever way that happened. */
val ignoringBatteryOptimizations = MutableStateFlow(false)
@@ -73,11 +79,13 @@ class CompanionLink(private val context: Context, private val settings: Settings
* which [launch] starts; pass the activity result to [onResult]. [onError] gets a message to show.
*/
fun associate(activity: Activity, address: String, launch: (IntentSender) -> Unit, onError: (String) -> Unit) {
- if (cdm == null) return onError(Strings.app.get(R.string.system_companion_unsupported))
+ // A failure is real: the offer is kept off, and the battery setting stands in for it ([declinedForGood]).
+ val fail = { message: String -> declinedForGood(); onError(message) }
+ if (cdm == null) return fail(Strings.app.get(R.string.system_companion_unsupported))
// The activity's own manager: before Android 13 associate() casts the manager's context to an Activity, and
// one from the application context crashes the app (seen on Android 11).
val cdm = activity.getSystemService(CompanionDeviceManager::class.java)
- ?: return onError(Strings.app.get(R.string.system_companion_unsupported))
+ ?: return fail(Strings.app.get(R.string.system_companion_unsupported))
// The strap is a BLE device; the classic filter also matches it once Android knows it from a connection.
val request = AssociationRequest.Builder()
.addDeviceFilter(BluetoothLeDeviceFilter.Builder().setScanFilter(ScanFilter.Builder().setDeviceAddress(address).build()).build())
@@ -99,20 +107,25 @@ class CompanionLink(private val context: Context, private val settings: Settings
override fun onFailure(error: CharSequence?) {
Log.w(TAG, "association failed: $error")
val reason = error ?: Strings.app.get(R.string.system_companion_no_reason)
- onError(Strings.app.format(R.string.system_companion_not_found, reason))
+ fail(Strings.app.format(R.string.system_companion_not_found, reason))
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) cdm.associate(request, activity.mainExecutor, callback)
else @Suppress("DEPRECATION") cdm.associate(request, callback, Handler(Looper.getMainLooper()))
}
+ private fun declinedForGood() {
+ scope.launch { settings.setCompanionDeclined(true) }
+ }
+
/**
* The result of the confirmation [associate] launched. On Android 13+ the association arrives through the
- * callback. Older versions only report it here. Returns false when the user turned it down.
+ * callback. Older versions only report it here. Returns false when it didn't end in an association: Back
+ * (RESULT_CANCELED) only hides the offer for now ([offerHidden]), any other result is a failure and is kept.
*/
fun onResult(resultCode: Int): Boolean {
if (resultCode != Activity.RESULT_OK) {
- scope.launch { settings.setCompanionDeclined(true) }
+ if (resultCode == Activity.RESULT_CANCELED) offerHidden.value = true else declinedForGood()
return false
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) scope.launch {
diff --git a/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt b/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt
index 34618afa..f2d7fa2a 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt
@@ -7,6 +7,7 @@ import org.openstrap.app.ble.GattUnusableException
import org.openstrap.app.i18n.Strings
import org.openstrap.protocol.ProtocolException
import org.openstrap.protocol.ProtocolTimeoutException
+import org.openstrap.protocol.auth.AuthException
/**
* Turns a failed connect into what the Device page says. The raw exception text ("Disconnected (status 133)") goes to
@@ -24,8 +25,12 @@ object ConnectErrors {
},
)
- /** True when trying again can't help until the user acts, so no reconnect is scheduled (audit E4). */
- fun isFinal(e: Throwable): Boolean = e is GattUnusableException || e.isPermission()
+ /**
+ * True when trying again can't help until the user acts (grants the permission, pairs again), so no reconnect is
+ * scheduled (audit E4) and background triggers stop trying.
+ */
+ fun isFinal(e: Throwable): Boolean =
+ e is GattUnusableException || e.isPermission() || (e is AuthException && PairingErrors.keyRejected(e.status))
private fun Throwable.isPermission(): Boolean = generateSequence(this) { it.cause }.any { it is SecurityException }
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt
index 73990ea1..1a4e66d8 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt
@@ -10,7 +10,9 @@ import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -84,7 +86,11 @@ internal class ConnectionManager(
/** True while the user wants the strap connected; cleared by [disconnect]. */
@Volatile private var wantConnected = false
private var retries = 0
- /** Set when a connect failed in a way retrying can't fix (no permission, a bad address): presence events don't retry. */
+ /**
+ * Set when a connect failed in a way retrying can't fix ([ConnectErrors.isFinal]: no permission, a bad address, a
+ * key the strap turned down): presence events and Bluetooth coming back don't retry. Cleared by the next connect
+ * the user starts or the app coming to the front ([wantConnection]).
+ */
@Volatile private var unusable = false
@Volatile override var gatt: GattClient? = null
private set
@@ -95,47 +101,78 @@ internal class ConnectionManager(
override val activeSession: ChannelSession? get() = session?.takeIf { connection.value is ConnectionState.Connected }
- /** Connect if a strap is paired and nothing is connected or in progress. Safe to call often. */
+ /**
+ * The user opened the app: clear their Disconnect and connect if a strap is paired and nothing is connected or in
+ * progress. Safe to call often. Reconnects nobody asked for on screen are [backgroundConnect], which never clears
+ * the hold.
+ */
// On the lane, and checking connectJob: callers race at process start (app start-up, the companion presence
// service, phone alerts), before the connect coroutine has moved the state off Disconnected.
fun autoConnect() {
onLane {
- when (connection.value) {
- is ConnectionState.Connected, ConnectionState.Connecting, ConnectionState.Authenticating -> return@onLane
- else -> Unit
- }
- if (reconnectJob?.isActive == true || connectJob?.isActive == true) return@onLane
+ if (busy()) return@onLane
hold(false)
wantConnection()
}
}
- /** The user's Disconnect, kept across process restarts; null until read from settings. See [backgroundConnect]. */
+ /** On the lane: connected, connecting or waiting to retry. */
+ private fun busy(): Boolean {
+ when (connection.value) {
+ is ConnectionState.Connected, ConnectionState.Connecting, ConnectionState.Authenticating -> return true
+ else -> Unit
+ }
+ return reconnectJob?.isActive == true || connectJob?.isActive == true
+ }
+
+ /**
+ * The user's Disconnect, kept across process restarts; null until read from settings. Changed on the lane only (by
+ * [hold] and [isHeld]), so a Disconnect can't be undone by a command queued before it.
+ */
@Volatile private var held: Boolean? = null
// One at a time, in order, so a quick Disconnect then Connect can't land the other way round.
// A lane of its own for the hold writes, so they can't queue behind the strap's traffic on the app scope.
@Suppress("InjectDispatcher")
private val heldWriter = CoroutineScope(SupervisorJob() + Dispatchers.IO.limitedParallelism(1))
+ /** On the lane. */
private fun hold(value: Boolean) {
if (held == value) return
held = value
heldWriter.launch { settings.setHeldDisconnected(value) }
}
+ /**
+ * On the lane: the hold, read from settings once. A Disconnect or Connect landing while it is read wins over the
+ * stored value.
+ */
+ private suspend fun isHeld(): Boolean {
+ val stored = held ?: settings.heldDisconnected.first()
+ if (held == null) held = stored
+ return held == true
+ }
+
+ /**
+ * Reconnects nobody asked for on screen (companion presence, phone alerts, process start, a workout starting, the
+ * widget's Sync now). Never clears the hold: after the user's Disconnect only [connect] or opening the app
+ * ([autoConnect]) connects.
+ */
fun backgroundConnect() {
- scope.launch {
+ onLane {
// Presence events repeat every few seconds while the strap advertises, so a skip isn't logged.
- if (held ?: settings.heldDisconnected.first().also { held = it }) return@launch
+ if (isHeld()) return@onLane
// Every try would fail the same way until the user acts (grants the permission, pairs again).
- if (unusable) return@launch
- autoConnect()
+ if (unusable) return@onLane
+ if (busy()) return@onLane
+ wantConnection()
}
}
fun connect() {
- hold(false)
- onLane { wantConnection() }
+ onLane {
+ hold(false)
+ wantConnection()
+ }
}
/** On the lane. */
@@ -150,9 +187,10 @@ internal class ConnectionManager(
private fun scheduleReconnect() {
if (!wantConnected) return
// Every attempt would fail at once; Bluetooth coming back on reconnects (see bluetoothChanged), as Zepp waits too.
- if (context.getSystemService(android.bluetooth.BluetoothManager::class.java)?.adapter?.isEnabled == false) {
+ if (bluetoothOff()) {
log("bluetooth is off, reconnecting once it's back on")
reconnectJob?.cancel()
+ connection.value = ConnectionState.BluetoothOff
return
}
val wait = RETRY_SECONDS[minOf(retries, RETRY_SECONDS.lastIndex)]
@@ -165,6 +203,10 @@ internal class ConnectionManager(
}
}
+ /** True when the phone's Bluetooth adapter is off or turning off. */
+ private fun bluetoothOff(): Boolean =
+ context.getSystemService(android.bluetooth.BluetoothManager::class.java)?.adapter?.isEnabled == false
+
/** On the lane, so the cancel and the new job are one step that nothing else can come between. */
// The catch-all rethrows whenever this job is cancelled, by asking the job rather than the exception's type (C1).
@Suppress("SuspendFunSwallowedCancellation", "TooGenericExceptionCaught")
@@ -177,6 +219,12 @@ internal class ConnectionManager(
return@onLane
}
catching { StrapService.start(context) }.onFailure { log("service start failed: $it") }
+ if (bluetoothOff()) {
+ // Nothing to connect over: the state says so, and Bluetooth coming back on connects (bluetoothChanged).
+ log("bluetooth is off, connecting once it's back on")
+ connection.value = ConnectionState.BluetoothOff
+ return@onLane
+ }
connection.value = ConnectionState.Connecting
// A client left over from a lost link still holds one of Android's few GATT client slots.
gatt?.close()
@@ -206,6 +254,11 @@ internal class ConnectionManager(
log("auth failed: ${e.message}")
connection.value = PairingErrors.authFailure(e)
close()
+ // Every presence event would otherwise run the handshake again, and fail the same way.
+ if (ConnectErrors.isFinal(e)) {
+ unusable = true
+ log("not retrying: the strap turned the key down")
+ }
} catch (e: Exception) {
// Asks the coroutine, not the exception: a timeout is a failure to report, only a cancelled job unwinds.
if (!currentCoroutineContext().isActive) {
@@ -235,12 +288,21 @@ internal class ConnectionManager(
override fun onReceive(c: Context, intent: android.content.Intent) {
when (intent.getIntExtra(android.bluetooth.BluetoothAdapter.EXTRA_STATE, -1)) {
android.bluetooth.BluetoothAdapter.STATE_TURNING_OFF, android.bluetooth.BluetoothAdapter.STATE_OFF -> {
- val client = gatt ?: return
log("bluetooth turned off")
- client.lost()
+ onLane {
+ if (wantConnected && !unusable && connection.value != ConnectionState.NotPaired) {
+ connection.value = ConnectionState.BluetoothOff
+ }
+ }
+ gatt?.lost()
}
android.bluetooth.BluetoothAdapter.STATE_ON -> onLane {
- if (!wantConnected || connection.value is ConnectionState.Connected || connectJob?.isActive == true) return@onLane
+ // Off was only shown for a strap the app was trying to reach; one it isn't trying for is Disconnected.
+ if (connection.value == ConnectionState.BluetoothOff && (!wantConnected || unusable)) {
+ connection.value = ConnectionState.Disconnected
+ }
+ val connected = connection.value is ConnectionState.Connected || connectJob?.isActive == true
+ if (!wantConnected || unusable || connected) return@onLane
log("bluetooth back on, reconnecting")
retries = 0
reconnectJob?.cancel()
@@ -255,6 +317,33 @@ internal class ConnectionManager(
context, bluetoothChanged, android.content.IntentFilter(android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED),
androidx.core.content.ContextCompat.RECEIVER_NOT_EXPORTED,
)
+ watchPaired()
+ }
+
+ /**
+ * NotPaired follows the paired strap, so after Forget the state is NotPaired and not a Disconnected the UI has to
+ * patch. Nothing is connected then: whatever is left of a link is ended here, in case Forget came without a
+ * Disconnect. Runs on the lane; the first value is the strap paired at start-up.
+ */
+ private fun watchPaired() = onLane {
+ settings.pairedDevice.map { it != null }.distinctUntilChanged().collect { paired ->
+ if (paired) {
+ if (connection.value == ConnectionState.NotPaired) connection.value = ConnectionState.Disconnected
+ return@collect
+ }
+ wantConnected = false
+ reconnectJob?.cancel()
+ connectJob?.cancel()
+ // Nothing to end at start-up, and the facade's hooks may not be wired yet.
+ val state = connection.value
+ if (gatt != null || (state != ConnectionState.Disconnected && state != ConnectionState.NotPaired)) {
+ hooks.onLinkEnded()
+ close()
+ }
+ connection.value = ConnectionState.NotPaired
+ // Forget removes the hold from settings; the next strap starts without it.
+ if (held == true) hold(false)
+ }
}
private fun watchDisconnect(client: GattClient) = onLane {
@@ -269,8 +358,9 @@ internal class ConnectionManager(
gatt = null
client.close()
if (wantConnected) {
- // Keep the foreground service up while we try to get the strap back.
- connection.value = ConnectionState.Connecting
+ // Keep the foreground service up while we try to get the strap back. With Bluetooth off, scheduleReconnect
+ // says so (the state skips Connecting).
+ connection.value = if (bluetoothOff()) ConnectionState.BluetoothOff else ConnectionState.Connecting
scheduleReconnect()
} else {
connection.value = ConnectionState.Disconnected
@@ -279,8 +369,8 @@ internal class ConnectionManager(
}
fun disconnect() {
- hold(true)
onLane {
+ hold(true)
wantConnected = false
reconnectJob?.cancel()
connectJob?.cancel()
diff --git a/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt b/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt
index 970f0f41..a0614cae 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt
@@ -404,14 +404,16 @@ class HistorySync internal constructor(
var ok = true
loop@ while (true) {
check(gatt.connected.value) { Strings.app.get(R.string.system_sync_link_dropped) }
- if (fastRecharge) { ok = got.isNotEmpty(); break }
+ if (fastRecharge) { ok = false; break }
val chunk = when (val f = client.fetch(spec.code, cursor, zone, previous)) {
is GdspFetch.Chunk -> f
GdspFetch.Empty -> break@loop
is GdspFetch.Failed -> {
log("history ${spec.type}: ${f.reason}")
if (f.fastRecharge) fastRecharge = true
- if (f.cyclic || --retries <= 0 || fastRecharge) { ok = got.isNotEmpty(); break@loop }
+ // Zepp's type result is the last exchange's status (`l59.f`, `ixi.a`): chunks that came first are
+ // still stored, but the type failed, and so does the sync.
+ if (f.cyclic || --retries <= 0 || fastRecharge) { ok = false; break@loop }
continue@loop
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt b/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt
index cbfc9c98..a4a57317 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt
@@ -73,7 +73,37 @@ object KeepRecordingNotice {
context.getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification)
}
+ /**
+ * Set while the service's own refusal is what the notice shows. The session clears the notice when its start call
+ * returns without throwing, which only says the start was queued: that clear can land after the service's refusal
+ * and cancel the one notice meant for it (audit S10), so [clear] leaves it alone then.
+ */
+ @Volatile private var refusedByService = false
+
+ /** The service was refused its foreground: asks for the tap, and holds the notice against [clear]. */
+ fun serviceRefused(context: Context, sportType: Int) {
+ refusedByService = true
+ show(context, sportType)
+ }
+
+ /** The service is in the foreground: the notice isn't needed. */
+ fun serviceUp(context: Context) {
+ refusedByService = false
+ cancel(context)
+ }
+
+ /** A start went through or a workout stopped: goes, unless the service itself was refused ([serviceRefused]). */
fun clear(context: Context) {
+ if (!refusedByService) cancel(context)
+ }
+
+ /** Nothing records any more: goes in every case. [WorkoutNotifier] calls it as the session's state leaves Recording. */
+ fun end(context: Context) {
+ refusedByService = false
+ cancel(context)
+ }
+
+ private fun cancel(context: Context) {
context.getSystemService(NotificationManager::class.java).cancel(NOTIFICATION_ID)
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt b/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt
index 0bbeb4a1..040502d6 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt
@@ -1,15 +1,23 @@
package org.openstrap.app.device
import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Job
+import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeoutOrNull
import org.openstrap.app.ble.GattClient
import org.openstrap.app.ble.StrapUuids
import org.openstrap.app.data.catching
@@ -39,80 +47,113 @@ internal class LiveHeartRateStream(
val liveHeartRate = MutableStateFlow(null)
val heartRateReadings = MutableSharedFlow(extraBufferCapacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST)
- private var liveJob: Job? = null
-
/** Which of the strap's heart rate sources is shown and recorded ([HeartRateSources]); guarded by itself. */
private val sources = HeartRateSources()
- @Volatile private var appVisible = false
- @Volatile private var workoutActive = false
+ /** Why live HR is wanted, besides a screen showing it: the app in front, or a workout recording. */
+ private enum class Reason { AppVisible, Workout }
+
+ private val reasons = MutableStateFlow>(emptySet())
/** The screens showing live HR now, each by its own key (Zepp's HeartRateCenter consumers). */
- private val screens = mutableSetOf()
+ private val screens = MutableStateFlow>(emptySet())
+
+ /** A workout records it, or a screen shows it with the app in front. */
+ private fun wanted(r: Set, shown: Set) = Reason.Workout in r || (Reason.AppVisible in r && shown.isNotEmpty())
+
+ /** Bumped by each new connection, so a stream is opened again even when the link dropped and came back unseen. */
+ private val connects = MutableStateFlow(0)
- private fun wanted() = workoutActive || (appVisible && synchronized(screens) { screens.isNotEmpty() })
+ /** True from the first command of a stream to the end of its stop, so a stop is sent only for a stream that opened. */
+ private val wireOpen = MutableStateFlow(false)
- val isRunning: Boolean get() = liveJob?.isActive == true
+ /** The session and client the open stream was sent on, for its stop. Touched by the one coroutine in [follow] only. */
+ private var openSession: ChannelSession? = null
+ private var openClient: GattClient? = null
- fun setAppVisible(visible: Boolean) {
- if (visible == appVisible) return
- appVisible = visible
- refresh()
+ /** What [follow] acts on: stream or not, on which connection. */
+ private data class Plan(val stream: Boolean, val connect: Int)
+
+ init {
+ // One ordered coroutine owns the wire: collectLatest ends a stream (cancelled, then joined) before the next
+ // block starts, so a stop and a start can't cross, and a failed flash that ends firmwareUpdating restarts it.
+ scope.launch {
+ combine(reasons, screens, connection, firmwareUpdating, connects) { r, shown, c, fw, n ->
+ Plan(wanted(r, shown) && c is ConnectionState.Connected && !fw, n)
+ }.distinctUntilChanged().collectLatest { follow(it) }
+ }
}
+ fun setAppVisible(visible: Boolean) { set(Reason.AppVisible, visible) }
+
fun setWorkoutActive(active: Boolean) {
- if (active == workoutActive) return
- workoutActive = active
- log(if (active) "workout started: live hr stays on in the background" else "workout ended")
- refresh()
+ if (set(Reason.Workout, active)) log(if (active) "workout started: live hr stays on in the background" else "workout ended")
}
/** A screen showing live HR came or went. */
fun showOnScreen(key: Any, shown: Boolean) {
- val changed = synchronized(screens) { if (shown) screens.add(key) else screens.remove(key) }
- if (changed) refresh()
+ screens.update { if (shown) it + key else it - key }
+ }
+
+ /** True when [reason] changed. */
+ private fun set(reason: Reason, on: Boolean): Boolean {
+ var changed = false
+ reasons.update { current ->
+ changed = (reason in current) != on
+ if (on) current + reason else current - reason
+ }
+ return changed
}
/** A new connection: starts again if something still uses it, as Zepp's `uyl.f` restarts its consumers. */
fun onConnected() {
- if (wanted()) start()
+ connects.update { it + 1 }
}
/** The link ended: the stream with it. */
fun onLinkEnded() {
- liveJob?.cancel()
liveHeartRate.value = null
synchronized(sources) { sources.reset() }
sessionLogged = false
}
- /** Starts or stops streaming to match [wanted]; a stream already running is left alone. */
- private fun refresh() {
- if (!wanted()) {
- if (liveJob?.isActive == true) pause()
- } else if (liveJob?.isActive != true && !firmwareUpdating.value && connection.value is ConnectionState.Connected) {
- start()
- }
+ /**
+ * Stops streaming and returns once the strap has been told (or a few seconds passed), for a firmware update, which
+ * sets [firmwareUpdating] first: the stream follows it on its own, and starts again if the update fails.
+ */
+ suspend fun pause() {
+ withTimeoutOrNull(PAUSE_WAIT_MS) { wireOpen.first { !it } }
+ }
+
+ private suspend fun follow(plan: Plan) {
+ if (plan.stream) stream() else closeWire()
}
- /** Stops streaming for now (e.g. during a firmware update); [refresh] starts it again when it's wanted. */
- fun pause() {
- liveJob?.cancel()
+ /** Tells the strap to stop, if a stream was opened and the link is still up. Not cancellable: both commands go out. */
+ private suspend fun closeWire() {
liveHeartRate.value = null
- val s = link.session
- val client = link.gatt
- scope.launch { stop(s, client) }
+ val s = openSession
+ val client = openClient
+ openSession = null
+ openClient = null
+ if (!wireOpen.value) return
+ withContext(NonCancellable) {
+ if (connection.value is ConnectionState.Connected) stop(s, client)
+ wireOpen.value = false
+ }
}
// The catch-all rethrows a cancellation, and a failed stream only stops showing live HR.
@Suppress("SuspendFunSwallowedCancellation", "TooGenericExceptionCaught")
- private fun start() {
- liveJob?.cancel()
+ private suspend fun stream() {
liveHeartRate.value = null
val s = link.activeSession ?: return
val client = link.gatt ?: return
synchronized(sources) { sources.reset() }
- liveJob = scope.launch {
+ openSession = s
+ openClient = client
+ wireOpen.value = true
+ coroutineScope {
launch { clearWhenStale() }
try {
val channel = s.services.has(Endpoints.HEART_RATE)
@@ -249,5 +290,6 @@ internal class LiveHeartRateStream(
const val OPEN_REPLY = 0x05
const val SUBSCRIBE_REPLY = 0x04
const val STALE_CHECK_MS = 2_000L
+ const val PAUSE_WAIT_MS = 5_000L
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt b/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt
index c8699baa..691aedd5 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt
@@ -15,15 +15,21 @@ object PairingErrors {
private const val BINDING_PROTECTED = 0x41
private const val CLOUD_BIND_REQUIRED = 0x81
- fun authFailure(e: AuthException, strings: Strings = Strings.app): ConnectionState.Failed = when (e.status) {
- WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED ->
- ConnectionState.Failed(strings.get(R.string.system_pairing_wrong_key), keyRejected = true)
- NO_KEY -> ConnectionState.Failed(strings.get(R.string.system_pairing_no_key), keyRejected = true)
- SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED ->
- ConnectionState.Failed(strings.get(R.string.system_pairing_cloud_bind), keyRejected = true)
- WORKOUT_RUNNING -> ConnectionState.Failed(strings.get(R.string.system_pairing_workout_running))
- else -> ConnectionState.Failed(
- strings.format(R.string.system_pairing_failed, e.message ?: strings.get(R.string.system_pairing_unknown_error)),
- )
- }
+ private val KEY_REJECTED = setOf(
+ WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED, NO_KEY, SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED,
+ )
+
+ /** True when the strap turned the key down: the same key fails the same way until the user pairs again. */
+ fun keyRejected(status: Int): Boolean = status in KEY_REJECTED
+
+ fun authFailure(e: AuthException, strings: Strings = Strings.app): ConnectionState.Failed = ConnectionState.Failed(
+ when (e.status) {
+ WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED -> strings.get(R.string.system_pairing_wrong_key)
+ NO_KEY -> strings.get(R.string.system_pairing_no_key)
+ SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED -> strings.get(R.string.system_pairing_cloud_bind)
+ WORKOUT_RUNNING -> strings.get(R.string.system_pairing_workout_running)
+ else -> strings.format(R.string.system_pairing_failed, e.message ?: strings.get(R.string.system_pairing_unknown_error))
+ },
+ keyRejected = keyRejected(e.status),
+ )
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt b/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt
index 608bc777..689afd1e 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt
@@ -292,12 +292,11 @@ class PhoneAlerts(
/**
* Reconnects a paired strap that isn't connected. Android can restart the process just to deliver a call or a
* notification (or to bind [StrapNotificationListener]); this alert is lost, but the next one reaches the strap.
- * A no-op while connected or connecting, while the user's Disconnect holds, and when the strap turned the key
- * down (retrying can't help).
+ * A no-op while connected or connecting, while the user's Disconnect holds, and when retrying can't help (a key
+ * the strap turned down): [StrapController.backgroundConnect] checks those.
*/
fun reconnectStrap() {
- val c = strap.connection.value
- if (c is ConnectionState.Connected || (c as? ConnectionState.Failed)?.keyRejected == true) return
+ if (strap.connection.value is ConnectionState.Connected) return
if (!BlePermissions.granted(context)) return
strap.backgroundConnect()
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt
index a115f040..65f68453 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt
@@ -41,23 +41,9 @@ internal class SavedWorkoutEditor(
fun discard(start: Long) {
scope.launch {
lock.withLock {
- // Not deleted, its summary stays, so Discard can be tried again.
- val w = catching {
- dao.appWorkoutOnce(start).also { w ->
- // 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.
- dao.deleteAppWorkout(start)
- if (w?.end != null) {
- val t = clock()
- val range = org.openstrap.app.data.Workouts.phoneRange(w, t)
- org.openstrap.app.data.Workouts.strapTwins(dao.workoutsOnce(range.first, range.last), range)
- .forEach { dao.deleteStrapWorkout(it.start, t) }
- // The strap's copy usually syncs after the summary shows, so after a Discard tapped there:
- // its time is remembered, and the sync leaves out a strap workout over it.
- dao.insertDismissedWorkouts(listOf(org.openstrap.app.data.db.DismissedWorkout(range.first, range.last)))
- }
- }
- }.onFailure { log("workout not discarded: ${it.message}") }.getOrElse { return@withLock }
+ // One transaction: not deleted, nothing is, its summary stays, and Discard can be tried again.
+ val w = catching { dao.discardAppWorkout(start, clock()) }
+ .onFailure { log("workout not discarded: ${it.message}") }.getOrElse { return@withLock }
if (w?.end != null) refreshDays(w.start, w.recordedEnd ?: w.end)
onDiscarded(start)
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt
index 5be4a4bf..271c7091 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt
@@ -50,7 +50,12 @@ internal class StrapCommands(
}
/** The alarm module's version for the connection it was read on: Zepp's `sq0.l`, asked again after a reconnect. */
- private var alarmCaps: Pair? = null
+ @Volatile private var alarmCaps: Pair? = null
+
+ /** The link ended or the strap was forgotten: the next alarm command asks the strap's limits again. */
+ fun forgetAlarmCaps() {
+ alarmCaps = null
+ }
private suspend fun alarmCaps(): AlarmCapabilities {
val s = link.activeSession
diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt
index 205c2ba8..9a858c03 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt
@@ -13,6 +13,8 @@ sealed interface ConnectionState {
data object NotPaired : ConnectionState
data object Disconnected : ConnectionState
data object Connecting : ConnectionState
+ /** Bluetooth is off on the phone, so nothing connects until it is on again. */
+ data object BluetoothOff : ConnectionState
data object Authenticating : ConnectionState
data class Connected(val batteryPercent: Int?, val firmware: String?, val charging: Boolean = false) : ConnectionState
/** [keyRejected]: the strap refused the auth key, so retrying with the same key can't work. */
@@ -28,11 +30,21 @@ sealed interface SyncState {
}
/**
- * When syncs last ran and how they ended, for the header chip and Today's stuck sync (spec 4.3). Epoch seconds, null
- * when not seen since the app started. [failingSince] is the first failure after the last good sync, null while
- * syncing works.
+ * When syncs last ran and how they ended, the one status the header chip, the Strap page, Today's stuck sync (spec 4.3)
+ * and the widgets read. Epoch seconds. [lastSuccess] is the last full sync, and [failingSince] the first failure after
+ * it, both kept across restarts ([SyncCoordinator] writes them); [lastAttempt] is null until a sync runs in this
+ * process. [failingSince] is null while syncing works.
*/
data class SyncRecord(val lastSuccess: Long? = null, val lastAttempt: Long? = null, val failingSince: Long? = null) {
+ /** A sync began at [now]. */
+ fun attempted(now: Long): SyncRecord = copy(lastAttempt = now)
+
+ /** A full sync finished well at [at]: the failure ends. A push's partial sync doesn't come here. */
+ fun succeeded(at: Long): SyncRecord = SyncRecord(lastSuccess = at, lastAttempt = lastAttempt ?: at)
+
+ /** A sync failed at [now]: the first failure after a good sync is when failing began. */
+ fun failed(now: Long): SyncRecord = copy(lastAttempt = lastAttempt ?: now, failingSince = failingSince ?: now)
+
/**
* The record after the sync state moved from [previous] to [state] at [now]. Each step of a running sync is a new
* [SyncState.Running], so only the first counts as an attempt. A failure seen without its running state (a state
@@ -102,12 +114,17 @@ interface StrapController {
fun connect()
- /** Connect to the paired strap if not already connected; no-op when nothing is paired. */
+ /**
+ * The user opened the app or tapped Retry: clears their Disconnect and connects to the paired strap if not already
+ * connected or trying; no-op when nothing is paired. Anything the user didn't ask for on screen is [backgroundConnect].
+ */
fun autoConnect()
/**
- * [autoConnect] for reconnects nobody asked for on screen (companion presence, phone alerts, process start):
- * a no-op while the user's Disconnect holds, which lasts until they connect again or open the app.
+ * [autoConnect] for reconnects nobody asked for on screen (companion presence, phone alerts, process start, a
+ * workout starting, the widget's Sync now): a no-op while the user's Disconnect holds, which lasts until they
+ * connect again or open the app (this never clears it), and after a failure retrying can't fix
+ * ([ConnectErrors.isFinal], such as a key the strap turned down).
*/
fun backgroundConnect()
fun disconnect()
diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt
index e5212b21..6b195149 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt
@@ -89,9 +89,10 @@ class StrapManager(
connected(job, session)
}
override fun onLinkEnded() {
- buzzer.endFind()
+ buzzer.linkEnded()
onWear(null)
live.onLinkEnded()
+ commands.forgetAlarmCaps()
}
},
)
@@ -151,6 +152,10 @@ class StrapManager(
* failed step is logged and setup goes on without it.
*/
private suspend fun afterAuth(client: GattClient, s: ChannelSession) {
+ // Facts of the last connection, so a step that fails here shows as unknown rather than as an old value.
+ battery = null
+ charging = false
+ firmware = null
clock.queryVersion(s)
clock.setOnConnect(s, client)
querySettingsVersion(s)
@@ -328,6 +333,18 @@ class StrapManager(
// The app was stopped while it knew the wear state: close that interval now, as nothing is connected yet.
val now = System.currentTimeMillis() / 1000
wearEvents.post { if (dao.lastWearEvent()?.worn != null) dao.insertWearEvent(WearEventRow(now, null)) }
+ // Forget: the old strap's facts go with it, so the Device page can't show them for the next one.
+ scope.launch {
+ settings.pairedDevice.map { it != null }.distinctUntilChanged().collect { paired ->
+ if (paired) return@collect
+ info.value = null
+ todaySteps.value = null
+ battery = null
+ charging = false
+ firmware = null
+ commands.forgetAlarmCaps()
+ }
+ }
// For the widgets' status line with the strap away: the battery and charging as last connected.
scope.launch {
connection.mapNotNull { c -> (c as? ConnectionState.Connected)?.let { it.batteryPercent?.let { b -> b to it.charging } } }
@@ -539,6 +556,14 @@ class StrapManager(
s.messagesFor(Endpoints.REALTIME_ACTIVITY).collect { p ->
val totals = RealtimeSteps.parseMessage(p)
if (totals == null) log("steps < ${p.toHex()}")
+ // Zepp's `yt00` on a step push (`mgk`): in the background with no phone workout, notify goes off, so a
+ // workout that ended behind the app doesn't leave the strap pushing steps.
+ val now = android.os.SystemClock.elapsedRealtime()
+ if (StepsNotify.offOnPush(p, appVisible, workoutActive, now - stepsOffAt)) {
+ stepsOffAt = now
+ log("steps: push in the background, notify off")
+ stepsNotify(s, on = false)
+ }
totals?.let {
if (todaySteps.value?.isPlausible != it.isPlausible) {
log("steps today=${it.steps} dist=${it.distanceMeters} kcal=${it.calories}" + if (!it.isPlausible) " (total doesn't match distance: counting from synced history)" else "")
@@ -662,6 +687,9 @@ class StrapManager(
@Volatile private var workoutActive = false
private var stepsJob: kotlinx.coroutines.Job? = null
+ /** When a step push last turned notify off, for Zepp's 1.5 s per-state debounce. */
+ private var stepsOffAt = Long.MIN_VALUE / 2
+
override fun setWorkoutActive(active: Boolean) {
workoutActive = active
live.setWorkoutActive(active)
@@ -741,7 +769,8 @@ class StrapManager(
try {
// A failure is logged and handed on to the Firmware page. A cancellation is rethrown by catching as it came.
catching {
- if (live.isRunning) live.pause()
+ // The stream follows firmwareUpdating off on its own; this waits until the strap has been told.
+ live.pause()
// Zepp asks for high connection priority only for a firmware transfer (`f4c`), never on a normal link.
client.requestHighPriority()
val link = GattDfuLink(client)
@@ -763,9 +792,25 @@ class StrapManager(
private companion object {
const val MTU_PUSH = 0x02
const val STEPS_NOTIFY_REPLY = 0x06
- const val STEPS_DEBOUNCE_MS = 1_500L
+ const val STEPS_DEBOUNCE_MS = StepsNotify.DEBOUNCE_MS
const val BATTERY_RETRY_MS = 2_000L
const val SENT_PROFILE = "profile_crc"
const val SENT_CALORIE_GOAL = "calorie_goal"
}
}
+
+/** Zepp's RealtimeStepService (`yt00`) rule for a step push, kept apart so it can be tested. */
+internal object StepsNotify {
+ /** Zepp's debounce per notify state (`yt00.j`). */
+ const val DEBOUNCE_MS = 1_500L
+ private const val PUSH = 0x07
+
+ /**
+ * Whether a message on 0x0016 is a step push (`07`) that turns notify off, as Zepp does on its `mgk` event: the app
+ * behind, no phone workout recording, and no off sent in the last [DEBOUNCE_MS].
+ */
+ fun offOnPush(payload: ByteArray, appVisible: Boolean, workoutActive: Boolean, sinceLastOffMs: Long): Boolean {
+ if (payload.isEmpty() || payload.u8(0) != PUSH) return false
+ return !appVisible && !workoutActive && sinceLastOffMs >= DEBOUNCE_MS
+ }
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt
index ae0115dc..530ad4d0 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt
@@ -18,7 +18,6 @@ import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChangedBy
@@ -41,7 +40,6 @@ import org.openstrap.app.data.Workouts
import org.openstrap.app.presentation.NotificationCopy
import org.openstrap.app.presentation.StrapBands
import org.openstrap.app.presentation.TimeOfDay
-import org.openstrap.app.presentation.Units
import org.openstrap.app.presentation.WorkoutColors
import org.openstrap.app.presentation.WorkoutWords
@@ -57,6 +55,13 @@ class StrapService : LifecycleService() {
private var shown: Notification? = null
/** The notification's End asks first: until this time (elapsed realtime) it shows "Yes, end" and "Cancel". */
private val confirmEnd = MutableStateFlow(0L)
+ /**
+ * "Yes, end" was tapped and [WorkoutSession.end] hasn't finished: the confirmation stays up so a tap on that spot
+ * can't land on Pause. Drops when the workout leaves Recording, or after [END_WAIT_MS] if the end failed.
+ */
+ private val ending = MutableStateFlow(false)
+ /** What the last start command answered, so a workout ending can take the sticky restart back ([syncSticky]). */
+ private var sticky = false
/** Today's scores for the everyday notification, refreshed after each sync. */
private val figures = MutableStateFlow(null)
/**
@@ -94,13 +99,13 @@ class StrapService : LifecycleService() {
if (!tryForeground(first, withGps, log) && (withGps == base || !tryForeground(first, base, log))) {
(workout.state.value as? WorkoutState.Recording)?.let {
log("service: no foreground while recording, asking to keep it going")
- KeepRecordingNotice.show(this, it.workout.sportType)
+ KeepRecordingNotice.serviceRefused(this, it.workout.sportType)
}
stopSelf()
return START_NOT_STICKY
}
foreground = true
- KeepRecordingNotice.clear(this)
+ KeepRecordingNotice.serviceUp(this)
}
when (intent?.action) {
// Debug: the workout card with sample figures as this service's notification, or ("clear") its own back.
@@ -113,12 +118,11 @@ class StrapService : LifecycleService() {
ACTION_RESUME -> workout.resume()
ACTION_END_ASK -> confirmEnd.value = SystemClock.elapsedRealtime() + CONFIRM_MS
ACTION_END_CANCEL -> confirmEnd.value = 0
- ACTION_END -> { confirmEnd.value = 0; workout.end() }
+ ACTION_END -> endConfirmed(workout)
ACTION_SYNC -> strap.syncNow()
ACTION_RETRY -> strap.autoConnect()
- ACTION_UNDO -> intent.getLongExtra(EXTRA_START, 0).takeIf { it > 0 }?.let {
- workout.undoTrim(it)
- getSystemService(NotificationManager::class.java).cancel(SUMMARY_ID)
+ ACTION_UNDO -> intent.getLongExtra(EXTRA_START, 0).takeIf { it > 0 }?.let { start ->
+ undo(workout, dao, start, intent.getLongExtra(EXTRA_END, 0), intent.getLongExtra(EXTRA_RECORDED_END, 0))
}
ACTION_END_AT -> workout.endAtPrompt()
ACTION_KEEP -> workout.keepGoing()
@@ -127,8 +131,7 @@ class StrapService : LifecycleService() {
ACTION_SET_DONE -> workout.setDone()
ACTION_EXTEND -> workout.extendRest()
}
- val recording = workout.state.value is WorkoutState.Recording
- if (observing) return if (recording) START_STICKY else START_NOT_STICKY
+ if (observing) return stickiness(workout)
observing = true
// "End?" falls back to the usual actions if nobody answers.
lifecycleScope.launch { confirmEnd.collectLatest { until -> if (until > 0) { delay(CONFIRM_MS); confirmEnd.value = 0 } } }
@@ -143,13 +146,12 @@ class StrapService : LifecycleService() {
}
}
}
- lifecycleScope.launch { watchEnded(workout.state, dao) }
lifecycleScope.launch {
// Live HR changes about once a second, and every post wakes the CPU and redraws the system UI.
// Connection, battery, charging and workout changes post at once; a bpm-only change waits for the refresh.
var status: String? = null
var lastPost = 0L
- val more = combine(strap.sync, figures, hidden, confirmEnd) { sync, f, h, end -> More(sync, f, h, end) }
+ val more = combine(strap.sync, figures, hidden, confirmEnd, ending) { sync, f, h, end, asked -> More(sync, f, h, end, asked) }
// Until the session has checked for a workout left recording (a restart after the process died), stay up.
combine(strap.connection, strap.liveHeartRate, workout.state, workout.restored, more) { c, hr, w, restored, m ->
Status(c, hr, w, restored, m)
@@ -157,7 +159,9 @@ class StrapService : LifecycleService() {
if (c is ConnectionState.Disconnected || c is ConnectionState.NotPaired) {
if (w !is WorkoutState.Recording && restored) { stopSelf(); return@collect }
}
- val confirming = m.confirmEnd > SystemClock.elapsedRealtime()
+ if (w !is WorkoutState.Recording && m.ending) ending.value = false
+ syncSticky(workout)
+ val confirming = m.confirmEnd > SystemClock.elapsedRealtime() || m.ending
val now = SystemClock.elapsedRealtime()
val n: Notification
if (w is WorkoutState.Recording) {
@@ -184,7 +188,51 @@ class StrapService : LifecycleService() {
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, n)
}
}
- return if (recording) START_STICKY else START_NOT_STICKY
+ return stickiness(workout)
+ }
+
+ /** "Yes, end": the confirmation stays up until the workout has ended ([ending]), where it used to reset at once. */
+ private fun endConfirmed(workout: WorkoutSession) {
+ ending.value = true
+ confirmEnd.value = 0
+ workout.end()
+ lifecycleScope.launch { delay(END_WAIT_MS); ending.value = false }
+ }
+
+ /**
+ * Saved's Undo: only while the workout is still as that notification left it (ended on its own, at the time it
+ * named). A trim made by hand since changes both, and is never undone from here. The notification goes either way.
+ */
+ private fun undo(workout: WorkoutSession, dao: HealthDao, start: Long, end: Long, recordedEnd: Long) {
+ lifecycleScope.launch {
+ val w = catching { dao.appWorkoutOnce(start) }.getOrNull()
+ if (w != null && WorkoutNotifier.undoApplies(w, end, recordedEnd)) workout.undoTrim(start)
+ WorkoutNotifier.cancelSaved(this@StrapService)
+ }
+ }
+
+ /**
+ * Sticky while a workout is in progress, or before the session has checked for one: a restart after the process
+ * died comes before [WorkoutSession.restore] finishes, and answering on that instant would drop the workout.
+ */
+ private fun stickiness(workout: WorkoutSession): Int {
+ val s = workout.state.value
+ sticky = !workout.restored.value || s is WorkoutState.Recording || s is WorkoutState.Ended
+ return if (sticky) START_STICKY else START_NOT_STICKY
+ }
+
+ /**
+ * A start command's answer holds until the next one, so once the session has checked and nothing is in progress,
+ * the service starts itself again to answer not sticky.
+ */
+ private fun syncSticky(workout: WorkoutSession) {
+ val s = workout.state.value
+ val idle = workout.restored.value && s !is WorkoutState.Recording && s !is WorkoutState.Ended
+ if (sticky && idle) {
+ sticky = false
+ // Android may refuse the start now; the answer then stays sticky until the next start.
+ runCatching { start(this) }
+ }
}
/**
@@ -212,9 +260,6 @@ class StrapService : LifecycleService() {
)
// Left by the old Quiet switch: Android raises a foreground service's MIN channel to LOW anyway.
nm.deleteNotificationChannel("strap_quiet")
- nm.createNotificationChannel(
- NotificationChannel(SAVED_CHANNEL, getString(R.string.system_channel_saved), NotificationManager.IMPORTANCE_LOW),
- )
WorkoutNotification.createChannel(this)
KeepRecordingNotice.createChannel(this)
// Left by workout auto-start ("Looks like a workout"), which is gone.
@@ -245,7 +290,7 @@ class StrapService : LifecycleService() {
/** What the everyday notification says; equal content isn't posted again. */
private data class IdleContent(
val title: String, val text: String, val header: String?, val syncedAt: Long?, val progress: Float?, val syncing: Boolean,
- val retry: Boolean, val connected: Boolean, val sport: Int, val problem: String?,
+ val retry: Boolean, val connected: Boolean, val sport: Int, val problem: String?, val bluetoothOff: Boolean = false,
)
/**
@@ -265,14 +310,18 @@ class StrapService : LifecycleService() {
text = idleText(c, sync, f, problem),
header = idleHeader(connected.takeIf { problem == null }, syncedAt),
syncedAt = syncedAt, progress = (sync as? SyncState.Running)?.progress, syncing = sync is SyncState.Running,
- retry = c is ConnectionState.Failed, connected = connected != null, sport = f?.sport ?: Workouts.DEFAULT_SPORTS.first(),
+ // A key the strap turned down fails the same way again: the Device page offers pairing again instead.
+ retry = c is ConnectionState.Failed && !c.keyRejected, connected = connected != null,
+ sport = f?.sport ?: Workouts.DEFAULT_SPORTS.first(),
problem = when { c is ConnectionState.Failed -> "failed"; low -> "low"; problem != null -> "off"; else -> null },
+ bluetoothOff = c is ConnectionState.BluetoothOff,
)
}
/** What's wrong, as the title: the strap out of reach, not connected, or low. Null when nothing is. */
private fun problemTitle(c: ConnectionState, low: Boolean, battery: Int?): String? = when {
c is ConnectionState.Failed -> getString(R.string.system_strap_failed)
+ c is ConnectionState.BluetoothOff -> getString(R.string.system_strap_bluetooth_off)
c is ConnectionState.Connected -> if (low) getString(R.string.system_strap_low_battery, battery) else null
c is ConnectionState.Connecting || c is ConnectionState.Authenticating -> null
else -> getString(R.string.system_strap_not_connected)
@@ -347,6 +396,7 @@ class StrapService : LifecycleService() {
i.syncedAt?.let { b.setShowWhen(true).setWhen(it * 1000) } ?: b.setShowWhen(false)
if (i.syncing) b.setProgress(100, ((i.progress ?: 0f) * 100).roundToInt(), i.progress == null)
if (i.retry) b.addAction(NotificationCompat.Action(0, getString(R.string.system_strap_action_retry), service(ACTION_RETRY)))
+ if (i.bluetoothOff) b.addAction(NotificationCompat.Action(0, getString(R.string.system_strap_action_turn_on), turnOnBluetooth()))
if (i.connected) {
b.addAction(NotificationCompat.Action(0, getString(R.string.system_strap_action_start_workout), startWorkout(i.sport)))
if (!i.syncing) b.addAction(NotificationCompat.Action(0, getString(R.string.system_strap_action_sync), service(ACTION_SYNC)))
@@ -354,6 +404,12 @@ class StrapService : LifecycleService() {
return b.build()
}
+ /** Android's dialog to turn Bluetooth on, from the notification's Turn on. */
+ private fun turnOnBluetooth(): PendingIntent = PendingIntent.getActivity(
+ this, REQUEST_BLUETOOTH, Intent(android.bluetooth.BluetoothAdapter.ACTION_REQUEST_ENABLE),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+
private fun startWorkout(sport: Int): PendingIntent = PendingIntent.getActivity(
this, REQUEST_START,
Intent(this, MainActivity::class.java).putExtra(MainActivity.EXTRA_READY_SPORT, sport).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
@@ -472,59 +528,6 @@ class StrapService : LifecycleService() {
WorkoutNotification.actions(paused = false, confirming = true, intent = ::service).forEach(::addAction)
}
- /**
- * Once a workout is saved, a quiet summary with View, and Undo when it ended on its own (the stop or car question)
- * and the time after was kept. It goes when the summary in the app is closed.
- */
- private suspend fun watchEnded(workoutState: StateFlow, dao: HealthDao) {
- val nm = getSystemService(NotificationManager::class.java)
- var previous: WorkoutState? = null
- workoutState.collect { st ->
- val was = previous
- previous = st
- when {
- st is WorkoutState.Ended && was is WorkoutState.Recording -> {
- val w = dao.appWorkoutOnce(st.start) ?: return@collect
- nm.notify(SUMMARY_ID, savedNotification(w))
- }
- st !is WorkoutState.Ended -> nm.cancel(SUMMARY_ID)
- }
- }
- }
-
- private fun savedNotification(w: org.openstrap.app.data.db.AppWorkout): Notification {
- val end = w.end ?: System.currentTimeMillis() / 1000
- val duration = WorkoutRecorder.activeSeconds(w.copy(end = null, pausedAt = null), end)
- val facts = listOfNotNull(
- Units.workoutClock(duration),
- w.distanceMeters?.let { Units.distance(it, Units.Precision.Workout, w.distanceFromSteps) },
- w.averageHeartRate?.let { getString(R.string.system_saved_average_bpm, it) },
- ).joinToString(", ")
- val auto = w.endReason == org.openstrap.app.data.db.AppWorkout.END_AUTO || w.endReason == org.openstrap.app.data.db.AppWorkout.END_CAR
- val cut = w.recordedEnd?.let { it - end }?.takeIf { auto && it >= 60 }
- val time = TimeOfDay.format(end, java.time.ZoneId.systemDefault())
- val text = if (cut != null) getString(R.string.system_saved_cut, facts, time, (cut / 60).toInt()) else facts
- val b = NotificationCompat.Builder(this, SAVED_CHANNEL)
- .setSmallIcon(R.drawable.ic_stat_unstrap)
- .setContentTitle(getString(R.string.system_saved_title, Workouts.sportName(w.sportType)))
- .setContentText(facts)
- .setStyle(NotificationCompat.BigTextStyle().bigText(text))
- .setCategory(NotificationCompat.CATEGORY_WORKOUT)
- .setAutoCancel(true)
- .setContentIntent(openApp())
- .addAction(NotificationCompat.Action(0, getString(R.string.system_saved_action_view), openApp()))
- if (cut != null) b.addAction(
- NotificationCompat.Action(
- 0, getString(R.string.system_saved_action_undo),
- PendingIntent.getService(
- this, REQUEST_UNDO, Intent(this, StrapService::class.java).setAction(ACTION_UNDO).putExtra(EXTRA_START, w.start),
- PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
- ),
- ),
- )
- return b.build()
- }
-
/** Strength on the lock screen: the set or the rest counting down, its progress, and the next step. */
private fun strengthNotification(r: WorkoutState.Recording, bpm: Int?, connected: Boolean, confirming: Boolean, zones: HeartZones): Notification {
val now = System.currentTimeMillis()
@@ -615,7 +618,7 @@ class StrapService : LifecycleService() {
PendingIntent.getService(this, action.hashCode(), Intent(this, StrapService::class.java).setAction(action), PendingIntent.FLAG_IMMUTABLE)
private data class Status(val connection: ConnectionState, val heartRate: Int?, val workout: WorkoutState, val restored: Boolean, val more: More)
- private data class More(val sync: SyncState, val figures: Figures?, val hidden: Hidden?, val confirmEnd: Long)
+ private data class More(val sync: SyncState, val figures: Figures?, val hidden: Hidden?, val confirmEnd: Long, val ending: Boolean)
private data class Hidden(val problem: String?)
private data class Figures(
val recovery: Int?, val charge: Int?, val sport: Int, val syncedAt: Long?,
@@ -629,14 +632,16 @@ class StrapService : LifecycleService() {
internal const val ACTION_END_CANCEL = "org.openstrap.app.workout.END_CANCEL"
private const val ACTION_SYNC = "org.openstrap.app.strap.SYNC"
private const val ACTION_RETRY = "org.openstrap.app.strap.RETRY"
- private const val ACTION_UNDO = "org.openstrap.app.workout.UNDO"
+ internal const val ACTION_UNDO = "org.openstrap.app.workout.UNDO"
private const val ACTION_HIDE = "org.openstrap.app.strap.HIDE"
- private const val EXTRA_START = "start"
- private const val SUMMARY_ID = 4
- private const val SAVED_CHANNEL = "workout_saved"
+ internal const val EXTRA_START = "start"
+ internal const val EXTRA_END = "end"
+ internal const val EXTRA_RECORDED_END = "recorded_end"
private const val REQUEST_START = 5
- private const val REQUEST_UNDO = 6
+ private const val REQUEST_BLUETOOTH = 7
private const val CONFIRM_MS = 6_000L
+ /** How long "Yes, end" stays up for an end that hasn't finished; a failed end brings the usual actions back. */
+ private const val END_WAIT_MS = 15_000L
private const val FIGURES_REFRESH_MS = 30 * 60_000L
/** The red dot in the "OS." logo, the app's heart colour: zone 5's red. */
private const val BRAND_DOT = WorkoutColors.ZONE_5
@@ -654,7 +659,7 @@ class StrapService : LifecycleService() {
private const val ACTION_EXTEND = "org.openstrap.app.workout.EXTEND"
/** Each zone's length on the notification's progress bar. */
private const val ZONE_SPAN = 20
- private const val REQUEST_OPEN = 2
+ internal const val REQUEST_OPEN = 2
/** Whether the service is up; a start then needn't (and, once swiped away, mustn't) post its notification. */
@Volatile var running = false
diff --git a/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt b/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt
index f7df6efd..1a5b392c 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt
@@ -2,6 +2,7 @@ package org.openstrap.app.device
import android.content.Context
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
@@ -63,12 +64,14 @@ internal class SyncCoordinator(
val isSyncing: Boolean get() = running
init {
- // Every sync's start and end, pulled or in the background, so Today can tell a stuck sync from a slow one.
+ // What the last runs left, kept across restarts: the one status the header, the Strap page and the widgets read.
scope.launch {
- var previous: SyncState = SyncState.Idle
- sync.collect { s ->
- syncRecord.update { it.next(previous, s, clock() / MILLIS_PER_SECOND) }
- previous = s
+ catching { settings.strapSnapshot.first() }.onSuccess { kept ->
+ // Not once a sync has run in this process: its own result is newer.
+ syncRecord.update {
+ if (it.lastAttempt != null) it
+ else it.copy(lastSuccess = it.lastSuccess ?: kept.lastSyncDone, failingSince = kept.failingSince ?: it.failingSince)
+ }
}
}
scope.launch { for (task in queue) runTask(task) }
@@ -152,24 +155,57 @@ internal class SyncCoordinator(
if (task !is SyncTask.Demand) lastStartMs = clock()
log("sync: $task")
running = true
+ syncRecord.update { it.attempted(clock() / MILLIS_PER_SECOND) }
+ // HistorySync writes into [inner]. The app sees its steps, but not how it ended before the work after it is done:
+ // until then the coordinator is busy, so the header can't say Synced and offer Disconnect while it still writes.
+ val inner = MutableStateFlow(SyncState.Idle)
+ val forward = scope.launch { inner.collect { if (it is SyncState.Running) sync.value = it } }
+ var end: SyncState? = null
try {
val only = (task as? SyncTask.Demand)?.types
catching {
withTimeout(SyncPolicy.WHOLE_SYNC_MS) {
- HistorySync(s, client, dao, settings, sync, log, notifiers.autoDetected::show).run(only)
+ HistorySync(s, client, dao, settings, inner, log, notifiers.autoDetected::show).run(only)
}
}.onFailure { log("sync: $it") }
- if (sync.value is SyncState.Running) sync.value = SyncState.Failed(Strings.app.get(R.string.system_sync_stopped))
- (sync.value as? SyncState.Done)?.let { d ->
- lastSuccessMs = d.atEpochSeconds * MILLIS_PER_SECOND
- catching { settings.setLastSyncDone(d.atEpochSeconds) }.onFailure { log("sync time not kept: $it") }
- }
+ forward.cancelAndJoin()
+ val result = inner.value.takeIf { it is SyncState.Done || it is SyncState.Failed }
+ ?: SyncState.Failed(Strings.app.get(R.string.system_sync_stopped))
+ end = result
+ if (sync.value !is SyncState.Running) sync.value = SyncState.Running(Strings.app.get(R.string.system_sync_preparing))
+ recordOutcome(task, result)
afterSync()
+ sync.value = result
if (link.activeSession === s) catching { afterFinished(s) }.onFailure { log("after sync: $it") }
// Everything a widget shows may have moved (widgets spec 7): they watch for this.
syncEnded.tryEmit(Unit)
} finally {
running = false
+ forward.cancel()
+ // A cancelled worker must not leave the state Running.
+ if (sync.value is SyncState.Running) sync.value = end ?: SyncState.Failed(Strings.app.get(R.string.system_sync_stopped))
+ }
+ }
+
+ /**
+ * What a finished sync leaves. Any success sets [lastSuccessMs], which the 120 s check reads, as in Zepp. Only a full
+ * sync moves the kept "Synced" time and ends the failure: a push syncs a few types. A failure of either begins one.
+ */
+ private suspend fun recordOutcome(task: SyncTask, end: SyncState) {
+ val now = clock() / MILLIS_PER_SECOND
+ when (end) {
+ is SyncState.Done -> {
+ lastSuccessMs = end.atEpochSeconds * MILLIS_PER_SECOND
+ if (task is SyncTask.Full) {
+ syncRecord.update { it.succeeded(end.atEpochSeconds) }
+ catching { settings.setLastSyncDone(end.atEpochSeconds) }.onFailure { log("sync time not kept: $it") }
+ }
+ }
+ is SyncState.Failed -> {
+ syncRecord.update { it.failed(now) }
+ catching { settings.setSyncFailing(now) }.onFailure { log("sync failure not kept: $it") }
+ }
+ else -> Unit
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt b/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt
index f98702ec..ab0756d2 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt
@@ -61,13 +61,20 @@ object WeeklyRecap {
catching { container.rewards.refreshNow(recordingStart) }.onFailure { Log.w("unstrap", "weekly recap: weeks not refreshed: $it") }
val weeks = container.database.healthDao().weekResultsOnce()
val week = weeks.firstOrNull { it.weekStart == lastWeek.toEpochDay() }
- settings.setRecapWeek(lastWeek.toEpochDay())
- if (week == null || week.count == 0) return
+ // Nothing to say about a week without a workout, and nothing will change that: done with it.
+ if (week == null || week.count == 0) {
+ settings.setRecapWeek(lastWeek.toEpochDay())
+ return
+ }
// Android 13 brought the notification permission. Before it, the check would always read as denied.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) return
- show(context, RewardsCopy.weekRange(lastWeek), RewardsCopy.recapText(week, Rewards.inARow(weeks, lastWeek)))
+ // Sent once it has been shown: a denied permission or a failed post leaves the week for the next look this morning.
+ val text = RewardsCopy.recapText(week, Rewards.inARow(weeks, lastWeek))
+ val shown = catching { show(context, RewardsCopy.weekRange(lastWeek), text) }
+ .onFailure { Log.w("unstrap", "weekly recap: not shown: $it") }
+ if (shown.isSuccess) settings.setRecapWeek(lastWeek.toEpochDay())
}
private fun show(context: Context, range: String, text: String) {
diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutNotifier.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutNotifier.kt
new file mode 100644
index 00000000..008028a1
--- /dev/null
+++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutNotifier.kt
@@ -0,0 +1,140 @@
+package org.openstrap.app.device
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import androidx.core.app.NotificationCompat
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.launch
+import org.openstrap.app.MainActivity
+import org.openstrap.app.R
+import org.openstrap.app.data.WorkoutRecorder
+import org.openstrap.app.data.Workouts
+import org.openstrap.app.data.catching
+import org.openstrap.app.data.db.AppWorkout
+import org.openstrap.app.presentation.TimeOfDay
+import org.openstrap.app.presentation.Units
+
+/**
+ * Owns the workout notifications that outlive [StrapService]: Saved, and the Keep recording notice. Both follow the
+ * session's state and live on the app scope, so a service that stops itself, or a fresh one, can't orphan, drop or
+ * cancel one (audit S10). The ongoing workout notification stays the service's: it is the foreground notification, and
+ * Android removes it with the service.
+ */
+class WorkoutNotifier(
+ context: Context,
+ private val state: StateFlow,
+ /** The stored workout by its start. */
+ private val workoutOnce: suspend (Long) -> AppWorkout?,
+ private val scope: CoroutineScope,
+) {
+ private val context = context.applicationContext
+ private var previous: WorkoutState? = null
+
+ /** Follows the session from now on. */
+ fun start() {
+ scope.launch { state.collect { sync(it) } }
+ }
+
+ /**
+ * Posts and cancels from [st]: Saved once a workout is saved, and gone as soon as the summary is closed or another
+ * workout starts; the Keep recording notice gone as soon as nothing records.
+ */
+ suspend fun sync(st: WorkoutState) {
+ val was = previous
+ previous = st
+ if (st !is WorkoutState.Recording) KeepRecordingNotice.end(context)
+ when {
+ st is WorkoutState.Ended && was is WorkoutState.Recording -> {
+ val w = catching { workoutOnce(st.start) }.getOrNull() ?: return
+ // The summary may already be closed by the time the read returns.
+ if (state.value == st) notifySaved(w)
+ }
+ st !is WorkoutState.Ended -> cancelSaved(context)
+ }
+ }
+
+ private fun notifySaved(w: AppWorkout) {
+ val nm = context.getSystemService(NotificationManager::class.java)
+ nm.createNotificationChannel(
+ NotificationChannel(SAVED_CHANNEL, context.getString(R.string.system_channel_saved), NotificationManager.IMPORTANCE_LOW),
+ )
+ nm.notify(SUMMARY_ID, savedNotification(w))
+ }
+
+ private fun openApp(): PendingIntent = PendingIntent.getActivity(
+ context, StrapService.REQUEST_OPEN,
+ Intent(context, MainActivity::class.java).putExtra(MainActivity.EXTRA_SHOW_WORKOUT, true).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+
+ /**
+ * A quiet summary with View, and Undo when it ended on its own (the stop or car question) and the time after was
+ * kept. Undo carries the end it was posted for, so it can tell a later trim by hand ([undoApplies]).
+ */
+ private fun savedNotification(w: AppWorkout): Notification {
+ val end = w.end ?: System.currentTimeMillis() / 1000
+ val duration = WorkoutRecorder.activeSeconds(w.copy(end = null, pausedAt = null), end)
+ val facts = listOfNotNull(
+ Units.workoutClock(duration),
+ w.distanceMeters?.let { Units.distance(it, Units.Precision.Workout, w.distanceFromSteps) },
+ w.averageHeartRate?.let { context.getString(R.string.system_saved_average_bpm, it) },
+ ).joinToString(", ")
+ val cut = cutSeconds(w)
+ val time = TimeOfDay.format(end, java.time.ZoneId.systemDefault())
+ val text = if (cut != null) context.getString(R.string.system_saved_cut, facts, time, (cut / 60).toInt()) else facts
+ val b = NotificationCompat.Builder(context, SAVED_CHANNEL)
+ .setSmallIcon(R.drawable.ic_stat_unstrap)
+ .setContentTitle(context.getString(R.string.system_saved_title, Workouts.sportName(w.sportType)))
+ .setContentText(facts)
+ .setStyle(NotificationCompat.BigTextStyle().bigText(text))
+ .setCategory(NotificationCompat.CATEGORY_WORKOUT)
+ .setAutoCancel(true)
+ .setContentIntent(openApp())
+ .addAction(NotificationCompat.Action(0, context.getString(R.string.system_saved_action_view), openApp()))
+ if (cut != null) b.addAction(
+ NotificationCompat.Action(
+ 0, context.getString(R.string.system_saved_action_undo),
+ PendingIntent.getService(
+ context, REQUEST_UNDO,
+ Intent(context, StrapService::class.java).setAction(StrapService.ACTION_UNDO)
+ .putExtra(StrapService.EXTRA_START, w.start)
+ .putExtra(StrapService.EXTRA_END, end)
+ .putExtra(StrapService.EXTRA_RECORDED_END, w.recordedEnd ?: 0L),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ ),
+ ),
+ )
+ return b.build()
+ }
+
+ companion object {
+ internal const val SUMMARY_ID = 4
+ internal const val SAVED_CHANNEL = "workout_saved"
+ private const val REQUEST_UNDO = 6
+ private const val MIN_CUT_S = 60
+
+ /** The time an automatic end left out, in seconds, when it is long enough to offer Undo for. */
+ internal fun cutSeconds(w: AppWorkout): Long? {
+ val end = w.end ?: return null
+ val auto = w.endReason == AppWorkout.END_AUTO || w.endReason == AppWorkout.END_CAR
+ return w.recordedEnd?.let { it - end }?.takeIf { auto && it >= MIN_CUT_S }
+ }
+
+ /**
+ * Whether Undo, posted for a workout that ended at [end] with [recordedEnd] recorded, may still be applied: only
+ * while it is as it was left, an automatic end. A trim by hand since is a user end at another time.
+ */
+ internal fun undoApplies(w: AppWorkout, end: Long, recordedEnd: Long): Boolean =
+ w.end == end && w.recordedEnd == recordedEnd &&
+ (w.endReason == AppWorkout.END_AUTO || w.endReason == AppWorkout.END_CAR)
+
+ fun cancelSaved(context: Context) {
+ context.getSystemService(NotificationManager::class.java).cancel(SUMMARY_ID)
+ }
+ }
+}
diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt
index df290d2a..e7c73a6b 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt
@@ -4,14 +4,17 @@ import android.content.Context
import android.os.PowerManager
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onSubscription
@@ -58,11 +61,24 @@ sealed interface WorkoutState {
val rounds: List = emptyList(),
val restExtra: Long = 0,
/**
- * The last save to the database failed. It records on in memory and the next change saves again, but a
- * process death now would lose what is unsaved, so the notification says so.
+ * The parts whose last save to the database failed, each tracked on its own so one success can't hide another
+ * failure. It records on in memory and the next change saves again, but a process death now would lose what is
+ * unsaved.
*/
- val saveFailed: Boolean = false,
+ val failing: Set = emptySet(),
+ /**
+ * End was tried and its save failed: the workout is still recording, and the live screen says "Not saved yet"
+ * with Try again, which runs End again.
+ */
+ val endFailed: Boolean = false,
) : WorkoutState {
+ /** Something isn't saved: the notification and the live screen say so. */
+ val saveFailed: Boolean get() = endFailed || failing.isNotEmpty()
+
+ /** This state with [part]'s last save [failed] or not, and the other parts as they were. */
+ fun withSave(part: SavePart, failed: Boolean): Recording =
+ if ((part in failing) == failed) this else copy(failing = if (failed) failing + part else failing - part)
+
/** Parsed once per state, not on every read: the rounds' clock reads it each second. */
val structure: org.openstrap.app.data.Structure? by lazy { org.openstrap.app.data.Structure.parse(workout.structure) }
@@ -83,6 +99,18 @@ sealed interface WorkoutState {
data class Ended(val start: Long, val preview: Boolean = false) : WorkoutState
}
+/** The parts of a recording workout that are saved separately, each with its own failure flag. */
+enum class SavePart { Workout, Sets, Rounds, HeartRate }
+
+/** A workout is in progress: recording, or ended with its summary still showing. */
+val WorkoutState.inProgress: Boolean get() = this is WorkoutState.Recording || this is WorkoutState.Ended
+
+/** What [WorkoutSession.start] came to. */
+enum class StartResult { Started, AlreadyRecording, Failed }
+
+/** What the phone knows of its GPS for the workout: not wanted, waiting for a first fix, fixes coming, or not available. */
+enum class GpsState { Off, Searching, Fixed, Unavailable }
+
/**
* The heart rate after a workout [start] ended at [end], for the summary's heart rate drop: what the strap sent, a
* reading a second (epoch seconds, bpm), until [until].
@@ -114,6 +142,8 @@ class WorkoutSession(
private val scope: CoroutineScope = fallbackScope(),
/** How long a workout left recording waits for the strap's history ([LeftRecording]). Tests shorten it. */
private val leftWaitMs: Long = LEFT_WAIT_MS,
+ /** How long a failed [restore] waits before trying again. Tests shorten it. */
+ private val restoreRetryMs: Long = RESTORE_RETRY_MS,
) {
private val lock = LOCK
@@ -132,6 +162,13 @@ class WorkoutSession(
private val _state = MutableStateFlow(WorkoutState.Idle)
val state: StateFlow = _state
+ /** A workout is recording, or ended with its summary showing: what every "in progress" check asks. */
+ val inProgress: Boolean get() = _state.value.inProgress
+
+ /** The GPS of the workout under way: [GpsState.Off] unless it uses GPS. */
+ private val _gps = MutableStateFlow(GpsState.Off)
+ val gps: StateFlow = _gps
+
/** Live readings of the last [RECENT_S] seconds, oldest first, for the live chart: (epoch seconds, bpm). */
private val _recent = MutableStateFlow>>(emptyList())
val recent: StateFlow>> = _recent
@@ -181,6 +218,9 @@ class WorkoutSession(
private var recordJob: Job? = null
private val buffer = mutableListOf()
private var lastSecond = -1L
+
+ /** The workout is being ended: its last flush is made, and a reading now would be written under no workout. */
+ @Volatile private var ending = false
private var wake: PowerManager.WakeLock? = null
/**
@@ -190,59 +230,98 @@ class WorkoutSession(
*/
fun restore() {
scope.launch {
+ var failed = false
try {
- val waiting = lock.withLock {
- if (_state.value is WorkoutState.Recording) return@withLock null
- val w = dao.activeAppWorkout() ?: return@withLock null
- val now = now()
- val stored = dao.appWorkoutHeartRateOnce(w.start)
- val last = maxOf(w.start, stored.maxOfOrNull { it.timestamp } ?: w.start)
- val waits = now - last > LEFT_RECORDING_S
- // Paused, nothing the strap measured since is part of it.
- if (waits && w.pausedAt != null) {
- endLeftRecording(w, last)
- return@withLock null
+ catching { restoreLocked() }
+ .onSuccess { waiting -> waiting?.let { scope.launch { awaitStrap(it) } } }
+ .onFailure {
+ // The active row is still stored, so it is tried again below rather than ended: ending would
+ // cost a workout that only hit a bad moment (a locked database, say).
+ log("workout not restored, trying again: ${it.message}")
+ failed = true
}
- // Set before it shows as recording, so an End tapped at once already waits for the strap.
- left = if (waits) LeftRecording.Left(w.start, last, now) else null
- _recent.value = stored.filter { !it.fromHistory && it.timestamp >= now - RECENT_S }.map { it.timestamp to it.bpm }
- sum = stored.sumOf { it.bpm.toLong() }
- count = stored.size.toLong()
- _stats.value = WorkoutRecorder.stats(stored)
- val live = stored.filter { !it.fromHistory }.map { it.timestamp to it.bpm }
- val maxHr = maxHeartRate()
- _zoneSeconds.value = WorkoutRecorder.liveZoneSeconds(live, maxHr, heartZones.value).toList()
- lastReading = live.lastOrNull()
- _kcal.value = null
- stepTotals = emptyList()
- synchronized(allReadings) { allReadings.clear(); allReadings.addAll(live) }
- _history.value = live
- window = live.filter { it.first >= now - STOP_WINDOW_S }
- // A kept route comes back. One that wasn't kept was only ever in memory, and so were the step
- // totals. What was stored then stands for the time before now, and the distance adds to it.
- _route.value = if (w.keepRoute) dao.routeOnce(w.start).map { it.point } else emptyList()
- savedPoints = _route.value.size
- trackFrom(w, routeSince = if (w.keepRoute) w.start else now, stepsSince = now, before = w)
- // A restart mustn't ask at once about a stop it can't see the start of.
- askSince = now
- val sets = dao.setsOnce(w.start)
- val restUntil = sets.lastOrNull()?.takeIf { it.end != null && it.restEnd == null }?.let { it.end!! + restRule(w).seconds }
- // Logging is the sport's setting at its start, which Ready saved then.
- val log = catching { settings.sportSettings.first()[org.openstrap.app.data.Workouts.tileType(w.sportType)]?.log }
- .onFailure { log("workout: sport settings not read: $it") }.getOrNull() == true
- val rounds = if (w.structure != null) dao.roundsOnce(w.start) else emptyList()
- begin(w, maxHr) {
- it.copy(sets = sets, restUntil = restUntil, exercise = sets.lastOrNull()?.exercise, logSets = log, rounds = rounds)
- }
- left
- }
- waiting?.let { scope.launch { awaitStrap(it) } }
} finally {
+ // Marked either way: the service and the backups wait on it, and an unrestored workout mustn't hold them.
_restored.value = true
}
+ if (failed) retryRestore()
+ }
+ }
+
+ /** A failed [restore] tried again, up to [RESTORE_TRIES] times, [restoreRetryMs] apart; then the row stays for the next start. */
+ private suspend fun retryRestore() {
+ repeat(RESTORE_TRIES) {
+ delay(restoreRetryMs)
+ val done = catching { restoreLocked()?.let { l -> scope.launch { awaitStrap(l) } } }
+ .onFailure { e -> log("workout not restored, ${e.message}") }.isSuccess
+ if (done) return
}
+ log("workout not restored: left as stored for the next start")
}
+ /** The picking up of [restore], under [lock]: the workout waiting for the strap's history ([LeftRecording]), if any. */
+ private suspend fun restoreLocked(): LeftRecording.Left? =
+ lock.withLock {
+ if (_state.value is WorkoutState.Recording) return@withLock null
+ val w = dao.activeAppWorkout() ?: return@withLock null
+ val now = now()
+ val stored = dao.appWorkoutHeartRateOnce(w.start)
+ val last = maxOf(w.start, stored.maxOfOrNull { it.timestamp } ?: w.start)
+ val waits = now - last > LEFT_RECORDING_S
+ // Paused, nothing the strap measured since is part of it.
+ if (waits && w.pausedAt != null) {
+ endLeftRecording(w, last)
+ return@withLock null
+ }
+ // Set before it shows as recording, so an End tapped at once already waits for the strap.
+ left = if (waits) LeftRecording.Left(w.start, last, now) else null
+ _recent.value = stored.filter { !it.fromHistory && it.timestamp >= now - RECENT_S }.map { it.timestamp to it.bpm }
+ sum = stored.sumOf { it.bpm.toLong() }
+ count = stored.size.toLong()
+ _stats.value = WorkoutRecorder.stats(stored)
+ val live = stored.filter { !it.fromHistory }.map { it.timestamp to it.bpm }
+ val maxHr = maxHeartRate()
+ _zoneSeconds.value = WorkoutRecorder.liveZoneSeconds(live, maxHr, heartZones.value).toList()
+ lastReading = live.lastOrNull()
+ // Never down: kept when this very workout's figure is still in memory (a second try after a failure),
+ // else it comes back from what was kept ([keepLive]), as does the rest time added. A question open
+ // and "in a car" start afresh: a restart mustn't ask at once ([askSince]).
+ val kept = catching { settings.workoutLive(w.start) }.onFailure { log("workout: live figures not read: $it") }.getOrNull()
+ keptLive = kept
+ if (trackStart != w.start) {
+ _kcal.value = kept?.let { k -> k.kcalActive?.let { a -> k.kcalTotal?.let { WorkoutRecorder.Kcal(a, it) } } }
+ }
+ stepTotals = emptyList()
+ synchronized(allReadings) { allReadings.clear(); allReadings.addAll(live) }
+ _history.value = live
+ window = live.filter { it.first >= now - STOP_WINDOW_S }
+ // A kept route comes back. One that wasn't kept was only ever in memory, and so were the step
+ // totals. What was stored then stands for the time before now, and the distance adds to it.
+ val restored = if (w.keepRoute) dao.routeOnce(w.start).map { it.point } else emptyList()
+ _route.update { restored }
+ savedPoints = _route.value.size
+ trackFrom(w, routeSince = if (w.keepRoute) w.start else now, stepsSince = now, before = w)
+ // A restart mustn't ask at once about a stop it can't see the start of.
+ askSince = now
+ val sets = dao.setsOnce(w.start)
+ val restUntil = sets.lastOrNull()?.takeIf { it.end != null && it.restEnd == null }?.let { it.end!! + restRule(w).seconds }
+ // Logging is the sport's setting at its start, which Ready saved then.
+ val log = catching { settings.sportSettings.first()[org.openstrap.app.data.Workouts.tileType(w.sportType)]?.log }
+ .onFailure { log("workout: sport settings not read: $it") }.getOrNull() == true
+ val rounds = if (w.structure != null) dao.roundsOnce(w.start) else emptyList()
+ begin(w, maxHr) {
+ it.copy(
+ sets = sets, restUntil = restUntil, exercise = sets.lastOrNull()?.exercise, logSets = log, rounds = rounds,
+ restExtra = kept?.restExtra ?: 0,
+ )
+ }
+ left
+ }
+
+ /**
+ * Starts a workout. The result says what came of it: [StartResult.AlreadyRecording] when one records already, and
+ * [StartResult.Failed] when its row or its recording couldn't be set up (nothing is left half started).
+ */
fun start(
sportType: Int, askToEnd: Boolean = true, target: org.openstrap.app.data.WorkoutTarget? = null,
useGps: Boolean = false, keepRoute: Boolean = false,
@@ -251,21 +330,26 @@ class WorkoutSession(
from: Long? = null, seed: List> = emptyList(), seedSteps: Int? = null,
/** Strength: a log card after each set. Rounds or periods ([AppWorkout.structure]). */
logSets: Boolean = false, structure: String? = null,
- ) {
- scope.launch {
+ ): Deferred = scope.async {
+ // The row's own write failing counts too: nothing was started then.
+ catching {
lock.withLock {
- if (_state.value is WorkoutState.Recording) return@withLock
+ if (_state.value is WorkoutState.Recording) return@withLock StartResult.AlreadyRecording
val w = AppWorkout(
start = from ?: now(), end = null, sportType = sportType, askToEnd = askToEnd, target = target?.code,
useGps = useGps, keepRoute = useGps && keepRoute,
rest = rest?.code, setsTarget = setsTarget, structure = structure,
)
- _route.value = emptyList()
+ _route.update { emptyList() }
savedPoints = 0
trackFrom(w, routeSince = w.start, stepsSince = w.start, before = null)
synchronized(allReadings) { allReadings.clear() }
+ // Nothing of an earlier workout is written under this one's start.
+ synchronized(buffer) { buffer.clear() }
+ lastSecond = -1L
_history.value = emptyList()
dao.upsertAppWorkout(w)
+ _gps.value = GpsState.Off
_recent.value = emptyList()
_stats.value = null
sum = 0
@@ -278,8 +362,16 @@ class WorkoutSession(
window = emptyList()
askSince = w.start
minimized.value = false
- begin(w, maxHeartRate(), seed) { it.copy(logSets = logSets) }
+ // Half started is not started: begin undid what it took, and the row goes too.
+ val begun = catching { begin(w, maxHeartRate(), seed) { it.copy(logSets = logSets) } }.onFailure {
+ log("workout not started: $it")
+ catching { dao.deleteAppWorkout(w.start) }.onFailure { e -> log("workout row not removed: ${e.message}") }
+ }
+ if (begun.isSuccess) StartResult.Started else StartResult.Failed
}
+ }.getOrElse {
+ log("workout not started: $it")
+ StartResult.Failed
}
}
@@ -333,6 +425,29 @@ class WorkoutSession(
@Volatile private var strapSessions = true
private var keepAlive: Job? = null
+ /**
+ * A STOP or ABANDON that didn't reach the strap (out of range, Bluetooth off). The strap keeps that session running
+ * and sends its frames, which then lead the live heart rate (audit S11, seen 2026-11-11), so the next connect with
+ * nothing recording sends it once ([resendEnd]). A new START replaces it.
+ */
+ private class UnsentEnd(val state: org.openstrap.protocol.services.SportSession.State, val w: AppWorkout, val elapsed: Long)
+ @Volatile private var unsentEnd: UnsentEnd? = null
+
+ init {
+ scope.launch {
+ strap.connection.map { it is ConnectionState.Connected }.distinctUntilChanged().collect { if (it) resendEnd() }
+ }
+ }
+
+ private suspend fun resendEnd() {
+ val e = unsentEnd ?: return
+ if (_state.value is WorkoutState.Recording) return
+ log("strap session: the ${e.state} that didn't go out goes now")
+ catching { strap.sportSession(e.state, e.w.sportType, e.w.start, e.elapsed, reconnect = false) }
+ .onSuccess { if (unsentEnd === e) unsentEnd = null }
+ .onFailure { log("strap session ${e.state} not sent again: ${it.message}") }
+ }
+
/**
* Tells the strap's sport module, when that's on; a failure is logged and the phone recording carries on. [send]
* false when the strap made the change itself: nothing goes out, but a pause still gets its keep-alive.
@@ -345,9 +460,16 @@ class WorkoutSession(
) {
if (!strapSessions) return
val elapsed = WorkoutRecorder.activeSeconds(w, now())
+ val end = state == org.openstrap.protocol.services.SportSession.State.STOP ||
+ state == org.openstrap.protocol.services.SportSession.State.ABANDON
+ if (state == org.openstrap.protocol.services.SportSession.State.START) unsentEnd = null
if (send) scope.launch {
catching { strap.sportSession(state, w.sportType, w.start, elapsed, reconnect) }
- .onFailure { (strap as? StrapManager)?.log("strap session $state not sent: ${it.message}") }
+ .onSuccess { if (end) unsentEnd = null }
+ .onFailure {
+ (strap as? StrapManager)?.log("strap session $state not sent: ${it.message}")
+ if (end) unsentEnd = UnsentEnd(state, w, elapsed)
+ }
}
keepAlive?.cancel()
// While paused, Zepp sends the module a keep-alive every 5 s.
@@ -441,6 +563,10 @@ class WorkoutSession(
lock.withLock {
val r = _state.value as? WorkoutState.Recording ?: return@withLock
if (startOf != null && r.workout.start != startOf) return@withLock
+ // Readings after this one are dropped ([record]): they would be written after the last flush, under
+ // the next workout's start or as rows of one just deleted.
+ ending = true
+ _state.update { s -> (s as? WorkoutState.Recording)?.takeIf { it.endFailed }?.copy(endFailed = false) ?: s }
flush()
saveDistance()
val w = r.workout
@@ -459,7 +585,9 @@ class WorkoutSession(
val stored = store(ended, recorded, kept, _route.value)
stored.exceptionOrNull()?.let {
log("workout ${if (kept) "not saved" else "not deleted"}, still recording: ${it.message}")
- _state.update { s -> (s as? WorkoutState.Recording)?.copy(saveFailed = true) ?: s }
+ _state.update { s -> (s as? WorkoutState.Recording)?.copy(endFailed = true) ?: s }
+ // Recording on, so readings count again.
+ ending = false
return@withLock
}
left = null
@@ -724,7 +852,8 @@ class WorkoutSession(
// while the save ran stays.
_state.update {
(it as? WorkoutState.Recording)
- ?.copy(sets = changed.sets, restUntil = changed.restUntil, exercise = changed.exercise, saveFailed = failed) ?: it
+ ?.copy(sets = changed.sets, restUntil = changed.restUntil, exercise = changed.exercise)
+ ?.withSave(SavePart.Sets, failed) ?: it
}
}
}
@@ -765,6 +894,22 @@ class WorkoutSession(
(s as? WorkoutState.Recording)?.takeIf { it.phase(t) is org.openstrap.app.data.Phase.Rest }
?.let { it.copy(restExtra = it.restExtra + REST_ADD_S) } ?: s
}
+ scope.launch { lock.withLock { keepLive() } }
+ }
+
+ /** The last figures [keepLive] wrote, so an unchanged tick writes nothing. */
+ private var keptLive: org.openstrap.app.data.settings.WorkoutLive? = null
+
+ /**
+ * Keeps the recording workout's rest time added and live kcal, which no row holds, so [restore] brings them back.
+ * Called under [lock], so the writes keep their order.
+ */
+ private suspend fun keepLive() {
+ val r = _state.value as? WorkoutState.Recording ?: return
+ val k = _kcal.value
+ val live = org.openstrap.app.data.settings.WorkoutLive(r.workout.start, r.restExtra, k?.active, k?.total)
+ if (live == keptLive) return
+ catching { settings.setWorkoutLive(live) }.onSuccess { keptLive = live }.onFailure { log("workout: live figures not kept: $it") }
}
/**
@@ -791,8 +936,10 @@ class WorkoutSession(
val failed = catching { dao.upsertRounds(step.rounds) }.onFailure { log("rounds not saved: ${it.message}") }.isFailure
_state.update { s ->
val now = s as? WorkoutState.Recording ?: return@update s
- now.copy(rounds = step.rounds, restExtra = if (step.switch != null) 0 else now.restExtra, saveFailed = failed)
+ now.copy(rounds = step.rounds, restExtra = if (step.switch != null) 0 else now.restExtra)
+ .withSave(SavePart.Rounds, failed)
}
+ keepLive()
}
step.switch?.let { buzz(org.openstrap.app.data.WorkoutBuzz.of(it, game = s is org.openstrap.app.data.Structure.Periods), it.name) }
if (step.switch == null && !skip) {
@@ -863,7 +1010,7 @@ class WorkoutSession(
// The whole workout is written each time, and again at its end, so a failed save costs nothing kept.
val failed = catching { dao.upsertAppWorkout(w) }.onFailure { log("workout not saved: ${it.message}") }.isFailure
// Only the workout is ours: everything else (an end prompt, say) may have changed while the save ran.
- _state.update { (it as? WorkoutState.Recording)?.copy(workout = w, saveFailed = failed) ?: it }
+ _state.update { (it as? WorkoutState.Recording)?.copy(workout = w)?.withSave(SavePart.Workout, failed) ?: it }
}
}
}
@@ -884,7 +1031,10 @@ class WorkoutSession(
private val allReadings = mutableListOf>()
private val location = WorkoutLocation(context) { p ->
val r = _state.value as? WorkoutState.Recording ?: return@WorkoutLocation
- if (!r.paused) _route.value = _route.value + p
+ // Nothing after End began: the route is read for the stored workout.
+ if (ending) return@WorkoutLocation
+ _gps.value = GpsState.Fixed
+ if (!r.paused) _route.update { it + p }
}
private var heightCm: Int? = null
@@ -934,21 +1084,42 @@ class WorkoutSession(
* before the live readings start, so [record] only ever runs on one coroutine at a time.
*/
private suspend fun begin(
- w: AppWorkout, maxHr: Int, seed: List> = emptyList(),
+ w0: AppWorkout, maxHr: Int, seed: List> = emptyList(),
setup: (WorkoutState.Recording) -> WorkoutState.Recording = { it },
) {
// Waited for, so the calm down's own switch-off can't land after this workout turns the stream on.
calmJob?.cancelAndJoin()
calmJob = null
- coach = org.openstrap.app.data.Coach(org.openstrap.app.data.WorkoutTarget.parse(w.target), w.targetReachedAt)
+ coach = org.openstrap.app.data.Coach(org.openstrap.app.data.WorkoutTarget.parse(w0.target), w0.targetReachedAt)
strapSessions = catching { settings.strapSessions.first() }
.onFailure { log("workout: strap sessions setting not read: $it") }.getOrDefault(true)
heightCm = catching { settings.profile.first().heightCm }.onFailure { log("workout: height not read: $it") }.getOrNull()
- if (w.useGps) location.start()
+ // No permission or no GPS provider: the workout says it doesn't use GPS, and measures from the strap's steps.
+ _gps.value = GpsState.Off
+ val w = if (w0.useGps && !location.start()) {
+ log("workout: GPS not available, distance from the strap's steps")
+ _gps.value = GpsState.Unavailable
+ w0.copy(useGps = false).also { catching { dao.upsertAppWorkout(it) }.onFailure { e -> log("workout not saved: ${e.message}") } }
+ } else {
+ if (w0.useGps) _gps.value = GpsState.Searching
+ w0
+ }
+ ending = false
_state.update { setup(WorkoutState.Recording(w, maxHr)) }
+ // Anything that fails from here on undoes the start, so a workout is never left Recording with nothing behind it.
+ catching { startRecording(w, maxHr, seed) }.onFailure {
+ _state.update { WorkoutState.Idle }
+ stop()
+ throw it
+ }
+ }
+
+ /** What recording [w] needs, after its state is set: the strap, the service, the wake lock and the readings. */
+ private suspend fun startRecording(w: AppWorkout, maxHr: Int, seed: List>) {
strap.setWorkoutActive(true)
startService(w.sportType)
- strap.autoConnect()
+ // Not autoConnect: a Disconnect the user chose holds, and the Ready screen offers Connect.
+ strap.backgroundConnect()
// The CPU must keep up with the strap's readings and the flushes while the screen is off.
wake = context.getSystemService(PowerManager::class.java)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "unstrap:workout").apply { acquire(MAX_WAKE_MS) }
@@ -961,10 +1132,12 @@ class WorkoutSession(
launch { strap.heartRateReadings.collect(::onReading) }
if (strapSessions) {
launch { strap.sportSessionPushes.collect(::onStrapPush) }
- // On every connect, the workout again as Zepp's `bo60.j(2)`: the config, then one state.
+ // Connected now, and on each new login, the workout again as Zepp's `bo60.j(2)`: the config, then one
+ // state. Zepp calls it at the start and on each AUTH_SUCCESS only (`xbc.k`, `rbc`, `yfk`), never on a
+ // battery change, which here is a new Connected value. Every login passes Connecting first.
launch {
- strap.connection.collect { c ->
- if (c !is ConnectionState.Connected) return@collect
+ strap.connection.map { it is ConnectionState.Connected }.distinctUntilChanged().collect { connected ->
+ if (!connected) return@collect
val now = (_state.value as? WorkoutState.Recording)?.workout ?: return@collect
strapState(reconnectState(now), now, reconnect = true)
}
@@ -997,8 +1170,11 @@ class WorkoutSession(
var tick = 0
while (isActive) {
delay(FLUSH_MS)
- flush()
- saveDistance()
+ // Under the lock finish takes, so a flush here can't run alongside the one that ends the workout.
+ lock.withLock {
+ flush()
+ saveDistance()
+ }
_history.value = synchronized(allReadings) { allReadings.toList() }
if (++tick % STOP_CHECK_TICKS == 0) checkStopped()
}
@@ -1044,6 +1220,7 @@ class WorkoutSession(
cue(c)
update { it.copy(targetReachedAt = t) }
}
+ if (tick % KCAL_READ_TICKS == 1) lock.withLock { keepLive() }
delay(KCAL_TICK_MS)
}
}
@@ -1131,10 +1308,12 @@ class WorkoutSession(
KeepRecordingNotice.clear(context)
_lastCue.value = null
location.stop()
+ _gps.value = GpsState.Off
if (carRegistered) runCatching { context.unregisterReceiver(carReceiver) }
carRegistered = false
recordJob?.cancel()
recordJob = null
+ synchronized(buffer) { buffer.clear() }
if (!keepLive) strap.setWorkoutActive(false)
wake?.takeIf { it.isHeld }?.release()
wake = null
@@ -1149,7 +1328,7 @@ class WorkoutSession(
val r = _state.value as? WorkoutState.Recording ?: return
if (r.paused || !WorkoutRecorder.isValid(bpm)) return
synchronized(buffer) {
- if (t == lastSecond) return
+ if (ending || t == lastSecond) return
lastSecond = t
buffer += AppWorkoutHeartRate(r.workout.start, t, bpm)
}
@@ -1180,6 +1359,7 @@ class WorkoutSession(
.onSuccess {
if (flushFailing) log("heart rate saved again")
flushFailing = false
+ setSaved(SavePart.HeartRate, failed = false)
}
.onFailure { e ->
// Kept for the next flush rather than lost, but only the newest [MAX_UNSAVED]: a database that keeps
@@ -1193,6 +1373,7 @@ class WorkoutSession(
if (dropped > 0 && !flushDropping) log("heart rate unsaved for too long, the oldest readings are dropped")
flushFailing = true
flushDropping = dropped > 0
+ setSaved(SavePart.HeartRate, failed = true)
}
}
@@ -1200,6 +1381,11 @@ class WorkoutSession(
private var flushFailing = false
private var flushDropping = false
+ /** Records that [part]'s last save [failed] or worked, on the state as it is now. */
+ private fun setSaved(part: SavePart, failed: Boolean) {
+ _state.update { s -> (s as? WorkoutState.Recording)?.withSave(part, failed) ?: s }
+ }
+
private fun now() = clock()
/** To the strap's log, which the Device screen shows. */
@@ -1218,6 +1404,9 @@ class WorkoutSession(
)
const val FLUSH_MS = 10_000L
+ /** A failed [restore] is tried again this many times, this far apart. */
+ const val RESTORE_TRIES = 3
+ const val RESTORE_RETRY_MS = 30_000L
/** Live readings held while the database refuses them: two hours, one a second. */
const val MAX_UNSAVED = 7_200
/** The live kcal is worked out again this often. */
diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt
index 971b442b..d27d55a2 100644
--- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt
+++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt
@@ -23,6 +23,9 @@ import org.openstrap.app.data.Workouts
class WorkoutTileService : TileService() {
private var watching: Job? = null
+ /** The sport Ready opens on when tapped idle: the last one done, as an id, never read back from the subtitle. */
+ @Volatile private var readySport: Int = Workouts.DEFAULT_SPORTS.first()
+
override fun onStartListening() {
super.onStartListening()
val container = (application as OpenStrapApp).container
@@ -31,12 +34,13 @@ class WorkoutTileService : TileService() {
.collect { (state, last) ->
val tile = qsTile ?: return@collect
val r = state as? WorkoutState.Recording
- tile.state = if (r != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
+ readySport = last?.sportType ?: Workouts.DEFAULT_SPORTS.first()
+ tile.state = if (state.inProgress) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
tile.label = if (r != null) Workouts.sportName(r.workout.sportType) else getString(R.string.tile_workout)
tile.subtitle = when {
r?.paused == true -> getString(R.string.system_tile_paused)
r != null -> getString(R.string.system_tile_recording)
- else -> Workouts.sportName(last?.sportType ?: Workouts.DEFAULT_SPORTS.first())
+ else -> Workouts.sportName(readySport)
}
tile.updateTile()
}
@@ -52,14 +56,11 @@ class WorkoutTileService : TileService() {
override fun onClick() {
super.onClick()
val container = (application as OpenStrapApp).container
- val recording = container.workout.state.value is WorkoutState.Recording
+ val inProgress = container.workout.inProgress
val intent = Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
- if (recording) {
- intent.putExtra(MainActivity.EXTRA_SHOW_WORKOUT, true)
- } else {
- val last = (qsTile?.subtitle?.toString())?.let { name -> Workouts.sports.firstOrNull { it.second == name }?.first }
- intent.putExtra(MainActivity.EXTRA_READY_SPORT, last ?: Workouts.DEFAULT_SPORTS.first())
- }
+ // Recording or showing its summary: the live screen or the summary, never Ready behind it.
+ if (inProgress) intent.putExtra(MainActivity.EXTRA_SHOW_WORKOUT, true)
+ else intent.putExtra(MainActivity.EXTRA_READY_SPORT, readySport)
val pending = PendingIntent.getActivity(this, REQUEST_TILE, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= 34) startActivityAndCollapse(pending)
else @Suppress("DEPRECATION") startActivityAndCollapse(intent)
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/export/AutoBackup.kt b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt
index 85f0ee4d..584b2d7e 100644
--- a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt
+++ b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt
@@ -19,8 +19,6 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.sync.Mutex
-import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.openstrap.app.OpenStrapApp
@@ -59,11 +57,11 @@ class AutoBackup(
data class Failed(val failure: BackupFailure) : Outcome
}
- suspend fun run(): Outcome = lock.withLock {
- val folder = settings.backup.first().folder ?: return@withLock Outcome.Off
+ suspend fun run(): Outcome = DataJobs.exclusive {
+ val folder = settings.backup.first().folder ?: return@exclusive Outcome.Off
// Until the session has looked for a workout left recording, Idle doesn't mean none.
withTimeoutOrNull(10_000) { restored.first { it } }
- if (workout.value is WorkoutState.Recording) return@withLock Outcome.Recording
+ if (workout.value is WorkoutState.Recording) return@exclusive Outcome.Recording
val now = System.currentTimeMillis() / 1000
catching {
val name = withContext(Dispatchers.IO) { write(Uri.parse(folder)) }
@@ -161,9 +159,6 @@ class AutoBackup(
}
companion object {
- /** One backup at a time, the daily one and Back up now alike. */
- private val lock = Mutex()
-
private const val DAILY = "auto-backup"
private const val AFTER_WORKOUT = "auto-backup-retry"
private const val TEMP_MIME = "application/octet-stream"
diff --git a/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt b/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt
index 85d3f2e1..329fc82d 100644
--- a/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt
+++ b/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt
@@ -4,14 +4,40 @@ import android.content.Context
import android.database.sqlite.SQLiteDatabase
import androidx.room.Room
import org.openstrap.app.data.db.OpenStrapDatabase
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
import java.io.Closeable
import java.io.File
+import java.util.UUID
+import kotlin.coroutines.AbstractCoroutineContextElement
+import kotlin.coroutines.CoroutineContext
+import kotlin.coroutines.coroutineContext
+
+/**
+ * The one lock for jobs that read or replace the whole database: the automatic backup, Save a copy and restore. Two of
+ * them at once would copy a half restored database or restore over a running backup. A job that already holds the lock
+ * and calls another (the automatic backup calling the zip writer) goes straight through instead of waiting on itself.
+ */
+object DataJobs {
+ private val mutex = Mutex()
+
+ /** Marks a coroutine that holds [mutex], and passes on to everything it starts in its context. */
+ private object Holding : AbstractCoroutineContextElement(Key) {
+ object Key : CoroutineContext.Key
+ }
+
+ /** Runs [block] when no other data job is running; a block already inside one runs at once. */
+ suspend fun exclusive(block: suspend () -> T): T =
+ if (coroutineContext[Holding.Key] != null) block() else mutex.withLock { withContext(Holding) { block() } }
+}
/**
* A copy of the database as it was at one moment, for a backup to read (data integrity item 23): a sync that writes
* while the zip is being written can't leave one table in it from before and another from after. `VACUUM INTO` makes
* the copy from committed data only, and holds the database only while it copies (a second or two for a year of
- * minutes), not while the zip is written, so a sync waits that long at most. [close] deletes the copy.
+ * minutes), not while the zip is written, so a sync waits that long at most. Each copy has its own file, so two never
+ * share one. [close] deletes the copy.
*/
class BackupSnapshot private constructor(private val file: File, val database: OpenStrapDatabase) : Closeable {
override fun close() {
@@ -20,17 +46,23 @@ class BackupSnapshot private constructor(private val file: File, val database: O
}
companion object {
- /** The copy's file in the app's cache, made again for every backup. */
- private const val FILE = "backup-snapshot.db"
+ /** The start of a copy's file name in the app's cache; every copy adds its own id, so no two share a file. */
+ private const val PREFIX = "backup-snapshot-"
/** Copies [source] into the cache and opens the copy. Blocking: call it off the main thread. */
+ @Suppress("TooGenericExceptionCaught")
fun take(context: Context, source: OpenStrapDatabase): BackupSnapshot {
- val file = File(context.cacheDir, FILE)
- SQLiteDatabase.deleteDatabase(file)
- // VACUUM takes no bind arguments, so the path, which is the app's own, goes in quoted.
- source.openHelper.writableDatabase.execSQL("VACUUM INTO '${file.path.replace("'", "''")}'")
- val copy = Room.databaseBuilder(context, OpenStrapDatabase::class.java, file.path).build()
- return BackupSnapshot(file, copy)
+ val file = File(context.cacheDir, "$PREFIX${UUID.randomUUID()}.db")
+ try {
+ // VACUUM takes no bind arguments, so the path, which is the app's own, goes in quoted.
+ source.openHelper.writableDatabase.execSQL("VACUUM INTO '${file.path.replace("'", "''")}'")
+ val copy = Room.databaseBuilder(context, OpenStrapDatabase::class.java, file.path).build()
+ return BackupSnapshot(file, copy)
+ } catch (e: Throwable) {
+ // A copy that never opened is not left behind, whatever went wrong. Rethrown as it was.
+ SQLiteDatabase.deleteDatabase(file)
+ throw e
+ }
}
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt b/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt
index 34e36e16..0b01f1ca 100644
--- a/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt
+++ b/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt
@@ -39,16 +39,17 @@ class CsvBackups(
*/
override suspend fun writeZip(out: OutputStream) {
val json = SettingsBackup.toJson(settings.backupValues(SettingsBackup::carries))
- withContext(io) {
+ // The same lock as the automatic backup and restore (the automatic one calls this while holding it).
+ DataJobs.exclusive { withContext(io) {
val snapshot = catching { BackupSnapshot.take(context, database) }
.onFailure { warn("backup: no copy of the database to read, reading it as it goes: $it") }
.getOrNull()
snapshot.use { (it?.let { s -> CsvExporter(s.database.healthDao()) } ?: csv).exportZip(out, settings = json) }
- }
+ } }
}
override suspend fun importCsv(from: Uri): BackupResult = catching {
- val result = withContext(io) { input(from).use { CsvImporter(database).importZip(it) } }
+ val result = DataJobs.exclusive { withContext(io) { input(from).use { CsvImporter(database).importZip(it) } } }
// A damaged settings file costs the settings only, not the records already restored.
val restored = result.settings?.let { json ->
catching { settings.restoreValues(SettingsBackup.fromJson(json), SettingsBackup::missing) }
diff --git a/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt b/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt
index c0a34fd4..12d6432c 100644
--- a/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt
+++ b/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt
@@ -141,11 +141,15 @@ class HealthConnectAutoSync(
}
}
- /** The user turned auto sync on, with the permissions granted: on, and the last 30 days written at once. Returns the records written. */
+ /**
+ * The user turned auto sync on, with the permissions granted: the last 30 days are written at once, and only when
+ * that works is it turned on. A failed first write throws and leaves it off, for the caller to show. Returns the
+ * records written.
+ */
suspend fun turnOn(): Int {
- settings.setHealthConnectAuto(true)
val now = System.currentTimeMillis() / 1000
val n = exporter.export(now - AutoHealthConnect.MAX_S, now)
+ settings.setHealthConnectAuto(true)
settings.setHealthConnectSynced(now)
return n
}
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 d0cade4d..f8c05881 100644
--- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt
+++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt
@@ -1,5 +1,7 @@
package org.openstrap.app.health
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import android.content.Context
import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.HealthConnectFeatures
@@ -25,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
@@ -62,6 +66,13 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
override suspend fun deleteRange(type: KClass, range: TimeRangeFilter) = client.deleteRecords(type, range)
}
+ /**
+ * Every write to Health Connect (the worker, turning auto sync on, a saved workout, an edited sleep, the manual
+ * copy) goes through this one lock. A write reads its own records, inserts, then deletes the stale ones, so two
+ * side by side could delete what the other had just inserted.
+ */
+ private val writeLock = Mutex()
+
/** Every record of [type] in [range] that OpenStrap wrote, a page at a time. */
private suspend fun readAll(type: KClass, range: TimeRangeFilter): List {
val out = mutableListOf()
@@ -87,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. */
- 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
@@ -122,9 +135,9 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
suspend fun hasPermissions(): Boolean =
client.permissionController.getGrantedPermissions().containsAll(permissions)
- /** Every permission a write asks for, the optional calorie ones too: when not, the write asks again first. */
- suspend fun hasRequestedPermissions(): Boolean =
- client.permissionController.getGrantedPermissions().containsAll(requestedPermissions)
+ /** 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 =
@@ -164,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)) {
@@ -190,8 +207,10 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
val resting = restingHr(from, to, ZoneId.systemDefault())
records += resting
- store.write(records, kcalRanges + (SleepSessionRecord::class to sleepRange(from, to)))
- store.dropMovedRestingHr(resting)
+ store.writeSerially(writeLock, records, kcalRanges + replaced + (SleepSessionRecord::class to sleepRange(from, to))) {
+ dropMovedRestingHr(resting)
+ dropStaleStrapWorkouts(from, to, strapSessions)
+ }
return records.size
}
@@ -216,7 +235,7 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt
*/
suspend fun exportSleep(from: Long, to: Long, now: Long = System.currentTimeMillis() / 1000): Int {
val records = sleep(from, to, now)
- store.write(records, listOf(SleepSessionRecord::class to sleepRange(from, to)))
+ store.writeSerially(writeLock, records, listOf(SleepSessionRecord::class to sleepRange(from, to)))
return records.size
}
@@ -280,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.write(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
}
@@ -355,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()
@@ -523,6 +609,20 @@ internal suspend fun RecordStore.write(records: List, replaced: List,
+ replaced: List, TimeRangeFilter>>,
+ after: suspend RecordStore.() -> Unit = {},
+) = lock.withLock {
+ write(records, replaced)
+ after()
+}
+
/** The most records one Health Connect call takes. */
internal const val HC_BATCH = 500
@@ -548,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/alarms/AlarmsScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt
index d2e9a950..f6a0375f 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt
@@ -17,6 +17,10 @@ import androidx.compose.material3.TimePickerDefaults
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.SideEffect
+import androidx.compose.runtime.key
+import androidx.compose.runtime.rememberCoroutineScope
+import kotlinx.coroutines.launch
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -141,13 +145,32 @@ fun AlarmsScreen(
onDismiss = { confirmDeleteAll = false },
)
}
+ // A refresh can change the alarm under an open sheet (a one-time alarm switching itself off, say). Saving the old copy
+ // would undo that, so the sheet moves to the refreshed alarm and starts from its values; if the alarm is gone, or the
+ // free slot of a new one was taken, there is nothing left to edit and the sheet closes.
+ SideEffect {
+ val open = editing ?: return@SideEffect
+ if (state.read !is AlarmsRead.Loaded) return@SideEffect
+ val (alarm, isNew) = open
+ val now = state.alarms.firstOrNull { it.index == alarm.index }
+ editing = when {
+ isNew -> if (now == null) open else null
+ now == null -> null
+ now != alarm -> now to false
+ else -> open
+ }
+ }
+ val scope = rememberCoroutineScope()
editing?.let { (alarm, isNew) ->
- AlarmSheet(
- alarm, isNew,
- onSave = { vm.save(it, isNew); editing = null },
- onDelete = { vm.delete(alarm); editing = null },
- onDismiss = { editing = null },
- )
+ // The sheet closes only when the strap took the change; a failure or a busy strap leaves it open for another try.
+ key(alarm, isNew) {
+ AlarmSheet(
+ alarm, isNew, busy = state.busy,
+ onSave = { edited -> scope.launch { if (vm.save(edited, isNew).await()) editing = null } },
+ onDelete = { scope.launch { if (vm.delete(alarm).await()) editing = null } },
+ onDismiss = { editing = null },
+ )
+ }
}
ScreenList(contentPadding, gutter = GlowLayout.Gutter) {
item { PageHeader(stringResource(R.string.you_alarms_title), onBack) }
@@ -156,6 +179,8 @@ fun AlarmsScreen(
item { PagePanel { PageNote(stringResource(R.string.you_alarms_reading)) } }
return@ScreenList
}
+ // Never read: the alarms are unknown, not empty, so the error above is all there is to show.
+ if (state.read is AlarmsRead.Failed) return@ScreenList
item {
AlarmsPanel(state, onToggle = vm::setEnabled, onEdit = { editing = it to false }, onAdd = {
vm.freeIndex()?.let { editing = Alarm(it, 7, 0, Alarm.WEEKDAYS, enabled = true) to true }
@@ -287,7 +312,7 @@ private fun HeartAlertsPanel(state: AlarmsUiState, vm: AlarmsViewModel) {
*/
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
-private fun AlarmSheet(alarm: Alarm, isNew: Boolean, onSave: (Alarm) -> Unit, onDelete: () -> Unit, onDismiss: () -> Unit) {
+private fun AlarmSheet(alarm: Alarm, isNew: Boolean, busy: Boolean, onSave: (Alarm) -> Unit, onDelete: () -> Unit, onDismiss: () -> Unit) {
val time = rememberTimePickerState(alarm.hour, alarm.minute, is24Hour = ClockSetting.use24Hour)
var days by remember { mutableIntStateOf(alarm.days) }
PageSheet(onDismiss, stringResource(if (isNew) R.string.you_alarms_new else R.string.you_alarms_edit), note = daysLabel(days)) {
@@ -306,12 +331,13 @@ private fun AlarmSheet(alarm: Alarm, isNew: Boolean, onSave: (Alarm) -> Unit, on
PageButton(
stringResource(R.string.you_action_save),
{ onSave(alarm.copy(hour = time.hour, minute = time.minute, days = days, enabled = true)) }, Modifier.weight(1f),
- primary = true,
+ enabled = !busy, primary = true,
)
}
if (!isNew) {
PageTextButton(
- stringResource(R.string.you_alarms_delete), onDelete, Modifier.align(Alignment.CenterHorizontally), color = DestructiveInk,
+ stringResource(R.string.you_alarms_delete), onDelete, Modifier.align(Alignment.CenterHorizontally),
+ enabled = !busy, color = DestructiveInk,
)
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt
index 6c43bd76..aab7ec08 100644
--- a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt
+++ b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt
@@ -4,6 +4,9 @@ import org.openstrap.app.R
import org.openstrap.app.i18n.Strings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
@@ -19,8 +22,19 @@ import org.openstrap.protocol.services.Setting
import org.openstrap.protocol.services.SettingsCodec
import org.openstrap.protocol.services.SettingsGroup
+/** What the screen knows about the strap's alarms: not yet read, never read (the first read failed), or read. */
+sealed interface AlarmsRead {
+ data object Loading : AlarmsRead
+ data class Failed(val message: String) : AlarmsRead
+ data object Loaded : AlarmsRead
+}
+
data class AlarmsUiState(
- val loading: Boolean = true,
+ /**
+ * Loading until the first read ends. Failed means no read has ever worked, so [caps] and [alarms] are unknown and the
+ * screen must not show them as "no alarms". Once Loaded it stays Loaded: a later failed read only sets [error].
+ */
+ val read: AlarmsRead = AlarmsRead.Loading,
/** A write is in flight; controls are disabled meanwhile. */
val busy: Boolean = false,
val error: String? = null,
@@ -28,6 +42,8 @@ data class AlarmsUiState(
val alarms: List = emptyList(),
val health: SettingsGroup? = null,
) {
+ val loading: Boolean get() = read is AlarmsRead.Loading
+
val canAdd: Boolean get() = caps != null && alarms.size < caps.maxCount
/** The strap only raises HR alerts while it measures often enough; Zepp allows continuous or every minute. */
@@ -41,6 +57,8 @@ data class AlarmsUiState(
}
/** Reads alarms and health settings from the strap and writes changes back, re-reading after each write. */
+// One function per strap setting the page changes, plus the read and the write queue.
+@Suppress("TooManyFunctions")
class AlarmsViewModel(private val strap: StrapController) : ViewModel() {
private val _state = MutableStateFlow(AlarmsUiState())
val state = _state.asStateFlow()
@@ -57,13 +75,21 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() {
}
}
- fun refresh() = run(loading = true) { }
+ /** A refresh asked for while a write or read was running; it runs when that one ends, so it isn't lost. */
+ private var refreshPending = false
+
+ fun refresh() {
+ // A retry after a failed first read goes back to "reading"; a refresh of a shown list keeps showing it.
+ _state.update { if (it.read is AlarmsRead.Failed) it.copy(read = AlarmsRead.Loading) else it }
+ run { }
+ }
fun setEnabled(alarm: Alarm, enabled: Boolean) = run { strap.saveAlarm(alarm.copy(enabled = enabled), isNew = false) }
- fun save(alarm: Alarm, isNew: Boolean) = run { strap.saveAlarm(alarm, isNew) }
+ /** Completes with true when the strap took the change, false when it failed or was busy (the screen keeps the sheet then). */
+ fun save(alarm: Alarm, isNew: Boolean): Deferred = run { strap.saveAlarm(alarm, isNew) }
- fun delete(alarm: Alarm) = run { strap.deleteAlarm(alarm.index) }
+ fun delete(alarm: Alarm): Deferred = run { strap.deleteAlarm(alarm.index) }
fun deleteAll() = run { strap.clearAlarms() }
@@ -99,31 +125,55 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() {
strap.writeHealthSettings(g.version, build(g))
}
- /** Runs [action] against the strap, then re-reads everything so the screen shows what the strap holds. */
- private fun run(loading: Boolean = false, action: suspend () -> Unit) {
- if (_state.value.busy) return
- _state.update { it.copy(busy = true, loading = loading || it.loading, error = null) }
- viewModelScope.launch {
+ /**
+ * Runs [action] against the strap, then re-reads everything so the screen shows what the strap holds. Completes with
+ * whether [action] worked. While another run is going, a refresh (an [action] that does nothing) is queued to run
+ * after it, and a write is refused (false) so the caller doesn't close its sheet as if it had been saved.
+ */
+ private fun run(action: suspend () -> Unit): Deferred {
+ if (_state.value.busy) {
+ // Only a plain refresh can wait: a write the user asked for is shown as not done, and the controls are disabled anyway.
+ refreshPending = true
+ return CompletableDeferred(false)
+ }
+ _state.update { it.copy(busy = true, error = null) }
+ return viewModelScope.async {
val error = try {
action()
null
} catch (e: StrapCommandException) {
e.message
}
- // The raw failure goes to Diagnostics, and the screen says it in plain words ([ErrorCopy.strap]).
- val read = catching {
- val (caps, alarms) = strap.readAlarms()
- Triple(caps, alarms.sortedWith(compareBy({ it.hour }, { it.minute })), strap.readHealthSettings())
- }.onFailure { (strap as? StrapManager)?.log("alarms: read from the strap failed: $it") }
- _state.update { s ->
- read.fold(
- { (caps, alarms, health) -> s.copy(loading = false, busy = false, error = error, caps = caps, alarms = alarms, health = health) },
- { e ->
- val failed = error ?: ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed))
- s.copy(loading = false, busy = false, error = failed)
- },
- )
+ readAll(error)
+ val again = refreshPending
+ refreshPending = false
+ if (again) {
+ _state.update { it.copy(busy = true) }
+ readAll(null)
}
+ error == null
+ }
+ }
+
+ /** Re-reads alarms and health from the strap. [error] is the failed write's reason, if any, and wins over a read failure's. */
+ private suspend fun readAll(error: String?) {
+ // The raw failure goes to Diagnostics, and the screen says it in plain words ([ErrorCopy.strap]).
+ val read = catching {
+ val (caps, alarms) = strap.readAlarms()
+ Triple(caps, alarms.sortedWith(compareBy({ it.hour }, { it.minute })), strap.readHealthSettings())
+ }.onFailure { (strap as? StrapManager)?.log("alarms: read from the strap failed: $it") }
+ _state.update { s ->
+ read.fold(
+ { (caps, alarms, health) ->
+ s.copy(read = AlarmsRead.Loaded, busy = false, error = error, caps = caps, alarms = alarms, health = health)
+ },
+ { e ->
+ val failed = error ?: ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed))
+ // Without an earlier good read there is nothing to show; with one, keep showing it beside the error.
+ val next = if (s.read is AlarmsRead.Loaded) s.read else AlarmsRead.Failed(failed)
+ s.copy(read = next, busy = false, error = failed)
+ },
+ )
}
}
}
diff --git a/app/src/main/kotlin/org/openstrap/app/ui/components/DayHold.kt b/app/src/main/kotlin/org/openstrap/app/ui/components/DayHold.kt
new file mode 100644
index 00000000..e1f7ebc1
--- /dev/null
+++ b/app/src/main/kotlin/org/openstrap/app/ui/components/DayHold.kt
@@ -0,0 +1,68 @@
+package org.openstrap.app.ui.components
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.SideEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import kotlinx.coroutines.delay
+import java.time.LocalDate
+
+/**
+ * How long a switch to another day keeps the last day up, dimmed, before the new day's placeholder shows. Long enough
+ * that a day read from the phone's own database lands without a flash, short enough that another day's numbers never
+ * stand for the new one.
+ */
+const val DAY_HOLD_MS = 300L
+
+/** How faint a held day is drawn, so it reads as on its way out. */
+const val DAY_HELD_ALPHA = 0.5f
+
+/** What a day's screen shows: [value], and whether it is another day's, kept for a moment ([rememberDayHold]). */
+class DayHold(val value: T?, val pending: Boolean)
+
+/**
+ * [value] of [day] once there is one. While there isn't:
+ * - the same day keeps the value it last had, as a refresh of the day shown;
+ * - another day keeps the last day's for at most [DAY_HOLD_MS], marked [DayHold.pending] so it is drawn dimmed, then
+ * none, so the screens show their placeholders;
+ * - a day that [failed] keeps nothing: its value is never coming.
+ */
+@Composable
+fun rememberDayHold(value: T?, day: LocalDate, failed: Boolean = false): DayHold {
+ val last = remember { LastOfDay() }
+ var gaveUp by remember(day) { mutableStateOf(false) }
+ LaunchedEffect(day, value == null) {
+ gaveUp = false
+ if (value == null) {
+ delay(DAY_HOLD_MS)
+ gaveUp = true
+ }
+ }
+ SideEffect {
+ if (value != null) {
+ last.day = day
+ last.value = value
+ }
+ }
+ val kept = last.value
+ return when {
+ value != null -> DayHold(value, pending = false)
+ failed || kept == null -> DayHold(null, pending = false)
+ last.day == day -> DayHold(kept, pending = false)
+ gaveUp -> DayHold(null, pending = false)
+ else -> DayHold(kept, pending = true)
+ }
+}
+
+/** Draws a held day ([DayHold.pending]) dimmed. */
+fun Modifier.dayHeld(pending: Boolean): Modifier = if (pending) alpha(DAY_HELD_ALPHA) else this
+
+private class LastOfDay {
+ var day: LocalDate? = null
+ var value: T? = null
+}
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 17775d68..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
@@ -1,6 +1,7 @@
package org.openstrap.app.ui.dashboard
import android.util.Log
+import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineDispatcher
@@ -16,10 +17,12 @@ import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
+import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -29,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
@@ -66,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. */
@@ -120,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(),
@@ -136,15 +147,61 @@ 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. */
data class RecoveryFailure(val date: LocalDate, val yesterday: Int?)
-/** Recovery worked out, or why not. */
-private sealed interface RecoveryOutcome {
- data class Ready(val result: RecoveryResult) : RecoveryOutcome
- data class Failed(val failure: RecoveryFailure) : RecoveryOutcome
+/** The day's Recovery: being worked out, worked out, or why not. */
+sealed interface RecoveryState {
+ /** The first read for the day, or a retry after a failure. */
+ data object Loading : RecoveryState
+ data class Ready(val result: RecoveryResult) : RecoveryState
+ data class Failed(val failure: RecoveryFailure) : RecoveryState
+}
+
+/**
+ * Everything the screens show of one [date], emitted together so a number never sits under another day's date (audit
+ * S7). On a day switch it starts as [loading] for the new date: the day's rows, Recovery, Healthspan, usual steps and
+ * activity are all empty or loading until they arrive, and never the old day's.
+ */
+data class DayScreenState(
+ val date: LocalDate,
+ val day: DayUiState = DayUiState(date = date),
+ val recoveryState: RecoveryState = RecoveryState.Loading,
+ /** The weekly Healthspan estimate for [date], or why it's withheld; null while loading or on failure. */
+ val healthspan: org.openstrap.app.data.Healthspan.Outcome? = null,
+ /** Your usual steps by the end of each hour, null until there are enough worn days. */
+ val usualSteps: List? = null,
+ val activity: ActivityHistory = ActivityHistory(),
+) {
+ /** The day's rows have arrived. */
+ val loaded: Boolean get() = day.loaded
+
+ /** Readiness and charge for [date]; null while loading or when it failed. */
+ val recovery: RecoveryResult? get() = (recoveryState as? RecoveryState.Ready)?.result
+
+ /** The day's Recovery failed to work out (spec 4.3), so the cards can say so instead of waiting forever. */
+ val recoveryFailure: RecoveryFailure? get() = (recoveryState as? RecoveryState.Failed)?.failure
+
+ companion object {
+ /** [date] before anything of it has arrived. */
+ fun loading(date: LocalDate) = DayScreenState(date)
+ }
}
/** One day's Heart points: those earned that day and the 7-day total. */
@@ -211,10 +268,15 @@ data class ActivityHistory(
}
}
+/** How long synced data must settle before the day's scores are worked out again. */
+private const val CHANGES_SETTLE_MS = 800L
+
@OptIn(ExperimentalCoroutinesApi::class)
+// One flow per part of the day's screen state, plus the day picking.
+@Suppress("TooManyFunctions")
class DayViewModel(
private val repo: DayRepository,
- profile: Flow = flowOf(UserProfile()),
+ private val profile: Flow = flowOf(UserProfile()),
/** A sleep or nap (by the strap's start) was moved, deleted or restored: Health Connect is written again. */
private val onSleepEdited: (Long) -> Unit = {},
/** The clock today is read from, asked afresh each time. Tests pass one they move by hand. */
@@ -223,13 +285,20 @@ class DayViewModel(
dateChanges: Flow = emptyFlow(),
/** Where the day's rows are worked into its state, off the main thread (audit C7). */
private val work: CoroutineDispatcher = Dispatchers.Default,
+ /** Keeps the day picked, so a restore reopens the same day. */
+ private val saved: SavedStateHandle = SavedStateHandle(),
) : ViewModel() {
/** Today as it moves, so a screen left open past midnight moves on to the new day (audit C10). */
private val today: StateFlow = Today.dates(clock, dateChanges)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Today.on(clock()))
/** The day picked, or null while the screen follows today. */
- private val picked = MutableStateFlow(null)
+ private val picked = MutableStateFlow(saved.get(PICKED_KEY)?.let(LocalDate::ofEpochDay))
+
+ private fun pick(date: LocalDate?) {
+ picked.value = date
+ saved[PICKED_KEY] = date?.toEpochDay()
+ }
/** The day shown: the one picked while it's before today, else today. */
private val shown: Flow = combine(picked, today) { p, t ->
@@ -237,22 +306,29 @@ class DayViewModel(
ShownDay(date, date == t)
}.distinctUntilChanged()
- private val selected: Flow = shown.map { it.date }.distinctUntilChanged()
-
private fun shownNow(): LocalDate = Today.on(clock()).let { t -> picked.value?.takeIf { it < t } ?: t }
- fun previousDay() { picked.value = shownNow().minusDays(1) }
- fun nextDay() { picked.value = shownNow().plusDays(1).takeIf { it < Today.on(clock()) } }
- fun select(date: LocalDate) { picked.value = date.takeIf { it < Today.on(clock()) } }
+ fun previousDay() { pick(shownNow().minusDays(1)) }
+ fun nextDay() { pick(shownNow().plusDays(1).takeIf { it < Today.on(clock()) }) }
+ fun select(date: LocalDate) { pick(date.takeIf { it < Today.on(clock()) }) }
/** Days the calendar lets you pick. */
val daysWithData: StateFlow> = repo.daysWithData()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())
- val state: StateFlow = shown.flatMapLatest { (date, isToday) -> repo.day(date, isToday) }
- .map(::toUiState)
+ /** The day shown with all it needs, from one flow on the day shown, so it moves to a new day in one step. */
+ val screen: StateFlow = shown.flatMapLatest { (date, isToday) ->
+ combine(
+ repo.day(date, isToday).map(::toUiState),
+ recoveryState(date),
+ healthspanOf(date),
+ usualStepsOf(date),
+ activityOf(date),
+ ) { day, recovery, healthspan, usual, activity -> DayScreenState(date, day, recovery, healthspan, usual, activity) }
+ .onStart { emit(DayScreenState.loading(date)) }
+ }
.flowOn(work)
- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DayUiState(date = Today.on(clock())))
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DayScreenState.loading(shownNow()))
/** Bumped by [retryRecovery], so the same day and data are worked out again. */
private val recoveryRetries = MutableStateFlow(0)
@@ -283,33 +359,26 @@ class DayViewModel(
@Volatile private var lastRecovery: RecoveryResult? = null
/**
- * Readiness and charge, recomputed (off the main thread) when the day, profile or synced data change: the result,
- * or why there's none. Null while the first is worked out.
+ * [date]'s Readiness and charge, recomputed (off the main thread) when the profile or synced data change: Loading
+ * first, and again on a retry, then the result or why there's none.
*/
@OptIn(FlowPreview::class)
- private val recoveryOutcome: StateFlow =
- combine(selected, profile, repo.changes().debounce(800), recoveryRetries) { d, p, _, _ -> d to p }
- .mapLatest { (d, p) ->
+ private fun recoveryState(date: LocalDate): Flow = recoveryRetries.flatMapLatest {
+ combine(profile, repo.changes().debounce(CHANGES_SETTLE_MS)) { p, _ -> p }
+ .mapLatest { p ->
withContext(work) {
// mapLatest cancels this when newer data arrives. That's not a failure, and catching lets it through.
- catching { repo.recovery(d, p) }.fold(
- onSuccess = { RecoveryOutcome.Ready(it.also { r -> lastRecovery = r }) },
+ catching { repo.recovery(date, p) }.fold(
+ onSuccess = { RecoveryState.Ready(it.also { r -> lastRecovery = r }) },
onFailure = { e ->
Log.w("unstrap", "recovery failed", e)
- RecoveryOutcome.Failed(RecoveryFailure(d, yesterdayScore(d, p)))
+ RecoveryState.Failed(RecoveryFailure(date, yesterdayScore(date, p)))
},
)
}
}
- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
-
- /** Readiness and charge for the day shown; null while loading or when it failed ([recoveryFailure] tells which). */
- val recovery: StateFlow = recoveryOutcome.map { (it as? RecoveryOutcome.Ready)?.result }
- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
-
- /** The day's Recovery failed to work out (spec 4.3), so the cards can say so instead of waiting forever. */
- val recoveryFailure: StateFlow = recoveryOutcome.map { (it as? RecoveryOutcome.Failed)?.failure }
- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
+ .onStart { emit(RecoveryState.Loading) }
+ }
/**
* Yesterday's score for a failed [date]: from the last Recovery worked out when its week covers yesterday, else
@@ -327,54 +396,51 @@ class DayViewModel(
}
/**
- * Your usual steps by the end of each hour ([org.openstrap.app.data.UsualSteps]), from the 28 days before the day
- * shown; null until there are enough worn days. Past days don't change through the day, so it's read once per day
- * shown, off the main thread, not on every sync.
+ * Your usual steps by the end of each hour ([org.openstrap.app.data.UsualSteps]), from the 28 days before [d]; null
+ * until there are enough worn days. Past days don't change through the day, so it's read once, off the main thread,
+ * not on every sync.
*/
- val usualSteps: StateFlow?> = selected
- .mapLatest { d ->
+ private fun usualStepsOf(d: LocalDate): Flow?> = flow {
+ emit(null)
+ emit(
withContext(work) {
catching {
val from = d.minusDays(org.openstrap.app.data.UsualSteps.DAYS.toLong())
org.openstrap.app.data.UsualSteps.byHour(repo.hourlySteps(from, d.minusDays(1)), d)
}.onFailure { Log.w("unstrap", "usual steps failed", it) }.getOrNull()
- }
- }
- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
+ },
+ )
+ }
- /** The weekly Healthspan estimate for the selected day, or why it's withheld; null while loading or on failure. */
+ /** The weekly Healthspan estimate for [d], or why it's withheld; null while loading or on failure. */
@OptIn(FlowPreview::class)
- val healthspan: StateFlow =
- combine(selected, profile, repo.changes().debounce(800)) { d, p, _ -> d to p }
- .mapLatest { (d, p) ->
+ private fun healthspanOf(d: LocalDate): Flow =
+ combine(profile, repo.changes().debounce(CHANGES_SETTLE_MS)) { p, _ -> p }
+ .mapLatest { p ->
withContext(work) {
catching { repo.healthspan(d, p) }.onFailure { Log.w("unstrap", "healthspan failed", it) }.getOrNull()
}
}
- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
-
- /** Each day's Heart points and stored calories up to the day shown, for the Activity tab and its details. */
- val activityHistory: StateFlow = selected.flatMapLatest { d ->
- combine(
- // The days after [d] up to today, for the strip's dots; nothing is read for today.
- stripLater(d),
- repo.dailyCalories(d.minusDays(ActivityHistory.CALORIES_DAYS - 1L), d),
- stepsAndBest(d),
- repo.dailyPai(d.minusDays(ActivityHistory.HEART_POINTS_DAYS - 1L), d),
- ) { later, calories, (steps, best), pai ->
- ActivityHistory(
- date = d,
- heartPoints = pai.mapValues { (_, p) -> HeartPointsDay(p.daily, p.total) },
- calories = calories.mapValues { (_, e) -> CaloriesDay(e.activeKcal, e.totalKcal, e.workoutKcal, e.partial) },
- steps = steps,
- stepsBest = best,
- heartPointsDays = (pai.filterKeys { it >= d.minusDays(ActivityHistory.STRIP_DAYS_BEFORE) } + later)
- .filterValues { it.daily > 0 }.keys,
- )
- }
- }
- .flowOn(work)
- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ActivityHistory())
+ .onStart { emit(null) }
+
+ /** Each day's Heart points and stored calories up to [d], for the Activity tab and its details. */
+ private fun activityOf(d: LocalDate): Flow = combine(
+ // The days after [d] up to today, for the strip's dots; nothing is read for today.
+ stripLater(d),
+ repo.dailyCalories(d.minusDays(ActivityHistory.CALORIES_DAYS - 1L), d),
+ stepsAndBest(d),
+ repo.dailyPai(d.minusDays(ActivityHistory.HEART_POINTS_DAYS - 1L), d),
+ ) { later, calories, (steps, best), pai ->
+ ActivityHistory(
+ date = d,
+ heartPoints = pai.mapValues { (_, p) -> HeartPointsDay(p.daily, p.total) },
+ calories = calories.mapValues { (_, e) -> CaloriesDay(e.activeKcal, e.totalKcal, e.workoutKcal, e.partial) },
+ steps = steps,
+ stepsBest = best,
+ heartPointsDays = (pai.filterKeys { it >= d.minusDays(ActivityHistory.STRIP_DAYS_BEFORE) } + later)
+ .filterValues { it.daily > 0 }.keys,
+ )
+ }.onStart { emit(ActivityHistory()) }
/** The Heart points of the days after [d] up to today, for the strip's later days; none when [d] is today. */
private fun stripLater(d: LocalDate): Flow