Krolyxon
Commit 744d2be

Branches

Refs →

budctl744d2be

android: the app, with Bluetooth and a plain screen

Step 4 of docs/android.md: a Kotlin app with libbudctl_android.so
inside, enough for the first phone checkpoints (A1, A2).

- Core.kt: the three native functions, and Platform, what the Rust
  worker calls on its own thread.
- Bluetooth.kt: Platform on Android's API. Paired devices from the
  adapter, "connected" from the A2DP and headset profiles; the RFCOMM
  socket through createRfcommSocketToServiceRecord (Android does the
  SDP lookup), with an 8 s watchdog since connect() takes no timeout.
  A refused connect while the audio link is up is "busy".
- Link.kt: a socket's input stream has no read timeout, so a thread
  reads it into a queue and recv waits on the queue. JVM tests cover it.
- MainActivity.kt: the status as text, the noise-control choices, a
  debug switch and the log with a copy button, so a checkpoint's output
  can be pasted from the phone. The worker runs only while the app is
  on screen (onStart/onStop), so the laptop gets the channel back.
- Gradle builds the Rust library with cargo-ndk (arm64-v8a; x86_64 too
  in debug builds, for the emulator), takes the version from
  Cargo.toml, and fails if the merged manifest asks for INTERNET
  (rule 1). There is no INTERNET permission.

Checked on the emulator (x86_64, Android 17): the permission prompt,
the library loading, commands reaching the worker and its events and
log lines reaching the screen ("no paired device": the emulator's
Bluetooth is simulated), the debug switch restarting the worker, and
the worker ending when the app leaves the screen.

New dependencies, all for the app: the Gradle wrapper (9.8.2, pinned
by checksum), the Android Gradle plugin and Kotlin's Compose plugin to
build it, Compose foundation and ui (the screen; no Material, the look
will be budctl's own), activity-compose (to host Compose and ask for
the permission), and junit for the JVM tests.
Author
krolyxon
Date
2026-11-01 22:27 +0530
Parent
e7b881a
Commit
744d2be7e4d50321ca7a001a79416e5504490c69

+973 −2

16 files changed

  1. M .gitignore +8 −0
  2. M CLAUDE.md +2 −0
  3. A android/app/build.gradle.kts +100 −0
  4. A android/app/src/main/AndroidManifest.xml +22 −0
  5. A android/app/src/main/kotlin/io/github/krolyxon/budctl/Bluetooth.kt +159 −0
  6. A android/app/src/main/kotlin/io/github/krolyxon/budctl/Core.kt +52 −0
  7. A android/app/src/main/kotlin/io/github/krolyxon/budctl/Link.kt +59 −0
  8. A android/app/src/main/kotlin/io/github/krolyxon/budctl/MainActivity.kt +231 −0
  9. A android/app/src/test/kotlin/io/github/krolyxon/budctl/LinkTest.kt +52 −0
  10. A android/build.gradle.kts +4 −0
  11. A android/gradle.properties +2 −0
  12. A android/gradle/wrapper/gradle-wrapper.jar
  13. A android/gradle/wrapper/gradle-wrapper.properties +10 −0
  14. A android/gradlew +248 −0
  15. A android/settings.gradle.kts +20 −0
  16. M docs/android.md +4 −2
