things: various fixes
- Commit
19a1e04b351ef8a74e8e7290ebce8025b0180b66- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-02 19:51 UTC (3 months ago)
- Parents
e1c296b
Diff
metadata_data/photos/things/1.png
diff --git a/metadata_data/photos/things/1.png b/metadata_data/photos/things/1.pngindex acc0b6e575..03f54d65a0 100644Binary files a/metadata_data/photos/things/1.png and b/metadata_data/photos/things/1.png differ
metadata_data/photos/things/2.png
diff --git a/metadata_data/photos/things/2.png b/metadata_data/photos/things/2.pngindex fae9190014..b1ab3d0d78 100644Binary files a/metadata_data/photos/things/2.png and b/metadata_data/photos/things/2.png differ
things/src/main/AndroidManifest.xml
diff --git a/things/src/main/AndroidManifest.xml b/things/src/main/AndroidManifest.xmlindex 9ba2277577..4009105a86 100644--- a/things/src/main/AndroidManifest.xml+++ b/things/src/main/AndroidManifest.xml@@ -7,6 +7,11 @@ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true" /> + <!-- Foreground service keeps the BLE links alive while the app is backgrounded/closed. -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <!-- Health Connect — write hydration + body composition (and read for permission gating). Matches the sibling health app's set (see health/AndroidManifest.xml). No INTERNET. --> <uses-permission android:name="android.permission.health.WRITE_HYDRATION" />@@ -39,6 +44,11 @@ </intent-filter> </activity> + <service+ android:name=".platform.DeviceService"+ android:foregroundServiceType="connectedDevice"+ android:exported="false" />+ <activity android:name=".ui.PermissionsRationaleActivity" android:exported="true">
things/src/main/java/com/vayunmathur/things/MainActivity.kt
diff --git a/things/src/main/java/com/vayunmathur/things/MainActivity.kt b/things/src/main/java/com/vayunmathur/things/MainActivity.ktindex 14e6530800..12d60461ef 100644--- a/things/src/main/java/com/vayunmathur/things/MainActivity.kt+++ b/things/src/main/java/com/vayunmathur/things/MainActivity.kt@@ -1,163 +1,33 @@ package com.vayunmathur.things -import kotlin.time.Clock-import kotlin.time.Instant-import kotlinx.datetime.LocalTime-import kotlinx.datetime.TimeZone-import kotlinx.datetime.format-import kotlinx.datetime.format.char-import kotlinx.datetime.toLocalDateTime import android.Manifest+import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.runtime.mutableIntStateOf-import androidx.compose.runtime.mutableStateListOf-import androidx.compose.runtime.mutableStateOf-import androidx.core.content.edit-import androidx.health.connect.client.HealthConnectClient-import androidx.lifecycle.lifecycleScope import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.things.platform.BleManager-import com.vayunmathur.things.platform.BodyComposition-import com.vayunmathur.things.platform.BodyMetrics-import com.vayunmathur.things.platform.BottleStatus+import com.vayunmathur.things.platform.DeviceController+import com.vayunmathur.things.platform.DeviceService import com.vayunmathur.things.platform.HealthConnectHelper-import com.vayunmathur.things.platform.HydrationReading-import com.vayunmathur.things.platform.ScaleBleManager-import com.vayunmathur.things.platform.ScaleMeasurement-import com.vayunmathur.things.platform.ScaleProfile-import com.vayunmathur.things.platform.SegmentalImpedance-import com.vayunmathur.things.platform.Sex-import java.time.LocalDate-import kotlinx.coroutines.launch class MainActivity : ComponentActivity() {- private lateinit var bleManager: BleManager- private lateinit var scaleBleManager: ScaleBleManager- val messages = mutableStateListOf<String>()- val totalMl = mutableIntStateOf(0)- val connectionState = mutableStateOf("Disconnected")- val scanning = mutableStateOf(false)- val discoveredDevices = mutableStateListOf<BleManager.BleDevice>()- val waterTempC = mutableStateOf<Int?>(null)- val tds = mutableStateOf<Int?>(null)- val batteryPct = mutableStateOf<Int?>(null)- val charging = mutableStateOf(false) - // Scale (Renpho Elis 1 / Qingniu) — offline BLE only, no cloud.- val scaleDevices = mutableStateListOf<ScaleBleManager.ScaleBleDevice>()- val scaleScanning = mutableStateOf(false)- val scaleConnectionState = mutableStateOf("Disconnected")- val scaleRealtimeWeight = mutableStateOf<Double?>(null)- val scaleWeight = mutableStateOf<Double?>(null)- val scaleR50 = mutableStateOf<Int?>(null)- val scaleR500 = mutableStateOf<Int?>(null)- val scaleMetrics = mutableStateOf<BodyMetrics?>(null)- val scaleProfile = mutableStateOf(ScaleProfile())- val scaleSex = mutableStateOf(Sex.Male)- val scaleAge = mutableStateOf("30")- val scaleHeight = mutableStateOf("175")- val scaleAthlete = mutableStateOf(false)-- private val prefs by lazy { getSharedPreferences("hydration", MODE_PRIVATE) }-- private fun today() = LocalDate.now().toString()- private fun isToday() = prefs.getString("date", null) == today()-- private fun loadTodayTotal() {- totalMl.intValue = if (isToday()) prefs.getInt("total_ml", 0) else 0- }-- private fun saveTotal() {- prefs.edit {- putString("date", today())- putInt("total_ml", totalMl.intValue)- }- }-- fun onDrinkLog(reading: HydrationReading) {- val instant = Instant.fromEpochMilliseconds(reading.epochMillis)- val local = instant.toLocalDateTime(TimeZone.currentSystemDefault())- val readingDate = LocalDate.of(local.date.year, local.date.monthNumber, local.date.dayOfMonth)- val isReadingToday = readingDate.toString() == today()- // Midnight rollover for the per-day persisted total.- if (!isToday()) {- totalMl.intValue = 0- messages.clear()- }- if (isReadingToday) {- totalMl.intValue += reading.amountMl- saveTotal()- }- val formatted = formatReadingTimestamp(local)- messages.add(0, "[$formatted] +${reading.amountMl} mL")- // Write to Health Connect (best-effort, no crash if unavailable).- writeHydrationToHealthConnect(reading)- }-- fun onBottleStatus(status: BottleStatus) {- waterTempC.value = status.tempC- tds.value = status.tds- batteryPct.value = status.batteryPct- charging.value = status.charging- }-- fun onScaleRealtimeWeight(weight: Double) {- scaleRealtimeWeight.value = weight- scaleConnectionState.value = "Weighing... %.1f kg".format(weight)- }-- fun onScaleMeasurement(- weightKg: Double,- r50: Int,- r500: Int,- stable: Boolean,- segmental: SegmentalImpedance? = null,- ) {- scaleRealtimeWeight.value = null- scaleWeight.value = weightKg- scaleR50.value = if (r50 == 0) null else r50- scaleR500.value = if (r500 == 0) null else r500- scaleConnectionState.value = if (stable) "Scale: %.1f kg".format(weightKg) else "Scale: %.1f kg".format(weightKg)- // Recompute metrics with current profile.- val profile = ScaleProfile(- sex = scaleSex.value,- age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: scaleProfile.value.age,- heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: scaleProfile.value.heightCm,- athlete = scaleAthlete.value,- )- scaleProfile.value = profile- val metrics = BodyComposition.calculate(profile, ScaleMeasurement(weightKg, r50, r500, segmental))- scaleMetrics.value = metrics- try {- prefs.edit {- putString("scale_sex", profile.sex.name)- putInt("scale_age", profile.age)- putString("scale_height", profile.heightCm.toString())- putString("scale_athlete", profile.athlete.toString())- }- } catch (_: Exception) {}- writeBodyCompositionToHealthConnect(weightKg, metrics)- }-- private fun formatReadingTimestamp(local: kotlinx.datetime.LocalDateTime): String {- val readingDate = LocalDate.of(local.date.year, local.date.monthNumber, local.date.dayOfMonth)- val timePart = local.time.format(LocalTime.Format { hour(); char(':'); minute() })- return if (readingDate.toString() != today()) {- "$readingDate $timePart"- } else {- timePart- }- }+ // Which scan to run once BLE permissions are granted (the launcher can't tell otherwise).+ private var pendingScan: (() -> Unit)? = null private val permissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { grants ->- if (grants.values.all { it }) {- bleManager.startScan()+ val action = pendingScan+ pendingScan = null+ // Only the BLE perms gate scanning; POST_NOTIFICATIONS only affects notification visibility.+ val bleGranted = grants[Manifest.permission.BLUETOOTH_SCAN] == true &&+ grants[Manifest.permission.BLUETOOTH_CONNECT] == true+ if (bleGranted && action != null) {+ DeviceService.start(this)+ action() } } @@ -170,164 +40,78 @@ class MainActivity : ComponentActivity() { } } - fun requestHealthConnectPermissions() {- val status = HealthConnectHelper.availabilityStatus(this)- if (status != HealthConnectClient.SDK_AVAILABLE) {- com.vayunmathur.library.util.AppMessages.show("Health Connect not available")- return- }- healthPermissionLauncher.launch(HealthConnectHelper.requiredPermissions)- }-- private fun loadScaleProfile() {- try {- val sexName = prefs.getString("scale_sex", null)- if (sexName != null) scaleSex.value = Sex.valueOf(sexName)- val ageInt = prefs.getInt("scale_age", -1)- if (ageInt != -1) scaleAge.value = ageInt.toString()- val hStr = prefs.getString("scale_height", null)- if (hStr != null) scaleHeight.value = hStr- val ath = prefs.getString("scale_athlete", null)- if (ath != null) scaleAthlete.value = ath.toBoolean()- scaleProfile.value = ScaleProfile(- sex = scaleSex.value,- age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: 30,- heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: 175.0,- athlete = scaleAthlete.value,- )- } catch (_: Exception) {}+ private fun requestScan(scan: () -> Unit) {+ pendingScan = scan+ permissionLauncher.launch(blePermissions()) } - private fun recalcScaleMetrics() {- val w = scaleWeight.value ?: return- val profile = ScaleProfile(- sex = scaleSex.value,- age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: scaleProfile.value.age,- heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: scaleProfile.value.heightCm,- athlete = scaleAthlete.value,+ private fun blePermissions(): Array<String> {+ val perms = mutableListOf(+ Manifest.permission.BLUETOOTH_SCAN,+ Manifest.permission.BLUETOOTH_CONNECT, )- scaleProfile.value = profile- val r50 = scaleR50.value ?: 0- val r500 = scaleR500.value ?: 0- scaleMetrics.value = BodyComposition.calculate(profile, ScaleMeasurement(w, r50, r500, null))- try {- prefs.edit {- putString("scale_sex", profile.sex.name)- putInt("scale_age", profile.age)- putString("scale_height", profile.heightCm.toString())- putString("scale_athlete", profile.athlete.toString())- }- } catch (_: Exception) {}- }-- private fun writeHydrationToHealthConnect(reading: HydrationReading) {- // Check Health Connect availability synchronously; writes are async.- val status = HealthConnectHelper.availabilityStatus(this)- if (status != HealthConnectClient.SDK_AVAILABLE) return- lifecycleScope.launch {- try {- val client = HealthConnectClient.getOrCreate(this@MainActivity)- if (!HealthConnectHelper.hasAllPermissions(client)) return@launch- val instant = java.time.Instant.ofEpochMilli(reading.epochMillis)- HealthConnectHelper.writeHydration(client, instant, reading.amountMl / 1000.0)- } catch (_: Exception) {}+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ perms.add(Manifest.permission.POST_NOTIFICATIONS) }+ return perms.toTypedArray() } - private fun writeBodyCompositionToHealthConnect(weightKg: Double, metrics: BodyMetrics) {- val status = HealthConnectHelper.availabilityStatus(this)- if (status != HealthConnectClient.SDK_AVAILABLE) return- lifecycleScope.launch {- try {- val client = HealthConnectClient.getOrCreate(this@MainActivity)- if (!HealthConnectHelper.hasAllPermissions(client)) return@launch- val instant = java.time.Instant.now()- val waterMassKg = if (metrics.waterPercent > 0) weightKg * metrics.waterPercent / 100.0 else null- HealthConnectHelper.writeBodyComposition(- client = client,- instant = instant,- weightKg = weightKg,- bodyFatPct = metrics.bodyFatPercent.takeIf { it > 0 },- leanMassKg = metrics.lbmKg.takeIf { it > 0 },- boneMassKg = metrics.boneKg.takeIf { it > 0 },- bodyWaterMassKg = waterMassKg,- bmrKcal = metrics.bmrKcal.takeIf { it > 0 },- )- } catch (_: Exception) {}- }+ private fun requestHealthConnectPermissions() {+ if (!DeviceController.isHealthConnectAvailable()) return+ healthPermissionLauncher.launch(HealthConnectHelper.requiredPermissions) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge()- bleManager = BleManager(this)- scaleBleManager = ScaleBleManager(this)- loadTodayTotal()- loadScaleProfile()+ DeviceController.init(applicationContext)+ // The service keeps the link alive in the background and drives auto-connect; in the+ // foreground reconnect still works because init() already built the managers.+ if (DeviceController.hasRememberedDevice()) DeviceService.start(this) setContent { DynamicTheme { Navigation(- totalMl = totalMl.intValue,- goalMl = GOAL_ML,- messages = messages,- connectionState = connectionState.value,- scanning = scanning.value,- discoveredDevices = discoveredDevices,- tempC = waterTempC.value,- tds = tds.value,- batteryPct = batteryPct.value,- charging = charging.value,- onScanClick = {- permissionLauncher.launch(- arrayOf(- Manifest.permission.BLUETOOTH_SCAN,- Manifest.permission.BLUETOOTH_CONNECT- )- )+ connectionState = DeviceController.connectionState.value,+ scanning = DeviceController.scanning.value,+ discoveredDevices = DeviceController.discoveredDevices,+ tempC = DeviceController.waterTempC.value,+ tds = DeviceController.tds.value,+ batteryPct = DeviceController.batteryPct.value,+ charging = DeviceController.charging.value,+ volumePct = DeviceController.bottleVolumePct.value,+ lastUpdatedMillis = DeviceController.bottleLastUpdated.value,+ onScanClick = { requestScan { DeviceController.startBottleScan() } },+ onDeviceClick = {+ DeviceService.start(this)+ DeviceController.connectBottle(it.address)+ },+ onDisconnectClick = {+ DeviceController.disconnectBottle()+ if (!DeviceController.hasRememberedDevice()) DeviceService.stop(this)+ },+ scaleConnectionState = DeviceController.scaleConnectionState.value,+ scaleScanning = DeviceController.scaleScanning.value,+ scaleDevices = DeviceController.scaleDevices,+ scaleSex = DeviceController.scaleSex.value,+ scaleAge = DeviceController.scaleAge.value,+ scaleHeight = DeviceController.scaleHeight.value,+ scaleAthlete = DeviceController.scaleAthlete.value,+ onScaleScanClick = { requestScan { DeviceController.startScaleScan() } },+ onScaleDeviceClick = {+ DeviceService.start(this)+ DeviceController.connectScale(it.address) },- onDeviceClick = { bleManager.connect(it.address) },- onDisconnectClick = { bleManager.disconnect() },- scaleWeight = scaleWeight.value,- scaleRealtimeWeight = scaleRealtimeWeight.value,- scaleR50 = scaleR50.value,- scaleConnectionState = scaleConnectionState.value,- scaleScanning = scaleScanning.value,- scaleDevices = scaleDevices,- scaleMetrics = scaleMetrics.value,- scaleSex = scaleSex.value,- scaleAge = scaleAge.value,- scaleHeight = scaleHeight.value,- scaleAthlete = scaleAthlete.value,- onScaleScanClick = {- permissionLauncher.launch(- arrayOf(- Manifest.permission.BLUETOOTH_SCAN,- Manifest.permission.BLUETOOTH_CONNECT- )- )- // Start scan after permission; the launcher callback starts bottle scan,- // so also start scale scan here (permission already granted path).- if (scaleBleManager.let { true }) scaleBleManager.startScan()+ onScaleDisconnectClick = {+ DeviceController.disconnectScale()+ if (!DeviceController.hasRememberedDevice()) DeviceService.stop(this) },- onScaleDeviceClick = { scaleBleManager.connect(it.address) },- onScaleDisconnectClick = { scaleBleManager.disconnect() },- onScaleSexChange = { scaleSex.value = it; recalcScaleMetrics() },- onScaleAgeChange = { scaleAge.value = it; recalcScaleMetrics() },- onScaleHeightChange = { scaleHeight.value = it; recalcScaleMetrics() },- onScaleAthleteChange = { scaleAthlete.value = it; recalcScaleMetrics() },+ onScaleSexChange = { DeviceController.scaleSex.value = it; DeviceController.recalcScaleMetrics() },+ onScaleAgeChange = { DeviceController.scaleAge.value = it; DeviceController.recalcScaleMetrics() },+ onScaleHeightChange = { DeviceController.scaleHeight.value = it; DeviceController.recalcScaleMetrics() },+ onScaleAthleteChange = { DeviceController.scaleAthlete.value = it; DeviceController.recalcScaleMetrics() }, onHealthConnectClick = { requestHealthConnectPermissions() }, ) } } }-- override fun onDestroy() {- super.onDestroy()- bleManager.close()- scaleBleManager.close()- }-- companion object {- private const val GOAL_ML = 2000- } }
things/src/main/java/com/vayunmathur/things/Navigation.kt
diff --git a/things/src/main/java/com/vayunmathur/things/Navigation.kt b/things/src/main/java/com/vayunmathur/things/Navigation.ktindex 4556e3d788..1664280374 100644--- a/things/src/main/java/com/vayunmathur/things/Navigation.kt+++ b/things/src/main/java/com/vayunmathur/things/Navigation.kt@@ -1,19 +1,22 @@ package com.vayunmathur.things import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.SiblingPage import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.things.platform.BleManager-import com.vayunmathur.things.platform.BodyMetrics import com.vayunmathur.things.platform.ScaleBleManager import com.vayunmathur.things.platform.Sex-import com.vayunmathur.things.ui.ThingsApp+import com.vayunmathur.things.ui.DevicesPage+import com.vayunmathur.things.ui.HomePage @Composable fun Navigation(- totalMl: Int,- goalMl: Int,- messages: List<String>, connectionState: String, scanning: Boolean, discoveredDevices: List<BleManager.BleDevice>,@@ -21,16 +24,14 @@ fun Navigation( tds: Int?, batteryPct: Int?, charging: Boolean,+ volumePct: Int?,+ lastUpdatedMillis: Long?, onScanClick: () -> Unit, onDeviceClick: (BleManager.BleDevice) -> Unit, onDisconnectClick: () -> Unit,- scaleWeight: Double?,- scaleRealtimeWeight: Double?,- scaleR50: Int?, scaleConnectionState: String, scaleScanning: Boolean, scaleDevices: List<ScaleBleManager.ScaleBleDevice>,- scaleMetrics: BodyMetrics?, scaleSex: Sex, scaleAge: String, scaleHeight: String,@@ -44,42 +45,69 @@ fun Navigation( onScaleAthleteChange: (Boolean) -> Unit, onHealthConnectClick: () -> Unit, ) {- val backStack = rememberNavBackStack<Route>(Route.Home)+ val backStack = rememberNavBackStack<Route>(Route.Devices)++ // Connection is derived from the managers' status strings (see BleManager/ScaleBleManager);+ // there is no separate boolean link-state to read.+ val bottleConnected = connectionState == "Connected"+ val scaleConnected = scaleConnectionState.startsWith("Scale: ") ||+ scaleConnectionState.contains("step on") ||+ scaleConnectionState.startsWith("Weighing")+ val anyConnected = bottleConnected || scaleConnected++ // On the first device connecting, swap Devices out for Home so there is no back to an empty+ // Devices screen. Only fires while sitting on Devices, so opening Devices manually later stays.+ var wasConnected by remember { mutableStateOf(anyConnected) }+ LaunchedEffect(anyConnected) {+ if (anyConnected && !wasConnected && backStack.last() == Route.Devices) {+ backStack.reset(Route.Home)+ }+ wasConnected = anyConnected+ }+ MainNavigation(backStack) {- entry<Route.Home> {- ThingsApp(- totalMl = totalMl,- goalMl = goalMl,- messages = messages,- connectionState = connectionState,- scanning = scanning,- discoveredDevices = discoveredDevices,+ entry<Route.Home>(SiblingPage()) {+ HomePage(+ bottleConnected = bottleConnected, tempC = tempC, tds = tds, batteryPct = batteryPct, charging = charging,- onScanClick = onScanClick,- onDeviceClick = onDeviceClick,- onDisconnectClick = onDisconnectClick,- scaleWeight = scaleWeight,- scaleRealtimeWeight = scaleRealtimeWeight,- scaleR50 = scaleR50,+ volumePct = volumePct,+ lastUpdatedMillis = lastUpdatedMillis,+ scaleConnected = scaleConnected, scaleConnectionState = scaleConnectionState,- scaleScanning = scaleScanning,- scaleDevices = scaleDevices,- scaleMetrics = scaleMetrics, scaleSex = scaleSex, scaleAge = scaleAge, scaleHeight = scaleHeight, scaleAthlete = scaleAthlete,- onScaleScanClick = onScaleScanClick,- onScaleDeviceClick = onScaleDeviceClick,- onScaleDisconnectClick = onScaleDisconnectClick, onScaleSexChange = onScaleSexChange, onScaleAgeChange = onScaleAgeChange, onScaleHeightChange = onScaleHeightChange, onScaleAthleteChange = onScaleAthleteChange,+ onOpenDevices = { backStack.add(Route.Devices) },+ )+ }+ entry<Route.Devices>(SiblingPage()) {+ DevicesPage(+ connectionState = connectionState,+ scanning = scanning,+ discoveredDevices = discoveredDevices,+ onScanClick = onScanClick,+ onDeviceClick = onDeviceClick,+ onDisconnectClick = onDisconnectClick,+ scaleConnectionState = scaleConnectionState,+ scaleScanning = scaleScanning,+ scaleDevices = scaleDevices,+ onScaleScanClick = onScaleScanClick,+ onScaleDeviceClick = onScaleDeviceClick,+ onScaleDisconnectClick = onScaleDisconnectClick, onHealthConnectClick = onHealthConnectClick,+ onNavigateBack = if (backStack.backStack.size > 1) {+ { backStack.pop() }+ } else {+ null+ }, ) } }
things/src/main/java/com/vayunmathur/things/Route.kt
diff --git a/things/src/main/java/com/vayunmathur/things/Route.kt b/things/src/main/java/com/vayunmathur/things/Route.ktindex 80a2ed70c8..32832476aa 100644--- a/things/src/main/java/com/vayunmathur/things/Route.kt+++ b/things/src/main/java/com/vayunmathur/things/Route.kt@@ -5,6 +5,9 @@ import kotlinx.serialization.Serializable @Serializable sealed interface Route : NavKey {+ @Serializable+ data object Devices : Route+ @Serializable data object Home : Route }
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 03b4d61228..7de03e5eca 100644--- a/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/BleManager.kt@@ -12,7 +12,7 @@ import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanSettings import android.os.Build-import com.vayunmathur.things.MainActivity+import android.util.Log import java.util.Calendar import java.util.UUID @@ -30,6 +30,7 @@ data class BottleStatus( val tds: Int?, val batteryPct: Int?, val charging: Boolean,+ val volumePct: Int?, ) /**@@ -41,8 +42,9 @@ data class BottleStatus( * and never touch its cloud backend. */ @SuppressLint("MissingPermission")-class BleManager(private val activity: MainActivity) {+class BleManager { companion object {+ private const val TAG = "WaterHBle" val NOTIFY_SERVICE_UUID: UUID = UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB") val NOTIFY_CHAR_UUID: UUID = UUID.fromString("0000FFE4-0000-1000-8000-00805F9B34FB") val WRITE_SERVICE_UUID: UUID = UUID.fromString("0000FFE5-0000-1000-8000-00805F9B34FB")@@ -55,15 +57,35 @@ class BleManager(private val activity: MainActivity) { private const val CMD_REQUEST_DATA = "47540001ff" // Set language (final step of the sync handshake). private const val CMD_SET_LANGUAGE = "50540003021b01"+ // First-time setup: take the bottle out of factory mode, then start registration.+ // Mirrors the official app's registerDevice() path (requestExitFactoryMode ++ // requestRegistration); this is what lights the bottle's blue LED and pairs it.+ private const val CMD_EXIT_FACTORY_MODE = "5054000302f400"+ private const val CMD_REQUEST_REGISTRATION = "50540003021c01"+ // Sent after the user confirms on the bottle (registration "Confirmed"); the bottle then+ // finalizes and replies "registration successful / clear data successful".+ private const val CMD_CLEAR_OFFLINE_DATA = "50540003021c05" } data class BleDevice(val name: String, val address: String) - private val bluetoothManager = activity.getSystemService(BluetoothManager::class.java)+ private val bluetoothManager = DeviceController.appContext.getSystemService(BluetoothManager::class.java) private val adapter = bluetoothManager.adapter private val scanner get() = adapter.bluetoothLeScanner private var gatt: BluetoothGatt? = null + // The device we want to stay connected to, and whether the last disconnect was user-initiated.+ // Used to keep connect() idempotent (so repeated auto-connect calls from the service don't+ // stack a second GATT client) and to drive passive background re-establishment.+ private var currentAddress: String? = null+ private var intentionalDisconnect = false+ // When true, run the one-time registration handshake on connect (blue LED + button press)+ // before requesting data, matching the official app's first-time setup path.+ private var pendingRegistration = false+ // Guards the one-shot clear-offline-data command sent after the button press is confirmed+ // (the bottle re-sends "Confirmed" several times).+ private var registrationClearSent = false+ // Command queue: one outstanding write at a time, drained on onCharacteristicWrite. private val commandQueue = ArrayDeque<String>() private var writing = false@@ -73,9 +95,11 @@ class BleManager(private val activity: MainActivity) { private var curTds: Int? = null private var curBattery: Int? = null private var curCharging = false+ private var curVolumePct: Int? = null // Water-log accumulation across PT packets. private var expectedLogs = 0+ private var parsedRecords = 0 private val collected = ArrayList<HydrationReading>() private val scanCallback = object : ScanCallback() {@@ -83,33 +107,50 @@ class BleManager(private val activity: MainActivity) { val name = result.device.name ?: return if (!name.startsWith("WaterH", ignoreCase = true)) return val addr = result.device.address- if (activity.discoveredDevices.none { it.address == addr }) {- activity.discoveredDevices.add(BleDevice(name, addr))+ if (DeviceController.discoveredDevices.none { it.address == addr }) {+ DeviceController.discoveredDevices.add(BleDevice(name, addr)) } } } fun startScan() {- activity.discoveredDevices.clear()- activity.scanning.value = true+ DeviceController.discoveredDevices.clear()+ DeviceController.scanning.value = true // WaterH advertises no service UUID; discover by name instead of a ScanFilter. val settings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build() scanner?.startScan(null, settings, scanCallback)- activity.connectionState.value = "Scanning..."+ DeviceController.connectionState.value = "Scanning..." } @Suppress("DEPRECATION")- fun connect(address: String) {+ fun connect(address: String, register: Boolean = false) {+ // Idempotent: if we already hold a GATT client for this device, don't open a second one.+ // Each connectGatt registers a new client interface with the Bluetooth stack; stacking+ // them leaks interfaces and confuses the bottle, which only services its first session+ // (its command char then silently ignores writes → the app hangs on "Waiting for data").+ if (gatt != null && currentAddress == address) return+ // Release any stale/previous client before opening a fresh one.+ close()+ currentAddress = address+ intentionalDisconnect = false+ pendingRegistration = register+ registrationClearSent = false+ openGatt(address, autoConnect = false)+ }++ private fun openGatt(address: String, autoConnect: Boolean) { scanner?.stopScan(scanCallback)- activity.scanning.value = false- activity.connectionState.value = "Connecting..."+ DeviceController.scanning.value = false+ DeviceController.connectionState.value = "Connecting..." val device = adapter.getRemoteDevice(address)- gatt = device.connectGatt(activity, false, gattCallback, BluetoothDevice.TRANSPORT_LE)+ gatt = device.connectGatt(DeviceController.appContext, autoConnect, gattCallback, BluetoothDevice.TRANSPORT_LE) } fun disconnect() {+ intentionalDisconnect = true+ currentAddress = null gatt?.disconnect() } @@ -129,12 +170,14 @@ class BleManager(private val activity: MainActivity) { curTds = null curBattery = null curCharging = false+ curVolumePct = null expectedLogs = 0+ parsedRecords = 0 collected.clear() } private fun enqueueCommand(hex: String) {- activity.runOnUiThread {+ DeviceController.runOnMain { commandQueue.addLast(hex) if (!writing) writeNext() }@@ -144,41 +187,85 @@ class BleManager(private val activity: MainActivity) { private fun writeNext() { val g = gatt ?: return val hex = commandQueue.removeFirstOrNull() ?: return- val service = g.getService(WRITE_SERVICE_UUID) ?: return- val char = service.getCharacteristic(WRITE_CHAR_UUID) ?: return+ val service = g.getService(WRITE_SERVICE_UUID)+ if (service == null) {+ Log.w(TAG, "writeNext: WRITE service $WRITE_SERVICE_UUID not found; dropping $hex")+ writing = false+ return+ }+ val char = service.getCharacteristic(WRITE_CHAR_UUID)+ if (char == null) {+ Log.w(TAG, "writeNext: WRITE char $WRITE_CHAR_UUID not found; dropping $hex")+ writing = false+ return+ } val bytes = hexToByteArray(hex) writing = true+ // FFE9 on this bottle is write-without-response (properties=0x4). Match the write type to+ // the characteristic's actual properties: on Android 13+ a write-with-response issued to a+ // no-response-only characteristic is silently dropped at the ATT layer (it never leaves the+ // phone), so the command must go out as WRITE_TYPE_NO_RESPONSE to reach the bottle.+ val writeType = if (char.properties and BluetoothGattCharacteristic.PROPERTY_WRITE != 0) {+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT+ } else {+ BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE+ }+ Log.d(TAG, "-> write $hex") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {- g.writeCharacteristic(char, bytes, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)+ g.writeCharacteristic(char, bytes, writeType) } else { char.setValue(bytes)- char.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT+ char.writeType = writeType g.writeCharacteristic(char) } } private val gattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {- activity.runOnUiThread {+ Log.d(TAG, "onConnectionStateChange status=$status newState=$newState")+ DeviceController.runOnMain { when (newState) { BluetoothProfile.STATE_CONNECTED -> { resetState()- activity.connectionState.value = "Connected"+ DeviceController.connectionState.value = "Connected" g.discoverServices() } BluetoothProfile.STATE_DISCONNECTED -> {- activity.connectionState.value = "Disconnected"- activity.discoveredDevices.clear()+ DeviceController.connectionState.value = "Disconnected"+ DeviceController.discoveredDevices.clear() resetState()+ // Release this GATT client so its interface doesn't leak in the stack.+ val g2 = gatt+ gatt = null+ g2?.let {+ it.close()+ refreshDeviceCache(it)+ }+ // Passive background re-establishment: if the link dropped on its own+ // (device slept / went out of range), reconnect with autoConnect=true so+ // the platform silently waits for it to return instead of churning.+ val addr = currentAddress+ if (!intentionalDisconnect && addr != null) {+ openGatt(addr, autoConnect = true)+ } } } } } override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {+ Log.d(TAG, "onServicesDiscovered status=$status") if (status != BluetoothGatt.GATT_SUCCESS) return- val service = g.getService(NOTIFY_SERVICE_UUID) ?: return- val char = service.getCharacteristic(NOTIFY_CHAR_UUID) ?: return+ val service = g.getService(NOTIFY_SERVICE_UUID)+ if (service == null) {+ Log.w(TAG, "NOTIFY service $NOTIFY_SERVICE_UUID not found; services=${g.services.map { it.uuid }}")+ return+ }+ val char = service.getCharacteristic(NOTIFY_CHAR_UUID)+ if (char == null) {+ Log.w(TAG, "NOTIFY char $NOTIFY_CHAR_UUID not found")+ return+ } g.setCharacteristicNotification(char, true) char.getDescriptor(CCCD_UUID)?.let { // The (descriptor, value) overload is API 33+; below that the@@ -191,16 +278,24 @@ class BleManager(private val activity: MainActivity) { @Suppress("DEPRECATION") g.writeDescriptor(it) }- }+ } ?: Log.w(TAG, "CCCD $CCCD_UUID not found on notify char") } override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {- // Notifications are on; kick off the handshake by asking for full bottle data.- enqueueCommand(CMD_REQUEST_DATA)+ if (pendingRegistration) {+ // First-time setup: exit factory mode + start registration (blue LED, button press).+ Log.d(TAG, "onDescriptorWrite status=$status; starting registration")+ enqueueCommand(CMD_EXIT_FACTORY_MODE)+ enqueueCommand(CMD_REQUEST_REGISTRATION)+ } else {+ // Notifications are on; kick off the handshake by asking for full bottle data.+ Log.d(TAG, "onDescriptorWrite status=$status; requesting bottle data")+ enqueueCommand(CMD_REQUEST_DATA)+ } } override fun onCharacteristicWrite(g: BluetoothGatt, char: BluetoothGattCharacteristic, status: Int) {- activity.runOnUiThread {+ DeviceController.runOnMain { writing = false if (commandQueue.isNotEmpty()) writeNext() }@@ -212,7 +307,8 @@ class BleManager(private val activity: MainActivity) { value: ByteArray ) { if (char.uuid != NOTIFY_CHAR_UUID || value.size < 2) return- activity.runOnUiThread { dispatch(value) }+ Log.d(TAG, "<- notify ${value.toHex()}")+ DeviceController.runOnMain { dispatch(value) } } } @@ -228,6 +324,7 @@ class BleManager(private val activity: MainActivity) { b0 == 0x50 && b1 == 0x54 -> handlePtFirst(value) // Water-log continuation packet. b1 == 0x06 -> handlePtContinuation(value)+ else -> Log.w(TAG, "dispatch: unhandled packet ${value.toHex()}") } } @@ -239,7 +336,8 @@ class BleManager(private val activity: MainActivity) { // Registration signature response (factory-fresh bottle): prompt for button press. if (b5 == 0x20) {- activity.connectionState.value = "Press the bottle button"+ Log.d(TAG, "RP: signature/registration → press bottle button")+ DeviceController.connectionState.value = "Press the bottle button" return } @@ -249,6 +347,8 @@ class BleManager(private val activity: MainActivity) { curBattery = value[9].toInt() and 0xFF curCharging = value[34].toInt() and 0xFF in intArrayOf(1, 2) curTds = beInt(value, 45)+ curVolumePct = volumePct(beInt(value, 49))+ Log.d(TAG, "RP Vita: temp=$curTemp batt=$curBattery charging=$curCharging tds=$curTds vol%=$curVolumePct") emitStatus() enqueueSyncAndLanguage() return@@ -257,44 +357,87 @@ class BleManager(private val activity: MainActivity) { // Boost full snapshot (temp/tds/volume arrive later via RT). curBattery = value[6].toInt() and 0xFF curCharging = value[31].toInt() and 0xFF in intArrayOf(1, 2)+ Log.d(TAG, "RP Boost: batt=$curBattery charging=$curCharging") emitStatus() enqueueSyncAndLanguage() return } if (b2 == 0x00 && b3 == 0x0F) { // Sync setting acknowledged; now request the water logs.+ Log.d(TAG, "RP: sync ack → request logs") enqueueCommand(CMD_REQUEST_LOGS) return } // Water-log availability flag: value[6]==0 means no offline logs to drain.- if (b5 == 0x06) return- // Registration state on the paired path: prompt the user.+ if (b5 == 0x06) {+ Log.d(TAG, "RP: water-log availability=${if (value.size > 6) value[6].toInt() and 0xFF else -1}")+ return+ }+ // Registration state: value[6]==2 = user must press the bottle button; ==6 = done. if (b5 == 0x1C) {- activity.connectionState.value = "Press the bottle button"+ if (!pendingRegistration) return+ val step = if (value.size > 6) value[6].toInt() and 0xFF else -1+ Log.d(TAG, "RP: registration step=$step")+ when (step) {+ 0x02 -> DeviceController.connectionState.value = "Press the bottle button"+ 0x06 -> {+ // Registration successful (and offline data cleared). Leave registration mode+ // and proceed to the normal data flow so status/logs start syncing.+ Log.d(TAG, "RP: registration successful → requesting bottle data")+ pendingRegistration = false+ DeviceController.connectionState.value = "Connected"+ enqueueCommand(CMD_REQUEST_DATA)+ }+ } } } private fun handleRt(value: ByteArray) { if (value.size < 7) return- when (value[5].toInt() and 0xFF) {+ when (val sel = value[5].toInt() and 0xFF) { 0x01 -> curTemp = value[6].toInt() 0x02 -> curBattery = value[6].toInt() and 0xFF 0x17 -> curCharging = value[6].toInt() and 0xFF in intArrayOf(1, 2) 0x08 -> {- // Volume changed => the user drank; re-request logs to pick it up live.- enqueueCommand(CMD_REQUEST_LOGS)- return+ // Volume changed (the user drank). The bottle reports the new fill level here;+ // offline drink logs are drained separately during the sync handshake.+ if (value.size < 8) return+ curVolumePct = volumePct(beInt(value, 6)) } 0x28 -> { if (value.size < 8) return curTds = beInt(value, 6) } 0x1C -> {- activity.connectionState.value = "Press the bottle button"+ // Registration: user confirmed on the bottle (6==3) or it failed (6==4).+ // Ignore once registration is done — the bottle keeps re-sending "confirmed".+ if (!pendingRegistration) return+ val result = value[6].toInt() and 0xFF+ Log.d(TAG, "RT: registration result=$result")+ when (result) {+ 0x03 -> {+ DeviceController.connectionState.value = "Registering…"+ // Finalize registration: the bottle replies with "successful" (RP 1C/06),+ // which then proceeds to the normal data flow. Send once (it repeats 03).+ if (!registrationClearSent) {+ registrationClearSent = true+ enqueueCommand(CMD_CLEAR_OFFLINE_DATA)+ }+ }+ 0x04 -> DeviceController.connectionState.value = "Registration failed"+ }+ return+ }+ 0xA1 -> {+ Log.d(TAG, "RT: recalibrate result=${value[6].toInt() and 0xFF}")+ return+ }+ else -> {+ Log.d(TAG, "RT: unhandled selector=0x${sel.toString(16)}") return }- else -> return }+ Log.d(TAG, "RT sel=0x${(value[5].toInt() and 0xFF).toString(16)} → temp=$curTemp batt=$curBattery charging=$curCharging tds=$curTds vol%=$curVolumePct") emitStatus() } @@ -302,6 +445,8 @@ class BleManager(private val activity: MainActivity) { if (value.size < 6 || (value[5].toInt() and 0xFF) != 0x06) return expectedLogs = beInt(value, 2) / RECORD_SIZE collected.clear()+ parsedRecords = 0+ Log.d(TAG, "logs: expecting $expectedLogs records") accumulate(value, 6) } @@ -312,14 +457,21 @@ class BleManager(private val activity: MainActivity) { private fun accumulate(value: ByteArray, start: Int) { var i = start while (i + RECORD_SIZE <= value.size) {- collected.add(parseLogRecord(value, i))+ parsedRecords+++ // Byte 12 is a validity flag; only 0 is a real drink record (matches the WaterH app,+ // which counts non-zero records separately and never builds a log entry for them).+ if ((value[i + 12].toInt() and 0xFF) == 0) {+ collected.add(parseLogRecord(value, i))+ } i += RECORD_SIZE }- if (expectedLogs > 0 && collected.size >= expectedLogs) {- collected.forEach { activity.onDrinkLog(it) }+ if (expectedLogs > 0 && parsedRecords >= expectedLogs) {+ Log.d(TAG, "logs: drained parsed=$parsedRecords drinks=${collected.size}")+ collected.forEach { DeviceController.onDrinkLog(it) } // Acknowledge/clear the drained logs from the bottle so each is counted once. enqueueCommand("525000040306" + toHex(expectedLogs * RECORD_SIZE, 4)) expectedLogs = 0+ parsedRecords = 0 collected.clear() } }@@ -345,7 +497,7 @@ class BleManager(private val activity: MainActivity) { } private fun emitStatus() {- activity.onBottleStatus(BottleStatus(curTemp, curTds, curBattery, curCharging))+ DeviceController.onBottleStatus(BottleStatus(curTemp, curTds, curBattery, curCharging, curVolumePct)) } private fun parseLogRecord(b: ByteArray, off: Int): HydrationReading {@@ -356,7 +508,9 @@ class BleManager(private val activity: MainActivity) { val min = b[off + 4].toInt() and 0xFF val sec = b[off + 5].toInt() and 0xFF val amount = beInt(b, off + 6)- val tds = b[off + 8].toInt() and 0xFF+ // TDS is a 2-byte big-endian value at [8..9] (confirmed via parseWaterLog bytecode).+ val tds = beInt(b, off + 8)+ // Raw whole-degree temperature; the WaterH app stores it as temp*10 (tenths). val temp = b[off + 10].toInt() val cal = Calendar.getInstance() cal.clear()@@ -364,6 +518,12 @@ class BleManager(private val activity: MainActivity) { return HydrationReading(amount, cal.timeInMillis, tds, temp) } + /** Fill level as a percentage, matching the WaterH app's `volume / 530 * 100`. */+ private fun volumePct(raw: Int): Int = Math.round(raw / 530f * 100).coerceIn(0, 100)++ private fun ByteArray.toHex(): String =+ joinToString("") { "%02x".format(it.toInt() and 0xFF) }+ private fun beInt(b: ByteArray, off: Int): Int = ((b[off].toInt() and 0xFF) shl 8) or (b[off + 1].toInt() and 0xFF)
things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt b/things/src/main/java/com/vayunmathur/things/platform/DeviceController.ktnew file mode 100644index 0000000000..944458522e--- /dev/null+++ b/things/src/main/java/com/vayunmathur/things/platform/DeviceController.kt@@ -0,0 +1,306 @@+package com.vayunmathur.things.platform++import android.Manifest+import android.bluetooth.BluetoothManager+import android.content.Context+import android.content.SharedPreferences+import android.content.pm.PackageManager+import android.os.Build+import android.os.Handler+import android.os.Looper+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.core.content.ContextCompat+import androidx.core.content.edit+import androidx.health.connect.client.HealthConnectClient+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Process-scoped owner of the BLE managers, device state, and all the bottle/scale logic that+ * used to live on [com.vayunmathur.things.MainActivity].+ *+ * Both [DeviceService] (which keeps the process alive in the background) and the Compose UI read+ * and drive this singleton, so the GATT links survive the Activity being stopped or swiped away.+ *+ * State is held as Compose `mutableStateOf`/`mutableStateListOf` directly (rather than the repo's+ * usual `StateFlow` singletons) because the whole `things` UI already passes these value types as+ * params through `Navigation` → `HomePage`/`DevicesPage`, so this keeps the UI layer unchanged.+ */+object DeviceController {++ private lateinit var appContextRef: Context+ val appContext: Context get() = appContextRef++ private lateinit var bleManager: BleManager+ private lateinit var scaleBleManager: ScaleBleManager++ private val mainHandler = Handler(Looper.getMainLooper())++ // Replaces the Activity's lifecycleScope for the async Health Connect writes.+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ private val prefs: SharedPreferences by lazy {+ appContextRef.getSharedPreferences("hydration", Context.MODE_PRIVATE)+ }++ private var initialized = false++ // Bottle state.+ val connectionState = mutableStateOf("Disconnected")+ val scanning = mutableStateOf(false)+ val discoveredDevices = mutableStateListOf<BleManager.BleDevice>()+ val waterTempC = mutableStateOf<Int?>(null)+ val tds = mutableStateOf<Int?>(null)+ val batteryPct = mutableStateOf<Int?>(null)+ val charging = mutableStateOf(false)+ val bottleVolumePct = mutableStateOf<Int?>(null)+ val bottleLastUpdated = mutableStateOf<Long?>(null)++ // Scale (Renpho Elis 1 / Qingniu) — offline BLE only, no cloud.+ val scaleDevices = mutableStateListOf<ScaleBleManager.ScaleBleDevice>()+ val scaleScanning = mutableStateOf(false)+ val scaleConnectionState = mutableStateOf("Disconnected")+ val scaleRealtimeWeight = mutableStateOf<Double?>(null)+ val scaleWeight = mutableStateOf<Double?>(null)+ val scaleR50 = mutableStateOf<Int?>(null)+ val scaleR500 = mutableStateOf<Int?>(null)+ val scaleMetrics = mutableStateOf<BodyMetrics?>(null)+ val scaleProfile = mutableStateOf(ScaleProfile())+ val scaleSex = mutableStateOf(Sex.Male)+ val scaleAge = mutableStateOf("30")+ val scaleHeight = mutableStateOf("175")+ val scaleAthlete = mutableStateOf(false)++ /** Idempotent. Safe to call from both the service and the Activity. */+ fun init(context: Context) {+ if (initialized) return+ appContextRef = context.applicationContext+ bleManager = BleManager()+ scaleBleManager = ScaleBleManager()+ loadScaleProfile()+ initialized = true+ }++ /** Marshal onto the main thread; replaces the Activity's `runOnUiThread`. */+ fun runOnMain(block: () -> Unit) {+ mainHandler.post(block)+ }++ // --- Callbacks invoked by the BLE managers ---++ fun onDrinkLog(reading: HydrationReading) {+ // Health data is owned by the Health app; this app only writes it to Health Connect and+ // never displays it. Body of the record stays; the on-screen total/list is gone.+ writeHydrationToHealthConnect(reading)+ }++ fun onBottleStatus(status: BottleStatus) {+ waterTempC.value = status.tempC+ tds.value = status.tds+ batteryPct.value = status.batteryPct+ charging.value = status.charging+ bottleVolumePct.value = status.volumePct+ bottleLastUpdated.value = System.currentTimeMillis()+ }++ fun onScaleRealtimeWeight(weight: Double) {+ scaleRealtimeWeight.value = weight+ scaleConnectionState.value = "Weighing... %.1f kg".format(weight)+ }++ fun onScaleMeasurement(+ weightKg: Double,+ r50: Int,+ r500: Int,+ stable: Boolean,+ segmental: SegmentalImpedance? = null,+ ) {+ scaleRealtimeWeight.value = null+ scaleWeight.value = weightKg+ scaleR50.value = if (r50 == 0) null else r50+ scaleR500.value = if (r500 == 0) null else r500+ scaleConnectionState.value = if (stable) "Scale: %.1f kg".format(weightKg) else "Scale: %.1f kg".format(weightKg)+ // Recompute metrics with current profile.+ val profile = ScaleProfile(+ sex = scaleSex.value,+ age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: scaleProfile.value.age,+ heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: scaleProfile.value.heightCm,+ athlete = scaleAthlete.value,+ )+ scaleProfile.value = profile+ val metrics = BodyComposition.calculate(profile, ScaleMeasurement(weightKg, r50, r500, segmental))+ scaleMetrics.value = metrics+ try {+ prefs.edit {+ putString("scale_sex", profile.sex.name)+ putInt("scale_age", profile.age)+ putString("scale_height", profile.heightCm.toString())+ putString("scale_athlete", profile.athlete.toString())+ }+ } catch (_: Exception) {}+ writeBodyCompositionToHealthConnect(weightKg, metrics)+ }++ // --- Actions used by the UI / service ---++ fun startBottleScan() = bleManager.startScan()++ fun connectBottle(address: String) {+ // First-ever connect to this bottle = setup: run the registration handshake (blue LED ++ // button press). Reconnects to the already-remembered bottle skip straight to data sync.+ val isNewDevice = prefs.getString(BOTTLE_ADDRESS_KEY, null) != address+ saveDeviceAddress(BOTTLE_ADDRESS_KEY, address)+ bleManager.connect(address, register = isNewDevice)+ }++ fun disconnectBottle() {+ clearDeviceAddress(BOTTLE_ADDRESS_KEY)+ bleManager.disconnect()+ }++ fun startScaleScan() = scaleBleManager.startScan()++ fun connectScale(address: String) {+ saveDeviceAddress(SCALE_ADDRESS_KEY, address)+ scaleBleManager.connect(address)+ }++ fun disconnectScale() {+ clearDeviceAddress(SCALE_ADDRESS_KEY)+ scaleBleManager.disconnect()+ }++ /** Reconnect to any remembered devices. No-op without permission or a powered-on adapter. */+ fun autoConnectSavedDevices() {+ if (!hasBluetoothConnectPermission() || !bluetoothEnabled()) return+ prefs.getString(BOTTLE_ADDRESS_KEY, null)?.let { bleManager.connect(it) }+ prefs.getString(SCALE_ADDRESS_KEY, null)?.let { scaleBleManager.connect(it) }+ }++ /** Whether at least one device is remembered (drives the service lifecycle). */+ fun hasRememberedDevice(): Boolean =+ prefs.getString(BOTTLE_ADDRESS_KEY, null) != null ||+ prefs.getString(SCALE_ADDRESS_KEY, null) != null++ /** Last-resort cleanup when the service is intentionally stopped. */+ fun closeManagers() {+ bleManager.close()+ scaleBleManager.close()+ }++ fun hasBluetoothConnectPermission(): Boolean =+ Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||+ ContextCompat.checkSelfPermission(appContext, Manifest.permission.BLUETOOTH_CONNECT) ==+ PackageManager.PERMISSION_GRANTED++ private fun bluetoothEnabled(): Boolean =+ appContext.getSystemService(BluetoothManager::class.java)?.adapter?.isEnabled == true++ /**+ * True iff Health Connect is available; otherwise surfaces a message. The actual permission+ * *request* stays in the Activity because it needs an Activity result launcher.+ */+ fun isHealthConnectAvailable(): Boolean {+ val status = HealthConnectHelper.availabilityStatus(appContext)+ if (status != HealthConnectClient.SDK_AVAILABLE) {+ AppMessages.show("Health Connect not available")+ return false+ }+ return true+ }++ fun recalcScaleMetrics() {+ val w = scaleWeight.value ?: return+ val profile = ScaleProfile(+ sex = scaleSex.value,+ age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: scaleProfile.value.age,+ heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: scaleProfile.value.heightCm,+ athlete = scaleAthlete.value,+ )+ scaleProfile.value = profile+ val r50 = scaleR50.value ?: 0+ val r500 = scaleR500.value ?: 0+ scaleMetrics.value = BodyComposition.calculate(profile, ScaleMeasurement(w, r50, r500, null))+ try {+ prefs.edit {+ putString("scale_sex", profile.sex.name)+ putInt("scale_age", profile.age)+ putString("scale_height", profile.heightCm.toString())+ putString("scale_athlete", profile.athlete.toString())+ }+ } catch (_: Exception) {}+ }++ // Remembered device addresses so the app silently reconnects to both devices on launch+ // instead of making the user scan and tap every time it is reopened.+ private fun saveDeviceAddress(key: String, address: String) {+ prefs.edit { putString(key, address) }+ }++ private fun clearDeviceAddress(key: String) {+ prefs.edit { remove(key) }+ }++ private fun loadScaleProfile() {+ try {+ val sexName = prefs.getString("scale_sex", null)+ if (sexName != null) scaleSex.value = Sex.valueOf(sexName)+ val ageInt = prefs.getInt("scale_age", -1)+ if (ageInt != -1) scaleAge.value = ageInt.toString()+ val hStr = prefs.getString("scale_height", null)+ if (hStr != null) scaleHeight.value = hStr+ val ath = prefs.getString("scale_athlete", null)+ if (ath != null) scaleAthlete.value = ath.toBoolean()+ scaleProfile.value = ScaleProfile(+ sex = scaleSex.value,+ age = scaleAge.value.toIntOrNull()?.coerceIn(3, 80) ?: 30,+ heightCm = scaleHeight.value.toDoubleOrNull()?.coerceIn(40.0, 240.0) ?: 175.0,+ athlete = scaleAthlete.value,+ )+ } catch (_: Exception) {}+ }++ private fun writeHydrationToHealthConnect(reading: HydrationReading) {+ // Check Health Connect availability synchronously; writes are async.+ val status = HealthConnectHelper.availabilityStatus(appContext)+ if (status != HealthConnectClient.SDK_AVAILABLE) return+ scope.launch {+ try {+ val client = HealthConnectClient.getOrCreate(appContext)+ if (!HealthConnectHelper.hasAllPermissions(client)) return@launch+ val instant = java.time.Instant.ofEpochMilli(reading.epochMillis)+ HealthConnectHelper.writeHydration(client, instant, reading.amountMl / 1000.0)+ } catch (_: Exception) {}+ }+ }++ private fun writeBodyCompositionToHealthConnect(weightKg: Double, metrics: BodyMetrics) {+ val status = HealthConnectHelper.availabilityStatus(appContext)+ if (status != HealthConnectClient.SDK_AVAILABLE) return+ scope.launch {+ try {+ val client = HealthConnectClient.getOrCreate(appContext)+ if (!HealthConnectHelper.hasAllPermissions(client)) return@launch+ val instant = java.time.Instant.now()+ val waterMassKg = if (metrics.waterPercent > 0) weightKg * metrics.waterPercent / 100.0 else null+ HealthConnectHelper.writeBodyComposition(+ client = client,+ instant = instant,+ weightKg = weightKg,+ bodyFatPct = metrics.bodyFatPercent.takeIf { it > 0 },+ leanMassKg = metrics.lbmKg.takeIf { it > 0 },+ boneMassKg = metrics.boneKg.takeIf { it > 0 },+ bodyWaterMassKg = waterMassKg,+ bmrKcal = metrics.bmrKcal.takeIf { it > 0 },+ )+ } catch (_: Exception) {}+ }+ }++ private const val BOTTLE_ADDRESS_KEY = "bottle_address"+ private const val SCALE_ADDRESS_KEY = "scale_address"+}
things/src/main/java/com/vayunmathur/things/platform/DeviceService.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/DeviceService.kt b/things/src/main/java/com/vayunmathur/things/platform/DeviceService.ktnew file mode 100644index 0000000000..d2f3d30606--- /dev/null+++ b/things/src/main/java/com/vayunmathur/things/platform/DeviceService.kt@@ -0,0 +1,104 @@+package com.vayunmathur.things.platform++import android.app.Notification+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.IBinder+import androidx.core.app.NotificationCompat+import com.vayunmathur.library.util.ensureNotificationChannel+import com.vayunmathur.things.MainActivity+import com.vayunmathur.things.R++/**+ * Foreground service whose only job is to keep the process (and therefore the GATT connections+ * owned by [DeviceController]) alive while the Activity is stopped or swiped away, and to drive+ * background auto-reconnect. Modeled on findfamily's `LocationTrackingService`.+ */+class DeviceService : Service() {++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onCreate() {+ super.onCreate()+ DeviceController.init(applicationContext)+ ensureNotificationChannel(+ CHANNEL_ID,+ getString(R.string.device_channel_name),+ NotificationManager.IMPORTANCE_LOW,+ getString(R.string.device_channel_desc),+ )+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ val notification = createNotification()+ // A connectedDevice foreground start requires a Bluetooth permission; if it was revoked+ // since we were scheduled, satisfy the foreground-start contract with a type-less+ // startForeground and then stop, mirroring the location template.+ if (!DeviceController.hasBluetoothConnectPermission()) {+ try {+ startForeground(NOTIFICATION_ID, notification)+ } catch (_: Exception) {+ }+ stopSelf()+ return START_NOT_STICKY+ }++ try {+ startForeground(+ NOTIFICATION_ID,+ notification,+ ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,+ )+ } catch (_: Exception) {+ stopSelf()+ return START_NOT_STICKY+ }++ DeviceController.autoConnectSavedDevices()+ return START_STICKY+ }++ override fun onDestroy() {+ super.onDestroy()+ // Last-resort cleanup when we're intentionally stopped (both devices forgotten).+ DeviceController.closeManagers()+ stopForeground(STOP_FOREGROUND_REMOVE)+ }++ private fun createNotification(): Notification {+ val pendingIntent = PendingIntent.getActivity(+ this, 0,+ Intent(this, MainActivity::class.java),+ PendingIntent.FLAG_IMMUTABLE,+ )+ return NotificationCompat.Builder(this, CHANNEL_ID)+ .setContentTitle(getString(R.string.device_notification_title))+ .setContentText(getString(R.string.device_notification_text))+ .setSmallIcon(R.drawable.ic_launcher_foreground)+ .setOngoing(true)+ .setContentIntent(pendingIntent)+ .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)+ .build()+ }++ companion object {+ private const val CHANNEL_ID = "things_device_channel"+ private const val NOTIFICATION_ID = 201++ fun start(context: Context) {+ context.applicationContext.startForegroundService(+ Intent(context.applicationContext, DeviceService::class.java)+ )+ }++ fun stop(context: Context) {+ context.applicationContext.stopService(+ Intent(context.applicationContext, DeviceService::class.java)+ )+ }+ }+}
things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt
diff --git a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.ktindex 6cbf80803d..1fe0aecaed 100644--- a/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt+++ b/things/src/main/java/com/vayunmathur/things/platform/ScaleBleManager.kt@@ -12,7 +12,6 @@ import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanSettings import android.os.Build-import com.vayunmathur.things.MainActivity import java.util.UUID /**@@ -35,7 +34,7 @@ import java.util.UUID * No wifi/internet/cloud/login — pure on-device BLE + BodyComposition math. */ @SuppressLint("MissingPermission")-class ScaleBleManager(private val activity: MainActivity) {+class ScaleBleManager { companion object { // Primary Qingniu GATT (covers Elis 1)@@ -57,11 +56,16 @@ class ScaleBleManager(private val activity: MainActivity) { data class ScaleBleDevice(val name: String, val address: String) - private val bluetoothManager = activity.getSystemService(BluetoothManager::class.java)+ private val bluetoothManager = DeviceController.appContext.getSystemService(BluetoothManager::class.java) private val adapter = bluetoothManager.adapter private val scanner get() = adapter.bluetoothLeScanner private var gatt: BluetoothGatt? = null + // See BleManager: keep connect() idempotent so repeated auto-connect calls don't stack a+ // second GATT client, and drive passive background re-establishment on an unexpected drop.+ private var currentAddress: String? = null+ private var intentionalDisconnect = false+ private var weightRatio = 10.0 private var notifyChar: UUID = CHAR_FFE1 private var writeChar: UUID = CHAR_FFE3@@ -85,37 +89,47 @@ class ScaleBleManager(private val activity: MainActivity) { val name = result.device.name if (!isScaleName(name)) return val addr = result.device.address- if (activity.scaleDevices.none { it.address == addr }) {- activity.scaleDevices.add(ScaleBleDevice(name ?: "Scale", addr))+ if (DeviceController.scaleDevices.none { it.address == addr }) {+ DeviceController.scaleDevices.add(ScaleBleDevice(name ?: "Scale", addr)) } } } fun startScan() {- activity.scaleDevices.clear()- activity.scaleScanning.value = true+ DeviceController.scaleDevices.clear()+ DeviceController.scaleScanning.value = true val settings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build() scanner?.startScan(null, settings, scanCallback)- activity.scaleConnectionState.value = "Scanning scales..."+ DeviceController.scaleConnectionState.value = "Scanning scales..." } fun stopScan() { scanner?.stopScan(scanCallback)- activity.scaleScanning.value = false+ DeviceController.scaleScanning.value = false } @Suppress("DEPRECATION") fun connect(address: String) {+ if (gatt != null && currentAddress == address) return+ close()+ currentAddress = address+ intentionalDisconnect = false+ openGatt(address, autoConnect = false)+ }++ private fun openGatt(address: String, autoConnect: Boolean) { scanner?.stopScan(scanCallback)- activity.scaleScanning.value = false- activity.scaleConnectionState.value = "Connecting scale..."+ DeviceController.scaleScanning.value = false+ DeviceController.scaleConnectionState.value = "Connecting scale..." val device = adapter.getRemoteDevice(address)- gatt = device.connectGatt(activity, false, gattCallback, BluetoothDevice.TRANSPORT_LE)+ gatt = device.connectGatt(DeviceController.appContext, autoConnect, gattCallback, BluetoothDevice.TRANSPORT_LE) } fun disconnect() {+ intentionalDisconnect = true+ currentAddress = null gatt?.disconnect() } @@ -134,17 +148,27 @@ class ScaleBleManager(private val activity: MainActivity) { private val gattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {- activity.runOnUiThread {+ DeviceController.runOnMain { when (newState) { BluetoothProfile.STATE_CONNECTED -> { resetPacketState()- activity.scaleConnectionState.value = "Discovering services..."+ DeviceController.scaleConnectionState.value = "Discovering services..." g.discoverServices() } BluetoothProfile.STATE_DISCONNECTED -> {- activity.scaleConnectionState.value = "Disconnected"- activity.scaleDevices.clear()+ DeviceController.scaleConnectionState.value = "Disconnected"+ DeviceController.scaleDevices.clear() resetPacketState()+ val g2 = gatt+ gatt = null+ g2?.let {+ it.close()+ refreshCache(it)+ }+ val addr = currentAddress+ if (!intentionalDisconnect && addr != null) {+ openGatt(addr, autoConnect = true)+ } } } }@@ -155,13 +179,13 @@ class ScaleBleManager(private val activity: MainActivity) { // Prefer FFE0/FFE1, fall back to FFF0/FFF1 if that's what the firmware exposes. val svc = g.getService(SERVICE_FFE0) ?: g.getService(SERVICE_FFF0) if (svc == null) {- activity.runOnUiThread { activity.scaleConnectionState.value = "Scale service not found" }+ DeviceController.runOnMain { DeviceController.scaleConnectionState.value = "Scale service not found" } return } serviceUuid = svc.uuid val ch = svc.getCharacteristic(CHAR_FFE1) ?: svc.getCharacteristic(CHAR_FFF1) if (ch == null) {- activity.runOnUiThread { activity.scaleConnectionState.value = "Scale notifying char not found" }+ DeviceController.runOnMain { DeviceController.scaleConnectionState.value = "Scale notifying char not found" } return } notifyChar = ch.uuid@@ -180,7 +204,7 @@ class ScaleBleManager(private val activity: MainActivity) { } override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {- activity.runOnUiThread { activity.scaleConnectionState.value = "Connected — step on scale" }+ DeviceController.runOnMain { DeviceController.scaleConnectionState.value = "Connected — step on scale" } // Scale sends c=18 scale-info unsolicited; no write needed to start. We just listen. } @@ -191,7 +215,7 @@ class ScaleBleManager(private val activity: MainActivity) { ) { if (characteristic.uuid != notifyChar) return if (value.isEmpty()) return- activity.runOnUiThread { dispatch(value) }+ DeviceController.runOnMain { dispatch(value) } } } @@ -205,7 +229,7 @@ class ScaleBleManager(private val activity: MainActivity) { // We treat stored the same as live: decode weight, notify. if (value.size >= 11) { val w = decodeWeight(twoByteInt(value[9], value[10]), weightRatio)- if (w > 0) activity.onScaleMeasurement(w, 0, 0, false)+ if (w > 0) DeviceController.onScaleMeasurement(w, 0, 0, false) } } }@@ -216,7 +240,7 @@ class ScaleBleManager(private val activity: MainActivity) { weightRatio = if ((v[10].toInt() and 0x01) == 1) 100.0 else 10.0 // Units etc. available at v[10] bits, v[16] lbPrecision, v[17] unit mask. // We keep ratio for weight decode; other bytes inform display only.- activity.scaleConnectionState.value = "Connected — step on scale"+ DeviceController.scaleConnectionState.value = "Connected — step on scale" } private fun handleMeasure(v: ByteArray) {@@ -227,18 +251,18 @@ class ScaleBleManager(private val activity: MainActivity) { when (c2) { 0 -> { // Real-time streaming weight- if (weight > 0) activity.onScaleRealtimeWeight(weight)+ if (weight > 0) DeviceController.onScaleRealtimeWeight(weight) } 1 -> { // Stabilized weight + 4-electrode impedance at 6..9 (fourResTwoByte2Int) if (v.size < 10) return val r50 = fourResTwoByte2Int(v[6], v[7]) val r500 = fourResTwoByte2Int(v[8], v[9])- activity.onScaleMeasurement(weight, r50, r500, true)+ DeviceController.onScaleMeasurement(weight, r50, r500, true) } 2 -> { // Overweight / error — treat as no-impedance measurement- activity.onScaleMeasurement(weight, 0, 0, true)+ DeviceController.onScaleMeasurement(weight, 0, 0, true) } else -> { // 8-electrode burst: top nibble=count, low nibble=current (QNDecoderImpl:472)@@ -273,7 +297,7 @@ class ScaleBleManager(private val activity: MainActivity) { ) val r50seg = (lh20k + rh20k).toInt() val r500seg = (lh100k + rh100k).toInt()- activity.onScaleMeasurement(weight, r50seg, r500seg, true, seg)+ DeviceController.onScaleMeasurement(weight, r50seg, r500seg, true, seg) } } }
things/src/main/java/com/vayunmathur/things/ui/DevicesPage.kt
diff --git a/things/src/main/java/com/vayunmathur/things/ui/DevicesPage.kt b/things/src/main/java/com/vayunmathur/things/ui/DevicesPage.ktnew file mode 100644index 0000000000..4255c2e521--- /dev/null+++ b/things/src/main/java/com/vayunmathur/things/ui/DevicesPage.kt@@ -0,0 +1,143 @@+package com.vayunmathur.things.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.things.R+import com.vayunmathur.things.platform.BleManager+import com.vayunmathur.things.platform.ScaleBleManager++/**+ * Device management: scan for, connect to, and disconnect both BLE devices, plus the Health Connect+ * permission setup. Shows a back arrow only when it was pushed over [HomePage] (i.e. a device is+ * connected); as the cold-start root it shows none.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DevicesPage(+ connectionState: String,+ scanning: Boolean,+ discoveredDevices: List<BleManager.BleDevice>,+ onScanClick: () -> Unit,+ onDeviceClick: (BleManager.BleDevice) -> Unit,+ onDisconnectClick: () -> Unit,+ scaleConnectionState: String,+ scaleScanning: Boolean,+ scaleDevices: List<ScaleBleManager.ScaleBleDevice>,+ onScaleScanClick: () -> Unit,+ onScaleDeviceClick: (ScaleBleManager.ScaleBleDevice) -> Unit,+ onScaleDisconnectClick: () -> Unit,+ onHealthConnectClick: () -> Unit,+ onNavigateBack: (() -> Unit)?,+) {+ AppScaffold(+ title = stringResource(R.string.devices),+ onNavigateBack = onNavigateBack,+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ LazyColumn(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding)+ .padding(horizontal = 16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ // Bottle+ item { Text(stringResource(R.string.bottle_status), style = MaterialTheme.typography.titleMedium) }+ item {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(connectionState, style = MaterialTheme.typography.titleSmall)+ if (connectionState == "Connected") {+ OutlinedButton(onClick = onDisconnectClick) { Text(stringResource(R.string.disconnect)) }+ } else {+ Button(onClick = onScanClick, enabled = !scanning) { Text(stringResource(R.string.scan)) }+ }+ }+ }+ if (discoveredDevices.isNotEmpty() && connectionState != "Connected") {+ item { Text(stringResource(R.string.devices_found), style = MaterialTheme.typography.labelLarge) }+ items(discoveredDevices) { device ->+ Card(+ modifier = Modifier+ .fillMaxWidth()+ .clickable { onDeviceClick(device) }+ ) {+ Column(modifier = Modifier.padding(12.dp)) {+ Text(device.name, style = MaterialTheme.typography.bodyLarge)+ Text(device.address, style = MaterialTheme.typography.bodySmall)+ }+ }+ }+ }++ item { HorizontalDivider() }++ // Scale+ item { Text(stringResource(R.string.scale_title), style = MaterialTheme.typography.titleMedium) }+ item { Text(stringResource(R.string.scale_subtitle), style = MaterialTheme.typography.bodySmall) }+ item {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(scaleConnectionState, style = MaterialTheme.typography.titleSmall)+ if (scaleConnected(scaleConnectionState)) {+ OutlinedButton(onClick = onScaleDisconnectClick) { Text(stringResource(R.string.disconnect)) }+ } else {+ Button(onClick = onScaleScanClick, enabled = !scaleScanning) { Text(stringResource(R.string.scan_scale)) }+ }+ }+ }+ if (scaleDevices.isNotEmpty() && !scaleConnected(scaleConnectionState)) {+ item { Text(stringResource(R.string.devices_found), style = MaterialTheme.typography.labelLarge) }+ items(scaleDevices) { device ->+ Card(+ modifier = Modifier+ .fillMaxWidth()+ .clickable { onScaleDeviceClick(device) }+ ) {+ Column(modifier = Modifier.padding(12.dp)) {+ Text(device.name, style = MaterialTheme.typography.bodyLarge)+ Text(device.address, style = MaterialTheme.typography.bodySmall)+ }+ }+ }+ }++ item { HorizontalDivider() }+ item {+ OutlinedButton(onClick = onHealthConnectClick, modifier = Modifier.fillMaxWidth()) {+ Text(stringResource(R.string.health_connect))+ }+ }+ }+ }+}++private fun scaleConnected(state: String): Boolean =+ state.startsWith("Scale: ") || state.contains("step on") || state.startsWith("Weighing")
things/src/main/java/com/vayunmathur/things/ui/HomePage.kt
diff --git a/things/src/main/java/com/vayunmathur/things/ui/HomePage.kt b/things/src/main/java/com/vayunmathur/things/ui/HomePage.ktnew file mode 100644index 0000000000..2d0994f987--- /dev/null+++ b/things/src/main/java/com/vayunmathur/things/ui/HomePage.kt@@ -0,0 +1,248 @@+package com.vayunmathur.things.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.Checkbox+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconWidgets+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.things.R+import com.vayunmathur.things.platform.Sex++/**+ * The landing screen once a device is connected: non-health device telemetry only.+ *+ * Health data (hydration volume, weight, body composition) is written to Health Connect by+ * [com.vayunmathur.things.MainActivity] and read by the Health app; this app deliberately does not+ * display any of it. What remains here is device/water telemetry (battery, charging, temperature,+ * purity) and the scale profile inputs, which are *inputs* to the body-composition calc rather than+ * health readouts.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun HomePage(+ bottleConnected: Boolean,+ tempC: Int?,+ tds: Int?,+ batteryPct: Int?,+ charging: Boolean,+ volumePct: Int?,+ lastUpdatedMillis: Long?,+ scaleConnected: Boolean,+ scaleConnectionState: String,+ scaleSex: Sex,+ scaleAge: String,+ scaleHeight: String,+ scaleAthlete: Boolean,+ onScaleSexChange: (Sex) -> Unit,+ onScaleAgeChange: (String) -> Unit,+ onScaleHeightChange: (String) -> Unit,+ onScaleAthleteChange: (Boolean) -> Unit,+ onOpenDevices: () -> Unit,+) {+ AppScaffold(+ title = stringResource(R.string.app_name),+ scrollBehavior = appBarScrollBehavior(),+ actions = {+ IconButton(onClick = onOpenDevices) { IconWidgets() }+ },+ ) { padding ->+ LazyColumn(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding)+ .padding(horizontal = 16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ if (bottleConnected) {+ item {+ BottleStatusCard(+ tempC = tempC,+ tds = tds,+ batteryPct = batteryPct,+ charging = charging,+ volumePct = volumePct,+ lastUpdatedMillis = lastUpdatedMillis,+ )+ }+ }++ if (scaleConnected) {+ item {+ ScaleTelemetryCard(+ connectionState = scaleConnectionState,+ sex = scaleSex,+ age = scaleAge,+ height = scaleHeight,+ athlete = scaleAthlete,+ onSexChange = onScaleSexChange,+ onAgeChange = onScaleAgeChange,+ onHeightChange = onScaleHeightChange,+ onAthleteChange = onScaleAthleteChange,+ )+ }+ }++ if (!bottleConnected && !scaleConnected) {+ item {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 48.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Text(+ stringResource(R.string.no_devices),+ style = MaterialTheme.typography.bodyLarge+ )+ Button(onClick = onOpenDevices) { Text(stringResource(R.string.open_devices)) }+ }+ }+ }+ }+ }+}++@Composable+private fun BottleStatusCard(+ tempC: Int?,+ tds: Int?,+ batteryPct: Int?,+ charging: Boolean,+ volumePct: Int?,+ lastUpdatedMillis: Long?,+) {+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ Text(+ stringResource(R.string.bottle_status),+ style = MaterialTheme.typography.titleSmall+ )+ val hasData = tempC != null || tds != null || batteryPct != null || volumePct != null+ if (!hasData) {+ Text(+ stringResource(R.string.waiting_for_data),+ style = MaterialTheme.typography.bodyMedium+ )+ } else {+ if (batteryPct != null) {+ val battery = if (charging) {+ stringResource(R.string.battery_charging, batteryPct)+ } else {+ stringResource(R.string.battery_pct, batteryPct)+ }+ StatusRow(stringResource(R.string.label_battery), battery)+ }+ if (volumePct != null) {+ StatusRow(stringResource(R.string.label_water_level), stringResource(R.string.percent, volumePct))+ }+ if (tempC != null) {+ StatusRow(stringResource(R.string.label_temperature), stringResource(R.string.temperature_c, tempC))+ }+ if (tds != null) {+ StatusRow(stringResource(R.string.label_purity), stringResource(R.string.purity_ppm, tds))+ }+ }+ if (lastUpdatedMillis != null) {+ val time = remember(lastUpdatedMillis) { formatClockTime(lastUpdatedMillis) }+ Text(+ stringResource(R.string.last_updated, time),+ style = MaterialTheme.typography.labelSmall+ )+ }+ }+ }+}++@Composable+private fun StatusRow(label: String, value: String) {+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ Text(label, style = MaterialTheme.typography.bodyMedium)+ Text(value, style = MaterialTheme.typography.bodyMedium)+ }+}++private fun formatClockTime(millis: Long): String =+ java.time.Instant.ofEpochMilli(millis)+ .atZone(java.time.ZoneId.systemDefault())+ .toLocalTime()+ .format(java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss"))++@Composable+private fun ScaleTelemetryCard(+ connectionState: String,+ sex: Sex,+ age: String,+ height: String,+ athlete: Boolean,+ onSexChange: (Sex) -> Unit,+ onAgeChange: (String) -> Unit,+ onHeightChange: (String) -> Unit,+ onAthleteChange: (Boolean) -> Unit,+) {+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(stringResource(R.string.scale_title), style = MaterialTheme.typography.titleSmall)+ Text(connectionState, style = MaterialTheme.typography.bodyMedium)++ Text(stringResource(R.string.scale_profile), style = MaterialTheme.typography.titleSmall)+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ FilterChip(selected = sex == Sex.Male, onClick = { onSexChange(Sex.Male) }, label = { Text(stringResource(R.string.sex_male)) })+ FilterChip(selected = sex == Sex.Female, onClick = { onSexChange(Sex.Female) }, label = { Text(stringResource(R.string.sex_female)) })+ }+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {+ OutlinedTextField(+ value = age,+ onValueChange = onAgeChange,+ label = { Text(stringResource(R.string.age)) },+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+ singleLine = true,+ modifier = Modifier.weight(1f)+ )+ OutlinedTextField(+ value = height,+ onValueChange = onHeightChange,+ label = { Text(stringResource(R.string.height_cm)) },+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+ singleLine = true,+ modifier = Modifier.weight(1f)+ )+ }+ Row(verticalAlignment = Alignment.CenterVertically) {+ Checkbox(checked = athlete, onCheckedChange = onAthleteChange)+ Text(stringResource(R.string.athlete), style = MaterialTheme.typography.bodyMedium)+ }+ Text(+ stringResource(R.string.syncs_to_health_connect),+ style = MaterialTheme.typography.bodySmall+ )+ }+ }+}
things/src/main/java/com/vayunmathur/things/ui/ThingsApp.kt
diff --git a/things/src/main/java/com/vayunmathur/things/ui/ThingsApp.kt b/things/src/main/java/com/vayunmathur/things/ui/ThingsApp.ktdeleted file mode 100644index 25b734cfff..0000000000--- a/things/src/main/java/com/vayunmathur/things/ui/ThingsApp.kt+++ /dev/null@@ -1,384 +0,0 @@-package com.vayunmathur.things.ui--import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.text.KeyboardOptions-import androidx.compose.runtime.Composable-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.input.KeyboardType-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.Checkbox-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.FilterChip-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.LinearProgressIndicator-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.things.R-import com.vayunmathur.things.platform.BleManager-import com.vayunmathur.things.platform.BodyMetrics-import com.vayunmathur.things.platform.ScaleBleManager-import com.vayunmathur.things.platform.Sex--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun ThingsApp(- totalMl: Int,- goalMl: Int,- messages: List<String>,- connectionState: String,- scanning: Boolean,- discoveredDevices: List<BleManager.BleDevice>,- tempC: Int?,- tds: Int?,- batteryPct: Int?,- charging: Boolean,- onScanClick: () -> Unit,- onDeviceClick: (BleManager.BleDevice) -> Unit,- onDisconnectClick: () -> Unit,- scaleWeight: Double?,- scaleRealtimeWeight: Double?,- scaleR50: Int?,- scaleConnectionState: String,- scaleScanning: Boolean,- scaleDevices: List<ScaleBleManager.ScaleBleDevice>,- scaleMetrics: BodyMetrics?,- scaleSex: Sex,- scaleAge: String,- scaleHeight: String,- scaleAthlete: Boolean,- onScaleScanClick: () -> Unit,- onScaleDeviceClick: (ScaleBleManager.ScaleBleDevice) -> Unit,- onScaleDisconnectClick: () -> Unit,- onScaleSexChange: (Sex) -> Unit,- onScaleAgeChange: (String) -> Unit,- onScaleHeightChange: (String) -> Unit,- onScaleAthleteChange: (Boolean) -> Unit,- onHealthConnectClick: () -> Unit,-) {- AppScaffold(- title = stringResource(R.string.hydration),- scrollBehavior = appBarScrollBehavior(),- ) { padding ->- LazyColumn(- modifier = Modifier- .fillMaxSize()- .padding(padding)- .padding(horizontal = 16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- item { HydrationCard(totalMl = totalMl, goalMl = goalMl) }-- if (connectionState == "Connected" && (tempC != null || tds != null || batteryPct != null)) {- item { BottleStatusCard(tempC = tempC, tds = tds, batteryPct = batteryPct, charging = charging) }- }-- item {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(connectionState, style = MaterialTheme.typography.titleMedium)- if (connectionState == "Connected") {- OutlinedButton(onClick = onDisconnectClick) { Text(stringResource(R.string.disconnect)) }- } else {- Button(onClick = onScanClick, enabled = !scanning) { Text(stringResource(R.string.scan)) }- }- }- }-- if (discoveredDevices.isNotEmpty() && connectionState != "Connected") {- item { Text(stringResource(R.string.devices_found), style = MaterialTheme.typography.labelLarge) }- items(discoveredDevices) { device ->- Card(- modifier = Modifier- .fillMaxWidth()- .clickable { onDeviceClick(device) }- ) {- Column(modifier = Modifier.padding(12.dp)) {- Text(device.name, style = MaterialTheme.typography.bodyLarge)- Text(device.address, style = MaterialTheme.typography.bodySmall)- }- }- }- }-- if (messages.isNotEmpty()) {- item { HorizontalDivider() }- item { Text(stringResource(R.string.today_s_drinks), style = MaterialTheme.typography.titleSmall) }- items(messages) { msg ->- Text(- text = msg,- style = MaterialTheme.typography.bodyMedium,- modifier = Modifier.padding(vertical = 4.dp)- )- }- }-- item { HorizontalDivider() }- item {- OutlinedButton(onClick = onHealthConnectClick, modifier = Modifier.fillMaxWidth()) {- Text(stringResource(R.string.health_connect))- }- }- item { ScaleSection(- weight = scaleWeight,- realtimeWeight = scaleRealtimeWeight,- r50 = scaleR50,- connectionState = scaleConnectionState,- scanning = scaleScanning,- devices = scaleDevices,- metrics = scaleMetrics,- sex = scaleSex,- age = scaleAge,- height = scaleHeight,- athlete = scaleAthlete,- onScanClick = onScaleScanClick,- onDeviceClick = onScaleDeviceClick,- onDisconnectClick = onScaleDisconnectClick,- onSexChange = onScaleSexChange,- onAgeChange = onScaleAgeChange,- onHeightChange = onScaleHeightChange,- onAthleteChange = onScaleAthleteChange,- ) }- }- }-}--@Composable-private fun ScaleSection(- weight: Double?,- realtimeWeight: Double?,- r50: Int?,- connectionState: String,- scanning: Boolean,- devices: List<ScaleBleManager.ScaleBleDevice>,- metrics: BodyMetrics?,- sex: Sex,- age: String,- height: String,- athlete: Boolean,- onScanClick: () -> Unit,- onDeviceClick: (ScaleBleManager.ScaleBleDevice) -> Unit,- onDisconnectClick: () -> Unit,- onSexChange: (Sex) -> Unit,- onAgeChange: (String) -> Unit,- onHeightChange: (String) -> Unit,- onAthleteChange: (Boolean) -> Unit,-) {- Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {- Text(stringResource(R.string.scale_title), style = MaterialTheme.typography.titleMedium)- Text(stringResource(R.string.scale_subtitle), style = MaterialTheme.typography.bodySmall)-- Card(modifier = Modifier.fillMaxWidth()) {- Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text(stringResource(R.string.scale_profile), style = MaterialTheme.typography.titleSmall)- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- FilterChip(selected = sex == Sex.Male, onClick = { onSexChange(Sex.Male) }, label = { Text(stringResource(R.string.sex_male)) })- FilterChip(selected = sex == Sex.Female, onClick = { onSexChange(Sex.Female) }, label = { Text(stringResource(R.string.sex_female)) })- }- Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {- OutlinedTextField(- value = age,- onValueChange = onAgeChange,- label = { Text(stringResource(R.string.age)) },- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),- singleLine = true,- modifier = Modifier.weight(1f)- )- OutlinedTextField(- value = height,- onValueChange = onHeightChange,- label = { Text(stringResource(R.string.height_cm)) },- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),- singleLine = true,- modifier = Modifier.weight(1f)- )- }- Row(verticalAlignment = Alignment.CenterVertically) {- Checkbox(checked = athlete, onCheckedChange = onAthleteChange)- Text(stringResource(R.string.athlete), style = MaterialTheme.typography.bodyMedium)- }- }- }-- if (realtimeWeight != null) {- Card(modifier = Modifier.fillMaxWidth()) {- Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {- Text(stringResource(R.string.weighing), style = MaterialTheme.typography.titleSmall)- Text("%.1f kg".format(realtimeWeight), style = MaterialTheme.typography.displaySmall)- }- }- } else if (weight != null) {- Card(modifier = Modifier.fillMaxWidth()) {- Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {- Text(stringResource(R.string.weight), style = MaterialTheme.typography.titleSmall)- Text("%.1f kg".format(weight), style = MaterialTheme.typography.displaySmall)- if (r50 != null) {- Text(stringResource(R.string.impedance, r50), style = MaterialTheme.typography.bodySmall)- } else {- Text(stringResource(R.string.no_impedance), style = MaterialTheme.typography.bodySmall)- }- }- }- }-- if (metrics != null) {- BodyMetricsCard(metrics = metrics)- }-- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(connectionState, style = MaterialTheme.typography.titleSmall)- if (connectionState.startsWith("Scale: ") || connectionState.contains("step on")) {- OutlinedButton(onClick = onDisconnectClick) { Text(stringResource(R.string.disconnect)) }- } else {- Button(onClick = onScanClick, enabled = !scanning) { Text(stringResource(R.string.scan_scale)) }- }- }-- if (devices.isNotEmpty() && !connectionState.startsWith("Scale:") && !connectionState.contains("step on")) {- Text(stringResource(R.string.devices_found), style = MaterialTheme.typography.labelLarge)- devices.forEach { device ->- Card(- modifier = Modifier- .fillMaxWidth()- .clickable { onDeviceClick(device) }- ) {- Column(modifier = Modifier.padding(12.dp)) {- Text(device.name, style = MaterialTheme.typography.bodyLarge)- Text(device.address, style = MaterialTheme.typography.bodySmall)- }- }- }- }- }-}--@Composable-private fun BodyMetricsCard(metrics: BodyMetrics) {- Card(modifier = Modifier.fillMaxWidth()) {- Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {- Text(stringResource(R.string.body_composition), style = MaterialTheme.typography.titleSmall)- MetricRow(stringResource(R.string.bmi), "%.1f".format(metrics.bmi))- if (metrics.bodyFatPercent != 0.0) {- MetricRow(stringResource(R.string.body_fat), "%.1f%%".format(metrics.bodyFatPercent))- MetricRow(stringResource(R.string.fat_mass), "%.1f kg".format(metrics.fatMassKg))- MetricRow(stringResource(R.string.lbm), "%.1f kg".format(metrics.lbmKg))- MetricRow(stringResource(R.string.water), "%.1f%%".format(metrics.waterPercent))- MetricRow(stringResource(R.string.muscle), "%.1f%% (%.1f kg)".format(metrics.musclePercent, metrics.muscleMassKg))- MetricRow(stringResource(R.string.bone), "%.1f kg".format(metrics.boneKg))- MetricRow(stringResource(R.string.protein), "%.1f%% (%.1f kg)".format(metrics.proteinPercent, metrics.proteinKg))- MetricRow(stringResource(R.string.bmr), "%d kcal".format(metrics.bmrKcal))- MetricRow(stringResource(R.string.visceral), "%d".format(metrics.visceralLevel))- MetricRow(stringResource(R.string.body_age), "%d".format(metrics.bodyAge))- MetricRow(stringResource(R.string.score), "%d".format(metrics.score))- if (metrics.segmental != null) {- Spacer(Modifier.height(4.dp))- Text(stringResource(R.string.segmental), style = MaterialTheme.typography.labelMedium)- MetricRow(stringResource(R.string.seg_arms), "%.1f / %.1f kg fat".format(metrics.segmental.fatRh, metrics.segmental.fatLh))- MetricRow(stringResource(R.string.seg_legs), "%.1f / %.1f kg fat".format(metrics.segmental.fatRf, metrics.segmental.fatLf))- MetricRow(stringResource(R.string.seg_trunk), "%.1f kg fat".format(metrics.segmental.fatT))- }- } else {- Text(stringResource(R.string.bmi_only), style = MaterialTheme.typography.bodySmall)- Text(stringResource(R.string.bmi_hint), style = MaterialTheme.typography.bodySmall)- }- }- }-}--@Composable-private fun MetricRow(label: String, value: String) {- Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {- Text(label, style = MaterialTheme.typography.bodyMedium)- Text(value, style = MaterialTheme.typography.bodyMedium)- }-}--@Composable-private fun BottleStatusCard(tempC: Int?, tds: Int?, batteryPct: Int?, charging: Boolean) {- Card(modifier = Modifier.fillMaxWidth()) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(16.dp),- verticalArrangement = Arrangement.spacedBy(6.dp)- ) {- Text(- stringResource(R.string.bottle_status),- style = MaterialTheme.typography.titleSmall- )- if (tempC != null) {- Text(- stringResource(R.string.temperature_c, tempC),- style = MaterialTheme.typography.bodyMedium- )- }- if (tds != null) {- Text(- stringResource(R.string.purity_ppm, tds),- style = MaterialTheme.typography.bodyMedium- )- }- if (batteryPct != null) {- val label = if (charging) {- stringResource(R.string.battery_charging, batteryPct)- } else {- stringResource(R.string.battery_pct, batteryPct)- }- Text(label, style = MaterialTheme.typography.bodyMedium)- }- }- }-}--@Composable-private fun HydrationCard(totalMl: Int, goalMl: Int) {- Card(modifier = Modifier.fillMaxWidth()) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(20.dp),- horizontalAlignment = Alignment.CenterHorizontally- ) {- Text(stringResource(R.string.today), style = MaterialTheme.typography.titleMedium)- Text(- stringResource(R.string.ml, totalMl),- style = MaterialTheme.typography.displayMedium- )- Spacer(Modifier.height(12.dp))- val progress = (totalMl.toFloat() / goalMl.coerceAtLeast(1)).coerceIn(0f, 1f)- LinearProgressIndicator(- progress = { progress },- modifier = Modifier.fillMaxWidth()- )- Spacer(Modifier.height(6.dp))- Text(- stringResource(R.string.goal_ml, goalMl),- style = MaterialTheme.typography.bodySmall- )- }- }-}
things/src/main/res/values/strings.xml
diff --git a/things/src/main/res/values/strings.xml b/things/src/main/res/values/strings.xmlindex 22eee3d0d5..5bce2dd060 100644--- a/things/src/main/res/values/strings.xml+++ b/things/src/main/res/values/strings.xml@@ -1,25 +1,35 @@ <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">- <!-- App name: launcher label, appears in app drawer -->+ <!-- App name: launcher label, appears in app drawer. Also the Home screen title --> <string name="app_name">Things</string> - <!-- TopAppBar title. Noun, refers to hydration tracking feature -->- <string name="hydration">Hydration</string>- <!-- HydrationCard: header label for today's total intake. Noun/adjective, Title Case -->- <string name="today">Today</string>+ <!-- Devices screen title: device management (scan/connect/disconnect). Noun -->+ <string name="devices">Devices</string>+ <!-- Home empty state when no device is connected. Sentence -->+ <string name="no_devices">No devices connected</string>+ <!-- Button on Home empty state that opens the Devices screen. Verb phrase -->+ <string name="open_devices">Open Devices</string>+ <!-- Scale note reassuring that measurements are saved to Health Connect. Sentence -->+ <string name="syncs_to_health_connect">Measurements sync to Health Connect</string>+ <!-- Button to start BLE scan for smart bottle/cup. Verb, short action label --> <string name="scan">Scan</string> <!-- Device list label when BLE devices discovered. Noun phrase, colon intentional --> <string name="devices_found">Devices found:</string> <!-- Button to disconnect from BLE device. Verb --> <string name="disconnect">Disconnect</string>- <!-- Section header above daily drink log LazyColumn. Noun phrase -->- <string name="today_s_drinks">Today\'s drinks</string>- <!-- HydrationCard: total consumed. %1$s = volume number e.g. 450. Keep mL unit after placeholder -->- <string name="ml"><xliff:g id="volume" example="450">%1$s</xliff:g> mL</string>- <!-- HydrationCard: daily goal beneath progress bar. %1$s = goal number e.g. 2000 -->- <string name="goal_ml">Goal <xliff:g id="goal" example="2000">%1$s</xliff:g> mL</string> <!-- Bottle status section header shown when connected and sensor values available --> <string name="bottle_status">Bottle status</string>+ <!-- Row labels in the bottle status card -->+ <string name="label_battery">Battery</string>+ <string name="label_water_level">Water level</string>+ <string name="label_temperature">Temperature</string>+ <string name="label_purity">Purity</string>+ <!-- Generic percentage value. %1$d = 0-100 -->+ <string name="percent"><xliff:g id="pct" example="60">%1$d</xliff:g>%%</string>+ <!-- Shown in the bottle card before the first sensor reading arrives -->+ <string name="waiting_for_data">Waiting for data…</string>+ <!-- Timestamp of the most recent sensor reading. %1$s = clock time e.g. 14:05:30 -->+ <string name="last_updated">Updated <xliff:g id="time" example="14:05:30">%1$s</xliff:g></string> <!-- Bottle status: water temperature. %1$d = degrees Celsius integer --> <string name="temperature_c"><xliff:g id="temp" example="22">%1$d</xliff:g>°C</string> <!-- Bottle status: water purity as TDS. %1$d = ppm integer -->@@ -45,33 +55,17 @@ <string name="athlete">Athlete mode</string> <!-- Scale scan button --> <string name="scan_scale">Scan scale</string>- <!-- Scale weight labels -->- <string name="weight">Weight</string>- <string name="weighing">Weighing…</string>- <!-- Impedance label. %1$d = ohms -->- <string name="impedance">Impedance %1$d Ω</string>- <string name="no_impedance">No impedance — BMI only</string>- <!-- Body composition -->- <string name="body_composition">Body composition</string>- <string name="bmi">BMI</string>- <string name="body_fat">Body fat</string>- <string name="fat_mass">Fat mass</string>- <string name="lbm">Lean mass</string>- <string name="water">Water</string>- <string name="muscle">Muscle</string>- <string name="bone">Bone</string>- <string name="protein">Protein</string>- <string name="bmr">BMR</string>- <string name="visceral">Visceral fat</string>- <string name="body_age">Body age</string>- <string name="score">Score</string>- <string name="segmental">Segmental (8-electrode)</string>- <string name="seg_arms">Arms R/L</string>- <string name="seg_legs">Legs R/L</string>- <string name="seg_trunk">Trunk</string>- <string name="bmi_only">BMI shown — step on bare feet for impedance</string>- <string name="bmi_hint">Impedance measures body fat via foot electrodes</string> <!-- Health Connect --> <!-- Button to grant Health Connect permissions. Verb phrase --> <string name="health_connect">Health Connect</string>++ <!-- Foreground service -->+ <!-- Notification channel name for the ongoing "keeping devices connected" notification -->+ <string name="device_channel_name">Device connection</string>+ <!-- Notification channel description shown in system notification settings -->+ <string name="device_channel_desc">Keeps your bottle and scale connected in the background</string>+ <!-- Ongoing foreground-service notification title -->+ <string name="device_notification_title">Devices connected</string>+ <!-- Ongoing foreground-service notification body text -->+ <string name="device_notification_text">Keeping your devices connected</string> </resources>
things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt
diff --git a/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt b/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.ktindex afa1a8fb68..f39f1aec8f 100644--- a/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt+++ b/things/src/screenshotTest/kotlin/com/vayunmathur/things/ui/MetadataPreviews.kt@@ -5,9 +5,6 @@ import androidx.compose.ui.tooling.preview.Preview import com.android.tools.screenshot.PreviewTest import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.things.platform.BleManager-import com.vayunmathur.things.platform.BodyComposition-import com.vayunmathur.things.platform.ScaleMeasurement-import com.vayunmathur.things.platform.ScaleProfile import com.vayunmathur.things.platform.Sex /** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */@@ -23,97 +20,56 @@ private const val PHONE = "spec:width=411dp,height=891dp,dpi=420" class MetadataPreviews { @PreviewTest- @Preview(name = "1-connected", device = PHONE, showSystemUi = true)+ @Preview(name = "1-home", device = PHONE, showSystemUi = true) @Composable- fun Preview1Connected() {- val metrics = BodyComposition.calculate(- ScaleProfile(sex = Sex.Male, age = 30, heightCm = 178.0, athlete = false),- ScaleMeasurement(weightKg = 78.0, resistance50 = 520, resistance500 = 480)- )+ fun Preview1Home() { DynamicTheme(darkTheme = true) {- ThingsApp(- totalMl = 1450,- goalMl = 2000,- messages = listOf(- "12:40 +250 ml",- "11:05 +500 ml",- "09:20 +350 ml",- "08:00 +350 ml",- ),- connectionState = "Connected",- scanning = false,- discoveredDevices = emptyList(),+ HomePage(+ bottleConnected = true, tempC = 22, tds = 85, batteryPct = 75, charging = false,- onScanClick = {},- onDeviceClick = {},- onDisconnectClick = {},- scaleWeight = 78.0,- scaleRealtimeWeight = null,- scaleR50 = 520,- scaleConnectionState = "Scale: 78.0 kg",- scaleScanning = false,- scaleDevices = emptyList(),- scaleMetrics = metrics,+ volumePct = 60,+ lastUpdatedMillis = 1_788_277_018_000L,+ scaleConnected = true,+ scaleConnectionState = "Connected — step on scale", scaleSex = Sex.Male, scaleAge = "30", scaleHeight = "178", scaleAthlete = false,- onScaleScanClick = {},- onScaleDeviceClick = {},- onScaleDisconnectClick = {}, onScaleSexChange = {}, onScaleAgeChange = {}, onScaleHeightChange = {}, onScaleAthleteChange = {},- onHealthConnectClick = {},+ onOpenDevices = {}, ) } } @PreviewTest- @Preview(name = "2-scanning", device = PHONE, showSystemUi = true)+ @Preview(name = "2-devices", device = PHONE, showSystemUi = true) @Composable- fun Preview2Scanning() {+ fun Preview2Devices() { DynamicTheme(darkTheme = true) {- ThingsApp(- totalMl = 0,- goalMl = 2000,- messages = emptyList(),+ DevicesPage( connectionState = "Scanning…", scanning = true, discoveredDevices = listOf( BleManager.BleDevice("HidrateSpark PRO", "C4:2F:90:1A:3B:7E"), BleManager.BleDevice("Smart Bottle 2", "D1:88:04:9C:22:10"), ),- tempC = null,- tds = null,- batteryPct = null,- charging = false, onScanClick = {}, onDeviceClick = {}, onDisconnectClick = {},- scaleWeight = null,- scaleRealtimeWeight = null,- scaleR50 = null, scaleConnectionState = "Disconnected", scaleScanning = true, scaleDevices = emptyList(),- scaleMetrics = null,- scaleSex = Sex.Female,- scaleAge = "28",- scaleHeight = "165",- scaleAthlete = false, onScaleScanClick = {}, onScaleDeviceClick = {}, onScaleDisconnectClick = {},- onScaleSexChange = {},- onScaleAgeChange = {},- onScaleHeightChange = {},- onScaleAthleteChange = {}, onHealthConnectClick = {},+ onNavigateBack = null, ) } }