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/db/Daos.kt b/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt index d015370f..bdd8e7fc 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 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/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..9d7d2f79 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 @@ -62,6 +64,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() @@ -95,7 +104,7 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class), ) - /** What a write asks Health Connect for. */ + /** What a write asks Health Connect for: the needed ones with the optional calories, so they are offered in the same screen. */ val requestedPermissions: Set get() = permissions + caloriePermissions /** Reading back what was exported; history is the permission to read further back than 30 days. */ @@ -122,9 +131,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 calorie permissions are granted, for the Health Connect page's offer to ask again. */ + suspend fun hasCaloriePermissions(): Boolean = + client.permissionController.getGrantedPermissions().containsAll(caloriePermissions) /** The record reads the user has granted (any of them is enough to import that kind). */ suspend fun hasReadPermissions(): Boolean = @@ -190,8 +199,9 @@ 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 + (SleepSessionRecord::class to sleepRange(from, to))) { + dropMovedRestingHr(resting) + } return records.size } @@ -216,7 +226,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 +290,7 @@ 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) + store.writeSerially(writeLock, records, kcalRanges) return records.size } @@ -523,6 +533,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 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/DayViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt index 17775d68..f67ffd9e 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 @@ -141,10 +144,42 @@ data class DayUiState( /** 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 +246,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 +263,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 +284,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 +337,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 +374,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 +447,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. 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..1054b510 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)) }) } } 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..453a20fe 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 @@ -99,7 +99,7 @@ fun metricIndex( strapScore: Int? = null, 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 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..41753093 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)) 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..f2654ff0 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 @@ -118,8 +118,8 @@ fun GlowRecoveryScreen( ) { 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 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 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..2fa2246f 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 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..4d5ca2bc 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 @@ -207,7 +207,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 +216,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, ) 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..20735678 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 --------------------------------------------- */ 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..ee12fc92 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 @@ -136,10 +138,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) } @@ -163,6 +173,8 @@ internal fun SleepScoreDetail( score != null -> DetailHeadline(score.toString(), SleepCopy.scoreLabel(isToday), 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 +196,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 +289,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 }, ) } @@ -553,10 +566,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() @@ -665,7 +684,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/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/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..d4ea2a7b 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 calorie 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 calorie permissions, for the Health Connect page's "Offer calories again". Granted when nothing is left to ask. */ + suspend fun healthConnectCalories(): HcState = HcState.blocked(healthConnect.availability()) ?: when { + healthConnect.hasCaloriePermissions() -> HcState.Granted + else -> HcState.Needs(healthConnect.caloriePermissions) + } + 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..c5eadc57 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,7 +72,7 @@ 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). is Detail.OfMetric -> GlowMetricDetailScreen( @@ -83,14 +89,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()), @@ -124,6 +132,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..d2a34dd7 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,10 @@ internal class HealthConnectActions( val export: () -> Unit, /** Auto sync on or off. */ val auto: (Boolean) -> Unit, + /** True while Health Connect is there and the calorie permissions are not granted: the page offers them again. */ + val caloriesMissing: Boolean, + /** Asks for just the calorie permissions. */ + val offerCalories: () -> Unit, ) internal val HC_UNAVAILABLE: String get() = Strings.app.get(R.string.day_hc_unavailable) @@ -69,6 +76,15 @@ 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.healthConnectCalories() }.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 @@ -82,6 +98,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 +118,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 calorie permissions are optional and 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 +134,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.healthConnectCalories()) { + 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..9dd40e7c 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,6 +47,7 @@ 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 @@ -84,6 +87,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 +99,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 +215,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 +254,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 } 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_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_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_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_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..03577567 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_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_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_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_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..7274a9d8 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 are left out until you allow them. + Offer calories 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/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/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/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/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..93347ff6 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 @@ -235,3 +236,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/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/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)