Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 3 additions & 1 deletion docs/WEAR_OS.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ versions by @cubetes): one design on every wrist. The rules live in `WatchLogic.
three, Stop. Finish mid-hold logs the seconds held. "Timed holds start by themselves" on the
phone: a 3-2-1 after the rest, then the hold.
- Metrics: the workout's time (it stands still while the phone has the workout paused), heart
rate, volume, sets. Music: a small remote (previous, play/pause, next, volume) for whatever
rate, volume, sets. Under it, by the crown or a swipe up, as on the Apple Watch: Pulse (the
average heart rate and the line of every reading, when there is one) and Effort (the mean
effort of each exercise rated on the watch today). Always On goes back to the numbers. Music: a small remote (previous, play/pause, next, volume) for whatever
plays on the watch.
- **"All done?"** after 20 minutes without a set: a card, Continue or Finish (which goes to the
Overview's hold). On Wear OS it only asks; it never ends a workout by itself.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ data class SessionState(
/** The week streak and whether anything at all came from the phone yet. */
val streak: Streak? = null,
val synced: Boolean = false,
/** Today's effort ratings made here, by SessionCore.effortKey (the Apple Watch's efforts, for the Effort page). */
val efforts: Map<String, Double>? = null,
Comment thread
cubetes marked this conversation as resolved.
Resolved
)

/** The end of a workout, on one screen. */
Expand All @@ -77,12 +79,22 @@ data class PhoneTick(val exId: String, val entryIdx: Int, val setIdx: Int, val a
object SessionCore {
fun key(exId: String, si: Int, side: String? = null) = if (side != null) "$exId#$si#$side" else "$exId#$si"

/** A rating's key: the exercise, which of its entries (the same one twice rates apart), the set. */
fun effortKey(entries: List<Entry>, ei: Int, si: Int) =
entries[ei].id.let { id -> "$id@${entries.take(ei).count { it.id == id }}#$si" }

/** A snapshot from the phone, over what the watch has. */
fun applySnapshot(s0: SessionState, snap: Snapshot): SessionState {
var s = s0.copy(ready = snap.ready, synced = true)
snap.unit?.let { s = s.copy(unit = it) }
snap.restSec?.let { if (it > 0) s = s.copy(restSec = it) }
snap.settings?.let { s = s.copy(settings = it) }
snap.settings?.let {
// The ratings follow the phone's scale: RIR = 10 - RPE (lib/effort.js); another scale drops them.
val was = s.settings.effort
val efforts = if (was == it.effort) s.efforts
else if (setOf(was, it.effort) == setOf("rpe", "rir")) s.efforts?.mapValues { (_, v) -> 10 - v } else null
s = s.copy(settings = it, efforts = efforts)
}
snap.streak?.let { s = s.copy(streak = it) }

val acked = snap.acked?.toSet() ?: emptySet()
Expand All @@ -98,13 +110,13 @@ object SessionCore {
if (next0 == null || (next0.id != null && s.finishedHere.contains(next0.id))) {
// No workout on the phone, or one the watch has finished already.
if (unconfirmed) return s
return s.copy(workout = null, pending = emptyMap())
return s.copy(workout = null, pending = emptyMap(), efforts = null)
}
val same = next0.id != null && next0.id == wid
if (next0.id != null && next0.id == s.startedHere) s = s.copy(startedHere = null, startId = null)
// The phone runs a different workout than the one started here: the watch keeps its own.
if (!same && unconfirmed) return s
if (!same) s = s.copy(pending = emptyMap(), skipped = emptyList(), entryIndex = next0.cur)
if (!same) s = s.copy(pending = emptyMap(), skipped = emptyList(), efforts = null, entryIndex = next0.cur)
// The phone moved to another exercise (its Next, or the last set of one ticked there): the watch
// goes along, as after a tick here. A page opened on the wrist stays while the phone stays put.
val was = s0.workout?.cur
Expand Down Expand Up @@ -141,7 +153,12 @@ object SessionCore {
val now = entries.indices.filter { entries[it].id == shown }
(now.getOrNull(nth) ?: now.lastOrNull())?.let { at = it }
}
return s.copy(workout = next, pending = pending, entryIndex = at)
// A set unticked on the phone loses its rating, so a later unrated tick does not bring it back.
val rated = entries.indices.flatMap { ei ->
entries[ei].sets.indices.filter { si -> entries[ei].sets[si].let { it.done || it.sides?.let { d -> d.L.done || d.R.done } == true } }
.map { effortKey(entries, ei, it) }
}.toSet()
return s.copy(workout = next, pending = pending, entryIndex = at, efforts = s.efforts?.filterKeys { it in rated })
}

/** One side of a per-side set done, the row following both sides (the phone's syncSideAggregate). */
Expand Down Expand Up @@ -173,9 +190,11 @@ object SessionCore {
else row.copy(done = true, w = w ?: row.w, r = r ?: row.r, sec = sec ?: row.sec, at = at)
val entries = workout.entries.toMutableList()
entries[ei] = e.copy(sets = e.sets.toMutableList().also { it[si] = newRow })
val rated = effort?.takeIf { Effort.notches(it.kind) != null }
val s = s0.copy(
workout = workout.copy(entries = entries),
pending = s0.pending + (key(e.id, si, oneSide) to PendingTick(w, r, at, sec, id)),
efforts = if (rated != null) (s0.efforts ?: emptyMap()) + (effortKey(entries, ei, si) to rated.value) else s0.efforts,
)
val event = buildJsonObject {
put("id", id); put("type", "setDone"); put("wid", workout.id ?: ""); put("exId", e.id)
Expand Down Expand Up @@ -278,7 +297,7 @@ object SessionCore {
fun start(s0: SessionState, session: ReadySession, wid: String, at: Double, id: String, bw: Double? = null): Pair<SessionState, Event> {
val workout = ActiveWorkout(id = wid, name = session.name, unit = s0.unit, cur = 0, restSec = s0.restSec,
entries = session.entries, start = at, healthType = session.healthType)
val s = s0.copy(workout = workout, startedHere = wid, startId = id, pending = emptyMap(), skipped = emptyList(), entryIndex = 0)
val s = s0.copy(workout = workout, startedHere = wid, startId = id, pending = emptyMap(), skipped = emptyList(), efforts = null, entryIndex = 0)
val event = buildJsonObject {
put("id", id); put("type", "start")
put("routineIds", JsonArray(session.routineIds.map { JsonPrimitive(it) }))
Expand All @@ -293,7 +312,7 @@ object SessionCore {
fun finish(s0: SessionState, at: Double, id: String, discard: Boolean = false, idle: Boolean = false, left: Boolean = false): Pair<SessionState, Event?> {
val w = s0.workout ?: return s0 to null
val s = s0.copy(
workout = null, pending = emptyMap(), skipped = emptyList(), startedHere = null, startId = null,
workout = null, pending = emptyMap(), skipped = emptyList(), efforts = null, startedHere = null, startId = null,
finishedHere = if (w.id != null) (s0.finishedHere + w.id).takeLast(5) else s0.finishedHere,
)
val event = buildJsonObject {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,43 @@ object Effort {
}
}

/** The Pulse and Effort pages' arithmetic (WatchCore Metrics.swift). Volume and sets are SessionCore's. */
object Metrics {
/** The mean of the readings (time, bpm) in whole bpm; none without any (zeros are no reading). */
fun average(samples: List<Pair<Long, Int>>): Int? {
val v = samples.map { it.second }.filter { it > 0 }
return if (v.isEmpty()) null else Math.round(v.sum().toDouble() / v.size).toInt()
}

/** The lowest and highest reading in whole bpm; none without any (zeros are no reading). */
fun range(samples: List<Pair<Long, Int>>): IntRange? {
val v = samples.map { it.second }.filter { it > 0 }
return if (v.isEmpty()) null else v.min()..v.max()
}

/** At most `n` points for drawing: buckets of consecutive samples, each averaged in time and value. */
fun downsample(samples: List<Pair<Long, Int>>, n: Int): List<Pair<Double, Double>> {
if (n <= 0) return emptyList()
if (samples.size <= n) return samples.map { it.first.toDouble() to it.second.toDouble() }
return (0 until n).map { i ->
val chunk = samples.subList(i * samples.size / n, (i + 1) * samples.size / n)
chunk.map { it.first.toDouble() }.average() to chunk.map { it.second.toDouble() }.average()
}
}

data class ExerciseEffort(val id: String, val name: String, val value: Double)

/** Today's effort: one row per exercise rated here, the mean of its rated sets, in workout order. */
fun effort(s: SessionState): List<ExerciseEffort> {
val w = s.workout ?: return emptyList()
val efforts = s.efforts ?: return emptyList()
return w.entries.mapIndexedNotNull { ei, e ->
val v = e.sets.indices.mapNotNull { efforts[SessionCore.effortKey(w.entries, ei, it)] }
if (v.isEmpty()) null else ExerciseEffort(e.id, e.name, v.average())
}
}
}

/* ---------- the sync status ---------- */

/** What the watch says about its sets and the phone (the Apple Watch's SyncState). */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ object WearStore {
val summary: StateFlow<WorkoutSummary?> = _summary
private val _heartRate = MutableStateFlow<Int?>(null)
val heartRate: StateFlow<Int?> = _heartRate
// heartRate skips equal values; this counts every reading so the Pulse page redraws on each
private val _readingCount = MutableStateFlow(0)
val readingCount: StateFlow<Int> = _readingCount
/** Whether the phone is connected right now. */
val phoneNear = MutableStateFlow(true)

Expand Down Expand Up @@ -741,10 +744,14 @@ object WearStore {
_heartRate.value = bpm
readings.addLast(at to bpm)
while (readings.size > 20_000) readings.removeFirst()
_readingCount.value++
}

fun clearHeartRate() { _heartRate.value = null }

/** The workout's heart-rate readings so far (time, bpm), for the Pulse page. */
fun heartSamples(): List<Pair<Long, Int>> = readings.toList()

/**
* A set ticked on the phone: measured here like a tick on the wrist, from when the set started
* up to the phone's tick, and sent as a setHr (the Apple Watch's phoneTicked). The next set
Expand Down Expand Up @@ -878,7 +885,12 @@ object WearStore {
"start" -> commit(_state.value.copy(workout = null))
"rest" -> completeSet()
"overview" -> page.value = Page.OVERVIEW
"metrics" -> page.value = Page.METRICS
"metrics" -> {
page.value = Page.METRICS
// The emulator has no heart rate: fake readings (min 96, max 171, average about 138) so the Pulse page has numbers.
val bpm = intArrayOf(96, 110, 125, 138, 150, 171, 160, 145, 130, 120, 135, 148, 155, 140, 128, 136, 142, 150, 138, 132)
bpm.forEachIndexed { i, b -> onHeartRate(b, now() - (bpm.size - i) * 60_000L) }
}
"media" -> page.value = Page.MEDIA
"fix" -> { completeSet(); stopRest(); fixLast() }
"hold" -> { _state.value.workout?.entries?.indexOfFirst { it.isTimed }?.takeIf { it >= 0 }?.let { jump(it) }; startHold(auto = true) }
Expand Down
Loading
Loading