Modern Apps git

← Modern-Apps.git

things: claim a dedicated scale user slot and filter stored records

Commit
7e98c0597b6db5dc1be304d592535156e098f332
Author
vayun-mathur <[email protected]>
When
2026-09-06 23:39 UTC (3 months ago)
Parents
2f19106

Diff

things/src/main/java/com/vayunmathur/things/Navigation.kt
diff --git a/things/src/main/java/com/vayunmathur/things/Navigation.kt b/things/src/main/java/com/vayunmathur/things/Navigation.ktindex b061da9838..1f78d17c89 100644--- a/things/src/main/java/com/vayunmathur/things/Navigation.kt+++ b/things/src/main/java/com/vayunmathur/things/Navigation.kt@@ -47,6 +47,7 @@ fun Navigation(                 scalePaired = DeviceController.scalePaired.value,                 scaleLink = DeviceController.scaleLink.value,                 scaleConnectionState = DeviceController.scaleConnectionState.value,+                scaleUserSlot = DeviceController.scaleUserSlot.value,                 scaleSex = DeviceController.scaleSex.value,                 scaleAge = DeviceController.scaleAge.value,                 scaleHeight = DeviceController.scaleHeight.value,@@ -69,6 +70,7 @@ fun Navigation(                 },                 onForgetBottle = onForgetBottle,                 onForgetScale = onForgetScale,+                onResetScale = { DeviceController.requestScaleReset() },                 onHealthConnectClick = onHealthConnectClick,                 onOpenDevices = { backStack.add(Route.Devices) },             )
things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt b/things/src/main/java/com/vayunmathur/things/platform/DeviceController.ktindex 1a75212a23..405bc6b9c8 100644--- a/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt@@ -18,6 +18,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch+import kotlin.random.Random  /**  * Process-scoped owner of the BLE managers, device state, and all the bottle/scale logic that@@ -73,6 +74,8 @@ object DeviceController {      // Scale (Renpho Elis 1 / Qingniu) — offline BLE only, no cloud.     val scaleDevices = mutableStateListOf<ScaleBleManager.ScaleBleDevice>()+    /** Which of the scale's eight user slots is ours, or null until we have registered. */+    val scaleUserSlot = mutableStateOf<Int?>(null)     val scaleScanning = mutableStateOf(false)     val scaleConnectionState = mutableStateOf("Disconnected")     val scaleRealtimeWeight = mutableStateOf<Double?>(null)@@ -94,6 +97,7 @@ object DeviceController {         scaleBleManager = ScaleBleManager()         loadScaleProfile()         loadBottleTelemetry()+        scaleUserSlot.value = scaleUserIndex()         refreshPaired()         initialized = true     }@@ -261,6 +265,9 @@ object DeviceController {      fun disconnectScale() {         clearDeviceAddress(SCALE_ADDRESS_KEY)+        // The slot belongs to this pairing; keeping it would strand a slot on the scale that we+        // could no longer visit.+        clearScaleUserSlot()         scaleBleManager.disconnect()     } @@ -280,6 +287,55 @@ object DeviceController {      fun savedScaleEncryptsResistance(): Boolean = prefs.getBoolean(SCALE_ENCRYPT_RES_KEY, false) +    /**+     * Our slot on the scale, or null if we have not registered yet.+     *+     * The slot's key cannot be read back off the scale (that needs characteristics this hardware+     * does not expose), so once assigned it has to survive forever — losing it strands the slot,+     * recoverable only by resetting the scale.+     */+    fun scaleUserIndex(): Int? =+        if (prefs.contains(SCALE_USER_INDEX_KEY)) prefs.getInt(SCALE_USER_INDEX_KEY, 0) else null++    /** Stable per-slot secret. Generated once; the scale expects the same value on every visit. */+    fun scaleUserKey(): Int {+        val existing = prefs.getInt(SCALE_USER_KEY_KEY, 0)+        if (existing in 1..9999) return existing+        val generated = Random.nextInt(1, 10000)+        prefs.edit { putInt(SCALE_USER_KEY_KEY, generated) }+        return generated+    }++    fun saveScaleUserIndex(index: Int) {+        prefs.edit { putInt(SCALE_USER_INDEX_KEY, index) }+        scaleUserSlot.value = index+    }++    private fun clearScaleUserSlot() {+        prefs.edit {+            remove(SCALE_USER_INDEX_KEY)+            remove(SCALE_USER_KEY_KEY)+        }+        scaleUserSlot.value = null+    }++    /**+     * Wipe every user slot on the scale. It is powered off between weigh-ins, so this is recorded+     * and carried out on the next connection rather than attempted now.+     */+    fun requestScaleReset() {+        prefs.edit { putBoolean(SCALE_PENDING_RESET_KEY, true) }+        clearScaleUserSlot()+        AppMessages.show("Scale will be reset next time it connects")+    }++    fun scaleResetPending(): Boolean = prefs.getBoolean(SCALE_PENDING_RESET_KEY, false)++    fun onScaleResetDone() {+        prefs.edit { remove(SCALE_PENDING_RESET_KEY) }+        clearScaleUserSlot()+    }+     /** Reconnect to any remembered devices. No-op without permission or a powered-on adapter. */     fun autoConnectSavedDevices() {         if (!hasBluetoothConnectPermission() || !bluetoothEnabled()) return@@ -439,4 +495,7 @@ object DeviceController {     private const val SCALE_ADDRESS_KEY = "scale_address"     private const val SCALE_CATEGORY_KEY = "scale_category"     private const val SCALE_ENCRYPT_RES_KEY = "scale_encrypt_resistance"+    private const val SCALE_USER_INDEX_KEY = "scale_user_index"+    private const val SCALE_USER_KEY_KEY = "scale_user_key"+    private const val SCALE_PENDING_RESET_KEY = "scale_pending_reset" }
things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.ktindex cfd29a4361..ab9a2acfee 100644--- a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt@@ -74,6 +74,7 @@ class ScaleBleManager {         private const val CMD_TIME = 0x20         private const val CMD_START = 0x22         private const val CMD_USER_SYNC = 0xA0+        private const val CMD_IDENTIFY_WEIGHT = 0xA2          /**          * VA-class scales (ScaleBleUtils.isVaScale) speak a variant of the protocol: the config@@ -81,10 +82,14 @@ class ScaleBleManager {          * 3..4, and nothing is reported at all until a user slot is synced with 0xA0.          */         private val VA_CATEGORIES = setOf(128, 129, 134, 143)+        private const val VA_SUB_REGISTER = 1         private const val VA_SUB_VISIT = 2+        private const val VA_SUB_DELETE = 4         private const val VA_VISITOR_INDEX = 0xFE         private const val VA_VISITOR_KEY_HI = 0xFF         private const val VA_VISITOR_KEY_LO = 0xEE+        /** Delete takes every slot at once; bit(n-1) selects slot n, so 0xFF is all eight. */+        private const val VA_DELETE_ALL_MASK = 0xFF         /** Body-fat algorithm id; we only use the scale's raw impedance, so this is inert. */         private const val VA_ALGORITHM = 7         /** 1 = Asia reference range, 2 = rest of world. */@@ -138,6 +143,14 @@ class ScaleBleManager {     /** VA scales scale the weight up by this instead of dividing by [weightRatio]. */     private var kgWeightRatio = 0.1     private var isVaScale = false+    /**+     * Set once the scale has accepted us into one of its eight slots. Null means we are running+     * as the transient visitor, either before the first registration or because all slots were+     * taken.+     */+    private var vaUserIndex: Int? = null+    /** 0x12 byte[16] bit 5: whether the scale accepts an app-supplied reference weight. */+    private var supportsIdentifyWeight = false     private var scaleType = 0     private var notifyChar: UUID = CHAR_FFE1     private var indicateChar: UUID? = null@@ -361,6 +374,9 @@ class ScaleBleManager {         timeRetries = 0         scaleType = 0         weightRatio = 10.0+        // Re-established from the 0x12 info frame and the user handshake on every connection.+        supportsIdentifyWeight = false+        vaUserIndex = null         resetBurst()     } @@ -594,7 +610,8 @@ class ScaleBleManager {                 handler.removeCallbacks(timeRetry)                 if (isVaScale) {                     // A VA scale reports nothing until it has a user slot to attribute it to.-                    sendVisitorUser()+                    // A pending wipe has to go first, since it invalidates any slot we hold.+                    if (DeviceController.scaleResetPending()) sendDeleteAllUsers() else syncUser()                 } else {                     Log.d(TAG, "time frame acknowledged; starting measurement")                     handler.removeCallbacks(sendStart)@@ -608,37 +625,101 @@ class ScaleBleManager {     }      /**-     * Register as the transient "visitor" slot. This is what QNBleApi.connectDevice does, and it-     * avoids consuming one of the scale's eight persistent user slots.+     * Claim our slot on the scale: visit the one we already hold, or register for a new one.+     *+     * Registering is what makes offline weigh-ins attributable — the scale stamps each stored+     * record with the slot it matched, so a dedicated slot is the only way to tell our readings+     * apart from the rest of the household's.+     */+    private fun syncUser() {+        val index = DeviceController.scaleUserIndex()+        if (index == null) {+            sendUserFrame(VA_SUB_REGISTER, index = 0, key = DeviceController.scaleUserKey())+        } else {+            sendUserFrame(VA_SUB_VISIT, index = index, key = DeviceController.scaleUserKey())+        }+    }++    /**+     * The transient slot, used only when the scale has no room left for us. Measurements still+     * work; they just cannot be told apart from anyone else's when taken offline.      */     private fun sendVisitorUser() {+        vaUserIndex = null+        sendUserFrame(VA_SUB_VISIT, VA_VISITOR_INDEX, keyHi = VA_VISITOR_KEY_HI, keyLo = VA_VISITOR_KEY_LO)+    }++    private fun sendUserFrame(+        sub: Int,+        index: Int,+        key: Int? = null,+        keyHi: Int = (key ?: 0) shr 8 and 0xFF,+        keyLo: Int = (key ?: 0) and 0xFF,+    ) {         val profile = DeviceController.scaleProfile.value+        // The wire encoding is the inverse of the SDK's own BleUser convention.         val gender = if (profile.sex == Sex.Male) 0 else 1         val age = profile.age.coerceIn(6, 80)         val heightMm = (profile.heightCm.coerceIn(40.0, 240.0) * 10).toInt()-        Log.d(TAG, "sync visitor user: gender=$gender age=$age heightMm=$heightMm")+        Log.d(TAG, "user sync sub=$sub index=$index gender=$gender age=$age heightMm=$heightMm")         enqueue(             bleWriteChar,             buildFrame(-                CMD_USER_SYNC, VA_SUB_VISIT,-                VA_VISITOR_INDEX, VA_VISITOR_KEY_HI, VA_VISITOR_KEY_LO,+                CMD_USER_SYNC, sub,+                index, keyHi, keyLo,                 gender, age, (heightMm shr 8) and 0xFF, heightMm and 0xFF,                 VA_ALGORITHM, VA_FAT_GRADE,             ),         )     } +    /** Frees all eight slots. Ten trailing zero bytes pad it to the length the scale expects. */+    private fun sendDeleteAllUsers() {+        Log.d(TAG, "resetting all scale user slots")+        enqueue(+            bleWriteChar,+            buildFrame(CMD_USER_SYNC, VA_SUB_DELETE, VA_DELETE_ALL_MASK, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),+        )+    }+     private fun handleUserSyncResult(v: ByteArray) {         if (v.size < 5) return         val sub = v[2].toInt() and 0xFF         val index = v[3].toInt() and 0xFF-        val result = v[4].toInt() and 0xFF-        Log.d(TAG, "user sync result sub=$sub index=$index result=$result")-        if (sub != VA_SUB_VISIT || result != 1) return-        // Ask for the stored records. Bit 0 is the visitor/unattributed bucket, which is where a-        // weigh-in taken with no phone present lands; bits 1..8 are other household members'-        // slots, which we deliberately do not claim as our own.-        enqueue(bleWriteChar, buildCmd(CMD_START, 0x00, 0x01))+        val ok = (v[4].toInt() and 0xFF) == 1+        Log.d(TAG, "user sync result sub=$sub index=$index ok=$ok")+        when (sub) {+            VA_SUB_REGISTER -> {+                if (!ok) {+                    // The scale only fails this when all eight slots are occupied.+                    Log.w(TAG, "no free scale slots; falling back to visitor")+                    sendVisitorUser()+                    return+                }+                DeviceController.saveScaleUserIndex(index)+                // Registering does not make us the active user; a visit still has to follow.+                sendUserFrame(VA_SUB_VISIT, index, key = DeviceController.scaleUserKey())+            }+            VA_SUB_VISIT -> {+                if (!ok) return+                vaUserIndex = if (index == VA_VISITOR_INDEX) null else index+                requestStoredRecords()+            }+            VA_SUB_DELETE -> {+                DeviceController.onScaleResetDone()+                if (ok) syncUser() else Log.w(TAG, "scale reset rejected")+            }+        }+    }++    /**+     * Ask for buffered records. The mask selects slots by bit(n); bit 0 is the unattributed+     * bucket, which we deliberately leave out — a weigh-in the scale could not match is more+     * likely to be someone else's than ours.+     */+    private fun requestStoredRecords() {+        val mask = vaUserIndex?.let { 1 shl it } ?: 1+        enqueue(bleWriteChar, buildCmd(CMD_START, (mask shr 8) and 0xFF, mask and 0xFF))     }      /**@@ -653,6 +734,14 @@ class ScaleBleManager {             return         }         val index = v[4].toInt() and 0xFF+        val recordUser = v[5].toInt() and 0xFF+        // The mask should already have filtered these scale-side; re-check rather than risk+        // filing someone else's weigh-in, or an unattributed one (0xF0), as ours.+        val ours = vaUserIndex+        if (ours != null && recordUser != ours) {+            Log.d(TAG, "stored record $index/$total belongs to user $recordUser; skipped")+            return+        }         // Timestamp is little-endian here while weight and impedance below are big-endian; that         // asymmetry is in the reference decoder, not a mistake.         var seconds = 0L@@ -665,7 +754,7 @@ class ScaleBleManager {         }         val weight = decodeWeightByMultiplication(twoByteInt(v[10], v[11]), kgWeightRatio)         if (weight <= 0) return-        Log.d(TAG, "stored record $index/$total user=${v[5].toInt() and 0xFF} weight=$weight")+        Log.d(TAG, "stored record $index/$total user=$recordUser weight=$weight")         DeviceController.onScaleHistory(             weightKg = weight,             r50 = fourResTwoByte2Int(v[12], v[13]),@@ -684,6 +773,7 @@ class ScaleBleManager {             0, 1, 18 -> if (weight > 0) DeviceController.onScaleRealtimeWeight(weight)             2 -> {                 enqueue(configChar, buildCmd(CMD_OVER, 0x10))+                sendIdentifyWeight(weight)                 if (v.size < 11) {                     DeviceController.onScaleMeasurement(weight, 0, 0)                     return@@ -697,6 +787,18 @@ class ScaleBleManager {         }     } +    /**+     * Tell the scale what our slot weighs. This is the reference the firmware matches against+     * when someone weighs in with no phone around, so keeping it current is what makes offline+     * attribution — and therefore the stored-record filter — work.+     */+    private fun sendIdentifyWeight(weightKg: Double) {+        val index = vaUserIndex ?: return+        if (!supportsIdentifyWeight || weightKg <= 0) return+        val raw = Math.round(weightKg * 100).toInt()+        enqueue(bleWriteChar, buildFrame(CMD_IDENTIFY_WEIGHT, index, (raw shr 8) and 0xFF, raw and 0xFF))+    }+     private fun handleScaleInfo(v: ByteArray) {         // scaleType is echoed back in every command we send, so read it before the length check.         if (v.size >= 3) scaleType = v[2].toInt() and 0xFF@@ -705,6 +807,7 @@ class ScaleBleManager {         if (v.size < 15) return         weightRatio = if ((v[10].toInt() and 0x01) == 1) 100.0 else 10.0         kgWeightRatio = if ((v[10].toInt() and 0x01) == 1) 0.01 else 0.1+        if (v.size > 16) supportsIdentifyWeight = ((v[16].toInt() shr 5) and 1) == 1         // Units etc. available at v[10] bits, v[16] lbPrecision, v[17] unit mask.         // We keep ratio for weight decode; other bytes inform display only.         DeviceController.scaleConnectionState.value = "Connected — step on scale"
things/src/main/java/com/vayunmathur/things/ui/HomePage.kt
diff --git a/things/src/main/java/com/vayunmathur/things/ui/HomePage.kt b/things/src/main/java/com/vayunmathur/things/ui/HomePage.ktindex d84fee3d49..4cc8540185 100644--- a/things/src/main/java/com/vayunmathur/things/ui/HomePage.kt+++ b/things/src/main/java/com/vayunmathur/things/ui/HomePage.kt@@ -9,7 +9,10 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource@@ -19,6 +22,7 @@ import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.Checkbox+import com.vayunmathur.library.ui.ConfirmDialog import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.IconButton@@ -57,6 +61,7 @@ fun HomePage(     scalePaired: Boolean,     scaleLink: LinkState,     scaleConnectionState: String,+    scaleUserSlot: Int?,     scaleSex: Sex,     scaleAge: String,     scaleHeight: String,@@ -67,6 +72,7 @@ fun HomePage(     onScaleAthleteChange: (Boolean) -> Unit,     onForgetBottle: () -> Unit,     onForgetScale: () -> Unit,+    onResetScale: () -> Unit,     onHealthConnectClick: () -> Unit,     onOpenDevices: () -> Unit, ) {@@ -105,6 +111,7 @@ fun HomePage(                     ScaleCard(                         link = scaleLink,                         connectionState = scaleConnectionState,+                        userSlot = scaleUserSlot,                         sex = scaleSex,                         age = scaleAge,                         height = scaleHeight,@@ -114,6 +121,7 @@ fun HomePage(                         onHeightChange = onScaleHeightChange,                         onAthleteChange = onScaleAthleteChange,                         onForget = onForgetScale,+                        onReset = onResetScale,                     )                 }             }@@ -238,6 +246,7 @@ private fun formatClockTime(millis: Long): String = private fun ScaleCard(     link: LinkState,     connectionState: String,+    userSlot: Int?,     sex: Sex,     age: String,     height: String,@@ -247,11 +256,23 @@ private fun ScaleCard(     onHeightChange: (String) -> Unit,     onAthleteChange: (Boolean) -> Unit,     onForget: () -> Unit,+    onReset: () -> Unit, ) {+    var confirmReset by remember { mutableStateOf(false) }     Card(modifier = Modifier.fillMaxWidth()) {         Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {             Text(stringResource(R.string.scale_title), style = MaterialTheme.typography.titleSmall)             LinkStatusText(link, connectionState)+            // The scale files each weigh-in under one of its eight slots; ours is what lets the+            // app pick out measurements taken while the phone was away.+            Text(+                if (userSlot != null) {+                    stringResource(R.string.scale_user_slot, userSlot)+                } else {+                    stringResource(R.string.scale_user_unregistered)+                },+                style = MaterialTheme.typography.bodySmall,+            )              // The profile drives the body-composition maths, so it stays editable whether or not             // the scale happens to be awake.@@ -286,7 +307,27 @@ private fun ScaleCard(                 stringResource(R.string.syncs_to_health_connect),                 style = MaterialTheme.typography.bodySmall             )+            OutlinedButton(onClick = { confirmReset = true }) {+                Text(stringResource(R.string.scale_reset_users))+            }             OutlinedButton(onClick = onForget) { Text(stringResource(R.string.forget_device)) }         }     }++    if (confirmReset) {+        ConfirmDialog(+            title = stringResource(R.string.scale_reset_title),+            message = stringResource(R.string.scale_reset_message),+            confirmLabel = stringResource(R.string.scale_reset_confirm),+            // Without an explicit dismiss label the dialog renders no cancel button, which is a+            // poor way to guard something destructive.+            dismissLabel = stringResource(R.string.cancel),+            destructive = true,+            onConfirm = {+                confirmReset = false+                onReset()+            },+            onDismiss = { confirmReset = false },+        )+    } }
things/src/main/res/values/strings.xml
diff --git a/things/src/main/res/values/strings.xml b/things/src/main/res/values/strings.xmlindex a307feffcd..125c051a70 100644--- a/things/src/main/res/values/strings.xml+++ b/things/src/main/res/values/strings.xml@@ -69,6 +69,18 @@     <string name="age">Age</string>     <string name="height_cm">Height (cm)</string>     <string name="athlete">Athlete mode</string>+    <!-- Which of the scale's eight user slots is ours. %1$d = slot number 1-8 -->+    <string name="scale_user_slot">Scale user <xliff:g id="slot" example="3">%1$d</xliff:g> of 8</string>+    <!-- Shown before the scale has assigned us one of its eight user slots -->+    <string name="scale_user_unregistered">Not registered on the scale yet</string>+    <!-- Button that erases every stored user profile on the scale. Verb phrase -->+    <string name="scale_reset_users">Reset scale users</string>+    <!-- Title of the confirmation dialog for erasing the scale's user slots -->+    <string name="scale_reset_title">Reset scale users?</string>+    <!-- Warns that the reset is not limited to this app's own slot -->+    <string name="scale_reset_message">This erases all eight user profiles stored on the scale, including any belonging to other people in your household. They would each have to set the scale up again. Your own measurements already in Health Connect are not affected.</string>+    <!-- Confirm button on the scale reset dialog. Verb -->+    <string name="scale_reset_confirm">Reset</string>     <!-- Scale scan button -->     <string name="scan_scale">Scan scale</string>     <!-- Health Connect -->
things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt
diff --git a/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt b/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.ktindex 184f2c1f0d..d24c6ce5ec 100644--- a/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt+++ b/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt@@ -37,6 +37,7 @@ class MetadataPreviews {                 scalePaired = true,                 scaleLink = LinkState.Connected,                 scaleConnectionState = "Connected — step on scale",+                scaleUserSlot = 1,                 scaleSex = Sex.Male,                 scaleAge = "30",                 scaleHeight = "178",@@ -47,6 +48,7 @@ class MetadataPreviews {                 onScaleAthleteChange = {},                 onForgetBottle = {},                 onForgetScale = {},+                onResetScale = {},                 onHealthConnectClick = {},                 onOpenDevices = {},             )