From b88541123acddb937396afdc452e8a76e4d1b787 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 22:15:28 +0000 Subject: [PATCH 1/4] Jring: import the ring's 15-minute BP/stress/sugar/HRV log; calibration on the detail screens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From the JRing 2.0.8 decompile: the app passes the ring's BP and sugar through unchanged. The ring computes them from the profile (0x02) and a cuff reference (0x33, write-only, default 120/80). The ring also logs those estimates every 15 minutes (0x55, gated on 0x20 bit 83, which the vendor builds LSB first). JringHistorySync now asks for it as the third step per day, after heart rate, and ends a past day on its 23:45 slot. RingDecoder.decodeSensorHistory stores BP only when both halves are set and every other value only when non-zero, as the vendor does. The BP and glucose detail screens gain a Calibration card: what the estimate is calibrated against, and a button to Settings → Calibration. TodayViewModel no longer adds the cuff reference to BP readings; it is a reference the ring uses, not an offset. Findings recorded in docs/jring-56ff-plan.md and AGENTS.md. Tests for the decoder and the new pager step. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 6 ++ app/src/main/assets/i18n/pt-BR.json | 4 + .../java/com/pulseloop/ring/JringDriver.kt | 9 +- .../com/pulseloop/ring/JringHistorySync.kt | 49 +++++++++- .../java/com/pulseloop/ring/RingDecoder.kt | 43 +++++++++ .../java/com/pulseloop/ring/RingEncoder.kt | 12 +++ .../java/com/pulseloop/ui/PulseLoopApp.kt | 1 + .../java/com/pulseloop/ui/screens/Screens.kt | 49 ++++++++++ .../com/pulseloop/ui/viewmodels/ViewModels.kt | 7 +- .../pulseloop/ring/JringHistorySyncTest.kt | 56 +++++++++++ .../pulseloop/ring/JringSensorHistoryTest.kt | 59 ++++++++++++ ...1-11-v2.16.2-calibration-sensor-history.md | 94 +++++++++++++++++++ docs/jring-56ff-plan.md | 66 ++++++++++++- 13 files changed, 444 insertions(+), 11 deletions(-) create mode 100644 app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt create mode 100644 audits/2026-11-11-v2.16.2-calibration-sensor-history.md diff --git a/AGENTS.md b/AGENTS.md index 0e3d4f81..1a9aeb79 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,6 +78,12 @@ 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, and is imported as the third step per day in +`JringHistorySync`. 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 diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index e9d01d36..0709b123 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -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", @@ -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.", diff --git a/app/src/main/java/com/pulseloop/ring/JringDriver.kt b/app/src/main/java/com/pulseloop/ring/JringDriver.kt index e1d2b428..aa820dcd 100644 --- a/app/src/main/java/com/pulseloop/ring/JringDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/JringDriver.kt @@ -125,8 +125,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() { @@ -193,7 +193,10 @@ 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 + } else -> {} } } diff --git a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt index da0e3773..b2d5f8ff 100644 --- a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt +++ b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt @@ -34,7 +34,8 @@ 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) → `0x55/offset` when the ring keeps an offline sensor log + * ([sensorHistory]) → its 23:45 slot (or 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`. * @@ -53,8 +54,16 @@ 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. */ + private enum class Leg { ACTIVITY, HEART_RATE, SENSOR } + + /** + * 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() private var currentDay: Int? = null @@ -111,9 +120,15 @@ 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) endHeartRateLeg() 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 (lastSlotOfDay(data)) advance() else restartSettle() + } } } @@ -143,14 +158,35 @@ class JringHistorySync( armStall() } + /** The day's heart rate is done: its sensor log next if the ring keeps one, else next day. */ + private fun endHeartRateLeg() { + val day = currentDay ?: return + if (!sensorHistory) { advance(); return } + cancelTimers() + leg = Leg.SENSOR + writer?.enqueue(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() + Leg.HEART_RATE -> endHeartRateLeg() + Leg.SENSOR -> advance() } } + /** Whether a 0x55 frame holds the 23:45 slot, read in the ring's own local clock. */ + private fun lastSlotOfDay(data: ByteArray): 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 + // Three slots per frame, 15 minutes apart. + return (0 until 3).any { minuteOfDay + it * 15 == LAST_SLOT_MINUTE } + } + // MARK: - Timers /** Data arrived: the stall no longer applies, and the quiet period starts over. */ @@ -193,6 +229,9 @@ 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 + /** 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 } diff --git a/app/src/main/java/com/pulseloop/ring/RingDecoder.kt b/app/src/main/java/com/pulseloop/ring/RingDecoder.kt index cbc01d90..3f28e36a 100644 --- a/app/src/main/java/com/pulseloop/ring/RingDecoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingDecoder.kt @@ -57,6 +57,7 @@ class RingDecoder(private val clock: JringClock? = null) { 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 0xF6 -> listOf(decodeFirmwareVersion(bytes)) else -> listOf(RingDecodedEvent.Unknown(commandId = packet.commandId, raw = bytes)) } @@ -269,6 +270,48 @@ 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 { + 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")) + } + } + // ── 0x3F: SpO₂ Result ───────────────────────────────────────────────── private fun decodeSpo2Result(bytes: ByteArray, now: Instant): RingDecodedEvent { diff --git a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt index e34b61ee..a555b7be 100644 --- a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt @@ -87,6 +87,18 @@ object RingEncoder { cmd[1] = dayOffset.coerceIn(0, 27).toByte() return cmd } + /** + * Offline sensor history for one day (0x55), the vendor SDK's `getAdvSensorOfflineData(day)` + * (`BluetoothLeService.c(int)`: `bArr[0] = 85; bArr[1] = day`). Same day offset as 0x10/0x16. + * The vendor asks for it only when the 0x20 capability bit 83 (`FUNCTION_HAS_PRESSURE`) is set, + * after the day's heart rate. The reply layout is in `RingDecoder.decodeSensorHistory`. + */ + fun makeSensorHistoryQueryCommand(dayOffset: Int = 0): ByteArray { + val cmd = ByteArray(20) + cmd[0] = 0x55 + cmd[1] = dayOffset.coerceIn(0, 27).toByte() + return cmd + } fun makeHeartRateStartCommand(): ByteArray = hexToBytes("14b4000000000000000000000000000000000000") fun makeHeartRateStopCommand(): ByteArray = hexToBytes("1500000000000000000000000000000000000000") /** diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index 6f79dd4f..5491de4d 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -956,6 +956,7 @@ fun PulseLoopApp() { onBack = { navController.popBackStack() }, db = db, apiKeyStore = apiKeyStore, + onCalibrate = { navController.navigate("settings/calibration") { launchSingleTop = true } }, ) } paddedComposable("onboarding") { diff --git a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt index 0a358529..1fd02f65 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -673,6 +673,8 @@ fun VitalDetailScreen( onBack: () -> Unit, db: com.pulseloop.data.PulseLoopDatabase, apiKeyStore: com.pulseloop.settings.ApiKeyStore? = null, + /** Opens Settings → Calibration; BP and glucose point there from their detail screen. */ + onCalibrate: (() -> Unit)? = null, ) { val context = LocalContext.current val units = apiKeyStore?.resolvedUnitSystem ?: com.pulseloop.settings.UnitSystem.METRIC @@ -930,11 +932,58 @@ fun VitalDetailScreen( if (!(metric == "stress" && state.isDerived)) { metricDisclaimer(metric, state.isDerived)?.let { disclaimer -> item { DisclaimerCard(disclaimer) } } } + // 8. The calibration these estimates are read against, and the way to change it. + if ((metric == "bp" || metric == "glucose") && onCalibrate != null && apiKeyStore != null) { + item { CalibrationStatusCard(metric, apiKeyStore, gUnit, onCalibrate) } + } } } } } +/** + * What the BP or glucose estimate is calibrated against, read from the stored calibration, and a + * button to Settings → Calibration. The ring itself can't be asked: its 0x33 reply is only an + * acknowledgement (vendor `onSetBPAdjust(1)`), so the app's stored reference, which it sends on + * every connect, is the calibration there is to show. Glucose has no ring-side calibration at all; + * its offset is applied by the app at display time. + */ +@Composable +private fun CalibrationStatusCard( + metric: String, + store: com.pulseloop.settings.ApiKeyStore, + gUnit: com.pulseloop.service.GlucoseUnit, + onCalibrate: () -> Unit, +) { + val status = if (metric == "bp") { + val s = store.bpAdjustSystolic + val d = store.bpAdjustDiastolic + if (s > 0 && d > 0) trf("Calibrated to your cuff reading of {0}/{1} mmHg. The ring adjusts its estimates to it.", s, d) + else tr("Not calibrated. Enter a reading from a validated cuff so the ring adjusts its estimates to you.") + } else { + val ref = store.glucoseRefMgdl + if (ref > 0) { + val shown = if (gUnit == com.pulseloop.service.GlucoseUnit.MMOL) "%.1f mmol/L".format(ref / 18.0182) + else "%.0f mg/dL".format(ref) + trf("Calibrated to your meter reading of {0}. The app shifts the ring's estimate to match it.", shown) + } else tr("Not calibrated. Enter a meter or lab reading to shift the ring's estimate to match it.") + } + Column( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(PulseColors.card) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text(tr("Calibration"), style = com.pulseloop.ui.theme.PulseType.eyebrow) + Text(status, style = MaterialTheme.typography.bodyMedium, color = PulseColors.textPrimary) + PulseButton(onClick = onCalibrate, style = PulseButtonStyle.Tonal, modifier = Modifier.fillMaxWidth()) { + Text(tr("Calibrate")) + } + } +} + /** The amber "this is an estimate" card (BP, glucose, derived stress). */ @Composable private fun DisclaimerCard(disclaimer: String) { diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index 7d66a485..0694699f 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -197,8 +197,11 @@ class TodayViewModel(db: PulseLoopDatabase, private val apiKeyStore: ApiKeyStore try { val sys = db.measurementDao().latest(MeasurementKind.BLOOD_PRESSURE_SYSTOLIC.name) val dia = db.measurementDao().latest(MeasurementKind.BLOOD_PRESSURE_DIASTOLIC.name) - val systolic = sys?.toInt()?.plus(apiKeyStore?.bpAdjustSystolic ?: 0) - val diastolic = dia?.toInt()?.plus(apiKeyStore?.bpAdjustDiastolic ?: 0) + // The stored cuff values are a *reference* the ring calibrates against + // (0x33, sent on connect), not an offset: adding them here turned 117/73 into + // 237/153 once someone calibrated. The ring's reading is already adjusted. + val systolic = sys?.toInt() + val diastolic = dia?.toInt() _state.update { if (it.bloodPressureSystolic == systolic && it.bloodPressureDiastolic == diastolic) it else it.copy( diff --git a/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt b/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt index c7c33dd4..f006e572 100644 --- a/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt +++ b/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt @@ -263,4 +263,60 @@ class JringHistorySyncTest { ) sync.cancel() } + + // ── 0x55 offline sensor log (BP, stress, sugar, HRV) ───────────────── + + /** A 0x55 frame whose first slot is at [minuteOfDay] in the ring's local clock. */ + private fun sensorFrame(minuteOfDay: Int): ByteArray { + val epoch = 1_794_355_200L + minuteOfDay * 60L // 2026-11-11 00:00 local-as-UTC + return ByteArray(20).also { + it[0] = 0x55 + for (b in 0 until 4) it[1 + b] = ((epoch shr (8 * b)) and 0xFF).toByte() + } + } + + @Test + fun `with the sensor log on, a day's heart rate is followed by its 0x55 request`() = runBlocking { + val writer = FakeWriter() + val sync = makeSync(writer, settleMs = 50) + sync.sensorHistory = true + sync.start(listOf(1, 0)) + + sync.noteFrame(activityFrame()) + delay(150) + sync.noteFrame(hrFinishedFrame()) + assertEquals(listOf(0x10 to 1, 0x16 to 1, 0x55 to 1), writer.requests) + + // The 23:15 frame carries 23:15, 23:30 and 23:45: the day's last slot ends the leg at once. + sync.noteFrame(sensorFrame(23 * 60 + 15)) + assertEquals(listOf(0x10 to 1, 0x16 to 1, 0x55 to 1, 0x10 to 0), writer.requests) + sync.cancel() + } + + @Test + fun `an earlier 0x55 frame keeps the leg open until the stream settles`() = runBlocking { + val writer = FakeWriter() + val sync = makeSync(writer, settleMs = 80) + sync.sensorHistory = true + sync.start(listOf(0)) + sync.noteFrame(activityFrame()); delay(200) + sync.noteFrame(hrFinishedFrame()) + + sync.noteFrame(sensorFrame(9 * 60)) + delay(30) + assertTrue("still streaming", sync.isRunning) + delay(200) + assertFalse("settled: today's pass is done", sync.isRunning) + } + + @Test + fun `without the capability bit no 0x55 is sent`() = runBlocking { + val writer = FakeWriter() + val sync = makeSync(writer, settleMs = 50) + sync.start(listOf(0)) + sync.noteFrame(activityFrame()); delay(150) + sync.noteFrame(hrFinishedFrame()) + assertEquals(listOf(0x10 to 0, 0x16 to 0), writer.requests) + assertFalse(sync.isRunning) + } } diff --git a/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt b/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt new file mode 100644 index 00000000..724480fe --- /dev/null +++ b/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt @@ -0,0 +1,59 @@ +package com.pulseloop.ring + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.Instant +import java.util.TimeZone + +/** + * 0x55, the ring's every-15-minutes log of its estimates, decoded the way the vendor SDK reads it + * (`BluetoothLeService` "55" branch → `onGetAdvSensorOfflineData(ts, sys, dia, stress, sugar, hrv)`). + */ +class JringSensorHistoryTest { + // UTC−3, the owner's zone: the ring's clock holds local wall time. + private val clock = JringClock(TimeZone.getTimeZone("America/Sao_Paulo"), Instant.parse("2026-11-11T12:00:00Z")) + private val decoder = RingDecoder(clock) + + private fun frame(localEpoch: Long, vararg slots: IntArray): ByteArray = ByteArray(20).also { + it[0] = 0x55 + for (b in 0 until 4) it[1 + b] = ((localEpoch shr (8 * b)) and 0xFF).toByte() + slots.forEachIndexed { i, s -> s.forEachIndexed { j, v -> it[5 + i * 5 + j] = v.toByte() } } + } + + private fun history(events: List) = events.filterIsInstance() + + @Test fun threeSlotsFifteenMinutesApartInTrueTime() { + val local0915 = 1_794_355_200L + (9 * 60 + 15) * 60L // 2026-11-11 09:15 on the ring + val out = history(decoder.decode(frame(local0915, + intArrayOf(118, 76, 40, 55, 42), + intArrayOf(120, 78, 35, 56, 0), + intArrayOf(0, 0, 0, 0, 0), + ))) + val first = Instant.parse("2026-11-11T12:15:00Z") // 09:15 at UTC−3 + val sys = out.filter { it.kind_field == MeasurementKind.BLOOD_PRESSURE_SYSTOLIC } + assertEquals(listOf(first, first.plusSeconds(900)), sys.map { it._timestamp }) + assertEquals(listOf(118.0, 120.0), sys.map { it.value }) + val sugar = out.first { it.kind_field == MeasurementKind.BLOOD_SUGAR } + assertEquals(5.5 * 18.016, sugar.value, 1e-9) + assertEquals(1, out.count { it.kind_field == MeasurementKind.HRV }) + assertEquals(2, out.count { it.kind_field == MeasurementKind.STRESS }) + } + + @Test fun bloodPressureNeedsBothHalves() { + val out = history(decoder.decode(frame(1_794_355_200L, intArrayOf(118, 0, 0, 0, 0)))) + assertTrue(out.none { it.kind_field == MeasurementKind.BLOOD_PRESSURE_SYSTOLIC }) + } + + @Test fun anEmptyFrameIsNotUnknown() { + val events = decoder.decode(frame(1_794_355_200L)) + assertTrue(events.none { it is RingDecodedEvent.Unknown }) + } + + @Test fun queryIsOpcodeAndDayOffset() { + val cmd = RingEncoder.makeSensorHistoryQueryCommand(2) + assertEquals(0x55, cmd[0].toInt() and 0xFF) + assertEquals(2, cmd[1].toInt()) + assertEquals(20, cmd.size) + } +} diff --git a/audits/2026-11-11-v2.16.2-calibration-sensor-history.md b/audits/2026-11-11-v2.16.2-calibration-sensor-history.md new file mode 100644 index 00000000..0610ba72 --- /dev/null +++ b/audits/2026-11-11-v2.16.2-calibration-sensor-history.md @@ -0,0 +1,94 @@ +# Audit: calibration on BP/glucose detail, 0x55 sensor history (2.16.2) + +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 + +- **BP and glucose detail screens: a Calibration card.** It sits under the amber "estimate" card, + says what the estimate is calibrated against (or that it isn't), and has a tonal "Calibrate" + button to Settings → Calibration. Before this, calibration was reachable only from Settings. +- **Jring offline sensor history (`0x55`).** BP, stress, sugar and HRV every 15 minutes, imported + per day after heart rate. It feeds the existing charts; there is no new screen. +- **Bug fix.** Today's view model added the cuff reference to BP readings. No screen read those + fields. +- Sugar stays visible (owner's decision). + +## ux-user-flows (§13 flow review checklist) + +Flow: Vitals → BP card → detail → Calibration card → Calibrate → Settings → Calibration → Save → +Back returns to the detail screen, where the card now shows the new reference. + +| # | Question | Result | +|---|---|---| +| 1 | Job | "Make this estimate about me", or "what is it calibrated against?" | +| 2 | Entries | Settings → Calibration (unchanged), plus the new card on the BP and glucose detail screens | +| 3 | Happy path | Two taps from the chart to the form | +| 4 | Branches | Calibrated or not, for BP and glucose separately | +| 5 | States | Both states have their own sentence; no loading state (local prefs) | +| 6 | Errors | Unchanged: the form validates | +| 7 | Control | Back returns to the chart | +| 8 | Progress and resume | n/a | +| 9 | Memory | The card reads the stored values each time it is shown | +| 10 | Exits | Back | +| 11 | Conventions | The same tonal button and card as the other detail-screen cards | +| 12 | Speed | Two taps | +| 13 | Accessibility | Text label, 52dp button | +| 14 | Ethics | Says plainly what calibration does, and that sugar is shifted by the app, not measured | +| 15 | Evidence | The vendor-app review of 2026-11-11 (`docs/jring-56ff-plan.md`) | + +## graphic-design-fundamentals (§13 checklist) + +| # | Question | Result | +|---|---|---| +| 1 | Brief | Put the way to calibrate right next to the number it changes | +| 2 | Concept | A status line plus one action | +| 3 | Hierarchy | Eyebrow, sentence, button: placed after the amber warning, as a follow-on to it | +| 4 | Contrast | `textPrimary` on `card` | +| 5 | Alignment and grid | 16dp padding, full width like its neighbours | +| 6 | Spacing | 12dp inside the card | +| 7 | Typography | `eyebrow` and `bodyMedium`; no new sizes | +| 8 | Colour | Neutral card; tonal button (the screen's one filled accent stays the Actions button) | +| 9 | Consistency | The same card shape as the stats cards | +| 10 | Simplicity | One sentence | +| 11 | Real-size test | pt-BR sentences wrap to 2–3 lines | +| 12 | Accessibility and ergonomics | Full-width target | +| 13 | Production | No new assets | + +## impeccable (audit, native / Android) + +| # | Dimension | Score | Key finding | +|---|---|---|---| +| 1 | Accessibility | 4 | Text-only status, labelled button | +| 2 | Performance | 4 | Reads prefs once per composition | +| 3 | Appearance & theming | 4 | Tokens only | +| 4 | Platform conformance | 4 | Normal push navigation | +| 5 | Adaptivity | 4 | Inside the 720dp content cap | +| | **Total** | **20/20** | | + +No P0–P2 findings. + +## less-is-more + +| Element | Question (1–5) | Kept / moved / merged / removed, and where | +|---|---|---| +| Calibration card | 1 (does it earn its place?) | Kept: calibration was otherwise out of reach from the number it changes | +| A second "go to Settings" sentence in the amber card | 4 (can it be cut?) | Not added; the button replaces that instruction | + +| Dimension | 0–4 | +|---|---| +| Elements per screen, compared with before | +1 card, on two detail screens only | +| Duplicates left | 0 | +| Text to read when tired | 4 | +| Taps on the common actions (must not rise) | Calibrating from the chart: 2 instead of 4 | + +## Evidence + +- The pt-BR missing-key check returns `[]`. +- `JringSensorHistoryTest` and the new `JringHistorySyncTest` cases cover the `0x55` work. +- Design canvas: see the PR. + +## Verdict + +Merge. Carried forward: +- Offline SpO₂ (bit 81). +- A hardware capture of a real `0x55` stream to confirm the slot layout on the owner's ring. diff --git a/docs/jring-56ff-plan.md b/docs/jring-56ff-plan.md index a8f32dab..7c513119 100644 --- a/docs/jring-56ff-plan.md +++ b/docs/jring-56ff-plan.md @@ -1,6 +1,6 @@ # JRing (56ff) plan: estimated BP and glucose, offsets, recalibration, and the rest of the ring -Status: plan, not started. Written 2026-10-20. +Status: plan, partly built. Written 2026-10-20; vendor-app findings added 2026-11-11. The 56ff ring's combined spot measurement (`0x23` → `0x24`) returns heart rate, blood pressure, SpO₂, fatigue, stress and blood sugar in one reply. Heart rate and SpO₂ come from the optical @@ -19,6 +19,65 @@ So this plan treats both as **estimates**: written as estimates wherever they ap with a user offset, checked against real readings when the user has them, and left as they are today in the coach and the Health Connect export (decided 2026-10-20). +## What the vendor app does with BP and sugar (read 2026-11-11) + +Read from JRing 2.0.8 (`com.jaga.ibraceletplus.jyring`), decompiled locally with jadx 1.5.1 +(`decompiled-jring-offical/`, gitignored; see AGENTS.md). The question was whether the app invents +these numbers or the ring sends them. + +**The app does not fake them.** It shows exactly what the ring sends. +- The SDK hands bytes 1–8 of the `0x24` reply to `onReceiveSensorData` unchanged + (`BluetoothLeService`, the `"24"` branch). +- The app stores them as received: HR, BP pair, SpO₂, fatigue, stress, sugar ÷ 10, HRV + (`DupMainActivity.onReceiveSensorData`). +- The app's only random-number code is demo generators that nothing calls: + - fake temperature (`FragmentMain.startTest`); + - fake steps for one week in 2024 (`loadDemoTask`); + - fake sleep for 13 Oct 2025 under a made-up MAC (`loadDemoSleepTask`). + + None of them touches BP or sugar. + +**The ring computes both numbers itself, and the app supplies its inputs.** +- `0x02` user info: age, sex, height, weight (`BluetoothLeService.a0`). +- `0x33` BP reference: the vendor's "BP adjust" screen (`BpAdjustActivity`) sends a cuff value, + defaulting to **120/80** (`CommonAttributes.P_USER_BPADJUST_SBP/DBP`). + - The ring only acknowledges it (`onSetBPAdjust(1)`) and has no command that reads it back. + - The vendor applies no app-side BP offset. +- Sugar has an on/off switch (`setSugarMode`) and no calibration command. + +So BP is an estimate anchored to a reference, and sugar is a figure with no sensor behind it. +A practical check: +1. Measure twice while still. +2. Change the profile's age by 20 years. +3. Measure twice more. + +If BP or sugar moves while the body didn't, the number comes from the profile. A cuff and a +finger-prick meter settle it. We keep both, labelled as estimates (owner's decision 2026-11-11: +don't hide sugar). + +**The ring keeps an offline log of these estimates every 15 minutes (`0x55`).** +- **Request:** `getAdvSensorOfflineData(day)` = `55 `. The vendor sends it only when the + `0x20` bit 83 (`FUNCTION_HAS_PRESSURE`) is set, after the day's heart rate. +- **Reply:** `[1..4]` the slot time (u32 LE, the ring's local wall clock). Then three slots of + five bytes at 5, 10 and 15: systolic, diastolic, stress, sugar × 10, HRV. The slots are + 15 minutes apart. +- **End of day:** the vendor ends it on the 23:45 slot, or after a 2000 ms idle timer. +- **Bit order:** the vendor builds the `0x20` bit array least-significant bit first (`utils.m.b`, + masks 1…128). That confirms `JringBandCapabilities.bit()`. The owner's ring (V138) sets bit 83. + +Imported since 2.16.2 as a third step per day in `JringHistorySync` (activity/sleep → HR → `0x55`), +decoded by `RingDecoder.decodeSensorHistory`. Same rules as the vendor: BP only when both halves +are non-zero, every other value only when non-zero. + +**Device modes (`0x0E`).** The vendor's `setDeviceMode`, confirmed by the buttons that send each +mode: 2 = device off, 3 = restart, 4 = factory reset. Used since 2.16.1 (Restart ring, Factory +reset). + +**A bug this review found.** `TodayViewModel` added the stored cuff *reference* to each BP reading, +as if it were an offset. Once someone calibrated, a 117/73 reading would have come out as 237/153. +Nothing displayed those fields, so no wrong number reached the screen; fixed in 2.16.2. The +reference goes to the ring (`0x33`) and nowhere else. + ## What exists today | Piece | Where | State | @@ -27,6 +86,8 @@ are today in the coach and the Health Connect export (decided 2026-10-20). | BP cuff calibration sent to ring | `RingEncoder.makeBPAdjustCommand` (`0x33`, LE u16 sys/dia), `CalibrationSettingsScreen` | Done. Stores `bpAdjustSystolic/Diastolic`, **no date** | | Glucose offset | `ApiKeyStore.glucoseOffsetMgdl`, applied at display in `ViewModels.kt` | Done. Stored rows stay raw | | Estimate disclaimers | `Screens.kt` detail copy and amber card | Done on the detail screen only | +| Calibration shown where the estimate is | `Screens.kt` `CalibrationStatusCard` on the BP and glucose detail screens | Done (2.16.2): the stored cuff/meter reference and a button to Calibration | +| Offline BP/stress/sugar/HRV history | `0x55`, `JringHistorySync`, `RingDecoder.decodeSensorHistory` | Done (2.16.2), gated on `0x20` bit 83 | | Card quality badge | `VitalCardState`: glucose ESTIMATED / NEEDS_CALIBRATION, BP likewise | Done, but no expiry | | Health Connect export | `VitalsExporter` exports `BLOOD_SUGAR` and BP pairs | Exports ring estimates as `BloodGlucoseRecord` / `BloodPressureRecord`, raw. Kept as is by decision | | Health Connect import | `HealthConnectBodyImport` (weight, body composition) | No BP or glucose | @@ -210,6 +271,9 @@ Independent of BP and glucose; listed so the "everything about this ring" pass i ring advertises. - **Caveat:** the bit order within a byte is still unconfirmed, so nothing may depend on these bits until a capture confirms it. + - **Update 2026-11-11:** the bit order is confirmed from the vendor code (LSB first), and the + `0x55` offline sensor history is implemented (see "What the vendor app does" above). + Offline SpO₂ (bit 81, `getDataByDay(13, day)`) is still open. ## Order and size From 68aefe5aad3ce85af0e77da92fb43f2ca8b77a3f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 22:16:53 +0000 Subject: [PATCH 2/4] docs: record the jring firmware lookup (V138 is current; image is encrypted) Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- docs/jring-56ff-plan.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/docs/jring-56ff-plan.md b/docs/jring-56ff-plan.md index 7c513119..2c7a35fa 100644 --- a/docs/jring-56ff-plan.md +++ b/docs/jring-56ff-plan.md @@ -78,6 +78,27 @@ as if it were an offset. Once someone calibrated, a 117/73 reading would have co Nothing displayed those fields, so no wrong number reached the screen; fixed in 2.16.2. The reference goes to the ring (`0x33`) and nowhere else. +## Firmware (looked up 2026-11-11) + +The vendor app checks for firmware at +`http://download.keeprapid.com/apps/smartband/keepfit/fwupdater///update.json` +(`Ota.java`, `CommonAttributes.fw_upgrade_xml`). `` is the first 8 characters of the ring's +firmware string. For the owner's ring (`003A002AV138`) that is `003A002A`. The manifest says: + +- **Current version:** `003A002AV138`. That is what the ring already runs, so there is no newer + firmware. +- **File:** `fwrelease/003A002A/V138.bin`, 136,320 bytes. Its MD5 `3c797b1d…0ddf` matches the + manifest. +- **Chip:** `chipType: "dialog"`, a Dialog Semiconductor (Renesas) BLE SoC. + +The image starts with a short header (`70 61`, with "1.138" in ASCII). After that it is +**encrypted or compressed**: 7.99 bits/byte of entropy and no readable strings. So it can't be read +for its BP or sugar algorithm without the decryption key, which the app doesn't carry: OTA sends +the file as-is. A web search (2026-11-11) found no public reverse-engineering of this SDK +(`com.sxr.sdk.ble.keepfit`), the app or this firmware. + +The binary was downloaded only to check it; it is not kept in the repo. + ## What exists today | Piece | Where | State | From 5653ac7aea86db69d8d6a82ce338f2965904481b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 22:20:23 +0000 Subject: [PATCH 3/4] Fix Long/Int comparison in JringHistorySync.lastSlotOfDay Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/java/com/pulseloop/ring/JringHistorySync.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt index b2d5f8ff..a9663642 100644 --- a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt +++ b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt @@ -184,7 +184,7 @@ class JringHistorySync( ((data[3].toLong() and 0xFF) shl 16) or ((data[4].toLong() and 0xFF) shl 24) val minuteOfDay = Math.floorMod(raw, 86_400L) / 60 // Three slots per frame, 15 minutes apart. - return (0 until 3).any { minuteOfDay + it * 15 == LAST_SLOT_MINUTE } + return (0 until 3).any { minuteOfDay + it * 15L == LAST_SLOT_MINUTE.toLong() } } // MARK: - Timers From 96ba842bf6d2f485b981a5174042d8467748bc00 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 22:26:29 +0000 Subject: [PATCH 4/4] =?UTF-8?q?Jring:=20import=20offline=20SpO=E2=82=82=20?= =?UTF-8?q?(0x40)=20and=20skin=20temperature=20(0x39)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After each day's heart rate, the vendor asks for each offline log the ring advertises, in this order: temperature (bit 10, 0x39), SpO₂ (bit 81, 0x40), then the 0x55 sensor log. JringHistorySync now runs the same chain, ends a leg on the 23:45 slot or when it settles, and skips a day the ring answers with B9 ("getdayabyday failed"). - 0x40: 15 one-minute SpO₂ readings per frame, kept in the 70–100 band. - 0x39: three 5-minute slots; only the surface (skin) value is stored. The 0x20 reply now also reports TEMPERATURE when bit 10 is set, granted per unit through JringCoordinator.bitmapGatedCapabilities. The owner's ring (003A002AV138) sets bits 10, 81, 83 and 84. Tests use that ring's real reply. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 5 +- .../java/com/pulseloop/ring/JringDriver.kt | 12 ++-- .../com/pulseloop/ring/JringHistorySync.kt | 65 +++++++++++++----- .../java/com/pulseloop/ring/RingDecoder.kt | 67 +++++++++++++++++-- .../java/com/pulseloop/ring/RingEncoder.kt | 14 +++- .../pulseloop/ring/JringHistorySyncTest.kt | 20 ++++++ .../pulseloop/ring/JringSensorHistoryTest.kt | 42 ++++++++++++ ...1-11-v2.16.2-calibration-sensor-history.md | 5 +- docs/jring-56ff-plan.md | 16 ++++- 9 files changed, 214 insertions(+), 32 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1a9aeb79..e749ec9b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,8 +81,9 @@ 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, and is imported as the third step per day in -`JringHistorySync`. Details: `docs/jring-56ff-plan.md`, "What the vendor app does with BP and sugar". +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" diff --git a/app/src/main/java/com/pulseloop/ring/JringDriver.kt b/app/src/main/java/com/pulseloop/ring/JringDriver.kt index aa820dcd..5ebd1df4 100644 --- a/app/src/main/java/com/pulseloop/ring/JringDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/JringDriver.kt @@ -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 = setOf(WearableCapability.TEMPERATURE) + override val iconSystemName = "circle.hexagongrid.circle.fill" override fun makeDriver(writer: RingCommandWriter): WearableDriver = JringDriver(writer) @@ -196,6 +198,8 @@ class JringSyncEngine( is RingDecodedEvent.BandFunction -> { bandCapabilities = event.capabilities historySync.sensorHistory = event.capabilities.hasPressureHistory + historySync.oxygenHistory = event.capabilities.hasOxygenOfflineHistory + historySync.temperatureHistory = event.capabilities.hasTemperature } else -> {} } diff --git a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt index a9663642..55400993 100644 --- a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt +++ b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt @@ -34,8 +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) → `0x55/offset` when the ring keeps an offline sensor log - * ([sensorHistory]) → its 23:45 slot (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`. * @@ -54,8 +55,15 @@ class JringHistorySync( private val encoder = RingEncoder private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob()) - /** The legs of one day, in the order the vendor asks for them. */ - private enum class Leg { ACTIVITY, HEART_RATE, SENSOR } + /** 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). @@ -120,14 +128,23 @@ 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) endHeartRateLeg() + 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 (lastSlotOfDay(data)) advance() else restartSettle() + if (holdsLastSlot(data, slots = 3, stepMinutes = 15)) advance() else restartSettle() } } } @@ -158,13 +175,26 @@ class JringHistorySync( armStall() } - /** The day's heart rate is done: its sensor log next if the ring keeps one, else next day. */ - private fun endHeartRateLeg() { + /** + * 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 - if (!sensorHistory) { advance(); 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 = Leg.SENSOR - writer?.enqueue(encoder.makeSensorHistoryQueryCommand(dayOffset = day)) + leg = next + writer?.enqueue(when (next) { + Leg.TEMPERATURE -> encoder.makeTemperatureHistoryQueryCommand(dayOffset = day) + Leg.OXYGEN -> encoder.makeOxygenHistoryQueryCommand(dayOffset = day) + else -> encoder.makeSensorHistoryQueryCommand(dayOffset = day) + }) armStall() } @@ -172,19 +202,17 @@ class JringHistorySync( private fun legSettled() { when (leg) { Leg.ACTIVITY -> beginHeartRateLeg() - Leg.HEART_RATE -> endHeartRateLeg() - Leg.SENSOR -> advance() + else -> nextLegAfter(leg) } } - /** Whether a 0x55 frame holds the 23:45 slot, read in the ring's own local clock. */ - private fun lastSlotOfDay(data: ByteArray): Boolean { + /** 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 - // Three slots per frame, 15 minutes apart. - return (0 until 3).any { minuteOfDay + it * 15L == LAST_SLOT_MINUTE.toLong() } + return (0 until slots).any { minuteOfDay + it.toLong() * stepMinutes == LAST_SLOT_MINUTE.toLong() } } // MARK: - Timers @@ -230,6 +258,9 @@ class JringHistorySync( 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`). */ diff --git a/app/src/main/java/com/pulseloop/ring/RingDecoder.kt b/app/src/main/java/com/pulseloop/ring/RingDecoder.kt index 3f28e36a..167ddc98 100644 --- a/app/src/main/java/com/pulseloop/ring/RingDecoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingDecoder.kt @@ -51,13 +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)) } @@ -312,6 +315,55 @@ class RingDecoder(private val clock: JringClock? = null) { } } + // ── 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 { + 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 { + 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 { @@ -360,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 { + 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 ─────────────────────────────────────────────────────────── diff --git a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt index a555b7be..1c402dff 100644 --- a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt @@ -93,9 +93,19 @@ object RingEncoder { * The vendor asks for it only when the 0x20 capability bit 83 (`FUNCTION_HAS_PRESSURE`) is set, * after the day's heart rate. The reply layout is in `RingDecoder.decodeSensorHistory`. */ - fun makeSensorHistoryQueryCommand(dayOffset: Int = 0): ByteArray { + fun makeSensorHistoryQueryCommand(dayOffset: Int = 0): ByteArray = dayQuery(0x55, dayOffset) + + /** Offline temperature for one day (0x39): `getDataByDay(12, day)` (`BluetoothLeService.a(int,int)`: + * type 12 → `bArr[0] = 57`). Asked only when 0x20 bit 10 (`FUNCTION_TEMPERATURE`) is set. */ + fun makeTemperatureHistoryQueryCommand(dayOffset: Int = 0): ByteArray = dayQuery(0x39, dayOffset) + + /** Offline SpO₂ for one day (0x40): `getDataByDay(13, day)` (type 13 → `bArr[0] = 64`). Asked + * only when 0x20 bit 81 (`FUNCTION_HAS_OXYGEN_OFFLINE`) is set. */ + fun makeOxygenHistoryQueryCommand(dayOffset: Int = 0): ByteArray = dayQuery(0x40, dayOffset) + + private fun dayQuery(opcode: Int, dayOffset: Int): ByteArray { val cmd = ByteArray(20) - cmd[0] = 0x55 + cmd[0] = opcode.toByte() cmd[1] = dayOffset.coerceIn(0, 27).toByte() return cmd } diff --git a/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt b/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt index f006e572..2950433c 100644 --- a/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt +++ b/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt @@ -319,4 +319,24 @@ class JringHistorySyncTest { assertEquals(listOf(0x10 to 0, 0x16 to 0), writer.requests) assertFalse(sync.isRunning) } + + @Test + fun `with every offline log on, a day runs in the vendor's order`() = runBlocking { + val writer = FakeWriter() + val sync = makeSync(writer, settleMs = 40) + sync.temperatureHistory = true + sync.oxygenHistory = true + sync.sensorHistory = true + sync.start(listOf(1)) + sync.noteFrame(activityFrame()); delay(120) + sync.noteFrame(hrFinishedFrame()) + // The ring has no temperature log for that day. + sync.noteFrame(ByteArray(20).also { it[0] = 0xB9.toByte() }) + delay(120) // nothing further may go out while the SpO₂ leg waits for its first frame + assertEquals( + listOf(0x10 to 1, 0x16 to 1, 0x39 to 1, 0x40 to 1), + writer.requests, + ) + sync.cancel() + } } diff --git a/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt b/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt index 724480fe..61d25202 100644 --- a/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt +++ b/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt @@ -56,4 +56,46 @@ class JringSensorHistoryTest { assertEquals(2, cmd[1].toInt()) assertEquals(20, cmd.size) } + + // ── 0x39 offline temperature, 0x40 offline SpO₂, and the owner's 0x20 reply ── + + @Test fun temperatureKeepsSkinValuesFiveMinutesApart() { + val f = ByteArray(20).also { + it[0] = 0x39 + val t = 1_794_355_200L + 9 * 3600L + for (b in 0 until 4) it[1 + b] = ((t shr (8 * b)) and 0xFF).toByte() + fun put(o: Int, v: Int) { it[o] = (v and 0xFF).toByte(); it[o + 1] = (v shr 8).toByte() } + put(5, 3412); put(7, 3655) // slot 0: 34.12 skin, 36.55 body + put(9, 0); put(11, 0) // slot 1: no reading + put(13, 3398); put(15, 3650) // slot 2 + } + val temps = history(decoder.decode(f)).filter { it.kind_field == MeasurementKind.TEMPERATURE } + assertEquals(listOf(34.12, 33.98), temps.map { it.value }) + assertEquals(600L, temps[1]._timestamp.epochSecond - temps[0]._timestamp.epochSecond) + } + + @Test fun oxygenIsFifteenOneMinuteReadingsInBand() { + val f = ByteArray(20).also { + it[0] = 0x40 + val t = 1_794_355_200L + 2 * 3600L + for (b in 0 until 4) it[1 + b] = ((t shr (8 * b)) and 0xFF).toByte() + for (k in 0 until 15) it[5 + k] = 97.toByte() + it[5 + 3] = 0; it[5 + 4] = 12 // empty and implausible + } + val spo2 = history(decoder.decode(f)).filter { it.kind_field == MeasurementKind.SPO2 } + assertEquals(13, spo2.size) + assertEquals(14 * 60L, spo2.last()._timestamp.epochSecond - spo2.first()._timestamp.epochSecond) + } + + @Test fun ownersBandFunctionGrantsTemperature() { + // The 0x20 reply from the owner's ring (firmware 003A002AV138), 2026-11-11. + val raw = ByteArray(20) + "2062ec0738090abebb02001b".chunked(2).forEachIndexed { i, h -> raw[i] = h.toInt(16).toByte() } + val events = decoder.decode(raw) + val caps = events.filterIsInstance().single().capabilities + assertTrue(caps.hasTemperature && caps.hasOxygenOfflineHistory && caps.hasPressureHistory) + val granted = events.filterIsInstance().single().capabilities + assertEquals(setOf(WearableCapability.TEMPERATURE), granted) + assertTrue(WearableCapability.TEMPERATURE in JringCoordinator.bitmapGatedCapabilities) + } } diff --git a/audits/2026-11-11-v2.16.2-calibration-sensor-history.md b/audits/2026-11-11-v2.16.2-calibration-sensor-history.md index 0610ba72..6bcf3252 100644 --- a/audits/2026-11-11-v2.16.2-calibration-sensor-history.md +++ b/audits/2026-11-11-v2.16.2-calibration-sensor-history.md @@ -8,7 +8,9 @@ Date: 2026-11-11 · PR: see the PR linking this file · Auditor: Claude Code (th says what the estimate is calibrated against (or that it isn't), and has a tonal "Calibrate" button to Settings → Calibration. Before this, calibration was reachable only from Settings. - **Jring offline sensor history (`0x55`).** BP, stress, sugar and HRV every 15 minutes, imported - per day after heart rate. It feeds the existing charts; there is no new screen. + per day after heart rate, with offline SpO₂ (`0x40`) and skin temperature (`0x39`). They feed + the existing charts. A ring that sets the temperature bit gets the existing temperature card; + there is no new screen. - **Bug fix.** Today's view model added the cuff reference to BP readings. No screen read those fields. - Sugar stays visible (owner's decision). @@ -90,5 +92,4 @@ No P0–P2 findings. ## Verdict Merge. Carried forward: -- Offline SpO₂ (bit 81). - A hardware capture of a real `0x55` stream to confirm the slot layout on the owner's ring. diff --git a/docs/jring-56ff-plan.md b/docs/jring-56ff-plan.md index 2c7a35fa..275306e2 100644 --- a/docs/jring-56ff-plan.md +++ b/docs/jring-56ff-plan.md @@ -65,6 +65,20 @@ don't hide sugar). - **Bit order:** the vendor builds the `0x20` bit array least-significant bit first (`utils.m.b`, masks 1…128). That confirms `JringBandCapabilities.bit()`. The owner's ring (V138) sets bit 83. +**Offline SpO₂ (`0x40`) and temperature (`0x39`)** come from the same per-day chain. The vendor +asks after heart rate in this order: temperature (bit 10, `getDataByDay(12)` = `39 `), SpO₂ +(bit 81, `getDataByDay(13)` = `40 `), then the `0x55` sensor log. +- **`0x40` reply:** a slot time, then 15 one-minute readings, one byte each. +- **`0x39` reply:** a slot time, then three 5-minute slots of surface and body temperature + (u16 LE, °C × 100). +- **No data:** a ring with no log for that day answers `B9` ("getdayabyday failed"). + +The owner's ring sets bits 10, 81, 83 and 84, so it advertises all three logs. That includes +temperature, which the family's baseline leaves out because SR08-class rings don't set bit 10. +Temperature is therefore granted per unit from the `0x20` reply (`bitmapGatedCapabilities`). +Only the surface (skin) value is stored. The "body" value is the ring's own model of core +temperature, so we leave it out. + Imported since 2.16.2 as a third step per day in `JringHistorySync` (activity/sleep → HR → `0x55`), decoded by `RingDecoder.decodeSensorHistory`. Same rules as the vendor: BP only when both halves are non-zero, every other value only when non-zero. @@ -294,7 +308,7 @@ Independent of BP and glucose; listed so the "everything about this ring" pass i bits until a capture confirms it. - **Update 2026-11-11:** the bit order is confirmed from the vendor code (LSB first), and the `0x55` offline sensor history is implemented (see "What the vendor app does" above). - Offline SpO₂ (bit 81, `getDataByDay(13, day)`) is still open. + Offline SpO₂ (bit 81) and temperature (bit 10) followed in the same release. ## Order and size