diff --git a/AGENTS.md b/AGENTS.md index e749ec9b..9ee1e4cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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" diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 0709b123..dc7b0d65 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -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", @@ -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)", diff --git a/app/src/main/java/com/pulseloop/diagnostics/DiagnosticsRedactor.kt b/app/src/main/java/com/pulseloop/diagnostics/DiagnosticsRedactor.kt index 409f97b4..a1f58827 100644 --- a/app/src/main/java/com/pulseloop/diagnostics/DiagnosticsRedactor.kt +++ b/app/src/main/java/com/pulseloop/diagnostics/DiagnosticsRedactor.kt @@ -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 diff --git a/app/src/main/java/com/pulseloop/ring/JringDriver.kt b/app/src/main/java/com/pulseloop/ring/JringDriver.kt index 5ebd1df4..261caaa3 100644 --- a/app/src/main/java/com/pulseloop/ring/JringDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/JringDriver.kt @@ -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 -> {} } diff --git a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt index 55400993..f2861e1e 100644 --- a/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt +++ b/app/src/main/java/com/pulseloop/ring/JringHistorySync.kt @@ -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 @@ -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() } } } @@ -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 } @@ -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() @@ -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 diff --git a/app/src/main/java/com/pulseloop/ring/PulseEventBus.kt b/app/src/main/java/com/pulseloop/ring/PulseEventBus.kt index 4c67857e..153ec4d9 100644 --- a/app/src/main/java/com/pulseloop/ring/PulseEventBus.kt +++ b/app/src/main/java/com/pulseloop/ring/PulseEventBus.kt @@ -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 } diff --git a/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt b/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt index dd813a1b..71761777 100644 --- a/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt +++ b/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt @@ -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 @@ -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 diff --git a/app/src/main/java/com/pulseloop/ring/RingDecoder.kt b/app/src/main/java/com/pulseloop/ring/RingDecoder.kt index 167ddc98..7065105e 100644 --- a/app/src/main/java/com/pulseloop/ring/RingDecoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingDecoder.kt @@ -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)) } @@ -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( @@ -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, @@ -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 { + 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 ───────────────────────────────────────── /** diff --git a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt index 1c402dff..b4b9fd24 100644 --- a/app/src/main/java/com/pulseloop/ring/RingEncoder.kt +++ b/app/src/main/java/com/pulseloop/ring/RingEncoder.kt @@ -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() diff --git a/app/src/main/java/com/pulseloop/ring/RingEventBridge.kt b/app/src/main/java/com/pulseloop/ring/RingEventBridge.kt index 0811a193..ba2bf5dd 100644 --- a/app/src/main/java/com/pulseloop/ring/RingEventBridge.kt +++ b/app/src/main/java/com/pulseloop/ring/RingEventBridge.kt @@ -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() diff --git a/app/src/main/java/com/pulseloop/service/ActivityDetection.kt b/app/src/main/java/com/pulseloop/service/ActivityDetection.kt index 81a33177..7755388d 100644 --- a/app/src/main/java/com/pulseloop/service/ActivityDetection.kt +++ b/app/src/main/java/com/pulseloop/service/ActivityDetection.kt @@ -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 } @@ -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, diff --git a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt index 508cf7df..87e3dabf 100644 --- a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt +++ b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt @@ -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 -> {} diff --git a/app/src/main/java/com/pulseloop/service/RingWorkoutLog.kt b/app/src/main/java/com/pulseloop/service/RingWorkoutLog.kt new file mode 100644 index 00000000..4ca3fc59 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/RingWorkoutLog.kt @@ -0,0 +1,110 @@ +package com.pulseloop.service + +import android.content.Context +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import org.json.JSONObject + +/** + * Workouts the ring recorded in its own sport mode (jring `0x25`, see `RingDecoder.decodeRingWorkouts`), + * offered on the Activity tab like another device's workouts and added on a tap (AGENTS.md + * "Detected workouts": nothing reaches Health Connect or Strava without one). + * + * The ring sends them a minute at a time, so the minutes are kept here (by minute, idempotent on + * re-sync) and grouped into sessions when the tab asks. Only the last [KEEP_DAYS] days are kept: + * the ring re-sends what it still holds, and an accepted workout lives on as a recorded activity. + * Device-derived and re-syncable, so it is not in the backup archive. + */ +object RingWorkoutLog { + + private const val PREFS = "ring_workouts" + private const val KEY = "minutes" + private const val KEEP_DAYS = 10L + private const val DAY_MS = 86_400_000L + /** A pause of up to this many minutes stays inside one workout. */ + private const val MAX_GAP_MIN = 3 + private const val MIN_MINUTES = 3 + + data class Session(val sportType: Int, val startAt: Long, val endAt: Long, val total: Int) + + @Synchronized + fun record(c: Context, sportType: Int, value: Int, atMs: Long) { + val prefs = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val json = runCatching { JSONObject(prefs.getString(KEY, "{}") ?: "{}") }.getOrDefault(JSONObject()) + val minute = atMs / 60_000L * 60_000L + json.put(minute.toString(), "$sportType:$value") + val cutoff = System.currentTimeMillis() - KEEP_DAYS * DAY_MS + json.keys().asSequence().toList().forEach { k -> if ((k.toLongOrNull() ?: 0L) < cutoff) json.remove(k) } + prefs.edit().putString(KEY, json.toString()).apply() + } + + @Synchronized + fun minutes(c: Context): List> { + val raw = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, "{}") ?: "{}" + val json = runCatching { JSONObject(raw) }.getOrDefault(JSONObject()) + return json.keys().asSequence().mapNotNull { k -> + val parts = json.optString(k).split(':') + val t = k.toLongOrNull() ?: return@mapNotNull null + val type = parts.getOrNull(0)?.toIntOrNull() ?: return@mapNotNull null + Triple(t, type, parts.getOrNull(1)?.toIntOrNull() ?: 0) + }.sortedBy { it.first }.toList() + } + + /** Runs of the same sport with pauses of at most [MAX_GAP_MIN] minutes. Pure, for tests. */ + fun sessions(minutes: List>): List { + val out = mutableListOf() + var cur: MutableList>? = null + fun close() { + val run = cur ?: return + if (run.size >= MIN_MINUTES) out += Session(run.first().second, run.first().first, run.last().first + 60_000L, run.sumOf { it.third }) + cur = null + } + for (m in minutes.sortedBy { it.first }) { + val last = cur?.last() + if (last != null && (m.second != last.second || m.first - last.first > (MAX_GAP_MIN + 1) * 60_000L)) close() + val run = cur ?: mutableListOf>().also { cur = it } + run.add(m) + } + close() + return out + } + + /** The PulseLoop type for a vendor sport index (the vendor's 139-name list, 1-based). */ + fun typeFor(sportType: Int): String = when (sportType) { + 1, 125 -> "walk" + 2, 38, 74, 90, 91, 115, 122 -> "run" + 3, 57, 58, 114 -> "cycle" + 4, 64, 87, 123, 124 -> "hike" + 14, 77, 83 -> "yoga" + 59, 60, 61, 62, 63, 108 -> "dance" + 48, 106 -> "squash" + 10, 17, 18, 22, 25, 44, 69, 70, 71, 72, 73, 75, 80, 81, 82, 110, 111, 112, 113, 116 -> "gym" + 6, 7, 8, 9, 11, 13, 15, 16, 19, 20, 21, 23, 24, 26, 45, 46, 47, 49, 50, 51, 52, 53, 54, 55, + 85, 94, 97, 126, 127, 128, 129, 130, 131 -> "sport" + else -> "other" + } + + /** Walk, run and climb carry steps per minute; every other sport carries calories ÷ 10. */ + fun countsSteps(sportType: Int): Boolean = sportType == 1 || sportType == 2 || sportType == 4 + + /** Suggestions for the Activity tab, in [from]..[to]. */ + fun proposals(c: Context, from: Long, to: Long): List = + sessions(minutes(c)).filter { it.endAt > from && it.startAt < to }.map { s -> + val type = typeFor(s.sportType) + val amount = if (countsSteps(s.sportType)) tr("%,d steps").format(s.total) + else trf("about {0} kcal", s.total * 10) + val ring = tr("your ring") + ActivityDetection.Proposal( + kind = when (type) { + "walk" -> ActivityDetection.Proposal.Kind.WALK + "run" -> ActivityDetection.Proposal.Kind.RUN + else -> ActivityDetection.Proposal.Kind.CARDIO + }, + startAt = s.startAt, + endAt = s.endAt, + detail = listOf(trf("Recorded by {0}", ring), amount).joinToString(" · "), + guesses = listOf(type) + ActivityClassifier.TYPES.filter { it != type }, + external = ActivityDetection.External("ring-${s.startAt}", ring), + ) + } +} diff --git a/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt b/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt index 2950433c..a5a30281 100644 --- a/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt +++ b/app/src/test/java/com/pulseloop/ring/JringHistorySyncTest.kt @@ -339,4 +339,19 @@ class JringHistorySyncTest { ) sync.cancel() } + + @Test + fun `the ring's workout log is the day's last request and A5 ends it`() = runBlocking { + val writer = FakeWriter() + val sync = makeSync(writer, settleMs = 40) + sync.workoutHistory = true + sync.start(listOf(1, 0)) + sync.noteFrame(activityFrame()); delay(120) + sync.noteFrame(hrFinishedFrame()) + assertEquals(listOf(0x10 to 1, 0x16 to 1, 0x25 to 1), writer.requests) + sync.noteFrame(ByteArray(20).also { it[0] = 0x25 }) + sync.noteFrame(ByteArray(20).also { it[0] = 0xA5.toByte(); it[1] = 0xFF.toByte() }) + assertEquals(listOf(0x10 to 1, 0x16 to 1, 0x25 to 1, 0x10 to 0), writer.requests) + sync.cancel() + } } diff --git a/app/src/test/java/com/pulseloop/ring/JringRingWorkoutTest.kt b/app/src/test/java/com/pulseloop/ring/JringRingWorkoutTest.kt new file mode 100644 index 00000000..cac692ba --- /dev/null +++ b/app/src/test/java/com/pulseloop/ring/JringRingWorkoutTest.kt @@ -0,0 +1,63 @@ +package com.pulseloop.ring + +import com.pulseloop.service.RingWorkoutLog +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.Instant +import java.util.TimeZone + +/** + * Workouts the ring recorded in sport mode (0x25), rebuilt from the vendor SDK's "25" branch + * (`onGetMultipleSportData(1, time, type, value)`), and grouped into sessions by [RingWorkoutLog]. + */ +class JringRingWorkoutTest { + private val clock = JringClock(TimeZone.getTimeZone("UTC"), Instant.parse("2026-11-11T12:00:00Z")) + private val decoder = RingDecoder(clock) + + /** Encode six (type, value) slots the way the ring does. */ + private fun frame(epoch: Long, slots: List>): ByteArray = ByteArray(20).also { f -> + f[0] = 0x25 + for (b in 0 until 4) f[1 + b] = ((epoch shr (8 * b)) and 0xFF).toByte() + val packed = IntArray(3) + slots.forEachIndexed { i, (type, value) -> + f[5 + i * 2] = (((value and 0x0F) shl 4) or (type and 0x0F)).toByte() + f[6 + i * 2] = ((value shr 4) and 0xFF).toByte() + val high = type and 0xF0 + packed[i / 2] = packed[i / 2] or (if (i % 2 == 0) high else high shr 4) + } + for (k in 0 until 3) f[17 + k] = packed[k].toByte() + } + + private fun minutes(events: List) = events.filterIsInstance() + + @Test fun decodesTypeAcrossBothNibblesAndTwelveBitValue() { + val t = 1_794_394_800L + // 113 = 0x71: low nibble in the slot, high nibble packed in byte 17-19. Value 1234 = 0x4D2. + val out = minutes(decoder.decode(frame(t, listOf(113 to 1234, 2 to 95, 0 to 0, 0 to 0, 0 to 0, 6 to 7)))) + assertEquals(listOf(113, 2, 6), out.map { it.sportType }) + assertEquals(listOf(1234, 95, 7), out.map { it.value }) + assertEquals(listOf(0L, 60L, 300L), out.map { it._timestamp.epochSecond - t }) + } + + @Test fun anIdleFrameIsNotUnknown() { + val events = decoder.decode(frame(1_794_394_800L, List(6) { 0 to 0 })) + assertTrue(events.none { it is RingDecodedEvent.Unknown }) + } + + @Test fun minutesGroupIntoSessionsAndShortPausesStayInside() { + val m = 60_000L + val t0 = 1_794_394_800_000L + val mins = (0 until 10).map { Triple(t0 + it * m, 2, 120) } + // 10 min run + (12 until 20).map { Triple(t0 + it * m, 2, 120) } + // 2-min pause: same run + (30 until 40).map { Triple(t0 + it * m, 6, 5) } + // badminton later + listOf(Triple(t0 + 50 * m, 1, 30)) // one stray minute + val s = RingWorkoutLog.sessions(mins) + assertEquals(2, s.size) + assertEquals(2, s[0].sportType); assertEquals(18 * 120, s[0].total) + assertEquals(t0 + 20 * m, s[0].endAt) + assertEquals("run", RingWorkoutLog.typeFor(2)) + assertEquals("sport", RingWorkoutLog.typeFor(s[1].sportType)) + assertTrue(RingWorkoutLog.countsSteps(2) && !RingWorkoutLog.countsSteps(6)) + } +} diff --git a/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt b/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt index 61d25202..d4480eba 100644 --- a/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt +++ b/app/src/test/java/com/pulseloop/ring/JringSensorHistoryTest.kt @@ -98,4 +98,17 @@ class JringSensorHistoryTest { assertEquals(setOf(WearableCapability.TEMPERATURE), granted) assertTrue(WearableCapability.TEMPERATURE in JringCoordinator.bitmapGatedCapabilities) } + + @Test fun spotMeasurementKeepsItsHrvByte() { + val f = ByteArray(20).also { it[0] = 0x24; it[1] = 70; it[2] = 118; it[3] = 76; it[8] = 42 } + val hrv = history(decoder.decode(f)).filter { it.kind_field == MeasurementKind.HRV } + assertEquals(listOf(42.0), hrv.map { it.value }) + } + + @Test fun the0x13FrameIsNamedSoDiagnosticsMaskIt() { + val raw = ByteArray(20) + "139ca0f46abe010000cc0600007017".chunked(2).forEachIndexed { i, h -> raw[i] = h.toInt(16).toByte() } + val events = decoder.decode(raw) + assertEquals("unused_health_frame", events.single().kind) + } } diff --git a/docs/jring-56ff-plan.md b/docs/jring-56ff-plan.md index 275306e2..4d042a4b 100644 --- a/docs/jring-56ff-plan.md +++ b/docs/jring-56ff-plan.md @@ -79,6 +79,34 @@ Temperature is therefore granted per unit from the `0x20` reply (`bitmapGatedCap Only the surface (skin) value is stored. The "body" value is the ring's own model of core temperature, so we leave it out. +**Workouts recorded on the ring (`0x25`)** are the vendor's last request of each day +(`getMultipleSportData(day)`). +- **Frame:** a timestamp, then six one-minute slots. Each slot's sport type is split into a low + nibble in the slot and a high nibble packed into bytes 17–19. +- **Value:** 12 bits per slot. It is steps for walk, run and climb, and calories ÷ 10 for every + other sport (`FragmentMain`, types 101/102/104). +- **End:** `A5 FF` ends the day. +- **The parser is reconstructed:** jadx marks it "decompiled incorrectly", so the layout comes from + its arithmetic. `JringRingWorkoutTest` round-trips it, and it still needs a hardware capture. + +In PulseLoop, `RingWorkoutLog` keeps the minutes for 10 days and groups them into sessions: the +same sport, pauses of 3 minutes or less, and 3 or more minutes long. The Activity tab offers them +like another device's workouts: "Recorded by your ring", one tap to add, and a `ring-` id that the +export does send. PulseLoop never starts the ring's sport mode itself, so these can't duplicate its +own recordings. + +**What else the vendor parses.** Every reply opcode the SDK handles was checked against +PulseLoop's decoder (2026-11-11). Two changes came out of it: +- **`0x24` byte 8 is HRV.** The vendor stores it as type 19 when it is above 0; PulseLoop now + keeps it, in 10–200 ms. +- **`0x13`** arrives about every sync. The SDK parses it as `onGetCurSportData(1, …)`, but the + app's handler drops everything except type 0, so its fields have no reliable meaning. It is + named `unused_health_frame` so diagnostics mask it. Before this, it was exported whole as + `unknown`. + +The rest are settings acknowledgements, ECG (bit 9, not set on the owner's ring), or watch-only +features (dials, contacts, AI, Wi-Fi). There is nothing left to import. + 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. @@ -284,8 +312,8 @@ statistics. Independent of BP and glucose; listed so the "everything about this ring" pass is in one place. -1. **HRV from the spot measurement.** The decoder comment says `0x24` byte 8 is HRV, and nothing - reads it. Decode it as `HistoryMeasurement(HRV)` when > 0 and plausible (10–200 ms). It's an +1. **HRV from the spot measurement.** Done in 2.16.3: `0x24` byte 8 is decoded as HRV (10–200 ms). + Before that, the decoder comment said byte 8 was HRV and nothing read it. Decode it as `HistoryMeasurement(HRV)` when > 0 and plausible (10–200 ms). It's an occasional spot value, not a nightly series, so it won't fill Readiness' HRV balance on its own. Confirm the byte against a capture first. 2. **Denser all-day heart rate.**