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
1 change: 1 addition & 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,7 @@ class PulseLoopApplication : Application() {
},
)
WidgetRefreshWorker.schedule(this)
appScope.launch { runCatching { com.pulseloop.service.StepCalibration.sample(this@PulseLoopApplication) } }
// Scheduled backups: the daily worker, plus a catch-up on start when one is overdue.
com.pulseloop.data.AutoBackup.schedule(this)
appScope.launch {
Expand Down
14 changes: 14 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchive.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ data class PulseArchive(
val foodPreferences: List<FoodPreferenceDTO> = emptyList(),
/** Drinks (v32). */
val drinks: List<DrinkEntryDTO> = emptyList(),
/** Logged periods (v34). */
val periods: List<PeriodDTO> = emptyList(),
/** Medications and supplements, and answered doses (v35). */
val meds: List<MedDTO> = emptyList(),
val medDoses: List<MedDoseDTO> = emptyList(),
)

@Serializable data class FoodPreferenceDTO(
Expand All @@ -58,6 +63,15 @@ data class PulseArchive(
val timesAgreed: Int = 1, val createdAt: Long, val updatedAt: Long,
)

@Serializable data class MedDTO(
val id: String, val name: String, val dose: String? = null, val kind: String = "medication",
val timesCsv: String, val active: Boolean = true, val createdAt: Long,
)

@Serializable data class MedDoseDTO(val id: String, val medId: String, val day: Long, val time: String, val status: String, val at: Long)

@Serializable data class PeriodDTO(val id: String, val startDay: Long, val endDay: Long? = null, val createdAt: Long)

@Serializable data class DrinkEntryDTO(
val id: String, val timestamp: Long, val day: Long, val type: String,
val volumeMl: Double, val abvPct: Double, val grams: Double, val kcal: Double,
Expand Down
19 changes: 19 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchiveService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,16 @@ object DataArchiveService {
timesAgreed = c.intOrNull("timesAgreed") ?: 1, createdAt = c.long("createdAt"), updatedAt = c.long("updatedAt"),
)
},
meds = collect("meds") { c ->
MedDTO(id = c.str("id"), name = c.str("name"), dose = c.strOrNull("dose"), kind = c.str("kind"),
timesCsv = c.str("timesCsv"), active = (c.intOrNull("active") ?: 1) == 1, createdAt = c.long("createdAt"))
},
medDoses = collect("med_doses") { c ->
MedDoseDTO(id = c.str("id"), medId = c.str("medId"), day = c.long("day"), time = c.str("time"), status = c.str("status"), at = c.long("at"))
},
periods = collect("periods") { c ->
PeriodDTO(id = c.str("id"), startDay = c.long("startDay"), endDay = c.longOrNull("endDay"), createdAt = c.long("createdAt"))
},
drinks = collect("drink_entries") { c ->
DrinkEntryDTO(
id = c.str("id"), timestamp = c.long("timestamp"), day = c.long("day"), type = c.str("type"),
Expand Down Expand Up @@ -433,6 +443,15 @@ object DataArchiveService {
timesAgreed = f.timesAgreed, createdAt = f.createdAt, updatedAt = f.updatedAt,
))
}
for (m in archive.meds) {
db.medDao().upsert(MedEntity(id = m.id, name = m.name, dose = m.dose, kind = m.kind, timesCsv = m.timesCsv, active = m.active, createdAt = m.createdAt))
}
for (d in archive.medDoses) {
db.medDao().upsertDose(MedDoseEntity(id = d.id, medId = d.medId, day = d.day, time = d.time, status = d.status, at = d.at))
}
for (p in archive.periods) {
db.periodDao().upsert(PeriodEntity(id = p.id, startDay = p.startDay, endDay = p.endDay, createdAt = p.createdAt))
}
for (d in archive.drinks) {
db.drinkDao().upsert(DrinkEntryEntity(
id = d.id, timestamp = d.timestamp, day = d.day, type = d.type, volumeMl = d.volumeMl,
Expand Down
38 changes: 37 additions & 1 deletion app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,11 @@ import com.pulseloop.data.entity.*
FoodPreferenceEntity::class,
DrinkEntryEntity::class,
FindingEntity::class,
PeriodEntity::class,
MedEntity::class,
MedDoseEntity::class,
],
version = 33,
version = 35,
exportSchema = false,
)
abstract class PulseLoopDatabase : RoomDatabase() {
Expand Down Expand Up @@ -81,6 +84,10 @@ abstract class PulseLoopDatabase : RoomDatabase() {
abstract fun drinkDao(): DrinkDao
/** "What changed" findings (v33). */
abstract fun findingDao(): FindingDao
/** Logged periods for cycle tracking (v34). */
abstract fun periodDao(): PeriodDao
/** Medications and supplements, and answered doses (v35). */
abstract fun medDao(): MedDao
abstract fun coachSummaryDao(): CoachSummaryDao
abstract fun wearableLogDao(): WearableLogDao
abstract fun rawPacketDao(): RawPacketDao
Expand Down Expand Up @@ -133,6 +140,8 @@ abstract class PulseLoopDatabase : RoomDatabase() {
"food_preferences",
"drink_entries",
"findings",
"periods",
"meds", "med_doses",
)

@Volatile private var INSTANCE: PulseLoopDatabase? = null
Expand Down Expand Up @@ -613,6 +622,31 @@ abstract class PulseLoopDatabase : RoomDatabase() {
}
}

/** v33 → v34: logged periods for cycle tracking. */
private val MIGRATION_33_34 = object : Migration(33, 34) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `periods` (`id` TEXT NOT NULL, `startDay` INTEGER NOT NULL, " +
"`endDay` INTEGER, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))"
)
}
}

/** v34 → v35: medications and supplements, and their answered doses. */
private val MIGRATION_34_35 = object : Migration(34, 35) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `meds` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `dose` TEXT, `kind` TEXT NOT NULL, " +
"`timesCsv` TEXT NOT NULL, `active` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))"
)
db.execSQL(
"CREATE TABLE IF NOT EXISTS `med_doses` (`id` TEXT NOT NULL, `medId` TEXT NOT NULL, `day` INTEGER NOT NULL, " +
"`time` TEXT NOT NULL, `status` TEXT NOT NULL, `at` INTEGER NOT NULL, PRIMARY KEY(`id`))"
)
db.execSQL("CREATE INDEX IF NOT EXISTS `index_med_doses_day` ON `med_doses` (`day`)")
}
}

