Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1386,6 +1386,13 @@ Rules a change must keep:
shifted bounds or a changed guess must not resurface a dismissed stretch.
- **Steps and heart stretches merge into one window** (`mergeActive`), so a run is never also
offered as cardio.
- **Another device's workouts are suggestions too** (`OtherDeviceWorkouts`): read from Health
Connect with a ring paired, never PulseLoop's own package, accepted under their `hc-` id so the
export skips them, and they win over a ring guess for the same time. Off while Health Connect is
the data source (that importer already brings them in).
- **The heart rule is built for a 5-minute grid** (`heartSessions`): it survives a 12-minute dip
and needs three raised readings and a raised average. Don't go back to ending a stretch on one
low reading: that is what split strength sessions into pieces too short to count.
- **Notify once, recent only** (`ActivityDetectionNotifier`): after a sync's `done`, for
activity ending in the last 12 h, never twice for the same stretch, behind its own switch and
channel. Today shows the newest as one line; the Activity tab's card is where it is answered.
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@
"All models from {0} ({1})": "Todos os modelos de {0} ({1})",
"All three hold. LAM is about 98% effective only while all three do.": "As três condições valem. A LAM tem cerca de 98% de eficácia somente enquanto as três valerem.",
"All-day heart rate": "Frequência cardíaca o dia todo",
"Allow": "Permitir",
"Allow Bluetooth access": "Permitir acesso ao Bluetooth",
"Allow access": "Permitir acesso",
"Allow background access so imports also run while PulseLoop is closed.": "Permita o acesso em segundo plano para que as importações também rodem com o PulseLoop fechado.",
Expand Down Expand Up @@ -850,6 +851,7 @@
"Idle": "Inativo",
"Idle between syncs": "Ocioso entre sincronizações",
"Idle · {0}%": "Inativo · {0}%",
"If a watch or another app records your workouts in Health Connect, PulseLoop can offer them here to add with a tap.": "Se um relógio ou outro app registra seus treinos no Health Connect, o PulseLoop pode oferecê-los aqui para adicionar com um toque.",
"If your watch syncs through an app like Health Sync, check that it's set to write to Health Connect.": "Se o seu relógio sincroniza por um app como o Health Sync, verifique se ele está configurado para gravar no Health Connect.",
"Image attachments": "Anexos de imagem",
"Imperial": "Imperial",
Expand Down Expand Up @@ -1383,6 +1385,7 @@
"Recompute": "Recalcular",
"Reconnect last ring": "Reconectar último anel",
"Record activity": "Registrar atividade",
"Recorded by {0}": "Registrado por {0}",
"Recording a workout needs the Physical activity permission. You can allow it in Android Settings › Apps › PulseLoop › Permissions.": "Gravar um treino precisa da permissão de Atividade física. Você pode permitir em Configurações do Android › Apps › PulseLoop › Permissões.",
"Records": "Registros",
"Recovery index": "Índice de recuperação",
Expand Down Expand Up @@ -1961,6 +1964,7 @@
"Workout not found": "Treino não encontrado",
"Workouts": "Treinos",
"Workouts / week": "Treinos / semana",
"Workouts from your other devices": "Treinos dos seus outros dispositivos",
"Worth a look": "Vale olhar",
"Write Actions": "Ações de escrita",
"YESTERDAY": "ONTEM",
Expand Down
83 changes: 71 additions & 12 deletions app/src/main/java/com/pulseloop/service/ActivityDetection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@ import java.time.ZoneId
*/
object ActivityDetection {

/** A workout another app saved to Health Connect: its record id (`hc-…`) and the app's name. */
data class External(val id: String, val app: String)

data class Proposal(
val kind: Kind, val startAt: Long, val endAt: Long, val detail: String,
/** Every activity type, most likely first (ActivityClassifier); empty for a nap. */
val guesses: List<String> = emptyList(),
/** What the guess was made from, kept with the user's answer so later guesses learn. */
val features: ActivityClassifier.Features? = null,
/** Set when another device recorded this workout (OtherDeviceWorkouts), not the ring's guess. */
val external: External? = null,
) {
enum class Kind { WALK, RUN, CARDIO, NAP }
/** The selected type: the classifier's first choice, else the kind's own. */
Expand Down Expand Up @@ -67,29 +72,61 @@ object ActivityDetection {
}

/**
* Cardio without many steps (cycling, a gym session): at least 20 minutes of readings at 40 %
* or more of heart-rate reserve above the user's quiet level, with gaps of at most 15 minutes.
* Cardio without many steps (cycling, a gym session), read off an all-day grid of a reading
* every few minutes:
* - a stretch starts at a reading at or above [ENTER_SHARE] of heart-rate reserve above the
* user's quiet level, and keeps going through lower readings (rest between sets) for up to
* [DIP_MS] after the last raised one;
* - it ends after [DIP_MS] with nothing raised, or a gap of more than [GAP_MS] in readings;
* - it counts when it spans 20 minutes or more, holds at least three raised readings, and its
* readings average at least [MEAN_SHARE] of reserve, so one high reading in a calm hour
* isn't a workout.
* The old rule (40 % of reserve, ended by any single lower reading) split a strength session
* into pieces too short to count.
*/
fun heartSessions(hr: List<Pair<Long, Double>>, quiet: Double, hrMax: Double): List<Proposal> {
val threshold = quiet + 0.4 * (hrMax - quiet)
val reserve = (hrMax - quiet).coerceAtLeast(1.0)
val enter = quiet + ENTER_SHARE * reserve
val meanFloor = quiet + MEAN_SHARE * reserve
val out = mutableListOf<Proposal>()
var start: Long? = null; var last = 0L; var peak = 0.0
var start: Long? = null
var lastRaised = 0L; var lastSeen = 0L; var raised = 0; var peak = 0.0
val inStretch = mutableListOf<Double>()
fun close() {
val s = start ?: return
if (last - s >= 20 * 60_000L) out += Proposal(Proposal.Kind.CARDIO, s, last, trf("Heart rate up to {0} bpm", peak.toInt()))
start = null; peak = 0.0
val s = start
if (s != null) {
// Readings after the last raised one are the cool-down, not the workout.
val mean = inStretch.average()
if (lastRaised - s >= 20 * 60_000L && raised >= 3 && mean >= meanFloor) {
out += Proposal(Proposal.Kind.CARDIO, s, lastRaised, trf("Heart rate up to {0} bpm", peak.toInt()))
}
}
start = null; raised = 0; peak = 0.0; inStretch.clear()
}
for ((t, bpm) in hr.sortedBy { it.first }) {
if (bpm >= threshold) {
if (start != null && t - last > 15 * 60_000L) close()
if (start != null && (t - lastSeen > GAP_MS || t - lastRaised > DIP_MS)) close()
if (bpm >= enter) {
if (start == null) start = t
last = t; peak = maxOf(peak, bpm)
} else if (start != null && t - last > 5 * 60_000L) close()
lastRaised = t; raised++; peak = maxOf(peak, bpm)
inStretch += bpm
} else if (start != null) {
inStretch += bpm
}
lastSeen = t
}
close()
return out
}

/** Share of heart-rate reserve that starts or extends a raised stretch. */
const val ENTER_SHARE = 0.30
/** Share of reserve a whole stretch must average. */
const val MEAN_SHARE = 0.25
/** How long a stretch survives lower readings (a rest between sets). */
const val DIP_MS = 12 * 60_000L
/** A longer silence in readings ends it: the ring wasn't measuring. */
const val GAP_MS = 15 * 60_000L

/**
* Naps: between 11:00 and 19:00, at least 25 minutes where heart rate stays at or below the
* user's quiet level and the ring counted (almost) no steps.
Expand Down Expand Up @@ -227,7 +264,12 @@ object ActivityDetection {
).joinToString(" · ")
Proposal(kind, w.first, w.last, detail, guesses, f)
}
val proposals = activities + (if (quiet != null) naps(recentHr, buckets, quiet, zone) else emptyList())
// Workouts another device recorded win over the ring's guess for the same time.
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) +
(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 @@ -240,6 +282,23 @@ suspend fun ActivityDetection.accept(c: Context, db: PulseLoopDatabase, p: Activ
val day = Instant.ofEpochMilli(p.startAt).atZone(zone).toLocalDate().atStartOfDay(zone).toInstant().toEpochMilli()
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.
if (db.activitySessionDao().byId(p.external.id) == null) {
val session = com.pulseloop.data.entity.ActivitySessionEntity(
id = p.external.id,
type = type,
statusRaw = "finished",
startedAt = p.startAt,
endedAt = p.endAt,
notes = trf("Recorded by {0}", p.external.app),
useGps = false,
)
val summarized = ActivityAggregates.recompute(db, session)
db.activitySessionDao().upsert(summarized)
ActivityRollup.credit(db, summarized)
}
p.features?.let { learn(c, it, type) }
} else {
ManualActivityService.create(db, type, p.startAt, p.minutes.toDouble(), notes = tr("Detected by PulseLoop and confirmed"))
// The answer teaches the next guess for a stretch like this one.
Expand Down
110 changes: 110 additions & 0 deletions app/src/main/java/com/pulseloop/service/OtherDeviceWorkouts.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package com.pulseloop.service

import android.content.Context
import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.ExerciseSessionRecord
import androidx.health.connect.client.request.ReadRecordsRequest
import androidx.health.connect.client.time.TimeRangeFilter
import com.pulseloop.health.HealthConnectAvailability
import com.pulseloop.health.HealthConnectSdk
import com.pulseloop.health.source.HealthConnectSource
import com.pulseloop.ui.i18n.trf
import java.time.Instant

/**
* Workouts another device or app saved to Health Connect (a watch, Strava, Samsung Health), offered
* on the Activity tab as suggestions, with a ring paired too. The other device knew a workout was
* happening, so its type and times beat any guess from the ring's 5-minute heart-rate grid.
*
* Rules, each of which fails silently if broken:
* - **PulseLoop's own records are never read back.** Its exported workouts come back from Health
* Connect under its own package, which is filtered out here.
* - **Nothing is saved without a tap**, like every detection (AGENTS.md "Detected workouts").
* - **An accepted one keeps the `hc-` id** ([HealthConnectSource.WORKOUT_ID_PREFIX]), so the
* export skips it (`WorkoutExporter`) and it is never written back under PulseLoop's name.
* - **Off while Health Connect is the data source**: that mode already imports these workouts.
*/
object OtherDeviceWorkouts {

data class Found(
/** `hc-` + the Health Connect record id: the session id if accepted. */
val id: String,
val type: String,
val startAt: Long,
val endAt: Long,
/** The app that wrote it, as the user knows it ("Galaxy Wearable"). */
val app: String,
)

val READ: String = HealthPermission.getReadPermission(ExerciseSessionRecord::class)

/** What the Activity tab asks for: the read, and background reading so a sync can notify. */
val REQUEST: Set<String> = setOf(READ, HealthPermission.PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND)

/** Whether reading can work at all on this phone right now (Health Connect there, not in source mode). */
fun applies(c: Context): Boolean =
!HealthConnectSource.isEnabled(c) && HealthConnectSdk.availability(c) == HealthConnectAvailability.AVAILABLE

suspend fun granted(c: Context): Boolean = applies(c) && runCatching {
READ in HealthConnectClient.getOrCreate(c).permissionController.getGrantedPermissions()
}.getOrDefault(false)

/** Workouts in [from]..[to] written by any app but PulseLoop. Empty when not allowed or unavailable. */
suspend fun read(c: Context, from: Long, to: Long): List<Found> {
if (!granted(c)) return emptyList()
val client = HealthConnectClient.getOrCreate(c)
val out = mutableListOf<Found>()
var token: String? = null
var pages = 0
do {
val response = client.readRecords(
ReadRecordsRequest(
ExerciseSessionRecord::class,
TimeRangeFilter.between(Instant.ofEpochMilli(from), Instant.ofEpochMilli(to)),
pageSize = 200, pageToken = token,
),
)
response.records.forEach { r ->
val pkg = r.metadata.dataOrigin.packageName
if (pkg != c.packageName && r.endTime > r.startTime) {
out += Found(
id = HealthConnectSource.WORKOUT_ID_PREFIX + r.metadata.id,
type = HealthConnectSource.workoutType(r.exerciseType),
startAt = r.startTime.toEpochMilli(),
endAt = r.endTime.toEpochMilli(),
app = HealthConnectSource.label(c, pkg),
)
}
}
token = response.pageToken
pages++
} while (token != null && pages < 5)
return out
}

/** Suggestions for [found], each offering its own type first. Pure, for tests. */
fun proposals(found: List<Found>): List<ActivityDetection.Proposal> = found
.filter { it.endAt - it.startAt >= 5 * 60_000L }
.map { f ->
ActivityDetection.Proposal(
kind = when (f.type) {
"walk" -> ActivityDetection.Proposal.Kind.WALK
"run" -> ActivityDetection.Proposal.Kind.RUN
else -> ActivityDetection.Proposal.Kind.CARDIO
},
startAt = f.startAt,
endAt = f.endAt,
detail = trf("Recorded by {0}", f.app),
guesses = listOf(f.type) + ActivityClassifier.TYPES.filter { it != f.type },
external = ActivityDetection.External(f.id, f.app),
)
}

/**
* Ring-detected stretches that overlap a workout another device recorded are dropped: the
* device's own record is the better answer for the same time.
*/
fun withoutOverlaps(detected: List<ActivityDetection.Proposal>, external: List<ActivityDetection.Proposal>) =
detected.filter { d -> external.none { e -> e.startAt < d.endAt && d.startAt < e.endAt } }
}
46 changes: 46 additions & 0 deletions app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,51 @@ private fun ActivityRecordsCard(
private const val ACTIVITY_RECORDS_PAGE_SIZE = 50


/**
* One quiet row, once: let PulseLoop read workouts another device saved to Health Connect, so they
* are offered here (OtherDeviceWorkouts). Hidden when granted, dismissed, or not applicable.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun OtherDeviceWorkoutsPrompt(onGranted: () -> Unit) {
val context = androidx.compose.ui.platform.LocalContext.current
val prefs = remember { context.getSharedPreferences("activity_detection", android.content.Context.MODE_PRIVATE) }
var dismissed by remember { mutableStateOf(prefs.getBoolean("otherDevicesDismissed", false)) }
var tick by remember { mutableIntStateOf(0) }
val show by produceState(false, tick, dismissed) {
value = !dismissed && com.pulseloop.service.OtherDeviceWorkouts.applies(context) &&
!com.pulseloop.service.OtherDeviceWorkouts.granted(context)
}
val launcher = rememberLauncherForActivityResult(
androidx.health.connect.client.PermissionController.createRequestPermissionResultContract(),
) { granted ->
tick++
if (com.pulseloop.service.OtherDeviceWorkouts.READ in granted) onGranted()
}
if (!show) return
Column(
Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card)
.border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(tr("Workouts from your other devices"), style = com.pulseloop.ui.theme.PulseType.title, color = PulseColors.textPrimary)
Text(
tr("If a watch or another app records your workouts in Health Connect, PulseLoop can offer them here to add with a tap."),
style = com.pulseloop.ui.theme.PulseType.body,
color = PulseColors.textSecondary,
)
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
PulseButton(PulseButtonStyle.Tonal, onClick = { launcher.launch(com.pulseloop.service.OtherDeviceWorkouts.REQUEST) }) {
Text(tr("Allow"))
}
PulseButton(PulseButtonStyle.Text, onClick = {
dismissed = true
prefs.edit().putBoolean("otherDevicesDismissed", true).apply()
}) { Text(tr("Not now")) }
}
}
}

/**
* Workouts and naps the ring's data suggests, waiting for the user's answer. Nothing is recorded
* until they confirm; a discard is remembered so the same stretch isn't offered again.
Expand All @@ -940,6 +985,7 @@ private fun DetectedActivityCard() {
val proposals by produceState<List<com.pulseloop.service.ActivityDetection.Proposal>>(emptyList(), tick) {
value = runCatching { com.pulseloop.service.ActivityDetection.load(context, db) }.getOrDefault(emptyList())
}
OtherDeviceWorkoutsPrompt(onGranted = { tick++ })
if (proposals.isEmpty()) return
Column(
Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card)
Expand Down
Loading
Loading