Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Watch: 3-2-1 countdown before a workout so set 1 has its heart rate

Adrián Fernández99b1f617966a
diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swift
index 5c7835014..e6db4f2ce 100644
--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift
+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift
@@ -9,6 +9,7 @@ import WidgetKit
* the obvious value control, black background, the accent colour only on the primary action.
*
* start today's workout as one big Start, the other routines in a short list below
+ * 3-2-1 with Apple Health on, a countdown before it starts (the heart-rate sensor warms up)
* set weight × reps in big rounded numerals, the round Done, the set dots; the crown turns
* the reps (or the weight, after a tap on it), marked by the crown symbol under it
* rest a full-screen ring around a huge countdown, +15 s and Skip as small round buttons
@@ -89,6 +90,8 @@ struct RootView: View {
WeighInView()
} else if let summary = store.summary {
SummaryView(summary: summary)
+ } else if store.workout == nil, let from = store.countdownFrom {
+ CountdownView(from: from)
} else if store.workout == nil {
IdleView()
} else if let end = store.holdEndsAt {
@@ -195,6 +198,40 @@ struct EdgeButton: View {
}
}
+/// The 3-2-1 before a workout started here: big numbers in a ring that empties once. A tap
+/// starts at once; the small button cancels (nothing starts, nothing is logged).
+struct CountdownView: View {
+ @EnvironmentObject var store: SessionStore
+ let from: Date
+
+ var body: some View {
+ VStack(spacing: 2) {
+ TimelineView(.periodic(from: from, by: 1)) { ctx in
+ let n = max(1, Countdown.number(at: ctx.date.timeIntervalSince(from)))
+ Button { store.startNow() } label: {
+ ZStack {
+ CountdownRing(start: from, end: from.addingTimeInterval(Double(Countdown.seconds)))
+ Text(verbatim: "\(n)")
+ .font(.system(size: 64, weight: .bold, design: .rounded).monospacedDigit())
+ .foregroundStyle(Theme.accent)
+ }
+ .aspectRatio(1, contentMode: .fit)
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text("Start workout"))
+ .accessibilityValue(Text(verbatim: "\(n)"))
+ }
+ .padding(.horizontal, 6)
+ HStack {
+ EdgeButton(systemImage: "xmark", label: Text("Cancel")) { store.cancelCountdown() }
+ Spacer()
+ }
+ }
+ .ignoresSafeArea(edges: .bottom)
+ }
+}
+
/* ---------- no workout: start one ---------- */
struct IdleView: View {
diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swift
index d81b5cb4c..7b11afbae 100644
--- a/frontend/ios/App/Watch/SessionStore.swift
+++ b/frontend/ios/App/Watch/SessionStore.swift
@@ -556,7 +556,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
weighInFor = session
return
}
- begin(session, bw: nil)
+ countIn(session, bw: nil)
}
/// The weigh-in answered: saved (a weigh-in for the phone, and the session's body weight) or
@@ -569,11 +569,54 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
send(event: ev)
bw = bodyWeight
}
- begin(session, bw: bw)
+ countIn(session, bw: bw)
}
func cancelWeighIn() { weighInFor = nil }
+ /// The 3-2-1 before the workout, while it runs: when it began (CountdownView).
+ @Published private(set) var countdownFrom: Date?
+ private var countdownFor: (session: ReadySession, bw: Double?)?
+ private var countdownTimer: Timer?
+
+ /// With Apple Health on, a 3-2-1 first: the workout session is prepared meanwhile, so the heart
+ /// rate sensor is warm by set 1. Without it there is nothing to wait for.
+ private func countIn(_ session: ReadySession, bw: Double?) {
+ guard health.enabled, !isDemo else { begin(session, bw: bw); return }
+ countdownFor = (session, bw)
+ let from = Date()
+ countdownFrom = from
+ health.prepare(type: session.healthType)
+ Haptics.count()
+ countdownTimer?.invalidate()
+ countdownTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
+ if Countdown.number(at: Date().timeIntervalSince(from) + 0.05) == 0 { self?.startNow() } else { Haptics.count() }
+ }
+ }
+
+ /// The countdown ran out, or a tap on it: the workout starts.
+ func startNow() {
+ guard let c = countdownFor else { return }
+ stopCountdown()
+ // A workout came from the phone meanwhile: that one runs (its session took the prepared one).
+ guard workout == nil else { return }
+ begin(c.session, bw: c.bw)
+ }
+
+ /// Cancel on the countdown: nothing starts, the prepared session is dropped.
+ func cancelCountdown() {
+ guard countdownFor != nil else { return }
+ stopCountdown()
+ if workout == nil { health.end(save: false) }
+ }
+
+ private func stopCountdown() {
+ countdownTimer?.invalidate()
+ countdownTimer = nil
+ countdownFor = nil
+ countdownFrom = nil
+ }
+
private func begin(_ session: ReadySession, bw: Double?) {
let now = Date()
let (next, event) = SessionCore.start(state, session, wid: "watch-" + UUID().uuidString,
@@ -897,6 +940,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
* start the system's start
* finished stop, then two successes: the workout is saved
* skip a soft one going down
+ * count a click each second of the 3-2-1 before a workout
*/
enum Haptics {
private static var device: WKInterfaceDevice { WKInterfaceDevice.current() }
@@ -911,4 +955,5 @@ enum Haptics {
static func start() { play([(0, .start)]) }
static func finished() { play([(0, .stop), (0.5, .success), (0.9, .success)]) }
static func skip() { play([(0, .directionDown)]) }
+ static func count() { play([(0, .click)]) }
}
diff --git a/frontend/ios/App/Watch/WorkoutManager.swift b/frontend/ios/App/Watch/WorkoutManager.swift
index 876cca9d9..814f309ac 100644
--- a/frontend/ios/App/Watch/WorkoutManager.swift
+++ b/frontend/ios/App/Watch/WorkoutManager.swift
@@ -104,15 +104,40 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
"yoga": .yoga, "flexibility": .flexibility, "other_workout": .other,
]
- /// A workout started here or picked up from the phone: the session starts now, as the type the
- /// phone planned (a run is a run in Apple Health), else as the type HealthKit opened the app
- /// with, else strength training. A session already running keeps its type.
+ /// A session made and prepared, not started yet (the countdown before a workout started here).
+ private var prepared = false
+
+ /// The countdown before a workout started here: the session is made and prepared, which turns
+ /// the heart-rate sensor on. It needs a few seconds to lock on, so set 1 has its heart rate.
+ func prepare(type: String? = nil) {
+ guard session == nil, make(type: type, opened: nil) else { return }
+ prepared = true
+ session?.prepare()
+ }
+
+ /// A workout started here or picked up from the phone: the session starts now (the prepared
+ /// one, after a countdown), as the type the phone planned (a run is a run in Apple Health),
+ /// else as the type HealthKit opened the app with, else strength training. A session already
+ /// running keeps its type.
func start(workoutId wid: String? = nil, type: String? = nil, opened: HKWorkoutActivityType? = nil) {
wanted = true
if let wid = wid { workoutId = wid }
// Already running (opened by the phone before its workout arrived): only the id to add.
- if session != nil { tag(); return }
- guard enabled, HKHealthStore.isHealthDataAvailable() else { return }
+ if session != nil && !prepared { tag(); return }
+ guard session != nil || make(type: type, opened: opened), let s = session, let b = builder else { return }
+ prepared = false
+ let now = Date()
+ s.startActivity(with: now)
+ b.beginCollection(withStart: now) { _, _ in }
+ tagged = nil
+ tag()
+ startQuery(from: now)
+ running = true
+ }
+
+ /// A new session of the planned type and its builder, when Apple Health is on.
+ private func make(type: String?, opened: HKWorkoutActivityType?) -> Bool {
+ guard enabled, HKHealthStore.isHealthDataAvailable() else { return false }
let config = HKWorkoutConfiguration()
config.activityType = type.flatMap { WorkoutManager.activityTypes[$0] } ?? opened ?? .traditionalStrengthTraining
config.locationType = .indoor
@@ -128,16 +153,11 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
heartRate = nil
calories = nil
paused = false
- let now = Date()
- s.startActivity(with: now)
- b.beginCollection(withStart: now) { _, _ in }
- tagged = nil
- tag()
- startQuery(from: now)
- running = true
+ return true
} catch {
session = nil
builder = nil
+ return false
}
}
@@ -274,6 +294,7 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
func end(save: Bool, totals: ((Totals) -> Void)? = nil) {
wanted = false
workoutId = nil
+ prepared = false
if let q = query { store.stop(q); query = nil }
let all = samples.map { $0.1 }
let hr = Totals(hrAvg: all.isEmpty ? nil : (all.reduce(0, +) / Double(all.count)).rounded(), hrMax: all.max()?.rounded(), calories: nil)
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
index b314f166d..4023c0212 100644
--- a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
@@ -397,3 +397,14 @@ struct TouchLock: Equatable {
mutating func unlock() { until = .distantPast }
func allows(at t: Date) -> Bool { t >= until }
}
+
+/// The 3-2-1 before a workout started on the watch: the heart-rate sensor warms up meanwhile (it
+/// needs a few seconds to lock on), so the first set has its heart rate. One second a number.
+enum Countdown {
+ static let seconds = 3
+
+ /// The number up `elapsed` seconds after the countdown began: 3, 2, 1, then 0 (go).
+ static func number(at elapsed: Double) -> Int {
+ max(seconds - Int(max(elapsed, 0).rounded(.down)), 0)
+ }
+}
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/CountdownTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/CountdownTests.swift
new file mode 100644
index 000000000..af0605e21
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/CountdownTests.swift
@@ -0,0 +1,15 @@
+import XCTest
+@testable import WatchCore
+
+/// The 3-2-1 before a workout started on the watch.
+final class CountdownTests: XCTestCase {
+ func testCountsThreeTwoOneThenGo() {
+ XCTAssertEqual(Countdown.number(at: 0), 3)
+ XCTAssertEqual(Countdown.number(at: 0.99), 3)
+ XCTAssertEqual(Countdown.number(at: 1), 2)
+ XCTAssertEqual(Countdown.number(at: 2.5), 1)
+ XCTAssertEqual(Countdown.number(at: 3), 0)
+ XCTAssertEqual(Countdown.number(at: 60), 0, "never below go")
+ XCTAssertEqual(Countdown.number(at: -1), 3, "a clock a moment behind still shows 3")
+ }
+}