Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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-*/
15 changes: 15 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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}",
Expand Down Expand Up @@ -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 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",
"Resting HR": "FC em repouso",
"Resting HR above your usual": "FC de repouso acima do normal",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
11 changes: 8 additions & 3 deletions app/src/main/java/com/pulseloop/ring/JringDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
22 changes: 22 additions & 0 deletions app/src/main/java/com/pulseloop/ring/RingEncoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)),
}
6 changes: 6 additions & 0 deletions app/src/main/java/com/pulseloop/ring/WearableDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) {}
Expand Down
33 changes: 33 additions & 0 deletions app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,10 @@ 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
/** 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
Expand Down Expand Up @@ -491,6 +495,35 @@ 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 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(if (rebooting) RESTART_REBOOT_GAP_MS else 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
Expand Down
44 changes: 44 additions & 0 deletions app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 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,
)
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."),
Expand Down
37 changes: 26 additions & 11 deletions app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand All @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
34 changes: 34 additions & 0 deletions app/src/test/java/com/pulseloop/ring/JringDeviceModeTest.kt
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading