diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index 471611d0..73332b8a 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -53,6 +53,14 @@ class PulseLoopApplication : Application() { }, ) WidgetRefreshWorker.schedule(this) + // Scheduled backups: the daily worker, plus a catch-up on start when one is overdue. + com.pulseloop.data.AutoBackup.schedule(this) + appScope.launch { + val c = this@PulseLoopApplication + if (com.pulseloop.data.AutoBackup.isEnabled(c) && + com.pulseloop.data.AutoBackup.isDue(com.pulseloop.data.AutoBackup.lastAt(c), com.pulseloop.data.AutoBackup.intervalDays(c), System.currentTimeMillis()) + ) com.pulseloop.data.AutoBackup.runNow(c) + } } } diff --git a/app/src/main/java/com/pulseloop/data/AutoBackup.kt b/app/src/main/java/com/pulseloop/data/AutoBackup.kt new file mode 100644 index 00000000..b1531107 --- /dev/null +++ b/app/src/main/java/com/pulseloop/data/AutoBackup.kt @@ -0,0 +1,130 @@ +package com.pulseloop.data + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.DocumentsContract +import androidx.work.Constraints +import androidx.work.CoroutineWorker +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.WorkerParameters +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.concurrent.TimeUnit + +/** + * Scheduled local backups into a folder the user picked (the Storage Access Framework, so it + * can be a folder synced by Drive, Nextcloud or a USB stick). Reuses the manual export's archive, + * keeps the newest [keep] files and deletes older ones it wrote. If the folder grant was revoked + * the backup fails and says so; it never quietly writes somewhere else (OpenStrap Edge's rule). + */ +object AutoBackup { + private const val PREFS = "auto_backup" + private const val WORK = "auto_backup" + const val PREFIX = "pulseloop-backup-" + + private fun prefs(c: Context) = c.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + + fun isEnabled(c: Context) = prefs(c).getBoolean("enabled", false) + fun folder(c: Context): Uri? = prefs(c).getString("folder", null)?.let(Uri::parse) + fun intervalDays(c: Context) = prefs(c).getInt("intervalDays", 1) + fun keep(c: Context) = prefs(c).getInt("keep", 5) + fun lastAt(c: Context) = prefs(c).getLong("lastAt", 0L) + fun lastError(c: Context): String? = prefs(c).getString("lastError", null) + + fun setEnabled(c: Context, on: Boolean) { prefs(c).edit().putBoolean("enabled", on).apply(); schedule(c) } + fun setIntervalDays(c: Context, days: Int) = prefs(c).edit().putInt("intervalDays", days).apply() + fun setKeep(c: Context, n: Int) = prefs(c).edit().putInt("keep", n.coerceIn(1, 30)).apply() + + /** Remember a folder from ACTION_OPEN_DOCUMENT_TREE, keeping read and write access across restarts. */ + fun setFolder(c: Context, tree: Uri) { + val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + runCatching { c.contentResolver.takePersistableUriPermission(tree, flags) } + prefs(c).edit().putString("folder", tree.toString()).remove("lastError").apply() + } + + /** The folder's name as the file picker shows it, or null. */ + fun folderName(c: Context): String? { + val tree = folder(c) ?: return null + return runCatching { + val doc = DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree)) + c.contentResolver.query(doc, arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } + }.getOrNull() + } + + /** Whether a backup is due at [now]. */ + fun isDue(lastAt: Long, intervalDays: Int, now: Long): Boolean = + lastAt <= 0L || now - lastAt >= intervalDays * 24L * 3_600_000L - 30 * 60_000L + + /** Of the backup files in a folder, the ones to delete so only the newest [keep] remain. */ + fun toPrune(names: List, keep: Int): List = + names.filter { it.startsWith(PREFIX) && it.endsWith(".json") }.sortedDescending().drop(keep) + + /** Write one backup now. Returns null on success, or the reason it failed. */ + suspend fun runNow(c: Context): String? { + val ctx = c.applicationContext + val tree = folder(ctx) ?: return fail(ctx, "Choose a folder first") + val granted = ctx.contentResolver.persistedUriPermissions.any { it.uri == tree && it.isWritePermission } + if (!granted) return fail(ctx, "PulseLoop lost access to the backup folder. Choose it again.") + return try { + val resolver = ctx.contentResolver + val parentId = DocumentsContract.getTreeDocumentId(tree) + val parent = DocumentsContract.buildDocumentUriUsingTree(tree, parentId) + val name = PREFIX + SimpleDateFormat("yyyy-MM-dd-HHmm", Locale.US).format(Date()) + ".json" + val doc = DocumentsContract.createDocument(resolver, parent, "application/json", name) + ?: return fail(ctx, "Couldn't create a file in the backup folder") + val text = DataArchiveService.exportJson(PulseLoopDatabase.getInstance(ctx)) + resolver.openOutputStream(doc, "w")?.use { it.write(text.toByteArray()) } + ?: return fail(ctx, "Couldn't write to the backup folder") + prune(ctx, tree, parentId) + prefs(ctx).edit().putLong("lastAt", System.currentTimeMillis()).remove("lastError").apply() + null + } catch (e: Exception) { + fail(ctx, "Backup failed: ${e.message ?: e.javaClass.simpleName}") + } + } + + private fun prune(c: Context, tree: Uri, parentId: String) { + val children = DocumentsContract.buildChildDocumentsUriUsingTree(tree, parentId) + val files = mutableMapOf() + c.contentResolver.query( + children, + arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME), + null, null, null, + )?.use { cur -> while (cur.moveToNext()) files[cur.getString(1)] = cur.getString(0) } + toPrune(files.keys.toList(), keep(c)).forEach { name -> + runCatching { DocumentsContract.deleteDocument(c.contentResolver, DocumentsContract.buildDocumentUriUsingTree(tree, files.getValue(name))) } + } + } + + private fun fail(c: Context, reason: String): String { + prefs(c).edit().putString("lastError", reason).apply() + return reason + } + + /** A daily check; the worker itself decides whether a backup is due. */ + fun schedule(c: Context) { + val wm = WorkManager.getInstance(c.applicationContext) + if (!isEnabled(c)) { wm.cancelUniqueWork(WORK); return } + val req = PeriodicWorkRequestBuilder(12, TimeUnit.HOURS) + .setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build()) + .build() + wm.enqueueUniquePeriodicWork(WORK, ExistingPeriodicWorkPolicy.KEEP, req) + } +} + +class AutoBackupWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { + override suspend fun doWork(): Result { + val c = applicationContext + if (!AutoBackup.isEnabled(c)) return Result.success() + if (!AutoBackup.isDue(AutoBackup.lastAt(c), AutoBackup.intervalDays(c), System.currentTimeMillis())) return Result.success() + AutoBackup.runNow(c) + // A failure is recorded for the settings screen; retrying a revoked folder won't help. + return Result.success() + } +} diff --git a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt index 2bf03ced..5925ca9a 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt @@ -353,6 +353,11 @@ object DataArchiveService { ) } + /** The whole archive as JSON, the same text a manual export writes. */ + suspend fun exportJson(db: PulseLoopDatabase): String = withContext(Dispatchers.Default) { + json.encodeToString(PulseArchive.serializer(), exportArchive(db)) + } + suspend fun exportToFile(context: Context, db: PulseLoopDatabase): Uri? = withContext(Dispatchers.Default) { val archive = exportArchive(db) val jsonStr = json.encodeToString(PulseArchive.serializer(), archive) diff --git a/app/src/main/java/com/pulseloop/ring/ColmiDecoder.kt b/app/src/main/java/com/pulseloop/ring/ColmiDecoder.kt index 6a2d0a02..3a2bbd28 100644 --- a/app/src/main/java/com/pulseloop/ring/ColmiDecoder.kt +++ b/app/src/main/java/com/pulseloop/ring/ColmiDecoder.kt @@ -175,16 +175,27 @@ object ColmiDecoder { val packet = ColmiPacket.validating(data) ?: return emptyList() val v = packet.bytes.map { it.toUByte() } return when (v[0]) { - ColmiCommandID.SYNC_HEART_RATE -> decodeHRHistory(v, day, zone, slotMinutes ?: 5) - ColmiCommandID.SYNC_STRESS -> decodeStressHistory(v, day, zone, slotMinutes ?: 30) - ColmiCommandID.SYNC_HRV -> decodeHRVHistory(v, day, zone, slotMinutes ?: 30) + ColmiCommandID.SYNC_HEART_RATE -> decodeHRHistory(v, day, zone, slotMinutes ?: 5, now) + ColmiCommandID.SYNC_STRESS -> decodeStressHistory(v, day, zone, slotMinutes ?: 30, now) + ColmiCommandID.SYNC_HRV -> decodeHRVHistory(v, day, zone, slotMinutes ?: 30, now) ColmiCommandID.SYNC_ACTIVITY -> decodeActivityHistory(v, zone, now) else -> emptyList() } } + /** + * The ring keeps one buffer slot per time of day and doesn't clear a slot it hasn't measured + * yet today, so yesterday's byte comes back in today's log at a time that hasn't happened + * (observed by OpenStrap Edge; our own HR echo comment noted the missing clamp). Drop + * anything later than now, with two minutes' grace for clock skew. + */ + internal fun isFutureSlot(ts: Instant, now: Instant): Boolean = ts.isAfter(now.plusSeconds(120)) + + /** A plausible stored heart rate; anything outside is a sensor artefact, not a reading. */ + internal val HR_HISTORY_BPM = 25..230 + private fun decodeHRHistory( - v: List, day: LocalDate, zone: ZoneId, slotMin: Int + v: List, day: LocalDate, zone: ZoneId, slotMin: Int, now: Instant, ): List { val packetNr = v[1].toInt() if (packetNr == 0xFF || packetNr == 0) return emptyList() @@ -193,8 +204,9 @@ object ColmiDecoder { val minutesInPrevious = if (packetNr > 1) (9 + (packetNr - 2) * 13) * slotMin else 0 return (startIndex until v.size - 1).mapNotNull { i -> val bpm = v[i].toInt() - if (bpm == 0) return@mapNotNull null + if (bpm !in HR_HISTORY_BPM) return@mapNotNull null val ts = base.plusMinutes((minutesInPrevious + (i - startIndex) * slotMin).toLong()).toInstant() + if (isFutureSlot(ts, now)) return@mapNotNull null RingDecodedEvent.HistoryMeasurement( kind_field = MeasurementKind.HEART_RATE, value = bpm.toDouble(), _timestamp = ts ) @@ -202,7 +214,7 @@ object ColmiDecoder { } private fun decodeStressHistory( - v: List, day: LocalDate, zone: ZoneId, slotMin: Int + v: List, day: LocalDate, zone: ZoneId, slotMin: Int, now: Instant, ): List { val packetNr = v[1].toInt() if (packetNr == 0xFF || packetNr == 0) return emptyList() @@ -213,6 +225,7 @@ object ColmiDecoder { val stress = v[i].toInt() if (stress == 0) return@mapNotNull null val ts = base.plusMinutes((minutesInPrevious + (i - startIndex) * slotMin).toLong()).toInstant() + if (isFutureSlot(ts, now)) return@mapNotNull null RingDecodedEvent.StressSample( value = stress, _timestamp = ts, @@ -222,7 +235,7 @@ object ColmiDecoder { } private fun decodeHRVHistory( - v: List, day: LocalDate, zone: ZoneId, slotMin: Int + v: List, day: LocalDate, zone: ZoneId, slotMin: Int, now: Instant, ): List { val packetNr = v[1].toInt() if (packetNr == 0xFF || packetNr == 0) return emptyList() @@ -233,6 +246,7 @@ object ColmiDecoder { val hrv = v[i].toInt() if (hrv == 0) return@mapNotNull null val ts = base.plusMinutes((minutesInPrevious + (i - startIndex) * slotMin).toLong()).toInstant() + if (isFutureSlot(ts, now)) return@mapNotNull null RingDecodedEvent.HistoryMeasurement( kind_field = MeasurementKind.HRV, value = hrv.toDouble(), @@ -267,8 +281,11 @@ object ColmiDecoder { val steps = ColmiBytes.u16(v[9], v[10]) val distance = ColmiBytes.u16(v[11], v[12]).toInt() + // Bytes 7-8 are the slot's calories (OpenStrap Edge reads them; a header flag may scale + // them ×10). Carried for diagnostics only until a capture confirms the scale. + val calories = ColmiBytes.u16(v[7], v[8]) return listOf(RingDecodedEvent.ActivityBucket( - _timestamp = ts, steps = steps, distanceMeters = distance + _timestamp = ts, steps = steps, distanceMeters = distance, rawCalories = calories, )) } @@ -472,13 +489,28 @@ object ColmiDecoder { } if (stages.isNotEmpty()) { events.add(RingDecodedEvent.SleepTimeline( - _timestamp = sessionStart.toInstant(), stages = stages + _timestamp = sleepAnchor(sessionStart, dayStart.atStartOfDay(zone).plusMinutes(sleepEnd.toLong()), stages.size).toInstant(), + stages = stages, )) } } return events } + /** + * Where a night's stage blocks start. Normally the header's start; when the header's span and + * the blocks' own minutes disagree by more than [SLEEP_ANCHOR_TOLERANCE_MIN], the night is laid + * back from its end instead, which is how the ring lays out its data (a header saying 22:00 + * over blocks that only cover 05:00–06:00 otherwise put an hour of sleep at 22:00). + */ + internal fun sleepAnchor(headerStart: java.time.ZonedDateTime, headerEnd: java.time.ZonedDateTime, blockMinutes: Int): java.time.ZonedDateTime { + val span = java.time.Duration.between(headerStart, headerEnd).toMinutes() + if (span <= 0 || kotlin.math.abs(span - blockMinutes) <= SLEEP_ANCHOR_TOLERANCE_MIN) return headerStart + return headerEnd.minusMinutes(blockMinutes.toLong()) + } + + internal const val SLEEP_ANCHOR_TOLERANCE_MIN = 15L + fun sleepStage(type: UByte): SleepStage = when (type) { ColmiCommandID.SLEEP_LIGHT -> SleepStage.LIGHT ColmiCommandID.SLEEP_DEEP -> SleepStage.DEEP diff --git a/app/src/main/java/com/pulseloop/ring/ColmiDriver.kt b/app/src/main/java/com/pulseloop/ring/ColmiDriver.kt index e6702a96..b7b4abd9 100644 --- a/app/src/main/java/com/pulseloop/ring/ColmiDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/ColmiDriver.kt @@ -45,6 +45,10 @@ class ColmiDriver(private val writer: RingCommandWriter) : WearableDriver { private fun ingestNormal(data: ByteArray): List { val op = if (data.isNotEmpty()) data[0].toUByte() else 0u + ColmiSyncEngine.rejectedHistoryOpcode(op)?.let { refused -> + engine.handleHistoryRejected(refused) + return listOf(RingDecodedEvent.Unknown(commandId = op, raw = data)) + } if (ColmiSyncEngine.isHistoryOpcode(op)) { return engine.handleHistoryFrame(data) } diff --git a/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt b/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt index 020449db..1b73a1d6 100644 --- a/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt +++ b/app/src/main/java/com/pulseloop/ring/ColmiSyncEngine.kt @@ -87,6 +87,22 @@ class ColmiSyncEngine( */ internal val legacyTemperatureWatchdogTimeoutMs = 3_000L + /** + * How long a paged day may sit silent after its last frame before it counts as complete. + * Explicit end markers still end a day at once; this only catches a day whose last packet + * never comes, which used to sit out the 10–20 s stage watchdog while the ring counts down + * its own ~20 s idle hang-up (OpenStrap Edge ends a walk after 800 ms of quiet; 2 s leaves + * slower firmware room). + */ + internal val pagedQuietMs = 2_000L + internal val activityQuietMs = 5_000L + + /** After a legacy temperature reply, how long to wait for the next day's reply before the + * sync is done; some firmware sends one reply per day. */ + internal val legacyTemperatureQuietMs = 1_500L + private var quietJob: Job? = null + private var legacyTemperatureReplies = 0 + // Realtime HR keepalive. // Volatile: written on Main (start/stop actions), read on the notify thread — // [handleRawNotify] → [onRealtimeHeartRateRejected] decides whether a `0x9E` is the reply to @@ -141,7 +157,21 @@ class ColmiSyncEngine( */ @Volatile private var sportRejected = false + override val hasLiveSession: Boolean + get() = realtimeHRActive || manualHRActive || manualSpO2Active || sportActive || + realtimeRejected && System.currentTimeMillis() - lastFallbackFrameAt < 30_000L + companion object { + private const val MAX_LEGACY_TEMPERATURE_REPLIES = 8 + private val PAGED_STAGES = setOf(Stage.ACTIVITY, Stage.HEART_RATE, Stage.STRESS, Stage.HRV) + + /** A history opcode with the high bit set: the ring refusing that history request. */ + fun rejectedHistoryOpcode(op: UByte): UByte? { + if (op.toInt() and 0x80 == 0) return null + val base = (op.toInt() and 0x7F).toUByte() + return base.takeIf { isHistoryOpcode(it) } + } + fun isHistoryOpcode(op: UByte): Boolean = op == ColmiCommandID.SYNC_ACTIVITY || op == ColmiCommandID.SYNC_HEART_RATE || @@ -365,11 +395,41 @@ class ColmiSyncEngine( fun handleHistoryFrame(data: ByteArray): List { captureStageMetadata(data) val events = decoder.decodeHistory(data, day = syncDay, slotMinutes = slotMinutes) + val before = stage to daysAgo advanceAfterPagedFrame(data) armWatchdog() + // The day didn't end on this frame: if nothing more arrives, end it on quiet. + if ((stage to daysAgo) == before && stage in PAGED_STAGES) armQuiet(before.first, before.second) return events } + /** + * The ring refused a history request (`opcode | 0x80`): this firmware doesn't keep that + * history, so the stage is over. Previously the refusal fell through to the plain decoder and + * the stage waited out its whole watchdog. + */ + fun handleHistoryRejected(op: UByte) { + val rejected = when (op) { + ColmiCommandID.SYNC_ACTIVITY -> Stage.ACTIVITY + ColmiCommandID.SYNC_HEART_RATE -> Stage.HEART_RATE + ColmiCommandID.SYNC_STRESS -> Stage.STRESS + ColmiCommandID.SYNC_HRV -> Stage.HRV + else -> return + } + if (stage != rejected) return + quietJob?.cancel() + forceAdvanceStage(rejected) + } + + private fun armQuiet(expected: Stage, day: Int) { + quietJob?.cancel() + quietJob = scope.launch { + // Activity keeps a longer quiet: its 20 s watchdog predates this and nothing records why. + delay(if (expected == Stage.ACTIVITY) activityQuietMs else pagedQuietMs) + if (isActive && stage == expected && daysAgo == day) advanceDay() + } + } + /** * Capture what the ring's own frames tell us about the current paged day, before decoding: * - packet 0 carries the day's packet count (v[2], drives terminal detection) and the @@ -448,7 +508,20 @@ class ColmiSyncEngine( // request the ring answers by re-emitting its temperature frame, which re-entered this // branch and looped into a GATT write storm that starved the sleep sync. The stage // guard also makes a repeated temperature frame idempotent (finish once, then ignore). - if (stage == Stage.TEMPERATURE) finishSync() + // + // Some firmware answers with one reply per day, so the finish waits a moment of quiet + // for the rest instead of firing on the first reply, which started the idle hang-up + // logic while data was still arriving. Capped so a ring that keeps re-sending can't + // hold the sync open. + if (stage != Stage.TEMPERATURE) return + legacyTemperatureReplies++ + watchdogJob?.cancel() + quietJob?.cancel() + if (legacyTemperatureReplies >= MAX_LEGACY_TEMPERATURE_REPLIES) { finishSync(); return } + quietJob = scope.launch { + delay(legacyTemperatureQuietMs) + if (isActive && stage == Stage.TEMPERATURE) finishSync() + } } ColmiCommandID.BIG_DATA_INTERVAL_TEMPERATURE -> { if (stage != Stage.TEMPERATURE) return @@ -531,6 +604,7 @@ class ColmiSyncEngine( lastIntervalTempPacket = -1 writer?.enqueue(encoder.bigDataIntervalTemperature(daysAgo, 0)) } else { + legacyTemperatureReplies = 0 writer?.enqueue(encoder.bigDataTemperature()) } } @@ -544,7 +618,12 @@ class ColmiSyncEngine( val isEmpty = packetNr == 0xFF val dayComplete = isEmpty || isTerminalPacket(data) if (!dayComplete) return + quietJob?.cancel() + advanceDay() + } + /** The current paged day is complete: ask for the next one, or move to the next stage. */ + private fun advanceDay() { when (stage) { Stage.ACTIVITY -> { if (daysAgo < 7) { daysAgo++; requestActivity() } @@ -628,6 +707,8 @@ class ColmiSyncEngine( stage = Stage.DONE watchdogJob?.cancel() watchdogJob = null + quietJob?.cancel() + quietJob = null // iOS publishes `.syncProgress("done")` here — it is the ONLY signal that stamps // `DeviceEntity.lastFullSyncAt`, and without it every freshness consumer silently // degrades for Colmi rings: the coach check-in skip gate and done-wait (#61c), the diff --git a/app/src/main/java/com/pulseloop/ring/IdleLinkPolicy.kt b/app/src/main/java/com/pulseloop/ring/IdleLinkPolicy.kt index 8aaabbe9..1f079f78 100644 --- a/app/src/main/java/com/pulseloop/ring/IdleLinkPolicy.kt +++ b/app/src/main/java/com/pulseloop/ring/IdleLinkPolicy.kt @@ -59,10 +59,19 @@ object IdleLinkPolicy { deviceType: RingDeviceType?, syncCompletedOnLink: Boolean, status: Int, + /** The app hung up itself after the sync ([RingBLEClient.settleIdleLink]): an idle drop + * whatever status the stack reports for a locally initiated disconnect. */ + requestedByApp: Boolean = false, ): Boolean = deviceType == RingDeviceType.COLMI_R02 && syncCompletedOnLink && - status in idleStatuses + (status in idleStatuses || requestedByApp) + + /** After a Colmi sync, how long the link must be quiet before the app hangs up itself. */ + const val SETTLE_QUIET_MS = 4_000L + + /** Stop waiting for quiet after this long: the ring hangs up on its own at ~20 s anyway. */ + const val SETTLE_MAX_MS = 15_000L /** Whether the watchdog should still leave an idle ring alone at [now]. */ fun isResting(restUntil: Long, now: Long): Boolean = now < restUntil diff --git a/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt b/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt index b6b3d25b..51a1506c 100644 --- a/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt +++ b/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt @@ -218,6 +218,9 @@ class RingBLEClient( // finished a sync (so a later quiet drop is the ring idling, not a fault) and how long the // watchdog should leave the ring alone afterwards. @Volatile private var syncCompletedOnLink = false + /** Set when the app hangs up a quiet Colmi link itself, so the disconnect counts as idle. */ + @Volatile private var appIdleDisconnect = false + private var settleJob: kotlinx.coroutines.Job? = null @Volatile private var idleRestUntil = 0L // When the reconnect budget ran out (0 = not spent); lets unattended retries resume later. private var budgetExhaustedAt = 0L @@ -246,6 +249,7 @@ class RingBLEClient( _state.value.connectionState == RingConnectionState.CONNECTED ) { syncCompletedOnLink = true + if (activeCoordinator?.deviceType == RingDeviceType.COLMI_R02) settleIdleLink() } } } @@ -572,6 +576,38 @@ class RingBLEClient( * into "connected-but-invisible" (won't appear in scans until Bluetooth is * toggled). Keeps the stored identity so [connectLastKnown] can reconnect later. */ + /** + * After a Colmi sync, hang up once the link has gone quiet instead of waiting for the ring's + * own ~20 s idle hang-up (OpenStrap Edge disconnects after every sync). A local disconnect has + * a clean status, the ring is free for its own app sooner, and the drop is still treated as + * idle (rest, no red error) through [IdleLinkPolicy.isIdleDrop]'s requestedByApp. Never while + * a live stream, spot measurement or workout runs, or while commands are still queued. + */ + private fun settleIdleLink() { + settleJob?.cancel() + settleJob = scope.launch { + val started = System.currentTimeMillis() + while (System.currentTimeMillis() - started < IdleLinkPolicy.SETTLE_MAX_MS) { + delay(1_000L) + if (_state.value.connectionState != RingConnectionState.CONNECTED) return@launch + if (activeSyncEngine?.hasLiveSession == true) return@launch + val busy = synchronized(opLock) { inFlightOp != null || opQueue.isNotEmpty() } + val quiet = System.currentTimeMillis() - lastActivityAt >= IdleLinkPolicy.SETTLE_QUIET_MS + if (!busy && quiet) { + val gatt = bluetoothGatt ?: return@launch + recordDiagnostic("sync done, link quiet — disconnecting until the next sync") + appIdleDisconnect = true + try { gatt.disconnect() } catch (_: Exception) { appIdleDisconnect = false; return@launch } + // Under Doze the stack can drop the STATE_DISCONNECTED callback; finish the + // teardown ourselves rather than leave a half-closed link marked connected. + delay(3_000L) + if (appIdleDisconnect && bluetoothGatt === gatt) handleDisconnect(gatt, BluetoothGatt.GATT_SUCCESS) + return@launch + } + } + } + } + fun disconnect() { // Lifecycle/worker teardown is intentional. Leave genuine link-loss callbacks eligible // for watchdog recovery, but do not let this client undo an explicit transient teardown. @@ -1952,8 +1988,10 @@ class RingBLEClient( deviceType = activeCoordinator?.deviceType, syncCompletedOnLink = syncCompletedOnLink, status = status, + requestedByApp = appIdleDisconnect, ) syncCompletedOnLink = false + appIdleDisconnect = false val now = System.currentTimeMillis() if (idleDrop) { // The ring hung up after syncing: let it rest instead of redialling straight away, diff --git a/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt b/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt index 5bf00b16..d6e25c90 100644 --- a/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt +++ b/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt @@ -137,11 +137,13 @@ sealed class RingDecodedEvent { data class ActivityBucket( val _timestamp: Instant, val steps: Int, - val distanceMeters: Int + val distanceMeters: Int, + /** The ring's per-slot calories where the protocol carries them, unscaled; diagnostics only. */ + val rawCalories: Int? = null, ) : RingDecodedEvent() { override val kind = "activity_bucket" override val confidence = DecodeConfidence.KNOWN - override val debugJSON = """{"steps":$steps,"distance_m":$distanceMeters}""" + override val debugJSON = """{"steps":$steps,"distance_m":$distanceMeters${rawCalories?.let { ",\"raw_kcal\":$it" } ?: ""}}""" } data class HeartRateSample( diff --git a/app/src/main/java/com/pulseloop/ring/WearableDriver.kt b/app/src/main/java/com/pulseloop/ring/WearableDriver.kt index e2316f37..23caf056 100644 --- a/app/src/main/java/com/pulseloop/ring/WearableDriver.kt +++ b/app/src/main/java/com/pulseloop/ring/WearableDriver.kt @@ -144,6 +144,12 @@ interface RingSyncEngine { const val DEFAULT_SPOT_SPO2_SECONDS = 60 } + /** + * A live stream, spot measurement or workout session is running on this link, so the app + * must not hang up on its own once history is done (see `RingBLEClient.settleIdleLink`). + */ + val hasLiveSession: Boolean get() = false + /** True only for protocols with one native command that returns a combined vitals packet. * Capability bits such as manual BP/glucose do not imply this transport feature. */ val supportsCombinedMeasurement: Boolean get() = false diff --git a/app/src/main/java/com/pulseloop/service/JournalInsights.kt b/app/src/main/java/com/pulseloop/service/JournalInsights.kt index 1519017d..0dd5203d 100644 --- a/app/src/main/java/com/pulseloop/service/JournalInsights.kt +++ b/app/src/main/java/com/pulseloop/service/JournalInsights.kt @@ -68,29 +68,58 @@ object JournalInsights { // Only days followed by a recorded night can say anything. val pairs = nightByDay.keys.map { wakeDay -> wakeDay.minusDays(1) to nightByDay.getValue(wakeDay) } val used = tagsByDay.values.flatten().toSet().mapNotNull { Tag.of(it) } - return used.map { tag -> + + // Every tag × outcome comparison, with its size and its p-value; the corrected set of + // survivors is decided across all of them at once. + class Test(val tag: Tag, val outcome: Int, val diff: Double, val p: Double) + val tests = mutableListOf() + val counts = mutableMapOf>() + for (tag in used) { val (with, without) = pairs.partition { (day, _) -> tagsByDay[day]?.contains(tag.key) == true } val w = with.map { it.second } val wo = without.map { it.second } - if (w.size < MIN_NIGHTS || wo.size < MIN_NIGHTS) { - Effect(tag, w.size, wo.size, null, null, null) - } else { - fun avg(list: List, f: (NightSummary) -> Double?) = list.mapNotNull(f).takeIf { it.size >= MIN_NIGHTS }?.average() - val sleepD = avg(w) { it.asleepMinutes.toDouble().takeIf { m -> m > 0 } }?.let { a -> avg(wo) { it.asleepMinutes.toDouble().takeIf { m -> m > 0 } }?.let { a - it } } - val hrvW = avg(w) { it.hrv } - val hrvWo = avg(wo) { it.hrv } - val hrvPct = if (hrvW != null && hrvWo != null && hrvWo > 0) (hrvW - hrvWo) / hrvWo * 100 else null - val rhrD = avg(w) { it.restingHr }?.let { a -> avg(wo) { it.restingHr }?.let { a - it } } - Effect( - tag, w.size, wo.size, - sleepMinutes = sleepD?.takeIf { abs(it) >= 15 }?.roundToInt(), - hrvPct = hrvPct?.takeIf { abs(it) >= 5 }?.roundToInt(), - restingHr = rhrD?.takeIf { abs(it) >= 2 }?.roundToInt(), - ) + counts[tag] = w.size to wo.size + if (w.size < MIN_NIGHTS || wo.size < MIN_NIGHTS) continue + fun values(list: List, f: (NightSummary) -> Double?) = list.mapNotNull(f) + val outcomes: List<(NightSummary) -> Double?> = listOf( + { it.asleepMinutes.toDouble().takeIf { m -> m > 0 } }, + { it.hrv }, + { it.restingHr }, + ) + outcomes.forEachIndexed { o, f -> + val a = values(w, f); val b = values(wo, f) + if (a.size < MIN_NIGHTS || b.size < MIN_NIGHTS) return@forEachIndexed + val diff = if (o == 1) { + val base = b.average() + if (base <= 0) return@forEachIndexed + (a.average() - base) / base * 100 + } else a.average() - b.average() + tests += Test(tag, o, diff, Stats.welchP(a, b)) } + } + val significant = Stats.benjaminiHochberg(tests.map { it.p }, FALSE_DISCOVERY_RATE) + val kept = tests.filterIndexed { i, _ -> significant[i] } + + return used.map { tag -> + val (nw, nwo) = counts.getValue(tag) + fun diff(o: Int, minimum: Double) = kept.firstOrNull { it.tag == tag && it.outcome == o }?.diff + ?.takeIf { abs(it) >= minimum }?.roundToInt() + Effect( + tag, nw, nwo, + sleepMinutes = diff(0, 15.0), + hrvPct = diff(1, 5.0), + restingHr = diff(2, 2.0), + ) }.sortedWith(compareByDescending { it.hasEffect }.thenByDescending { strength(it) }) } + /** Comparisons [effects] runs for these tags and nights: what the correction is spread over. */ + fun comparisonCount(tagsByDay: Map>): Int = + tagsByDay.values.flatten().toSet().mapNotNull { Tag.of(it) }.size * 3 + + /** Benjamini-Hochberg false-discovery rate for "what affects you". */ + const val FALSE_DISCOVERY_RATE = 0.10 + private fun strength(e: Effect): Double = abs(e.hrvPct ?: 0) / 5.0 + abs(e.restingHr ?: 0) / 2.0 + abs(e.sleepMinutes ?: 0) / 15.0 } diff --git a/app/src/main/java/com/pulseloop/service/Stats.kt b/app/src/main/java/com/pulseloop/service/Stats.kt new file mode 100644 index 00000000..3174e7b7 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/Stats.kt @@ -0,0 +1,94 @@ +package com.pulseloop.service + +import kotlin.math.abs +import kotlin.math.exp +import kotlin.math.ln +import kotlin.math.sqrt + +/** + * The small amount of statistics the insight screens need, without a library: Welch's t-test and + * the Benjamini-Hochberg false-discovery correction. "What affects you" tests every tag against + * several outcomes; uncorrected, a user with a dozen tags would be shown a couple of "findings" + * that are chance by construction (OpenStrap Edge corrects for exactly this). + */ +object Stats { + + /** Two-sided p-value of Welch's unequal-variance t-test; 1.0 when it can't be computed. */ + fun welchP(a: List, b: List): Double { + if (a.size < 2 || b.size < 2) return 1.0 + val ma = a.average(); val mb = b.average() + val va = a.sumOf { (it - ma) * (it - ma) } / (a.size - 1) + val vb = b.sumOf { (it - mb) * (it - mb) } / (b.size - 1) + val se2 = va / a.size + vb / b.size + if (se2 <= 0.0) return if (ma == mb) 1.0 else 0.0 + val t = (ma - mb) / sqrt(se2) + val df = se2 * se2 / ((va / a.size) * (va / a.size) / (a.size - 1) + (vb / b.size) * (vb / b.size) / (b.size - 1)) + return twoSidedT(t, df) + } + + /** P(|T| ≥ |t|) for Student's t with [df] degrees of freedom. */ + fun twoSidedT(t: Double, df: Double): Double { + if (!df.isFinite() || df <= 0) return 1.0 + return incompleteBeta(df / 2, 0.5, df / (df + t * t)).coerceIn(0.0, 1.0) + } + + /** + * Which of [pValues] survive the Benjamini-Hochberg procedure at false-discovery rate [q]: + * sort ascending, find the largest k with p(k) ≤ k/m·q, and keep the first k. + */ + fun benjaminiHochberg(pValues: List, q: Double = 0.10): List { + val m = pValues.size + if (m == 0) return emptyList() + val order = pValues.indices.sortedBy { pValues[it] } + var cutoff = -1 + order.forEachIndexed { rank, i -> if (pValues[i] <= (rank + 1).toDouble() / m * q) cutoff = rank } + val keep = BooleanArray(m) + for (rank in 0..cutoff) keep[order[rank]] = true + return keep.toList() + } + + // Regularised incomplete beta I_x(a, b) (Numerical Recipes, continued fraction). + private fun incompleteBeta(a: Double, b: Double, x: Double): Double { + if (x <= 0.0) return 0.0 + if (x >= 1.0) return 1.0 + val bt = exp(lnGamma(a + b) - lnGamma(a) - lnGamma(b) + a * ln(x) + b * ln(1 - x)) + return if (x < (a + 1) / (a + b + 2)) bt * betaCf(a, b, x) / a else 1 - bt * betaCf(b, a, 1 - x) / b + } + + private fun betaCf(a: Double, b: Double, x: Double): Double { + val tiny = 1e-30 + var c = 1.0 + var d = 1 - (a + b) * x / (a + 1) + if (abs(d) < tiny) d = tiny + d = 1 / d + var h = d + for (m in 1..200) { + val m2 = 2 * m + var aa = m * (b - m) * x / ((a + m2 - 1) * (a + m2)) + d = 1 + aa * d; if (abs(d) < tiny) d = tiny + c = 1 + aa / c; if (abs(c) < tiny) c = tiny + d = 1 / d; h *= d * c + aa = -(a + m) * (a + b + m) * x / ((a + m2) * (a + m2 + 1)) + d = 1 + aa * d; if (abs(d) < tiny) d = tiny + c = 1 + aa / c; if (abs(c) < tiny) c = tiny + d = 1 / d + val del = d * c + h *= del + if (abs(del - 1) < 3e-12) break + } + return h + } + + private val LANCZOS = doubleArrayOf( + 76.18009172947146, -86.50532032941677, 24.01409824083091, + -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5, + ) + + private fun lnGamma(xx: Double): Double { + var y = xx + val tmp = xx + 5.5 - (xx + 0.5) * ln(xx + 5.5) + var ser = 1.000000000190015 + for (c in LANCZOS) { y += 1; ser += c / y } + return -tmp + ln(2.5066282746310005 * ser / xx) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt index 118a62e3..e5f2057e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt @@ -200,7 +200,7 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - } } Text( - "These are patterns in your own data, not proof of cause and effect. They get more reliable the more days you tag.", + "These are patterns in your own data, not proof of cause and effect. Every tag is checked against your sleep, HRV and resting heart rate together, so a difference that could easily be chance isn't shown. They get more reliable the more days you tag.", fontSize = 12.sp, color = PulseColors.textMuted, ) Spacer(Modifier.height(24.dp)) diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 7119d8e1..5f8b5f9c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -2463,6 +2463,8 @@ fun PrivacyDataSettingsScreen( } } + AutoBackupCard() + // App data — destructive reset/restore actions. Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { @@ -3675,3 +3677,83 @@ private fun CoachManagedCard(fields: Set, } } } + + +/** Scheduled backups into a folder the user picks (see data/AutoBackup.kt). */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AutoBackupCard() { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var enabled by remember { mutableStateOf(com.pulseloop.data.AutoBackup.isEnabled(context)) } + var folderName by remember { mutableStateOf(com.pulseloop.data.AutoBackup.folderName(context)) } + var interval by remember { mutableStateOf(com.pulseloop.data.AutoBackup.intervalDays(context)) } + var status by remember { mutableStateOf(backupStatus(context)) } + var running by remember { mutableStateOf(false) } + val picker = androidx.activity.compose.rememberLauncherForActivityResult( + androidx.activity.result.contract.ActivityResultContracts.OpenDocumentTree() + ) { uri -> + if (uri != null) { + com.pulseloop.data.AutoBackup.setFolder(context, uri) + folderName = com.pulseloop.data.AutoBackup.folderName(context) + if (!enabled) { enabled = true; com.pulseloop.data.AutoBackup.setEnabled(context, true) } + status = backupStatus(context) + } + } + Card(Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text("Automatic backups", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text( + "Saves the same file as Export to a folder you choose, and keeps the latest 5.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Switch(checked = enabled, onCheckedChange = { + if (it && com.pulseloop.data.AutoBackup.folder(context) == null) picker.launch(null) + else { enabled = it; com.pulseloop.data.AutoBackup.setEnabled(context, it) } + }) + } + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "Folder: ${folderName ?: "not chosen"}", + style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f), + ) + TextButton(onClick = { picker.launch(null) }) { Text(if (folderName == null) "Choose" else "Change") } + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(1 to "Daily", 7 to "Weekly").forEach { (d, label) -> + FilterChip( + selected = interval == d, + onClick = { interval = d; com.pulseloop.data.AutoBackup.setIntervalDays(context, d) }, + label = { Text(label) }, + ) + } + } + Text(status, style = MaterialTheme.typography.bodySmall, + color = if (com.pulseloop.data.AutoBackup.lastError(context) != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) + OutlinedButton( + enabled = !running && folderName != null, + onClick = { + running = true + scope.launch { + com.pulseloop.data.AutoBackup.runNow(context) + status = backupStatus(context) + running = false + } + }, + modifier = Modifier.fillMaxWidth(), + ) { Text(if (running) "Backing up…" else "Back up now") } + } + } +} + +private fun backupStatus(context: android.content.Context): String { + com.pulseloop.data.AutoBackup.lastError(context)?.let { return it } + val last = com.pulseloop.data.AutoBackup.lastAt(context) + if (last <= 0) return "No backup yet." + val fmt = java.text.SimpleDateFormat("EEE d MMM, HH:mm", java.util.Locale.getDefault()) + return "Last backup: ${fmt.format(java.util.Date(last))}" +} diff --git a/app/src/test/java/com/pulseloop/data/AutoBackupTest.kt b/app/src/test/java/com/pulseloop/data/AutoBackupTest.kt new file mode 100644 index 00000000..69430b94 --- /dev/null +++ b/app/src/test/java/com/pulseloop/data/AutoBackupTest.kt @@ -0,0 +1,28 @@ +package com.pulseloop.data + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class AutoBackupTest { + private val day = 24 * 3_600_000L + + @Test + fun `a backup is due after its interval, with half an hour of slack`() { + val now = 100 * day + assertTrue(AutoBackup.isDue(0L, 1, now)) + assertTrue(AutoBackup.isDue(now - day + 10 * 60_000L, 1, now)) + assertFalse(AutoBackup.isDue(now - 12 * 3_600_000L, 1, now)) + assertFalse(AutoBackup.isDue(now - 3 * day, 7, now)) + } + + @Test + fun `only our own backups beyond the newest few are pruned`() { + val names = listOf( + "pulseloop-backup-2026-10-01-0300.json", "pulseloop-backup-2026-10-03-0300.json", + "pulseloop-backup-2026-10-02-0300.json", "holiday.jpg", "pulseloop-export-2026-09-01-1200.json", + ) + assertEquals(listOf("pulseloop-backup-2026-10-01-0300.json"), AutoBackup.toPrune(names, 2)) + } +} diff --git a/app/src/test/java/com/pulseloop/ring/ColmiEdgeLessonsTest.kt b/app/src/test/java/com/pulseloop/ring/ColmiEdgeLessonsTest.kt new file mode 100644 index 00000000..27d1def9 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ring/ColmiEdgeLessonsTest.kt @@ -0,0 +1,100 @@ +package com.pulseloop.ring + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneOffset + +/** + * Colmi sync behaviour learned from OpenStrap Edge's adapter (ideas reimplemented, not code): + * refusals end a stage, future-dated buffer slots are dropped, a night whose header disagrees + * with its blocks is laid back from its end, and an app-side hang-up after sync counts as idle. + */ +class ColmiEdgeLessonsTest { + + private class RecordingWriter : RingCommandWriter { + val commands = mutableListOf() + override fun enqueue(command: ByteArray) { commands.add(command) } + } + + private val utc = ZoneOffset.UTC + + @Test + fun `a refused activity request moves straight on to heart rate`() { + val writer = RecordingWriter() + val driver = ColmiDriver(writer) + val engine = driver.makeSyncEngine() as ColmiSyncEngine + engine.runStartup() + val before = writer.commands.size + val refusal = ColmiPacket.frame(byteArrayOf((0x43 or 0x80).toByte())) + val events = driver.ingest(refusal, ColmiUUIDs.NOTIFY_V1) + assertTrue(events.single() is RingDecodedEvent.Unknown) + assertEquals(before + 1, writer.commands.size) + assertEquals(ColmiCommandID.SYNC_HEART_RATE.toByte(), writer.commands.last()[0]) + engine.destroy() + } + + @Test + fun `only history opcodes with the high bit read as refusals`() { + assertEquals(ColmiCommandID.SYNC_HRV, ColmiSyncEngine.rejectedHistoryOpcode((0x39 or 0x80).toUByte())) + assertEquals(ColmiCommandID.SYNC_HEART_RATE, ColmiSyncEngine.rejectedHistoryOpcode(0x95u)) + assertNull(ColmiSyncEngine.rejectedHistoryOpcode(0x15u)) + assertNull(ColmiSyncEngine.rejectedHistoryOpcode(ColmiCommandID.REALTIME_HEART_RATE_ERROR)) + } + + @Test + fun `a refusal for another stage is ignored`() { + val writer = RecordingWriter() + val driver = ColmiDriver(writer) + val engine = driver.makeSyncEngine() as ColmiSyncEngine + engine.runStartup() // stage = ACTIVITY + val before = writer.commands.size + driver.ingest(ColmiPacket.frame(byteArrayOf((0x39 or 0x80).toByte())), ColmiUUIDs.NOTIFY_V1) + assertEquals(before, writer.commands.size) + engine.destroy() + } + + @Test + fun `heart-rate slots later than now and implausible bpm are dropped`() { + val day = LocalDate.of(2026, 10, 21) + val now = day.atTime(0, 20).toInstant(utc) + val frame = ColmiPacket.frame(byteArrayOf( + 0x15, 0x01, 0, 0, 0, 0, + 70, 20, 70, 70, 70, 70, 70, 70, 70, + )) + val hr = ColmiDecoder.decodeHistory(frame, day = day, now = now, zone = utc, slotMinutes = 5) + .filterIsInstance() + // 00:00 … 00:20 kept (the 20 bpm at 00:05 dropped); 00:25 onward is in the future. + assertEquals(listOf(0L, 10L, 15L, 20L), hr.map { (it._timestamp.epochSecond - day.atStartOfDay(utc).toEpochSecond()) / 60 }) + assertTrue(hr.all { it.value == 70.0 }) + } + + @Test + fun `a night whose header disagrees with its blocks is laid back from its end`() { + val day = LocalDate.of(2026, 10, 21) + val headerStart = day.minusDays(1).atTime(22, 0).atZone(utc) + val headerEnd = day.atTime(6, 0).atZone(utc) + assertEquals(day.atTime(5, 0).atZone(utc), ColmiDecoder.sleepAnchor(headerStart, headerEnd, 60)) + // Within the tolerance the header's start stands. + assertEquals(headerStart, ColmiDecoder.sleepAnchor(headerStart, headerEnd, 470)) + } + + @Test + fun `an app-side hang-up after a completed Colmi sync is an idle drop`() { + assertTrue(IdleLinkPolicy.isIdleDrop(RingDeviceType.COLMI_R02, syncCompletedOnLink = true, status = 0, requestedByApp = true)) + assertFalse(IdleLinkPolicy.isIdleDrop(RingDeviceType.COLMI_R02, syncCompletedOnLink = true, status = 0)) + assertFalse(IdleLinkPolicy.isIdleDrop(RingDeviceType.COLMI_R02, syncCompletedOnLink = false, status = 0, requestedByApp = true)) + assertFalse(IdleLinkPolicy.isIdleDrop(RingDeviceType.JRING, syncCompletedOnLink = true, status = 0, requestedByApp = true)) + } + + @Test + fun `isFutureSlot allows two minutes of clock skew`() { + val now = Instant.parse("2026-10-21T10:00:00Z") + assertFalse(ColmiDecoder.isFutureSlot(now.plusSeconds(90), now)) + assertTrue(ColmiDecoder.isFutureSlot(now.plusSeconds(180), now)) + } +} diff --git a/app/src/test/java/com/pulseloop/service/JournalInsightsTest.kt b/app/src/test/java/com/pulseloop/service/JournalInsightsTest.kt index 23d3c796..8d16167c 100644 --- a/app/src/test/java/com/pulseloop/service/JournalInsightsTest.kt +++ b/app/src/test/java/com/pulseloop/service/JournalInsightsTest.kt @@ -58,4 +58,17 @@ class JournalInsightsTest { } assertFalse(JournalInsights.effects(tags, nights).single().hasEffect) } + + @Test + fun `a big-looking difference that is only noise is not reported`() { + // HRV alternates 30/50 for everyone; the three tagged nights happen to average 36.7 + // against about 40.6 — a 10 % "drop" the old rule reported, and chance at p ≈ 0.6. + val tags = setOf(1, 3, 6).associate { start.plusDays(it.toLong()) to setOf("stress") } + val nights = (1..20).map { i -> + NightSummary(start.plusDays(i.toLong()), 0, 8 * 3600_000L, 450, 55.0, if (i % 2 == 0) 30.0 else 50.0, 1.0) + } + val e = JournalInsights.effects(tags, nights).single() + assertNull(e.hrvPct) + assertFalse(e.hasEffect) + } } diff --git a/app/src/test/java/com/pulseloop/service/StatsTest.kt b/app/src/test/java/com/pulseloop/service/StatsTest.kt new file mode 100644 index 00000000..4f9b550b --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/StatsTest.kt @@ -0,0 +1,21 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Test + +class StatsTest { + + @Test + fun `welch t-test matches a textbook value`() { + // Means 3 and 5, variance 2.5 each, n = 5: t = -2 on 8 df, two-sided p ≈ 0.0805. + assertEquals(0.0805, Stats.welchP(listOf(1.0, 2.0, 3.0, 4.0, 5.0), listOf(3.0, 4.0, 5.0, 6.0, 7.0)), 0.001) + assertEquals(1.0, Stats.welchP(listOf(2.0, 2.0), listOf(2.0, 2.0)), 0.0) + assertEquals(0.0, Stats.welchP(listOf(2.0, 2.0), listOf(3.0, 3.0)), 0.0) + } + + @Test + fun `benjamini-hochberg keeps the ranks under the line`() { + assertEquals(listOf(true, true, true, false), Stats.benjaminiHochberg(listOf(0.01, 0.04, 0.03, 0.2), 0.10)) + assertEquals(listOf(false, false), Stats.benjaminiHochberg(listOf(0.3, 0.5), 0.10)) + } +}