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
8 changes: 8 additions & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

}
}
130 changes: 130 additions & 0 deletions app/src/main/java/com/pulseloop/data/AutoBackup.kt
Original file line number Diff line number Diff line change
@@ -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<String>, keep: Int): List<String> =
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<String, String>()
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<AutoBackupWorker>(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()
}
}
5 changes: 5 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchiveService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
50 changes: 41 additions & 9 deletions app/src/main/java/com/pulseloop/ring/ColmiDecoder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<UByte>, day: LocalDate, zone: ZoneId, slotMin: Int
v: List<UByte>, day: LocalDate, zone: ZoneId, slotMin: Int, now: Instant,
): List<RingDecodedEvent> {
val packetNr = v[1].toInt()
if (packetNr == 0xFF || packetNr == 0) return emptyList()
Expand All @@ -193,16 +204,17 @@ 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
)
}
}

private fun decodeStressHistory(
v: List<UByte>, day: LocalDate, zone: ZoneId, slotMin: Int
v: List<UByte>, day: LocalDate, zone: ZoneId, slotMin: Int, now: Instant,
): List<RingDecodedEvent> {
val packetNr = v[1].toInt()
if (packetNr == 0xFF || packetNr == 0) return emptyList()
Expand All @@ -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,
Expand All @@ -222,7 +235,7 @@ object ColmiDecoder {
}

private fun decodeHRVHistory(
v: List<UByte>, day: LocalDate, zone: ZoneId, slotMin: Int
v: List<UByte>, day: LocalDate, zone: ZoneId, slotMin: Int, now: Instant,
): List<RingDecodedEvent> {
val packetNr = v[1].toInt()
if (packetNr == 0xFF || packetNr == 0) return emptyList()
Expand All @@ -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(),
Expand Down Expand Up @@ -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,
))
}

Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/pulseloop/ring/ColmiDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ class ColmiDriver(private val writer: RingCommandWriter) : WearableDriver {

private fun ingestNormal(data: ByteArray): List<RingDecodedEvent> {
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)
}
Expand Down
Loading
Loading