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
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ in Ring & sync sends mode 3 and then reconnects (`RingSyncEngine.restartDevice`)
without a verified reboot, it only reconnects. YCBT and LuckRing still have no reset; add one
the same way, from their own decompiles.

The same decompile shows the app passes the ring's BP and sugar through unchanged. The ring
computes them from the profile (`0x02`) and a cuff reference (`0x33`, default 120/80, write-only).
That reference is sent to the ring, **never added to readings**. The ring's 15-minute log of those
estimates is `0x55`, gated on `0x20` bit 83. After each day's heart rate, `JringHistorySync`
imports it together with offline temperature (`0x39`, bit 10) and offline SpO₂ (`0x40`, bit 81),
in the vendor's order. A unit that sets bit 10 is granted TEMPERATURE at runtime. Details: `docs/jring-56ff-plan.md`, "What the vendor app does with BP and sugar".

## 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
4 changes: 4 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,8 @@
"Café com leite": "Café com leite",
"Caipirinha": "Caipirinha",
"Calibrate": "Calibrar",
"Calibrated to your cuff reading of {0}/{1} mmHg. The ring adjusts its estimates to it.": "Calibrado com sua medição de manguito de {0}/{1} mmHg. O anel ajusta as estimativas a ela.",
"Calibrated to your meter reading of {0}. The app shifts the ring's estimate to match it.": "Calibrado com sua medição de glicosímetro de {0}. O app ajusta a estimativa do anel para bater com ela.",
"Calibrated ✓ (offset %+.0f mg/dL)": "Calibrado ✓ (ajuste %+.0f mg/dL)",
"Calibration": "Calibração",
"Calibration cleared": "Calibração apagada",
Expand Down Expand Up @@ -1201,6 +1203,8 @@
"Not all three hold, so LAM doesn't apply now.": "Nem todas as três condições valem, então a LAM não se aplica agora.",
"Not allowed to read: ": "Sem permissão para ler: ",
"Not breastfeeding": "Não estou amamentando",
"Not calibrated. Enter a meter or lab reading to shift the ring's estimate to match it.": "Não calibrado. Informe uma medição de glicosímetro ou de laboratório para ajustar a estimativa do anel.",
"Not calibrated. Enter a reading from a validated cuff so the ring adjusts its estimates to you.": "Não calibrado. Informe uma medição de um manguito validado para o anel ajustar as estimativas a você.",
"Not connected": "Não conectado",
"Not downloaded yet": "Ainda não baixado",
"Not enough data for this period.": "Dados insuficientes para este período.",
Expand Down
21 changes: 14 additions & 7 deletions app/src/main/java/com/pulseloop/ring/JringDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,14 @@ object JringCoordinator : WearableCoordinator {
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
// shared SDK only for smartwatch variants.
// NOTE: No TEMPERATURE in the baseline. The vendor gates it on the 0x20 bit
// FUNCTION_TEMPERATURE (zArr[10]), and SR08-class rings don't set it. Some units do
// (firmware 003A002AV138 does), so it is granted per unit through
// [bitmapGatedCapabilities] when the 0x20 reply sets the bit (RingDecoder.decodeBandFunction).
)

override val bitmapGatedCapabilities: Set<WearableCapability> = setOf(WearableCapability.TEMPERATURE)

override val iconSystemName = "circle.hexagongrid.circle.fill"

