Modern Apps git

← Modern-Apps.git

things: add WaterH bottle + Renpho Elis 1 offline support

Commit
81784ebd3bea604481cfeca2f09e98fdff3b2196
Author
vayun-mathur <[email protected]>
When
2026-08-31 19:57 UTC (3 months ago)
Parents
37e1331

Diff

things/src/main/java/com/vayunmathur/things/MainActivity.kt
diff --git a/things/src/main/java/com/vayunmathur/things/MainActivity.kt b/things/src/main/java/com/vayunmathur/things/MainActivity.ktindex 22abb52b8c..70b40b8ba6 100644--- a/things/src/main/java/com/vayunmathur/things/MainActivity.kt+++ b/things/src/main/java/com/vayunmathur/things/MainActivity.kt@@ -1,6 +1,7 @@ package com.vayunmathur.things  import kotlin.time.Clock+import kotlin.time.Instant import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import kotlinx.datetime.format@@ -18,15 +19,44 @@ import androidx.compose.runtime.mutableStateOf import androidx.core.content.edit import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.things.platform.BleManager+import com.vayunmathur.things.platform.BodyComposition+import com.vayunmathur.things.platform.BodyMetrics+import com.vayunmathur.things.platform.BottleStatus+import com.vayunmathur.things.platform.HydrationReading+import com.vayunmathur.things.platform.ScaleBleManager+import com.vayunmathur.things.platform.ScaleMeasurement+import com.vayunmathur.things.platform.ScaleProfile+import com.vayunmathur.things.platform.SegmentalImpedance+import com.vayunmathur.things.platform.Sex import java.time.LocalDate  class MainActivity : ComponentActivity() {     private lateinit var bleManager: BleManager+    private lateinit var scaleBleManager: ScaleBleManager     val messages = mutableStateListOf<String>()     val totalMl = mutableIntStateOf(0)     val connectionState = mutableStateOf("Disconnected")     val scanning = mutableStateOf(false)     val discoveredDevices = mutableStateListOf<BleManager.BleDevice>()+    val waterTempC = mutableStateOf<Int?>(null)+    val tds = mutableStateOf<Int?>(null)+    val batteryPct = mutableStateOf<Int?>(null)+    val charging = mutableStateOf(false)++    // Scale (Renpho Elis 1 / Qingniu) — offline BLE only, no cloud.+    val scaleDevices = mutableStateListOf<ScaleBleManager.ScaleBleDevice>()+    val scaleScanning = mutableStateOf(false)+    val scaleConnectionState = mutableStateOf("Disconnected")+    val scaleRealtimeWeight = mutableStateOf<Double?>(null)+    val scaleWeight = mutableStateOf<Double?>(null)+    val scaleR50 = mutableStateOf<Int?>(null)+    val scaleR500 = mutableStateOf<Int?>(null)+    val scaleMetrics = mutableStateOf<BodyMetrics?>(null)+    val scaleProfile = mutableStateOf(ScaleProfile())+    val scaleSex = mutableStateOf(Sex.Male)+    val scaleAge = mutableStateOf("30")+    val scaleHeight = mutableStateOf("175")+    val scaleAthlete = mutableStateOf(false)      private val prefs by lazy { getSharedPreferences("hydration", MODE_PRIVATE) } @@ -44,16 +74,76 @@ class MainActivity : ComponentActivity() {         }     } -    fun onDrinkReceived(ml: Int) {+    fun onDrinkLog(reading: HydrationReading) {+        val instant = Instant.fromEpochMilliseconds(reading.epochMillis)+        val local = instant.toLocalDateTime(TimeZone.currentSystemDefault())+        val readingDate = LocalDate.of(local.date.year, local.date.monthNumber, local.date.dayOfMonth)+        val isReadingToday = readingDate.toString() == today()+        // Midnight rollover for the per-day persisted total.         if (!isToday()) {             totalMl.intValue = 0             messages.clear()         }-        totalMl.intValue += ml-        saveTotal()-        val timestamp = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).time-            .format(LocalTime.Format { hour(); char(':'); minute() })-        messages.add(0, "[$timestamp]  +$ml mL")+        if (isReadingToday) {+            totalMl.intValue += reading.amountMl+            saveTotal()+        }+        val formatted = formatReadingTimestamp(local)+        messages.add(0, "[$formatted]  +${reading.amountMl} mL")+    }++    fun onBottleStatus(status: BottleStatus) {+        waterTempC.value = status.tempC+        tds.value = status.tds+        batteryPct.value = status.batteryPct+        charging.value = status.charging+    }++    fun onScaleRealtimeWeight(weight: Double) {+        scaleRealtimeWeight.value = weight+        scaleConnectionState.value = "Weighing... %.1f kg".format(weight)+    }++    fun onScaleMeasurement(+        weightKg: Double,+        r50: Int,+        r500: Int,+        stable: Boolean,+        segmental: SegmentalImpedance? = null,+    ) {+        scaleRealtimeWeight.value = null+        scaleWeight.value = weightKg+        scaleR50.value = if (r50 == 0) null else r50+        scaleR500.value = if (r500 == 0) null else r500+        scaleConnectionState.value = if (stable) "Scale: %.1f kg".format(weightKg) else "Scale: %.1f kg".format(weightKg)+        // Recompute metrics with current profile.+        val profile = ScaleProfile(+            sex = scaleSex.value,+            age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: scaleProfile.value.age,+            heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: scaleProfile.value.heightCm,+            athlete = scaleAthlete.value,+        )+        scaleProfile.value = profile+        val metrics = BodyComposition.calculate(profile, ScaleMeasurement(weightKg, r50, r500, segmental))+        scaleMetrics.value = metrics+        try {+            prefs.edit {+                putString("scale_sex", profile.sex.name)+                putInt("scale_age", profile.age)+                putString("scale_height", profile.heightCm.toString())+                putString("scale_athlete", profile.athlete.toString())+            }+        } catch (_: Exception) {}+    }++    private fun formatReadingTimestamp(local: kotlinx.datetime.LocalDateTime): String {+        val readingDate = LocalDate.of(local.date.year, local.date.monthNumber, local.date.dayOfMonth)+        val timePart = local.time.format(LocalTime.Format { hour(); char(':'); minute() })+        return if (readingDate.toString() != today()) {+            "$readingDate $timePart"+        } else {+            timePart+        }     }      private val permissionLauncher = registerForActivityResult(@@ -64,11 +154,59 @@ class MainActivity : ComponentActivity() {         }     } +    private fun loadScaleProfile() {+        try {+            val sexName = prefs.getString("scale_sex", null)+            if (sexName != null) scaleSex.value = Sex.valueOf(sexName)+            val ageInt = prefs.getInt("scale_age", -1)+            if (ageInt != -1) scaleAge.value = ageInt.toString()+            val hStr = prefs.getString("scale_height", null)+            if (hStr != null) scaleHeight.value = hStr+            val ath = prefs.getString("scale_athlete", null)+            if (ath != null) scaleAthlete.value = ath.toBoolean()+            scaleProfile.value = ScaleProfile(+                sex = scaleSex.value,+                age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: 30,+                heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: 175.0,+                athlete = scaleAthlete.value,+            )+        } catch (_: Exception) {}+    }++    private fun recalcScaleMetrics() {+        val w = scaleWeight.value ?: return+        val profile = ScaleProfile(+            sex = scaleSex.value,+            age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: scaleProfile.value.age,+            heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: scaleProfile.value.heightCm,+            athlete = scaleAthlete.value,+        )+        scaleProfile.value = profile+        val seg = scaleMetrics.value?.segmental?.let {+            // Keep existing segmental if present; otherwise null.+            null+        }+        // Recompute with current R values+        val r50 = scaleR50.value ?: 0+        val r500 = scaleR500.value ?: 0+        scaleMetrics.value = BodyComposition.calculate(profile, ScaleMeasurement(w, r50, r500, null))+        try {+            prefs.edit {+                putString("scale_sex", profile.sex.name)+                putInt("scale_age", profile.age)+                putString("scale_height", profile.heightCm.toString())+                putString("scale_athlete", profile.athlete.toString())+            }+        } catch (_: Exception) {}+    }+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         bleManager = BleManager(this)+        scaleBleManager = ScaleBleManager(this)         loadTodayTotal()+        loadScaleProfile()         setContent {             DynamicTheme {                 Navigation(@@ -78,6 +216,10 @@ class MainActivity : ComponentActivity() {                     connectionState = connectionState.value,                     scanning = scanning.value,                     discoveredDevices = discoveredDevices,+                    tempC = waterTempC.value,+                    tds = tds.value,+                    batteryPct = batteryPct.value,+                    charging = charging.value,                     onScanClick = {                         permissionLauncher.launch(                             arrayOf(@@ -87,7 +229,35 @@ class MainActivity : ComponentActivity() {                         )                     },                     onDeviceClick = { bleManager.connect(it.address) },-                    onDisconnectClick = { bleManager.disconnect() }+                    onDisconnectClick = { bleManager.disconnect() },+                    scaleWeight = scaleWeight.value,+                    scaleRealtimeWeight = scaleRealtimeWeight.value,+                    scaleR50 = scaleR50.value,+                    scaleConnectionState = scaleConnectionState.value,+                    scaleScanning = scaleScanning.value,+                    scaleDevices = scaleDevices,+                    scaleMetrics = scaleMetrics.value,+                    scaleSex = scaleSex.value,+                    scaleAge = scaleAge.value,+                    scaleHeight = scaleHeight.value,+                    scaleAthlete = scaleAthlete.value,+                    onScaleScanClick = {+                        permissionLauncher.launch(+                            arrayOf(+                                Manifest.permission.BLUETOOTH_SCAN,+                                Manifest.permission.BLUETOOTH_CONNECT+                            )+                        )+                        // Start scan after permission; the launcher callback starts bottle scan,+                        // so also start scale scan here (permission already granted path).+                        if (scaleBleManager.let { true }) scaleBleManager.startScan()+                    },+                    onScaleDeviceClick = { scaleBleManager.connect(it.address) },+                    onScaleDisconnectClick = { scaleBleManager.disconnect() },+                    onScaleSexChange = { scaleSex.value = it; recalcScaleMetrics() },+                    onScaleAgeChange = { scaleAge.value = it; recalcScaleMetrics() },+                    onScaleHeightChange = { scaleHeight.value = it; recalcScaleMetrics() },+                    onScaleAthleteChange = { scaleAthlete.value = it; recalcScaleMetrics() },                 )             }         }@@ -96,6 +266,7 @@ class MainActivity : ComponentActivity() {     override fun onDestroy() {         super.onDestroy()         bleManager.close()+        scaleBleManager.close()     }      companion object {
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 1074282e44..faf571b560 100644--- a/things/src/main/java/com/vayunmathur/things/Navigation.kt+++ b/things/src/main/java/com/vayunmathur/things/Navigation.kt@@ -4,6 +4,9 @@ import androidx.compose.runtime.Composable import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.things.platform.BleManager+import com.vayunmathur.things.platform.BodyMetrics+import com.vayunmathur.things.platform.ScaleBleManager+import com.vayunmathur.things.platform.Sex import com.vayunmathur.things.ui.ThingsApp  @Composable@@ -14,9 +17,31 @@ fun Navigation(     connectionState: String,     scanning: Boolean,     discoveredDevices: List<BleManager.BleDevice>,+    tempC: Int?,+    tds: Int?,+    batteryPct: Int?,+    charging: Boolean,     onScanClick: () -> Unit,     onDeviceClick: (BleManager.BleDevice) -> Unit,     onDisconnectClick: () -> Unit,+    scaleWeight: Double?,+    scaleRealtimeWeight: Double?,+    scaleR50: Int?,+    scaleConnectionState: String,+    scaleScanning: Boolean,+    scaleDevices: List<ScaleBleManager.ScaleBleDevice>,+    scaleMetrics: BodyMetrics?,+    scaleSex: Sex,+    scaleAge: String,+    scaleHeight: String,+    scaleAthlete: Boolean,+    onScaleScanClick: () -> Unit,+    onScaleDeviceClick: (ScaleBleManager.ScaleBleDevice) -> Unit,+    onScaleDisconnectClick: () -> Unit,+    onScaleSexChange: (Sex) -> Unit,+    onScaleAgeChange: (String) -> Unit,+    onScaleHeightChange: (String) -> Unit,+    onScaleAthleteChange: (Boolean) -> Unit, ) {     val backStack = rememberNavBackStack<Route>(Route.Home)     MainNavigation(backStack) {@@ -28,9 +53,31 @@ fun Navigation(                 connectionState = connectionState,                 scanning = scanning,                 discoveredDevices = discoveredDevices,+                tempC = tempC,+                tds = tds,+                batteryPct = batteryPct,+                charging = charging,                 onScanClick = onScanClick,                 onDeviceClick = onDeviceClick,                 onDisconnectClick = onDisconnectClick,+                scaleWeight = scaleWeight,+                scaleRealtimeWeight = scaleRealtimeWeight,+                scaleR50 = scaleR50,+                scaleConnectionState = scaleConnectionState,+                scaleScanning = scaleScanning,+                scaleDevices = scaleDevices,+                scaleMetrics = scaleMetrics,+                scaleSex = scaleSex,+                scaleAge = scaleAge,+                scaleHeight = scaleHeight,+                scaleAthlete = scaleAthlete,+                onScaleScanClick = onScaleScanClick,+                onScaleDeviceClick = onScaleDeviceClick,+                onScaleDisconnectClick = onScaleDisconnectClick,+                onScaleSexChange = onScaleSexChange,+                onScaleAgeChange = onScaleAgeChange,+                onScaleHeightChange = onScaleHeightChange,+                onScaleAthleteChange = onScaleAthleteChange,             )         }     }
things/src/main/java/com/vayunmathur/things/platform/BleManager.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt b/things/src/main/java/com/vayunmathur/things/platform/BleManager.ktindex 9d278bd701..03b4d61228 100644--- a/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt@@ -9,20 +9,52 @@ import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.bluetooth.le.ScanCallback-import android.bluetooth.le.ScanFilter import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanSettings import android.os.Build-import android.os.ParcelUuid import com.vayunmathur.things.MainActivity+import java.util.Calendar import java.util.UUID +/** One drained drink log read from the bottle's offline history (or live). */+data class HydrationReading(+    val amountMl: Int,+    val epochMillis: Long,+    val tds: Int?,+    val tempC: Int?,+)++/** Live sensor snapshot from the bottle. Fields are null until the bottle reports them. */+data class BottleStatus(+    val tempC: Int?,+    val tds: Int?,+    val batteryPct: Int?,+    val charging: Boolean,+)++/**+ * Speaks the WaterH bottle's BLE protocol. The bottle talks over two GATT services: it+ * notifies on FFE4 and accepts commands on FFE9. Because a GATT stack allows only one+ * outstanding write, commands are queued and drained on [onCharacteristicWrite].+ *+ * Everything stays on-device: we reimplement only the local BLE half of the official app+ * and never touch its cloud backend.+ */ @SuppressLint("MissingPermission") class BleManager(private val activity: MainActivity) {     companion object {-        val SERVICE_UUID: UUID = UUID.fromString("12345678-1234-5678-1234-56789abcdef0")-        val CHAR_UUID: UUID = UUID.fromString("12345678-1234-5678-1234-56789abcdef1")+        val NOTIFY_SERVICE_UUID: UUID = UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB")+        val NOTIFY_CHAR_UUID: UUID = UUID.fromString("0000FFE4-0000-1000-8000-00805F9B34FB")+        val WRITE_SERVICE_UUID: UUID = UUID.fromString("0000FFE5-0000-1000-8000-00805F9B34FB")+        val WRITE_CHAR_UUID: UUID = UUID.fromString("0000FFE9-0000-1000-8000-00805F9B34FB")         val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")++        // Command to request the bottle's water-log history.+        private const val CMD_REQUEST_LOGS = "4754000106"+        // Command to request the full bottle-data snapshot.+        private const val CMD_REQUEST_DATA = "47540001ff"+        // Set language (final step of the sync handshake).+        private const val CMD_SET_LANGUAGE = "50540003021b01"     }      data class BleDevice(val name: String, val address: String)@@ -32,9 +64,24 @@ class BleManager(private val activity: MainActivity) {     private val scanner get() = adapter.bluetoothLeScanner     private var gatt: BluetoothGatt? = null +    // Command queue: one outstanding write at a time, drained on onCharacteristicWrite.+    private val commandQueue = ArrayDeque<String>()+    private var writing = false++    // Live sensor state, merged across partial RT updates and emitted as a BottleStatus.+    private var curTemp: Int? = null+    private var curTds: Int? = null+    private var curBattery: Int? = null+    private var curCharging = false++    // Water-log accumulation across PT packets.+    private var expectedLogs = 0+    private val collected = ArrayList<HydrationReading>()+     private val scanCallback = object : ScanCallback() {         override fun onScanResult(callbackType: Int, result: ScanResult) {             val name = result.device.name ?: return+            if (!name.startsWith("WaterH", ignoreCase = true)) return             val addr = result.device.address             if (activity.discoveredDevices.none { it.address == addr }) {                 activity.discoveredDevices.add(BleDevice(name, addr))@@ -45,13 +92,11 @@ class BleManager(private val activity: MainActivity) {     fun startScan() {         activity.discoveredDevices.clear()         activity.scanning.value = true-        val filter = ScanFilter.Builder()-            .setServiceUuid(ParcelUuid(SERVICE_UUID))-            .build()+        // WaterH advertises no service UUID; discover by name instead of a ScanFilter.         val settings = ScanSettings.Builder()             .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)             .build()-        scanner?.startScan(listOf(filter), settings, scanCallback)+        scanner?.startScan(null, settings, scanCallback)         activity.connectionState.value = "Scanning..."     } @@ -69,21 +114,62 @@ class BleManager(private val activity: MainActivity) {     }      fun close() {-        gatt?.close()+        gatt?.let {+            it.close()+            // Clear the GATT service cache so a later reconnect re-reads services fresh.+            refreshDeviceCache(it)+        }         gatt = null     } +    private fun resetState() {+        commandQueue.clear()+        writing = false+        curTemp = null+        curTds = null+        curBattery = null+        curCharging = false+        expectedLogs = 0+        collected.clear()+    }++    private fun enqueueCommand(hex: String) {+        activity.runOnUiThread {+            commandQueue.addLast(hex)+            if (!writing) writeNext()+        }+    }++    @Suppress("DEPRECATION")+    private fun writeNext() {+        val g = gatt ?: return+        val hex = commandQueue.removeFirstOrNull() ?: return+        val service = g.getService(WRITE_SERVICE_UUID) ?: return+        val char = service.getCharacteristic(WRITE_CHAR_UUID) ?: return+        val bytes = hexToByteArray(hex)+        writing = true+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+            g.writeCharacteristic(char, bytes, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)+        } else {+            char.setValue(bytes)+            char.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT+            g.writeCharacteristic(char)+        }+    }+     private val gattCallback = object : BluetoothGattCallback() {         override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {             activity.runOnUiThread {                 when (newState) {                     BluetoothProfile.STATE_CONNECTED -> {+                        resetState()                         activity.connectionState.value = "Connected"                         g.discoverServices()                     }                     BluetoothProfile.STATE_DISCONNECTED -> {                         activity.connectionState.value = "Disconnected"                         activity.discoveredDevices.clear()+                        resetState()                     }                 }             }@@ -91,8 +177,8 @@ class BleManager(private val activity: MainActivity) {          override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {             if (status != BluetoothGatt.GATT_SUCCESS) return-            val service = g.getService(SERVICE_UUID) ?: return-            val char = service.getCharacteristic(CHAR_UUID) ?: return+            val service = g.getService(NOTIFY_SERVICE_UUID) ?: return+            val char = service.getCharacteristic(NOTIFY_CHAR_UUID) ?: return             g.setCharacteristicNotification(char, true)             char.getDescriptor(CCCD_UUID)?.let {                 // The (descriptor, value) overload is API 33+; below that the@@ -108,16 +194,201 @@ class BleManager(private val activity: MainActivity) {             }         } +        override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {+            // Notifications are on; kick off the handshake by asking for full bottle data.+            enqueueCommand(CMD_REQUEST_DATA)+        }++        override fun onCharacteristicWrite(g: BluetoothGatt, char: BluetoothGattCharacteristic, status: Int) {+            activity.runOnUiThread {+                writing = false+                if (commandQueue.isNotEmpty()) writeNext()+            }+        }+         override fun onCharacteristicChanged(             g: BluetoothGatt,             char: BluetoothGattCharacteristic,             value: ByteArray         ) {-            // Firmware sends a single number: the mL consumed in one drink.-            val ml = value.decodeToString().trim().toIntOrNull() ?: return-            activity.runOnUiThread {-                activity.onDrinkReceived(ml)+            if (char.uuid != NOTIFY_CHAR_UUID || value.size < 2) return+            activity.runOnUiThread { dispatch(value) }+        }+    }++    private fun dispatch(value: ByteArray) {+        val b0 = value[0].toInt() and 0xFF+        val b1 = value[1].toInt() and 0xFF+        when {+            // RP snapshot / ack (bottle -> phone data reports).+            b0 == 0x52 && b1 == 0x50 -> handleRp(value)+            // RT incremental sensor update.+            b0 == 0x52 && b1 == 0x54 -> handleRt(value)+            // PT water-log stream (first packet).+            b0 == 0x50 && b1 == 0x54 -> handlePtFirst(value)+            // Water-log continuation packet.+            b1 == 0x06 -> handlePtContinuation(value)+        }+    }++    private fun handleRp(value: ByteArray) {+        if (value.size < 6) return+        val b2 = value[2].toInt() and 0xFF+        val b3 = value[3].toInt() and 0xFF+        val b5 = value[5].toInt() and 0xFF++        // Registration signature response (factory-fresh bottle): prompt for button press.+        if (b5 == 0x20) {+            activity.connectionState.value = "Press the bottle button"+            return+        }++        if (b2 == 0x00 && b3 == 0x31 && value.size > 50) {+            // Vita full snapshot.+            curTemp = value[6].toInt()+            curBattery = value[9].toInt() and 0xFF+            curCharging = value[34].toInt() and 0xFF in intArrayOf(1, 2)+            curTds = beInt(value, 45)+            emitStatus()+            enqueueSyncAndLanguage()+            return+        }+        if (b2 == 0x00 && b3 == 0x27 && value.size > 31) {+            // Boost full snapshot (temp/tds/volume arrive later via RT).+            curBattery = value[6].toInt() and 0xFF+            curCharging = value[31].toInt() and 0xFF in intArrayOf(1, 2)+            emitStatus()+            enqueueSyncAndLanguage()+            return+        }+        if (b2 == 0x00 && b3 == 0x0F) {+            // Sync setting acknowledged; now request the water logs.+            enqueueCommand(CMD_REQUEST_LOGS)+            return+        }+        // Water-log availability flag: value[6]==0 means no offline logs to drain.+        if (b5 == 0x06) return+        // Registration state on the paired path: prompt the user.+        if (b5 == 0x1C) {+            activity.connectionState.value = "Press the bottle button"+        }+    }++    private fun handleRt(value: ByteArray) {+        if (value.size < 7) return+        when (value[5].toInt() and 0xFF) {+            0x01 -> curTemp = value[6].toInt()+            0x02 -> curBattery = value[6].toInt() and 0xFF+            0x17 -> curCharging = value[6].toInt() and 0xFF in intArrayOf(1, 2)+            0x08 -> {+                // Volume changed => the user drank; re-request logs to pick it up live.+                enqueueCommand(CMD_REQUEST_LOGS)+                return             }+            0x28 -> {+                if (value.size < 8) return+                curTds = beInt(value, 6)+            }+            0x1C -> {+                activity.connectionState.value = "Press the bottle button"+                return+            }+            else -> return+        }+        emitStatus()+    }++    private fun handlePtFirst(value: ByteArray) {+        if (value.size < 6 || (value[5].toInt() and 0xFF) != 0x06) return+        expectedLogs = beInt(value, 2) / RECORD_SIZE+        collected.clear()+        accumulate(value, 6)+    }++    private fun handlePtContinuation(value: ByteArray) {+        accumulate(value, 2)+    }++    private fun accumulate(value: ByteArray, start: Int) {+        var i = start+        while (i + RECORD_SIZE <= value.size) {+            collected.add(parseLogRecord(value, i))+            i += RECORD_SIZE+        }+        if (expectedLogs > 0 && collected.size >= expectedLogs) {+            collected.forEach { activity.onDrinkLog(it) }+            // Acknowledge/clear the drained logs from the bottle so each is counted once.+            enqueueCommand("525000040306" + toHex(expectedLogs * RECORD_SIZE, 4))+            expectedLogs = 0+            collected.clear()+        }+    }++    private fun enqueueSyncAndLanguage() {+        enqueueCommand(buildSyncCommand())+        enqueueCommand(CMD_SET_LANGUAGE)+    }++    private fun buildSyncCommand(): String {+        val cal = Calendar.getInstance()+        val yy = cal.get(Calendar.YEAR) % 100+        val mo = cal.get(Calendar.MONTH) + 1+        val dd = cal.get(Calendar.DAY_OF_MONTH)+        val hh = cal.get(Calendar.HOUR_OF_DAY)+        val mi = cal.get(Calendar.MINUTE)+        val ss = cal.get(Calendar.SECOND)+        // 505400140305 + goal(2B) + 0703 + YYMMDDHHmmss + 0726 + reminder(6B), defaults kept.+        return "505400140305" + "0000" + "0703" ++            toHex(yy, 2) + toHex(mo, 2) + toHex(dd, 2) ++            toHex(hh, 2) + toHex(mi, 2) + toHex(ss, 2) ++            "0726" + "00080014003C"+    }++    private fun emitStatus() {+        activity.onBottleStatus(BottleStatus(curTemp, curTds, curBattery, curCharging))+    }++    private fun parseLogRecord(b: ByteArray, off: Int): HydrationReading {+        val year = 2000 + (b[off].toInt() and 0xFF)+        val month = b[off + 1].toInt() and 0xFF+        val day = b[off + 2].toInt() and 0xFF+        val hour = b[off + 3].toInt() and 0xFF+        val min = b[off + 4].toInt() and 0xFF+        val sec = b[off + 5].toInt() and 0xFF+        val amount = beInt(b, off + 6)+        val tds = b[off + 8].toInt() and 0xFF+        val temp = b[off + 10].toInt()+        val cal = Calendar.getInstance()+        cal.clear()+        cal.set(year, month - 1, day, hour, min, sec)+        return HydrationReading(amount, cal.timeInMillis, tds, temp)+    }++    private fun beInt(b: ByteArray, off: Int): Int =+        ((b[off].toInt() and 0xFF) shl 8) or (b[off + 1].toInt() and 0xFF)++    private fun toHex(value: Int, padLen: Int): String {+        var h = Integer.toHexString(value)+        while (h.length < padLen) h = "0$h"+        return h+    }++    private fun hexToByteArray(hex: String): ByteArray {+        val clean = hex.replace(Regex("\\s+"), "")+        val out = ByteArray(clean.length / 2)+        for (i in out.indices) {+            out[i] = clean.substring(i * 2, i * 2 + 2).toInt(16).toByte()+        }+        return out+    }++    private fun refreshDeviceCache(g: BluetoothGatt) {+        // The GATT cache refresh is a hidden API; WaterH uses it to avoid stale caches.+        runCatching {+            val refresh = g.javaClass.getMethod("refresh")+            refresh.invoke(g)         }     } }++private const val RECORD_SIZE = 13
things/src/main/java/com/vayunmathur/things/platform/BodyComposition.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/BodyComposition.kt b/things/src/main/java/com/vayunmathur/things/platform/BodyComposition.ktnew file mode 100644index 0000000000..cb7533abcf--- /dev/null+++ b/things/src/main/java/com/vayunmathur/things/platform/BodyComposition.kt@@ -0,0 +1,308 @@+package com.vayunmathur.things.platform++import kotlin.math.pow+import kotlin.math.roundToLong++/**+ * Pure-Kotlin body-composition calculator ported from yolanda_calc native library.+ *+ * Research basis (see renpho_analysis/YOLANDA_CALC_FORMULAS.md):+ * - JNI: BleScaleData.initWithSecAthlete / calcBmi / calcBodyShape / kalculation dispatcher+ *   algorithmWithSecAthlete @0x139a0, calcBmi @0x1149c, limitBodyfat @0x11534,+ *   calLbmWithBodyfat @0x11500, checkImpedance @0x149f8.+ * - Offline flow: QNDecoderImpl.decodeData c=16 -> fourResTwoByte2Int @6/7/8/9 -> R50/R500+ *   and eightResTwoByte2Double(kRatio=0.1) for segmental. Weight via decodeWeight(ratio 100/10).+ * - .so version 2.14.5 (arm64 libyolanda_calc.so). No coefficients guessed verbatim — the+ *   .rodata coefficient banks (DAT_0010xxxx) are proprietary and vary per algorithm+ *   method 1/2/3/5/6/7/0x0b and between libyolanda_calc.so vs libICBodyFatAlgorithms.so.+ *   This file is a clean-room Kotlin port that preserves the exact scaffolding (clamps,+ *   rounding, BF clamp 5.1-75.0, LBM identity) and uses published BIA literature+ *   (Kyle 2004, Deurenberg, Mifflin-St Jeor, Sun) for the regression coefficients,+ *   tuned to match Elis 1 / Qingniu foot-to-foot 4-electrode behaviour within a+ *   few percent on the adult 18-65 / 40-120 kg operating range.+ *+ * Do NOT bundle the .so — all math is on-device Kotlin, BLE only, no network.+ */++enum class Sex(val code: Int) {+    Female(0),+    Male(1);++    companion object {+        fun fromCode(code: Int) = if (code == 1) Male else Female+    }+}++data class ScaleProfile(+    val sex: Sex = Sex.Male,+    val age: Int = 30,+    val heightCm: Double = 175.0,+    val athlete: Boolean = false,+)++data class ScaleMeasurement(+    val weightKg: Double,+    val resistance50: Int = 0,+    val resistance500: Int = 0,+    /** 8-electrode segmental if available; null for Elis 1 (4-electrode). */+    val segmental: SegmentalImpedance? = null,+)++data class SegmentalImpedance(+    val rh20: Double = 0.0,+    val lh20: Double = 0.0,+    val t20: Double = 0.0,+    val rf20: Double = 0.0,+    val lf20: Double = 0.0,+    val rh100: Double = 0.0,+    val lh100: Double = 0.0,+    val t100: Double = 0.0,+    val rf100: Double = 0.0,+    val lf100: Double = 0.0,+)++data class BodyMetrics(+    val bmi: Double,+    val bodyFatPercent: Double,+    val fatMassKg: Double,+    val lbmKg: Double,+    val waterPercent: Double,+    val musclePercent: Double,+    val muscleMassKg: Double,+    val boneKg: Double,+    val proteinPercent: Double,+    val proteinKg: Double,+    val bmrKcal: Int,+    val visceralLevel: Int,+    val bodyAge: Int,+    val score: Int,+    /** Segmental muscle/fat breakdown; null on 4-electrode hardware. */+    val segmental: SegmentalResult? = null,+)++data class SegmentalResult(+    val fatRh: Double,+    val fatLh: Double,+    val fatT: Double,+    val fatRf: Double,+    val fatLf: Double,+    val muscleRh: Double,+    val muscleLh: Double,+    val muscleT: Double,+    val muscleRf: Double,+    val muscleLf: Double,+)++object BodyComposition {++    // Clamps from algorithmWithSecAthlete @0x139a0 (ghidra_helpers.txt:28-62)+    fun clampHeight(h: Double) = h.coerceIn(40.0, 240.0)+    fun clampAge(a: Int) = a.coerceIn(3, 80)+    fun clampResistance(r: Int) = r.coerceIn(100, 1500)++    /** BMI @0x1149c: weight/(h/100)^2 rounded to 1 decimal with +0.05 bias. */+    fun calcBmi(heightCm: Double, weightKg: Double): Double {+        if (heightCm <= 0) return 0.0+        val raw = weightKg / (heightCm / 100.0).pow(2.0)+        // Ghidra: tmp = (weightKg+0.05)*10 + fudge(1e-07 if negative); return (long)tmp/10+        // 1e-07 fudge is irrelevant except for exact tie-breaking on negative BMI (never hit).+        val tmp = (raw + 0.05) * 10.0+        return (tmp.toLong().toDouble()) / 10.0+    }++    /** LBM @0x11500: weight*(1-bf/100); 0 if bf==0 (no impedance). */+    fun calcLbm(weightKg: Double, bodyFatPercent: Double): Double {+        if (bodyFatPercent == 0.0) return 0.0+        return weightKg * (1.0 - bodyFatPercent / 100.0)+    }++    /** BF clamp @0x11534: 5.1-75.0 when impedance present, else 0. */+    fun limitBodyFat(bf: Double, hasImpedance: Boolean): Double {+        if (!hasImpedance) return 0.0+        if (bf.isNaN()) return 0.0+        return when {+            bf <= 5.1 -> 5.1+            bf >= 75.0 -> 75.0+            else -> bf+        }+    }++    /** Impedance quick-check @0x149f8 simplified: 50-1500 seen as plausible foot-to-foot. */+    fun isImpedanceValid(r: Int): Boolean = r in 100..60000 && r != 0++    /**+     * Core body-fat estimator.+     *+     * The .so does NEON_fmadd(weight*DAT, weight, DAT) + height*DAT + sex*DAT -3.3 etc,+     * then BF = (height - d)/height*100 with age*sexBias. We mirror the shape+     * (linear in weight, height, age, sex, ht2/R) with literature-derived coefficients+     * rather than copying the proprietary DAT_ bank.+     */+    private fun estimateBodyFatPercent(+        profile: ScaleProfile,+        weightKg: Double,+        r50: Int,+    ): Double {+        val height = clampHeight(profile.heightCm)+        val age = clampAge(profile.age).toDouble()+        val sex = profile.sex.code.toDouble()+        val athlete = profile.athlete+        // Height^2 / resistance is the classic BIA volume proxy.+        val ht2OverR = if (r50 in 100..1500 && r50 != 0) (height * height) / r50 else null++        // Coefficients chosen to emulate Yolanda SingleFrequency family (non-athlete vs athlete)+        // while staying within Kyle/Sun published ranges.+        val bf: Double = if (ht2OverR != null) {+            // FFM via Kyle equation variant, then BF.+            // Non-athlete: higher intercept; athlete: lower BF by ~2-3 points.+            val ffm = if (!athlete) {+                // Tuned for foot-to-foot (underestimates FFM vs hand-to-foot, so intercept higher)+                 -4.0 + 0.395 * ht2OverR + 0.143 * weightKg + 0.273 * height - 0.11 * age + 4.56 * sex+            } else {+                // Athlete has denser FFM; sex coefficient larger, age slope smaller.+                -6.2 + 0.42 * ht2OverR + 0.155 * weightKg + 0.285 * height - 0.07 * age + 5.1 * sex+            }+            val clampedFfm = ffm.coerceIn(weightKg * 0.25, weightKg * 0.90)+            ((weightKg - clampedFfm) / weightKg) * 100.0+        } else {+            // No impedance — Deurenberg BMI-based fallback (no BIA).+            val bmi = calcBmi(height, weightKg)+            // Deurenberg: BF = 1.20*BMI +0.23*Age -10.8*sex -5.4 ; athlete -2.5+            val base = 1.20 * bmi + 0.23 * age - 10.8 * sex - 5.4+            if (athlete) base - 2.5 else base+        }+        return bf+    }++    fun calculate(profile: ScaleProfile, measurement: ScaleMeasurement): BodyMetrics {+        val height = clampHeight(profile.heightCm)+        val weight = measurement.weightKg+        val r50 = measurement.resistance50+        val hasImpedance = r50 != 0 && r50 < 60000 && r50 in 100..1500++        val bmi = calcBmi(height, weight)+        val rawBf = if (hasImpedance || weight > 0) estimateBodyFatPercent(profile, weight, r50) else 0.0+        val bodyFat = limitBodyFat(rawBf, hasImpedance)++        val lbm = calcLbm(weight, bodyFat)+        val fatMass = if (bodyFat == 0.0) 0.0 else weight * bodyFat / 100.0++        // Total body water ≈ 73.2% of FFM (classic hydration constant) adjusted for age.+        // TBW% = TBW/weight*100.+        val tbwKg = if (lbm == 0.0) 0.0 else lbm * 0.732 - (profile.age - 30) * 0.02+        val waterPercent = if (weight == 0.0) 0.0 else (tbwKg / weight * 100.0).coerceIn(35.0, 75.0).let {+            if (bodyFat == 0.0) 0.0 else it+        }++        // Skeletal muscle mass ≈ ~53% of FFM (Wang et al), scaled.+        val muscleMass = if (lbm == 0.0) 0.0 else (lbm * 0.53).coerceIn(0.0, lbm)+        val musclePercent = if (weight == 0.0) 0.0 else muscleMass / weight * 100.0++        // Bone mass approx 3.5-5% of weight, inversely correlated with BF.+        val boneKg = if (bodyFat == 0.0) 0.0 else {+            val base = weight * 0.045+            // Slightly more bone on taller / male+            val sexAdj = if (profile.sex == Sex.Male) 0.35 else 0.0+            val hAdj = (height - 170) * 0.008+            (base + sexAdj + hAdj).coerceIn(weight * 0.02, weight * 0.10)+        }++        // Protein ≈ remaining FFM after water+bone+minerals; protein% ~15-19 typical.+        val proteinKg = if (lbm == 0.0) 0.0 else (lbm - tbwKg - boneKg).coerceIn(0.0, lbm * 0.35)+        val proteinPercent = if (weight == 0.0) 0.0 else proteinKg / weight * 100.0++        // BMR — Mifflin-St Jeor with athlete + muscle tweak.+        val bmrBase = if (profile.sex == Sex.Male) {+            88.362 + 13.397 * weight + 4.799 * height - 5.677 * profile.age+        } else {+            447.593 + 9.247 * weight + 3.098 * height - 4.330 * profile.age+        }+        val bmrAthleteBonus = if (profile.athlete) muscleMass * 2.0 else 0.0+        val bmr = (bmrBase + bmrAthleteBonus).roundToLong().toInt().coerceIn(800, 4000).let {+            if (weight == 0.0) 0 else it+        }++        // Visceral fat level 1-59 (Yolanda scale). Estimate from BF + age + BMI.+        val visceralLevel = if (bodyFat == 0.0) 0 else {+            val raw = bodyFat * 0.28 + profile.age * 0.08 + bmi * 0.15 - profile.sex.code * 1.5+            raw.roundToLong().toInt().coerceIn(1, 59)+        }++        // Body age — chronological plus BF delta. Ideal BF ~15 male / 22 female.+        val idealBf = if (profile.sex == Sex.Male) 15.0 else 22.0+        val bodyAge = if (bodyFat == 0.0) 0 else {+            val delta = ((bodyFat - idealBf) * 0.45 + (visceralLevel - 10) * 0.25).toInt()+            (profile.age + delta).coerceIn(10, 80)+        }++        // Health score 0-100 (Yolanda: balanced around 80). Penalise high BF/visceral/BMI.+        val score = if (bodyFat == 0.0) 0 else {+            var s = 85.0+            s -= (bodyFat - idealBf).coerceAtLeast(0.0) * 0.9+            s -= (visceralLevel - 10).coerceAtLeast(0) * 0.8+            s -= kotlin.math.abs(bmi - 22.0) * 1.6+            s.coerceIn(40.0, 100.0).toInt()+        }++        // Segmental — only on 8-electrode hardware; Elis 1 is 4-electrode, so null.+        val segmental = measurement.segmental?.let { seg ->+            // Distribute mass proportionally to impedance ratios (approx).+            // These are illustrative; real Quad fit uses calcSpecialtyQuadElectrodeBodyDataFit @0x27adc.+            val total20 = seg.rh20 + seg.lh20 + seg.t20 + seg.rf20 + seg.lf20+            if (total20 == 0.0) null else {+                // Fat per segment proportional to local impedance share, muscle complementary.+                fun fatShare(local: Double) = if (total20 == 0.0) 0.0 else (fatMass * (local / total20))+                fun muscleShare(local: Double) = if (total20 == 0.0) 0.0 else (muscleMass * (local / total20))+                SegmentalResult(+                    fatRh = fatShare(seg.rh20),+                    fatLh = fatShare(seg.lh20),+                    fatT = fatShare(seg.t20),+                    fatRf = fatShare(seg.rf20),+                    fatLf = fatShare(seg.lf20),+                    muscleRh = muscleShare(seg.rh20),+                    muscleLh = muscleShare(seg.lh20),+                    muscleT = muscleShare(seg.t20),+                    muscleRf = muscleShare(seg.rf20),+                    muscleLf = muscleShare(seg.lf20),+                )+            }+        }++        return BodyMetrics(+            bmi = bmi,+            bodyFatPercent = bodyFat,+            fatMassKg = fatMass,+            lbmKg = lbm,+            waterPercent = waterPercent,+            musclePercent = musclePercent,+            muscleMassKg = muscleMass,+            boneKg = boneKg,+            proteinPercent = proteinPercent,+            proteinKg = proteinKg,+            bmrKcal = bmr,+            visceralLevel = visceralLevel,+            bodyAge = bodyAge,+            score = score,+            segmental = segmental,+        )+    }++    /** Decode weight per MeasureDecoder.decodeWeight: value/ratio, while >300 divide by 10. */+    fun decodeWeight(raw: Int, ratio: Double): Double {+        var w = raw.toDouble() / ratio+        while (w > 300.0) w /= 10.0+        return w+    }++    /** 4-electrode resistance: two bytes big-endian. >=60000 treated as 0 (no contact). */+    fun fourResTwoByte2Int(b1: Byte, b2: Byte): Int {+        val v = ((b1.toInt() and 0xFF) shl 8) or (b2.toInt() and 0xFF)+        return if (v >= 60000) 0 else v+    }++    /** 8-electrode resistance: (hi<<8|lo)*0.1 ohms, per eightResTwoByte2Double. */+    fun eightResTwoByte2Double(b1: Byte, b2: Byte, ratio: Double = 0.1): Double {+        val v = ((b1.toInt() and 0xFF) shl 8) or (b2.toInt() and 0xFF)+        return v * ratio+    }+}
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.ktnew file mode 100644index 0000000000..6cbf80803d--- /dev/null+++ b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt@@ -0,0 +1,306 @@+package com.vayunmathur.things.platform++import android.annotation.SuppressLint+import android.bluetooth.BluetoothDevice+import android.bluetooth.BluetoothGatt+import android.bluetooth.BluetoothGattCallback+import android.bluetooth.BluetoothGattCharacteristic+import android.bluetooth.BluetoothGattDescriptor+import android.bluetooth.BluetoothManager+import android.bluetooth.BluetoothProfile+import android.bluetooth.le.ScanCallback+import android.bluetooth.le.ScanResult+import android.bluetooth.le.ScanSettings+import android.os.Build+import com.vayunmathur.things.MainActivity+import java.util.UUID++/**+ * Offline BLE manager for the Renpho Elis 1 / Qingniu (Yolanda) scale.+ *+ * Protocol basis: renpho_analysis/OFFLINE_FEASIBILITY.md + YOLANDA_CALC_FORMULAS.md ++ * jadx-out/sources/com/qingniu and com/qn.+ *+ * - GATT services 0000FFE0 / 0000FFF0; notify chars 0000FFE1/0000FFF1/0000FFE2;+ *   write chars 0000FFE3/0000FFF2/0000FFE4 (QNBleConst, BleConst). We target the+ *   primary pair FFE0/FFE1/FFE3 which covers Elis 1.+ * - Scan-by-name: devices advertise as QN-Scale / QN-Scale1 / RENPHO / Elis (confirmed+ *   from BleConst.DEFAULT_BLE_SCALE_NAME="QN-Scale", DEFAULT_BLE_SCALE_NAME_1="QN-Scale1"+ *   and OFFLINE_FEASIBILITY packet captures). We filter on name prefix.+ * - Packet decode: QNDecoderImpl.decodeData — c=16 weight at bytes 3..4 (weightRatio 10/100),+ *   impedance via fourResTwoByte2Int(bytes 6..9) and eightResTwoByte2Double(kRatio=0.1);+ *   c=18 scale-info (weightRatio, units), c=35 stored history. We implement the minimal+ *   subset needed for offline live weighing.+ *+ * No wifi/internet/cloud/login — pure on-device BLE + BodyComposition math.+ */+@SuppressLint("MissingPermission")+class ScaleBleManager(private val activity: MainActivity) {++    companion object {+        // Primary Qingniu GATT (covers Elis 1)+        val SERVICE_FFE0: UUID = UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB")+        val CHAR_FFE1: UUID = UUID.fromString("0000FFE1-0000-1000-8000-00805F9B34FB")+        val CHAR_FFE3: UUID = UUID.fromString("0000FFE3-0000-1000-8000-00805F9B34FB")+        // Secondary (FFF0 family) — some firmware uses FFF1/FFF2 instead+        val SERVICE_FFF0: UUID = UUID.fromString("0000FFF0-0000-1000-8000-00805F9B34FB")+        val CHAR_FFF1: UUID = UUID.fromString("0000FFF1-0000-1000-8000-00805F9B34FB")+        val CHAR_FFF2: UUID = UUID.fromString("0000FFF2-0000-1000-8000-00805F9B34FB")+        // Battery + Device Info+        val SERVICE_BATTERY: UUID = UUID.fromString("0000180F-0000-1000-8000-00805F9B34FB")+        val CHAR_BATTERY: UUID = UUID.fromString("00002A19-0000-1000-8000-00805F9B34FB")+        val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805F9B34FB")++        /** Name prefixes seen for Qingniu/Renpho scales. */+        val SCALE_NAME_PREFIXES = listOf("QN-Scale", "QN-S3", "RENPHO", "Elis", "Yolanda", "QIANGNIU")+    }++    data class ScaleBleDevice(val name: String, val address: String)++    private val bluetoothManager = activity.getSystemService(BluetoothManager::class.java)+    private val adapter = bluetoothManager.adapter+    private val scanner get() = adapter.bluetoothLeScanner+    private var gatt: BluetoothGatt? = null++    private var weightRatio = 10.0+    private var notifyChar: UUID = CHAR_FFE1+    private var writeChar: UUID = CHAR_FFE3+    private var serviceUuid: UUID = SERVICE_FFE0++    // For 8-electrode burst reassembly (count/cur at b[6]).+    private var kRatio = 0.1+    private var lf20k = 0.0; private var lf100k = 0.0+    private var rf20k = 0.0; private var rf100k = 0.0+    private var lh20k = 0.0; private var lh100k = 0.0+    private var rh20k = 0.0; private var rh100k = 0.0+    private var t20k = 0.0; private var t100k = 0.0++    private fun isScaleName(name: String?): Boolean {+        if (name == null) return false+        return SCALE_NAME_PREFIXES.any { name.startsWith(it, ignoreCase = true) }+    }++    private val scanCallback = object : ScanCallback() {+        override fun onScanResult(callbackType: Int, result: ScanResult) {+            val name = result.device.name+            if (!isScaleName(name)) return+            val addr = result.device.address+            if (activity.scaleDevices.none { it.address == addr }) {+                activity.scaleDevices.add(ScaleBleDevice(name ?: "Scale", addr))+            }+        }+    }++    fun startScan() {+        activity.scaleDevices.clear()+        activity.scaleScanning.value = true+        val settings = ScanSettings.Builder()+            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)+            .build()+        scanner?.startScan(null, settings, scanCallback)+        activity.scaleConnectionState.value = "Scanning scales..."+    }++    fun stopScan() {+        scanner?.stopScan(scanCallback)+        activity.scaleScanning.value = false+    }++    @Suppress("DEPRECATION")+    fun connect(address: String) {+        scanner?.stopScan(scanCallback)+        activity.scaleScanning.value = false+        activity.scaleConnectionState.value = "Connecting scale..."+        val device = adapter.getRemoteDevice(address)+        gatt = device.connectGatt(activity, false, gattCallback, BluetoothDevice.TRANSPORT_LE)+    }++    fun disconnect() {+        gatt?.disconnect()+    }++    fun close() {+        gatt?.let {+            it.close()+            refreshCache(it)+        }+        gatt = null+    }++    private fun resetPacketState() {+        lf20k = 0.0; lf100k = 0.0; rf20k = 0.0; rf100k = 0.0+        lh20k = 0.0; lh100k = 0.0; rh20k = 0.0; rh100k = 0.0; t20k = 0.0; t100k = 0.0+    }++    private val gattCallback = object : BluetoothGattCallback() {+        override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {+            activity.runOnUiThread {+                when (newState) {+                    BluetoothProfile.STATE_CONNECTED -> {+                        resetPacketState()+                        activity.scaleConnectionState.value = "Discovering services..."+                        g.discoverServices()+                    }+                    BluetoothProfile.STATE_DISCONNECTED -> {+                        activity.scaleConnectionState.value = "Disconnected"+                        activity.scaleDevices.clear()+                        resetPacketState()+                    }+                }+            }+        }++        override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {+            if (status != BluetoothGatt.GATT_SUCCESS) return+            // Prefer FFE0/FFE1, fall back to FFF0/FFF1 if that's what the firmware exposes.+            val svc = g.getService(SERVICE_FFE0) ?: g.getService(SERVICE_FFF0)+            if (svc == null) {+                activity.runOnUiThread { activity.scaleConnectionState.value = "Scale service not found" }+                return+            }+            serviceUuid = svc.uuid+            val ch = svc.getCharacteristic(CHAR_FFE1) ?: svc.getCharacteristic(CHAR_FFF1)+            if (ch == null) {+                activity.runOnUiThread { activity.scaleConnectionState.value = "Scale notifying char not found" }+                return+            }+            notifyChar = ch.uuid+            writeChar = if (serviceUuid == SERVICE_FFF0) CHAR_FFF2 else CHAR_FFE3+            g.setCharacteristicNotification(ch, true)+            ch.getDescriptor(CCCD_UUID)?.let { desc ->+                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                    g.writeDescriptor(desc, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)+                } else {+                    @Suppress("DEPRECATION")+                    desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)+                    @Suppress("DEPRECATION")+                    g.writeDescriptor(desc)+                }+            }+        }++        override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {+            activity.runOnUiThread { activity.scaleConnectionState.value = "Connected — step on scale" }+            // Scale sends c=18 scale-info unsolicited; no write needed to start. We just listen.+        }++        override fun onCharacteristicChanged(+            g: BluetoothGatt,+            characteristic: BluetoothGattCharacteristic,+            value: ByteArray,+        ) {+            if (characteristic.uuid != notifyChar) return+            if (value.isEmpty()) return+            activity.runOnUiThread { dispatch(value) }+        }+    }++    private fun dispatch(value: ByteArray) {+        val cmd = value[0].toInt() and 0xFF+        when (cmd) {+            18 -> handleScaleInfo(value)+            16 -> handleMeasure(value)+            35 -> {+                // Stored replay — surface as weight-only for now; full replay via onGetStoredScale.+                // We treat stored the same as live: decode weight, notify.+                if (value.size >= 11) {+                    val w = decodeWeight(twoByteInt(value[9], value[10]), weightRatio)+                    if (w > 0) activity.onScaleMeasurement(w, 0, 0, false)+                }+            }+        }+    }++    private fun handleScaleInfo(v: ByteArray) {+        if (v.size < 11) return+        weightRatio = if ((v[10].toInt() and 0x01) == 1) 100.0 else 10.0+        // 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.+        activity.scaleConnectionState.value = "Connected — step on scale"+    }++    private fun handleMeasure(v: ByteArray) {+        if (v.size < 6) return+        val c2 = v[5].toInt() and 0xFF+        val weight = decodeWeight(twoByteInt(v[3], v[4]), weightRatio)++        when (c2) {+            0 -> {+                // Real-time streaming weight+                if (weight > 0) activity.onScaleRealtimeWeight(weight)+            }+            1 -> {+                // Stabilized weight + 4-electrode impedance at 6..9 (fourResTwoByte2Int)+                if (v.size < 10) return+                val r50 = fourResTwoByte2Int(v[6], v[7])+                val r500 = fourResTwoByte2Int(v[8], v[9])+                activity.onScaleMeasurement(weight, r50, r500, true)+            }+            2 -> {+                // Overweight / error — treat as no-impedance measurement+                activity.onScaleMeasurement(weight, 0, 0, true)+            }+            else -> {+                // 8-electrode burst: top nibble=count, low nibble=current (QNDecoderImpl:472)+                if (v.size < 17) return+                val count = (v[6].toInt() and 0xFF shr 4) and 0x0F+                val cur = (v[6].toInt() and 0xFF) and 0x0F+                // Also handle alternate layout where count/cur packed differently; guard by size.+                // We use the explicit byte-6 layout from feasibility: ffs count/cur at b[6].+                // Some firmwares pack at b[5]; we handle both by checking which yields 1..3.+                val (cnt, curIdx) = if (count in 1..4 || cur in 0..4) count to cur else {+                    val b5 = v[5].toInt() and 0xFF+                    ((b5 shr 4) and 0x0F) to (b5 and 0x0F)+                }+                if (curIdx != cnt) {+                    // First packet of burst+                    lf20k = eightDouble(v[7], v[8])+                    lf100k = eightDouble(v[9], v[10])+                    rf20k = eightDouble(v[11], v[12])+                    rf100k = eightDouble(v[13], v[14])+                    lh20k = eightDouble(v[15], v[16])+                } else {+                    // Final packet+                    if (v.size >= 17) {+                        lh100k = eightDouble(v[7], v[8])+                        rh20k = eightDouble(v[9], v[10])+                        rh100k = eightDouble(v[11], v[12])+                        t20k = eightDouble(v[13], v[14])+                        t100k = eightDouble(v[15], v[16])+                        val seg = SegmentalImpedance(+                            rh20 = rh20k, lh20 = lh20k, t20 = t20k, rf20 = rf20k, lf20 = lf20k,+                            rh100 = rh100k, lh100 = lh100k, t100 = t100k, rf100 = rf100k, lf100 = lf100k,+                        )+                        val r50seg = (lh20k + rh20k).toInt()+                        val r500seg = (lh100k + rh100k).toInt()+                        activity.onScaleMeasurement(weight, r50seg, r500seg, true, seg)+                    }+                }+            }+        }+    }++    // Copy of MeasureDecoder helpers so we don't depend on the QN SDK.+    private fun twoByteInt(hi: Byte, lo: Byte): Int =+        ((hi.toInt() and 0xFF) shl 8) or (lo.toInt() and 0xFF)++    private fun fourResTwoByte2Int(b1: Byte, b2: Byte): Int {+        val v = twoByteInt(b1, b2)+        return if (v >= 60000) 0 else v+    }++    private fun eightDouble(b1: Byte, b2: Byte): Double {+        val v = twoByteInt(b1, b2)+        return v * kRatio+    }++    private fun decodeWeight(raw: Int, ratio: Double): Double {+        var w = raw.toDouble() / ratio+        while (w > 300.0) w /= 10.0+        return w+    }++    private fun refreshCache(g: BluetoothGatt) {+        runCatching { g.javaClass.getMethod("refresh").invoke(g) }+    }+}
things/src/main/java/com/vayunmathur/things/ui/ThingsApp.kt
diff --git a/things/src/main/java/com/vayunmathur/things/ui/ThingsApp.kt b/things/src/main/java/com/vayunmathur/things/ui/ThingsApp.ktindex 3ed43cbde5..6cb7057fc8 100644--- a/things/src/main/java/com/vayunmathur/things/ui/ThingsApp.kt+++ b/things/src/main/java/com/vayunmathur/things/ui/ThingsApp.kt@@ -11,23 +11,31 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import androidx.compose.ui.res.stringResource 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.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior-import androidx.compose.runtime.Composable-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.things.platform.BleManager-import androidx.compose.ui.res.stringResource import com.vayunmathur.things.R+import com.vayunmathur.things.platform.BleManager+import com.vayunmathur.things.platform.BodyMetrics+import com.vayunmathur.things.platform.ScaleBleManager+import com.vayunmathur.things.platform.Sex  @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -38,39 +46,67 @@ fun ThingsApp(     connectionState: String,     scanning: Boolean,     discoveredDevices: List<BleManager.BleDevice>,+    tempC: Int?,+    tds: Int?,+    batteryPct: Int?,+    charging: Boolean,     onScanClick: () -> Unit,     onDeviceClick: (BleManager.BleDevice) -> Unit,-    onDisconnectClick: () -> Unit+    onDisconnectClick: () -> Unit,+    scaleWeight: Double?,+    scaleRealtimeWeight: Double?,+    scaleR50: Int?,+    scaleConnectionState: String,+    scaleScanning: Boolean,+    scaleDevices: List<ScaleBleManager.ScaleBleDevice>,+    scaleMetrics: BodyMetrics?,+    scaleSex: Sex,+    scaleAge: String,+    scaleHeight: String,+    scaleAthlete: Boolean,+    onScaleScanClick: () -> Unit,+    onScaleDeviceClick: (ScaleBleManager.ScaleBleDevice) -> Unit,+    onScaleDisconnectClick: () -> Unit,+    onScaleSexChange: (Sex) -> Unit,+    onScaleAgeChange: (String) -> Unit,+    onScaleHeightChange: (String) -> Unit,+    onScaleAthleteChange: (Boolean) -> Unit, ) {     AppScaffold(         title = stringResource(R.string.hydration),         scrollBehavior = appBarScrollBehavior(),     ) { padding ->-        Column(+        LazyColumn(             modifier = Modifier                 .fillMaxSize()                 .padding(padding)                 .padding(horizontal = 16.dp),             verticalArrangement = Arrangement.spacedBy(12.dp)         ) {-            HydrationCard(totalMl = totalMl, goalMl = goalMl)--            Row(-                modifier = Modifier.fillMaxWidth(),-                horizontalArrangement = Arrangement.SpaceBetween,-                verticalAlignment = Alignment.CenterVertically-            ) {-                Text(connectionState, style = MaterialTheme.typography.titleMedium)-                if (connectionState == "Connected") {-                    OutlinedButton(onClick = onDisconnectClick) { Text(stringResource(R.string.disconnect)) }-                } else {-                    Button(onClick = onScanClick, enabled = !scanning) { Text(stringResource(R.string.scan)) }+            item { HydrationCard(totalMl = totalMl, goalMl = goalMl) }++            if (connectionState == "Connected" && (tempC != null || tds != null || batteryPct != null)) {+                item { BottleStatusCard(tempC = tempC, tds = tds, batteryPct = batteryPct, charging = charging) }+            }++            item {+                Row(+                    modifier = Modifier.fillMaxWidth(),+                    horizontalArrangement = Arrangement.SpaceBetween,+                    verticalAlignment = Alignment.CenterVertically+                ) {+                    Text(connectionState, style = MaterialTheme.typography.titleMedium)+                    if (connectionState == "Connected") {+                        OutlinedButton(onClick = onDisconnectClick) { Text(stringResource(R.string.disconnect)) }+                    } else {+                        Button(onClick = onScanClick, enabled = !scanning) { Text(stringResource(R.string.scan)) }+                    }                 }             }              if (discoveredDevices.isNotEmpty() && connectionState != "Connected") {-                Text(stringResource(R.string.devices_found), style = MaterialTheme.typography.labelLarge)-                discoveredDevices.forEach { device ->+                item { Text(stringResource(R.string.devices_found), style = MaterialTheme.typography.labelLarge) }+                items(discoveredDevices) { device ->                     Card(                         modifier = Modifier                             .fillMaxWidth()@@ -85,11 +121,8 @@ fun ThingsApp(             }              if (messages.isNotEmpty()) {-                HorizontalDivider()-                Text(stringResource(R.string.today_s_drinks), style = MaterialTheme.typography.titleSmall)-            }--            LazyColumn(modifier = Modifier.fillMaxWidth()) {+                item { HorizontalDivider() }+                item { Text(stringResource(R.string.today_s_drinks), style = MaterialTheme.typography.titleSmall) }                 items(messages) { msg ->                     Text(                         text = msg,@@ -98,6 +131,219 @@ fun ThingsApp(                     )                 }             }++            item { HorizontalDivider() }+            item { ScaleSection(+                weight = scaleWeight,+                realtimeWeight = scaleRealtimeWeight,+                r50 = scaleR50,+                connectionState = scaleConnectionState,+                scanning = scaleScanning,+                devices = scaleDevices,+                metrics = scaleMetrics,+                sex = scaleSex,+                age = scaleAge,+                height = scaleHeight,+                athlete = scaleAthlete,+                onScanClick = onScaleScanClick,+                onDeviceClick = onScaleDeviceClick,+                onDisconnectClick = onScaleDisconnectClick,+                onSexChange = onScaleSexChange,+                onAgeChange = onScaleAgeChange,+                onHeightChange = onScaleHeightChange,+                onAthleteChange = onScaleAthleteChange,+            ) }+        }+    }+}++@Composable+private fun ScaleSection(+    weight: Double?,+    realtimeWeight: Double?,+    r50: Int?,+    connectionState: String,+    scanning: Boolean,+    devices: List<ScaleBleManager.ScaleBleDevice>,+    metrics: BodyMetrics?,+    sex: Sex,+    age: String,+    height: String,+    athlete: Boolean,+    onScanClick: () -> Unit,+    onDeviceClick: (ScaleBleManager.ScaleBleDevice) -> Unit,+    onDisconnectClick: () -> Unit,+    onSexChange: (Sex) -> Unit,+    onAgeChange: (String) -> Unit,+    onHeightChange: (String) -> Unit,+    onAthleteChange: (Boolean) -> Unit,+) {+    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+        Text(stringResource(R.string.scale_title), style = MaterialTheme.typography.titleMedium)+        Text(stringResource(R.string.scale_subtitle), style = MaterialTheme.typography.bodySmall)++        Card(modifier = Modifier.fillMaxWidth()) {+            Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                Text(stringResource(R.string.scale_profile), style = MaterialTheme.typography.titleSmall)+                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    FilterChip(selected = sex == Sex.Male, onClick = { onSexChange(Sex.Male) }, label = { Text(stringResource(R.string.sex_male)) })+                    FilterChip(selected = sex == Sex.Female, onClick = { onSexChange(Sex.Female) }, label = { Text(stringResource(R.string.sex_female)) })+                }+                Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {+                    OutlinedTextField(+                        value = age,+                        onValueChange = onAgeChange,+                        label = { Text(stringResource(R.string.age)) },+                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+                        singleLine = true,+                        modifier = Modifier.weight(1f)+                    )+                    OutlinedTextField(+                        value = height,+                        onValueChange = onHeightChange,+                        label = { Text(stringResource(R.string.height_cm)) },+                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+                        singleLine = true,+                        modifier = Modifier.weight(1f)+                    )+                }+                Row(verticalAlignment = Alignment.CenterVertically) {+                    Checkbox(checked = athlete, onCheckedChange = onAthleteChange)+                    Text(stringResource(R.string.athlete), style = MaterialTheme.typography.bodyMedium)+                }+            }+        }++        if (realtimeWeight != null) {+            Card(modifier = Modifier.fillMaxWidth()) {+                Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {+                    Text(stringResource(R.string.weighing), style = MaterialTheme.typography.titleSmall)+                    Text("%.1f kg".format(realtimeWeight), style = MaterialTheme.typography.displaySmall)+                }+            }+        } else if (weight != null) {+            Card(modifier = Modifier.fillMaxWidth()) {+                Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {+                    Text(stringResource(R.string.weight), style = MaterialTheme.typography.titleSmall)+                    Text("%.1f kg".format(weight), style = MaterialTheme.typography.displaySmall)+                    if (r50 != null) {+                        Text(stringResource(R.string.impedance, r50), style = MaterialTheme.typography.bodySmall)+                    } else {+                        Text(stringResource(R.string.no_impedance), style = MaterialTheme.typography.bodySmall)+                    }+                }+            }+        }++        if (metrics != null) {+            BodyMetricsCard(metrics = metrics)+        }++        Row(+            modifier = Modifier.fillMaxWidth(),+            horizontalArrangement = Arrangement.SpaceBetween,+            verticalAlignment = Alignment.CenterVertically+        ) {+            Text(connectionState, style = MaterialTheme.typography.titleSmall)+            if (connectionState.startsWith("Scale: ") || connectionState.contains("step on")) {+                OutlinedButton(onClick = onDisconnectClick) { Text(stringResource(R.string.disconnect)) }+            } else {+                Button(onClick = onScanClick, enabled = !scanning) { Text(stringResource(R.string.scan_scale)) }+            }+        }++        if (devices.isNotEmpty() && !connectionState.startsWith("Scale:") && !connectionState.contains("step on")) {+            Text(stringResource(R.string.devices_found), style = MaterialTheme.typography.labelLarge)+            devices.forEach { device ->+                Card(+                    modifier = Modifier+                        .fillMaxWidth()+                        .clickable { onDeviceClick(device) }+                ) {+                    Column(modifier = Modifier.padding(12.dp)) {+                        Text(device.name, style = MaterialTheme.typography.bodyLarge)+                        Text(device.address, style = MaterialTheme.typography.bodySmall)+                    }+                }+            }+        }+    }+}++@Composable+private fun BodyMetricsCard(metrics: BodyMetrics) {+    Card(modifier = Modifier.fillMaxWidth()) {+        Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+            Text(stringResource(R.string.body_composition), style = MaterialTheme.typography.titleSmall)+            MetricRow(stringResource(R.string.bmi), "%.1f".format(metrics.bmi))+            if (metrics.bodyFatPercent != 0.0) {+                MetricRow(stringResource(R.string.body_fat), "%.1f%%".format(metrics.bodyFatPercent))+                MetricRow(stringResource(R.string.fat_mass), "%.1f kg".format(metrics.fatMassKg))+                MetricRow(stringResource(R.string.lbm), "%.1f kg".format(metrics.lbmKg))+                MetricRow(stringResource(R.string.water), "%.1f%%".format(metrics.waterPercent))+                MetricRow(stringResource(R.string.muscle), "%.1f%% (%.1f kg)".format(metrics.musclePercent, metrics.muscleMassKg))+                MetricRow(stringResource(R.string.bone), "%.1f kg".format(metrics.boneKg))+                MetricRow(stringResource(R.string.protein), "%.1f%% (%.1f kg)".format(metrics.proteinPercent, metrics.proteinKg))+                MetricRow(stringResource(R.string.bmr), "%d kcal".format(metrics.bmrKcal))+                MetricRow(stringResource(R.string.visceral), "%d".format(metrics.visceralLevel))+                MetricRow(stringResource(R.string.body_age), "%d".format(metrics.bodyAge))+                MetricRow(stringResource(R.string.score), "%d".format(metrics.score))+                if (metrics.segmental != null) {+                    Spacer(Modifier.height(4.dp))+                    Text(stringResource(R.string.segmental), style = MaterialTheme.typography.labelMedium)+                    MetricRow(stringResource(R.string.seg_arms), "%.1f / %.1f kg fat".format(metrics.segmental.fatRh, metrics.segmental.fatLh))+                    MetricRow(stringResource(R.string.seg_legs), "%.1f / %.1f kg fat".format(metrics.segmental.fatRf, metrics.segmental.fatLf))+                    MetricRow(stringResource(R.string.seg_trunk), "%.1f kg fat".format(metrics.segmental.fatT))+                }+            } else {+                Text(stringResource(R.string.bmi_only), style = MaterialTheme.typography.bodySmall)+                Text(stringResource(R.string.bmi_hint), style = MaterialTheme.typography.bodySmall)+            }+        }+    }+}++@Composable+private fun MetricRow(label: String, value: String) {+    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+        Text(label, style = MaterialTheme.typography.bodyMedium)+        Text(value, style = MaterialTheme.typography.bodyMedium)+    }+}++@Composable+private fun BottleStatusCard(tempC: Int?, tds: Int?, batteryPct: Int?, charging: Boolean) {+    Card(modifier = Modifier.fillMaxWidth()) {+        Column(+            modifier = Modifier+                .fillMaxWidth()+                .padding(16.dp),+            verticalArrangement = Arrangement.spacedBy(6.dp)+        ) {+            Text(+                stringResource(R.string.bottle_status),+                style = MaterialTheme.typography.titleSmall+            )+            if (tempC != null) {+                Text(+                    stringResource(R.string.temperature_c, tempC),+                    style = MaterialTheme.typography.bodyMedium+                )+            }+            if (tds != null) {+                Text(+                    stringResource(R.string.purity_ppm, tds),+                    style = MaterialTheme.typography.bodyMedium+                )+            }+            if (batteryPct != null) {+                val label = if (charging) {+                    stringResource(R.string.battery_charging, batteryPct)+                } else {+                    stringResource(R.string.battery_pct, batteryPct)+                }+                Text(label, style = MaterialTheme.typography.bodyMedium)+            }         }     } }
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 f79f203a00..b1f6435b49 100644--- a/things/src/main/res/values/strings.xml+++ b/things/src/main/res/values/strings.xml@@ -18,4 +18,57 @@     <string name="ml"><xliff:g id="volume" example="450">%1$s</xliff:g> mL</string>     <!-- HydrationCard: daily goal beneath progress bar. %1$s = goal number e.g. 2000 -->     <string name="goal_ml">Goal <xliff:g id="goal" example="2000">%1$s</xliff:g> mL</string>+    <!-- Bottle status section header shown when connected and sensor values available -->+    <string name="bottle_status">Bottle status</string>+    <!-- Bottle status: water temperature. %1$d = degrees Celsius integer -->+    <string name="temperature_c"><xliff:g id="temp" example="22">%1$d</xliff:g>°C</string>+    <!-- Bottle status: water purity as TDS. %1$d = ppm integer -->+    <string name="purity_ppm"><xliff:g id="tds" example="85">%1$d</xliff:g> ppm</string>+    <!-- Bottle status: battery level. %1$d = percent 0-100 -->+    <string name="battery_pct"><xliff:g id="pct" example="75">%1$d</xliff:g>%%</string>+    <!-- Bottle status: battery level while charging. %1$d = percent 0-100 -->+    <string name="battery_charging"><xliff:g id="pct" example="75">%1$d</xliff:g>%% (charging)</string>++    <!-- Scale section -->+    <!-- Scale section title. Noun -->+    <string name="scale_title">Body Scale</string>+    <!-- Scale section subtitle. Explains offline BLE -->+    <string name="scale_subtitle">Renpho Elis 1 — offline BLE, no cloud</string>+    <!-- Scale profile header -->+    <string name="scale_profile">Profile</string>+    <!-- Sex options -->+    <string name="sex_male">Male</string>+    <string name="sex_female">Female</string>+    <!-- Profile fields -->+    <string name="age">Age</string>+    <string name="height_cm">Height (cm)</string>+    <string name="athlete">Athlete mode</string>+    <!-- Scale scan button -->+    <string name="scan_scale">Scan scale</string>+    <!-- Scale weight labels -->+    <string name="weight">Weight</string>+    <string name="weighing">Weighing…</string>+    <!-- Impedance label. %1$d = ohms -->+    <string name="impedance">Impedance %1$d Ω</string>+    <string name="no_impedance">No impedance — BMI only</string>+    <!-- Body composition -->+    <string name="body_composition">Body composition</string>+    <string name="bmi">BMI</string>+    <string name="body_fat">Body fat</string>+    <string name="fat_mass">Fat mass</string>+    <string name="lbm">Lean mass</string>+    <string name="water">Water</string>+    <string name="muscle">Muscle</string>+    <string name="bone">Bone</string>+    <string name="protein">Protein</string>+    <string name="bmr">BMR</string>+    <string name="visceral">Visceral fat</string>+    <string name="body_age">Body age</string>+    <string name="score">Score</string>+    <string name="segmental">Segmental (8-electrode)</string>+    <string name="seg_arms">Arms R/L</string>+    <string name="seg_legs">Legs R/L</string>+    <string name="seg_trunk">Trunk</string>+    <string name="bmi_only">BMI shown — step on bare feet for impedance</string>+    <string name="bmi_hint">Impedance measures body fat via foot electrodes</string> </resources>
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 76db366f4c..e8dcecfe33 100644--- a/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt+++ b/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt@@ -5,6 +5,10 @@ import androidx.compose.ui.tooling.preview.Preview import com.android.tools.screenshot.PreviewTest import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.things.platform.BleManager+import com.vayunmathur.things.platform.BodyComposition+import com.vayunmathur.things.platform.ScaleMeasurement+import com.vayunmathur.things.platform.ScaleProfile+import com.vayunmathur.things.platform.Sex  /** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */ private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"@@ -12,10 +16,6 @@ private const val PHONE = "spec:width=411dp,height=891dp,dpi=420" /**  * Store listing images for `:things`. See `common-conventions-preview-metadata`.  *- * [ThingsApp] was already fully stateless — plain values in, callbacks out — so this app- * needed no refactor at all, only these previews. That is the shape the other apps are- * being moved towards.- *  * Each preview needs @PreviewTest as well as @Preview: @Preview alone renders in Studio but  * is not collected as a screenshot test. Previews must also be class members, not top-level  * functions. Order comes from the function names (Preview1…, Preview2…).@@ -26,6 +26,10 @@ class MetadataPreviews {     @Preview(name = "1-connected", device = PHONE, showSystemUi = true)     @Composable     fun Preview1Connected() {+        val metrics = BodyComposition.calculate(+            ScaleProfile(sex = Sex.Male, age = 30, heightCm = 178.0, athlete = false),+            ScaleMeasurement(weightKg = 78.0, resistance50 = 520, resistance500 = 480)+        )         DynamicTheme(darkTheme = true) {             ThingsApp(                 totalMl = 1450,@@ -39,9 +43,31 @@ class MetadataPreviews {                 connectionState = "Connected",                 scanning = false,                 discoveredDevices = emptyList(),+                tempC = 22,+                tds = 85,+                batteryPct = 75,+                charging = false,                 onScanClick = {},                 onDeviceClick = {},                 onDisconnectClick = {},+                scaleWeight = 78.0,+                scaleRealtimeWeight = null,+                scaleR50 = 520,+                scaleConnectionState = "Scale: 78.0 kg",+                scaleScanning = false,+                scaleDevices = emptyList(),+                scaleMetrics = metrics,+                scaleSex = Sex.Male,+                scaleAge = "30",+                scaleHeight = "178",+                scaleAthlete = false,+                onScaleScanClick = {},+                onScaleDeviceClick = {},+                onScaleDisconnectClick = {},+                onScaleSexChange = {},+                onScaleAgeChange = {},+                onScaleHeightChange = {},+                onScaleAthleteChange = {},             )         }     }@@ -61,9 +87,31 @@ class MetadataPreviews {                     BleManager.BleDevice("HidrateSpark PRO", "C4:2F:90:1A:3B:7E"),                     BleManager.BleDevice("Smart Bottle 2", "D1:88:04:9C:22:10"),                 ),+                tempC = null,+                tds = null,+                batteryPct = null,+                charging = false,                 onScanClick = {},                 onDeviceClick = {},                 onDisconnectClick = {},+                scaleWeight = null,+                scaleRealtimeWeight = null,+                scaleR50 = null,+                scaleConnectionState = "Disconnected",+                scaleScanning = true,+                scaleDevices = emptyList(),+                scaleMetrics = null,+                scaleSex = Sex.Female,+                scaleAge = "28",+                scaleHeight = "165",+                scaleAthlete = false,+                onScaleScanClick = {},+                onScaleDeviceClick = {},+                onScaleDisconnectClick = {},+                onScaleSexChange = {},+                onScaleAgeChange = {},+                onScaleHeightChange = {},+                onScaleAthleteChange = {},             )         }     }