Add per-routine target heart rate with live in-run indicator
Endurance routines (HIIT, cardio, cycling) can carry an optional target bpm (RoutineDocument.targetHeartRate, not schema-bumped — same preference-field rationale as restSeconds/autoAdvance), snapshotted onto the WorkoutDocument at plan time like the other pacing fields. During a run, the watch streams its live HR sample to the phone over a new best-effort liveHeartRate message — deliberately outside the LiveProgress machinery (no version bump, no staging/retry; a gauge, not a record), throttled to changed-bpm-or-10s in the watch bridge. LiveRunState holds the sample with a 30s staleness auto-clear so a dead stream never shows a frozen number. Both run screens show the reading only when the run carries a target: the phone's ExerciseProgressView as a top pill, the watch's in the top-trailing toolbar slot, each tinted by a shared ±5 bpm HeartRateBand with an arrow cue to push harder (low) or ease off (high) — e.g. dialing in a treadmill incline to hold a steady effort. Claude-Session: https://claude.ai/code/session_01Y7ZhkCYWNiTSAFhFCGnJ8n
This commit is contained in:
@@ -217,6 +217,28 @@ final class WatchConnectivityBridge: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Live heart rate (ephemeral; best-effort)
|
||||
|
||||
/// Rounded bpm last sent and when, to throttle the forward: HR samples land every few
|
||||
/// seconds, but an unchanged reading only needs an occasional keep-alive so the phone's
|
||||
/// staleness window doesn't blank the readout mid-run.
|
||||
private var lastHRSentBpm: Int?
|
||||
private var lastHRSentAt = Date.distantPast
|
||||
|
||||
/// Forward a live heart-rate sample to a mirroring phone. Unlike the run frames this is
|
||||
/// pure best-effort — reachable-only, no staging, no retry: a gauge, not a record. The
|
||||
/// durable HR summary still lands in `WorkoutMetrics` when the session finishes.
|
||||
func sendLiveHeartRate(_ bpm: Double) {
|
||||
guard let session, session.activationState == .activated, session.isReachable else { return }
|
||||
let rounded = Int(bpm.rounded())
|
||||
let now = Date()
|
||||
if rounded == lastHRSentBpm, now.timeIntervalSince(lastHRSentAt) < 10 { return }
|
||||
lastHRSentBpm = rounded
|
||||
lastHRSentAt = now
|
||||
session.sendMessage(WCPayload.encodeLiveHeartRate(bpm: bpm, at: now),
|
||||
replyHandler: nil, errorHandler: nil)
|
||||
}
|
||||
|
||||
/// Apply a live-run frame the phone sent. Catches our send counter up first (shared per-run
|
||||
/// sequence), then arbitrates against our own staged outbound frame for the same run: if the
|
||||
/// incoming frame outranks it, drop the staged one (so a later reconnect can't re-send stale
|
||||
|
||||
@@ -25,6 +25,12 @@ import WatchKit
|
||||
struct ExerciseProgressView: View {
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
/// Live HR straight off the session's builder — drives the target-HR readout when
|
||||
/// this run carries a `targetHeartRate`. Optional so hosts without a session
|
||||
/// manager in the environment (the screenshot root) render without it.
|
||||
@Environment(WorkoutSessionManager.self) private var sessionManager: WorkoutSessionManager?
|
||||
@Environment(\.isLuminanceReduced) private var dimmed
|
||||
|
||||
/// The shared working workout document owned by the parent. We mutate the matching
|
||||
/// log in place and ask the parent to forward each change through the bridge —
|
||||
/// driving the UI from this doc (not the cache) avoids losing rapid edits to the
|
||||
@@ -285,6 +291,9 @@ struct ExerciseProgressView: View {
|
||||
Image(systemName: "xmark")
|
||||
}
|
||||
}
|
||||
ToolbarItem(placement: .topBarTrailing) {
|
||||
heartRateReadout
|
||||
}
|
||||
}
|
||||
.confirmationDialog("Cancel Exercise?", isPresented: $showingCancelConfirm, titleVisibility: .visible) {
|
||||
Button("Cancel Exercise", role: .destructive) { dismiss() }
|
||||
@@ -364,6 +373,26 @@ struct ExerciseProgressView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Live heart rate vs. target
|
||||
|
||||
/// Compact live HR against this run's target (cardio routines only): bpm tinted by
|
||||
/// band with a cue arrow — ease off (down) or push harder (up). Renders nothing
|
||||
/// unless the run carries a target and a sample exists; dims under Always-On like
|
||||
/// the timers.
|
||||
@ViewBuilder
|
||||
private var heartRateReadout: some View {
|
||||
if let target = doc.targetHeartRate, let bpm = sessionManager?.currentHeartRate {
|
||||
let band = HeartRateBand(bpm: bpm, target: target)
|
||||
HStack(spacing: 2) {
|
||||
Text("\(Int(bpm.rounded()))")
|
||||
.monospacedDigit()
|
||||
Image(systemName: band.cueSymbol)
|
||||
}
|
||||
.font(.caption2.weight(.semibold))
|
||||
.foregroundStyle(dimmed ? Color.secondary : band.tint)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Live mirror
|
||||
|
||||
/// Finish the initial-page restore, then either follow an in-progress remote driver or, if
|
||||
@@ -749,6 +778,27 @@ private extension Color {
|
||||
static let restTimer = Color(white: 0.74)
|
||||
}
|
||||
|
||||
// MARK: - Heart-rate band presentation
|
||||
|
||||
private extension HeartRateBand {
|
||||
/// The correction cue: below target → push harder (up), above → ease off (down).
|
||||
var cueSymbol: String {
|
||||
switch self {
|
||||
case .low: "arrow.up"
|
||||
case .inRange: "checkmark"
|
||||
case .high: "arrow.down"
|
||||
}
|
||||
}
|
||||
|
||||
var tint: Color {
|
||||
switch self {
|
||||
case .low: .blue
|
||||
case .inRange: .green
|
||||
case .high: .orange
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Phase Timer Layout
|
||||
|
||||
/// The live timer a phase shows, described by its wall-clock anchors so `PhaseTimerLayout` can
|
||||
|
||||
@@ -36,6 +36,9 @@ final class WatchAppServices {
|
||||
self.sessionCoordinator = coordinator
|
||||
// weak break: the coordinator is held here; the bridge only borrows it.
|
||||
bridge.onWorkoutsChanged = { [weak coordinator] in coordinator?.reconcile() }
|
||||
// Forward each live HR sample to a mirroring phone (best-effort, display-only).
|
||||
// No cycle: the bridge never references the session manager back.
|
||||
sessionManager.onHeartRateSample = { [bridge] bpm in bridge.sendLiveHeartRate(bpm) }
|
||||
bridge.activate()
|
||||
// Seed `previouslyActiveIDs` from whatever the bridge already applied at launch, so the
|
||||
// first real change is measured against a correct baseline (and the launch race — a
|
||||
|
||||
@@ -38,6 +38,11 @@ final class WorkoutSessionManager: NSObject {
|
||||
private(set) var currentHeartRate: Double?
|
||||
private(set) var currentActiveEnergyKcal: Double?
|
||||
|
||||
/// Fired with each fresh heart-rate sample while the session runs. The bridge hangs
|
||||
/// off this to forward the reading to the phone (best-effort, display-only) — a
|
||||
/// callback rather than observation so the sensor stream has exactly one push path.
|
||||
var onHeartRateSample: ((Double) -> Void)?
|
||||
|
||||
/// Seconds accumulated in each of 5 heart-rate zones (low→high). Built on the
|
||||
/// watch because it's the only place with the full HR stream. Empty/ignored when
|
||||
/// the user's age (hence max HR) is unknown.
|
||||
@@ -182,7 +187,10 @@ final class WorkoutSessionManager: NSObject {
|
||||
let dt = now.timeIntervalSince(last)
|
||||
if dt > 0, dt < 60 { hrZoneSeconds[Self.zoneIndex(for: prevHR, maxHR: maxHeartRate)] += dt }
|
||||
}
|
||||
if let newHR { currentHeartRate = newHR }
|
||||
if let newHR {
|
||||
currentHeartRate = newHR
|
||||
onHeartRateSample?(newHR)
|
||||
}
|
||||
lastHRSampleDate = now
|
||||
|
||||
currentActiveEnergyKcal = builder?.statistics(for: HKQuantityType(.activeEnergyBurned))?
|
||||
|
||||
Reference in New Issue
Block a user