override fun makeDriver(writer: RingCommandWriter): WearableDriver = JringDriver(writer)
Expand Down Expand Up @@ -125,8 +127,8 @@ class JringSyncEngine(
private val encoder = RingEncoder

/** The ring's self-reported feature bits (0x20 reply), or `null` if it never answered.
* Nothing branches on these yet — captured so a future offline-history sync chain can gate
* its extra per-day queries once the bit ordering is confirmed against real hardware. */
* Bit 83 gates the per-day 0x55 sensor log ([JringHistorySync.sensorHistory]); the vendor
* builds the same array least-significant bit first (`utils.m.b`, mask {1,2,4,…,128}). */
private var bandCapabilities: JringBandCapabilities? = null

override fun runStartup() {
Expand Down Expand Up @@ -193,7 +195,12 @@ class JringSyncEngine(
0 -> if (event.state == 0) writer?.enqueue(encoder.makeBindAppStartCommand()) // INIT → APP_START
2 -> writer?.enqueue(encoder.makeBindSuccessCommand()) // ACK → SUCCESS
}
is RingDecodedEvent.BandFunction -> bandCapabilities = event.capabilities
is RingDecodedEvent.BandFunction -> {
bandCapabilities = event.capabilities
historySync.sensorHistory = event.capabilities.hasPressureHistory
historySync.oxygenHistory = event.capabilities.hasOxygenOfflineHistory
historySync.temperatureHistory = event.capabilities.hasTemperature
}
else -> {}
}
}
Expand Down
80 changes: 75 additions & 5 deletions app/src/main/java/com/pulseloop/ring/JringHistorySync.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ import kotlinx.coroutines.launch
* settle/stall timers are only its fallback.
*
* Per day: `0x10/offset` → the day's activity+sleep stream → settles → `0x16/offset` → the day's
* HR stream → `0xFF` (or settles) → next day. A day that answers nothing at all still gets its HR
* HR stream → `0xFF` (or settles) → each offline log the ring advertises, in the vendor's order:
* temperature `0x39` ([temperatureHistory]), SpO₂ `0x40` ([oxygenHistory]), BP/stress/sugar/HRV
* `0x55` ([sensorHistory]); each ends on its 23:45 slot or when it settles → next day. A day that answers nothing at all still gets its HR
* request, because `16 00` was previously sent unconditionally and today's HR must not become
* collateral of a silent `0x10`.
*
Expand All @@ -53,8 +55,23 @@ class JringHistorySync(
private val encoder = RingEncoder
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())

/** The two legs of one day, in the order the vendor asks for them. */
private enum class Leg { ACTIVITY, HEART_RATE }
/** The legs of one day, in the order the vendor asks for them (`FragmentMain`'s
* `ACTION_NOTIFY_BLE_SYNC_DATA_BY_DAY_END` chain: 1 → 2 → 12 → 13 → advanced sensor). */
private enum class Leg { ACTIVITY, HEART_RATE, TEMPERATURE, OXYGEN, SENSOR }

/** Offline skin temperature (0x39, `getDataByDay(12, day)`), gated on 0x20 bit 10. */
@Volatile var temperatureHistory: Boolean = false

/** Offline SpO₂ (0x40, `getDataByDay(13, day)`), gated on 0x20 bit 81. */
@Volatile var oxygenHistory: Boolean = false

/**
* Whether to ask each day for the ring's offline sensor log (0x55: BP, stress, sugar, HRV).
* Set from the 0x20 capability bit 83 ([JringBandCapabilities.hasPressureHistory]), which is
* the vendor's own gate (`FragmentMain`, `FUNCTION_HAS_PRESSURE` → `getAdvSensorOfflineData`).
* Read when a day's heart-rate leg ends, by which time the 0x20 reply has long arrived.
*/
@Volatile var sensorHistory: Boolean = false

private var queue = mutableListOf<Int>()
private var currentDay: Int? = null
Expand Down Expand Up @@ -111,9 +128,24 @@ class JringHistorySync(
if (leg != Leg.HEART_RATE) return
// The one genuine end-of-stream signal in this protocol — take it rather than
// waiting out the settle window.
if (data.size >= 2 && (data[1].toInt() and 0xFF) == HR_SYNC_FINISHED) advance()
if (data.size >= 2 && (data[1].toInt() and 0xFF) == HR_SYNC_FINISHED) nextLegAfter(Leg.HEART_RATE)
else restartSettle()
}
OPCODE_TEMPERATURE -> if (leg == Leg.TEMPERATURE) restartSettle()
// The vendor's "getdayabyday failed" reply: the ring has no temperature log for that
// day (`BluetoothLeService` "b9" → `onGetDataByDayEnd(12, 0)`). Move on.
OPCODE_DAY_FAILED -> if (leg == Leg.TEMPERATURE) nextLegAfter(Leg.TEMPERATURE)
OPCODE_OXYGEN -> {
if (leg != Leg.OXYGEN) return
// 15 one-minute readings per frame; the frame holding 23:45 is the day's last.
if (holdsLastSlot(data, slots = 15, stepMinutes = 1)) nextLegAfter(Leg.OXYGEN) else restartSettle()
}
OPCODE_SENSOR -> {
if (leg != Leg.SENSOR) return
// The vendor ends the day's log when a slot lands on 23:45 (the last of the day)
// and otherwise on its 2000 ms idle timer; a past day ends here, today settles.
if (holdsLastSlot(data, slots = 3, stepMinutes = 15)) advance() else restartSettle()
}
}
}

