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
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ computes them from the profile (`0x02`) and a cuff reference (`0x33`, default 12
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".
in the vendor's order, and then the workouts the ring recorded in sport mode (`0x25`). Those are
offered on the Activity tab and added on a tap, like another device's workouts (`RingWorkoutLog`).
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"

Expand Down
2 changes: 2 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -2092,6 +2092,7 @@
"Zoom in": "Aproximar",
"Zoom out": "Afastar",
"a {0} fits.": "cabe um(a) {0}.",
"about {0} kcal": "cerca de {0} kcal",
"above": "acima",
"above {0}": "acima de {0}",
"adjusted by your accuracy check": "ajustado pela sua verificação de precisão",
Expand Down Expand Up @@ -2168,6 +2169,7 @@
"workouts": "treinos",
"workouts a week": "treinos por semana",
"your limit of {0}": "seu limite de {0}",
"your ring": "seu anel",
"{0} % of {1} min on the same stage": "{0} % de {1} min no mesmo estágio",
"{0} % same stage": "{0} % no mesmo estágio",
"{0} (Tailscale)": "{0} (Tailscale)",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ object DiagnosticsRedactor {
private val HEALTH_KINDS = setOf(
"activity", "activity_bucket", "hr_sample", "spo2_progress", "spo2_result",
"sleep_timeline", "history_measurement", "stress_sample", "hrv_sample", "temperature_sample",
"sport_telemetry", "spot_vital_sample", "spot_vital_no_reading", "realtime_stop_ack",
"sport_telemetry", "ring_workout_minute", "unused_health_frame", "spot_vital_sample", "spot_vital_no_reading", "realtime_stop_ack",
// A live vital result outside its plausible band: no reading, but the byte is still a value.
"rejected_vital_result",
// Half of a frame still being reassembled (RingDecodedEvent.FramePending). Masked because
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/com/pulseloop/ring/JringDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ class JringSyncEngine(
historySync.sensorHistory = event.capabilities.hasPressureHistory
historySync.oxygenHistory = event.capabilities.hasOxygenOfflineHistory
historySync.temperatureHistory = event.capabilities.hasTemperature
historySync.workoutHistory = true
}
else -> {}
}
Expand Down
16 changes: 14 additions & 2 deletions app/src/main/java/com/pulseloop/ring/JringHistorySync.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@ class JringHistorySync(

/** 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 }
private enum class Leg { ACTIVITY, HEART_RATE, TEMPERATURE, OXYGEN, SENSOR, WORKOUTS }

/** Workouts recorded on the ring (0x25, `getMultipleSportData(day)`), the vendor's last request
* of each day. The vendor asks unconditionally; the driver turns this on once the ring has
* answered 0x20, so a ring that never does isn't asked for logs it may not keep. */
@Volatile var workoutHistory: Boolean = false

/** Offline skin temperature (0x39, `getDataByDay(12, day)`), gated on 0x20 bit 10. */
@Volatile var temperatureHistory: Boolean = false
Expand Down Expand Up @@ -140,11 +145,13 @@ class JringHistorySync(
// 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_WORKOUTS -> if (leg == Leg.WORKOUTS) restartSettle()
OPCODE_WORKOUTS_END -> if (leg == Leg.WORKOUTS) advance()
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()
if (holdsLastSlot(data, slots = 3, stepMinutes = 15)) nextLegAfter(Leg.SENSOR) else restartSettle()
}
}
}
Expand Down Expand Up @@ -185,6 +192,7 @@ class JringHistorySync(
Leg.TEMPERATURE to temperatureHistory,
Leg.OXYGEN to oxygenHistory,
Leg.SENSOR to sensorHistory,
Leg.WORKOUTS to workoutHistory,
)
val next = optional.firstOrNull { (l, on) -> on && l.ordinal > done.ordinal }?.first
if (next == null) { advance(); return }
Expand All @@ -193,6 +201,7 @@ class JringHistorySync(
writer?.enqueue(when (next) {
Leg.TEMPERATURE -> encoder.makeTemperatureHistoryQueryCommand(dayOffset = day)
Leg.OXYGEN -> encoder.makeOxygenHistoryQueryCommand(dayOffset = day)
Leg.WORKOUTS -> encoder.makeRingWorkoutQueryCommand(dayOffset = day)
else -> encoder.makeSensorHistoryQueryCommand(dayOffset = day)
})
armStall()
Expand Down Expand Up @@ -258,6 +267,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_WORKOUTS = 0x25
/** `A5 FF`: the day's workout minutes are done (`onGetMultipleSportData(0, …)`). */
private const val OPCODE_WORKOUTS_END = 0xA5
private const val OPCODE_TEMPERATURE = 0x39
private const val OPCODE_OXYGEN = 0x40
private const val OPCODE_DAY_FAILED = 0xB9
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/pulseloop/ring/PulseEventBus.kt
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ sealed class PulseEvent {
/** The ring's on-finger / skin-contact state changed. `worn == false` ⇒ an optical spot
* measurement can't produce a reading, so the coordinator fast-fails it (issue #29). */
data class WearState(val worn: Boolean) : PulseEvent()
/** A minute of a workout the ring recorded itself (jring `0x25`), kept by [com.pulseloop.service.RingWorkoutLog]. */
data class RingWorkoutMinute(val sportType: Int, val value: Int, val timestampMs: Long) : PulseEvent()
}

enum class RingConnectionState { IDLE, SCANNING, CONNECTING, CONNECTED, DISCONNECTED, RECONNECTING, FAILED }
Expand Down
25 changes: 25 additions & 0 deletions app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ sealed class RingDecodedEvent {
is HeartRateSample -> this._timestamp
is HeartRateComplete -> this._timestamp
is SportTelemetry -> this._timestamp
is RingWorkoutMinute -> this._timestamp
is UnusedHealthFrame -> Instant.EPOCH
is Spo2Progress -> this._timestamp
is Spo2Result -> this._timestamp
is Spo2Complete -> this._timestamp
Expand Down Expand Up @@ -171,6 +173,29 @@ sealed class RingDecodedEvent {
* [HeartRateSample] when it is plausible; a warm-up frame carries bpm 0 but still carries the
* workout's live step count, distance and calories, which must not reach a report in clear.
*/
/**
* One minute of a workout the ring recorded in its own sport mode (jring `0x25`).
* [sportType] is the vendor's sport index (1 walk, 2 run, 3 cycling, …); [value] is steps for
* walk, run and climb and calories ÷ 10 for every other sport, as the vendor reads it.
*/
/** A health-bearing frame we recognise but don't use (jring `0x13`). Named so diagnostics
* mask it rather than export it whole as `unknown`. */
data class UnusedHealthFrame(val commandId: UByte) : RingDecodedEvent() {
override val kind = "unused_health_frame"
override val confidence = DecodeConfidence.PARTIAL
override val debugJSON = """{"cmd":$commandId}"""
}

data class RingWorkoutMinute(
val sportType: Int,
val value: Int,
val _timestamp: Instant,
) : RingDecodedEvent() {
override val kind = "ring_workout_minute"
override val confidence = DecodeConfidence.KNOWN
override val debugJSON = """{"sportType":$sportType}"""
}

data class SportTelemetry(
val bpm: Int,
val _timestamp: Instant
Expand Down
47 changes: 47 additions & 0 deletions app/src/main/java/com/pulseloop/ring/RingDecoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ class RingDecoder(private val clock: JringClock? = null) {
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"))
0x25 -> decodeRingWorkouts(bytes) // sport-mode minutes, 6 per frame
// The vendor parses 0x13 as onGetCurSportData(1, …) and its handler then drops every
// call but type 0 (`DupMainActivity.onGetCurSportData`), so its fields mean nothing we
// can rely on. Named, not imported: undecoded it was logged `unknown` and exported whole.
0x13 -> listOf(RingDecodedEvent.UnusedHealthFrame(commandId = 0x13u))
0xA5 -> listOf(RingDecodedEvent.HistorySyncProgress(stage = "ring_workouts_done"))
0xF6 -> listOf(decodeFirmwareVersion(bytes))
else -> listOf(RingDecodedEvent.Unknown(commandId = packet.commandId, raw = bytes))
}
Expand Down Expand Up @@ -243,6 +249,8 @@ class RingDecoder(private val clock: JringClock? = null) {
val fatigue = bytes[5].toInt() and 0xFF
val stress = if (bytes.size > 6) bytes[6].toInt() and 0xFF else 0
val bloodSugarRaw = if (bytes.size > 7) bytes[7].toInt() and 0xFF else 0
// byte[8] is HRV (vendor `onReceiveSensorData` i8, stored as type 19 when > 0).
val hrv = if (bytes.size > 8) bytes[8].toInt() and 0xFF else 0

if (hr > 0) add(RingDecodedEvent.HeartRateSample(bpm = hr, _timestamp = now))
if (systolic > 0 || diastolic > 0) add(RingDecodedEvent.HistoryMeasurement(
Expand All @@ -264,6 +272,11 @@ class RingDecoder(private val clock: JringClock? = null) {
_timestamp = now,
))
if (stress > 0) add(RingDecodedEvent.StressSample(value = stress, _timestamp = now))
if (hrv in 10..200) add(RingDecodedEvent.HistoryMeasurement(
kind_field = MeasurementKind.HRV,
value = hrv.toDouble(),
_timestamp = now,
))
// Blood sugar: byte[7] = mmol/L × 10 → store mg/dL = (raw / 10) × 18.016
if (bloodSugarRaw > 0) add(RingDecodedEvent.HistoryMeasurement(
kind_field = MeasurementKind.BLOOD_SUGAR,
Expand Down Expand Up @@ -315,6 +328,40 @@ class RingDecoder(private val clock: JringClock? = null) {
}
}

// ── 0x25: Workouts recorded on the ring ───────────────────────────────

/**
* The vendor SDK's "25" branch → `onGetMultipleSportData(1, time, type, value)`, rebuilt from
* a decompile jadx marks as "decompiled incorrectly", so the layout is read from the arithmetic:
*
* [1..4] the first minute (u32 LE, ring-local epoch); six one-minute slots of two bytes at
* 5, 7, 9, 11, 13, 15. For slot i with bytes (lo, hi):
* - sport type = (lo & 0x0F) | high nibble, the high nibbles packed in bytes 17–19:
* slot 0 `b17 & 0xF0`, slot 1 `(b17 & 0x0F) << 4`, slot 2 `b18 & 0xF0`,
* slot 3 `(b18 & 0x0F) << 4`, slot 4 `b19 & 0xF0`, slot 5 `(b19 & 0x0F) << 4`;
* - value = (hi << 4) + (lo >> 4), 12 bits.
*
* Type 0 is a minute outside any workout (the vendor's +100 maps it to 100, which it skips).
* `A5 FF` ends the day.
*/
private fun decodeRingWorkouts(bytes: ByteArray): List<RingDecodedEvent> {
if (bytes.size < 20) return listOf(unknown(0x25, bytes))
val base = ringDate(u32le(bytes, 1).toLong())
val packed = intArrayOf(bytes[17].toInt() and 0xFF, bytes[18].toInt() and 0xFF, bytes[19].toInt() and 0xFF)
return buildList {
for (i in 0 until 6) {
val lo = bytes[5 + i * 2].toInt() and 0xFF
val hi = bytes[6 + i * 2].toInt() and 0xFF
val p = packed[i / 2]
val high = if (i % 2 == 0) p and 0xF0 else (p and 0x0F) shl 4
val type = (lo and 0x0F) or high
val value = (hi shl 4) + (lo shr 4)
if (type in 1..139) add(RingDecodedEvent.RingWorkoutMinute(type, value, base.plusSeconds(i * 60L)))
}
if (isEmpty()) add(RingDecodedEvent.HistorySyncProgress(stage = "ring_workouts"))
}
}

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

/**
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/pulseloop/ring/RingEncoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ object RingEncoder {
* only when 0x20 bit 81 (`FUNCTION_HAS_OXYGEN_OFFLINE`) is set. */
fun makeOxygenHistoryQueryCommand(dayOffset: Int = 0): ByteArray = dayQuery(0x40, dayOffset)

/** Workouts the ring recorded in sport mode, one day (0x25): `getMultipleSportData(day)`
* (`BluetoothLeService.e(int)`: `bArr[0] = 37`). The vendor's last request of each day. */
fun makeRingWorkoutQueryCommand(dayOffset: Int = 0): ByteArray = dayQuery(0x25, dayOffset)

private fun dayQuery(opcode: Int, dayOffset: Int): ByteArray {
val cmd = ByteArray(20)
cmd[0] = opcode.toByte()
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/com/pulseloop/ring/RingEventBridge.kt
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ object RingEventBridge {
// Sport telemetry is a diagnostics marker; its bpm arrives as its own HeartRateSample.
is RingDecodedEvent.SportTelemetry -> emptyList()

is RingDecodedEvent.UnusedHealthFrame -> emptyList()

is RingDecodedEvent.RingWorkoutMinute ->
listOf(PulseEvent.RingWorkoutMinute(decoded.sportType, decoded.value, decoded._timestamp.toEpochMilli()))

is RingDecodedEvent.TimeSyncAck, is RingDecodedEvent.CommandAck, is RingDecodedEvent.Unknown ->
emptyList()

Expand Down
9 changes: 7 additions & 2 deletions app/src/main/java/com/pulseloop/service/ActivityDetection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,11 @@ object ActivityDetection {
val external = runCatching { OtherDeviceWorkouts.proposals(OtherDeviceWorkouts.read(c, from, now)) }
.getOrDefault(emptyList())
.map { it.copy(features = ActivityClassifier.features(it.startAt, it.endAt, recentSteps, recentHr, quiet ?: 60.0, hrMax)) }
val proposals = external + OtherDeviceWorkouts.withoutOverlaps(activities, external) +
// Workouts the ring recorded itself, unless another device recorded the same time.
val ringRecorded = OtherDeviceWorkouts.withoutOverlaps(RingWorkoutLog.proposals(c, from, now), external)
.map { it.copy(features = ActivityClassifier.features(it.startAt, it.endAt, recentSteps, recentHr, quiet ?: 60.0, hrMax)) }
val recorded = external + ringRecorded
val proposals = recorded + OtherDeviceWorkouts.withoutOverlaps(activities, recorded) +
(if (quiet != null) naps(recentHr, buckets, quiet, zone) else emptyList())
val sessions = db.activitySessionDao().recent(50).map { it.startedAt..(it.endedAt ?: it.startedAt) }
return open(proposals, sessions + nights, answered(c)).sortedByDescending { it.startAt }
Expand All @@ -283,7 +287,8 @@ suspend fun ActivityDetection.accept(c: Context, db: PulseLoopDatabase, p: Activ
val tag = JournalInsights.Tag.NAP.key
db.journalDao().upsert(com.pulseloop.data.entity.JournalEntryEntity(com.pulseloop.data.entity.JournalEntryEntity.idFor(day, tag), day, tag))
} else if (p.external != null) {
// Keeps the Health Connect id, so the export never writes it back under PulseLoop's name.
// Keeps the record's own id: an `hc-` one (another app's) is skipped by the export, so it
// is never written back under PulseLoop's name; a `ring-` one is the user's ring and is exported.
if (db.activitySessionDao().byId(p.external.id) == null) {
val session = com.pulseloop.data.entity.ActivitySessionEntity(
id = p.external.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,8 @@ class EventPersistenceSubscriber(
is PulseEvent.SpotVitalNoReading -> {}
is PulseEvent.RealtimeStreamStopped -> {}
is PulseEvent.WearState -> {} // Product orchestration only (fast-fail a measure); not persisted.
// Offered on the Activity tab, added on a tap (ActivityDetection); kept until then.
is PulseEvent.RingWorkoutMinute -> RingWorkoutLog.record(context, event.sportType, event.value, event.timestampMs)
// Both persisted by DiagnosticsSubscriber, which also stamps and bounds them.
is PulseEvent.RawPacket -> {}
is PulseEvent.Diagnostic -> {}
Expand Down
Loading
Loading