From bf5ce036feca64e078ee46ad6ed2c1f8e0cc3ad5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:49:30 +0000 Subject: [PATCH] Compare two rings: a second ring, kept apart, side by side The owner wears a Colmi and a JRing to see which is more reliable, and chose "compare only": the main ring keeps feeding the app. - RingBLEClient gains a role. The comparison client has its own connection slot and saved ring, and publishes to ComparisonBus instead of PulseEventBus (only its diagnostics cross, marked). - Drivers that publish on their own (YCBT, LuckRing, Colmi, jring) go through RingCommandWriter.publish, which the comparison client overrides, so no family can leak a second ring's data. - comparison_readings (v38) holds its HR, SpO2, HRV, steps and per-minute sleep. Nothing but the comparison screen reads it. - ComparisonRing (AppServices) connects it, runs its startup and history, and streams its heart rate during recorded workouts. - Settings > My ring > Compare rings: find and pair the second ring; per day both heart-rate curves, time-weighted averages, hours with readings and how close the two were; steps and sleep; each workout ring against ring. Docs: docs/ring-comparison.md, AGENTS.md. Audit: audits/2026-11-17-compare-rings.md. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 17 + app/src/main/assets/i18n/pt-BR.json | 28 ++ .../main/java/com/pulseloop/AppServices.kt | 5 +- .../com/pulseloop/data/PulseLoopDatabase.kt | 17 +- .../main/java/com/pulseloop/data/dao/Daos.kt | 16 + .../data/entity/ComparisonEntities.kt | 28 ++ .../com/pulseloop/ring/ColmiSyncEngine.kt | 2 +- .../java/com/pulseloop/ring/ComparisonBus.kt | 33 ++ .../java/com/pulseloop/ring/JringDriver.kt | 3 +- .../com/pulseloop/ring/LuckRingHistorySync.kt | 2 +- .../java/com/pulseloop/ring/RingBLEClient.kt | 86 +++- .../java/com/pulseloop/ring/WearableDriver.kt | 5 + .../java/com/pulseloop/ring/YCBTDriver.kt | 2 +- .../com/pulseloop/ring/YCBTHistoryTransfer.kt | 2 +- .../com/pulseloop/service/ComparisonRing.kt | 127 +++++ .../pulseloop/service/LiveWorkoutManager.kt | 5 + .../com/pulseloop/service/RingComparison.kt | 72 +++ .../java/com/pulseloop/ui/PulseLoopApp.kt | 7 + .../ui/screens/RingComparisonScreen.kt | 433 ++++++++++++++++++ .../pulseloop/ui/screens/SettingsScreen.kt | 10 + .../service/ComparisonReadingsTest.kt | 39 ++ .../pulseloop/service/RingComparisonTest.kt | 46 ++ audits/2026-11-17-compare-rings.md | 109 +++++ docs/ring-comparison.md | 57 +++ 24 files changed, 1120 insertions(+), 31 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/data/entity/ComparisonEntities.kt create mode 100644 app/src/main/java/com/pulseloop/ring/ComparisonBus.kt create mode 100644 app/src/main/java/com/pulseloop/service/ComparisonRing.kt create mode 100644 app/src/main/java/com/pulseloop/service/RingComparison.kt create mode 100644 app/src/main/java/com/pulseloop/ui/screens/RingComparisonScreen.kt create mode 100644 app/src/test/java/com/pulseloop/service/ComparisonReadingsTest.kt create mode 100644 app/src/test/java/com/pulseloop/service/RingComparisonTest.kt create mode 100644 audits/2026-11-17-compare-rings.md create mode 100644 docs/ring-comparison.md diff --git a/AGENTS.md b/AGENTS.md index 20894822..a4ceab3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,6 +93,23 @@ A unit that sets bit 10 is granted TEMPERATURE at runtime. Details: `docs/jring- 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". +## A second ring is for comparison only, and its data never reaches the app's + +**Read this before touching `RingBLEClient`'s publishing, `ComparisonRing` or any driver that +publishes events itself.** Full design: `docs/ring-comparison.md`. + +- **The comparison ring publishes to `ComparisonBus`, never `PulseEventBus`.** The app's bus feeds + persistence, the device row, the accuracy watcher, Health Connect, Strava and the sync + coordinator, all of which are the main ring's. Only diagnostics cross over, marked + `[comparison ring]`. +- **A driver publishes through `RingCommandWriter.publish`, not `PulseEventBus` directly.** The + comparison client overrides it. A direct `PulseEventBus.publishBlocking` in a driver leaks a + second ring of that family into the user's history. +- **`comparison_readings` is read by the comparison screen only.** Never by a score, chart, + export or the coach, and not in the backup. +- **Stop comparing forgets without unbinding** (`clearSavedRing`, not `forget`), so the ring stays + paired to its own app. + ## 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 f5fcfcee..ff5250d4 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -227,6 +227,7 @@ "Ask the coach about it": "Pergunte ao coach", "Ask the coach for a plan": "Pedir um plano ao coach", "Ask the coach...": "Pergunte ao coach...", + "Asleep (night before)": "Dormindo (noite anterior)", "Asleep {0}": "Dormindo {0}", "At 1% of body weight a week this takes about {0} days.": "A 1% do peso corporal por semana, isso leva cerca de {0} dias.", "At baseline": "Na linha de base", @@ -407,12 +408,15 @@ "Collapsed": "Recolhido", "Collected on": "Coletado em", "Collecting: needs {0} days with at least {1} steps on both. Carry your phone as usual.": "Coletando: são necessários {0} dias com pelo menos {1} passos em ambos. Leve o celular como de costume.", + "Compare": "Comparar", "Compare my ring with this": "Comparar meu anel com isto", + "Compare rings": "Comparar anéis", "Compare with my phone": "Comparar com meu celular", "Compare your ring with another device": "Compare seu anel com outro dispositivo", "Compared with your own recent nights. This can follow illness, stress, alcohol or a hard day. It isn't a diagnosis; consider an easier day.": "Comparado com suas noites recentes. Isso pode acompanhar doença, estresse, álcool ou um dia puxado. Não é um diagnóstico; considere um dia mais leve.", "Compared with your typical week": "Comparado com sua semana típica", "Compared: {0}. These stop exporting to Health Connect until the check ends and you choose what to do with those days.": "Comparados: {0}. Eles deixam de ser exportados para o Health Connect até a verificação terminar e você escolher o que fazer com esses dias.", + "Comparison ring": "Anel de comparação", "Concerning": "Preocupante", "Connect": "Conectar", "Connect + Query": "Conectar + consultar", @@ -427,6 +431,7 @@ "Connected · {0}%": "Conectado · {0}%", "Connected — {0} · {1}%": "Conectado — {0} · {1}%", "Connected. {0} of {1} permission types granted.": "Conectado. {0} de {1} tipos de permissão concedidos.", + "Connecting": "Conectando", "Connecting to {0}…": "Conectando a {0}…", "Connecting…": "Conectando…", "Connection failed": "Falha na conexão", @@ -732,6 +737,7 @@ "Fewer steps than usual": "Menos passos que o normal", "Filter models": "Filtrar modelos", "Filter, e.g. claude": "Filtrar, ex.: claude", + "Find a ring": "Procurar um anel", "Find ring": "Encontrar anel", "Findings carry the formula version that made them (now v{0}). Patterns, not diagnoses.": "Os achados indicam a versão da fórmula que os gerou (agora v{0}). Padrões, não diagnósticos.", "Finish": "Concluir", @@ -822,6 +828,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 from both rings over the day": "Frequência cardíaca dos dois anéis ao longo do dia", "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", @@ -850,10 +857,12 @@ "High stress score. Wellness estimate, not a diagnosis.": "Pontuação de estresse alta. Estimativa de bem-estar, não um diagnóstico.", "Higher": "Mais alto", "Higher risk": "Risco maior", + "Highest": "Máxima", "Hiking": "Trilha", "Hormones": "Hormônios", "Hourly readings are estimated from heart rate — this ring's hourly SpO₂ isn't a separate measurement. Spot readings you take are measured.": "As leituras horárias são estimadas a partir da frequência cardíaca — o SpO₂ horário deste anel não é uma medição separada. As leituras pontuais que você faz são medidas.", "Hourly readings are estimated from heart rate — this ring's hourly SpO₂ isn't a separate measurement. Spot readings you take are measured. On this ring the same heart rate always comes with the same hourly SpO₂, so a night-time dip here follows a low sleeping heart rate rather than measuring oxygen.": "As leituras horárias são estimadas a partir da frequência cardíaca — o SpO₂ horário deste anel não é uma medição separada. As leituras pontuais que você faz são medidas. Neste anel, a mesma frequência cardíaca sempre vem com o mesmo SpO₂ horário, então uma queda durante a noite aqui acompanha uma frequência cardíaca baixa durante o sono, e não uma medição de oxigênio.", + "Hours with readings": "Horas com leituras", "How am I doing on my goal? What should I focus on this week?": "Como estou indo na minha meta? No que devo focar esta semana?", "How am I doing today?": "Como estou hoje?", "How can I sleep better?": "Como posso dormir melhor?", @@ -917,6 +926,7 @@ "It's at {0}%. A short charge now keeps tonight's sleep tracked.": "Está em {0}%. Uma carga rápida agora garante o registro do sono desta noite.", "Its dose record goes too. To stop the reminders but keep the record, switch off Active instead.": "O registro de doses também será apagado. Para parar os lembretes e manter o registro, desative Ativo.", "Its markers and its PDF are removed from this phone.": "Os marcadores e o PDF dele são removidos deste celular.", + "Its readings stay apart: they never change your scores, and nothing from it goes to Health Connect or Strava. Your main ring keeps working as it does now.": "As leituras dele ficam separadas: nunca mudam suas pontuações, e nada dele vai para o Health Connect ou o Strava. Seu anel principal continua funcionando como agora.", "Journal": "Diário", "Keep": "Manter", "Keep at least a minute of what the ring recorded ({0} – {1}).": "Mantenha pelo menos um minuto do que o anel registrou ({0} – {1}).", @@ -1025,6 +1035,7 @@ "Long-term insights appear as more nights are tracked.": "Insights de longo prazo aparecem conforme mais noites são registradas.", "Look again": "Verificar novamente", "Looking for apps writing to Health Connect…": "Procurando apps que gravam no Health Connect…", + "Looking… keep the second ring close to the phone, and closed in the vendor's app.": "Procurando… deixe o segundo anel perto do celular e feche o app do fabricante.", "Looks like a hike": "Parece uma trilha", "Looks like a ride": "Parece um pedal", "Looks like a run": "Parece uma corrida", @@ -1050,6 +1061,7 @@ "MIN": "MIN", "MOOD CHECK-IN": "CHECK-IN DE HUMOR", "MY WEEK": "MINHA SEMANA", + "Main ring": "Anel principal", "Major signs": "Sinais fortes", "Make me a plan from my lab reports, starting with {0}.": "Monte um plano para mim a partir dos meus laudos, começando por {0}.", "Make me a plan from my lab reports.": "Monte um plano para mim a partir dos meus laudos.", @@ -1104,6 +1116,7 @@ "MiniMax": "MiniMax", "MiniMax API Key": "Chave de API do MiniMax", "Minor signs": "Sinais leves", + "Minutes with readings": "Minutos com leituras", "Missed": "Perdida", "Model": "Modelo", "Model download needed": "É preciso baixar o modelo", @@ -1138,6 +1151,7 @@ "Needs 5 nights in the last 2 weeks": "Precisa de 5 noites nas últimas 2 semanas", "Needs care": "Requer atenção", "Needs work": "Precisa melhorar", + "Neither ring is known to be right: two rings can agree and both be off. To check one against a watch, use the accuracy check.": "Não se sabe qual anel está certo: dois anéis podem concordar e ambos estarem errados. Para conferir um com um relógio, use a verificação de precisão.", "Never": "Nunca", "Never mind": "Deixa pra lá", "New chat": "Nova conversa", @@ -1184,6 +1198,7 @@ "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 heart rate from either ring on this day.": "Nenhum dos anéis registrou frequência cardíaca neste dia.", "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.", @@ -1300,6 +1315,7 @@ "Open profile": "Abrir perfil", "Open ring settings": "Abrir configurações do anel", "Open settings": "Abrir configurações", + "Open the accuracy check": "Abrir a verificação de precisão", "Open today's activity": "Abrir atividade de hoje", "Open-source health tracker. Ported from iOS.\nCC BY 4.0 · Free to share and adapt, including commercially, with appropriate credit.": "Rastreador de saúde de código aberto. Portado do iOS.\nCC BY 4.0 · Livre para compartilhar e adaptar, inclusive comercialmente, com o devido crédito.", "OpenAI": "OpenAI", @@ -1532,6 +1548,7 @@ "Ring model estimate": "Estimativa do modelo do anel", "Ring restarted. Syncing now.": "Anel reiniciado. Sincronizando agora.", "Ring steps vs your phone": "Passos do anel vs. do seu celular", + "Rings nearby": "Anéis por perto", "Road, trail, or stationary": "Rua, trilha ou estacionária", "Route by": "Rotear por", "Route map: {0} GPS points": "Mapa do percurso: {0} pontos de GPS", @@ -1724,6 +1741,8 @@ "Steps {0}{1}%": "Passos {0}{1}%", "Stool": "Fezes", "Stop": "Parar", + "Stop comparing": "Parar de comparar", + "Stop comparing?": "Parar de comparar?", "Stop scanning": "Parar busca", "Stop using Health Connect": "Parar de usar o Health Connect", "Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message.": "Armazenada com segurança no Android Keystore. Nunca sai do seu dispositivo, exceto para chamar o modelo. Mudanças de provedor valem a partir da sua próxima mensagem.", @@ -1807,6 +1826,7 @@ "The coach on this phone can't estimate meals. Pick a cloud or self-hosted coach in Settings → AI Coach, or enter the meal manually.": "O coach deste celular não estima refeições. Escolha um coach na nuvem ou no seu servidor em Ajustes → Coach de IA, ou registre a refeição à mão.", "The coach on this phone can't read lab reports. Pick a cloud or self-hosted coach in Settings → AI Coach.": "O coach deste celular não lê exames. Escolha um coach na nuvem ou no seu servidor em Ajustes → Coach de IA.", "The coach will forget \"{0}\". This can't be undone.": "O Coach vai esquecer \"{0}\". Isso não pode ser desfeito.", + "The comparison ring disconnects and is forgotten here. It isn't unpaired from its own app, and your main ring isn't affected.": "O anel de comparação se desconecta e é esquecido aqui. Ele não é desvinculado do próprio app, e seu anel principal não é afetado.", "The date needs more of a deficit than is safe; the suggestion is held at the floor.": "A data exige um déficit maior do que o seguro; a sugestão fica no limite mínimo.", "The download didn't finish. Check your connection and try again.": "O download não terminou. Verifique sua conexão e tente de novo.", "The download didn't match its published checksum, so it was deleted. Try again.": "O download não bateu com o checksum publicado e foi apagado. Tente de novo.", @@ -1832,6 +1852,7 @@ "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ã.", "The target date has passed; agree a new one.": "A data-alvo já passou; defina uma nova.", "The tile and the morning-after line disappear. Your logged drinks stay on this phone until you delete them or clear your data.": "O bloco e a linha da manhã seguinte desaparecem. Suas bebidas registradas ficam neste celular até você excluí-las ou apagar seus dados.", + "The two rings never measured within 3 minutes of each other, so they can't be compared reading by reading yet.": "Os dois anéis nunca mediram com menos de 3 minutos de diferença, então ainda não dá para comparar leitura a leitura.", "The two weeks before a period: skin temperature and resting heart rate often run a little higher.": "As duas semanas antes da menstruação: a temperatura da pele e a frequência cardíaca em repouso costumam ficar um pouco mais altas.", "The values read from it and your changes are lost. You'd need to add the PDF again.": "Os valores lidos e suas alterações serão perdidos. Você precisará adicionar o PDF de novo.", "The window must be longer than the {0} min of pauses in this workout.": "A janela precisa ser maior que os {0} min de pausas deste treino.", @@ -1994,6 +2015,7 @@ "Warm": "Quente", "Warmer than typical. Trends matter more than a single reading.": "Mais quente que o normal. A tendência importa mais que uma leitura isolada.", "We suggest a quarter less to start": "Sugerimos um quarto a menos para começar", + "Wear a second ring to see how the two compare": "Use um segundo anel para ver como os dois se comparam", "Wear both as usual. Health Connect export paused for: {0}.": "Use os dois normalmente. Exportação para o Health Connect pausada para: {0}.", "Wear both devices as you normally would, including at night.": "Use os dois dispositivos normalmente, inclusive à noite.", "Wear the ring and a watch or band you trust for a few days. PulseLoop reads that device's data from Health Connect and shows where the ring agrees and where it falls short.": "Use o anel e um relógio ou pulseira em que você confia por alguns dias. O PulseLoop lê os dados desse aparelho no Health Connect e mostra onde o anel concorda e onde fica devendo.", @@ -2024,6 +2046,7 @@ "What your ring saw you doing, to add with a tap": "O que seu anel viu você fazendo, para adicionar com um toque", "What's your goal?": "Qual é a sua meta?", "When": "Quando", + "When both measured within 3 minutes ({0} times), they were typically {1} bpm apart, and {2}.": "Quando os dois mediram com até 3 minutos de diferença ({0} vezes), ficaram tipicamente a {1} bpm um do outro, e {2}.", "When did it end?": "Quando terminou?", "When did it start?": "Quando começou?", "When the ring is at 30% or less a couple of hours before your usual bedtime.": "Quando o anel estiver com 30% ou menos algumas horas antes do seu horário habitual de dormir.", @@ -2147,6 +2170,7 @@ "bpm range": "bpm (faixa)", "calories": "calorias", "compared over the {0} h both were on": "comparado nas {0} h em que os dois estavam ligados", + "comparison": "comparação", "daily calories": "calorias diárias", "daily calories {0} kcal": "calorias diárias {0} kcal", "day": "dia", @@ -2170,8 +2194,10 @@ "less": "menos", "logged {0} times": "registrado {0} vezes", "lower": "menor", + "main": "principal", "min": "min", "more": "mais", + "neither reads higher on average": "nenhum lê mais alto em média", "night": "noite", "nights": "noites", "no overlap": "sem sobreposição", @@ -2197,6 +2223,8 @@ "steady": "estável", "steps": "passos", "steps {0} a day": "passos {0} por dia", + "the comparison ring reads {0} higher on average": "o anel de comparação lê {0} a mais em média", + "the comparison ring reads {0} lower on average": "o anel de comparação lê {0} a menos em média", "the ring": "o anel", "trending down": "em queda", "trending up": "em alta", diff --git a/app/src/main/java/com/pulseloop/AppServices.kt b/app/src/main/java/com/pulseloop/AppServices.kt index 8c59e441..975a63f3 100644 --- a/app/src/main/java/com/pulseloop/AppServices.kt +++ b/app/src/main/java/com/pulseloop/AppServices.kt @@ -1,5 +1,6 @@ package com.pulseloop +import com.pulseloop.service.ComparisonRing import android.content.Context import com.pulseloop.coach.config.CoachProviderSettingsStore import com.pulseloop.coach.summaries.CoachSummaryCoordinator @@ -36,7 +37,9 @@ class AppServices private constructor(context: Context) { val apiKeyStore = ApiKeyStore(context) val coordinator = RingSyncCoordinator(bleClient, db, apiKeyStore) val gpsRecorder = GpsRouteRecorder(context, db) - val liveWorkout = LiveWorkoutManager(coordinator, db, gpsRecorder, context) + /** A second ring worn only to compare with this one (docs/ring-comparison.md). */ + val comparison = ComparisonRing(context, db) + val liveWorkout = LiveWorkoutManager(coordinator, db, gpsRecorder, context, comparison) /** Process-wide, not per-[AppServices]: background workers need it without the UI's services. */ val persistence = EventPersistenceSubscriber.shared(context) diff --git a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt index e97d10e9..ef976b59 100644 --- a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt +++ b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt @@ -58,8 +58,9 @@ import com.pulseloop.data.entity.* AccuracyCorrectionEntity::class, LabReportEntity::class, LabResultEntity::class, + ComparisonReadingEntity::class, ], - version = 37, + version = 38, exportSchema = false, ) abstract class PulseLoopDatabase : RoomDatabase() { @@ -109,6 +110,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { abstract fun journalDao(): JournalDao /** Lab reports the user added as PDFs, and the markers read from them (v37). */ abstract fun labDao(): LabDao + abstract fun comparisonDao(): ComparisonDao /** * Empty every table, atomically. Goes through Room's [withTransaction] rather than a raw @@ -716,6 +718,18 @@ abstract class PulseLoopDatabase : RoomDatabase() { } } + /** The comparison ring's readings (docs/ring-comparison.md). */ + private val MIGRATION_37_38 = object : Migration(37, 38) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `comparison_readings` (`id` TEXT NOT NULL, `deviceAddress` TEXT NOT NULL, " + + "`kind` TEXT NOT NULL, `value` REAL NOT NULL, `timestamp` INTEGER NOT NULL, `source` TEXT NOT NULL, " + + "PRIMARY KEY(`id`))" + ) + db.execSQL("CREATE INDEX IF NOT EXISTS `index_comparison_readings_deviceAddress_kind_timestamp` ON `comparison_readings` (`deviceAddress`, `kind`, `timestamp`)") + } + } + private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) { db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`") db.execSQL( @@ -819,6 +833,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { MIGRATION_34_35, MIGRATION_35_36, MIGRATION_36_37, + MIGRATION_37_38, ) // Downgrades only (sideloading an older APK). A blanket destructive // fallback would silently wipe every measurement, sleep session, and diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 1352832c..84a13eb8 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -1197,3 +1197,19 @@ interface LabDao { @Query("DELETE FROM lab_reports WHERE id = :id") suspend fun deleteReport(id: String) } + +/** The comparison ring's readings (docs/ring-comparison.md). Read only by the comparison screen. */ +@Dao +interface ComparisonDao { + @Upsert + suspend fun upsert(rows: List) + + @Query("SELECT * FROM comparison_readings WHERE deviceAddress = :address AND kind = :kind AND timestamp BETWEEN :start AND :end ORDER BY timestamp") + suspend fun range(address: String, kind: String, start: Long, end: Long): List + + @Query("SELECT * FROM comparison_readings WHERE deviceAddress = :address AND timestamp BETWEEN :start AND :end ORDER BY timestamp") + fun rangeFlow(address: String, start: Long, end: Long): Flow> + + @Query("DELETE FROM comparison_readings WHERE deviceAddress = :address") + suspend fun clear(address: String) +} diff --git a/app/src/main/java/com/pulseloop/data/entity/ComparisonEntities.kt b/app/src/main/java/com/pulseloop/data/entity/ComparisonEntities.kt new file mode 100644 index 00000000..cefc8333 --- /dev/null +++ b/app/src/main/java/com/pulseloop/data/entity/ComparisonEntities.kt @@ -0,0 +1,28 @@ +package com.pulseloop.data.entity + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +/** + * One reading from the ring connected only for comparison (docs/ring-comparison.md). Kept apart + * from `measurements` on purpose: nothing here feeds a score, a chart outside the comparison + * screen, Health Connect, Strava or the backup. The id is `:` within one ring, so + * a history re-sync updates a row instead of adding one. + * + * [kind] is a `MeasurementKind` name, or `STEPS` (one activity bucket's steps) or `SLEEP` (one + * minute, with the `SleepStage` ordinal as the value). + */ +@Entity( + tableName = "comparison_readings", + indices = [Index(value = ["deviceAddress", "kind", "timestamp"])], +) +data class ComparisonReadingEntity( + @PrimaryKey val id: String, + val deviceAddress: String, + val kind: String, + val value: Double, + val timestamp: Long, + /** "live" for a streamed sample, "history" for one the ring logged. */ + val source: String, +) diff --git a/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt b/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt index 1b73a1d6..fa779b4e 100644 --- a/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt +++ b/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt @@ -714,7 +714,7 @@ class ColmiSyncEngine( // degrades for Colmi rings: the coach check-in skip gate and done-wait (#61c), the // >12h staleness warning, the morning sleep-sync gate (#65f), the summary // coordinator's sync recheck, and the post-workout vitals reconcile (#57e). - PulseEventBus.publishBlocking(PulseEvent.SyncProgress("done")) + writer?.publish(PulseEvent.SyncProgress("done")) ?: PulseEventBus.publishBlocking(PulseEvent.SyncProgress("done")) } // MARK: Measurement actions diff --git a/app/src/main/java/com/pulseloop/ring/ComparisonBus.kt b/app/src/main/java/com/pulseloop/ring/ComparisonBus.kt new file mode 100644 index 00000000..40f79b32 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ring/ComparisonBus.kt @@ -0,0 +1,33 @@ +package com.pulseloop.ring + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.launch + +/** + * The event stream of the ring connected only for comparison (`RingRole.COMPARISON`). It is a + * separate bus on purpose: everything listening to [PulseEventBus] (persistence, the accuracy + * watcher, the device row, Health Connect, the sync coordinator) belongs to the app's own ring, + * and a second ring's readings must never reach any of it. Only `ComparisonRing` listens here. + */ +object ComparisonBus { + private val _events = MutableSharedFlow(replay = 0, extraBufferCapacity = 256) + val events: SharedFlow = _events.asSharedFlow() + private val pending = Channel(capacity = Channel.UNLIMITED) + + init { + CoroutineScope(SupervisorJob() + Dispatchers.Default).launch { + for (event in pending) runCatching { _events.emit(event) } + } + } + + fun publish(event: PulseEvent) { pending.trySend(event) } +} + +/** Which job a [RingBLEClient] does: the app's ring, or a second one connected only to compare. */ +enum class RingRole { PRIMARY, COMPARISON } diff --git a/app/src/main/java/com/pulseloop/ring/JringDriver.kt b/app/src/main/java/com/pulseloop/ring/JringDriver.kt index daedc6ca..9f543457 100644 --- a/app/src/main/java/com/pulseloop/ring/JringDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/JringDriver.kt @@ -256,7 +256,8 @@ class JringSyncEngine( } private fun log(message: String) { - PulseEventBus.publishBlocking(PulseEvent.Diagnostic(message, RingDeviceType.JRING)) + val event = PulseEvent.Diagnostic(message, RingDeviceType.JRING) + writer?.publish(event) ?: PulseEventBus.publishBlocking(event) } override fun stopWorkoutHeartRate() { diff --git a/app/src/main/java/com/pulseloop/ring/LuckRingHistorySync.kt b/app/src/main/java/com/pulseloop/ring/LuckRingHistorySync.kt index 47c2f887..ceeebc62 100644 --- a/app/src/main/java/com/pulseloop/ring/LuckRingHistorySync.kt +++ b/app/src/main/java/com/pulseloop/ring/LuckRingHistorySync.kt @@ -69,7 +69,7 @@ class LuckRingHistorySync( val isRunning: Boolean get() = currentType != null private fun publish(event: PulseEvent) { - if (progressSink != null) progressSink.invoke(event) else PulseEventBus.publishBlocking(event) + if (progressSink != null) progressSink.invoke(event) else writer?.publish(event) ?: PulseEventBus.publishBlocking(event) } /** Seed the queue and request the first type. A pass already in flight wins -- a re-entrant diff --git a/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt b/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt index f04e95e9..1f3e981b 100644 --- a/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt +++ b/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt @@ -35,6 +35,10 @@ import java.util.UUID class RingBLEClient( private val context: Context, private val transientOwner: Boolean = false, + /** [RingRole.COMPARISON]: a second ring connected only to compare with the app's own. It has + * its own connection slot and saved ring, and publishes to [ComparisonBus] instead of + * [PulseEventBus], so its readings never reach the app's data (docs/ring-comparison.md). */ + val role: RingRole = RingRole.PRIMARY, ) { /** Registry of supported wearables. Adding a wearable = append one entry. @@ -197,7 +201,8 @@ class RingBLEClient( private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) private val prefs: SharedPreferences = - context.getSharedPreferences("ring_ble", Context.MODE_PRIVATE) + // Its own file per role, so the comparison ring never overwrites the app's saved ring. + context.getSharedPreferences(if (role == RingRole.COMPARISON) "ring_ble_compare" else "ring_ble", Context.MODE_PRIVATE) // MARK: Liveness watchdog // @@ -243,7 +248,7 @@ class RingBLEClient( onPending = { recordDiagnostic("CRP reconnect scheduled in 3000ms") updateState { copy(connectionState = RingConnectionState.RECONNECTING) } - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged(RingConnectionState.RECONNECTING, lastKnownIdentifier) ) }, @@ -647,7 +652,7 @@ class RingBLEClient( releaseConnectionOwnership() connectingStartedAt = 0 updateState { copy(connectionState = RingConnectionState.FAILED, lastError = reason) } - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged(RingConnectionState.DISCONNECTED, null) ) scheduleCrpRecovery() @@ -726,7 +731,7 @@ class RingBLEClient( } updateState { copy(connectionState = RingConnectionState.DISCONNECTED) } if (shouldPublishDisconnect) { - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged(RingConnectionState.DISCONNECTED, null) ) } @@ -821,7 +826,7 @@ class RingBLEClient( val waitState = if (userInitiated) RingConnectionState.CONNECTING else RingConnectionState.RECONNECTING updateState { copy(connectionState = waitState) } - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged(waitState, target.address) ) teardownWaitAddress = target.address @@ -951,7 +956,7 @@ class RingBLEClient( activeCapabilities = emptySet(), ) } - PulseEventBus.publishBlocking(PulseEvent.DeviceForgotten) + publish(PulseEvent.DeviceForgotten) } finally { synchronized(forgetLock) { if (forgetCompletion === completion) forgetCompletion = null @@ -1007,6 +1012,20 @@ class RingBLEClient( val hasLastKnownRing: Boolean get() = lastKnownIdentifier != null + /** The saved ring's address, or null. The comparison screen uses it to tell the two apart. */ + val lastKnownAddress: String? get() = lastKnownIdentifier + + /** Forgets the saved ring without unbinding it, so the ring stays usable by the app that owns + * it. Used to stop comparing: [forget] would send the vendor's unbind. */ + fun clearSavedRing() { + prefs.edit() + .remove(LAST_PERIPHERAL_KEY) + .remove(LAST_DEVICE_TYPE_KEY) + .remove(LAST_WEARABLE_MODEL_KEY) + .remove(USER_DISCONNECTED_KEY) + .apply() + } + private val lastKnownIdentifier: String? get() = prefs.getString(LAST_PERIPHERAL_KEY, null) private val lastKnownDeviceType: RingDeviceType? @@ -1099,7 +1118,7 @@ class RingBLEClient( updateState { copy(connectionState = RingConnectionState.CONNECTING) } // Mirror the attempt to the persisted state so the Today/Settings views show // "Connecting…" rather than a stale "Connected" while autoConnect is pending. - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged(RingConnectionState.CONNECTING, target.address) ) @@ -1229,7 +1248,10 @@ class RingBLEClient( forgetPending = false forgetFinalizing = false } - val driver = coordinator.makeDriver { enqueueWrite(it) } + val driver = coordinator.makeDriver(object : RingCommandWriter { + override fun enqueue(command: ByteArray) = enqueueWrite(command) + override fun publish(event: PulseEvent) = this@RingBLEClient.publish(event) + }) activeCoordinator = coordinator activeDriver = driver driver.connectionDidStart() @@ -1261,7 +1283,7 @@ class RingBLEClient( val granted = reported.intersect(coordinator.bitmapGatedCapabilities) if (granted.isEmpty() || granted.all { it in _state.value.activeCapabilities }) return updateState { copy(activeCapabilities = activeCapabilities + granted) } - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceIdentified( deviceType = coordinator.deviceType, wearableModelID = _state.value.activeWearableModelID, @@ -1392,7 +1414,7 @@ class RingBLEClient( // asks for transport detail gets every attempt; capture retention bounds it. val verbose = activeDriver?.verboseTransportDiagnostics == true if (op.attempts == 0 || verbose) { - PulseEventBus.publishBlocking( + publish( PulseEvent.RawPacket(PacketDirection.OUTGOING, op.data, RingDecodedEvent.CommandAck(commandId = if (op.data.isNotEmpty()) op.data[0].toUByte() else 0u), deviceType = activeCoordinator?.deviceType, @@ -1537,7 +1559,7 @@ class RingBLEClient( ) { // `generation` is the forget generation: it separates one pairing's traffic from the next, // not one reconnect from another. - PulseEventBus.publishBlocking(PulseEvent.Diagnostic( + publish(PulseEvent.Diagnostic( "generation=$forgetGeneration $message", activeCoordinator?.deviceType, error, traffic, )) Log.i("RingBLEClient", message) @@ -1557,7 +1579,7 @@ class RingBLEClient( */ private fun captureAuxiliary(uuid: String, bytes: ByteArray) { val copy = bytes.copyOf() - PulseEventBus.publishBlocking(PulseEvent.RawPacket(PacketDirection.INCOMING, copy, + publish(PulseEvent.RawPacket(PacketDirection.INCOMING, copy, RingDecodedEvent.FramePending(copy, startsFrame = false), activeCoordinator?.deviceType, transportJSON = packetMetadata(uuid))) } @@ -1927,7 +1949,7 @@ class RingBLEClient( if (value != null && value.isNotEmpty()) { val pct = value[0].toInt() and 0xFF updateState { copy(batteryPercent = pct) } - PulseEventBus.publishBlocking(PulseEvent.BatteryLevel(pct)) + publish(PulseEvent.BatteryLevel(pct)) } } else if (characteristic.uuid == FW_REV_UUID || characteristic.uuid.toString().startsWith("00002a26") || @@ -1978,7 +2000,7 @@ class RingBLEClient( val systolic = decodeSFLOAT(value[1], value[2]) val diastolic = decodeSFLOAT(value[3], value[4]) if (acceptsCallback(callbackForgetGeneration)) { - PulseEventBus.publishBlocking( + publish( PulseEvent.BloodPressureSample( systolic = systolic.toInt(), diastolic = diastolic.toInt(), @@ -1994,7 +2016,7 @@ class RingBLEClient( if (value.size >= 12) { val glucoseKgL = decodeSFLOAT(value[10], value[11]) if (acceptsCallback(callbackForgetGeneration)) { - PulseEventBus.publishBlocking(PulseEvent.HistoryMeasurement(MeasurementKind.BLOOD_SUGAR, glucoseKgL * 100000.0, java.time.Instant.now())) + publish(PulseEvent.HistoryMeasurement(MeasurementKind.BLOOD_SUGAR, glucoseKgL * 100000.0, java.time.Instant.now())) } } return @@ -2020,7 +2042,7 @@ class RingBLEClient( commandId = captured.firstOrNull()?.toUByte() ?: 0u, raw = captured, ) - PulseEventBus.publishBlocking( + publish( PulseEvent.RawPacket(PacketDirection.INCOMING, captured, diagnostic, deviceType = activeCoordinator?.deviceType, capturedAt = capturedAt, transportJSON = packetMetadata(uuid)) @@ -2037,7 +2059,7 @@ class RingBLEClient( } for (event in RingEventBridge.eventsFor(decoded)) { if (!acceptsCallback(callbackForgetGeneration)) break - PulseEventBus.publishBlocking(event) + publish(event) } if (acceptsCallback(callbackForgetGeneration)) activeSyncEngine?.handle(decoded) } @@ -2119,7 +2141,7 @@ class RingBLEClient( else editor.remove(LAST_WEARABLE_MODEL_KEY) editor.apply() - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged( RingConnectionState.CONNECTED, device.address, @@ -2128,7 +2150,7 @@ class RingBLEClient( ) ) activeCoordinator?.let { coord -> - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceIdentified( deviceType = coord.deviceType, wearableModelID = modelID, @@ -2202,7 +2224,7 @@ class RingBLEClient( closeGattQuietly(gatt) releaseConnectionOwnership() - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged(RingConnectionState.DISCONNECTED, null) ) @@ -2254,7 +2276,7 @@ class RingBLEClient( if (shown == RingConnectionState.RECONNECTING || (pairingWait && shown == RingConnectionState.CONNECTING)) { updateState { copy(connectionState = RingConnectionState.DISCONNECTED) } - PulseEventBus.publishBlocking( + publish( PulseEvent.DeviceStateChanged(RingConnectionState.DISCONNECTED, null) ) } @@ -2286,13 +2308,27 @@ class RingBLEClient( return releasedConnection } + /** The app's ring and the comparison ring each have their own slot: a ring has one command + * stream, but two different rings are two streams. */ + private val ownerSlot get() = if (role == RingRole.COMPARISON) comparisonConnectionOwner else processConnectionOwner + private fun claimConnectionOwnership(): Boolean { - val owner = processConnectionOwner.get() - return owner === this || (owner == null && processConnectionOwner.compareAndSet(null, this)) + val owner = ownerSlot.get() + return owner === this || (owner == null && ownerSlot.compareAndSet(null, this)) } private fun releaseConnectionOwnership(): Boolean = - processConnectionOwner.compareAndSet(this, null) + ownerSlot.compareAndSet(this, null) + + /** Routes this client's events: the app's ring to [PulseEventBus]; the comparison ring to + * [ComparisonBus], except its diagnostics, which go to the app's log marked as the second ring. */ + private fun publish(event: PulseEvent) { + if (role == RingRole.PRIMARY) { PulseEventBus.publishBlocking(event); return } + when (event) { + is PulseEvent.Diagnostic -> PulseEventBus.publishBlocking(event.copy(message = "[comparison ring] " + event.message)) + else -> ComparisonBus.publish(event) + } + } companion object { private const val LAST_PERIPHERAL_KEY = "ring.lastPeripheralIdentifier" @@ -2304,6 +2340,8 @@ class RingBLEClient( /** A ring has one command stream; never let this process open competing GATT clients. */ private val processConnectionOwner = java.util.concurrent.atomic.AtomicReference(null) + private val comparisonConnectionOwner = + java.util.concurrent.atomic.AtomicReference(null) /** Foreground retry delay while a short-lived background client yields ownership. */ private const val PROCESS_OWNER_RETRY_MS = 1_000L /** How often the liveness watchdog runs. */ diff --git a/app/src/main/java/com/pulseloop/ring/WearableDriver.kt b/app/src/main/java/com/pulseloop/ring/WearableDriver.kt index f56cf0f8..fe8433bd 100644 --- a/app/src/main/java/com/pulseloop/ring/WearableDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/WearableDriver.kt @@ -6,6 +6,11 @@ package com.pulseloop.ring */ fun interface RingCommandWriter { fun enqueue(command: ByteArray) + + /** Where this connection's own events go. The app's ring publishes to [PulseEventBus]; a + * ring connected only for comparison overrides this, so nothing a driver publishes on its own + * (history progress, out-of-band readings) can reach the app's data. */ + fun publish(event: PulseEvent) { PulseEventBus.publishBlocking(event) } } enum class SubscriptionMode { NOTIFICATION, INDICATION } diff --git a/app/src/main/java/com/pulseloop/ring/YCBTDriver.kt b/app/src/main/java/com/pulseloop/ring/YCBTDriver.kt index 91dda648..8b441cbd 100644 --- a/app/src/main/java/com/pulseloop/ring/YCBTDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/YCBTDriver.kt @@ -159,7 +159,7 @@ class YCBTDriver( for (event in events.filter(::isSupported)) { syncEngine?.handle(event) for (pulseEvent in RingEventBridge.eventsFor(event)) { - PulseEventBus.publishBlocking(pulseEvent) + writer.publish(pulseEvent) } } } diff --git a/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt b/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt index ead919f4..8bade867 100644 --- a/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt +++ b/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt @@ -15,7 +15,7 @@ class YCBTHistoryTransfer( private val onOutOfBandEvents: (List) -> Unit = { events -> for (event in events) { for (pulseEvent in RingEventBridge.eventsFor(event)) { - PulseEventBus.publishBlocking(pulseEvent) + writer?.publish(pulseEvent) ?: PulseEventBus.publishBlocking(pulseEvent) } } }, diff --git a/app/src/main/java/com/pulseloop/service/ComparisonRing.kt b/app/src/main/java/com/pulseloop/service/ComparisonRing.kt new file mode 100644 index 00000000..098d90dc --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/ComparisonRing.kt @@ -0,0 +1,127 @@ +package com.pulseloop.service + +import android.content.Context +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.ComparisonReadingEntity +import com.pulseloop.ring.ComparisonBus +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.ring.PulseEvent +import com.pulseloop.ring.RingBLEClient +import com.pulseloop.ring.RingConnectionState +import com.pulseloop.ring.RingRole +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +/** + * A second ring worn alongside the app's own, connected only to compare the two + * (docs/ring-comparison.md). It runs its own [RingBLEClient] in [RingRole.COMPARISON]: its own + * connection slot and saved ring, and its events on [ComparisonBus], which only this class reads. + * Its readings go to `comparison_readings` and nowhere else: no score, no Health Connect, no + * Strava, no backup, no device row. + * + * On each connect it runs the ring's normal startup (time, settings, history), so its log for the + * day arrives like the app ring's does. During a recorded workout it streams heart rate too, so a + * workout can be compared ring against ring. + */ +class ComparisonRing(context: Context, private val db: PulseLoopDatabase) { + val client = RingBLEClient(context.applicationContext, role = RingRole.COMPARISON) + val state get() = client.state + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private var started = false + /** The recording workout's type while one runs, so a reconnect restarts its stream. */ + @Volatile private var workoutType: String? = null + + val address: String? get() = client.lastKnownAddress + val isSetUp: Boolean get() = client.hasLastKnownRing + + fun start() { + if (started) return + started = true + client.onConnected = { + val engine = client.syncEngine + engine?.runStartup() + workoutType?.let { engine?.startWorkoutHeartRate(it) } + } + scope.launch { ComparisonBus.events.collect { persist(it) } } + if (client.hasLastKnownRing) client.connectLastKnown() + } + + fun startScanning() = client.startScanning() + fun stopScanning() = client.stopScanning() + + fun pair(id: String) { + client.stopScanning() + client.connectTo(id) + } + + /** Stops comparing: disconnects and forgets the saved ring without unbinding it, so the ring + * is still the vendor app's (or the app's, after a swap). The readings already kept stay + * until [clearReadings]. */ + fun stopComparing() { + workoutType = null + client.userDisconnect() + client.clearSavedRing() + } + + suspend fun clearReadings(address: String) = db.comparisonDao().clear(address) + + fun startWorkout(activityType: String) { + workoutType = activityType + if (client.state.value.connectionState == RingConnectionState.CONNECTED) { + client.syncEngine?.startWorkoutHeartRate(activityType) + } + } + + fun stopWorkout() { + if (workoutType == null) return + workoutType = null + if (client.state.value.connectionState == RingConnectionState.CONNECTED) { + client.syncEngine?.stopWorkoutHeartRate() + } + } + + private suspend fun persist(event: PulseEvent) { + val addr = address ?: return + val rows = ComparisonReadings.rowsFor(addr, event) + if (rows.isNotEmpty()) runCatching { db.comparisonDao().upsert(rows) } + } +} + +/** Which comparison rows an event becomes. Pure, so it is tested (`ComparisonReadingsTest`). */ +object ComparisonReadings { + fun rowsFor(address: String, event: PulseEvent): List { + fun row(kind: String, value: Double, ts: Long, source: String) = + ComparisonReadingEntity("$address:$kind:$ts", address, kind, value, ts, source) + return when (event) { + is PulseEvent.HeartRateSample -> if (event.bpm > 0 && !event.spot) + listOf(row(MeasurementKind.HEART_RATE.name, event.bpm.toDouble(), event.timestamp.toEpochMilli(), "live")) else emptyList() + is PulseEvent.HistoryMeasurement -> if (event.value > 0) + listOf(row(event.kind.name, event.value, event.timestamp.toEpochMilli(), "history")) else emptyList() + is PulseEvent.Spo2Result -> if (event.value in 70..100) + listOf(row(MeasurementKind.SPO2.name, event.value.toDouble(), event.timestamp.toEpochMilli(), "live")) else emptyList() + is PulseEvent.HrvSample -> if (event.value > 0) + listOf(row(MeasurementKind.HRV.name, event.value.toDouble(), event.timestamp.toEpochMilli(), "live")) else emptyList() + is PulseEvent.ActivityBucket -> if (event.steps > 0) + listOf(row(STEPS, event.steps.toDouble(), event.timestamp.toEpochMilli(), "history")) else emptyList() + is PulseEvent.ActivityUpdate -> { + // The ring's running total for its day, kept once per local day (the latest wins). + val day = com.pulseloop.util.TimeUtil.startOfDayLocal(event.timestamp.toEpochMilli()) + listOf(row(STEPS_TOTAL, event.steps.toDouble(), day, "live")) + } + is PulseEvent.SleepTimeline -> { + val start = event.timestamp.toEpochMilli() + event.stages.mapIndexed { i, stage -> row(SLEEP, stage.ordinal.toDouble(), start + i * 60_000L, "history") } + } + else -> emptyList() + } + } + + /** One activity bucket's steps. */ + const val STEPS = "STEPS" + /** The ring's own running step total for a local day, stamped at the day's start. */ + const val STEPS_TOTAL = "STEPS_TOTAL" + /** One minute of sleep; the value is the `SleepStage` ordinal. */ + const val SLEEP = "SLEEP" +} diff --git a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt index 461cf267..ecf5a1f5 100644 --- a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt +++ b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt @@ -22,6 +22,8 @@ class LiveWorkoutManager( private val db: PulseLoopDatabase, val gps: GpsRouteRecorder, private val context: Context, + /** The second ring, if one is set up to compare: it streams heart rate during a workout too. */ + private val comparison: ComparisonRing? = null, ) { data class WorkoutState( val isRecording: Boolean = false, @@ -89,6 +91,7 @@ class LiveWorkoutManager( db.activitySessionDao().upsert(session) coordinator.startWorkoutHeartRate(type) + comparison?.startWorkout(type) if (useGps) gps.start(session.id, type) polling.start(session.id) startForegroundService(session.type) @@ -196,6 +199,7 @@ class LiveWorkoutManager( db.activitySessionDao().upsert(summarized) runCatching { ActivityRollup.credit(db, summarized) } coordinator.stopWorkoutHeartRate() + comparison?.stopWorkout() finishForegroundService(summarized) _state.value = WorkoutState(finishedSessionId = summarized.id) uploadToStravaIfConnected() @@ -228,6 +232,7 @@ class LiveWorkoutManager( statusRaw = "cancelled", endedAt = System.currentTimeMillis(), updatedAt = System.currentTimeMillis() )) coordinator.stopWorkoutHeartRate() + comparison?.stopWorkout() _state.value = WorkoutState() } diff --git a/app/src/main/java/com/pulseloop/service/RingComparison.kt b/app/src/main/java/com/pulseloop/service/RingComparison.kt new file mode 100644 index 00000000..579899a8 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/RingComparison.kt @@ -0,0 +1,72 @@ +package com.pulseloop.service + +import kotlin.math.abs + +/** + * How two rings worn together compare (docs/ring-comparison.md). Pure, so it is unit-tested + * (`RingComparisonTest`). There is no ground truth here: two rings can agree and both be wrong, + * which is why the screen says so and points at the accuracy check for a watch. + */ +object RingComparison { + data class Reading(val atMs: Long, val value: Double) + + data class Coverage(val slotsWithReadings: Int, val slots: Int) { + val fraction: Double get() = if (slots == 0) 0.0 else slotsWithReadings.toDouble() / slots + } + + data class Agreement( + /** Readings from the second ring that had one from the first within the tolerance. */ + val pairs: Int, + /** Median of |second − first|, the typical gap. */ + val medianAbsDiff: Double?, + /** Mean of (second − first): positive when the second ring reads higher. */ + val meanDiff: Double?, + ) + + /** + * How much of [start, end) has at least one reading, in slots of [slotMs]. Slots, not each + * reading's time: a ring that logs every five minutes and one that streams every second both + * "cover" a five-minute slot, which is the honest comparison for an all-day log. + */ + fun coverage(readings: List, start: Long, end: Long, slotMs: Long): Coverage { + if (end <= start || slotMs <= 0) return Coverage(0, 0) + val slots = ((end - start + slotMs - 1) / slotMs).toInt() + val filled = readings.asSequence() + .filter { it.atMs in start until end } + .map { ((it.atMs - start) / slotMs).toInt() } + .toSet().size + return Coverage(filled, slots) + } + + /** Pairs each second-ring reading with the first ring's nearest one within [toleranceMs]. */ + fun agreement(first: List, second: List, toleranceMs: Long): Agreement { + val sorted = first.sortedBy { it.atMs } + if (sorted.isEmpty() || second.isEmpty()) return Agreement(0, null, null) + val times = sorted.map { it.atMs }.toLongArray() + val diffs = second.mapNotNull { r -> + var i = times.binarySearch(r.atMs).let { if (it < 0) -it - 1 else it } + val candidates = listOfNotNull(sorted.getOrNull(i - 1), sorted.getOrNull(i)) + val nearest = candidates.minByOrNull { abs(it.atMs - r.atMs) } ?: return@mapNotNull null + if (abs(nearest.atMs - r.atMs) <= toleranceMs) r.value - nearest.value else null + } + if (diffs.isEmpty()) return Agreement(0, null, null) + val absSorted = diffs.map { abs(it) }.sorted() + val median = if (absSorted.size % 2 == 1) absSorted[absSorted.size / 2] + else (absSorted[absSorted.size / 2 - 1] + absSorted[absSorted.size / 2]) / 2 + return Agreement(diffs.size, median, diffs.average()) + } + + /** Heart rate averaged by time over [start, end), like a workout's (WorkoutHeart): a ring that + * streamed for an hour must not outvote one that logged all day. Null when there are none. */ + fun averageHeartRate(readings: List, start: Long, end: Long): Double? { + val w = WorkoutHeart.weighted( + readings.filter { it.atMs in start until end }.map { WorkoutHeart.Sample(it.atMs, it.value) }, end, + ) + val minutes = w.sumOf { it.minutes } + return when { + w.isEmpty() -> null + minutes <= 0.0 -> w.map { it.bpm }.average() + else -> w.sumOf { it.bpm * it.minutes } / minutes + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index 3a63ff4b..38e65512 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -223,6 +223,7 @@ fun PulseLoopApp() { persistence.start() batteryAlerts.start() coordinator.start() + services.comparison.start() summaryCoordinator.start() checkinDataTrigger.start() @@ -828,6 +829,12 @@ fun PulseLoopApp() { paddedComposable("settings/accuracy-check") { AccuracyCheckSettingsScreen(onBack = { navController.popBackStack() }) } + paddedComposable("settings/compare") { + RingComparisonScreen( + onBack = { navController.popBackStack() }, + onOpenAccuracyCheck = { navController.navigate("settings/accuracy-check") }, + ) + } paddedComposable("settings/mcp") { McpSettingsScreen(onBack = { navController.popBackStack() }) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/RingComparisonScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/RingComparisonScreen.kt new file mode 100644 index 00000000..b4837288 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/RingComparisonScreen.kt @@ -0,0 +1,433 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +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.platform.LocalContext +import androidx.compose.ui.semantics.Role +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.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.AppServices +import com.pulseloop.data.entity.ActivitySessionEntity +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.ring.RingConnectionState +import com.pulseloop.ring.SleepStage +import com.pulseloop.service.ComparisonReadings +import com.pulseloop.service.RingComparison +import com.pulseloop.service.RingComparison.Reading +import com.pulseloop.service.WorkoutHeart +import com.pulseloop.ui.calm.Look +import com.pulseloop.ui.calm.LookLabel +import com.pulseloop.ui.calm.lookCard +import com.pulseloop.ui.components.ActivityMeta +import com.pulseloop.ui.components.PulseButton +import com.pulseloop.ui.components.PulseButtonStyle +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import com.pulseloop.ui.theme.PulseColors +import com.pulseloop.util.TimeUtil +import kotlinx.coroutines.launch +import kotlin.math.abs +import kotlin.math.roundToInt + +/** + * Compare rings (docs/ring-comparison.md): a second ring worn alongside the app's own, side by + * side, day by day. The second ring's readings live in `comparison_readings` and are shown only + * here; the app's ring keeps feeding everything else. + */ +@Composable +fun RingComparisonScreen(onBack: () -> Unit, onOpenAccuracyCheck: () -> Unit) { + val context = LocalContext.current + val services = remember { AppServices.get(context) } + val comparison = services.comparison + val second by comparison.state.collectAsState() + val main by services.bleClient.state.collectAsState() + var setUp by remember { mutableStateOf(comparison.isSetUp) } + // Refresh when the second ring connects (setUp turns true on the first connect). + LaunchedEffect(second.connectionState) { setUp = comparison.isSetUp } + + SettingsSubScreen(title = tr("Compare rings"), onBack = onBack) { + if (!setUp) { + FindSecondRing(mainAddress = services.bleClient.lastKnownAddress) + } else { + RingsCard(main, second, onStop = { + comparison.stopComparing() + setUp = false + }) + ComparisonDays(comparison.address ?: return@SettingsSubScreen, onOpenAccuracyCheck) + } + } +} + +/** The empty state and the scan list: one sentence of why, one action, then the rings found. */ +@Composable +private fun FindSecondRing(mainAddress: String?) { + val context = LocalContext.current + val comparison = remember { AppServices.get(context).comparison } + val st by comparison.state.collectAsState() + var scanning by rememberSaveable { mutableStateOf(false) } + DisposableEffect(Unit) { onDispose { if (scanning) comparison.stopScanning() } } + + Column(Modifier.fillMaxWidth().lookCard().padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(tr("Wear a second ring to see how the two compare"), style = Look.titleStyle, color = Look.text) + Text( + tr("Its readings stay apart: they never change your scores, and nothing from it goes to Health Connect or Strava. Your main ring keeps working as it does now."), + style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary, + ) + if (!scanning) { + PulseButton(PulseButtonStyle.Tonal, onClick = { scanning = true; comparison.startScanning() }, modifier = Modifier.fillMaxWidth()) { + Text(tr("Find a ring")) + } + } + } + if (scanning) { + val found = st.discovered.filter { it.id != mainAddress } + LookLabel(tr("Rings nearby")) + Column(Modifier.fillMaxWidth().lookCard()) { + if (found.isEmpty()) { + Text( + tr("Looking… keep the second ring close to the phone, and closed in the vendor's app."), + style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary, + modifier = Modifier.padding(16.dp), + ) + } + found.forEachIndexed { i, ring -> + Row( + Modifier.fillMaxWidth().heightIn(min = 56.dp) + .clickable(role = Role.Button) { scanning = false; comparison.pair(ring.id) } + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(ring.name, style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp), color = Look.text) + Text(ring.id, style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textMuted) + } + Text(tr("Compare"), style = MaterialTheme.typography.labelLarge.copy(fontSize = 14.sp, fontWeight = FontWeight.SemiBold), color = PulseColors.accent) + } + if (i < found.lastIndex) HorizontalDivider(color = Look.border) + } + } + } +} + +/** The two rings, which colour and line each one is drawn in, and the way out. */ +@Composable +internal fun RingsCard( + main: com.pulseloop.ring.RingBLEClient.BLEState, + second: com.pulseloop.ring.RingBLEClient.BLEState, + onStop: () -> Unit, +) { + var confirm by remember { mutableStateOf(false) } + Column(Modifier.fillMaxWidth().lookCard()) { + RingRow(tr("Main ring"), main, MAIN_COLOR, dashed = false) + HorizontalDivider(color = Look.border) + RingRow(tr("Comparison ring"), second, SECOND_COLOR, dashed = true) + HorizontalDivider(color = Look.border) + Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), horizontalArrangement = Arrangement.End) { + PulseButton(PulseButtonStyle.Text, onClick = { confirm = true }) { + Text(tr("Stop comparing"), color = Look.textSecondary) + } + } + } + if (confirm) { + AlertDialog( + onDismissRequest = { confirm = false }, + title = { Text(tr("Stop comparing?")) }, + text = { Text(tr("The comparison ring disconnects and is forgotten here. It isn't unpaired from its own app, and your main ring isn't affected.")) }, + confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { confirm = false; onStop() }) { Text(tr("Stop comparing")) } }, + dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = { confirm = false }) { Text(tr("Cancel")) } }, + ) + } +} + +@Composable +private fun RingRow(role: String, st: com.pulseloop.ring.RingBLEClient.BLEState, color: Color, dashed: Boolean) { + val name = com.pulseloop.wearables.WearableModel.model(st.activeWearableModelID)?.displayName + ?: st.activeDeviceType?.displayName ?: "—" + val status = when (st.connectionState) { + RingConnectionState.CONNECTED -> tr("Connected") + RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING, RingConnectionState.SCANNING -> tr("Connecting") + else -> tr("Not connected") + } + Row( + Modifier.fillMaxWidth().heightIn(min = 64.dp).padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + LineSwatch(color, dashed) + Column(Modifier.weight(1f)) { + Text(role, style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textSecondary) + Text(name, style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp, fontWeight = FontWeight.SemiBold), color = Look.text, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Column(horizontalAlignment = Alignment.End) { + Text(status, style = MaterialTheme.typography.bodySmall.copy(fontSize = 14.sp), color = if (st.connectionState == RingConnectionState.CONNECTED) PulseColors.success else Look.textSecondary) + st.batteryPercent?.let { Text("$it%", style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textMuted) } + } + } +} + +/** A short line in the ring's colour, dashed for the comparison ring: colour is never the only cue. */ +@Composable +private fun LineSwatch(color: Color, dashed: Boolean) { + Canvas(Modifier.width(24.dp).height(12.dp)) { + drawLine( + color, Offset(0f, size.height / 2), Offset(size.width, size.height / 2), 3.dp.toPx(), + cap = StrokeCap.Round, + pathEffect = if (dashed) PathEffect.dashPathEffect(floatArrayOf(6f, 6f)) else null, + ) + } +} + +private val MAIN_COLOR get() = PulseColors.heartRate +private val SECOND_COLOR get() = PulseColors.info + +/** Everything both rings recorded on one local day. */ +internal class DayData( + val dayStart: Long, + val mainHr: List, + val secondHr: List, + val mainSteps: Int?, + val secondSteps: Int?, + val mainSleep: Int?, + val secondSleep: Int?, + val workouts: List, +) + +@Composable +private fun ComparisonDays(address: String, onOpenAccuracyCheck: () -> Unit) { + val context = LocalContext.current + val db = remember { AppServices.get(context).db } + var offset by rememberSaveable { mutableIntStateOf(0) } + var data by remember { mutableStateOf(null) } + var reloadTick by remember { mutableIntStateOf(0) } + val scope = rememberCoroutineScope() + + LaunchedEffect(address, offset, reloadTick) { + val dayStart = TimeUtil.startOfTodayLocal() - offset * 86_400_000L + val dayEnd = dayStart + 86_400_000L + val dao = db.comparisonDao() + val mainHr = db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, dayStart, dayEnd) + .filter { it.value > 0 }.map { Reading(it.timestamp, it.value) } + val secondHr = dao.range(address, MeasurementKind.HEART_RATE.name, dayStart, dayEnd).map { Reading(it.timestamp, it.value) } + val mainSteps = db.activityDailyDao().byDay(dayStart)?.takeIf { it.source != "mock" && it.source != "demo" }?.steps + val buckets = dao.range(address, ComparisonReadings.STEPS, dayStart, dayEnd - 1).sumOf { it.value }.toInt() + val total = dao.range(address, ComparisonReadings.STEPS_TOTAL, dayStart, dayStart).maxOfOrNull { it.value }?.toInt() ?: 0 + val secondSteps = maxOf(buckets, total).takeIf { it > 0 } + // Sleep is filed under the waking day, as everywhere in the app. + val mainSleep = db.sleepSessionDao().ringByDay(dayStart)?.totalMinutes?.takeIf { it > 0 } + val sleepRows = dao.range(address, ComparisonReadings.SLEEP, dayStart - 12 * 3_600_000L, dayEnd) + .filter { TimeUtil.wakingDayLocal(it.timestamp) == dayStart } + val secondSleep = sleepRows.count { it.value.toInt() != SleepStage.AWAKE.ordinal }.takeIf { it > 0 } + val workouts = db.activitySessionDao().finishedStartedBetween(dayStart, dayEnd) + data = DayData(dayStart, mainHr, secondHr, mainSteps, secondSteps, mainSleep, secondSleep, workouts) + } + // New readings arrive while the screen is open (a sync, a workout): look again now and then. + LaunchedEffect(Unit) { while (true) { kotlinx.coroutines.delay(30_000); reloadTick++ } } + + DayHeader(offset, onPrev = { offset++ }, onNext = { if (offset > 0) offset-- }) + val d = data ?: return + HeartCard(d) + TotalsCard(d) + if (d.workouts.isNotEmpty()) WorkoutsCard(d) + Text( + tr("Neither ring is known to be right: two rings can agree and both be off. To check one against a watch, use the accuracy check."), + style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = Look.textMuted, + ) + PulseButton(PulseButtonStyle.Text, onClick = onOpenAccuracyCheck) { Text(tr("Open the accuracy check")) } +} + +@Composable +internal fun DayHeader(offset: Int, onPrev: () -> Unit, onNext: () -> Unit) { + val label = when (offset) { + 0 -> tr("Today") + 1 -> tr("Yesterday") + else -> com.pulseloop.ui.components.PhoneFormat.date("EEEMMMd", TimeUtil.startOfTodayLocal() - offset * 86_400_000L) + } + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = onPrev) { Icon(Icons.AutoMirrored.Filled.KeyboardArrowLeft, tr("Previous day"), tint = Look.text) } + Text(label, style = Look.titleStyle, color = Look.text, textAlign = TextAlign.Center, modifier = Modifier.weight(1f)) + IconButton(onClick = onNext, enabled = offset > 0) { + Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, tr("Next day"), tint = if (offset > 0) Look.text else Look.border) + } + } +} + +@Composable +internal fun HeartCard(d: DayData) { + val end = minOf(d.dayStart + 86_400_000L, System.currentTimeMillis()) + val slot = 5 * 60_000L + val mainCov = RingComparison.coverage(d.mainHr, d.dayStart, end, slot) + val secondCov = RingComparison.coverage(d.secondHr, d.dayStart, end, slot) + val agree = RingComparison.agreement(d.mainHr, d.secondHr, 3 * 60_000L) + Column(Modifier.fillMaxWidth().lookCard().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(tr("Heart rate"), style = Look.titleStyle, color = Look.text) + if (d.mainHr.isEmpty() && d.secondHr.isEmpty()) { + Text(tr("No heart rate from either ring on this day."), style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary) + return@Column + } + DualChart(d.mainHr, d.secondHr, d.dayStart, d.dayStart + 86_400_000L) + Row(Modifier.fillMaxWidth()) { + Text("0:00", style = MaterialTheme.typography.labelSmall.copy(fontSize = 12.sp), color = Look.textMuted, modifier = Modifier.weight(1f)) + Text("24:00", style = MaterialTheme.typography.labelSmall.copy(fontSize = 12.sp), color = Look.textMuted) + } + CompareHeader() + CompareRow(tr("Average"), RingComparison.averageHeartRate(d.mainHr, d.dayStart, end)?.let { "${it.roundToInt()}" }, RingComparison.averageHeartRate(d.secondHr, d.dayStart, end)?.let { "${it.roundToInt()}" }, "bpm") + CompareRow(tr("Hours with readings"), hours(mainCov), hours(secondCov), null) + val gap = agree.medianAbsDiff + Text( + if (gap == null) tr("The two rings never measured within 3 minutes of each other, so they can't be compared reading by reading yet.") + else { + val mean = agree.meanDiff ?: 0.0 + val lean = when { + abs(mean) < 1.0 -> tr("neither reads higher on average") + mean > 0 -> trf("the comparison ring reads {0} higher on average", "${mean.roundToInt()}") + else -> trf("the comparison ring reads {0} lower on average", "${(-mean).roundToInt()}") + } + trf("When both measured within 3 minutes ({0} times), they were typically {1} bpm apart, and {2}.", "${agree.pairs}", "${gap.roundToInt()}", lean) + }, + style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.textSecondary, + ) + } +} + +private fun hours(c: RingComparison.Coverage): String? = + if (c.slots == 0) null else "%.1f h".format(c.slotsWithReadings * 5 / 60.0) + +@Composable +internal fun TotalsCard(d: DayData) { + Column(Modifier.fillMaxWidth().lookCard().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + CompareHeader() + CompareRow(tr("Steps"), d.mainSteps?.let { "%,d".format(it) }, d.secondSteps?.let { "%,d".format(it) }, null) + CompareRow(tr("Asleep (night before)"), d.mainSleep?.let { minutesLabel(it) }, d.secondSleep?.let { minutesLabel(it) }, null) + } +} + +private fun minutesLabel(m: Int) = "${m / 60}h ${"%02d".format(m % 60)}" + +@Composable +internal fun WorkoutsCard(d: DayData) { + Column(Modifier.fillMaxWidth().lookCard().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(tr("Workouts"), style = Look.titleStyle, color = Look.text) + CompareHeader() + d.workouts.forEach { w -> + val end = w.endedAt ?: return@forEach + fun avg(r: List) = WorkoutHeart.summary(r.filter { it.atMs in w.startedAt..end }.map { WorkoutHeart.Sample(it.atMs, it.value) }, end, null) + val a = avg(d.mainHr); val b = avg(d.secondHr) + val title = ActivityMeta.label(w.type) + " · " + com.pulseloop.ui.components.PhoneFormat.clock( + android.text.format.DateFormat.is24HourFormat(LocalContext.current), w.startedAt, + ) + Text(title, style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp, fontWeight = FontWeight.SemiBold), color = Look.text, modifier = Modifier.padding(top = 4.dp)) + CompareRow(tr("Average"), a?.average?.let { "${it.roundToInt()}" }, b?.average?.let { "${it.roundToInt()}" }, "bpm") + CompareRow(tr("Highest"), a?.max?.let { "${it.roundToInt()}" }, b?.max?.let { "${it.roundToInt()}" }, "bpm") + val mins = ((end - w.startedAt) / 60_000.0) + CompareRow(tr("Minutes with readings"), + a?.let { "${it.coveredMinutes.roundToInt()}/${mins.roundToInt()}" }, + b?.let { "${it.coveredMinutes.roundToInt()}/${mins.roundToInt()}" }, null) + } + } +} + +/** Column heads: each ring's line, as drawn in the rings card above, so a long ring or column + * name can't truncate here (Portuguese "Comparação" at 1.3× did). TalkBack reads the names. */ +@Composable +private fun CompareHeader() { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.weight(1f)) + Box(Modifier.width(VALUE_W).semantics { contentDescription = tr("Main ring") }, contentAlignment = Alignment.CenterEnd) { LineSwatch(MAIN_COLOR, false) } + Box(Modifier.width(VALUE_W).semantics { contentDescription = tr("Comparison ring") }, contentAlignment = Alignment.CenterEnd) { LineSwatch(SECOND_COLOR, true) } + } +} + +private val VALUE_W = 96.dp + +@Composable +private fun CompareRow(label: String, main: String?, second: String?, unit: String?) { + Row( + Modifier.fillMaxWidth().semantics(mergeDescendants = true) { + contentDescription = "$label: " + tr("main") + " ${main ?: "—"}, " + tr("comparison") + " ${second ?: "—"}" + (unit?.let { " $it" } ?: "") + }, + verticalAlignment = Alignment.CenterVertically, + ) { + Text(label, style = MaterialTheme.typography.bodyMedium.copy(fontSize = 14.sp), color = Look.text, modifier = Modifier.weight(1f)) + Text(main ?: "—", style = MaterialTheme.typography.titleMedium.copy(fontSize = 16.sp, fontWeight = FontWeight.SemiBold), color = Look.text, textAlign = TextAlign.End, modifier = Modifier.width(VALUE_W)) + Text(second ?: "—", style = MaterialTheme.typography.titleMedium.copy(fontSize = 16.sp, fontWeight = FontWeight.SemiBold), color = Look.text, textAlign = TextAlign.End, modifier = Modifier.width(VALUE_W)) + } +} + +/** Both rings' heart rate over the day, in 5-minute means; a gap over 15 minutes breaks a line. */ +@Composable +private fun DualChart(a: List, b: List, start: Long, end: Long) { + fun bucket(r: List) = r.groupBy { (it.atMs - start) / 300_000L }.toSortedMap() + .map { (k, xs) -> (k * 5.0) to xs.map { it.value }.average() } + val pa = bucket(a); val pb = bucket(b) + val all = (pa + pb).map { it.second } + val lo = (all.minOrNull() ?: 50.0) - 5; val hi = (all.maxOrNull() ?: 100.0) + 5 + val span = (end - start) / 60_000.0 + val main = MAIN_COLOR; val second = SECOND_COLOR; val grid = Look.border + Canvas( + Modifier.fillMaxWidth().height(160.dp).semantics { + contentDescription = tr("Heart rate from both rings over the day") + }, + ) { + fun x(m: Double) = (m / span * size.width).toFloat() + fun y(v: Double) = (size.height - (v - lo) / (hi - lo) * size.height).toFloat() + drawLine(grid, Offset(0f, size.height), Offset(size.width, size.height), 1.dp.toPx()) + fun draw(points: List>, color: Color, dashed: Boolean) { + val path = Path() + points.forEachIndexed { i, (m, v) -> + if (i == 0 || m - points[i - 1].first > 15) path.moveTo(x(m), y(v)) else path.lineTo(x(m), y(v)) + } + drawPath(path, color, style = Stroke(2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round, + pathEffect = if (dashed) PathEffect.dashPathEffect(floatArrayOf(10f, 8f)) else null)) + if (points.size == 1) drawCircle(color, 3.dp.toPx(), Offset(x(points[0].first), y(points[0].second))) + } + draw(pa, main, false) + draw(pb, second, true) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index cf4a5a40..107c095d 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -94,6 +94,12 @@ fun SettingsScreen( } else tr("Report ready") } ?: tr("Adjusting your ring").takeIf { !accuracyCorrections.isEmpty } + val comparison = remember { com.pulseloop.AppServices.get(context).comparison } + val comparisonState by comparison.state.collectAsState() + val compareTrailing = if (comparison.isSetUp) { + if (comparisonState.connectionState == com.pulseloop.ring.RingConnectionState.CONNECTED) tr("Connected") else tr("On") + } else null + fun navigate(route: String) { navController?.navigate(route) } @@ -160,6 +166,10 @@ fun SettingsScreen( navigate("settings/calibration") }) } + // A second ring worn only to compare with this one (docs/ring-comparison.md). + add(SettingsRowItem(Icons.Filled.CompareArrows, PulseColors.info, tr("Compare rings"), compareTrailing) { + navigate("settings/compare") + }) add(SettingsRowItem(Icons.Filled.Watch, PulseColors.info, tr("Use without a ring")) { navigate("settings/hc-source") }) diff --git a/app/src/test/java/com/pulseloop/service/ComparisonReadingsTest.kt b/app/src/test/java/com/pulseloop/service/ComparisonReadingsTest.kt new file mode 100644 index 00000000..4cf6b2f1 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/ComparisonReadingsTest.kt @@ -0,0 +1,39 @@ +package com.pulseloop.service + +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.ring.PulseEvent +import com.pulseloop.ring.SleepStage +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.Instant + +class ComparisonReadingsTest { + private val addr = "AA:BB" + + @Test + fun `a re-synced history reading keeps its id`() { + val e = PulseEvent.HistoryMeasurement(MeasurementKind.HEART_RATE, 72.0, Instant.ofEpochMilli(1_000)) + assertEquals(ComparisonReadings.rowsFor(addr, e).single().id, ComparisonReadings.rowsFor(addr, e).single().id) + } + + @Test + fun `a sleep record becomes one row per minute`() { + val e = PulseEvent.SleepTimeline(Instant.ofEpochMilli(0), listOf(SleepStage.LIGHT, SleepStage.DEEP, SleepStage.AWAKE)) + val rows = ComparisonReadings.rowsFor(addr, e) + assertEquals(listOf(0L, 60_000L, 120_000L), rows.map { it.timestamp }) + assertTrue(rows.all { it.kind == ComparisonReadings.SLEEP }) + } + + @Test + fun `our own settled spot value and empty readings are not kept`() { + assertTrue(ComparisonReadings.rowsFor(addr, PulseEvent.HeartRateSample(80, Instant.now(), spot = true)).isEmpty()) + assertTrue(ComparisonReadings.rowsFor(addr, PulseEvent.HeartRateSample(0, Instant.now())).isEmpty()) + assertTrue(ComparisonReadings.rowsFor(addr, PulseEvent.Spo2Result(0, Instant.now())).isEmpty()) + } + + @Test + fun `connection and device events are not readings`() { + assertTrue(ComparisonReadings.rowsFor(addr, PulseEvent.BatteryLevel(50)).isEmpty()) + } +} diff --git a/app/src/test/java/com/pulseloop/service/RingComparisonTest.kt b/app/src/test/java/com/pulseloop/service/RingComparisonTest.kt new file mode 100644 index 00000000..0cd58041 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/RingComparisonTest.kt @@ -0,0 +1,46 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class RingComparisonTest { + private val min = 60_000L + private fun r(m: Double, v: Double) = RingComparison.Reading((m * min).toLong(), v) + + @Test + fun `coverage counts slots with a reading, not readings`() { + // A stream every second for 10 minutes and nothing else, over an hour of 5-minute slots. + val stream = (0 until 600).map { RingComparison.Reading(it * 1000L, 80.0) } + val c = RingComparison.coverage(stream, 0, 60 * min, 5 * min) + assertEquals(2, c.slotsWithReadings) + assertEquals(12, c.slots) + } + + @Test + fun `agreement pairs nearest readings within the tolerance only`() { + val first = listOf(r(0.0, 70.0), r(10.0, 80.0), r(20.0, 90.0)) + val second = listOf(r(1.0, 74.0), r(10.5, 78.0), r(40.0, 100.0)) + val a = RingComparison.agreement(first, second, 2 * min) + assertEquals(2, a.pairs) + assertEquals(3.0, a.medianAbsDiff!!, 1e-9) // |4| and |-2| → 3 + assertEquals(1.0, a.meanDiff!!, 1e-9) // (4 - 2) / 2 + } + + @Test + fun `no overlap means no agreement figure`() { + val a = RingComparison.agreement(listOf(r(0.0, 70.0)), listOf(r(30.0, 70.0)), 2 * min) + assertEquals(0, a.pairs) + assertNull(a.medianAbsDiff) + } + + @Test + fun `day average is weighted by time`() { + // Ten minutes streamed at 120, and a log of 60 every five minutes for the rest of the hour. + val stream = (0 until 600).map { RingComparison.Reading(it * 1000L, 120.0) } + val log = (2..11).map { r(it * 5.0, 60.0) } + val avg = RingComparison.averageHeartRate(stream + log, 0, 60 * min)!! + // Per reading it would be ~119; by time the log's 50 minutes count (2 min each, capped). + assertEquals(true, avg < 100) + } +} diff --git a/audits/2026-11-17-compare-rings.md b/audits/2026-11-17-compare-rings.md new file mode 100644 index 00000000..fe28fe46 --- /dev/null +++ b/audits/2026-11-17-compare-rings.md @@ -0,0 +1,109 @@ +# Audit: Compare rings + +Date: 2026-11-17 · PR: see the PR linking this file · Auditor: Claude Code. impeccable was loaded +(context, `craft-floor.md`, `android.md`) and applied to **rendered** cards. The rings card, the day +header, heart rate, totals and workouts were drawn on the JVM with Robolectric, with two rings' +worth of sample data, at font scale 1.0 and 1.3. The harness is local only. The device check is +owed (no emulator here). ux-user-flows, graphic-design-fundamentals and less-is-more were applied +by hand from their SKILL.md files. + +## Scope + +A new screen, Settings → My ring → Compare rings (`settings/compare`), plus its row on the hub. The +owner's request: keep using the main ring for everything, and wear a second one only to see which +is more reliable. Design and data rules: `docs/ring-comparison.md`. + +## ux-user-flows (§13 flow review checklist) + +- **Entry:** the Settings hub row "Compare rings", whose trailing value reads Connected / On when a + second ring is set up. +- **Not set up:** + 1. One card: what this is, and the promise that the second ring's data stays apart. + 2. "Find a ring". + 3. The scan lists nearby rings, excluding the main ring, with a "keep it close, close the vendor + app" hint while the list is empty. + 4. Tap a ring to connect it. The screen then switches to the comparing state when the ring + connects. +- **Comparing:** + 1. The rings card: each ring's role, name, line style, status and battery, and "Stop comparing" + behind a confirm dialog that says what it does and doesn't do. + 2. A day switcher. + 3. Heart rate. + 4. Totals. + 5. Workouts, if any that day. + 6. The "neither is known to be right" note, with a link to the accuracy check. +- **States:** + - either ring disconnected (status shows it; its numbers read "—"); + - no heart rate from either ring that day; + - no overlapping readings (the agreement sentence says so instead of a number); + - no workouts (the card is hidden); + - future days unreachable (the next arrow is disabled at today). +- **Exits:** Back; Stop comparing (returns to the empty state); Open the accuracy check. +- **Checklist:** every state has words; no dead end; no data-destroying action without a confirm. + Stop comparing keeps the stored readings. + +## impeccable + +### Audit (native, on renders) + +| # | Dimension | Score | Key finding | +|---|---|---|---| +| 1 | Accessibility | 3 | Each comparison row reads as one sentence ("Average: main 78, comparison 73 bpm"); the column swatches carry names for TalkBack; the chart has a description; rings differ by line style as well as colour. Device TalkBack pass owed. | +| 2 | Performance | 4 | One day of rows per load; the chart buckets to 5-minute means; a 30 s refresh while open. | +| 3 | Appearance & theming | 4 | Look tokens, calm cards, sizes on the scale. | +| 4 | Platform conformance | 4 | Scaffold, top bar, AlertDialog, `PulseButton` throughout. | +| 5 | Adaptivity | 4 | 1.3× renders without clipping after the polish below; 720dp cap from the scaffold. | +| | **Total** | **19/20** | | + +### Critique + +| # | Heuristic | Score | Key issue | +|---|---|---|---| +| 1 | Visibility of status | 4 | Both rings' connection and battery on top. | +| 2 | Match real world | 4 | "Hours with readings", "typically 3 bpm apart", not statistics jargon. | +| 3 | User control | 4 | Stop comparing, with a confirm. | +| 4 | Consistency | 4 | Same day switcher, cards and type as the other converted screens. | +| 5 | Error prevention | 4 | The main ring is excluded from the scan list. | +| 6 | Recognition | 4 | Each ring keeps one colour and one line style everywhere on the screen. | +| 7 | Flexibility | 3 | Day by day only; no week view yet. | +| 8 | Minimalist | 4 | Three cards; SpO₂/HRV left out until they're needed. | +| 9 | Error recovery | 3 | Scan hint covers the common failure (vendor app holding the ring). | +| 10 | Help | 4 | States that neither ring is ground truth and where to get one. | +| | **Total** | **37/40** | Excellent | + +### Polish (from the renders) + +- [fixed] At 1.3× the "Comparison" column heading truncated, and Portuguese would truncate at 1.0×. + The column heads are now the two line swatches (named for TalkBack), matching the rings card. +- [fixed] Workouts crammed the workout's name into the first row ("Gym · 7:00 AM · avg") with + lowercase fragments below. Each workout now has its own title line, then Average / Highest / + Minutes with readings. +- [P3] The day average and the paired agreement can disagree in direction (a streamed workout on + one ring raises its average but has no pair on the other). The sentence names the paired figure, + so it stays truthful. + +No P0 or P1. + +## graphic-design-fundamentals (§13 checklist) + +- **Hierarchy:** card titles 16sp semibold; values 16sp semibold; labels 14sp; notes 12–14sp. +- **Colour:** + - The main ring uses the heart-rate coral, solid; the comparison ring uses the info cyan, + dashed. + - Mint appears only on the scan list's "Compare" action and the tonal button. + - Status uses `success`. +- **Alignment:** a label column plus two fixed 96dp value columns, right-aligned, so numbers line up + across cards. +- **Contrast:** calm neutrals; the line colours are drawn on the card, not used as text. +- **Real size:** checked at 411dp, 1.0 and 1.3. + +## less-is-more + +| Element | Verdict | +|---|---| +| Per-ring averages, coverage, agreement | Kept: the three numbers that answer "which is more reliable" | +| SpO₂ / HRV / temperature comparison | Left out for now; stored, shown when asked | +| A week view | Left out; day switcher covers the first use | +| Column names in each table | Replaced by the line swatches the rings card already names | + +No existing action gained a tap: the hub gained one row in My ring. diff --git a/docs/ring-comparison.md b/docs/ring-comparison.md new file mode 100644 index 00000000..9591ab45 --- /dev/null +++ b/docs/ring-comparison.md @@ -0,0 +1,57 @@ +# Comparing two rings + +The owner wears two rings (a Colmi and a JRing) to see which is more reliable. The owner's choice +(2026-11-17): **compare only**. The main ring keeps feeding the whole app; the second ring is shown +only on Settings → My ring → Compare rings. + +## How it is kept apart ✅ + +- **Its own client:** `RingBLEClient(role = RingRole.COMPARISON)`, built once in `AppServices` + (`ComparisonRing`). It has: + - its own connection slot (`comparisonConnectionOwner`), so the two rings never block each other; + - its own saved ring (`ring_ble_compare` prefs), so it never overwrites the main ring's. +- **Its own event stream: `ComparisonBus`, never `PulseEventBus`.** Everything on the app's bus + belongs to the main ring: + - persistence and the device row; + - the accuracy watcher; + - Health Connect and Strava; + - the sync coordinator. + + So the comparison client publishes there only its diagnostics, marked `[comparison ring]`. +- **Driver publishes go through the writer.** Drivers that publish on their own (YCBT history, + LuckRing history, Colmi's sync "done", jring's log) use `RingCommandWriter.publish`, which the + comparison client overrides. A new driver that publishes must do the same, or a second ring of + that family leaks into the app's data. +- **Its own table: `comparison_readings`** (v38). It holds: + - heart rate, SpO₂ and HRV; + - steps (buckets, plus the ring's running daily total); + - sleep, one row per minute with the stage. + + Ids are `
::`, so a re-sync updates rather than duplicates. Nothing else + reads it: no score, no Health Connect, no Strava, and it is not in the backup archive. + +## What it does ✅ + +- **On every connect:** the second ring runs its own startup and history sync, so its log for the + day arrives like the main ring's. +- **During a recorded workout:** it streams heart rate too (`LiveWorkoutManager` → + `ComparisonRing.startWorkout`), and a reconnect restarts that stream. +- **"Stop comparing":** disconnects the ring and forgets it without the vendor unbind, so it is + still paired to its own app. Readings already kept stay in the table. + +## The screen ✅ + +Per local day: +- **Heart rate:** both rings' curves (main solid, comparison dashed, each in its own colour), the + time-weighted average, the hours with readings (5-minute slots), and how close the two were when + both measured within 3 minutes (`RingComparison.agreement`). +- **Totals:** steps, and sleep for the night before. +- **Workouts:** each workout's average, highest and minutes with readings, per ring. + +It says plainly that neither ring is known to be right, and links the accuracy check for a watch. + +## Not yet ⬜ + +- The background sync worker syncs only the main ring. The second ring catches up whenever the app + is open or a workout is recording. +- No SpO₂, HRV or temperature comparison on screen yet (the rows are stored).