From 02a869d788f962245164d9580e16d710f6415ff6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:22:56 +0000 Subject: [PATCH] Workout detail in two tabs; jring workouts stream heart rate the whole session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 46-minute gym session read 76/97 bpm against a watch's 116/149. The jring workout started the vendor's 180-second spot check (14 b4…), so only the warm-up streamed. The vendor's run screen sends duration 0 and the sport mode when 0x20 bit 56 is set (RunRecordActivity, setHeartRateMode); do the same, and stop in the same mode. SpO2 is no longer polled while a workout stream runs. The summary now weights heart rate by time (WorkoutHeart), so a 1 Hz stream can't outvote the ring's log, and adds active/resting calories and a training load estimate (Banister TRIMP). The workout screen becomes two tabs: Summary (total kcal, active and resting, duration, average HR, training load) and Heart rate (curve with average, maximum, minutes per zone). Audit in audits/2026-11-16-workout-detail-tabs.md. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 6 + app/src/main/assets/i18n/pt-BR.json | 17 ++ .../java/com/pulseloop/ring/JringDriver.kt | 37 +++ .../java/com/pulseloop/ring/RingEncoder.kt | 24 ++ .../java/com/pulseloop/ring/RingProtocol.kt | 4 + .../pulseloop/service/ActivityAggregates.kt | 10 +- .../com/pulseloop/service/WorkoutHeart.kt | 94 ++++++ .../service/WorkoutSensorPollingService.kt | 8 +- .../pulseloop/ui/screens/WorkoutDetailTabs.kt | 282 ++++++++++++++++++ .../ui/screens/WorkoutSummaryScreen.kt | 177 +++++------ .../ring/JringWorkoutHeartRateTest.kt | 71 +++++ .../com/pulseloop/service/WorkoutHeartTest.kt | 67 +++++ audits/2026-11-16-workout-detail-tabs.md | 115 +++++++ docs/jring-56ff-plan.md | 35 +++ 14 files changed, 843 insertions(+), 104 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/service/WorkoutHeart.kt create mode 100644 app/src/main/java/com/pulseloop/ui/screens/WorkoutDetailTabs.kt create mode 100644 app/src/test/java/com/pulseloop/ring/JringWorkoutHeartRateTest.kt create mode 100644 app/src/test/java/com/pulseloop/service/WorkoutHeartTest.kt create mode 100644 audits/2026-11-16-workout-detail-tabs.md diff --git a/AGENTS.md b/AGENTS.md index 5b7a0ad6..20894822 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,6 +87,12 @@ in the vendor's order, and then the workouts the ring recorded in sport mode (`0 offered on the Activity tab and added on a tap, like another device's workouts (`RingWorkoutLog`). A unit that sets bit 10 is granted TEMPERATURE at runtime. Details: `docs/jring-56ff-plan.md`, "What the vendor app does with BP and sugar". +**A jring workout's heart rate is the vendor's sport mode, not its 180-second check.** `0x14` is +`setHeartRateMode`: bytes 1-4 a duration in seconds (0 = until stopped), byte 5 the sport mode. +`14 b4…` is the vendor's spot check, so workouts used to stream for three minutes. Workouts send +duration 0 and the sport's mode when `0x20` bit 56 (`FUNCTION_SPORT_FROM_APP`) is set, as +`RunRecordActivity` does. Details: `docs/jring-56ff-plan.md`, "Workout heart rate". + ## Colmi/Yawell OS-bonding is a hand-curated allowlist — not "match QRing exactly" **This is the one rule in this file most likely to get silently reverted by a future "generalize diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index f0a3cd9c..3e7fa006 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -242,6 +242,7 @@ "Automatic backups": "Backups automáticos", "Average": "Média", "Average difference {0}; 95 % of differences between {1} and {2}": "Diferença média {0}; 95 % das diferenças entre {1} e {2}", + "Average heart rate": "Frequência cardíaca média", "Averaging {0} against a need of {1}": "Média de {0} contra uma necessidade de {1}", "Averaging {0} over {1} nights": "Média de {0} em {1} noites", "Avg ": "Méd. ", @@ -661,6 +662,7 @@ "Estimated from heart rate": "Estimado pela frequência cardíaca", "Estimated from resting heart rate and age": "Estimado a partir da frequência cardíaca em repouso e da idade", "Estimated from the current discharge at %.1f %%/h.": "Estimado a partir da descarga atual de %.1f %%/h.", + "Estimated from your heart rate": "Estimada pela sua frequência cardíaca", "Estimated wellness metric": "Métrica de bem-estar estimada", "Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is FDA-authorized to measure or estimate glucose on its own.": "Métrica de bem-estar estimada — não use para dosar medicamentos nem para decisões sobre diabetes. Nenhum anel ou relógio inteligente tem autorização da FDA para medir ou estimar glicose sozinho.", "Estimated · calibrate with a cuff": "Estimado · calibre com um medidor de pressão", @@ -819,6 +821,7 @@ "Heart rate": "Frequência cardíaca", "Heart rate above your quiet waking {0} bpm, {1} min well above it": "Frequência cardíaca acima do seu nível tranquilo acordado de {0} bpm, {1} min bem acima", "Heart rate at rest": "Frequência cardíaca em repouso", + "Heart rate over the workout, average {0} bpm": "Frequência cardíaca durante o treino, média de {0} bpm", "Heart rate since last night": "Frequência cardíaca desde ontem à noite", "Heart rate since last night: latest {0} bpm, range {1}–{2} bpm, {3} readings": "Frequência cardíaca desde ontem à noite: última {0} bpm, faixa {1}–{2} bpm, {3} leituras", "Heart rate stayed at your quiet level with no steps": "A frequência cardíaca ficou no seu nível tranquilo, sem passos", @@ -1058,6 +1061,7 @@ "Max": "Máx.", "Max HR": "FC máx.", "Max tokens": "Máximo de tokens", + "Maximum": "Máxima", "Maçã": "Maçã", "Me": "Eu", "Meal": "Refeição", @@ -1177,6 +1181,7 @@ "No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically.": "Nenhuma exportação foi feita ainda. Com a chave principal ativada e uma opção de histórico escolhida, o PulseLoop exporta automaticamente.", "No fatigue data yet — take a measurement.": "Ainda não há dados de fadiga — faça uma medição.", "No goal set · {0} is a typical day": "Sem meta definida · {0} é um dia típico", + "No heart rate for this workout": "Sem frequência cardíaca neste treino", "No meals logged this week": "Nenhuma refeição registrada nesta semana", "No night to read": "Nenhuma noite para ler", "No nights tracked in this range yet.": "Nenhuma noite registrada neste período ainda.", @@ -1427,6 +1432,7 @@ "Reading failed: {0}": "A leitura falhou: {0}", "Reading your drinks…": "Lendo suas bebidas…", "Reading your history…": "Lendo seu histórico…", + "Readings cover {0} of {1} min.": "As leituras cobrem {0} de {1} min.", "Ready to start the day? Take a measurement and I'll help you plan it.": "Pronto para começar o dia? Faça uma medição e eu ajudo você a planejá-lo.", "Ready · {0}": "Pronto · {0}", "Reasoning effort": "Nível de raciocínio", @@ -1735,6 +1741,7 @@ "Studio, cardio, or freestyle": "Aula, cardio ou livre", "Suggested next check-in: {0}": "Próximo check-in sugerido: {0}", "Summarize my week": "Resumir minha semana", + "Summary": "Resumo", "Summary copied. It holds counts and timings only, no readings.": "Resumo copiado. Ele contém apenas contagens e horários, nenhuma leitura.", "Sunday evening: your week compared with the last one, and one thing to focus on.": "Domingo à noite: sua semana comparada com a anterior e um ponto para focar.", "Supplement": "Suplemento", @@ -1817,6 +1824,7 @@ "The ring isn't detecting your finger. Put it on snugly, then try again.": "O anel não está detectando seu dedo. Coloque-o bem justo e tente novamente.", "The ring recorded this as one record": "O anel registrou isto como um único registro", "The ring recorded this night in {0} parts": "O anel registrou esta noite em {0} partes", + "The ring sent no readings while it was recorded. Keep the ring snug and connected during the next one.": "O anel não enviou leituras durante a gravação. No próximo, mantenha o anel justo e conectado.", "The scan failed. Try again in a moment.": "A busca falhou. Tente novamente em instantes.", "The share of your time in bed spent asleep. Around 85% or more is considered good.": "A parte do seu tempo na cama em que você dormiu. Cerca de 85% ou mais é considerado bom.", "The stage mix was useful, but total sleep time was short for a full recovery window. A slightly earlier wind-down would likely improve tomorrow's score.": "A combinação de estágios foi boa, mas o tempo total de sono foi curto para uma recuperação completa. Começar a relaxar um pouco mais cedo deve melhorar a pontuação de amanhã.", @@ -1858,6 +1866,7 @@ "Time": "Horário", "Time asleep": "Tempo dormindo", "Time for {0}": "Hora de {0}", + "Time in each zone": "Tempo em cada zona", "Time to move": "Hora de se mexer", "Time to wind down": "Hora de relaxar", "Timeout (s)": "Tempo limite (s)", @@ -1873,6 +1882,7 @@ "Tonight: {0} drink{1}": "Hoje à noite: {0} bebida{1}", "Tool calling": "Chamada de ferramentas", "Tools that connect over HTTP": "Ferramentas que se conectam por HTTP", + "Total calories": "Calorias totais", "Total sleep": "Sono total", "Total workout time this week. Health guidelines suggest at least 150 minutes of moderate activity a week.": "Tempo total de treino nesta semana. As diretrizes de saúde sugerem pelo menos 150 minutos de atividade moderada por semana.", "Track Bedtime / DND mode": "Monitorar modo Hora de dormir / Não perturbe", @@ -1881,6 +1891,7 @@ "Tracked {0} {1} this year": "Este ano você registrou {0} {1}", "Trails and elevation": "Trilhas e elevação", "Training frequency": "Frequência de treinos", + "Training load": "Carga de treino", "Training volume": "Volume de treino", "Travel": "Viagem", "Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold.": "Trata uma frequência cardíaca em repouso baixa como sinal de condicionamento, e não de preocupação, e flexibiliza o limite de HR baixa.", @@ -2115,6 +2126,7 @@ "Your usual {0}-day cycle would have ended {1} day{2} ago.": "Seu ciclo habitual de {0} dias teria terminado há {1} dia{2}.", "Your week at a glance": "Sua semana num relance", "Your workout is still recording. Finish it now, or keep recording?": "Seu treino ainda está sendo gravado. Finalizar agora ou continuar gravando?", + "Zones are shares of an estimated maximum of {0} bpm, from your age.": "As zonas são frações de uma máxima estimada de {0} bpm, pela sua idade.", "Zoom in": "Aproximar", "Zoom out": "Afastar", "a {0} fits.": "cabe um(a) {0}.", @@ -2124,6 +2136,7 @@ "adjusted by your accuracy check": "ajustado pela sua verificação de precisão", "any meal": "qualquer refeição", "average week": "semana média", + "avg {0}": "média {0}", "avg {0} bpm": "média {0} bpm", "bed {0}": "deitar {0}", "below": "abaixo", @@ -2185,6 +2198,7 @@ "the ring": "o anel", "trending down": "em queda", "trending up": "em alta", + "under {0}": "abaixo de {0}", "unknown error": "erro desconhecido", "up": "a mais", "up {0}": "acordar {0}", @@ -2200,6 +2214,7 @@ "{0} % same stage": "{0} % no mesmo estágio", "{0} (Tailscale)": "{0} (Tailscale)", "{0} / week": "{0} / semana", + "{0} active · {1} resting": "{0} ativas · {1} em repouso", "{0} asleep": "{0} dormindo", "{0} asleep · woke {1} times · longest stretch {2}": "{0} dormindo · acordou {1} vezes · maior trecho {2}", "{0} at {1}.": "{0} às {1}.", @@ -2298,10 +2313,12 @@ "{0}% higher over two weeks than the four before.": "{0}% mais alta nas últimas duas semanas que nas quatro anteriores.", "{0}% of the night asleep": "{0}% da noite dormindo", "{0}% {1} baseline": "{0}% {1} da linha de base", + "{0}+": "{0}+", "{0}, about {1} MB": "{0}, cerca de {1} MB", "{0}, about {1} MB. Downloads on Wi-Fi only, unless you choose mobile data.": "{0}, cerca de {1} MB. Baixa só no Wi-Fi, a menos que você escolha os dados móveis.", "{0}, higher than your usual {1}": "{0}, acima do seu habitual de {1}", "{0}, lower than your usual {1}": "{0}, abaixo do seu habitual de {1}", + "{0}, {1} bpm: {2} min": "{0}, {1} bpm: {2} min", "{0}. Open PulseLoop to mark it taken or skipped.": "{0}. Abra o PulseLoop para marcar como tomado ou pulado.", "{0}: latest {1}, range {2}–{3}, {4} readings": "{0}: última {1}, faixa {2}–{3}, {4} leituras", "{0}d ago": "há {0}d", diff --git a/app/src/main/java/com/pulseloop/ring/JringDriver.kt b/app/src/main/java/com/pulseloop/ring/JringDriver.kt index 847cb326..aad1b9fa 100644 --- a/app/src/main/java/com/pulseloop/ring/JringDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/JringDriver.kt @@ -201,6 +201,10 @@ class JringSyncEngine( historySync.oxygenHistory = event.capabilities.hasOxygenOfflineHistory historySync.temperatureHistory = event.capabilities.hasTemperature historySync.workoutHistory = true + val pendingType = workoutActivityType + if (pendingType != null && workoutSportMode == null && event.capabilities.supportsSportFromApp) { + startWorkoutHeartRate(pendingType) + } } else -> {} } @@ -223,6 +227,39 @@ class JringSyncEngine( writer?.enqueue(encoder.makeHeartRateStartCommand()) } + /** The sport mode a running workout stream was started with, or null when none is. */ + private var workoutSportMode: Int? = null + /** The running workout's type, kept so a `0x20` reply that lands after the start (a reconnect + * mid-workout restarts the stream before the ring has re-sent its feature bits) can still + * move it onto the continuous stream. */ + private var workoutActivityType: String? = null + + /** + * Workout heart rate the way the vendor's run screen does it: continuous, in the sport's mode, + * when the ring sets `FUNCTION_SPORT_FROM_APP` (bit 56). A ring that hasn't answered `0x20`, or + * doesn't set the bit, keeps the old 180-second start: the vendor shows no heart rate at all + * on such a ring, so there is nothing better to match. + */ + override fun startWorkoutHeartRate(activityType: String) { + workoutActivityType = activityType + if (bandCapabilities?.supportsSportFromApp == true) { + val mode = encoder.jringSportMode(activityType) + workoutSportMode = mode + writer?.enqueue(encoder.makeWorkoutHeartRateStartCommand(mode)) + } else { + workoutSportMode = null + startHeartRate() + } + } + + override fun stopWorkoutHeartRate() { + workoutActivityType = null + val mode = workoutSportMode ?: return stopHeartRate() + workoutSportMode = null + writer?.enqueue(encoder.makeWorkoutHeartRateStopCommand(mode)) + writer?.enqueue(encoder.makeAutomaticHeartRateCommand(enabled = true, cadenceMinutes = 30)) + } + override fun stopHeartRate() { writer?.enqueue(encoder.makeHeartRateStopCommand()) writer?.enqueue(encoder.makeAutomaticHeartRateCommand(enabled = true, cadenceMinutes = 30)) diff --git a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt index b4b9fd24..9a634367 100644 --- a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt @@ -115,6 +115,30 @@ object RingEncoder { } fun makeHeartRateStartCommand(): ByteArray = hexToBytes("14b4000000000000000000000000000000000000") fun makeHeartRateStopCommand(): ByteArray = hexToBytes("1500000000000000000000000000000000000000") + + /** + * Continuous heart rate for a workout: the vendor's `setHeartRateMode(true, 0, mode)` + * (`RunRecordActivity.startHeartrateMode`). Bytes 1-4 are a duration in seconds, little-endian, + * and 0 means "until stopped". Byte 5 is the sport mode (1 walk, 2 run, 3 cycle, 4 climb, + * 5 golf/swim). [makeHeartRateStartCommand]'s `b4` is the vendor's 180-second spot check + * (`FragmentMain.startTestHeart`, `CommonAttributes.sport_situps` = 180), which is why a workout + * started with it lost its heart rate after three minutes. + */ + fun makeWorkoutHeartRateStartCommand(sportMode: Int): ByteArray = + ByteArray(20).also { it[0] = 0x14; it[5] = sportMode.toByte() } + + /** Ends [makeWorkoutHeartRateStartCommand]: the vendor's `setHeartRateMode(false, 0, mode)`. */ + fun makeWorkoutHeartRateStopCommand(sportMode: Int): ByteArray = + ByteArray(20).also { it[0] = 0x15; it[5] = sportMode.toByte() } + + /** The vendor's sport mode for a PulseLoop activity type (`RunRecordActivity`'s mapping; any + * other type gets its default, walk). */ + fun jringSportMode(activityType: String): Int = when (activityType) { + "run" -> 2 + "cycle" -> 3 + "hike" -> 4 + else -> 1 + } /** * One-shot combined-sensor measurement (0x23). byte[1] is a *mode* selector, not a generic * start flag (vendor `setBloodPressureMode`/`setSpoMode` write 0x23 with a different byte[1]): diff --git a/app/src/main/java/com/pulseloop/ring/RingProtocol.kt b/app/src/main/java/com/pulseloop/ring/RingProtocol.kt index a52da889..5d789dc7 100644 --- a/app/src/main/java/com/pulseloop/ring/RingProtocol.kt +++ b/app/src/main/java/com/pulseloop/ring/RingProtocol.kt @@ -86,6 +86,10 @@ data class JringBandCapabilities(val bytes: ByteArray) { val hasOxygenOfflineHistory: Boolean get() = bit(81) val hasPressureHistory: Boolean get() = bit(83) + /** `FUNCTION_SPORT_FROM_APP` (`DupMainActivity`, zArr[56]): the ring runs a phone-started + * workout with continuous heart rate. Without it the vendor shows no heart rate on a run. */ + val supportsSportFromApp: Boolean get() = bit(56) + override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is JringBandCapabilities) return false diff --git a/app/src/main/java/com/pulseloop/service/ActivityAggregates.kt b/app/src/main/java/com/pulseloop/service/ActivityAggregates.kt index 5f1f80ca..8ec098be 100644 --- a/app/src/main/java/com/pulseloop/service/ActivityAggregates.kt +++ b/app/src/main/java/com/pulseloop/service/ActivityAggregates.kt @@ -34,6 +34,8 @@ object ActivityAggregates { } else null val distanceMeters = resolveDistanceMeters(session, acceptedCount, routeDistance) + val hrSamples = hrRows.map { WorkoutHeart.Sample(it.timestamp, it.value) } + val heart = WorkoutHeart.summary(hrSamples, end, profileEntity?.age) val calories = WorkoutMetricsEngine.calories( type = session.type, durationSeconds = duration, @@ -44,9 +46,11 @@ object ActivityAggregates { return session.copy( calories = calories, distanceMeters = distanceMeters, - avgHeartRate = hrRows.map { it.value }.average0(), - maxHeartRate = hrRows.maxOfOrNull { it.value }, - minHeartRate = hrRows.minOfOrNull { it.value }, + // Weighted by time (WorkoutHeart): a second-by-second stream must not outvote the + // ring's log for the rest of the session. + avgHeartRate = heart?.average, + maxHeartRate = heart?.max, + minHeartRate = WorkoutHeart.weighted(hrSamples, end).minOfOrNull { it.bpm }, avgSpO2 = spo2Rows.map { it.value }.average0(), latestSpO2 = spo2Rows.lastOrNull()?.value, gpsPointCount = acceptedCount, diff --git a/app/src/main/java/com/pulseloop/service/WorkoutHeart.kt b/app/src/main/java/com/pulseloop/service/WorkoutHeart.kt new file mode 100644 index 00000000..3ad1d0a1 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/WorkoutHeart.kt @@ -0,0 +1,94 @@ +package com.pulseloop.service + +import kotlin.math.exp + +/** + * A workout's heart-rate figures, weighted by time rather than by sample. + * + * A workout's window holds rows at very different rates: the live stream about once a second, the + * ring's own log every few minutes, a spot reading now and then. Averaged per row, three minutes + * of stream outweigh forty minutes of log, so the summary said whatever those three minutes said + * (the 12 Nov gym session read 76 bpm against a watch's 116). Each reading here counts for the time + * until the next one, capped at [MAX_SAMPLE_WEIGHT_MS] so a gap with no readings is not credited + * to the reading before it. + * + * Pure, so the rules are unit-tested (`WorkoutHeartTest`). + */ +object WorkoutHeart { + /** Readings outside this band are sensor noise, not a heart rate. */ + const val MIN_BPM = 30.0 + const val MAX_BPM = 230.0 + + /** The longest stretch one reading may stand for. Longer than the ring's 5-minute log is too + * generous for exercise; two minutes covers the burstiest live stream seen (issue #59). */ + const val MAX_SAMPLE_WEIGHT_MS = 120_000L + + data class Sample(val atMs: Long, val bpm: Double) + + /** One reading and the minutes it stands for. */ + data class Weighted(val bpm: Double, val minutes: Double) + + data class Summary( + val average: Double, + val max: Double, + /** Minutes in each [HeartRateZones.Zone], in enum order. */ + val zoneMinutes: Map, + /** Minutes the readings cover, at most the workout's length. */ + val coveredMinutes: Double, + ) + + fun weighted(samples: List, endMs: Long): List { + val clean = samples.filter { it.bpm in MIN_BPM..MAX_BPM }.sortedBy { it.atMs } + return clean.mapIndexed { i, s -> + val next = clean.getOrNull(i + 1)?.atMs ?: endMs + val span = (next - s.atMs).coerceIn(0L, MAX_SAMPLE_WEIGHT_MS) + Weighted(s.bpm, span / 60_000.0) + } + } + + fun summary(samples: List, endMs: Long, age: Int?): Summary? { + val w = weighted(samples, endMs) + if (w.isEmpty()) return null + val covered = w.sumOf { it.minutes } + // A single reading at the very end stands for no time; fall back to a plain mean. + val average = if (covered > 0) w.sumOf { it.bpm * it.minutes } / covered else w.map { it.bpm }.average() + val zones = HeartRateZones.Zone.entries.associateWith { 0.0 }.toMutableMap() + w.forEach { zones.merge(HeartRateZones.zoneFor(it.bpm.toInt(), age ?: DEFAULT_AGE), it.minutes, Double::plus) } + return Summary(average, w.maxOf { it.bpm }, zones, covered) + } + + /** + * Banister's training impulse (TRIMP): minutes × heart-rate reserve fraction × a sex-specific + * exponential weighting (Banister 1991; Morton, Fitz-Clarke & Banister 1990). An estimate of + * how hard the session was for this person; watches publish their own variants of it as + * "training load", which is why it can sit near theirs but is never the same number. + * + * Null without readings. [restingBpm] falls back to 60 and age to [DEFAULT_AGE]. + */ + fun trainingLoad(samples: List, endMs: Long, age: Int?, sex: String?, restingBpm: Double?): Double? { + val w = weighted(samples, endMs) + if (w.isEmpty() || w.sumOf { it.minutes } <= 0.0) return null + val max = HeartRateZones.maxHR(age ?: DEFAULT_AGE).toDouble() + val rest = (restingBpm ?: 60.0).coerceIn(35.0, max - 20) + val female = sex?.lowercase() == "female" + val a = if (female) 0.86 else 0.64 + val b = if (female) 1.67 else 1.92 + return w.sumOf { s -> + val reserve = ((s.bpm - rest) / (max - rest)).coerceIn(0.0, 1.0) + s.minutes * reserve * a * exp(b * reserve) + } + } + + /** + * Resting energy over [minutes] (Mifflin-St Jeor), so a workout's total can be split into + * active and resting the way a watch does. Null when the profile lacks any input. + */ + fun restingCalories(minutes: Double, sex: String?, age: Int?, weightKg: Double?, heightCm: Double?): Double? { + val s = sex?.lowercase()?.takeIf { it == "male" || it == "female" } ?: return null + if (age == null || weightKg == null || heightCm == null) return null + val perDay = 10 * weightKg + 6.25 * heightCm - 5 * age + if (s == "male") 5 else -161 + return perDay / 1440.0 * minutes + } + + const val DEFAULT_AGE = 30 +} diff --git a/app/src/main/java/com/pulseloop/service/WorkoutSensorPollingService.kt b/app/src/main/java/com/pulseloop/service/WorkoutSensorPollingService.kt index c4aa9f74..f070cd01 100644 --- a/app/src/main/java/com/pulseloop/service/WorkoutSensorPollingService.kt +++ b/app/src/main/java/com/pulseloop/service/WorkoutSensorPollingService.kt @@ -6,7 +6,8 @@ import kotlinx.coroutines.* /** * Ported from [WorkoutSensorPollingService] in WorkoutSensorPollingService.swift. - * Periodically polls the ring for HR (~60s) and SpO2 (~5min) during a workout. + * Periodically polls the ring for HR (~60s) and SpO2 (~5min) during a workout, each only while no + * workout heart-rate stream is running. */ class WorkoutSensorPollingService( private val coordinator: RingSyncCoordinator, @@ -52,7 +53,10 @@ class WorkoutSensorPollingService( nextHRPoll = System.currentTimeMillis() + if (didRead) hrIntervalMs else disconnectedRetryMs } - if (!isPolling && now >= nextSpO2Poll) { + // Not while the workout's heart-rate stream runs: the ring has one optical + // sensor, so each SpO2 reading stops the stream for up to a minute, every five + // minutes. Neither the vendor's run screen nor a watch measures SpO2 mid-workout. + if (!isPolling && now >= nextSpO2Poll && !coordinator.workoutHRActive) { val didRead = poll("spo2") { coordinator.measureSpO2() } nextSpO2Poll = System.currentTimeMillis() + if (didRead) spo2IntervalMs else disconnectedRetryMs } diff --git a/app/src/main/java/com/pulseloop/ui/screens/WorkoutDetailTabs.kt b/app/src/main/java/com/pulseloop/ui/screens/WorkoutDetailTabs.kt new file mode 100644 index 00000000..430cc3c4 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/WorkoutDetailTabs.kt @@ -0,0 +1,282 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.service.HeartRateZones +import com.pulseloop.service.WorkoutHeart +import com.pulseloop.ui.calm.Look +import com.pulseloop.ui.calm.lookCard +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import com.pulseloop.ui.theme.PulseColors +import kotlin.math.roundToInt + +/** + * The finished workout's two tabs: Summary (what it cost and how hard it was) and Heart rate (how + * the effort went). Styled through [Look], so it follows whichever look is on. + */ + +/** Everything both tabs read, worked out once per load. Heart-rate values already carry the + * accuracy corrections (display only). */ +internal data class WorkoutFigures( + val totalKcal: Double?, + val activeKcal: Double?, + val durationSec: Int?, + val heart: WorkoutHeart.Summary?, + val trainingLoad: Double?, + /** The readings as drawn: minutes from the start, bpm. */ + val curve: List>, + val workoutMinutes: Double, +) + +@Composable +internal fun WorkoutTabs(selected: Int, onSelect: (Int) -> Unit) { + val items = listOf(tr("Summary"), tr("Heart rate")) + Row(Modifier.fillMaxWidth()) { + items.forEachIndexed { i, label -> + val on = i == selected + Column( + Modifier.weight(1f).heightIn(min = 48.dp) + .selectable(selected = on, role = Role.Tab, onClick = { onSelect(i) }), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Bottom, + ) { + Text( + label, + style = MaterialTheme.typography.titleMedium.copy(fontSize = 16.sp, fontWeight = FontWeight.SemiBold), + color = if (on) Look.text else Look.textMuted, + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(bottom = 10.dp), + ) + Box(Modifier.fillMaxWidth(0.6f).height(2.dp).background(if (on) Look.text else Color.Transparent)) + } + } + } + HorizontalDivider(color = Look.border) +} + +@Composable +internal fun WorkoutSummaryTab(f: WorkoutFigures) { + Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { + // The one big number: what the workout burned. Active and resting sit under it, like a watch. + Column(Modifier.fillMaxWidth().lookCard().padding(20.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row(verticalAlignment = Alignment.Bottom) { + Text( + f.totalKcal?.roundToInt()?.toString() ?: "—", + style = MaterialTheme.typography.displaySmall.copy(fontSize = 40.sp, fontWeight = FontWeight.SemiBold), + color = Look.text, + ) + Text(" kcal", style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp), color = Look.textSecondary, modifier = Modifier.padding(bottom = 6.dp)) + } + Text(tr("Total calories"), style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary) + val active = f.activeKcal + val total = f.totalKcal + if (active != null && total != null) { + Text( + trf("{0} active · {1} resting", active.roundToInt().toString(), (total - active).roundToInt().toString()), + style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.text, + ) + } + } + + Column(Modifier.fillMaxWidth().lookCard()) { + FactRow(tr("Duration"), f.durationSec?.let { com.pulseloop.ui.components.ActivityMeta.duration(it) } ?: "—") + HorizontalDivider(color = Look.border) + FactRow(tr("Average heart rate"), f.heart?.let { trf("{0} bpm", it.average.roundToInt().toString()) } ?: "—") + HorizontalDivider(color = Look.border) + FactRow( + tr("Training load"), + f.trainingLoad?.roundToInt()?.toString() ?: "—", + note = if (f.trainingLoad != null) tr("Estimated from your heart rate") else null, + ) + } + } +} + +@Composable +private fun FactRow(label: String, value: String, note: String? = null) { + Row( + Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column(Modifier.weight(1f)) { + Text(label, style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp), color = Look.text) + if (note != null) Text(note, style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textMuted) + } + Text(value, style = MaterialTheme.typography.titleMedium.copy(fontSize = 20.sp, fontWeight = FontWeight.SemiBold), color = Look.text, maxLines = 1) + } +} + +@Composable +internal fun WorkoutHeartTab(f: WorkoutFigures, age: Int?) { + val heart = f.heart + if (heart == null || f.curve.size < 2) { + Column(Modifier.fillMaxWidth().lookCard().padding(20.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(tr("No heart rate for this workout"), style = MaterialTheme.typography.titleMedium.copy(fontSize = 16.sp, fontWeight = FontWeight.SemiBold), color = Look.text) + Text( + tr("The ring sent no readings while it was recorded. Keep the ring snug and connected during the next one."), + style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary, + ) + } + return + } + Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { + Column(Modifier.fillMaxWidth().lookCard().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) { + HeartFigure(tr("Average"), heart.average) + HeartFigure(tr("Maximum"), heart.max) + } + HeartChart(f.curve, heart.average, f.workoutMinutes) + Row(Modifier.fillMaxWidth()) { + Text("0", style = MaterialTheme.typography.labelSmall.copy(fontSize = 12.sp), color = Look.textMuted, modifier = Modifier.weight(1f)) + Text(trf("{0} min", f.workoutMinutes.roundToInt().toString()), style = MaterialTheme.typography.labelSmall.copy(fontSize = 12.sp), color = Look.textMuted) + } + // Honest about gaps: a figure from half the session is still a figure, but say so. + if (f.workoutMinutes > 0 && heart.coveredMinutes < f.workoutMinutes * 0.6) { + Text( + trf("Readings cover {0} of {1} min.", heart.coveredMinutes.roundToInt().toString(), f.workoutMinutes.roundToInt().toString()), + style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textMuted, + ) + } + } + + Text(tr("Time in each zone"), style = MaterialTheme.typography.titleMedium.copy(fontSize = 20.sp, fontWeight = FontWeight.SemiBold), color = Look.text, modifier = Modifier.padding(top = 8.dp)) + Column(Modifier.fillMaxWidth().lookCard().padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + val maxHr = HeartRateZones.maxHR(age ?: WorkoutHeart.DEFAULT_AGE) + val longest = heart.zoneMinutes.values.maxOrNull()?.takeIf { it > 0 } ?: 1.0 + // Hardest first, as a watch lists them. + HeartRateZones.Zone.entries.reversed().forEach { zone -> + ZoneRow(zone, heart.zoneMinutes[zone] ?: 0.0, longest, maxHr) + } + Text( + trf("Zones are shares of an estimated maximum of {0} bpm, from your age.", maxHr.toString()), + style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textMuted, + ) + } + } +} + +@Composable +private fun HeartFigure(label: String, bpm: Double) { + Column { + Row(verticalAlignment = Alignment.Bottom) { + Text(bpm.roundToInt().toString(), style = MaterialTheme.typography.headlineMedium.copy(fontSize = 28.sp, fontWeight = FontWeight.SemiBold), color = Look.text) + Text(" bpm", style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) + } + Text(label, style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary) + } +} + +internal fun zoneColor(zone: HeartRateZones.Zone): Color = when (zone) { + HeartRateZones.Zone.REST -> PulseColors.textMuted + HeartRateZones.Zone.FAT_BURN -> PulseColors.zoneMint + HeartRateZones.Zone.CARDIO -> PulseColors.zoneAmber + HeartRateZones.Zone.PEAK -> PulseColors.zoneOrange + HeartRateZones.Zone.MAX -> PulseColors.zoneRed +} + +@Composable +private fun ZoneRow(zone: HeartRateZones.Zone, minutes: Double, longest: Double, maxHr: Int) { + val lo = zone.range.first * maxHr / 100 + val range = if (zone == HeartRateZones.Zone.REST) trf("under {0}", (60 * maxHr / 100).toString()) + else if (zone == HeartRateZones.Zone.MAX) trf("{0}+", lo.toString()) + else "$lo–${(zone.range.last + 1) * maxHr / 100 - 1}" + val mins = minutes.roundToInt() + Column( + Modifier.fillMaxWidth().semantics(mergeDescendants = true) { + contentDescription = trf("{0}, {1} bpm: {2} min", zone.label, range, mins.toString()) + }, + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(zone.label, style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp), color = Look.text) + Text(" $range", style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textMuted, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(trf("{0} min", mins.toString()), style = MaterialTheme.typography.titleMedium.copy(fontSize = 16.sp, fontWeight = FontWeight.SemiBold), color = Look.text) + } + Box(Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)).background(Look.border)) { + if (minutes > 0) { + Box( + Modifier.fillMaxWidth((minutes / longest).toFloat().coerceIn(0.02f, 1f)).height(8.dp) + .clip(RoundedCornerShape(4.dp)).background(zoneColor(zone)), + ) + } + } + } +} + +/** The session's heart rate over time, with its average as a dashed line. A gap over five minutes + * breaks the line rather than bridging it with a guess. */ +@Composable +private fun HeartChart(curve: List>, average: Double, minutes: Double) { + val line = PulseColors.heartRate + val grid = Look.border + val avgColor = Look.textSecondary + val lo = (curve.minOf { it.second } - 10).coerceAtLeast(30.0) + val hi = curve.maxOf { it.second } + 10 + val span = minutes.coerceAtLeast(curve.last().first).coerceAtLeast(1.0) + val chartHeight = 160.dp + // The dashed line's own label, just above it at the right edge. + val avgFrac = ((average - lo) / (hi - lo)).toFloat().coerceIn(0f, 1f) + Box(Modifier.fillMaxWidth()) { + Canvas( + Modifier.fillMaxWidth().height(chartHeight).semantics { + contentDescription = trf("Heart rate over the workout, average {0} bpm", average.roundToInt().toString()) + }, + ) { + fun x(m: Double) = (m / span * size.width).toFloat() + fun y(b: Double) = (size.height - (b - lo) / (hi - lo) * size.height).toFloat() + drawLine(grid, Offset(0f, size.height), Offset(size.width, size.height), 1.dp.toPx()) + val path = Path() + curve.forEachIndexed { i, (m, b) -> + val gap = i > 0 && m - curve[i - 1].first > 5.0 + if (i == 0 || gap) path.moveTo(x(m), y(b)) else path.lineTo(x(m), y(b)) + } + drawPath(path, line, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round)) + val ay = y(average) + drawLine(avgColor, Offset(0f, ay), Offset(size.width, ay), 1.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(8f, 8f))) + } + Text( + trf("avg {0}", average.roundToInt().toString()), + style = MaterialTheme.typography.labelSmall.copy(fontSize = 12.sp), + color = Look.textSecondary, + modifier = Modifier.align(Alignment.TopEnd) + .offset(y = (chartHeight * (1f - avgFrac) - 18.dp).coerceAtLeast(0.dp)) + .background(Look.card).padding(horizontal = 4.dp) + .clearAndSetSemantics {}, + ) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt index 3b143165..210a1c80 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt @@ -63,6 +63,9 @@ import com.pulseloop.settings.UnitSystem import com.pulseloop.ui.components.ActivityMeta import com.pulseloop.ui.components.WorkoutMapView import com.pulseloop.ui.theme.PulseColors +import com.pulseloop.ui.calm.Look +import com.pulseloop.ui.calm.lookCard +import androidx.compose.runtime.saveable.rememberSaveable import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Calendar @@ -90,6 +93,9 @@ fun WorkoutSummaryScreen( // Separate from `session == null`, which is also the state while the first load runs. var loaded by remember { mutableStateOf(false) } var points by remember { mutableStateOf>(emptyList()) } + var hrSamples by remember { mutableStateOf>(emptyList()) } + var profile by remember { mutableStateOf(null) } + var tab by rememberSaveable { mutableIntStateOf(0) } var confirmDelete by remember { mutableStateOf(false) } var editing by remember { mutableStateOf(false) } // Set when applyEdit refuses the save, so the sheet says so instead of silently staying open. @@ -108,12 +114,16 @@ fun WorkoutSummaryScreen( .filter { it.accepted && it.timestamp in loaded.startedAt..end } .sortedBy { it.timestamp } } + hrSamples = if (loaded == null) emptyList() else db.measurementDao() + .range(com.pulseloop.ring.MeasurementKind.HEART_RATE.name, loaded.startedAt, loaded.endedAt ?: System.currentTimeMillis()) + .map { com.pulseloop.service.WorkoutHeart.Sample(it.timestamp, it.value) } + profile = db.userProfileDao().get() } LaunchedEffect(sessionId) { reload(); loaded = true } val s = session ?: run { - if (loaded) MissingWorkout(onBack) else Box(Modifier.fillMaxSize().background(PulseColors.background)) + if (loaded) MissingWorkout(onBack) else Box(Modifier.fillMaxSize().background(Look.page)) return } // Duration excludes pauses and is clamped at 0 (iOS clamps in ActivityMeta.duration's @@ -122,7 +132,8 @@ fun WorkoutSummaryScreen( val is24h = android.text.format.DateFormat.is24HourFormat(context) - Column(Modifier.fillMaxSize().background(PulseColors.background)) { + com.pulseloop.ui.calm.CalmTypography(enabled = Look.calm) { + Column(Modifier.fillMaxSize().background(Look.page)) { // The shared pushed-screen bar (was a hand-rolled row of circles): Back, then the screen's // own actions on the trailing edge. com.pulseloop.ui.components.PulseTopBar(title = tr("Workout"), onBack = onBack) { @@ -146,36 +157,50 @@ fun WorkoutSummaryScreen( IconButton(onClick = { editing = true }) { Icon(Icons.Filled.Edit, tr("Edit workout"), tint = PulseColors.textSecondary) } IconButton(onClick = { confirmDelete = true }) { Icon(Icons.Filled.Delete, tr("Delete workout"), tint = PulseColors.danger) } } + val corrections = rememberAccuracyCorrections() + val figures = remember(s, hrSamples, profile, corrections) { workoutFigures(s, durationSec, hrSamples, profile, corrections) } LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { item { - Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { + // Which workout, then the tabs. Left-aligned and quiet: the figures below are the point. + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { Box( // Decoration, not a tap target: no mint. - Modifier.size(72.dp).clip(CircleShape).dither(PulseColors.textSecondary, 0.18f), + Modifier.size(48.dp).clip(CircleShape).dither(PulseColors.textSecondary, 0.18f), contentAlignment = Alignment.Center, ) { - Icon(ActivityMeta.icon(s.type), null, tint = PulseColors.textPrimary, modifier = Modifier.size(32.dp)) + Icon(ActivityMeta.icon(s.type), null, tint = Look.text, modifier = Modifier.size(24.dp)) + } + Column { + Text(ActivityMeta.label(s.type), style = androidx.compose.material3.MaterialTheme.typography.titleLarge.copy(fontSize = 24.sp, fontWeight = FontWeight.SemiBold), color = Look.text) + Text(dateRange(s, is24h), style = androidx.compose.material3.MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary) } - Text(ActivityMeta.label(s.type), fontSize = 24.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(dateRange(s, is24h), fontSize = 14.sp, color = PulseColors.textMuted) } } - item { SummaryHeroBand(s, durationSec, units) } - item { StatsGrid(s) } - if (s.useGps) { - item { WorkoutMapView(points = points) } - // Splits follow iOS's ActivityMetricSet — shown for pace/speed activities, not sport. - if (ActivityMeta.metricSet(s.type).showsSplits) { - item { SplitsCard(points, units, s.type) } + item { WorkoutTabs(tab) { tab = it } } + if (tab == 0) { + item { WorkoutSummaryTab(figures) } + if (s.useGps) { + item { GpsBand(s, durationSec, units) } + item { WorkoutMapView(points = points) } + // Splits follow iOS's ActivityMetricSet — shown for pace/speed activities, not sport. + if (ActivityMeta.metricSet(s.type).showsSplits) { + item { SplitsCard(points, units, s.type) } + } } + } else { + item { WorkoutHeartTab(figures, profile?.age) } } + corrections.describe(setOf( + com.pulseloop.health.accuracy.ComparisonMetric.HR_REST, com.pulseloop.health.accuracy.ComparisonMetric.HR_ACTIVE, + ))?.let { item { AdjustedCaption(it) } } item { Spacer(Modifier.height(48.dp)) } } } + } if (confirmDelete) { AlertDialog( @@ -442,103 +467,57 @@ private fun dateRange(s: ActivitySessionEntity, is24h: Boolean): String { return "$day · ${fmt.clock(is24h, s.startedAt)} – ${fmt.clock(is24h, ended)}" } -/** Three large headline stats: GPS → distance/duration/pace-or-speed (calories for sport); - * indoor → duration/active/calories. The third GPS metric follows iOS's ActivityMetricSet: - * pace for foot activities, speed for cycling, calories when neither applies. */ +/** A GPS workout's distance and its pace (foot) or speed (cycling), following iOS's + * ActivityMetricSet. Duration and calories are already in the Summary card above. */ @Composable -private fun SummaryHeroBand(s: ActivitySessionEntity, durationSec: Int?, units: UnitSystem) { - data class M(val value: String, val label: String, val tint: Color) - val corrections = rememberAccuracyCorrections() - val dur = durationSec?.let { ActivityMeta.duration(it) } ?: "—" - val metrics = if (s.useGps) { - val metricSet = ActivityMeta.metricSet(s.type) - val dist = s.distanceMeters?.let { "%.2f".format(UnitConverter.distance(it, units)) } - val third = when { - metricSet.showsPace -> - M(ActivityMeta.pace(s.distanceMeters, durationSec, units) ?: "—", tr("Pace").uppercase() + " " + ActivityMeta.paceUnit(units), PulseColors.textPrimary) - metricSet.showsSpeed -> { - val parts = ActivityMeta.speedParts(s.distanceMeters, durationSec, units) - M(parts?.first ?: "—", parts?.second ?: tr("Speed").uppercase(), PulseColors.textPrimary) - } - else -> M(s.calories?.let { "${it.toInt()}" } ?: "—", tr("CALORIES"), PulseColors.calories) +private fun GpsBand(s: ActivitySessionEntity, durationSec: Int?, units: UnitSystem) { + val metricSet = ActivityMeta.metricSet(s.type) + val metrics = buildList { + add(Pair(s.distanceMeters?.let { "%.2f".format(UnitConverter.distance(it, units)) } ?: "—", tr("Distance") + " · " + UnitConverter.distanceUnit(units))) + when { + metricSet.showsPace -> add(Pair(ActivityMeta.pace(s.distanceMeters, durationSec, units) ?: "—", tr("Pace") + " · " + ActivityMeta.paceUnit(units))) + metricSet.showsSpeed -> ActivityMeta.speedParts(s.distanceMeters, durationSec, units) + .let { add(Pair(it?.first ?: "—", tr("Speed") + (it?.second?.let { u -> " · " + u.lowercase() } ?: ""))) } } - listOf( - M(dist ?: "—", UnitConverter.distanceUnit(units).uppercase(java.util.Locale.ROOT), PulseColors.distance), - M(dur, tr("DURATION"), PulseColors.textPrimary), - third, - ) - } else { - listOf( - M(dur, tr("DURATION"), PulseColors.textPrimary), - // Was "ACTIVE MIN", which is the duration again in minutes. Average heart rate is the - // figure an indoor workout has instead of distance; the grid below then skips it. - M(s.avgHeartRate?.let { "${corrections.heartRate(it).toInt()}" } ?: "—", tr("Avg HR").uppercase(), PulseColors.heartRate), - M(s.calories?.let { "${it.toInt()}" } ?: "—", tr("CALORIES"), PulseColors.calories), - ) } - val shape = RoundedCornerShape(8.dp) Row( - Modifier - .fillMaxWidth() - .clip(shape) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, shape) - .padding(vertical = 16.dp, horizontal = 8.dp), + Modifier.fillMaxWidth().lookCard().padding(vertical = 16.dp, horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { - metrics.forEachIndexed { i, m -> + metrics.forEachIndexed { i, (value, label) -> Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text(m.value, fontSize = 28.sp, fontWeight = FontWeight.SemiBold, color = m.tint, maxLines = 1) - Text(m.label, style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textMuted, maxLines = 2, textAlign = TextAlign.Center) - } - if (i != metrics.lastIndex) { - Box(Modifier.width(1.dp).height(40.dp).background(PulseColors.borderSubtle)) + Text(value, style = androidx.compose.material3.MaterialTheme.typography.headlineMedium.copy(fontSize = 28.sp, fontWeight = FontWeight.SemiBold), color = Look.text, maxLines = 1) + Text(label, style = androidx.compose.material3.MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary, maxLines = 2, textAlign = TextAlign.Center) } + if (i != metrics.lastIndex) Box(Modifier.width(1.dp).height(40.dp).background(Look.border)) } } } -/** Secondary stat tiles, 3-per-row (WorkoutMetricsSections.statsGrid). */ -@Composable -private fun StatsGrid(s: ActivitySessionEntity) { - // Accuracy corrections at display only: the stored summary is what Health Connect and Strava get. - val corrections = rememberAccuracyCorrections() - fun hr(v: Double?) = v?.let { "${corrections.heartRate(it).toInt()}" } ?: "—" - val stats = buildList { - if (s.useGps) add(tr("Calories") to (s.calories?.let { "${it.toInt()}" } ?: "—")) - // Indoor workouts already lead with it in the band above. - if (s.useGps) add(tr("Avg HR") to hr(s.avgHeartRate)) - add(tr("Max HR") to hr(s.maxHeartRate)) - add(tr("Min HR") to hr(s.minHeartRate)) - add("SpO₂" to (s.latestSpO2?.let { "${corrections.spo2(it).toInt()}%" } ?: "—")) - } - Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - corrections.describe(setOf( - com.pulseloop.health.accuracy.ComparisonMetric.HR_REST, com.pulseloop.health.accuracy.ComparisonMetric.HR_ACTIVE, - com.pulseloop.health.accuracy.ComparisonMetric.SPO2, - ))?.let { AdjustedCaption(it) } - stats.chunked(3).forEach { row -> - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { - row.forEach { (label, value) -> - val shape = RoundedCornerShape(8.dp) - Column( - Modifier - .weight(1f) - .clip(shape) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, shape) - .padding(vertical = 16.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text(value, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(label.uppercase(), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textMuted) - } - } - repeat(3 - row.size) { Spacer(Modifier.weight(1f)) } - } - } - } +/** Both tabs' figures from the session and its heart-rate rows. Corrections are applied to the + * readings first (display only), so the average, zones, load and chart agree with each other. */ +internal fun workoutFigures( + s: ActivitySessionEntity, + durationSec: Int?, + raw: List, + profile: com.pulseloop.data.entity.UserProfileEntity?, + corrections: com.pulseloop.health.accuracy.Corrections, +): WorkoutFigures { + val heartModel = com.pulseloop.service.WorkoutHeart + val end = s.endedAt ?: System.currentTimeMillis() + val samples = raw.map { it.copy(bpm = corrections.heartRate(it.bpm)) } + val heart = heartModel.summary(samples, end, profile?.age) + val load = heartModel.trainingLoad(samples, end, profile?.age, profile?.sex, profile?.hrRestingBaseline) + val minutes = (durationSec ?: 0) / 60.0 + val resting = heartModel.restingCalories(minutes, profile?.sex, profile?.age, profile?.weightKg, profile?.heightCm) + val total = s.calories + val active = if (total != null && resting != null && total > resting) total - resting else null + // One point per 15 s: a 1 Hz stream would draw thousands of segments for nothing. + val curve = samples.filter { it.bpm in heartModel.MIN_BPM..heartModel.MAX_BPM } + .groupBy { (it.atMs - s.startedAt) / 15_000L } + .toSortedMap() + .map { (bucket, xs) -> bucket * 0.25 to xs.map { it.bpm }.average() } + return WorkoutFigures(total, active, durationSec, heart, load, curve, ((end - s.startedAt) / 60_000.0)) } /** Per-km (or per-mi) splits with relative pace bars; fastest split highlighted (SplitsTable). */ diff --git a/app/src/test/java/com/pulseloop/ring/JringWorkoutHeartRateTest.kt b/app/src/test/java/com/pulseloop/ring/JringWorkoutHeartRateTest.kt new file mode 100644 index 00000000..6f21dc19 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ring/JringWorkoutHeartRateTest.kt @@ -0,0 +1,71 @@ +package com.pulseloop.ring + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** Workout heart rate on jring follows the vendor's run screen (`RunRecordActivity`). */ +class JringWorkoutHeartRateTest { + private class FakeWriter : RingCommandWriter { + val sent = mutableListOf() + override fun enqueue(command: ByteArray) { sent += command.joinToString("") { "%02x".format(it) } } + } + + /** The owner's ring's `0x20` reply (2026-11-11 export): sets bit 56, sport from app. */ + private val ownerRing = RingDecodedEvent.BandFunction( + JringBandCapabilities(hex("62ec0738090abebb02001b0000000000000000")), + ) + private val noSportBit = RingDecodedEvent.BandFunction(JringBandCapabilities(ByteArray(19))) + + private fun hex(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + private fun cmd(op: String, mode: Int) = op + "00000000" + "%02x".format(mode) + "00".repeat(14) + + @Test + fun `owner ring sets the sport bit`() { + assertEquals(true, ownerRing.capabilities.supportsSportFromApp) + } + + @Test + fun `a workout runs continuously in its sport mode and stops in the same mode`() { + val w = FakeWriter() + val e = JringSyncEngine(w) + e.handle(ownerRing) + w.sent.clear() + e.startWorkoutHeartRate("gym") + assertEquals(listOf(cmd("14", 1)), w.sent) + w.sent.clear() + e.stopWorkoutHeartRate() + assertEquals(cmd("15", 1), w.sent.first()) + assertEquals("19", w.sent[1].take(2)) + } + + @Test + fun `sport modes follow the vendor mapping`() { + assertEquals(2, RingEncoder.jringSportMode("run")) + assertEquals(3, RingEncoder.jringSportMode("cycle")) + assertEquals(4, RingEncoder.jringSportMode("hike")) + assertEquals(1, RingEncoder.jringSportMode("walk")) + assertEquals(1, RingEncoder.jringSportMode("other")) + } + + @Test + fun `without the sport bit the old start is kept`() { + val w = FakeWriter() + val e = JringSyncEngine(w) + e.handle(noSportBit) + w.sent.clear() + e.startWorkoutHeartRate("run") + assertEquals(listOf("14b4" + "00".repeat(18)), w.sent) + } + + @Test + fun `a feature reply after a reconnect moves the workout onto the continuous stream`() { + val w = FakeWriter() + val e = JringSyncEngine(w) + e.startWorkoutHeartRate("run") + assertEquals("14b4", w.sent.single().take(4)) + e.handle(ownerRing) + assertEquals(cmd("14", 2), w.sent.last()) + e.handle(ownerRing) + assertEquals(2, w.sent.size) + } +} diff --git a/app/src/test/java/com/pulseloop/service/WorkoutHeartTest.kt b/app/src/test/java/com/pulseloop/service/WorkoutHeartTest.kt new file mode 100644 index 00000000..a3e88d56 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/WorkoutHeartTest.kt @@ -0,0 +1,67 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class WorkoutHeartTest { + private val min = 60_000L + private fun s(atMin: Double, bpm: Double) = WorkoutHeart.Sample((atMin * min).toLong(), bpm) + + @Test + fun `a burst of stream readings does not outvote the rest of the session`() { + // Three minutes of 1 Hz stream at 70, then the ring's log every 5 min at 120 for 40 min. + val stream = (0 until 180).map { WorkoutHeart.Sample(it * 1000L, 70.0) } + val log = (1..8).map { s(3.0 + (it - 1) * 5, 120.0) } + val end = (43 * min) + val summary = WorkoutHeart.summary(stream + log, end, age = 40)!! + // Per row the mean would be ~72; by time it is near 120 for the 40 logged minutes, but + // each log reading only stands for two minutes, so it lands between the two. + assertTrue("was ${summary.average}", summary.average > 100) + assertEquals(120.0, summary.max, 0.0) + } + + @Test + fun `a gap is not credited to the reading before it`() { + val w = WorkoutHeart.weighted(listOf(s(0.0, 100.0), s(30.0, 100.0)), endMs = 31 * min) + assertEquals(2.0, w[0].minutes, 1e-9) + assertEquals(1.0, w[1].minutes, 1e-9) + } + + @Test + fun `noise outside the plausible band is dropped`() { + val w = WorkoutHeart.weighted(listOf(s(0.0, 0.0), s(1.0, 12.0), s(2.0, 250.0), s(3.0, 90.0)), 4 * min) + assertEquals(listOf(90.0), w.map { it.bpm }) + } + + @Test + fun `zone minutes add up to the covered time`() { + val samples = (0 until 30).map { s(it.toDouble(), if (it < 10) 100.0 else 150.0) } + val summary = WorkoutHeart.summary(samples, 30 * min, age = 40)!! // max 180 + assertEquals(30.0, summary.zoneMinutes.values.sum(), 1e-9) + assertEquals(10.0, summary.zoneMinutes[HeartRateZones.Zone.REST]!!, 1e-9) // 55% + assertEquals(20.0, summary.zoneMinutes[HeartRateZones.Zone.PEAK]!!, 1e-9) // 83% + } + + @Test + fun `training load lands near a watch's for the 12 Nov gym session`() { + // 46 minutes averaging 116 bpm, man of about 40 resting at 60: the watch said 34. + val samples = (0 until 46).map { s(it.toDouble(), 116.0) } + val load = WorkoutHeart.trainingLoad(samples, 46 * min, age = 40, sex = "male", restingBpm = 60.0)!! + assertEquals(34.0, load, 8.0) + } + + @Test + fun `no readings means no load and no summary`() { + assertNull(WorkoutHeart.trainingLoad(emptyList(), min, 40, "male", 60.0)) + assertNull(WorkoutHeart.summary(emptyList(), min, 40)) + } + + @Test + fun `resting calories need the whole profile`() { + assertNull(WorkoutHeart.restingCalories(60.0, "male", 40, 80.0, null)) + // Mifflin-St Jeor: 10*80 + 6.25*180 - 5*40 + 5 = 1730 kcal/day. + assertEquals(1730.0 / 24, WorkoutHeart.restingCalories(60.0, "male", 40, 80.0, 180.0)!!, 1e-9) + } +} diff --git a/audits/2026-11-16-workout-detail-tabs.md b/audits/2026-11-16-workout-detail-tabs.md new file mode 100644 index 00000000..b5365993 --- /dev/null +++ b/audits/2026-11-16-workout-detail-tabs.md @@ -0,0 +1,115 @@ +# Audit: workout detail in two tabs, and the ring's workout heart rate + +Date: 2026-11-16 · PR: see the PR linking this file · Auditor: Claude Code. impeccable was run with +the skill loaded (`impeccable context --target WorkoutSummaryScreen.kt`, `craft-floor.md`, +`android.md`), on **rendered** screens: both tabs were drawn on the JVM with Robolectric native +graphics, in both looks and at font scale 1.3. That harness was local and is not committed. No +emulator in this environment (no KVM), so the device check is still owed. ux-user-flows, +graphic-design-fundamentals and less-is-more were applied by hand from their SKILL.md files. + +## What prompted it + +The owner compared one gym session (12 Nov) against a Huawei watch: + +| | Watch | PulseLoop before | +|---|---|---| +| Average HR | 116 | 76 | +| Max HR | 149 | 97 | +| Calories | 315 active / 379 total | 297 | +| Training load | 34 | none | + +Cause, from the vendor app (`docs/jring-56ff-plan.md`, "Workout heart rate"): the workout started +the ring's 180-second spot check, so only the warm-up streamed. Fixed by sending the vendor's own +continuous sport-mode start. The summary also averaged per row, so a 1 Hz stream outvoted the +ring's log; it is now weighted by time (`WorkoutHeart`). + +## Scope + +`activity_detail/{id}` (Workout). Before: a centred icon and title, a three-figure band, a grid of +small tiles (Calories, Avg/Max/Min HR, SpO₂), then the map and splits. + +After: one header line (icon, type, date and time), then two tabs. +- **Summary**: total calories as the one large number, with active and resting under it. Then a + list: duration, average heart rate, and training load marked "Estimated from your heart rate". + GPS workouts keep distance with pace or speed, the map and the splits here. +- **Heart rate**: average and maximum, the session's curve with a labelled dashed average, a note + when readings cover under 60% of the session, then minutes in each zone with each zone's bpm + range. An empty state says the ring sent nothing and what to do next time. + +Styled through `Look`, so it follows whichever look is on, with `CalmTypography` in the new one. + +## ux-user-flows (§13 flow review checklist) + +- **Entry:** Activity tab → a workout row, or straight after finishing or logging one. Unchanged. +- **Steps:** one view with two tabs. Summary is the default because "how much did it burn / how + hard was it" is the question asked on arrival. The tab is kept across rotation (`rememberSaveable`). +- **States:** loading (blank page, as before, no flash of the empty state), missing workout + (unchanged), no heart rate (Heart rate tab says so and why), partial heart rate (coverage note), + no profile (active/resting line hidden; load and zones use age 30 and resting 60), GPS / not GPS, + accuracy corrections on (caption at the bottom of both tabs). +- **Exits:** Back, Edit, Delete, Share GPX. Unchanged, still in the top bar. +- **Checklist:** every state reachable and named; no dead end; no new decisions asked of the user; + taps to the common answer unchanged (0 for calories, 1 for zones, which was not shown before). + +## impeccable + +### Audit (native, on renders) + +| # | Dimension | Score | Key finding | +|---|---|---|---| +| 1 | Accessibility | 3 | Tabs are `Role.Tab` and 48dp; each zone row reads as one sentence; the chart has a description. Colour is never alone: every zone carries its name and range. Device TalkBack pass owed. | +| 2 | Performance | 4 | The curve is bucketed to 15 s, so a 1 Hz stream draws ~180 points, not thousands. Figures computed once per load (`remember`). | +| 3 | Appearance & theming | 4 | Look tokens only; sizes on `PulseType.SCALE`; 12/8dp radii per look. | +| 4 | Platform conformance | 4 | Material tab semantics, top-app-bar actions kept, system Back unchanged. | +| 5 | Adaptivity | 3 | 1.3× renders without clipping. Landscape keeps the single column (no rail change needed). | +| | **Total** | **18/20** | | + +### Critique + +| # | Heuristic | Score | Key issue | +|---|---|---|---| +| 1 | Visibility of status | 4 | Coverage note says when the heart rate is partial instead of presenting it as whole. | +| 2 | Match real world | 4 | Same split as the watch the owner compares with: total, active, resting, load. | +| 3 | User control | 3 | Unchanged actions. | +| 4 | Consistency | 3 | Zones reuse `HeartRateZones`, as the live workout screen does. Top bar is still the old `PulseTopBar` (NL-4). | +| 5 | Error prevention | 3 | n/a | +| 6 | Recognition | 4 | Values labelled in words, not caps tiles. | +| 7 | Flexibility | 3 | n/a | +| 8 | Minimalist | 4 | Min HR and SpO₂ dropped (see less-is-more). | +| 9 | Error recovery | 3 | The empty state names the cause and the next step. | +| 10 | Help | 3 | Load and zones each say what they are estimated from. | +| | **Total** | **34/40** | Good | + +### Polish (from the renders) + +- [fixed] The dashed average line was unlabelled; it now carries "avg 111" at its right end. +- [fixed] The craft-floor ban on an eyebrow over a heading: the old CAPS tile labels are gone, and + "Time in each zone" is a plain section title. +- [P2] `PulseTopBar` is the old look's bar; it moves with NL-4 like the other pushed screens. + +No P0 or P1. + +## graphic-design-fundamentals (§13 checklist) + +- **Hierarchy:** one dominant figure per tab (40sp kcal; 28sp average and maximum), then 20sp + values in rows, then 12sp notes. +- **Contrast:** text on card uses `text`/`textSecondary`/`textMuted`, all ≥ 4.5:1 per the tokens. +- **Alignment and grid:** 16dp gutters; labels left, values right in one column. +- **Spacing:** 16dp between cards, 12–14dp inside; more above the zone title than below. +- **Colour:** zone colours are the data palette (`zoneGood`, `zoneBorderline`, `zoneElevated`, + `zoneHigh`), not mint; heart rate line in the heart-rate metric colour. +- **Consistency / simplicity / real size:** checked at 411dp and 1.3×. + +## less-is-more + +| Element | Helps now? | Duplicate? | Understood once? | Weak? | Rare? | Verdict | +|---|---|---|---|---|---|---| +| Big centred icon (72dp) | No | Type name says it | Yes | Yes | No | Shrunk to 48dp beside the title | +| Total kcal | Yes | — | Yes | — | — | Lead figure | +| Active · resting | Yes | — | Yes | — | — | One line | +| Duration, average HR, load | Yes | — | Yes | — | — | Rows | +| Min HR | No | — | Misleading in a workout (a rest between sets) | Yes | — | Cut | +| SpO₂ | No | — | Not measured mid-workout any more | Yes | — | Cut | +| Zone minutes | Yes | — | Yes | — | — | Heart rate tab | + +Taps on the common action did not rise: calories and duration are on arrival as before. diff --git a/docs/jring-56ff-plan.md b/docs/jring-56ff-plan.md index 509e6681..5dd67b2e 100644 --- a/docs/jring-56ff-plan.md +++ b/docs/jring-56ff-plan.md @@ -375,3 +375,38 @@ diagnostics export taken after a combined measurement, and one after a full hist 2. Decided 2026-10-20: Health Connect export and the coach stay as they are today. 3. Glucose recalibration reminder: deliberately left out (see Phase 2). Revisit only if the user imports real glucose and the agreement check shows the estimate tracking it. + +## Workout heart rate: continuous sport mode, not the 180-second check (2026-11-16) + +**Report.** A 46-minute gym session read average 76 / max 97 bpm against a Huawei watch's 116 / 149 +on the same workout, and calories and the new training load followed it down. + +**Cause.** PulseLoop started a workout's heart rate with `14 b4 00 00 00 00`. In the vendor SDK, +`setHeartRateMode(on, seconds, mode)` (`BluetoothLeService`, the `setHeartRateMode2` builder) +writes `0x14`, then `seconds` as a little-endian u32 in bytes 1-4, then `mode` in byte 5; `0x15` +with the same mode byte stops it. `b4` is 180 seconds: it is the vendor's **spot check** +(`FragmentMain.startTestHeart` passes `CommonAttributes.sport_situps` = 180, mode 0). So every +workout streamed for three minutes, the warm-up, and the rest of the session only had the ring's +own log. + +**What the vendor does for a workout.** `RunRecordActivity.startHeartrateMode(true)` calls +`setHeartRateMode(true, 0, heartrate_mode)`: duration 0 (until stopped), and the sport mode +1 walk, 2 run, 3 cycle, 4 climb, 5 golf or swim (any other sport gets 1). Stop sends the same with +`false`. It does this only when the ring's `0x20` reply sets bit 56 (`FUNCTION_SPORT_FROM_APP`, +`DupMainActivity` `zArr[56]`); without it the vendor shows no heart rate on a run at all. The +owner's ring sets bit 56 (2026-11-11 export: `20 62ec0738090abebb02001b…`). + +**In PulseLoop.** `JringSyncEngine.startWorkoutHeartRate` sends +`RingEncoder.makeWorkoutHeartRateStartCommand(jringSportMode(type))` when bit 56 is set, and +falls back to the old start otherwise; a `0x20` reply landing after a mid-workout reconnect moves +the stream across. Stop sends `0x15` in the same mode, then re-arms the 30-minute log as before. +SpO₂ is no longer polled while a workout stream runs (one optical sensor; the vendor's run screen +doesn't measure it either). `JringWorkoutHeartRateTest` pins the frames. Still to confirm on +hardware: that a session's stream lasts the whole workout. + +**Summary figures.** Averages, maximum, zone minutes and the training load are weighted by time +(`WorkoutHeart`), so a 1 Hz stream can't outvote the ring's log, and a reading stands for at most +two minutes. + +Source: JRing 2.0.8 (`com.jaga.ibraceletplus.jyring`), decompiled locally with jadx 1.5.1 into the +gitignored `decompiled-jring-offical/`.