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> { @@ -403,6 +469,8 @@ class DayViewModel( } companion object { + private const val PICKED_KEY = "pickedDay" + /** * [data] as the screens show it: the heart rate as a chart, the steps by hour, the trends with their weekday * labels and the stages as spans. @@ -414,6 +482,7 @@ class DayViewModel( val sleep = data.sleep val series = Summaries.heartRateSeries(data.heartRate, data.minutes) val hourly = Summaries.hourlySteps(data.minutes, data.day.from) + val nightSeries = Summaries.heartRateSeries(data.nightHeartRate, emptyList()) return DayUiState( loaded = true, date = data.date, @@ -422,6 +491,7 @@ class DayViewModel( hourlySteps = hourly, activeHours = Summaries.activeHours(hourly), heartRate = Summaries.bucketAverage(series).map { ChartPoint(it.first, it.second.toFloat()) }, + heartMinutes = series, latestHeartRate = series.lastOrNull()?.second, restingHeartRate = data.restingTrend.lastOrNull()?.value?.toInt(), restingEstimated = data.restingEstimated.lastOrNull() ?: false, @@ -455,9 +525,10 @@ class DayViewModel( activeCalories = data.activeCalories, alerts = data.alerts, nights = data.nights, - sleepHeartRate = Summaries.bucketAverage(Summaries.heartRateSeries(data.nightHeartRate, emptyList())).map { + sleepHeartRate = Summaries.bucketAverage(nightSeries).map { ChartPoint(it.first, it.second.toFloat()) }, + sleepHeartMinutes = nightSeries, sleepHrv = data.sleepHrv.map { ChartPoint(it.timestamp, it.milliseconds.toFloat()) }, sleepSkinTemperature = data.sleepSkin.map { ChartPoint(it.timestamp, it.celsius) }, dayStart = data.day.from, diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt index caa3039b..0f692d7a 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/InfoCopy.kt @@ -358,7 +358,7 @@ object InfoCopy { if (strapScore != null) add(strings.format(R.string.day_info_recovery_note_strap, strapScore)) ready ?: return@buildList if (ready.capped) add(strings.get(R.string.day_info_recovery_note_capped)) - ready.fallbackHrv?.let { add(strings.format(R.string.day_info_recovery_note_hrv, it.toInt())) } + ready.fallbackHrv?.let { add(strings.format(R.string.day_info_recovery_note_hrv, Math.round(it))) } ready.fallbackRestingHr?.let { add(strings.format(R.string.day_info_recovery_note_resting_hr, it.toInt())) } if (ready.hrvWeekThin) add(strings.format(R.string.day_info_recovery_note_week_thin, ready.hrvWeekNights)) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/LatestReading.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/LatestReading.kt new file mode 100644 index 00000000..4bb40d01 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/LatestReading.kt @@ -0,0 +1,94 @@ +package org.openstrap.app.ui.dashboard + +import org.openstrap.app.R +import org.openstrap.app.i18n.Strings +import org.openstrap.app.presentation.ChartPoint +import org.openstrap.app.presentation.StressLevel + +/** + * Blood oxygen and stress on Today, All metrics, the Recovery tab and the details opened from them: the day's latest + * reading and when it was taken, as heart rate leads with its latest. The strap reads blood oxygen day and night, so a + * night's average is only on the Sleep and Recovery tabs ([SleepCopy.nightValue]). Stress is judged by the level of the + * reading shown ([StressLevel]): its line says the level, and only a High reading gets a tag and a rim ([stressTag]). + * The sentence under its chart still reads the day's average against your usual. + */ +internal object LatestReading { + /** The newest of the day's blood oxygen readings, day or night; null before the day has one. */ + fun spo2(state: DayUiState): ChartPoint? = state.spo2.maxByOrNull { it.x } + + /** The newest of the day's stress readings, those during and after a workout already left out; null before the day has one. */ + fun stress(state: DayUiState): ChartPoint? = state.stress.maxByOrNull { it.x } + + /** The metrics whose day leads with their latest reading. */ + val METRICS: Set = setOf( + org.openstrap.app.presentation.Metric.Spo2, org.openstrap.app.presentation.Metric.Stress, + ) + + /** [metric]'s latest reading of the day, null for a metric that doesn't lead with one or before it has one. */ + fun of(metric: org.openstrap.app.presentation.Metric, state: DayUiState): ChartPoint? = when (metric) { + org.openstrap.app.presentation.Metric.Spo2 -> spo2(state) + org.openstrap.app.presentation.Metric.Stress -> stress(state) + else -> null + } + + /** How old a reading may be, in seconds, before cards and rows say when it was taken. */ + const val STALE_AFTER_S = 60 * 60L + + /** Whether a reading taken at [at] is more than an hour before [now] (epoch seconds); every reading of a past day is. */ + fun isStale(at: Long, now: Long): Boolean = now - at > STALE_AFTER_S + + /** The day's sleep window, the main sleep's start to its end, null on a day without one. */ + fun sleepWindow(state: DayUiState): LongRange? = state.sleep?.let { it.start..it.end } + + /** Whether a reading at [at] falls inside the sleep [window]; without a window every reading counts as daytime. */ + fun isAsleep(at: Long, window: LongRange?): Boolean = window != null && at in window + + /** + * The indices of a chart's [count] readings, one every [slot] seconds from the start of [day], that fall inside the + * sleep [window]; null without a window, or when it doesn't touch the day. + */ + fun shadeIndices(window: LongRange?, day: LongRange, slot: Long, count: Int): IntRange? { + val touches = window != null && window.first <= day.last && window.last >= day.first + if (window == null || count < 2 || !touches) return null + val from = ((window.first - day.first).coerceAtLeast(0) / slot).toInt() + val to = ((window.last - day.first) / slot).toInt().coerceAtMost(count - 1) + return (from..to).takeIf { from < to } + } + + /** Whether the day's latest blood oxygen reading was taken inside the sleep window; false without a reading. */ + fun spo2Asleep(state: DayUiState): Boolean = spo2(state)?.let { isAsleep(it.x, sleepWindow(state)) } == true + + /** + * The line under a blood oxygen reading taken at [at]: "Daytime" or "While asleep", with the time ("Daytime, 12:50") + * once the reading is stale at [now]. [time] writes an epoch second as a clock time. + */ + fun spo2Line(at: Long, window: LongRange?, now: Long, strings: Strings = Strings.app, time: (Long) -> String): String { + val asleep = isAsleep(at, window) + return if (isStale(at, now)) { + strings.format(if (asleep) R.string.glow_today_spo2_asleep_at else R.string.glow_today_spo2_daytime_at, time(at)) + } else { + strings.get(if (asleep) R.string.glow_today_spo2_asleep else R.string.glow_today_spo2_daytime) + } + } + + /** The stress tag: "High" when the reading's [level] is High, null for the other levels, which have no tag and no rim. */ + fun stressTag(level: StressLevel, strings: Strings = Strings.app): NewsTag? = + if (level == StressLevel.High) NewsTag(level.word(strings), goal = false) else null + + /** + * The line under a stress reading of [value] taken at [at]: its level word ("Normal"), with the time ("Normal, + * 12:50") once the reading is stale at [now]. Where the High tag shows ([tagged]) the tag says the level already, so + * the line is null when fresh and "Latest at 12:50" when stale. + */ + fun stressLine( + at: Long, value: Float, now: Long, tagged: Boolean, strings: Strings = Strings.app, time: (Long) -> String, + ): String? { + val level = StressLevel.of(value) + val stale = isStale(at, now) + return when { + tagged && level == StressLevel.High -> if (stale) strings.format(R.string.glow_today_latest_at, time(at)) else null + stale -> strings.format(R.string.glow_today_stress_level_at, level.word(strings), time(at)) + else -> level.word(strings) + } + } +} diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt index 0badc45e..85dfd6fa 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/OffStatuses.kt @@ -4,7 +4,6 @@ import org.openstrap.app.data.DayStat import org.openstrap.app.data.Healthspan import org.openstrap.app.data.History import org.openstrap.app.data.RecoveryResult -import org.openstrap.app.presentation.ChartPoint import org.openstrap.app.presentation.LoadBand import org.openstrap.app.presentation.LoadBands import java.time.Instant @@ -91,9 +90,3 @@ fun habitAgeOffStatus(outcome: Healthspan.Outcome?): OffStatus { else -> OffStatus.Usual } } - -/** The day's mean stress from its [samples], null without any: the value Stress' daily history keeps. */ -fun stressMean(samples: List): Float? = samples.takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.toFloat() - -/** The day's stress ([stressMean] of [samples]) against your normal (`rememberNormal(Metric.Stress)`). */ -fun stressOffStatus(samples: List, normal: History.Normal?): OffStatus = offStatus(stressMean(samples), normal) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt index cd06d4ff..f7a09778 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepCopy.kt @@ -8,6 +8,7 @@ import org.openstrap.app.data.History import org.openstrap.app.data.SleepEdits import org.openstrap.app.data.SleepHistory import org.openstrap.app.data.SleepRegularity +import org.openstrap.app.data.HeartReadings import org.openstrap.app.i18n.Strings import org.openstrap.app.presentation.ChartPoint import org.openstrap.app.presentation.Ranges @@ -47,23 +48,32 @@ internal object SleepCopy { else -> null } - /** The night's heart rate readings while asleep (5-minute averages). */ + /** The night's heart rate readings while asleep (5-minute averages), for its line. */ fun sleepHeart(state: DayUiState): List = state.sleep?.let { s -> state.sleepHeartRate.filter { it.x in s.start..s.end } }.orEmpty() - /** The lowest heart rate while asleep, and when. */ - fun lowestHeart(state: DayUiState): ChartPoint? = sleepHeart(state).minByOrNull { it.y } + /** The night's stored heart rate readings while asleep, one a minute, for its lowest and mean. */ + private fun sleepMinutes(state: DayUiState): List> = + state.sleep?.let { s -> HeartReadings.within(state.sleepHeartMinutes, s.start, s.end) }.orEmpty() - /** The average heart rate while asleep: the strap's for the night, else the average of the readings. */ - fun averageHeart(state: DayUiState): Int? = - state.sleep?.averageHeartRate ?: sleepHeart(state).takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.roundToInt() + /** The lowest heart rate while asleep, and when: the lowest stored reading, not the lowest 5-minute average. */ + fun lowestHeart(state: DayUiState): ChartPoint? = + HeartReadings.lowest(sleepMinutes(state))?.let { (t, bpm) -> ChartPoint(t, bpm.toFloat()) } + + /** The average heart rate while asleep: the strap's for the night, else the mean of the stored readings. */ + fun averageHeart(state: DayUiState): Int? = state.sleep?.averageHeartRate ?: HeartReadings.mean(sleepMinutes(state)) /** - * The signals the strap reads in your sleep. Wherever one shows, on any tab, in its detail or a related row, it's + * The signals the strap reads only in your sleep. Wherever one shows, on any tab, in its detail or a related row, it's * the night's average ([nightValue]) against the nights before ([nightNormal]), so they all say the same. The * calendar day would split the night at midnight and judge it against whole days, hours off the wrist included. + * Blood oxygen is not one: the strap reads it all day too, so only the Sleep and Recovery tabs show its night + * ([NIGHT_FIGURES]), and Today and All metrics lead with its latest reading ([LatestReading]). */ - val NIGHT_SIGNALS: Set = setOf(Metric.Hrv, Metric.Breathing, Metric.Spo2, Metric.SkinTemperature) + val NIGHT_SIGNALS: Set = setOf(Metric.Hrv, Metric.Breathing, Metric.SkinTemperature) + + /** The metrics whose figure on the Sleep and Recovery tabs is the night's, so their details open scoped to the night. */ + val NIGHT_FIGURES: Set = NIGHT_SIGNALS + Metric.Spo2 /** * What a night signal says while its normal is still forming: "Learning, 5 of 7 nights". The same words on every @@ -123,8 +133,8 @@ internal object SleepCopy { */ fun nightDaily(metric: Metric): DailyMetric = if (metric == Metric.Spo2) DailyMetric.SleepSpo2 else metric.daily - /** Whether [nightDaily] comes only from sleep (breathing rate, night blood oxygen), so Month and Year are nights too. */ - fun dailyIsNightly(metric: Metric): Boolean = metric == Metric.Spo2 || metric == Metric.Breathing + /** Whether [nightDaily] comes only from sleep (breathing rate, night blood oxygen, HRV), so Month and Year are nights too. */ + fun dailyIsNightly(metric: Metric): Boolean = metric == Metric.Spo2 || metric == Metric.Breathing || metric == Metric.Hrv /** * The label under a night-scoped value: "ms, average asleep", "ms, average of the last 7 nights". Month and Year say @@ -176,8 +186,10 @@ internal object SleepCopy { /* -------------------------------------------- Sleep score ------------------------------------------- */ /** The label under the score. */ - fun scoreLabel(today: Boolean, strings: Strings = Strings.app): String = - strings.get(if (today) R.string.day_sleep_score_label_last_night else R.string.day_sleep_score_label_that_night) + fun scoreLabel(today: Boolean, adjusted: Boolean = false, strings: Strings = Strings.app): String { + val label = strings.get(if (today) R.string.day_sleep_score_label_last_night else R.string.day_sleep_score_label_that_night) + return if (adjusted) strings.format(R.string.day_sleep_score_label_adjusted, label) else label + } /** The Sleep score's state with no score: no sleep at all, or a night the strap didn't score. */ fun noScore(hasSleep: Boolean, today: Boolean, strings: Strings = Strings.app): Pair = when { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt index d26c0d6d..febd400f 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/SleepPanels.kt @@ -34,6 +34,7 @@ import java.time.format.TextStyle as DayStyle import java.util.Locale import kotlin.math.roundToInt import org.openstrap.app.presentation.AFTER_FIRST_NIGHT +import org.openstrap.app.presentation.DetailCopy import org.openstrap.app.presentation.Metric import org.openstrap.app.presentation.TodayCopy @@ -52,8 +53,10 @@ internal class NightVital( /** * The six night vitals the Sleep tab lists (spec 5.2), always all six, in order: lowest heart rate, HRV, breathing - * rate, blood oxygen, skin temperature (as its change from your normal once there is one) and average heart rate. + * rate, blood oxygen, skin temperature (its level, with the signed change from your normal under it once there is one) and + * average heart rate. * HRV, breathing, blood oxygen and skin temperature are read against your previous nights once there are a week of them. + * Blood oxygen's line says it is the night average, and skin temperature's its change from your normal. */ internal fun nightVitals(state: DayUiState, firstNights: Boolean = false, strings: Strings = Strings.app): List { val session = state.sleep @@ -63,11 +66,14 @@ internal fun nightVitals(state: DayUiState, firstNights: Boolean = false, string else -> strings.get(R.string.day_sleep_vital_no_reading) } // The same value and normal the night-scoped detail shows ([SleepCopy]). - fun against(metric: Metric, label: String, color: Color, show: (Float, History.Normal?) -> String): NightVital { + fun against( + metric: Metric, label: String, color: Color, second: (Float, History.Normal?) -> String? = { _, _ -> null }, + show: (Float, History.Normal?) -> String, + ): NightVital { val v = SleepCopy.nightValue(state, metric) ?: return NightVital(metric, label, color, null, missing) val n = SleepCopy.nightNormal(state, metric) val direction = History.status(v, n) - val status = SleepCopy.learning(state, metric, strings) ?: TodayCopy.normalWord(direction) + val status = second(v, n) ?: SleepCopy.learning(state, metric, strings) ?: TodayCopy.normalWord(direction) return NightVital(metric, label, color, show(v, n), status, direction.takeIf { n != null }) } val lowest = SleepCopy.lowestHeart(state) @@ -81,11 +87,16 @@ internal fun nightVitals(state: DayUiState, firstNights: Boolean = false, string against(Metric.Breathing, strings.get(R.string.day_info_breathing_name), MetricColors.sleepLight) { v, _ -> Metric.Breathing.format(v) }, - against(Metric.Spo2, strings.get(R.string.day_info_spo2_name), MetricColors.spo2) { v, _ -> "${v.roundToInt()}%" }, - // Skin temperature means little on its own; once there's a normal, show how far off it is. - against(Metric.SkinTemperature, strings.get(R.string.day_info_skin_temp_name), MetricColors.temperature) { v, n -> - n?.let { Metric.SkinTemperature.formatChange(v - it.mean) } ?: Metric.SkinTemperature.format(v) - }, + // Blood oxygen is read all day too, so its row says this is the night's average. + against( + Metric.Spo2, strings.get(R.string.day_info_spo2_name), MetricColors.spo2, + second = { _, _ -> strings.get(R.string.glow_today_spo2_night_average) }, + ) { v, _ -> "${v.roundToInt()}%" }, + // The night's average level, with how far it is from your normal under it once there is one. + against( + Metric.SkinTemperature, strings.get(R.string.day_info_skin_temp_name), MetricColors.temperature, + second = { v, n -> n?.let { DetailCopy.changeWithUnit(Metric.SkinTemperature, v - it.mean) } }, + ) { v, _ -> Metric.SkinTemperature.format(v) }, NightVital( Metric.HeartRate, strings.get(R.string.day_sleep_vital_average_heart), MetricColors.heart, average?.toString(), if (average != null) strings.get(R.string.day_sleep_vital_while_asleep) else missing, diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt index dfd5e759..e1c8ad42 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Tags.kt @@ -92,7 +92,7 @@ enum class OffWords { /** Blood oxygen: only Below normal is news. */ LowOnly, - /** Recovery, Stress, Load: Above or Below usual. */ + /** Recovery, Load: Above or Below usual. */ Usual, /** Last night: Long or Short. */ diff --git a/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceScreen.kt index 973516c8..68af502e 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceScreen.kt @@ -104,14 +104,20 @@ internal fun strapStateLine( lastSeen: Long?, now: Long, strings: Strings = Strings.app, + /** The last full sync ([org.openstrap.app.device.SyncRecord.lastSuccess]), kept across restarts. */ + lastSync: Long? = null, ): String = when (connection) { - is ConnectionState.Connected -> when { - connection.charging -> strings.get(R.string.you_strap_state_charging) - sync is SyncState.Running -> strings.get(R.string.you_strap_state_syncing) - sync is SyncState.Done -> strings.format(R.string.you_strap_state_synced, agoText(now - sync.atEpochSeconds).lowercase()) - sync is SyncState.Failed -> strings.get(R.string.you_strap_state_not_synced) - else -> strings.get(R.string.you_strap_state_connected) + is ConnectionState.Connected -> { + val synced = lastSync ?: (sync as? SyncState.Done)?.atEpochSeconds + when { + connection.charging -> strings.get(R.string.you_strap_state_charging) + sync is SyncState.Running -> strings.get(R.string.you_strap_state_syncing) + sync is SyncState.Failed -> strings.get(R.string.you_strap_state_not_synced) + synced != null -> strings.format(R.string.you_strap_state_synced, agoText(now - synced).lowercase()) + else -> strings.get(R.string.you_strap_state_connected) + } } + ConnectionState.BluetoothOff -> strings.get(R.string.you_strap_state_bluetooth_off) ConnectionState.Connecting, ConnectionState.Authenticating -> strings.get(R.string.you_strap_state_connecting) is ConnectionState.Failed -> strings.get(if (connection.keyRejected) R.string.you_strap_state_key_rejected else R.string.you_strap_state_cant_connect) @@ -153,6 +159,7 @@ fun DeviceScreen( val strapConnected = connection is ConnectionState.Connected androidx.compose.runtime.LaunchedEffect(strapConnected) { if (strapConnected) vm.checkCanRestart() } val sync by vm.sync.collectAsStateWithLifecycle() + val record by vm.syncRecord.collectAsStateWithLifecycle() val scan by vm.scan.collectAsStateWithLifecycle() val info by vm.info.collectAsStateWithLifecycle() val calls by vm.buzzOnCalls.collectAsStateWithLifecycle() @@ -205,7 +212,12 @@ fun DeviceScreen( item { PairPanel(vm, scan, onRequestBluetooth) } return@ScreenList } - item { StrapHero(device.name, preview?.connection ?: connection, preview?.sync ?: sync, preview?.lastSeen ?: lastSeen) } + item { + StrapHero( + device.name, preview?.connection ?: connection, preview?.sync ?: sync, preview?.lastSeen ?: lastSeen, + (preview?.record ?: record).lastSuccess, + ) + } val failed = connection as? ConnectionState.Failed if (failed?.keyRejected == true) item { KeyRejectedPanel(failed.reason, onPairAgain = vm::forget) } else item { @@ -221,6 +233,13 @@ fun DeviceScreen( } ConnectionState.Connecting, ConnectionState.Authenticating -> PageButton(stringResource(R.string.you_action_cancel), vm::disconnect, Modifier.fillMaxWidth().height(56.dp)) + ConnectionState.BluetoothOff -> { + val context = LocalContext.current + PageButton( + stringResource(R.string.you_strap_turn_on_bluetooth), { onRequestBluetooth { turnOnBluetooth(context) } }, + Modifier.fillMaxWidth().height(56.dp), primary = true, icon = AppIcons.Bluetooth, + ) + } else -> PageButton( stringResource(R.string.you_strap_connect), { onRequestBluetooth { vm.connect() } }, Modifier.fillMaxWidth().height(56.dp), primary = true, @@ -293,6 +312,17 @@ fun DeviceScreen( } } +/** + * Asks Android to turn Bluetooth on, which shows its own dialog. Where that can't be asked (no permission yet, or a phone + * that refuses), opens the Bluetooth settings. + */ +private fun turnOnBluetooth(context: android.content.Context) { + runCatching { context.startActivity(android.content.Intent(android.bluetooth.BluetoothAdapter.ACTION_REQUEST_ENABLE)) } + .onFailure { + runCatching { context.startActivity(android.content.Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS)) } + } +} + /** Find strap: buzzes the strap and becomes Stop while it runs; it stops by itself after 60 s, as Zepp's does. */ @Composable private fun FindStrapButton(vm: DeviceViewModel, modifier: Modifier) { @@ -338,6 +368,7 @@ private fun KeepConnectedRow(vm: DeviceViewModel, keepConnected: KeepConnected, val associated by vm.companionAssociated.collectAsStateWithLifecycle() val ignoringBattery by vm.ignoringBatteryOptimizations.collectAsStateWithLifecycle() val declined by vm.companionDeclined.collectAsStateWithLifecycle() + val hidden by vm.companionOfferHidden.collectAsStateWithLifecycle() val title = stringResource(R.string.you_strap_row_background) val on = stringResource(R.string.you_value_on) val off = stringResource(R.string.you_value_off) @@ -345,7 +376,7 @@ private fun KeepConnectedRow(vm: DeviceViewModel, keepConnected: KeepConnected, val icon = AppIcons.Bluetooth when { associated -> PageRow(title, on, icon = icon) - vm.companionSupported && !declined -> PageRow(title, off, onClick = { keepConnected.associate(address) }, icon = icon) + vm.companionSupported && !declined && !hidden -> PageRow(title, off, onClick = { keepConnected.associate(address) }, icon = icon) !ignoringBattery -> PageRow(title, off, icon = icon, onClick = { runCatching { context.startActivity( @@ -360,7 +391,7 @@ private fun KeepConnectedRow(vm: DeviceViewModel, keepConnected: KeepConnected, /** The strap in a glow card: its name, the state line, a drawing of it with its light, and the battery. */ @Composable -internal fun StrapHero(name: String, connection: ConnectionState, sync: SyncState, lastSeen: Long?) { +internal fun StrapHero(name: String, connection: ConnectionState, sync: SyncState, lastSeen: Long?, lastSync: Long? = null) { val connected = connection as? ConnectionState.Connected val battery = connected?.batteryPercent val led = when { @@ -378,8 +409,9 @@ internal fun StrapHero(name: String, connection: ConnectionState, sync: SyncStat Column(Modifier.fillMaxWidth().padding(end = 112.dp)) { Text(name, color = Color.White, style = GlowType.cardTitle, maxLines = 1, overflow = TextOverflow.Ellipsis) Text( - strapStateLine(connection, sync, lastSeen, now), color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), - style = GlowType.secondary, modifier = Modifier.padding(top = 4.dp), + strapStateLine(connection, sync, lastSeen, now, lastSync = lastSync), + color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, + modifier = Modifier.padding(top = 4.dp), ) } // 5 dp under it, so the space below the battery matches the space the title's line height leaves above it. diff --git a/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceViewModel.kt index 4c7212cd..b8a78060 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/device/DeviceViewModel.kt @@ -29,6 +29,7 @@ import org.openstrap.app.device.ConnectionState import org.openstrap.app.device.StrapController import org.openstrap.app.device.StrapInfo import org.openstrap.app.device.StrapManager +import org.openstrap.app.device.SyncRecord import org.openstrap.app.device.SyncState import org.openstrap.app.export.AutoBackup import org.openstrap.app.health.HealthConnectAutoSync @@ -78,6 +79,7 @@ class DeviceViewModel( val connection: StateFlow get() = strap.connection val sync: StateFlow get() = strap.sync + val syncRecord: StateFlow get() = strap.syncRecord val info: StateFlow get() = strap.info val findingStrap: StateFlow get() = strap.findingStrap @@ -159,6 +161,9 @@ class DeviceViewModel( val companionDeclined: StateFlow = settings.companionDeclined.stateIn(viewModelScope, SharingStarted.Eagerly, false) + /** The prompt was backed out of: the offer is hidden until the app starts again, and the battery setting shows meanwhile. */ + val companionOfferHidden: StateFlow get() = companion.offerHidden + /** "Stay connected in background": whether Android can associate the strap, and whether it is, or battery optimization is off. */ val companionSupported: Boolean get() = companion.supported val companionAssociated: StateFlow get() = companion.associated @@ -168,7 +173,10 @@ class DeviceViewModel( fun associate(activity: Activity, address: String, launch: (IntentSender) -> Unit) = companion.associate(activity, address, launch, onError = ::showMessage) - /** The association prompt's answer. Turned down, the page says what else keeps the strap connected. */ + /** + * The association prompt's answer. Backed out of, the offer hides for now and the page says what else keeps the strap + * connected; a failure of the system's own is kept ([CompanionLink.onResult]). + */ fun associationResult(resultCode: Int) { if (!companion.onResult(resultCode)) showMessage(strings.get(R.string.you_strap_not_linked)) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt b/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt index cd351457..b4cdb7ec 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt @@ -55,6 +55,8 @@ fun HealthConnectPage( onOpen: () -> Unit, onInstall: () -> Unit, onBack: () -> Unit, + caloriesMissing: Boolean = false, + onOfferCalories: () -> Unit = {}, ) { BackHandler(onBack = onBack) ScreenList(contentPadding, gutter = GlowLayout.Gutter) { @@ -86,6 +88,7 @@ fun HealthConnectPage( ) } } + if (caloriesMissing) item { CaloriesOffer(onOfferCalories) } } } @@ -103,6 +106,15 @@ private fun InstallPanel(onInstall: () -> Unit) { } } +/** Calories off: why they are left out, and the button that asks for just those permissions. */ +@Composable +private fun CaloriesOffer(onOffer: () -> Unit) { + Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + PageNote(stringResource(R.string.you_hc_calories_note)) + PageButton(stringResource(R.string.you_hc_calories_offer), onOffer, Modifier.fillMaxWidth(), icon = AppIcons.Plus) + } +} + /** * Opens Health Connect's home, where OpenStrap is one tap away under Your health apps, or its Data and access screen * where the home isn't there. False when neither opens (Health Connect missing or disabled). OpenStrap's own diff --git a/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt b/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt index 75f95772..715804cc 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt @@ -35,6 +35,7 @@ import org.openstrap.app.ui.glow.PagePanel import org.openstrap.app.ui.glow.PageRow import org.openstrap.app.ui.glow.PageRows import org.openstrap.app.ui.theme.AppIcons +import org.openstrap.app.update.Check import org.openstrap.app.update.Install import org.openstrap.app.update.NoteBlock import org.openstrap.app.update.NoteSpan @@ -81,7 +82,7 @@ fun UpdatesPage( PageRow( stringResource(R.string.you_updates_check_now), UpdateCopy.checkStatus(state, now), onClick = onCheck, below = true, divider = newest != null, - enabled = !state.checking, icon = AppIcons.Refresh04, + enabled = state.check != Check.Checking, icon = AppIcons.Refresh04, ) PageSwitchRow( stringResource(R.string.you_updates_daily), stringResource(R.string.you_updates_daily_note), auto, onAuto, diff --git a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt index 43325bb2..1981b886 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt @@ -248,6 +248,9 @@ fun ZeppAccountScreen(vm: FirmwareViewModel, contentPadding: PaddingValues, onBa } } +/** What the Zepp account panel is doing: one value, so editing the token and signing in can't both be on. */ +private enum class AccountMode { Idle, EditingToken, SigningIn } + @Composable private fun AccountPanel( account: ZeppAccount?, @@ -256,18 +259,17 @@ private fun AccountPanel( onClear: () -> Unit, onSignIn: (DeviceListing, BoundDevice?) -> Unit, ) { - var editing by rememberSaveable { mutableStateOf(false) } - var signIn by rememberSaveable { mutableStateOf(false) } - if (signIn) { + var mode by rememberSaveable { mutableStateOf(AccountMode.Idle) } + if (mode == AccountMode.SigningIn) { ZeppSignInDialog( preferredApiBase = account?.apiBase, confirmLabel = stringResource(R.string.you_zepp_save_sign_in), - onDismiss = { signIn = false }, - onConfirm = { listing, strap -> signIn = false; onSignIn(listing, strap) }, + onDismiss = { mode = AccountMode.Idle }, + onConfirm = { listing, strap -> mode = AccountMode.Idle; onSignIn(listing, strap) }, ) } PagePanel { - if (!editing) { + if (mode != AccountMode.EditingToken) { Body( when { account == null -> stringResource(R.string.you_zepp_account_none) @@ -276,12 +278,14 @@ private fun AccountPanel( }, ) PageButton( - stringResource(if (account == null) R.string.you_pair_sign_in else R.string.you_zepp_sign_in_again), { signIn = true }, + stringResource(if (account == null) R.string.you_pair_sign_in else R.string.you_zepp_sign_in_again), + { mode = AccountMode.SigningIn }, Modifier.fillMaxWidth(), enabled = enabled, primary = true, ) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { PageButton( - stringResource(if (account == null) R.string.you_zepp_paste_token else R.string.you_zepp_edit), { editing = true }, + stringResource(if (account == null) R.string.you_zepp_paste_token else R.string.you_zepp_edit), + { mode = AccountMode.EditingToken }, Modifier.weight(1f), enabled = enabled, ) if (account != null) { @@ -292,10 +296,12 @@ private fun AccountPanel( } return@PagePanel } - var token by rememberSaveable { mutableStateOf("") } - var user by rememberSaveable { mutableStateOf(account?.userId.orEmpty()) } - var api by rememberSaveable { mutableStateOf(account?.apiBase ?: ZeppAccount.DEFAULT_API_BASE) } - var china by rememberSaveable { mutableStateOf(account?.china == true) } + // Keyed on the account, so a fresh sign-in or renewed token starts the fields again from it and a stale copy + // can't be written back over it. The pasted token is the secret: plain remember, so it never reaches the saved state. + var token by remember(account) { mutableStateOf("") } + var user by rememberSaveable(account) { mutableStateOf(account?.userId.orEmpty()) } + var api by rememberSaveable(account) { mutableStateOf(account?.apiBase ?: ZeppAccount.DEFAULT_API_BASE) } + var china by rememberSaveable(account) { mutableStateOf(account?.china == true) } PageField( token, { token = it }, stringResource(R.string.you_zepp_app_token), Modifier.fillMaxWidth(), placeholder = if (account != null) stringResource(R.string.you_zepp_keep_token) else null, @@ -310,10 +316,10 @@ private fun AccountPanel( stringResource(R.string.you_zepp_china), stringResource(R.string.you_zepp_china_note), china, { china = it }, divider = false, ) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { - PageButton(stringResource(R.string.you_action_cancel), { editing = false }, Modifier.weight(1f)) + PageButton(stringResource(R.string.you_action_cancel), { mode = AccountMode.Idle }, Modifier.weight(1f)) PageButton( stringResource(R.string.you_action_save), - { onSave(token.ifBlank { account?.appToken.orEmpty() }, user, api, china); editing = false }, Modifier.weight(1f), + { onSave(token.ifBlank { account?.appToken.orEmpty() }, user, api, china); mode = AccountMode.Idle }, Modifier.weight(1f), enabled = token.isNotBlank() || account != null, primary = true, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt index 092a4b06..7a09c35b 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File @@ -103,15 +104,28 @@ class FirmwareViewModel( fun reset() { if (!busy) _step.value = FirmwareStep.Idle } - private val busy get() = _step.value.let { it is FirmwareStep.Checking || it is FirmwareStep.Downloading || it is FirmwareStep.Installing } + private val busy get() = _step.value.isBusy() + private fun FirmwareStep.isBusy() = this is FirmwareStep.Checking || this is FirmwareStep.Downloading || this is FirmwareStep.Installing + + /** + * Moves to [next] only while the step is still the kind [S] this work started in. Work that outlives its step (a + * late progress callback, a result after the page was reset) is dropped, so it can't pull the step back. + */ + private inline fun settle(next: FirmwareStep) { + _step.update { if (it is S) next else it } + } + + // Each return is a reason the check can't start. + @Suppress("ReturnCount") fun check() { + if (busy) return val acc = account.value ?: return fail(strings.get(R.string.you_firmware_no_account)) val info = strap.info.value val firmware = info?.firmware ?: return fail(strings.get(R.string.you_firmware_no_version)) _step.value = FirmwareStep.Checking viewModelScope.launch { - _step.value = catching { + settle(catching { val identity = StrapIdentity( firmwareVersion = firmware, hardwareVersion = info.hardware, @@ -128,7 +142,7 @@ class FirmwareViewModel( cloud.check(current.apiBase, current.appToken, current.userId, identity) } FirmwareStep.Checked(result) - }.getOrElse { failed("firmware check", it, strings.get(R.string.you_firmware_check_failed)) } + }.getOrElse { failed("firmware check", it, strings.get(R.string.you_firmware_check_failed)) }) } } @@ -147,12 +161,13 @@ class FirmwareViewModel( /** Downloads the first part in install order and stages it. Further parts follow after the strap restarts. */ fun download(part: FirmwarePart) { + if (busy) return val type = part.type ?: return fail(strings.format(R.string.you_firmware_unknown_part, part.prefix)) _step.value = FirmwareStep.Downloading(part, 0f) viewModelScope.launch { - _step.value = catching { + settle(catching { val bytes = cloud.download(part) { done, total -> - if (total > 0) _step.value = FirmwareStep.Downloading(part, done.toFloat() / total) + if (total > 0) settle(FirmwareStep.Downloading(part, done.toFloat() / total)) } val trailer = HmfwTrailer.read(bytes) FirmwareStep.Ready( @@ -162,13 +177,14 @@ class FirmwareViewModel( trailer, trailerWarnings(bytes, trailer, type), ), ) - }.getOrElse { failed("firmware download", it, strings.get(R.string.you_firmware_download_failed)) } + }.getOrElse { failed("firmware download", it, strings.get(R.string.you_firmware_download_failed)) }) } } /** Stages a file the user picked. Only plain firmware images are accepted from files. */ fun loadFile(uri: Uri) = viewModelScope.launch { - _step.value = catching { + if (busy) return@launch + val next = catching { val bytes = withContext(Dispatchers.IO) { val input = openFile(uri) ?: throw FileNotFoundException("no input stream for $uri") input.use { it.readBytes() } @@ -191,6 +207,8 @@ class FirmwareViewModel( log("firmware: file not read: $it") FirmwareStep.Failed(strings.get(R.string.you_firmware_file_unread)) } + // The read takes a while: a check, download or install that began meanwhile keeps the step. + _step.update { if (it.isBusy()) it else next } } /** Problems that make an image look wrong for this strap (docs/protocol/03 §2.2, advisory). */ @@ -218,25 +236,28 @@ class FirmwareViewModel( if (strap.info.value?.dfuAvailable == false) add(strings.get(R.string.system_firmware_no_service)) } + // Each return is a reason not to install: one running, updates off, or something blocking it. + @Suppress("ReturnCount") fun install(image: ReadyImage) { + if (busy) return if (!UPDATES_ENABLED) return fail(strings.get(R.string.you_firmware_install_failed)) val blocking = blockers() if (blocking.isNotEmpty()) return fail(blocking.joinToString(" ")) _step.value = FirmwareStep.Installing(strings.get(R.string.you_firmware_step_starting), null) viewModelScope.launch { - _step.value = catching { + settle(catching { strap.installFirmware(image.bytes, image.type) { p -> - _step.value = when (p) { + settle(when (p) { is DfuProgress.Transferring -> FirmwareStep.Installing( strings.get(R.string.you_firmware_step_sending), p.sent.toFloat() / p.total, ) DfuProgress.Validating -> FirmwareStep.Installing(strings.get(R.string.you_firmware_step_validating), null) DfuProgress.Applying -> FirmwareStep.Installing(strings.get(R.string.you_firmware_step_applying), null) DfuProgress.Done -> FirmwareStep.Installing(strings.get(R.string.you_firmware_step_restarting), 1f) - } + }) } FirmwareStep.Installed - }.getOrElse { failed("firmware install", it, strings.get(R.string.you_firmware_install_failed)) } + }.getOrElse { failed("firmware install", it, strings.get(R.string.you_firmware_install_failed)) }) } } @@ -258,9 +279,8 @@ class FirmwareViewModel( const val MIN_BATTERY = 30 /** - * Off for now: since firmware 3.27.0.1 the strap's own sleep result is empty or wrong on nights it was worn - * (2026-11-07), so no more strap updates until that is understood. The Strap page shows the version without - * opening this page, and [install] refuses. + * Off for now (since 2026-11-07). The Strap page shows the version without opening this page, and [install] + * refuses. */ const val UPDATES_ENABLED = false } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt index 298b6cac..9dca56a5 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt @@ -15,7 +15,9 @@ import org.openstrap.app.data.RecoveryResult import org.openstrap.app.data.WorkoutAnalysis import org.openstrap.app.ui.dashboard.DayUiState import org.openstrap.app.ui.dashboard.Detail +import org.openstrap.app.presentation.DetailCopy import org.openstrap.app.presentation.Metric +import org.openstrap.app.ui.dashboard.LatestReading import org.openstrap.app.ui.dashboard.SleepCopy import org.openstrap.app.ui.dashboard.avg import org.openstrap.app.ui.theme.MetricColors @@ -97,9 +99,11 @@ fun metricIndex( today: LocalDate = LocalDate.now(), /** The strap's own Recovery for the day, shown as its estimate while OpenStrap's score is withheld, as on Today. */ strapScore: Int? = null, + /** The time as epoch seconds, which says whether a latest reading is old enough to show when it was taken. */ + now: Long = java.time.Instant.now().epochSecond, strings: Strings = Strings.app, ): List { - val rec = recovery?.takeIf { it.date == state.date } + val rec = recovery val (habitValue, habitStatus) = habitAgeRow(healthspan, strings) val weekFrom = state.date.minusDays(6) // The 7 days up to the day shown, not Your week's Monday to Sunday, so the row says so. The strap's own @@ -143,7 +147,7 @@ fun metricIndex( ), ), ), - ) + signalGroups(state, strings) + listOf( + ) + signalGroups(state, now, strings) + listOf( IndexGroup( strings.get(R.string.glow_metrics_group_activity), listOf( @@ -173,10 +177,30 @@ private fun metric( value: Float?, @StringRes status: Int = R.string.glow_metrics_day_average, suffix: String = "", -) = row(strings.get(name), color, value?.let { m.format(it) + suffix }, strings.get(status), IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS))) + /** The status as already worded, for a latest reading whose line depends on its time. */ + line: String? = null, +) = row(strings.get(name), color, value?.let { m.format(it) + suffix }, line ?: strings.get(status), IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS))) + +/** + * Skin temperature's row: the night's average level, with its change from your normal in the status line once there's + * a normal, as the Sleep tab says it; before that, "Average asleep". + */ +private fun skinTemperatureRow(state: DayUiState, strings: Strings): IndexRow { + val m = Metric.SkinTemperature + val v = SleepCopy.nightValue(state, m) + val normal = SleepCopy.nightNormal(state, m) + val name = strings.get(R.string.glow_metrics_skin_temperature) + val target = IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS)) + val status = if (v != null && normal != null) { + DetailCopy.changeWithUnit(m, v - normal.mean) + } else { + strings.get(R.string.glow_metrics_night_average) + } + return row(name, MetricColors.temperature, v?.let { m.format(it) }, status, target) +} /** The index's Heart and Body signals groups, a row for each of their metrics. */ -private fun signalGroups(state: DayUiState, strings: Strings): List = listOf( +private fun signalGroups(state: DayUiState, now: Long, strings: Strings): List = listOf( IndexGroup( strings.get(R.string.glow_metrics_group_heart), listOf( @@ -184,9 +208,10 @@ private fun signalGroups(state: DayUiState, strings: Strings): List strings, Metric.HeartRate, R.string.glow_metrics_heart_rate, MetricColors.heart, state.latestHeartRate?.toFloat(), R.string.glow_metrics_latest_reading, ), + // Our own estimate says so when the strap sent none for the day. metric( - strings, Metric.RestingHr, R.string.glow_metrics_resting_heart_rate, MetricColors.heart, - state.restingHeartRate?.toFloat(), R.string.glow_metrics_for_the_day, + strings, Metric.RestingHr, R.string.glow_metrics_resting_heart_rate, MetricColors.heart, state.restingHeartRate?.toFloat(), + if (state.restingEstimated) R.string.glow_metrics_for_the_day_estimated else R.string.glow_metrics_for_the_day, ), metric( strings, Metric.Hrv, R.string.glow_metrics_hrv, MetricColors.hrv, SleepCopy.nightValue(state, Metric.Hrv), @@ -197,20 +222,23 @@ private fun signalGroups(state: DayUiState, strings: Strings): List IndexGroup( strings.get(R.string.glow_metrics_group_body), listOf( - // Night signals: last night's, as every tab and detail shows them (SleepCopy.NIGHT_SIGNALS). + // Blood oxygen leads with the day's latest reading, as heart rate does, and opens the day's detail. The line says + // whether it was taken awake or asleep, and when once it is an hour old. metric( - strings, Metric.Spo2, R.string.glow_metrics_blood_oxygen, MetricColors.spo2, SleepCopy.nightValue(state, Metric.Spo2), - R.string.glow_metrics_night_average, suffix = "%", - ), - metric( - strings, Metric.SkinTemperature, R.string.glow_metrics_skin_temperature, MetricColors.temperature, - SleepCopy.nightValue(state, Metric.SkinTemperature), R.string.glow_metrics_night_average, + strings, Metric.Spo2, R.string.glow_metrics_blood_oxygen, MetricColors.spo2, LatestReading.spo2(state)?.y, + suffix = "%", line = latestLine(Metric.Spo2, state, now, strings, time = ::clock), ), + // Night signals: last night's, as every tab and detail shows them (SleepCopy.NIGHT_SIGNALS). + skinTemperatureRow(state, strings), metric( strings, Metric.Breathing, R.string.glow_metrics_breathing_rate, MetricColors.sleepLight, SleepCopy.nightValue(state, Metric.Breathing), R.string.glow_metrics_night_average, ), - metric(strings, Metric.Stress, R.string.glow_metrics_stress, MetricColors.stress, state.stress.avg()?.toFloat()), + // The latest reading, as on Today; its High tag and rim are on the Today and Recovery cards, so the line says the level. + metric( + strings, Metric.Stress, R.string.glow_metrics_stress, MetricColors.stress, LatestReading.stress(state)?.y, + line = latestLine(Metric.Stress, state, now, strings, time = ::clock), + ), ), ), ) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt index ea59e259..04e9fed0 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt @@ -169,7 +169,7 @@ fun GlowActivityScreen( } val stored = activity.heartPointsOn(state.date) val heartPoints = state.pai?.total ?: stored[state.date]?.total - val r = recovery?.takeIf { it.date == state.date } + val r = recovery val live = liveHeartRate?.takeIf { isToday } org.openstrap.app.ui.components.HoldLiveHeartRate(isToday) val slots = activityCards(ActivityFacts(isToday = isToday, suggestion = suggestion != null, live = live != null)) @@ -215,7 +215,7 @@ fun GlowActivityScreen( } ActivityCard.Load -> DayLoadCard(r) { open(Score.Load) } ActivityCard.HeartRate -> HeartRateCard( - state, live, restingRange, rememberNormal(Metric.HeartRate, state.date, history), + state, live, restingRange, ) { onOpenMetric(Metric.HeartRate) } ActivityCard.Facts -> DayFactsList(state, r, workouts, isToday, onEditProfile, open, partial) ActivityCard.Workouts -> WorkoutsList( @@ -393,12 +393,11 @@ private val LevelFillHeight = 28.dp /** * Heart rate (spec 5.3, 6): the day's line through your [resting] range as a dim band ([DayLine]), the number under it - * following the finger while you hold the line. When the latest reading is off your heart rate [normal] the rim lights - * at the line's end, over the top when above and the foot when below, with "Above normal" or "Below normal" after the - * number (spec 2.5). Opens the heart rate detail. + * following the finger while you hold the line. A reading moves all day, so there is no tag and no rim (resting heart + * rate carries its own). Opens the heart rate detail. */ @Composable -private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal?, normal: History.Normal?, onClick: () -> Unit) { +private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal?, onClick: () -> Unit) { val step = HEART_STEP_SECONDS val values = remember(state.heartRate, state.dayStart) { bucket(state.heartRate, state.dayStart..state.dayEnd, step) } var picked by remember(values) { mutableStateOf(null) } @@ -406,12 +405,9 @@ private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal val pad = with(LocalDensity.current) { LinePad.toPx() } val scrubbed = picked?.let { i -> values.getOrNull(i)?.let { it.roundToInt() to state.dayStart + i * step } } val now = scrubbed?.first ?: live ?: state.latestHeartRate - val status = bodyOffStatus(state.latestHeartRate?.toFloat(), normal) - val tag = offTag(OffWords.Normal, status) - val rim = if (tag != null) dayLineRim(values, status == OffStatus.Above, PictureSize.Wide) else null - PictureCard(MetricColors.heart, Modifier.fillMaxWidth().gridSize(CardSize.Wide), rim = rim, onClick = onClick) { + PictureCard(MetricColors.heart, Modifier.fillMaxWidth().gridSize(CardSize.Wide), onClick = onClick) { EdgeTitle( - stringResource(R.string.glow_today_heart_rate), state.restingHeartRate?.let { stringResource(R.string.glow_today_resting, it) }, + stringResource(R.string.glow_today_heart_rate), restingNote(state), ) if (state.heartRate.size >= 2) { Spacer(Modifier.height(GlowLayout.TitleGap)) @@ -424,17 +420,21 @@ private fun HeartRateCard(state: DayUiState, live: Int?, resting: History.Normal .scrub(values) { x -> picked = x?.let { nearestReading(values, it, width.toFloat(), pad) } }, ) } - // The tag is about now, so a scrubbed point leaves it out. TaggedNumber( - now?.toString(), stringResource(R.string.glow_unit_bpm), tag.takeIf { scrubbed == null }, Modifier.padding(top = 14.dp), + now?.toString(), stringResource(R.string.glow_unit_bpm), null, Modifier.padding(top = 14.dp), ) val at = scrubbed?.second ?: state.heartRate.lastOrNull()?.x - StatusLine(TodayCopy.heartAt(live != null && scrubbed == null, at?.let(::clock))) + // A held point is the average of a 10-minute stretch, not one reading. + StatusLine( + if (scrubbed != null) stringResource(R.string.core_today_heart_average_from, step / SECONDS_PER_MINUTE, clock(scrubbed.second)) + else TodayCopy.heartAt(live != null, at?.let(::clock)), + ) } } /** The heart rate line's buckets: 10 minutes each. */ private const val HEART_STEP_SECONDS = 10 * 60L +private const val SECONDS_PER_MINUTE = 60L /** The line's height on the card and the inset [DayLine] draws inside its edges. */ private val DayLineHeight = 70.dp diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt index 76efc80d..9eadbbfb 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowCharts.kt @@ -169,6 +169,8 @@ fun GlowLineChart( yRange: ClosedFloatingPointRange? = null, /** A usual range drawn as a band of the colour at 12%, no edge lines (e.g. your normal). */ band: ClosedFloatingPointRange? = null, + /** The readings, by index, to shade lightly behind the line (e.g. the hours asleep); null for none. */ + shade: IntRange? = null, /** How the average label prints a value. */ format: (Float) -> String = { it.roundToInt().toString() }, /** @@ -212,6 +214,11 @@ fun GlowLineChart( val axisLabels = m.measureAll(labels) val h = g.plotBottom onDrawBehind { + if (shade != null) { + val x0 = g.xOf(shade.first) + val box = Size(g.xOf(shade.last) - x0, g.plotBottom - g.top) + drawRect(Color.White.copy(alpha = SHADE_ALPHA), Offset(x0, g.top), box) + } drawLineChartBody(g, paths, color) if (average != null) { @@ -242,6 +249,9 @@ fun GlowLineChart( ) } +/** The hours shaded behind a line chart, in white. */ +private const val SHADE_ALPHA = 0.07f + /** Your normal behind a chart: a band of the ink at 12% (spec 2.7). */ private const val NormalBandAlpha = ChartInk.NORMAL_BAND_ALPHA diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt index 23826943..36e1dd17 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowList.kt @@ -129,7 +129,7 @@ private fun ListNote(note: String, onNote: (() -> Unit)?) { * A row in a [ListPanel]: the metric's [icon] in its ink [color] (or in [iconTint], as a workout's sport in white), the * [name] with its [status] under it, the [value] in dot-matrix digits in its own column on the right, and the tap caret * when [onClick] opens something (spec 2.5, Grouped list). Name and value stay white, the status Secondary. Off your - * normal, [tag] takes the status's place as a news tag ([NewsPill]), and a row has no rim. A null [value] is a waiting row: a dim dash, the icon at 30%, and [status] says what it waits for ("After + * normal, [tag] sits after the [status] on its line as a news tag ([NewsPill]), and a row has no rim. A null [value] is a waiting row: a dim dash, the icon at 30%, and [status] says what it waits for ("After * your first night"). A row that isn't a metric passes no icon. [divider] draws the hairline above the row. */ @Composable @@ -139,7 +139,7 @@ fun ListRow( value: String?, status: String?, modifier: Modifier = Modifier, - /** Off your normal: the off tag in place of [status] (spec 2.5, Tags). */ + /** Off your normal: the off tag after [status] on its line, the line giving way to it (spec 2.5, Tags). */ tag: org.openstrap.app.ui.dashboard.NewsTag? = null, onClick: (() -> Unit)? = null, divider: Boolean = true, @@ -176,12 +176,7 @@ fun ListRow( } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { RowName(name) - if (tag != null && !waiting) NewsPill(tag) - else if (status != null) Text( - status, - color = if (waiting) Color.White.copy(alpha = 0.45f) else Color.White.copy(alpha = 0.6f), - style = GlowType.secondary, - ) + RowLine(status, tag.takeIf { !waiting }, waiting) } Spacer(Modifier.width(12.dp)) if (value != null) CompositionLocalProvider(LocalCardNumbers provides opening?.numbers) { @@ -195,6 +190,25 @@ fun ListRow( } } +/** A row's second line: the [status], then the off [tag] after it, which keeps its place while the status gives way. */ +@Composable +private fun RowLine(status: String?, tag: org.openstrap.app.ui.dashboard.NewsTag?, waiting: Boolean) { + if (status == null && tag == null) return + Row(verticalAlignment = Alignment.CenterVertically) { + if (status != null) Text( + status, + Modifier.weight(1f, fill = false), + color = if (waiting) Color.White.copy(alpha = 0.45f) else Color.White.copy(alpha = 0.6f), + style = GlowType.secondary, + // Beside a tag the line stays on one row, the tag keeping its place. + maxLines = if (tag != null) 1 else Int.MAX_VALUE, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + ) + if (status != null && tag != null) Spacer(Modifier.width(8.dp)) + if (tag != null) NewsPill(tag) + } +} + /** A row's icon, and the gap after it, as on the You and Strap pages. */ internal val RowIcon = 20.dp internal val RowIconGap = 14.dp diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt index 59209844..081d9372 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt @@ -89,9 +89,11 @@ import org.openstrap.app.presentation.Metric import org.openstrap.app.ui.dashboard.NIGHTLY import org.openstrap.app.ui.dashboard.RELATED import org.openstrap.app.presentation.Range +import org.openstrap.app.presentation.StressLevel import org.openstrap.app.ui.dashboard.ScreenList import org.openstrap.app.ui.dashboard.avg import org.openstrap.app.ui.dashboard.colorOf +import org.openstrap.app.ui.dashboard.LatestReading import org.openstrap.app.ui.dashboard.SleepCopy import org.openstrap.app.ui.dashboard.siblingsOf import java.time.LocalDate @@ -493,14 +495,19 @@ internal fun DetailEmpty(text: String) { private val HOURS = listOf("00", "06", "12", "18", "24") -/** A day's value of [metric]: the live or latest heart rate, the strap's resting heart rate, the day's steps, else the average of its readings. */ +/** + * A day's value of [metric]: the live or latest heart rate, the resting heart rate, the day's steps, HRV from the night's + * readings, else the average of the day's readings. + */ internal fun dayValue(metric: Metric, state: DayUiState, live: Int? = null): Float? = when (metric) { Metric.HeartRate -> (live ?: state.latestHeartRate)?.toFloat() Metric.RestingHr -> state.restingHeartRate?.toFloat() Metric.Steps -> state.steps.toFloat().takeIf { it > 0f } - Metric.Hrv -> state.hrv.avg()?.toFloat() - Metric.Spo2 -> state.spo2.avg()?.toFloat() - Metric.Stress -> state.stress.avg()?.toFloat() + // The night's average, the one HRV figure on every screen ([NightMetrics.sleepHrv]). + Metric.Hrv -> SleepCopy.nightValue(state, Metric.Hrv) + // The latest reading, as heart rate: blood oxygen's night average is only on the Sleep and Recovery tabs + // ([SleepCopy.nightValue]); stress is judged by that reading's level ([StressLevel]). + Metric.Spo2, Metric.Stress -> LatestReading.of(metric, state)?.y Metric.SkinTemperature -> state.skinTemperature.takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.toFloat() Metric.Breathing -> state.breathRate.takeIf { it.isNotEmpty() }?.map { it.y }?.average()?.toFloat() } @@ -565,15 +572,39 @@ fun GlowMetricDetailScreen( range == Range.Day -> dayValue(metric, state, live) else -> summary?.average } - // Heart rate's normal is a daily average, not a reading, so the day's reading gets no word; nor does a night's. + // Heart rate's normal is a daily average, not a reading, so the day's reading gets no word; nor does a night's, + // nor a latest reading (blood oxygen, stress), which has no baseline of its own. + val latestReading = !night && range == Range.Day && metric in LatestReading.METRICS val status = when { fromNight -> History.status(value, nightNormal) - range == Range.Year || (range == Range.Day && metric == Metric.HeartRate) -> null + range == Range.Year || (range == Range.Day && metric == Metric.HeartRate) || latestReading -> null else -> History.status(value, normal) } - val label = if (night) SleepCopy.nightLabel(metric, range) else DetailCopy.valueLabel(metric, range, live = live != null, today = isToday) + val label = if (night) SleepCopy.nightLabel(metric, range) else DetailCopy.valueLabel( + metric, range, live = live != null, today = isToday, estimated = metric == Metric.RestingHr && state.restingEstimated, + latest = LatestReading.of(metric, state)?.let { + DetailCopy.Latest( + clock(it.x), asleep = metric == Metric.Spo2 && LatestReading.spo2Asleep(state), + level = if (metric == Metric.Stress) StressLevel.of(it.y) else null, + ) + }, + ) + // What the day is read against your usual with: the status of its value, or for stress, whose headline is the latest + // reading, of the day's average, the figure the sentence under its chart reads. + val dayStatus = if (latestReading && metric == Metric.Stress) History.status(state.stress.avg()?.toFloat(), normal) else status + // The normal the value is read against, for skin temperature's change from it, which its label says after what the + // number is. A day's only: a longer range's value is an average over days, not a level to place against one night. + val headNormal = (if (fromNight) nightNormal else normal).takeIf { range == Range.Day } val headline = when { - value != null -> DetailHeadline(metric.format(value, Units.DOT_LOCALE), label, DetailCopy.statusWord(status)) + value != null -> DetailHeadline( + metric.format(value, Units.DOT_LOCALE), label, + // Skin temperature's day says how far it is from your normal, and which side, in place of the plain word. + if (metric == Metric.SkinTemperature && headNormal != null && status != null) { + DetailCopy.skinChangeWord(metric, value - headNormal.mean, status) + } else { + DetailCopy.statusWord(status) + }, + ) night && range == Range.Day -> SleepCopy.nightNoValue(state.sleep != null, isToday).let { (word, why) -> DetailHeadline.none(word, why) } night && range == Range.Week -> DetailHeadline.none(stringResource(R.string.glow_no_reading), stringResource(R.string.glow_metrics_last_7_nights)) @@ -600,7 +631,7 @@ fun GlowMetricDetailScreen( val sentence = when { value == null -> null metric == Metric.HeartRate -> SleepCopy.lowestHeart(state).let { low -> - SleepCopy.nightHeart(low?.y?.toInt(), low?.x?.let(::clock), Math.round(value), isToday) + SleepCopy.nightHeart(low?.y?.let(Math::round), low?.x?.let(::clock), Math.round(value), isToday) } else -> DetailCopy.day(status, org.openstrap.app.presentation.DaySource.Night, isToday, nightDays) } @@ -634,11 +665,11 @@ fun GlowMetricDetailScreen( } else if (range == Range.Day) { item { DayChart(metric, state, color, value != null, normalOf = { m -> rememberNormal(m, end, history) }) { scrub = it } } val sentence = when { - value == null -> null - metric == Metric.HeartRate -> state.heartRate.takeIf { it.isNotEmpty() }?.let { s -> - DetailCopy.heartDay(s.minOf { it.y }.toInt(), s.maxOf { it.y }.toInt(), isToday) - } - else -> DetailCopy.day(status, org.openstrap.app.presentation.daySource(metric), isToday, normalDays) + // Blood oxygen's latest reading has no sentence; stress's is the day's average against your usual. + value == null || (latestReading && metric == Metric.Spo2) -> null + // The day's stored lowest and highest readings, the strap's own maximum when higher, not the chart's averages. + metric == Metric.HeartRate -> state.heartRateRange?.let { (low, high) -> DetailCopy.heartDay(low, high, isToday) } + else -> DetailCopy.day(dayStatus, org.openstrap.app.presentation.daySource(metric), isToday, normalDays) } if (sentence != null) item { DetailSentence(sentence) } } else { @@ -664,7 +695,7 @@ fun GlowMetricDetailScreen( if (sentence != null) item { DetailSentence(sentence) } } val related = RELATED[metric].orEmpty() - if (related.isNotEmpty() || night) item { RelatedList(related, state, history, onOpen, sleepRow = night) } + if (related.isNotEmpty() || night) item { RelatedList(related, state, history, onOpen, night = night) } } if (info) { @@ -672,6 +703,7 @@ fun GlowMetricDetailScreen( val sheetStatus = when { night -> History.status(SleepCopy.nightValue(state, metric), nightNormal) range == Range.Year -> null + latestReading -> dayStatus else -> History.status(value, normal) } InfoSheet( @@ -711,24 +743,30 @@ private fun NightChart(metric: Metric, state: DayUiState, color: Color, onScrub: Column(Modifier.padding(top = 8.dp)) { GlowLineChart( values, height = 220.dp, labels = listOf(clock(window.first), clock(window.last)), color = color, showAverage = false, format = metric::format, + yRange = SPO2_AXIS.takeIf { metric == Metric.Spo2 }, onScrub = { i -> - onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot) }) + onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot, slot) }) }, ) } } -/** A scrubbed reading of [metric] in the headline: its value and the time it was taken, "bpm at 22:30". */ -private fun scrubAt(metric: Metric, v: Float, at: Long, strings: Strings = Strings.app) = DetailHeadline( +/** + * A scrubbed point of [metric]'s line in the headline: its value and the time it starts. The line is made of averages + * over [slot] seconds, so it says so: "bpm, 5 min average from 22:30". + */ +private fun scrubAt(metric: Metric, v: Float, at: Long, slot: Long, strings: Strings = Strings.app) = DetailHeadline( metric.format(v, Units.DOT_LOCALE), if (metric.unit.isBlank()) { - strings.format(R.string.glow_metrics_at_time, clock(at)) + strings.format(R.string.glow_metrics_average_from_time, slot / SECONDS_PER_MINUTE, clock(at)) } else { - strings.format(R.string.glow_metrics_unit_at_time, metric.unit, clock(at)) + strings.format(R.string.glow_metrics_unit_average_from_time, metric.unit, slot / SECONDS_PER_MINUTE, clock(at)) }, null, ) +private const val SECONDS_PER_MINUTE = 60L + /** A held hour's steps in the headline: "steps, 09:00 to 10:00". */ private fun hourSteps(hour: Int, steps: Float, strings: Strings = Strings.app): DetailHeadline { val (from, to) = TimeOfDay.minutes(hour * MINUTES_PER_HOUR) to TimeOfDay.minutes((hour + 1) * MINUTES_PER_HOUR) @@ -739,6 +777,9 @@ private fun hourSteps(hour: Int, steps: Float, strings: Strings = Strings.app): private const val MINUTES_PER_HOUR = 60 +/** Blood oxygen's chart scale, so the lowest reading doesn't sit on the bottom edge: a fixed 80 to 100 %. */ +private val SPO2_AXIS = 80f..100f + /** * The selected day's own chart: steps by the hour, the week of resting heart rates, or the day's readings as a line * to scrub, which moves the headline ([onScrub], null on release). Heart rate's line has your resting range behind it. @@ -781,10 +822,15 @@ private fun DayChart(metric: Metric, state: DayUiState, color: Color, hasValue: val values = remember(series, window) { bucket(series, window, slot) } val labels = if (window == day) HOURS else listOf(clock(window.first), clock(window.last)) val band = if (metric == Metric.HeartRate) normalOf(Metric.RestingHr)?.let { it.low..it.high } else null + // Blood oxygen's hours inside the sleep window are shaded, so a night reading shows as one. + val sleep = LatestReading.sleepWindow(state) + val shade = if (metric == Metric.Spo2) LatestReading.shadeIndices(sleep, window, slot, values.size) else null GlowLineChart( - values, height = 220.dp, labels = labels, color = color, showAverage = false, band = band, format = metric::format, + values, height = 220.dp, labels = labels, color = color, showAverage = false, band = band, shade = shade, + yRange = SPO2_AXIS.takeIf { metric == Metric.Spo2 }, + format = metric::format, onScrub = { i -> - onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot) }) + onScrub(i?.let { values[it] }?.let { v -> scrubAt(metric, v, window.first + i * slot, slot) }) }, ) } @@ -858,10 +904,10 @@ internal fun series( * [sleepRow], as a night-scoped detail has, the night's Sleep score leads. */ @Composable -private fun RelatedList(related: List, state: DayUiState, history: DailyHistory, onOpen: (Detail) -> Unit, sleepRow: Boolean = false) { +private fun RelatedList(related: List, state: DayUiState, history: DailyHistory, onOpen: (Detail) -> Unit, night: Boolean = false) { RelatedPanel { - if (sleepRow) SleepScoreRow(state, divider = false, onOpen) - related.forEachIndexed { i, m -> RelatedMetricRow(m, state, history, divider = i > 0 || sleepRow, onOpen) } + if (night) SleepScoreRow(state, divider = false, onOpen) + related.forEachIndexed { i, m -> RelatedMetricRow(m, state, history, divider = i > 0 || night, onOpen, nightScoped = night) } } } @@ -893,26 +939,57 @@ internal fun RecoveryScoreRow(ready: org.openstrap.app.data.Recovery.Readiness?, ready?.score?.let { org.openstrap.app.presentation.TodayCopy.recoveryWord(it, ready.strainAlert) } ?: NO_VALUE, divider, onOpen, ) -/** A body signal as a related row: the day's value and its word against your normal, marked when it's off normal. */ +/** + * A body signal as a related row: the day's value and its word against your normal, marked when it's off normal. On a + * page scoped to the night ([nightScoped]) blood oxygen is the night's average, elsewhere its latest reading, as + * stress's is; stress's High tag judges that reading's level. + */ @Composable -internal fun RelatedMetricRow(m: Metric, state: DayUiState, history: DailyHistory, divider: Boolean, onOpen: (Detail) -> Unit) { +internal fun RelatedMetricRow( + m: Metric, state: DayUiState, history: DailyHistory, divider: Boolean, onOpen: (Detail) -> Unit, nightScoped: Boolean = false, +) { // A night signal reads as everywhere else: last night's against the nights before (SleepCopy.NIGHT_SIGNALS). - val night = m in SleepCopy.NIGHT_SIGNALS + val night = m in SleepCopy.NIGHT_SIGNALS || (m == Metric.Spo2 && nightScoped) + // Blood oxygen and stress on a day-scoped page are their latest reading, which has no normal to be read against. + val latest = m in LatestReading.METRICS && !night val dayNormal = rememberNormal(m, state.date, history) val normal = if (night) SleepCopy.nightNormal(state, m) else dayNormal val v = if (night) SleepCopy.nightValue(state, m) else dayValue(m, state) - // The heart rate moves all day, so it has no word against a normal. - val status = if (m == Metric.HeartRate) null else History.status(v, normal) + // The heart rate moves all day, so it has no word against a normal; nor has a latest reading. + val status = if (m == Metric.HeartRate || latest) null else History.status(v, normal) // A percent stays on its number, as on Recovery ("99%"): the line under it is the word, not the unit. + val tag = relatedTag(m, v, status) ListRow( m.title, colorOf(m), v?.let { if (m == Metric.Spo2) "${m.format(it)}%" else m.format(it) }, when { v == null -> NO_VALUE + // Blood oxygen on a night page is the night's average. + night && m == Metric.Spo2 -> stringResource(R.string.glow_today_spo2_night_average) // A night signal whose normal is still forming says so, with the count, as on every tab. night && normal == null -> SleepCopy.learning(state, m) + // The time shows once the reading is an hour old or more. + latest -> latestLine(m, state, java.time.Instant.now().epochSecond, tagged = tag != null, time = ::clock) + // The tag already says which way it is off. + tag != null -> null else -> DetailCopy.statusWord(status) ?: m.unit.ifEmpty { null } }, - tag = org.openstrap.app.ui.dashboard.bodyTag(m, status), onClick = { onOpen(Detail.OfMetric(m, night)) }, divider = divider, + tag = tag, onClick = { onOpen(Detail.OfMetric(m, night)) }, divider = divider, icon = m.rowIcon(), ) } + +/** A related row's tag: stress is judged by the level of its reading [v] (High is tagged), the rest by [status] against their normal. */ +private fun relatedTag(m: Metric, v: Float?, status: Int?): org.openstrap.app.ui.dashboard.NewsTag? = + if (m == Metric.Stress) v?.let { LatestReading.stressTag(StressLevel.of(it)) } else org.openstrap.app.ui.dashboard.bodyTag(m, status) + +/** + * The line under [m]'s latest reading of the day in [state] (blood oxygen or stress) at [now]; null without a reading, + * or for a stress reading whose High [tagged] tag says it already and is fresh. + */ +internal fun latestLine( + m: Metric, state: DayUiState, now: Long, strings: Strings = Strings.app, tagged: Boolean = false, time: (Long) -> String, +): String? { + val at = LatestReading.of(m, state) ?: return null + return if (m == Metric.Spo2) LatestReading.spo2Line(at.x, LatestReading.sleepWindow(state), now, strings, time) + else LatestReading.stressLine(at.x, at.y, now, tagged, strings, time) +} diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt index f8b5e14c..0ca206ed 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.Alignment import androidx.compose.ui.text.style.TextOverflow import kotlin.math.roundToInt +import org.openstrap.app.presentation.StressLevel import org.openstrap.app.presentation.Units import org.openstrap.app.ui.components.cardNumber import org.openstrap.app.ui.dashboard.SleepCopy @@ -20,8 +21,7 @@ import org.openstrap.app.ui.dashboard.OffWords import org.openstrap.app.ui.dashboard.bodyOffStatus import org.openstrap.app.ui.dashboard.bodyTag import org.openstrap.app.ui.dashboard.offTag -import org.openstrap.app.ui.dashboard.stressMean -import org.openstrap.app.ui.dashboard.stressOffStatus +import org.openstrap.app.ui.dashboard.LatestReading import org.openstrap.app.ui.glow.pictures.PictureSize import org.openstrap.app.ui.glow.pictures.RangeFill import org.openstrap.app.ui.glow.pictures.SplitBar @@ -53,13 +53,13 @@ import org.openstrap.app.data.History import org.openstrap.app.data.Recovery import org.openstrap.app.data.RecoveryResult import org.openstrap.app.presentation.AFTER_FIRST_NIGHT -import org.openstrap.app.ui.dashboard.DailyHistory import org.openstrap.app.ui.dashboard.FIRST_SCORE import org.openstrap.app.ui.dashboard.PARTIAL_DAY import org.openstrap.app.ui.dashboard.Wear import org.openstrap.app.ui.dashboard.DayUiState import org.openstrap.app.ui.dashboard.InfoCopy import org.openstrap.app.ui.dashboard.Score +import org.openstrap.app.presentation.DetailCopy import org.openstrap.app.presentation.Metric import org.openstrap.app.ui.dashboard.FAILED_SHORT import org.openstrap.app.ui.dashboard.RECOVERY_FAILED @@ -90,7 +90,6 @@ import org.openstrap.app.ui.glow.draw.DotSize fun GlowRecoveryScreen( state: DayUiState, recovery: RecoveryResult?, - history: DailyHistory, /** The tab's header, or a back header when the screen is opened from a card on another tab. */ header: @Composable () -> Unit, contentPadding: PaddingValues, @@ -117,9 +116,9 @@ fun GlowRecoveryScreen( firstScore: Boolean = false, ) { val list = rememberLazyListState() - val signals = rememberSignals(state, history) - val r = recovery?.takeIf { it.date == state.date } - val failure = recoveryFailure?.takeIf { it.date == state.date && r == null } + val signals = rememberSignals(state) + val r = recovery + val failure = recoveryFailure?.takeIf { r == null } val learning = r?.readiness?.calibrating == true val firstNights = r != null && !r.charge.anchored val waiting = if (firstNights) AFTER_FIRST_NIGHT else NO_READING @@ -415,9 +414,10 @@ private fun ChargeSmall(c: Recovery.ChargeDay?, recharged: Boolean, modifier: Mo private const val DIAL_SHARE = 0.44f /** - * Skin temperature as a short Wide (spec 5.1): the change from your normal in dots with °C and its off tag at the - * left, the dial at the right centred on your normal. Off your normal the rim lights at the dial's top when above, its - * foot when below. Before there's a normal it waits for one. Opens the skin temperature detail. + * Skin temperature as a short Wide (spec 5.1): last night's average in dots with °C and its off tag at the left, the + * dial at the right centred on your normal with the change from it written in the arc. Off your normal the rim lights at the + * dial's top when above, its foot when below. Before there's a normal the line says how far along it is. Opens the skin + * temperature detail. */ @Composable private fun SkinTempCard( @@ -438,12 +438,10 @@ private fun SkinTempCard( Column(Modifier.weight(1f)) { CardTitle(stringResource(R.string.glow_recovery_skin_temperature)) Spacer(Modifier.height(12.dp)) - // Off your normal the tag says which way, and nothing under the number repeats it. + // Last night's average, as the Sleep tab shows it; the change from your normal is read in the dial. NumberWithTag(tag) { androidx.compose.foundation.layout.Row(verticalAlignment = Alignment.Bottom) { - // Against your normal once there is one; until then last night's reading, as the Sleep tab shows it. - val shown = deviation?.let { Metric.SkinTemperature.formatChange(it, Units.DOT_LOCALE) } - ?: today?.let { Metric.SkinTemperature.format(it, Units.DOT_LOCALE) } + val shown = today?.let { Metric.SkinTemperature.format(it, Units.DOT_LOCALE) } if (shown != null) DotMatrixText(shown, Modifier.cardNumber(shown), dot = DotSize.Edge) else WaitingDash(Modifier.padding(vertical = 8.dp)) if (shown != null) Text( @@ -452,11 +450,11 @@ private fun SkinTempCard( ) } } + // The change from your normal is the dial's reading; the line under the number is for when there is none. val line = when { today == null -> waiting normal == null || deviation == null -> learning ?: TodayCopy.normalWord(null) - tag != null -> null - else -> stringResource(R.string.glow_recovery_skin_close) + else -> null } if (line != null) Text( line, @@ -464,7 +462,10 @@ private fun SkinTempCard( modifier = Modifier.padding(top = 6.dp), maxLines = 2, overflow = TextOverflow.Ellipsis, ) } - TempDial(deviation, band, MetricColors.temperature, PictureSize.Wide, Modifier.fillMaxWidth(DIAL_SHARE).height(84.dp)) + TempDial( + deviation, band, MetricColors.temperature, PictureSize.Wide, Modifier.fillMaxWidth(DIAL_SHARE).height(84.dp), + reading = deviation?.let { DetailCopy.changeWithUnit(Metric.SkinTemperature, it) }, + ) } } } @@ -481,31 +482,37 @@ private class BodySignal( val tag: NewsTag?, /** What the row says while its normal is forming, "Learning, 5 of 7 nights"; null for the plain word. */ val learning: String? = null, + /** What the row says instead of a word against your normal: the night average, or when the day's latest reading was taken. */ + val line: String? = null, ) /** The Recovery tab's body signals: the rows of the list and skin temperature for its own card. */ private class Signals(val rows: List, val skin: Float?, val skinNormal: History.Normal?, val skinLearning: String?) /** - * Loads the last 30 days of each body signal, enough for its normal ([rememberNormal], keyed on the day and the - * history, each normal worked out once per load), and the signals once per day state (audit K8). Breathing rate, + * The body signals once per day state (audit K8), each night signal against its normal. Breathing rate, * blood oxygen and stress make the list (spec 5.1): HRV and resting heart rate are in What drove it already. */ @Composable -private fun rememberSignals(state: DayUiState, history: DailyHistory): Signals { - val stress = rememberNormal(Metric.Stress, state.date, history) +private fun rememberSignals(state: DayUiState): Signals { val breathName = stringResource(R.string.glow_recovery_breathing_rate) val spo2Name = stringResource(R.string.glow_recovery_blood_oxygen) val stressName = stringResource(R.string.glow_recovery_stress) - return remember(state, stress) { - fun body(metric: Metric, name: String, accent: Color, today: Float?, normal: History.Normal?, unit: String = ""): BodySignal { + val nightAverage = stringResource(R.string.glow_today_spo2_night_average) + return remember(state) { + fun body( + metric: Metric, name: String, accent: Color, today: Float?, normal: History.Normal?, unit: String = "", line: String? = null, + ): BodySignal { val direction = History.status(today, normal) return BodySignal( metric, name, accent, today?.let { metric.format(it) + unit }, direction, bodyTag(metric, direction), - SleepCopy.learning(state, metric), + SleepCopy.learning(state, metric), line, ) } - val stressToday = stressMean(state.stress) + // The row's number is the latest reading; its word is that reading's level, and only a High one is tagged. + val stressLatest = LatestReading.stress(state) + val stressTag = stressLatest?.let { LatestReading.stressTag(StressLevel.of(it.y)) } + val now = java.time.Instant.now().epochSecond Signals( listOf( // Night signals: last night's against the nights before, as the Sleep tab and their details read them. @@ -515,11 +522,12 @@ private fun rememberSignals(state: DayUiState, history: DailyHistory): Signals { ), body( Metric.Spo2, spo2Name, MetricColors.spo2, SleepCopy.nightValue(state, Metric.Spo2), - SleepCopy.nightNormal(state, Metric.Spo2), unit = "%", + SleepCopy.nightNormal(state, Metric.Spo2), unit = "%", line = nightAverage, ), BodySignal( - Metric.Stress, stressName, MetricColors.stress, stressToday?.let { Metric.Stress.format(it) }, - History.status(stressToday, stress), offTag(OffWords.Usual, stressOffStatus(state.stress, stress)), + Metric.Stress, stressName, MetricColors.stress, stressLatest?.let { Metric.Stress.format(it.y) }, + null, stressTag, + line = stressLatest?.let { LatestReading.stressLine(it.x, it.y, now, tagged = stressTag != null, time = ::clock) }, ), ), // Tonight's against the nights before (spec 2.7, Dial): the day's mean counts hours off the wrist, which @@ -531,16 +539,19 @@ private fun rememberSignals(state: DayUiState, history: DailyHistory): Signals { } } -/** Body signals against your normal, each opening its metric, its off tag in place of its word. [waiting] is what a row with no reading says. */ +/** Body signals against your normal, each opening its metric, its off tag after its line. [waiting] is what a row with no reading says. */ @Composable private fun SignalsList(signals: List, waiting: String, onOpen: (Metric) -> Unit) { ListPanel(title = stringResource(R.string.glow_recovery_body_signals), note = stringResource(R.string.glow_recovery_against_normal)) { signals.forEachIndexed { i, s -> ListRow( s.label, s.accent, s.value, + // The tag already says which way it is off, so the word against your normal gives way to it. when { s.value == null -> waiting + s.line != null -> s.line s.learning != null -> s.learning + s.tag != null -> null else -> TodayCopy.normalWord(s.direction) }, tag = s.tag, onClick = { onOpen(s.metric) }, divider = i > 0, icon = s.metric.rowIcon(), diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt index 1d02c4fb..dddde6ab 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt @@ -102,7 +102,7 @@ fun GlowSleepScreen( onRestore: (org.openstrap.app.data.db.SleepSession) -> Unit = {}, ) { val list = rememberLazyListState() - val rec = recovery?.takeIf { it.date == state.date } + val rec = recovery val breathing = rec?.breathingDisturbances // Before the strap has seen a night, cards keep their shape and wait (spec 4.3): breathing disturbances too. val firstNights = rec != null && !rec.charge.anchored && state.sleep == null @@ -181,7 +181,9 @@ private fun NightHero(state: DayUiState, firstNights: Boolean, onRestore: (org.o HeroNumber( score?.toString(), listOfNotNull( - TabCopy.sleepScoreLine(score), + TabCopy.sleepScoreLine(score).let { + if (state.sleepScoreAdjusted) stringResource(R.string.glow_sleep_score_adjusted, it) else it + }, TabCopy.woke(session.wakeCount), ), ) @@ -260,9 +262,12 @@ internal val SleepRowColors: List = DayViewModel.SLEEP_STAGE_ROWS.let { r private fun VitalsList(state: DayUiState, firstNights: Boolean, onOpen: (Metric) -> Unit) { ListPanel(title = stringResource(R.string.glow_sleep_vitals_title), note = stringResource(R.string.glow_sleep_vitals_note)) { nightVitals(state, firstNights).forEachIndexed { i, v -> + val tag = org.openstrap.app.ui.dashboard.bodyTag(v.metric, v.direction) ListRow( - v.label, v.color, v.value, v.status, - tag = org.openstrap.app.ui.dashboard.bodyTag(v.metric, v.direction), onClick = { onOpen(v.metric) }, divider = i > 0, + v.label, v.color, v.value, + // The tag already says which way it is off, so the plain word against your normal gives way to it. + v.status.takeUnless { tag != null && it == org.openstrap.app.presentation.TodayCopy.normalWord(v.direction) }, + tag = tag, onClick = { onOpen(v.metric) }, divider = i > 0, icon = v.metric.rowIcon(), ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt index bd7e357b..2ae656af 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt @@ -50,6 +50,7 @@ import org.openstrap.app.ui.components.HapticEvent import org.openstrap.app.ui.components.rememberHaptics import org.openstrap.app.ui.dashboard.DailyHistory import org.openstrap.app.ui.dashboard.DayUiState +import org.openstrap.app.ui.dashboard.LatestReading import org.openstrap.app.ui.dashboard.SleepCopy import org.openstrap.app.ui.dashboard.Tier import org.openstrap.app.ui.dashboard.lookOr @@ -207,7 +208,7 @@ fun GlowTodayScreen( val now = Instant.now() val isToday = state.date == now.atZone(zone).toLocalDate() org.openstrap.app.ui.components.HoldLiveHeartRate(isToday) - val rec = recovery?.takeIf { it.date == state.date } + val rec = recovery val lastWorkout = workouts.maxByOrNull { it.end } val ctx = TodayContext( state, rec, liveHeartRate, workouts, lastWorkout, isToday, now.epochSecond, zone, moment, @@ -216,7 +217,7 @@ fun GlowTodayScreen( stuck = strap.paired && syncStuck(isToday, state.asleepSeconds != null, strap.record.failingSince, now.epochSecond, zone), strapScore = strapScore, stopped = strap.stopped, staleAfter = strap.staleAfter, - recoveryFailure = recoveryFailure?.takeIf { it.date == state.date && rec == null }, + recoveryFailure = recoveryFailure?.takeIf { rec == null }, partial = partialTag.takeIf { wear?.partial == true }, firstScore = firstScore, ) @@ -785,16 +786,25 @@ private fun TodayRow( BodyRow( stringResource(R.string.glow_today_resting_hr), MetricColors.heart, s.restingHeartRate?.toFloat(), normal(Metric.RestingHr), "", Metric.RestingHr, + source = if (s.restingEstimated) BodyValue.Estimated else BodyValue.Plain, ), // Night signals: last night's against the nights before, as the Sleep tab and their details read them. BodyRow( stringResource(R.string.glow_today_hrv), MetricColors.hrv, SleepCopy.nightValue(s, Metric.Hrv), SleepCopy.nightNormal(s, Metric.Hrv), "", Metric.Hrv, SleepCopy.learning(s, Metric.Hrv), ), - BodyRow( - stringResource(R.string.glow_today_blood_oxygen), MetricColors.spo2, SleepCopy.nightValue(s, Metric.Spo2), - SleepCopy.nightNormal(s, Metric.Spo2), "%", Metric.Spo2, SleepCopy.learning(s, Metric.Spo2), - ), + // Blood oxygen leads with the day's latest reading, said as daytime or asleep, with its time once an hour + // old. A single reading has no normal, so the row has no tag; the night's average, with its tag, is + // on the Sleep and Recovery tabs. + LatestReading.spo2(s).let { latest -> + BodyRow( + stringResource(R.string.glow_today_blood_oxygen), MetricColors.spo2, latest?.y, + null, "%", Metric.Spo2, + source = BodyValue.Latest( + latest?.let { LatestReading.spo2Line(it.x, LatestReading.sleepWindow(s), ctx.now, time = ::clock) }.orEmpty(), + ), + ) + }, BodyRow( stringResource(R.string.glow_today_breathing_rate), MetricColors.sleepLight, SleepCopy.nightValue(s, Metric.Breathing), SleepCopy.nightNormal(s, Metric.Breathing), "", Metric.Breathing, SleepCopy.learning(s, Metric.Breathing), @@ -807,12 +817,11 @@ private fun TodayRow( else LastNightCard(s, ctx.firstNights, onOpenSleep, modifier, stuck = ctx.stuck, size = size) // A live reading is never stale. TodayCard.HeartRate -> HeartDayCard( - s, ctx.live, size, { onOpenMetric(Metric.HeartRate) }, modifier, restingRange = ctx.restingRange, normal = normal(Metric.HeartRate), + s, ctx.live, size, { onOpenMetric(Metric.HeartRate) }, modifier, restingRange = ctx.restingRange, upTo = if (ctx.live == null) ctx.upTo(s.heartRate.lastOrNull()?.x) else null, ) TodayCard.Stress -> StressDayCard( - s, size, normal(Metric.Stress), ctx.waiting, { onOpenMetric(Metric.Stress) }, modifier, - upTo = ctx.upTo(s.stress.lastOrNull()?.x), + s, size, ctx.waiting, { onOpenMetric(Metric.Stress) }, modifier, now = ctx.now, ) // Steps come in the same records as the rest of the day, so the day's newest reading is how far they go. The // count stays in dots in the evening too, under the hero's: the goal tag needs a number to sit by (spec 2.5). diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt index 404e66a0..d5493b77 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt @@ -5,6 +5,7 @@ import android.provider.Settings import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth @@ -13,6 +14,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Icon +import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -35,6 +37,8 @@ import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import org.openstrap.app.OpenStrapApp import org.openstrap.app.R import org.openstrap.app.data.SportSettings import org.openstrap.app.data.Strength @@ -230,6 +234,7 @@ fun GlowWorkoutReadyScreen( RoundIcon(AppIcons.X, stringResource(R.string.glow_close), onBack, Modifier.align(Alignment.CenterStart)) Box(Modifier.align(Alignment.Center)) { IconPill(Workouts.shortName(type), { picking = true }, caret = true) } } + StrapHeldNotice(connection) if (cardio) { ReadyHeartCard(connection, liveHeartRate) ReadyWhere( @@ -340,6 +345,29 @@ internal fun MinusPlus( } } +/** + * When the strap is away because you disconnected it, nothing reconnects it on its own (starting a workout doesn't): + * says so and offers Connect, which is an explicit connect. Nothing shows while it is connected, connecting, or away + * for any other reason. + */ +@Composable +private fun StrapHeldNotice(connection: ConnectionState) { + val container = (LocalContext.current.applicationContext as? OpenStrapApp)?.container ?: return + val held by container.settings.heldDisconnected.collectAsStateWithLifecycle(false) + val away = connection == ConnectionState.Disconnected || connection == ConnectionState.BluetoothOff || + connection is ConnectionState.Failed + if (!held || !away) return + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text( + stringResource(R.string.glow_ready_strap_disconnected), + color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, + ) + PageButton( + stringResource(R.string.glow_ready_connect), container.strap::connect, Modifier.fillMaxWidth(), icon = AppIcons.Bluetooth, + ) + } +} + /** The strap in one line with its dot, on Choose: "Strap ready, 72 bpm". */ @Composable internal fun StrapLine(connection: ConnectionState, liveHeartRate: Int?) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt index 3d19ba1d..b375ad29 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt @@ -16,8 +16,6 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.SideEffect import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -28,7 +26,9 @@ import org.openstrap.app.presentation.chargeShown import org.openstrap.app.data.DailyMetric import org.openstrap.app.data.Recovery import org.openstrap.app.data.RecoveryResult +import org.openstrap.app.ui.components.dayHeld import org.openstrap.app.ui.components.detailNumber +import org.openstrap.app.ui.components.rememberDayHold import org.openstrap.app.ui.dashboard.ActivityHistory import org.openstrap.app.ui.dashboard.DailyHistory import org.openstrap.app.ui.dashboard.DayUiState @@ -44,7 +44,6 @@ import org.openstrap.app.presentation.TabCopy import org.openstrap.app.presentation.TodayCopy import org.openstrap.app.ui.theme.MetricColors import java.time.LocalDate -import kotlinx.coroutines.delay import java.time.LocalTime import org.openstrap.app.ui.glow.draw.DotSize import org.openstrap.app.ui.glow.pictures.PictureSize @@ -72,6 +71,7 @@ fun GlowScoreDetailScreen( onSelectDay: (LocalDate) -> Unit, contentPadding: PaddingValues, onBack: () -> Unit, + modifier: Modifier = Modifier, /** For the Activity details: the workouts, each day's Heart points and stored calories, and the way to the profile. */ workouts: List = emptyList(), activity: ActivityHistory = ActivityHistory(), @@ -84,11 +84,12 @@ fun GlowScoreDetailScreen( val r = recovery?.takeIf { it.date == state.date } // The day shown failed, so its result is never coming: nothing is held for it. val failed = recoveryFailure?.date == state.date - // Recovery, Load and Active minutes are read from the day's result, which takes a moment to work out on another - // day. Until it comes, their page stays on the last day's, so it moves to the next instead of emptying and filling; - // the strip follows the tap at once. Energy holds its own, with its curve. The strap's score is held with its day, - // as it stands in for Recovery while the score is learning: else the held page would lose its number meanwhile. - val held = rememberHeld(r?.let { HeldDay(state, it, strapScore) }, state.date, failed) + // Recovery, Energy, Load and Active minutes are read from the day's result, which takes a moment to work out on + // another day. For a moment their page stays on the last day's, dimmed, so a quick day doesn't flash; then the + // placeholder, never another day's numbers for long ([rememberDayHold]). The strip follows the tap at once. The + // strap's score is held with its day, as it stands in for Recovery while the score is learning. + val hold = rememberDayHold(r?.let { HeldDay(state, it, strapScore) }, state.date, failed) + val held = hold.value val heldState = held?.state ?: state val heldR = held?.result val heldStrapScore = if (held != null) held.strapScore else strapScore @@ -96,19 +97,24 @@ fun GlowScoreDetailScreen( s, result, workouts, activity, history, onOpen, onSwitch, onSelectDay, onEditProfile, contentPadding, onBack, stripDate = state.date, ) - when (score) { + Box(modifier.dayHeld(hold.pending && score in HELD_SCORES)) { when (score) { Score.Recovery -> RecoveryDetail( heldState, heldR, heldStrapScore, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack, state.date, ) - Score.Energy -> ChargeDetail(state, r, failed, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) + Score.Energy -> ChargeDetail( + held?.state ?: state, heldR, state.date, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack, + ) Score.Sleep -> SleepScoreDetail(state, r, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack, sleepEditing) Score.Regularity -> RegularityDetail(state, r, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) Score.Naps -> NapsDetail(state, r, onOpen, onSwitch, onSelectDay, contentPadding, onBack, sleepEditing) Score.ActiveMinutes, Score.Load -> ActivityScoreDetail(score, activityOf(heldState, heldR)) Score.HeartPoints, Score.Vo2Max, Score.Recover, Score.Calories, Score.Distance -> ActivityScoreDetail(score, activityOf(state, r)) - } + } } } +/** The details whose page is held for a moment on a day switch ([rememberDayHold]). */ +private val HELD_SCORES = setOf(Score.Recovery, Score.Energy, Score.ActiveMinutes, Score.Load) + /** The days a metric has data for, from the day after [from] to [to]; none when [from] isn't before [to]. */ @Composable internal fun daysWithData(metric: DailyMetric, from: LocalDate, to: LocalDate, history: DailyHistory): Set { @@ -259,14 +265,10 @@ private const val SHORT_CURVE_HOURS = 3f */ @Composable private fun ChargeDetail( - liveState: DayUiState, liveR: RecoveryResult?, failed: Boolean, history: DailyHistory, + state: DayUiState, r: RecoveryResult?, stripDate: LocalDate, history: DailyHistory, onOpen: (Detail) -> Unit, onSwitch: (Detail) -> Unit, onSelectDay: (LocalDate) -> Unit, contentPadding: PaddingValues, onBack: () -> Unit, ) { - // Another day's Energy takes a moment to work out. Until it is, the last one stays up, so the page moves from one day's - // to the next instead of emptying and filling; the strip follows the tap at once. A day that [failed] isn't waited for. - val held = rememberHeld(liveR?.let { liveState to it }, liveState.date, failed) - val state = held?.first ?: liveState - val r = held?.second + // [state] and [r] are the day held for a moment by [ScoreDetail] ([rememberDayHold]); the strip follows [stripDate]. val c = r?.charge val now = c?.latest?.let(::chargeShown) val atWake = c?.atWake?.toInt() @@ -276,7 +278,7 @@ private fun ChargeDetail( var scrub by remember(state.date) { mutableStateOf(null) } var info by rememberSaveable { mutableStateOf(false) } // Charge runs on heart rate, so the days with heart rate are the days with a Charge. - val strip = DetailCopy.strip(liveState.date, today, emptySet()) + val strip = DetailCopy.strip(stripDate, today, emptySet()) val withData = daysWithData(DailyMetric.HeartRate, strip.first().date.minusDays(1), strip.last().date, history) // The latest Charge is where the curve ends, which can be well before now while the strap catches up. val lastAt = c?.points?.lastOrNull { it.state != Recovery.State.NoData }?.t @@ -305,7 +307,7 @@ private fun ChargeDetail( DetailTemplate( Score.Energy.title, color, siblings(Detail.OfScore(Score.Energy), onSwitch), onInfo = { info = true }, onBack = onBack, contentPadding = contentPadding, headline = headline, - strip = DetailCopy.strip(liveState.date, today, withData), onDay = onSelectDay, + strip = DetailCopy.strip(stripDate, today, withData), onDay = onSelectDay, ranges = listOf(Range.Day), range = Range.Day, onRange = {}, scrubbed = { scrub }, // The figures are the held day's, so they move when it does, not with the strip. headlineDay = state.date, @@ -363,31 +365,7 @@ private fun ChargeDetail( ) } -/** - * [value] while there is one, else the last there was, so a day that is slow to work out is waited for. Not when the - * day [failed]: its value is never coming, so it lets go at once rather than leave another day's page up. Not past - * [HOLD_MS] either, for a day that never comes without a failure saying so. Null before the first. - */ -@Composable -private fun rememberHeld(value: T?, day: LocalDate, failed: Boolean): T? { - val last = remember { Last() } - var gaveUp by remember(day) { mutableStateOf(false) } - LaunchedEffect(day, value == null) { - gaveUp = false - if (value == null) { - delay(HOLD_MS) - gaveUp = true - } - } - SideEffect { if (value != null) last.value = value } - return value ?: last.value.takeUnless { gaveUp || failed } -} - -private const val HOLD_MS = 4_000L - -private class Last { var value: T? = null } - -/** A day's page as [rememberHeld] keeps it: the day, its result, and the strap's own score for its night. */ +/** A day's page as [rememberDayHold] keeps it: the day, its result, and the strap's own score for its night. */ private class HeldDay(val state: DayUiState, val result: RecoveryResult, val strapScore: Int?) /* ---------------------------------------------- Related --------------------------------------------- */ @@ -413,7 +391,7 @@ private fun ScoreRelated(score: Score, state: DayUiState, r: RecoveryResult?, hi stringResource(if (asleep == null) R.string.glow_recovery_no_sleep else R.string.glow_recovery_asleep), onClick = { onOpen(Detail.OfScore(Score.Sleep)) }, icon = Score.Sleep.rowIcon(), ) - metrics.forEach { m -> RelatedMetricRow(m, state, history, divider = true, onOpen) } + metrics.forEach { m -> RelatedMetricRow(m, state, history, divider = true, onOpen, nightScoped = true) } } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt index 3b0af06a..a2ae7b14 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt @@ -42,6 +42,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Color @@ -85,6 +86,25 @@ private val PhotoRoom = 64.dp /** How long "Saved" stays on the button. */ private const val SAVED_MS = 2_000L +/** + * The photo behind the card: none picked, being read (Save waits, or the card would export without it), ready, or + * unreadable. Ready and Failed remember which [uri] they answer, so a newer pick reads as Loading at once. + */ +internal sealed interface SharePhoto { + data object None : SharePhoto + data object Loading : SharePhoto + data class Ready(val uri: Uri, val bitmap: ImageBitmap) : SharePhoto + data class Failed(val uri: Uri) : SharePhoto +} + +/** What to show for the picked [uri], given the latest [decoded] answer (which may still be for an earlier pick). */ +internal fun sharePhotoFor(uri: Uri?, decoded: SharePhoto): SharePhoto = when { + uri == null -> SharePhoto.None + decoded is SharePhoto.Ready && decoded.uri == uri -> decoded + decoded is SharePhoto.Failed && decoded.uri == uri -> decoded + else -> SharePhoto.Loading +} + /** What the card is being drawn for. */ private enum class Export { Save, Share } @@ -132,7 +152,14 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str } val context = LocalContext.current var photoUri by rememberSaveable { mutableStateOf(null) } - val photo by produceState(null, photoUri) { value = photoUri?.let { decodePhoto(context, it) } } + val decoded by produceState(SharePhoto.None, photoUri) { + value = photoUri?.let { uri -> + decodePhoto(context, uri)?.let { SharePhoto.Ready(uri, it) } ?: SharePhoto.Failed(uri) + } ?: SharePhoto.None + } + val photoState = sharePhotoFor(photoUri, decoded) + val photo = (photoState as? SharePhoto.Ready)?.bitmap + val canExport = photoState !is SharePhoto.Loading var routeMode by rememberSaveable { mutableStateOf(StoryRoute.Line) } var hideEnds by rememberSaveable { mutableStateOf(true) } val hasRoute = card is StoryCard.Run && Route.mappable(route) @@ -143,7 +170,8 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str // Save and Share draw the card again off screen at 1080 by 1920, record it, and turn the recording into a PNG. var export by remember { mutableStateOf(null) } - var saved by remember { mutableStateOf(null) } + // Saveable: a turn of the phone while the picture is written keeps the answer to show. + var saved by rememberSaveable { mutableStateOf(null) } val layer = rememberGraphicsLayer() val recorded = remember(export) { CompletableDeferred() } fun save() { @@ -186,10 +214,16 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str null -> R.string.glow_save }, ) - WorkoutButton(saveLabel, Raised, Color.White, { if (export == null) save() }, Modifier.weight(1f), icon = if (saved == true) AppIcons.Tick02 else AppIcons.DownloadSimple) + // Not while the photo is still being read (the card would save without it) or another export is running. + val ready = canExport && export == null + val dim = Modifier.alpha(if (canExport) 1f else 0.4f) + WorkoutButton( + saveLabel, Raised, Color.White, { if (ready) save() }, Modifier.weight(1f).then(dim), + icon = if (saved == true) AppIcons.Tick02 else AppIcons.DownloadSimple, + ) WorkoutButton( - stringResource(R.string.glow_share), Color.White, Color.Black, { if (export == null) export = Export.Share }, - Modifier.weight(1f), icon = AppIcons.UploadSimple, + stringResource(R.string.glow_share), Color.White, Color.Black, { if (ready) export = Export.Share }, + Modifier.weight(1f).then(dim), icon = AppIcons.UploadSimple, ) } }, @@ -231,6 +265,13 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str stringResource(if (photo != null) R.string.glow_share_change_photo else R.string.glow_share_add_photo), { pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }, icon = AppIcons.Image, ) + if (photoState is SharePhoto.Failed) { + Text( + stringResource(R.string.glow_share_photo_failed), + color = Color.White.copy(alpha = 0.6f), style = GlowType.secondary, + modifier = Modifier.padding(top = 8.dp), + ) + } } } if (hasRoute) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt index 02c203e5..6903c5d2 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt @@ -25,6 +25,8 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf @@ -50,6 +52,7 @@ import org.openstrap.app.data.Recovery import org.openstrap.app.data.RecoveryResult import org.openstrap.app.data.SleepEdits import org.openstrap.app.data.SleepHistory +import org.openstrap.app.data.HeartReadings import org.openstrap.app.data.Summaries import org.openstrap.app.data.db.SleepSession import org.openstrap.app.data.wasoMinutes @@ -136,10 +139,18 @@ internal fun SleepScoreDetail( val session = state.sleep val score = session?.score val color = MetricColors.sleepDeep - var adjusting by remember(state.date) { mutableStateOf(false) } - var deleting by remember(state.date) { mutableStateOf(false) } - // The strap's session just deleted, while its Undo shows. - var undo by remember { mutableStateOf(null) } + // Saveable, so turning the phone doesn't close the sheet being used. + var adjusting by rememberSaveable(state.date) { mutableStateOf(false) } + var deleting by rememberSaveable(state.date) { mutableStateOf(false) } + // The strap's session just asked to be deleted, and once the day shows it gone, the same session while its Undo + // shows. Both are for this day only, so Undo never names another day, and Undo is never offered for a delete that + // didn't happen. + var pendingDelete by remember(state.date) { mutableStateOf(null) } + var undo by remember(state.date) { mutableStateOf(null) } + SideEffect { + val gone = pendingDelete ?: return@SideEffect + if (session == null) { undo = gone; pendingDelete = null } + } // TODO(step 6): Month and Year wait for a stored history of the strap's sleep scores; the day loads only 14 nights. val ranges = listOf(Range.Day, Range.Week) var rangeIndex by rememberSaveable { mutableIntStateOf(0) } @@ -160,9 +171,13 @@ internal fun SleepScoreDetail( DetailHeadline(Math.round(known.average()).toString(), stringResource(R.string.glow_sleep_week_average), null) range == Range.Week -> DetailHeadline.none(stringResource(R.string.glow_sleep_no_scores), stringResource(R.string.glow_sleep_in_last_7_nights)) - score != null -> DetailHeadline(score.toString(), SleepCopy.scoreLabel(isToday), TabCopy.sleepScoreWord(score)) + score != null -> DetailHeadline( + score.toString(), SleepCopy.scoreLabel(isToday, state.sleepScoreAdjusted), TabCopy.sleepScoreWord(score), + ) session == null && state.deletedSleep != null -> DetailHeadline.none(stringResource(R.string.glow_sleep_no_score), SleepCopy.noScoreDeleted(isToday)) + // The day's rows haven't arrived: nothing yet, not "No score". + !state.loaded -> DetailHeadline.none("", "") else -> SleepCopy.noScore(session != null, isToday).let { (word, why) -> DetailHeadline.none(word, why) } } @@ -184,7 +199,8 @@ internal fun SleepScoreDetail( if (session == null && deleted != null) { item { DeletedNight(SleepCopy.deletedNight(clock(deleted.start), clock(deleted.end), isToday)) { editing.restore(deleted.strap) } } } else if (session == null) { - item { DetailEmpty(TabCopy.noNight(state.naps.isNotEmpty(), isToday)) } + // Not before the day has loaded: an empty state isn't "No night". + if (state.loaded) item { DetailEmpty(TabCopy.noNight(state.naps.isNotEmpty(), isToday)) } } else { val asleep = state.asleepSeconds ?: (session.end - session.start) val detected = state.sleepAsDetected @@ -276,7 +292,7 @@ internal fun SleepScoreDetail( ) if (deleting && session != null && detected != null) DeleteSleepSheet( SleepCopy.deleteTitle(false, isToday), Ranges.of(clock(session.start), clock(session.end)), - onDelete = { deleting = false; editing.delete(detected); undo = detected }, onDismiss = { deleting = false }, + onDelete = { deleting = false; editing.delete(detected); pendingDelete = detected }, onDismiss = { deleting = false }, ) } @@ -438,7 +454,12 @@ private fun NightLines(state: DayUiState, window: LongRange, onScrub: (DetailHea if (hr.isNotEmpty()) { ChartTitle( stringResource(R.string.glow_sleep_heart_rate), - stringResource(R.string.glow_sleep_heart_note, hr.minOf { it.y }.toInt(), hr.map { it.y }.average().toInt()), + // The lowest stored reading and the night's average, as the Sleep tab says them; not the line's 5-minute averages. + stringResource( + R.string.glow_sleep_heart_note, + SleepCopy.lowestHeart(state)?.y?.let(Math::round) ?: Math.round(hr.minOf { it.y }), + SleepCopy.averageHeart(state) ?: Math.round(hr.map { it.y }.average()).toInt(), + ), scrubbed = hrAt, ) ScrubLine(hr, window, 130.dp, labels, MetricColors.heart, stringResource(R.string.glow_unit_bpm)) { hrAt = it; onScrub(it) } @@ -553,10 +574,16 @@ internal fun NapsDetail( ) { val naps = state.naps.sortedBy { it.start } // The nap whose times are being adjusted, or that's being deleted, by its start as shown. - var adjusting by remember(state.date) { mutableStateOf(null) } - var deleting by remember(state.date) { mutableStateOf(null) } - // The strap's nap just deleted and its start as shown, while its Undo shows. - var undo by remember { mutableStateOf?>(null) } + var adjusting by rememberSaveable(state.date) { mutableStateOf(null) } + var deleting by rememberSaveable(state.date) { mutableStateOf(null) } + // As in the Sleep score: the nap asked to be deleted with its start as shown, then, once the day no longer has it, + // the same while its Undo shows. For this day only. + var pendingDelete by remember(state.date) { mutableStateOf?>(null) } + var undo by remember(state.date) { mutableStateOf?>(null) } + SideEffect { + val gone = pendingDelete ?: return@SideEffect + if (state.napsAsDetected[gone.second] == null) { undo = gone; pendingDelete = null } + } val total = naps.sumOf { it.end - it.start } val color = MetricColors.sleepDeep val today = LocalDate.now() @@ -630,6 +657,9 @@ internal fun NapsDetail( // The strap sends no average for a nap, so its heart rate is the day's readings in its window. val window = nap.start..nap.end val hr = remember(state.heartRate, window) { state.heartRate.filter { it.x in window } } + val minutes = remember(state.heartMinutes, window) { + HeartReadings.within(state.heartMinutes, window.first, window.last) + } if (hr.isNotEmpty()) { Box(Modifier.padding(top = 16.dp)) { ScrubLine( @@ -637,7 +667,12 @@ internal fun NapsDetail( stringResource(R.string.glow_unit_bpm), ) { scrub = it } } - Caption(SleepCopy.napHeart(hr.minOf { it.y }.toInt(), hr.map { it.y }.average().toInt()), Modifier.padding(top = 6.dp, bottom = 8.dp)) + // The nap's lowest and average from the stored readings, not the line's averages. + val low = HeartReadings.lowest(minutes)?.second + val average = HeartReadings.mean(minutes) + if (low != null && average != null) { + Caption(SleepCopy.napHeart(low, average), Modifier.padding(top = 6.dp, bottom = 8.dp)) + } } } } @@ -665,7 +700,8 @@ internal fun NapsDetail( if (nap == null || detected == null) androidx.compose.runtime.SideEffect { deleting = null } else DeleteSleepSheet( SleepCopy.deleteTitle(true, isToday), Ranges.of(clock(nap.start), clock(nap.end)), - onDelete = { deleting = null; editing.delete(detected); undo = detected to nap.start }, onDismiss = { deleting = null }, + onDelete = { deleting = null; editing.delete(detected); pendingDelete = detected to nap.start }, + onDismiss = { deleting = null }, ) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt index 24f854a5..866b0487 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/TodayCards.kt @@ -7,6 +7,7 @@ import androidx.compose.ui.res.pluralStringResource import org.openstrap.app.i18n.Strings import org.openstrap.app.presentation.DayWords import org.openstrap.app.presentation.Ranges +import org.openstrap.app.presentation.StressLevel import org.openstrap.app.presentation.Units import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement @@ -471,12 +472,15 @@ internal fun HeartCard( MetricColors.heart, modifier.fillMaxWidth().gridSize(CardSize.Wide), onClick = onClick, ) { EdgeTitle( - stringResource(R.string.glow_today_heart_rate), state.restingHeartRate?.let { stringResource(R.string.glow_today_resting, it) }, + stringResource(R.string.glow_today_heart_rate), restingNote(state), marker = upTo, ) val at = scrubbed?.second ?: state.heartRate.lastOrNull()?.x EdgeValue( - now?.toString(), stringResource(R.string.glow_unit_bpm), TodayCopy.heartAt(live != null && scrubbed == null, at?.let(::clock)), + now?.toString(), stringResource(R.string.glow_unit_bpm), + // A held point is the average of a 10-minute stretch, not one reading. + if (scrubbed != null) stringResource(R.string.core_today_heart_average_from, step / SECONDS_PER_MINUTE, clock(scrubbed.second)) + else TodayCopy.heartAt(live != null, at?.let(::clock)), ) if (state.heartRate.size >= 2) { Spacer(Modifier.height(10.dp)) @@ -494,60 +498,60 @@ internal fun HeartCard( /** * Heart rate on Today (spec 4.2): the day's line through your resting range ([restingRange], your normal resting - * heart rate) as a dim band, the latest reading or the [live] one in dots. Off your [normal] heart rate for a day, the - * day so far running high or low, the card rims at the line's end and says Above or Below normal. One high reading - * isn't news, a day running high is. No scrub here: that lives on Activity's Wide and in the detail. + * heart rate) as a dim band, the latest reading or the [live] one in dots. A reading moves all day, so the card has no + * tag and no rim; resting heart rate carries its own. No scrub here: that lives on Activity's Wide and in the detail. */ @Composable internal fun HeartDayCard( state: DayUiState, live: Int?, size: PictureSize, onClick: () -> Unit, modifier: Modifier = Modifier, - restingRange: org.openstrap.app.data.History.Normal? = null, normal: org.openstrap.app.data.History.Normal? = null, - upTo: String? = null, + restingRange: org.openstrap.app.data.History.Normal? = null, upTo: String? = null, ) { val values = remember(state.heartRate, state.dayStart, state.dayEnd) { bucket(state.heartRate, state.dayStart..state.dayEnd, HEART_STEP) } - val mean = remember(values) { values.filterNotNull().takeIf { it.isNotEmpty() }?.average()?.toFloat() } val now = live ?: state.latestHeartRate - val off = bodyOffStatus(mean, normal) val at = TodayCopy.heartAt(live != null, state.heartRate.lastOrNull()?.x?.let(::clock)) TodayPictureCard( MetricColors.heart, stringResource(R.string.glow_today_heart_rate), size, now?.toString(), stringResource(R.string.glow_unit_bpm), - offTag(OffWords.Normal, off), - // A Small says where the day sits against your normal once there is one, a Wide when the reading was taken. - if (size == PictureSize.Small && normal != null && mean != null && !off.off) TodayCopy.normalWord(0) else at, - modifier, note = state.restingHeartRate?.let { stringResource(R.string.glow_today_resting, it) }, - rim = if (rimLit(OffWords.Normal, off)) dayLineRim(values, off == OffStatus.Above, size) else null, + // The "Up to" marker already says when the line ends. + null, at.takeIf { upTo == null }, + modifier, note = restingNote(state), onClick = onClick, marker = upTo, picture = if (state.heartRate.size < 2) null else { m -> DayLine(values, restingRange?.let { it.low..it.high }, MetricColors.heart, size, m) }, ) } +/** The heart rate cards' note on the title row: the day's resting heart rate, marked as an estimate when the strap sent none. */ +@Composable +@ReadOnlyComposable +internal fun restingNote(state: DayUiState): String? = state.restingHeartRate?.let { + stringResource(if (state.restingEstimated) R.string.glow_today_resting_estimated else R.string.glow_today_resting, it) +} + /** Heart rate's line on Today: a point every ten minutes. */ private const val HEART_STEP = 10 * 60L +private const val SECONDS_PER_MINUTE = 60L /** * Stress on Today (spec 4.2): the day as one strip, calm to high ([DayStrip], [DayUiState.stressStrip]), the latest - * reading in dots. The day so far against your [normal] stress says Above or Below usual, with the rim over the - * stretch that's off. + * reading in dots with its level under it ([StressLevel]). Only a High latest reading tags the card "High", with the + * rim over the strip's latest stretch; the other levels carry neither. */ @Composable internal fun StressDayCard( - state: DayUiState, size: PictureSize, normal: org.openstrap.app.data.History.Normal?, waiting: String, onClick: () -> Unit, - modifier: Modifier = Modifier, upTo: String? = null, + state: DayUiState, size: PictureSize, waiting: String, onClick: () -> Unit, + modifier: Modifier = Modifier, now: Long = java.time.Instant.now().epochSecond, ) { - val off = org.openstrap.app.ui.dashboard.stressOffStatus(state.stress, normal) val levels = state.stressStrip - val now = state.stress.lastOrNull() + val latest = org.openstrap.app.ui.dashboard.LatestReading.stress(state) + val tag = latest?.let { org.openstrap.app.ui.dashboard.LatestReading.stressTag(StressLevel.of(it.y)) } TodayPictureCard( - MetricColors.stress, stringResource(R.string.glow_today_stress), size, now?.y?.roundToInt()?.toString(), null, - offTag(OffWords.Usual, off), + MetricColors.stress, stringResource(R.string.glow_today_stress), size, latest?.y?.roundToInt()?.toString(), null, + tag, when { - now == null -> waiting - // Off, the tag says how it's going and the line when it was read. - off.off -> TodayCopy.heartAt(false, clock(now.x)) - normal == null -> TodayCopy.normalWord(null) - else -> TodayCopy.normalWord(0) + latest == null -> waiting + // The number is the latest reading, whenever it was taken: its level, with the time once it is an hour old. + else -> org.openstrap.app.ui.dashboard.LatestReading.stressLine(latest.x, latest.y, now, tagged = tag != null, time = ::clock) }, - modifier, rim = if (rimLit(OffWords.Usual, off)) dayStripRim(levels, size) else null, onClick = onClick, marker = upTo, + modifier, rim = if (tag != null) dayStripRim(levels, size) else null, onClick = onClick, picture = if (levels.none { it != null }) null else { m -> DayStrip(levels, MetricColors.stress, size, m) }, ) } @@ -868,8 +872,25 @@ internal class BodyRow( val name: String, val color: Color, val value: Float?, val normal: org.openstrap.app.data.History.Normal?, val unit: String, val metric: Metric, /** What the row says while its normal is forming, "Learning, 5 of 7 nights"; null for the plain word. */ val learning: String? = null, + /** Where [value] comes from, when it isn't a plain figure read against [normal]. */ + val source: BodyValue = BodyValue.Plain, ) +/** What a [BodyRow]'s value is. */ +internal sealed interface BodyValue { + /** The day's figure, read against your normal. */ + data object Plain : BodyValue + + /** unstrap's own estimate, which the row says. */ + data object Estimated : BodyValue + + /** + * The day's latest reading: the row says [line] (when it was taken, awake or asleep) instead of a word against your + * normal, and it has no tag or direction, since a single reading has no baseline of its own. + */ + data class Latest(val line: String) : BodyValue +} + /** * Body values against your normal, each opening its metric, read and rounded as the Recovery tab's body signals are. * [waiting] is what an empty row says. @@ -880,15 +901,23 @@ internal fun BodyList( ) { ListPanel(modifier, title = title, note = stringResource(R.string.glow_today_against_normal), marker = upTo) { rows.forEachIndexed { i, r -> - val direction = org.openstrap.app.data.History.status(r.value, r.normal) + val source = r.source + val direction = if (source is BodyValue.Latest) null else org.openstrap.app.data.History.status(r.value, r.normal) + val tag = org.openstrap.app.ui.dashboard.bodyTag(r.metric, direction) ListRow( r.name, r.color, r.value?.let { r.metric.format(it) + r.unit }, + // The tag already says which way it is off, so the word against your normal gives way to it. when { r.value == null -> waiting + source is BodyValue.Latest -> source.line r.normal == null && r.learning != null -> r.learning + source == BodyValue.Estimated -> + if (tag != null) stringResource(R.string.glow_today_estimated) + else stringResource(R.string.glow_today_body_estimated, TodayCopy.normalWord(direction)) + tag != null -> null else -> TodayCopy.normalWord(direction) }, - tag = org.openstrap.app.ui.dashboard.bodyTag(r.metric, direction), onClick = { onOpenMetric(r.metric) }, divider = i > 0, + tag = tag, onClick = { onOpenMetric(r.metric) }, divider = i > 0, icon = r.metric.rowIcon(), ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt index d265e806..0eda9109 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt @@ -199,6 +199,7 @@ internal fun LiveFrame( if (!connected && !r.paused) { PageNote(WorkoutCopy.STRAP_GONE_NOTE) } + if (r.endFailed) NotSavedNotice(controls.onEnd) r.endPrompt?.let { at -> StoppedPrompt(r, at, controls.onEndAtPrompt, controls.onKeepGoing) } if (!fill || r.paused) Spacer(Modifier.weight(1f)) FrameControls(r, controls, lap, labelled, paused != null, quiet, tapHint) @@ -245,6 +246,7 @@ private fun ColumnScope.LandscapePanes( // Beside a shared bar the moving time stays over the page, as it is upright. if (bar && time != null) MovingTime(time) if (!bar && !connected && !r.paused) PageNote(WorkoutCopy.STRAP_GONE_NOTE) + if (!bar && r.endFailed) NotSavedNotice(controls.onEnd) if (!bar) r.endPrompt?.let { at -> StoppedPrompt(r, at, controls.onEndAtPrompt, controls.onKeepGoing) } if (r.paused && paused != null) paused() else content() } @@ -442,6 +444,7 @@ internal fun LiveBottomBar( val density = androidx.compose.ui.platform.LocalDensity.current val items: @Composable ColumnScope.() -> Unit = { if (!connected) PageNote(WorkoutCopy.STRAP_GONE_NOTE) + if (r.endFailed) NotSavedNotice(controls.onEnd) r.endPrompt?.let { at -> StoppedPrompt(r, at, controls.onEndAtPrompt, controls.onKeepGoing) } val at = position() val view = stringResource(R.string.workout_live_view_of, kotlin.math.round(at).toInt() + 1, count) @@ -533,6 +536,16 @@ internal fun FlatButton(container: Color, size: Dp, modifier: Modifier = Modifie ) { content() } } +/** End was tried and couldn't save: the workout records on, and Try again runs End again. */ +@Composable +internal fun NotSavedNotice(onTryAgain: () -> Unit) { + QuietPanel { + GlowHeader(stringResource(R.string.workout_live_not_saved_title)) + PageNote(stringResource(R.string.workout_live_not_saved_note)) + WorkoutButton(stringResource(R.string.workout_live_try_again), Color.White, Color.Black, onTryAgain) + } +} + /** "Looks like you've stopped": end where the wearer stopped, or keep going. The strap has buzzed already. */ @Composable internal fun StoppedPrompt(r: WorkoutState.Recording, at: Long, onEnd: () -> Unit, onKeep: () -> Unit) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt index 8009b514..a9243975 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/pictures/LinePictures.kt @@ -15,9 +15,12 @@ import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.clipPath +import androidx.compose.ui.text.drawText +import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import org.openstrap.app.presentation.StageSpan +import org.openstrap.app.ui.glow.GlowType import org.openstrap.app.ui.glow.Rim import org.openstrap.app.ui.glow.draw.ChartInk import org.openstrap.app.ui.glow.draw.stageColor @@ -31,9 +34,9 @@ import kotlin.math.sin /* * The line-like pictures (spec 2.7): Heart rate's day line through your resting band, Stress's day strip, Skin * temperature's dial, Sleep regularity's bed and wake bars and the day with the naps on it. Each draws in its metric's - * ink to fill its modifier, solid, never dotted or dashed and with no digits, and each but the naps has a rim function - * saying where on the card the off part sits (spec 2.5). The geometry is in plain functions so it is tested without a - * screen. + * ink to fill its modifier, solid, never dotted or dashed and with no digits (but the dial's reading), and each but the + * naps has a rim function saying where on the card the off part sits (spec 2.5). The geometry is in plain functions so it + * is tested without a screen. */ /* ------------------------------------------------------------------------------------------------ */ @@ -188,7 +191,7 @@ fun DayStrip(levels: List, ink: Color, size: PictureSize, modifier: Modi } } -/** Where Stress's card lights when above usual (spec 2.5): at the strip's end, the latest stretch. Null with none. */ +/** Where Stress's card lights when its latest reading is High (spec 2.5): at the strip's end, the latest stretch. Null with none. */ fun dayStripRim(levels: List, size: PictureSize, slots: Int = levels.size): Rim? { val last = stripStretches(levels, slots).lastOrNull() ?: return null return Rim(lineCardX(last.x1, size), lineCardY(0.5f), reachX = 0.6f, reachY = 1.1f) @@ -227,7 +230,8 @@ internal fun dialPoint(fit: DialFit, angle: Float, inset: Float = 0f): Offset { * Skin temperature's picture (spec 2.7, Dial): a half dial reaching [DIAL_RANGE] either side of your normal, a white * track at 8%, your [normal] (a deviation range in °C, like -0.3..0.3) as a band of [ink] at the top, and a needle at * tonight's [deviation] in the ink. Centred in its modifier: on a Wide the card puts the number left and gives the dial - * a square-ish box at the right ([WIDE_DIAL_CENTER_X]). + * a square-ish box at the right ([WIDE_DIAL_CENTER_X]). The [reading], when given, is the dial's one line of text, at + * the foot of the arc inside the needle's reach, in the larger type if it fits there ([dialReadingFits]). */ @Composable fun TempDial( @@ -236,7 +240,9 @@ fun TempDial( ink: Color, size: PictureSize, modifier: Modifier = Modifier, + reading: String? = null, ) { + val measurer = rememberTextMeasurer() Canvas(modifier.pictureArea(size)) { val track = 4.dp.toPx() val bandW = 9.dp.toPx() @@ -257,9 +263,22 @@ fun TempDial( drawLine(ink, dialPoint(fit, angle, fit.radius * 0.55f), dialPoint(fit, angle, dot), 2.dp.toPx(), StrokeCap.Round) drawCircle(ink, dot, tip) } + if (reading != null) { + val large = measurer.measure(reading, GlowType.secondary.copy(color = Color.White)) + val text = if (dialReadingFits(large.size.width.toFloat(), large.size.height.toFloat(), fit.radius)) large + else measurer.measure(reading, GlowType.caption.copy(color = Color.White)) + drawText(text, topLeft = Offset(fit.center.x - text.size.width / 2f, fit.center.y - text.size.height)) + } } } +/** The share of the dial's radius left clear of the needle, which starts 55% of the way out. */ +private const val DIAL_CLEAR_SHARE = 0.55f + +/** Whether a [width] by [height] text, centred on the foot of a dial of [radius], stays inside the needle's reach. */ +internal fun dialReadingFits(width: Float, height: Float, radius: Float): Boolean = + kotlin.math.hypot(width / 2, height) <= radius * DIAL_CLEAR_SHARE + /** Where a Wide's dial sits across the card: in a square-ish box at the right, after the number. */ const val WIDE_DIAL_CENTER_X = 0.78f diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt index eb8417b7..503b8ba0 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt @@ -187,7 +187,13 @@ class AppNavState(initial: Snapshot = Snapshot()) { /** Opens [page] over the tab, unless it's already on top. */ fun openPage(page: Page) { - if (pages.lastOrNull() != page) pages = pages + page + pages = when { + // You and Strap are roots, opened from a tab's header: one replaces the other rather than stack on it. Two + // taps landing during the page's slide-in stacked [You, Strap], and Back then went to You (audit S21). + page in ROOT_PAGES -> listOf(page) + pages.lastOrNull() == page -> pages + else -> pages + page + } } /** Closes the top page. */ @@ -264,6 +270,14 @@ class AppNavState(initial: Snapshot = Snapshot()) { workout = WorkoutOverlay.None } + /** + * The session left Idle, however it started (the app, the tile, the strap): Ready and Choose close, so neither + * comes back after the summary. Also closes one a request opened while the summary showed. + */ + fun sessionInProgress() { + if (workout != WorkoutOverlay.None) workout = WorkoutOverlay.None + } + /** Your zones, over Ready. */ fun openZones() { (workout as? WorkoutOverlay.Ready)?.let { workout = it.copy(zones = true) } @@ -357,6 +371,8 @@ class AppNavState(initial: Snapshot = Snapshot()) { fun snapshot(): Snapshot = Snapshot(tab, pages, stacks, allMetricsOpen, editGoals, addingOn, savingStretch, workout) companion object { + /** The pages a tab's header opens, each the root of the pages over the tab. */ + private val ROOT_PAGES = setOf(Page.You, Page.Strap) private const val TAB = "tab" private const val PAGES = "pages" private const val STACK = "stack." diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt index eb192124..fe84f616 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt @@ -74,7 +74,8 @@ sealed interface FirstScoreDay { } /** The day shown's own extras: the check-in. The strap's score comes with its Recovery ([RecoveryResult.strapScore]). */ -data class DayExtras(val checkIn: Int? = null) +/** The check-in of [date], null while that day's is read. */ +data class DayExtras(val date: LocalDate? = null, val checkIn: Int? = null) /** A badge past history earned, with the weekly goal it was earned at when it is a goal badge. */ data class EarnedBadge(val badge: Rewards.Badge, val goal: Int?) @@ -190,7 +191,7 @@ class AppRootViewModel( /** The day shown's check-in, from [dayShown]. */ val dayExtras: StateFlow = shownDay.filterNotNull().flatMapLatest { date -> - health.checkIn(date).map { DayExtras(it?.feeling) } + health.checkIn(date).map { DayExtras(date, it?.feeling) } }.state(DayExtras()) init { @@ -259,12 +260,21 @@ class AppRootViewModel( suspend fun summaryRewards(start: Long): SummaryRewards? = catching { rewards.summary(start, workouts.value, goals.value.workoutsPerWeek) }.getOrNull() - /** The manual copy and auto sync write with these. The calorie ones are optional but asked for until granted. */ + /** + * The manual copy and auto sync write with these. Only the needed permissions decide: the optional ones are asked + * for in the same screen when the needed ones are missing, and never again by themselves. + */ suspend fun healthConnectWrite(): HcState = HcState.blocked(healthConnect.availability()) ?: when { - healthConnect.hasRequestedPermissions() -> HcState.Granted + healthConnect.hasPermissions() -> HcState.Granted else -> HcState.Needs(healthConnect.requestedPermissions) } + /** Just the optional permissions, for the Health Connect page's offer to ask again. Granted when nothing is left to ask. */ + suspend fun healthConnectOptional(): HcState = HcState.blocked(healthConnect.availability()) ?: when { + healthConnect.hasOptionalPermissions() -> HcState.Granted + else -> HcState.Needs(healthConnect.optionalPermissions) + } + suspend fun healthConnectRead(): HcState = HcState.blocked(healthConnect.availability()) ?: when { healthConnect.hasReadPermissions() -> HcState.Granted else -> HcState.Needs(healthConnect.readPermissions) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt index fe9ec415..7748f205 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt @@ -7,10 +7,12 @@ import androidx.compose.ui.res.stringResource import org.openstrap.app.R import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.runtime.remember +import androidx.compose.ui.graphics.Color import androidx.lifecycle.compose.collectAsStateWithLifecycle import java.time.Instant import java.time.LocalDate @@ -35,10 +37,14 @@ import org.openstrap.app.ui.glow.GlowScoreDetailScreen import org.openstrap.app.ui.glow.GlowSleepScreen import org.openstrap.app.ui.glow.GlowWorkoutDetailScreen import org.openstrap.app.ui.glow.GlowWorkoutsScreen +import org.openstrap.app.ui.dashboard.ScreenList +import org.openstrap.app.ui.glow.GlowLayout +import org.openstrap.app.ui.glow.GlowType import org.openstrap.app.ui.glow.PageHeader import org.openstrap.app.ui.glow.SleepEditing import org.openstrap.app.ui.glow.WeekDetail import org.openstrap.app.ui.glow.dayName +import org.openstrap.app.ui.workout.OpenedWorkout import org.openstrap.app.ui.workout.WorkoutsViewModel /** @@ -66,9 +72,10 @@ internal fun DetailHost( val push: (Detail) -> Unit = { nav.push(tab, it) } val onSwitch: (Detail) -> Unit = { nav.replaceTop(tab, it) } val workouts by workoutsVm.workouts.collectAsStateWithLifecycle() - val activity by dayVm.activityHistory.collectAsStateWithLifecycle() + val activity = shown.activity when (detail) { - // A night signal's detail is always the night's, as its rows read it (SleepCopy.NIGHT_SIGNALS). + // A night signal's detail is always the night's, as its rows read it (SleepCopy.NIGHT_SIGNALS). Blood oxygen's + // is the night's only when the Sleep or Recovery tab opened it, so it comes with its own scope. is Detail.OfMetric -> GlowMetricDetailScreen( detail.metric, detail.night || detail.metric in SleepCopy.NIGHT_SIGNALS, day, histories.daily, live.bpm, live.canUse, push, onSwitch, dayVm::select, padding, pop, @@ -83,14 +90,16 @@ internal fun DetailHost( ) Detail.Week -> WeekDetail( ActivityDetailContext( - day, shown.recovery?.takeIf { it.date == day.date }, workouts, activity, histories.daily, onOpen = push, onSwitch = {}, + day, shown.recovery, workouts, activity, histories.daily, onOpen = push, onSwitch = {}, onSelectDay = dayVm::select, onEditProfile = onOpenProfile, contentPadding = padding, onBack = pop, ), ) is Detail.Workout -> { - val openWorkout by workoutsVm.open.collectAsStateWithLifecycle() - WorkoutDetail( - openWorkout?.takeIf { it.workout.start == detail.start }, padding, onBack = pop, + val opened by workoutsVm.opened.collectAsStateWithLifecycle() + // Only the answer for this workout counts: the one before it may still be showing as the new key loads. + val found = (opened as? OpenedWorkout.Found)?.analysis?.takeIf { it.workout.start == detail.start } + if (opened == OpenedWorkout.Missing(detail.start)) WorkoutMissing(padding, onBack = pop) else WorkoutDetail( + found, padding, onBack = pop, onDelete = { container.workout.discard(detail.start); pop() }, workoutsVm = workoutsVm, session = container.workout, bmrPerMinute = EnergyExpenditure.bmrPerMinute(profile, profile.age()), @@ -105,9 +114,9 @@ internal fun DetailHost( Detail.Recovery -> { BackHandler(onBack = pop) GlowRecoveryScreen( - day, shown.recovery, histories.daily, + day, shown.recovery, header = { PageHeader(stringResource(R.string.day_tab_recovery), pop, subtitle = dayName(day.date)) }, - contentPadding = padding, onOpenMetric = { push(Detail.OfMetric(it)) }, + contentPadding = padding, onOpenMetric = { push(Detail.OfMetric(it, night = it in SleepCopy.NIGHT_FIGURES)) }, onOpenScore = { push(Detail.OfScore(it)) }, strapScore = shown.strapScore, healthspan = shown.healthspan, onOpenHealthspan = { seeHabitAge(); push(Detail.Healthspan) }, onOpenProfile = onOpenProfile, recoveryFailure = shown.recoveryFailure, onRetryRecovery = dayVm::retryRecovery, @@ -124,6 +133,24 @@ internal fun DetailHost( } } +/** + * The page for a workout that no longer exists (deleted, with a notification or a restored stack still pointing at + * it): the header with its back button and one line saying so, instead of the loading state, which would never end. + */ +@Composable +private fun WorkoutMissing(contentPadding: PaddingValues, onBack: () -> Unit) { + BackHandler(onBack = onBack) + ScreenList(contentPadding, gutter = GlowLayout.Gutter) { + item { PageHeader(stringResource(R.string.glow_workout_untitled), onBack) } + item { + Text( + stringResource(R.string.glow_workout_deleted), + color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, + ) + } + } +} + /** A workout's detail: one page for the strap's and the phone's ([GlowWorkoutDetailScreen]). */ @Composable private fun WorkoutDetail( diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt index 773256a7..d937fce2 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt @@ -13,13 +13,16 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.health.connect.client.PermissionController +import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.launch +import org.openstrap.app.data.catching import org.openstrap.app.health.HcAvailability import org.openstrap.app.ui.device.BackupCopy import org.openstrap.app.ui.device.DeviceViewModel @@ -47,6 +50,13 @@ internal class HealthConnectActions( val export: () -> Unit, /** Auto sync on or off. */ val auto: (Boolean) -> Unit, + /** + * True while Health Connect is there and the optional permissions (calories, breathing rate, VO2 max) are not + * granted: the page offers them again. + */ + val caloriesMissing: Boolean, + /** Asks for just the optional permissions. */ + val offerCalories: () -> Unit, ) internal val HC_UNAVAILABLE: String get() = Strings.app.get(R.string.day_hc_unavailable) @@ -69,12 +79,22 @@ internal fun hcMissingMessage(availability: HcAvailability): String = internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: DeviceViewModel): HealthConnectActions { val context = LocalContext.current val scope = rememberCoroutineScope() + var caloriesMissing by remember { mutableStateOf(false) } + val refreshCalories: () -> Unit = { + scope.launch { caloriesMissing = catching { rootVm.healthConnectOptional() }.getOrNull() is HcState.Needs } + } + // Read again on every return to the app, since the grant can change in Health Connect's own screen. + LifecycleResumeEffect(Unit) { + refreshCalories() + onPauseOrDispose { } + } var hcForAuto by rememberSaveable { mutableStateOf(false) } val hcLauncher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { granted -> val auto = hcForAuto hcForAuto = false scope.launch { - // The needed ones may have been granted before, outside what this screen returns. The calorie ones may stay off. + // The needed ones may have been granted before, outside what this screen returns. The optional ones + // (calories, breathing rate, VO2 max) may stay off. when { !rootVm.healthConnectWriteGranted(granted) -> Toast.makeText(context, HC_NOT_GRANTED, Toast.LENGTH_LONG).show() auto -> deviceVm.setAutoHealthConnect(true) @@ -82,6 +102,9 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De } } } + val hcCalorieLauncher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { + refreshCalories() + } val hcReadLauncher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { granted -> if (rootVm.healthConnectReadGranted(granted)) deviceVm.importHealthConnect() else Toast.makeText(context, HC_NOT_GRANTED, Toast.LENGTH_LONG).show() @@ -99,8 +122,7 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De // The manual copy, or turning auto sync on ([forAuto]): with the write permissions, asked for first when missing. val write: (Boolean) -> Unit = { forAuto -> scope.launch { - // The calorie permissions are optional, but asked for again until granted: the launcher goes on with the - // ones it needs. + // The optional permissions (calories, breathing rate, VO2 max) are asked for only along with the needed ones. when (val hc = rootVm.healthConnectWrite()) { HcState.Unavailable -> Toast.makeText(context, HC_UNAVAILABLE, Toast.LENGTH_LONG).show() HcState.Installable -> Toast.makeText(context, HC_INSTALL_FIRST, Toast.LENGTH_LONG).show() @@ -116,6 +138,17 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De import = import, export = { write(false) }, auto = { on -> if (on) write(true) else deviceVm.setAutoHealthConnect(false) }, + caloriesMissing = caloriesMissing, + offerCalories = { + scope.launch { + when (val hc = rootVm.healthConnectOptional()) { + HcState.Unavailable -> Toast.makeText(context, HC_UNAVAILABLE, Toast.LENGTH_LONG).show() + HcState.Installable -> Toast.makeText(context, HC_INSTALL_FIRST, Toast.LENGTH_LONG).show() + HcState.Granted -> caloriesMissing = false + is HcState.Needs -> hcCalorieLauncher.launch(hc.permissions) + } + } + }, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt index e108e69a..7e2aa57b 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt @@ -2,19 +2,31 @@ package org.openstrap.app.ui.root import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState +import androidx.lifecycle.compose.collectAsStateWithLifecycle import org.openstrap.app.NavRequest import org.openstrap.app.NavigationRequests +import org.openstrap.app.device.WorkoutState import org.openstrap.app.ui.dashboard.Detail +import kotlinx.coroutines.flow.StateFlow /** * What a notification, a widget, the tile or a shortcut asked for, each once and in the order asked. A request sent * before the first frame waits for it. */ @Composable -internal fun NavRequestsEffect(requests: NavigationRequests, nav: AppNavState, hooks: NavRequestHooks) { +internal fun NavRequestsEffect( + requests: NavigationRequests, nav: AppNavState, hooks: NavRequestHooks, session: StateFlow, +) { val current by rememberUpdatedState(hooks) + // Whatever started the workout, Ready and Choose go with it; re-run if one is opened while it is in progress. + val state by session.collectAsStateWithLifecycle() + val inProgress = state is WorkoutState.Recording || state is WorkoutState.Ended + val overlay = nav.workout + // Reads overlay so a Ready opened during the session is closed too. + if (inProgress && overlay != WorkoutOverlay.None) SideEffect { nav.sessionInProgress() } LaunchedEffect(requests, nav) { requests.requests.collect { r -> val h = current diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt index f50dc6b8..7edb1a07 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt @@ -38,6 +38,7 @@ import dev.chrisbanes.haze.HazeState import dev.chrisbanes.haze.hazeSource import org.openstrap.app.AppContainer import org.openstrap.app.PendingAction +import org.openstrap.app.R import org.openstrap.app.data.HeartZones import org.openstrap.app.data.Recovery import org.openstrap.app.data.SampleData @@ -367,6 +368,8 @@ private fun HealthConnectPageHost(hooks: PageHooks, padding: PaddingValues, onBa if (!installHealthConnect(context)) Toast.makeText(context, HC_STORE_FAILED, Toast.LENGTH_LONG).show() }, onBack = onBack, + caloriesMissing = hooks.healthConnect.caloriesMissing, + onOfferCalories = hooks.healthConnect.offerCalories, ) } @@ -403,11 +406,24 @@ private fun UpdatesPageHost(container: AppContainer, rootVm: AppRootViewModel, p val allowLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { (waiting as? PendingAction.Install)?.let { install -> waiting = install.copy(answered = true) } } + val context = LocalContext.current + // Whatever way the wait ends, it is cleared: the install goes ahead, "install unknown apps" stayed off (a toast says + // so), or the release is gone from the list (the list is only empty before the saved one is read, so that waits). LaunchedEffect(waiting, updates.releases) { val install = (waiting as? PendingAction.Install)?.takeIf { it.answered } ?: return@LaunchedEffect - val release = updates.releases.firstOrNull { it.tag == install.tag } ?: return@LaunchedEffect + val release = updates.releases.firstOrNull { it.tag == install.tag } + if (release == null && updates.releases.isEmpty()) return@LaunchedEffect waiting = null - if (updater.canInstall()) updater.install(release) + when { + release == null -> Unit + updater.canInstall() -> updater.install(release) + else -> Toast.makeText(context, R.string.update_install_not_allowed, Toast.LENGTH_LONG).show() + } + } + // Back from Android's confirm screen with nothing installing, the page doesn't stay on Installing. + LifecycleResumeEffect(updater) { + updater.reconcile() + onPauseOrDispose { } } val uri = LocalUriHandler.current UpdatesPage( diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt index b57ddddd..51cd62b1 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt @@ -22,7 +22,7 @@ import org.openstrap.app.data.WorkoutPlan import org.openstrap.app.device.BlePermissions import org.openstrap.app.ui.glow.PageConfirm -/** The Bluetooth and location gates in front of a workout and the Strap page's actions. */ +/** The Bluetooth, location and notification gates in front of a workout and the Strap page's actions. */ internal class PermissionGates( /** Runs the action once Bluetooth may be used. */ val requestBluetooth: (() -> Unit) -> Unit, @@ -30,21 +30,31 @@ internal class PermissionGates( val startPlan: (WorkoutPlan, SportSettings?) -> Unit, /** Asks for location, then runs the action whatever the answer. */ val requestLocation: (() -> Unit) -> Unit, - private val blocked: MutableState, + private val blocked: MutableState, ) { - /** Bluetooth was turned down for good: Android shows no dialog any more, so the app offers its settings page. */ - val bluetoothBlocked: Boolean get() = blocked.value + /** What was turned down for good: Android shows no dialog any more, so the app offers its settings page. */ + val blockedPermission: BlockedPermission? get() = blocked.value fun dismissBlocked() { - blocked.value = false + blocked.value = null } } +/** A permission turned down for good, saved by name so the dialog survives a recreate. */ +internal enum class BlockedPermission { BLUETOOTH, LOCATION, NOTIFICATIONS } + +/** What waits on the location answer besides a workout: a name rather than a closure, so it can be saved. */ +private enum class GateAction { + /** Ready's "Turn on location": the Ready screen reads the phone's location again. */ + REFRESH_READY, +} + /** * The permission gates. A workout waits as saveable data, so the answer still starts it after the activity was - * recreated behind the dialog. A Strap page action waits in [pendingStrap], which outlives a fold. Location for a GPS - * workout is asked only when GPS is on, and the workout starts either way (steps without it). Ready's "Turn on - * location" hands over a closure that only refreshes Ready, so that one isn't saved. + * recreated behind the dialog. A Strap page action waits in [pendingStrap], which outlives a fold, and one Bluetooth + * answer runs both. Location for a GPS workout is asked only when GPS is on, and the workout starts either way (steps + * without it). Ready's "Turn on location" is a saved [GateAction] tag, with the closure that refreshes Ready kept + * beside it. */ @Composable internal fun rememberPermissionGates( @@ -59,15 +69,26 @@ internal fun rememberPermissionGates( val bluetoothRequired = stringResource(if (android11) R.string.day_bluetooth_required_location else R.string.day_bluetooth_required) val locationDeclined = stringResource(R.string.day_location_declined) var pending by rememberSaveable(stateSaver = PendingAction.Saver) { mutableStateOf(null) } - val blocked = rememberSaveable { mutableStateOf(false) } + val blocked = rememberSaveable { mutableStateOf(null) } val btLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result -> val waiting = pending as? PendingAction.StartPlan val strapAction = pendingStrap.action pending = null pendingStrap.action = null when { - BlePermissions.granted(result) -> waiting?.let(start) ?: strapAction?.invoke() - activity != null && BlePermissions.turnedDownForGood(activity, BlePermissions.bluetooth) -> blocked.value = true + // Whoever queued behind this one question gets the answer: the workout and the Strap page action both. + BlePermissions.granted(result) -> { + waiting?.let(start) + strapAction?.invoke() + // Notifications are not needed to go ahead, but a no for good leaves the workout notification missing. + if (BlePermissions.notificationsDenied(result) && activity != null && + BlePermissions.turnedDownForGood(activity, BlePermissions.notifications) + ) { + blocked.value = BlockedPermission.NOTIFICATIONS + } + } + activity != null && BlePermissions.turnedDownForGood(activity, BlePermissions.bluetooth) -> + blocked.value = BlockedPermission.BLUETOOTH else -> Toast.makeText(context, bluetoothRequired, Toast.LENGTH_LONG).show() } } @@ -76,29 +97,40 @@ internal fun rememberPermissionGates( btLauncher.launch(BlePermissions.required()) } val withBluetooth: (PendingAction.StartPlan) -> Unit = { action -> - if (BlePermissions.granted(context)) { + // Asked again while notifications are missing, so a no for good shows its dialog at the start of a workout. + if (BlePermissions.granted(context) && BlePermissions.notificationsGranted(context)) { start(action) } else { pending = action btLauncher.launch(BlePermissions.required()) } } - var afterLocation by remember { mutableStateOf<(() -> Unit)?>(null) } + // Which follow-up waits on the location answer is saved, so it survives a recreate. Ready's closure behind it only + // refreshes the Ready screen that asked, which a recreate replaces: the new Ready reads location itself when it + // shows and on every resume, so a lost closure leaves nothing undone. + var afterLocation by rememberSaveable { mutableStateOf(null) } + var refreshReady by remember { mutableStateOf<(() -> Unit)?>(null) } + val locationPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) val locationLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result -> if (result.values.none { it }) { - Toast.makeText(context, locationDeclined, Toast.LENGTH_LONG).show() + if (activity != null && BlePermissions.turnedDownForGood(activity, locationPermissions.asList())) { + blocked.value = BlockedPermission.LOCATION + } else { + Toast.makeText(context, locationDeclined, Toast.LENGTH_LONG).show() + } } val waiting = pending as? PendingAction.StartPlan if (waiting != null) { pending = null withBluetooth(waiting) } - afterLocation?.invoke() + if (afterLocation == GateAction.REFRESH_READY) refreshReady?.invoke() afterLocation = null + refreshReady = null } - val locationPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) val requestLocation: (() -> Unit) -> Unit = { then -> - afterLocation = then + afterLocation = GateAction.REFRESH_READY + refreshReady = then locationLauncher.launch(locationPermissions) } val startPlan: (WorkoutPlan, SportSettings?) -> Unit = { plan, saved -> @@ -113,14 +145,28 @@ internal fun rememberPermissionGates( return PermissionGates(requestBluetooth, startPlan, requestLocation, blocked) } -/** Nearby devices turned down for good: the way to OpenStrap's settings page, where it can be turned on. */ +/** + * Whatever was turned down for good (Nearby devices, location, notifications): the way to unstrap's settings page, + * where it can be turned on. Named for Bluetooth, which it first served. + */ @Composable internal fun BluetoothBlockedDialog(gates: PermissionGates) { - if (!gates.bluetoothBlocked) return + val blocked = gates.blockedPermission ?: return val context = LocalContext.current + val location = BlePermissions.scanNeedsLocationOn + val title = when (blocked) { + BlockedPermission.BLUETOOTH -> if (location) R.string.day_nearby_title_location else R.string.day_nearby_title + BlockedPermission.LOCATION -> R.string.day_nearby_title_location + BlockedPermission.NOTIFICATIONS -> R.string.day_notifications_blocked_title + } + val text = when (blocked) { + BlockedPermission.BLUETOOTH -> if (location) R.string.day_nearby_text_location else R.string.day_nearby_text + BlockedPermission.LOCATION -> R.string.day_location_blocked_text + BlockedPermission.NOTIFICATIONS -> R.string.day_notifications_blocked_text + } PageConfirm( - title = stringResource(if (BlePermissions.scanNeedsLocationOn) R.string.day_nearby_title_location else R.string.day_nearby_title), - text = stringResource(if (BlePermissions.scanNeedsLocationOn) R.string.day_nearby_text_location else R.string.day_nearby_text), + title = stringResource(title), + text = stringResource(text), confirm = stringResource(R.string.day_nearby_open_settings), onConfirm = { gates.dismissBlocked() diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt index 0ad3fa59..cc79062a 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt @@ -13,6 +13,7 @@ import java.time.LocalDate import org.openstrap.app.data.Recovery import org.openstrap.app.data.RecoveryResult import org.openstrap.app.ui.dashboard.DataPreview +import org.openstrap.app.ui.dashboard.DayScreenState import org.openstrap.app.ui.dashboard.DayUiState import org.openstrap.app.ui.dashboard.DayViewModel import org.openstrap.app.ui.dashboard.FirstScore @@ -22,11 +23,17 @@ import org.openstrap.app.ui.dashboard.earliestScore import org.openstrap.app.ui.dashboard.firstScore import org.openstrap.app.ui.dashboard.previewed import org.openstrap.app.ui.dashboard.wear +import org.openstrap.app.ui.components.rememberDayHold private const val S_PER_MIN = 60 /** The day, its Recovery and a failed Recovery as the screens are shown them, the debug previews applied. */ -class PreviewedDay(val day: DayUiState, val recovery: RecoveryResult?, val recoveryFailure: RecoveryFailure?) +class PreviewedDay( + val screen: DayScreenState, + val day: DayUiState, + val recovery: RecoveryResult?, + val recoveryFailure: RecoveryFailure?, +) /** * The day shown with the debug previews applied: a strap [preview] of a failed Recovery shows the day as failed, with @@ -35,9 +42,10 @@ class PreviewedDay(val day: DayUiState, val recovery: RecoveryResult?, val recov */ @Composable internal fun rememberPreviewedDay(dayVm: DayViewModel, preview: StrapPreview?, data: DataPreview?): PreviewedDay { - val realRecovery by dayVm.recovery.collectAsStateWithLifecycle() - val realRecoveryFailure by dayVm.recoveryFailure.collectAsStateWithLifecycle() - val realDay by dayVm.state.collectAsStateWithLifecycle() + val screen by dayVm.screen.collectAsStateWithLifecycle() + val realRecovery = screen.recovery + val realRecoveryFailure = screen.recoveryFailure + val realDay = screen.day val day = remember(realDay, data) { realDay.previewed(data) } val previewFailure = if (preview == StrapPreview.RecoveryFail) { realRecovery?.let { r -> RecoveryFailure(r.date, r.readinessTrend.firstOrNull { it.first == r.date.minusDays(1) }?.second) } @@ -45,7 +53,7 @@ internal fun rememberPreviewedDay(dayVm: DayViewModel, preview: StrapPreview?, d null } val recovery = if (previewFailure != null) null else realRecovery?.previewed(data) - return PreviewedDay(day, recovery, previewFailure ?: realRecoveryFailure) + return PreviewedDay(screen, day, recovery, previewFailure ?: realRecoveryFailure) } /** @@ -54,24 +62,28 @@ internal fun rememberPreviewedDay(dayVm: DayViewModel, preview: StrapPreview?, d */ @Composable internal fun rememberShownDay( - shown: PreviewedDay, - dayVm: DayViewModel, + live: PreviewedDay, rootVm: AppRootViewModel, clockDate: LocalDate, now: Long, preview: StrapPreview?, data: DataPreview?, ): ShownDay { + // Another day's rows take a moment to arrive: for that moment the last day stays up, dimmed, then the placeholder + // ([rememberDayHold]), never the old day's numbers for long. + val hold = rememberDayHold(live.takeIf { it.screen.loaded }, live.screen.date) + val shown = hold.value ?: live val day = shown.day val recovery = shown.recovery - val healthspan by dayVm.healthspan.collectAsStateWithLifecycle() LaunchedEffect(day.date) { rootVm.dayShown(day.date) } val dayExtras by rootVm.dayExtras.collectAsStateWithLifecycle() + // The check-in follows the day by its own flow, so it only counts once it's this day's. + val checkIn = dayExtras.takeIf { it.date == day.date }?.checkIn val dayIsToday = day.date == clockDate val wear = day.wear(recovery, dayIsToday) .previewed(data, (((if (dayIsToday) now else day.dayEnd + 1) - day.dayStart) / S_PER_MIN).toInt()) val firstScoreDay by rootVm.firstScoreDay.collectAsStateWithLifecycle() - val dayRecovery = recovery?.takeIf { it.date == day.date } + val dayRecovery = recovery val first = if (firstScoreDay == FirstScoreDay.Loading) { FirstScore(false) } else { @@ -84,7 +96,8 @@ internal fun rememberShownDay( if (preview == null && data == null) first.remember?.let(rootVm::markFirstScore) } return ShownDay( - day, recovery, shown.recoveryFailure, healthspan, dayExtras.checkIn, wear, + day, recovery, shown.recoveryFailure, shown.screen.healthspan, checkIn, wear, firstScore = first.show || data == DataPreview.FirstScoreShown, + loading = !shown.screen.loaded, pending = hold.pending, usualSteps = shown.screen.usualSteps, activity = shown.screen.activity, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/StrapHeader.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/StrapHeader.kt index 4634f5eb..810bdca9 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/StrapHeader.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/StrapHeader.kt @@ -14,7 +14,6 @@ import androidx.compose.runtime.setValue import java.time.LocalDate import kotlinx.coroutines.delay import org.openstrap.app.device.ConnectionState -import org.openstrap.app.device.SyncState import org.openstrap.app.ui.dashboard.DataPreview import org.openstrap.app.ui.dashboard.DayUiState import org.openstrap.app.ui.dashboard.PAIRED_HOLD_MS @@ -54,7 +53,8 @@ internal fun rememberStrapHeader(facts: StrapFacts, day: DayUiState, preview: St } val realLastSeen = listOfNotNull( seenConnected, - (facts.sync as? SyncState.Done)?.atEpochSeconds, + // The kept time of the last full sync, the status every screen and widget reads, not this run's last Done. + facts.syncRecord.lastSuccess, day.heartRate.lastOrNull()?.x?.takeIf { day.date == LocalDate.now() }, ).maxOrNull() // The chip's "18 min ago" moves on by itself. diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt index 0c9bacb5..09d133df 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt @@ -8,7 +8,9 @@ import androidx.compose.animation.core.tween import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.pager.HorizontalPager +import org.openstrap.app.ui.components.dayHeld import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.runtime.Composable @@ -45,11 +47,13 @@ import org.openstrap.app.ui.components.sinkBehind import org.openstrap.app.ui.dashboard.DailyHistory import org.openstrap.app.ui.dashboard.DayPicker import org.openstrap.app.ui.dashboard.DayUiState +import org.openstrap.app.ui.dashboard.ActivityHistory import org.openstrap.app.ui.dashboard.DayViewModel import org.openstrap.app.ui.dashboard.Detail import org.openstrap.app.ui.dashboard.LocalScrollToTop import org.openstrap.app.ui.dashboard.MomentHeader import org.openstrap.app.ui.dashboard.RecoveryFailure +import org.openstrap.app.ui.dashboard.SleepCopy import org.openstrap.app.ui.dashboard.StrapChip import org.openstrap.app.ui.dashboard.Wear import org.openstrap.app.presentation.dayTitle @@ -84,6 +88,8 @@ fun tabItems(): List = Tab.entries.map { tab -> } /** The day shown as every tab and detail sees it: the debug previews applied, its Recovery, strap score and check-in. */ +// One field per part of the day the screens show. +@Suppress("LongParameterList") class ShownDay( val day: DayUiState, val recovery: RecoveryResult?, @@ -94,9 +100,17 @@ class ShownDay( val wear: Wear?, /** The first real score shows its moment (E4). */ val firstScore: Boolean, + /** The day's rows haven't arrived yet: the screens show their placeholders, never another day's numbers. */ + val loading: Boolean = false, + /** The last day, kept for a moment while this one loads ([org.openstrap.app.ui.components.rememberDayHold]): drawn dimmed. */ + val pending: Boolean = false, + /** Your usual steps by hour for the day shown, null until there are enough worn days. */ + val usualSteps: List? = null, + /** Heart points, calories and steps up to the day shown. */ + val activity: ActivityHistory = ActivityHistory(), ) { /** The strap's own score for the day shown's night, by the strap session it came from ([RecoveryResult.strapScore]). */ - val strapScore: Int? get() = recovery?.takeIf { it.date == day.date }?.strapScore + val strapScore: Int? get() = recovery?.strapScore } /** The stored histories the charts read. */ @@ -202,10 +216,10 @@ internal fun TabsPager( detail = { stack -> stack.lastOrNull()?.let { detail(t, it) } }, ) { PullToSync(strap.sync, connected, container.strap::syncNow) { - TabRoot( + Box(Modifier.dayHeld(shown.pending)) { TabRoot( t, nav, shown, histories, today, container, dayVm, workoutsVm, rootVm, live, padding, showCharge, onChargeConsume, header, onOpenPage, seeHabitAge, - ) + ) } } } } @@ -241,8 +255,8 @@ private fun TabRoot( ) { val day = shown.day val workouts by workoutsVm.workouts.collectAsStateWithLifecycle() - val usualSteps by dayVm.usualSteps.collectAsStateWithLifecycle() - val activity by dayVm.activityHistory.collectAsStateWithLifecycle() + val usualSteps = shown.usualSteps + val activity = shown.activity val suggestions by workoutsVm.suggestions.collectAsStateWithLifecycle() // Hidden while a workout records: the strap's history may show the one under way. val suggestion = suggestions.firstOrNull().takeIf { today.running == null } @@ -292,8 +306,8 @@ private fun TabRoot( ) } Tab.Recovery -> GlowRecoveryScreen( - day, shown.recovery, histories.daily, header = { TabHeader(Tab.Recovery, header) }, contentPadding = padding, - onOpenMetric = { openStack(Tab.Recovery, Detail.OfMetric(it)) }, + day, shown.recovery, header = { TabHeader(Tab.Recovery, header) }, contentPadding = padding, + onOpenMetric = { openStack(Tab.Recovery, Detail.OfMetric(it, night = it in SleepCopy.NIGHT_FIGURES)) }, onOpenScore = { openStack(Tab.Recovery, Detail.OfScore(it)) }, strapScore = shown.strapScore, healthspan = shown.healthspan, diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt index 24018d8f..cb5c15da 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt @@ -1,6 +1,7 @@ package org.openstrap.app.ui.root import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.createSavedStateHandle import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import kotlinx.coroutines.flow.StateFlow @@ -24,7 +25,10 @@ internal object ViewModelFactories { /** The day shown, which moves on to the new day as soon as the phone's date, time or time zone changes. */ fun day(c: AppContainer): ViewModelProvider.Factory = viewModelFactory { initializer { - DayViewModel(c.days, c.settings.profile, c.autoHealthConnect::sleepEdited, dateChanges = Today.changes(c.app)) + DayViewModel( + c.days, c.settings.profile, c.autoHealthConnect::sleepEdited, dateChanges = Today.changes(c.app), + saved = createSavedStateHandle(), + ) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt index 823a9e0b..92289010 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt @@ -44,6 +44,7 @@ import org.openstrap.app.data.db.SavedWorkout import org.openstrap.app.device.ConnectionState import org.openstrap.app.device.WorkoutSession import org.openstrap.app.device.WorkoutState +import org.openstrap.app.device.inProgress import org.openstrap.app.device.locationAvailable import org.openstrap.app.presentation.SummaryRewards import org.openstrap.app.ui.dashboard.DayUiState @@ -228,7 +229,7 @@ internal fun BoxScope.WorkoutLayer( else -> Unit } // The ready screen comes and goes like any other screen, and a workout starting replaces it at once. - val recording = state is WorkoutState.Recording || state is WorkoutState.Ended + val recording = state.inProgress // Read once for both screens, and handed down to be read only there. val saved by remember { container.workout.savedWorkouts() }.collectAsStateWithLifecycle(emptyList()) // Choose sits under Ready, so closing Ready comes back to it. diff --git a/app/src/main/kotlin/org/openstrap/app/ui/workout/ReadyHero.kt b/app/src/main/kotlin/org/openstrap/app/ui/workout/ReadyHero.kt index d12fd115..70a263a5 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/workout/ReadyHero.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/workout/ReadyHero.kt @@ -26,6 +26,6 @@ fun WorkoutCopy.readyHero(connection: ConnectionState, bpm: Int?, strings: Strin ReadyHero(strings.get(R.string.workout_ready_connecting), strings.get(R.string.workout_ready_anyway), live = false) ConnectionState.NotPaired -> ReadyHero(strings.get(R.string.workout_ready_not_paired), strings.get(R.string.workout_ready_anyway), live = false) - ConnectionState.Disconnected, is ConnectionState.Failed -> + ConnectionState.Disconnected, ConnectionState.BluetoothOff, is ConnectionState.Failed -> ReadyHero(strings.get(R.string.workout_ready_not_connected), strings.get(R.string.workout_ready_anyway), live = false) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/workout/StartCopy.kt b/app/src/main/kotlin/org/openstrap/app/ui/workout/StartCopy.kt index 9627c9a3..1147e43d 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/workout/StartCopy.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/workout/StartCopy.kt @@ -31,7 +31,8 @@ object StartCopy { bpm?.let { strings.format(R.string.workout_start_strap_ready_bpm, it) } ?: strings.get(R.string.workout_start_strap_ready) ConnectionState.Connecting, ConnectionState.Authenticating -> strings.get(R.string.workout_start_strap_connecting) ConnectionState.NotPaired -> strings.get(R.string.workout_start_strap_not_paired) - ConnectionState.Disconnected, is ConnectionState.Failed -> strings.get(R.string.workout_start_strap_not_connected) + ConnectionState.Disconnected, ConnectionState.BluetoothOff, is ConnectionState.Failed -> + strings.get(R.string.workout_start_strap_not_connected) } /** The goal chip for no goal, named for the sport: "Just run", "Just walk", "Just ride", else "Just go". */ diff --git a/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt index 7b40792a..ccb45c54 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt @@ -14,6 +14,7 @@ import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -32,6 +33,21 @@ import java.time.LocalDate /** The data layer's summary, kept under its old name for the screens. */ typealias PhoneSummary = org.openstrap.app.data.WorkoutSummaryData +/** What reading the workout open in detail has found so far. */ +sealed interface OpenedWorkout { + /** Nothing has answered yet. */ + data object Loading : OpenedWorkout + + data class Found(val analysis: WorkoutAnalysis) : OpenedWorkout + + /** No workout starts at [start]: it was deleted. */ + data class Missing(val start: Long) : OpenedWorkout + + companion object { + fun of(start: Long, analysis: WorkoutAnalysis?): OpenedWorkout = if (analysis == null) Missing(start) else Found(analysis) + } +} + /** Workouts list (newest first) and the one open in detail. */ @OptIn(ExperimentalCoroutinesApi::class) class WorkoutsViewModel( @@ -77,8 +93,17 @@ class WorkoutsViewModel( private val openStart = MutableStateFlow(null) - val open: StateFlow = openStart.flatMapLatest { start -> if (start == null) flowOf(null) else repo.open(start) } - .flowOn(work).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) + /** + * The workout open in detail, read by its key: [OpenedWorkout.Loading] until the first read answers, + * [OpenedWorkout.Found], or [OpenedWorkout.Missing] when there is none with that start (deleted since a + * notification or a restored stack pointed at it). Each answer carries its key, so the one for the workout before + * is never taken for the one now. + */ + val opened: StateFlow = + openStart.flatMapLatest { start -> + if (start == null) flowOf(OpenedWorkout.Loading) else repo.open(start).map { OpenedWorkout.of(start, it) } + } + .flowOn(work).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), OpenedWorkout.Loading) /** * A phone workout's summary: its analysis, everything recorded (for trimming), and the strap's own record of it diff --git a/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt b/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt index 88e14e34..a5aadbf6 100644 --- a/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt +++ b/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt @@ -20,6 +20,7 @@ import androidx.work.WorkManager import androidx.work.WorkerParameters import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -56,14 +57,20 @@ sealed interface Install { data class Failed(val tag: String, val failure: InstallFailure, val detail: String? = null) : Install } +/** Where reading the release list stands: one value, so "checking" and "failed" can't both be true. */ +sealed interface Check { + data object Idle : Check + data object Checking : Check + /** The last check couldn't reach GitHub or read its reply. */ + data object Failed : Check +} + data class UpdateState( /** Every release GitHub listed at the last check (kept across restarts), newest first. */ val releases: List = emptyList(), /** When that check was, epoch seconds. */ val checkedAt: Long? = null, - val checking: Boolean = false, - /** The last check couldn't reach GitHub or read its reply. */ - val checkFailed: Boolean = false, + val check: Check = Check.Idle, val install: Install = Install.Idle, ) @@ -110,8 +117,43 @@ class AppUpdater( /** Sets the daily check going, or stops it, as the switch says; each app start. */ fun start() { scope.launch { if (settings.updateAuto.first()) schedule(app) else cancel(app) } + reconcile() } + /** True from creating the installer session until it is committed, when no session is yet there to find. */ + @Volatile private var committing = false + + /** + * Brings the saved "installing" tag and [Install.Installing] in line with what Android has. Each app start, and when the + * Updates page comes back to the front (the user may have walked away from Android's confirm screen): + * - the tag is for this version or an older one: the update is in, the tag goes; + * - no installer session of ours is open: nothing is installing, so the tag goes and the page is back to Idle; + * - a session is open and memory says Idle (the process died after the commit): the page shows Installing again. + */ + fun reconcile() { + scope.launch { + if (committing) return@launch + val tag = (_state.value.install as? Install.Installing)?.tag ?: settings.updateInstalling() ?: return@launch + val target = Releases.version(tag) + val mine = Releases.version(installed) + val inThere = target != null && mine != null && Releases.compare(target, mine) <= 0 + val live = !inThere && withContext(Dispatchers.IO) { sessionOpen() } + if (committing) return@launch + when { + live -> _state.update { if (it.install is Install.Idle) it.copy(install = Install.Installing(tag)) else it } + else -> { + settings.setUpdateInstalling(null) + _state.update { if (it.install is Install.Installing) it.copy(install = Install.Idle) else it } + } + } + } + } + + /** An installer session of this app is open: committed or not, Android hasn't finished with it. */ + private fun sessionOpen(): Boolean = runCatching { + app.packageManager.packageInstaller.mySessions.any { it.appPackageName == app.packageName } + }.getOrDefault(false) + fun setAuto(on: Boolean) { scope.launch { settings.setUpdateAuto(on) @@ -125,7 +167,7 @@ class AppUpdater( /** Reads the release list from GitHub; true when it got one. */ suspend fun check(): Boolean = checkLock.withLock { - _state.update { it.copy(checking = true) } + _state.update { it.copy(check = Check.Checking) } try { catching { val json = get(Releases.API, github = true) @@ -137,16 +179,16 @@ class AppUpdater( } val now = System.currentTimeMillis() / 1000 settings.setUpdateChecked(now) - _state.update { it.copy(releases = releases, checkedAt = now, checkFailed = false) } + _state.update { it.copy(releases = releases, checkedAt = now, check = Check.Idle) } true }.getOrElse { e -> Log.i(TAG, "Update check failed: $e") - _state.update { it.copy(checkFailed = true) } + _state.update { it.copy(check = Check.Failed) } false } } finally { // Cancelled too: the page doesn't stay on Checking. - _state.update { it.copy(checking = false) } + _state.update { if (it.check == Check.Checking) it.copy(check = Check.Idle) else it } } } @@ -179,14 +221,36 @@ class AppUpdater( checkArchive(file) // The download can outlast a workout's start. if (recording()) throw Stop(InstallFailure.Recording) + committing = true _state.update { it.copy(install = Install.Installing(tag)) } settings.setUpdateInstalling(tag) commit(file) + watchInstalling(tag) }.onFailure { e -> val failure = failureFor(e) if (e !is Stop) Log.i(TAG, "Update install failed ($failure): $e") fail(tag, failure, e.message.takeIf { failure == InstallFailure.Android }) } + committing = false + } + } + + /** + * Installing has a way out: when the user ignores Android's confirm screen nothing is ever reported, so after + * [INSTALL_TIMEOUT_MS] the open session is abandoned and the page goes back to Idle. + */ + private fun watchInstalling(tag: String) { + scope.launch { + delay(INSTALL_TIMEOUT_MS) + if ((_state.value.install as? Install.Installing)?.tag != tag) return@launch + withContext(Dispatchers.IO) { + runCatching { + val installer = app.packageManager.packageInstaller + installer.mySessions.filter { it.appPackageName == app.packageName }.forEach { installer.abandonSession(it.sessionId) } + } + } + settings.setUpdateInstalling(null) + _state.update { if ((it.install as? Install.Installing)?.tag == tag) it.copy(install = Install.Idle) else it } } } @@ -195,14 +259,16 @@ class AppUpdater( _state.update { if (it.install is Install.Failed) it.copy(install = Install.Idle) else it } } - /** What Android's package installer reported ([UpdateReceiver]). */ + /** + * What Android's package installer reported ([UpdateReceiver]). The tag is the one in memory, or the saved one when the + * process died after the commit, so a failure then is shown and the saved tag cleared instead of lost. + */ internal fun installResult(context: Context, status: Int, message: String?, confirm: Intent?) { - val tag = (_state.value.install as? Install.Installing)?.tag when (status) { // Android asks the user first: its own confirmation screen. PackageInstaller.STATUS_PENDING_USER_ACTION -> confirm?.let { runCatching { context.startActivity(it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } - .onFailure { e -> tag?.let { t -> fail(t, InstallFailure.Android, e.message) } } + .onFailure { e -> withTag { t -> fail(t, InstallFailure.Android, e.message) } } } // On success Android closes the app, so this is rarely seen. PackageInstaller.STATUS_SUCCESS -> _state.update { it.copy(install = Install.Idle) } @@ -217,11 +283,18 @@ class AppUpdater( else -> InstallFailure.Android } Log.i(TAG, "Update install failed: status $status, $message") - fail(tag ?: return, failure, message) + withTag { t -> fail(t, failure, message) } } } } + /** Runs [block] with the tag being installed: from memory, or else the saved one. Nothing when neither is there. */ + private fun withTag(block: (String) -> Unit) { + val tag = (_state.value.install as? Install.Installing)?.tag + if (tag != null) return block(tag) + scope.launch { settings.updateInstalling()?.let(block) } + } + private fun fail(tag: String, failure: InstallFailure, detail: String? = null) { _state.update { it.copy(install = Install.Failed(tag, failure, detail)) } scope.launch { settings.setUpdateInstalling(null) } @@ -358,6 +431,9 @@ class AppUpdater( private const val TAG = "unstrap" private const val DAILY = "update-check" + /** How long Installing waits for Android's report before the page goes back to Idle. */ + internal const val INSTALL_TIMEOUT_MS = 10 * 60 * 1000L + /** Starts the daily check; a no-op when it's already scheduled. Runs only with a network. */ fun schedule(context: Context) { val request = PeriodicWorkRequestBuilder(1, TimeUnit.DAYS) diff --git a/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt b/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt index 60c44bd9..f4db953d 100644 --- a/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt +++ b/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt @@ -24,7 +24,7 @@ object UpdateCopy { ): String { val newest = Releases.newer(state.releases, installed).firstOrNull() if (newest != null) return strings.format(R.string.update_summary_ready, newest.versionName) - if (state.checking) return strings.get(R.string.update_summary_checking) + if (state.check == Check.Checking) return strings.get(R.string.update_summary_checking) val checked = state.checkedAt ?: return strings.format(R.string.update_summary_version, installed) return strings.format(R.string.update_summary_up_to_date, DayWords.whenDone(checked, now, zone, locale = locale)) } @@ -37,9 +37,9 @@ object UpdateCopy { locale: Locale = Locale.getDefault(), strings: Strings = Strings.app, ): String { - if (state.checking) return strings.get(R.string.update_check_checking) + if (state.check == Check.Checking) return strings.get(R.string.update_check_checking) val checked = state.checkedAt?.let { DayWords.whenDone(it, now, zone, locale = locale) } - if (state.checkFailed) { + if (state.check == Check.Failed) { return if (checked != null) { strings.format(R.string.update_check_failed_last, checked) } else { diff --git a/app/src/main/kotlin/org/openstrap/app/widget/StrapStatus.kt b/app/src/main/kotlin/org/openstrap/app/widget/StrapStatus.kt index e86db52e..78f9afba 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/StrapStatus.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/StrapStatus.kt @@ -23,17 +23,30 @@ sealed interface StrapStatus { /** The stale line's sync, under way. */ data object Syncing : StrapStatus + + /** The last sync failed and none has worked since, the app's own "not synced". A tap syncs. */ + data object SyncFailed : StrapStatus + + /** Bluetooth is off on the phone. Opens the Strap page, which turns it on. */ + data object BluetoothOff : StrapStatus } /** - * The status line, first match wins: not [paired], then [battery] at [StrapBands.LOW_BATTERY] or less and not [charging], - * then [lastSync] (epoch seconds) more than [StrapBands.STALE_AFTER_S] before [now]. While [syncing] the stale line reads - * Syncing instead; a sync while all is well shows nothing, so the background syncs don't flash a line. Before the - * first sync is known there's no time to give, so no line. + * The status line, first match wins: not [paired], then [bluetoothOff], then [battery] at [StrapBands.LOW_BATTERY] or + * less and not [charging], then a failed sync ([failingSince] set, the app's "not synced"), then [lastSync] (epoch + * seconds) more than [StrapBands.STALE_AFTER_S] before [now]. While [syncing] the last two read Syncing instead; a sync + * while all is well shows nothing, so the background syncs don't flash a line. Before the first sync is known there's + * no time to give, so no line. */ -fun strapStatus(paired: Boolean, battery: Int?, charging: Boolean, lastSync: Long?, now: Long, syncing: Boolean = false): StrapStatus? = when { +@Suppress("LongParameterList") // Each one is a fact the line reads. +fun strapStatus( + paired: Boolean, battery: Int?, charging: Boolean, lastSync: Long?, now: Long, syncing: Boolean = false, + failingSince: Long? = null, bluetoothOff: Boolean = false, +): StrapStatus? = when { !paired -> StrapStatus.NotPaired + bluetoothOff -> StrapStatus.BluetoothOff battery != null && StrapBands.lowBattery(battery, charging) -> StrapStatus.LowBattery(battery) + failingSince != null -> if (syncing) StrapStatus.Syncing else StrapStatus.SyncFailed syncStale(lastSync, now) -> if (syncing) StrapStatus.Syncing else StrapStatus.StaleSync(lastSync!!) else -> null } @@ -41,10 +54,17 @@ fun strapStatus(paired: Boolean, battery: Int?, charging: Boolean, lastSync: Lon /** True when the last sync ended more than [StrapBands.STALE_AFTER_S] before [now] ([StrapBands.stale]). */ fun syncStale(lastSync: Long?, now: Long): Boolean = StrapBands.stale(lastSync, now) -/** True when the line for the strap's state could read otherwise: pairing, the low battery edge or charging changed. */ -fun strapStateChanged(paired: Boolean, battery: Int?, charging: Boolean, wasPaired: Boolean, wasBattery: Int?, wasCharging: Boolean): Boolean { +/** + * True when the line for the strap's state could read otherwise: pairing, the low battery edge, charging or whether + * syncs are failing ([failing], [wasFailing]) changed. + */ +@Suppress("LongParameterList") // The old and new of each fact the line reads. +fun strapStateChanged( + paired: Boolean, battery: Int?, charging: Boolean, wasPaired: Boolean, wasBattery: Int?, wasCharging: Boolean, + failing: Boolean = false, wasFailing: Boolean = false, +): Boolean { fun low(b: Int?) = b != null && b <= StrapBands.LOW_BATTERY - return paired != wasPaired || charging != wasCharging || low(battery) != low(wasBattery) + return paired != wasPaired || charging != wasCharging || low(battery) != low(wasBattery) || failing != wasFailing } /** @@ -57,6 +77,8 @@ fun strapStatusLine( StrapStatus.NotPaired -> strings.get(R.string.system_widget_status_not_paired) is StrapStatus.LowBattery -> strings.format(R.string.system_widget_status_low_battery, status.percent) StrapStatus.Syncing -> strings.get(R.string.system_widget_status_syncing) + StrapStatus.SyncFailed -> strings.get(R.string.system_widget_status_not_synced) + StrapStatus.BluetoothOff -> strings.get(R.string.system_widget_status_bluetooth_off) is StrapStatus.StaleSync -> strings.format(R.string.system_widget_status_synced, syncedWhen(status.at, now, zone, locale)) } diff --git a/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt b/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt index cb160751..c6952869 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt @@ -13,7 +13,7 @@ import org.openstrap.app.device.ConnectionState /** * The strap status button's tap on a stale sync (widgets spec 4, 5): syncs in place, no activity. Connected, it's the same * sync as pulling Today down. Away, it reconnects as the app does in the background (a Disconnect the user tapped - * holds), and connecting syncs on its own. The line reads Syncing while it runs, and [WidgetUpdater] + * holds, and Sync now doesn't end it), and connecting syncs on its own. The line reads Syncing while it runs, and [WidgetUpdater] * refreshes the widgets as it starts and ends. */ class SyncNowAction : ActionCallback { diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetParts.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetParts.kt index 382c3d5e..0012676d 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetParts.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetParts.kt @@ -155,7 +155,12 @@ internal val LocalStatusLine = staticCompositionLocalOf { null } internal fun statusLine(data: WidgetData): StatusLine? { val t = data.now.epochSecond val status = if (WidgetRefresh.statusOverride != null) WidgetRefresh.debugStatus(t) else { - data.strap?.let { s -> strapStatus(s.paired, s.battery, s.charging, s.lastSyncDone, t, syncing = data.syncing) } + data.strap?.let { s -> + strapStatus( + s.paired, s.battery, s.charging, s.lastSyncDone, t, syncing = data.syncing, + failingSince = s.failingSince, bluetoothOff = data.bluetoothOff, + ) + } } return status?.let { StatusLine.of(it, t, data.zone) } } @@ -354,8 +359,8 @@ private fun StatusTapTarget(line: StatusLine, top: Float) { private fun statusAction(status: StrapStatus): Action? { val context = LocalContext.current return when (status) { - StrapStatus.NotPaired, is StrapStatus.LowBattery -> actionStartActivity(openStrap(context)) - is StrapStatus.StaleSync -> actionRunCallback() + StrapStatus.NotPaired, is StrapStatus.LowBattery, StrapStatus.BluetoothOff -> actionStartActivity(openStrap(context)) + is StrapStatus.StaleSync, StrapStatus.SyncFailed -> actionRunCallback() StrapStatus.Syncing -> null } } @@ -470,7 +475,8 @@ private fun StatusButtonView(line: StatusLine, f: WidgetFrame) { return } val (icon, color) = when (status) { - is StrapStatus.StaleSync -> AppIcons.Refresh04 to MetricColors.warn + is StrapStatus.StaleSync, StrapStatus.SyncFailed -> AppIcons.Refresh04 to MetricColors.warn + StrapStatus.BluetoothOff -> AppIcons.Bluetooth to MetricColors.warn is StrapStatus.LowBattery -> AppIcons.BatteryLow to MetricColors.warn else -> AppIcons.Watch to Color.White } diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt index 710167ad..8fbd9e8c 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt @@ -2,6 +2,7 @@ package org.openstrap.app.widget import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update import org.openstrap.app.BuildConfig import org.openstrap.app.data.WidgetKind import org.openstrap.app.ui.glow.draw.GlowMood @@ -17,7 +18,7 @@ object WidgetRefresh { fun version(kind: WidgetKind): StateFlow = versions.getValue(kind) fun bump(kind: WidgetKind) { - versions.getValue(kind).value++ + versions.getValue(kind).update { it + 1 } } private val resizes = WidgetKind.entries.associateWith { MutableStateFlow(0) } @@ -26,7 +27,7 @@ object WidgetRefresh { fun resized(kind: WidgetKind): StateFlow = resizes.getValue(kind) fun resize(kind: WidgetKind) { - resizes.getValue(kind).value++ + resizes.getValue(kind).update { it + 1 } } /** @@ -52,7 +53,7 @@ object WidgetRefresh { /** * Debug builds: the strap status line every widget shows instead of the real one, for the gallery: "notpaired", - * "low", "stale" (4 hours ago), "yesterday", "week" (3 days ago), "syncing", or "none" for no line; null reads + * "low", "stale" (4 hours ago), "yesterday", "week" (3 days ago), "syncing", "failed", "bluetooth", or "none" for no line; null reads * the strap. */ @Volatile @@ -69,6 +70,8 @@ object WidgetRefresh { "yesterday" -> StrapStatus.StaleSync(now - 86_400) "week" -> StrapStatus.StaleSync(now - 3 * 86_400) "syncing" -> StrapStatus.Syncing + "failed" -> StrapStatus.SyncFailed + "bluetooth" -> StrapStatus.BluetoothOff else -> null } diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt index ccf6c9b8..134f270f 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt @@ -58,6 +58,8 @@ class WidgetData( val recovery: RecoveryRead?, val sleep: Result?, val momentWidget: Result?, + /** Bluetooth is off on the phone, which the status line says before anything about the strap. */ + val bluetoothOff: Boolean = false, ) { /** The moment's inputs with [bedtime], null when they couldn't be read. */ fun momentInputs(bedtime: LocalTime?): MomentInputs? = moment?.getOrNull()?.copy(usualBedtime = bedtime) @@ -110,11 +112,15 @@ class WidgetSnapshot( private val location: () -> Boolean, /** The widgets placed now. */ private val placed: () -> Set, + /** Whether Bluetooth is off on the phone now. */ + private val bluetoothOff: () -> Boolean = { false }, ) { suspend fun gather(kinds: Set, now: Instant, zone: ZoneId): WidgetData { val today = now.atZone(zone).toLocalDate() val t = now.epochSecond + // The strap's status and whether it is syncing, read together: one moment for the status line. val strap = catching { settings.strapSnapshot.first() }.onFailure { logUnread("strap status", it) }.getOrNull() + val isSyncing = syncing() val workouts = if (kinds.any { it in MOOD_KINDS }) catching { recentWorkouts(t) } else null val span = if (kinds.any { it in NIGHT_KINDS }) catching { sleepSpanSessions(today, zone) } else null val moment = workouts?.let { w -> catching { momentInputs(w.getOrThrow(), span?.getOrNull(), today, t, zone) } } @@ -131,7 +137,8 @@ class WidgetSnapshot( now = now, zone = zone, strap = strap, - syncing = syncing(), + syncing = isSyncing, + bluetoothOff = bluetoothOff(), moment = moment, usualBedtime = bedtime, steps = goal?.takeIf { WidgetKind.Steps in kinds }?.let { StepsRead(it, day) }, diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetStatusLine.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetStatusLine.kt index 09ed7867..e1186f3f 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetStatusLine.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetStatusLine.kt @@ -30,7 +30,8 @@ data class StatusLine(val status: StrapStatus, val options: List) { val shorter = when (status) { StrapStatus.NotPaired -> listOf(strings.get(R.string.system_widget_status_not_paired_short)) is StrapStatus.LowBattery -> listOf(strings.format(R.string.system_widget_status_percent, status.percent)) - StrapStatus.Syncing -> emptyList() + StrapStatus.Syncing, StrapStatus.SyncFailed -> emptyList() + StrapStatus.BluetoothOff -> listOf(strings.get(R.string.system_widget_status_bluetooth_off_short)) is StrapStatus.StaleSync -> { val then = Instant.ofEpochSecond(status.at).atZone(zone).toLocalDate() val days = ChronoUnit.DAYS.between(then, Instant.ofEpochSecond(now).atZone(zone).toLocalDate()) diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetTriggers.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetTriggers.kt index 811eaea9..d828b479 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetTriggers.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetTriggers.kt @@ -51,6 +51,8 @@ internal class WidgetTriggers( val profile: Flow, /** The phone's clock, date or time zone was changed ([org.openstrap.app.data.Today.changes]). */ val clockChanges: Flow = emptyFlow(), + /** Whether Bluetooth is off on the phone: the status line says so. */ + val bluetoothOff: Flow = emptyFlow(), val now: () -> Long, ) @@ -74,21 +76,30 @@ internal fun CoroutineScope.watchWidgetTriggers(t: WidgetTriggers, changed: (Set var previous: SyncState = SyncState.Idle t.sync.collect { s -> if (s is SyncState.Running && previous !is SyncState.Running) launch { - val done = catching { t.strapSnapshot.first().lastSyncDone }.getOrNull() - if (syncStale(done, t.now())) changed(all) + val kept = catching { t.strapSnapshot.first() }.getOrNull() + // Stale or failing: their line turns to Syncing. + if (syncStale(kept?.lastSyncDone, t.now()) || kept?.failingSince != null) changed(all) } previous = s } } - // When the status line could change: pairing, the low battery edge, charging. + // When the status line could change: pairing, the low battery edge, charging, a sync failing or working again. launch { var before: StrapSnapshot? = null t.strapSnapshot.collect { now -> val was = before before = now - if (was != null && strapStateChanged(now.paired, now.battery, now.charging, was.paired, was.battery, was.charging)) changed(all) + if (was != null && strapStateChanged( + now.paired, now.battery, now.charging, was.paired, was.battery, was.charging, + failing = now.failingSince != null, wasFailing = was.failingSince != null, + ) + ) { + changed(all) + } } } + // Bluetooth going off or on moves the line, whatever the strap's own state says. + launch { t.bluetoothOff.distinctUntilChanged().drop(1).collect { changed(all) } } launch { t.todaySteps.filterNotNull().collect { stepsChanged() } } // Everything a widget shows may have moved. launch { t.syncEnded.collect { changed(all) } } diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt index a7e188ae..cbb4d5a0 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt @@ -19,7 +19,10 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import org.openstrap.app.BuildConfig import org.openstrap.app.OpenStrapApp import org.openstrap.app.data.MomentInputs @@ -27,6 +30,7 @@ import org.openstrap.app.data.Today import org.openstrap.app.data.WidgetKind import org.openstrap.app.data.catching import org.openstrap.app.data.settings.SettingsStore +import org.openstrap.app.device.ConnectionState import org.openstrap.app.device.StrapController import org.openstrap.app.device.WorkoutSession import org.openstrap.app.device.launchForBroadcast @@ -94,6 +98,7 @@ class WidgetUpdater( sleepEdits = sleepEdits, profile = settings.profile, clockChanges = Today.changes(app), + bluetoothOff = strap.connection.map { it == ConnectionState.BluetoothOff }, now = { System.currentTimeMillis() / 1000 }, ) scope.watchWidgetTriggers(triggers, ::changed, ::stepsChanged) @@ -197,7 +202,15 @@ class WidgetUpdater( /** [kind]'s receiver and widget, null before it exists: for the debug widget gallery. */ internal fun registration(kind: WidgetKind): Registration? = WIDGETS[kind] - internal suspend fun update(kinds: Set) { + /** + * One refresh at a time, in the order asked: a refresh reads and applies under this lock, so an older read can't + * land after a newer one (a sync's start and end can overlap on a short sync). + */ + private val refreshing = Mutex() + + internal suspend fun update(kinds: Set) = refreshing.withLock { refresh(kinds) } + + private suspend fun refresh(kinds: Set) { val shown = placed().intersect(kinds) if (shown.isEmpty()) return // One read for every widget this refresh updates. A session that can't use it reads for itself. diff --git a/app/src/main/res/values-zh-rCN/strings_core_detail.xml b/app/src/main/res/values-zh-rCN/strings_core_detail.xml index a119cee5..df033d93 100644 --- a/app/src/main/res/values-zh-rCN/strings_core_detail.xml +++ b/app/src/main/res/values-zh-rCN/strings_core_detail.xml @@ -35,11 +35,18 @@ 当前 bpm bpm,最近一次 bpm 静息 + bpm 静息,估算 步,今日目前 步 br/min,睡眠期间 全天平均 %1$s,全天平均 + %1$s,最新于 %2$s + %1$s,高于你的常态 + %1$s,低于你的常态 + %1$s,符合你的常态 + %1$s,白天,最新于 %2$s + %1$s,睡眠中,最新于 %2$s 每日步数,最近 7 天 每日步数,最近 30 天 每日步数,最近 12 个月 diff --git a/app/src/main/res/values-zh-rCN/strings_core_today.xml b/app/src/main/res/values-zh-rCN/strings_core_today.xml index 35f2ed9c..f985dfd9 100644 --- a/app/src/main/res/values-zh-rCN/strings_core_today.xml +++ b/app/src/main/res/values-zh-rCN/strings_core_today.xml @@ -119,5 +119,6 @@ 按住折线可查看任意时刻数值。 实时监测中 于 %1$s + %2$s 起 %1$d 分钟平均 等待手环连接 diff --git a/app/src/main/res/values-zh-rCN/strings_day_info.xml b/app/src/main/res/values-zh-rCN/strings_day_info.xml index a0952238..bc919348 100644 --- a/app/src/main/res/values-zh-rCN/strings_day_info.xml +++ b/app/src/main/res/values-zh-rCN/strings_day_info.xml @@ -30,32 +30,32 @@ 手环佩戴偏松、手部冰凉或手臂频繁活动都可能导致读数跳动。实时测量频率更高,因此开启时曲线看起来波动更频繁。 静息心率 你在最平静时的心率。数值越低,通常代表体能越好、心脏休息越充分。 - 手环每天会根据你最平静的一段时间(通常在睡眠中)计算出该数值。当过去 30 天中有 7 天具有有效数据时,其居中水平加减常规波动范围即为你的常态。 + 通常采用手环当天提供的数值,取自你最平静的一段时间(通常在睡眠中)。若手环当天没有提供,unstrap 会根据全天最平静的半小时进行估算,并会注明。当过去 30 天中有 7 天具有有效数据时,其居中水平加减常规波动范围即为你的常态。 在高强度训练、深夜进食、饮酒、睡眠不佳或身体在抵抗不适时,它会上升;随着体能提升,它会逐渐下降。 夜间手环佩戴偏松或未佩戴会导致参考数据不足。单日的偏高并不能说明太多问题,连续数天的趋势更有参考价值。 HRV 心率变异性,即每次心跳之间微小的时间变化。高于你的常态通常意味着身体恢复良好。 - 手环会在你静止时(主要是睡眠中)测量每次心跳之间的时间间隔,单位为毫秒(ms),当日数值为测量读数的平均值。该数值会与你自己的常态进行对照:即过去 30 天的居中水平加减常规波动范围。 + 手环会在你静止时(主要是睡眠中)测量每次心跳之间的时间间隔,单位为毫秒(ms)。该数值为整个睡眠期间测量读数的平均值,精确到毫秒。该数值会与你自己的常态进行对照:即过去 30 天的居中水平加减常规波动范围。 良好的睡眠和充分的休息会让它升高;压力、高强度训练和饮酒会使它降低。请将其与你自己的常态对比,而不是与他人比较。 测量期间身体活动、手环佩戴偏松或睡眠时间过短都会减少有效读数。HRV 每天的波动很大,因此连续数天的走势比单日读数更具参考意义。 血氧 你的血液携氧能力占比。大多数人的血氧处于 95 到 100%% 之间。 - 手环通过红光和红外光穿透皮肤,并对比两种光线的反射量。当日数值为所有测量读数的平均值。 + 手环通过红光和红外光穿透皮肤,并对比两种光线的反射量。手环白天和夜间都会测量,显示的数值是最近一次读数。睡眠页和恢复页显示的是睡眠期间的平均值。 高海拔环境以及睡眠中的呼吸暂停可能会使它降低。 手环佩戴偏松、皮肤冰凉或测量时身体活动都可能导致读数偏低。此读数仅供健康参考,不作为医疗依据。 压力 手环测得的压力水平,范围从 0 到 100。数值越高,表明身体处于更高的警觉状态。 - 手环会在你静止时根据心率及其变异性计算该数值。运动期间及刚结束后的读数会被排除在外,因为运动并不等同于压力。 + 手环会在你静止时根据心率及其变异性计算该数值。显示的数值是最近一次读数,与你的常态比较的是全天平均值。运动期间及刚结束后的读数会被排除在外,因为运动并不等同于压力。 精神压力、咖啡因和睡眠不足会使它上升;平缓呼吸、充分休息和户外活动能让它降下来。 情绪激动、燥热环境以及生病在手环看来都类似压力;久坐时的微小动作也可能推高读数。 皮肤温度 - 手环下方皮肤的温度。重要的不是绝对数值,而是相对于你常态的变化。 - 手环紧贴皮肤进行测量。绝对温度受佩戴松紧和室温影响,因此 unstrap 会将其显示为相对于过去 30 天常态的变化量。 + 手环下方皮肤的温度。更值得关注的是相对于你常态的变化,而不是数值本身。 + 手环紧贴皮肤进行测量。显示的数值是整个睡眠期间的平均值。绝对温度受佩戴松紧和室温影响,因此 unstrap 会同时显示相对于过去 30 天常态的变化量。 它会随饮酒、室内偏暖、高强度训练、生理周期或身体抵抗不适而产生波动。 温暖的被窝、厚重的被子或手环佩戴偏松,都可能在身体本身并无变化的情况下改变读数。 呼吸频率 你在睡眠中每分钟呼吸的次数。对大多数人而言,这一数值十分稳定。 - 手环会在睡眠期间进行测量,因此每晚生成一个数值,并与过去 30 天你的常态进行对比。 + 手环会在整个睡眠期间进行测量,该数值为这些读数的平均值,并与过去 30 天你的常态进行对比。 在高强度训练之后、处于温暖闷热的房间或身体在抵抗不适时,它可能会高于你的常态。 夜间辗转反侧或部分时间未佩戴手环,都会导致可供参考的读数变少。 步数 @@ -128,7 +128,7 @@ 有 %1$d 分钟来自心率测量而非步数。 从夜间睡眠中打开时,仅显示你的睡眠数据:从入睡到醒来的心率曲线、睡眠中的最低心率以及手环记录的整夜平均值。“月”与“年”视图则为全天完整数据。 - 从夜间睡眠中打开时,显示手环在睡眠期间的读数(与白天的单次测量分开记录),并与你之前的夜间数据进行对比。 + 从夜间睡眠中打开时,显示手环在睡眠期间的读数(与白天的读数分开记录),并与你之前的夜间数据进行对比。 从夜间睡眠中打开时,显示当晚的读数,并与你之前的夜间数据进行对比。 从夜间睡眠中打开时,显示你睡眠期间测量读数的平均值,并与你之前的夜间数据进行对比。“月”与“年”视图则为昼夜全天的完整数据。 呼吸紊乱 diff --git a/app/src/main/res/values-zh-rCN/strings_day_root.xml b/app/src/main/res/values-zh-rCN/strings_day_root.xml index 0a840a0d..196ec53a 100644 --- a/app/src/main/res/values-zh-rCN/strings_day_root.xml +++ b/app/src/main/res/values-zh-rCN/strings_day_root.xml @@ -16,6 +16,9 @@ 在 Android 11 上,unstrap 需要位置权限来查找并连接你的手环。应用不会使用你的位置信息。Android 不会再次询问,请在 unstrap 的设置中前往「权限」开启。 打开设置 暂不 + GPS 运动需要位置权限。Android 不会再次询问,请在 unstrap 的系统设置中开启“权限”。 + 允许通知 + unstrap 通过通知显示运动和手环状态。Android 不会再次询问,请在 unstrap 的系统设置中开启“通知”。 无法同步。%1$s 手环未连接。 正在同步手环… diff --git a/app/src/main/res/values-zh-rCN/strings_day_sleep.xml b/app/src/main/res/values-zh-rCN/strings_day_sleep.xml index b04d06bd..7d438bbf 100644 --- a/app/src/main/res/values-zh-rCN/strings_day_sleep.xml +++ b/app/src/main/res/values-zh-rCN/strings_day_sleep.xml @@ -20,6 +20,7 @@ 过去 7 晚睡眠平均 %1$d bpm,范围 %2$d 至 %3$d。 昨晚 当晚 + %1$s,已调整 暂无分数 手环未对昨晚睡眠评分 手环未对当晚睡眠评分 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml b/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml index 35881e47..ddc6299d 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_metrics.xml @@ -26,6 +26,7 @@ 日终值 最新读数 全天值 + 全天值,估算 全天平均 睡眠平均 最近 7 天 @@ -43,8 +44,8 @@ 当天暂无数据。 呼吸频率在睡眠期间测量。 %1$s,%2$s - %1$s 于 %2$s - 于 %1$s + %1$s,%3$s 起 %2$d 分钟平均 + %2$s 起 %1$d 分钟平均 步,%1$s %1$s 当周 相关指标 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_ready.xml b/app/src/main/res/values-zh-rCN/strings_glow_ready.xml index 5cac8196..dbd7579e 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_ready.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_ready.xml @@ -35,4 +35,6 @@ %1$d 轮,%2$d 秒运动,%3$d 秒休息 + 手环未连接。没有手环也能记录,但没有实时心率。 + 连接手环 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml b/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml index 852a0b54..4d3a72c2 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_recovery.xml @@ -21,7 +21,6 @@ 压力 身体信号 对比你的常态 - 接近你的常态 最近 7 天平均 暂无分数 最近 7 天 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_share.xml b/app/src/main/res/values-zh-rCN/strings_glow_share.xml index 390b5a89..0df769fa 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_share.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_share.xml @@ -36,4 +36,5 @@ 关闭 线条 隐藏起点与终点 + 无法读取这张照片 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml b/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml index c698c5f5..9d6bb68c 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_sleep.xml @@ -2,6 +2,7 @@ 呼吸紊乱 昨晚 + %1$s,已调整 恢复 %1$s,%2$s,%3$d 分钟 夜间体征 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_today.xml b/app/src/main/res/values-zh-rCN/strings_glow_today.xml index 01314762..0674955d 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_today.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_today.xml @@ -58,6 +58,20 @@ %1$s,睡眠 %2$s 心率 静息 %1$d + 静息 %1$d 估算 + %1$s,估算 + 最新于 %1$s + 放松 + 正常 + 中等 + 偏高 + %1$s,%2$s + 估算 + 白天 + 白天,%1$s + 睡眠中 + 睡眠中,%1$s + 夜间平均 步数 目标 %1$s 今晨 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_workout.xml b/app/src/main/res/values-zh-rCN/strings_glow_workout.xml index 66514a74..989db025 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_workout.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_workout.xml @@ -47,4 +47,5 @@ 暂停 下一项 %1$s。%2$s + 此次运动已删除。 diff --git a/app/src/main/res/values-zh-rCN/strings_system_notifications.xml b/app/src/main/res/values-zh-rCN/strings_system_notifications.xml index 29cc2253..36cd2cd3 100644 --- a/app/src/main/res/values-zh-rCN/strings_system_notifications.xml +++ b/app/src/main/res/values-zh-rCN/strings_system_notifications.xml @@ -31,6 +31,7 @@ 正在验证密钥… 无法连接手环 手环未连接 + 蓝牙已关闭 %1$s 手环电量 %1$d%%。请在今晚充电。 手环已连接 @@ -42,6 +43,7 @@ 手环充电中,%1$d%% %1$s,已同步 重试 + 打开 开始运动 立即同步 已暂停 diff --git a/app/src/main/res/values-zh-rCN/strings_system_widgets.xml b/app/src/main/res/values-zh-rCN/strings_system_widgets.xml index 8e553a6f..b8d5035f 100644 --- a/app/src/main/res/values-zh-rCN/strings_system_widgets.xml +++ b/app/src/main/res/values-zh-rCN/strings_system_widgets.xml @@ -5,6 +5,9 @@ 手环电量 %1$d%% %1$d%% 正在同步… + 未同步 + 蓝牙已关闭 + 蓝牙关闭 已同步 %1$s 打开 本周 diff --git a/app/src/main/res/values-zh-rCN/strings_update.xml b/app/src/main/res/values-zh-rCN/strings_update.xml index dcf091cb..0e7f02e6 100644 --- a/app/src/main/res/values-zh-rCN/strings_update.xml +++ b/app/src/main/res/values-zh-rCN/strings_update.xml @@ -28,4 +28,5 @@ 已更新至 unstrap %1$s 轻触查看新变化。 应用更新 + unstrap 没有安装应用的权限,因此未能更新 diff --git a/app/src/main/res/values-zh-rCN/strings_workout_live.xml b/app/src/main/res/values-zh-rCN/strings_workout_live.xml index 3899be7b..4e1ae61b 100644 --- a/app/src/main/res/values-zh-rCN/strings_workout_live.xml +++ b/app/src/main/res/values-zh-rCN/strings_workout_live.xml @@ -179,4 +179,8 @@ 使用此名称 当前 不命名,仅按组编号 + + 尚未保存 + 运动未能保存,仍在继续记录。 + 重试 diff --git a/app/src/main/res/values-zh-rCN/strings_you_data.xml b/app/src/main/res/values-zh-rCN/strings_you_data.xml index 55d50180..9837c768 100644 --- a/app/src/main/res/values-zh-rCN/strings_you_data.xml +++ b/app/src/main/res/values-zh-rCN/strings_you_data.xml @@ -57,6 +57,8 @@ 找回 unstrap 曾保存在那里的数据 打开 Health Connect 权限与数据 + 允许后才会复制卡路里、呼吸频率和最大摄氧量。 + 再次请求 安装 Health Connect 在此手机上 Health Connect 是来自 Play 商店的应用。请安装它以便将数据复制到其中。 无法打开 Play 商店。 diff --git a/app/src/main/res/values-zh-rCN/strings_you_strap.xml b/app/src/main/res/values-zh-rCN/strings_you_strap.xml index 7b3e49cf..7c2a0a2f 100644 --- a/app/src/main/res/values-zh-rCN/strings_you_strap.xml +++ b/app/src/main/res/values-zh-rCN/strings_you_strap.xml @@ -11,6 +11,7 @@ 未配对 上次连接于 %1$s 未连接 + 蓝牙已关闭 断开手环连接? 手环会继续独立记录,但在重新连接之前,unstrap 将无法同步数据或显示实时心率。 正在进行的同步将停止。手环会继续独立记录,但只有再次连接后,unstrap 才会同步或显示实时心率。 @@ -25,6 +26,7 @@ 你的手环 立即同步 连接 + 打开蓝牙 查找手环 停止振动 正在读取… diff --git a/app/src/main/res/values/strings_core_data.xml b/app/src/main/res/values/strings_core_data.xml index 0bec06e9..0d190494 100644 --- a/app/src/main/res/values/strings_core_data.xml +++ b/app/src/main/res/values/strings_core_data.xml @@ -22,7 +22,7 @@ %1$s/min vs usual - %1$s%%, %2$s vs usual + %1$s%%, %2$s vs usual Load %1$s, usual %2$s diff --git a/app/src/main/res/values/strings_core_detail.xml b/app/src/main/res/values/strings_core_detail.xml index 9d1b94bc..4157339e 100644 --- a/app/src/main/res/values/strings_core_detail.xml +++ b/app/src/main/res/values/strings_core_detail.xml @@ -58,6 +58,8 @@ bpm now bpm, latest bpm resting + + bpm resting, estimated steps so far today steps @@ -66,6 +68,15 @@ Day average %1$s, day average + + %1$s, latest at %2$s + + %1$s, above your normal + %1$s, below your normal + %1$s, within your normal + + %1$s, daytime, latest at %2$s + %1$s, while asleep, latest at %2$s steps a day, last 7 days steps a day, last 30 days diff --git a/app/src/main/res/values/strings_core_today.xml b/app/src/main/res/values/strings_core_today.xml index e7b622b4..c647724c 100644 --- a/app/src/main/res/values/strings_core_today.xml +++ b/app/src/main/res/values/strings_core_today.xml @@ -256,6 +256,8 @@ Live now At %1$s + + %1$d min average from %2$s Waiting for the strap diff --git a/app/src/main/res/values/strings_day_info.xml b/app/src/main/res/values/strings_day_info.xml index 6b446bca..8388d6d7 100644 --- a/app/src/main/res/values/strings_day_info.xml +++ b/app/src/main/res/values/strings_day_info.xml @@ -57,42 +57,42 @@ Resting heart rate Your heart rate at its calmest. Lower usually means a fitter, well rested heart. - The strap calculates it each day from your calmest stretch, usually in sleep. Your normal is the middle of your last 30 days, give or take a usual spread, once 7 of them have a value. + Normally it\'s the strap\'s own figure for the day, from your calmest stretch, usually in sleep. When the strap sent none, unstrap estimates it from the calmest half hour of the day, and says so. Your normal is the middle of your last 30 days, give or take a usual spread, once 7 of them have a value. It rises after hard training, late meals, alcohol, poor sleep or when your body is fighting something off, and falls as fitness builds. A night with the strap loose or off gives it less to go on. One high day says less than a few in a row. HRV Heart rate variability, the small changes in time between heartbeats. Higher than your normal often means your body is well recovered. - The strap measures the time between beats, in milliseconds (ms), while you\'re still, mostly in sleep, and the day\'s value is the average of its readings. It\'s read against your own normal: the middle of your last 30 days, give or take a usual spread. + The strap measures the time between beats, in milliseconds (ms), while you\'re still, mostly in sleep. The figure is the average of its readings through your sleep, to the nearest ms. It\'s read against your own normal: the middle of your last 30 days, give or take a usual spread. Good sleep and rest raise it. Stress, hard training and alcohol lower it. Compare it with your own normal, not other people\'s. Moving during a reading, a loose strap or a short night leave fewer clean readings. HRV swings a lot from day to day, so a few days in a row say more than one. Blood oxygen How much of your blood\'s capacity is carrying oxygen. Most people sit at 95 to 100%%. - The strap shines red and infrared light through the skin and compares how much of each comes back. The day\'s value is the average of its readings. + The strap shines red and infrared light through the skin and compares how much of each comes back. It reads through the day and night, and the number is the latest reading. The Sleep and Recovery tabs show the average while you slept. Altitude and pauses in breathing during sleep can lower it. A loose strap, cold skin or moving during a reading can give low values. It\'s a wellness reading, not a medical one. Stress The strap\'s stress level from 0 to 100. Higher means your body is more on alert. - The strap calculates it from your heart rate and its variability while you\'re still. Readings during and just after a workout are left out, since exercise isn\'t stress. + The strap calculates it from your heart rate and its variability while you\'re still. The number is the latest reading, and the day\'s average is what is compared with your usual. Readings during and just after a workout are left out, since exercise isn\'t stress. Pressure, caffeine and too little sleep raise it. Calm breathing, rest and time outdoors bring it down. Excitement, heat and an illness look like stress to the strap. Small movements while sitting can push it up. Skin temperature - The temperature of your skin under the strap. What matters is the change from your normal, not the level. - The strap measures it against your skin. The level depends on fit and the room, so unstrap shows it as a change from your normal of the last 30 days. + The temperature of your skin under the strap. What to watch is the change from your normal, more than the level. + The strap measures it against your skin. The number is the average through your sleep. The level depends on fit and the room, so unstrap shows the change from your normal of the last 30 days with it. It moves with alcohol, a warm room, hard training, the menstrual cycle, or when your body is fighting something off. A warm bed, a heavy duvet or the strap sitting loose all change it without your body changing. Breathing rate How many breaths you take a minute while asleep. It stays very steady for most people. - The strap measures it during sleep, so there\'s one value a night, read against your normal of the last 30 days. + The strap measures it through your sleep, and the figure is the average of those readings, read against your normal of the last 30 days. It can rise above your normal after a hard training day, in a warm, stuffy room, or when your body is fighting something off. A restless night, or the strap off for part of it, leaves fewer readings to go on. @@ -215,7 +215,7 @@ Opened from the night, it shows only your sleep: the line from falling asleep to waking, the lowest while asleep and the strap\'s average for the night. Month and Year are whole days. - Opened from the night, it shows the strap\'s readings in sleep, kept apart from the spot readings in the day, against your earlier nights. + Opened from the night, it shows the strap\'s readings in sleep, kept apart from the readings in the day, against your earlier nights. Opened from the night, it\'s that night\'s readings, against your earlier nights. diff --git a/app/src/main/res/values/strings_day_root.xml b/app/src/main/res/values/strings_day_root.xml index d80f69a1..52c7fd59 100644 --- a/app/src/main/res/values/strings_day_root.xml +++ b/app/src/main/res/values/strings_day_root.xml @@ -35,6 +35,11 @@ Open settings Not now + + GPS workouts need location access. Android won\'t ask again, so turn it on in unstrap\'s settings, under Permissions. + + Allow notifications + unstrap shows your workout and strap status as a notification. Android won\'t ask again, so turn it on in unstrap\'s settings, under Notifications. Couldn\'t sync. %1$s diff --git a/app/src/main/res/values/strings_day_sleep.xml b/app/src/main/res/values/strings_day_sleep.xml index d2b0e254..ed66fecd 100644 --- a/app/src/main/res/values/strings_day_sleep.xml +++ b/app/src/main/res/values/strings_day_sleep.xml @@ -48,6 +48,8 @@ last night that night + + %1$s, adjusted No score diff --git a/app/src/main/res/values/strings_glow_metrics.xml b/app/src/main/res/values/strings_glow_metrics.xml index ecfac6d6..8dc2a934 100644 --- a/app/src/main/res/values/strings_glow_metrics.xml +++ b/app/src/main/res/values/strings_glow_metrics.xml @@ -52,6 +52,8 @@ Latest reading For the day + + For the day, estimated Day average Average asleep @@ -89,10 +91,10 @@ Breathing rate is measured during sleep. %1$s, %2$s - - %1$s at %2$s - - at %1$s + + %1$s, %2$d min average from %3$s + + %1$d min average from %2$s steps, %1$s diff --git a/app/src/main/res/values/strings_glow_ready.xml b/app/src/main/res/values/strings_glow_ready.xml index 67d77404..da03201f 100644 --- a/app/src/main/res/values/strings_glow_ready.xml +++ b/app/src/main/res/values/strings_glow_ready.xml @@ -39,6 +39,10 @@ %d sports + + Your strap is disconnected. Recording works without it, but with no live heart rate. + + Connect strap bpm, live from your strap diff --git a/app/src/main/res/values/strings_glow_recovery.xml b/app/src/main/res/values/strings_glow_recovery.xml index 8bced953..1859a527 100644 --- a/app/src/main/res/values/strings_glow_recovery.xml +++ b/app/src/main/res/values/strings_glow_recovery.xml @@ -47,8 +47,6 @@ Body signals Against your normal - - Close to your normal Average of the last 7 days diff --git a/app/src/main/res/values/strings_glow_share.xml b/app/src/main/res/values/strings_glow_share.xml index 3eb28385..4ff028db 100644 --- a/app/src/main/res/values/strings_glow_share.xml +++ b/app/src/main/res/values/strings_glow_share.xml @@ -70,6 +70,8 @@ Change photo Add a photo + + Couldn\'t read that photo Route diff --git a/app/src/main/res/values/strings_glow_sleep.xml b/app/src/main/res/values/strings_glow_sleep.xml index fbce50b4..442102ce 100644 --- a/app/src/main/res/values/strings_glow_sleep.xml +++ b/app/src/main/res/values/strings_glow_sleep.xml @@ -8,6 +8,8 @@ Breathing disturbances Last night + + %1$s, adjusted Restore diff --git a/app/src/main/res/values/strings_glow_today.xml b/app/src/main/res/values/strings_glow_today.xml index 484f3997..185c1e95 100644 --- a/app/src/main/res/values/strings_glow_today.xml +++ b/app/src/main/res/values/strings_glow_today.xml @@ -120,6 +120,28 @@ Heart rate Resting %1$d + + Resting %1$d est. + + Relaxed + Normal + Medium + High + + %1$s, %2$s + + %1$s, estimated + + Latest at %1$s + + Estimated + + Daytime + Daytime, %1$s + While asleep + While asleep, %1$s + + Night average Steps diff --git a/app/src/main/res/values/strings_glow_workout.xml b/app/src/main/res/values/strings_glow_workout.xml index 87906176..2bd71414 100644 --- a/app/src/main/res/values/strings_glow_workout.xml +++ b/app/src/main/res/values/strings_glow_workout.xml @@ -6,6 +6,8 @@ unstrap is the app's name, written in lowercase even at the start of a sentence. Keep it as it is. --> + + This workout was deleted. Workout diff --git a/app/src/main/res/values/strings_system_notifications.xml b/app/src/main/res/values/strings_system_notifications.xml index 812630e8..570091d0 100644 --- a/app/src/main/res/values/strings_system_notifications.xml +++ b/app/src/main/res/values/strings_system_notifications.xml @@ -64,6 +64,7 @@ Couldn\'t reach the strap Strap not connected + Bluetooth is off %1$s @@ -82,6 +83,7 @@ %1$s, synced Retry + Turn on Start workout Sync now diff --git a/app/src/main/res/values/strings_system_widgets.xml b/app/src/main/res/values/strings_system_widgets.xml index b94725e2..a7306337 100644 --- a/app/src/main/res/values/strings_system_widgets.xml +++ b/app/src/main/res/values/strings_system_widgets.xml @@ -15,6 +15,9 @@ %1$d%% Syncing… + Not synced + Bluetooth is off + Bluetooth off Synced %1$s diff --git a/app/src/main/res/values/strings_update.xml b/app/src/main/res/values/strings_update.xml index 09a5c798..5633dc47 100644 --- a/app/src/main/res/values/strings_update.xml +++ b/app/src/main/res/values/strings_update.xml @@ -30,6 +30,8 @@ Downloading, %1$s Installing. unstrap closes when it\'s done + + unstrap isn\'t allowed to install apps, so it wasn\'t updated No app file in this release. Open it on GitHub diff --git a/app/src/main/res/values/strings_workout_live.xml b/app/src/main/res/values/strings_workout_live.xml index 0f6e8ba9..f4891f56 100644 --- a/app/src/main/res/values/strings_workout_live.xml +++ b/app/src/main/res/values/strings_workout_live.xml @@ -386,4 +386,11 @@ Now No name, just number the sets + + + Not saved yet + + The workout couldn\'t be saved, so it keeps recording. + + Try again diff --git a/app/src/main/res/values/strings_you_data.xml b/app/src/main/res/values/strings_you_data.xml index 2d4d47fc..bba72357 100644 --- a/app/src/main/res/values/strings_you_data.xml +++ b/app/src/main/res/values/strings_you_data.xml @@ -99,6 +99,9 @@ Bring back what unstrap saved there Open Health Connect Permissions and data + + Calories, breathing rate and VO2 max are left out until you allow them. + Ask again Install Health Connect On this phone Health Connect is an app from the Play Store. Install it to copy your data there. diff --git a/app/src/main/res/values/strings_you_strap.xml b/app/src/main/res/values/strings_you_strap.xml index 948390dd..8a37e8ee 100644 --- a/app/src/main/res/values/strings_you_strap.xml +++ b/app/src/main/res/values/strings_you_strap.xml @@ -20,6 +20,7 @@ Last seen %1$s Not connected + Bluetooth is off Disconnect the strap? @@ -44,6 +45,7 @@ Sync now Connect + Turn on Bluetooth Find strap Stop buzzing diff --git a/app/src/test/kotlin/org/openstrap/app/data/NightMetricsTest.kt b/app/src/test/kotlin/org/openstrap/app/data/NightMetricsTest.kt new file mode 100644 index 00000000..113a0824 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/data/NightMetricsTest.kt @@ -0,0 +1,42 @@ +package org.openstrap.app.data + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.openstrap.app.data.db.HrvSample + +/** The night's HRV: one gate and one rounding for Recovery and for every screen. */ +class NightMetricsTest { + private val start = 10_000L + private val end = 40_000L + + private fun at(t: Long, ms: Int) = HrvSample(t, ms) + + @Test fun `only readings inside the sleep and from 5 to 200 ms count`() { + val readings = listOf( + at(start - 1, 60), at(start, 40), at(start + 600, 4), at(start + 1200, 5), at(start + 1800, 200), + at(start + 2400, 201), at(end, 60), at(end + 1, 90), + ) + // 40, 5, 200 and 60 are in; 4 and 201 are out of range, and the two outside the sleep are out of it. + assertEquals(listOf(40, 5, 200, 60), NightMetrics.sleepHrvReadings(readings, start, end)) + assertEquals(76.25f, NightMetrics.hrvMean(NightMetrics.sleepHrvReadings(readings, start, end))) + } + + @Test fun `the figure shown is the mean to the nearest whole ms`() { + // 51.5 goes up and 51.33 down; a cut to a whole number would give 51 for both. + assertEquals(52f, NightMetrics.sleepHrv(listOf(at(start, 51), at(start + 60, 52)), start, end)) + assertEquals(51f, NightMetrics.sleepHrv(listOf(at(start, 51), at(start + 60, 51), at(start + 120, 52)), start, end)) + } + + @Test fun `a night with no clean reading has no figure`() { + assertNull(NightMetrics.sleepHrv(emptyList(), start, end)) + assertNull(NightMetrics.sleepHrv(listOf(at(start + 10, 3), at(start + 20, 400)), start, end)) + assertNull(NightMetrics.hrvMean(emptyList())) + } + + @Test fun `the screens and Recovery take the same mean`() { + val readings = (0 until 20).map { at(start + it * 600L, 30 + it * 3) } + val mean = NightMetrics.hrvMean(NightMetrics.sleepHrvReadings(readings, start, end))!! + assertEquals(Math.round(mean).toFloat(), NightMetrics.sleepHrv(readings, start, end)) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt b/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt index fae0e57d..1525e164 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/SummariesTest.kt @@ -61,3 +61,39 @@ class BucketTest { assertEquals(listOf(0L to 70, 300L to 90), Summaries.bucketAverage(s)) } } + +class HeartRangeTest { + // One reading a minute with a single dip and a single spike that 5-minute averages would flatten. + private val series = (0 until 10).map { i -> i * 60L to if (i == 3) 44 else if (i == 6) 151 else 70 } + + @Test + fun theDayRangeIsTheStoredLowestAndHighest() { + assertEquals(44 to 151, HeartReadings.heartRange(series, null)) + // Averaged into one 5-minute bucket the same minutes read much narrower. + assertEquals(listOf(0L to 65, 300L to 86), Summaries.bucketAverage(series)) + } + + @Test + fun theStrapsOwnMaximumLeadsOnlyWhenHigher() { + assertEquals(44 to 163, HeartReadings.heartRange(series, 163)) + assertEquals(44 to 151, HeartReadings.heartRange(series, 120)) + // A reading outside what a heart can be is not taken as a maximum. + assertEquals(44 to 151, HeartReadings.heartRange(series, 255)) + assertNull(HeartReadings.heartRange(emptyList(), 163)) + } + + @Test + fun lowestIsTheEarliestOfTheLowestAndMeanIsRounded() { + assertEquals(60L to 44, HeartReadings.lowest(listOf(0L to 70, 60L to 44, 120L to 44))) + assertNull(HeartReadings.lowest(emptyList())) + assertEquals(52, HeartReadings.mean(listOf(0L to 51, 60L to 52))) + assertEquals(51, HeartReadings.mean(listOf(0L to 51, 60L to 51, 120L to 52))) + assertNull(HeartReadings.mean(emptyList())) + } + + @Test + fun withinKeepsTheReadingsInsideBothEnds() { + assertEquals(listOf(60L to 70, 120L to 70), HeartReadings.within(series, 60, 120)) + assertEquals(listOf(60L to 70, 120L to 70, 180L to 44), HeartReadings.within(series, 60, 180)) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/data/settings/ForgetDeviceTest.kt b/app/src/test/kotlin/org/openstrap/app/data/settings/ForgetDeviceTest.kt index 2413b117..41370fc0 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/settings/ForgetDeviceTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/settings/ForgetDeviceTest.kt @@ -57,7 +57,7 @@ class ForgetDeviceTest { val strap = setOf( "device_address", "device_auth_key", "device_name", "companion_association_id", "companion_declined", "held_disconnected", - "strap_battery", "strap_charging", "strap_last_sync_done", + "strap_battery", "strap_charging", "strap_last_sync_done", "strap_sync_failing_since", "zepp_app_token", "zepp_user_id", "zepp_api_base", "zepp_china", "zepp_login_token", "zepp_app_token_at", "zepp_app_ttl", "last_sync_gdsp_1", "last_sync_gdsp_16", ) @@ -65,6 +65,15 @@ class ForgetDeviceTest { assertEquals(strap - setOf("last_sync_gdsp_1", "last_sync_gdsp_16"), SettingsStore.STRAP_KEYS) } + @Test fun `a failure is kept from its first time and a full sync's success ends it`() = runTest { + settings.setLastSyncDone(100) + settings.setSyncFailing(200) + settings.setSyncFailing(300) + assertEquals(StrapSnapshot(false, null, false, 100, 200), settings.strapSnapshot.first()) + settings.setLastSyncDone(400) + assertEquals(StrapSnapshot(false, null, false, 400, null), settings.strapSnapshot.first()) + } + @Test fun `a write to another setting doesn't re-emit a flow`() = runTest { val seen = Collections.synchronizedList(mutableListOf()) val job = scope.launch { settings.goals.collect { seen += it } } diff --git a/app/src/test/kotlin/org/openstrap/app/data/settings/WorkoutLiveTest.kt b/app/src/test/kotlin/org/openstrap/app/data/settings/WorkoutLiveTest.kt new file mode 100644 index 00000000..cd101c6a --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/data/settings/WorkoutLiveTest.kt @@ -0,0 +1,24 @@ +package org.openstrap.app.data.settings + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class WorkoutLiveTest { + @Test fun `kept figures read back as written`() { + val live = WorkoutLive(1_700_000_000, 30, 42.5f, 110f) + assertEquals(live, WorkoutLive.decode(live.encode())) + } + + @Test fun `no kcal yet reads back as none`() { + val live = WorkoutLive(1_700_000_000, 10, null, null) + assertEquals(live, WorkoutLive.decode(live.encode())) + } + + @Test fun `nothing or something broken reads as nothing`() { + assertNull(WorkoutLive.decode(null)) + assertNull(WorkoutLive.decode("")) + assertNull(WorkoutLive.decode("x,1,2,3")) + assertNull(WorkoutLive.decode("1,2,3")) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt b/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt index 2f226b71..0a13c511 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt @@ -79,6 +79,18 @@ class BlePermissionsTest { assertFalse(BlePermissions.granted(mapOf(Manifest.permission.BLUETOOTH_CONNECT to true))) } + @Test @Config(sdk = [34]) fun `a notifications denial is told apart from no answer`() { + val n = Manifest.permission.POST_NOTIFICATIONS + assertTrue(BlePermissions.notificationsDenied(mapOf(n to false))) + assertFalse(BlePermissions.notificationsDenied(mapOf(n to true))) + assertFalse(BlePermissions.notificationsDenied(emptyMap())) + assertEquals(listOf(n), BlePermissions.notifications) + shadowOf(app).denyPermissions(n) + assertFalse(BlePermissions.notificationsGranted(app)) + shadowOf(app).grantPermissions(n) + assertTrue(BlePermissions.notificationsGranted(app)) + } + @Test fun `turned down for good once Android owes no rationale for any of them`() { val activity = Robolectric.buildActivity(android.app.Activity::class.java).setup().get() val pm = shadowOf(activity.packageManager) diff --git a/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt b/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt index 3c7f5edf..4c556d1c 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt @@ -4,6 +4,7 @@ import androidx.room.Room import androidx.test.core.app.ApplicationProvider import kotlinx.coroutines.test.runTest import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.openstrap.app.data.db.OpenStrapDatabase @@ -29,4 +30,18 @@ class FindStrapTest { db.close() } } + + @Test + fun aStartThatFailsLeavesFindingOff() = runTest { + val context = ApplicationProvider.getApplicationContext() + val db = Room.inMemoryDatabaseBuilder(context, OpenStrapDatabase::class.java).allowMainThreadQueries().build() + try { + val strap = StrapManager(context, SettingsStore(context), db.healthDao()) + // Not connected, so the start is refused: Find strap is set before it goes out and rolled back after. + assertTrue(runCatching { strap.findStrap() }.exceptionOrNull() is StrapCommandException) + assertFalse(strap.findingStrap.value) + } finally { + db.close() + } + } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt b/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt index 9961dfc6..432791e5 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt @@ -299,6 +299,17 @@ class HistorySyncTest { assertEquals(1, table("SELECT * FROM pai").size) } + @Test fun `a type cut off after its first chunk keeps that chunk and fails the sync, as Zepp`() = runTest { + seedStrap() + // The first HRV START is served, every later one refused. + strap.refuse = { type -> if (type == HistoryDataType.HRV_RMSSD.code && strap.starts.count { it.first == type } > 1) 5 else null } + runSync() + // The first chunk (two records, one a zero) is stored, and the cursor moved past it. + assertEquals(listOf(listOf(base, 41L)), table("SELECT timestamp, milliseconds FROM hrv ORDER BY timestamp")) + assertEquals(base + 301, cursors.values[key(HistoryDataType.HRV_RMSSD)]) + assertEquals(SyncState.Failed("Sync failed"), state.value) + } + @Test fun `fast-charge mode is acknowledged and starts nothing more`() = runTest { seedStrap() strap.fastRecharge = true diff --git a/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt b/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt index 100dbe54..3c10d7b8 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt @@ -49,4 +49,25 @@ class KeepRecordingNoticeTest { service.destroy() } } + + @Test + fun aClearThatLandsAfterTheServicesRefusalLeavesTheNoticeUp() { + KeepRecordingNotice.serviceRefused(context, sportType = 1) + // The session's start call returned without throwing, after the service had already been refused. + KeepRecordingNotice.clear(context) + assertNotNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + KeepRecordingNotice.serviceUp(context) + assertNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + } + + @Test + fun theNoticeGoesWhenNothingRecordsEvenAfterTheServicesRefusal() { + KeepRecordingNotice.serviceRefused(context, sportType = 1) + KeepRecordingNotice.end(context) + assertNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + // And a plain clear works again afterwards. + KeepRecordingNotice.show(context, sportType = 1) + KeepRecordingNotice.clear(context) + assertNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/LiveHeartRateStreamTest.kt b/app/src/test/kotlin/org/openstrap/app/device/LiveHeartRateStreamTest.kt new file mode 100644 index 00000000..481432cc --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/device/LiveHeartRateStreamTest.kt @@ -0,0 +1,42 @@ +package org.openstrap.app.device + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test +import org.openstrap.app.ble.GattClient +import org.openstrap.app.ble.GattStrapLink +import org.openstrap.protocol.ChannelSession + +/** Live HR's reasons: the workout and the screen are separate, and a pause with nothing open doesn't wait. */ +class LiveHeartRateStreamTest { + private val noLink = object : LiveLink { + override val session: ChannelSession? = null + override val gatt: GattClient? = null + override val link: GattStrapLink? = null + override val activeSession: ChannelSession? = null + } + + @Test + fun theWorkoutAndTheScreenAreSeparateReasons() = runTest { + val log = mutableListOf() + val live = LiveHeartRateStream( + backgroundScope, noLink, MutableStateFlow(ConnectionState.Disconnected), MutableStateFlow(false), { log += it }, clock = { 0L }, + ) + live.setAppVisible(true) + live.setWorkoutActive(true) + live.setWorkoutActive(true) + live.setAppVisible(false) + live.setWorkoutActive(false) + // Each change of the workout is logged once, whatever else is on. + assertEquals(listOf("workout started: live hr stays on in the background", "workout ended"), log) + } + + @Test + fun pauseReturnsAtOnceWhenNothingIsOpen() = runTest { + val live = LiveHeartRateStream( + backgroundScope, noLink, MutableStateFlow(ConnectionState.Disconnected), MutableStateFlow(false), {}, clock = { 0L }, + ) + live.pause() + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt b/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt index f93b26bf..fe075006 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt @@ -14,6 +14,7 @@ import org.junit.Test import org.openstrap.app.ble.GattTimeoutException import org.openstrap.app.testing.assertCleanCopy import org.openstrap.protocol.ProtocolTimeoutException +import org.openstrap.protocol.auth.AuthException /** afterAuth's steps (audit C5) and the connect failure copy (E4, E6). */ @OptIn(ExperimentalCoroutinesApi::class) @@ -77,10 +78,23 @@ class SetupStepTest { } @Test - fun onlyPermissionAndAddressFailuresAreFinal() { + fun onlyPermissionAddressAndTurnedDownKeyFailuresAreFinal() { assertTrue(ConnectErrors.isFinal(org.openstrap.app.ble.GattUnusableException("bad", IllegalArgumentException()))) assertTrue(ConnectErrors.isFinal(SecurityException("denied"))) assertEquals(false, ConnectErrors.isFinal(GattTimeoutException("slow"))) assertEquals(false, ConnectErrors.isFinal(ProtocolTimeoutException("slow"))) + // Wrong key, cloud bind required: the same key fails again. A workout running on the strap ends. + assertTrue(ConnectErrors.isFinal(AuthException(0x26, "wrong key"))) + assertTrue(ConnectErrors.isFinal(AuthException(0x81, "cloud bind"))) + assertEquals(false, ConnectErrors.isFinal(AuthException(5, "workout running"))) + assertEquals(false, ConnectErrors.isFinal(AuthException(0x99, "unknown"))) + } + + @Test + fun aKeyIsTurnedDownExactlyWhenRetryingCantHelp() { + for (status in listOf(5, 7, 8, 0x23, 0x25, 0x26, 0x41, 0x81, 0x99)) { + val e = AuthException(status, "status $status") + assertEquals("status $status", ConnectErrors.isFinal(e), PairingErrors.authFailure(e).keyRejected) + } } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/StepsNotifyTest.kt b/app/src/test/kotlin/org/openstrap/app/device/StepsNotifyTest.kt new file mode 100644 index 00000000..3d56c4b6 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/device/StepsNotifyTest.kt @@ -0,0 +1,32 @@ +package org.openstrap.app.device + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Zepp's `yt00` on a step push: notify goes off only behind the app, with no phone workout, once per 1.5 s. */ +class StepsNotifyTest { + private val push = byteArrayOf(0x07, 0x01, 0x10, 0x27, 0x00, 0x00) + private val longAgo = 10_000L + + @Test fun `a push behind the app with no workout turns notify off`() { + assertTrue(StepsNotify.offOnPush(push, appVisible = false, workoutActive = false, sinceLastOffMs = longAgo)) + } + + @Test fun `a push with the app in front or a workout recording leaves it on`() { + assertFalse(StepsNotify.offOnPush(push, appVisible = true, workoutActive = false, sinceLastOffMs = longAgo)) + assertFalse(StepsNotify.offOnPush(push, appVisible = false, workoutActive = true, sinceLastOffMs = longAgo)) + } + + @Test fun `a query reply or an ack is not a push`() { + val reply = byteArrayOf(0x04, 0x01, 0x01, 0x10, 0x27, 0x00, 0x00) + assertFalse(StepsNotify.offOnPush(reply, appVisible = false, workoutActive = false, sinceLastOffMs = longAgo)) + assertFalse(StepsNotify.offOnPush(byteArrayOf(0x06, 0x01), appVisible = false, workoutActive = false, sinceLastOffMs = longAgo)) + assertFalse(StepsNotify.offOnPush(ByteArray(0), appVisible = false, workoutActive = false, sinceLastOffMs = longAgo)) + } + + @Test fun `a second push within 1_5 s sends no second off`() { + assertFalse(StepsNotify.offOnPush(push, appVisible = false, workoutActive = false, sinceLastOffMs = 1_000)) + assertTrue(StepsNotify.offOnPush(push, appVisible = false, workoutActive = false, sinceLastOffMs = 1_500)) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt index c188fffc..7a19e837 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt @@ -105,6 +105,17 @@ class StrapConnectTest { assertTrue(open(address).isEmpty()) } + @Test + fun bluetoothOffIsItsOwnStateAndNothingIsOpened() = runTest { + val address = "AA:BB:CC:00:00:09" + pair(address) + shadowOf(adapter).setEnabled(false) + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.connect() + strap.connection.first { it == ConnectionState.BluetoothOff } + assertTrue(gatts(address).isEmpty()) + } + @Test fun aSilentStrapOnALiveLinkEndsInFailedWithAReconnect() = runTest { val address = "AA:BB:CC:00:00:02" @@ -170,6 +181,74 @@ class StrapConnectTest { assertTrue(strap.log.value.joinToString("\n"), strap.log.value.none { it.contains("reconnecting") }) } + @Test + fun afterAFailureForGoodNeitherPresenceNorBluetoothComingBackRetries() = runTest { + pair("not an address") + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.connect() + strap.connection.first { it is ConnectionState.Failed } + // What a key the strap turned down sets too (ConnectErrors.isFinal): before, presence events and Bluetooth + // coming back ran the handshake again every few seconds. + strap.backgroundConnect() + context.sendBroadcast( + android.content.Intent(android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED) + .setPackage(context.packageName) + .putExtra(android.bluetooth.BluetoothAdapter.EXTRA_STATE, android.bluetooth.BluetoothAdapter.STATE_ON), + ) + shadowOf(android.os.Looper.getMainLooper()).idle() + delay(10 * 60_000L) + val log = strap.log.value + assertEquals(log.joinToString("\n"), 1, log.count { it.contains("connecting to") }) + assertTrue(log.joinToString("\n"), log.none { it.contains("bluetooth back on") }) + // The user's own connect still tries again. + strap.connect() + delay(1_000) + assertEquals(strap.log.value.joinToString("\n"), 2, strap.log.value.count { it.contains("connecting to") }) + } + + @Test + fun afterDisconnectOnlyOpeningTheAppReconnects() = runTest { + val address = "AA:BB:CC:00:00:06" + pair(address) + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.connect() + strap.connection.first { it == ConnectionState.Connecting } + strap.disconnect() + strap.connection.first { it == ConnectionState.Disconnected } + // Presence events, a workout starting and the widget's Sync now all come through here. + strap.backgroundConnect() + delay(1_000) + assertEquals(strap.log.value.joinToString("\n"), 1, strap.log.value.count { it.contains("connecting to") }) + assertEquals(ConnectionState.Disconnected, strap.connection.value) + // Opening the app is the user's: it clears the hold and connects. + strap.autoConnect() + // The connect reads the paired strap on a real thread first, so wait for it rather than for virtual time. + strap.connection.first { it == ConnectionState.Connecting } + assertEquals(strap.log.value.joinToString("\n"), 2, strap.log.value.count { it.contains("connecting to") }) + } + + @Test + fun aHoldFromBeforeTheProcessRestartStopsBackgroundConnects() = runTest { + pair("AA:BB:CC:00:00:07") + settings.setHeldDisconnected(true) + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.backgroundConnect() + delay(1_000) + assertTrue(strap.log.value.joinToString("\n"), strap.log.value.none { it.contains("connecting to") }) + } + + @Test + fun forgettingTheStrapShowsNotPaired() = runTest { + pair("AA:BB:CC:00:00:08") + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.connect() + strap.connection.first { it == ConnectionState.Connecting } + settings.forgetDevice() + strap.connection.first { it == ConnectionState.NotPaired } + assertEquals(null, strap.info.value) + assertTrue(open("AA:BB:CC:00:00:08").isEmpty()) + } + @Test fun racingConnectsLeaveOneClientOpen() { val address = "AA:BB:CC:00:00:05" diff --git a/app/src/test/kotlin/org/openstrap/app/device/SyncRecordTest.kt b/app/src/test/kotlin/org/openstrap/app/device/SyncRecordTest.kt index 422ae534..571e503c 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/SyncRecordTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/SyncRecordTest.kt @@ -39,4 +39,15 @@ class SyncRecordTest { assertEquals(500L, r.lastAttempt) assertEquals(500L, r.failingSince) } + + @Test fun `a full sync's success ends the failure and a failure keeps the first time`() { + val failing = SyncRecord(lastSuccess = 50).attempted(100).failed(130).attempted(200).failed(230) + assertEquals(130L, failing.failingSince) + assertEquals(50L, failing.lastSuccess) + assertEquals(200L, failing.lastAttempt) + val ok = failing.attempted(300).succeeded(330) + assertEquals(330L, ok.lastSuccess) + assertEquals(300L, ok.lastAttempt) + assertNull(ok.failingSince) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutNotifierTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutNotifierTest.kt new file mode 100644 index 00000000..15e4090d --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutNotifierTest.kt @@ -0,0 +1,81 @@ +package org.openstrap.app.device + +import android.app.NotificationManager +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.openstrap.app.data.db.AppWorkout + +/** Saved and the Keep recording notice follow the session's state, whatever the service is doing (audit S10). */ +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class WorkoutNotifierTest { + private val context = ApplicationProvider.getApplicationContext() + private val manager = shadowOf(context.getSystemService(NotificationManager::class.java)) + private val start = 1_000_000L + private val state = MutableStateFlow(WorkoutState.Idle) + private val stored = AppWorkout( + start = start, end = start + 1_200, sportType = 1, endReason = AppWorkout.END_AUTO, recordedEnd = start + 1_800, + ) + + private fun notifier(scope: TestScope) = WorkoutNotifier(context, state, { stored }, scope) + + private fun recording() = WorkoutState.Recording(stored.copy(end = null, recordedEnd = null), maxHeartRate = 190) + + private fun saved() = manager.getNotification(WorkoutNotifier.SUMMARY_ID) + + @Test + fun savedPostsWhenARecordingEndsAndGoesWhenTheSummaryCloses() = runTest { + val n = notifier(this) + n.sync(recording()) + assertNull(saved()) + state.value = WorkoutState.Ended(start) + n.sync(state.value) + assertNotNull(saved()) + state.value = WorkoutState.Idle + n.sync(WorkoutState.Idle) + assertNull(saved()) + } + + @Test + fun aFreshNotifierDoesNotPostSavedForAnEndedStateItNeverSawRecording() = runTest { + state.value = WorkoutState.Ended(start) + notifier(this).sync(state.value) + assertNull(saved()) + } + + @Test + fun theKeepRecordingNoticeGoesWhenTheSessionStopsRecording() = runTest { + KeepRecordingNotice.serviceRefused(context, sportType = 1) + val n = notifier(this) + n.sync(recording()) + assertNotNull(manager.getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + n.sync(WorkoutState.Idle) + assertNull(manager.getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + } + + @Test + fun undoOnlyAppliesWhileTheWorkoutIsAsTheNotificationLeftIt() { + assertTrue(WorkoutNotifier.undoApplies(stored, stored.end!!, stored.recordedEnd!!)) + // A trim by hand: a user end at another time. + val trimmed = stored.copy(end = start + 900, endReason = AppWorkout.END_USER) + assertFalse(WorkoutNotifier.undoApplies(trimmed, stored.end!!, stored.recordedEnd!!)) + // Trimmed by hand to the same end, still a user end. + assertFalse(WorkoutNotifier.undoApplies(stored.copy(endReason = AppWorkout.END_USER), stored.end!!, stored.recordedEnd!!)) + assertEquals(600L, WorkoutNotifier.cutSeconds(stored)) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt index 5b4e2b51..dcd3ab89 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -101,9 +101,10 @@ class WorkoutSessionTest { private fun session( leftWaitMs: Long = WorkoutSession.LEFT_WAIT_MS, on: Context = context, settings: SettingsStore = SettingsStore(context), + restoreRetryMs: Long = WorkoutSession.RESTORE_RETRY_MS, ) = WorkoutSession( on, dao, settings, strap, MaxHeartRates(dao, flowOf(profile())), clock = { clock.now }, scope = scope, - leftWaitMs = leftWaitMs, + leftWaitMs = leftWaitMs, restoreRetryMs = restoreRetryMs, ) private fun StateFlow.await(what: String = "state", predicate: (T) -> Boolean): T = runBlocking { @@ -157,14 +158,46 @@ class WorkoutSessionTest { } /** Zepp's `bo60.j(2)` on a reconnect: the config, then PAUSE while paused, RESUME once resumed, else START. */ + @Test + fun anEndThatDidNotReachTheStrapGoesOnTheNextConnectOnce() { + val s = session() + val connected = ConnectionState.Connected(80, "3.27.0.1") + strap.connection.value = connected + s.start(sportType = 24) + s.recording() + clock.advance(Duration.ofSeconds(120)) + // Out of range: the STOP fails. + strap.connection.value = ConnectionState.Disconnected + strap.sportFails = true + s.end() + s.state.await { it !is WorkoutState.Recording } + runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.none { it.first == SportSession.State.STOP }) delay(POLL_MS) } } + strap.sportFails = false + strap.sportStates.clear() + // Back in range: the STOP goes once, with nothing recording. + strap.connection.value = connected + runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.isEmpty()) delay(POLL_MS) } } + Thread.sleep(SETTLE_MS) + assertEquals(listOf(SportSession.State.STOP to false), strap.sportStates.toList()) + // And not again on the next connect. + strap.sportStates.clear() + strap.connection.value = ConnectionState.Connecting + Thread.sleep(SETTLE_MS) + strap.connection.value = connected + Thread.sleep(SETTLE_MS) + assertTrue(strap.sportStates.isEmpty()) + } + @Test fun reconnectSendsTheConfigAndOneStateAsZepp() { val s = session() - var battery = 80 - // A new battery level each time, so the state flow can't fold a quick drop and return into no change. + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") + // A login always passes Connecting, so the session sees the link go and come back. fun reconnect(): Pair { strap.sportStates.clear() - strap.connection.value = ConnectionState.Connected(battery--, "3.27.0.1") + strap.connection.value = ConnectionState.Connecting + Thread.sleep(SETTLE_MS) + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") return runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.none { it.second }) delay(POLL_MS) @@ -187,6 +220,49 @@ class WorkoutSessionTest { s.state.await { it is WorkoutState.Ended } } + /** + * Zepp sends the workout once at its start and then only on a new login (`xbc.k`, then `rbc` on AUTH_SUCCESS). A + * battery or charging change, a new Connected value here, sends nothing. + */ + @Test + fun aBatteryChangeDoesNotSendTheWorkoutAgain() { + val s = session() + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") + s.start(sportType = 1) + s.recording() + runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.isEmpty()) delay(POLL_MS) } } + Thread.sleep(SETTLE_MS) + assertEquals("the start sends it once", listOf(SportSession.State.START to true), strap.sportStates.toList()) + + strap.sportStates.clear() + strap.connection.value = ConnectionState.Connected(79, "3.27.0.1") + strap.connection.value = ConnectionState.Connected(79, "3.27.0.1", charging = true) + Thread.sleep(SETTLE_MS) + assertEquals(emptyList>(), strap.sportStates.toList()) + s.end() + // Seconds long, so it ends unsaved: Idle, not Ended. + s.state.await { it !is WorkoutState.Recording } + } + + /** A workout started with the strap away sends it when the strap logs in, as Zepp's connect callback does. */ + @Test + fun aWorkoutStartedWithTheStrapAwaySendsItOnConnect() { + val s = session() + s.start(sportType = 1) + s.recording() + Thread.sleep(SETTLE_MS) + assertEquals(emptyList>(), strap.sportStates.toList()) + strap.connection.value = ConnectionState.Connecting + Thread.sleep(SETTLE_MS) + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") + runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.isEmpty()) delay(POLL_MS) } } + Thread.sleep(SETTLE_MS) + assertEquals(listOf(SportSession.State.START to true), strap.sportStates.toList()) + s.end() + // Seconds long, so it ends unsaved: Idle, not Ended. + s.state.await { it !is WorkoutState.Recording } + } + @Test fun endedWhilePausedEndsWhereThePauseBegan() { val s = session() @@ -259,6 +335,112 @@ class WorkoutSessionTest { } } + @Test + fun discardTakesTheTwinsAndDismissesInOneStep() { + val t0 = clock.now + runBlocking { + db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = t0 + 300, sportType = 1)) + db.healthDao().insertWorkouts(listOf(Workout(t0 + 3, t0 + 304, 1, 300, null, null, null, null, null, null, null, null, null, 6))) + val gone = db.healthDao().discardAppWorkout(t0, clock.now) + assertEquals(t0, gone?.start) + assertNull(db.healthDao().appWorkoutOnce(t0)) + assertNull(db.healthDao().workoutOnce(t0 + 3)) + assertTrue(db.healthDao().dismissedWorkoutsAll().any { it.start == t0 && it.end == t0 + 300 }) + // A second call finds nothing and changes nothing. + assertNull(db.healthDao().discardAppWorkout(t0, clock.now)) + } + } + + @Test + fun aStartWithoutGpsAvailableDoesNotClaimGps() { + val s = session() + val t0 = clock.now + s.start(sportType = 1, useGps = true, keepRoute = true) + // No location permission in the test: the workout records from steps and says so. + assertEquals(false, s.recording().workout.useGps) + assertEquals(false, stored(t0)!!.useGps) + } + + @Test + fun aStartThatFailsHalfWayLeavesNothingBehind() { + val s = session() + val t0 = clock.now + strap.failActive = true + s.start(sportType = 1) + runBlocking { + withTimeout(WAIT_MS) { + while (strap.refused == 0 || stored(t0) != null || s.state.value !is WorkoutState.Idle) delay(POLL_MS) + } + } + assertNull(stored(t0)) + // And the next one starts as usual. + strap.failActive = false + s.start(sportType = 1) + assertEquals(t0, s.recording().workout.start) + } + + @Test + fun aRestoreThatFailsIsTriedAgainAndKeepsTheRow() { + val t0 = clock.now - 600 + runBlocking { db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1)) } + strap.failActive = true + val s = session(restoreRetryMs = POLL_MS) + s.restore() + s.restored.await { it } + // Marked restored so nothing waits on it, yet the workout is not ended. + assertNull(stored(t0)!!.end) + strap.failActive = false + assertEquals(t0, s.recording().workout.start) + } + + @Test + fun aRestartBringsBackTheRestTimeAddedAndTheKcal() { + val t0 = clock.now - 600 + val settings = SettingsStore(context) + runBlocking { + db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1)) + settings.setWorkoutLive(org.openstrap.app.data.settings.WorkoutLive(t0, 20, 50f, 120f)) + } + val s = session(settings = settings) + s.restore() + assertEquals(20L, s.recording().restExtra) + assertEquals(WorkoutRecorder.Kcal(50f, 120f), s.kcal.value) + } + + @Test + fun anotherWorkoutsKeptFiguresAreNotRestored() { + val t0 = clock.now - 600 + val settings = SettingsStore(context) + runBlocking { + db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1)) + settings.setWorkoutLive(org.openstrap.app.data.settings.WorkoutLive(t0 - 3_600, 20, 50f, 120f)) + } + val s = session(settings = settings) + s.restore() + assertEquals(0L, s.recording().restExtra) + assertNull(s.kcal.value) + } + + @Test + fun theLiveKcalIsKeptWhileRecording() { + val settings = SettingsStore(context) + runBlocking { settings.saveProfile(profile()) } + try { + val s = session(settings = settings) + s.start(sportType = 1) + val start = s.recording().workout.start + runBlocking { + withTimeout(WAIT_MS) { + while (settings.workoutLive(start) == null) delay(POLL_MS) + } + } + s.end() + s.state.await { it !is WorkoutState.Recording } + } finally { + runBlocking { settings.saveProfile(org.openstrap.app.data.settings.UserProfile()) } + } + } + @Test fun aWorkoutLeftRecordingComesBackAfterProcessDeath() { val t0 = clock.now - 600 @@ -608,6 +790,64 @@ class WorkoutSessionTest { assertNotNull(stored(t0)?.end) } + @Test + fun aFailedEndShowsOnTheLiveStateAndTryAgainEndsIt() { + val s = session() + val t0 = clock.now + s.start(sportType = 1) + s.recording() + clock.advance(Duration.ofSeconds(300)) + dao.failing = true + s.end() + val failed = s.recording { it.endFailed } + assertTrue(failed.saveFailed) + assertNull(stored(t0)?.end) + + // Try again is End again, and the flag goes once it saves. + dao.failing = false + s.end() + s.state.await { it is WorkoutState.Ended } + assertNotNull(stored(t0)?.end) + } + + @Test + fun aLaterSuccessDoesNotHideUnsavedSets() { + val s = session() + s.start(sportType = 1) + s.recording() + dao.failingSets = true + s.startSet() + s.recording { SavePart.Sets in it.failing } + // A lap saves the workout fine, and the sets are still unsaved. + clock.advance(Duration.ofSeconds(30)) + s.lap() + val r = s.recording { it.workout.lapMarks.isNotEmpty() } + assertTrue(SavePart.Sets in r.failing) + assertTrue(r.saveFailed) + + dao.failingSets = false + clock.advance(Duration.ofSeconds(5)) + s.setDone() + s.recording { it.failing.isEmpty() && !it.saveFailed } + } + + @Test + fun startSaysWhetherItStartedOrAWorkoutRecordsAlready() { + val s = session() + assertEquals(StartResult.Started, runBlocking { s.start(sportType = 1).await() }) + assertTrue(s.inProgress) + assertEquals(StartResult.AlreadyRecording, runBlocking { s.start(sportType = 2).await() }) + } + + @Test + fun startFailsWhenTheRowCantBeWritten() { + val s = session() + dao.failing = true + assertEquals(StartResult.Failed, runBlocking { s.start(sportType = 1).await() }) + assertTrue(!s.inProgress) + assertTrue(s.state.value is WorkoutState.Idle) + } + @Test fun theSeedIsRecordedBeforeTheLiveReadings() { val t0 = clock.now @@ -737,6 +977,8 @@ class WorkoutSessionTest { /** [HealthDao] that can fail every workout save, or hold the next one until released. */ private class SwitchableDao(private val real: HealthDao) : HealthDao by real { @Volatile var failing = false + /** Only the sets' saves fail. */ + @Volatile var failingSets = false @Volatile private var gate: Gate? = null class Gate { @@ -757,7 +999,7 @@ class WorkoutSessionTest { } override suspend fun upsertSets(sets: List) { - if (failing) throw android.database.sqlite.SQLiteException("disk I/O error") + if (failing || failingSets) throw android.database.sqlite.SQLiteException("disk I/O error") real.upsertSets(sets) } @@ -793,7 +1035,15 @@ class WorkoutSessionTest { override fun disconnect() = Unit override fun syncNow() = Unit override fun setAppVisible(visible: Boolean) = Unit - override fun setWorkoutActive(active: Boolean) = Unit + /** Turning the live stream on fails, as a start that throws half way does. */ + @Volatile var failActive = false + @Volatile var refused = 0 + override fun setWorkoutActive(active: Boolean) { + if (failActive && active) { + refused++ + throw IllegalStateException("strap refused") + } + } override fun showLiveHeartRate(key: Any, shown: Boolean) = Unit override suspend fun checkCanRestart() = Unit override suspend fun installFirmware(file: ByteArray, type: Int, onProgress: (org.openstrap.protocol.firmware.DfuProgress) -> Unit) = Unit @@ -807,8 +1057,12 @@ class WorkoutSessionTest { override suspend fun buzz(pattern: List) = Unit override suspend fun sportSession(state: SportSession.State, sportType: Int, startTime: Long, elapsedSeconds: Long, reconnect: Boolean) { sportStates += state to reconnect + if (sportFails) throw IllegalStateException("not connected") } + /** Every sport command fails, as with the strap out of range. */ + @Volatile var sportFails = false + val sportStates: MutableList> = Collections.synchronizedList(mutableListOf()) override suspend fun sportSessionKeepAlive() = Unit override suspend fun startCallBuzz(pulsed: Boolean) = Unit diff --git a/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt b/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt index 2a753410..4bb98f33 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/ZeppJobsTest.kt @@ -30,11 +30,11 @@ class ZeppJobsTest { } @Test - fun theStrapsJobListIsZepps() { + fun theStrapsJobListIsZeppsThenSkinTemperature() { assertEquals( listOf( "58", "66", "72", "1", "r08", "5", "r0c", "r06", "73", "19", "18", "37", "38", "39", "59", "pai", - "56", "57", "70", "61", "74", "76", "87", "88", "78", "44", + "56", "57", "70", "61", "74", "76", "87", "88", "78", "44", "46", ), names(ZeppJobs.list(gates())), ) @@ -47,8 +47,12 @@ class ZeppJobsTest { assertTrue("r0c" !in jobs && "44" !in jobs && "pai" !in jobs && "13" in jobs) // No readiness module, no readiness jobs. assertTrue(names(ZeppJobs.list(gates(endpoints = emptySet()))).none { it.startsWith("r") || it == "pai" }) - // Never: 2, 46, 43, 86, 7. - assertTrue(names(ZeppJobs.list(gates())).none { it in setOf("2", "46", "43", "86", "7") }) + // Never: 2, 43, 86, 7. + assertTrue(names(ZeppJobs.list(gates())).none { it in setOf("2", "43", "86", "7") }) + // Skin temperature (46) is last, after statistics or without them, and only when the strap advertises it. + assertEquals("46", names(ZeppJobs.list(gates(statisticsDue = false))).last()) + val unadvertised = ZeppJobs.Gates(advertised - 46, features, { true }, 3, 5, sleepPlan = true, statisticsDue = true) + assertTrue("46" !in names(ZeppJobs.list(unadvertised))) } @Test diff --git a/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt b/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt index 506cddc0..3578f511 100644 --- a/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt @@ -7,6 +7,8 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals @@ -88,8 +90,38 @@ class BackupSnapshotTest { assertEquals(10, lines(zip, "activity_minute.csv").size) // The copy was made and is gone again. assertFalse(logged.toString(), logged.any { "no copy" in it }) - assertFalse(File(context.cacheDir, "backup-snapshot.db").exists()) + assertEquals(emptyList(), snapshotFiles()) // The sync's rows are in the database itself. assertEquals(11, db.healthDao().heartRateOnce(t, t + 7200).size) } + + /** The snapshot files left in the cache. */ + private fun snapshotFiles() = context.cacheDir.listFiles { f -> f.name.startsWith("backup-snapshot") }.orEmpty().map { it.name } + + @Test fun `two copies at once use different files and each cleans up its own`() { + val a = BackupSnapshot.take(context, db) + val b = BackupSnapshot.take(context, db) + assertEquals(2, snapshotFiles().filter { it.endsWith(".db") }.size) + a.close() + assertEquals(1, snapshotFiles().filter { it.endsWith(".db") }.size) + b.close() + assertEquals(emptyList(), snapshotFiles()) + } + + @Test fun `data jobs run one at a time and a job inside a job doesn't wait on itself`() = runBlocking { + val order = java.util.Collections.synchronizedList(mutableListOf()) + val first = scope.launch { + DataJobs.exclusive { + order += "a start" + // Calling another data job from inside one goes straight through. + DataJobs.exclusive { order += "a inner" } + delay(100) + order += "a end" + } + } + delay(30) + val second = scope.launch { DataJobs.exclusive { order += "b" } } + first.join(); second.join() + assertEquals(listOf("a start", "a inner", "a end", "b"), order) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/export/SettingsBackupTest.kt b/app/src/test/kotlin/org/openstrap/app/export/SettingsBackupTest.kt index 9b119942..82d438c3 100644 --- a/app/src/test/kotlin/org/openstrap/app/export/SettingsBackupTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/export/SettingsBackupTest.kt @@ -74,11 +74,11 @@ class SettingsBackupTest { "device_address", "device_auth_key", "device_name", "zepp_app_token", "zepp_user_id", "zepp_api_base", "zepp_china", "zepp_login_token", "zepp_app_token_at", "zepp_app_ttl", "companion_association_id", "companion_declined", "held_disconnected", - "strap_battery", "strap_charging", "strap_last_sync_done", "strap_sessions", + "strap_battery", "strap_charging", "strap_last_sync_done", "strap_sync_failing_since", "strap_sessions", "buzz_calls", "buzz_notifications", "health_connect_auto", "health_connect_synced", "health_connect_auto_stopped", "backup_folder", "backup_folder_name", "backup_last_done", "backup_failed", "backup_failed_at", "goal_moment_week", "recap_week", "rewards_started", "history_badges_waiting", "habit_age_seen", "habit_age_seen_day", - "update_checked_at", "update_notified_tag", "update_installing_tag", "update_seen_tag", + "update_checked_at", "update_notified_tag", "update_installing_tag", "update_seen_tag", "workout_live", ) val keys = org.openstrap.app.data.settings.SettingsKeys::class.java.declaredFields .filter { java.lang.reflect.Modifier.isStatic(it.modifiers) && it.type == String::class.java && !it.name.endsWith("_PREFIX") } diff --git a/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt b/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt index 84b43c7b..9d2c59e1 100644 --- a/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/health/HealthConnectRoundTripTest.kt @@ -1,9 +1,13 @@ package org.openstrap.app.health import android.content.Context +import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.HeartRateRecord +import androidx.health.connect.client.records.OxygenSaturationRecord +import androidx.health.connect.client.records.RespiratoryRateRecord import androidx.health.connect.client.records.Record import androidx.health.connect.client.records.SleepSessionRecord +import androidx.health.connect.client.records.Vo2MaxRecord import androidx.health.connect.client.records.metadata.Device import androidx.health.connect.client.records.metadata.Metadata import androidx.test.core.app.ApplicationProvider @@ -14,11 +18,16 @@ import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.openstrap.app.data.db.AppWorkout +import org.openstrap.app.data.db.BreathRate import org.openstrap.app.data.db.HeartRateSample import org.openstrap.app.data.db.OpenStrapDatabase import org.openstrap.app.data.db.SleepEdit import org.openstrap.app.data.db.SleepSession import org.openstrap.app.data.db.SleepStage +import org.openstrap.app.data.db.Spo2Sample +import org.openstrap.app.data.db.SportEffectRow +import org.openstrap.app.data.db.Workout import org.openstrap.app.testing.inMemoryDb import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @@ -115,4 +124,81 @@ class HealthConnectRoundTripTest { assertEquals(null, SleepImport.strapStart("openstrap:hr:360000")) assertEquals(null, SleepImport.strapStart(null)) } + + @Test fun `every breathing rate sample is exported as it was stored`() = runTest { + dao.insertBreathRate(listOf(BreathRate(100 * h, 14), BreathRate(100 * h + 60, 9), BreathRate(300 * h, 16))) + val records = exporter.breathing(100 * h, 101 * h).map { it as RespiratoryRateRecord } + assertEquals(listOf("openstrap:breath:${100 * h}", "openstrap:breath:${100 * h + 60}"), records.map { it.metadata.clientRecordId }) + assertEquals(listOf(14.0, 9.0), records.map { it.rate }) + assertEquals(Instant.ofEpochSecond(100 * h), records.first().time) + } + + @Test fun `blood oxygen is exported from 80 to 100 only, as it is stored`() = runTest { + dao.insertSpo2(listOf(0, 1, 70, 79, 80, 100, 101, 127).mapIndexed { i, p -> Spo2Sample(100 * h + i * 60, p) }) + val records = exporter.bloodOxygen(100 * h, 101 * h).map { it as OxygenSaturationRecord } + assertEquals(listOf(80.0, 100.0), records.map { it.percentage.value }) + } + + private fun strap(start: Long, end: Long, sport: Int = 1, vo2max: Int? = null) = Workout( + start, end, sport, exerciseSeconds = null, calories = null, averageHeartRate = null, maxHeartRate = null, minHeartRate = null, + aerobicTrainingEffect = null, anaerobicTrainingEffect = null, trainingLoad = null, vo2max = vo2max, steps = null, + ) + + private fun effect(end: Long, vo2max: Float?) = SportEffectRow(end, null, vo2max, null, null, null, null, null, null) + + @Test fun `the strap's VO2 max is exported at the workout's end, from the workout or else its effect`() = runTest { + // A day apart, so no workout takes another's effect. + dao.insertWorkouts(listOf(strap(100 * h, 101 * h, vo2max = 48), strap(130 * h, 131 * h), strap(160 * h, 161 * h, vo2max = 0), strap(190 * h, 191 * h, vo2max = 101))) + dao.insertSportEffects(listOf(effect(131 * h + 120, 52.4f), effect(161 * h + 120, 0f))) + val records = exporter.vo2max(90 * h, 240 * h).map { it as Vo2MaxRecord } + assertEquals(listOf("openstrap:vo2max:${100 * h}", "openstrap:vo2max:${130 * h}"), records.map { it.metadata.clientRecordId }) + assertEquals(listOf(48.0, 52.0), records.map { it.vo2MillilitersPerMinuteKilogram }) + assertEquals(listOf(Instant.ofEpochSecond(101 * h), Instant.ofEpochSecond(131 * h + 120)), records.map { it.time }) + assertTrue(records.all { it.measurementMethod == Vo2MaxRecord.MEASUREMENT_METHOD_OTHER }) + } + + @Test fun `unstrap's own VO2 max estimate is not exported`() = runTest { + dao.insertAppWorkouts(listOf(AppWorkout(start = 100 * h, end = 101 * h, sportType = 1, vo2max = 45f))) + assertTrue(exporter.vo2max(90 * h, 140 * h).isEmpty()) + } + + @Test fun `a strap workout is exported as a session of its own`() = runTest { + dao.insertWorkouts(listOf(strap(100 * h, 101 * h, sport = 1), strap(110 * h, 110 * h))) + val records = exporter.strapWorkouts(90 * h, 140 * h).map { it as ExerciseSessionRecord } + // The empty one is left out: Health Connect rejects a session that doesn't end after it starts. + assertEquals(listOf("openstrap:strapworkout:${100 * h}"), records.map { it.metadata.clientRecordId }) + assertEquals(Instant.ofEpochSecond(100 * h), records.single().startTime) + assertEquals(Instant.ofEpochSecond(101 * h), records.single().endTime) + assertEquals(ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, records.single().exerciseType) + } + + @Test fun `a strap workout overlapping a phone workout is left out`() = runTest { + dao.insertAppWorkouts(listOf(AppWorkout(start = 100 * h + 30, end = 101 * h, sportType = 1))) + // The strap's own session of it starts a little after, the next one is clear of it. + dao.insertWorkouts(listOf(strap(100 * h + 40, 101 * h + 60), strap(102 * h, 103 * h))) + assertEquals(listOf("openstrap:strapworkout:${102 * h}"), exporter.strapWorkouts(90 * h, 140 * h).map { it.metadata.clientRecordId }) + } + + @Test fun `a strap workout a phone workout now overlaps loses its record`() = runTest { + val written = ExerciseSessionRecord( + startTime = Instant.ofEpochSecond(100 * h), startZoneOffset = ZoneOffset.UTC, + endTime = Instant.ofEpochSecond(101 * h), endZoneOffset = ZoneOffset.UTC, exerciseType = ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, + metadata = Metadata.autoRecorded(device = band, clientRecordId = "openstrap:strapworkout:${100 * h}"), + ) + val phone = ExerciseSessionRecord( + startTime = Instant.ofEpochSecond(100 * h), startZoneOffset = ZoneOffset.UTC, + endTime = Instant.ofEpochSecond(101 * h), endZoneOffset = ZoneOffset.UTC, exerciseType = ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, + metadata = Metadata.autoRecorded(device = band, clientRecordId = "openstrap:workout:${100 * h}"), + ) + val deleted = mutableListOf() + val store = object : RecordStore { + override suspend fun insert(records: List) = Unit + override suspend fun ownRecords(type: kotlin.reflect.KClass, range: androidx.health.connect.client.time.TimeRangeFilter) = listOf(written, phone) + override suspend fun deleteIds(type: kotlin.reflect.KClass, ids: List) { deleted += ids.map { it } } + override suspend fun deleteRange(type: kotlin.reflect.KClass, range: androidx.health.connect.client.time.TimeRangeFilter) = Unit + } + // Nothing of the strap's is written any more: only its own session goes, the phone's stays. + store.dropStaleStrapWorkouts(90 * h, 140 * h, emptyList()) + assertEquals(listOf(written.metadata.id), deleted) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt b/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt index ba2026e2..ed7b99cf 100644 --- a/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt @@ -4,7 +4,11 @@ import androidx.health.connect.client.records.Record import androidx.health.connect.client.records.SleepSessionRecord import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.time.TimeRangeFilter +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.yield import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test @@ -81,4 +85,26 @@ class RecordStoreTest { assertEquals(listOf("deleteRange", "insert"), store.calls) assertEquals(listOf("openstrap:sleep:1000"), store.records.map { it.metadata.clientRecordId }) } + + @Test fun `writers sharing a lock never run side by side`() = runTest { + val lock = Mutex() + var inside = 0 + var overlapped = false + // A store that lets other coroutines run during its insert, as a real Health Connect call does. + val slow = object : RecordStore { + override suspend fun insert(records: List) { + inside++ + if (inside > 1) overlapped = true + yield() + inside-- + } + override suspend fun ownRecords(type: KClass, range: TimeRangeFilter): List? = emptyList() + override suspend fun deleteIds(type: KClass, ids: List) = Unit + override suspend fun deleteRange(type: KClass, range: TimeRangeFilter) = Unit + } + val one = listOf(sleep(1000, "openstrap:sleep:1000")) + val writers = List(4) { async { slow.writeSerially(lock, one, listOf(SleepSessionRecord::class to range)) } } + writers.awaitAll() + assertTrue(!overlapped) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt index 0bef6667..32378d0e 100644 --- a/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/presentation/DataCopyTest.kt @@ -101,12 +101,14 @@ class DataCopyTest { assertEquals( listOf( "52 ms, −8% vs usual", "54 bpm, +2 vs usual", "7 h 40 asleep", "No sleep debt", "1 h 15 of sleep debt", - "Lowest heart rate 1 h 35 before waking", "±0,0 °C vs usual", "+0,4/min vs usual", "96,3%, −1,2 vs usual", + "Lowest heart rate 1 h 35 before waking", "±0,0 °C vs usual", "+0,4/min vs usual", "96%, −1,2 vs usual", "Load 140, usual 95", ), all.map { RecoveryCopy.detail(it) }, ) - assertEquals("96.3%, −1.2 vs usual", RecoveryCopy.detail(Recovery.Detail.BloodOxygen(96.25f, -1.2f), Locale.US)) + // A whole percent, rounded; the change against usual keeps its decimal. + assertEquals("96%, −1.2 vs usual", RecoveryCopy.detail(Recovery.Detail.BloodOxygen(96.25f, -1.2f), Locale.US)) + assertEquals("97%, −1.2 vs usual", RecoveryCopy.detail(Recovery.Detail.BloodOxygen(96.5f, -1.2f), Locale.US)) assertCleanCopy(all.map { RecoveryCopy.detail(it) } + all.map { RecoveryCopy.detail(it, Locale.US) }) } } diff --git a/app/src/test/kotlin/org/openstrap/app/presentation/StressLevelTest.kt b/app/src/test/kotlin/org/openstrap/app/presentation/StressLevelTest.kt new file mode 100644 index 00000000..6b6252ac --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/presentation/StressLevelTest.kt @@ -0,0 +1,28 @@ +package org.openstrap.app.presentation + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** Zepp's stress bands: relaxed 0 to 39, normal 40 to 59, medium 60 to 79, high 80 to 100. */ +class StressLevelTest { + @Test fun `a stress value is judged by Zepp's bands`() { + assertEquals(StressLevel.Relaxed, StressLevel.of(0f)) + assertEquals(StressLevel.Relaxed, StressLevel.of(39f)) + assertEquals(StressLevel.Normal, StressLevel.of(40f)) + assertEquals(StressLevel.Normal, StressLevel.of(59f)) + assertEquals(StressLevel.Medium, StressLevel.of(60f)) + assertEquals(StressLevel.Medium, StressLevel.of(79f)) + assertEquals(StressLevel.High, StressLevel.of(80f)) + assertEquals(StressLevel.High, StressLevel.of(100f)) + } + + @Test fun `the level agrees with the whole number shown`() { + assertEquals(StressLevel.Normal, StressLevel.of(39.6f)) + assertEquals(StressLevel.Relaxed, StressLevel.of(39.4f)) + assertEquals(StressLevel.High, StressLevel.of(79.5f)) + } + + @Test fun `each level has its word`() { + assertEquals(listOf("Relaxed", "Normal", "Medium", "High"), StressLevel.entries.map { it.word() }) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt index e3462e15..0026fc7d 100644 --- a/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt @@ -2,6 +2,7 @@ package org.openstrap.app.presentation import org.junit.Assert.assertEquals import org.junit.Test +import org.openstrap.app.update.Check import org.openstrap.app.update.Install import org.openstrap.app.update.InstallFailure import org.openstrap.app.update.Release @@ -21,20 +22,20 @@ class UpdateCopyTest { @Test fun `the You page's row says a new version, checking, up to date, or just the version`() { assertEquals("unstrap 2.2.0 is ready to install", UpdateCopy.summary(UpdateState(listOf(r220, r210), checkedAt = now), "2.1.0", now, utc, Locale.UK)) - assertEquals("Checking…", UpdateCopy.summary(UpdateState(listOf(r210), checking = true), "2.1.0", now, utc, Locale.UK)) + assertEquals("Checking…", UpdateCopy.summary(UpdateState(listOf(r210), check = Check.Checking), "2.1.0", now, utc, Locale.UK)) assertEquals("Up to date. Checked today at 19:00", UpdateCopy.summary(UpdateState(listOf(r210), checkedAt = now - 3600), "2.1.0", now, utc, Locale.UK)) assertEquals("Version 2.1.0", UpdateCopy.summary(UpdateState(), "2.1.0", now, utc, Locale.UK)) } @Test fun `Check now says when it last looked, and when GitHub couldn't be reached`() { assertEquals("Never checked", UpdateCopy.checkStatus(UpdateState(), now, utc, Locale.UK)) - assertEquals("Checking GitHub…", UpdateCopy.checkStatus(UpdateState(checking = true), now, utc, Locale.UK)) + assertEquals("Checking GitHub…", UpdateCopy.checkStatus(UpdateState(check = Check.Checking), now, utc, Locale.UK)) assertEquals("Last checked yesterday at 23:50", UpdateCopy.checkStatus(UpdateState(checkedAt = 1792195200L - 600), now, utc, Locale.UK)) assertEquals( "Couldn't reach GitHub. Last checked today at 19:00", - UpdateCopy.checkStatus(UpdateState(checkedAt = now - 3600, checkFailed = true), now, utc, Locale.UK), + UpdateCopy.checkStatus(UpdateState(checkedAt = now - 3600, check = Check.Failed), now, utc, Locale.UK), ) - assertEquals("Couldn't reach GitHub", UpdateCopy.checkStatus(UpdateState(checkFailed = true), now, utc, Locale.UK)) + assertEquals("Couldn't reach GitHub", UpdateCopy.checkStatus(UpdateState(check = Check.Failed), now, utc, Locale.UK)) } @Test fun `the install row follows the download and says why it stopped`() { diff --git a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt index 1ad05762..33e9d860 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt @@ -13,12 +13,17 @@ import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.openstrap.app.ble.GattTimeoutException import org.openstrap.app.device.StrapCommandException import org.openstrap.app.device.StrapController import org.openstrap.app.testing.endMain +import org.openstrap.protocol.services.Alarm +import org.openstrap.protocol.services.AlarmCapabilities +import org.openstrap.protocol.services.SettingsGroup import java.lang.reflect.Proxy import kotlin.coroutines.Continuation import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED @@ -72,4 +77,82 @@ class AlarmsViewModelTest { } } as StrapController } + + @Test fun `a failed first read is Failed, not an empty list, and there is nothing to add to`() { + val vm = AlarmsViewModel(failingStrap(StrapCommandException("The strap isn't connected"))).also { models += it } + val state = vm.state.value + assertEquals(AlarmsRead.Failed("The strap isn't connected"), state.read) + assertNull(state.caps) + assertFalse(state.canAdd) + } + + @Test fun `a save during a refresh is refused and the refresh that was asked for still runs after`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + assertEquals(AlarmsRead.Loaded, vm.state.value.read) + // A write is in flight and waiting on the strap. + strap.holdSave = true + val writing = vm.save(Alarm(0, 7, 0, Alarm.WEEKDAYS, enabled = true), isNew = true) + assertTrue(vm.state.value.busy) + // A push asks for a refresh meanwhile, and a second save comes in. + vm.refresh() + val second = vm.save(Alarm(1, 8, 0, 0, enabled = true), isNew = true) + assertTrue(second.isCompleted) + assertFalse(second.getCompleted()) + val readsBefore = strap.reads + strap.release() + assertTrue(writing.getCompleted()) + // One read for the write, one more for the refresh that was waiting. + assertEquals(readsBefore + 2, strap.reads) + assertFalse(vm.state.value.busy) + } + + @Test fun `a failed save completes false so the sheet stays open`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + strap.saveFailure = StrapCommandException("Slot taken") + val done = vm.save(Alarm(0, 7, 0, 0, enabled = true), isNew = true) + assertFalse(done.getCompleted()) + assertEquals("Slot taken", vm.state.value.error) + } + + /** A strap that holds one alarm, can hold a save until [release], and counts its reads. */ + private class FakeStrap { + var reads = 0 + var holdSave = false + var saveFailure: Throwable? = null + private var held: Continuation? = null + private val caps = AlarmCapabilities(version = 1, maxCount = 10, titles = false, smartSupported = false) + private val flows = mutableMapOf() + + fun release() { + held?.resumeWith(Result.success(Unit)) + held = null + holdSave = false + } + + @Suppress("UNCHECKED_CAST") + val controller: StrapController = Proxy.newProxyInstance(StrapController::class.java.classLoader, arrayOf(StrapController::class.java)) { proxy, method, args -> + fun done(r: Result): Any? { + (args.last() as Continuation).resumeWith(r) + return COROUTINE_SUSPENDED + } + when { + method.name == "hashCode" -> System.identityHashCode(proxy) + method.name == "equals" -> proxy === args?.firstOrNull() + method.name == "toString" -> "fake strap" + method.name == "readAlarms" -> { reads++; done(Result.success(caps to listOf(Alarm(0, 6, 0, Alarm.WEEKDAYS, enabled = true)))) } + method.name == "readHealthSettings" -> done(Result.success(SettingsGroup(0, 1, emptyMap()))) + method.name == "saveAlarm" -> when { + saveFailure != null -> done(Result.failure(saveFailure!!)) + holdSave -> { held = args.last() as Continuation; COROUTINE_SUSPENDED } + else -> done(Result.success(Unit)) + } + StateFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableStateFlow(null) } + SharedFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableSharedFlow() } + method.returnType == java.lang.Boolean.TYPE -> false + else -> Unit + } + } as StrapController + } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/components/DayHoldTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/components/DayHoldTest.kt new file mode 100644 index 00000000..c0d5ad8b --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/components/DayHoldTest.kt @@ -0,0 +1,86 @@ +package org.openstrap.app.ui.components + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.openstrap.app.testing.ComposeRules +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.time.LocalDate + +/** A day switch keeps the last day up, dimmed, for a moment only, then the new day's placeholder. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class DayHoldTest { + @get:Rule val rules = ComposeRules() + + private val monday = LocalDate.of(2026, 11, 9) + private val tuesday = monday.plusDays(1) + + private var value by mutableStateOf("monday") + private var day by mutableStateOf(monday) + private var failed by mutableStateOf(false) + private lateinit var hold: DayHold + + private fun show() { + rules.compose.mainClock.autoAdvance = false + rules.compose.setContent { hold = rememberDayHold(value, day, failed) } + rules.compose.mainClock.advanceTimeByFrame() + } + + private fun switchTo(newDay: LocalDate, newValue: String?) { + day = newDay + value = newValue + frame() + } + + /** The writes above reach the composition, and one frame runs. */ + private fun frame() { + Snapshot.sendApplyNotifications() + rules.compose.mainClock.advanceTimeByFrame() + } + + @Test fun `another day keeps the last one dimmed for a moment, then shows the placeholder`() { + show() + switchTo(tuesday, null) + assertEquals("monday", hold.value) + assertTrue(hold.pending) + rules.compose.mainClock.advanceTimeBy(DAY_HOLD_MS + 100) + assertNull(hold.value) + assertFalse(hold.pending) + } + + @Test fun `the new day replaces the held one as soon as it comes`() { + show() + switchTo(tuesday, null) + value = "tuesday" + frame() + assertEquals("tuesday", hold.value) + assertFalse(hold.pending) + } + + @Test fun `a refresh of the same day keeps its value, undimmed, however long it takes`() { + show() + value = null + frame() + rules.compose.mainClock.advanceTimeBy(DAY_HOLD_MS * 10) + assertEquals("monday", hold.value) + assertFalse(hold.pending) + } + + @Test fun `a day that failed holds nothing`() { + show() + failed = true + switchTo(tuesday, null) + assertNull(hold.value) + assertFalse(hold.pending) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelClockTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelClockTest.kt index 629938a5..5deacb52 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelClockTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelClockTest.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.TestCoroutineScheduler @@ -115,3 +116,6 @@ class DayViewModelClockTest { const val WAIT_MS = 10_000L } } + +/** The day's rows, now part of [DayViewModel.screen]. */ +private val DayViewModel.state get() = screen.map { it.day } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt index 6eddfd4d..4cfcab66 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DayViewModelUiStateTest.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain @@ -142,6 +143,24 @@ class DayViewModelUiStateTest { assertEquals(listOf(ChartPoint(at(12), 45f)), s.hrv) } + @Test fun `the day's lowest and highest come from the minutes, the strap's maximum when higher`() { + // A one-minute dip and spike inside two 5-minute buckets that average them away. + val hr = (0 until 10).map { HeartRateSample(at(10) + it * 60L, if (it == 3) 44 else if (it == 6) 151 else 70) } + val s = DayViewModel.toUiState(DayData(date, heartRate = hr)) + assertEquals(hr.map { it.timestamp to it.bpm }, s.heartMinutes) + assertEquals(listOf(65f, 86f), s.heartRate.map { it.y }) + assertEquals(44 to 151, s.heartRateRange) + assertEquals(44 to 163, DayViewModel.toUiState(DayData(date, heartRate = hr, dailyMaxHeartRate = 163)).heartRateRange) + assertEquals(44 to 151, DayViewModel.toUiState(DayData(date, heartRate = hr, dailyMaxHeartRate = 120)).heartRateRange) + assertNull(DayViewModel.toUiState(DayData(date)).heartRateRange) + } + + @Test fun `the night's stored readings are kept for its lowest`() { + val night = listOf(HeartRateSample(at(2), 52), HeartRateSample(at(2, 1), 46), HeartRateSample(at(2, 2), 55)) + val s = DayViewModel.toUiState(DayData(date, nightHeartRate = night)) + assertEquals(night.map { it.timestamp to it.bpm }, s.sleepHeartMinutes) + } + @Test fun `the Activity screens get the day's Heart points and energy as state`() = runTest { val repo = FakeDays() val clock = FixedClock(Instant.parse("2026-01-15T12:00:00Z")) @@ -235,3 +254,6 @@ class DayViewModelUiStateTest { } } } + +/** The activity history, now part of [DayViewModel.screen]. */ +private val DayViewModel.activityHistory get() = screen.map { it.activity } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt index bbdfa6a8..2e1d7b17 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt @@ -53,8 +53,8 @@ class DeletedNightStateTest { db.healthDao().insertSleepSessions(listOf(before, night)) val repo = HealthRepository(db.healthDao()) val vm = DayViewModel(RoomDayRepository(repo, LiveSteps())) - val collector = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.state.collect {} } - suspend fun settled(check: (DayUiState) -> Boolean) = vm.state.first { it.loaded && check(it) } + val collector = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.screen.collect {} } + suspend fun settled(check: (DayUiState) -> Boolean) = vm.screen.first { it.loaded && check(it.day) }.day settled { it.sleep != null }.let { s -> assertEquals(setOf(today.minusDays(1), today), s.nights.filter { it.session != null }.map { it.date }.toSet()) } repo.deleteSleep(night) @@ -69,4 +69,13 @@ class DeletedNightStateTest { } collector.cancel() } + + @Test fun `the picked day is saved, and a restored view model opens on it`() = runTest { + val today = LocalDate.now(ZoneId.systemDefault()) + val repo = RoomDayRepository(HealthRepository(db.healthDao()), LiveSteps()) + val handle = androidx.lifecycle.SavedStateHandle() + DayViewModel(repo, saved = handle).select(today.minusDays(3)) + val restored = DayViewModel(repo, saved = androidx.lifecycle.SavedStateHandle(mapOf("pickedDay" to handle.get("pickedDay")))) + assertEquals(today.minusDays(3), restored.screen.value.date) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt index 773cbb5e..b4753534 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DetailCopyTest.kt @@ -5,13 +5,16 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import org.openstrap.app.data.History +import org.openstrap.app.presentation.DetailCopy.Latest import org.openstrap.app.presentation.DetailCopy.Level import java.time.LocalDate import java.util.Locale +import org.openstrap.app.presentation.localNumber import org.openstrap.app.presentation.DaySource import org.openstrap.app.presentation.DetailCopy import org.openstrap.app.presentation.Metric import org.openstrap.app.presentation.Range +import org.openstrap.app.presentation.StressLevel import org.openstrap.app.presentation.daySource import org.openstrap.app.presentation.TodayCopy @@ -110,11 +113,40 @@ class DetailCopyTest { @Test fun `the label under the value names what it is for the range`() { assertEquals("bpm now", DetailCopy.valueLabel(Metric.HeartRate, Range.Day, live = true)) assertEquals("ms, day average", DetailCopy.valueLabel(Metric.Hrv, Range.Day)) + // Blood oxygen's day is its latest reading and when it was taken; its longer ranges stay averages. + assertEquals("%, daytime, latest at 14:05", DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("14:05"))) + assertEquals("%, while asleep, latest at 05:10", DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("05:10", asleep = true))) + // Stress is never asleep or awake: its day says the level of its latest reading and when it was taken. + assertEquals("High, latest at 14:05", DetailCopy.valueLabel(Metric.Stress, Range.Day, latest = Latest("14:05", asleep = true, level = StressLevel.High))) + assertEquals("%, average of the last 30 days", DetailCopy.valueLabel(Metric.Spo2, Range.Month, latest = Latest("14:05"))) assertEquals("Day average", DetailCopy.valueLabel(Metric.Stress, Range.Day)) + // Stress has no unit: its longer ranges stay averages. + assertEquals("Normal, latest at 14:05", DetailCopy.valueLabel(Metric.Stress, Range.Day, latest = Latest("14:05", level = StressLevel.Normal))) + assertEquals("Average of the last 30 days", DetailCopy.valueLabel(Metric.Stress, Range.Month, latest = Latest("14:05", level = StressLevel.High))) + assertEquals("bpm resting", DetailCopy.valueLabel(Metric.RestingHr, Range.Day)) + assertEquals("bpm resting, estimated", DetailCopy.valueLabel(Metric.RestingHr, Range.Day, estimated = true)) assertEquals("steps a day, last 7 days", DetailCopy.valueLabel(Metric.Steps, Range.Week)) assertEquals("ms, average of the last 30 days", DetailCopy.valueLabel(Metric.Hrv, Range.Month)) } + @Test fun `skin temperature's change on a card is just the signed change and its unit`() { + // Numbers as the test's locale writes them: the build also runs these under German. + fun n(ascii: String) = localNumber(ascii, Locale.getDefault()) + assertEquals("+${n("0.3")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, 0.3f)) + assertEquals("\u2212${n("0.2")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, -0.2f)) + // No change, or one that rounds to nothing, keeps a plus, never a lone minus. + assertEquals("+${n("0.0")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, 0f)) + assertEquals("+${n("0.0")} °C", DetailCopy.changeWithUnit(Metric.SkinTemperature, -0.01f)) + } + + @Test fun `skin temperature's day says its change and which side of your normal it is on`() { + val skin = Metric.SkinTemperature + fun n(ascii: String) = localNumber(ascii, Locale.getDefault()) + assertEquals("\u2212${n("0.7")} °C, below your normal", DetailCopy.skinChangeWord(skin, -0.7f, -1)) + assertEquals("+${n("1.4")} °C, above your normal", DetailCopy.skinChangeWord(skin, 1.4f, 1)) + assertEquals("+${n("0.1")} °C, within your normal", DetailCopy.skinChangeWord(skin, 0.1f, 0)) + } + @Test fun `the strip ends today while the day shown is in the last week`() { val today = LocalDate.of(2026, 10, 22) val strip = DetailCopy.strip(LocalDate.of(2026, 10, 19), today, setOf(LocalDate.of(2026, 10, 20)), Locale.UK) @@ -130,6 +162,10 @@ class DetailCopyTest { @Test fun `no detail sentence uses an interpunct, semicolon or em dash`() { val lines = listOfNotNull( DetailCopy.day(0, DaySource.Night, true, 30), DetailCopy.heartDay(1, 2, false), DetailCopy.year("1", "2", "ms"), + DetailCopy.valueLabel(Metric.RestingHr, Range.Day, estimated = true), DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("14:05")), + DetailCopy.valueLabel(Metric.Spo2, Range.Day, latest = Latest("05:10", asleep = true)), + DetailCopy.valueLabel(Metric.Stress, Range.Day, latest = Latest("14:05", level = StressLevel.High)), + DetailCopy.skinChangeWord(Metric.SkinTemperature, -0.7f, -1), DetailCopy.span(Range.Month, listOf(Level.Above, Level.Above), false, true, 30), DetailCopy.scoreWeek(listOf(1, 2)), DetailCopy.charge(1, 2, 1, true, false, 3), DetailCopy.learningNormal(1, true), DetailCopy.bandLabel(normal) { it.toString() }, ) + Metric.entries.flatMap { m -> Range.entries.map { DetailCopy.valueLabel(m, it) } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/LatestReadingTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/LatestReadingTest.kt new file mode 100644 index 00000000..7410ee2f --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/LatestReadingTest.kt @@ -0,0 +1,112 @@ +package org.openstrap.app.ui.dashboard + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.openstrap.app.data.db.SleepSession +import org.openstrap.app.presentation.ChartPoint +import org.openstrap.app.presentation.Metric +import org.openstrap.app.presentation.StressLevel + +/** Blood oxygen's latest reading of the day, which Today, All metrics and the details opened from them lead with. */ +class LatestReadingTest { + @Test fun `the latest reading is the newest of the day, whatever the order they arrive in`() { + val day = DayUiState(spo2 = listOf(ChartPoint(300, 95f), ChartPoint(900, 97f), ChartPoint(600, 94f))) + assertEquals(ChartPoint(900, 97f), LatestReading.spo2(day)) + } + + @Test fun `a day without a reading has no latest one`() { + assertNull(LatestReading.spo2(DayUiState())) + } + + @Test fun `stress's latest reading is the newest of the day's, whatever the order`() { + val day = DayUiState(stress = listOf(ChartPoint(300, 40f), ChartPoint(900, 62f), ChartPoint(600, 55f))) + assertEquals(ChartPoint(900, 62f), LatestReading.stress(day)) + assertNull(LatestReading.stress(DayUiState())) + assertEquals(ChartPoint(900, 62f), LatestReading.of(Metric.Stress, day)) + assertNull(LatestReading.of(Metric.HeartRate, day)) + } + + @Test fun `a night average is not the latest reading`() { + // The night's readings stay in their own series: only the day's series, day and night, counts. + val day = DayUiState(sleepSpo2 = listOf(ChartPoint(100, 90f))) + assertNull(LatestReading.spo2(day)) + } + + private val hour = 3600L + private fun clock(t: Long) = "t$t" + + @Test fun `a reading is stale once it is more than an hour old`() { + assertFalse(LatestReading.isStale(1000, 1000)) + assertFalse(LatestReading.isStale(1000, 1000 + hour)) + assertTrue(LatestReading.isStale(1000, 1000 + hour + 1)) + // A reading taken after now (clock skew) is fresh. + assertFalse(LatestReading.isStale(2000, 1000)) + } + + @Test fun `a reading is asleep inside the sleep window, ends included, and daytime without one`() { + val window = 1000L..5000L + assertTrue(LatestReading.isAsleep(1000, window)) + assertTrue(LatestReading.isAsleep(5000, window)) + assertFalse(LatestReading.isAsleep(999, window)) + assertFalse(LatestReading.isAsleep(5001, window)) + assertFalse(LatestReading.isAsleep(3000, null)) + } + + @Test fun `the sleep window is the main sleep's start to its end`() { + assertNull(LatestReading.sleepWindow(DayUiState())) + assertEquals(100L..900L, LatestReading.sleepWindow(DayUiState(sleep = SleepSession(start = 100, end = 900)))) + } + + @Test fun `blood oxygen's line says daytime or asleep, with the time only once the reading is stale`() { + val window = 1000L..5000L + assertEquals("Daytime", LatestReading.spo2Line(8000, window, 8000 + 60, time = ::clock)) + assertEquals("Daytime, t8000", LatestReading.spo2Line(8000, window, 8000 + 2 * hour, time = ::clock)) + assertEquals("While asleep", LatestReading.spo2Line(3000, window, 3000 + 60, time = ::clock)) + assertEquals("While asleep, t3000", LatestReading.spo2Line(3000, window, 3000 + 2 * hour, time = ::clock)) + // No sleep window known: daytime. + assertEquals("Daytime, t3000", LatestReading.spo2Line(3000, null, 3000 + 2 * hour, time = ::clock)) + } + + @Test fun `stress's line is the level of the reading, with the time only once it is stale`() { + assertEquals("Normal", LatestReading.stressLine(500, 45f, 600, tagged = true, time = ::clock)) + assertEquals("Normal, t500", LatestReading.stressLine(500, 45f, 500 + 2 * hour, tagged = true, time = ::clock)) + assertEquals("Relaxed", LatestReading.stressLine(500, 12f, 600, tagged = false, time = ::clock)) + assertEquals("Medium, t500", LatestReading.stressLine(500, 70f, 500 + 2 * hour, tagged = false, time = ::clock)) + } + + @Test fun `where the High tag shows the line doesn't repeat it`() { + assertNull(LatestReading.stressLine(500, 85f, 600, tagged = true, time = ::clock)) + assertEquals("Latest at t500", LatestReading.stressLine(500, 85f, 500 + 2 * hour, tagged = true, time = ::clock)) + // A row with no tag to show says the level itself. + assertEquals("High", LatestReading.stressLine(500, 85f, 600, tagged = false, time = ::clock)) + assertEquals("High, t500", LatestReading.stressLine(500, 85f, 500 + 2 * hour, tagged = false, time = ::clock)) + } + + @Test fun `only a High stress reading is tagged`() { + assertNull(LatestReading.stressTag(StressLevel.Relaxed)) + assertNull(LatestReading.stressTag(StressLevel.Normal)) + assertNull(LatestReading.stressTag(StressLevel.Medium)) + assertEquals(NewsTag("High", goal = false), LatestReading.stressTag(StressLevel.High)) + } + + @Test fun `the latest blood oxygen reading is asleep by the day's sleep window`() { + val sleep = SleepSession(start = 1000, end = 5000) + assertTrue(LatestReading.spo2Asleep(DayUiState(sleep = sleep, spo2 = listOf(ChartPoint(900, 95f), ChartPoint(3000, 94f))))) + assertFalse(LatestReading.spo2Asleep(DayUiState(sleep = sleep, spo2 = listOf(ChartPoint(3000, 94f), ChartPoint(9000, 96f))))) + assertFalse(LatestReading.spo2Asleep(DayUiState(sleep = sleep))) + } + + @Test fun `the shaded hours are the readings inside the sleep window, clipped to the day`() { + val day = 0L..(24 * hour) + val slot = 15 * 60L + val count = (24 * hour / slot).toInt() + 1 + // A night from 23:00 the evening before to 07:00 shades from the start of the day to 07:00. + assertEquals(0..28, LatestReading.shadeIndices(-hour..7 * hour, day, slot, count)) + assertEquals(4..8, LatestReading.shadeIndices(hour..2 * hour, day, slot, count)) + assertNull(LatestReading.shadeIndices(null, day, slot, count)) + assertNull(LatestReading.shadeIndices(-10 * hour..-9 * hour, day, slot, count)) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt index 9f691720..929774b1 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/OffStatusesTest.kt @@ -9,7 +9,6 @@ import org.openstrap.app.data.Recovery import org.openstrap.app.data.RecoveryResult import org.openstrap.app.data.db.SleepSession import org.openstrap.app.data.settings.UserProfile -import org.openstrap.app.presentation.ChartPoint import java.time.LocalDate import java.time.ZoneOffset @@ -120,12 +119,4 @@ class OffStatusesTest { assertEquals(OffStatus.Usual, habitAgeOffStatus(Healthspan.Outcome(null, null))) assertEquals(OffStatus.Usual, habitAgeOffStatus(null)) } - - @Test fun `stress is the day's mean against your normal`() { - val samples = listOf(ChartPoint(0, 60f), ChartPoint(60, 80f)) - assertEquals(70f, stressMean(samples)!!, 0.001f) - assertNull(stressMean(emptyList())) - assertEquals(OffStatus.Above, stressOffStatus(samples, History.Normal(40f, 30f, 50f, 20))) - assertEquals(OffStatus.Usual, stressOffStatus(emptyList(), History.Normal(40f, 30f, 50f, 20))) - } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt index 6446b829..6f24a94a 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/SleepCopyTest.kt @@ -41,6 +41,11 @@ class SleepCopyTest { hrv = listOf(ChartPoint(midnight + 14 * 3600, 90f)), sleepHrv = listOf(ChartPoint(midnight + 3600, 40f), ChartPoint(midnight - 7200, 41f)), sleepHeartRate = listOf(ChartPoint(midnight - 1800, 60f), ChartPoint(midnight + 3 * 3600, 48f), ChartPoint(midnight + 9 * 3600, 70f)), + // The stored readings behind the line's 5-minute averages: one minute dips below the 48 average. + sleepHeartMinutes = listOf( + midnight - 1800 to 60, midnight + 3 * 3600 to 52, midnight + 3 * 3600 + 60 to 46, midnight + 3 * 3600 + 120 to 48, + midnight + 9 * 3600 to 70, + ), ) } @@ -50,7 +55,9 @@ class SleepCopyTest { assertEquals(94f, SleepCopy.nightValue(s, Metric.Spo2)) // Heart rate's night value is the strap's average for the night; the lowest is only from readings while asleep. assertEquals(55f, SleepCopy.nightValue(s, Metric.HeartRate)) - assertEquals(48f, SleepCopy.lowestHeart(s)!!.y) + // The lowest is the lowest stored reading and when it was, not the lowest 5-minute average (48). + assertEquals(46f, SleepCopy.lowestHeart(s)!!.y) + assertEquals(midnight + 3 * 3600 + 60, SleepCopy.lowestHeart(s)!!.x) // Readings outside the sleep (the 70 after waking) stay out of the night's line. assertEquals(listOf(60f, 48f), SleepCopy.nightSeries(s, Metric.HeartRate).map { it.y }) assertEquals(listOf(40f), SleepCopy.nightSeries(s, Metric.Hrv).map { it.y }) @@ -58,6 +65,24 @@ class SleepCopyTest { assertNull(SleepCopy.nightValue(state(sleep = null), Metric.Hrv)) } + @Test fun `the average while asleep is the strap's, else the mean of the stored readings`() { + assertEquals(55, SleepCopy.averageHeart(state())) + // 60, 52, 46 and 48 inside the sleep (the 70 after waking is out): 51.5, rounded up rather than cut to 51. + assertEquals(52, SleepCopy.averageHeart(state(sleep = session.copy(averageHeartRate = null)))) + // Without the 60: 52, 46 and 48 average 48.67, which is 49. + assertEquals(49, SleepCopy.averageHeart(state(sleep = session.copy(averageHeartRate = null)).let { it.copy(sleepHeartMinutes = it.sleepHeartMinutes.drop(1)) })) + } + + @Test fun `a score the user's times moved says it is adjusted`() { + val moved = session.copy(start = session.start + 1800) + assertFalse(state().sleepScoreAdjusted) + assertFalse(state().copy(sleepAsDetected = session).sleepScoreAdjusted) + assertTrue(state(sleep = moved).copy(sleepAsDetected = session).sleepScoreAdjusted) + assertEquals("last night, adjusted", SleepCopy.scoreLabel(true, adjusted = true)) + assertEquals("that night, adjusted", SleepCopy.scoreLabel(false, adjusted = true)) + assertEquals("last night", SleepCopy.scoreLabel(true)) + } + @Test fun `a night vital reads against the nights before, as the Sleep tab's row does`() { val s = state() val normal = SleepCopy.nightNormal(s, Metric.Hrv)!! @@ -73,6 +98,27 @@ class SleepCopyTest { assertNull(SleepCopy.nightNormal(s, Metric.HeartRate)) } + @Test fun `skin temperature's row is the night's level, its change from your normal under it once there is one`() { + fun row(nights: Int): NightVital { + // Nights at 35.9 and 36.1 by turns (a normal of 36.0), then tonight at 36.5. + val before = (nights.toLong() downTo 1L).map { back -> + SleepNight(date.minusDays(back), session, skinTemperature = if (back % 2 == 0L) 35.9f else 36.1f) + } + return nightVitals(DayUiState(date = date, sleep = session, nights = before + SleepNight(date, session, skinTemperature = 36.5f))) + .first { it.metric == Metric.SkinTemperature } + } + val formed = row(8) + fun n(ascii: String) = org.openstrap.app.presentation.localNumber(ascii, java.util.Locale.getDefault()) + assertEquals(n("36.5"), formed.value) + assertEquals("+${n("0.5")} \u00B0C", formed.status) + assertEquals(1, formed.direction) + // While the normal forms, the level and how far along it is. + val forming = row(3) + assertEquals(n("36.5"), forming.value) + assertTrue(forming.status, forming.status.startsWith("Learning")) + assertNull(forming.direction) + } + @Test fun `the night's week ends on the night shown, with the same value as its Day`() { val week = SleepCopy.nightWeek(state(), Metric.Hrv) assertEquals(7, week.size) @@ -86,17 +132,42 @@ class SleepCopyTest { assertEquals("Lowest 48 bpm at 03:00 last night, 55 on average while asleep.", SleepCopy.nightHeart(48, "03:00", 55, today = true)) assertEquals("55 bpm on average while asleep that night.", SleepCopy.nightHeart(null, null, 55, today = false)) assertEquals("ms, average asleep", SleepCopy.nightLabel(Metric.Hrv, Range.Day)) + // Skin temperature's label no longer carries its change from your normal (DetailCopy.skinChangeWord says it). + assertEquals("°C, average asleep", SleepCopy.nightLabel(Metric.SkinTemperature, Range.Day)) assertEquals("ms, average of the last 7 nights", SleepCopy.nightLabel(Metric.Hrv, Range.Week)) // Month and Year say when their days aren't only nights. - assertTrue("day and night" in SleepCopy.nightLabel(Metric.Hrv, Range.Month)) + assertEquals("ms, last 30 nights", SleepCopy.nightLabel(Metric.Hrv, Range.Month)) + assertTrue("day and night" in SleepCopy.nightLabel(Metric.SkinTemperature, Range.Month)) assertEquals("%, last 30 nights", SleepCopy.nightLabel(Metric.Spo2, Range.Month)) assertEquals("No sleep" to "None recorded last night", SleepCopy.nightNoValue(hasSleep = false, today = true)) assertEquals("No reading" to "Not measured that night", SleepCopy.nightNoValue(hasSleep = true, today = false)) } + @Test fun `blood oxygen is the night's on the Sleep and Recovery tabs only, the day's latest reading elsewhere`() { + assertFalse(Metric.Spo2 in SleepCopy.NIGHT_SIGNALS) + assertTrue(Metric.Spo2 in SleepCopy.NIGHT_FIGURES) + // The other night signals are forced to the night wherever they open. + assertTrue(SleepCopy.NIGHT_SIGNALS.containsAll(listOf(Metric.Hrv, Metric.Breathing, Metric.SkinTemperature))) + assertTrue(SleepCopy.NIGHT_FIGURES.containsAll(SleepCopy.NIGHT_SIGNALS)) + assertFalse(Metric.RestingHr in SleepCopy.NIGHT_FIGURES) + // The night's average stays what the Sleep tab reads, whatever the day's readings are. + val s = state().copy(spo2 = listOf(ChartPoint(midnight + 14 * 3600, 91f))) + assertEquals(94f, SleepCopy.nightValue(s, Metric.Spo2)) + assertEquals(91f, LatestReading.spo2(s)?.y) + } + + @Test fun `blood oxygen's row on the Sleep tab says it is the night average, tag or not`() { + val row = nightVitals(state()).first { it.metric == Metric.Spo2 } + assertEquals("94%", row.value) + assertEquals("Night average", row.status) + } + @Test fun `night blood oxygen draws on its own table`() { assertEquals(DailyMetric.SleepSpo2, SleepCopy.nightDaily(Metric.Spo2)) - assertEquals(DailyMetric.Hrv, SleepCopy.nightDaily(Metric.Hrv)) + // HRV is the night's figure on every range, so its Month and Year come from the sleeps too. + assertEquals(DailyMetric.SleepHrv, SleepCopy.nightDaily(Metric.Hrv)) + assertEquals(DailyMetric.SleepHrv, Metric.Hrv.daily) + assertTrue(SleepCopy.dailyIsNightly(Metric.Hrv)) assertTrue(SleepCopy.dailyIsNightly(Metric.Breathing)) assertFalse(SleepCopy.dailyIsNightly(Metric.SkinTemperature)) } @@ -142,7 +213,7 @@ class SleepCopyTest { val lines = listOf( SleepCopy.nightHeart(48, "03:00", 55, true), SleepCopy.nightHeart(null, null, 55, false), SleepCopy.heartWeek(listOf(52, null, 55)), SleepCopy.heartWeek(listOf(52)), - SleepCopy.scoreLabel(true), SleepCopy.scoreLabel(false), + SleepCopy.scoreLabel(true), SleepCopy.scoreLabel(false), SleepCopy.scoreLabel(true, adjusted = true), SleepCopy.night("Short night", 5 * 3600L, listOf(7 * 3600L, 8 * 3600L, 6 * 3600L)), SleepCopy.regularityNight(23 * 60, 7 * 60, 23 * 60, true), SleepCopy.noNight(true), SleepCopy.noNight(false), SleepCopy.napsLabel(true), SleepCopy.naps(3, 3600), SleepCopy.napHeart(58, 64), SleepCopy.NAP_NO_STAGES, diff --git a/app/src/test/kotlin/org/openstrap/app/ui/device/StrapPageTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/device/StrapPageTest.kt index 3d62b1d1..ca13d62a 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/device/StrapPageTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/device/StrapPageTest.kt @@ -24,6 +24,17 @@ class StrapPageTest { assertEquals("Connecting…", strapStateLine(ConnectionState.Connecting, SyncState.Idle, null, now)) } + @Test fun `state line reads the kept sync time, so it survives a restart`() { + assertEquals("Connected. Synced 2 min ago", strapStateLine(connected, SyncState.Idle, null, now, lastSync = now - 120)) + // A push's Done doesn't move it: the full sync's time stands. + assertEquals("Connected. Synced 1 h ago", strapStateLine(connected, SyncState.Done(now - 5), null, now, lastSync = now - 3600)) + assertEquals("Connected. Not synced", strapStateLine(connected, SyncState.Failed("x"), null, now, lastSync = now - 3600)) + } + + @Test fun `state line says Bluetooth is off`() { + assertEquals("Bluetooth is off", strapStateLine(ConnectionState.BluetoothOff, SyncState.Idle, now - 60, now)) + } + @Test fun `You page values`() { val goals = Goals(steps = 8000, sleepMinutes = 450, activeHours = 8, calories = 450) assertEquals("8,000 steps, 450 active kcal, 8 active hours", goalsLine(goals, Locale.UK)) diff --git a/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt index 5a538e29..4646eca7 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt @@ -18,7 +18,9 @@ import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before +import org.junit.Ignore import org.junit.Rule +import org.junit.Assert.assertTrue import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith @@ -31,6 +33,11 @@ import org.robolectric.annotation.Config import java.io.ByteArrayInputStream import java.io.InputStream import java.lang.reflect.Proxy +import kotlin.coroutines.Continuation +import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED +import kotlin.coroutines.resume +import org.openstrap.protocol.firmware.DfuProgress +import org.openstrap.protocol.firmware.FirmwareType /** The firmware view model stands on the strap, the settings, a cache folder and a file reader, not the whole app (audit A3). */ @OptIn(ExperimentalCoroutinesApi::class) @@ -76,6 +83,39 @@ class FirmwareViewModelTest { assertEquals(connection.value, vm.connection.value) } + @Ignore("Firmware updates are off (FirmwareViewModel.UPDATES_ENABLED), so install refuses. Runs again once they're back.") + @Test fun `events that don't fit the step are ignored, and late progress can't revive an install`() = runBlocking { + connection.value = ConnectionState.Connected(50, "3.25") + val vm = vm { ByteArrayInputStream(ByteArray(10)) } + val image = ReadyImage(ByteArray(2048), FirmwareType.FIRMWARE, "Firmware", null, fromCloud = false, trailer = null, warnings = emptyList()) + vm.install(image) + val installing = vm.step.value + assertTrue(installing is FirmwareStep.Installing) + + // A file picked, a check, or a second install during the install change nothing. + vm.loadFile(picked).join() + vm.check() + vm.install(image) + vm.reset() + assertEquals(installing, vm.step.value) + + // Progress is applied while installing, then the install ends. + progress!!(DfuProgress.Applying) + assertTrue(vm.step.value is FirmwareStep.Installing) + installDone!!.resume(Unit) + assertEquals(FirmwareStep.Installed, vm.step.value) + + // A callback that arrives after the end doesn't start it again. + progress!!(DfuProgress.Validating) + assertEquals(FirmwareStep.Installed, vm.step.value) + vm.reset() + progress!!(DfuProgress.Validating) + assertEquals(FirmwareStep.Idle, vm.step.value) + } + + private var progress: ((DfuProgress) -> Unit)? = null + private var installDone: Continuation? = null + /** A strap whose link is [connection] and that does nothing else. */ private fun strap(): StrapController { val flows = mutableMapOf() @@ -85,6 +125,14 @@ class FirmwareViewModelTest { method.name == "equals" -> proxy === args?.firstOrNull() method.name == "toString" -> "test strap" method.name == "getConnection" -> connection + // An install that stays open until the test ends it. + method.name == "installFirmware" -> { + @Suppress("UNCHECKED_CAST") + progress = args!![2] as (DfuProgress) -> Unit + @Suppress("UNCHECKED_CAST") + installDone = args[3] as Continuation + COROUTINE_SUSPENDED + } StateFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableStateFlow(null) } SharedFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableSharedFlow() } method.returnType == java.lang.Boolean.TYPE -> false diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt index 0f7b0a5b..68ce73af 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/AllMetricsTest.kt @@ -21,7 +21,7 @@ class AllMetricsTest { private val empty = DayUiState() - /** A metric's detail as the index opens it: a night signal's scoped to the night. */ + /** A metric's detail as the index opens it: a night signal's scoped to the night, blood oxygen's to the day. */ private fun open(m: Metric) = IndexTarget.Open(Detail.OfMetric(m, m in SleepCopy.NIGHT_SIGNALS)) @Test fun `every metric detail appears exactly once`() { @@ -47,23 +47,69 @@ class AllMetricsTest { assertEquals(NO_VALUE, hrv.status) } - @Test fun `values are the day's, night signals last night's, in the metric's format`() { + @Test fun `values are the day's, night signals last night's, blood oxygen's latest reading, in the metric's format`() { val sleep = SleepSession(start = 0, end = 8 * 3600) val day = empty.copy( steps = 13860, latestHeartRate = 58, - // The calendar day's readings differ from the night's: the index shows the night's, as every tab does. + // Blood oxygen is the day's latest reading, the other signals the night's, as every tab does. spo2 = listOf(ChartPoint(0, 90f), ChartPoint(60, 92f)), skinTemperature = listOf(ChartPoint(0, 31.4f), ChartPoint(60, 31.6f)), sleep = sleep, nights = listOf(SleepNight(empty.date, sleep, spo2 = 97f, skinTemperature = 36.5f)), ) - val rows = metricIndex(day, null, null, emptyList()).flatMap { it.rows }.associateBy { it.target } + val rows = metricIndex(day, null, null, emptyList(), now = 120).flatMap { it.rows }.associateBy { it.target } assertEquals("13,860", rows.getValue(IndexTarget.Open(Detail.OfMetric(Metric.Steps))).value) assertEquals("58", rows.getValue(IndexTarget.Open(Detail.OfMetric(Metric.HeartRate))).value) - assertEquals("97%", rows.getValue(open(Metric.Spo2)).value) + assertEquals("92%", rows.getValue(open(Metric.Spo2)).value) + // Taken inside the night's sleep window a minute ago: no time yet. + assertEquals("While asleep", rows.getValue(open(Metric.Spo2)).status) + assertEquals(IndexTarget.Open(Detail.OfMetric(Metric.Spo2, night = false)), rows.getValue(open(Metric.Spo2)).target) assertEquals("36.5", rows.getValue(open(Metric.SkinTemperature)).value) } + @Test fun `blood oxygen's row says daytime without a sleep window, and the time once the reading is old`() { + val day = empty.copy(spo2 = listOf(ChartPoint(60, 92f))) + fun status(now: Long) = metricIndex(day, null, null, emptyList(), now = now).flatMap { it.rows }.first { it.name == "Blood oxygen" }.status + assertEquals("Daytime", status(120)) + assertTrue(status(120 + 2 * 3600), status(120 + 2 * 3600).startsWith("Daytime, ")) + } + + @Test fun `a resting heart rate unstrap estimated says so`() { + fun status(estimated: Boolean) = metricIndex(empty.copy(restingHeartRate = 54, restingEstimated = estimated), null, null, emptyList()) + .flatMap { it.rows }.first { it.target == open(Metric.RestingHr) }.status + assertEquals("For the day", status(false)) + assertEquals("For the day, estimated", status(true)) + } + + @Test fun `stress is the day's latest reading, not its average`() { + val day = empty.copy(stress = listOf(ChartPoint(0, 80f), ChartPoint(60, 30f), ChartPoint(120, 40f))) + val row = metricIndex(day, null, null, emptyList(), now = 180).flatMap { it.rows }.first { it.name == "Stress" } + assertEquals("40", row.value) + // The row has no tag, so its line says the level of the reading. + assertEquals("Normal", row.status) + // An hour on, the row says when. + val old = metricIndex(day, null, null, emptyList(), now = 120 + 2 * 3600).flatMap { it.rows }.first { it.name == "Stress" } + assertTrue(old.status, old.status.startsWith("Normal, ")) + val high = metricIndex(day.copy(stress = listOf(ChartPoint(0, 85f))), null, null, emptyList(), now = 60).flatMap { it.rows }.first { it.name == "Stress" } + assertEquals("High", high.status) + assertEquals(IndexTarget.Open(Detail.OfMetric(Metric.Stress)), row.target) + } + + @Test fun `skin temperature leads with its level, its change from your normal under it once there is one`() { + val sleep = SleepSession(start = 0, end = 8 * 3600) + // Eight nights at 35.9 and 36.1 by turns: a normal of 36.0. + val before = (1L..8L).map { SleepNight(empty.date.minusDays(it), SleepSession(0, 1), skinTemperature = if (it % 2 == 0L) 35.9f else 36.1f) } + fun row(nights: List) = metricIndex( + empty.copy(sleep = sleep, nights = nights + SleepNight(empty.date, sleep, skinTemperature = 36.5f)), null, null, emptyList(), + ).flatMap { it.rows }.first { it.target == open(Metric.SkinTemperature) } + // Before there's a normal, the night's average says so. + assertEquals("36.5", row(emptyList()).value) + assertEquals("Average asleep", row(emptyList()).status) + val led = row(before) + assertEquals("36.5", led.value) + assertEquals("+0.5 °C", led.status) + } + private fun readiness(score: Int?, nights: Int, withheld: Boolean = false) = org.openstrap.app.data.Recovery.Readiness(score, emptyList(), nights, false, emptyList(), false, withheld = withheld) diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt new file mode 100644 index 00000000..a417f741 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt @@ -0,0 +1,34 @@ +package org.openstrap.app.ui.glow + +import android.net.Uri +import androidx.compose.ui.graphics.asImageBitmap +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** The share screen's photo: a fresh pick reads as Loading until its own answer arrives, so Save never exports without it. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class SharePhotoTest { + private val first = Uri.parse("content://photos/1") + private val second = Uri.parse("content://photos/2") + private val bitmap = android.graphics.Bitmap.createBitmap(1, 1, android.graphics.Bitmap.Config.ARGB_8888).asImageBitmap() + + @Test fun `no pick is None whatever was decoded before`() { + assertEquals(SharePhoto.None, sharePhotoFor(null, SharePhoto.Ready(first, bitmap))) + } + + @Test fun `a pick waits as Loading until its own answer comes`() { + assertEquals(SharePhoto.Loading, sharePhotoFor(first, SharePhoto.None)) + assertEquals(SharePhoto.Loading, sharePhotoFor(second, SharePhoto.Ready(first, bitmap))) + assertEquals(SharePhoto.Loading, sharePhotoFor(second, SharePhoto.Failed(first))) + } + + @Test fun `the answer for the picked photo is shown, ready or failed`() { + val ready = SharePhoto.Ready(first, bitmap) + assertEquals(ready, sharePhotoFor(first, ready)) + assertEquals(SharePhoto.Failed(second), sharePhotoFor(second, SharePhoto.Failed(second))) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt index 869dca45..df040ac3 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt @@ -78,6 +78,25 @@ class AppNavStateTest { assertEquals(30_720, checked) } + @Test + fun `You and Strap opened one after the other don't stack, so Back goes home, not to the first`() { + val nav = AppNavState() + nav.openPage(Page.You) + nav.openPage(Page.Strap) + assertEquals(listOf(Page.Strap), nav.pages) + nav.closePage() + assertEquals(emptyList(), nav.pages) + } + + @Test + fun `a page opened from a row stacks on its root, and the same page twice opens once`() { + val nav = AppNavState() + nav.openPage(Page.Strap) + nav.openPage(Page.Firmware) + nav.openPage(Page.Firmware) + assertEquals(listOf(Page.Strap, Page.Firmware), nav.pages) + } + @Test fun `back from a tab goes to the tab before, then Today, and Today's root is home`() { val nav = AppNavState(AppNavState.Snapshot(tab = TabNav(Tab.Activity.ordinal, Tab.Sleep.ordinal))) @@ -130,6 +149,19 @@ class AppNavStateTest { assertEquals(WorkoutOverlay.None, nav.workout) } + @Test + fun `a session in progress closes Ready and Choose however it started`() { + val nav = AppNavState() + nav.openChoose() + nav.openReady(5) + nav.sessionInProgress() + assertEquals(WorkoutOverlay.None, nav.workout) + // A request opening Ready during the summary is closed again by the same effect. + nav.apply(NavRequest.OpenReady(4), recording = false, firmwareInstalling = false) + nav.sessionInProgress() + assertEquals(WorkoutOverlay.None, nav.workout) + } + @Test fun `an update installing keeps its pages open`() { val nav = AppNavState(AppNavState.Snapshot(pages = listOf(Page.Strap, Page.Firmware))) diff --git a/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt index 0a8908e6..05ae10ac 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt @@ -129,7 +129,7 @@ class AppRootViewModelTest { assertEquals(4, await(vm.dayExtras) { it.checkIn != null }.checkIn) val next = day.plusDays(1) vm.dayShown(next) - assertEquals(DayExtras(), await(vm.dayExtras) { it.checkIn == null }) + assertEquals(DayExtras(next), await(vm.dayExtras) { it.date == next && it.checkIn == null }) } @Test fun `the strap facts follow the connection`() { diff --git a/app/src/test/kotlin/org/openstrap/app/ui/workout/OpenedWorkoutTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/workout/OpenedWorkoutTest.kt new file mode 100644 index 00000000..fdf817c5 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/workout/OpenedWorkoutTest.kt @@ -0,0 +1,29 @@ +package org.openstrap.app.ui.workout + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Test +import org.openstrap.app.data.db.Workout +import org.openstrap.app.data.WorkoutAnalysis + +/** A workout's detail tells "no such workout" from "still loading", and each answer names its workout. */ +class OpenedWorkoutTest { + private fun analysis(start: Long) = WorkoutAnalysis( + Workout(start, start + 600, 1, 600, 50, 140, 160, 90, null, null, null, null, null), + start + 600, emptyList(), null, null, null, null, List(5) { 0 }, 190, + ) + + @Test fun `no workout at the key is missing, not loading`() { + assertEquals(OpenedWorkout.Missing(100), OpenedWorkout.of(100, null)) + assertNotEquals(OpenedWorkout.Loading, OpenedWorkout.of(100, null)) + } + + @Test fun `a workout at the key is found`() { + val a = analysis(100) + assertEquals(OpenedWorkout.Found(a), OpenedWorkout.of(100, a)) + } + + @Test fun `a missing answer for one key is not the answer for another`() { + assertNotEquals(OpenedWorkout.Missing(100), OpenedWorkout.Missing(200)) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt b/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt index 11994d9b..ff4332c7 100644 --- a/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt @@ -86,4 +86,36 @@ class AppUpdaterTest { assertTrue(thrown.toString(), thrown is FileNotFoundException) assertEquals(emptyList(), installer.allSessions) } + + @Test fun `a failure after the process died is shown from the saved tag and clears it`() = runBlocking { + val settings = SettingsStore(app) + settings.setUpdateInstalling("v9.0.0") + val updater = AppUpdater(app, settings, recording = { false }, scope = scope) + updater.installResult(app, android.content.pm.PackageInstaller.STATUS_FAILURE_STORAGE, "full", null) + val failed = withTimeout(10_000) { updater.state.first { it.install is Install.Failed }.install as Install.Failed } + assertEquals("v9.0.0", failed.tag) + assertEquals(InstallFailure.Storage, failed.failure) + withTimeout(10_000) { while (settings.updateInstalling() != null) kotlinx.coroutines.delay(20) } + } + + @Test fun `a saved tag with no installer session open is cleared at start`() = runBlocking { + val settings = SettingsStore(app) + settings.setUpdateInstalling("v9.0.0") + val updater = AppUpdater(app, settings, recording = { false }, scope = scope) + updater.reconcile() + withTimeout(10_000) { while (settings.updateInstalling() != null) kotlinx.coroutines.delay(20) } + assertEquals(Install.Idle, updater.state.value.install) + } + + @Test fun `a saved tag for the version running is cleared`() = runBlocking { + val settings = SettingsStore(app) + val updater = AppUpdater(app, settings, recording = { false }, scope = scope) + settings.setUpdateInstalling("v${updater.installed}") + updater.reconcile() + withTimeout(10_000) { while (settings.updateInstalling() != null) kotlinx.coroutines.delay(20) } + } + + @Test fun `the check state is one value`() { + assertEquals(Check.Idle, UpdateState().check) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/widget/StrapStatusTest.kt b/app/src/test/kotlin/org/openstrap/app/widget/StrapStatusTest.kt index be0933ad..69ba5c09 100644 --- a/app/src/test/kotlin/org/openstrap/app/widget/StrapStatusTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/widget/StrapStatusTest.kt @@ -51,6 +51,22 @@ class StrapStatusTest { assertNull(strapStatus(true, 80, false, fresh, now, syncing = true)) } + @Test fun `a failing sync shows as the app does, over an old one, while syncing reads Syncing`() { + assertEquals(StrapStatus.SyncFailed, strapStatus(true, 80, false, fresh, now, failingSince = now - 600)) + assertEquals(StrapStatus.SyncFailed, strapStatus(true, 80, false, old, now, failingSince = now - 600)) + assertEquals(StrapStatus.Syncing, strapStatus(true, 80, false, fresh, now, syncing = true, failingSince = now - 600)) + // A low battery still comes first, and a good sync (no failing time) shows nothing. + assertEquals(StrapStatus.LowBattery(5), strapStatus(true, 5, false, fresh, now, failingSince = now - 600)) + assertNull(strapStatus(true, 80, false, fresh, now, failingSince = null)) + } + + @Test fun `Bluetooth off comes before everything but not paired`() { + assertEquals(StrapStatus.BluetoothOff, strapStatus(true, 5, false, old, now, failingSince = now - 600, bluetoothOff = true)) + assertEquals(StrapStatus.NotPaired, strapStatus(false, 80, false, fresh, now, bluetoothOff = true)) + assertEquals("Not synced", strapStatusLine(StrapStatus.SyncFailed, now, zone, Locale.UK)) + assertEquals("Bluetooth is off", strapStatusLine(StrapStatus.BluetoothOff, now, zone, Locale.UK)) + } + @Test fun `the words`() { fun line(s: StrapStatus) = strapStatusLine(s, now, zone, Locale.UK) assertEquals("Pair your strap", line(StrapStatus.NotPaired)) diff --git a/app/src/test/kotlin/org/openstrap/app/widget/WidgetRefreshTest.kt b/app/src/test/kotlin/org/openstrap/app/widget/WidgetRefreshTest.kt new file mode 100644 index 00000000..3baec848 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/widget/WidgetRefreshTest.kt @@ -0,0 +1,19 @@ +package org.openstrap.app.widget + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Test +import org.openstrap.app.data.WidgetKind + +/** The version a running widget watches: every bump counts, even from several threads at once. */ +class WidgetRefreshTest { + @Test fun `bumps from many threads are all counted`() = runBlocking { + val kind = WidgetKind.Steps + val before = WidgetRefresh.version(kind).value + (1..8).map { async(Dispatchers.Default) { repeat(500) { WidgetRefresh.bump(kind) } } }.awaitAll() + assertEquals(before + 4000, WidgetRefresh.version(kind).value) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/widget/WidgetTriggersTest.kt b/app/src/test/kotlin/org/openstrap/app/widget/WidgetTriggersTest.kt index 92bd974d..70575348 100644 --- a/app/src/test/kotlin/org/openstrap/app/widget/WidgetTriggersTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/widget/WidgetTriggersTest.kt @@ -109,6 +109,41 @@ class WidgetTriggersTest { assertEquals(listOf(all), changed) } + @Test fun `a sync failing or working again refreshes all`() { + watch() + snapshot.value = snapshot.value.copy(failingSince = NOW - 30) + scope.runCurrent() + assertEquals(listOf(all), changed) + // A second failure keeps the first time: the line is the same. + snapshot.value = snapshot.value.copy(lastSyncDone = NOW - 10) + scope.runCurrent() + assertEquals(listOf(all), changed) + snapshot.value = snapshot.value.copy(failingSince = null) + scope.runCurrent() + assertEquals(listOf(all, all), changed) + } + + @Test fun `a sync starting while failing refreshes all, so the line reads Syncing`() { + snapshot.value = snapshot.value.copy(failingSince = NOW - 30) + watch() + sync.value = SyncState.Running("x") + scope.runCurrent() + assertEquals(listOf(all), changed) + } + + @Test fun `Bluetooth going off or on refreshes all`() { + val bluetooth = MutableStateFlow(false) + val t = WidgetTriggers(goals, sides, snapshot, sync, steps, ended, workout, sleepEdits, profiles, clock, bluetooth) { NOW } + scope.watchWidgetTriggers(t, { changed += it }, { stepPushes++ }) + scope.runCurrent() + assertEquals(emptyList>(), changed) + bluetooth.value = true + scope.runCurrent() + bluetooth.value = false + scope.runCurrent() + assertEquals(listOf(all, all), changed) + } + @Test fun `a sync ending, live steps and a workout reach the widgets`() { watch() ended.tryEmit(Unit) diff --git a/docs/releases/v3.0.0.md b/docs/releases/v3.0.0.md index da3bf946..81992fa0 100644 --- a/docs/releases/v3.0.0.md +++ b/docs/releases/v3.0.0.md @@ -44,7 +44,7 @@ - A Keep recording notice when Android won't let a workout run in the background. - Save a copy and Restore open in Downloads. - A faster app, from the first launch after an install or update. -- Strap firmware updates are off for now while I look into a sleep bug in firmware 3.27.0.1. +- Strap firmware updates are off for now. ## Fixes diff --git a/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt b/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt index f6f0fce5..cf9a368d 100644 --- a/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt +++ b/protocol/src/main/kotlin/org/openstrap/protocol/history/Records.kt @@ -159,7 +159,7 @@ data class SpO2Reading( val isAuto: Boolean, val history: List?, ) : HistoryRecord { - /** The app keeps only 80..100 (02 §3.5). */ + /** Zepp 10.10.5 keeps only 80..100 and drops the rest before storing (`d/eo00.java:158`); 127 is the invalid marker. */ val isPlausible: Boolean get() = spo2 in 80..100 } diff --git a/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt b/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt index f521ecb8..24eeb81b 100644 --- a/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt +++ b/protocol/src/test/kotlin/org/openstrap/protocol/history/RecordParsersTest.kt @@ -213,10 +213,12 @@ class RecordParsersTest { @Test fun spo2Legacy() { - val p = w().u32(t0).u8(0x80 or 97).u32(t0 + 60).u8(70).toByteArray() + val p = w().u32(t0).u8(0x80 or 97).u32(t0 + 60).u8(70).u32(t0 + 120).u8(127).u32(t0 + 180).u8(0).toByteArray() val res = ok(HistoryParsers.spo2Single.parse(p, ctx)) assertEquals(97, res.records[0].spo2); assertTrue(res.records[0].isAuto); assertTrue(res.records[0].isPlausible) + // Only 80 to 100 is kept, as Zepp does: 70 is out, 127 is the invalid marker and 0 is none. assertEquals(70, res.records[1].spo2); assertFalse(res.records[1].isAuto); assertFalse(res.records[1].isPlausible) + assertFalse(res.records[2].isPlausible); assertFalse(res.records[3].isPlausible) assertNull(res.records[0].history) }