diff --git a/app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json b/app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json new file mode 100644 index 00000000..178ce099 --- /dev/null +++ b/app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json @@ -0,0 +1,1968 @@ +{ + "formatVersion": 1, + "database": { + "version": 32, + "identityHash": "4c98ef956993353c8c59be4837dd05ba", + "entities": [ + { + "tableName": "heart_rate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, `source` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "activity_minute", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `steps` INTEGER NOT NULL, `intensity` INTEGER NOT NULL, `kind` INTEGER NOT NULL, `heartRate` INTEGER, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "steps", + "columnName": "steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "intensity", + "columnName": "intensity", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "heartRate", + "columnName": "heartRate", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "sleep_session", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, `day` INTEGER NOT NULL DEFAULT 0, `nap` INTEGER NOT NULL DEFAULT 0, `score` INTEGER, `averageHeartRate` INTEGER, `deepMinutes` INTEGER, `lightMinutes` INTEGER, `remMinutes` INTEGER, `awakeMinutes` INTEGER, `wakeCount` INTEGER, `source` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "nap", + "columnName": "nap", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "score", + "columnName": "score", + "affinity": "INTEGER" + }, + { + "fieldPath": "averageHeartRate", + "columnName": "averageHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "deepMinutes", + "columnName": "deepMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "lightMinutes", + "columnName": "lightMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "remMinutes", + "columnName": "remMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "awakeMinutes", + "columnName": "awakeMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "wakeCount", + "columnName": "wakeCount", + "affinity": "INTEGER" + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_sleep_session_day", + "unique": false, + "columnNames": [ + "day" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sleep_session_day` ON `${TABLE_NAME}` (`day`)" + }, + { + "name": "index_sleep_session_nap_end", + "unique": false, + "columnNames": [ + "nap", + "end" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sleep_session_nap_end` ON `${TABLE_NAME}` (`nap`, `end`)" + } + ] + }, + { + "tableName": "sleep_stage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, `sessionStart` INTEGER NOT NULL, `stage` INTEGER NOT NULL, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sessionStart", + "columnName": "sessionStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_sleep_stage_sessionStart", + "unique": false, + "columnNames": [ + "sessionStart" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sleep_stage_sessionStart` ON `${TABLE_NAME}` (`sessionStart`)" + } + ] + }, + { + "tableName": "spo2", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `percent` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "percent", + "columnName": "percent", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "stress", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `value` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "hrv", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `milliseconds` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "milliseconds", + "columnName": "milliseconds", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "resting_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "skin_temperature", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `celsius` REAL NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "celsius", + "columnName": "celsius", + "affinity": "REAL", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "breath_rate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `perMinute` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "perMinute", + "columnName": "perMinute", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "pai", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `daily` REAL NOT NULL, `total` REAL NOT NULL, `restingHeartRate` INTEGER NOT NULL, `maxHeartRate` INTEGER NOT NULL, `tomorrowTotal` REAL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "daily", + "columnName": "daily", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "total", + "columnName": "total", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "restingHeartRate", + "columnName": "restingHeartRate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maxHeartRate", + "columnName": "maxHeartRate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tomorrowTotal", + "columnName": "tomorrowTotal", + "affinity": "REAL" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "hrv_sdnn", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `milliseconds` REAL NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "milliseconds", + "columnName": "milliseconds", + "affinity": "REAL", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "workout", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, `sportType` INTEGER NOT NULL, `exerciseSeconds` INTEGER, `calories` INTEGER, `averageHeartRate` INTEGER, `maxHeartRate` INTEGER, `minHeartRate` INTEGER, `aerobicTrainingEffect` REAL, `anaerobicTrainingEffect` REAL, `trainingLoad` INTEGER, `vo2max` INTEGER, `steps` INTEGER, `subtype` INTEGER, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sportType", + "columnName": "sportType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "exerciseSeconds", + "columnName": "exerciseSeconds", + "affinity": "INTEGER" + }, + { + "fieldPath": "calories", + "columnName": "calories", + "affinity": "INTEGER" + }, + { + "fieldPath": "averageHeartRate", + "columnName": "averageHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxHeartRate", + "columnName": "maxHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "minHeartRate", + "columnName": "minHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "aerobicTrainingEffect", + "columnName": "aerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "anaerobicTrainingEffect", + "columnName": "anaerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "trainingLoad", + "columnName": "trainingLoad", + "affinity": "INTEGER" + }, + { + "fieldPath": "vo2max", + "columnName": "vo2max", + "affinity": "INTEGER" + }, + { + "fieldPath": "steps", + "columnName": "steps", + "affinity": "INTEGER" + }, + { + "fieldPath": "subtype", + "columnName": "subtype", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + } + }, + { + "tableName": "workout_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, PRIMARY KEY(`workoutStart`, `timestamp`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "timestamp" + ] + } + }, + { + "tableName": "sport_effect", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`end` INTEGER NOT NULL, `recoveryMinutes` INTEGER, `vo2max` REAL, `epoc` REAL, `weeklyLoad` REAL, `monthlyLoad` REAL, `optimalLoadMin` INTEGER, `optimalLoadMax` INTEGER, `maximalHeartRate` INTEGER, PRIMARY KEY(`end`))", + "fields": [ + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recoveryMinutes", + "columnName": "recoveryMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "vo2max", + "columnName": "vo2max", + "affinity": "REAL" + }, + { + "fieldPath": "epoc", + "columnName": "epoc", + "affinity": "REAL" + }, + { + "fieldPath": "weeklyLoad", + "columnName": "weeklyLoad", + "affinity": "REAL" + }, + { + "fieldPath": "monthlyLoad", + "columnName": "monthlyLoad", + "affinity": "REAL" + }, + { + "fieldPath": "optimalLoadMin", + "columnName": "optimalLoadMin", + "affinity": "INTEGER" + }, + { + "fieldPath": "optimalLoadMax", + "columnName": "optimalLoadMax", + "affinity": "INTEGER" + }, + { + "fieldPath": "maximalHeartRate", + "columnName": "maximalHeartRate", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "end" + ] + } + }, + { + "tableName": "strap_readiness", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `score` INTEGER, `hrvScore` INTEGER, `restingHrScore` INTEGER, `skinTemperatureScore` INTEGER, `breathingScore` INTEGER, `sleepHrv` INTEGER, `sleepRestingHr` INTEGER, `algorithmVersion` TEXT NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "score", + "columnName": "score", + "affinity": "INTEGER" + }, + { + "fieldPath": "hrvScore", + "columnName": "hrvScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "restingHrScore", + "columnName": "restingHrScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "skinTemperatureScore", + "columnName": "skinTemperatureScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "breathingScore", + "columnName": "breathingScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "sleepHrv", + "columnName": "sleepHrv", + "affinity": "INTEGER" + }, + { + "fieldPath": "sleepRestingHr", + "columnName": "sleepRestingHr", + "affinity": "INTEGER" + }, + { + "fieldPath": "algorithmVersion", + "columnName": "algorithmVersion", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "sleep_spo2", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `percent` INTEGER NOT NULL, `time` INTEGER, `high` BLOB, `low` BLOB, `signalQuality` BLOB, `extend` BLOB, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "percent", + "columnName": "percent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "time", + "affinity": "INTEGER" + }, + { + "fieldPath": "high", + "columnName": "high", + "affinity": "BLOB" + }, + { + "fieldPath": "low", + "columnName": "low", + "affinity": "BLOB" + }, + { + "fieldPath": "signalQuality", + "columnName": "signalQuality", + "affinity": "BLOB" + }, + { + "fieldPath": "extend", + "columnName": "extend", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "osa_event", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `drop` INTEGER NOT NULL, `spo2` BLOB, `heartRate` BLOB, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "drop", + "columnName": "drop", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "spo2", + "columnName": "spo2", + "affinity": "BLOB" + }, + { + "fieldPath": "heartRate", + "columnName": "heartRate", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "osa_result", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`belongTime` INTEGER NOT NULL, `validTime` INTEGER NOT NULL, `odiRaw` INTEGER NOT NULL, `odiScore` INTEGER NOT NULL, `dispCode` INTEGER NOT NULL, `eventCount` INTEGER NOT NULL, `version` INTEGER NOT NULL, PRIMARY KEY(`belongTime`))", + "fields": [ + { + "fieldPath": "belongTime", + "columnName": "belongTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "validTime", + "columnName": "validTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "odiRaw", + "columnName": "odiRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "odiScore", + "columnName": "odiScore", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dispCode", + "columnName": "dispCode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventCount", + "columnName": "eventCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "belongTime" + ] + } + }, + { + "tableName": "daily_max_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "recovery_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `samples` BLOB NOT NULL, PRIMARY KEY(`workoutStart`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "samples", + "columnName": "samples", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart" + ] + } + }, + { + "tableName": "activity_extended", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `floors` INTEGER NOT NULL, `run` INTEGER NOT NULL, `fatBurn` INTEGER NOT NULL, `stand` INTEGER NOT NULL, `walk` INTEGER NOT NULL, `sit` INTEGER NOT NULL, `steps` INTEGER NOT NULL, `calories` INTEGER NOT NULL, `distanceCm` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "floors", + "columnName": "floors", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "run", + "columnName": "run", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fatBurn", + "columnName": "fatBurn", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "stand", + "columnName": "stand", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walk", + "columnName": "walk", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sit", + "columnName": "sit", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "steps", + "columnName": "steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "calories", + "columnName": "calories", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "distanceCm", + "columnName": "distanceCm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "raw_record", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`type` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `payload` BLOB NOT NULL, PRIMARY KEY(`type`, `timestamp`))", + "fields": [ + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "type", + "timestamp" + ] + } + }, + { + "tableName": "health_alert", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `type` INTEGER NOT NULL, `value` INTEGER NOT NULL, PRIMARY KEY(`timestamp`, `type`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp", + "type" + ] + } + }, + { + "tableName": "check_in", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `feeling` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "feeling", + "columnName": "feeling", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "day_tag", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `tag` TEXT NOT NULL, PRIMARY KEY(`day`, `tag`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tag", + "columnName": "tag", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day", + "tag" + ] + } + }, + { + "tableName": "night_metrics", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `hrvLn` REAL, `hrvSamples` INTEGER NOT NULL, `rhrLowest30` REAL, `rhrMeanSleep` REAL, `rhrP10` REAL, `hrMinutes` INTEGER NOT NULL, `strapHrv` INTEGER, `strapRestingHr` INTEGER, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hrvLn", + "columnName": "hrvLn", + "affinity": "REAL" + }, + { + "fieldPath": "hrvSamples", + "columnName": "hrvSamples", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rhrLowest30", + "columnName": "rhrLowest30", + "affinity": "REAL" + }, + { + "fieldPath": "rhrMeanSleep", + "columnName": "rhrMeanSleep", + "affinity": "REAL" + }, + { + "fieldPath": "rhrP10", + "columnName": "rhrP10", + "affinity": "REAL" + }, + { + "fieldPath": "hrMinutes", + "columnName": "hrMinutes", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "strapHrv", + "columnName": "strapHrv", + "affinity": "INTEGER" + }, + { + "fieldPath": "strapRestingHr", + "columnName": "strapRestingHr", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "app_workout", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER, `sportType` INTEGER NOT NULL, `source` INTEGER NOT NULL, `pauses` TEXT NOT NULL, `pausedAt` INTEGER, `endReason` INTEGER, `averageHeartRate` INTEGER, `maxHeartRate` INTEGER, `askToEnd` INTEGER NOT NULL DEFAULT 1, `recordedEnd` INTEGER, `shownStart` INTEGER, `target` TEXT, `useGps` INTEGER NOT NULL DEFAULT 0, `keepRoute` INTEGER NOT NULL DEFAULT 0, `distanceMeters` REAL, `distanceFromSteps` INTEGER NOT NULL DEFAULT 0, `rest` TEXT, `setsTarget` INTEGER, `laps` TEXT NOT NULL DEFAULT '', `epoc` REAL, `aerobicTrainingEffect` REAL, `recoveryMinutes` INTEGER, `vo2max` REAL, `anaerobicTrainingEffect` REAL, `effectFromStrap` INTEGER NOT NULL DEFAULT 0, `ownRecoveryMinutes` INTEGER, `activeKcal` REAL, `totalKcal` REAL, `targetReachedAt` INTEGER, `structure` TEXT, `stretches` TEXT, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER" + }, + { + "fieldPath": "sportType", + "columnName": "sportType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pauses", + "columnName": "pauses", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pausedAt", + "columnName": "pausedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "endReason", + "columnName": "endReason", + "affinity": "INTEGER" + }, + { + "fieldPath": "averageHeartRate", + "columnName": "averageHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxHeartRate", + "columnName": "maxHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "askToEnd", + "columnName": "askToEnd", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "recordedEnd", + "columnName": "recordedEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "shownStart", + "columnName": "shownStart", + "affinity": "INTEGER" + }, + { + "fieldPath": "target", + "columnName": "target", + "affinity": "TEXT" + }, + { + "fieldPath": "useGps", + "columnName": "useGps", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "keepRoute", + "columnName": "keepRoute", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "distanceMeters", + "columnName": "distanceMeters", + "affinity": "REAL" + }, + { + "fieldPath": "distanceFromSteps", + "columnName": "distanceFromSteps", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "rest", + "columnName": "rest", + "affinity": "TEXT" + }, + { + "fieldPath": "setsTarget", + "columnName": "setsTarget", + "affinity": "INTEGER" + }, + { + "fieldPath": "laps", + "columnName": "laps", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "epoc", + "columnName": "epoc", + "affinity": "REAL" + }, + { + "fieldPath": "aerobicTrainingEffect", + "columnName": "aerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "recoveryMinutes", + "columnName": "recoveryMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "vo2max", + "columnName": "vo2max", + "affinity": "REAL" + }, + { + "fieldPath": "anaerobicTrainingEffect", + "columnName": "anaerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "effectFromStrap", + "columnName": "effectFromStrap", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "ownRecoveryMinutes", + "columnName": "ownRecoveryMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "activeKcal", + "columnName": "activeKcal", + "affinity": "REAL" + }, + { + "fieldPath": "totalKcal", + "columnName": "totalKcal", + "affinity": "REAL" + }, + { + "fieldPath": "targetReachedAt", + "columnName": "targetReachedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "structure", + "columnName": "structure", + "affinity": "TEXT" + }, + { + "fieldPath": "stretches", + "columnName": "stretches", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_app_workout_end", + "unique": false, + "columnNames": [ + "end" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_app_workout_end` ON `${TABLE_NAME}` (`end`)" + } + ] + }, + { + "tableName": "app_workout_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, `fromHistory` INTEGER NOT NULL, PRIMARY KEY(`workoutStart`, `timestamp`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fromHistory", + "columnName": "fromHistory", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "timestamp" + ] + } + }, + { + "tableName": "app_workout_dismissed", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_app_workout_dismissed_end", + "unique": false, + "columnNames": [ + "end" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_app_workout_dismissed_end` ON `${TABLE_NAME}` (`end`)" + } + ] + }, + { + "tableName": "app_workout_route", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL, `accuracy` REAL NOT NULL, `speed` REAL, `bearing` REAL, `altitude` REAL, `speedAccuracy` REAL, `bearingAccuracy` REAL, PRIMARY KEY(`workoutStart`, `timestamp`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lat", + "columnName": "lat", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "lon", + "columnName": "lon", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "accuracy", + "columnName": "accuracy", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "speed", + "columnName": "speed", + "affinity": "REAL" + }, + { + "fieldPath": "bearing", + "columnName": "bearing", + "affinity": "REAL" + }, + { + "fieldPath": "altitude", + "columnName": "altitude", + "affinity": "REAL" + }, + { + "fieldPath": "speedAccuracy", + "columnName": "speedAccuracy", + "affinity": "REAL" + }, + { + "fieldPath": "bearingAccuracy", + "columnName": "bearingAccuracy", + "affinity": "REAL" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "timestamp" + ] + } + }, + { + "tableName": "app_workout_set", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `index` INTEGER NOT NULL, `start` INTEGER NOT NULL, `end` INTEGER, `restEnd` INTEGER, `exercise` TEXT, `reps` INTEGER, `weightKg` REAL, PRIMARY KEY(`workoutStart`, `index`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER" + }, + { + "fieldPath": "restEnd", + "columnName": "restEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "exercise", + "columnName": "exercise", + "affinity": "TEXT" + }, + { + "fieldPath": "reps", + "columnName": "reps", + "affinity": "INTEGER" + }, + { + "fieldPath": "weightKg", + "columnName": "weightKg", + "affinity": "REAL" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "index" + ] + } + }, + { + "tableName": "wear_event", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `worn` INTEGER, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "worn", + "columnName": "worn", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "habit_age_week", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`asOf` INTEGER NOT NULL, `estimate` REAL NOT NULL, `low` INTEGER NOT NULL, `high` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`asOf`))", + "fields": [ + { + "fieldPath": "asOf", + "columnName": "asOf", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "estimate", + "columnName": "estimate", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "low", + "columnName": "low", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "high", + "columnName": "high", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "asOf" + ] + } + }, + { + "tableName": "workout_deleted", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `effectEnd` INTEGER, `deletedAt` INTEGER NOT NULL, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "effectEnd", + "columnName": "effectEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + } + }, + { + "tableName": "daily_energy", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `totalKcal` REAL NOT NULL, `activeKcal` REAL NOT NULL, `bmrKcal` REAL NOT NULL, `minutesWithData` INTEGER NOT NULL, `partial` INTEGER NOT NULL, `workoutKcal` REAL NOT NULL, `walkingKcal` REAL NOT NULL, `hourly` TEXT NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalKcal", + "columnName": "totalKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "activeKcal", + "columnName": "activeKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "bmrKcal", + "columnName": "bmrKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "minutesWithData", + "columnName": "minutesWithData", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "partial", + "columnName": "partial", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workoutKcal", + "columnName": "workoutKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "walkingKcal", + "columnName": "walkingKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "hourly", + "columnName": "hourly", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "sleep_edit", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`strapStart` INTEGER NOT NULL, `nap` INTEGER NOT NULL DEFAULT 0, `start` INTEGER, `end` INTEGER, `deleted` INTEGER NOT NULL DEFAULT 0, `editedAt` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`strapStart`))", + "fields": [ + { + "fieldPath": "strapStart", + "columnName": "strapStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nap", + "columnName": "nap", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER" + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER" + }, + { + "fieldPath": "deleted", + "columnName": "deleted", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "editedAt", + "columnName": "editedAt", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "strapStart" + ] + } + }, + { + "tableName": "app_workout_round", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `index` INTEGER NOT NULL, `workStart` INTEGER NOT NULL, `workEnd` INTEGER, `restEnd` INTEGER, `peakBpm` INTEGER, PRIMARY KEY(`workoutStart`, `index`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workStart", + "columnName": "workStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workEnd", + "columnName": "workEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "restEnd", + "columnName": "restEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "peakBpm", + "columnName": "peakBpm", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "index" + ] + } + }, + { + "tableName": "saved_workout", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `sport` INTEGER NOT NULL, `structure` TEXT NOT NULL, `goal` TEXT, `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sport", + "columnName": "sport", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "structure", + "columnName": "structure", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "goal", + "columnName": "goal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "exercise", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `lastReps` INTEGER, `lastKg` REAL, `usedAt` INTEGER NOT NULL, PRIMARY KEY(`name`))", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lastReps", + "columnName": "lastReps", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastKg", + "columnName": "lastKg", + "affinity": "REAL" + }, + { + "fieldPath": "usedAt", + "columnName": "usedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "name" + ] + } + }, + { + "tableName": "personal_best", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `value` REAL NOT NULL, `date` INTEGER NOT NULL, `workoutStart` INTEGER, PRIMARY KEY(`kind`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind" + ] + } + }, + { + "tableName": "badge", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `earnedAt` INTEGER NOT NULL, `workoutStart` INTEGER, `day` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "earnedAt", + "columnName": "earnedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER" + }, + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "week_result", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`weekStart` INTEGER NOT NULL, `goal` INTEGER NOT NULL, `count` INTEGER NOT NULL, `met` INTEGER NOT NULL, PRIMARY KEY(`weekStart`))", + "fields": [ + { + "fieldPath": "weekStart", + "columnName": "weekStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "goal", + "columnName": "goal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "count", + "columnName": "count", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "met", + "columnName": "met", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "weekStart" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '4c98ef956993353c8c59be4837dd05ba')" + ] + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt index b59af8cf..bae906a8 100644 --- a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt +++ b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt @@ -50,6 +50,7 @@ class AppContainer(val app: Application) { val autoHealthConnect = org.openstrap.app.health.HealthConnectAutoSync(app, settings, healthConnect, strap, scope = appScope) val workout = org.openstrap.app.device.WorkoutSession( app, database.healthDao(), settings, strap, maxHeartRates, callRinging = { phoneAlerts.callRinging }, onSaved = autoHealthConnect::workoutSaved, + onRemoved = autoHealthConnect::workoutDiscarded, scope = appScope, ) /** Saved and the Keep recording notice, from the session's state, on the app scope (audit S10). */ diff --git a/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt b/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt index 039798ae..d000ed2f 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt @@ -85,11 +85,10 @@ class RewardsKeeper( /** Works everything out again from [workouts] against [goal] and stores it. */ suspend fun refresh(workouts: List, goal: Int) = refreshLock.withLock { - // The list starts empty before it loads: only a database with no workouts at all starts the rewards empty. - if (workouts.isEmpty()) { - if (!settings.rewardsStarted.first() && !dao.anyWorkoutOnce()) settings.startRewards(historyBadges = false) - return@withLock - } + // The list starts empty before it loads, so an empty list waits while workouts are stored. With none stored it + // is worked out all the same: the step badges and bests need no workout, and deleting the last workout takes + // its bests and its week with it. + if (workouts.isEmpty() && dao.anyWorkoutOnce()) return@withLock val f = facts(workouts) withContext(Dispatchers.Default) { val today = LocalDate.now(f.zone) diff --git a/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt b/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt index cea1ae26..ce7e4114 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt @@ -52,10 +52,12 @@ class RoomDayRepository( val span = DayWindow( SleepHistory.endingOn(date.minusDays(SleepHistory.NIGHTS - 1L), zone).from, SleepHistory.endingOn(date, zone).to, ) + // The oldest night began the evening before its day, so its readings start there, not at that midnight. + val readings = DayWindow(SleepHistory.readingsOf(date.minusDays(SleepHistory.NIGHTS - 1L), zone).from, span.to) val extras = combine(health.skinTemperature(day), health.breathRate(night), health.latestPai(day.to)) { skin, breath, pai -> Triple(skin, breath, pai?.takeIf { it.timestamp >= day.from }) } - val sleepAndExtras = combine(nights(date, night, span, zone), extras, baselines(date)) { s, e, b -> Triple(s, e, b) } + val sleepAndExtras = combine(nights(date, night, span, readings, zone), extras, baselines(date)) { s, e, b -> Triple(s, e, b) } // The strap's own running total covers steps whose minute records were already taken by another app. val todayLive = if (isToday) strapSteps else flowOf(null) @@ -117,13 +119,13 @@ class RoomDayRepository( } /** - * The day's sleep ([sleep]), the [SleepHistory.NIGHTS] nights over [span] with the vitals averaged over each, and - * the night's own readings for the charts of the night-scoped details. + * The day's sleep ([sleep]), the [SleepHistory.NIGHTS] nights over [span] with the vitals averaged over each (read over + * [readings], from the oldest night's evening), and the night's own readings for the charts of the night-scoped details. */ - private fun nights(date: LocalDate, night: DayWindow, span: DayWindow, zone: ZoneId): Flow = combine( + private fun nights(date: LocalDate, night: DayWindow, span: DayWindow, readings: DayWindow, zone: ZoneId): Flow = combine( sleep(date, span, zone), - combine(health.hrv(span), health.skinTemperature(span)) { h, s -> h to s }, - combine(health.spo2(span), health.breathRate(span)) { o, b -> o to b }, + combine(health.hrv(readings), health.skinTemperature(readings)) { h, s -> h to s }, + combine(health.spo2(readings), health.breathRate(readings)) { o, b -> o to b }, health.heartRate(night), ) { sleepParts, (hrv, skin), (spo2, breath), hr -> val (parts, sessions, osa) = sleepParts diff --git a/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt b/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt index 58f7a494..dafb73f5 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt @@ -55,7 +55,7 @@ import java.time.ZoneId BadgeRow::class, WeekResult::class, ], - version = 31, + version = 32, autoMigrations = [ AutoMigration(from = 1, to = 2), AutoMigration(from = 2, to = 3), AutoMigration(from = 3, to = 4), AutoMigration(from = 4, to = 5), AutoMigration(from = 5, to = 6), @@ -81,7 +81,7 @@ abstract class OpenStrapDatabase : RoomDatabase() { * converted ([DayKeyMigration]), so it is the phone's zone when the database first opens after the upgrade. */ fun migrations(zone: () -> ZoneId = ZoneId::systemDefault): Array = - arrayOf(WorkoutsMigration, IndicesMigration, DayKeyMigration(zone), MinuteSleepMigration) + arrayOf(WorkoutsMigration, IndicesMigration, DayKeyMigration(zone), MinuteSleepMigration, OrphanSleepEditMigration) /** [migrations] in the phone's zone. */ val MIGRATIONS = migrations() diff --git a/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt b/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt new file mode 100644 index 00000000..4778aef1 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt @@ -0,0 +1,34 @@ +package org.openstrap.app.data.db + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import org.openstrap.app.data.SleepEdits + +/** + * Version 31 to 32: the edits left behind by the nights [MinuteSleepMigration] deleted go. An edit finds a session of + * its kind within [SleepEdits.MATCH_SECONDS], so one of those could have moved or hidden a real strap night near it. + * + * Only where those nights could be: main sleeps from [FROM] to [TO], the two weeks 3.0.0 to 3.0.2 looked back over and + * the days they ran. Such an edit with no main sleep that close goes, except a marker for a deleted sleep whose time + * to restore has run out ([SleepEdits.marker]), which has none by design. Every other edit stays as it was. No schema + * change. + */ +@Suppress("MagicNumber") // The versions it runs between, and the dates the minute nights were made for, are what it is. +object OrphanSleepEditMigration : Migration(31, 32) { + /** 2026-10-20 00:00 UTC, before the earliest night 3.0.0 (7 November) could make from the minutes. */ + const val FROM = 1_792_454_400L + + /** 2026-11-12 00:00 UTC, after 3.0.3 (10 November) deleted them and made no more. */ + const val TO = 1_794_441_600L + + override fun migrate(db: SupportSQLiteDatabase) { + val keptBefore = System.currentTimeMillis() / 1000 - SleepEdits.KEEP_DAYS * 86_400L + db.execSQL( + "DELETE FROM `sleep_edit` WHERE `nap` = 0 AND `strapStart` BETWEEN ? AND ? " + + "AND NOT (`deleted` = 1 AND `start` IS NULL AND `editedAt` < ?) AND NOT EXISTS " + + "(SELECT 1 FROM `sleep_session` WHERE `sleep_session`.`nap` = 0 AND " + + "ABS(`sleep_session`.`start` - `sleep_edit`.`strapStart`) <= ${SleepEdits.MATCH_SECONDS})", + arrayOf(FROM, TO, keptBefore), + ) + } +} diff --git a/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt b/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt index a0614cae..25ff39cd 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt @@ -420,8 +420,11 @@ class HistorySync internal constructor( val headerTime = chunk.headerTime val payload = chunk.payload // The size field counts records, not bytes (activity: size 4 = four 8-byte minutes). + // A chunk it can't read ends the type as before, and the type fails, so a stop here shows instead of + // the sync saying Done while this type gets no further. What goes to the strap is the same. val unit = chunk.unit ?: run { log("history ${spec.type}: got ${payload.size} bytes for size ${chunk.sizeField}, not read") + ok = false break@loop } log( @@ -433,6 +436,7 @@ class HistorySync internal constructor( // Zepp parses after the ACK and tells the strap nothing of a parse failure. if (result is ParseResult.Failure) { log("history ${spec.type}: parse failed: ${result.reason}") + ok = false break@loop } val records = (result as ParseResult.Success).records @@ -492,13 +496,17 @@ class HistorySync internal constructor( /** * Workouts as Zepp's `pxk`: the summary, then its detail from the same cursor (04 §3.16), the next pair from the * summary's header + 1 s. The pairs are stored when the loop ends, then the cursor goes to the last workout + 1 s - * (at most now) for both 5 and 6. A failed detail fails the job and stores nothing, so the cursor stays. + * (at most now) for both 5 and 6. A failed detail fails the job and stores nothing, so the cursor stays, as Zepp's + * receiver drops what a failed job fetched. A summary that can't be read is left out and the loop goes on, as + * Zepp's, which only parses once it ends: the type fails so it shows, and the cursor passes it once a later one + * is stored. */ // Each return or break ends the loop for a reason of its own. @Suppress("ReturnCount", "LoopWithTooManyJumpStatements") private suspend fun syncWorkouts(spec: HistoryTypeSpec): Boolean { var cursor = startOf(spec.type, System.currentTimeMillis() / 1000) val pairs = mutableListOf() + var unreadable = 0 while (true) { if (fastRecharge) return false when (val w = client.fetchWorkout(cursor, zone)) { @@ -508,6 +516,13 @@ class HistorySync internal constructor( if (w.fastRecharge) fastRecharge = true return false } + // Left out, and the ones after it still come: the type fails, so it shows, but nothing is held up. + is WorkoutFetch.Unreadable -> { + log("history workout from ${Instant.ofEpochSecond(w.nextCursor - 1)}: ${w.reason}, left out") + unreadable++ + if (w.nextCursor <= cursor) break + cursor = w.nextCursor + } is WorkoutFetch.Workout -> { if (w.retryDetail) { log("history workout: detail failed, nothing stored"); return false } pairs += w @@ -516,14 +531,14 @@ class HistorySync internal constructor( } } } - if (pairs.isEmpty()) return true + if (pairs.isEmpty()) return unreadable == 0 for (w in pairs) storeWorkout(w) val now = System.currentTimeMillis() / 1000 val last = pairs.maxOf { it.summary.trackId } + 1 val saved = if (last > now) now else last save(HistoryDataType.SPORT_SUMMARY, saved, now) save(HistoryDataType.SPORT_DETAIL, saved, now) - return true + return unreadable == 0 } private suspend fun storeWorkout(w: WorkoutFetch.Workout) { diff --git a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt index 65f68453..006eeb9d 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt @@ -32,6 +32,8 @@ internal class SavedWorkoutEditor( private val scope: CoroutineScope, /** The route and step totals still in memory for the workout [start] (the last one recorded), else null. */ private val track: (start: Long) -> WorkoutDistance.Track? = { null }, + /** The workout [start] was deleted, with all it was recorded over, [from] to [to]: auto sync takes it out of Health Connect. */ + private val onRemoved: (start: Long, from: Long, to: Long) -> Unit = { _, _, _ -> }, ) { /** * Deletes a phone workout, and closes its summary if it is the one showing. The strap's own records of it @@ -44,7 +46,10 @@ internal class SavedWorkoutEditor( // One transaction: not deleted, nothing is, its summary stays, and Discard can be tried again. val w = catching { dao.discardAppWorkout(start, clock()) } .onFailure { log("workout not discarded: ${it.message}") }.getOrElse { return@withLock } - if (w?.end != null) refreshDays(w.start, w.recordedEnd ?: w.end) + if (w?.end != null) { + refreshDays(w.start, w.recordedEnd ?: w.end) + onRemoved(w.start, w.start, w.recordedEnd ?: w.end) + } onDiscarded(start) } } @@ -93,7 +98,9 @@ internal class SavedWorkoutEditor( scope.launch { lock.withLock { val w = catching { dao.appWorkoutOnce(start) }.getOrNull()?.takeIf { it.end != null } ?: return@withLock - val changed = change(w).let { c -> if (c.from == w.from && c.end == w.end) c else withDistance(w, c) } + val changed = change(w).let { c -> + if (c.from == w.from && c.end == w.end) c else trackOf(w).let { withStretches(withDistance(w, c, it), it) } + } if (changed == w) return@withLock catching { dao.upsertAppWorkout(withEffect(changed, dao.appWorkoutHeartRateOnce(start))) } .onFailure { log("workout edit not saved: ${it.message}") } @@ -105,21 +112,37 @@ internal class SavedWorkoutEditor( } } + /** What [old]'s distance and stretches are worked out from again: the route and step totals in memory, or a kept route. */ + private suspend fun trackOf(old: AppWorkout): WorkoutDistance.Track? = track(old.start) ?: run { + if (!old.keepRoute) return@run null + catching { dao.routeOnce(old.start).map { it.point } }.getOrNull() + ?.let { WorkoutDistance.Track(it, emptyList(), null, routeSince = old.start, stepsSince = old.start) } + } + /** - * [new], a new range of [old], with the distance over it ([WorkoutDistance]): from the route and step totals in - * memory, or a kept route, and without either [old]'s by the share of moving time kept. + * [new], a new range of [old], with the distance over it ([WorkoutDistance]): from [track], and without it + * [old]'s by the share of moving time kept. */ - private suspend fun withDistance(old: AppWorkout, new: AppWorkout): AppWorkout { - val track = track(old.start) ?: run { - if (!old.keepRoute) return@run null - catching { dao.routeOnce(old.start).map { it.point } }.getOrNull() - ?.let { WorkoutDistance.Track(it, emptyList(), null, routeSince = old.start, stepsSince = old.start) } - } + private fun withDistance(old: AppWorkout, new: AppWorkout, track: WorkoutDistance.Track?): AppWorkout { val shown = track?.let { WorkoutDistance.shown(new, clock(), it) } return if (shown != null) new.copy(distanceMeters = shown.first, distanceFromSteps = shown.second) else new.copy(distanceMeters = WorkoutDistance.scaledTo(old, new)) } + /** + * [w] with its fastest stretches worked out again over the range it shows, as when it was saved: a trim can leave a + * stretch that started outside it, and an undo needs ones never worked out. Left as they are without the whole route. + */ + private fun withStretches(w: AppWorkout, track: WorkoutDistance.Track?): AppWorkout { + val end = w.end + // Only a route from the start: one picked up after a restart would lose the stretches before it. + val whole = track?.takeIf { it.routeSince <= w.start && it.route.isNotEmpty() } + if (end == null || whole == null) return w + val stretches = org.openstrap.app.data.Rewards.stretches(whole.route.filter { it.t in w.from..end }, w.pauseRanges) + .let(org.openstrap.app.data.Rewards.Stretch::format) + return w.copy(stretches = stretches) + } + /** Writes the daily calories rows from [from] to [to] again ([org.openstrap.app.data.DailyCaloriesHistory.updateDays]). */ suspend fun refreshDays(from: Long, to: Long) { catching { org.openstrap.app.data.DailyCaloriesHistory(dao).updateDays(from, to, settings.profile.first()) } diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt index 6b195149..c3a423ac 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt @@ -388,7 +388,8 @@ class StrapManager( val write = SettingsCodec.calorieTargetFor(group, kcal) if (write != null) { val ack = commands.command(Endpoints.SETTINGS, write) - log(if (SettingsCodec.isWriteSuccess(ack)) "calorie goal sent: $kcal" else "calorie goal refused: ${ack.toHex()}") + if (!SettingsCodec.isWriteSuccess(ack)) return@catching log("calorie goal refused: ${ack.toHex()}") + log("calorie goal sent: $kcal") } settings.setSentToStrap(SENT_CALORIE_GOAL, kcal.toLong()) }.onFailure { log("calorie goal send failed: $it") } diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt index 1351d606..7bdf36fe 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt @@ -37,7 +37,7 @@ internal object WorkoutDistance { val lo = maxOf(from, since) val memory = when { lo >= to -> null - gps -> route(track.route, lo, to, w.pauseRanges) to false + gps -> withSteps(w, track, lo, to) else -> steps(w, track, lo, to)?.let { it to true } } // Before a restart only the stored total is left, so the part of it the range keeps is its share of the time. @@ -48,6 +48,19 @@ internal object WorkoutDistance { return (memory?.first ?: 0f) + (earlier?.first ?: 0f) to (memory?.second == true || earlier?.second == true) } + /** + * The route's metres from [lo] to [to], with the steps walked before its first fix in front of them, since GPS + * takes a while to settle and those metres are real. Counted as from steps only when they are most of the + * distance, so a run GPS followed nearly all the way stays a GPS run. + */ + private fun withSteps(w: AppWorkout, track: Track, lo: Long, to: Long): Pair { + val metres = route(track.route, lo, to, w.pauseRanges) + val fix = Route.clean(track.route).first().t + val start = maxOf(lo, track.stepsSince) + val before = if (fix > start) steps(w, track, start, minOf(fix, to)) ?: 0f else 0f + return metres + before to (before > metres) + } + /** [w] with its distance over the range it shows ([shown]), or as it was when nothing says. */ fun withShown(w: AppWorkout, now: Long, track: Track): AppWorkout = shown(w, now, track)?.let { (m, steps) -> w.copy(distanceMeters = m, distanceFromSteps = steps) } ?: w diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt index e7c73a6b..4789a2ba 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -136,6 +136,8 @@ class WorkoutSession( private val callRinging: () -> Boolean = { false }, /** A finished workout was saved or changed, by its start: auto sync writes it to Health Connect. Returns at once. */ private val onSaved: (start: Long) -> Unit = {}, + /** A saved workout was deleted, by its start and the range it was recorded over: auto sync takes it out of Health Connect. */ + onRemoved: (start: Long, from: Long, to: Long) -> Unit = { _, _, _ -> }, /** Epoch seconds now. Tests pass a clock they move by hand. */ private val clock: () -> Long = { System.currentTimeMillis() / 1000 }, /** Where the workout's long-lived work runs: the app's scope, `AppContainer.appScope`. */ @@ -150,7 +152,7 @@ class WorkoutSession( /** Discard, trim and save from history: changes to workouts already saved, under the same [lock]. */ private val editor = SavedWorkoutEditor( dao, settings, lock, onSaved, onDiscarded = ::closeDiscarded, log = { log(it) }, clock = clock, scope = scope, - track = { start -> if (start == trackStart) track() else null }, + track = { start -> if (start == trackStart) track() else null }, onRemoved = onRemoved, ) /** @@ -266,15 +268,21 @@ class WorkoutSession( val w = dao.activeAppWorkout() ?: return@withLock null val now = now() val stored = dao.appWorkoutHeartRateOnce(w.start) - val last = maxOf(w.start, stored.maxOfOrNull { it.timestamp } ?: w.start) + // A kept route comes back. One that wasn't kept was only ever in memory, and so were the step totals. + val restored = if (w.keepRoute) dao.routeOnce(w.start).map { it.point } else emptyList() + val sets = dao.setsOnce(w.start) + val rounds = if (w.structure != null) dao.roundsOnce(w.start) else emptyList() + val last = lastKnown(w, stored, restored, sets, rounds) val waits = now - last > LEFT_RECORDING_S - // Paused, nothing the strap measured since is part of it. - if (waits && w.pausedAt != null) { + // Paused, nothing the strap measured since is part of it. Ending it then would leave under a minute only + // when nothing of it was stored: it comes back paused instead, for the wearer to end or delete. + if (waits && w.pausedAt != null && keptEndingAt(w, last)) { endLeftRecording(w, last) return@withLock null } - // Set before it shows as recording, so an End tapped at once already waits for the strap. - left = if (waits) LeftRecording.Left(w.start, last, now) else null + // Set before it shows as recording, so an End tapped at once already waits for the strap. One left paused + // only gets here when ending it would delete it: it doesn't wait. + left = if (waits && w.pausedAt == null) LeftRecording.Left(w.start, last, now) else null _recent.value = stored.filter { !it.fromHistory && it.timestamp >= now - RECENT_S }.map { it.timestamp to it.bpm } sum = stored.sumOf { it.bpm.toLong() } count = stored.size.toLong() @@ -295,20 +303,16 @@ class WorkoutSession( synchronized(allReadings) { allReadings.clear(); allReadings.addAll(live) } _history.value = live window = live.filter { it.first >= now - STOP_WINDOW_S } - // A kept route comes back. One that wasn't kept was only ever in memory, and so were the step - // totals. What was stored then stands for the time before now, and the distance adds to it. - val restored = if (w.keepRoute) dao.routeOnce(w.start).map { it.point } else emptyList() + // What was stored stands for the time before now, and the distance adds to it. _route.update { restored } savedPoints = _route.value.size trackFrom(w, routeSince = if (w.keepRoute) w.start else now, stepsSince = now, before = w) // A restart mustn't ask at once about a stop it can't see the start of. askSince = now - val sets = dao.setsOnce(w.start) val restUntil = sets.lastOrNull()?.takeIf { it.end != null && it.restEnd == null }?.let { it.end!! + restRule(w).seconds } // Logging is the sport's setting at its start, which Ready saved then. val log = catching { settings.sportSettings.first()[org.openstrap.app.data.Workouts.tileType(w.sportType)]?.log } .onFailure { log("workout: sport settings not read: $it") }.getOrNull() == true - val rounds = if (w.structure != null) dao.roundsOnce(w.start) else emptyList() begin(w, maxHr) { it.copy( sets = sets, restUntil = restUntil, exercise = sets.lastOrNull()?.exercise, logSets = log, rounds = rounds, @@ -540,7 +544,7 @@ class WorkoutSession( val l = left ?: return finish(null, AppWorkout.END_USER, toStrap) scope.launch { val v = judge(l, final = true) - if (v is LeftRecording.Verdict.End) finish(v.at, AppWorkout.END_AUTO, toStrap, startOf = l.start) + if (v is LeftRecording.Verdict.End) finish(v.at, AppWorkout.END_AUTO, toStrap, startOf = l.start, ifShort = IfShort.EndAsRecorded) else finish(null, AppWorkout.END_USER, toStrap) } } @@ -557,8 +561,21 @@ class WorkoutSession( _state.update { s -> (s as? WorkoutState.Recording)?.takeIf { it.endPrompt != null }?.copy(endPrompt = null, inCar = false) ?: s } } - /** [toStrap] false when the strap ended its session itself. [startOf]: only if it is still that workout recording. */ - private fun finish(at: Long?, reason: Int, toStrap: Boolean = true, startOf: Long? = null) { + /** What an end the app worked out ([LeftRecording]) does when it would leave under a minute, which deletes it. */ + private enum class IfShort { + /** Deleted, as any workout under a minute. */ + Delete, + /** Not ended: it records on for the wearer to end or delete (an end nobody chose). */ + RecordOn, + /** Ended where it was recorded to (End was tapped, so it ends, but not by deleting it). */ + EndAsRecorded, + } + + /** + * [toStrap] false when the strap ended its session itself. [startOf]: only if it is still that workout recording. + * [ifShort]: what an end at [at] that would leave under a minute does instead. + */ + private fun finish(at: Long?, reason: Int, toStrap: Boolean = true, startOf: Long? = null, ifShort: IfShort = IfShort.Delete) { scope.launch { lock.withLock { val r = _state.value as? WorkoutState.Recording ?: return@withLock @@ -571,10 +588,20 @@ class WorkoutSession( saveDistance() val w = r.workout val recorded = w.pausedAt ?: now() - val end = at?.coerceIn(w.start, recorded) ?: recorded + // Nothing said how long a workout left recording ran: deleting it would lose one the wearer started. + val asked = at?.coerceIn(w.start, recorded) ?: recorded + val short = !keptEndingAt(w, asked) + if (short && ifShort == IfShort.RecordOn) { + log("workout left recording: ending at ${java.time.Instant.ofEpochSecond(asked)} would delete it, it records on") + ending = false + left = null + return@withLock + } + val end = if (short && ifShort == IfShort.EndAsRecorded) recorded else asked + val endReason = if (end == asked) reason else AppWorkout.END_USER // Its distance written here, over the range it shows: an update() queued behind this lock would find // the workout already ended, and an early End leaves out what came after. - val ended = w.copy(end = end, pausedAt = null, endReason = reason, recordedEnd = recorded.takeIf { it > end }) + val ended = w.copy(end = end, pausedAt = null, endReason = endReason, recordedEnd = recorded.takeIf { it > end }) .let { WorkoutDistance.withShown(it, recorded, track()) } val kept = WorkoutRecorder.activeSeconds(ended, end) >= MIN_SAVED_S closeLast(r.sets, r.rounds, end) @@ -633,6 +660,24 @@ class WorkoutSession( } } + /** + * The last moment anything stored says [w] went on: its heart rate [stored], its kept [route], its [sets] and + * [rounds], its laps and pauses. Never before its start. Without the strap's heart rate a GPS run still has its + * route, so it isn't taken as ended at its start. + */ + private fun lastKnown( + w: AppWorkout, stored: List, route: List, + sets: List, rounds: List, + ): Long = ( + stored.map { it.timestamp } + route.map { it.t } + w.lapMarks + w.pauseRanges.map { it.last } + + listOfNotNull(w.pausedAt) + sets.flatMap { listOfNotNull(it.start, it.end, it.restEnd) } + + rounds.flatMap { listOfNotNull(it.workStart, it.workEnd, it.restEnd) } + ).fold(w.start, ::maxOf) + + /** Whether [w] ended at [end] would be kept: [MIN_SAVED_S] active, or it is deleted as a mis-tap. */ + private fun keptEndingAt(w: AppWorkout, end: Long): Boolean = + WorkoutRecorder.activeSeconds(w.copy(end = end, pausedAt = null), end) >= MIN_SAVED_S + /** * A workout the app was killed during while paused, with no reading for [LEFT_RECORDING_S]: ended at its [last] * reading, as End then would have, and its summary shows. Nothing after [last] is part of it, so a gap fill has @@ -682,7 +727,7 @@ class WorkoutSession( when (v) { is LeftRecording.Verdict.End -> { log("workout left recording: ${v.why}, ended at ${java.time.Instant.ofEpochSecond(v.at)}") - finish(v.at, AppWorkout.END_AUTO, startOf = l.start) + finish(v.at, AppWorkout.END_AUTO, startOf = l.start, ifShort = IfShort.RecordOn) } LeftRecording.Verdict.CarryOn -> { log("workout left recording: still under way, it records on") @@ -840,7 +885,8 @@ class WorkoutSession( /** "+30 s". */ fun extendRest() = editSets { r -> r.restUntil?.let { r.copy(restUntil = it + org.openstrap.app.data.Strength.EXTEND_S) } ?: r } - private fun editSets(change: (WorkoutState.Recording) -> WorkoutState.Recording) { + /** [change] to the sets under the lock, saved; [then] runs once it is applied, not when it changed nothing. */ + private fun editSets(then: (() -> Unit)? = null, change: (WorkoutState.Recording) -> WorkoutState.Recording) { scope.launch { lock.withLock { val r = _state.value as? WorkoutState.Recording ?: return@withLock @@ -855,18 +901,31 @@ class WorkoutSession( ?.copy(sets = changed.sets, restUntil = changed.restUntil, exercise = changed.exercise) ?.withSave(SavePart.Sets, failed) ?: it } + then?.invoke() } } } - /** Once a second while resting: rest is over at its time, or once heart rate holds below the chosen level. */ + /** + * Once a second while resting: rest is over at its time, or once heart rate holds below the chosen level. Never + * while paused. Decided again under the lock, so a set started or +10 s tapped meanwhile wins, and the cue only + * plays for a rest it really ended. + */ private fun checkRest() { val r = _state.value as? WorkoutState.Recording ?: return - val until = r.restUntil ?: return - val last = r.sets.lastOrNull()?.end ?: return - if (!org.openstrap.app.data.Strength.restOver(restRule(r.workout), last, until, window, now())) return - editSets { it.copy(sets = it.sets.dropLast(1) + it.sets.last().copy(restEnd = now()), restUntil = null) } - cue(org.openstrap.app.data.Cue.RestOver) + if (restEnded(r) == null) return + editSets(then = { cue(org.openstrap.app.data.Cue.RestOver) }) { restEnded(it) ?: it } + } + + /** [r] with its rest ended now, when a finished set's rest is under way, not paused, and over; else null. */ + private fun restEnded(r: WorkoutState.Recording): WorkoutState.Recording? { + val until = r.restUntil.takeIf { !r.paused } + val last = r.sets.lastOrNull()?.takeIf { it.restEnd == null } + val setEnd = last?.end + val over = until != null && setEnd != null && + org.openstrap.app.data.Strength.restOver(restRule(r.workout), setEnd, until, window, now()) + if (!over || last == null) return null + return r.copy(sets = r.sets.dropLast(1) + last.copy(restEnd = now()), restUntil = null) } /* ------------------------------------------- Rounds -------------------------------------------- */ diff --git a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt index 584b2d7e..a45fd5e0 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt @@ -121,9 +121,21 @@ class AutoBackup( var written = false try { (resolver.openOutputStream(temp.uri, "w") ?: throw Failed(BackupFailure.CantWrite)).use { backups.writeZip(it) } - // A second run on the same day replaces the first. - dir.findFile(name)?.delete() - if (!temp.renameTo(name)) copyAs(dir, temp, name) + // A second run on the same day replaces the first, but only once the new one is in place: the old one is + // moved aside, and put back if the new one can't be written. A provider that can't rename deletes it first, + // as before: the new one is complete by then. + val aside = BackupFiles.asideName(today) + val previous = dir.findFile(name) + val movedAside = previous != null && previous.renameTo(aside) + if (previous != null && !movedAside && !previous.delete()) throw Failed(BackupFailure.CantWrite) + var installed = false + try { + if (!temp.renameTo(name)) copyAs(dir, temp, name) + installed = true + } finally { + if (!installed && movedAside) runCatching { dir.findFile(aside)?.renameTo(name) } + } + dir.findFile(aside)?.let(::deleteQuietly) written = true } finally { // Failed or cancelled part way: the temp copy goes, and the failure itself is what's reported. diff --git a/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt b/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt index 23261e70..da3b3da3 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt @@ -16,7 +16,7 @@ object BackupFiles { // Before the app was renamed unstrap its backups were "OpenStrap-backup-". Both stay ours, so old backups are // still found, kept in the count and deleted in turn. private val BACKUP = Regex("""^(?:unstrap|OpenStrap)-backup-(\d{4}-\d{2}-\d{2})\.zip$""") - private val TEMP = Regex("""^(?:unstrap|OpenStrap)-backup-\d{4}-\d{2}-\d{2}\.part$""") + private val TEMP = Regex("""^(?:unstrap|OpenStrap)-backup-\d{4}-\d{2}-\d{2}(?:-previous)?\.part$""") /** "unstrap-backup-2026-10-29.zip". */ fun name(date: LocalDate): String = "unstrap-backup-$date.zip" @@ -24,6 +24,9 @@ object BackupFiles { /** The name a backup is written under until it is complete. Not .zip, so no provider adds an extension to it. */ fun tempName(date: LocalDate): String = "unstrap-backup-$date.part" + /** The name the earlier backup of the same day waits under while its replacement is put in place. Counts as a temp. */ + fun asideName(date: LocalDate): String = "unstrap-backup-$date-previous.part" + /** The day a backup file was made, or null when [name] isn't one of ours. */ fun dateOf(name: String): LocalDate? = BACKUP.matchEntire(name)?.groupValues?.get(1)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } diff --git a/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt b/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt index 12d6432c..aef22ef7 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt @@ -116,6 +116,16 @@ class HealthConnectAutoSync( } } + /** A phone workout was deleted: takes its session and distance out of Health Connect now, as it is saved now. */ + fun workoutDiscarded(start: Long, from: Long, to: Long) { + scope.launch { + guarded("workout $start deleted") { + exporter.deleteWorkout(start, from, to) + Log.i(TAG, "health connect: took out workout $start") + } + } + } + /** * A sleep or nap the strap started at [strapStart] was moved, deleted or brought back: writes its night again now * ([AutoHealthConnect.sleepRange]), not on the next sync, so Health Connect moves or drops it too. diff --git a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt index f8c05881..777815dc 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt @@ -305,6 +305,14 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt return records.size } + /** + * The phone workout [start], deleted, taken out of Health Connect: its exercise session and distance, found within + * [from, to], all it was recorded over. Its days' calories are written again by the next sync, as any change to them. + */ + suspend fun deleteWorkout(start: Long, from: Long, to: Long) { + writeLock.withLock { store.dropPhoneWorkout(start, from, to) } + } + /** * Active kcal an hour and each finished full day's total ([CalorieRecords]) over the whole local days [from] to * [to] are in, from the stored days, each only with its permission granted. A day worked out again can lose an @@ -665,6 +673,25 @@ internal suspend fun RecordStore.dropStaleStrapWorkouts(from: Long, to: Long, wr stale.chunked(HC_BATCH).forEach { deleteIds(androidx.health.connect.client.records.ExerciseSessionRecord::class, it) } } +/** + * Takes out OpenStrap's own exercise session and distance records of the phone workout [start], found within + * [from, to] (all it was recorded over): the workout was deleted. Nothing is taken out when the records can't be read. + */ +internal suspend fun RecordStore.dropPhoneWorkout(start: Long, from: Long, to: Long) { + // A day wider each side: the ids pick the records, so the range only has to hold them, however the filter treats + // a session's ends. + val range = TimeRangeFilter.between( + Instant.ofEpochSecond(from).minus(Duration.ofDays(1)), Instant.ofEpochSecond(to).plus(Duration.ofDays(1)), + ) + for ((type, id) in listOf( + androidx.health.connect.client.records.ExerciseSessionRecord::class to "openstrap:workout:$start", + androidx.health.connect.client.records.DistanceRecord::class to "openstrap:distance:$start", + )) { + val stale = ownRecords(type, range).orEmpty().filter { it.metadata.clientRecordId == id }.map { it.metadata.id } + stale.chunked(HC_BATCH).forEach { deleteIds(type, it) } + } +} + /** The blood oxygen percents that are kept, and so exported: Zepp's range. */ private val SPO2_KEPT = 80..100 diff --git a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt index f6a0375f..912a4454 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt @@ -174,7 +174,7 @@ fun AlarmsScreen( } ScreenList(contentPadding, gutter = GlowLayout.Gutter) { item { PageHeader(stringResource(R.string.you_alarms_title), onBack) } - state.error?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } + (state.error ?: state.alarmsError)?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } if (state.loading) { item { PagePanel { PageNote(stringResource(R.string.you_alarms_reading)) } } return@ScreenList @@ -195,7 +195,7 @@ fun HealthAlertsScreen(vm: AlarmsViewModel, state: AlarmsUiState, contentPadding BackHandler(onBack = onBack) ScreenList(contentPadding, gutter = GlowLayout.Gutter) { item { PageHeader(stringResource(R.string.you_health_title), onBack) } - state.error?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } + (state.error ?: state.healthError)?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } if (state.loading) { item { PagePanel { PageNote(stringResource(R.string.you_alarms_reading)) } } return@ScreenList diff --git a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt index aab7ec08..dd8bb0fa 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt @@ -32,12 +32,17 @@ sealed interface AlarmsRead { data class AlarmsUiState( /** * Loading until the first read ends. Failed means no read has ever worked, so [caps] and [alarms] are unknown and the - * screen must not show them as "no alarms". Once Loaded it stays Loaded: a later failed read only sets [error]. + * screen must not show them as "no alarms". Once Loaded it stays Loaded: a later failed read only sets [alarmsError]. */ val read: AlarmsRead = AlarmsRead.Loading, /** A write is in flight; controls are disabled meanwhile. */ val busy: Boolean = false, + /** A failed write's reason. */ val error: String? = null, + /** Why the alarms read failed, if it did; shown on the Alarms page only. */ + val alarmsError: String? = null, + /** Why the health settings read failed, if it did; shown on the Health page only. */ + val healthError: String? = null, val caps: AlarmCapabilities? = null, val alarms: List = emptyList(), val health: SettingsGroup? = null, @@ -149,31 +154,39 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() { refreshPending = false if (again) { _state.update { it.copy(busy = true) } - readAll(null) + // The write's reason stays up: the queued read isn't what the user is waiting to hear about. + readAll(error) } error == null } } - /** Re-reads alarms and health from the strap. [error] is the failed write's reason, if any, and wins over a read failure's. */ + /** + * Re-reads alarms and health from the strap, each on its own so one failing doesn't hide the other. [error] is the + * failed write's reason, if any; a read failure is kept apart from it ([AlarmsUiState.alarmsError], [AlarmsUiState.healthError]). + */ private suspend fun readAll(error: String?) { // The raw failure goes to Diagnostics, and the screen says it in plain words ([ErrorCopy.strap]). - val read = catching { + val alarmsRead = catching { val (caps, alarms) = strap.readAlarms() - Triple(caps, alarms.sortedWith(compareBy({ it.hour }, { it.minute })), strap.readHealthSettings()) + caps to alarms.sortedWith(compareBy({ it.hour }, { it.minute })) }.onFailure { (strap as? StrapManager)?.log("alarms: read from the strap failed: $it") } + val healthRead = catching { strap.readHealthSettings() } + .onFailure { (strap as? StrapManager)?.log("alarms: health settings read from the strap failed: $it") } _state.update { s -> - read.fold( - { (caps, alarms, health) -> - s.copy(read = AlarmsRead.Loaded, busy = false, error = error, caps = caps, alarms = alarms, health = health) - }, + val withAlarms = alarmsRead.fold( + { (caps, alarms) -> s.copy(read = AlarmsRead.Loaded, caps = caps, alarms = alarms, alarmsError = null) }, { e -> - val failed = error ?: ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed)) + val failed = ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed)) // Without an earlier good read there is nothing to show; with one, keep showing it beside the error. - val next = if (s.read is AlarmsRead.Loaded) s.read else AlarmsRead.Failed(failed) - s.copy(read = next, busy = false, error = failed) + s.copy(read = if (s.read is AlarmsRead.Loaded) s.read else AlarmsRead.Failed(failed), alarmsError = failed) }, ) + // A failed re-read keeps the last good settings. + healthRead.fold( + { health -> withAlarms.copy(health = health, healthError = null) }, + { e -> withAlarms.copy(healthError = ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed))) }, + ).copy(busy = false, error = error) } } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt index a289afa2..8b1248f7 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt @@ -31,7 +31,7 @@ import org.openstrap.app.ui.theme.MetricColors /** The scale on the Healthspan screen's bars: a habit this many years either side of the middle fills its half. */ private const val BAR_FULL_YEARS = 1.5f -/** "Updated Sunday, next in 5 days", from the Sunday the estimate was made. */ +/** "Updated Sunday, next in 5 days", from the Sunday the estimate was made; a week old or more says only that it's weekly. */ @Composable @ReadOnlyComposable private fun updatedText(asOf: Long): String { @@ -40,6 +40,7 @@ private fun updatedText(asOf: Long): String { return when (next) { 7 -> stringResource(R.string.glow_healthspan_updated_today) 1 -> stringResource(R.string.glow_healthspan_updated_tomorrow) + 0 -> stringResource(R.string.glow_healthspan_updated_weekly) else -> pluralStringResource(R.plurals.glow_healthspan_updated_next, next, next) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt index 660dee66..eb868fb9 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt @@ -267,7 +267,7 @@ fun WeeklyRecapPage(view: RewardsView?, first: LocalDate, contentPadding: Paddin GoalWeekCard( stringResource(if (week?.met == true) R.string.glow_goals_goal_met else R.string.glow_goals_weekly_goal), count, goal, weekDots(view, first), - if (run > 0) { + if (week?.met == true && run > 0) { pluralStringResource(R.plurals.glow_goals_weekly_streak, run, run) } else { (goal - count).coerceAtLeast(0).let { pluralStringResource(R.plurals.glow_goals_short_of_goal, it, it) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt index fe84f616..21aaae3c 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt @@ -5,6 +5,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -14,13 +15,13 @@ import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChangedBy -import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -175,11 +176,29 @@ class AppRootViewModel( val rewardsView: StateFlow = combine(workouts, goals.map { it.workoutsPerWeek }, dao.personalBests(), dao.badges()) { list, goal, bests, earned -> RewardsInputs(list, goal, bests, earned) - }.filter { it.workouts.isNotEmpty() || !dao.anyWorkoutOnce() } - .mapLatest { i -> catching { rewards.view(i.workouts, i.goal, i.bests, i.earned) }.getOrNull() } + }.mapLatest { i -> viewOf(i, dao) } + // Null is the list still loading, or a view that couldn't be worked out: what showed before stays. + .filterNotNull() .flowOn(work) .state(null) + /** + * The rewards page for [i], tried [VIEW_TRIES] times [VIEW_RETRY_MS] apart, as a read can hit a locked database. + * Null while the list is still loading (empty with workouts stored), or when every try failed. + */ + // Each return is a way it ends: still loading, worked out, or every try failed. + @Suppress("ReturnCount") + private suspend fun viewOf(i: RewardsInputs, dao: HealthDao): RewardsView? { + repeat(VIEW_TRIES) { n -> + if (n > 0) delay(VIEW_RETRY_MS) + catching { + if (i.workouts.isEmpty() && dao.anyWorkoutOnce()) return null + return rewards.view(i.workouts, i.goal, i.bests, i.earned) + }.onFailure { Log.w(TAG, "rewards page not worked out", it) } + } + return null + } + private class RewardsInputs( val workouts: List, val goal: Int, @@ -199,11 +218,12 @@ class AppRootViewModel( // (workouts spec 4), and on a new goal. The one recording isn't in it until it ends. Started at once, as the // weekly recap notification reads what's stored. val recording = workout.state.map { (it as? WorkoutState.Recording)?.workout?.start }.distinctUntilChanged() + // Each sync too: the step badges and the most steps follow the days' steps, which only a sync writes. viewModelScope.launch(work) { - combine(workouts, recording, settings.goals) { list, start, g -> + val inputs = combine(workouts, recording, settings.goals) { list, start, g -> list.filter { it.workout.start != start } to g.workoutsPerWeek - } - .distinctUntilChangedBy { (list, goal) -> list.map { Triple(it.workout.start, it.shownStart, it.end) } to goal } + }.distinctUntilChangedBy { (list, goal) -> list.map { Triple(it.workout.start, it.shownStart, it.end) } to goal } + combine(inputs, strap.syncEnded.onSubscription { emit(Unit) }) { i, _ -> i } .collectLatest { (list, goal) -> catching { rewards.refresh(list, goal) }.onFailure { Log.w(TAG, "rewards failed", it) } } } } @@ -289,5 +309,7 @@ class AppRootViewModel( private companion object { const val TAG = "unstrap" const val STOP_MS = 5_000L + const val VIEW_TRIES = 3 + const val VIEW_RETRY_MS = 2_000L } } diff --git a/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt b/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt index 15c34581..fd1f4c69 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt @@ -115,6 +115,34 @@ class RewardsKeeperTest { assertTrue(settings.rewardsStarted.first()) } + @Test fun `steps earn their badge and best with no workout at all`() = runBlocking { + val dao = db.healthDao() + // 10,000 steps in one day: 100 minutes of 100, from 10:00 local so they never cross midnight. + val morning = java.time.LocalDate.of(2026, 10, 15).atTime(10, 0).atZone(java.time.ZoneId.systemDefault()).toEpochSecond() + dao.insertActivity((0 until 100).map { ActivityMinute(morning + it * 60L, 100, 0, 0, null) }) + RewardsKeeper(dao, settings).refresh(emptyList(), 3) + assertTrue(dao.badgesOnce().any { it.id == "first_10k_steps" }) + assertTrue(dao.personalBestsOnce().any { it.kind == Rewards.Kind.MOST_STEPS }) + // Earned before the rewards started, so it waits with the history badges. + assertTrue(settings.historyBadgesWaiting.first()) + } + + @Test fun `deleting the last workout takes its bests and its week, and the badges stay`() = runBlocking { + val dao = db.healthDao() + val keeper = RewardsKeeper(dao, settings) + val w = workout(0) + dao.insertAppWorkouts(listOf(w)) + keeper.refresh(listOf(WorkoutRecorder.analyse(w, emptyList(), 190, HeartZones.STANDARD)), 3) + assertTrue(dao.personalBestsOnce().isNotEmpty()) + assertEquals(1, dao.weekResultsOnce().sumOf { it.count }) + val badges = dao.badgesOnce() + dao.deleteAppWorkout(w.start) + keeper.refresh(emptyList(), 3) + assertTrue(dao.personalBestsOnce().isEmpty()) + assertEquals(0, dao.weekResultsOnce().sumOf { it.count }) + assertEquals(badges, dao.badgesOnce()) + } + @Test fun `a strap workout is history, so the empty list waits for it`() = runBlocking { val dao = db.healthDao() dao.insertWorkouts(listOf(org.openstrap.app.testing.workout(start))) diff --git a/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt b/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt index e8fafeff..71953dca 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt @@ -16,6 +16,7 @@ import org.openstrap.app.data.db.ActivityMinute import org.openstrap.app.data.db.HrvSample import org.openstrap.app.data.db.OpenStrapDatabase import org.openstrap.app.data.db.SleepSession +import org.openstrap.app.data.db.Spo2Sample import org.openstrap.app.testing.ZoneRule import org.openstrap.app.testing.inMemoryDb import org.openstrap.protocol.services.StepTotals @@ -91,6 +92,18 @@ class RoomDayRepositoryTest { assertEquals(listOf(60), d.sleepHrv.map { it.milliseconds }) } + @Test fun `the oldest night's averages include its evening, from before that midnight`() { + val oldest = date.minusDays(SleepHistory.NIGHTS - 1L) + // It began at 23:00 the evening before its day, so the reading at 23:30 is before the midnight its day starts at. + runBlocking { + db.healthDao().insertSleepSessions(listOf(SleepSession(at(oldest.minusDays(1), 23), at(oldest, 7)))) + db.healthDao().insertSpo2(listOf(Spo2Sample(at(oldest.minusDays(1), 23, 30), 95))) + } + val d = day { n -> n.nights.first().spo2 != null } + assertEquals(oldest, d.nights.first().date) + assertEquals(95f, d.nights.first().spo2) + } + @Test fun `the week's trends run to the day shown, with nothing where a day has no data`() { val d = day() assertEquals((6L downTo 0L).map { date.minusDays(it) }, d.hrvTrend.map { it.date }) diff --git a/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt b/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt index 2e69654a..a73d33ef 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt @@ -135,7 +135,7 @@ class DayKeyMigrationTest { assertEquals(wakes.flatMap { listOf(listOf(it, 61L, 0L), listOf(it + 60, 64L, 1L)) }, rows(db, "SELECT * FROM heart_rate ORDER BY timestamp")) assertEquals(wakes.map { it - 9 * 3600 }, keys(db, "osa_result", "belongTime")) assertEquals(listOf(listOf(1_780_000_000L, 1_780_000_600L, 1_780_028_800L)), rows(db, "SELECT strapStart, start, `end` FROM sleep_edit")) - assertEquals(31, db.openHelper.readableDatabase.version) + assertEquals(32, db.openHelper.readableDatabase.version) // Room reads them as the dates. val dao = db.healthDao() assertEquals(dates, dao.restingHrAll().map { it.day }) @@ -220,7 +220,7 @@ class DayKeyMigrationTest { put("INSERT INTO personal_best (kind, value, date, workoutStart) VALUES ('MOST_STEPS', 15000, 1790000000, NULL)") } val db = harness.open(file, newYork) - assertEquals(31, db.openHelper.readableDatabase.version) + assertEquals(32, db.openHelper.readableDatabase.version) assertEquals(listOf(d), db.healthDao().restingHrAll().map { it.day }) assertEquals(listOf(listOf("steps_10k", 1_790_000_000L, null, d.toEpochDay())), rows(db, "SELECT * FROM badge")) assertEquals(listOf(listOf(d.toEpochDay(), 3L, 4L, 1L)), rows(db, "SELECT * FROM week_result")) diff --git a/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt b/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt index 93ecb4b7..7e3f06fc 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt @@ -30,7 +30,7 @@ class MigrationChainTest { @Test fun `every exported version opens at the current one`() = runTest { val versions = SourceTree.schemas.listFiles()!!.filter { it.extension == "json" }.map { it.nameWithoutExtension.toInt() }.sorted() assertEquals((1..current).toList(), versions) - assertEquals(31, current) + assertEquals(32, current) for (v in 1 until current) { val db = harness.open(harness.create(v)) // Any read opens it, running the migrations and Room's check of the result. diff --git a/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt b/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt new file mode 100644 index 00000000..136e87a9 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt @@ -0,0 +1,68 @@ +package org.openstrap.app.data.db + +import android.database.sqlite.SQLiteDatabase +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.test.runTest +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +/** A version 31 database opens at 32 without the sleep edits that match no session, those of a real night and the markers of an expired delete kept. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class OrphanSleepEditMigrationTest { + @Test + fun orphanEditsGoOthersStay() = runTest { + val file = File(System.getProperty("java.io.tmpdir"), "openstrap-migration-${System.nanoTime()}.db") + // Built from the exported schema, so it's the database version 31 really made. + val schema = JSONObject(File("schemas/org.openstrap.app.data.db.OpenStrapDatabase/31.json").readText()).getJSONObject("database") + SQLiteDatabase.openOrCreateDatabase(file, null).use { db -> + val entities = schema.getJSONArray("entities") + for (i in 0 until entities.length()) { + val e = entities.getJSONObject(i) + val table = e.getString("tableName") + db.execSQL(e.getString("createSql").replace("\${TABLE_NAME}", table)) + val indices = e.optJSONArray("indices") ?: continue + for (j in 0 until indices.length()) db.execSQL(indices.getJSONObject(j).getString("createSql").replace("\${TABLE_NAME}", table)) + } + val setup = schema.getJSONArray("setupQueries") + for (i in 0 until setup.length()) db.execSQL(setup.getString(i)) + val old = System.currentTimeMillis() / 1000 - 8 * 86_400L + val now = System.currentTimeMillis() / 1000 + // 21 October 2026 22:00 UTC, inside the weeks minute nights were made for. + val night = 1_792_620_000L + fun edit(strapStart: Long, nap: Int, start: Long?, end: Long?, deleted: Int, at: Long) = + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES ($strapStart, $nap, $start, $end, $deleted, $at)") + db.execSQL("INSERT INTO sleep_session (start, `end`, day, nap, source) VALUES ($night, ${night + 30_000}, 86400, 0, 0)") + // A strap night's edits stay: exact, and resent 10 minutes off. A nap edit is never touched. + edit(night, 0, night - 1000, night + 31_000, 0, now) + edit(night - 600, 0, null, null, 1, now) + edit(night + 500, 1, night, night + 3000, 0, now) + // Left by minute nights: a move and a delete with no night near go; an expired delete marker stays. + edit(night + 400_000, 0, night + 399_000, night + 430_000, 0, now) + edit(night + 500_000, 0, null, null, 1, now) + edit(night + 600_000, 0, null, null, 1, old) + // Outside those weeks nothing is touched, with a night near or not. + edit(100_000, 0, 99_000, 130_000, 0, now) + db.version = 31 + } + + val room = Room.databaseBuilder(ApplicationProvider.getApplicationContext(), OpenStrapDatabase::class.java, file.absolutePath) + .addMigrations(*OpenStrapDatabase.MIGRATIONS).allowMainThreadQueries().build() + try { + val db = room.openHelper.readableDatabase + assertEquals( + listOf(100_000L, 1_792_620_000L - 600, 1_792_620_000L, 1_792_620_000L + 500, 1_792_620_000L + 600_000), + db.query("SELECT strapStart FROM sleep_edit ORDER BY strapStart").use { c -> List(c.count) { c.moveToNext(); c.getLong(0) } }, + ) + } finally { + room.close() + listOf("", "-wal", "-shm", "-journal").forEach { File(file.path + it).delete() } + } + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt index 379df352..62460850 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt @@ -53,6 +53,44 @@ class WorkoutDistanceTest { assertEquals(500f, WorkoutDistance.shown(early, t0 + 900, track(steps = totals(since, 5), since = since, before = stored))!!.first, 0.01f) } + @Test + fun stepsBeforeTheFirstFixAreKeptWhenGpsTakesOver() { + // 3 minutes of steps, then a fix every 10 s for 10 minutes: the route adds to them, it doesn't replace them. + val fix = t0 + 180 + val route = line(600).map { it.copy(t = it.t + 180) } + val w = AppWorkout(t0, t0 + 780, SportTypes.WALK) + val gps = WorkoutDistance.shown(w, t0 + 780, track(route))!! + val both = WorkoutDistance.shown(w, t0 + 780, track(route, totals(t0, 13)))!! + val before = 300 * Activity.stepLength(100, 175) + assertEquals(gps.first + before, both.first, 0.01f) + // The route is nearly all of it, so it is still a GPS run. + assertEquals(false, both.second) + // Before the first fix settles the figure is the steps, and it doesn't drop when the fix arrives. + val early = WorkoutDistance.shown(w.copy(end = null), fix - 10, track(steps = totals(t0, 13)))!! + assertTrue(early.second) + assertTrue(both.first >= early.first) + } + + @Test + fun withMostlyStepsBeforeTheFirstFixItStaysFromSteps() { + val route = line(60).map { it.copy(t = it.t + 540) } + val w = AppWorkout(t0, t0 + 600, SportTypes.WALK) + val m = WorkoutDistance.shown(w, t0 + 600, track(route, totals(t0, 10)))!! + assertTrue(m.second) + assertTrue(m.first > 500 * Activity.stepLength(100, 175) * 0.8f) + } + + @Test + fun aTrimmedStartAfterTheFirstFixCountsNoStepsAndABikeNeverDoes() { + val route = line(600).map { it.copy(t = it.t + 180) } + val trimmed = AppWorkout(t0, t0 + 780, SportTypes.WALK, shownStart = t0 + 300) + val gps = WorkoutDistance.shown(trimmed, t0 + 780, track(route))!! + assertEquals(gps, WorkoutDistance.shown(trimmed, t0 + 780, track(route, totals(t0, 13)))) + // A bike has no steps to add. + val bike = AppWorkout(t0, t0 + 780, SportTypes.OUTDOOR_CYCLING) + assertEquals(WorkoutDistance.shown(bike, t0 + 780, track(route))!!, WorkoutDistance.shown(bike, t0 + 780, track(route, totals(t0, 13)))!!) + } + @Test fun theTotalGoingBackToZeroAtMidnightCostsOnlyTheStepsBeforeIt() { assertEquals(200, WorkoutDistance.taken(listOf(0L to 9_000, 60L to 9_100, 120L to 50, 180L to 150), 0, 180)) diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt index dcd3ab89..780bf5fc 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -648,6 +648,53 @@ class WorkoutSessionTest { assertNull(saved.recordedEnd) } + @Test + fun aGpsRunLeftRecordingWithNoHeartRateEndsAtItsLastRoutePoint() { + // The strap was off: a 20 minute run with its route kept and no heart rate, and the app back five hours on. + val t0 = clock.now - 5 * 3600 + runBlocking { + db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1, useGps = true, keepRoute = true)) + db.healthDao().insertRoutePoints( + (0..1200 step 5).map { AppWorkoutRoutePoint.of(t0, org.openstrap.app.data.Route.Point(t0 + it, 51.5 + it * 1e-5, -0.1, 5f)) }, + ) + } + val s = session(leftWaitMs = SHORT_WAIT_MS) + s.restore() + assertEquals(WorkoutState.Ended(t0), s.state.await { it is WorkoutState.Ended }) + val saved = stored(t0)!! + assertEquals(t0 + 1200, saved.end) + assertEquals(241, runBlocking { db.healthDao().routeOnce(t0) }.size) + } + + @Test + fun aWorkoutLeftRecordingWithNothingStoredRecordsOnInsteadOfBeingDeleted() { + val t0 = clock.now - 5 * 3600 + runBlocking { db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1)) } + val s = session(leftWaitMs = SHORT_WAIT_MS) + s.restore() + s.restored.await { it } + // Past the wait, with nothing from the strap: still there and still recording, for the wearer to end. + runBlocking { delay(SHORT_WAIT_MS * 3) } + assertEquals(t0, s.recording().workout.start) + assertNull(stored(t0)!!.end) + // End tapped then ends it where it was recorded to, not by deleting it. + s.end() + assertEquals(WorkoutState.Ended(t0), s.state.await { it is WorkoutState.Ended }) + assertEquals(clock.now, stored(t0)!!.end) + } + + @Test + fun aWorkoutLeftPausedWithNothingStoredComesBackPaused() { + val t0 = clock.now - 5 * 3600 + runBlocking { db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1, pausedAt = t0 + 30)) } + val s = session() + s.restore() + s.restored.await { it } + val r = s.recording() + assertTrue(r.paused) + assertNull(stored(t0)!!.end) + } + @Test fun aRestartAddsToTheDistanceStoredBeforeIt() { val settings = SettingsStore(context) @@ -700,6 +747,32 @@ class WorkoutSessionTest { assertEquals(full, storedOnce(t0) { it?.end == t0 + 600 }!!.distanceMeters!!, 0.5f) } + @Test + fun aTrimWorksTheFastestStretchesOutAgainFromTheKeptRoute() { + val t0 = clock.now - 7200 + // A straight line at 3 m/s for twenty minutes, a fix every 10 s: 3.6 km. + val route = (0L..1200L step 10).map { Route.Point(t0 + it, 51.5 + it * 3 / 111_195.0, -0.1, 5f) } + val first = org.openstrap.app.data.Rewards.Stretch(1000, 333, t0) + runBlocking { + db.healthDao().upsertAppWorkout( + AppWorkout( + start = t0, end = t0 + 1200, sportType = SportTypes.WALK, useGps = true, keepRoute = true, + distanceMeters = Route.distance(route).toFloat(), stretches = first.code, + ), + ) + db.healthDao().insertRoutePoints(route.map { AppWorkoutRoutePoint.of(t0, it) }) + } + val s = session() + s.trim(t0, from = t0 + 300, to = t0 + 1200) + val trimmed = storedOnce(t0) { it?.shownStart == t0 + 300 }!! + val kept = org.openstrap.app.data.Rewards.Stretch.parse(trimmed.stretches).single { it.meters == 1000 } + assertTrue(kept.start >= t0 + 300) + assertEquals(333f, kept.seconds.toFloat(), 5f) + s.undoTrim(t0) + val back = storedOnce(t0) { it?.shownStart == null }!! + assertTrue(org.openstrap.app.data.Rewards.Stretch.parse(back.stretches).any { it.meters == 1000 }) + } + @Test fun aTrimWithNoRouteLeftKeepsTheShareOfTheDistance() { val t0 = clock.now - 3600 @@ -810,6 +883,30 @@ class WorkoutSessionTest { assertNotNull(stored(t0)?.end) } + @Test + fun aRestDoesNotEndWhilePausedAndEndsOnceResumed() { + val s = session() + // Strength: only its rest is checked each second. + s.start(sportType = SportTypes.STRENGTH_TRAINING) + s.recording() + s.startSet() + s.recording { it.inSet } + clock.advance(Duration.ofSeconds(40)) + s.setDone() + s.recording { it.restUntil != null } + s.pause() + s.recording { it.paused } + // Well past the 90 s rest, paused: the once a second check leaves it alone. + clock.advance(Duration.ofSeconds(120)) + runBlocking { delay(2_500) } + val paused = s.recording() + assertNotNull(paused.restUntil) + assertNull(paused.sets.last().restEnd) + s.resume() + val resumed = s.recording { it.restUntil == null } + assertEquals(clock.now, resumed.sets.last().restEnd) + } + @Test fun aLaterSuccessDoesNotHideUnsavedSets() { val s = session() diff --git a/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt b/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt index 95b8b842..ee97de0f 100644 --- a/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt @@ -21,6 +21,12 @@ class BackupFilesTest { assertFalse(BackupFiles.isTemp(BackupFiles.name(day))) } + @Test fun `the name an old backup waits under is a temp, never a backup`() { + assertTrue(BackupFiles.isTemp(BackupFiles.asideName(day))) + assertNull(BackupFiles.dateOf(BackupFiles.asideName(day))) + assertTrue(BackupFiles.toDelete(listOf(BackupFiles.asideName(day))).isEmpty()) + } + @Test fun `only our own names count as backups`() { for (name in listOf( "unstrap-backup-2026-10-29 (1).zip", "Unstrap-backup-2026-10-29.zip", "unstrap-backup-2026-10-29.zip.bak", diff --git a/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt b/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt index ed7b99cf..129015fe 100644 --- a/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt @@ -1,9 +1,12 @@ package org.openstrap.app.health +import androidx.health.connect.client.records.DistanceRecord +import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.Record import androidx.health.connect.client.records.SleepSessionRecord import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.time.TimeRangeFilter +import androidx.health.connect.client.units.Length import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.sync.Mutex @@ -107,4 +110,42 @@ class RecordStoreTest { writers.awaitAll() assertTrue(!overlapped) } + + private val device = androidx.health.connect.client.records.metadata.Device(type = 0) + + private fun session(start: Long, id: String, recordId: String) = ExerciseSessionRecord( + startTime = Instant.ofEpochSecond(start), startZoneOffset = ZoneOffset.UTC, + endTime = Instant.ofEpochSecond(start + 1800), endZoneOffset = ZoneOffset.UTC, + exerciseType = ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, + metadata = Metadata.autoRecorded(device = device, clientRecordId = id), + ).also { setId(it.metadata, recordId) } + + private fun distance(start: Long, id: String, recordId: String) = DistanceRecord( + startTime = Instant.ofEpochSecond(start), startZoneOffset = ZoneOffset.UTC, + endTime = Instant.ofEpochSecond(start + 1800), endZoneOffset = ZoneOffset.UTC, + distance = Length.meters(5000.0), metadata = Metadata.autoRecorded(device = device, clientRecordId = id), + ).also { setId(it.metadata, recordId) } + + private fun setId(metadata: Metadata, recordId: String) { + Metadata::class.java.getDeclaredField("id").apply { isAccessible = true }.set(metadata, recordId) + } + + @Test fun `a deleted phone workout takes its session and distance out, and no other`() = runTest { + val store = FakeStore( + listOf( + session(1000, "openstrap:workout:1000", "a"), distance(1000, "openstrap:distance:1000", "b"), + session(9000, "openstrap:workout:9000", "c"), distance(9000, "openstrap:distance:9000", "d"), + session(1000, "openstrap:strapworkout:1000", "e"), + ), + ) + store.dropPhoneWorkout(1000, 1000, 2800) + assertEquals(listOf("c", "d", "e"), store.records.map { it.metadata.id }) + } + + @Test fun `a deleted phone workout stays when its records can't be read`() = runTest { + val held = listOf(session(1000, "openstrap:workout:1000", "a")) + val store = FakeStore(held, readable = false) + store.dropPhoneWorkout(1000, 1000, 2800) + assertEquals(held, store.records) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt index 33e9d860..e4d30ee6 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt @@ -53,7 +53,8 @@ class AlarmsViewModelTest { val vm = AlarmsViewModel(failingStrap(failure)).also { models += it } val state = vm.state.value assertFalse(state.loading) - return state.error + // A failed read is the Alarms page's own error, apart from a failed write's. + return state.alarmsError } /** A strap whose alarm read fails with [failure]. Everything else answers empty. */ @@ -116,17 +117,54 @@ class AlarmsViewModelTest { assertEquals("Slot taken", vm.state.value.error) } + @Test fun `a failed alarms read leaves the health settings read and its own error on the Alarms page`() { + val strap = FakeStrap().apply { alarmsFailure = StrapCommandException("Alarms unreadable") } + val vm = AlarmsViewModel(strap.controller).also { models += it } + val state = vm.state.value + assertEquals("Alarms unreadable", state.alarmsError) + assertNull(state.healthError) + assertTrue(state.health != null) + } + + @Test fun `a failed health read leaves the alarms read and keeps the last good settings`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + assertTrue(vm.state.value.health != null) + strap.healthFailure = StrapCommandException("Settings unreadable") + vm.refresh() + val state = vm.state.value + assertEquals("Settings unreadable", state.healthError) + assertNull(state.alarmsError) + assertEquals(AlarmsRead.Loaded, state.read) + assertEquals(1, state.alarms.size) + assertTrue(state.health != null) + } + + @Test fun `a failed save's reason survives the refresh that was queued meanwhile`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + strap.holdSave = true + val writing = vm.save(Alarm(0, 7, 0, 0, enabled = true), isNew = true) + vm.refresh() + strap.release(StrapCommandException("Slot taken")) + assertFalse(writing.getCompleted()) + assertEquals("Slot taken", vm.state.value.error) + assertFalse(vm.state.value.busy) + } + /** A strap that holds one alarm, can hold a save until [release], and counts its reads. */ private class FakeStrap { var reads = 0 var holdSave = false var saveFailure: Throwable? = null + var alarmsFailure: Throwable? = null + var healthFailure: Throwable? = null private var held: Continuation? = null private val caps = AlarmCapabilities(version = 1, maxCount = 10, titles = false, smartSupported = false) private val flows = mutableMapOf() - fun release() { - held?.resumeWith(Result.success(Unit)) + fun release(failure: Throwable? = null) { + held?.resumeWith(failure?.let { Result.failure(it) } ?: Result.success(Unit)) held = null holdSave = false } @@ -141,8 +179,8 @@ class AlarmsViewModelTest { method.name == "hashCode" -> System.identityHashCode(proxy) method.name == "equals" -> proxy === args?.firstOrNull() method.name == "toString" -> "fake strap" - method.name == "readAlarms" -> { reads++; done(Result.success(caps to listOf(Alarm(0, 6, 0, Alarm.WEEKDAYS, enabled = true)))) } - method.name == "readHealthSettings" -> done(Result.success(SettingsGroup(0, 1, emptyMap()))) + method.name == "readAlarms" -> { reads++; done(alarmsFailure?.let { Result.failure(it) } ?: Result.success(caps to listOf(Alarm(0, 6, 0, Alarm.WEEKDAYS, enabled = true)))) } + method.name == "readHealthSettings" -> done(healthFailure?.let { Result.failure(it) } ?: Result.success(SettingsGroup(0, 1, emptyMap()))) method.name == "saveAlarm" -> when { saveFailure != null -> done(Result.failure(saveFailure!!)) holdSave -> { held = args.last() as Continuation; COROUTINE_SUSPENDED } diff --git a/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt b/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt index bda6e0ac..f44cb8fa 100644 --- a/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt +++ b/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt @@ -218,10 +218,15 @@ class GdspClient( val parsed = WorkoutParsers.summary.parse(s.payload, ParseContext(s.headerTime)) // The detail is asked for whether or not the summary parses, as Zepp does. val d = fetch(HistoryDataType.SPORT_DETAIL.code, since, zone) - if (parsed !is ParseResult.Success) return WorkoutFetch.Failed("summary: ${(parsed as ParseResult.Failure).reason}") - val summary = parsed.records.singleOrNull() ?: return WorkoutFetch.None // Zepp's next START: the summary's header time + 1000 ms. val next = s.headerTime + 1 + // Zepp keeps the raw bytes and parses after the loop, so a summary it can't read never stops it: on to the next. + if (parsed !is ParseResult.Success) { + return WorkoutFetch.Unreadable("summary: ${(parsed as ParseResult.Failure).reason}", next) + } + if (parsed.records.isEmpty()) return WorkoutFetch.None + val summary = parsed.records.singleOrNull() + ?: return WorkoutFetch.Unreadable("summary: ${parsed.records.size} workouts in one", next) var retry = false val detail = when (d) { is GdspFetch.Chunk -> when (val r = WorkoutParsers.detail.parse(d.payload, ParseContext(summary.trackId))) { @@ -250,6 +255,8 @@ class GdspClient( sealed interface WorkoutFetch { data object None : WorkoutFetch data class Failed(val reason: String, val fastRecharge: Boolean = false) : WorkoutFetch + /** A summary fetched whole that couldn't be read ([reason]); the next one is asked from [nextCursor]. */ + data class Unreadable(val reason: String, val nextCursor: Long) : WorkoutFetch /** [retryDetail] is set when the detail exchange failed (worth fetching again), not when it was empty or unreadable. */ data class Workout(val summary: WorkoutSummary, val detail: WorkoutDetail?, val nextCursor: Long, val retryDetail: Boolean = false) : WorkoutFetch } diff --git a/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt b/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt index 4361f5fa..8ed931ec 100644 --- a/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt +++ b/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt @@ -113,6 +113,22 @@ class GdspClientTest { assertEquals(3, strap.acks.size) } + @Test + fun anUnreadableSummaryIsLeftOutAndTheNextOneStillComes() = runTest { + val odd = trackId - 3600 + // Version 1, not protobuf: fetched whole, but not read. + val strap = SimulatedGdspStrap( + mapOf(odd to (byteArrayOf(1, 0, 0, 0) to fixture("detail_6.bin")), trackId to (fixture("summary_5.bin") to fixture("detail_6.bin"))), + ) + val client = GdspClient(strap::send, strap.control, strap.data) + val u = client.fetchWorkout(odd - 60, zone) as WorkoutFetch.Unreadable + assertEquals(odd + 1, u.nextCursor) + // Its detail is asked for too, as Zepp does, so the traffic is the same. + assertEquals(listOf(5 to odd - 60, 6 to odd - 60), strap.starts) + val w = client.fetchWorkout(u.nextCursor, zone) as WorkoutFetch.Workout + assertEquals(trackId, w.summary.trackId) + } + @Test fun fastRechargeIsAcknowledgedWith33() = runTest { val strap = strap().apply { fastRecharge = true }