M .gitignore View
@@ -5,3 +5,11 @@
55 /contrib/arch/pkg/
66 /contrib/arch/*.tar.gz
77 /contrib/arch/*.pkg.tar.*
8+# Gradle and Android Studio output in android/
9+/android/.gradle/
10+/android/.kotlin/
11+/android/build/
12+/android/app/build/
13+/android/local.properties
14+/android/.idea/
15+*.iml
M CLAUDE.md View
@@ -37,6 +37,7 @@ The first supported device is the **realme Buds T310**. More devices are added a
3737 - `crates/budctl-cli`: package and binary `budctl`.
3838 - `crates/budctl-gui`: package and binary `budctl-gui`, built with iced 0.14 for Wayland only, with the CPU renderer (tiny-skia).
3939 - `crates/budctl-android`: `libbudctl_android.so` for the Android app, built with `cargo ndk`: three JNI exports, JSON commands and events, and a `Transport` over the app's Bluetooth link (`docs/android.md#boundary`).
40+- The Android app, `android/` (Gradle, Kotlin, Compose; application id `io.github.krolyxon.budctl`, minSdk 31): `cd android && ./gradlew assembleDebug testDebugUnitTest`, with `JAVA_HOME=/opt/android-studio/jbr` on the owner's machine. Gradle runs cargo-ndk for the Rust library (arm64-v8a, plus x86_64 for the emulator in debug builds) and fails the build if the merged manifest asks for `INTERNET`. The app's Bluetooth code is `Bluetooth.kt` and `Link.kt`.
4041 - On Linux, Bluetooth goes through BlueZ:
4142 - Raw `AF_BLUETOOTH` sockets via `libc`: RFCOMM for the control link, L2CAP to read the buds' SDP record.
4243 - `zbus` (blocking API) only to list paired devices.
@@ -48,6 +49,7 @@ The first supported device is the **realme Buds T310**. More devices are added a
4849 - cli: `clap`, `serde_json`
4950 - gui: `iced`, `serde`, `serde_json`; `iced_test` for tests
5051 - android: `jni`, `serde`, `serde_json`
52+ - the Android app: the Compose BOM (`foundation`, `ui`) and `activity-compose`; `junit` for tests
5153
5254 ## Device plugin contract
5355
A android/app/build.gradle.kts View
@@ -0,0 +1,100 @@
1+import com.android.build.api.artifact.SingleArtifact
2+
3+plugins {
4+ id("com.android.application")
5+ id("org.jetbrains.kotlin.plugin.compose")
6+}
7+
8+// One version for everything (CLAUDE.md, releases): the cargo workspace's.
9+val workspace: File = rootDir.parentFile
10+val version: String = workspace.resolve("Cargo.toml").readLines()
11+ .first { it.startsWith("version = ") }
12+ .substringAfter('"').substringBefore('"')
13+
14+android {
15+ namespace = "io.github.krolyxon.budctl"
16+ compileSdk = 37
17+ // For stripping the Rust library's debug symbols from the APK, and for cargo-ndk.
18+ ndkVersion = "30.0.16248370"
19+
20+ defaultConfig {
21+ applicationId = "io.github.krolyxon.budctl"
22+ // Android 12: BLUETOOTH_CONNECT begins there (docs/android.md#bluetooth).
23+ minSdk = 31
24+ targetSdk = 37
25+ versionName = version
26+ versionCode = version.split('.').fold(0) { code, part -> code * 100 + part.toInt() }
27+ }
28+
29+ buildTypes {
30+ // Only where the Rust library is built for: the phone, and the emulator in debug builds.
31+ debug {
32+ ndk { abiFilters += listOf("arm64-v8a", "x86_64") }
33+ }
34+ release {
35+ ndk { abiFilters += listOf("arm64-v8a") }
36+ // The Rust library calls Platform's methods by name, so nothing may rename them.
37+ isMinifyEnabled = false
38+ }
39+ }
40+
41+ buildFeatures {
42+ compose = true
43+ }
44+}
45+
46+dependencies {
47+ implementation(platform("androidx.compose:compose-bom:2026.09.00"))
48+ implementation("androidx.activity:activity-compose:1.13.0")
49+ implementation("androidx.compose.foundation:foundation")
50+ implementation("androidx.compose.ui:ui")
51+ testImplementation("junit:junit:4.13.2")
52+}
53+
54+/** The Rust library (crates/budctl-android), built by cargo-ndk into [output]/<abi>/. */
55+abstract class CargoNdk : Exec() {
56+ @get:OutputDirectory
57+ abstract val output: DirectoryProperty
58+}
59+
60+/** Rule 1 (CLAUDE.md): the app never gets network access, not even from a library's manifest. */
61+abstract class CheckNoInternet : DefaultTask() {
62+ @get:InputFile
63+ abstract val manifest: RegularFileProperty
64+
65+ @TaskAction
66+ fun check() {
67+ if ("android.permission.INTERNET" in manifest.get().asFile.readText()) {
68+ throw GradleException("The merged manifest asks for INTERNET; budctl must not (CLAUDE.md rule 1).")
69+ }
70+ }
71+}
72+
73+androidComponents {
74+ onVariants { variant ->
75+ val name = variant.name.replaceFirstChar { it.uppercase() }
76+ val release = variant.buildType == "release"
77+ // Debug builds also run on the emulator (x86_64); releases only on the phone.
78+ val abis = if (release) listOf("arm64-v8a") else listOf("arm64-v8a", "x86_64")
79+ val ndk = sdkComponents.ndkDirectory
80+
81+ val cargo = tasks.register<CargoNdk>("cargoNdk$name") {
82+ workingDir = workspace
83+ executable = "cargo"
84+ // Cargo knows what to rebuild, so it always runs.
85+ outputs.upToDateWhen { false }
86+ argumentProviders.add {
87+ listOf("ndk", "--platform", "31") + abis.flatMap { listOf("--target", it) } +
88+ listOf("--output-dir", output.get().asFile.path, "build", "-p", "budctl-android") +
89+ if (release) listOf("--release") else emptyList()
90+ }
91+ doFirst { environment("ANDROID_NDK_HOME", ndk.get().asFile.path) }
92+ }
93+ variant.sources.jniLibs?.addGeneratedSourceDirectory(cargo, CargoNdk::output)
94+
95+ val check = tasks.register<CheckNoInternet>("check${name}NoInternet") {
96+ manifest.set(variant.artifacts.get(SingleArtifact.MERGED_MANIFEST))
97+ }
98+ tasks.matching { it.name == "package$name" }.configureEach { dependsOn(check) }
99+ }
100+}
A android/app/src/main/AndroidManifest.xml View
@@ -0,0 +1,22 @@
1+<?xml version="1.0" encoding="utf-8"?>
2+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
3+
4+ <!-- Bluetooth only. There is no INTERNET permission, so the app cannot reach the network
5+ (CLAUDE.md rule 1); the build fails if a library adds it. -->
6+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
7+ <uses-feature android:name="android.hardware.bluetooth" android:required="true" />
8+
9+ <application
10+ android:allowBackup="false"
11+ android:label="budctl"
12+ android:theme="@android:style/Theme.Material.NoActionBar">
13+ <activity
14+ android:name=".MainActivity"
15+ android:exported="true">
16+ <intent-filter>
17+ <action android:name="android.intent.action.MAIN" />
18+ <category android:name="android.intent.category.LAUNCHER" />
19+ </intent-filter>
20+ </activity>
21+ </application>
22+</manifest>
A android/app/src/main/kotlin/io/github/krolyxon/budctl/Bluetooth.kt View
@@ -0,0 +1,159 @@
1+package io.github.krolyxon.budctl
2+
3+import android.annotation.SuppressLint
4+import android.bluetooth.BluetoothAdapter
5+import android.bluetooth.BluetoothDevice
6+import android.bluetooth.BluetoothManager
7+import android.bluetooth.BluetoothProfile
8+import android.content.Context
9+import java.io.IOException
10+import java.util.Timer
11+import java.util.UUID
12+import java.util.concurrent.ConcurrentHashMap
13+import java.util.concurrent.CountDownLatch
14+import java.util.concurrent.TimeUnit
15+import java.util.concurrent.atomic.AtomicBoolean
16+import kotlin.concurrent.schedule
17+import org.json.JSONArray
18+import org.json.JSONObject
19+
20+/**
21+ * The phone's side of the worker (docs/android.md#bluetooth): the paired devices and one RFCOMM
22+ * link, used by the Rust worker on its own thread, and where its events and log lines go.
23+ * Written from Android's API reference.
24+ */
25+@SuppressLint("MissingPermission") // The activity starts the worker only once BLUETOOTH_CONNECT is granted.
26+class Bluetooth(
27+ context: Context,
28+ private val onEvent: (String) -> Unit,
29+ private val onLog: (String) -> Unit,
30+) : Platform {
31+ private val adapter: BluetoothAdapter? = context.getSystemService(BluetoothManager::class.java)?.adapter
32+ private val profiles = ConcurrentHashMap<Int, BluetoothProfile>()
33+ private val profilesReady = CountDownLatch(AUDIO_PROFILES.size)
34+
35+ @Volatile
36+ private var link: Link? = null
37+
38+ init {
39+ val listener = object : BluetoothProfile.ServiceListener {
40+ override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
41+ profiles[profile] = proxy
42+ profilesReady.countDown()
43+ }
44+
45+ override fun onServiceDisconnected(profile: Int) {
46+ profiles.remove(profile)
47+ }
48+ }
49+ for (profile in AUDIO_PROFILES) {
50+ if (adapter?.getProfileProxy(context, listener, profile) != true) profilesReady.countDown()
51+ }
52+ }
53+
54+ /** Whether the buds' audio link is up: their control channel only opens then. */
55+ private fun connected(device: BluetoothDevice): Boolean {
56+ // The proxies come soon after start; this runs on the worker's thread, so it may wait.
57+ profilesReady.await(PROFILE_WAIT_MS, TimeUnit.MILLISECONDS)
58+ return profiles.values.any { it.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED }
59+ }
60+
61+ override fun pairedDevices(): String {
62+ val list = JSONArray()
63+ for (device in adapter?.bondedDevices.orEmpty()) {
64+ list.put(
65+ JSONObject()
66+ .put("address", device.address)
67+ .put("name", device.name ?: "")
68+ .put("alias", device.alias ?: device.name ?: device.address)
69+ .put("connected", connected(device))
70+ .put("uuids", JSONArray(device.uuids.orEmpty().map { it.uuid.toString() })),
71+ )
72+ }
73+ return list.toString()
74+ }
75+
76+ override fun connect(address: String, service: String): String? {
77+ close()
78+ val adapter = adapter ?: return failure("not-connected", "this phone has no Bluetooth")
79+ if (!adapter.isEnabled) return failure("not-connected", "Bluetooth is off")
80+ val device = adapter.getRemoteDevice(address)
81+ val socket = try {
82+ device.createRfcommSocketToServiceRecord(UUID.fromString(service))
83+ } catch (e: IOException) {
84+ return failure("failed", "could not make an RFCOMM socket: ${e.message}")
85+ }
86+ // connect() takes no timeout: a watchdog closes the socket after 8 s, when budctl gives
87+ // up on Linux too.
88+ val timedOut = AtomicBoolean(false)
89+ val watchdog = Timer("budctl-connect", true)
90+ watchdog.schedule(CONNECT_TIMEOUT_MS) {
91+ timedOut.set(true)
92+ quietly { socket.close() }
93+ }
94+ try {
95+ socket.connect()
96+ } catch (e: IOException) {
97+ quietly { socket.close() }
98+ val detail = e.message ?: "refused"
99+ return when {
100+ timedOut.get() -> failure("timeout", "the control channel did not connect in 8 s")
101+ // The audio link is up but the control channel refused: someone else holds it.
102+ connected(device) -> failure("busy", detail)
103+ else -> failure("not-connected", "the buds are not connected ($detail)")
104+ }
105+ } finally {
106+ watchdog.cancel()
107+ }
108+ link = Link(socket.inputStream, socket.outputStream, socket)
109+ return null
110+ }
111+
112+ override fun send(bytes: ByteArray): String? {
113+ val link = link ?: return "no link is open"
114+ return try {
115+ link.send(bytes)
116+ null
117+ } catch (e: IOException) {
118+ e.message ?: "the link failed"
119+ }
120+ }
121+
122+ override fun recv(timeoutMs: Long): ByteArray? {
123+ val link = link ?: return ByteArray(0)
124+ return link.recv(timeoutMs)
125+ }
126+
127+ override fun close() {
128+ link?.close()
129+ link = null
130+ }
131+
132+ override fun event(json: String) = onEvent(json)
133+
134+ override fun log(line: String) = onLog(line)
135+
136+ /** Lets go of everything, once the app is done with Bluetooth. */
137+ fun release() {
138+ close()
139+ for ((profile, proxy) in profiles) adapter?.closeProfileProxy(profile, proxy)
140+ profiles.clear()
141+ }
142+
143+ private fun failure(kind: String, message: String): String =
144+ JSONObject().put("kind", kind).put("message", message).toString()
145+
146+ private inline fun quietly(block: () -> Unit) {
147+ try {
148+ block()
149+ } catch (_: IOException) {
150+ // Closing what is already closed.
151+ }
152+ }
153+
154+ private companion object {
155+ val AUDIO_PROFILES = listOf(BluetoothProfile.A2DP, BluetoothProfile.HEADSET)
156+ const val PROFILE_WAIT_MS = 2_000L
157+ const val CONNECT_TIMEOUT_MS = 8_000L
158+ }
159+}
A android/app/src/main/kotlin/io/github/krolyxon/budctl/Core.kt View
@@ -0,0 +1,52 @@
1+package io.github.krolyxon.budctl
2+
3+/**
4+ * budctl-core, in libbudctl_android.so (crates/budctl-android): the worker that owns the session
5+ * with the buds. See docs/android.md#boundary.
6+ */
7+object Core {
8+ init {
9+ System.loadLibrary("budctl_android")
10+ }
11+
12+ /** Starts the worker, in place of any running one. Null, or why it could not start. */
13+ @JvmStatic
14+ external fun start(platform: Platform, idleMs: Long, debug: Boolean): String?
15+
16+ /** Queues one command (JSON); its event comes back through [Platform.event]. Null, or why not. */
17+ @JvmStatic
18+ external fun command(json: String): String?
19+
20+ /** Ends the worker, which closes any session once the command at hand is done. */
21+ @JvmStatic
22+ external fun stop()
23+}
24+
25+/**
26+ * What the worker calls, on its own thread. The Rust side calls these by name, so they keep their
27+ * names and signatures. None of them throws: a failure is an answer.
28+ */
29+interface Platform {
30+ /** The paired devices, as JSON: address, name, alias, connected, service UUIDs. */
31+ fun pairedDevices(): String
32+
33+ /**
34+ * Opens the RFCOMM link to [service] on the device at [address], in place of any open one.
35+ * Null, or `{"kind", "message"}` with the kind `busy`, `not-connected`, `timeout` or `failed`.
36+ */
37+ fun connect(address: String, service: String): String?
38+
39+ /** Null, or why the link failed. */
40+ fun send(bytes: ByteArray): String?
41+
42+ /** The next bytes; null once [timeoutMs] passes; an empty array once the link is closed. */
43+ fun recv(timeoutMs: Long): ByteArray?
44+
45+ fun close()
46+
47+ /** One worker event, as JSON. */
48+ fun event(json: String)
49+
50+ /** A session or debug line. */
51+ fun log(line: String)
52+}
A android/app/src/main/kotlin/io/github/krolyxon/budctl/Link.kt View
@@ -0,0 +1,59 @@
1+package io.github.krolyxon.budctl
2+
3+import java.io.Closeable
4+import java.io.IOException
5+import java.io.InputStream
6+import java.io.OutputStream
7+import java.util.concurrent.LinkedBlockingQueue
8+import java.util.concurrent.TimeUnit
9+import kotlin.concurrent.thread
10+
11+/**
12+ * One RFCOMM link to the buds. A Bluetooth socket's input stream has no read timeout, so a thread
13+ * of its own reads it into a queue and [recv] waits on the queue. Closing the socket ends that
14+ * thread.
15+ */
16+class Link(private val input: InputStream, private val output: OutputStream, private val socket: Closeable) {
17+ private val received = LinkedBlockingQueue<ByteArray>()
18+
19+ init {
20+ thread(name = "budctl-link", isDaemon = true) {
21+ val buffer = ByteArray(1024)
22+ try {
23+ while (true) {
24+ val n = input.read(buffer)
25+ if (n < 0) break
26+ if (n > 0) received.put(buffer.copyOf(n))
27+ }
28+ } catch (_: IOException) {
29+ // Closed, by us or by the buds.
30+ }
31+ received.put(CLOSED)
32+ }
33+ }
34+
35+ fun send(bytes: ByteArray) {
36+ output.write(bytes)
37+ output.flush()
38+ }
39+
40+ /** The next bytes; null if none came within [timeoutMs]; an empty array once the link is closed. */
41+ fun recv(timeoutMs: Long): ByteArray? {
42+ val bytes = received.poll(timeoutMs, TimeUnit.MILLISECONDS) ?: return null
43+ // Closed stays closed, for the next call too.
44+ if (bytes.isEmpty()) received.put(CLOSED)
45+ return bytes
46+ }
47+
48+ fun close() {
49+ try {
50+ socket.close()
51+ } catch (_: IOException) {
52+ // Already closed.
53+ }
54+ }
55+
56+ private companion object {
57+ val CLOSED = ByteArray(0)
58+ }
59+}
A android/app/src/main/kotlin/io/github/krolyxon/budctl/MainActivity.kt View
@@ -0,0 +1,231 @@
1+package io.github.krolyxon.budctl
2+
3+import android.Manifest
4+import android.content.ClipData
5+import android.content.ClipboardManager
6+import android.content.pm.PackageManager
7+import android.os.Bundle
8+import android.util.Log
9+import androidx.activity.ComponentActivity
10+import androidx.activity.compose.setContent
11+import androidx.activity.enableEdgeToEdge
12+import androidx.activity.result.contract.ActivityResultContracts
13+import androidx.compose.foundation.background
14+import androidx.compose.foundation.clickable
15+import androidx.compose.foundation.layout.Arrangement
16+import androidx.compose.foundation.layout.Column
17+import androidx.compose.foundation.layout.Row
18+import androidx.compose.foundation.layout.fillMaxSize
19+import androidx.compose.foundation.layout.padding
20+import androidx.compose.foundation.layout.safeDrawingPadding
21+import androidx.compose.foundation.rememberScrollState
22+import androidx.compose.foundation.shape.RoundedCornerShape
23+import androidx.compose.foundation.text.BasicText
24+import androidx.compose.foundation.verticalScroll
25+import androidx.compose.runtime.Composable
26+import androidx.compose.runtime.getValue
27+import androidx.compose.runtime.mutableStateListOf
28+import androidx.compose.runtime.mutableStateOf
29+import androidx.compose.runtime.setValue
30+import androidx.compose.ui.Modifier
31+import androidx.compose.ui.draw.clip
32+import androidx.compose.ui.graphics.Color
33+import androidx.compose.ui.text.TextStyle
34+import androidx.compose.ui.text.font.FontFamily
35+import androidx.compose.ui.unit.dp
36+import androidx.compose.ui.unit.sp
37+import org.json.JSONObject
38+
39+/**
40+ * The plain screen of step 4 (docs/android.md#steps): what the buds report, the noise-control
41+ * choices, and the log, for checkpoints A1 and A2. The real pages come in step 5.
42+ *
43+ * The worker runs while the app is on screen: it starts in onStart and stops in onStop, so the
44+ * control channel is free for the laptop once the app is left.
45+ */
46+class MainActivity : ComponentActivity() {
47+ private lateinit var bluetooth: Bluetooth
48+
49+ private var permitted by mutableStateOf(false)
50+ private var debug by mutableStateOf(false)
51+ private var name by mutableStateOf<String?>(null)
52+ private var status by mutableStateOf<JSONObject?>(null)
53+ private var waiting by mutableStateOf(false)
54+ private var problem by mutableStateOf<String?>(null)
55+ private val log = mutableStateListOf<String>()
56+
57+ private val askPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
58+ permitted = granted
59+ if (granted) startWorker()
60+ }
61+
62+ override fun onCreate(savedInstanceState: Bundle?) {
63+ super.onCreate(savedInstanceState)
64+ enableEdgeToEdge()
65+ bluetooth = Bluetooth(
66+ this,
67+ onEvent = { json -> runOnUiThread { answer(JSONObject(json)) } },
68+ onLog = { line ->
69+ Log.i(TAG, line)
70+ runOnUiThread { addLine(line) }
71+ },
72+ )
73+ debug = getSharedPreferences(PREFERENCES, MODE_PRIVATE).getBoolean("debug", false)
74+ permitted = checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
75+ if (!permitted) askPermission.launch(Manifest.permission.BLUETOOTH_CONNECT)
76+ setContent { Screen() }
77+ }
78+
79+ override fun onStart() {
80+ super.onStart()
81+ if (permitted) startWorker()
82+ }
83+
84+ override fun onStop() {
85+ super.onStop()
86+ Core.stop()
87+ }
88+
89+ override fun onDestroy() {
90+ super.onDestroy()
91+ bluetooth.release()
92+ }
93+
94+ private fun startWorker() {
95+ val failure = Core.start(bluetooth, IDLE_MS, debug)
96+ if (failure != null) problem = failure else send(JSONObject().put("command", "read"))
97+ }
98+
99+ private fun send(command: JSONObject) {
100+ waiting = true
101+ Core.command(command.toString())?.let {
102+ problem = it
103+ waiting = false
104+ }
105+ }
106+
107+ private fun noise(mode: String) = send(JSONObject().put("command", "noise").put("mode", mode))
108+
109+ /** One event from the worker, on the main thread. */
110+ private fun answer(event: JSONObject) {
111+ when (event.getString("event")) {
112+ "found" -> name = event.getString("name")
113+ "lost" -> problem = event.getString("message")
114+ else -> {
115+ waiting = false
116+ when (event.getString("event")) {
117+ "read" -> {
118+ status = event.getJSONObject("status")
119+ problem = null
120+ }
121+ "noise" -> {
122+ val now = JSONObject().put("mode", event.getString("mode")).put("level", event.opt("level"))
123+ status = JSONObject(status?.toString() ?: "{}").put("noise_control", now)
124+ problem = null
125+ }
126+ "failed" -> problem = event.getString("message")
127+ }
128+ }
129+ }
130+ }
131+
132+ private fun addLine(line: String) {
133+ log.add(line)
134+ if (log.size > MAX_LINES) log.removeRange(0, log.size - MAX_LINES)
135+ }
136+
137+ private fun toggleDebug() {
138+ debug = !debug
139+ getSharedPreferences(PREFERENCES, MODE_PRIVATE).edit().putBoolean("debug", debug).apply()
140+ Core.stop()
141+ if (permitted) startWorker()
142+ }
143+
144+ private fun copyLog() {
145+ val clipboard = getSystemService(ClipboardManager::class.java)
146+ clipboard.setPrimaryClip(ClipData.newPlainText("budctl log", log.joinToString("\n")))
147+ }
148+
149+ @Composable
150+ private fun Screen() {
151+ Column(
152+ Modifier
153+ .fillMaxSize()
154+ .background(Color.Black)
155+ .safeDrawingPadding()
156+ .verticalScroll(rememberScrollState())
157+ .padding(16.dp),
158+ verticalArrangement = Arrangement.spacedBy(14.dp),
159+ ) {
160+ BasicText(name ?: "budctl", style = TEXT.copy(fontSize = 26.sp))
161+ if (!permitted) {
162+ BasicText("budctl needs the Nearby devices permission to reach the buds.", style = TEXT)
163+ Chip("Allow") { askPermission.launch(Manifest.permission.BLUETOOTH_CONNECT) }
164+ return@Column
165+ }
166+ problem?.let { BasicText(it, style = TEXT.copy(color = RED)) }
167+ if (waiting) BasicText("Working…", style = DIM)
168+ status?.let { Status(it) }
169+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
170+ Chip("Off") { noise("off") }
171+ Chip("Transparency") { noise("transparency") }
172+ Chip("ANC") { noise("anc") }
173+ }
174+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
175+ Chip("Read") { send(JSONObject().put("command", "read")) }
176+ Chip(if (debug) "Debug on" else "Debug off") { toggleDebug() }
177+ Chip("Copy log") { copyLog() }
178+ }
179+ BasicText(log.joinToString("\n"), style = DIM.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp))
180+ }
181+ }
182+
183+ @Composable
184+ private fun Status(status: JSONObject) {
185+ val battery = status.optJSONObject("battery")
186+ val charges = listOf("left" to "L", "right" to "R", "case" to "Case").mapNotNull { (key, label) ->
187+ battery?.optJSONObject(key)?.let { charge ->
188+ "$label ${charge.getInt("level")}%" + if (charge.getBoolean("charging")) " (charging)" else ""
189+ }
190+ }
191+ val lines = mutableListOf("Battery: " + charges.joinToString(" · ").ifEmpty { "unknown" })
192+ status.optJSONObject("noise_control")?.let { noise ->
193+ lines += "Noise control: " + noise.getString("mode") +
194+ (noise.optString("level").takeUnless { it.isEmpty() || it == "null" }?.let { " ($it)" } ?: "")
195+ }
196+ status.optString("eq").takeUnless { it.isEmpty() || it == "null" }?.let { lines += "EQ: $it" }
197+ status.optJSONArray("switches")?.let { switches ->
198+ for (i in 0 until switches.length()) {
199+ val switch = switches.getJSONObject(i)
200+ lines += switch.getString("label") + ": " + if (switch.getBoolean("on")) "on" else "off"
201+ }
202+ }
203+ status.optString("codec").takeUnless { it.isEmpty() || it == "null" }?.let { lines += "Codec: $it" }
204+ status.optString("firmware").takeUnless { it.isEmpty() || it == "null" }?.let { lines += "Firmware: $it" }
205+ BasicText(lines.joinToString("\n"), style = TEXT)
206+ }
207+
208+ @Composable
209+ private fun Chip(label: String, onClick: () -> Unit) {
210+ BasicText(
211+ label,
212+ style = TEXT.copy(color = Color.Black),
213+ modifier = Modifier
214+ .clip(RoundedCornerShape(50))
215+ .background(Color.White)
216+ .clickable(onClick = onClick)
217+ .padding(horizontal = 16.dp, vertical = 10.dp),
218+ )
219+ }
220+
221+ private companion object {
222+ const val TAG = "budctl"
223+ const val PREFERENCES = "budctl"
224+ /** How long a session stays open after the last command, as on the desktop. */
225+ const val IDLE_MS = 10_000L
226+ const val MAX_LINES = 1_000
227+ val TEXT = TextStyle(color = Color.White, fontSize = 15.sp)
228+ val DIM = TEXT.copy(color = Color(0xFF9A9A9A))
229+ val RED = Color(0xFFFF5A4F)
230+ }
231+}
A android/app/src/test/kotlin/io/github/krolyxon/budctl/LinkTest.kt View
@@ -0,0 +1,52 @@
1+package io.github.krolyxon.budctl
2+
3+import java.io.ByteArrayOutputStream
4+import java.io.PipedInputStream
5+import java.io.PipedOutputStream
6+import org.junit.Assert.assertArrayEquals
7+import org.junit.Assert.assertNull
8+import org.junit.Assert.assertTrue
9+import org.junit.Test
10+
11+/** The link's reader thread and timeouts, with pipes for the socket. */
12+class LinkTest {
13+ private val buds = PipedOutputStream()
14+ private val sent = ByteArrayOutputStream()
15+ private var closed = false
16+
17+ // Closing the socket ends the stream, as with a real one.
18+ private val link = Link(PipedInputStream(buds), sent) {
19+ closed = true
20+ buds.close()
21+ }
22+
23+ @Test
24+ fun bytesFromTheBudsArrive() {
25+ buds.write(byteArrayOf(0xAA.toByte(), 0x07))
26+ buds.flush()
27+ assertArrayEquals(byteArrayOf(0xAA.toByte(), 0x07), link.recv(1_000))
28+ }
29+
30+ @Test
31+ fun silenceIsNullOnceTheTimeRunsOut() {
32+ val start = System.nanoTime()
33+ assertNull(link.recv(100))
34+ assertTrue("waited the timeout", System.nanoTime() - start >= 90_000_000)
35+ }
36+
37+ @Test
38+ fun aClosedLinkStaysClosed() {
39+ buds.close()
40+ assertArrayEquals(ByteArray(0), link.recv(1_000))
41+ assertArrayEquals(ByteArray(0), link.recv(1_000))
42+ }
43+
44+ @Test
45+ fun sendWritesAndCloseClosesTheSocket() {
46+ link.send(byteArrayOf(0x01, 0x02))
47+ assertArrayEquals(byteArrayOf(0x01, 0x02), sent.toByteArray())
48+ link.close()
49+ assertTrue(closed)
50+ assertArrayEquals(ByteArray(0), link.recv(1_000))
51+ }
52+}
A android/build.gradle.kts View
@@ -0,0 +1,4 @@
1+plugins {
2+ id("com.android.application") version "9.5.0" apply false
3+ id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false
4+}
A android/gradle.properties View
@@ -0,0 +1,2 @@
1+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
2+android.useAndroidX=true
A android/gradle/wrapper/gradle-wrapper.jar View