private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) {
db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`")
db.execSQL(
Expand Down Expand Up @@ -712,6 +746,8 @@ abstract class PulseLoopDatabase : RoomDatabase() {
MIGRATION_30_31,
MIGRATION_31_32,
MIGRATION_32_33,
MIGRATION_33_34,
MIGRATION_34_35,
)
// Downgrades only (sideloading an older APK). A blanket destructive
// fallback would silently wipe every measurement, sleep session, and
Expand Down
51 changes: 51 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 @@ -980,3 +980,54 @@ interface FindingDao {
@Upsert
suspend fun upsertAll(rows: List<FindingEntity>)
}

@Dao
interface PeriodDao {
@Query("SELECT * FROM periods ORDER BY startDay DESC")
suspend fun all(): List<PeriodEntity>

@Query("SELECT * FROM periods ORDER BY startDay DESC")
fun allFlow(): Flow<List<PeriodEntity>>

@Upsert
suspend fun upsert(p: PeriodEntity)

@Query("DELETE FROM periods WHERE id = :id")
suspend fun delete(id: String)
}

@Dao
interface MedDao {
@Query("SELECT * FROM meds ORDER BY active DESC, name ASC")
fun allFlow(): Flow<List<MedEntity>>

@Query("SELECT * FROM meds WHERE active = 1")
suspend fun active(): List<MedEntity>

@Query("SELECT * FROM meds")
suspend fun all(): List<MedEntity>

@Upsert
suspend fun upsert(m: MedEntity)

@Query("DELETE FROM meds WHERE id = :id")
suspend fun delete(id: String)

@Query("SELECT * FROM med_doses WHERE day >= :fromDay")
fun dosesSinceFlow(fromDay: Long): Flow<List<MedDoseEntity>>

@Query("SELECT * FROM med_doses WHERE day >= :fromDay")
suspend fun dosesSince(fromDay: Long): List<MedDoseEntity>

@Query("SELECT * FROM med_doses")
suspend fun allDoses(): List<MedDoseEntity>

@Upsert
suspend fun upsertDose(d: MedDoseEntity)

@Query("DELETE FROM med_doses WHERE id = :id")
suspend fun deleteDose(id: String)

@Query("DELETE FROM med_doses WHERE medId = :medId")
suspend fun deleteDosesFor(medId: String)
}
37 changes: 37 additions & 0 deletions app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt
Original file line number Diff line number Diff line change
Expand Up @@ -432,3 +432,40 @@ data class FindingEntity(
val algorithmVersion: Int,
val createdAt: Long = System.currentTimeMillis(),
)

/** A logged period (service/Cycle.kt); days are epoch days in the user's calendar. */
@Entity(tableName = "periods")
data class PeriodEntity(
@PrimaryKey val id: String = java.util.UUID.randomUUID().toString(),
val startDay: Long,
val endDay: Long? = null,
val createdAt: Long = System.currentTimeMillis(),
)

/** A medication or supplement on a daily schedule (service/Meds.kt). [timesCsv] is "08:00,20:00". */
@Entity(tableName = "meds")
data class MedEntity(
@PrimaryKey val id: String = java.util.UUID.randomUUID().toString(),
val name: String,
val dose: String? = null,
/** "medication" or "supplement". */
val kind: String = "medication",
val timesCsv: String,
val active: Boolean = true,
val createdAt: Long = System.currentTimeMillis(),
)

/** One answered dose: taken or skipped. A past dose with no row is missed; nothing is stored for it. */
@Entity(tableName = "med_doses", indices = [Index("day")])
data class MedDoseEntity(
@PrimaryKey val id: String,
val medId: String,
/** Epoch day of the scheduled dose. */
val day: Long,
val time: String,
/** "taken" or "skipped". */
val status: String,
val at: Long = System.currentTimeMillis(),
) {
companion object { fun idFor(medId: String, day: Long, time: String) = "$medId:$day:$time" }
}
24 changes: 24 additions & 0 deletions app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ class GuidancePrefs(context: Context) {
internal var lastInactivityAt: Long
get() = p.getLong("lastInactivityAt", 0L)
set(v) = p.edit().putLong("lastInactivityAt", v).apply()
var medReminders: Boolean
get() = p.getBoolean("medReminders", true)
set(v) = p.edit().putBoolean("medReminders", v).apply()
internal var remindedDoses: Set<String>
get() = p.getStringSet("remindedDoses", emptySet()).orEmpty()
set(v) = p.edit().putStringSet("remindedDoses", v).apply()
internal var lastProgressDay: String?
get() = p.getString("lastProgressDay", null)
set(v) = p.edit().putString("lastProgressDay", v).apply()
Expand Down Expand Up @@ -102,6 +108,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork
val local = Instant.ofEpochMilli(now).atZone(zone)
val today = local.toLocalDate()
val inputs = runCatching { ReadinessRepository.loadInputs(db, now, zone) }.getOrNull() ?: return Result.success()
runCatching { com.pulseloop.service.StepCalibration.sample(ctx, now, zone) }
// Keep the "what changed" log current even when the screen isn't opened.
runCatching { com.pulseloop.service.FindingsRepository.refresh(db, now, zone) }

Expand Down Expand Up @@ -189,6 +196,22 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork
}
}

// 8. Medication doses: once per dose, from its time until it would count as missed.
runCatching {
val meds = db.medDao().active()
if (meds.isNotEmpty() && prefs.medReminders) {
val answers = db.medDao().dosesSince(today.toEpochDay())
val due = com.pulseloop.service.Meds.dosesOn(today, meds, answers, local.toLocalDateTime())
.filter { it.state == com.pulseloop.service.Meds.State.DUE && !local.toLocalTime().isBefore(java.time.LocalTime.parse(it.time)) }
val fresh = due.filter { it.id !in prefs.remindedDoses }
if (fresh.isNotEmpty()) {
val names = fresh.joinToString(", ") { it.med.name + (it.med.dose?.let { d -> " $d" } ?: "") }
notify(ctx, ID_MEDS, "Time for ${fresh.first().med.name}" + if (fresh.size > 1) " and more" else "",
"$names. Open PulseLoop to mark it taken or skipped.")
prefs.remindedDoses = (prefs.remindedDoses + fresh.map { it.id }).toList().takeLast(50).toSet()
}
}
}
// 4. Meal reminder — optional, and only while nothing has been logged for that meal.
if (prefs.mealReminder && db.userGoalDao().get()?.nutritionEnabled == true) {
val meals = db.mealEntryDao().byDay(todayStart).map { it.timestamp }
Expand All @@ -214,6 +237,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork
private const val ID_BATTERY = 3005
private const val ID_INACTIVE = 3006
private const val ID_PROGRESS = 3007
private const val ID_MEDS = 3008

/** Minutes from [now] until [target] later today or, if already past, tomorrow. */
internal fun minutesUntil(now: LocalTime, target: LocalTime): Int {
Expand Down
Loading
Loading