From 9aa5c56198c44a822df28e94401810b75bc04c64 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 20:48:14 +0000 Subject: [PATCH 1/2] Vital cards show the last reading's time; add Restart ring - Vital cards: "Updated 2h ago" becomes "Last reading 14:28". An owner read the age as a failed sync; their diagnostics showed the ring itself had logged nothing between 14:28 and 17:28. - Translate the remaining English on those cards (bpm range, % avg, the vs earlier/baseline/previous trend suffixes) and add pt-BR entries. - Ring & sync: Restart ring, for every ring. It drops the link and reconnects, so the connect sequence re-sends clock, background-logging settings and profile, then runs a full history pass. Nothing is erased. Factory reset stays gated on FACTORY_RESET: there is no verified vendor reset command for JRING/YCBT/LuckRing. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/pt-BR.json | 11 ++ .../pulseloop/service/RingSyncCoordinator.kt | 22 ++++ .../ui/screens/SettingsSubScreens.kt | 44 ++++++++ .../pulseloop/ui/viewmodels/VitalCardState.kt | 37 +++++-- .../ui/viewmodels/LastReadingLabelTest.kt | 43 ++++++++ ...11-11-v2.16.1-last-reading-restart-ring.md | 102 ++++++++++++++++++ 6 files changed, 248 insertions(+), 11 deletions(-) create mode 100644 app/src/test/java/com/pulseloop/ui/viewmodels/LastReadingLabelTest.kt create mode 100644 audits/2026-11-11-v2.16.1-last-reading-restart-ring.md diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 502d65e6..c571fe6d 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -19,6 +19,7 @@ " · {0}% taken this week": " · {0}% tomados nesta semana", "\"Nearby devices\"": "\"Dispositivos próximos\"", "\"{0}\" will be removed from this day's log.": "\"{0}\" será removido do registro deste dia.", + "% avg": "% média", "%,d of %,d steps": "%,d de %,d passos", "%,d steps": "%,d passos", "%,d steps a day": "%,d passos por dia", @@ -945,6 +946,7 @@ "Last night: {0}. A few dry nights will show what it does to you.": "Noite passada: {0}. Algumas noites sem álcool vão mostrar o efeito em você.", "Last night: {0}. Your night looked close to your dry ones.": "Noite passada: {0}. Sua noite ficou parecida com as noites sem álcool.", "Last night: {0}. {1}.": "Noite passada: {0}. {1}.", + "Last reading {0}": "Última leitura {0}", "Last seen: {0}": "Visto por último: {0}", "Last sync {0} — ": "Última sincronização {0} — ", "Last synced: {0}": "Última sincronização: {0}", @@ -1465,6 +1467,9 @@ "Rest Mode on": "Modo Descanso ativo", "Rest Mode on until {0}": "Modo Descanso ativo até {0}", "Rest days let your body adapt to training. One or two easier days a week is enough for most people.": "Dias de descanso permitem que o corpo se adapte ao treino. Um ou dois dias mais leves por semana bastam para a maioria das pessoas.", + "Restart reconnects the ring and sends it its clock and monitoring settings again. Nothing is erased. Try it if the ring stops recording or syncing.": "Reiniciar reconecta o anel e envia de novo o relógio e as configurações de monitoramento. Nada é apagado. Use se o anel parar de registrar ou de sincronizar.", + "Restart ring": "Reiniciar anel", + "Restarting…": "Reiniciando…", "Restfulness": "Tranquilidade", "Resting HR": "FC em repouso", "Resting HR above your usual": "FC de repouso acima do normal", @@ -1496,6 +1501,7 @@ "Ring hasn't synced in >12h — today's data may be stale.": "O anel não sincroniza há mais de 12h — os dados de hoje podem estar desatualizados.", "Ring management": "Gerenciamento do anel", "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", "Road, trail, or stationary": "Rua, trilha ou estacionária", "Route by": "Rotear por", @@ -1779,6 +1785,7 @@ "The previous record ends at {0}.": "O registro anterior termina às {0}.", "The report covers the days so far. You'll then choose what happens to the paused Health Connect export.": "O relatório abrange os dias até agora. Depois você escolherá o que acontece com a exportação pausada para o Health Connect.", "The report printed no range for this marker.": "O laudo não trouxe faixa de referência para este marcador.", + "The ring didn't come back. Keep it near the phone and try again.": "O anel não voltou. Deixe-o perto do celular e tente de novo.", "The ring disconnected during measurement.": "O anel se desconectou durante a medição.", "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", @@ -2091,6 +2098,7 @@ "below": "abaixo", "below {0}": "abaixo de {0}", "best dry streak": "melhor sequência sem beber", + "bpm range": "bpm (faixa)", "calories": "calorias", "compared over the {0} h both were on": "comparado nas {0} h em que os dois estavam ligados", "daily calories": "calorias diárias", @@ -2149,6 +2157,9 @@ "unknown error": "erro desconhecido", "up": "a mais", "up {0}": "acordar {0}", + "vs baseline": "vs sua base", + "vs earlier": "vs antes", + "vs previous": "vs anterior", "workout": "treino", "workouts": "treinos", "workouts a week": "treinos por semana", diff --git a/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt b/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt index 4bcddbee..716a44ab 100644 --- a/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt +++ b/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt @@ -250,6 +250,7 @@ class RingSyncCoordinator( HR_MEASURE_SECONDS + SPO2_MEASURE_SECONDS + BP_MEASURE_SECONDS + HRV_MEASURE_SECONDS + 3 /** Max time to wait for the pre-factory-reset history sync before resetting anyway. */ const val SYNC_BEFORE_RESET_TIMEOUT_MS = 30_000L + const val RESTART_GAP_MS = 2_000L } private val engine: RingSyncEngine? get() = client.syncEngine @@ -491,6 +492,27 @@ class RingSyncCoordinator( } } + /** + * Non-destructive "restart": drop the link and connect again, so the ring gets the whole + * connect sequence afresh — clock, background-logging settings, user profile, then a full + * history pass. That is everything the app itself can re-tell a ring, and it works for every + * family. It is the safe answer to "something on the ring side is stuck" for rings whose + * vendor reset command we have not verified (jring, YCBT, LuckRing): those keep their + * `factoryReset()` a no-op rather than send a guessed opcode (AGENTS.md). + * + * Nothing is erased: the ring keeps its stored history and the next pass re-reads it. + */ + fun restartRing() { + scope.launch { + client.disconnect() + // Let the old GATT handle close before the new connect (the client closes it + // ~500 ms after disconnect; CRP's teardown monitor takes longer and is waited on + // by the client itself). + kotlinx.coroutines.delay(RESTART_GAP_MS) + client.userConnect() + } + } + /** * Destructive: wipe the ring's on-device storage. Because a Colmi ring buffers days of * unsynced history, we sync the latest data into the app FIRST, then send the factory diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index ffe194e1..64e7349c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -2153,6 +2153,28 @@ fun WearableSettingsScreen( var showForgetRing by remember { mutableStateOf(false) } var resetting by remember { mutableStateOf(false) } var resetStatus by remember { mutableStateOf("") } + // Restart = drop the link and connect again (RingSyncCoordinator.restartRing). It is done when + // the ring has gone away and come back; the 45 s cap ends the spinner if it never returns. + var restarting by remember { mutableStateOf(false) } + var restartSawDrop by remember { mutableStateOf(false) } + val snackbar = com.pulseloop.ui.components.LocalAppSnackbar.current + LaunchedEffect(restarting, bleState.connectionState) { + if (!restarting) return@LaunchedEffect + if (bleState.connectionState != RingConnectionState.CONNECTED) { + restartSawDrop = true + } else if (restartSawDrop) { + restarting = false + snackbar?.show(tr("Ring restarted. Syncing now.")) + } + } + LaunchedEffect(restarting) { + if (!restarting) return@LaunchedEffect + kotlinx.coroutines.delay(45_000) + if (restarting) { + restarting = false + snackbar?.show(tr("The ring didn't come back. Keep it near the phone and try again.")) + } + } // Exact model preferred; falls back to the family / advertised-name heuristic. val wearableDisplayName = WearableModel.model(bleState.activeWearableModelID)?.displayName @@ -2272,6 +2294,28 @@ fun WearableSettingsScreen( Column(Modifier.padding(16.dp)) { Text(tr("Ring management"), style = PulseType.title) Spacer(Modifier.height(8.dp)) + Text( + tr("Restart reconnects the ring and sends it its clock and monitoring " + + "settings again. Nothing is erased. Try it if the ring stops recording " + + "or syncing."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(12.dp)) + PulseButton(PulseButtonStyle.Outlined, + enabled = !restarting && !resetting && bleClient?.hasLastKnownRing == true, + onClick = { + restartSawDrop = false + restarting = true + coordinator?.restartRing() + }, + modifier = Modifier.fillMaxWidth(), + ) { + Icon(Icons.Filled.Refresh, null, Modifier.size(16.dp)) + Spacer(Modifier.width(4.dp)) + Text(if (restarting) tr("Restarting…") else tr("Restart ring")) + } + Spacer(Modifier.height(16.dp)) Text( tr("Forget unbinds the ring and removes it from the app so it can be paired " + "elsewhere. The app stays connected automatically the rest of the time."), diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt index e167dcc0..cb3c203c 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt @@ -91,12 +91,12 @@ data class TrendSummary( // Sub-unit deltas keep one decimal (truncated, matching iOS Int-cast); larger deltas round. val rounded = if (abs(delta) < 1 && delta != 0.0) (delta * 10).toInt() / 10.0 else roundAwayFromZero(delta) if (abs(rounded) < 0.5) { - return TrendSummary(TrendDirection.STABLE, trf("Stable {0}", suffix), "→") + return TrendSummary(TrendDirection.STABLE, trf("Stable {0}", tr(suffix)), "→") } val unit = if (unitLabel.isEmpty()) "" else " $unitLabel" val sign = if (rounded > 0) "+" else "−" val magnitude = if (abs(rounded) % 1.0 == 0.0) "${abs(rounded).toInt()}" else "${abs(rounded)}" - val text = "$sign$magnitude$unit $suffix" + val text = "$sign$magnitude$unit ${tr(suffix)}" return TrendSummary( direction = if (rounded > 0) TrendDirection.RISING else TrendDirection.FALLING, deltaText = text, @@ -219,7 +219,7 @@ object VitalsCardFactory { return VitalCardState( metric = MetricKind.HEART_RATE, title = MetricKind.HEART_RATE.title, valueText = valueText, latestValue = latest, - unitText = if (latest != null) "bpm range" else null, + unitText = if (latest != null) tr("bpm range") else null, statusText = interp?.displayLabel ?: tr("No reading"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, subtitleText = "$resting · $peak", @@ -245,7 +245,7 @@ object VitalsCardFactory { return VitalCardState( metric = MetricKind.SPO2, title = MetricKind.SPO2.title, valueText = averageLabel(samples, latest), latestValue = latest, - unitText = if (latest != null) "% avg" else null, + unitText = if (latest != null) tr("% avg") else null, statusText = interp?.displayLabel ?: tr("No reading"), statusToken = interp?.statusColorToken ?: VitalColorToken.Neutral, subtitleText = subtitle, @@ -529,14 +529,29 @@ object VitalsCardFactory { return listOf(ReferenceBand(lower, upper, normal.colorToken)) } - private fun lastUpdated(dateMs: Long?, nowMs: Long): String? { + /** + * When the newest stored reading was taken, as a clock time ("Last reading 14:28"), not an age. + * "Updated 2h ago" read as a stale sync when the sync had just run and the ring simply had + * recorded nothing newer (ring off the finger, or moving too much to read); the reading's own + * time says what the app actually knows. Older than today adds the weekday, older than a + * week the date. Formats follow the default Locale, which L10n sets. + */ + internal fun lastUpdated( + dateMs: Long?, + nowMs: Long, + zone: java.time.ZoneId = java.time.ZoneId.systemDefault(), + ): String? { if (dateMs == null) return null - val minutes = ((nowMs - dateMs) / 60_000L).toInt() - if (minutes < 1) return "Updated just now" - if (minutes < 60) return "Updated ${minutes}m ago" - val hours = minutes / 60 - if (hours < 24) return "Updated ${hours}h ago" - return "Updated ${hours / 24}d ago" + val at = java.time.Instant.ofEpochMilli(dateMs).atZone(zone) + val today = java.time.Instant.ofEpochMilli(nowMs).atZone(zone).toLocalDate() + val time = at.format(java.time.format.DateTimeFormatter.ofLocalizedTime(java.time.format.FormatStyle.SHORT)) + val days = java.time.temporal.ChronoUnit.DAYS.between(at.toLocalDate(), today) + val label = when { + days <= 0L -> time + days < 7L -> at.format(java.time.format.DateTimeFormatter.ofPattern("EEE")) + " " + time + else -> at.format(java.time.format.DateTimeFormatter.ofPattern("d MMM")) + } + return trf("Last reading {0}", label) } // Unit conversions (iOS UnitsFormatter). °C is canonical for temperature; mg/dL for glucose. diff --git a/app/src/test/java/com/pulseloop/ui/viewmodels/LastReadingLabelTest.kt b/app/src/test/java/com/pulseloop/ui/viewmodels/LastReadingLabelTest.kt new file mode 100644 index 00000000..fe42afa9 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ui/viewmodels/LastReadingLabelTest.kt @@ -0,0 +1,43 @@ +package com.pulseloop.ui.viewmodels + +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test +import java.time.LocalDateTime +import java.time.ZoneId +import java.util.Locale + +/** + * The vital cards say when the newest reading was taken, not how long ago: "Updated 2h ago" + * read as a stale sync when the ring had simply recorded nothing newer. + */ +class LastReadingLabelTest { + private val zone = ZoneId.of("America/Sao_Paulo") + private lateinit var saved: Locale + + @Before fun setUp() { saved = Locale.getDefault(); Locale.setDefault(Locale.UK) } + @After fun tearDown() { Locale.setDefault(saved) } + + private fun ms(y: Int, mo: Int, d: Int, h: Int, mi: Int) = + LocalDateTime.of(y, mo, d, h, mi).atZone(zone).toInstant().toEpochMilli() + + private val now = ms(2026, 11, 11, 17, 4) + + @Test fun todayShowsTheClockTime() { + assertEquals("Last reading 14:28", VitalsCardFactory.lastUpdated(ms(2026, 11, 11, 14, 28), now, zone)) + } + + @Test fun earlierThisWeekAddsTheWeekday() { + assertEquals("Last reading Mon 22:10", VitalsCardFactory.lastUpdated(ms(2026, 11, 9, 22, 10), now, zone)) + } + + @Test fun olderThanAWeekShowsTheDate() { + assertEquals("Last reading 1 Nov", VitalsCardFactory.lastUpdated(ms(2026, 11, 1, 9, 0), now, zone)) + } + + @Test fun noReadingNoLabel() { + assertNull(VitalsCardFactory.lastUpdated(null, now, zone)) + } +} diff --git a/audits/2026-11-11-v2.16.1-last-reading-restart-ring.md b/audits/2026-11-11-v2.16.1-last-reading-restart-ring.md new file mode 100644 index 00000000..03ea04fd --- /dev/null +++ b/audits/2026-11-11-v2.16.1-last-reading-restart-ring.md @@ -0,0 +1,102 @@ +# Audit: last-reading label, Vitals translations, Restart ring (2.16.1) + +Date: 2026-11-11 · PR: see the PR linking this file · Auditor: Claude Code (the four skills applied by hand from their SKILL.md files) + +## Scope + +- **Vital cards, top-right label.** "Updated 2h ago" becomes "Last reading 14:28" (weekday added for + earlier this week, date for older). Trigger: a JRING owner read "Updated 2h ago" as a failed sync. + Their diagnostics showed the sync had worked: the ring's own history held nothing between 14:28 + and 17:28, so the age was correct but read as the app's fault. +- **Translations.** "bpm range", "% avg", "vs earlier" / "vs baseline" / "vs previous" and the new + label now go through `tr()`, with pt-BR entries. +- **Ring & sync → Ring management → Restart ring.** A non-destructive action for every ring: drop + the link, connect again, and let the connect sequence re-send the clock, background-logging + settings and profile, then run a full history pass. It shows "Restarting…" until the ring has + dropped and come back, then shows a snackbar. After 45 s with no reconnect, the snackbar says so. + Factory reset is unchanged and still gated on `FACTORY_RESET`: JRING, YCBT and LuckRing have no + verified vendor reset command, and AGENTS.md forbids guessing one. + +## ux-user-flows (§13 flow review checklist) + +Flow: Ring & sync → Restart ring → (link drops) → "Restarting…" → (ring back) → snackbar "Ring +restarted. Syncing now." / (45 s, no ring) → snackbar "The ring didn't come back…" → button enabled again. + +| # | Question | Result | +|---|---|---| +| 1 | Job | "Something on the ring seems stuck; make it start over without losing anything." | +| 2 | Entries | One: Ring management card, where Forget and Factory reset already live. | +| 3 | Happy path | One tap, no dialog. Nothing is erased, so a confirm would only cost a tap. | +| 4 | Branches | Ring returns / doesn't return in 45 s. | +| 5 | States | Idle, restarting (button disabled, label "Restarting…"), done (snackbar), timed out (snackbar). | +| 6 | Errors | Timeout message says what to do (keep it near the phone, try again). | +| 7 | Control | The user can leave the screen; the reconnect runs on the coordinator's scope. | +| 8 | Progress and resume | The label shows progress; the snackbar outlives the screen. | +| 9 | Memory | None needed. | +| 10 | Exits | Back at any time. | +| 11 | Conventions | Same outlined button as the card's other actions; same snackbar as workout Add. | +| 12 | Speed | About 2 s gap plus a normal connect. | +| 13 | Accessibility | Button text changes with state; the snackbar is announced by TalkBack. | +| 14 | Ethics | The copy says plainly that nothing is erased; destructive reset keeps its confirm. | +| 15 | Evidence | The owner's diagnostics (2026-11-11) and their request for an in-app reset. | + +No critical or important issues. + +## graphic-design-fundamentals (§13 checklist) + +| # | Question | Result | +|---|---|---| +| 1 | Brief | Make "is the data stale, or did the ring record nothing?" answerable at a glance. | +| 2 | Concept | Show the time of the reading itself, not an age that reads like a sync status. | +| 3 | Hierarchy | Unchanged: the label stays a quiet 12sp top-right line. | +| 4 | Contrast | `onSurfaceVariant`, unchanged. | +| 5 | Alignment and grid | Unchanged; the Restart row reuses the card's 12/16dp rhythm. | +| 6 | Spacing | 16dp separates Restart from Forget, which marks them as two different kinds of action. | +| 7 | Typography | Uses the scale (12sp); no new sizes. | +| 8 | Colour | Restart is neutral (not error red): it is not destructive. | +| 9 | Consistency | The same label everywhere a vital card shows one (Vitals, Today). | +| 10 | Simplicity | Shorter than before in English ("Last reading 14:28" vs "Updated 2h ago"). | +| 11 | Real-size test | pt-BR "Última leitura 14:28" fits the 160dp label cap at 12sp. | +| 12 | Accessibility and ergonomics | Full-width 52dp button. | +| 13 | Production | No new assets or tokens. | + +## impeccable (audit, native / Android) + +| # | Dimension | Score | Key finding | +|---|---|---|---| +| 1 | Accessibility | 4 | Stateful button text; snackbar announced. | +| 2 | Performance | 4 | Two `LaunchedEffect`s keyed on state; no polling. | +| 3 | Appearance & theming | 4 | Existing components and tokens only. | +| 4 | Platform conformance | 4 | Snackbar for a transient result, as Material recommends. | +| 5 | Adaptivity | 4 | Locale-aware time (`FormatStyle.SHORT`): 12/24h follows the language. | +| | **Total** | **20/20** | | + +Findings: P3 — the time format follows the app's language, not the phone's 12/24h switch. Kept: +the rest of the app formats times the same way. + +## less-is-more + +| Element | Question (1–5) | Kept / moved / merged / removed, and where | +|---|---|---| +| "Updated Xh ago" | 2 (is it the right words?) | Replaced by the reading's time. | +| Restart ring button | 1 (does it earn its place?) | Kept: it is the only fix the app can offer for ring-side trouble on rings without a verified reset, and it lives in the existing management card rather than a new one. | +| Restart confirm dialog | 4 (can it be cut?) | Not added: nothing is lost. | + +| Dimension | 0–4 | +|---|---| +| Elements per screen, compared with before | +1 button and one line of text on Ring & sync; Vitals unchanged | +| Duplicates left | 0 | +| Text to read when tired | 4 | +| Taps on the common actions (must not rise) | Unchanged | + +## Evidence + +- No colour, token or type change, so `check_tokens.py` and `drift.py` don't apply. +- The pt-BR missing-key check returns `[]`. +- `LastReadingLabelTest` covers the three label forms plus "no reading". +- Design canvas: see the PR description. + +## Verdict + +Merge. Carried forward: +- A real factory reset for JRING, YCBT and LuckRing needs each vendor's decompiled app. From 77f1468da8088cd168802f8031c812d93b067207 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 21:11:54 +0000 Subject: [PATCH 2/2] Jring: factory reset and ring reboot from the vendor app Read from JRing 2.0.8 (com.jaga.ibraceletplus.jyring), decompiled with jadx: the vendor SDK's setDeviceMode writes 0x0E plus an 8-byte key. The vendor buttons name the modes: 2 "Device off", 3 "Restart device", 4 "Factory reset". Jring now sends mode 4 for factory reset (the existing sync-first, wipe, forget flow, now offered for jring) and mode 3 when Restart ring runs, before it reconnects. Other families keep the reconnect-only restart. decompiled-*/ is gitignored: vendor code is read locally and cited, never committed. AGENTS.md records where the modes come from. Byte-level test against the vendor frames. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .gitignore | 2 ++ AGENTS.md | 15 ++++++++ app/src/main/assets/i18n/pt-BR.json | 2 +- .../java/com/pulseloop/ring/JringDriver.kt | 11 ++++-- .../java/com/pulseloop/ring/RingEncoder.kt | 22 ++++++++++++ .../java/com/pulseloop/ring/WearableDriver.kt | 6 ++++ .../pulseloop/service/RingSyncCoordinator.kt | 17 ++++++++-- .../ui/screens/SettingsSubScreens.kt | 6 ++-- .../com/pulseloop/ring/JringDeviceModeTest.kt | 34 +++++++++++++++++++ ...11-11-v2.16.1-last-reading-restart-ring.md | 10 ++++-- 10 files changed, 112 insertions(+), 13 deletions(-) create mode 100644 app/src/test/java/com/pulseloop/ring/JringDeviceModeTest.kt diff --git a/.gitignore b/.gitignore index 23a3b8d4..a08b8b51 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ gradle/.DS_Store .DS_Store .kotlin/ .claude/worktrees/ +# Decompiled vendor apps: the vendor's code, read locally, never committed (AGENTS.md). +decompiled-*/ diff --git a/AGENTS.md b/AGENTS.md index bbc44a0e..0e3d4f81 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,6 +63,21 @@ Same lesson, different field: a name pattern is one convention, so keep it in on `modelForAdvertisedName` returns a card at all, and whether `ColmiSmartHealthCoordinator` accepts the name — and the two copies that used to exist drifted into the same bug. +## Decompiled vendor apps stay out of git; jring's device modes come from one + +`decompiled-*/` is gitignored: a decompiled vendor app is the vendor's code, so read it locally and +cite it, never commit it. `decompiled-jring-offical/` is JRing 2.0.8 +(`com.jaga.ibraceletplus.jyring`), decompiled with jadx 1.5.1, and does have Java sources (an +older note calls it dex-only). Its SDK is `com.sxr.sdk.ble.keepfit` (`BluetoothLeService`, +`IRemoteService`). + +Restart and factory reset for jring are the vendor's `setDeviceMode` (`0x0E` + an 8-byte key, +`RingEncoder.makeDeviceModeCommand`). The mode numbers are confirmed by the vendor buttons that +send them: 2 "Device off", 3 "Restart device", 4 "Factory reset" / "Reset device". "Restart ring" +in Ring & sync sends mode 3 and then reconnects (`RingSyncEngine.restartDevice`). For a family +without a verified reboot, it only reconnects. YCBT and LuckRing still have no reset; add one +the same way, from their own decompiles. + ## 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 c571fe6d..e9d01d36 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -1467,7 +1467,7 @@ "Rest Mode on": "Modo Descanso ativo", "Rest Mode on until {0}": "Modo Descanso ativo até {0}", "Rest days let your body adapt to training. One or two easier days a week is enough for most people.": "Dias de descanso permitem que o corpo se adapte ao treino. Um ou dois dias mais leves por semana bastam para a maioria das pessoas.", - "Restart reconnects the ring and sends it its clock and monitoring settings again. Nothing is erased. Try it if the ring stops recording or syncing.": "Reiniciar reconecta o anel e envia de novo o relógio e as configurações de monitoramento. Nada é apagado. Use se o anel parar de registrar ou de sincronizar.", + "Restart reboots the ring if it supports that, reconnects it, and sends it its clock and monitoring settings again. Nothing is erased. Try it if the ring stops recording or syncing.": "Reiniciar reinicia o anel, se ele permitir, reconecta e envia de novo o relógio e as configurações de monitoramento. Nada é apagado. Use se o anel parar de registrar ou de sincronizar.", "Restart ring": "Reiniciar anel", "Restarting…": "Reiniciando…", "Restfulness": "Tranquilidade", diff --git a/app/src/main/java/com/pulseloop/ring/JringDriver.kt b/app/src/main/java/com/pulseloop/ring/JringDriver.kt index 4b7c9654..e1d2b428 100644 --- a/app/src/main/java/com/pulseloop/ring/JringDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/JringDriver.kt @@ -45,6 +45,7 @@ object JringCoordinator : WearableCoordinator { WearableCapability.MANUAL_SPO2, WearableCapability.REALTIME_HEART_RATE, WearableCapability.FIND_DEVICE, + WearableCapability.FACTORY_RESET, // 0x0E mode 4, the vendor's "Factory reset" // NOTE: No TEMPERATURE — the Jring (SR08-class PPG ring) has no skin-temperature // sensor. In the official app temperature is gated by the 0x20 capability bit // FUNCTION_TEMPERATURE (zArr[10]), which these rings do not set; it exists in the @@ -269,7 +270,11 @@ class JringSyncEngine( writer?.enqueue(cmd) } - // Jring has no power-off or factory-reset capabilities — no-ops - override fun powerOff() {} - override fun factoryReset() {} + // 0x0E device modes, from the vendor app (RingEncoder.makeDeviceModeCommand). + override fun powerOff() { writer?.enqueue(encoder.makeDeviceModeCommand(JringDeviceMode.POWER_OFF)) } + override fun factoryReset() { writer?.enqueue(encoder.makeDeviceModeCommand(JringDeviceMode.FACTORY_RESET)) } + override fun restartDevice(): Boolean { + writer?.enqueue(encoder.makeDeviceModeCommand(JringDeviceMode.RESTART)) + return true + } } diff --git a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt index af5a879f..e34b61ee 100644 --- a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt @@ -10,6 +10,21 @@ import java.util.TimeZone object RingEncoder { fun makeStatusCommand(): ByteArray = hexToBytes("0c00000000000000000000000000000000000000") + + /** + * Device mode (0x0E), the vendor SDK's `setDeviceMode(int)` (`BluetoothLeService.m`, reached + * through `IRemoteService.setDeviceMode`). Each mode is the opcode plus a fixed 8-byte key, + * zero-padded to 20 bytes, written on the same path as 0x19/0x3A. The vendor app's buttons + * name the modes: 2 = "Device off" (`SettingMoreActivity.OnClicktvLow`), 3 = "Restart device" + * (`OnClicktvRestart`), 4 = "Factory reset" / "Reset device" (`FragmentSetting.OnClicktvLow` + * and `OnClicktvReset`). Mode 1 is only sent from the OTA wallpaper flow and is not used here. + */ + fun makeDeviceModeCommand(mode: JringDeviceMode): ByteArray { + val cmd = ByteArray(20) + cmd[0] = 0x0E + mode.key.forEachIndexed { i, b -> cmd[i + 1] = b.toByte() } + return cmd + } fun makeLocaleCommand(locale: String = "en-US"): ByteArray { val localeBytes = locale.toByteArray(Charsets.US_ASCII) val cmd = ByteArray(20) @@ -277,3 +292,10 @@ object RingEncoder { fun ByteArray.toHexString(): String = joinToString("") { String.format("%02x", it) } } + +/** The vendor's `setDeviceMode` keys (see [RingEncoder.makeDeviceModeCommand]). */ +enum class JringDeviceMode(val key: IntArray) { + POWER_OFF(intArrayOf(0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10)), + RESTART(intArrayOf(0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0)), + FACTORY_RESET(intArrayOf(0x12, 0x34, 0x12, 0x34, 0x12, 0x34, 0x12, 0x34)), +} diff --git a/app/src/main/java/com/pulseloop/ring/WearableDriver.kt b/app/src/main/java/com/pulseloop/ring/WearableDriver.kt index 23caf056..5b7f1422 100644 --- a/app/src/main/java/com/pulseloop/ring/WearableDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/WearableDriver.kt @@ -244,6 +244,12 @@ interface RingSyncEngine { fun setGoal(steps: Int) fun powerOff() fun factoryReset() + /** + * Ask the ring to reboot itself, if its vendor app has a verified command for it. Returns + * whether one was sent; a family without one returns false and "Restart ring" falls back to + * reconnecting only. Never implement this with a guessed opcode (AGENTS.md). + */ + fun restartDevice(): Boolean = false /** Push user anthropometrics (age/sex/height/weight) so on-device BP/sugar/calorie * algorithms have real inputs. No-op if unsupported. */ fun setUserInfo(ageYears: Int, isMale: Boolean, heightCm: Int, weightKg: Int) {} diff --git a/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt b/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt index 716a44ab..544f42f3 100644 --- a/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt +++ b/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt @@ -251,6 +251,9 @@ class RingSyncCoordinator( /** Max time to wait for the pre-factory-reset history sync before resetting anyway. */ const val SYNC_BEFORE_RESET_TIMEOUT_MS = 30_000L const val RESTART_GAP_MS = 2_000L + /** A rebooting ring stops advertising for a few seconds; the reconnect's own backoff + * covers a slower boot. */ + const val RESTART_REBOOT_GAP_MS = 8_000L } private val engine: RingSyncEngine? get() = client.syncEngine @@ -497,18 +500,26 @@ class RingSyncCoordinator( * connect sequence afresh — clock, background-logging settings, user profile, then a full * history pass. That is everything the app itself can re-tell a ring, and it works for every * family. It is the safe answer to "something on the ring side is stuck" for rings whose - * vendor reset command we have not verified (jring, YCBT, LuckRing): those keep their - * `factoryReset()` a no-op rather than send a guessed opcode (AGENTS.md). + * vendor reboot command we have not verified: those only reconnect. Jring also reboots itself + * first ([RingSyncEngine.restartDevice], the vendor's "Restart device"). * * Nothing is erased: the ring keeps its stored history and the next pass re-reads it. */ fun restartRing() { scope.launch { + // A family with a verified reboot command (jring 0x0E mode 3) restarts the ring + // itself first; wait until the frame has actually left the queue before tearing the + // link down, and give the ring time to boot before reconnecting. + var rebooting = false + if (isConnected && engine?.restartDevice() == true) { + client.awaitOpsFlushed() + rebooting = true + } client.disconnect() // Let the old GATT handle close before the new connect (the client closes it // ~500 ms after disconnect; CRP's teardown monitor takes longer and is waited on // by the client itself). - kotlinx.coroutines.delay(RESTART_GAP_MS) + kotlinx.coroutines.delay(if (rebooting) RESTART_REBOOT_GAP_MS else RESTART_GAP_MS) client.userConnect() } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 64e7349c..2eeb524e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -2295,9 +2295,9 @@ fun WearableSettingsScreen( Text(tr("Ring management"), style = PulseType.title) Spacer(Modifier.height(8.dp)) Text( - tr("Restart reconnects the ring and sends it its clock and monitoring " + - "settings again. Nothing is erased. Try it if the ring stops recording " + - "or syncing."), + tr("Restart reboots the ring if it supports that, reconnects it, and sends it " + + "its clock and monitoring settings again. Nothing is erased. Try it if " + + "the ring stops recording or syncing."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/app/src/test/java/com/pulseloop/ring/JringDeviceModeTest.kt b/app/src/test/java/com/pulseloop/ring/JringDeviceModeTest.kt new file mode 100644 index 00000000..dde40c16 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ring/JringDeviceModeTest.kt @@ -0,0 +1,34 @@ +package com.pulseloop.ring + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The 0x0E device-mode frames, byte for byte against the vendor SDK's `setDeviceMode` + * (`BluetoothLeService.m(int)` in JRing 2.0.8, `com.jaga.ibraceletplus.jyring`). + */ +class JringDeviceModeTest { + private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) } + private val pad = "00".repeat(11) + + @Test fun factoryResetIsMode4() { + assertEquals("0e1234123412341234$pad", hex(RingEncoder.makeDeviceModeCommand(JringDeviceMode.FACTORY_RESET))) + } + + @Test fun restartIsMode3() { + assertEquals("0e123456789abcdef0$pad", hex(RingEncoder.makeDeviceModeCommand(JringDeviceMode.RESTART))) + } + + @Test fun powerOffIsMode2() { + assertEquals("0efedcba9876543210$pad", hex(RingEncoder.makeDeviceModeCommand(JringDeviceMode.POWER_OFF))) + } + + @Test fun everyFrameIsTwentyBytes() { + JringDeviceMode.values().forEach { assertEquals(20, RingEncoder.makeDeviceModeCommand(it).size) } + } + + @Test fun jringOffersFactoryReset() { + assertTrue(WearableCapability.FACTORY_RESET in JringCoordinator.capabilities) + } +} diff --git a/audits/2026-11-11-v2.16.1-last-reading-restart-ring.md b/audits/2026-11-11-v2.16.1-last-reading-restart-ring.md index 03ea04fd..2df40323 100644 --- a/audits/2026-11-11-v2.16.1-last-reading-restart-ring.md +++ b/audits/2026-11-11-v2.16.1-last-reading-restart-ring.md @@ -14,8 +14,11 @@ Date: 2026-11-11 · PR: see the PR linking this file · Auditor: Claude Code (th the link, connect again, and let the connect sequence re-send the clock, background-logging settings and profile, then run a full history pass. It shows "Restarting…" until the ring has dropped and come back, then shows a snackbar. After 45 s with no reconnect, the snackbar says so. - Factory reset is unchanged and still gated on `FACTORY_RESET`: JRING, YCBT and LuckRing have no - verified vendor reset command, and AGENTS.md forbids guessing one. + On a jring ring, Restart first sends the ring's own reboot command (vendor "Restart device", + `0x0E` mode 3) and then reconnects. +- **Factory reset for jring rings.** The existing Factory reset row (sync first, wipe, forget) + now appears for jring too. It sends the vendor's "Factory reset" (`0x0E` mode 4), read from + JRing 2.0.8's own decompile. YCBT and LuckRing still have no verified reset command. ## ux-user-flows (§13 flow review checklist) @@ -99,4 +102,5 @@ the rest of the app formats times the same way. ## Verdict Merge. Carried forward: -- A real factory reset for JRING, YCBT and LuckRing needs each vendor's decompiled app. +- YCBT and LuckRing factory reset needs each vendor's decompiled app. +- Hardware check owed: jring restart (mode 3) and factory reset (mode 4) on a real ring.