Expand Down Expand Up @@ -143,14 +175,46 @@ class JringHistorySync(
armStall()
}

/**
* After [done], ask for the day's next offline log the ring keeps, in the vendor's order, or
* move to the next day. Each is gated on the 0x20 bit the vendor gates it on.
*/
private fun nextLegAfter(done: Leg) {
val day = currentDay ?: return
val optional = listOf(
Leg.TEMPERATURE to temperatureHistory,
Leg.OXYGEN to oxygenHistory,
Leg.SENSOR to sensorHistory,
)
val next = optional.firstOrNull { (l, on) -> on && l.ordinal > done.ordinal }?.first
if (next == null) { advance(); return }
cancelTimers()
leg = next
writer?.enqueue(when (next) {
Leg.TEMPERATURE -> encoder.makeTemperatureHistoryQueryCommand(dayOffset = day)
Leg.OXYGEN -> encoder.makeOxygenHistoryQueryCommand(dayOffset = day)
else -> encoder.makeSensorHistoryQueryCommand(dayOffset = day)
})
armStall()
}

/** A leg's stream went quiet: hand over to the next leg, or the next day. */
private fun legSettled() {
when (leg) {
Leg.ACTIVITY -> beginHeartRateLeg()
Leg.HEART_RATE -> advance()
else -> nextLegAfter(leg)
}
}

/** Whether a frame's slots include 23:45, read in the ring's own local clock. */
private fun holdsLastSlot(data: ByteArray, slots: Int, stepMinutes: Int): Boolean {
if (data.size < 5) return false
val raw = (data[1].toLong() and 0xFF) or ((data[2].toLong() and 0xFF) shl 8) or
((data[3].toLong() and 0xFF) shl 16) or ((data[4].toLong() and 0xFF) shl 24)
val minuteOfDay = Math.floorMod(raw, 86_400L) / 60
return (0 until slots).any { minuteOfDay + it.toLong() * stepMinutes == LAST_SLOT_MINUTE.toLong() }
}

// MARK: - Timers

