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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions app/src/main/kotlin/org/openstrap/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ class MainActivity : ComponentActivity() {
)
val container = (application as OpenStrapApp).container
showLiveWorkoutWhenLocked(container)
// Only a fresh launch asks for something. A restored activity (process death, then back from Recents) is
// handed its original launch intent again, extras intact, and nav is restored too: replaying them would
// pile the old request on top of where the user had got to.
if (savedInstanceState == null && !launchedFromHistory(intent)) showWorkoutFromIntent()
setContent {
OpenStrapTheme {
AppRoot(container, navRequests, previews, pendingStrap)
Expand Down Expand Up @@ -170,8 +174,10 @@ class MainActivity : ComponentActivity() {
(application as OpenStrapApp).container.workout.inFront()
// The association or battery setting may have changed in system settings meanwhile.
(application as OpenStrapApp).container.companion.refresh()
// Call and notification access may have been granted in system settings meanwhile.
(application as OpenStrapApp).container.phoneAlerts.refresh()
// Debug extras only: the real launch extras are read once, in onCreate and onNewIntent.
handleDebugIntent(previews)
showWorkoutFromIntent()
}

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

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

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

/** The moment as the Moment widget reads it, for the strap's notification: its name, lead and Today's sentence. */
Expand Down Expand Up @@ -112,6 +117,7 @@ class OpenStrapApp : Application(), androidx.work.Configuration.Provider {
container.companion.refresh()
// A workout still recording when the process died carries on (the service restarts it too).
container.workout.restore()
container.workoutNotifier.start()
// Android restarts the process on its own (companion presence, a reboot): reconnect without the screen.
// A no-op when nothing is paired, a connection is already up, or the user tapped Disconnect.
if (BlePermissions.granted(this)) container.strap.backgroundConnect()
Expand Down
21 changes: 21 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,27 @@ interface HealthDao : RangedReads {
deleteAppWorkoutRow(start)
}

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

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -621,13 +628,17 @@ class SettingsStore private constructor(private val store: DataStore<Preferences
private val strapBattery = androidx.datastore.preferences.core.intPreferencesKey(SettingsKeys.STRAP_BATTERY)
private val strapCharging = androidx.datastore.preferences.core.booleanPreferencesKey(SettingsKeys.STRAP_CHARGING)
private val syncDone = longPreferencesKey(SettingsKeys.STRAP_LAST_SYNC_DONE)
private val syncFailingSince = longPreferencesKey(SettingsKeys.STRAP_SYNC_FAILING_SINCE)

/**
* What a widget's strap status line reads with the strap away (widgets spec 5): pairing, the battery and charging
* as last connected, and when a sync last finished.
*/
val strapSnapshot: Flow<StrapSnapshot> = 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. */
Expand All @@ -638,9 +649,31 @@ class SettingsStore private constructor(private val store: DataStore<Preferences
}
}

/** When a history sync last finished (epoch seconds). Per type cursors are [lastSync]. */
/**
* When a full history sync last finished (epoch seconds). The failure [setSyncFailing] kept ends with it. Per type
* cursors are [lastSync].
*/
suspend fun setLastSyncDone(epochSeconds: Long) {
store.edit { it[syncDone] = epochSeconds }
store.edit {
it[syncDone] = epochSeconds
it.remove(syncFailingSince)
}
}

/** A sync failed at [epochSeconds]: kept as the start of the failing run unless one is already kept. */
suspend fun setSyncFailing(epochSeconds: Long) {
store.edit { if (it[syncFailingSince] == null) it[syncFailingSince] = epochSeconds }
}

private val workoutLive = stringPreferencesKey(SettingsKeys.WORKOUT_LIVE)

/** What the workout recording since [start] kept of its live-only figures, null when none or another workout's. */
suspend fun workoutLive(start: Long): WorkoutLive? =
WorkoutLive.decode(store.data.first()[workoutLive])?.takeIf { it.start == start }

/** Kept for the one workout recording now: a process death brings them back ([workoutLive]). */
suspend fun setWorkoutLive(live: WorkoutLive) {
store.edit { it[workoutLive] = live.encode() }
}

/** What the strap last took for [what] (a profile checksum, a goal), so a connect alone doesn't send it again. */
Expand Down Expand Up @@ -786,7 +819,7 @@ class SettingsStore private constructor(private val store: DataStore<Preferences
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,
)
}
Expand Down Expand Up @@ -866,6 +899,8 @@ object SettingsKeys {
const val STRAP_BATTERY = "strap_battery"
const val STRAP_CHARGING = "strap_charging"
const val STRAP_LAST_SYNC_DONE = "strap_last_sync_done"
const val STRAP_SYNC_FAILING_SINCE = "strap_sync_failing_since"
const val WORKOUT_LIVE = "workout_live"
const val BACKUP_FOLDER = "backup_folder"
const val BACKUP_FOLDER_NAME = "backup_folder_name"
const val BACKUP_LAST_DONE = "backup_last_done"
Expand All @@ -886,3 +921,20 @@ object SettingsKeys {
/** The key each sport's [SportSettings][org.openstrap.app.data.SportSettings] is stored under, before the sport's id. */
const val SPORT_SETTINGS_PREFIX = "sport_settings_"
}

/**
* A recording workout's figures that live only in memory and aren't in its rows: the seconds added to the rest under
* way, and the live kcal, which never goes down. Without them a restart would cut the rest short and drop the kcal.
*/
data class WorkoutLive(val start: Long, val restExtra: Long, val kcalActive: Float?, val kcalTotal: Float?) {
fun encode(): String = listOf(start, restExtra, kcalActive ?: "", kcalTotal ?: "").joinToString(",")

companion object {
private const val FIELDS = 4

fun decode(text: String?): WorkoutLive? {
val p = text?.split(",")?.takeIf { it.size == FIELDS } ?: return null
return p[0].toLongOrNull()?.let { WorkoutLive(it, p[1].toLongOrNull() ?: 0, p[2].toFloatOrNull(), p.last().toFloatOrNull()) }
}
}
}
13 changes: 13 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/device/BlePermissions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ object BlePermissions {
bluetooth.toTypedArray()
}

/** Notifications for the foreground service's notification: asked for on Android 13 and later, granted before. */
val notifications: List<String>
@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<String, Boolean>): 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 }
Expand Down
28 changes: 25 additions & 3 deletions app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
23 changes: 18 additions & 5 deletions app/src/main/kotlin/org/openstrap/app/device/CompanionLink.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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())
Expand All @@ -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 {
Expand Down
9 changes: 7 additions & 2 deletions app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 }
}
Loading