[Binary file]

A android/gradle/wrapper/gradle-wrapper.properties View
@@ -0,0 +1,10 @@
1+distributionBase=GRADLE_USER_HOME
2+distributionPath=wrapper/dists
3+distributionSha256Sum=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607
4+distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
5+networkTimeout=10000
6+retries=0
7+retryBackOffMs=500
8+validateDistributionUrl=true
9+zipStoreBase=GRADLE_USER_HOME
10+zipStorePath=wrapper/dists
A android/gradlew View
@@ -0,0 +1,248 @@
1+#!/bin/sh
2+
3+#
4+# Copyright © 2015 the original authors.
5+#
6+# Licensed under the Apache License, Version 2.0 (the "License");
7+# you may not use this file except in compliance with the License.
8+# You may obtain a copy of the License at
9+#
10+# https://www.apache.org/licenses/LICENSE-2.0
11+#
12+# Unless required by applicable law or agreed to in writing, software
13+# distributed under the License is distributed on an "AS IS" BASIS,
14+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+# See the License for the specific language governing permissions and
16+# limitations under the License.
17+#
18+# SPDX-License-Identifier: Apache-2.0
19+#
20+
21+##############################################################################
22+#
23+# gradlew start up script for POSIX generated by Gradle.
24+#
25+# Important for running:
26+#
27+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28+# noncompliant, but you have some other compliant shell such as ksh or
29+# bash, then to run this script, type that shell name before the whole
30+# command line, like:
31+#
32+# ksh gradlew
33+#
34+# Busybox and similar reduced shells will NOT work, because this script
35+# requires all of these POSIX shell features:
36+# * functions;
37+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39+# * compound commands having a testable exit status, especially «case»;
40+# * various built-in commands including «command», «set», and «ulimit».
41+#
42+# Important for patching:
43+#
44+# (2) This script targets any POSIX shell, so it avoids extensions provided
45+# by Bash, Ksh, etc; in particular arrays are avoided.
46+#
47+# The "traditional" practice of packing multiple parameters into a
48+# space-separated string is a well documented source of bugs and security
49+# problems, so this is (mostly) avoided, by progressively accumulating
50+# options in "$@", and eventually passing that to Java.
51+#
52+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54+# see the in-line comments for details.
55+#
56+# There are tweaks for specific operating systems such as AIX, CygWin,
57+# Darwin, MinGW, and NonStop.
58+#
59+# (3) This script is generated from the Groovy template
60+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61+# within the Gradle project.
62+#
63+# You can find Gradle at https://github.com/gradle/gradle/.
64+#
65+##############################################################################
66+
67+# Attempt to set APP_HOME
68+
69+# Resolve links: $0 may be a link
70+app_path=$0
71+
72+# Need this for daisy-chained symlinks.
73+while
74+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75+ [ -h "$app_path" ]
76+do
77+ ls=$( ls -ld "$app_path" )
78+ link=${ls#*' -> '}
79+ case $link in #(
80+ /*) app_path=$link ;; #(
81+ *) app_path=$APP_HOME$link ;;
82+ esac
83+done
84+
85+# This is normally unused
86+# shellcheck disable=SC2034
87+APP_BASE_NAME=${0##*/}
88+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
90+
91+# Use the maximum available, or set MAX_FD != -1 to use that value.
92+MAX_FD=maximum
93+
94+warn () {
95+ echo "$*"
96+} >&2
97+
98+die () {
99+ echo
100+ echo "$*"
101+ echo
102+ exit 1
103+} >&2
104+
105+# OS specific support (must be 'true' or 'false').
106+cygwin=false
107+msys=false
108+darwin=false
109+nonstop=false
110+case "$( uname )" in #(
111+ CYGWIN* ) cygwin=true ;; #(
112+ Darwin* ) darwin=true ;; #(
113+ MSYS* | MINGW* ) msys=true ;; #(
114+ NONSTOP* ) nonstop=true ;;
115+esac
116+
117+
118+
119+# Determine the Java command to use to start the JVM.
120+if [ -n "$JAVA_HOME" ] ; then
121+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
122+ # IBM's JDK on AIX uses strange locations for the executables
123+ JAVACMD=$JAVA_HOME/jre/sh/java
124+ else
125+ JAVACMD=$JAVA_HOME/bin/java
126+ fi
127+ if [ ! -x "$JAVACMD" ] ; then
128+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
129+
130+Please set the JAVA_HOME variable in your environment to match the
131+location of your Java installation."
132+ fi
133+else
134+ JAVACMD=java
135+ if ! command -v java >/dev/null 2>&1
136+ then
137+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
138+
139+Please set the JAVA_HOME variable in your environment to match the
140+location of your Java installation."
141+ fi
142+fi
143+
144+# Increase the maximum file descriptors if we can.
145+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
146+ case $MAX_FD in #(
147+ max*)
148+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
149+ # shellcheck disable=SC2039,SC3045
150+ MAX_FD=$( ulimit -H -n ) ||
151+ warn "Could not query maximum file descriptor limit"
152+ esac
153+ case $MAX_FD in #(
154+ '' | soft) :;; #(
155+ *)
156+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
157+ # shellcheck disable=SC2039,SC3045
158+ ulimit -n "$MAX_FD" ||
159+ warn "Could not set maximum file descriptor limit to $MAX_FD"
160+ esac
161+fi
162+
163+# Collect all arguments for the java command, stacking in reverse order:
164+# * args from the command line
165+# * the main class name
166+# * -classpath
167+# * -D...appname settings
168+# * --module-path (only if needed)
169+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
170+
171+# For Cygwin or MSYS, switch paths to Windows format before running java
172+if "$cygwin" || "$msys" ; then
173+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
174+
175+ JAVACMD=$( cygpath --unix "$JAVACMD" )
176+
177+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
178+ for arg do
179+ if
180+ case $arg in #(
181+ -*) false ;; # don't mess with options #(
182+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183+ [ -e "$t" ] ;; #(
184+ *) false ;;
185+ esac
186+ then
187+ arg=$( cygpath --path --ignore --mixed "$arg" )
188+ fi
189+ # Roll the args list around exactly as many times as the number of
190+ # args, so each arg winds up back in the position where it started, but
191+ # possibly modified.
192+ #
193+ # NB: a `for` loop captures its iteration list before it begins, so
194+ # changing the positional parameters here affects neither the number of
195+ # iterations, nor the values presented in `arg`.
196+ shift # remove old arg
197+ set -- "$@" "$arg" # push replacement arg
198+ done
199+fi
200+
201+
202+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204+
205+# Collect all arguments for the java command:
206+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207+# and any embedded shellness will be escaped.
208+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209+# treated as '${Hostname}' itself on the command line.
210+
211+set -- \
212+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
213+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
214+ "$@"
215+
216+# Stop when "xargs" is not available.
217+if ! command -v xargs >/dev/null 2>&1
218+then
219+ die "xargs is not available"
220+fi
221+
222+# Use "xargs" to parse quoted args.
223+#
224+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
225+#
226+# In Bash we could simply go:
227+#
228+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
229+# set -- "${ARGS[@]}" "$@"
230+#
231+# but POSIX shell has neither arrays nor command substitution, so instead we
232+# post-process each arg (as a line of input to sed) to backslash-escape any
233+# character that might be a shell metacharacter, then use eval to reverse
234+# that process (while maintaining the separation between arguments), and wrap
235+# the whole thing up as a single "set" statement.
236+#
237+# This will of course break if any of these variables contains a newline or
238+# an unmatched quote.
239+#
240+
241+eval "set -- $(
242+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
243+ xargs -n1 |
244+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
245+ tr '\n' ' '
246+ )" '"$@"'
247+
248+exec "$JAVACMD" "$@"
A android/settings.gradle.kts View
@@ -0,0 +1,20 @@
1+// The Android app (docs/android.md). The Rust side lives in the cargo workspace one level up.
2+
3+pluginManagement {
4+ repositories {
5+ google()
6+ mavenCentral()
7+ gradlePluginPortal()
8+ }
9+}
10+
11+dependencyResolutionManagement {
12+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
13+ repositories {
14+ google()
15+ mavenCentral()
16+ }
17+}
18+
19+rootProject.name = "budctl"
20+include(":app")
M docs/android.md View
@@ -126,8 +126,10 @@ Written from Android's API reference. No other app's code is read for it (rule 2
126126 *Done when* `cargo ndk -t arm64-v8a build -p budctl-android` builds and the crate's tests
127127 (JSON round trips, a scripted link) pass on Linux.
128128 4. **The Android project** (`android/`): Gradle, with `cargo ndk` run from Gradle, `Bluetooth.kt`,
129− `Core.kt`, and a plain screen with the status as text, the noise-control choice and the debug
130− log. JVM tests cover the link's reader thread and timeouts.
129+ `Link.kt`, `Core.kt`, and a plain screen with the status as text, the noise-control choice and
130+ the debug log. JVM tests cover the link's reader thread and timeouts. Build and install with
131+ `cd android && ./gradlew assembleDebug` and
132+ `adb install -r app/build/outputs/apk/debug/app-debug.apk`.
131133 *Done when* **A1** and **A2** pass on the phone.
132134 5. **The pages**, built the way the desktop app was: first the look with demo buds, then live
133135 buds, then one page at a time (Overview, Equalizer, Gestures, Earbuds, Settings).