watch: build phone and watch companion app
- Commit
8c9d1aaaf7b96274726cee4e6758c90d6942b29f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-05 18:18 UTC (5 months ago)
- Parents
0439f5c
Diff
build-logic/src/main/kotlin/common-conventions-wear.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts b/build-logic/src/main/kotlin/common-conventions-wear.gradle.ktsnew file mode 100644index 0000000000..e7a356a0a9--- /dev/null+++ b/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts@@ -0,0 +1,118 @@+plugins {+ id("com.android.application")+ id("org.jetbrains.kotlin.plugin.compose")+ id("org.jetbrains.kotlin.plugin.serialization")+ id("com.google.devtools.ksp")+}++val libs = the<org.gradle.accessors.dm.LibrariesForLibs>()++fun readVersionInfo(): Pair<Int, String> {+ val versionFile = File(rootDir, "version.txt")++ return if (versionFile.exists()) {+ val lines = versionFile.readLines()+ if (lines.size >= 2) {+ val code = lines[0].trim().toIntOrNull() ?: 1+ val name = lines[1].trim()+ code to name+ } else throw IllegalStateException("Invalid version.txt format")+ } else throw IllegalStateException("version.txt not found")+}++val proguardFile+ get() = File(rootDir, "proguard-rules.pro")++val (appVersionCode, appVersionName) = readVersionInfo()++configure<com.android.build.api.dsl.ApplicationExtension> {+ dependenciesInfo {+ includeInApk = false+ includeInBundle = false+ }+ buildFeatures {+ compose = true+ }++ namespace = "com.vayunmathur${path.replace(":", ".")}"+ compileSdk {+ version = release(37)+ }++ androidResources {+ generateLocaleConfig = true+ }++ ndkVersion = "29.0.14206865"++ defaultConfig {+ minSdk = 30+ versionCode = appVersionCode+ versionName = appVersionName+ targetSdk = 37+ }++ signingConfigs {+ val isSigningConfigAvailable = project.hasProperty("RELEASE_STORE_FILE")++ if (isSigningConfigAvailable) {+ create("release") {+ storeFile = file(project.property("RELEASE_STORE_FILE") as String)+ storePassword = project.property("RELEASE_STORE_PASSWORD") as String+ keyAlias = project.property("RELEASE_KEY_ALIAS") as String+ keyPassword = project.property("RELEASE_KEY_PASSWORD") as String++ enableV1Signing = true+ enableV2Signing = true+ enableV3Signing = true+ enableV4Signing = false+ }+ }+ }++ buildTypes {+ release {+ isMinifyEnabled = true+ isShrinkResources = true+ signingConfig = if (signingConfigs.findByName("release") != null) {+ signingConfigs.getByName("release")+ } else {+ signingConfigs.getByName("debug")+ }+ proguardFiles(+ getDefaultProguardFile("proguard-android-optimize.txt"), proguardFile.absolutePath,+ )++ ndk {+ abiFilters.add("arm64-v8a")+ }+ }+ create("dev") {+ initWith(getByName("release"))+ isMinifyEnabled = false+ isShrinkResources = false+ matchingFallbacks += listOf("release")+ }+ }+}++dependencies {+ // AndroidX Core & Lifecycle+ implementation(libs.okio)+ implementation(libs.kotlinx.datetime)+ implementation(libs.androidx.core.ktx)+ implementation(libs.androidx.lifecycle.runtime.ktx)+ implementation(libs.androidx.activity.compose)++ // Compose UI (BOM Managed)+ implementation(platform(libs.androidx.compose.bom))+ implementation(libs.androidx.compose.ui)+ implementation(libs.androidx.compose.ui.graphics)++ // Wear Compose+ implementation(libs.androidx.wear.compose.material)+ implementation(libs.androidx.wear.compose.foundation)++ // Kotlin Serialization+ implementation(libs.kotlinx.serialization.json)+}
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 9f8b33d99c..8667a21bdd 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -23,6 +23,7 @@ activityCompose = "1.13.0" material3 = "1.5.0-alpha21" reorderable = "3.1.0" material = "1.14.0"+wearComposeMaterial = "1.5.4" # Navigation navigation3 = "1.1.2"@@ -93,6 +94,8 @@ androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" } androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" } androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }+androidx-wear-compose-material = { group = "androidx.wear.compose", name = "compose-material", version.ref = "wearComposeMaterial" }+androidx-wear-compose-foundation = { group = "androidx.wear.compose", name = "compose-foundation", version.ref = "wearComposeMaterial" } androidx-compose-runtime-livedata = { group = "androidx.compose.runtime", name = "runtime-livedata" } # Navigation
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 835cebd9b0..1147dfc8f5 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -66,3 +66,5 @@ include(":launcher") include(":things") include(":office") include(":tools:holidaygen")+include(":watch:watch")+include(":watch:phone")
watch/phone/build.gradle.kts
diff --git a/watch/phone/build.gradle.kts b/watch/phone/build.gradle.ktsnew file mode 100644index 0000000000..76ea340d34--- /dev/null+++ b/watch/phone/build.gradle.kts@@ -0,0 +1,16 @@+plugins {+ id("common-conventions-app")+ alias(libs.plugins.ksp)+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.watch.phone"+ minSdk = 34+ }+}++dependencies {+ implementation(libs.androidx.connect.client)+ implementation(libs.androidx.work.runtime.ktx)+}
watch/phone/src/main/AndroidManifest.xml
diff --git a/watch/phone/src/main/AndroidManifest.xml b/watch/phone/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..b78040a015--- /dev/null+++ b/watch/phone/src/main/AndroidManifest.xml@@ -0,0 +1,72 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-feature+ android:name="android.hardware.bluetooth_le"+ android:required="true" />++ <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />+ <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 -->+ <uses-permission android:name="android.permission.health.WRITE_HEART_RATE" />+ <uses-permission android:name="android.permission.health.WRITE_STEPS" />++ <queries>+ <package android:name="com.google.android.apps.healthdata" />+ <intent>+ <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />+ </intent>+ </queries>++ <application+ android:allowBackup="true"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">++ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <service+ android:name=".sync.SyncForegroundService"+ android:exported="false"+ android:foregroundServiceType="connectedDevice" />++ <!-- Health Connect permissions rationale (Android 13 and below). -->+ <activity+ android:name=".ui.PermissionsRationaleActivity"+ android:exported="true">+ <intent-filter>+ <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />+ </intent-filter>+ </activity>++ <!-- Health Connect permissions rationale (Android 14+). -->+ <activity-alias+ android:name="ViewPermissionUsageActivity"+ android:exported="true"+ android:targetActivity=".ui.PermissionsRationaleActivity"+ android:permission="android.permission.START_VIEW_PERMISSION_USAGE">+ <intent-filter>+ <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />+ <category android:name="android.intent.category.HEALTH_PERMISSIONS" />+ </intent-filter>+ </activity-alias>++ </application>++</manifest>
watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.ktnew file mode 100644index 0000000000..49a22f979a--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt@@ -0,0 +1,137 @@+package com.vayunmathur.watch.phone++import android.Manifest+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.compose.setContent+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Button+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.health.connect.client.PermissionController+import com.vayunmathur.watch.phone.ble.ConnectionState+import com.vayunmathur.watch.phone.health.HealthConnectManager+import com.vayunmathur.watch.phone.sync.SyncForegroundService++class MainActivity : ComponentActivity() {++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ setContent {+ MaterialTheme {+ Scaffold { padding ->+ SyncScreen(Modifier.padding(padding))+ }+ }+ }+ }++ @Composable+ private fun SyncScreen(modifier: Modifier) {+ val context = this+ val health = remember { HealthConnectManager(context) }++ val connection by SyncForegroundService.connectionStateFlow.collectAsState()+ val synced by SyncForegroundService.syncedCountFlow.collectAsState()++ var hasBlePerms by remember { mutableStateOf(false) }+ var hasHcPerms by remember { mutableStateOf(false) }+ var hcAvailable by remember { mutableStateOf(true) }++ val blePermsLauncher = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.RequestMultiplePermissions(),+ onResult = { result -> hasBlePerms = result.values.all { it } },+ )++ val hcPermsLauncher = rememberLauncherForActivityResult(+ contract = PermissionController.createRequestPermissionResultContract(),+ onResult = { granted -> hasHcPerms = granted.containsAll(health.permissions) },+ )++ LaunchedEffect(Unit) {+ hasBlePerms = blePermissions().all {+ checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED+ }+ hcAvailable = health.isAvailable()+ if (hcAvailable) hasHcPerms = health.hasAllPermissions()+ }++ Column(+ modifier = modifier.fillMaxSize().padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Text(stringResource(R.string.status_connection, connection.label()))+ Text(stringResource(R.string.status_synced, synced))++ when {+ !hasBlePerms -> Button(onClick = { blePermsLauncher.launch(blePermissions()) }) {+ Text(stringResource(R.string.grant_ble_permissions))+ }+ !hcAvailable -> Button(onClick = { openHealthConnectInstall() }) {+ Text(stringResource(R.string.install_health_connect))+ }+ !hasHcPerms -> Button(onClick = { hcPermsLauncher.launch(health.permissions) }) {+ Text(stringResource(R.string.grant_hc_permissions))+ }+ else -> {+ Button(onClick = { SyncForegroundService.start(context) }) {+ Text(stringResource(R.string.scan_pair))+ }+ Button(onClick = { SyncForegroundService.stop(context) }) {+ Text(stringResource(R.string.stop_sync))+ }+ }+ }+ }+ }++ @Composable+ private fun ConnectionState.label(): String = when (this) {+ ConnectionState.Disconnected -> stringResource(R.string.state_disconnected)+ ConnectionState.Scanning -> stringResource(R.string.state_scanning)+ ConnectionState.Connecting -> stringResource(R.string.state_connecting)+ ConnectionState.Connected -> stringResource(R.string.state_connected)+ }++ private fun blePermissions(): Array<String> = arrayOf(+ Manifest.permission.BLUETOOTH_SCAN,+ Manifest.permission.BLUETOOTH_CONNECT,+ Manifest.permission.ACCESS_FINE_LOCATION,+ Manifest.permission.POST_NOTIFICATIONS,+ )++ private fun openHealthConnectInstall() {+ val uri = Uri.parse("market://details?id=com.google.android.apps.healthdata")+ try {+ startActivity(Intent(Intent.ACTION_VIEW, uri))+ } catch (e: Exception) {+ startActivity(+ Intent(+ Intent.ACTION_VIEW,+ Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata"),+ ),+ )+ }+ }+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.ktnew file mode 100644index 0000000000..6321b67a44--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/BleConstants.kt@@ -0,0 +1,19 @@+package com.vayunmathur.watch.phone.ble++import java.util.UUID++/**+ * Shared BLE contract between the watch (GATT server) and phone (GATT client).+ * These UUIDs and opcodes are duplicated verbatim from the :watch:watch module.+ */+object BleConstants {+ val SERVICE_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-567812345678")+ val DATA_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-567812345679")+ val CONTROL_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-56781234567a")+ val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")++ const val OPCODE_ACK: Byte = 0x01+ const val OPCODE_CLEAR: Byte = 0x02++ val EOT_MARKER: ByteArray = byteArrayOf(0x04)+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.ktnew file mode 100644index 0000000000..ccb384f8da--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt@@ -0,0 +1,188 @@+package com.vayunmathur.watch.phone.ble++import android.annotation.SuppressLint+import android.bluetooth.BluetoothDevice+import android.bluetooth.BluetoothGatt+import android.bluetooth.BluetoothGattCallback+import android.bluetooth.BluetoothGattCharacteristic+import android.bluetooth.BluetoothGattDescriptor+import android.bluetooth.BluetoothManager+import android.bluetooth.BluetoothProfile+import android.bluetooth.le.ScanCallback+import android.bluetooth.le.ScanFilter+import android.bluetooth.le.ScanResult+import android.bluetooth.le.ScanSettings+import android.content.Context+import android.os.ParcelUuid+import android.util.Log+import com.vayunmathur.watch.phone.data.WatchBatch+import com.vayunmathur.watch.phone.data.WatchRecord+import java.io.ByteArrayOutputStream+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.serialization.json.Json++enum class ConnectionState {+ Disconnected,+ Scanning,+ Connecting,+ Connected,+}++/**+ * Scans for the watch by Service UUID, connects, discovers services, requests a+ * larger MTU, subscribes to the Data characteristic, reassembles the streamed+ * JSON batch until the EOT marker, deserializes it, then writes an ACK opcode to+ * the Control characteristic so the watch can clear the acked rows.+ */+@SuppressLint("MissingPermission")+class GattClientManager(private val context: Context) {++ private val json = Json { ignoreUnknownKeys = true }++ private val bluetoothManager =+ context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager++ private var gatt: BluetoothGatt? = null+ private var scanning = false++ private val reassembly = ByteArrayOutputStream()++ private val _state = MutableStateFlow(ConnectionState.Disconnected)+ val state: StateFlow<ConnectionState> = _state++ private val _batches = MutableSharedFlow<List<WatchRecord>>(extraBufferCapacity = 8)+ val batches: SharedFlow<List<WatchRecord>> = _batches++ fun startScan() {+ val scanner = bluetoothManager.adapter?.bluetoothLeScanner ?: return+ if (scanning) return+ scanning = true+ _state.value = ConnectionState.Scanning+ val filter = ScanFilter.Builder()+ .setServiceUuid(ParcelUuid(BleConstants.SERVICE_UUID))+ .build()+ val settings = ScanSettings.Builder()+ .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)+ .build()+ scanner.startScan(listOf(filter), settings, scanCallback)+ }++ private fun stopScan() {+ if (!scanning) return+ scanning = false+ bluetoothManager.adapter?.bluetoothLeScanner?.stopScan(scanCallback)+ }++ fun disconnect() {+ stopScan()+ gatt?.disconnect()+ gatt?.close()+ gatt = null+ _state.value = ConnectionState.Disconnected+ }++ private val scanCallback = object : ScanCallback() {+ override fun onScanResult(callbackType: Int, result: ScanResult) {+ stopScan()+ connect(result.device)+ }++ override fun onScanFailed(errorCode: Int) {+ Log.e(TAG, "Scan failed: $errorCode")+ scanning = false+ _state.value = ConnectionState.Disconnected+ }+ }++ private fun connect(device: BluetoothDevice) {+ _state.value = ConnectionState.Connecting+ gatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE)+ }++ private val gattCallback = object : BluetoothGattCallback() {+ override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {+ when (newState) {+ BluetoothProfile.STATE_CONNECTED -> gatt.requestMtu(REQUESTED_MTU)+ BluetoothProfile.STATE_DISCONNECTED -> {+ _state.value = ConnectionState.Disconnected+ gatt.close()+ [email protected] = null+ }+ }+ }++ override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {+ gatt.discoverServices()+ }++ override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {+ if (status != BluetoothGatt.GATT_SUCCESS) return+ val service = gatt.getService(BleConstants.SERVICE_UUID) ?: return+ val dataChar = service.getCharacteristic(BleConstants.DATA_CHARACTERISTIC_UUID) ?: return+ _state.value = ConnectionState.Connected+ subscribe(gatt, dataChar)+ }++ override fun onDescriptorWrite(+ gatt: BluetoothGatt,+ descriptor: BluetoothGattDescriptor,+ status: Int,+ ) {+ // Subscription active; the watch will now push the batch.+ reassembly.reset()+ }++ override fun onCharacteristicChanged(+ gatt: BluetoothGatt,+ characteristic: BluetoothGattCharacteristic,+ value: ByteArray,+ ) {+ if (characteristic.uuid != BleConstants.DATA_CHARACTERISTIC_UUID) return+ if (value.contentEquals(BleConstants.EOT_MARKER)) {+ finishBatch(gatt)+ } else {+ reassembly.write(value)+ }+ }+ }++ private fun subscribe(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {+ gatt.setCharacteristicNotification(characteristic, true)+ val cccd = characteristic.getDescriptor(BleConstants.CCCD_UUID) ?: return+ gatt.writeDescriptor(cccd, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)+ }++ private fun finishBatch(gatt: BluetoothGatt) {+ val bytes = reassembly.toByteArray()+ reassembly.reset()+ val records = try {+ if (bytes.isEmpty()) emptyList()+ else json.decodeFromString<WatchBatch>(bytes.toString(Charsets.UTF_8)).records+ } catch (e: Exception) {+ Log.e(TAG, "Failed to parse batch", e)+ return+ }+ if (records.isNotEmpty()) {+ _batches.tryEmit(records)+ }+ sendAck(gatt)+ }++ private fun sendAck(gatt: BluetoothGatt) {+ val service = gatt.getService(BleConstants.SERVICE_UUID) ?: return+ val control = service.getCharacteristic(BleConstants.CONTROL_CHARACTERISTIC_UUID) ?: return+ gatt.writeCharacteristic(+ control,+ byteArrayOf(BleConstants.OPCODE_ACK),+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,+ )+ }++ companion object {+ private const val TAG = "GattClientManager"+ private const val REQUESTED_MTU = 512+ }+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.ktnew file mode 100644index 0000000000..c8a04b6cbc--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/data/WatchPayload.kt@@ -0,0 +1,16 @@+package com.vayunmathur.watch.phone.data++import kotlinx.serialization.Serializable++/** Matches the JSON emitted by the watch's GattServerManager. */+@Serializable+data class WatchRecord(+ val id: Long,+ val type: String,+ val timestamp: Long,+ val value: Double,+ val delta: Double,+)++@Serializable+data class WatchBatch(val records: List<WatchRecord>)
watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.ktnew file mode 100644index 0000000000..4ccf35d3a1--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt@@ -0,0 +1,82 @@+package com.vayunmathur.watch.phone.health++import android.content.Context+import android.util.Log+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.permission.HealthPermission+import androidx.health.connect.client.records.HeartRateRecord+import androidx.health.connect.client.records.StepsRecord+import androidx.health.connect.client.records.metadata.Metadata+import com.vayunmathur.watch.phone.data.WatchRecord+import java.time.Instant+import java.time.ZoneId++/**+ * Wraps Health Connect onboarding, permissions, and inserting the watch's+ * heart-rate and step records.+ */+class HealthConnectManager(private val context: Context) {++ val permissions: Set<String> = setOf(+ HealthPermission.getWritePermission(HeartRateRecord::class),+ HealthPermission.getWritePermission(StepsRecord::class),+ )++ fun sdkStatus(): Int = HealthConnectClient.getSdkStatus(context)++ fun isAvailable(): Boolean = sdkStatus() == HealthConnectClient.SDK_AVAILABLE++ fun client(): HealthConnectClient = HealthConnectClient.getOrCreate(context)++ suspend fun hasAllPermissions(): Boolean =+ client().permissionController.getGrantedPermissions().containsAll(permissions)++ suspend fun insert(records: List<WatchRecord>) {+ if (records.isEmpty()) return+ val zone = ZoneId.systemDefault()+ val hcRecords = records.mapNotNull { record ->+ val time = Instant.ofEpochMilli(record.timestamp)+ val offset = zone.rules.getOffset(time)+ when (record.type) {+ "HeartRate" -> HeartRateRecord(+ startTime = time,+ startZoneOffset = offset,+ endTime = time,+ endZoneOffset = offset,+ samples = listOf(+ HeartRateRecord.Sample(+ time = time,+ beatsPerMinute = record.value.toLong(),+ ),+ ),+ metadata = Metadata.manualEntry(clientRecordId = "hr-${record.id}"),+ )+ "Steps" -> {+ val count = record.delta.toLong()+ if (count <= 0L) return@mapNotNull null+ val start = time.minusSeconds(STEP_WINDOW_SECONDS)+ StepsRecord(+ startTime = start,+ startZoneOffset = zone.rules.getOffset(start),+ endTime = time,+ endZoneOffset = offset,+ count = count,+ metadata = Metadata.manualEntry(clientRecordId = "steps-${record.id}"),+ )+ }+ else -> null+ }+ }+ if (hcRecords.isEmpty()) return+ try {+ client().insertRecords(hcRecords)+ } catch (e: Exception) {+ Log.e(TAG, "insertRecords failed", e)+ }+ }++ companion object {+ private const val TAG = "HealthConnectManager"+ private const val STEP_WINDOW_SECONDS = 60L+ }+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.ktnew file mode 100644index 0000000000..a7103ce739--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt@@ -0,0 +1,106 @@+package com.vayunmathur.watch.phone.sync++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.os.IBinder+import com.vayunmathur.watch.phone.R+import com.vayunmathur.watch.phone.ble.ConnectionState+import com.vayunmathur.watch.phone.ble.GattClientManager+import com.vayunmathur.watch.phone.health.HealthConnectManager+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.launch++/**+ * Persistent foreground service that owns the BLE link. It drives the+ * [GattClientManager], keeps re-scanning when disconnected, and writes each+ * received+acked batch to Health Connect via [HealthConnectManager].+ */+class SyncForegroundService : Service() {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)++ private lateinit var client: GattClientManager+ private lateinit var health: HealthConnectManager++ override fun onCreate() {+ super.onCreate()+ client = GattClientManager(this)+ health = HealthConnectManager(this)++ scope.launch {+ client.state.collect { state ->+ connectionState.value = state+ // Auto-reconnect whenever the link drops.+ if (state == ConnectionState.Disconnected) {+ client.startScan()+ }+ }+ }++ scope.launch {+ client.batches.collect { records ->+ health.insert(records)+ syncedCount.value += records.size+ }+ }+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ startForeground(NOTIFICATION_ID, buildNotification())+ client.startScan()+ return START_STICKY+ }++ private fun buildNotification(): Notification {+ val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ val channel = NotificationChannel(+ CHANNEL_ID,+ getString(R.string.notification_channel_name),+ NotificationManager.IMPORTANCE_LOW,+ )+ manager.createNotificationChannel(channel)+ return Notification.Builder(this, CHANNEL_ID)+ .setContentTitle(getString(R.string.notification_title))+ .setContentText(getString(R.string.notification_text))+ .setSmallIcon(R.drawable.ic_launcher_foreground)+ .setOngoing(true)+ .build()+ }++ override fun onDestroy() {+ client.disconnect()+ scope.cancel()+ connectionState.value = ConnectionState.Disconnected+ super.onDestroy()+ }++ override fun onBind(intent: Intent?): IBinder? = null++ companion object {+ private const val CHANNEL_ID = "watch_sync"+ private const val NOTIFICATION_ID = 1++ val connectionState = MutableStateFlow(ConnectionState.Disconnected)+ val syncedCount = MutableStateFlow(0)++ val connectionStateFlow: StateFlow<ConnectionState> = connectionState+ val syncedCountFlow: StateFlow<Int> = syncedCount++ fun start(context: Context) {+ context.startForegroundService(Intent(context, SyncForegroundService::class.java))+ }++ fun stop(context: Context) {+ context.stopService(Intent(context, SyncForegroundService::class.java))+ }+ }+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/ui/PermissionsRationaleActivity.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ui/PermissionsRationaleActivity.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ui/PermissionsRationaleActivity.ktnew file mode 100644index 0000000000..c8830e9a42--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ui/PermissionsRationaleActivity.kt@@ -0,0 +1,50 @@+package com.vayunmathur.watch.phone.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.watch.phone.R++/**+ * Shown when the user taps the Health Connect privacy policy link. Explains why+ * the app requests write access to heart-rate and step data.+ */+class PermissionsRationaleActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ setContent {+ MaterialTheme {+ Scaffold { padding ->+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding)+ .padding(24.dp)+ .verticalScroll(rememberScrollState()),+ ) {+ Text(+ text = stringResource(R.string.rationale_title),+ style = MaterialTheme.typography.headlineSmall,+ )+ Text(+ text = stringResource(R.string.rationale_body),+ modifier = Modifier.padding(top = 12.dp),+ style = MaterialTheme.typography.bodyLarge,+ )+ }+ }+ }+ }+ }+}
watch/phone/src/main/res/drawable/ic_launcher_foreground.xml
diff --git a/watch/phone/src/main/res/drawable/ic_launcher_foreground.xml b/watch/phone/src/main/res/drawable/ic_launcher_foreground.xmlnew file mode 100644index 0000000000..b6440328d1--- /dev/null+++ b/watch/phone/src/main/res/drawable/ic_launcher_foreground.xml@@ -0,0 +1,15 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp"+ android:height="108dp"+ android:viewportWidth="960"+ android:viewportHeight="960"+ android:tint="#000000">+ <group android:scaleX="0.58"+ android:scaleY="0.58"+ android:translateX="201.6"+ android:translateY="201.6">+ <path+ android:fillColor="@android:color/white"+ android:pathData="M480,840Q462,840 445.5,833.5Q429,827 416,814L148,545Q113,510 96.5,465Q80,420 80,371Q80,268 147,194Q214,120 314,120Q362,120 404.5,139Q447,158 480,192L480,192L480,192Q512,158 554.5,139Q597,120 645,120Q745,120 812.5,194Q880,268 880,370Q880,419 863,464Q846,509 812,544L543,814Q530,827 514,833.5Q498,840 480,840ZM520,320Q530,320 539,325Q548,330 553,338L621,440L787,440Q794,423 797.5,405.5Q801,388 801,370Q799,301 755,251.5Q711,202 645,202Q614,202 585.5,214Q557,226 536,249L509,278Q504,284 496,287.5Q488,291 480,291Q472,291 464,287.5Q456,284 450,278L423,249Q402,226 374,213Q346,200 314,200Q248,200 204,250.5Q160,301 160,370Q160,388 163,405.5Q166,423 173,440L360,440Q370,440 379,445Q388,450 393,458L428,510L482,348Q486,336 496.5,328Q507,320 520,320ZM532,450L478,612Q474,624 463,632Q452,640 439,640Q429,640 420,635Q411,630 406,622L338,520L236,520L473,757Q475,759 476.5,759.5Q478,760 480,760Q482,760 483.5,759.5Q485,759 487,757L723,520L600,520Q590,520 581,515Q572,510 566,502L532,450Z"/>+ </group>+</vector>
watch/phone/src/main/res/mipmap-anydpi/ic_launcher.xml
diff --git a/watch/phone/src/main/res/mipmap-anydpi/ic_launcher.xml b/watch/phone/src/main/res/mipmap-anydpi/ic_launcher.xmlnew file mode 100644index 0000000000..0b0d585e42--- /dev/null+++ b/watch/phone/src/main/res/mipmap-anydpi/ic_launcher.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/ic_launcher_background"/>+ <foreground android:drawable="@drawable/ic_launcher_foreground"/>+ <monochrome android:drawable="@drawable/ic_launcher_foreground"/>+</adaptive-icon>
watch/phone/src/main/res/resources.properties
diff --git a/watch/phone/src/main/res/resources.properties b/watch/phone/src/main/res/resources.propertiesnew file mode 100644index 0000000000..467b3efec9--- /dev/null+++ b/watch/phone/src/main/res/resources.properties@@ -0,0 +1 @@+unqualifiedResLocale=en-US
watch/phone/src/main/res/values/strings.xml
diff --git a/watch/phone/src/main/res/values/strings.xml b/watch/phone/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..7cee3744a4--- /dev/null+++ b/watch/phone/src/main/res/values/strings.xml@@ -0,0 +1,19 @@+<resources>+ <string name="app_name">Watch Sync</string>+ <string name="scan_pair">Scan & Pair Watch</string>+ <string name="stop_sync">Stop Sync</string>+ <string name="grant_ble_permissions">Grant Bluetooth Permissions</string>+ <string name="grant_hc_permissions">Grant Health Connect Permissions</string>+ <string name="install_health_connect">Install Health Connect</string>+ <string name="status_connection">Connection: %1$s</string>+ <string name="status_synced">Records synced: %1$d</string>+ <string name="state_disconnected">Disconnected</string>+ <string name="state_scanning">Scanning</string>+ <string name="state_connecting">Connecting</string>+ <string name="state_connected">Connected</string>+ <string name="rationale_title">Health Connect Permissions</string>+ <string name="rationale_body">This app writes heart rate and step data collected from your watch into Health Connect.</string>+ <string name="notification_channel_name">Watch Sync</string>+ <string name="notification_title">Syncing watch health data</string>+ <string name="notification_text">Maintaining BLE link and writing to Health Connect</string>+</resources>
watch/watch/build.gradle.kts
diff --git a/watch/watch/build.gradle.kts b/watch/watch/build.gradle.ktsnew file mode 100644index 0000000000..343a5b6072--- /dev/null+++ b/watch/watch/build.gradle.kts@@ -0,0 +1,14 @@+plugins {+ id("common-conventions-wear")+ alias(libs.plugins.ksp)+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.watch.watch"+ }+}++dependencies {+ implementRoom(libs)+}
watch/watch/src/main/AndroidManifest.xml
diff --git a/watch/watch/src/main/AndroidManifest.xml b/watch/watch/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..28d0de4052--- /dev/null+++ b/watch/watch/src/main/AndroidManifest.xml@@ -0,0 +1,49 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-feature+ android:name="android.hardware.type.watch" />+ <uses-feature+ android:name="android.hardware.bluetooth_le"+ android:required="true" />++ <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />+ <uses-permission android:name="android.permission.BODY_SENSORS" />+ <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />+ <uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_HEALTH" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <uses-permission android:name="android.permission.WAKE_LOCK" />++ <application+ android:allowBackup="true"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/AppTheme">++ <uses-library+ android:name="com.google.android.wearable"+ android:required="false" />++ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:theme="@style/AppTheme">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <service+ android:name=".service.SensorBackgroundService"+ android:exported="false"+ android:foregroundServiceType="health|connectedDevice" />++ </application>++</manifest>
watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.ktnew file mode 100644index 0000000000..0c1279b616--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt@@ -0,0 +1,109 @@+package com.vayunmathur.watch.watch++import android.Manifest+import android.os.Build+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.compose.setContent+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.wear.compose.material.Button+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.watch.watch.data.SensorDatabase+import com.vayunmathur.watch.watch.service.SensorBackgroundService++class MainActivity : ComponentActivity() {++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ setContent {+ MaterialTheme {+ CollectorScreen()+ }+ }+ }++ @Composable+ private fun CollectorScreen() {+ val context = this+ val dao = remember { SensorDatabase.get(context).sensorDao() }+ val rowCount by dao.countFlow().collectAsState(0)++ var hasPermissions by remember { mutableStateOf(false) }+ var collecting by remember { mutableStateOf(false) }++ val requestPermissions = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.RequestMultiplePermissions(),+ onResult = { result -> hasPermissions = result.values.all { it } },+ )++ LaunchedEffect(Unit) {+ hasPermissions = requiredPermissions().all {+ checkSelfPermission(it) == android.content.pm.PackageManager.PERMISSION_GRANTED+ }+ }++ Column(+ modifier = Modifier.fillMaxSize().padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ if (!hasPermissions) {+ Button(onClick = { requestPermissions.launch(requiredPermissions()) }) {+ Text(stringResource(R.string.grant_permissions))+ }+ return@Column+ }++ val onOff = if (collecting) stringResource(R.string.on) else stringResource(R.string.off)+ Text(stringResource(R.string.status_collecting, onOff))+ Text(stringResource(R.string.status_rows, rowCount))+ Button(+ onClick = {+ collecting = if (collecting) {+ SensorBackgroundService.stop(context)+ false+ } else {+ SensorBackgroundService.start(context)+ true+ }+ },+ modifier = Modifier.padding(top = 8.dp),+ ) {+ Text(+ if (collecting) stringResource(R.string.action_stop)+ else stringResource(R.string.action_start),+ )+ }+ }+ }++ private fun requiredPermissions(): Array<String> {+ val perms = mutableListOf(+ Manifest.permission.BLUETOOTH_ADVERTISE,+ Manifest.permission.BLUETOOTH_CONNECT,+ Manifest.permission.BODY_SENSORS,+ Manifest.permission.ACTIVITY_RECOGNITION,+ )+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ perms += Manifest.permission.POST_NOTIFICATIONS+ }+ return perms.toTypedArray()+ }+}
watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/BleConstants.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/BleConstants.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/BleConstants.ktnew file mode 100644index 0000000000..1b7fc60020--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/BleConstants.kt@@ -0,0 +1,27 @@+package com.vayunmathur.watch.watch.ble++import java.util.UUID++/**+ * Shared BLE contract between the watch (GATT server) and phone (GATT client).+ * These UUIDs and opcodes are duplicated verbatim in the :watch:phone module.+ */+object BleConstants {+ val SERVICE_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-567812345678")++ // READ + NOTIFY: watch streams JSON batch chunks to the phone.+ val DATA_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-567812345679")++ // WRITE: phone sends control opcodes (ACK / CLEAR) back to the watch.+ val CONTROL_CHARACTERISTIC_UUID: UUID = UUID.fromString("4a3b2c1d-1234-5678-1234-56781234567a")++ // Client Characteristic Configuration Descriptor (standard 0x2902).+ val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")++ // Control opcodes (first byte of a Control characteristic write).+ const val OPCODE_ACK: Byte = 0x01+ const val OPCODE_CLEAR: Byte = 0x02++ // End-of-transfer marker sent as its own notification after the last chunk.+ val EOT_MARKER: ByteArray = byteArrayOf(0x04)+}
watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.ktnew file mode 100644index 0000000000..cf66f398a2--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt@@ -0,0 +1,266 @@+package com.vayunmathur.watch.watch.ble++import android.annotation.SuppressLint+import android.bluetooth.BluetoothDevice+import android.bluetooth.BluetoothGattCharacteristic+import android.bluetooth.BluetoothGattDescriptor+import android.bluetooth.BluetoothGattServer+import android.bluetooth.BluetoothGattServerCallback+import android.bluetooth.BluetoothGattService+import android.bluetooth.BluetoothManager+import android.bluetooth.le.AdvertiseCallback+import android.bluetooth.le.AdvertiseData+import android.bluetooth.le.AdvertiseSettings+import android.bluetooth.le.BluetoothLeAdvertiser+import android.content.Context+import android.os.ParcelUuid+import android.util.Log+import com.vayunmathur.watch.watch.data.SensorDao+import com.vayunmathur.watch.watch.data.SensorRecord+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++@Serializable+private data class WireRecord(+ val id: Long,+ val type: String,+ val timestamp: Long,+ val value: Double,+ val delta: Double,+)++@Serializable+private data class WireBatch(val records: List<WireRecord>)++/**+ * Owns the BLE advertiser and GATT server. When a client subscribes to (or reads)+ * the Data characteristic, all currently-stored Room rows are serialized to JSON,+ * chunked to MTU-sized notifications, and streamed followed by an EOT marker.+ * When the client writes an ACK opcode to the Control characteristic, the rows+ * that were streamed are deleted from Room.+ */+@SuppressLint("MissingPermission")+class GattServerManager(+ private val context: Context,+ private val dao: SensorDao,+ private val scope: CoroutineScope,+) {+ private val json = Json { ignoreUnknownKeys = true }++ private val bluetoothManager =+ context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager++ private var gattServer: BluetoothGattServer? = null+ private var advertiser: BluetoothLeAdvertiser? = null++ private lateinit var dataCharacteristic: BluetoothGattCharacteristic+ private lateinit var controlCharacteristic: BluetoothGattCharacteristic++ // Per-device negotiated MTU (default 23 until MTU exchange).+ private val deviceMtu = mutableMapOf<String, Int>()++ // Ids streamed to each device in the last batch, pending ACK.+ private val pendingAck = mutableMapOf<String, List<Long>>()++ private val _advertising = MutableStateFlow(false)+ val advertising: StateFlow<Boolean> = _advertising++ fun start() {+ val adapter = bluetoothManager.adapter ?: return+ if (!adapter.isEnabled) {+ Log.w(TAG, "Bluetooth adapter disabled")+ return+ }+ openGattServer()+ startAdvertising(adapter.bluetoothLeAdvertiser)+ }++ fun stop() {+ try {+ advertiser?.stopAdvertising(advertiseCallback)+ } catch (e: Exception) {+ Log.e(TAG, "stopAdvertising failed", e)+ }+ _advertising.value = false+ gattServer?.close()+ gattServer = null+ }++ private fun openGattServer() {+ val server = bluetoothManager.openGattServer(context, serverCallback) ?: return+ gattServer = server++ val service = BluetoothGattService(+ BleConstants.SERVICE_UUID,+ BluetoothGattService.SERVICE_TYPE_PRIMARY,+ )++ dataCharacteristic = BluetoothGattCharacteristic(+ BleConstants.DATA_CHARACTERISTIC_UUID,+ BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_NOTIFY,+ BluetoothGattCharacteristic.PERMISSION_READ,+ )+ dataCharacteristic.addDescriptor(+ BluetoothGattDescriptor(+ BleConstants.CCCD_UUID,+ BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE,+ ),+ )++ controlCharacteristic = BluetoothGattCharacteristic(+ BleConstants.CONTROL_CHARACTERISTIC_UUID,+ BluetoothGattCharacteristic.PROPERTY_WRITE,+ BluetoothGattCharacteristic.PERMISSION_WRITE,+ )++ service.addCharacteristic(dataCharacteristic)+ service.addCharacteristic(controlCharacteristic)+ server.addService(service)+ }++ private fun startAdvertising(bleAdvertiser: BluetoothLeAdvertiser?) {+ advertiser = bleAdvertiser+ if (bleAdvertiser == null) {+ Log.w(TAG, "BLE advertising not supported")+ return+ }+ val settings = AdvertiseSettings.Builder()+ .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)+ .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)+ .setConnectable(true)+ .build()+ val data = AdvertiseData.Builder()+ .setIncludeDeviceName(false)+ .addServiceUuid(ParcelUuid(BleConstants.SERVICE_UUID))+ .build()+ bleAdvertiser.startAdvertising(settings, data, advertiseCallback)+ }++ private val advertiseCallback = object : AdvertiseCallback() {+ override fun onStartSuccess(settingsInEffect: AdvertiseSettings?) {+ _advertising.value = true+ }++ override fun onStartFailure(errorCode: Int) {+ Log.e(TAG, "Advertising failed: $errorCode")+ _advertising.value = false+ }+ }++ private val serverCallback = object : BluetoothGattServerCallback() {+ override fun onMtuChanged(device: BluetoothDevice, mtu: Int) {+ deviceMtu[device.address] = mtu+ }++ override fun onDescriptorWriteRequest(+ device: BluetoothDevice,+ requestId: Int,+ descriptor: BluetoothGattDescriptor,+ preparedWrite: Boolean,+ responseNeeded: Boolean,+ offset: Int,+ value: ByteArray?,+ ) {+ if (responseNeeded) {+ gattServer?.sendResponse(device, requestId, 0 /* GATT_SUCCESS */, offset, value)+ }+ // Subscription enabled -> stream the current batch.+ if (descriptor.uuid == BleConstants.CCCD_UUID && value != null &&+ value.isNotEmpty() && value[0].toInt() != 0+ ) {+ streamBatch(device)+ }+ }++ override fun onCharacteristicReadRequest(+ device: BluetoothDevice,+ requestId: Int,+ offset: Int,+ characteristic: BluetoothGattCharacteristic,+ ) {+ // A plain read triggers a fresh stream and returns an empty ack payload.+ gattServer?.sendResponse(device, requestId, 0, offset, ByteArray(0))+ if (characteristic.uuid == BleConstants.DATA_CHARACTERISTIC_UUID) {+ streamBatch(device)+ }+ }++ override fun onCharacteristicWriteRequest(+ device: BluetoothDevice,+ requestId: Int,+ characteristic: BluetoothGattCharacteristic,+ preparedWrite: Boolean,+ responseNeeded: Boolean,+ offset: Int,+ value: ByteArray?,+ ) {+ if (characteristic.uuid == BleConstants.CONTROL_CHARACTERISTIC_UUID &&+ value != null && value.isNotEmpty()+ ) {+ handleControl(device, value)+ }+ if (responseNeeded) {+ gattServer?.sendResponse(device, requestId, 0, offset, null)+ }+ }+ }++ private fun handleControl(device: BluetoothDevice, value: ByteArray) {+ when (value[0]) {+ BleConstants.OPCODE_ACK -> {+ val ids = pendingAck.remove(device.address).orEmpty()+ if (ids.isNotEmpty()) {+ scope.launch(Dispatchers.IO) { dao.deleteByIds(ids) }+ }+ }+ BleConstants.OPCODE_CLEAR -> {+ pendingAck.remove(device.address)+ }+ }+ }++ private fun streamBatch(device: BluetoothDevice) {+ scope.launch(Dispatchers.IO) {+ val rows: List<SensorRecord> = dao.getAll()+ val batch = WireBatch(rows.map {+ WireRecord(it.id, it.type.name, it.timestamp, it.value, it.delta)+ })+ pendingAck[device.address] = rows.map { it.id }++ val payload = json.encodeToString(batch).toByteArray(Charsets.UTF_8)+ val mtu = deviceMtu[device.address] ?: DEFAULT_MTU+ val chunkSize = (mtu - 3).coerceAtLeast(20)++ var offset = 0+ while (offset < payload.size) {+ val end = minOf(offset + chunkSize, payload.size)+ notify(device, payload.copyOfRange(offset, end))+ offset = end+ }+ // Zero-length batches still send EOT so the client can complete.+ notify(device, BleConstants.EOT_MARKER)+ }+ }++ @Suppress("DEPRECATION")+ private fun notify(device: BluetoothDevice, bytes: ByteArray) {+ val server = gattServer ?: return+ try {+ dataCharacteristic.value = bytes+ server.notifyCharacteristicChanged(device, dataCharacteristic, false)+ } catch (e: Exception) {+ Log.e(TAG, "notify failed", e)+ }+ }++ companion object {+ private const val TAG = "GattServerManager"+ private const val DEFAULT_MTU = 23+ }+}
watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.ktnew file mode 100644index 0000000000..fbb6cdf5a7--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt@@ -0,0 +1,65 @@+package com.vayunmathur.watch.watch.data++import android.content.Context+import androidx.room.Dao+import androidx.room.Database+import androidx.room.Entity+import androidx.room.Insert+import androidx.room.PrimaryKey+import androidx.room.Query+import androidx.room.Room+import androidx.room.RoomDatabase+import kotlinx.coroutines.flow.Flow++enum class MetricType {+ HeartRate,+ Steps,+}++@Entity+data class SensorRecord(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val type: MetricType,+ val timestamp: Long,+ // For HeartRate: the bpm reading. For Steps: cumulative counter value.+ val value: Double,+ // For Steps: increment since the previous reading. For HeartRate: 0.+ val delta: Double = 0.0,+)++@Dao+interface SensorDao {+ @Insert+ suspend fun insert(record: SensorRecord)++ @Query("SELECT * FROM SensorRecord ORDER BY timestamp ASC")+ suspend fun getAll(): List<SensorRecord>++ @Query("SELECT * FROM SensorRecord ORDER BY timestamp ASC")+ fun getAllFlow(): Flow<List<SensorRecord>>++ @Query("SELECT COUNT(*) FROM SensorRecord")+ fun countFlow(): Flow<Int>++ @Query("DELETE FROM SensorRecord WHERE id IN (:ids)")+ suspend fun deleteByIds(ids: List<Long>)+}++@Database(entities = [SensorRecord::class], version = 1, exportSchema = false)+abstract class SensorDatabase : RoomDatabase() {+ abstract fun sensorDao(): SensorDao++ companion object {+ @Volatile+ private var INSTANCE: SensorDatabase? = null++ fun get(context: Context): SensorDatabase =+ INSTANCE ?: synchronized(this) {+ INSTANCE ?: Room.databaseBuilder(+ context.applicationContext,+ SensorDatabase::class.java,+ "sensor.db",+ ).build().also { INSTANCE = it }+ }+ }+}
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.ktnew file mode 100644index 0000000000..da0a3da47b--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt@@ -0,0 +1,150 @@+package com.vayunmathur.watch.watch.service++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.hardware.Sensor+import android.hardware.SensorEvent+import android.hardware.SensorEventListener+import android.hardware.SensorManager+import android.os.IBinder+import android.util.Log+import com.vayunmathur.watch.watch.R+import com.vayunmathur.watch.watch.ble.GattServerManager+import com.vayunmathur.watch.watch.data.MetricType+import com.vayunmathur.watch.watch.data.SensorDatabase+import com.vayunmathur.watch.watch.data.SensorRecord+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++/**+ * Foreground service that listens to the native heart-rate and step-counter+ * sensors, persists readings to Room, and hosts the BLE GATT server that serves+ * those readings to the paired phone.+ */+class SensorBackgroundService : Service(), SensorEventListener {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)++ private lateinit var sensorManager: SensorManager+ private lateinit var gattServer: GattServerManager++ private var lastHeartRateAt = 0L+ // The step counter reports a cumulative count since boot; we store deltas.+ private var lastStepCount = -1.0++ override fun onCreate() {+ super.onCreate()+ val db = SensorDatabase.get(this)+ gattServer = GattServerManager(this, db.sensorDao(), scope)+ sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ startForeground(NOTIFICATION_ID, buildNotification())+ registerSensors()+ gattServer.start()+ return START_STICKY+ }++ private fun registerSensors() {+ sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE)?.let {+ sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)+ }+ sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)?.let {+ sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)+ }+ }++ override fun onSensorChanged(event: SensorEvent) {+ val now = System.currentTimeMillis()+ when (event.sensor.type) {+ Sensor.TYPE_HEART_RATE -> {+ val bpm = event.values.firstOrNull()?.toDouble() ?: return+ if (bpm <= 0.0) return+ // Sample roughly once per minute to conserve battery.+ if (now - lastHeartRateAt < HEART_RATE_INTERVAL_MS) return+ lastHeartRateAt = now+ persist(SensorRecord(type = MetricType.HeartRate, timestamp = now, value = bpm))+ }+ Sensor.TYPE_STEP_COUNTER -> {+ val cumulative = event.values.firstOrNull()?.toDouble() ?: return+ if (lastStepCount < 0.0) {+ lastStepCount = cumulative+ return+ }+ val delta = cumulative - lastStepCount+ lastStepCount = cumulative+ if (delta <= 0.0) return+ persist(+ SensorRecord(+ type = MetricType.Steps,+ timestamp = now,+ value = cumulative,+ delta = delta,+ ),+ )+ }+ }+ }++ private fun persist(record: SensorRecord) {+ val db = SensorDatabase.get(this)+ scope.launch(Dispatchers.IO) {+ try {+ db.sensorDao().insert(record)+ } catch (e: Exception) {+ Log.e(TAG, "insert failed", e)+ }+ }+ }++ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}++ private fun buildNotification(): Notification {+ val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ val channel = NotificationChannel(+ CHANNEL_ID,+ getString(R.string.notification_channel_name),+ NotificationManager.IMPORTANCE_LOW,+ )+ manager.createNotificationChannel(channel)+ return Notification.Builder(this, CHANNEL_ID)+ .setContentTitle(getString(R.string.notification_title))+ .setContentText(getString(R.string.notification_text))+ .setSmallIcon(R.drawable.ic_launcher_foreground)+ .setOngoing(true)+ .build()+ }++ override fun onDestroy() {+ sensorManager.unregisterListener(this)+ gattServer.stop()+ scope.cancel()+ super.onDestroy()+ }++ override fun onBind(intent: Intent?): IBinder? = null++ companion object {+ private const val TAG = "SensorBackgroundService"+ private const val CHANNEL_ID = "sensor_collection"+ private const val NOTIFICATION_ID = 1+ private const val HEART_RATE_INTERVAL_MS = 60_000L++ fun start(context: Context) {+ val intent = Intent(context, SensorBackgroundService::class.java)+ context.startForegroundService(intent)+ }++ fun stop(context: Context) {+ context.stopService(Intent(context, SensorBackgroundService::class.java))+ }+ }+}
watch/watch/src/main/res/drawable/ic_launcher_foreground.xml
diff --git a/watch/watch/src/main/res/drawable/ic_launcher_foreground.xml b/watch/watch/src/main/res/drawable/ic_launcher_foreground.xmlnew file mode 100644index 0000000000..b6440328d1--- /dev/null+++ b/watch/watch/src/main/res/drawable/ic_launcher_foreground.xml@@ -0,0 +1,15 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp"+ android:height="108dp"+ android:viewportWidth="960"+ android:viewportHeight="960"+ android:tint="#000000">+ <group android:scaleX="0.58"+ android:scaleY="0.58"+ android:translateX="201.6"+ android:translateY="201.6">+ <path+ android:fillColor="@android:color/white"+ android:pathData="M480,840Q462,840 445.5,833.5Q429,827 416,814L148,545Q113,510 96.5,465Q80,420 80,371Q80,268 147,194Q214,120 314,120Q362,120 404.5,139Q447,158 480,192L480,192L480,192Q512,158 554.5,139Q597,120 645,120Q745,120 812.5,194Q880,268 880,370Q880,419 863,464Q846,509 812,544L543,814Q530,827 514,833.5Q498,840 480,840ZM520,320Q530,320 539,325Q548,330 553,338L621,440L787,440Q794,423 797.5,405.5Q801,388 801,370Q799,301 755,251.5Q711,202 645,202Q614,202 585.5,214Q557,226 536,249L509,278Q504,284 496,287.5Q488,291 480,291Q472,291 464,287.5Q456,284 450,278L423,249Q402,226 374,213Q346,200 314,200Q248,200 204,250.5Q160,301 160,370Q160,388 163,405.5Q166,423 173,440L360,440Q370,440 379,445Q388,450 393,458L428,510L482,348Q486,336 496.5,328Q507,320 520,320ZM532,450L478,612Q474,624 463,632Q452,640 439,640Q429,640 420,635Q411,630 406,622L338,520L236,520L473,757Q475,759 476.5,759.5Q478,760 480,760Q482,760 483.5,759.5Q485,759 487,757L723,520L600,520Q590,520 581,515Q572,510 566,502L532,450Z"/>+ </group>+</vector>
watch/watch/src/main/res/mipmap-anydpi/ic_launcher.xml
diff --git a/watch/watch/src/main/res/mipmap-anydpi/ic_launcher.xml b/watch/watch/src/main/res/mipmap-anydpi/ic_launcher.xmlnew file mode 100644index 0000000000..0b0d585e42--- /dev/null+++ b/watch/watch/src/main/res/mipmap-anydpi/ic_launcher.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/ic_launcher_background"/>+ <foreground android:drawable="@drawable/ic_launcher_foreground"/>+ <monochrome android:drawable="@drawable/ic_launcher_foreground"/>+</adaptive-icon>
watch/watch/src/main/res/resources.properties
diff --git a/watch/watch/src/main/res/resources.properties b/watch/watch/src/main/res/resources.propertiesnew file mode 100644index 0000000000..467b3efec9--- /dev/null+++ b/watch/watch/src/main/res/resources.properties@@ -0,0 +1 @@+unqualifiedResLocale=en-US
watch/watch/src/main/res/values/ic_launcher_background.xml
diff --git a/watch/watch/src/main/res/values/ic_launcher_background.xml b/watch/watch/src/main/res/values/ic_launcher_background.xmlnew file mode 100644index 0000000000..cdde88fb8d--- /dev/null+++ b/watch/watch/src/main/res/values/ic_launcher_background.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <color name="ic_launcher_background">#000000</color>+</resources>
watch/watch/src/main/res/values/strings.xml
diff --git a/watch/watch/src/main/res/values/strings.xml b/watch/watch/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..e9bb044d5a--- /dev/null+++ b/watch/watch/src/main/res/values/strings.xml@@ -0,0 +1,14 @@+<resources>+ <string name="app_name">Health Collector</string>+ <string name="status_collecting">Collecting: %1$s</string>+ <string name="status_advertising">Advertising: %1$s</string>+ <string name="status_rows">Stored rows: %1$d</string>+ <string name="action_start">Start</string>+ <string name="action_stop">Stop</string>+ <string name="grant_permissions">Grant Permissions</string>+ <string name="on">on</string>+ <string name="off">off</string>+ <string name="notification_channel_name">Sensor Collection</string>+ <string name="notification_title">Collecting health data</string>+ <string name="notification_text">Reading sensors and serving over BLE</string>+</resources>
watch/watch/src/main/res/values/themes.xml
diff --git a/watch/watch/src/main/res/values/themes.xml b/watch/watch/src/main/res/values/themes.xmlnew file mode 100644index 0000000000..33bc3e6ca0--- /dev/null+++ b/watch/watch/src/main/res/values/themes.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <style name="AppTheme" parent="@android:style/Theme.DeviceDefault" />+</resources>