Skip to content
Open
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
10 changes: 10 additions & 0 deletions app/src/main/java/com/pulseloop/data/dao/Daos.kt
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,9 @@ interface ActivityBucketDao {
@Query("SELECT * FROM activity_buckets WHERE date = :day ORDER BY startEpoch ASC")
suspend fun byDay(day: Long): List<ActivityBucketEntity>

@Query("SELECT EXISTS(SELECT 1 FROM activity_buckets)")
suspend fun hasAny(): Boolean

/** Distinct past days that have synced buckets — the DataRepairs recompute scope. */
@Query("SELECT DISTINCT date FROM activity_buckets WHERE date < :day ORDER BY date ASC")
suspend fun daysBefore(day: Long): List<Long>
Expand Down Expand Up @@ -866,6 +869,13 @@ interface MeasurementDeletionDao {
suspend fun isSleepRecordDeleted(dayStart: Long, recordStartAt: Long): Boolean =
isDeleted(sleepRecordDeleteId(dayStart, recordStartAt))

@Query(
"SELECT timestamp FROM measurement_deletions " +
"WHERE kindRaw = 'SLEEP_RECORD_DELETE' " +
"AND measurementId LIKE 'sleep:record:' || :dayStart || ':%'",
)
suspend fun deletedSleepRecordStarts(dayStart: Long): List<Long>

companion object {
/** The prefix `EventPersistenceSubscriber.historyMeasurementId` builds its stable ids from.
* A measurement whose id starts with this is one the ring can hand us again. */
Expand Down
10 changes: 8 additions & 2 deletions app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class YCBTHistoryTransfer(
private var bufferCap = DEFAULT_BUFFER_CAP
private var watchdogJob: Job? = null
private var typeDeadline: Long? = null
private var emitFinishedOnComplete = true

companion object {
private const val DEFAULT_BUFFER_CAP = 64 * 1024
Expand All @@ -45,8 +46,9 @@ class YCBTHistoryTransfer(
val isActive: Boolean get() = state != State.IDLE

@Synchronized
fun start(types: List<YCBTHistoryType>) {
fun start(types: List<YCBTHistoryType>, isFullSync: Boolean = true) {
if (isActive) return
emitFinishedOnComplete = isFullSync
queue = types.filter { !unsupported.contains(it.queryKey) }.toMutableList()
advance()
}
Expand All @@ -59,6 +61,7 @@ class YCBTHistoryTransfer(
}
if (additions.isEmpty()) return
if (state == State.IDLE) {
emitFinishedOnComplete = true
queue = additions.toMutableList()
advance()
} else {
Expand All @@ -73,6 +76,7 @@ class YCBTHistoryTransfer(
currentType = null
queue.clear()
buffer = ByteArray(0)
emitFinishedOnComplete = true
}

private fun advance(): List<RingDecodedEvent> {
Expand All @@ -83,7 +87,9 @@ class YCBTHistoryTransfer(
if (queue.isEmpty()) {
state = State.IDLE
currentType = null
return listOf(RingDecodedEvent.HistorySyncFinished)
val shouldEmit = emitFinishedOnComplete
emitFinishedOnComplete = true
return if (shouldEmit) listOf(RingDecodedEvent.HistorySyncFinished) else emptyList()
}
val next = queue.removeAt(0)
sendQuery(next)
Expand Down
10 changes: 5 additions & 5 deletions app/src/main/java/com/pulseloop/ring/YCBTSyncEngine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class YCBTSyncEngine(
)) {
writer?.enqueue(command)
}
transfer.start(types = supportedHistoryTypes(HISTORY_TYPES))
transfer.start(types = supportedHistoryTypes(HISTORY_TYPES), isFullSync = true)
}

@Synchronized
Expand Down Expand Up @@ -111,22 +111,22 @@ class YCBTSyncEngine(
// Ask for current cumulative activity before the slower multi-type history walk. Without
// this, pull-to-refresh can leave steps stale until an unsolicited live push arrives.
writer?.enqueue(encoder.enableLiveStatus())
transfer.start(types = supportedHistoryTypes(HISTORY_TYPES))
transfer.start(types = supportedHistoryTypes(HISTORY_TYPES), isFullSync = true)
}

@Synchronized
override fun querySleep() {
transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP)))
transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP)), isFullSync = false)
}

@Synchronized
override fun syncVitalsHistory() {
transfer.start(types = supportedHistoryTypes(VITALS_TYPES))
transfer.start(types = supportedHistoryTypes(VITALS_TYPES), isFullSync = false)
}

@Synchronized
override fun syncSleepNow() {
transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP)))
transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP)), isFullSync = false)
}

private fun supportedHistoryTypes(types: List<YCBTHistoryType>): List<YCBTHistoryType> =
Expand Down
22 changes: 15 additions & 7 deletions app/src/main/java/com/pulseloop/service/SleepInsights.kt
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,22 @@ object SleepScore {
// and judged against asleep time the coverage test below would be true for every ring,
// handing a ring that never labels awake the full awake sub-score for nothing.
//
// Minutes the wearer added over time the ring missed (issue #106) are asleep but carry no
// stage, so the score judges the night the ring measured: they leave `total` (they would
// dilute every stage share) and the coverage test, and stay in `span`, which held them as a
// between-record gap before the edit and still does.
// Minutes the wearer added over time the ring missed (issue #106, #148) are asleep but carry
// no stage, so the score judges the night the ring measured: they leave `total` (they
// would dilute every stage share) and the coverage test, and `span` stays the span across
// the ring's own measured blocks (preserving interior between-record gaps while keeping
// outward extensions score-neutral even when a night has no AWAKE blocks).
val added = addedMinutes(blocks)
val total = if (session.totalMinutes > 0) (session.totalMinutes - added).coerceAtLeast(0).toDouble() else 0.0
val span = session.spanMinutes.toDouble().takeIf { it > 0 } ?: total
val measured = blocks.filterNot { it.stageRaw == SleepStage.ADDED.name }
val measuredSpan = if (added > 0 && measured.isNotEmpty() && measured.all { it.startAt > 0L }) {
val first = measured.minOf { it.startAt }
val last = measured.maxOf { it.startAt + it.durationMinutes * 60_000L }
((last - first) / 60_000L).toInt().coerceAtLeast(0).toDouble()
} else {
0.0
}
val span = measuredSpan.takeIf { it > 0 } ?: session.spanMinutes.toDouble().takeIf { it > 0 } ?: total
// stageRaw is persisted as the SleepStage enum name (uppercase) — match it exactly.
// Some rings report REM in big-data sleep; the score model has no REM band, so fold
// REM into deep (both are restorative sleep the deep band rewards).
Expand All @@ -93,8 +102,7 @@ object SleepScore {
val deep = minutesFor(SleepStage.DEEP, SleepStage.REM)
val light = minutesFor(SleepStage.LIGHT)
val awake = minutesFor(SleepStage.AWAKE)
val coveredStageMin = blocks.filterNot { it.stageRaw == SleepStage.ADDED.name }
.sumOf { it.durationMinutes.toDouble() }
val coveredStageMin = measured.sumOf { it.durationMinutes.toDouble() }
val hasAwakeSignal = blocks.any { it.stageRaw == SleepStage.AWAKE.name } ||
awake > 0 || (span > 0 && coveredStageMin >= span * 0.95)

Expand Down
Loading
Loading