/** Data arrived: the stall no longer applies, and the quiet period starts over. */
Expand Down Expand Up @@ -193,6 +257,12 @@ class JringHistorySync(
private const val OPCODE_ACTIVITY = 0x10
private const val OPCODE_SLEEP = 0x11
private const val OPCODE_HEART_RATE = 0x16
private const val OPCODE_SENSOR = 0x55
private const val OPCODE_TEMPERATURE = 0x39
private const val OPCODE_OXYGEN = 0x40
private const val OPCODE_DAY_FAILED = 0xB9
/** 23:45 — the vendor's end-of-day slot for the 0x55 log. */
private const val LAST_SLOT_MINUTE = 23 * 60 + 45
/** `0x16` subtype `0xFF` — "sync finished" (`RingDecoder.decodeHeartRateHistory`). */
private const val HR_SYNC_FINISHED = 0xFF
}
Expand Down
110 changes: 106 additions & 4 deletions app/src/main/java/com/pulseloop/ring/RingDecoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,16 @@ class RingDecoder(private val clock: JringClock? = null) {
0x11 -> listOf(decodeSleepTimeline(bytes))
0x14 -> listOf(decodeLiveHeartRate(bytes, now))
0x16 -> decodeHeartRateHistory(bytes) // multi-packet protocol
0x20 -> listOf(decodeBandFunction(bytes))
0x20 -> decodeBandFunction(bytes)
0x24 -> decodeCombinedSensor(bytes, now) // 5 metrics in one packet
0x27 -> listOf(RingDecodedEvent.HeartRateComplete(_timestamp = now))
0x28 -> listOf(RingDecodedEvent.Spo2Complete(_timestamp = now))
0x3F -> listOf(decodeSpo2Result(bytes, now))
0x4B -> listOf(decodeBindNotify(bytes)) // ring-side bind/unbind handshake
0x55 -> decodeSensorHistory(bytes) // offline BP/stress/sugar/HRV, 3× 15-min slots
0x39 -> decodeTemperatureHistory(bytes) // offline skin temperature, 3× 5-min slots
0x40 -> decodeOxygenHistory(bytes) // offline SpO₂, 15× 1-min readings
0xB9 -> listOf(RingDecodedEvent.HistorySyncProgress(stage = "day_unavailable"))
0xF6 -> listOf(decodeFirmwareVersion(bytes))
else -> listOf(RingDecodedEvent.Unknown(commandId = packet.commandId, raw = bytes))
}
Expand Down Expand Up @@ -269,6 +273,97 @@ class RingDecoder(private val clock: JringClock? = null) {
}
}

// ── 0x55: Offline sensor history ──────────────────────────────────────

/**
* The ring's own every-15-minutes log of its estimates, from the vendor SDK's 0x55 branch
* (`BluetoothLeService`, `str3 == "55"` → `onGetAdvSensorOfflineData`):
*
* [0] 0x55, [1..4] slot time (u32 LE, the ring's local-wall-clock epoch, see [JringClock]),
* then three slots of five bytes at 5, 10, 15:
* systolic, diastolic, stress, blood sugar (mmol/L × 10), HRV.
* Slot n is 15 minutes after slot 0.
*
* The vendor app stores BP only when both halves are non-zero and every other value only when
* non-zero (`DupMainActivity.onGetAdvSensorOfflineData`), with no other change; so do we.
* These are the same figures the live 0x24 measurement returns, so they are estimates, and
* the UI labels them as such.
*/
private fun decodeSensorHistory(bytes: ByteArray): List<RingDecodedEvent> {
if (bytes.size < 20) return listOf(unknown(0x55, bytes))
val base = ringDate(u32le(bytes, 1).toLong())
return buildList {
for (slot in 0 until 3) {
val o = 5 + slot * 5
val at = base.plusSeconds(slot * 15L * 60L)
val sys = bytes[o].toInt() and 0xFF
val dia = bytes[o + 1].toInt() and 0xFF
val stress = bytes[o + 2].toInt() and 0xFF
val sugar = bytes[o + 3].toInt() and 0xFF
val hrv = bytes[o + 4].toInt() and 0xFF
if (sys > 0 && dia > 0) {
add(RingDecodedEvent.HistoryMeasurement(MeasurementKind.BLOOD_PRESSURE_SYSTOLIC, sys.toDouble(), at))
add(RingDecodedEvent.HistoryMeasurement(MeasurementKind.BLOOD_PRESSURE_DIASTOLIC, dia.toDouble(), at))
}
if (stress > 0) add(RingDecodedEvent.HistoryMeasurement(MeasurementKind.STRESS, stress.toDouble(), at))
if (sugar > 0) add(RingDecodedEvent.HistoryMeasurement(MeasurementKind.BLOOD_SUGAR, (sugar / 10.0) * 18.016, at))
if (hrv > 0) add(RingDecodedEvent.HistoryMeasurement(MeasurementKind.HRV, hrv.toDouble(), at))
}
// A frame of empty slots still belongs to the stream: say so, so it isn't logged as
// `unknown` and exported in clear (AGENTS.md, diagnostics masking).
if (isEmpty()) add(RingDecodedEvent.HistorySyncProgress(stage = "sensor_history"))
}
}

