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
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,12 @@ in the vendor's order, and then the workouts the ring recorded in sport mode (`0
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".

**A jring workout's heart rate is the vendor's sport mode, not its 180-second check.** `0x14` is
`setHeartRateMode`: bytes 1-4 a duration in seconds (0 = until stopped), byte 5 the sport mode.
`14 b4…` is the vendor's spot check, so workouts used to stream for three minutes. Workouts send
duration 0 and the sport's mode when `0x20` bit 56 (`FUNCTION_SPORT_FROM_APP`) is set, as
`RunRecordActivity` does. Details: `docs/jring-56ff-plan.md`, "Workout heart rate".

## Colmi/Yawell OS-bonding is a hand-curated allowlist — not "match QRing exactly"

**This is the one rule in this file most likely to get silently reverted by a future "generalize
Expand Down
17 changes: 17 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@
"Automatic backups": "Backups automáticos",
"Average": "Média",
"Average difference {0}; 95 % of differences between {1} and {2}": "Diferença média {0}; 95 % das diferenças entre {1} e {2}",
"Average heart rate": "Frequência cardíaca média",
"Averaging {0} against a need of {1}": "Média de {0} contra uma necessidade de {1}",
"Averaging {0} over {1} nights": "Média de {0} em {1} noites",
"Avg ": "Méd. ",
Expand Down Expand Up @@ -661,6 +662,7 @@
"Estimated from heart rate": "Estimado pela frequência cardíaca",
"Estimated from resting heart rate and age": "Estimado a partir da frequência cardíaca em repouso e da idade",
"Estimated from the current discharge at %.1f %%/h.": "Estimado a partir da descarga atual de %.1f %%/h.",
"Estimated from your heart rate": "Estimada pela sua frequência cardíaca",
"Estimated wellness metric": "Métrica de bem-estar estimada",
"Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is FDA-authorized to measure or estimate glucose on its own.": "Métrica de bem-estar estimada — não use para dosar medicamentos nem para decisões sobre diabetes. Nenhum anel ou relógio inteligente tem autorização da FDA para medir ou estimar glicose sozinho.",
"Estimated · calibrate with a cuff": "Estimado · calibre com um medidor de pressão",
Expand Down Expand Up @@ -819,6 +821,7 @@
"Heart rate": "Frequência cardíaca",
"Heart rate above your quiet waking {0} bpm, {1} min well above it": "Frequência cardíaca acima do seu nível tranquilo acordado de {0} bpm, {1} min bem acima",
"Heart rate at rest": "Frequência cardíaca em repouso",
"Heart rate over the workout, average {0} bpm": "Frequência cardíaca durante o treino, média de {0} bpm",
"Heart rate since last night": "Frequência cardíaca desde ontem à noite",
"Heart rate since last night: latest {0} bpm, range {1}–{2} bpm, {3} readings": "Frequência cardíaca desde ontem à noite: última {0} bpm, faixa {1}–{2} bpm, {3} leituras",
"Heart rate stayed at your quiet level with no steps": "A frequência cardíaca ficou no seu nível tranquilo, sem passos",
Expand Down Expand Up @@ -1058,6 +1061,7 @@
"Max": "Máx.",
"Max HR": "FC máx.",
"Max tokens": "Máximo de tokens",
"Maximum": "Máxima",
"Maçã": "Maçã",
"Me": "Eu",
"Meal": "Refeição",
Expand Down Expand Up @@ -1177,6 +1181,7 @@
"No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically.": "Nenhuma exportação foi feita ainda. Com a chave principal ativada e uma opção de histórico escolhida, o PulseLoop exporta automaticamente.",
"No fatigue data yet — take a measurement.": "Ainda não há dados de fadiga — faça uma medição.",
"No goal set · {0} is a typical day": "Sem meta definida · {0} é um dia típico",
"No heart rate for this workout": "Sem frequência cardíaca neste treino",
"No meals logged this week": "Nenhuma refeição registrada nesta semana",
"No night to read": "Nenhuma noite para ler",
"No nights tracked in this range yet.": "Nenhuma noite registrada neste período ainda.",
Expand Down Expand Up @@ -1427,6 +1432,7 @@
"Reading failed: {0}": "A leitura falhou: {0}",
"Reading your drinks…": "Lendo suas bebidas…",
"Reading your history…": "Lendo seu histórico…",
"Readings cover {0} of {1} min.": "As leituras cobrem {0} de {1} min.",
"Ready to start the day? Take a measurement and I'll help you plan it.": "Pronto para começar o dia? Faça uma medição e eu ajudo você a planejá-lo.",
"Ready · {0}": "Pronto · {0}",
"Reasoning effort": "Nível de raciocínio",
Expand Down Expand Up @@ -1735,6 +1741,7 @@
"Studio, cardio, or freestyle": "Aula, cardio ou livre",
"Suggested next check-in: {0}": "Próximo check-in sugerido: {0}",
"Summarize my week": "Resumir minha semana",
"Summary": "Resumo",
"Summary copied. It holds counts and timings only, no readings.": "Resumo copiado. Ele contém apenas contagens e horários, nenhuma leitura.",
"Sunday evening: your week compared with the last one, and one thing to focus on.": "Domingo à noite: sua semana comparada com a anterior e um ponto para focar.",
"Supplement": "Suplemento",
Expand Down Expand Up @@ -1817,6 +1824,7 @@
"The ring isn't detecting your finger. Put it on snugly, then try again.": "O anel não está detectando seu dedo. Coloque-o bem justo e tente novamente.",
"The ring recorded this as one record": "O anel registrou isto como um único registro",
"The ring recorded this night in {0} parts": "O anel registrou esta noite em {0} partes",
"The ring sent no readings while it was recorded. Keep the ring snug and connected during the next one.": "O anel não enviou leituras durante a gravação. No próximo, mantenha o anel justo e conectado.",
"The scan failed. Try again in a moment.": "A busca falhou. Tente novamente em instantes.",
"The share of your time in bed spent asleep. Around 85% or more is considered good.": "A parte do seu tempo na cama em que você dormiu. Cerca de 85% ou mais é considerado bom.",
"The stage mix was useful, but total sleep time was short for a full recovery window. A slightly earlier wind-down would likely improve tomorrow's score.": "A combinação de estágios foi boa, mas o tempo total de sono foi curto para uma recuperação completa. Começar a relaxar um pouco mais cedo deve melhorar a pontuação de amanhã.",
Expand Down Expand Up @@ -1858,6 +1866,7 @@
"Time": "Horário",
"Time asleep": "Tempo dormindo",
"Time for {0}": "Hora de {0}",
"Time in each zone": "Tempo em cada zona",
"Time to move": "Hora de se mexer",
"Time to wind down": "Hora de relaxar",
"Timeout (s)": "Tempo limite (s)",
Expand All @@ -1873,6 +1882,7 @@
"Tonight: {0} drink{1}": "Hoje à noite: {0} bebida{1}",
"Tool calling": "Chamada de ferramentas",
"Tools that connect over HTTP": "Ferramentas que se conectam por HTTP",
"Total calories": "Calorias totais",
"Total sleep": "Sono total",
"Total workout time this week. Health guidelines suggest at least 150 minutes of moderate activity a week.": "Tempo total de treino nesta semana. As diretrizes de saúde sugerem pelo menos 150 minutos de atividade moderada por semana.",
"Track Bedtime / DND mode": "Monitorar modo Hora de dormir / Não perturbe",
Expand All @@ -1881,6 +1891,7 @@
"Tracked {0} {1} this year": "Este ano você registrou {0} {1}",
"Trails and elevation": "Trilhas e elevação",
"Training frequency": "Frequência de treinos",
"Training load": "Carga de treino",
"Training volume": "Volume de treino",
"Travel": "Viagem",
"Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold.": "Trata uma frequência cardíaca em repouso baixa como sinal de condicionamento, e não de preocupação, e flexibiliza o limite de HR baixa.",
Expand Down Expand Up @@ -2115,6 +2126,7 @@
"Your usual {0}-day cycle would have ended {1} day{2} ago.": "Seu ciclo habitual de {0} dias teria terminado há {1} dia{2}.",
"Your week at a glance": "Sua semana num relance",
"Your workout is still recording. Finish it now, or keep recording?": "Seu treino ainda está sendo gravado. Finalizar agora ou continuar gravando?",
"Zones are shares of an estimated maximum of {0} bpm, from your age.": "As zonas são frações de uma máxima estimada de {0} bpm, pela sua idade.",
"Zoom in": "Aproximar",
"Zoom out": "Afastar",
"a {0} fits.": "cabe um(a) {0}.",
Expand All @@ -2124,6 +2136,7 @@
"adjusted by your accuracy check": "ajustado pela sua verificação de precisão",
"any meal": "qualquer refeição",
"average week": "semana média",
"avg {0}": "média {0}",
"avg {0} bpm": "média {0} bpm",
"bed {0}": "deitar {0}",
"below": "abaixo",
Expand Down Expand Up @@ -2185,6 +2198,7 @@
"the ring": "o anel",
"trending down": "em queda",
"trending up": "em alta",
"under {0}": "abaixo de {0}",
"unknown error": "erro desconhecido",
"up": "a mais",
"up {0}": "acordar {0}",
Expand All @@ -2200,6 +2214,7 @@
"{0} % same stage": "{0} % no mesmo estágio",
"{0} (Tailscale)": "{0} (Tailscale)",
"{0} / week": "{0} / semana",
"{0} active · {1} resting": "{0} ativas · {1} em repouso",
"{0} asleep": "{0} dormindo",
"{0} asleep · woke {1} times · longest stretch {2}": "{0} dormindo · acordou {1} vezes · maior trecho {2}",
"{0} at {1}.": "{0} às {1}.",
Expand Down Expand Up @@ -2298,10 +2313,12 @@
"{0}% higher over two weeks than the four before.": "{0}% mais alta nas últimas duas semanas que nas quatro anteriores.",
"{0}% of the night asleep": "{0}% da noite dormindo",
"{0}% {1} baseline": "{0}% {1} da linha de base",
"{0}+": "{0}+",
"{0}, about {1} MB": "{0}, cerca de {1} MB",
"{0}, about {1} MB. Downloads on Wi-Fi only, unless you choose mobile data.": "{0}, cerca de {1} MB. Baixa só no Wi-Fi, a menos que você escolha os dados móveis.",
"{0}, higher than your usual {1}": "{0}, acima do seu habitual de {1}",
"{0}, lower than your usual {1}": "{0}, abaixo do seu habitual de {1}",
"{0}, {1} bpm: {2} min": "{0}, {1} bpm: {2} min",
"{0}. Open PulseLoop to mark it taken or skipped.": "{0}. Abra o PulseLoop para marcar como tomado ou pulado.",
"{0}: latest {1}, range {2}–{3}, {4} readings": "{0}: última {1}, faixa {2}–{3}, {4} leituras",
"{0}d ago": "há {0}d",
Expand Down
37 changes: 37 additions & 0 deletions app/src/main/java/com/pulseloop/ring/JringDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,10 @@ class JringSyncEngine(
historySync.oxygenHistory = event.capabilities.hasOxygenOfflineHistory
historySync.temperatureHistory = event.capabilities.hasTemperature
historySync.workoutHistory = true
val pendingType = workoutActivityType
if (pendingType != null && workoutSportMode == null && event.capabilities.supportsSportFromApp) {
startWorkoutHeartRate(pendingType)
}
}
else -> {}
}
Expand All @@ -223,6 +227,39 @@ class JringSyncEngine(
writer?.enqueue(encoder.makeHeartRateStartCommand())
}

