Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
df9c322
Weekly recap: the streak line only shows on a week that met the goal
sayed0am Nov 12, 2026
49dc072
Healthspan: an estimate a week old or more says it updates weekly, no…
sayed0am Nov 12, 2026
cbd6108
Auto backup keeps the day's earlier backup until its replacement is i…
sayed0am Nov 12, 2026
55552da
A calorie goal the strap refused is not marked as sent, so it is trie…
sayed0am Nov 12, 2026
e03020d
A phone workout's distance keeps the steps walked before GPS found it…
sayed0am Nov 12, 2026
ebf1c15
A failed alarms read no longer hides the health switches, and the rev…
sayed0am Nov 12, 2026
83df5db
A failed write's reason stays on screen when a refresh was queued beh…
sayed0am Nov 12, 2026
1d78b88
Sleep edits that match no session are cleared in a new migration, so …
sayed0am Nov 12, 2026
e290aec
A deleted phone workout is taken out of Health Connect too, with its …
sayed0am Nov 12, 2026
c8bf4f1
The oldest of the fourteen nights now averages its HRV, skin temperat…
sayed0am Nov 12, 2026
276760e
A trimmed or untrimmed workout works its fastest 1k, 5k and 10k out a…
sayed0am Nov 12, 2026
cc896ff
Step badges and bests come without workouts, follow each sync, and th…
sayed0am Nov 12, 2026
f99283e
Auto backup: a provider that can't rename still replaces the day's ea…
sayed0am Nov 12, 2026
72ca7e3
Health Connect: a deleted workout's records are looked for a day eith…
sayed0am Nov 12, 2026
c63964e
Merge fix/66-glow
sayed0am Nov 12, 2026
9dd80a9
Merge fix/66-misc
sayed0am Nov 12, 2026
264d197
Merge fix/66-workouts
sayed0am Nov 12, 2026
81b2ddd
Merge fix/66-distance
sayed0am Nov 12, 2026
3a4fbb0
Merge fix/66-alarms
sayed0am Nov 12, 2026
2a1724f
Merge fix/66-sleep
sayed0am Nov 12, 2026
9088b5d
Orphan sleep edits: only main sleeps in the weeks minute nights were …
sayed0am Nov 12, 2026
f34faba
A workout left recording is never deleted for looking short, and a re…
sayed0am Nov 12, 2026
fa47841
An unreadable workout no longer stops workout syncing, and a chunk th…
sayed0am Nov 12, 2026
cf5472d
Detekt and the rest test: shorter lines and conditions, no !!, a try/…
sayed0am Nov 12, 2026
d1312a7
Merge pull request #67 from sayed0am/fix/issue-66
sayed0am Nov 12, 2026
533a75e
The week view shows the days after the one shown
sayed0am Nov 12, 2026
4e81431
Merge pull request #68 from sayed0am/fix/week-active-minutes
sayed0am Nov 12, 2026
d315148
Release notes for 3.0.7
sayed0am Nov 12, 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
1,968 changes: 1,968 additions & 0 deletions app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ class AppContainer(val app: Application) {
val autoHealthConnect = org.openstrap.app.health.HealthConnectAutoSync(app, settings, healthConnect, strap, scope = appScope)
val workout = org.openstrap.app.device.WorkoutSession(
app, database.healthDao(), settings, strap, maxHeartRates, callRinging = { phoneAlerts.callRinging }, onSaved = autoHealthConnect::workoutSaved,
onRemoved = autoHealthConnect::workoutDiscarded,
scope = appScope,
)
/** Saved and the Keep recording notice, from the session's state, on the app scope (audit S10). */
Expand Down
9 changes: 4 additions & 5 deletions app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,10 @@ class RewardsKeeper(

/** Works everything out again from [workouts] against [goal] and stores it. */
suspend fun refresh(workouts: List<WorkoutAnalysis>, goal: Int) = refreshLock.withLock {
// The list starts empty before it loads: only a database with no workouts at all starts the rewards empty.
if (workouts.isEmpty()) {
if (!settings.rewardsStarted.first() && !dao.anyWorkoutOnce()) settings.startRewards(historyBadges = false)
return@withLock
}
// The list starts empty before it loads, so an empty list waits while workouts are stored. With none stored it
// is worked out all the same: the step badges and bests need no workout, and deleting the last workout takes
// its bests and its week with it.
if (workouts.isEmpty() && dao.anyWorkoutOnce()) return@withLock
val f = facts(workouts)
withContext(Dispatchers.Default) {
val today = LocalDate.now(f.zone)
Expand Down
14 changes: 8 additions & 6 deletions app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,12 @@ class RoomDayRepository(
val span = DayWindow(
SleepHistory.endingOn(date.minusDays(SleepHistory.NIGHTS - 1L), zone).from, SleepHistory.endingOn(date, zone).to,
)
// The oldest night began the evening before its day, so its readings start there, not at that midnight.
val readings = DayWindow(SleepHistory.readingsOf(date.minusDays(SleepHistory.NIGHTS - 1L), zone).from, span.to)
val extras = combine(health.skinTemperature(day), health.breathRate(night), health.latestPai(day.to)) { skin, breath, pai ->
Triple(skin, breath, pai?.takeIf { it.timestamp >= day.from })
}
val sleepAndExtras = combine(nights(date, night, span, zone), extras, baselines(date)) { s, e, b -> Triple(s, e, b) }
val sleepAndExtras = combine(nights(date, night, span, readings, zone), extras, baselines(date)) { s, e, b -> Triple(s, e, b) }

// The strap's own running total covers steps whose minute records were already taken by another app.
val todayLive = if (isToday) strapSteps else flowOf(null)
Expand Down Expand Up @@ -117,13 +119,13 @@ class RoomDayRepository(
}

/**
* The day's sleep ([sleep]), the [SleepHistory.NIGHTS] nights over [span] with the vitals averaged over each, and
* the night's own readings for the charts of the night-scoped details.
* The day's sleep ([sleep]), the [SleepHistory.NIGHTS] nights over [span] with the vitals averaged over each (read over
* [readings], from the oldest night's evening), and the night's own readings for the charts of the night-scoped details.
*/
private fun nights(date: LocalDate, night: DayWindow, span: DayWindow, zone: ZoneId): Flow<DayData> = combine(
private fun nights(date: LocalDate, night: DayWindow, span: DayWindow, readings: DayWindow, zone: ZoneId): Flow<DayData> = combine(
sleep(date, span, zone),
combine(health.hrv(span), health.skinTemperature(span)) { h, s -> h to s },
combine(health.spo2(span), health.breathRate(span)) { o, b -> o to b },
combine(health.hrv(readings), health.skinTemperature(readings)) { h, s -> h to s },
combine(health.spo2(readings), health.breathRate(readings)) { o, b -> o to b },
health.heartRate(night),
) { sleepParts, (hrv, skin), (spo2, breath), hr ->
val (parts, sessions, osa) = sleepParts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import java.time.ZoneId
BadgeRow::class,
WeekResult::class,
],
version = 31,
version = 32,
autoMigrations = [
AutoMigration(from = 1, to = 2), AutoMigration(from = 2, to = 3), AutoMigration(from = 3, to = 4),
AutoMigration(from = 4, to = 5), AutoMigration(from = 5, to = 6),
Expand All @@ -81,7 +81,7 @@ abstract class OpenStrapDatabase : RoomDatabase() {
* converted ([DayKeyMigration]), so it is the phone's zone when the database first opens after the upgrade.
*/
fun migrations(zone: () -> ZoneId = ZoneId::systemDefault): Array<Migration> =
arrayOf(WorkoutsMigration, IndicesMigration, DayKeyMigration(zone), MinuteSleepMigration)
arrayOf(WorkoutsMigration, IndicesMigration, DayKeyMigration(zone), MinuteSleepMigration, OrphanSleepEditMigration)

/** [migrations] in the phone's zone. */
val MIGRATIONS = migrations()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.openstrap.app.data.db

import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.openstrap.app.data.SleepEdits

/**
* Version 31 to 32: the edits left behind by the nights [MinuteSleepMigration] deleted go. An edit finds a session of
* its kind within [SleepEdits.MATCH_SECONDS], so one of those could have moved or hidden a real strap night near it.
*
* Only where those nights could be: main sleeps from [FROM] to [TO], the two weeks 3.0.0 to 3.0.2 looked back over and
* the days they ran. Such an edit with no main sleep that close goes, except a marker for a deleted sleep whose time
* to restore has run out ([SleepEdits.marker]), which has none by design. Every other edit stays as it was. No schema
* change.
*/
@Suppress("MagicNumber") // The versions it runs between, and the dates the minute nights were made for, are what it is.
object OrphanSleepEditMigration : Migration(31, 32) {
/** 2026-10-20 00:00 UTC, before the earliest night 3.0.0 (7 November) could make from the minutes. */
const val FROM = 1_792_454_400L

/** 2026-11-12 00:00 UTC, after 3.0.3 (10 November) deleted them and made no more. */
const val TO = 1_794_441_600L

override fun migrate(db: SupportSQLiteDatabase) {
val keptBefore = System.currentTimeMillis() / 1000 - SleepEdits.KEEP_DAYS * 86_400L
db.execSQL(
"DELETE FROM `sleep_edit` WHERE `nap` = 0 AND `strapStart` BETWEEN ? AND ? " +
"AND NOT (`deleted` = 1 AND `start` IS NULL AND `editedAt` < ?) AND NOT EXISTS " +
"(SELECT 1 FROM `sleep_session` WHERE `sleep_session`.`nap` = 0 AND " +
"ABS(`sleep_session`.`start` - `sleep_edit`.`strapStart`) <= ${SleepEdits.MATCH_SECONDS})",
arrayOf<Any>(FROM, TO, keptBefore),
)
}
}
21 changes: 18 additions & 3 deletions app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt
Original file line number Diff line number Diff line change
Expand Up @@ -420,8 +420,11 @@ class HistorySync internal constructor(
val headerTime = chunk.headerTime
val payload = chunk.payload
// The size field counts records, not bytes (activity: size 4 = four 8-byte minutes).
// A chunk it can't read ends the type as before, and the type fails, so a stop here shows instead of
// the sync saying Done while this type gets no further. What goes to the strap is the same.
val unit = chunk.unit ?: run {
log("history ${spec.type}: got ${payload.size} bytes for size ${chunk.sizeField}, not read")
ok = false
break@loop
}
log(
Expand All @@ -433,6 +436,7 @@ class HistorySync internal constructor(
// Zepp parses after the ACK and tells the strap nothing of a parse failure.
if (result is ParseResult.Failure) {
log("history ${spec.type}: parse failed: ${result.reason}")
ok = false
break@loop
}
val records = (result as ParseResult.Success).records
Expand Down Expand Up @@ -492,13 +496,17 @@ class HistorySync internal constructor(
/**
* Workouts as Zepp's `pxk`: the summary, then its detail from the same cursor (04 §3.16), the next pair from the
* summary's header + 1 s. The pairs are stored when the loop ends, then the cursor goes to the last workout + 1 s
* (at most now) for both 5 and 6. A failed detail fails the job and stores nothing, so the cursor stays.
* (at most now) for both 5 and 6. A failed detail fails the job and stores nothing, so the cursor stays, as Zepp's
* receiver drops what a failed job fetched. A summary that can't be read is left out and the loop goes on, as
* Zepp's, which only parses once it ends: the type fails so it shows, and the cursor passes it once a later one
* is stored.
*/
// Each return or break ends the loop for a reason of its own.
@Suppress("ReturnCount", "LoopWithTooManyJumpStatements")
private suspend fun syncWorkouts(spec: HistoryTypeSpec): Boolean {
var cursor = startOf(spec.type, System.currentTimeMillis() / 1000)
val pairs = mutableListOf<WorkoutFetch.Workout>()
var unreadable = 0
while (true) {
if (fastRecharge) return false
when (val w = client.fetchWorkout(cursor, zone)) {
Expand All @@ -508,6 +516,13 @@ class HistorySync internal constructor(
if (w.fastRecharge) fastRecharge = true
return false
}
// Left out, and the ones after it still come: the type fails, so it shows, but nothing is held up.
is WorkoutFetch.Unreadable -> {
log("history workout from ${Instant.ofEpochSecond(w.nextCursor - 1)}: ${w.reason}, left out")
unreadable++
if (w.nextCursor <= cursor) break
cursor = w.nextCursor
}
is WorkoutFetch.Workout -> {
if (w.retryDetail) { log("history workout: detail failed, nothing stored"); return false }
pairs += w
Expand All @@ -516,14 +531,14 @@ class HistorySync internal constructor(
}
}
}
if (pairs.isEmpty()) return true
if (pairs.isEmpty()) return unreadable == 0
for (w in pairs) storeWorkout(w)
val now = System.currentTimeMillis() / 1000
val last = pairs.maxOf { it.summary.trackId } + 1
val saved = if (last > now) now else last
save(HistoryDataType.SPORT_SUMMARY, saved, now)
save(HistoryDataType.SPORT_DETAIL, saved, now)
return true
return unreadable == 0
}

private suspend fun storeWorkout(w: WorkoutFetch.Workout) {
Expand Down
43 changes: 33 additions & 10 deletions app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ internal class SavedWorkoutEditor(
private val scope: CoroutineScope,
/** The route and step totals still in memory for the workout [start] (the last one recorded), else null. */
private val track: (start: Long) -> WorkoutDistance.Track? = { null },
/** The workout [start] was deleted, with all it was recorded over, [from] to [to]: auto sync takes it out of Health Connect. */
private val onRemoved: (start: Long, from: Long, to: Long) -> Unit = { _, _, _ -> },
) {
/**
* Deletes a phone workout, and closes its summary if it is the one showing. The strap's own records of it
Expand All @@ -44,7 +46,10 @@ internal class SavedWorkoutEditor(
// 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)
if (w?.end != null) {
refreshDays(w.start, w.recordedEnd ?: w.end)
onRemoved(w.start, w.start, w.recordedEnd ?: w.end)
}
onDiscarded(start)
}
}
Expand Down Expand Up @@ -93,7 +98,9 @@ internal class SavedWorkoutEditor(
scope.launch {
lock.withLock {
val w = catching { dao.appWorkoutOnce(start) }.getOrNull()?.takeIf { it.end != null } ?: return@withLock
val changed = change(w).let { c -> if (c.from == w.from && c.end == w.end) c else withDistance(w, c) }
val changed = change(w).let { c ->
if (c.from == w.from && c.end == w.end) c else trackOf(w).let { withStretches(withDistance(w, c, it), it) }
}
if (changed == w) return@withLock
catching { dao.upsertAppWorkout(withEffect(changed, dao.appWorkoutHeartRateOnce(start))) }
.onFailure { log("workout edit not saved: ${it.message}") }
Expand All @@ -105,21 +112,37 @@ internal class SavedWorkoutEditor(
}
}

/** What [old]'s distance and stretches are worked out from again: the route and step totals in memory, or a kept route. */
private suspend fun trackOf(old: AppWorkout): WorkoutDistance.Track? = track(old.start) ?: run {
if (!old.keepRoute) return@run null
catching { dao.routeOnce(old.start).map { it.point } }.getOrNull()
?.let { WorkoutDistance.Track(it, emptyList(), null, routeSince = old.start, stepsSince = old.start) }
}

/**
* [new], a new range of [old], with the distance over it ([WorkoutDistance]): from the route and step totals in
* memory, or a kept route, and without either [old]'s by the share of moving time kept.
* [new], a new range of [old], with the distance over it ([WorkoutDistance]): from [track], and without it
* [old]'s by the share of moving time kept.
*/
private suspend fun withDistance(old: AppWorkout, new: AppWorkout): AppWorkout {
val track = track(old.start) ?: run {
if (!old.keepRoute) return@run null
catching { dao.routeOnce(old.start).map { it.point } }.getOrNull()
?.let { WorkoutDistance.Track(it, emptyList(), null, routeSince = old.start, stepsSince = old.start) }
}
private fun withDistance(old: AppWorkout, new: AppWorkout, track: WorkoutDistance.Track?): AppWorkout {
val shown = track?.let { WorkoutDistance.shown(new, clock(), it) }
return if (shown != null) new.copy(distanceMeters = shown.first, distanceFromSteps = shown.second)
else new.copy(distanceMeters = WorkoutDistance.scaledTo(old, new))
}

/**
* [w] with its fastest stretches worked out again over the range it shows, as when it was saved: a trim can leave a
* stretch that started outside it, and an undo needs ones never worked out. Left as they are without the whole route.
*/
private fun withStretches(w: AppWorkout, track: WorkoutDistance.Track?): AppWorkout {
val end = w.end
// Only a route from the start: one picked up after a restart would lose the stretches before it.
val whole = track?.takeIf { it.routeSince <= w.start && it.route.isNotEmpty() }
if (end == null || whole == null) return w
val stretches = org.openstrap.app.data.Rewards.stretches(whole.route.filter { it.t in w.from..end }, w.pauseRanges)
.let(org.openstrap.app.data.Rewards.Stretch::format)
return w.copy(stretches = stretches)
}

/** Writes the daily calories rows from [from] to [to] again ([org.openstrap.app.data.DailyCaloriesHistory.updateDays]). */
suspend fun refreshDays(from: Long, to: Long) {
catching { org.openstrap.app.data.DailyCaloriesHistory(dao).updateDays(from, to, settings.profile.first()) }
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,8 @@ class StrapManager(
val write = SettingsCodec.calorieTargetFor(group, kcal)
if (write != null) {
val ack = commands.command(Endpoints.SETTINGS, write)
log(if (SettingsCodec.isWriteSuccess(ack)) "calorie goal sent: $kcal" else "calorie goal refused: ${ack.toHex()}")
if (!SettingsCodec.isWriteSuccess(ack)) return@catching log("calorie goal refused: ${ack.toHex()}")
log("calorie goal sent: $kcal")
}
settings.setSentToStrap(SENT_CALORIE_GOAL, kcal.toLong())
}.onFailure { log("calorie goal send failed: $it") }
Expand Down
15 changes: 14 additions & 1 deletion app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ internal object WorkoutDistance {
val lo = maxOf(from, since)
val memory = when {
lo >= to -> null
gps -> route(track.route, lo, to, w.pauseRanges) to false
gps -> withSteps(w, track, lo, to)
else -> steps(w, track, lo, to)?.let { it to true }
}
// Before a restart only the stored total is left, so the part of it the range keeps is its share of the time.
Expand All @@ -48,6 +48,19 @@ internal object WorkoutDistance {
return (memory?.first ?: 0f) + (earlier?.first ?: 0f) to (memory?.second == true || earlier?.second == true)
}

/**
* The route's metres from [lo] to [to], with the steps walked before its first fix in front of them, since GPS
* takes a while to settle and those metres are real. Counted as from steps only when they are most of the
* distance, so a run GPS followed nearly all the way stays a GPS run.
*/
private fun withSteps(w: AppWorkout, track: Track, lo: Long, to: Long): Pair<Float, Boolean> {
val metres = route(track.route, lo, to, w.pauseRanges)
val fix = Route.clean(track.route).first().t
val start = maxOf(lo, track.stepsSince)
val before = if (fix > start) steps(w, track, start, minOf(fix, to)) ?: 0f else 0f
return metres + before to (before > metres)
}

/** [w] with its distance over the range it shows ([shown]), or as it was when nothing says. */
fun withShown(w: AppWorkout, now: Long, track: Track): AppWorkout =
shown(w, now, track)?.let { (m, steps) -> w.copy(distanceMeters = m, distanceFromSteps = steps) } ?: w
Expand Down
Loading