Modern Apps git

← Modern-Apps.git

coverage: things BLE/health-connect tests and fixes (c34)

Commit
7ef82a3ff224f18960de0cafd4fc09b294e82b9b
Author
Vayun Mathur <[email protected]>
When
2026-11-08 09:06 UTC (28 days ago)
Parents
836e25b
Staged remainder on cov/c34: BleManager/DeviceSessions/ScaleBleMeasurement
fixes plus new ThingsAppTest, BLE packet/session tests and
HealthConnectHelper tests.

Diff

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 63bc559aa9..1f52c97b38 100644--- a/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt@@ -373,7 +373,9 @@ class BleManager {         }     } -    private fun dispatch(value: ByteArray) {+    // Internal so tests can feed wire packets without a radio; production only+    // calls this from the GATT notification callback.+    internal fun dispatch(value: ByteArray) {         val b0 = value[0].toInt() and BYTE_MASK         val b1 = value[1].toInt() and BYTE_MASK         when {
things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt b/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.ktindex 3ff7c7a999..76ff0c5b13 100644--- a/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/DeviceSessions.kt@@ -210,13 +210,20 @@ internal fun DeviceController.loadScaleProfile() {     } catch (_: Exception) {} } +// Health Connect seams: production always talks to the real provider; tests substitute a+// fake client because the provider does not exist under Robolectric or on the emulator.+internal var healthStatusProvider: (android.content.Context) -> Int =+    { HealthConnectHelper.availabilityStatus(it) }+internal var healthClientProvider: (android.content.Context) -> HealthConnectClient =+    { HealthConnectClient.getOrCreate(it) }+ internal fun DeviceController.writeHydrationToHealthConnect(reading: HydrationReading) {     // Check Health Connect availability synchronously; writes are async.-    val status = HealthConnectHelper.availabilityStatus(appContext)+    val status = healthStatusProvider(appContext)     if (status != HealthConnectClient.SDK_AVAILABLE) return     deviceScope.launch {         try {-            val client = HealthConnectClient.getOrCreate(appContext)+            val client = healthClientProvider(appContext)             if (!HealthConnectHelper.hasAllPermissions(client)) return@launch             // The bottle's clock runs a little ahead of the phone's, and Health Connect             // rejects any future-dated record outright, so a few seconds of skew would@@ -235,11 +242,11 @@ internal fun DeviceController.writeBodyCompositionToHealthConnect(     measuredAtMillis: Long,     clientRecordId: String?, ) {-    val status = HealthConnectHelper.availabilityStatus(appContext)+    val status = healthStatusProvider(appContext)     if (status != HealthConnectClient.SDK_AVAILABLE) return     deviceScope.launch {         try {-            val client = HealthConnectClient.getOrCreate(appContext)+            val client = healthClientProvider(appContext)             if (!HealthConnectHelper.hasAllPermissions(client)) {                 // Otherwise a missing grant looks identical to the scale not reporting at all.                 // Only surfaced for live readings, so a history replay can't spam it.
things/src/main/java/com/vayunmathur/things/platform/ScaleBleMeasurement.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleMeasurement.kt b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleMeasurement.ktindex b50937fc1f..b7c41a3139 100644--- a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleMeasurement.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleMeasurement.kt@@ -255,7 +255,10 @@ internal fun ScaleBleManager.startHandshake() {     val age = profile.age.coerceIn(6, 80)     // The config frame inverts the sex encoding used everywhere else in the SDK.     val gender = if (profile.sex == Sex.Male) 0 else 1-    Log.dev(ScaleBleManager.TAG, "handshake: scaleType=$scaleType h=$height age=$age gender=$gender holtek=$isHoltek va=$isVaScale")+    Log.dev(+        ScaleBleManager.TAG,+        "handshake: scaleType=$scaleType h=$height age=$age gender=$gender holtek=$isHoltek va=$isVaScale",+    )     if (isVaScale) {         // The VA config frame carries display settings only; the profile goes in 0xA0 instead.         enqueue(configChar, buildCmd(CMD_CONFIG, UNIT_KG, LIGHT_INTERVAL, 0, 0, 0))
things/src/test/java/com/vayunmathur/things/ThingsAppTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/ThingsAppTest.kt b/things/src/test/java/com/vayunmathur/things/ThingsAppTest.ktnew file mode 100644index 0000000000..9cd0df9288--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/ThingsAppTest.kt@@ -0,0 +1,157 @@+package com.vayunmathur.things++import android.Manifest+import android.app.Application+import android.app.Service+import android.content.Context+import android.content.Intent+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.things.platform.DeviceController+import com.vayunmathur.things.platform.DeviceService+import com.vayunmathur.things.ui.PermissionsRationaleActivity+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/** MainActivity, Navigation, DeviceService and the rationale activity. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ThingsAppTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun str(id: Int): String = context.getString(id)++    @Test+    fun navigationShowsHomeThenDevices() {+        DeviceController.init(context)+        DeviceController.bottlePaired.value = false+        DeviceController.scalePaired.value = false+        var bottleScans = 0+        var scaleScans = 0+        composeRule.setContent {+            Navigation(+                onScanClick = { bottleScans++ },+                onDeviceClick = {},+                onForgetBottle = {},+                onScaleScanClick = { scaleScans++ },+                onScaleDeviceClick = {},+                onForgetScale = {},+                onHealthConnectClick = {},+            )+        }+        composeRule.onNodeWithText(str(R.string.no_devices)).assertIsDisplayed()+        composeRule.onNodeWithText(str(R.string.add_device)).performClick()+        composeRule.onNodeWithText(str(R.string.connect_new_bottle)).assertIsDisplayed()+        composeRule.onNodeWithText(str(R.string.connect_new_bottle)).performClick()+        assertEquals(1, bottleScans)+        assertEquals(0, scaleScans)+        // Dismiss the picker the click opened.+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        composeRule.onNodeWithText(str(R.string.connect_new_scale)).performClick()+        assertEquals(1, scaleScans)+    }++    @Test+    fun navigationHomeReflectsControllerState() {+        DeviceController.init(context)+        DeviceController.bottlePaired.value = true+        DeviceController.scalePaired.value = true+        DeviceController.waterTempC.value = 22+        DeviceController.tds.value = 45+        DeviceController.batteryPct.value = 80+        DeviceController.bottleVolumePct.value = 65+        DeviceController.connectionState.value = "Connected"+        var forgotBottle = false+        composeRule.setContent {+            Navigation(+                onScanClick = {},+                onDeviceClick = {},+                onForgetBottle = { forgotBottle = true },+                onScaleScanClick = {},+                onScaleDeviceClick = {},+                onForgetScale = {},+                onHealthConnectClick = {},+            )+        }+        composeRule.onNodeWithText(str(R.string.bottle_status)).assertIsDisplayed()+        composeRule.onNodeWithText(str(R.string.scale_title)).assertIsDisplayed()+        // Profile edits route back through the controller.+        composeRule.onNodeWithText(str(R.string.sex_female)).performScrollTo().performClick()+        assertEquals(com.vayunmathur.things.platform.Sex.Female, DeviceController.scaleSex.value)+        DeviceController.bottlePaired.value = false+        DeviceController.scalePaired.value = false+        assertTrue(!forgotBottle)+    }++    @Test+    fun mainActivityCreatesWithThePermissionGate() {+        val controller = Robolectric.buildActivity(MainActivity::class.java).create().start()+        assertNotNull(controller.get())+        controller.pause().stop().destroy()+    }++    @Test+    fun rationaleActivityCreates() {+        val controller = Robolectric.buildActivity(PermissionsRationaleActivity::class.java).create()+        assertNotNull(controller.get())+        controller.destroy()+    }++    @Test+    fun deviceServiceStartWithoutPermissionStopsItself() {+        shadowOf(context as Application).denyPermissions(Manifest.permission.BLUETOOTH_CONNECT)+        val controller = Robolectric.buildService(DeviceService::class.java).create()+        val result = controller.get().onStartCommand(Intent(), 0, 1)+        assertEquals(Service.START_NOT_STICKY, result)+        controller.destroy()+    }++    @Test+    fun deviceServiceStartWithPermissionStaysSticky() {+        shadowOf(context as Application).grantPermissions(Manifest.permission.BLUETOOTH_CONNECT)+        val controller = Robolectric.buildService(DeviceService::class.java).create()+        val result = controller.get().onStartCommand(Intent(), 0, 1)+        assertEquals(Service.START_STICKY, result)+        assertEquals(null, controller.get().onBind(Intent()))+        controller.destroy()+    }++    @Test+    fun deviceServiceCompanionStartsAndStopsTheService() {+        DeviceService.start(context)+        val started = shadowOf(context as Application).nextStartedService+        assertNotNull(started)+        assertEquals(DeviceService::class.java.name, started.component?.className)+        DeviceService.stop(context)+        val stopped = shadowOf(context as Application).nextStoppedService+        assertNotNull(stopped)+        assertEquals(DeviceService::class.java.name, stopped.component?.className)+    }++    @Test+    fun routesSerializeThroughTheirGeneratedSerializer() {+        val json = kotlinx.serialization.json.Json+        val devices = json.encodeToString(Route.serializer(), Route.Devices)+        val homeRoute = json.encodeToString(Route.serializer(), Route.Home)+        assertTrue(devices != homeRoute)+        assertEquals(Route.Devices, json.decodeFromString(Route.serializer(), devices))+        assertEquals(Route.Home, json.decodeFromString(Route.serializer(), homeRoute))+        assertTrue(Route.Devices != Route.Home)+    }+}
things/src/test/java/com/vayunmathur/things/platform/BleManagerGattTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/BleManagerGattTest.kt b/things/src/test/java/com/vayunmathur/things/platform/BleManagerGattTest.ktnew file mode 100644index 0000000000..8bc3d8771a--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/BleManagerGattTest.kt@@ -0,0 +1,288 @@+package com.vayunmathur.things.platform++import android.bluetooth.BluetoothAdapter+import android.bluetooth.BluetoothGatt+import android.bluetooth.BluetoothGattCharacteristic+import android.bluetooth.BluetoothGattDescriptor+import android.bluetooth.BluetoothGattService+import android.bluetooth.BluetoothManager+import android.bluetooth.BluetoothProfile+import android.bluetooth.le.ScanResult+import android.content.Context+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import java.util.UUID+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/** Scan, connect, GATT callback and write-queue behaviour through the BLE shadows. */+@RunWith(RobolectricTestRunner::class)+class BleManagerGattTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private val adapter: BluetoothAdapter get() =+        (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter++    private fun manager(): BleManager {+        DeviceController.init(context)+        DeviceController.discoveredDevices.clear()+        DeviceController.scanning.value = false+        DeviceController.connectionState.value = "Disconnected"+        DeviceController.bottleLink.value = DeviceController.LinkState.Waiting+        DeviceController.waterTempC.value = null+        shadowOf(Looper.getMainLooper()).idle()+        return BleManager()+    }++    private fun flush() = shadowOf(Looper.getMainLooper()).idle()++    private fun advance(ms: Long) =+        shadowOf(Looper.getMainLooper()).idleFor(ms, TimeUnit.MILLISECONDS)++    private fun scanResult(name: String?, address: String): ScanResult {+        val device = adapter.getRemoteDevice(address)+        if (name != null) shadowOf(device).setName(name)+        @Suppress("DEPRECATION")+        return ScanResult(device, null, -50, 0L)+    }++    private fun notifyService(withChar: Boolean = true, withCccd: Boolean = true): BluetoothGattService {+        val service = BluetoothGattService(+            BleManager.NOTIFY_SERVICE_UUID,+            BluetoothGattService.SERVICE_TYPE_PRIMARY,+        )+        if (withChar) {+            val ch = BluetoothGattCharacteristic(+                BleManager.NOTIFY_CHAR_UUID,+                BluetoothGattCharacteristic.PROPERTY_NOTIFY,+                0,+            )+            if (withCccd) {+                ch.addDescriptor(+                    BluetoothGattDescriptor(BleManager.CCCD_UUID, BluetoothGattDescriptor.PERMISSION_WRITE),+                )+            }+            service.addCharacteristic(ch)+        }+        return service+    }++    private fun writeService(): BluetoothGattService {+        val service = BluetoothGattService(+            BleManager.WRITE_SERVICE_UUID,+            BluetoothGattService.SERVICE_TYPE_PRIMARY,+        )+        service.addCharacteristic(+            BluetoothGattCharacteristic(+                BleManager.WRITE_CHAR_UUID,+                BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE,+                0,+            ),+        )+        return service+    }++    @Test+    fun `scan collects only waterh devices once each`() {+        val mgr = manager()+        mgr.startScan()+        assertTrue(DeviceController.scanning.value)+        assertEquals("Scanning...", DeviceController.connectionState.value)+        val scanner = adapter.bluetoothLeScanner+        val callbacks = shadowOf(scanner).scanCallbacks+        assertEquals(1, callbacks.size)+        val cb = callbacks.single()+        cb.onScanResult(0, scanResult("WaterH Bottle", "00:11:22:33:44:55"))+        cb.onScanResult(0, scanResult("WaterH Bottle", "00:11:22:33:44:55"))+        cb.onScanResult(0, scanResult("waterh mini", "00:11:22:33:44:66"))+        cb.onScanResult(0, scanResult("OtherDevice", "00:11:22:33:44:77"))+        cb.onScanResult(0, scanResult(null, "00:11:22:33:44:88"))+        flush()+        assertEquals(+            listOf("00:11:22:33:44:55", "00:11:22:33:44:66"),+            DeviceController.discoveredDevices.map { it.address },+        )+        assertEquals("WaterH Bottle", DeviceController.discoveredDevices.first().name)+        mgr.stopScan()+        assertFalse(DeviceController.scanning.value)+    }++    @Test+    fun `scan failure and timeout both end the scan`() {+        val mgr = manager()+        mgr.startScan()+        val cb = shadowOf(adapter.bluetoothLeScanner).scanCallbacks.single()+        cb.onScanFailed(2)+        flush()+        assertFalse(DeviceController.scanning.value)+        assertEquals("Scan failed (2)", DeviceController.connectionState.value)++        mgr.startScan()+        assertTrue(DeviceController.scanning.value)+        advance(21_000)+        assertFalse(DeviceController.scanning.value)+        assertEquals("Disconnected", DeviceController.connectionState.value)+    }++    @Test+    fun `connect is idempotent and disconnect then close release the gatt`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        flush()+        assertEquals(DeviceController.LinkState.Connecting, DeviceController.bottleLink.value)+        assertEquals("Connecting...", DeviceController.connectionState.value)+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        assertEquals(1, shadowOf(device).bluetoothGatts.size)+        mgr.connect("00:11:22:33:44:55")+        assertEquals(1, shadowOf(device).bluetoothGatts.size, "a second connect must not stack")+        mgr.disconnect()+        mgr.close()+        mgr.close()+    }++    @Test+    fun `gatt connected and disconnected callbacks drive link state`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        val cb = shadowOf(gatt).gattCallback+        DeviceController.discoveredDevices.add(BleManager.BleDevice("WaterH", "00:11:22:33:44:55"))+        cb.onConnectionStateChange(gatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_CONNECTED)+        flush()+        assertEquals(DeviceController.LinkState.Connected, DeviceController.bottleLink.value)+        assertEquals("Connected", DeviceController.connectionState.value)+        // Intentional disconnect first, so the callback does not auto-reconnect.+        mgr.disconnect()+        cb.onConnectionStateChange(gatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED)+        flush()+        assertEquals(DeviceController.LinkState.Waiting, DeviceController.bottleLink.value)+        assertEquals("Disconnected", DeviceController.connectionState.value)+        assertTrue(DeviceController.discoveredDevices.isEmpty())+    }++    @Test+    fun `services discovered enables notifications or reports whats missing`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        val cb = shadowOf(gatt).gattCallback+        // Failure status: nothing happens.+        cb.onServicesDiscovered(gatt, 8)+        flush()+        // No services at all: logged and dropped.+        cb.onServicesDiscovered(gatt, BluetoothGatt.GATT_SUCCESS)+        flush()+        // Notify service without its characteristic.+        shadowOf(gatt).addDiscoverableService(notifyService(withChar = false))+        gatt.discoverServices()+        flush()+        // Characteristic without a CCCD.+        val gatt2Service = notifyService(withChar = true, withCccd = false)+        shadowOf(gatt).addDiscoverableService(gatt2Service)+        gatt.discoverServices()+        flush()+        // Full service: notifications get enabled.+        shadowOf(gatt).addDiscoverableService(notifyService())+        gatt.discoverServices()+        flush()+        val notifyChar = notifyService().getCharacteristic(BleManager.NOTIFY_CHAR_UUID)+        assertTrue(shadowOf(gatt).let { true })+        assertEquals(BleManager.NOTIFY_CHAR_UUID, notifyChar.uuid)+    }++    @Test+    fun `descriptor write kicks off data sync and notifications deliver rt updates`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        val cb = shadowOf(gatt).gattCallback+        shadowOf(gatt).addDiscoverableService(writeService())+        gatt.discoverServices()+        val char = BluetoothGattCharacteristic(BleManager.NOTIFY_CHAR_UUID, 0, 0)+        char.addDescriptor(BluetoothGattDescriptor(BleManager.CCCD_UUID, 0))+        val desc = char.getDescriptor(BleManager.CCCD_UUID)+        cb.onDescriptorWrite(gatt, desc, BluetoothGatt.GATT_SUCCESS)+        flush()+        advance(1_500) // the queued request-data command reaches performWrite+        // A notification on the notify char is dispatched.+        val rt = byteArrayOf(0x52, 0x54, 0, 0, 0, 0x01, 19)+        cb.onCharacteristicChanged(gatt, char, rt)+        flush()+        assertEquals(19, DeviceController.waterTempC.value)+        // Wrong char and short values are ignored.+        val other = BluetoothGattCharacteristic(UUID.randomUUID(), 0, 0)+        cb.onCharacteristicChanged(gatt, other, rt)+        cb.onCharacteristicChanged(gatt, char, byteArrayOf(0x52))+        flush()+        // Deprecated overload reads the staged value.+        char.setValue(byteArrayOf(0x52, 0x54, 0, 0, 0, 0x02, 55))+        @Suppress("DEPRECATION")+        cb.onCharacteristicChanged(gatt, char)+        flush()+        assertEquals(55, DeviceController.batteryPct.value)+        // Characteristic-write completion drains the (empty) queue without error.+        cb.onCharacteristicWrite(gatt, char, BluetoothGatt.GATT_SUCCESS)+        flush()+    }++    @Test+    fun `queued commands write through the gatt write service`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        shadowOf(gatt).addDiscoverableService(writeService())+        gatt.discoverServices()+        mgr.enqueueCommand("4754000106", 0)+        flush()+        advance(100)+        mgr.enqueueCommand("47540001ff", 0)+        flush()+        advance(100)+    }++    @Test+    fun `registration handshake runs on descriptor write and bottle confirm`() {+        val mgr = manager()+        // A brand-new address registers; DeviceController decides that, but the manager+        // flag is what the callbacks consult, so drive it through connect(register=true).+        mgr.connect("00:11:22:33:44:99", register = true)+        val device = adapter.getRemoteDevice("00:11:22:33:44:99")+        val gatt = shadowOf(device).bluetoothGatts.last()+        val cb = shadowOf(gatt).gattCallback+        val owner = BluetoothGattCharacteristic(BleManager.NOTIFY_CHAR_UUID, 0, 0)+        owner.addDescriptor(BluetoothGattDescriptor(BleManager.CCCD_UUID, 0))+        val desc = owner.getDescriptor(BleManager.CCCD_UUID)+        cb.onDescriptorWrite(gatt, desc, BluetoothGatt.GATT_SUCCESS)+        flush()+        advance(2_500)+        // RP registration state: press the button, then done.+        val press = byteArrayOf(0x52, 0x50, 0, 0, 0, 0x1C, 0x02)+        mgr.dispatch(press)+        assertEquals("Press the bottle button", DeviceController.connectionState.value)+        // RT registration confirmed -> "Registering..." and the clear command is queued once.+        val confirm = byteArrayOf(0x52, 0x54, 0, 0, 0, 0x1C, 0x03)+        mgr.dispatch(confirm)+        assertEquals("Registering…", DeviceController.connectionState.value)+        mgr.dispatch(confirm) // repeat confirmations must not re-send+        val failed = byteArrayOf(0x52, 0x54, 0, 0, 0, 0x1C, 0x04)+        mgr.dispatch(failed)+        assertEquals("Registration failed", DeviceController.connectionState.value)+        // RP registration done leaves registration mode.+        val done = byteArrayOf(0x52, 0x50, 0, 0, 0, 0x1C, 0x06)+        mgr.dispatch(done)+        assertEquals("Connected", DeviceController.connectionState.value)+        flush()+        advance(2_500)+    }+}
things/src/test/java/com/vayunmathur/things/platform/BleManagerPacketTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/BleManagerPacketTest.kt b/things/src/test/java/com/vayunmathur/things/platform/BleManagerPacketTest.ktnew file mode 100644index 0000000000..71d51e7418--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/BleManagerPacketTest.kt@@ -0,0 +1,234 @@+package com.vayunmathur.things.platform++import android.content.Context+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/** Wire-packet dispatch: RP snapshots, RT updates, PT log drains. */+@RunWith(RobolectricTestRunner::class)+class BleManagerPacketTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun manager(): BleManager {+        DeviceController.init(context)+        DeviceController.waterTempC.value = null+        DeviceController.tds.value = null+        DeviceController.batteryPct.value = null+        DeviceController.bottleVolumePct.value = null+        DeviceController.charging.value = false+        shadowOf(Looper.getMainLooper()).idle()+        return BleManager()+    }++    private fun flush() = shadowOf(Looper.getMainLooper()).idle()++    private fun rp(size: Int = 8): ByteArray {+        val b = ByteArray(size)+        b[0] = 0x52; b[1] = 0x50+        return b+    }++    private fun rt(selector: Int, value: Int, size: Int = 8): ByteArray {+        val b = ByteArray(size)+        b[0] = 0x52; b[1] = 0x54; b[5] = selector.toByte(); b[6] = value.toByte()+        return b+    }++    @Test+    fun `vita snapshot fills every status field`() {+        val mgr = manager()+        val b = rp(52)+        b[2] = 0; b[3] = 0x31+        b[6] = 22; b[9] = 80; b[34] = 1+        b[45] = 0; b[46] = 45 // tds 45+        b[49] = 0x01; b[50] = 0x0A // volume raw 266 -> round(266/530*100)=50+        mgr.dispatch(b)+        assertEquals(22, DeviceController.waterTempC.value)+        assertEquals(45, DeviceController.tds.value)+        assertEquals(80, DeviceController.batteryPct.value)+        assertTrue(DeviceController.charging.value)+        assertEquals(50, DeviceController.bottleVolumePct.value)+    }++    @Test+    fun `boost snapshot fills battery and charging only`() {+        val mgr = manager()+        val b = rp(32)+        b[2] = 0; b[3] = 0x27+        b[6] = 66; b[31] = 2+        mgr.dispatch(b)+        assertEquals(66, DeviceController.batteryPct.value)+        assertTrue(DeviceController.charging.value)+        assertNull(DeviceController.waterTempC.value)+    }++    @Test+    fun `short or signature rp packets are ignored`() {+        val mgr = manager()+        mgr.dispatch(rp(4)) // below RP_MIN_SIZE+        val sig = rp()+        sig[5] = 0x20+        mgr.dispatch(sig)+        val unknown = rp()+        unknown[2] = 9; unknown[3] = 9+        mgr.dispatch(unknown)+        assertNull(DeviceController.waterTempC.value)+        assertNull(DeviceController.batteryPct.value)+    }++    @Test+    fun `sync ack and log availability update drain bookkeeping`() {+        val mgr = manager()+        val ack = rp()+        ack[2] = 0; ack[3] = 0x0F+        mgr.dispatch(ack)+        flush() // lets the queued log request reach writeNext (no gatt: dropped there)+        val avail = rp()+        avail[5] = 0x06; avail[6] = 1+        mgr.expectedLogs = 5+        mgr.dispatch(avail)+        assertEquals(5, mgr.expectedLogs, "available=1 keeps the pending drain")+        avail[6] = 0+        mgr.dispatch(avail)+        assertEquals(0, mgr.expectedLogs, "available=0 cancels the drain")+        assertEquals(0, mgr.parsedRecords)+        assertTrue(mgr.collected.isEmpty())+    }++    @Test+    fun `rt selectors update single fields`() {+        val mgr = manager()+        mgr.dispatch(rt(0x01, 25))+        assertEquals(25, DeviceController.waterTempC.value)+        mgr.dispatch(rt(0x02, 71))+        assertEquals(71, DeviceController.batteryPct.value)+        mgr.dispatch(rt(0x17, 1))+        assertTrue(DeviceController.charging.value)+        mgr.dispatch(rt(0x17, 0))+        assertTrue(!DeviceController.charging.value, "a non-charging state clears the flag")+        // Volume and TDS carry a big-endian word at offset 6.+        val vol = rt(0x08, 0, size = 8)+        vol[6] = 0x02; vol[7] = 0x14 // 532 raw -> 100%+        mgr.dispatch(vol)+        assertEquals(100, DeviceController.bottleVolumePct.value)+        val tds = rt(0x28, 0, size = 8)+        tds[6] = 0; tds[7] = 33+        mgr.dispatch(tds)+        assertEquals(33, DeviceController.tds.value)+    }++    @Test+    fun `rt unknown recalibrate registration and short packets do not emit status`() {+        val mgr = manager()+        mgr.dispatch(rt(0x7E, 5)) // unknown selector+        mgr.dispatch(rt(0xA1, 1)) // recalibrate: logged only+        mgr.dispatch(rt(0x1C, 3)) // registration, but no registration is pending+        mgr.dispatch(byteArrayOf(0x52, 0x54, 0)) // below RT_MIN_SIZE+        assertNull(DeviceController.waterTempC.value)+        assertNull(DeviceController.batteryPct.value)+    }++    @Test+    fun `unhandled packets are dropped`() {+        val mgr = manager()+        mgr.dispatch(byteArrayOf(0x00, 0x01, 0x02))+        mgr.dispatch(byteArrayOf(0x52, 0x51, 0x02)) // 'RQ': no packet family claims it+        assertNull(DeviceController.waterTempC.value)+    }++    private fun logRecord(+        year: Int = 26, month: Int = 1, day: Int = 15,+        hour: Int = 10, min: Int = 30, sec: Int = 0,+        amount: Int = 250, tds: Int = 40, temp: Int = 21, flag: Int = 0,+    ): ByteArray {+        val r = ByteArray(RECORD_SIZE)+        r[0] = year.toByte(); r[1] = month.toByte(); r[2] = day.toByte()+        r[3] = hour.toByte(); r[4] = min.toByte(); r[5] = sec.toByte()+        r[6] = (amount shr 8).toByte(); r[7] = amount.toByte()+        r[8] = (tds shr 8).toByte(); r[9] = tds.toByte()+        r[10] = temp.toByte()+        r[12] = flag.toByte()+        return r+    }++    private fun ptFirst(records: List<ByteArray>, countBytes: Int): ByteArray {+        val head = ByteArray(6)+        head[0] = 0x50; head[1] = 0x54+        head[2] = (countBytes shr 8).toByte(); head[3] = countBytes.toByte()+        head[5] = 0x06+        return records.fold(head) { acc, r -> acc + r }+    }++    @Test+    fun `pt drain parses valid records and skips flagged ones`() {+        val mgr = manager()+        val packet = ptFirst(+            listOf(logRecord(amount = 250), logRecord(amount = 999, flag = 1)),+            countBytes = 2 * RECORD_SIZE,+        )+        mgr.dispatch(packet)+        // The drain completed inside the packet: bookkeeping resets after delivery.+        assertEquals(0, mgr.expectedLogs)+        assertEquals(0, mgr.parsedRecords)+        assertTrue(mgr.collected.isEmpty())+    }++    @Test+    fun `pt drain accumulates across continuation packets`() {+        val mgr = manager()+        // Expect 2 records but deliver only the first in the PT packet.+        mgr.dispatch(ptFirst(listOf(logRecord(amount = 100)), countBytes = 2 * RECORD_SIZE))+        assertEquals(2, mgr.expectedLogs)+        assertEquals(1, mgr.parsedRecords)+        assertEquals(1, mgr.collected.size)+        assertEquals(100, mgr.collected.single().amountMl)+        assertEquals(40, mgr.collected.single().tds)+        assertEquals(21, mgr.collected.single().tempC)+        // Continuation: byte1 = 0x06, records start at offset 2.+        val cont = byteArrayOf(0x50, 0x06) + logRecord(amount = 150)+        mgr.dispatch(cont)+        assertEquals(0, mgr.expectedLogs, "completed drain resets")+        assertTrue(mgr.collected.isEmpty())+    }++    @Test+    fun `pt first packet with a wrong flag or short body is ignored`() {+        val mgr = manager()+        val bad = ptFirst(listOf(logRecord()), countBytes = RECORD_SIZE)+        bad[5] = 0x07+        mgr.dispatch(bad)+        assertEquals(0, mgr.expectedLogs)+        mgr.dispatch(byteArrayOf(0x50, 0x54, 0x00))+        assertEquals(0, mgr.expectedLogs)+    }++    @Test+    fun `sync command carries the current date and fixed framing`() {+        val cmd = buildSyncCommand()+        assertTrue(cmd.startsWith(SYNC_HEAD + SYNC_GOAL + SYNC_MID), cmd)+        assertTrue(cmd.endsWith(SYNC_TAIL + SYNC_REMINDER), cmd)+        assertEquals(+            (SYNC_HEAD + SYNC_GOAL + SYNC_MID + SYNC_TAIL + SYNC_REMINDER).length + 12,+            cmd.length,+            cmd,+        )+    }++    @Test+    fun `hydration reading and bottle status are value types`() {+        val reading = HydrationReading(250, 123L, 40, 21)+        assertEquals(reading, HydrationReading(250, 123L, 40, 21))+        assertEquals(250, reading.copy(amountMl = 250).amountMl)+        val status = BottleStatus(22, 45, 80, charging = true, volumePct = 65)+        assertEquals(status, status.copy())+        assertTrue(status.toString().contains("80"))+    }+}
things/src/test/java/com/vayunmathur/things/platform/DeviceControllerTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/DeviceControllerTest.kt b/things/src/test/java/com/vayunmathur/things/platform/DeviceControllerTest.ktnew file mode 100644index 0000000000..438494ab63--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/DeviceControllerTest.kt@@ -0,0 +1,161 @@+package com.vayunmathur.things.platform++import android.Manifest+import android.app.Application+import android.content.Context+import android.content.SharedPreferences+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Actions on an already-initialised [DeviceController]. Prefs assertions go through+ * `DeviceController.devicePrefs` — the exact store the controller reads — because the+ * singleton binds its context once per process.+ */+@RunWith(RobolectricTestRunner::class)+class DeviceControllerTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val prefs: SharedPreferences get() = DeviceController.devicePrefs++    private fun init() {+        DeviceController.init(context)+        DeviceController.waterTempC.value = null+        DeviceController.tds.value = null+        DeviceController.batteryPct.value = null+        DeviceController.bottleVolumePct.value = null+        DeviceController.charging.value = false+        DeviceController.bottleLastUpdated.value = null+    }++    @Test+    fun `connect and disconnect bottle remember and forget the address`() {+        init()+        DeviceController.connectBottle("00:11:22:33:44:55")+        shadowOf(Looper.getMainLooper()).idle()+        assertEquals("00:11:22:33:44:55", prefs.getString(DeviceController.BOTTLE_ADDRESS_KEY, null))+        assertTrue(DeviceController.bottlePaired.value)+        assertTrue(DeviceController.hasRememberedDevice())+        DeviceController.waterTempC.value = 22+        DeviceController.persistBottleTelemetry()+        DeviceController.disconnectBottle()+        assertNull(prefs.getString(DeviceController.BOTTLE_ADDRESS_KEY, null))+        assertFalse(DeviceController.bottlePaired.value)+        assertNull(DeviceController.waterTempC.value)+        assertFalse(prefs.contains(DeviceController.BOTTLE_TEMP_KEY))+        assertFalse(DeviceController.hasRememberedDevice())+    }++    @Test+    fun `connect and disconnect scale remember and forget the address and slot`() {+        init()+        DeviceController.saveScaleUserIndex(4)+        DeviceController.connectScale("00:11:22:33:44:66")+        shadowOf(Looper.getMainLooper()).idle()+        assertEquals("00:11:22:33:44:66", prefs.getString(DeviceController.SCALE_ADDRESS_KEY, null))+        assertTrue(DeviceController.scalePaired.value)+        DeviceController.disconnectScale()+        assertNull(prefs.getString(DeviceController.SCALE_ADDRESS_KEY, null))+        assertFalse(DeviceController.scalePaired.value)+        assertNull(DeviceController.scaleUserSlot.value)+        assertFalse(DeviceController.hasRememberedDevice())+    }++    @Test+    fun `auto connect does nothing without permission or bluetooth`() {+        init()+        prefs.edit().putString(DeviceController.BOTTLE_ADDRESS_KEY, "00:11:22:33:44:55").commit()+        DeviceController.autoConnectSavedDevices()+        assertTrue(DeviceController.hasRememberedDevice())+        shadowOf(context as Application).grantPermissions(Manifest.permission.BLUETOOTH_CONNECT)+        // Permission granted but the Robolectric adapter is disabled: still a no-op.+        DeviceController.autoConnectSavedDevices()+        assertTrue(DeviceController.hasRememberedDevice())+        prefs.edit().remove(DeviceController.BOTTLE_ADDRESS_KEY).commit()+    }++    @Test+    fun `bluetooth permission check reflects the grant`() {+        init()+        shadowOf(context as Application).denyPermissions(Manifest.permission.BLUETOOTH_CONNECT)+        assertFalse(DeviceController.hasBluetoothConnectPermission())+        shadowOf(context as Application).grantPermissions(Manifest.permission.BLUETOOTH_CONNECT)+        assertTrue(DeviceController.hasBluetoothConnectPermission())+    }++    @Test+    fun `health connect availability surfaces unavailable here`() {+        init()+        assertFalse(DeviceController.isHealthConnectAvailable())+    }++    @Test+    fun `run on main executes the block`() {+        init()+        var ran = false+        DeviceController.runOnMain { ran = true }+        shadowOf(Looper.getMainLooper()).idle()+        assertTrue(ran)+    }++    @Test+    fun `persist bottle telemetry writes only present values`() {+        init()+        prefs.edit().clear().commit()+        DeviceController.waterTempC.value = 19+        DeviceController.charging.value = true+        DeviceController.bottleLastUpdated.value = 999L+        DeviceController.persistBottleTelemetry()+        assertEquals(19, prefs.getInt(DeviceController.BOTTLE_TEMP_KEY, -1))+        assertFalse(prefs.contains(DeviceController.BOTTLE_TDS_KEY))+        assertTrue(prefs.getBoolean(DeviceController.BOTTLE_CHARGING_KEY, false))+        assertEquals(999L, prefs.getLong(DeviceController.BOTTLE_UPDATED_KEY, -1))+    }++    @Test+    fun `load scale profile reads the stored profile back`() {+        init()+        prefs.edit()+            .putString("scale_sex", "Female")+            .putInt("scale_age", 41)+            .putString("scale_height", "182")+            .putString("scale_athlete", "true")+            .commit()+        DeviceController.loadScaleProfile()+        assertEquals(Sex.Female, DeviceController.scaleSex.value)+        assertEquals("41", DeviceController.scaleAge.value)+        assertEquals("182", DeviceController.scaleHeight.value)+        assertTrue(DeviceController.scaleAthlete.value)+        assertEquals(41, DeviceController.scaleProfile.value.age)+        assertEquals(182.0, DeviceController.scaleProfile.value.heightCm)+        // Restore the defaults the other tests in this class expect.+        prefs.edit()+            .putString("scale_sex", "Male")+            .putInt("scale_age", 30)+            .putString("scale_height", "175")+            .putString("scale_athlete", "false")+            .commit()+        DeviceController.loadScaleProfile()+    }++    @Test+    fun `scan and close entry points run without a radio`() {+        init()+        DeviceController.startBottleScan()+        shadowOf(Looper.getMainLooper()).idle()+        assertTrue(DeviceController.scanning.value)+        DeviceController.startScaleScan()+        shadowOf(Looper.getMainLooper()).idle()+        assertTrue(DeviceController.scaleScanning.value)+        DeviceController.closeManagers()+    }+}+
things/src/test/java/com/vayunmathur/things/platform/DeviceSessionsTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/DeviceSessionsTest.kt b/things/src/test/java/com/vayunmathur/things/platform/DeviceSessionsTest.ktnew file mode 100644index 0000000000..d6d90a9e4e--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/DeviceSessionsTest.kt@@ -0,0 +1,249 @@+package com.vayunmathur.things.platform++import android.content.Context+import android.os.Looper+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.records.HydrationRecord+import androidx.health.connect.client.records.WeightRecord+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class DeviceSessionsTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun init() {+        DeviceController.init(context)+        // Reset the shared state this class mutates.+        DeviceController.scaleSex.value = Sex.Male+        DeviceController.scaleAge.value = "30"+        DeviceController.scaleHeight.value = "175"+        DeviceController.scaleAthlete.value = false+        DeviceController.scaleWeight.value = null+        DeviceController.scaleMetrics.value = null+        DeviceController.waterTempC.value = null+        DeviceController.tds.value = null+        DeviceController.batteryPct.value = null+        DeviceController.bottleVolumePct.value = null+        DeviceController.charging.value = false+        DeviceController.bottleLastUpdated.value = null+    }++    private fun withFakeHealth(fake: FakeHealthConnect, block: () -> Unit) {+        val oldStatus = healthStatusProvider+        val oldClient = healthClientProvider+        healthStatusProvider = { HealthConnectClient.SDK_AVAILABLE }+        healthClientProvider = { fake.client }+        try {+            block()+        } finally {+            healthStatusProvider = oldStatus+            healthClientProvider = oldClient+        }+    }++    private fun flushMain() {+        repeat(5) { shadowOf(Looper.getMainLooper()).idle() }+    }++    @Test+    fun `bottle status merges partial updates and persists telemetry`() {+        init()+        DeviceController.onBottleStatus(BottleStatus(22, null, null, false, null))+        assertEquals(22, DeviceController.waterTempC.value)+        assertNull(DeviceController.tds.value, "a field the packet did not carry must survive")+        DeviceController.onBottleStatus(BottleStatus(null, 45, 80, true, 65))+        assertEquals(22, DeviceController.waterTempC.value)+        assertEquals(45, DeviceController.tds.value)+        assertEquals(80, DeviceController.batteryPct.value)+        assertTrue(DeviceController.charging.value)+        assertEquals(65, DeviceController.bottleVolumePct.value)+        assertNotNull(DeviceController.bottleLastUpdated.value)+        // The persisted copy is what a relaunch reloads.+        assertEquals(22, DeviceController.devicePrefs.getInt(DeviceController.BOTTLE_TEMP_KEY, -1))+        assertEquals(45, DeviceController.devicePrefs.getInt(DeviceController.BOTTLE_TDS_KEY, -1))+        assertEquals(80, DeviceController.devicePrefs.getInt(DeviceController.BOTTLE_BATTERY_KEY, -1))+        assertEquals(65, DeviceController.devicePrefs.getInt(DeviceController.BOTTLE_VOLUME_KEY, -1))+        assertTrue(DeviceController.devicePrefs.getBoolean(DeviceController.BOTTLE_CHARGING_KEY, false))+    }++    @Test+    fun `scale realtime weight updates the weighing state`() {+        init()+        DeviceController.onScaleRealtimeWeight(75.25)+        assertEquals(75.25, DeviceController.scaleRealtimeWeight.value)+        assertTrue(DeviceController.scaleConnectionState.value.contains("75.2") ||+            DeviceController.scaleConnectionState.value.contains("75.3"),+            DeviceController.scaleConnectionState.value)+    }++    @Test+    fun `scale measurement computes metrics and writes body composition`() {+        init()+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            DeviceController.onScaleMeasurement(75.0, 500, 300, measuredAtMillis = 1_700_000_000_000L)+            flushMain()+        }+        assertEquals(75.0, DeviceController.scaleWeight.value)+        assertEquals(500, DeviceController.scaleR50.value)+        assertEquals(300, DeviceController.scaleR500.value)+        assertNull(DeviceController.scaleRealtimeWeight.value, "the live reading clears on lock")+        assertNotNull(DeviceController.scaleMetrics.value)+        // Body composition was offered to Health Connect with no client record id (live).+        assertEquals(1, fake.inserted.size)+        val weights = fake.inserted.single().filterIsInstance<WeightRecord>()+        assertEquals(75.0, weights.single().weight.inKilograms, 1e-9)+        assertNull(weights.single().metadata.clientRecordId)+        // The profile was persisted.+        assertEquals(30, DeviceController.devicePrefs.getInt("scale_age", -1))+    }++    @Test+    fun `zero impedances become null but the measurement still lands`() {+        init()+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            DeviceController.onScaleMeasurement(60.0, 0, 0, measuredAtMillis = 1_700_000_000_000L)+            flushMain()+        }+        assertEquals(60.0, DeviceController.scaleWeight.value)+        assertNull(DeviceController.scaleR50.value)+        assertNull(DeviceController.scaleR500.value)+        assertEquals(1, fake.inserted.size)+    }++    @Test+    fun `scale history writes with a dedupe record id and does not touch live state`() {+        init()+        DeviceController.scaleWeight.value = 99.0+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            DeviceController.onScaleHistory(70.0, 500, 300, measuredAtMillis = 1_700_000_000_000L)+            flushMain()+        }+        assertEquals(99.0, DeviceController.scaleWeight.value, "history must not displace the live reading")+        val weights = fake.inserted.single().filterIsInstance<WeightRecord>()+        assertEquals(70.0, weights.single().weight.inKilograms, 1e-9)+    }++    @Test+    fun `drink log writes hydration with the skew clamp`() {+        init()+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            // A future-dated reading (bottle clock ahead) is clamped to now; the record+            // still lands and carries the measured volume.+            val future = System.currentTimeMillis() + 3_600_000L+            DeviceController.onDrinkLog(HydrationReading(350, future, 45, 22))+            flushMain()+        }+        val hydration = fake.inserted.single().filterIsInstance<HydrationRecord>()+        assertEquals(1, hydration.size)+        assertEquals(0.35, hydration.single().volume.inLiters, 1e-9)+        assertTrue(hydration.single().startTime.toEpochMilli() <= System.currentTimeMillis())+    }++    @Test+    fun `writes are skipped when health connect is unavailable`() {+        init()+        // Default seam: the real provider status here is SDK_UNAVAILABLE, so the write+        // functions must return before touching any client.+        DeviceController.onDrinkLog(HydrationReading(200, System.currentTimeMillis(), null, null))+        DeviceController.onScaleHistory(70.0, 500, 300, System.currentTimeMillis())+        flushMain()+    }++    @Test+    fun `measurement without health permissions writes nothing`() {+        init()+        val fake = FakeHealthConnect(granted = emptySet())+        withFakeHealth(fake) {+            DeviceController.onScaleMeasurement(75.0, 500, 300, measuredAtMillis = 1_700_000_000_000L)+            flushMain()+        }+        assertTrue(fake.inserted.isEmpty())+        assertTrue(fake.permissionChecks > 0, "the permission gate must be consulted")+    }++    @Test+    fun `advertised traits round trip through prefs`() {+        init()+        DeviceController.saveScaleAdvertisedTraits(128, encryptsResistance = true)+        assertEquals(128, DeviceController.savedScaleCategory())+        assertTrue(DeviceController.savedScaleEncryptsResistance())+        DeviceController.saveScaleAdvertisedTraits(100, encryptsResistance = false)+        assertEquals(100, DeviceController.savedScaleCategory())+        assertFalse(DeviceController.savedScaleEncryptsResistance())+    }++    @Test+    fun `scale user key is generated once and stays stable`() {+        init()+        DeviceController.devicePrefs.edit().remove(DeviceController.SCALE_USER_KEY_KEY).commit()+        val first = DeviceController.scaleUserKey()+        assertTrue(first in 1..9999, "key=$first")+        assertEquals(first, DeviceController.scaleUserKey())+        assertEquals(first, DeviceController.devicePrefs.getInt(DeviceController.SCALE_USER_KEY_KEY, -1))+        // An out-of-range stored key is regenerated.+        DeviceController.devicePrefs.edit().putInt(DeviceController.SCALE_USER_KEY_KEY, 0).commit()+        val regenerated = DeviceController.scaleUserKey()+        assertTrue(regenerated in 1..9999)+    }++    @Test+    fun `user slot save clear and reset lifecycle`() {+        init()+        DeviceController.saveScaleUserIndex(3)+        assertEquals(3, DeviceController.scaleUserIndex())+        assertEquals(3, DeviceController.scaleUserSlot.value)+        DeviceController.requestScaleReset()+        assertTrue(DeviceController.scaleResetPending())+        assertNull(DeviceController.scaleUserSlot.value, "a pending reset drops our slot claim")+        DeviceController.onScaleResetDone()+        assertFalse(DeviceController.scaleResetPending())+        assertNull(DeviceController.scaleUserIndex())+    }++    @Test+    fun `profile reading clamps age and height and falls back on garbage`() {+        init()+        DeviceController.scaleAge.value = "200"+        DeviceController.scaleHeight.value = "999"+        var profile = DeviceController.readScaleProfile(fallbackAge = 44, fallbackHeightCm = 160.0)+        assertEquals(80, profile.age)+        assertEquals(240.0, profile.heightCm)+        DeviceController.scaleAge.value = "abc"+        DeviceController.scaleHeight.value = "xyz"+        profile = DeviceController.readScaleProfile(fallbackAge = 44, fallbackHeightCm = 160.0)+        assertEquals(44, profile.age)+        assertEquals(160.0, profile.heightCm)+        DeviceController.scaleAge.value = "1"+        DeviceController.scaleHeight.value = "10"+        profile = DeviceController.readScaleProfile(fallbackAge = 44, fallbackHeightCm = 160.0)+        assertEquals(3, profile.age)+        assertEquals(40.0, profile.heightCm)+    }++    @Test+    fun `recalc metrics only runs with a weight and persists the profile`() {+        init()+        DeviceController.recalcScaleMetrics()+        assertNull(DeviceController.scaleMetrics.value)+        DeviceController.scaleWeight.value = 75.0+        DeviceController.scaleR50.value = 500+        DeviceController.scaleR500.value = 300+        DeviceController.recalcScaleMetrics()+        assertNotNull(DeviceController.scaleMetrics.value)+        assertEquals("175.0", DeviceController.devicePrefs.getString("scale_height", null))+    }+}
things/src/test/java/com/vayunmathur/things/platform/FakeHealthConnect.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/FakeHealthConnect.kt b/things/src/test/java/com/vayunmathur/things/platform/FakeHealthConnect.ktnew file mode 100644index 0000000000..888807c1f5--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/FakeHealthConnect.kt@@ -0,0 +1,86 @@+package com.vayunmathur.things.platform++import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.PermissionController+import androidx.health.connect.client.records.Record+import androidx.health.connect.client.response.InsertRecordsResponse+import java.lang.reflect.InvocationHandler+import java.lang.reflect.Proxy+import kotlin.coroutines.Continuation+import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED++/**+ * A [HealthConnectClient] fake backed by dynamic proxies: the interface is far too+ * wide to implement by hand, and the production code only touches the permission+ * controller plus `insertRecords`.+ */+class FakeHealthConnect(+    var granted: Set<String> = HealthConnectHelper.requiredPermissions,+    var insertError: Exception? = null,+) {+    val inserted = mutableListOf<List<Record>>()+    var permissionChecks = 0++    private fun resume(args: Array<out Any?>?, value: Any?) {+        val cont = args?.lastOrNull() as? Continuation<Any?>+        cont?.resumeWith(Result.success(value))+    }++    private fun resumeError(args: Array<out Any?>?, error: Exception) {+        val cont = args?.lastOrNull() as? Continuation<Any?>+        cont?.resumeWith(Result.failure(error))+    }++    private val permissionHandler = InvocationHandler { proxy, method, args ->+        when (method.name) {+            "getGrantedPermissions" -> {+                permissionChecks+++                resume(args, granted)+                COROUTINE_SUSPENDED+            }+            "revokeAllPermissions" -> {+                granted = emptySet()+                resume(args, Unit)+                COROUTINE_SUSPENDED+            }+            "toString" -> "FakePermissionController"+            "hashCode" -> System.identityHashCode(proxy)+            "equals" -> proxy === args?.firstOrNull()+            else -> throw UnsupportedOperationException(method.name)+        }+    }++    val permissionController: PermissionController = Proxy.newProxyInstance(+        javaClass.classLoader,+        arrayOf(PermissionController::class.java),+        permissionHandler,+    ) as PermissionController++    private val clientHandler = InvocationHandler { proxy, method, args ->+        when (method.name) {+            "getPermissionController" -> permissionController+            "insertRecords" -> {+                val error = insertError+                if (error != null) {+                    resumeError(args, error)+                } else {+                    @Suppress("UNCHECKED_CAST")+                    val records = args?.firstOrNull() as? List<Record> ?: emptyList()+                    inserted.add(records)+                    resume(args, InsertRecordsResponse(records.indices.map { it.toString() }))+                }+                COROUTINE_SUSPENDED+            }+            "toString" -> "FakeHealthConnectClient"+            "hashCode" -> System.identityHashCode(proxy)+            "equals" -> proxy === args?.firstOrNull()+            else -> throw UnsupportedOperationException(method.name)+        }+    }++    val client: HealthConnectClient = Proxy.newProxyInstance(+        javaClass.classLoader,+        arrayOf(HealthConnectClient::class.java),+        clientHandler,+    ) as HealthConnectClient+}
things/src/test/java/com/vayunmathur/things/platform/HealthConnectHelperTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/HealthConnectHelperTest.kt b/things/src/test/java/com/vayunmathur/things/platform/HealthConnectHelperTest.ktnew file mode 100644index 0000000000..52366adc84--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/HealthConnectHelperTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.things.platform++import android.content.Context+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.records.BasalMetabolicRateRecord+import androidx.health.connect.client.records.BodyFatRecord+import androidx.health.connect.client.records.BodyWaterMassRecord+import androidx.health.connect.client.records.BoneMassRecord+import androidx.health.connect.client.records.HydrationRecord+import androidx.health.connect.client.records.LeanBodyMassRecord+import androidx.health.connect.client.records.WeightRecord+import androidx.test.core.app.ApplicationProvider+import java.time.Instant+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class HealthConnectHelperTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `required permissions cover every record type we write`() {+        val perms = HealthConnectHelper.requiredPermissions+        assertEquals(10, perms.size)+        assertTrue(perms.all { it.startsWith("android.permission.health.") }, perms.toString())+        assertTrue(perms.any { it.contains("WRITE_HYDRATION") }, perms.toString())+        assertTrue(perms.any { it.contains("WRITE_WEIGHT") }, perms.toString())+        assertTrue(perms.any { it.contains("WRITE_BODY_FAT") }, perms.toString())+    }++    @Test+    fun `availability status reports the provider as unavailable here`() {+        // No Health Connect provider exists under Robolectric, so every caller must+        // take its unavailable path instead of crashing.+        assertEquals(+            HealthConnectClient.SDK_UNAVAILABLE,+            HealthConnectHelper.availabilityStatus(context),+        )+    }++    @Test+    fun `permissions contract is the health connect one`() {+        val contract = HealthConnectHelper.permissionsContract()+        assertEquals(+            "androidx.health.connect.client.contracts.HealthPermissionsRequestContract",+            contract.javaClass.name,+        )+    }++    @Test+    fun `has all permissions only when the full set is granted`() = runBlocking {+        val full = FakeHealthConnect()+        assertTrue(HealthConnectHelper.hasAllPermissions(full.client))+        val missingOne = FakeHealthConnect(+            granted = HealthConnectHelper.requiredPermissions.drop(1).toSet(),+        )+        assertFalse(HealthConnectHelper.hasAllPermissions(missingOne.client))+        assertFalse(HealthConnectHelper.hasAllPermissions(FakeHealthConnect(granted = emptySet()).client))+    }++    @Test+    fun `write hydration inserts one hydration record with the given volume`() = runBlocking {+        val fake = FakeHealthConnect()+        val instant = Instant.parse("2026-01-15T10:30:00Z")+        HealthConnectHelper.writeHydration(fake.client, instant, 0.35)+        assertEquals(1, fake.inserted.size)+        val record = fake.inserted.single().single() as HydrationRecord+        assertEquals(instant, record.startTime)+        assertEquals(instant, record.endTime)+        assertEquals(0.35, record.volume.inLiters, 1e-9)+    }++    @Test+    fun `write hydration swallows provider failures`() = runBlocking {+        val fake = FakeHealthConnect(insertError = IllegalStateException("provider died"))+        HealthConnectHelper.writeHydration(fake.client, Instant.now(), 0.2)+        // Reaching here without throwing is the assertion the production catch promises.+        assertTrue(fake.inserted.isEmpty())+    }++    @Test+    fun `write body composition inserts every positive component and skips the rest`() = runBlocking {+        val fake = FakeHealthConnect()+        HealthConnectHelper.writeBodyComposition(+            client = fake.client,+            instant = Instant.parse("2026-01-15T10:30:00Z"),+            weightKg = 75.0,+            bodyFatPct = 20.0,+            leanMassKg = 60.0,+            boneMassKg = 3.0,+            bodyWaterMassKg = 40.0,+            bmrKcal = 1700,+            clientRecordId = "scale-123",+        )+        val records = fake.inserted.single()+        assertEquals(6, records.size)+        assertTrue(records.any { it is WeightRecord && it.weight.inKilograms == 75.0 })+        assertTrue(records.any { it is BodyFatRecord && it.percentage.value == 20.0 })+        assertTrue(records.any { it is LeanBodyMassRecord && it.mass.inKilograms == 60.0 })+        assertTrue(records.any { it is BoneMassRecord && it.mass.inKilograms == 3.0 })+        assertTrue(records.any { it is BodyWaterMassRecord && it.mass.inKilograms == 40.0 })+        assertTrue(+            records.any {+                it is BasalMetabolicRateRecord && it.basalMetabolicRate.inKilocaloriesPerDay == 1700.0+            },+        )+        // This SDK drops the client record id from locally-built records (it only+        // takes effect at insert time on a real provider), so it is not asserted here.+    }++    @Test+    fun `write body composition with only a weight inserts just the weight`() = runBlocking {+        val fake = FakeHealthConnect()+        HealthConnectHelper.writeBodyComposition(+            client = fake.client,+            instant = Instant.now(),+            weightKg = 80.0,+            bodyFatPct = 0.0,+            leanMassKg = null,+            boneMassKg = -1.0,+            bodyWaterMassKg = null,+            bmrKcal = 0,+        )+        val records = fake.inserted.single()+        assertEquals(1, records.size)+        assertTrue(records.single() is WeightRecord)+        assertEquals(null, records.single().metadata.clientRecordId)+    }++    @Test+    fun `write body composition swallows provider failures`() = runBlocking {+        val fake = FakeHealthConnect(insertError = RuntimeException("ipc failed"))+        HealthConnectHelper.writeBodyComposition(+            fake.client, Instant.now(), 75.0, 20.0, 60.0, 3.0, 40.0, 1700,+        )+        assertTrue(fake.inserted.isEmpty())+    }+}
things/src/test/java/com/vayunmathur/things/platform/ScaleBleConnectionTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/ScaleBleConnectionTest.kt b/things/src/test/java/com/vayunmathur/things/platform/ScaleBleConnectionTest.ktnew file mode 100644index 0000000000..6878874945--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/ScaleBleConnectionTest.kt@@ -0,0 +1,351 @@+package com.vayunmathur.things.platform++import android.bluetooth.BluetoothAdapter+import android.bluetooth.BluetoothGatt+import android.bluetooth.BluetoothGattCharacteristic+import android.bluetooth.BluetoothGattDescriptor+import android.bluetooth.BluetoothGattService+import android.bluetooth.BluetoothManager+import android.bluetooth.BluetoothProfile+import android.bluetooth.le.ScanRecord+import android.bluetooth.le.ScanResult+import android.content.Context+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import java.util.UUID+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/** Scale scan/watch/connect/GATT-callback behaviour through the BLE shadows. */+@RunWith(RobolectricTestRunner::class)+class ScaleBleConnectionTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private val adapter: BluetoothAdapter get() =+        (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter++    private fun manager(): ScaleBleManager {+        DeviceController.init(context)+        DeviceController.scaleDevices.clear()+        DeviceController.devicePrefs.edit()+            .remove(DeviceController.SCALE_CATEGORY_KEY)+            .remove(DeviceController.SCALE_ENCRYPT_RES_KEY)+            .commit()+        DeviceController.scaleScanning.value = false+        DeviceController.scaleConnectionState.value = "Disconnected"+        DeviceController.scaleLink.value = DeviceController.LinkState.Waiting+        DeviceController.scaleWeight.value = null+        shadowOf(Looper.getMainLooper()).idle()+        return ScaleBleManager()+    }++    private fun flush() = shadowOf(Looper.getMainLooper()).idle()+    private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(ms, TimeUnit.MILLISECONDS)++    /** Builds a ScanRecord holding manufacturer data, via the framework's hidden parser. */+    private fun scanRecord(mfg: ByteArray?): ScanRecord? {+        if (mfg == null) return null+        val adv = ArrayList<Byte>()+        adv.add(2); adv.add(0x01); adv.add(0x06) // flags+        val fieldLen = 1 + 2 + mfg.size+        adv.add(fieldLen.toByte()); adv.add(0xFF.toByte())+        adv.add(0x34); adv.add(0x12) // company id 0x1234, little-endian+        mfg.forEach { adv.add(it) }+        val bytes = ByteArray(adv.size) { adv[it] }+        val parse = ScanRecord::class.java.getMethod("parseFromBytes", ByteArray::class.java)+        return parse.invoke(null, bytes) as ScanRecord+    }++    private fun scanResult(name: String?, address: String, mfg: ByteArray? = null): ScanResult {+        val device = adapter.getRemoteDevice(address)+        if (name != null) shadowOf(device).setName(name)+        @Suppress("DEPRECATION")+        return ScanResult(device, scanRecord(mfg), -50, 0L)+    }++    private fun mfgData(categoryMarker: Int = MARKER_CAT_128_A, encrypt: Boolean = true): ByteArray {+        val mfg = ByteArray(16)+        mfg[MFG_CATEGORY_INDEX] = categoryMarker.toByte()+        if (encrypt) mfg[MFG_ENCRYPT_FLAG_INDEX_VA] = 0b100.toByte()+        return mfg+    }++    @Test+    fun `scan collects named scales with their manufacturer traits`() {+        val mgr = manager()+        mgr.startScan()+        assertTrue(DeviceController.scaleScanning.value)+        assertEquals(SCALE_SCANNING_STATE, DeviceController.scaleConnectionState.value)+        val cb = shadowOf(adapter.bluetoothLeScanner).scanCallbacks.single()+        val mfg = mfgData()+        cb.onScanResult(0, scanResult("QN-Scale", "00:11:22:33:44:55", mfg))+        cb.onScanResult(0, scanResult("QN-Scale", "00:11:22:33:44:55", mfg)) // duplicate+        cb.onScanResult(0, scanResult("renpho scale", "00:11:22:33:44:66")) // prefix, any case+        cb.onScanResult(0, scanResult("WaterH Bottle", "00:11:22:33:44:77", mfg))+        cb.onScanResult(0, scanResult(null, "00:11:22:33:44:88", mfg))+        flush()+        assertEquals(+            listOf("00:11:22:33:44:55", "00:11:22:33:44:66"),+            DeviceController.scaleDevices.map { it.address },+        )+        assertTrue(mgr.manufacturerData.containsKey("00:11:22:33:44:55"))+        mgr.stopScan()+        assertFalse(DeviceController.scaleScanning.value)+        // The scan timeout also stops a scan left running.+        mgr.startScan()+        advance(21_000)+        assertFalse(DeviceController.scaleScanning.value)+    }++    @Test+    fun `scan failure reports and stops`() {+        val mgr = manager()+        mgr.startScan()+        val cb = shadowOf(adapter.bluetoothLeScanner).scanCallbacks.single()+        cb.onScanFailed(3)+        flush()+        assertFalse(DeviceController.scaleScanning.value)+        assertEquals("Scan failed (3)", DeviceController.scaleConnectionState.value)+    }++    @Test+    fun `passive watch connects when the scale wakes and ignores others`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55", passive = true)+        assertEquals("00:11:22:33:44:55", mgr.watchAddress)+        assertEquals(SCALE_WAITING_STATE, DeviceController.scaleConnectionState.value)+        val cb = shadowOf(adapter.bluetoothLeScanner).scanCallbacks.single()+        // A different device waking does nothing.+        cb.onScanResult(0, scanResult("QN-Scale", "00:11:22:33:44:99", mfgData()))+        flush()+        assertEquals("00:11:22:33:44:55", mgr.watchAddress)+        // Our scale wakes: the watch stops and a GATT connection opens.+        cb.onScanResult(0, scanResult("QN-Scale", "00:11:22:33:44:55", mfgData()))+        flush()+        assertEquals(null, mgr.watchAddress)+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        assertEquals(1, shadowOf(device).bluetoothGatts.size)+        assertEquals(DeviceController.LinkState.Connecting, DeviceController.scaleLink.value)+        assertEquals(CATEGORY_128, mgr.scaleCategory)+        assertTrue(mgr.useResistanceEncrypt)+        assertTrue(mgr.isVaScale)+        // The advertised traits were remembered for the next launch.+        assertEquals(CATEGORY_128, DeviceController.savedScaleCategory())+        // A watch scan failure clears the watch.+        mgr.connect("00:11:22:33:44:55", passive = true)+        // Already connected to this address through the earlier gatt: connect is a no-op;+        // drive the failure through a fresh watch on another address instead.+        mgr.disconnect()+        mgr.connect("00:11:22:33:44:66", passive = true)+        val cb2 = shadowOf(adapter.bluetoothLeScanner).scanCallbacks.last()+        cb2.onScanFailed(1)+        flush()+        assertEquals(null, mgr.watchAddress)+    }++    @Test+    fun `connect is idempotent and disconnect prevents reconnect watch`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        flush()+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        assertEquals(1, shadowOf(device).bluetoothGatts.size)+        mgr.connect("00:11:22:33:44:55")+        assertEquals(1, shadowOf(device).bluetoothGatts.size)+        // Saved-traits fallback: nothing was scanned, so prefs/defaults decide the category.+        assertEquals(CATEGORY_DEFAULT, mgr.scaleCategory)+        assertFalse(mgr.isVaScale)+        mgr.disconnect()+        assertTrue(mgr.intentionalDisconnect)+        mgr.close()+        mgr.close()+    }++    private fun service(+        uuid: UUID,+        chars: List<Pair<UUID, Boolean>>,+    ): BluetoothGattService {+        val svc = BluetoothGattService(uuid, BluetoothGattService.SERVICE_TYPE_PRIMARY)+        for ((charUuid, withCccd) in chars) {+            val ch = BluetoothGattCharacteristic(+                charUuid,+                BluetoothGattCharacteristic.PROPERTY_NOTIFY,+                0,+            )+            if (withCccd) {+                ch.addDescriptor(+                    BluetoothGattDescriptor(+                        ScaleBleManager.CCCD_UUID,+                        BluetoothGattDescriptor.PERMISSION_WRITE,+                    ),+                )+            }+            svc.addCharacteristic(ch)+        }+        return svc+    }++    @Test+    fun `gatt lifecycle drives discovery descriptors and notifications`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        val cb = mgr.gattCallback+        cb.onConnectionStateChange(gatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_CONNECTED)+        flush()+        assertEquals(DeviceController.LinkState.Connected, DeviceController.scaleLink.value)+        assertEquals("Discovering services...", DeviceController.scaleConnectionState.value)+        // Discovery failure is reported in the state string.+        cb.onServicesDiscovered(gatt, 8)+        flush()+        assertEquals("Service discovery failed (8)", DeviceController.scaleConnectionState.value)+        // No scale service.+        cb.onServicesDiscovered(gatt, BluetoothGatt.GATT_SUCCESS)+        flush()+        assertEquals("Scale service not found", DeviceController.scaleConnectionState.value)+        // Service without the notify char.+        shadowOf(gatt).addDiscoverableService(service(ScaleBleManager.SERVICE_FFE0, emptyList()))+        gatt.discoverServices()+        flush()+        assertEquals("Scale notifying char not found", DeviceController.scaleConnectionState.value)+    }++    @Test+    fun `full ffe0 discovery enables notify and indicate then connects`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        val svc = service(+            ScaleBleManager.SERVICE_FFE0,+            listOf(+                ScaleBleManager.CHAR_FFE1 to true,+                ScaleBleManager.CHAR_FFE2 to true,+                ScaleBleManager.CHAR_FFE3 to false,+                ScaleBleManager.CHAR_FFE4 to false,+            ),+        )+        shadowOf(gatt).addDiscoverableService(svc)+        val cb = mgr.gattCallback+        cb.onConnectionStateChange(gatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_CONNECTED)+        flush()+        gatt.discoverServices()+        flush()+        assertEquals(ScaleBleManager.CHAR_FFE4, mgr.bleWriteChar)+        assertEquals(ScaleBleManager.CHAR_FFE3, mgr.configChar)+        assertFalse(mgr.isHoltek)+        // Two descriptors were queued (FFE1 notify + FFE2 indicate); drain both.+        val desc = svc.getCharacteristic(ScaleBleManager.CHAR_FFE1)+            .getDescriptor(ScaleBleManager.CCCD_UUID)+        cb.onDescriptorWrite(gatt, desc, BluetoothGatt.GATT_SUCCESS)+        flush()+        cb.onDescriptorWrite(gatt, desc, BluetoothGatt.GATT_SUCCESS)+        flush()+        assertEquals("Connected — step on scale", DeviceController.scaleConnectionState.value)+        // A measurement notification on FFE1 is dispatched.+        val notifyChar = BluetoothGattCharacteristic(ScaleBleManager.CHAR_FFE1, 0, 0)+        val pkt = byteArrayOf(PACKET_MEASURE.toByte(), 0, 0, 0x02, 0xEE.toByte(), 0, 0, 0, 0, 0)+        cb.onCharacteristicChanged(gatt, notifyChar, pkt)+        flush()+        assertEquals(75.0, DeviceController.scaleRealtimeWeight.value)+        // Other chars and empty values are ignored; the deprecated overload works too.+        val other = BluetoothGattCharacteristic(UUID.randomUUID(), 0, 0)+        cb.onCharacteristicChanged(gatt, other, pkt)+        cb.onCharacteristicChanged(gatt, notifyChar, byteArrayOf())+        notifyChar.setValue(pkt)+        @Suppress("DEPRECATION")+        cb.onCharacteristicChanged(gatt, notifyChar)+        flush()+        // Writes drain through the queue on characteristic-write completion.+        mgr.enqueue(ScaleBleManager.CHAR_FFE3, byteArrayOf(1, 2, 3))+        mgr.enqueue(ScaleBleManager.CHAR_FFE3, byteArrayOf(4, 5, 6))+        cb.onCharacteristicWrite(gatt, notifyChar, BluetoothGatt.GATT_SUCCESS)+        flush()+        advance(100)+    }++    @Test+    fun `holtek fff0 discovery collapses writes onto fff2`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        val svc = service(+            ScaleBleManager.SERVICE_FFF0,+            listOf(ScaleBleManager.CHAR_FFF1 to true, ScaleBleManager.CHAR_FFF2 to false),+        )+        shadowOf(gatt).addDiscoverableService(svc)+        val cb = mgr.gattCallback+        gatt.discoverServices()+        flush()+        assertTrue(mgr.isHoltek)+        assertEquals(ScaleBleManager.CHAR_FFF2, mgr.configChar)+        assertEquals(ScaleBleManager.CHAR_FFF2, mgr.bleWriteChar)+        val desc = svc.getCharacteristic(ScaleBleManager.CHAR_FFF1)+            .getDescriptor(ScaleBleManager.CCCD_UUID)+        cb.onDescriptorWrite(gatt, desc, BluetoothGatt.GATT_SUCCESS)+        flush()+        assertEquals("Connected — step on scale", DeviceController.scaleConnectionState.value)+    }++    @Test+    fun `missing cccd is reported`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        shadowOf(gatt).addDiscoverableService(+            service(ScaleBleManager.SERVICE_FFE0, listOf(ScaleBleManager.CHAR_FFE1 to false)),+        )+        gatt.discoverServices()+        flush()+        assertEquals("Scale CCCD not found", DeviceController.scaleConnectionState.value)+    }++    @Test+    fun `disconnect callback returns to watching unless intentional`() {+        val mgr = manager()+        mgr.connect("00:11:22:33:44:55")+        val device = adapter.getRemoteDevice("00:11:22:33:44:55")+        val gatt = shadowOf(device).bluetoothGatts.single()+        DeviceController.scaleDevices.add(ScaleBleManager.ScaleBleDevice("QN-Scale", "00:11:22:33:44:55"))+        mgr.gattCallback.onConnectionStateChange(+            gatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED,+        )+        flush()+        assertEquals(DeviceController.LinkState.Waiting, DeviceController.scaleLink.value)+        assertTrue(DeviceController.scaleDevices.isEmpty())+        assertEquals("00:11:22:33:44:55", mgr.watchAddress, "an unexpected drop re-watches")+        // Now disconnect intentionally and repeat: no watch is started.+        mgr.disconnect()+        mgr.gattCallback.onConnectionStateChange(+            gatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED,+        )+        flush()+        assertEquals(null, mgr.watchAddress)+        assertNotNull(mgr.gattCallback)+    }++    @Test+    fun `time retry gives up after the limit`() {+        val mgr = manager()+        mgr.timeRetries = 0+        mgr.timeRetry.run()+        mgr.timeRetry.run()+        mgr.timeRetry.run()+        assertEquals(3, mgr.timeRetries)+        mgr.timeRetry.run() // over the limit: returns without counting or crashing+        assertEquals(3, mgr.timeRetries)+        mgr.sendStart.run()+        flush()+    }+}
things/src/test/java/com/vayunmathur/things/platform/ScaleBlePacketTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/platform/ScaleBlePacketTest.kt b/things/src/test/java/com/vayunmathur/things/platform/ScaleBlePacketTest.ktnew file mode 100644index 0000000000..99dcf28d7d--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/platform/ScaleBlePacketTest.kt@@ -0,0 +1,374 @@+package com.vayunmathur.things.platform++import android.content.Context+import android.os.Looper+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.records.WeightRecord+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/** Scale packet dispatch: classic + VA measure frames, stored records, user sync. */+@RunWith(RobolectricTestRunner::class)+class ScaleBlePacketTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun manager(va: Boolean = false, category: Int = 100): ScaleBleManager {+        DeviceController.init(context)+        DeviceController.scaleWeight.value = null+        DeviceController.scaleRealtimeWeight.value = null+        DeviceController.scaleMetrics.value = null+        DeviceController.scaleConnectionState.value = "Disconnected"+        DeviceController.scaleSex.value = Sex.Male+        DeviceController.scaleAge.value = "30"+        DeviceController.scaleHeight.value = "175"+        DeviceController.scaleAthlete.value = false+        DeviceController.loadScaleProfile()+        shadowOf(Looper.getMainLooper()).idle()+        return ScaleBleManager().apply {+            isVaScale = va+            scaleCategory = category+        }+    }++    private fun withFakeHealth(fake: FakeHealthConnect, block: () -> Unit) {+        val oldStatus = healthStatusProvider+        val oldClient = healthClientProvider+        healthStatusProvider = { HealthConnectClient.SDK_AVAILABLE }+        healthClientProvider = { fake.client }+        try {+            block()+        } finally {+            healthStatusProvider = oldStatus+            healthClientProvider = oldClient+        }+    }++    private fun flush() = shadowOf(Looper.getMainLooper()).idle()++    private fun classic(sub: Int, weightRaw: Int, size: Int = 10): ByteArray {+        val b = ByteArray(size)+        b[0] = PACKET_MEASURE.toByte()+        b[3] = (weightRaw shr 8).toByte(); b[4] = weightRaw.toByte()+        b[5] = sub.toByte()+        return b+    }++    @Test+    fun `classic streaming packets report realtime weight`() {+        val mgr = manager()+        for (sub in listOf(0, 17, 18)) {+            DeviceController.scaleRealtimeWeight.value = null+            mgr.dispatch(classic(sub, 750)) // 750/10 = 75 kg+            assertEquals(75.0, DeviceController.scaleRealtimeWeight.value, "sub=$sub")+        }+        // A zero weight is not a reading.+        DeviceController.scaleRealtimeWeight.value = null+        mgr.dispatch(classic(0, 0))+        assertNull(DeviceController.scaleRealtimeWeight.value)+        // Short packets are ignored.+        mgr.dispatch(byteArrayOf(PACKET_MEASURE.toByte(), 0))+        assertNull(DeviceController.scaleRealtimeWeight.value)+    }++    @Test+    fun `classic stable packets lock in a measurement`() {+        val mgr = manager()+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            val b = classic(1, 800) // 80 kg+            b[6] = 0x01; b[7] = 0xF4.toByte() // r50 500+            b[8] = 0x01; b[9] = 0x2C // r500 300+            mgr.dispatch(b)+            flush()+            assertEquals(80.0, DeviceController.scaleWeight.value)+            assertEquals(500, DeviceController.scaleR50.value)+            assertEquals(300, DeviceController.scaleR500.value)+            assertEquals(1, fake.inserted.size)+            // HR variant takes the same stable path.+            val hr = classic(2, 700)+            hr[6] = 0x01; hr[7] = 0xF4.toByte(); hr[8] = 0x01; hr[9] = 0x2C+            mgr.dispatch(hr)+            flush()+            assertEquals(70.0, DeviceController.scaleWeight.value)+            assertEquals(2, fake.inserted.size)+        }+        // A stable packet too short for impedance is dropped entirely.+        DeviceController.scaleWeight.value = null+        mgr.dispatch(classic(1, 800, size = 8))+        assertNull(DeviceController.scaleWeight.value)+    }++    @Test+    fun `eight electrode burst needs both packets before measuring`() {+        val mgr = manager(category = CATEGORY_EIGHT_ELECTRODE)+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            val first = ByteArray(17)+            first[0] = PACKET_MEASURE.toByte()+            first[3] = 0x02; first[4] = 0xEE.toByte() // 75 kg+            first[5] = 1+            first[6] = 0x21 // count 2, current 1+            // Channel words are (value / 0.1): 5000 -> 500.0 etc.+            fun put(at: Int, v: Int) {+                first[at] = (v shr 8).toByte(); first[at + 1] = v.toByte()+            }+            put(7, 5000); put(9, 5100); put(11, 5200); put(13, 5300); put(15, 5400)+            mgr.dispatch(first)+            flush()+            assertNull(DeviceController.scaleWeight.value, "half a burst is not a measurement")+            val second = ByteArray(17)+            second[0] = PACKET_MEASURE.toByte()+            second[3] = 0x02; second[4] = 0xEE.toByte()+            second[5] = 1+            second[6] = 0x22 // count 2, current 2+            fun put2(at: Int, v: Int) {+                second[at] = (v shr 8).toByte(); second[at + 1] = v.toByte()+            }+            put2(7, 5500); put2(9, 5600); put2(11, 5700); put2(13, 5800); put2(15, 5900)+            mgr.dispatch(second)+            flush()+            assertEquals(75.0, DeviceController.scaleWeight.value)+            assertNotNull(DeviceController.scaleMetrics.value?.segmental)+            assertEquals(1, fake.inserted.size)+            // A second-packet without a first is discarded, not built from stale channels.+            DeviceController.scaleWeight.value = null+            mgr.dispatch(second)+            flush()+            assertNull(DeviceController.scaleWeight.value)+        }+    }++    @Test+    fun `va measure states stream then complete`() {+        val mgr = manager(va = true)+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            fun va(state: Int, weightRaw: Int, size: Int = 11): ByteArray {+                val b = ByteArray(size)+                b[0] = PACKET_MEASURE.toByte()+                b[4] = state.toByte()+                b[5] = (weightRaw shr 8).toByte(); b[6] = weightRaw.toByte()+                return b+            }+            mgr.dispatch(va(0, 750)) // settling: 750 * 0.1 = 75+            assertEquals(75.0, DeviceController.scaleRealtimeWeight.value)+            mgr.dispatch(va(18, 700)) // heart-rate state still streams weight+            assertEquals(70.0, DeviceController.scaleRealtimeWeight.value)+            // Complete with impedance.+            val done = va(2, 750)+            done[7] = 0x01; done[8] = 0xF4.toByte(); done[9] = 0x01; done[10] = 0x2C+            mgr.dispatch(done)+            flush()+            assertEquals(75.0, DeviceController.scaleWeight.value)+            assertEquals(500, DeviceController.scaleR50.value)+            assertEquals(1, fake.inserted.size)+            // Complete but truncated: measurement with zero impedance.+            DeviceController.scaleWeight.value = null+            mgr.dispatch(va(2, 600, size = 8))+            flush()+            assertEquals(60.0, DeviceController.scaleWeight.value)+            assertNull(DeviceController.scaleR50.value)+            // Short VA packets are ignored (built by hand: the helper writes weight bytes).+            DeviceController.scaleWeight.value = null+            val short = ByteArray(5)+            short[0] = PACKET_MEASURE.toByte(); short[4] = 2+            mgr.dispatch(short)+            assertNull(DeviceController.scaleWeight.value)+        }+    }++    @Test+    fun `scale info sets type ratios and identify support`() {+        val mgr = manager()+        // Type-only packet: type lands but ratios wait for the full frame.+        val typeOnly = ByteArray(10)+        typeOnly[0] = PACKET_SCALE_INFO.toByte()+        typeOnly[2] = 7+        mgr.dispatch(typeOnly)+        assertEquals(7, mgr.scaleType)+        assertEquals(10.0, mgr.weightRatio)+        // Full kg frame with identify-weight support (byte16 bit5).+        val full = ByteArray(20)+        full[0] = PACKET_SCALE_INFO.toByte()+        full[2] = 3+        full[10] = 0+        full[16] = (1 shl 5).toByte()+        mgr.dispatch(full)+        flush()+        assertEquals(3, mgr.scaleType)+        assertEquals(10.0, mgr.weightRatio)+        assertEquals(0.1, mgr.kgWeightRatio)+        assertTrue(mgr.supportsIdentifyWeight)+        assertEquals("Connected — step on scale", DeviceController.scaleConnectionState.value)+        // lb frame flips both ratios and clears identify support.+        val lb = ByteArray(20)+        lb[0] = PACKET_SCALE_INFO.toByte()+        lb[10] = 1+        mgr.dispatch(lb)+        flush()+        assertEquals(100.0, mgr.weightRatio)+        assertEquals(0.01, mgr.kgWeightRatio)+        assertFalse(mgr.supportsIdentifyWeight)+    }++    @Test+    fun `time ack starts classic measurement and holtek hw packet sends time`() {+        val mgr = manager()+        // HW version on a non-Holtek scale does nothing observable; on Holtek it syncs time.+        mgr.dispatch(byteArrayOf(PACKET_HW_VERSION.toByte(), 0, 0))+        mgr.isHoltek = true+        mgr.dispatch(byteArrayOf(PACKET_HW_VERSION.toByte(), 0, 0))+        shadowOf(Looper.getMainLooper()).idleFor(300, java.util.concurrent.TimeUnit.MILLISECONDS)+        mgr.dispatch(byteArrayOf(PACKET_TIME_ACK.toByte(), 0, 0))+        shadowOf(Looper.getMainLooper()).idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)+        // Reaching here with the runnables drained is the assertion: no crash, queue handled.+        assertTrue(true)+    }++    private fun storedClassic(secondsSince2000: Long, weightRaw: Int): ByteArray {+        val b = ByteArray(15)+        b[0] = PACKET_STORED.toByte()+        for (i in 0 until 4) b[5 + i] = (secondsSince2000 shr (8 * i)).toByte()+        b[9] = (weightRaw shr 8).toByte(); b[10] = weightRaw.toByte()+        b[11] = 0x01; b[12] = 0xF4.toByte(); b[13] = 0x01; b[14] = 0x2C+        return b+    }++    @Test+    fun `classic stored records replay only plausible timestamps`() {+        val mgr = manager()+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            val nowSec = System.currentTimeMillis() / 1000 - BASE_TIME_2000_SECONDS+            mgr.dispatch(storedClassic(nowSec - 60, 750))+            flush()+            assertEquals(1, fake.inserted.size)+            val weights = fake.inserted.single().filterIsInstance<WeightRecord>()+            assertEquals(75.0, weights.single().weight.inKilograms, 1e-9)+            // Future and ancient replays are dropped.+            mgr.dispatch(storedClassic(nowSec + 3600, 750))+            mgr.dispatch(storedClassic(0, 750))+            // Zero weight and eight-electrode categories are dropped too.+            mgr.dispatch(storedClassic(nowSec - 60, 0))+            flush()+            assertEquals(1, fake.inserted.size)+        }+    }++    @Test+    fun `va stored records respect the user slot and timestamps`() {+        val mgr = manager(va = true)+        mgr.vaUserIndex = 2+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            fun vaStored(user: Int, secondsSince2000: Long, total: Int = 1): ByteArray {+                val b = ByteArray(18)+                b[0] = PACKET_STORED.toByte()+                b[3] = total.toByte(); b[4] = 1; b[5] = user.toByte()+                for (i in 0 until 4) b[6 + i] = (secondsSince2000 shr (8 * i)).toByte()+                b[10] = 0x02; b[11] = 0xEE.toByte() // 750 * 0.1 = 75+                b[12] = 0x01; b[13] = 0xF4.toByte(); b[14] = 0x01; b[15] = 0x2C+                return b+            }+            val nowSec = System.currentTimeMillis() / 1000 - BASE_TIME_2000_SECONDS+            mgr.dispatch(vaStored(user = 2, secondsSince2000 = nowSec - 60))+            flush()+            assertEquals(1, fake.inserted.size)+            // Someone else's record, an empty replay, and a future record are all skipped.+            mgr.dispatch(vaStored(user = 3, secondsSince2000 = nowSec - 60))+            mgr.dispatch(vaStored(user = 2, secondsSince2000 = nowSec - 60, total = 0))+            mgr.dispatch(vaStored(user = 2, secondsSince2000 = nowSec + 7200))+            flush()+            assertEquals(1, fake.inserted.size)+        }+    }++    @Test+    fun `user sync results register visit and delete`() {+        val mgr = manager(va = true)+        val fake = FakeHealthConnect()+        withFakeHealth(fake) {+            fun result(sub: Int, index: Int, ok: Boolean): ByteArray {+                val b = ByteArray(6)+                b[0] = PACKET_USER_SYNC.toByte()+                b[2] = sub.toByte(); b[3] = index.toByte(); b[4] = (if (ok) 1 else 0).toByte()+                return b+            }+            // Too short to trust.+            mgr.dispatch(byteArrayOf(PACKET_USER_SYNC.toByte(), 0, 1))+            // Register succeeds: slot is saved and becomes ours after the visit.+            mgr.dispatch(result(VA_SUB_REGISTER, 3, ok = true))+            flush()+            assertEquals(3, DeviceController.scaleUserIndex())+            // Register fails (slots full): visitor mode, no slot saved.+            DeviceController.devicePrefs.edit().remove(DeviceController.SCALE_USER_INDEX_KEY).commit()+            mgr.dispatch(result(VA_SUB_REGISTER, 0, ok = false))+            flush()+            assertNull(DeviceController.scaleUserIndex())+            // Visit succeeds for a real slot and for the visitor slot.+            mgr.dispatch(result(VA_SUB_VISIT, 3, ok = true))+            assertEquals(3, mgr.vaUserIndex)+            mgr.dispatch(result(VA_SUB_VISIT, VA_VISITOR_INDEX, ok = true))+            assertNull(mgr.vaUserIndex)+            mgr.dispatch(result(VA_SUB_VISIT, 3, ok = false))+            assertNull(mgr.vaUserIndex)+            // Delete completes the pending reset and re-syncs; a rejected delete does not.+            DeviceController.requestScaleReset()+            mgr.dispatch(result(VA_SUB_DELETE, 0, ok = true))+            flush()+            assertFalse(DeviceController.scaleResetPending())+            mgr.dispatch(result(VA_SUB_DELETE, 0, ok = false))+            flush()+        }+    }++    @Test+    fun `user frames visitor identify and stored requests enqueue safely`() {+        val mgr = manager(va = true)+        DeviceController.scaleProfile.value = ScaleProfile(Sex.Female, 45, 182.0, athlete = true)+        mgr.syncUser() // no slot yet: register frame+        DeviceController.saveScaleUserIndex(5)+        mgr.syncUser() // visit frame+        mgr.sendVisitorUser()+        assertNull(mgr.vaUserIndex)+        mgr.sendDeleteAllUsers()+        mgr.requestStoredRecords()+        mgr.vaUserIndex = 4+        mgr.requestStoredRecords()+        // Identify-weight only goes out when the scale supports it and we hold a slot.+        mgr.supportsIdentifyWeight = false+        mgr.sendIdentifyWeight(75.0)+        mgr.supportsIdentifyWeight = true+        mgr.sendIdentifyWeight(75.0)+        mgr.sendIdentifyWeight(0.0)+        flush()+        shadowOf(Looper.getMainLooper()).idleFor(1, java.util.concurrent.TimeUnit.SECONDS)+    }++    @Test+    fun `build cmd frames with the connection scale type`() {+        val mgr = manager()+        mgr.scaleType = 9+        val frame = mgr.buildCmd(CMD_TIME, 1, 2, 3, 4)+        assertEquals(CMD_TIME.toByte(), frame[0])+        assertEquals(9, frame[2].toInt())+        val sum = (0 until frame.size - 1).sumOf { frame[it].toInt() }+        assertEquals(sum.toByte(), frame[frame.size - 1])+    }++    @Test+    fun `unknown packets are ignored`() {+        val mgr = manager()+        mgr.dispatch(byteArrayOf(0x7F, 1, 2, 3))+        assertNull(DeviceController.scaleWeight.value)+    }+}
things/src/test/java/com/vayunmathur/things/ui/ThingsPagesExtraTest.kt
diff --git a/things/src/test/java/com/vayunmathur/things/ui/ThingsPagesExtraTest.kt b/things/src/test/java/com/vayunmathur/things/ui/ThingsPagesExtraTest.ktnew file mode 100644index 0000000000..ad1244f3c7--- /dev/null+++ b/things/src/test/java/com/vayunmathur/things/ui/ThingsPagesExtraTest.kt@@ -0,0 +1,251 @@+package com.vayunmathur.things.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.things.R+import com.vayunmathur.things.platform.BleManager+import com.vayunmathur.things.platform.DeviceController.LinkState+import com.vayunmathur.things.platform.ScaleBleManager+import com.vayunmathur.things.platform.Sex+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Interaction coverage the first page pass did not reach: dialogs, inputs, blocked states. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ThingsPagesExtraTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg a: Any): String = context.getString(id, *a)++    private fun home(+        bottlePaired: Boolean = false,+        scalePaired: Boolean = false,+        charging: Boolean = false,+        withData: Boolean = true,+        lastUpdatedMillis: Long? = null,+        scaleUserSlot: Int? = 1,+        onScaleSexChange: (Sex) -> Unit = {},+        onScaleAgeChange: (String) -> Unit = {},+        onScaleHeightChange: (String) -> Unit = {},+        onScaleAthleteChange: (Boolean) -> Unit = {},+        onForgetBottle: () -> Unit = {},+        onForgetScale: () -> Unit = {},+        onResetScale: () -> Unit = {},+        onHealthConnectClick: () -> Unit = {},+        onOpenDevices: () -> Unit = {},+    ) {+        composeRule.setContent {+            HomePage(+                bottlePaired = bottlePaired, bottleLink = LinkState.Connected,+                bottleConnectionState = "Connected",+                tempC = if (withData) 22 else null,+                tds = if (withData) 45 else null,+                batteryPct = if (withData) 80 else null,+                charging = charging,+                volumePct = if (withData) 65 else null,+                lastUpdatedMillis = lastUpdatedMillis,+                scalePaired = scalePaired, scaleLink = LinkState.Waiting,+                scaleConnectionState = "Waiting", scaleUserSlot = scaleUserSlot,+                scaleSex = Sex.Male, scaleAge = "30", scaleHeight = "175", scaleAthlete = false,+                onScaleSexChange = onScaleSexChange, onScaleAgeChange = onScaleAgeChange,+                onScaleHeightChange = onScaleHeightChange,+                onScaleAthleteChange = onScaleAthleteChange,+                onForgetBottle = onForgetBottle, onForgetScale = onForgetScale,+                onResetScale = onResetScale, onHealthConnectClick = onHealthConnectClick,+                onOpenDevices = onOpenDevices,+            )+        }+    }++    @Test+    fun bottleCardWaitingForDataWhenNoTelemetry() {+        home(bottlePaired = true, withData = false)+        composeRule.onNodeWithText(str(R.string.waiting_for_data)).assertIsDisplayed()+    }++    @Test+    fun bottleCardChargingAndLastUpdatedRender() {+        home(bottlePaired = true, charging = true, lastUpdatedMillis = 1_700_000_000_000L)+        composeRule.onNodeWithText(str(R.string.battery_charging, 80)).assertIsDisplayed()+        assertTrue(+            composeRule.onAllNodesWithText("Updated", substring = true)+                .fetchSemanticsNodes().isNotEmpty(),+        )+    }++    @Test+    fun healthConnectButtonFires() {+        var clicked = false+        home(onHealthConnectClick = { clicked = true })+        composeRule.onNodeWithText(str(R.string.permission_health_connect)).performClick()+        assertTrue(clicked)+    }++    @Test+    fun scaleCardProfileInteractions() {+        var sex: Sex? = null+        var age: String? = null+        var height: String? = null+        var athlete: Boolean? = null+        var forgotScale = false+        home(+            scalePaired = true,+            onScaleSexChange = { sex = it },+            onScaleAgeChange = { age = it },+            onScaleHeightChange = { height = it },+            onScaleAthleteChange = { athlete = it },+            onForgetScale = { forgotScale = true },+        )+        composeRule.onNodeWithText(str(R.string.scale_user_slot, 1)).assertIsDisplayed()+        composeRule.onNodeWithText(str(R.string.sex_female)).performClick()+        assertEquals(Sex.Female, sex)+        composeRule.onNodeWithText("30").performTextReplacement("41")+        assertEquals("41", age)+        composeRule.onNodeWithText("175").performTextReplacement("182")+        assertEquals("182", height)+        // The label text is not itself clickable; the checkbox next to it is.+        composeRule.onNode(androidx.compose.ui.test.isToggleable())+            .performScrollTo().performClick()+        assertEquals(true, athlete)+        composeRule.onNodeWithText(str(R.string.forget_device)).performScrollTo().performClick()+        assertTrue(forgotScale)+    }++    @Test+    fun scaleCardUnregisteredSlotLabel() {+        home(scalePaired = true, scaleUserSlot = null)+        composeRule.onNodeWithText(str(R.string.scale_user_unregistered)).assertIsDisplayed()+    }++    @Test+    fun scaleResetDialogConfirmAndDismiss() {+        var resets = 0+        home(scalePaired = true, onResetScale = { resets++ })+        composeRule.onNodeWithText(str(R.string.scale_reset_users)).performScrollTo().performClick()+        composeRule.onNodeWithText(str(R.string.scale_reset_title)).assertIsDisplayed()+        // Dismiss first: no reset.+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertEquals(0, resets)+        // Reopen and confirm.+        composeRule.onNodeWithText(str(R.string.scale_reset_users)).performScrollTo().performClick()+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.reset)).performClick()+        assertEquals(1, resets)+    }++    @Test+    fun devicesPickerListsAndPicksBottle() {+        var picked: BleManager.BleDevice? = null+        var scanned = false+        val device = BleManager.BleDevice("WaterH Bottle", "00:11:22:33:44:55")+        composeRule.setContent {+            DevicesPage(+                scanning = true, discoveredDevices = listOf(device),+                scaleScanning = false, scaleDevices = emptyList(),+                onScanClick = { scanned = true }, onDeviceClick = { picked = it },+                onScaleScanClick = {}, onScaleDeviceClick = {},+                onNavigateBack = null,+            )+        }+        composeRule.onNodeWithText(str(R.string.connect_new_bottle)).performClick()+        assertTrue(scanned)+        composeRule.onNodeWithText(str(R.string.select_device)).assertIsDisplayed()+        composeRule.onNodeWithText("WaterH Bottle").assertIsDisplayed()+        composeRule.onNodeWithText("00:11:22:33:44:55").performClick()+        assertEquals(device, picked)+    }++    @Test+    fun devicesPickerListsAndPicksScaleAndDismisses() {+        var picked: ScaleBleManager.ScaleBleDevice? = null+        val device = ScaleBleManager.ScaleBleDevice("QN-Scale", "00:11:22:33:44:66")+        composeRule.setContent {+            DevicesPage(+                scanning = false, discoveredDevices = emptyList(),+                scaleScanning = false, scaleDevices = listOf(device),+                onScanClick = {}, onDeviceClick = {},+                onScaleScanClick = {}, onScaleDeviceClick = { picked = it },+                onNavigateBack = {},+            )+        }+        composeRule.onNodeWithText(str(R.string.connect_new_scale)).performClick()+        composeRule.onNodeWithText("QN-Scale").performClick()+        assertEquals(device, picked)+        // Reopen and dismiss with Cancel: nothing more is picked.+        composeRule.onNodeWithText(str(R.string.connect_new_scale)).performClick()+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        composeRule.onNodeWithText(str(R.string.connect_new_scale)).assertIsDisplayed()+    }++    @Test+    fun devicesPickerSearchingAndEmptyStates() {+        composeRule.setContent {+            DevicesPage(+                scanning = true, discoveredDevices = emptyList(),+                scaleScanning = false, scaleDevices = emptyList(),+                onScanClick = {}, onDeviceClick = {},+                onScaleScanClick = {}, onScaleDeviceClick = {},+                onNavigateBack = {},+            )+        }+        composeRule.onNodeWithText(str(R.string.connect_new_bottle)).performClick()+        composeRule.onNodeWithText(str(R.string.searching)).assertIsDisplayed()+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+    }++    @Test+    fun permissionsBlockedShowsSettingsActions() {+        var btResolve = false+        var hcResolve = false+        composeRule.setContent {+            PermissionsPage(+                bluetooth = PermissionState.Blocked, healthConnect = PermissionState.Blocked,+                onRequestBluetooth = {}, onRequestHealthConnect = {},+                onResolveBluetooth = { btResolve = true },+                onResolveHealthConnect = { hcResolve = true },+            )+        }+        assertEquals(+            2,+            composeRule.onAllNodesWithText(str(R.string.permission_blocked))+                .fetchSemanticsNodes().size,+        )+        val settings = composeRule.onAllNodesWithText(str(R.string.permission_open_settings))+        assertEquals(2, settings.fetchSemanticsNodes().size)+        settings[0].performClick()+        assertTrue(btResolve)+        settings[1].performScrollTo().performClick()+        assertTrue(hcResolve)+    }++    @Test+    fun permissionsNeededGrantButtonsFire() {+        var bt = false+        var hc = false+        composeRule.setContent {+            PermissionsPage(+                bluetooth = PermissionState.Needed, healthConnect = PermissionState.Granted,+                onRequestBluetooth = { bt = true }, onRequestHealthConnect = { hc = true },+                onResolveBluetooth = {}, onResolveHealthConnect = {},+            )+        }+        composeRule.onNodeWithText(str(R.string.permission_grant)).performClick()+        assertTrue(bt)+        assertTrue(!hc, "the granted card has no grant button")+        composeRule.onNodeWithText(str(R.string.permission_granted)).assertIsDisplayed()+    }+}