/** The sport mode a running workout stream was started with, or null when none is. */
private var workoutSportMode: Int? = null
/** The running workout's type, kept so a `0x20` reply that lands after the start (a reconnect
* mid-workout restarts the stream before the ring has re-sent its feature bits) can still
* move it onto the continuous stream. */
private var workoutActivityType: String? = null

/**
* Workout heart rate the way the vendor's run screen does it: continuous, in the sport's mode,
* when the ring sets `FUNCTION_SPORT_FROM_APP` (bit 56). A ring that hasn't answered `0x20`, or
* doesn't set the bit, keeps the old 180-second start: the vendor shows no heart rate at all
* on such a ring, so there is nothing better to match.
*/
override fun startWorkoutHeartRate(activityType: String) {
workoutActivityType = activityType
if (bandCapabilities?.supportsSportFromApp == true) {
val mode = encoder.jringSportMode(activityType)
workoutSportMode = mode
writer?.enqueue(encoder.makeWorkoutHeartRateStartCommand(mode))
} else {
workoutSportMode = null
startHeartRate()
}
}

override fun stopWorkoutHeartRate() {
workoutActivityType = null
val mode = workoutSportMode ?: return stopHeartRate()
workoutSportMode = null
writer?.enqueue(encoder.makeWorkoutHeartRateStopCommand(mode))
writer?.enqueue(encoder.makeAutomaticHeartRateCommand(enabled = true, cadenceMinutes = 30))
}