// ── 0x39: Offline temperature ─────────────────────────────────────────

/**
* The vendor SDK's "39" branch → `onGetDataByDay(12, t, surface, body)`:
* `[1..4]` slot time (ring-local epoch), then three 5-minute slots of four bytes at 5, 9, 13:
* surface temperature (u16 LE, °C × 100) and body temperature (u16 LE, °C × 100).
*
* Only the surface value is stored, as [MeasurementKind.TEMPERATURE]: that is what the card
* shows for every other ring (skin temperature). The "body" figure is the ring's own model of
* core temperature, a second estimate on top of the first, and is left out. Out of 25–45 °C
* (0 included) means no reading.
*/
private fun decodeTemperatureHistory(bytes: ByteArray): List<RingDecodedEvent> {
if (bytes.size < 20) return listOf(unknown(0x39, bytes))
val base = ringDate(u32le(bytes, 1).toLong())
return buildList {
for (slot in 0 until 3) {
val o = 5 + slot * 4
val surface = ((bytes[o].toInt() and 0xFF) or ((bytes[o + 1].toInt() and 0xFF) shl 8)) / 100.0
if (surface in 25.0..45.0) add(RingDecodedEvent.HistoryMeasurement(
MeasurementKind.TEMPERATURE, surface, base.plusSeconds(slot * 300L),
))
}
if (isEmpty()) add(RingDecodedEvent.HistorySyncProgress(stage = "temperature_history"))
}
}

// ── 0x40: Offline SpO₂ ────────────────────────────────────────────────

/**
* The vendor SDK's "40" branch → `onGetOxygenOfflineData(t, value)`: `[1..4]` slot time
* (ring-local epoch), then fifteen one-minute readings at bytes 5–19, one byte each, percent.
* The vendor keeps 1–100 (`FragmentMain`, type 13); we keep 70–100, the band used for every
* other ring's SpO₂, so a stray low byte can't read as a desaturation.
*/
private fun decodeOxygenHistory(bytes: ByteArray): List<RingDecodedEvent> {
if (bytes.size < 20) return listOf(unknown(0x40, bytes))
val base = ringDate(u32le(bytes, 1).toLong())
return buildList {
for (i in 0 until 15) {
val v = bytes[5 + i].toInt() and 0xFF
if (v in 70..100) add(RingDecodedEvent.HistoryMeasurement(
MeasurementKind.SPO2, v.toDouble(), base.plusSeconds(i * 60L),
))
}
if (isEmpty()) add(RingDecodedEvent.HistorySyncProgress(stage = "oxygen_history"))
}
}

// ── 0x3F: SpO₂ Result ─────────────────────────────────────────────────

private fun decodeSpo2Result(bytes: ByteArray, now: Instant): RingDecodedEvent {
Expand Down Expand Up @@ -317,9 +412,16 @@ class RingDecoder(private val clock: JringClock? = null) {

// ── 0x20: Capability Bitmask ─────────────────────────────────────────

private fun decodeBandFunction(bytes: ByteArray): RingDecodedEvent {
if (bytes.size < 2) return unknown(0x20, bytes)
return RingDecodedEvent.BandFunction(JringBandCapabilities(bytes.copyOfRange(1, bytes.size)))
private fun decodeBandFunction(bytes: ByteArray): List<RingDecodedEvent> {
if (bytes.size < 2) return listOf(unknown(0x20, bytes))
val caps = JringBandCapabilities(bytes.copyOfRange(1, bytes.size))
// A unit that sets bit 10 has a temperature log the app can read (0x39), so it gets the
// card; the family baseline leaves TEMPERATURE out because most of these rings don't.
val reported = buildSet { if (caps.hasTemperature) add(WearableCapability.TEMPERATURE) }
return listOfNotNull(
RingDecodedEvent.BandFunction(caps),
reported.takeIf { it.isNotEmpty() }?.let { RingDecodedEvent.SupportFunctions(it) },
)
}

// ── Helpers ───────────────────────────────────────────────────────────
Expand Down
Loading
Loading