override fun stopHeartRate() {
writer?.enqueue(encoder.makeHeartRateStopCommand())
writer?.enqueue(encoder.makeAutomaticHeartRateCommand(enabled = true, cadenceMinutes = 30))
Expand Down
24 changes: 24 additions & 0 deletions app/src/main/java/com/pulseloop/ring/RingEncoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,30 @@ object RingEncoder {
}
fun makeHeartRateStartCommand(): ByteArray = hexToBytes("14b4000000000000000000000000000000000000")
fun makeHeartRateStopCommand(): ByteArray = hexToBytes("1500000000000000000000000000000000000000")

/**
* Continuous heart rate for a workout: the vendor's `setHeartRateMode(true, 0, mode)`
* (`RunRecordActivity.startHeartrateMode`). Bytes 1-4 are a duration in seconds, little-endian,
* and 0 means "until stopped". Byte 5 is the sport mode (1 walk, 2 run, 3 cycle, 4 climb,
* 5 golf/swim). [makeHeartRateStartCommand]'s `b4` is the vendor's 180-second spot check
* (`FragmentMain.startTestHeart`, `CommonAttributes.sport_situps` = 180), which is why a workout
* started with it lost its heart rate after three minutes.
*/
fun makeWorkoutHeartRateStartCommand(sportMode: Int): ByteArray =
ByteArray(20).also { it[0] = 0x14; it[5] = sportMode.toByte() }

/** Ends [makeWorkoutHeartRateStartCommand]: the vendor's `setHeartRateMode(false, 0, mode)`. */
fun makeWorkoutHeartRateStopCommand(sportMode: Int): ByteArray =
ByteArray(20).also { it[0] = 0x15; it[5] = sportMode.toByte() }

/** The vendor's sport mode for a PulseLoop activity type (`RunRecordActivity`'s mapping; any
* other type gets its default, walk). */
fun jringSportMode(activityType: String): Int = when (activityType) {
"run" -> 2
"cycle" -> 3
"hike" -> 4
else -> 1
}
/**
* One-shot combined-sensor measurement (0x23). byte[1] is a *mode* selector, not a generic
* start flag (vendor `setBloodPressureMode`/`setSpoMode` write 0x23 with a different byte[1]):
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/pulseloop/ring/RingProtocol.kt
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ data class JringBandCapabilities(val bytes: ByteArray) {
val hasOxygenOfflineHistory: Boolean get() = bit(81)
val hasPressureHistory: Boolean get() = bit(83)

/** `FUNCTION_SPORT_FROM_APP` (`DupMainActivity`, zArr[56]): the ring runs a phone-started
* workout with continuous heart rate. Without it the vendor shows no heart rate on a run. */
val supportsSportFromApp: Boolean get() = bit(56)

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is JringBandCapabilities) return false
Expand Down
10 changes: 7 additions & 3 deletions app/src/main/java/com/pulseloop/service/ActivityAggregates.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ object ActivityAggregates {
} else null
val distanceMeters = resolveDistanceMeters(session, acceptedCount, routeDistance)

val hrSamples = hrRows.map { WorkoutHeart.Sample(it.timestamp, it.value) }
val heart = WorkoutHeart.summary(hrSamples, end, profileEntity?.age)
val calories = WorkoutMetricsEngine.calories(
type = session.type,
durationSeconds = duration,
Expand All @@ -44,9 +46,11 @@ object ActivityAggregates {
return session.copy(
calories = calories,
distanceMeters = distanceMeters,
avgHeartRate = hrRows.map { it.value }.average0(),
maxHeartRate = hrRows.maxOfOrNull { it.value },
minHeartRate = hrRows.minOfOrNull { it.value },
// Weighted by time (WorkoutHeart): a second-by-second stream must not outvote the
// ring's log for the rest of the session.
avgHeartRate = heart?.average,
maxHeartRate = heart?.max,
minHeartRate = WorkoutHeart.weighted(hrSamples, end).minOfOrNull { it.bpm },
avgSpO2 = spo2Rows.map { it.value }.average0(),
latestSpO2 = spo2Rows.lastOrNull()?.value,
gpsPointCount = acceptedCount,
Expand Down
Loading
Loading