Modern Apps git

← Modern-Apps.git

headphones: new app

Commit
b627c1c6edb55e9743f8a0da4c90a179e7ad7bd2
Author
Vayun Mathur <[email protected]>
When
2026-07-10 00:42 UTC (4 months ago)
Parents
de17e01

Diff

headphones/build.gradle.kts
diff --git a/headphones/build.gradle.kts b/headphones/build.gradle.ktsnew file mode 100644index 0000000000..685bc43aa4--- /dev/null+++ b/headphones/build.gradle.kts@@ -0,0 +1,20 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-metadata")+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.headphones"+        minSdk = 34+    }+}++metadataScreenshots {+    permissions.add("android.permission.BLUETOOTH_CONNECT")+    permissions.add("android.permission.POST_NOTIFICATIONS")+}++dependencies {+    testImplementation("junit:junit:4.13.2")+}
headphones/src/main/AndroidManifest.xml
diff --git a/headphones/src/main/AndroidManifest.xml b/headphones/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..83535752b7--- /dev/null+++ b/headphones/src/main/AndroidManifest.xml@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-feature+        android:name="android.hardware.bluetooth"+        android:required="true" />++    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />+    <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" />++    <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:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            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=".service.HeadphonesService"+            android:exported="false"+            android:foregroundServiceType="connectedDevice" />+    </application>+</manifest>
headphones/src/main/java/com/vayunmathur/headphones/HeadphonesState.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/HeadphonesState.kt b/headphones/src/main/java/com/vayunmathur/headphones/HeadphonesState.ktnew file mode 100644index 0000000000..8540992669--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/HeadphonesState.kt@@ -0,0 +1,30 @@+package com.vayunmathur.headphones++import com.vayunmathur.headphones.bluetooth.ConnectionState+import com.vayunmathur.headphones.protocol.BatteryInfo+import com.vayunmathur.headphones.protocol.DeviceCapabilities+import com.vayunmathur.headphones.protocol.EqBands+import com.vayunmathur.headphones.protocol.EqPreset+import com.vayunmathur.headphones.protocol.Feature+import com.vayunmathur.headphones.protocol.NcAsmState+import com.vayunmathur.headphones.protocol.PairedDevice++/**+ * The single aggregated snapshot of everything the UI observes. The service folds each parsed+ * [com.vayunmathur.headphones.protocol.SonyResponse] into this and republishes it as one+ * `StateFlow`, mirroring the companion-`StateFlow` pattern from `SyncForegroundService`.+ */+data class HeadphonesState(+    val connection: ConnectionState = ConnectionState.Disconnected,+    val deviceName: String? = null,+    val deviceAddress: String? = null,+    val battery: BatteryInfo = BatteryInfo(),+    val ncAsm: NcAsmState = NcAsmState(),+    val eqPreset: EqPreset = EqPreset.OFF,+    val eqBands: EqBands = EqBands.FLAT,+    val capabilities: DeviceCapabilities = DeviceCapabilities(),+    val features: Map<Feature, Boolean> = emptyMap(),+    val pairedDevices: List<PairedDevice> = emptyList(),+) {+    val isConnected: Boolean get() = connection == ConnectionState.Connected+}
headphones/src/main/java/com/vayunmathur/headphones/MainActivity.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/MainActivity.kt b/headphones/src/main/java/com/vayunmathur/headphones/MainActivity.ktnew file mode 100644index 0000000000..6412bee4d6--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/MainActivity.kt@@ -0,0 +1,92 @@+package com.vayunmathur.headphones++import android.Manifest+import android.os.Build+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.headphones.bluetooth.ConnectionState+import com.vayunmathur.headphones.service.HeadphonesService+import com.vayunmathur.headphones.ui.EqualizerPage+import com.vayunmathur.headphones.ui.HomePage+import com.vayunmathur.headphones.ui.SettingsPage+import com.vayunmathur.headphones.ui.SupportedDevicesPage+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.PermissionsChecker+import com.vayunmathur.library.util.BottomBarItem+import com.vayunmathur.library.util.BottomNavBar+import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        // Reconnect to a previously-chosen device on launch.+        HeadphonesService.startIfConfigured(this)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                PermissionsChecker(requiredPermissions(), stringResource(R.string.grant_permissions)) {+                    App()+                }+            }+        }+    }++    private fun requiredPermissions(): Array<String> {+        val perms = mutableListOf(Manifest.permission.BLUETOOTH_CONNECT)+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+            perms.add(Manifest.permission.POST_NOTIFICATIONS)+        }+        return perms.toTypedArray()+    }+}++/** Single supported-devices page until a device is chosen; the tabbed UI once connecting. */+@Composable+fun App() {+    val state by HeadphonesService.state.collectAsState()+    val hasDevice = state.deviceAddress != null || state.connection != ConnectionState.Disconnected+    if (hasDevice) Navigation() else SupportedDevicesPage()+}++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Home : Route++    @Serializable+    data object Equalizer : Route++    @Serializable+    data object Settings : Route+}++@Composable+private fun mainPages() = listOf(+    BottomBarItem(stringResource(R.string.label_home), Route.Home, R.drawable.home_24px),+    BottomBarItem(stringResource(R.string.label_equalizer), Route.Equalizer, R.drawable.tune_24px),+    BottomBarItem(stringResource(R.string.label_settings), Route.Settings, R.drawable.settings_24px),+)++@Composable+fun Navigation() {+    val backStack = rememberNavBackStack<Route>(Route.Home)+    val currentPage = backStack.backStack.last()+    MainNavigation(+        backStack,+        bottomBar = { BottomNavBar(backStack, mainPages(), currentPage) },+    ) {+        entry<Route.Home>(metadata = ListPage()) { HomePage() }+        entry<Route.Equalizer>(metadata = ListPage()) { EqualizerPage() }+        entry<Route.Settings>(metadata = ListPage()) { SettingsPage() }+    }+}
headphones/src/main/java/com/vayunmathur/headphones/bluetooth/BondedDeviceFinder.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/bluetooth/BondedDeviceFinder.kt b/headphones/src/main/java/com/vayunmathur/headphones/bluetooth/BondedDeviceFinder.ktnew file mode 100644index 0000000000..5c2a80597b--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/bluetooth/BondedDeviceFinder.kt@@ -0,0 +1,45 @@+package com.vayunmathur.headphones.bluetooth++import android.annotation.SuppressLint+import android.bluetooth.BluetoothAdapter+import android.bluetooth.BluetoothDevice+import android.bluetooth.BluetoothManager+import android.content.Context++/** A bonded device that looks like a controllable Sony headphone. */+data class HeadphoneDevice(+    val name: String,+    val address: String,+)++/**+ * Finds already-bonded Sony headphones. We never scan — the XM5 is bonded by the OS for audio,+ * so we enumerate [BluetoothAdapter.bondedDevices] and keep the ones that either advertise the+ * Sony RFCOMM service UUID or have a Sony-style name.+ */+@SuppressLint("MissingPermission")+class BondedDeviceFinder(private val context: Context) {++    private val adapter: BluetoothAdapter?+        get() = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter++    fun findCandidates(): List<HeadphoneDevice> {+        val bonded = adapter?.bondedDevices ?: return emptyList()+        return bonded.filter { looksLikeSonyHeadphone(it) }+            .map { HeadphoneDevice(name = it.name ?: it.address, address = it.address) }+    }++    fun deviceFor(address: String): BluetoothDevice? =+        adapter?.bondedDevices?.firstOrNull { it.address == address }++    private fun looksLikeSonyHeadphone(device: BluetoothDevice): Boolean {+        val hasSonyUuid = device.uuids?.any { it.uuid == RfcommManager.SONY_UUID } == true+        if (hasSonyUuid) return true+        val name = device.name?.uppercase() ?: return false+        return SONY_NAME_HINTS.any { name.contains(it) }+    }++    private companion object {+        val SONY_NAME_HINTS = listOf("WF-1000XM", "WH-1000XM", "WF-", "WH-", "LINKBUDS", "SONY")+    }+}
headphones/src/main/java/com/vayunmathur/headphones/bluetooth/RfcommManager.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/bluetooth/RfcommManager.kt b/headphones/src/main/java/com/vayunmathur/headphones/bluetooth/RfcommManager.ktnew file mode 100644index 0000000000..6f23996f81--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/bluetooth/RfcommManager.kt@@ -0,0 +1,270 @@+package com.vayunmathur.headphones.bluetooth++import android.annotation.SuppressLint+import android.bluetooth.BluetoothDevice+import android.util.Log+import com.vayunmathur.headphones.protocol.CommandBuilders+import com.vayunmathur.headphones.protocol.DataType+import com.vayunmathur.headphones.protocol.FrameAccumulator+import com.vayunmathur.headphones.protocol.ResponseParsers+import com.vayunmathur.headphones.protocol.SonyFraming+import com.vayunmathur.headphones.protocol.SonyMessage+import com.vayunmathur.headphones.protocol.SonyResponse+import com.vayunmathur.headphones.protocol.toHexString+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream+import java.util.UUID+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.channels.Channel+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull++enum class ConnectionState { Disconnected, Connecting, Connected }++/**+ * Owns a single Bluetooth Classic RFCOMM connection to the earbuds and exposes a Flow surface+ * mirroring [com.vayunmathur.watch.phone.ble.GattClientManager]: a [state] `StateFlow`, an+ * inbound [responses] `SharedFlow`, and a fire-and-forget [send].+ *+ * The XM5 is already OS-bonded for audio, so we never scan — the caller supplies a bonded+ * [BluetoothDevice]. A blocking read loop feeds the [FrameAccumulator]; a writer loop drains an+ * outbound queue, applying the rolling 1-bit sequence number and waiting for each ACK before the+ * next send. Received data messages are ACK'd automatically.+ */+@SuppressLint("MissingPermission")+class RfcommManager {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private var socket: android.bluetooth.BluetoothSocket? = null+    private var input: InputStream? = null+    private var output: OutputStream? = null+    private var readJob: Job? = null+    private var writeJob: Job? = null++    private val outbound = Channel<SonyMessage>(Channel.UNLIMITED)+    private var outgoingSeq = 0++    @Volatile+    private var ackWaiter: kotlinx.coroutines.CompletableDeferred<Unit>? = null++    private val _state = MutableStateFlow(ConnectionState.Disconnected)+    val state: StateFlow<ConnectionState> = _state++    private val _responses = MutableSharedFlow<SonyResponse>(extraBufferCapacity = 64)+    val responses: SharedFlow<SonyResponse> = _responses++    /** Raw TX/RX frames (hex) for the Debug Log page. */+    private val _traffic = MutableSharedFlow<TrafficEntry>(extraBufferCapacity = 128)+    val traffic: SharedFlow<TrafficEntry> = _traffic++    /** A decoded view of one wire frame for the Debug Log. */+    data class TrafficEntry(+        val outbound: Boolean,+        val dataType: String,+        val commandId: Int,+        val payloadHex: String,+        val frameHex: String,+    )++    private fun entryFor(outbound: Boolean, message: SonyMessage, frameHex: String) = TrafficEntry(+        outbound = outbound,+        dataType = message.dataType.name,+        commandId = message.commandId,+        payloadHex = message.payload.toHexString(),+        frameHex = frameHex,+    )++    /** Opens the RFCOMM socket to [device] and starts the read/write loops. */+    fun connect(device: BluetoothDevice) {+        if (_state.value != ConnectionState.Disconnected) return+        _state.value = ConnectionState.Connecting+        scope.launch {+            val opened = openSocket(device)+            if (opened == null) {+                _state.value = ConnectionState.Disconnected+                return@launch+            }+            socket = opened+            input = opened.inputStream+            output = opened.outputStream+            outgoingSeq = 0+            _state.value = ConnectionState.Connected+            startReadLoop()+            startWriteLoop()+        }+    }++    private fun openSocket(device: BluetoothDevice): android.bluetooth.BluetoothSocket? {+        // Discovery must not be running during connect, or it fails.+        try {+            android.bluetooth.BluetoothAdapter.getDefaultAdapter()?.cancelDiscovery()+        } catch (_: SecurityException) {+        }++        // Connect to the MDR control service by SDP UUID lookup, which resolves the correct+        // RFCOMM channel (it is NOT a fixed channel, and it is NOT the 96cc203e discovery UUID —+        // that is not even an RFCOMM service). Try the known MDR service UUID first, then fall+        // back to probing the device's other advertised custom services.+        connectUuid(device, MDR_UUID, secure = true)?.let { return it }+        connectUuid(device, MDR_UUID, secure = false)?.let { return it }++        val candidates = try {+            device.uuids?.mapNotNull { it?.uuid }?.filter { it !in WELL_KNOWN_UUIDS } ?: emptyList()+        } catch (_: SecurityException) {+            emptyList()+        }+        for (uuid in candidates) {+            if (uuid == MDR_UUID) continue+            connectUuid(device, uuid, secure = true)?.let { return it }+            connectUuid(device, uuid, secure = false)?.let { return it }+        }+        Log.e(TAG, "No MDR RFCOMM service could be connected")+        return null+    }++    private fun connectUuid(+        device: BluetoothDevice,+        uuid: UUID,+        secure: Boolean,+    ): android.bluetooth.BluetoothSocket? = try {+        val socket = if (secure) {+            device.createRfcommSocketToServiceRecord(uuid)+        } else {+            device.createInsecureRfcommSocketToServiceRecord(uuid)+        }+        socket.connect()+        Log.i(TAG, "Connected via ${if (secure) "secure" else "insecure"} SDP uuid=$uuid")+        socket+    } catch (e: IOException) {+        Log.w(TAG, "Connect uuid=$uuid secure=$secure failed", e)+        null+    }++    private fun startReadLoop() {+        readJob = scope.launch {+            val accumulator = FrameAccumulator()+            val buf = ByteArray(2048)+            val stream = input ?: return@launch+            Log.i(TAG, "Read loop started")+            try {+                while (true) {+                    val n = stream.read(buf)+                    if (n < 0) break+                    if (n == 0) continue+                    val chunk = buf.copyOf(n)+                    Log.i(TAG, "RAW-RX $n bytes: ${chunk.toHexString()}")+                    for (message in accumulator.feed(chunk)) handleInbound(message)+                }+            } catch (e: IOException) {+                Log.w(TAG, "Read loop ended", e)+            }+            teardown()+        }+    }++    private suspend fun handleInbound(message: SonyMessage) {+        val frameHex = SonyFraming.frame(message).toHexString()+        Log.i(TAG, "RX ${message.dataType} cmd=0x%02x payload=%s".format(message.commandId, message.payload.toHexString()))+        _traffic.tryEmit(entryFor(outbound = false, message = message, frameHex = frameHex))+        if (message.dataType == DataType.ACK) {+            ackWaiter?.complete(Unit)+            return+        }+        _responses.tryEmit(ResponseParsers.parse(message))+        // ACK every non-ACK message the device sends.+        writeRaw(CommandBuilders.ack(message.sequenceNumber))+    }++    private fun startWriteLoop() {+        writeJob = scope.launch {+            for (message in outbound) {+                val waiter = kotlinx.coroutines.CompletableDeferred<Unit>()+                ackWaiter = waiter+                val toSend = message.copy(sequenceNumber = outgoingSeq)+                if (!writeRaw(toSend)) break+                // Wait for the device ACK, then flip the sequence bit. Proceed anyway on timeout.+                withTimeoutOrNull(ACK_TIMEOUT_MS) { waiter.await() }+                outgoingSeq = 1 - outgoingSeq+                ackWaiter = null+            }+        }+    }++    private fun writeRaw(message: SonyMessage): Boolean {+        val stream = output ?: return false+        return try {+            val bytes = SonyFraming.frame(message)+            stream.write(bytes)+            stream.flush()+            Log.i(TAG, "TX ${message.dataType} cmd=0x%02x payload=%s".format(message.commandId, message.payload.toHexString()))+            _traffic.tryEmit(entryFor(outbound = true, message = message, frameHex = bytes.toHexString()))+            true+        } catch (e: IOException) {+            Log.w(TAG, "Write failed", e)+            teardown()+            false+        }+    }++    /** Queues a command; the sequence number is assigned by the writer loop. */+    fun send(message: SonyMessage) {+        outbound.trySend(message)+    }++    fun disconnect() {+        scope.launch { teardown() }+    }++    private fun teardown() {+        if (_state.value == ConnectionState.Disconnected) return+        readJob?.cancel(); readJob = null+        writeJob?.cancel(); writeJob = null+        try { socket?.close() } catch (_: IOException) {}+        socket = null; input = null; output = null+        ackWaiter = null+        _state.value = ConnectionState.Disconnected+    }++    fun release() {+        teardown()+        scope.cancel()+    }++    companion object {+        private const val TAG = "RfcommManager"+        private const val ACK_TIMEOUT_MS = 1000L++        /**+         * The RFCOMM service UUID for Sony's legacy "MDR" control protocol on the WF-1000XM5,+         * discovered from the device's SDP records. This is what carries the 0x3e-framed+         * battery/NC/EQ traffic. NOTE: this is NOT `96CC203E-…`, which is only the app-discovery+         * (Companion/EIR) UUID and is not an RFCOMM service.+         */+        val MDR_UUID: UUID = UUID.fromString("956C7B26-D49A-4BA8-B03F-B17D393CB6E2")++        /** Sony's app-discovery UUID (not an RFCOMM service; kept for device matching only). */+        val SONY_UUID: UUID = UUID.fromString("96CC203E-5068-46AD-B32D-E316F5E069BA")++        /** Standard audio/utility services to skip when probing for the MDR service. */+        private val WELL_KNOWN_UUIDS: Set<UUID> = setOf(+            UUID.fromString("0000110A-0000-1000-8000-00805F9B34FB"), // A2DP source+            UUID.fromString("0000110B-0000-1000-8000-00805F9B34FB"), // A2DP sink+            UUID.fromString("0000110C-0000-1000-8000-00805F9B34FB"), // AVRCP target+            UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB"), // AVRCP+            UUID.fromString("0000111E-0000-1000-8000-00805F9B34FB"), // Handsfree+            UUID.fromString("00001108-0000-1000-8000-00805F9B34FB"), // Headset+            UUID.fromString("00001203-0000-1000-8000-00805F9B34FB"), // GenericAudio+            UUID.fromString("0000112F-0000-1000-8000-00805F9B34FB"), // PBAP+        )+    }+}
headphones/src/main/java/com/vayunmathur/headphones/protocol/CommandBuilders.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/protocol/CommandBuilders.kt b/headphones/src/main/java/com/vayunmathur/headphones/protocol/CommandBuilders.ktnew file mode 100644index 0000000000..9a43d7ffba--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/protocol/CommandBuilders.kt@@ -0,0 +1,164 @@+package com.vayunmathur.headphones.protocol++/**+ * Builds outbound [SonyMessage]s. Each builder returns a message with the given [sequence]+ * number (the transport rewrites it to the live rolling value before sending); the payload is+ * the command id followed by its parameters.+ */+object CommandBuilders {++    private fun command(payload: ByteArray, sequence: Int): SonyMessage =+        SonyMessage(SonyProtocol.COMMAND_DATA_TYPE, sequence, payload)++    /** Device-management commands ride the DATA_MDR_NO2 (0x0e) channel. */+    private fun command2(payload: ByteArray, sequence: Int): SonyMessage =+        SonyMessage(DataType.DATA_MDR_NO2, sequence, payload)++    /** ACK for a received message. The ACK's sequence number is the *flip* of the received one. */+    fun ack(receivedSequence: Int): SonyMessage =+        SonyMessage(DataType.ACK, 1 - receivedSequence, ByteArray(0))++    // --- Init handshake ---++    fun getProtocolInfo(sequence: Int = 0): SonyMessage =+        command(byteArrayOf(SonyProtocol.CONNECT_GET_PROTOCOL_INFO.toByte(), 0x00), sequence)++    fun getCapabilities(sequence: Int = 0): SonyMessage =+        command(byteArrayOf(SonyProtocol.CONNECT_GET_CAPABILITY_INFO.toByte(), 0x00), sequence)++    // --- Battery ---++    fun getBattery(type: Int, sequence: Int = 0): SonyMessage =+        command(byteArrayOf(SonyProtocol.BATTERY_GET.toByte(), type.toByte()), sequence)++    fun getSingleBattery(sequence: Int = 0) = getBattery(SonyProtocol.BATTERY_TYPE_SINGLE, sequence)+    fun getDualBattery(sequence: Int = 0) = getBattery(SonyProtocol.BATTERY_TYPE_DUAL, sequence)+    fun getCaseBattery(sequence: Int = 0) = getBattery(SonyProtocol.BATTERY_TYPE_CASE, sequence)++    // --- Noise cancelling / ambient sound ---++    /**+     * Sets the NC/ASM state. Real WF-1000XM5 payload (decoded from device traffic):+     * `[NCASM_SET, 0x17, 0x01, enabled, ambientMode, focusOnVoice, ambientLevel]`+     * where enabled=0 → Off, ambientMode=1 → Ambient Sound / 0 → Noise Cancelling,+     * focusOnVoice=1 lets speech through in Ambient mode, and ambientLevel is 0..20.+     */+    fun setNcAsm(state: NcAsmState, sequence: Int = 0): SonyMessage {+        val enabled = if (state.mode == NcAsmMode.OFF) 0x00 else 0x01+        val ambientMode = if (state.mode == NcAsmMode.AMBIENT_SOUND) 0x01 else 0x00+        val focus = if (state.voicePassthrough) 0x01 else 0x00+        val level = state.ambientLevel.coerceIn(0, NcAsmState.MAX_AMBIENT_LEVEL)+        return command(+            byteArrayOf(+                SonyProtocol.NCASM_SET.toByte(),+                SonyProtocol.NCASM_TYPE_XM5.toByte(),+                0x01, // commit (vs 0x00 during slider preview)+                enabled.toByte(),+                ambientMode.toByte(),+                focus.toByte(),+                level.toByte(),+            ),+            sequence,+        )+    }++    fun getNcAsm(sequence: Int = 0): SonyMessage =+        command(+            byteArrayOf(SonyProtocol.NCASM_GET.toByte(), SonyProtocol.NCASM_TYPE_XM5.toByte()),+            sequence,+        )++    // --- Equalizer ---++    fun getEq(sequence: Int = 0): SonyMessage =+        command(byteArrayOf(SonyProtocol.EQ_GET.toByte(), SonyProtocol.EQ_TYPE_PRESET.toByte()), sequence)++    /** Selects a built-in preset. Payload: `[EQ_SET, 0x00, presetId, 0x00]`. */+    fun setEqPreset(preset: EqPreset, sequence: Int = 0): SonyMessage =+        command(+            byteArrayOf(+                SonyProtocol.EQ_SET.toByte(),+                SonyProtocol.EQ_TYPE_PRESET.toByte(),+                preset.value.toByte(),+                0x00,+            ),+            sequence,+        )++    /**+     * Sets a custom EQ curve by writing the 6-band values into the "Custom" slot. Payload+     * (confirmed from device traffic):+     * `[EQ_SET, 0x00, EQ_CUSTOM_SLOT, numBands(6), clearBass, b0, b1, b2, b3, b4]`.+     * Band values are raw wire bytes 0..20 (10 = flat).+     */+    fun setEqCustom(bands: EqBands, sequence: Int = 0): SonyMessage {+        val payload = ByteArray(4 + 1 + EqBands.BAND_COUNT)+        payload[0] = SonyProtocol.EQ_SET.toByte()+        payload[1] = SonyProtocol.EQ_TYPE_PRESET.toByte()+        payload[2] = SonyProtocol.EQ_CUSTOM_SLOT.toByte()+        payload[3] = (EqBands.BAND_COUNT + 1).toByte() // clear-bass + 5 bands+        payload[4] = bands.clearBass.coerceIn(0, EqBands.STEPS - 1).toByte()+        for (i in 0 until EqBands.BAND_COUNT) {+            payload[5 + i] = bands.bands[i].coerceIn(0, EqBands.STEPS - 1).toByte()+        }+        return command(payload, sequence)+    }++    // --- Simple feature toggles (best-effort; verify on-device) ---++    /** Generic `<domain>_SET, <inquiredType>, <enabled>` toggle. */+    fun setSimpleToggle(setCommand: Int, inquiredType: Int, enabled: Boolean, sequence: Int = 0): SonyMessage =+        command(+            byteArrayOf(setCommand.toByte(), inquiredType.toByte(), if (enabled) 0x01 else 0x00),+            sequence,+        )++    /**+     * Multipoint (connect to two devices). Confirmed WF-1000XM5 payload: `[0xd8, 0xd2, 0x00, v]`+     * where v is inverted — `0x00` = multipoint on, `0x01` = off (sound-quality priority).+     */+    fun setMultipoint(enabled: Boolean, sequence: Int = 0): SonyMessage =+        command(+            byteArrayOf(+                SonyProtocol.CONFIG_SET.toByte(),+                SonyProtocol.CONFIG_SUBTYPE_MULTIPOINT.toByte(),+                0x00,+                if (enabled) 0x00 else 0x01,+            ),+            sequence,+        )++    fun setFeature(feature: Feature, enabled: Boolean, sequence: Int = 0): SonyMessage = when (feature) {+        Feature.MULTIPOINT -> setMultipoint(enabled, sequence)+        Feature.DSEE ->+            setSimpleToggle(SonyProtocol.AUDIO_SET, SonyProtocol.AUDIO_TYPE_DSEE, enabled, sequence)+        Feature.SPEAK_TO_CHAT ->+            setSimpleToggle(SonyProtocol.SYSTEM_SET, SonyProtocol.SYSTEM_TYPE_SPEAK_TO_CHAT, enabled, sequence)+        Feature.ADAPTIVE_SOUND_CONTROL ->+            setSimpleToggle(SonyProtocol.SYSTEM_SET, SonyProtocol.SYSTEM_TYPE_ASC, enabled, sequence)+        Feature.TOUCH_SENSOR ->+            setSimpleToggle(SonyProtocol.SYSTEM_SET, 0x00, enabled, sequence)+    }++    /** Subscribes to (and triggers a push of) the multipoint paired-device list. */+    fun subscribePairedDevices(sequence: Int = 0): SonyMessage =+        command2(+            byteArrayOf(SonyProtocol.PAIRED_SUBSCRIBE.toByte(), SonyProtocol.PAIRED_SUBTYPE.toByte(), 0x01),+            sequence,+        )++    /** Cancels a device's registration. Payload: `3c 02 02 <MAC as 17-char ASCII>`. */+    fun removePairedDevice(address: String, sequence: Int = 0): SonyMessage {+        val mac = address.uppercase().toByteArray(Charsets.US_ASCII)+        val payload = byteArrayOf(+            SonyProtocol.PAIRED_REMOVE.toByte(),+            SonyProtocol.PAIRED_SUBTYPE.toByte(),+            0x02,+        ) + mac+        return command2(payload, sequence)+    }++    /** Sends an arbitrary raw payload (Debug Log "send raw hex"). */+    fun raw(payload: ByteArray, dataType: DataType = SonyProtocol.COMMAND_DATA_TYPE, sequence: Int = 0): SonyMessage =+        SonyMessage(dataType, sequence, payload)+}
headphones/src/main/java/com/vayunmathur/headphones/protocol/Models.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/protocol/Models.kt b/headphones/src/main/java/com/vayunmathur/headphones/protocol/Models.ktnew file mode 100644index 0000000000..ecd1e18990--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/protocol/Models.kt@@ -0,0 +1,134 @@+package com.vayunmathur.headphones.protocol++/** Battery level for one component (0..100), with [charging] state. -1 level = unknown. */+data class BatteryComponent(+    val level: Int,+    val charging: Boolean,+) {+    val isKnown: Boolean get() = level in 0..100++    companion object {+        val UNKNOWN = BatteryComponent(level = -1, charging = false)+    }+}++/**+ * Battery for the earbuds. For true-wireless (XM5) [left]/[right]/[case] are populated;+ * over-ear models populate only [single].+ */+data class BatteryInfo(+    val single: BatteryComponent = BatteryComponent.UNKNOWN,+    val left: BatteryComponent = BatteryComponent.UNKNOWN,+    val right: BatteryComponent = BatteryComponent.UNKNOWN,+    val case: BatteryComponent = BatteryComponent.UNKNOWN,+)++/** Top-level noise-management mode. */+enum class NcAsmMode {+    OFF,+    NOISE_CANCELLING,+    AMBIENT_SOUND,+}++/**+ * Noise-cancelling / ambient-sound state.+ *+ * @param mode current top-level mode+ * @param ambientLevel 0..20 ambient-sound level (only meaningful in [NcAsmMode.AMBIENT_SOUND])+ * @param voicePassthrough "Focus on Voice" — let speech through in ambient mode+ * @param windNoiseReduction wind-noise reduction (NC sub-mode on supported models)+ * @param adaptive Adaptive Sound Control is driving the mode automatically+ */+data class NcAsmState(+    val mode: NcAsmMode = NcAsmMode.OFF,+    val ambientLevel: Int = 0,+    val voicePassthrough: Boolean = false,+    val windNoiseReduction: Boolean = false,+    val adaptive: Boolean = false,+) {+    companion object {+        const val MAX_AMBIENT_LEVEL = 20+    }+}++/** Built-in EQ presets for the WF-1000XM5 (ids decoded from device traffic). */+enum class EqPreset(val value: Int) {+    OFF(0x00),+    BRIGHT(0x10),+    EXCITED(0x11),+    MELLOW(0x12),+    RELAXED(0x13),+    VOCAL(0x14),+    TREBLE_BOOST(0x15),+    BASS_BOOST(0x16),+    SPEECH(0x17),+    CUSTOM(0xa0),+    USER_SETTING_1(0xa1),+    USER_SETTING_2(0xa2),+    UNKNOWN(-1);++    companion object {+        fun fromValue(value: Int): EqPreset =+            entries.firstOrNull { it.value == value } ?: UNKNOWN+    }+}++/**+ * A 6-value EQ curve: [clearBass] plus 5 frequency bands (400/1k/2.5k/6.3k/16kHz).+ * Each value is the raw on-wire byte, 0..[STEPS]-1, centred at [CENTER] (= flat).+ */+data class EqBands(+    val clearBass: Int = CENTER,+    val bands: List<Int> = List(BAND_COUNT) { CENTER },+) {+    init {+        require(bands.size == BAND_COUNT) { "Expected $BAND_COUNT bands, got ${bands.size}" }+    }++    companion object {+        const val BAND_COUNT = 5+        const val STEPS = 21 // 0..20 on the wire+        const val CENTER = 10 // flat+        val FLAT = EqBands()+    }+}++/** A device registered to the earbuds for multipoint. */+data class PairedDevice(+    val address: String,+    val name: String,+    val connected: Boolean,+)++/** State of a simple on/off device feature. */+data class FeatureToggle(+    val feature: Feature,+    val enabled: Boolean,+)++/** Simple boolean features exposed in Settings. */+enum class Feature {+    DSEE,+    SPEAK_TO_CHAT,+    MULTIPOINT,+    ADAPTIVE_SOUND_CONTROL,+    TOUCH_SENSOR,+}++/**+ * Which optional features a connected device reports as supported. Unsupported features are+ * hidden in the UI. Populated from the capability handshake; conservative defaults are all-off.+ */+data class DeviceCapabilities(+    val supportsBattery: Boolean = false,+    val supportsDualBattery: Boolean = false,+    val supportsCaseBattery: Boolean = false,+    val supportsNcAsm: Boolean = false,+    val supportsAmbientLevel: Boolean = false,+    val supportsWindNoiseReduction: Boolean = false,+    val supportsEqualizer: Boolean = false,+    val supportsClearBass: Boolean = false,+    val features: Set<Feature> = emptySet(),+) {+    fun supports(feature: Feature): Boolean = feature in features+}
headphones/src/main/java/com/vayunmathur/headphones/protocol/ResponseParsers.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/protocol/ResponseParsers.kt b/headphones/src/main/java/com/vayunmathur/headphones/protocol/ResponseParsers.ktnew file mode 100644index 0000000000..c8aa5c53eb--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/protocol/ResponseParsers.kt@@ -0,0 +1,156 @@+package com.vayunmathur.headphones.protocol++/**+ * Turns inbound [SonyMessage]s into typed [SonyResponse]s. Unknown or malformed messages+ * become [SonyResponse.Raw] so nothing is silently dropped (and so the Debug Log can show+ * them for on-device opcode iteration).+ */+object ResponseParsers {++    fun parse(message: SonyMessage): SonyResponse {+        if (message.dataType == DataType.ACK) {+            return SonyResponse.Ack(message.sequenceNumber)+        }+        val p = message.payload+        if (p.isEmpty()) return SonyResponse.Raw(message)++        return when (p[0].toInt() and 0xFF) {+            SonyProtocol.BATTERY_RET ->+                parseBattery(p) ?: SonyResponse.Raw(message)+            SonyProtocol.NCASM_RET, SonyProtocol.NCASM_NTFY ->+                parseNcAsm(p) ?: SonyResponse.Raw(message)+            SonyProtocol.EQ_RET, SonyProtocol.EQ_NTFY ->+                parseEq(p) ?: SonyResponse.Raw(message)+            SonyProtocol.CONFIG_NTFY ->+                parseConfig(p) ?: SonyResponse.Raw(message)+            SonyProtocol.PAIRED_LIST_NTFY ->+                parsePairedDevices(p) ?: SonyResponse.Raw(message)+            SonyProtocol.CONNECT_RET_CAPABILITY_INFO ->+                SonyResponse.Capabilities(parseCapabilities(p))+            else -> SonyResponse.Raw(message)+        }+    }++    /**+     * `39 02 <count> { mac(17 ascii) flag info×3 nameLen name } terminator`.+     * flag 0x02 = currently connected, else registered/idle.+     */+    private fun parsePairedDevices(p: ByteArray): SonyResponse.PairedDevices? {+        if (p.size < 3) return null+        val count = u(p[2])+        var i = 3+        val devices = ArrayList<PairedDevice>(count)+        repeat(count) {+            if (i + 17 + 5 > p.size) return@repeat+            val mac = String(p, i, 17, Charsets.US_ASCII); i += 17+            val flag = u(p[i]); i += 1+            i += 3 // device-type/icon info+            val nameLen = u(p[i]); i += 1+            if (i + nameLen > p.size) return@repeat+            val name = String(p, i, nameLen, Charsets.US_ASCII); i += nameLen+            devices.add(PairedDevice(address = mac, name = name, connected = flag == 0x02))+        }+        return SonyResponse.PairedDevices(devices)+    }++    /** `[0xd9, subtype, 0x00, value]`. Multipoint (subtype 0xd2) value is inverted (0 = on). */+    private fun parseConfig(p: ByteArray): SonyResponse.SimpleFeature? {+        if (p.size < 4) return null+        return when (u(p[1])) {+            SonyProtocol.CONFIG_SUBTYPE_MULTIPOINT ->+                SonyResponse.SimpleFeature(FeatureToggle(Feature.MULTIPOINT, enabled = u(p[3]) == 0))+            else -> null+        }+    }++    private fun u(b: Byte): Int = b.toInt() and 0xFF++    private fun component(level: Int, charge: Int): BatteryComponent =+        BatteryComponent(level = level.coerceIn(-1, 100), charging = charge != 0)++    /**+     * `[cmd, type, ...]`:+     * - SINGLE `0x00`: `level, charge`+     * - DUAL `0x09`: `leftLevel, leftCharge, rightLevel, rightCharge`+     * - CASE `0x0a`: `level, charge`+     */+    private fun parseBattery(p: ByteArray): SonyResponse.Battery? {+        if (p.size < 2) return null+        return when (u(p[1])) {+            SonyProtocol.BATTERY_TYPE_SINGLE -> {+                if (p.size < 4) return null+                SonyResponse.Battery(BatteryInfo(single = component(u(p[2]), u(p[3]))))+            }+            SonyProtocol.BATTERY_TYPE_DUAL -> {+                if (p.size < 6) return null+                SonyResponse.Battery(+                    BatteryInfo(+                        left = component(u(p[2]), u(p[3])),+                        right = component(u(p[4]), u(p[5])),+                    ),+                )+            }+            SonyProtocol.BATTERY_TYPE_CASE -> {+                if (p.size < 4) return null+                SonyResponse.Battery(BatteryInfo(case = component(u(p[2]), u(p[3]))))+            }+            else -> null+        }+    }++    /** `[cmd, 0x17, commit, enabled, ambientMode, focusOnVoice, level]` (WF-1000XM5, decoded). */+    private fun parseNcAsm(p: ByteArray): SonyResponse.NcAsm? {+        if (p.size < 7) return null+        val enabled = u(p[3])+        val ambientMode = u(p[4])+        val focus = u(p[5]) != 0+        val level = u(p[6])+        val ncMode = when {+            enabled == 0 -> NcAsmMode.OFF+            ambientMode == 1 -> NcAsmMode.AMBIENT_SOUND+            else -> NcAsmMode.NOISE_CANCELLING+        }+        return SonyResponse.NcAsm(+            NcAsmState(+                mode = ncMode,+                ambientLevel = level.coerceIn(0, NcAsmState.MAX_AMBIENT_LEVEL),+                voicePassthrough = focus,+            ),+        )+    }++    /** `[cmd, 0x00, presetId, numBands, clearBass, b0..b4]`. */+    private fun parseEq(p: ByteArray): SonyResponse.Eq? {+        if (p.size < 4) return null+        val preset = EqPreset.fromValue(u(p[2]))+        val numBands = u(p[3])+        if (numBands == 0 || p.size < 4 + numBands) {+            return SonyResponse.Eq(preset, EqBands.FLAT)+        }+        val clearBass = u(p[4])+        val bands = ArrayList<Int>(EqBands.BAND_COUNT)+        for (i in 0 until EqBands.BAND_COUNT) {+            val idx = 5 + i+            bands.add(if (idx < p.size) u(p[idx]) else EqBands.CENTER)+        }+        return SonyResponse.Eq(preset, EqBands(clearBass = clearBass, bands = bands))+    }++    /**+     * Deep capability parsing is model-specific and not reliably documented, so for the XM5+     * target we report the standard super-set. Refine on-device via the Debug Log if needed.+     */+    private fun parseCapabilities(@Suppress("UNUSED_PARAMETER") p: ByteArray): DeviceCapabilities =+        DeviceCapabilities(+            supportsBattery = true,+            supportsDualBattery = true,+            supportsCaseBattery = true,+            supportsNcAsm = true,+            supportsAmbientLevel = true,+            supportsWindNoiseReduction = true,+            supportsEqualizer = true,+            supportsClearBass = true,+            // Only multipoint is verified on the WF-1000XM5 so far; hide unverified toggles.+            features = setOf(Feature.MULTIPOINT),+        )+}
headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyFraming.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyFraming.kt b/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyFraming.ktnew file mode 100644index 0000000000..f27cd60f85--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyFraming.kt@@ -0,0 +1,146 @@+package com.vayunmathur.headphones.protocol++/**+ * Wire framing for Sony's RFCOMM protocol.+ *+ * A message on the wire is:+ * ```+ * START | escape( dataType | seq | len[4 BE] | payload | checksum ) | END+ * ```+ * where `checksum = (dataType + seq + len bytes + payload bytes) mod 256`, `len` is the+ * payload length as a 4-byte big-endian integer, and any [START]/[END]/[ESCAPE] byte that+ * would otherwise appear inside the frame is replaced by [ESCAPE] followed by `byte & 0xEF`.+ */+object SonyFraming {+    const val START: Int = 0x3E+    const val END: Int = 0x3C+    const val ESCAPE: Int = 0x3D++    /** Escaping clears bit 4 (0x10); unescaping restores it. */+    private const val ESCAPE_CLEAR_MASK: Int = 0xEF+    private const val ESCAPE_RESTORE_MASK: Int = 0x10++    /** Sum of the given bytes, mod 256. */+    fun checksum(bytes: ByteArray): Int {+        var sum = 0+        for (b in bytes) sum += b.toInt() and 0xFF+        return sum and 0xFF+    }++    /** Builds the checksum-covered region (before escaping): dataType | seq | len | payload. */+    private fun header(message: SonyMessage): ByteArray {+        val len = message.payload.size+        val out = ByteArray(6 + len)+        out[0] = message.dataType.value.toByte()+        out[1] = message.sequenceNumber.toByte()+        out[2] = (len ushr 24 and 0xFF).toByte()+        out[3] = (len ushr 16 and 0xFF).toByte()+        out[4] = (len ushr 8 and 0xFF).toByte()+        out[5] = (len and 0xFF).toByte()+        message.payload.copyInto(out, 6)+        return out+    }++    /** Serializes a [SonyMessage] into a complete, wire-ready frame. */+    fun frame(message: SonyMessage): ByteArray {+        val body = header(message)+        val checksum = checksum(body)+        val withChecksum = body + checksum.toByte()++        val out = ArrayList<Byte>(withChecksum.size + 4)+        out.add(START.toByte())+        for (b in withChecksum) {+            val v = b.toInt() and 0xFF+            if (v == START || v == END || v == ESCAPE) {+                out.add(ESCAPE.toByte())+                out.add((v and ESCAPE_CLEAR_MASK).toByte())+            } else {+                out.add(b)+            }+        }+        out.add(END.toByte())+        return out.toByteArray()+    }++    /**+     * Parses a single unescaped frame body (the bytes between START and END, still escaped).+     * Returns null if the frame is malformed or the checksum does not match.+     */+    fun parse(escapedBody: ByteArray): SonyMessage? {+        val body = unescape(escapedBody) ?: return null+        // Need at least dataType + seq + 4 len + checksum.+        if (body.size < 7) return null++        val dataType = body[0].toInt() and 0xFF+        val seq = body[1].toInt() and 0xFF+        val len = ((body[2].toInt() and 0xFF) shl 24) or+            ((body[3].toInt() and 0xFF) shl 16) or+            ((body[4].toInt() and 0xFF) shl 8) or+            (body[5].toInt() and 0xFF)++        if (len < 0 || 6 + len + 1 != body.size) return null++        val payload = body.copyOfRange(6, 6 + len)+        val expected = body[6 + len].toInt() and 0xFF+        val actual = checksum(body.copyOfRange(0, 6 + len))+        if (expected != actual) return null++        return SonyMessage(DataType.fromValue(dataType), seq, payload)+    }++    /** Reverses escaping; returns null if a trailing dangling escape is present. */+    private fun unescape(escaped: ByteArray): ByteArray? {+        val out = ArrayList<Byte>(escaped.size)+        var i = 0+        while (i < escaped.size) {+            val v = escaped[i].toInt() and 0xFF+            if (v == ESCAPE) {+                if (i + 1 >= escaped.size) return null+                val next = escaped[i + 1].toInt() and 0xFF+                out.add((next or ESCAPE_RESTORE_MASK).toByte())+                i += 2+            } else {+                out.add(escaped[i])+                i+++            }+        }+        return out.toByteArray()+    }+}++/**+ * Reassembles complete [SonyMessage]s from arbitrarily-chunked socket reads.+ *+ * RFCOMM reads may split or merge frames, so callers feed raw bytes as they arrive and+ * drain any messages that have become complete. Bytes before the first START are dropped;+ * a partial frame is retained until its END arrives.+ */+class FrameAccumulator {+    private val buffer = ArrayList<Byte>()++    /** Feeds newly-read bytes and returns any messages completed by them (may be empty). */+    fun feed(bytes: ByteArray): List<SonyMessage> {+        val messages = ArrayList<SonyMessage>()+        for (b in bytes) {+            val v = b.toInt() and 0xFF+            when {+                v == SonyFraming.START -> {+                    buffer.clear()+                    buffer.add(b)+                }+                v == SonyFraming.END && buffer.isNotEmpty() -> {+                    // Strip the leading START; parse the escaped body.+                    val body = ByteArray(buffer.size - 1)+                    for (j in 1 until buffer.size) body[j - 1] = buffer[j]+                    SonyFraming.parse(body)?.let { messages.add(it) }+                    buffer.clear()+                }+                buffer.isNotEmpty() -> buffer.add(b)+                // else: stray byte before any START — ignore.+            }+        }+        return messages+    }++    fun reset() = buffer.clear()+}
headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyMessage.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyMessage.kt b/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyMessage.ktnew file mode 100644index 0000000000..b3eb31fff6--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyMessage.kt@@ -0,0 +1,84 @@+package com.vayunmathur.headphones.protocol++/**+ * Sony's framed RFCOMM protocol carries a one-byte "data type" that identifies the+ * transport channel a message belongs to. Command/response payloads ride on the MDR+ * channels; ACKs use [ACK].+ *+ * Values are from the community-documented protocol (SonyHeadphonesClient /+ * HeadphonesToolbox). The XM5 uses the "v2" MDR channel ([DATA_MDR_NO2]); older+ * models use [DATA_MDR].+ */+enum class DataType(val value: Int) {+    DATA(0x00),+    ACK(0x01),+    DATA_MC_NO1(0x02),+    DATA_ICD(0x09),+    DATA_EV(0x0a),+    DATA_MDR(0x0c),+    DATA_COMMON(0x0d),+    DATA_MDR_NO2(0x0e),+    SHOT(0x10),+    SHOT_MC_NO1(0x12),+    SHOT_ICD(0x19),+    SHOT_EV(0x1a),+    SHOT_MDR(0x1c),+    SHOT_COMMON(0x1d),+    SHOT_MDR_NO2(0x1e),+    LARGE_DATA_COMMON(0x2d),+    UNKNOWN(-1);++    companion object {+        fun fromValue(value: Int): DataType =+            entries.firstOrNull { it.value == value } ?: UNKNOWN+    }+}++/**+ * A single, unframed protocol message: the [dataType], a 1-bit rolling [sequenceNumber]+ * used for the ACK handshake, and the raw [payload] (the command id + its parameters).+ *+ * This is the pure representation; [SonyFraming] turns it into escaped, checksummed,+ * START/END-delimited bytes for the wire and back.+ */+data class SonyMessage(+    val dataType: DataType,+    val sequenceNumber: Int,+    val payload: ByteArray,+) {+    /** The command id, i.e. the first payload byte, or -1 for an empty payload (e.g. ACK). */+    val commandId: Int+        get() = if (payload.isNotEmpty()) payload[0].toInt() and 0xFF else -1++    override fun equals(other: Any?): Boolean {+        if (this === other) return true+        if (other !is SonyMessage) return false+        return dataType == other.dataType &&+            sequenceNumber == other.sequenceNumber &&+            payload.contentEquals(other.payload)+    }++    override fun hashCode(): Int {+        var result = dataType.hashCode()+        result = 31 * result + sequenceNumber+        result = 31 * result + payload.contentHashCode()+        return result+    }++    override fun toString(): String =+        "SonyMessage(dataType=$dataType, seq=$sequenceNumber, payload=${payload.toHexString()})"+}++/** Lowercase, space-free hex rendering, e.g. `0c00000000010a`. */+fun ByteArray.toHexString(): String =+    joinToString("") { "%02x".format(it.toInt() and 0xFF) }++/** Parses a hex string (optionally space/`0x`-separated) into bytes; ignores non-hex chars. */+fun String.hexToByteArray(): ByteArray {+    val cleaned = replace("0x", "", ignoreCase = true)+        .filter { it.isDigit() || it in 'a'..'f' || it in 'A'..'F' }+    require(cleaned.length % 2 == 0) { "Hex string must have an even number of digits" }+    return ByteArray(cleaned.length / 2) { i ->+        cleaned.substring(i * 2, i * 2 + 2).toInt(16).toByte()+    }+}
headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyProtocol.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyProtocol.kt b/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyProtocol.ktnew file mode 100644index 0000000000..c42e2d92f9--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/protocol/SonyProtocol.kt@@ -0,0 +1,99 @@+package com.vayunmathur.headphones.protocol++/**+ * Command ids and enum-parameter values for Sony's MDR message protocol.+ *+ * The framing in [SonyFraming] is fully specified and verified. The *command ids* and their+ * parameter layouts below follow the community-reverse-engineered spec (SonyHeadphonesClient /+ * HeadphonesToolbox). The WF-1000XM5 uses the "v2" NC/ASM + EQ variants; the least-documented+ * "extras" (DSEE, Speak-to-Chat, Multipoint, ASC) are best-effort and are intended to be+ * confirmed on-device via the Debug Log page (see plan Phases 4/6).+ */+object SonyProtocol {+    /** Default transport channel for commands. The XM5 uses DATA_MDR (0x0c) — confirmed by+     * decoding real WF-1000XM5 RFCOMM traffic. (0x0e/DATA_MDR_NO2 is used only for a few+     * secondary command families.) */+    val COMMAND_DATA_TYPE = DataType.DATA_MDR++    // --- Capability / init handshake ---+    const val CONNECT_GET_PROTOCOL_INFO = 0x00+    const val CONNECT_RET_PROTOCOL_INFO = 0x01+    const val CONNECT_GET_CAPABILITY_INFO = 0x02+    const val CONNECT_RET_CAPABILITY_INFO = 0x03++    // --- Battery (COMMON domain) — WF-1000XM5 uses 0x22/0x23 ---+    const val BATTERY_GET = 0x22+    const val BATTERY_RET = 0x23+    const val BATTERY_NTFY = 0x23+    const val BATTERY_STATUS_GET = 0x12+    const val BATTERY_STATUS_RET = 0x13++    /** Battery "inquired type" selects which component a battery message refers to. */+    const val BATTERY_TYPE_SINGLE = 0x00+    const val BATTERY_TYPE_DUAL = 0x09+    const val BATTERY_TYPE_CASE = 0x0a++    // --- Noise cancelling / ambient sound (v2, XM4/XM5) ---+    const val NCASM_GET = 0x66+    const val NCASM_RET = 0x67+    const val NCASM_SET = 0x68+    const val NCASM_NTFY = 0x69++    /**+     * NC/ASM "inquired type" 0x17 = NC + Ambient + Wind + Focus-on-Voice (the XM5 super-set).+     * Payload after the type byte, per [CommandBuilders.setNcAsm]:+     * `[on/off, 0x01, mode, focusOnVoice, ambientLevel]`.+     */+    const val NCASM_TYPE_XM5 = 0x17+    const val NCASM_MODE_AMBIENT = 0x00+    const val NCASM_MODE_NC = 0x01+    const val NCASM_MODE_WIND = 0x02++    // --- Equalizer (EQEBB domain) ---+    const val EQ_GET = 0x56+    const val EQ_RET = 0x57+    const val EQ_SET = 0x58+    const val EQ_NTFY = 0x59++    /** EQ inquired type 0x00 = preset + 6-band custom curve. */+    const val EQ_TYPE_PRESET = 0x00++    /** Writable custom EQ slot ("Custom 1"), confirmed from device traffic. */+    const val EQ_CUSTOM_SLOT = 0xa1++    // --- Simple feature toggles ---+    // Multipoint lives in the "system config" domain (SET 0xd8 / NTFY 0xd9), subtype 0xd2,+    // confirmed by the device's own "MULTIPOINT_SETTING" descriptor. Its value is inverted:+    // 0x00 = multipoint on (connect 2 devices), 0x01 = off (prioritize sound quality).+    const val CONFIG_SET = 0xd8+    const val CONFIG_NTFY = 0xd9+    const val CONFIG_SUBTYPE_MULTIPOINT = 0xd2++    // --- Multipoint paired-device management (data type 0x0e) ---+    const val PAIRED_SUBSCRIBE = 0x34 // 34 02 <1=subscribe|0=unsub> -> device pushes 0x39+    const val PAIRED_LIST_NTFY = 0x39 // 39 02 <count> { mac(17) flag info3 nameLen name } 01+    const val PAIRED_REMOVE = 0x3c    // 3c 02 02 <mac ascii> : cancel a device's registration+    const val PAIRED_SUBTYPE = 0x02++    // The following simple-feature opcodes are best-effort and not yet verified for XM5.+    const val AUDIO_SET = 0xe8 // DSEE / upscaling domain (unverified for XM5)+    const val AUDIO_TYPE_DSEE = 0x02+    const val SYSTEM_SET = 0xd8 // Speak-to-Chat / ASC / misc system domain (unverified for XM5)+    const val SYSTEM_TYPE_SPEAK_TO_CHAT = 0x0c+    const val SYSTEM_TYPE_ASC = 0x03+}++/**+ * Parsed inbound messages the app understands. Anything unrecognised surfaces as [Raw] so the+ * Debug Log can show it (and so unknown opcodes can be iterated on-device).+ */+sealed interface SonyResponse {+    data class Battery(val info: BatteryInfo) : SonyResponse+    data class NcAsm(val state: NcAsmState) : SonyResponse+    data class Eq(val preset: EqPreset, val bands: EqBands) : SonyResponse+    data class Capabilities(val capabilities: DeviceCapabilities) : SonyResponse+    data class SimpleFeature(val toggle: FeatureToggle) : SonyResponse+    data class PairedDevices(val devices: List<PairedDevice>) : SonyResponse+    data class Ack(val sequenceNumber: Int) : SonyResponse+    data class Raw(val message: SonyMessage) : SonyResponse+}
headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesController.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesController.kt b/headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesController.ktnew file mode 100644index 0000000000..095ae4e049--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesController.kt@@ -0,0 +1,73 @@+package com.vayunmathur.headphones.service++import com.vayunmathur.headphones.protocol.CommandBuilders+import com.vayunmathur.headphones.protocol.EqBands+import com.vayunmathur.headphones.protocol.EqPreset+import com.vayunmathur.headphones.protocol.Feature+import com.vayunmathur.headphones.protocol.NcAsmMode+import com.vayunmathur.headphones.protocol.NcAsmState++/**+ * High-level command API used by the UI. Each method translates an intent into the appropriate+ * [CommandBuilders] message and hands it to [HeadphonesService] for sending. NC/ASM edits are+ * applied as deltas on top of the last-known state so partial changes (e.g. just the ambient+ * slider) preserve the other fields.+ */+object HeadphonesController {++    private val currentNcAsm: NcAsmState+        get() = HeadphonesService.state.value.ncAsm++    fun setMode(mode: NcAsmMode) {+        HeadphonesService.send(CommandBuilders.setNcAsm(currentNcAsm.copy(mode = mode)))+    }++    fun setAmbientLevel(level: Int) {+        HeadphonesService.send(+            CommandBuilders.setNcAsm(+                currentNcAsm.copy(mode = NcAsmMode.AMBIENT_SOUND, ambientLevel = level),+            ),+        )+    }++    fun setVoicePassthrough(enabled: Boolean) {+        HeadphonesService.send(CommandBuilders.setNcAsm(currentNcAsm.copy(voicePassthrough = enabled)))+    }++    fun setWindNoiseReduction(enabled: Boolean) {+        HeadphonesService.send(+            CommandBuilders.setNcAsm(+                currentNcAsm.copy(mode = NcAsmMode.NOISE_CANCELLING, windNoiseReduction = enabled),+            ),+        )+    }++    fun setEqPreset(preset: EqPreset) {+        HeadphonesService.send(CommandBuilders.setEqPreset(preset))+    }++    fun setEqBands(bands: EqBands) {+        HeadphonesService.send(CommandBuilders.setEqCustom(bands))+    }++    fun setFeature(feature: Feature, enabled: Boolean) {+        HeadphonesService.send(CommandBuilders.setFeature(feature, enabled))+    }++    /** Cancels a device's multipoint registration. */+    fun removePairedDevice(address: String) {+        HeadphonesService.send(CommandBuilders.removePairedDevice(address))+    }++    fun refresh() {+        HeadphonesService.send(CommandBuilders.getDualBattery())+        HeadphonesService.send(CommandBuilders.getCaseBattery())+        HeadphonesService.send(CommandBuilders.getNcAsm())+        HeadphonesService.send(CommandBuilders.getEq())+    }++    /** Sends an arbitrary raw payload (Debug Log). */+    fun sendRaw(payload: ByteArray) {+        HeadphonesService.send(CommandBuilders.raw(payload))+    }+}
headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesService.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesService.kt b/headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesService.ktnew file mode 100644index 0000000000..220f02e24d--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/service/HeadphonesService.kt@@ -0,0 +1,258 @@+package com.vayunmathur.headphones.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.os.IBinder+import com.vayunmathur.headphones.HeadphonesState+import com.vayunmathur.headphones.R+import com.vayunmathur.headphones.bluetooth.BondedDeviceFinder+import com.vayunmathur.headphones.bluetooth.ConnectionState+import com.vayunmathur.headphones.bluetooth.RfcommManager+import com.vayunmathur.headphones.protocol.CommandBuilders+import com.vayunmathur.headphones.protocol.NcAsmMode+import com.vayunmathur.headphones.protocol.SonyMessage+import com.vayunmathur.headphones.protocol.SonyResponse+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++/**+ * Persistent foreground service that owns the [RfcommManager] connection, auto-reconnects with+ * backoff, runs the initial state queries on connect, folds parsed responses into a single+ * [HeadphonesState], and surfaces it through a companion `StateFlow` (the same pattern as+ * `SyncForegroundService`) so the UI can observe and command across recomposition.+ */+class HeadphonesService : Service() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+    private lateinit var manager: RfcommManager+    private lateinit var finder: BondedDeviceFinder+    private lateinit var ds: DataStoreUtils++    private var reconnectJob: Job? = null++    @Volatile+    private var targetAddress: String? = null++    override fun onCreate() {+        super.onCreate()+        instance = this+        manager = RfcommManager()+        finder = BondedDeviceFinder(this)+        ds = DataStoreUtils.getInstance(this)+        targetAddress = ds.getString(PREF_ADDRESS)?.takeIf { it.isNotBlank() }++        scope.launch {+            manager.state.collect { conn ->+                _state.update { it.copy(connection = conn) }+                updateNotification()+                when (conn) {+                    ConnectionState.Connected -> onConnected()+                    ConnectionState.Disconnected -> scheduleReconnect()+                    ConnectionState.Connecting -> {}+                }+            }+        }+        scope.launch { manager.responses.collect(::onResponse) }+        scope.launch {+            manager.traffic.collect { entry ->+                _traffic.tryEmit(entry)+                _trafficLog.value = (listOf(entry) + _trafficLog.value).take(MAX_TRAFFIC_LOG)+            }+        }+    }++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        startForeground(NOTIFICATION_ID, buildNotification())+        intent?.getStringExtra(EXTRA_ADDRESS)?.let { address ->+            targetAddress = address+            scope.launch { ds.setString(PREF_ADDRESS, address) }+        }+        attemptConnect()+        return START_STICKY+    }++    private fun attemptConnect() {+        val address = targetAddress ?: return+        if (manager.state.value != ConnectionState.Disconnected) return+        val device = finder.deviceFor(address) ?: return+        _state.update { it.copy(deviceName = device.name ?: address, deviceAddress = address) }+        manager.connect(device)+    }++    private fun scheduleReconnect() {+        if (targetAddress == null) return+        if (reconnectJob?.isActive == true) return+        reconnectJob = scope.launch {+            var delayMs = INITIAL_BACKOFF_MS+            while (manager.state.value == ConnectionState.Disconnected && targetAddress != null) {+                delay(delayMs)+                attemptConnect()+                delayMs = (delayMs * 2).coerceAtMost(MAX_BACKOFF_MS)+            }+        }+    }++    /** On connect, query the device for its capabilities and current state. */+    private fun onConnected() {+        reconnectJob?.cancel()+        manager.send(CommandBuilders.getCapabilities())+        manager.send(CommandBuilders.getDualBattery())+        manager.send(CommandBuilders.getCaseBattery())+        manager.send(CommandBuilders.getSingleBattery())+        manager.send(CommandBuilders.getNcAsm())+        manager.send(CommandBuilders.getEq())+        manager.send(CommandBuilders.subscribePairedDevices())+    }++    private fun onResponse(response: SonyResponse) {+        _state.update { current ->+            when (response) {+                is SonyResponse.Battery -> current.copy(battery = mergeBattery(current.battery, response))+                is SonyResponse.NcAsm -> current.copy(ncAsm = response.state)+                is SonyResponse.Eq -> current.copy(eqPreset = response.preset, eqBands = response.bands)+                is SonyResponse.Capabilities -> current.copy(capabilities = response.capabilities)+                is SonyResponse.SimpleFeature ->+                    current.copy(features = current.features + (response.toggle.feature to response.toggle.enabled))+                is SonyResponse.PairedDevices -> current.copy(pairedDevices = response.devices)+                is SonyResponse.Ack, is SonyResponse.Raw -> current+            }+        }+        updateNotification()+    }++    private fun mergeBattery(+        current: com.vayunmathur.headphones.protocol.BatteryInfo,+        response: SonyResponse.Battery,+    ): com.vayunmathur.headphones.protocol.BatteryInfo {+        val incoming = response.info+        return current.copy(+            single = if (incoming.single.isKnown) incoming.single else current.single,+            left = if (incoming.left.isKnown) incoming.left else current.left,+            right = if (incoming.right.isKnown) incoming.right else current.right,+            case = if (incoming.case.isKnown) incoming.case else current.case,+        )+    }++    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)+        val s = _state.value+        return Notification.Builder(this, CHANNEL_ID)+            .setContentTitle(s.deviceName ?: getString(R.string.notification_title))+            .setContentText(notificationText(s))+            .setSmallIcon(R.drawable.ic_launcher_foreground)+            .setOngoing(true)+            .build()+    }++    private fun notificationText(s: HeadphonesState): String {+        if (!s.isConnected) return getString(R.string.notification_disconnected)+        val parts = mutableListOf<String>()+        val b = s.battery+        when {+            b.left.isKnown || b.right.isKnown -> {+                if (b.left.isKnown) parts += "L ${b.left.level}%"+                if (b.right.isKnown) parts += "R ${b.right.level}%"+                if (b.case.isKnown) parts += "Case ${b.case.level}%"+            }+            b.single.isKnown -> parts += "${b.single.level}%"+        }+        parts += when (s.ncAsm.mode) {+            NcAsmMode.OFF -> "Off"+            NcAsmMode.NOISE_CANCELLING -> "Noise Cancelling"+            NcAsmMode.AMBIENT_SOUND -> "Ambient"+        }+        return parts.joinToString(" · ")+    }++    private fun updateNotification() {+        val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+        nm.notify(NOTIFICATION_ID, buildNotification())+    }++    override fun onDestroy() {+        manager.release()+        scope.cancel()+        instance = null+        _state.update { it.copy(connection = ConnectionState.Disconnected) }+        super.onDestroy()+    }++    override fun onBind(intent: Intent?): IBinder? = null++    companion object {+        private const val CHANNEL_ID = "headphones_connection"+        private const val NOTIFICATION_ID = 1+        private const val PREF_ADDRESS = "headphones_device_address"+        private const val EXTRA_ADDRESS = "address"+        private const val INITIAL_BACKOFF_MS = 2_000L+        private const val MAX_BACKOFF_MS = 60_000L++        @Volatile+        private var instance: HeadphonesService? = null++        private val _state = MutableStateFlow(HeadphonesState())+        val state: StateFlow<HeadphonesState> = _state++        private val _traffic = MutableSharedFlow<RfcommManager.TrafficEntry>(extraBufferCapacity = 256)+        val traffic: SharedFlow<RfcommManager.TrafficEntry> = _traffic++        /** Retained rolling log so the Debug page shows frames captured before it was opened. */+        private val _trafficLog = MutableStateFlow<List<RfcommManager.TrafficEntry>>(emptyList())+        val trafficLog: StateFlow<List<RfcommManager.TrafficEntry>> = _trafficLog+        private const val MAX_TRAFFIC_LOG = 300++        /** Persists [address] and (re)starts the service pointed at that device. */+        fun connectTo(context: Context, address: String) {+            val intent = Intent(context, HeadphonesService::class.java).putExtra(EXTRA_ADDRESS, address)+            context.startForegroundService(intent)+        }++        fun start(context: Context) =+            context.startForegroundService(Intent(context, HeadphonesService::class.java))++        /** Starts the service only if a device was previously chosen (so no idle notification). */+        fun startIfConfigured(context: Context) {+            val saved = DataStoreUtils.getInstance(context).getString(PREF_ADDRESS)+            if (!saved.isNullOrBlank()) start(context)+        }++        fun stop(context: Context) =+            context.stopService(Intent(context, HeadphonesService::class.java))++        /** Forgets the saved device and stops the connection. */+        fun forget(context: Context) {+            val svc = instance+            svc?.targetAddress = null+            svc?.scope?.launch { svc.ds.setString(PREF_ADDRESS, "") }+            svc?.manager?.disconnect()+            _state.value = HeadphonesState()+            stop(context)+        }++        /** Sends a command to the live connection (no-op if disconnected). */+        fun send(message: SonyMessage) {+            instance?.manager?.send(message)+        }+    }+}
headphones/src/main/java/com/vayunmathur/headphones/ui/Common.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/ui/Common.kt b/headphones/src/main/java/com/vayunmathur/headphones/ui/Common.ktnew file mode 100644index 0000000000..9d31e8af20--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/ui/Common.kt@@ -0,0 +1,23 @@+package com.vayunmathur.headphones.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp++@Composable+fun NotConnected() {+    Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {+        Text(+            "Not connected. Connect your headphones from the Home tab.",+            style = MaterialTheme.typography.bodyLarge,+            textAlign = TextAlign.Center,+        )+    }+}
headphones/src/main/java/com/vayunmathur/headphones/ui/Debouncer.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/ui/Debouncer.kt b/headphones/src/main/java/com/vayunmathur/headphones/ui/Debouncer.ktnew file mode 100644index 0000000000..95abce530b--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/ui/Debouncer.kt@@ -0,0 +1,31 @@+package com.vayunmathur.headphones.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import androidx.compose.runtime.rememberCoroutineScope++/**+ * Coalesces rapid UI events (slider drags, band edits) into a single trailing action so we don't+ * flood the RFCOMM link. Each [run] cancels the previous pending action.+ */+class Debouncer(private val scope: CoroutineScope, private val delayMs: Long) {+    private var job: Job? = null++    fun run(block: () -> Unit) {+        job?.cancel()+        job = scope.launch {+            delay(delayMs)+            block()+        }+    }+}++@Composable+fun rememberDebouncer(delayMs: Long = 250): Debouncer {+    val scope = rememberCoroutineScope()+    return remember { Debouncer(scope, delayMs) }+}
headphones/src/main/java/com/vayunmathur/headphones/ui/EqualizerPage.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/ui/EqualizerPage.kt b/headphones/src/main/java/com/vayunmathur/headphones/ui/EqualizerPage.ktnew file mode 100644index 0000000000..88b89c0cef--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/ui/EqualizerPage.kt@@ -0,0 +1,129 @@+package com.vayunmathur.headphones.ui++import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.material3.Card+import androidx.compose.material3.FilterChip+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Slider+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+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.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.headphones.protocol.EqBands+import com.vayunmathur.headphones.service.HeadphonesController+import com.vayunmathur.headphones.service.HeadphonesService++/**+ * Example EQ curves. These mirror the WF-1000XM5's built-in presets, but the app applies them+ * through the custom-EQ write (not the built-in preset id), so every change — example or manual+ * slider — is just an edit to the one custom curve.+ */+private data class ExampleEq(val name: String, val bands: EqBands)++private fun eq(clearBass: Int, vararg bands: Int) = EqBands(clearBass = clearBass, bands = bands.toList())++private val EXAMPLE_EQS = listOf(+    ExampleEq("Flat", eq(10, 10, 10, 10, 10, 10)),+    ExampleEq("Bright", eq(9, 10, 15, 17, 17, 19)),+    ExampleEq("Excited", eq(18, 9, 11, 10, 13, 15)),+    ExampleEq("Mellow", eq(7, 9, 8, 7, 6, 4)),+    ExampleEq("Relaxed", eq(1, 7, 9, 7, 5, 2)),+    ExampleEq("Vocal", eq(10, 16, 14, 12, 13, 9)),+    ExampleEq("Treble Boost", eq(10, 10, 10, 12, 16, 20)),+    ExampleEq("Bass Boost", eq(17, 10, 10, 10, 10, 10)),+    ExampleEq("Speech", eq(0, 14, 13, 11, 12, 0)),+)++private val BAND_LABELS = listOf("Clear Bass", "400", "1k", "2.5k", "6.3k", "16k")++@Composable+fun EqualizerPage() {+    val state by HeadphonesService.state.collectAsState()++    if (!state.isConnected) {+        NotConnected()+        return+    }+    if (!state.capabilities.supportsEqualizer) {+        Column(Modifier.fillMaxSize().padding(16.dp)) {+            Text("Equalizer is not supported on this device.")+        }+        return+    }++    val debouncer = rememberDebouncer()+    // Local slider state, seeded from the device and re-seeded when the device reports new bands.+    var bands by remember(state.eqBands) { mutableStateOf(state.eqBands) }++    fun apply(newBands: EqBands) {+        bands = newBands+        debouncer.run { HeadphonesController.setEqBands(newBands) }+    }++    Column(+        Modifier.fillMaxSize().padding(16.dp),+        verticalArrangement = Arrangement.spacedBy(16.dp),+    ) {+        Text("Presets", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+        Row(+            Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),+            horizontalArrangement = Arrangement.spacedBy(8.dp),+        ) {+            EXAMPLE_EQS.forEach { example ->+                FilterChip(+                    selected = bands == example.bands,+                    onClick = { apply(example.bands) },+                    label = { Text(example.name) },+                )+            }+        }++        Card(Modifier.fillMaxWidth()) {+            Column(Modifier.fillMaxWidth().padding(16.dp)) {+                Text("Custom bands", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                val values = listOf(bands.clearBass) + bands.bands+                values.forEachIndexed { index, value ->+                    BandSlider(BAND_LABELS[index], value) { newValue ->+                        apply(+                            if (index == 0) {+                                bands.copy(clearBass = newValue)+                            } else {+                                bands.copy(bands = bands.bands.toMutableList().also { it[index - 1] = newValue })+                            },+                        )+                    }+                }+            }+        }+    }+}++@Composable+private fun BandSlider(label: String, value: Int, onValueChange: (Int) -> Unit) {+    Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+        Text(label, Modifier.width(72.dp), style = MaterialTheme.typography.bodySmall)+        Slider(+            value = value.toFloat(),+            onValueChange = { onValueChange(it.toInt()) },+            valueRange = 0f..(EqBands.STEPS - 1).toFloat(),+            steps = EqBands.STEPS - 2,+            modifier = Modifier.weight(1f),+        )+        Text("${value - EqBands.CENTER}", Modifier.width(32.dp))+    }+}
headphones/src/main/java/com/vayunmathur/headphones/ui/HomePage.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/ui/HomePage.kt b/headphones/src/main/java/com/vayunmathur/headphones/ui/HomePage.ktnew file mode 100644index 0000000000..35046544f6--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/ui/HomePage.kt@@ -0,0 +1,173 @@+package com.vayunmathur.headphones.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.material3.Card+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.Slider+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+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.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.headphones.R+import com.vayunmathur.headphones.bluetooth.ConnectionState+import com.vayunmathur.headphones.protocol.BatteryComponent+import com.vayunmathur.headphones.protocol.BatteryInfo+import com.vayunmathur.headphones.protocol.DeviceCapabilities+import com.vayunmathur.headphones.protocol.NcAsmMode+import com.vayunmathur.headphones.protocol.NcAsmState+import com.vayunmathur.headphones.service.HeadphonesController+import com.vayunmathur.headphones.service.HeadphonesService++@Composable+fun HomePage() {+    val state by HeadphonesService.state.collectAsState()++    Column(+        Modifier.fillMaxSize().padding(16.dp),+        verticalArrangement = Arrangement.spacedBy(16.dp),+    ) {+        ConnectionCard(state.deviceName ?: state.deviceAddress ?: "", state.connection)+        if (state.connection == ConnectionState.Connected) {+            BatteryCard(state.battery)+            if (state.capabilities.supportsNcAsm) {+                NcAsmCard(state.ncAsm, state.capabilities)+            }+        }+    }+}++@Composable+private fun ConnectionCard(name: String, connection: ConnectionState) {+    Card(Modifier.fillMaxWidth()) {+        Row(+            Modifier.fillMaxWidth().padding(16.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            Column(Modifier.weight(1f)) {+                Text(name, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                Text(+                    when (connection) {+                        ConnectionState.Connected -> "Connected"+                        ConnectionState.Connecting -> "Connecting…"+                        ConnectionState.Disconnected -> "Disconnected"+                    },+                    style = MaterialTheme.typography.bodyMedium,+                )+            }+            if (connection == ConnectionState.Connecting) {+                CircularProgressIndicator(Modifier.size(24.dp))+            }+        }+    }+}++@Composable+private fun BatteryCard(battery: BatteryInfo) {+    Card(Modifier.fillMaxWidth()) {+        Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+            Text("Battery", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+            val dual = battery.left.isKnown || battery.right.isKnown+            if (dual) {+                BatteryRow("Left", battery.left)+                BatteryRow("Right", battery.right)+                if (battery.case.isKnown) BatteryRow("Case", battery.case)+            } else if (battery.single.isKnown) {+                BatteryRow("Battery", battery.single)+            } else {+                Text("—", style = MaterialTheme.typography.bodyMedium)+            }+        }+    }+}++@Composable+private fun BatteryRow(label: String, component: BatteryComponent) {+    Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+        Text(label, Modifier.weight(1f))+        if (component.charging) {+            Icon(painterResource(R.drawable.bolt_24px), contentDescription = "Charging", Modifier.size(16.dp))+            Spacer(Modifier.size(4.dp))+        }+        Text(if (component.isKnown) "${component.level}%" else "—", fontWeight = FontWeight.Bold)+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun NcAsmCard(ncAsm: NcAsmState, capabilities: DeviceCapabilities) {+    val debouncer = rememberDebouncer()+    var ambient by remember(ncAsm.ambientLevel) { mutableStateOf(ncAsm.ambientLevel.toFloat()) }++    Card(Modifier.fillMaxWidth()) {+        Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+            Text("Noise Control", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)++            val modes = listOf(+                NcAsmMode.NOISE_CANCELLING to "Noise Cancel",+                NcAsmMode.AMBIENT_SOUND to "Ambient",+                NcAsmMode.OFF to "Off",+            )+            SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {+                modes.forEachIndexed { index, (mode, label) ->+                    SegmentedButton(+                        selected = ncAsm.mode == mode,+                        onClick = { HeadphonesController.setMode(mode) },+                        shape = SegmentedButtonDefaults.itemShape(index, modes.size),+                    ) { Text(label) }+                }+            }++            if (ncAsm.mode == NcAsmMode.AMBIENT_SOUND && capabilities.supportsAmbientLevel) {+                Text("Ambient level: ${ambient.toInt()}", style = MaterialTheme.typography.bodyMedium)+                Slider(+                    value = ambient,+                    onValueChange = {+                        ambient = it+                        debouncer.run { HeadphonesController.setAmbientLevel(it.toInt()) }+                    },+                    valueRange = 0f..NcAsmState.MAX_AMBIENT_LEVEL.toFloat(),+                    steps = NcAsmState.MAX_AMBIENT_LEVEL - 1,+                )+                Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+                    Text("Focus on Voice", Modifier.weight(1f))+                    Switch(+                        checked = ncAsm.voicePassthrough,+                        onCheckedChange = { HeadphonesController.setVoicePassthrough(it) },+                    )+                }+            }++            if (ncAsm.mode == NcAsmMode.NOISE_CANCELLING && capabilities.supportsWindNoiseReduction) {+                Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+                    Text("Wind Noise Reduction", Modifier.weight(1f))+                    Switch(+                        checked = ncAsm.windNoiseReduction,+                        onCheckedChange = { HeadphonesController.setWindNoiseReduction(it) },+                    )+                }+            }+        }+    }+}
headphones/src/main/java/com/vayunmathur/headphones/ui/SettingsPage.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/ui/SettingsPage.kt b/headphones/src/main/java/com/vayunmathur/headphones/ui/SettingsPage.ktnew file mode 100644index 0000000000..eedf383e96--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/ui/SettingsPage.kt@@ -0,0 +1,93 @@+package com.vayunmathur.headphones.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Card+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.headphones.protocol.Feature+import com.vayunmathur.headphones.service.HeadphonesController+import com.vayunmathur.headphones.service.HeadphonesService++private val FEATURE_LABELS = listOf(+    Feature.DSEE to "DSEE (Upscaling)",+    Feature.SPEAK_TO_CHAT to "Speak-to-Chat",+    Feature.MULTIPOINT to "Multipoint",+    Feature.ADAPTIVE_SOUND_CONTROL to "Adaptive Sound Control",+)++@Composable+fun SettingsPage() {+    val context = LocalContext.current+    val state by HeadphonesService.state.collectAsState()++    Column(+        Modifier.fillMaxSize().padding(16.dp),+        verticalArrangement = Arrangement.spacedBy(16.dp),+    ) {+        if (state.isConnected) {+            if (state.pairedDevices.isNotEmpty()) {+                Card(Modifier.fillMaxWidth()) {+                    Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                        Text("Paired devices", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                        state.pairedDevices.forEach { device ->+                            Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+                                Column(Modifier.weight(1f)) {+                                    Text(device.name)+                                    Text(+                                        if (device.connected) "Connected" else "Registered",+                                        style = MaterialTheme.typography.bodySmall,+                                    )+                                }+                                TextButton(onClick = { HeadphonesController.removePairedDevice(device.address) }) {+                                    Text("Remove")+                                }+                            }+                        }+                    }+                }+            }++            Card(Modifier.fillMaxWidth()) {+                Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                    Text("Features", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                    val supported = FEATURE_LABELS.filter { state.capabilities.supports(it.first) }+                    if (supported.isEmpty()) {+                        Text("No optional features reported by this device.")+                    }+                    supported.forEach { (feature, label) ->+                        Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+                            Text(label, Modifier.weight(1f))+                            Switch(+                                checked = state.features[feature] == true,+                                onCheckedChange = { HeadphonesController.setFeature(feature, it) },+                            )+                        }+                    }+                }+            }+        } else {+            Text("Not connected.", style = MaterialTheme.typography.bodyMedium)+        }++        OutlinedButton(+            onClick = { HeadphonesService.forget(context) },+            modifier = Modifier.fillMaxWidth(),+        ) { Text("Forget device") }+    }+}
headphones/src/main/java/com/vayunmathur/headphones/ui/SupportedDevicesPage.kt
diff --git a/headphones/src/main/java/com/vayunmathur/headphones/ui/SupportedDevicesPage.kt b/headphones/src/main/java/com/vayunmathur/headphones/ui/SupportedDevicesPage.ktnew file mode 100644index 0000000000..d893bece43--- /dev/null+++ b/headphones/src/main/java/com/vayunmathur/headphones/ui/SupportedDevicesPage.kt@@ -0,0 +1,107 @@+package com.vayunmathur.headphones.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material3.Card+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.SnackbarHost+import androidx.compose.material3.SnackbarHostState+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.headphones.R+import com.vayunmathur.headphones.bluetooth.BondedDeviceFinder+import com.vayunmathur.headphones.service.HeadphonesService+import kotlinx.coroutines.launch++private data class SupportedModel(+    val name: String,+    val type: String,+    /** Uppercase substring used to match the bonded device by name. */+    val nameMatch: String,+)++private val SUPPORTED_MODELS = listOf(+    SupportedModel(name = "Sony WF-1000XM5", type = "Earbuds", nameMatch = "WF-1000XM5"),+)++/** Landing page shown until a device is connected: the list of supported headphones. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SupportedDevicesPage() {+    val context = LocalContext.current+    val finder = remember { BondedDeviceFinder(context) }+    val snackbar = remember { SnackbarHostState() }+    val scope = rememberCoroutineScope()++    Scaffold(+        topBar = { TopAppBar(title = { Text(stringResource(R.string.app_name)) }) },+        snackbarHost = { SnackbarHost(snackbar) },+    ) { innerPadding ->+        LazyColumn(+            modifier = Modifier+                .fillMaxSize()+                .padding(innerPadding)+                .padding(horizontal = 16.dp),+            verticalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            item {+                Text(+                    "Connect a device",+                    style = MaterialTheme.typography.titleMedium,+                    modifier = Modifier.padding(top = 8.dp),+                )+            }+            items(SUPPORTED_MODELS) { model ->+                DeviceCard(model) {+                    val match = finder.findCandidates()+                        .firstOrNull { it.name.uppercase().contains(model.nameMatch) }+                    if (match != null) {+                        HeadphonesService.connectTo(context, match.address)+                    } else {+                        scope.launch {+                            snackbar.showSnackbar("Pair your ${model.name} in Bluetooth settings first")+                        }+                    }+                }+            }+        }+    }+}++@Composable+private fun DeviceCard(model: SupportedModel, onClick: () -> Unit) {+    Card(Modifier.fillMaxWidth().clickable(onClick = onClick)) {+        Row(+            Modifier.fillMaxWidth().padding(16.dp),+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.spacedBy(16.dp),+        ) {+            Icon(painterResource(R.drawable.headphones_24px), contentDescription = null, Modifier.size(40.dp))+            Column(Modifier.weight(1f)) {+                Text(model.name, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                Text(model.type, style = MaterialTheme.typography.bodyMedium)+            }+        }+    }+}
headphones/src/main/res/drawable/bolt_24px.xml
diff --git a/headphones/src/main/res/drawable/bolt_24px.xml b/headphones/src/main/res/drawable/bolt_24px.xmlnew file mode 100644index 0000000000..168d13a6d6--- /dev/null+++ b/headphones/src/main/res/drawable/bolt_24px.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M7,2v11h3v9l7,-12h-4l4,-8z"/>+</vector>
headphones/src/main/res/drawable/bug_24px.xml
diff --git a/headphones/src/main/res/drawable/bug_24px.xml b/headphones/src/main/res/drawable/bug_24px.xmlnew file mode 100644index 0000000000..7853f61c9a--- /dev/null+++ b/headphones/src/main/res/drawable/bug_24px.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M20,8h-2.81c-0.45,-0.78 -1.07,-1.45 -1.82,-1.96L17,4.41 15.59,3l-2.17,2.17C12.96,5.06 12.49,5 12,5c-0.49,0 -0.96,0.06 -1.41,0.17L8.41,3 7,4.41l1.62,1.63C7.88,6.55 7.26,7.22 6.81,8L4,8v2h2.09c-0.05,0.33 -0.09,0.66 -0.09,1v1L4,12v2h2v1c0,0.34 0.04,0.67 0.09,1L4,16v2h2.81c1.04,1.79 2.97,3 5.19,3s4.15,-1.21 5.19,-3L20,18v-2h-2.09c0.05,-0.33 0.09,-0.66 0.09,-1v-1h2v-2h-2v-1c0,-0.34 -0.04,-0.67 -0.09,-1L20,10L20,8zM14,16h-4v-2h4v2zM14,12h-4v-2h4v2z"/>+</vector>
headphones/src/main/res/drawable/headphones_24px.xml
diff --git a/headphones/src/main/res/drawable/headphones_24px.xml b/headphones/src/main/res/drawable/headphones_24px.xmlnew file mode 100644index 0000000000..fd8c6e578f--- /dev/null+++ b/headphones/src/main/res/drawable/headphones_24px.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M12,1C7.03,1 3,5.03 3,10v7c0,1.66 1.34,3 3,3h3v-8H5v-2c0,-3.87 3.13,-7 7,-7s7,3.13 7,7v2h-4v8h3c1.66,0 3,-1.34 3,-3v-7c0,-4.97 -4.03,-9 -9,-9z"/>+</vector>
headphones/src/main/res/drawable/home_24px.xml
diff --git a/headphones/src/main/res/drawable/home_24px.xml b/headphones/src/main/res/drawable/home_24px.xmlnew file mode 100644index 0000000000..3a4c7dac9d--- /dev/null+++ b/headphones/src/main/res/drawable/home_24px.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M10,20v-6h4v6h5v-8h3L12,3 2,12h3v8z"/>+</vector>
headphones/src/main/res/drawable/ic_launcher_foreground.xml
diff --git a/headphones/src/main/res/drawable/ic_launcher_foreground.xml b/headphones/src/main/res/drawable/ic_launcher_foreground.xmlnew file mode 100644index 0000000000..1351d29f87--- /dev/null+++ b/headphones/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="24"+    android:viewportHeight="24"+    android:tint="#000000">+  <group android:scaleX="0.522"+      android:scaleY="0.522"+      android:translateX="5.736"+      android:translateY="5.736">+    <path+        android:fillColor="@android:color/white"+        android:pathData="M12,1C7.03,1 3,5.03 3,10v7c0,1.66 1.34,3 3,3h3v-8H5v-2c0,-3.87 3.13,-7 7,-7s7,3.13 7,7v2h-4v8h3c1.66,0 3,-1.34 3,-3v-7c0,-4.97 -4.03,-9 -9,-9z"/>+  </group>+</vector>
headphones/src/main/res/drawable/settings_24px.xml
diff --git a/headphones/src/main/res/drawable/settings_24px.xml b/headphones/src/main/res/drawable/settings_24px.xmlnew file mode 100644index 0000000000..41a82ede8b--- /dev/null+++ b/headphones/src/main/res/drawable/settings_24px.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M19.14,12.94c0.04,-0.3 0.06,-0.61 0.06,-0.94c0,-0.32 -0.02,-0.64 -0.07,-0.94l2.03,-1.58c0.18,-0.14 0.23,-0.41 0.12,-0.61l-1.92,-3.32c-0.12,-0.22 -0.37,-0.29 -0.59,-0.22l-2.39,0.96c-0.5,-0.38 -1.03,-0.7 -1.62,-0.94L14.4,2.81c-0.04,-0.24 -0.24,-0.41 -0.48,-0.41h-3.84c-0.24,0 -0.43,0.17 -0.47,0.41L9.25,5.35C8.66,5.59 8.12,5.92 7.63,6.29L5.24,5.33c-0.22,-0.08 -0.47,0 -0.59,0.22L2.74,8.87C2.62,9.08 2.66,9.34 2.86,9.48l2.03,1.58C4.84,11.36 4.8,11.69 4.8,12s0.02,0.64 0.07,0.94l-2.03,1.58c-0.18,0.14 -0.23,0.41 -0.12,0.61l1.92,3.32c0.12,0.22 0.37,0.29 0.59,0.22l2.39,-0.96c0.5,0.38 1.03,0.7 1.62,0.94l0.36,2.54c0.05,0.24 0.24,0.41 0.48,0.41h3.84c0.24,0 0.44,-0.17 0.47,-0.41l0.36,-2.54c0.59,-0.24 1.13,-0.56 1.62,-0.94l2.39,0.96c0.22,0.08 0.47,0 0.59,-0.22l1.92,-3.32c0.12,-0.22 0.07,-0.47 -0.12,-0.61L19.14,12.94zM12,15.6c-1.98,0 -3.6,-1.62 -3.6,-3.6s1.62,-3.6 3.6,-3.6s3.6,1.62 3.6,3.6S13.98,15.6 12,15.6z"/>+</vector>
headphones/src/main/res/drawable/tune_24px.xml
diff --git a/headphones/src/main/res/drawable/tune_24px.xml b/headphones/src/main/res/drawable/tune_24px.xmlnew file mode 100644index 0000000000..e8d34f1427--- /dev/null+++ b/headphones/src/main/res/drawable/tune_24px.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M3,17v2h6v-2L3,17zM3,5v2h10L13,5L3,5zM13,21v-2h8v-2h-8v-2h-2v6h2zM7,9v2L3,11v2h4v2h2L9,9L7,9zM21,13v-2L11,11v2h10zM15,9h2L17,7h4L21,5h-4L17,3h-2v6z"/>+</vector>
headphones/src/main/res/mipmap-anydpi/ic_launcher.xml
diff --git a/headphones/src/main/res/mipmap-anydpi/ic_launcher.xml b/headphones/src/main/res/mipmap-anydpi/ic_launcher.xmlnew file mode 100644index 0000000000..0b0d585e42--- /dev/null+++ b/headphones/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>
headphones/src/main/res/resources.properties
diff --git a/headphones/src/main/res/resources.properties b/headphones/src/main/res/resources.propertiesnew file mode 100644index 0000000000..467b3efec9--- /dev/null+++ b/headphones/src/main/res/resources.properties@@ -0,0 +1 @@+unqualifiedResLocale=en-US
headphones/src/main/res/values/strings.xml
diff --git a/headphones/src/main/res/values/strings.xml b/headphones/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..96809870b2--- /dev/null+++ b/headphones/src/main/res/values/strings.xml@@ -0,0 +1,17 @@+<resources>+    <string name="app_name">Headphones</string>++    <!-- Navigation / page labels -->+    <string name="label_home">Home</string>+    <string name="label_equalizer">Equalizer</string>+    <string name="label_settings">Settings</string>+    <string name="label_debug">Debug</string>++    <!-- Permissions -->+    <string name="grant_permissions">Grant Bluetooth permission</string>++    <!-- Foreground service notification -->+    <string name="notification_channel_name">Headphones connection</string>+    <string name="notification_title">Headphones</string>+    <string name="notification_disconnected">Disconnected</string>+</resources>
headphones/src/test/java/com/vayunmathur/headphones/protocol/CommandBuildersTest.kt
diff --git a/headphones/src/test/java/com/vayunmathur/headphones/protocol/CommandBuildersTest.kt b/headphones/src/test/java/com/vayunmathur/headphones/protocol/CommandBuildersTest.ktnew file mode 100644index 0000000000..99d4d06122--- /dev/null+++ b/headphones/src/test/java/com/vayunmathur/headphones/protocol/CommandBuildersTest.kt@@ -0,0 +1,105 @@+package com.vayunmathur.headphones.protocol++import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Test++class CommandBuildersTest {++    private fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }++    @Test+    fun ack_flipsSequenceNumberAndHasEmptyPayload() {+        val a = CommandBuilders.ack(0)+        assertEquals(DataType.ACK, a.dataType)+        assertEquals(1, a.sequenceNumber)+        assertEquals(0, a.payload.size)++        assertEquals(0, CommandBuilders.ack(1).sequenceNumber)+    }++    @Test+    fun battery_getters() {+        assertArrayEquals(bytes(0x22, 0x00), CommandBuilders.getSingleBattery().payload)+        assertArrayEquals(bytes(0x22, 0x09), CommandBuilders.getDualBattery().payload)+        assertArrayEquals(bytes(0x22, 0x0a), CommandBuilders.getCaseBattery().payload)+    }++    @Test+    fun setNcAsm_off() {+        val msg = CommandBuilders.setNcAsm(NcAsmState(mode = NcAsmMode.OFF))+        assertEquals(SonyProtocol.COMMAND_DATA_TYPE, msg.dataType)+        assertArrayEquals(bytes(0x68, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00), msg.payload)+    }++    @Test+    fun setNcAsm_ambientWithLevel() {+        val msg = CommandBuilders.setNcAsm(+            NcAsmState(mode = NcAsmMode.AMBIENT_SOUND, ambientLevel = 15),+        )+        assertArrayEquals(bytes(0x68, 0x17, 0x01, 0x01, 0x01, 0x00, 0x0f), msg.payload)+    }++    @Test+    fun setNcAsm_ambientWithVoicePassthrough() {+        val msg = CommandBuilders.setNcAsm(+            NcAsmState(mode = NcAsmMode.AMBIENT_SOUND, ambientLevel = 5, voicePassthrough = true),+        )+        assertArrayEquals(bytes(0x68, 0x17, 0x01, 0x01, 0x01, 0x01, 0x05), msg.payload)+    }++    @Test+    fun setNcAsm_noiseCancelling() {+        val msg = CommandBuilders.setNcAsm(NcAsmState(mode = NcAsmMode.NOISE_CANCELLING))+        assertArrayEquals(bytes(0x68, 0x17, 0x01, 0x01, 0x00, 0x00, 0x00), msg.payload)+    }++    @Test+    fun setNcAsm_clampsAmbientLevel() {+        val msg = CommandBuilders.setNcAsm(NcAsmState(mode = NcAsmMode.AMBIENT_SOUND, ambientLevel = 99))+        assertEquals(NcAsmState.MAX_AMBIENT_LEVEL, msg.payload[6].toInt() and 0xFF)+    }++    @Test+    fun setEqPreset() {+        assertArrayEquals(bytes(0x58, 0x00, 0x10, 0x00), CommandBuilders.setEqPreset(EqPreset.BRIGHT).payload)+    }++    @Test+    fun setEqCustom() {+        val bands = EqBands(clearBass = 12, bands = listOf(8, 9, 10, 11, 12))+        val msg = CommandBuilders.setEqCustom(bands)+        assertArrayEquals(+            bytes(0x58, 0x00, 0xa1, 0x06, 12, 8, 9, 10, 11, 12),+            msg.payload,+        )+    }++    @Test+    fun setMultipoint() {+        // Inverted: on = 0x00, off = 0x01.+        assertArrayEquals(bytes(0xd8, 0xd2, 0x00, 0x00), CommandBuilders.setFeature(Feature.MULTIPOINT, true).payload)+        assertArrayEquals(bytes(0xd8, 0xd2, 0x00, 0x01), CommandBuilders.setFeature(Feature.MULTIPOINT, false).payload)+    }++    @Test+    fun setFeature_dsee() {+        assertArrayEquals(bytes(0xe8, 0x02, 0x01), CommandBuilders.setFeature(Feature.DSEE, true).payload)+        assertArrayEquals(bytes(0xe8, 0x02, 0x00), CommandBuilders.setFeature(Feature.DSEE, false).payload)+    }++    @Test+    fun removePairedDevice() {+        val msg = CommandBuilders.removePairedDevice("C0:1C:6A:8D:67:FE")+        assertEquals(DataType.DATA_MDR_NO2, msg.dataType)+        val expected = bytes(0x3c, 0x02, 0x02) + "C0:1C:6A:8D:67:FE".toByteArray(Charsets.US_ASCII)+        assertArrayEquals(expected, msg.payload)+    }++    @Test+    fun raw_passesPayloadThrough() {+        val payload = bytes(0xde, 0xad, 0xbe, 0xef)+        val msg = CommandBuilders.raw(payload)+        assertArrayEquals(payload, msg.payload)+    }+}
headphones/src/test/java/com/vayunmathur/headphones/protocol/ResponseParsersTest.kt
diff --git a/headphones/src/test/java/com/vayunmathur/headphones/protocol/ResponseParsersTest.kt b/headphones/src/test/java/com/vayunmathur/headphones/protocol/ResponseParsersTest.ktnew file mode 100644index 0000000000..3ce9768b1b--- /dev/null+++ b/headphones/src/test/java/com/vayunmathur/headphones/protocol/ResponseParsersTest.kt@@ -0,0 +1,121 @@+package com.vayunmathur.headphones.protocol++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++class ResponseParsersTest {++    private fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }+    private fun mdr(vararg v: Int) = SonyMessage(DataType.DATA_MDR_NO2, 0, bytes(*v))++    @Test+    fun parsesDualBattery() {+        val r = ResponseParsers.parse(mdr(0x23, 0x09, 0x64, 0x00, 0x50, 0x01))+        assertTrue(r is SonyResponse.Battery)+        val info = (r as SonyResponse.Battery).info+        assertEquals(100, info.left.level)+        assertFalse(info.left.charging)+        assertEquals(80, info.right.level)+        assertTrue(info.right.charging)+    }++    @Test+    fun parsesSingleAndCaseBattery() {+        val single = ResponseParsers.parse(mdr(0x23, 0x00, 0x2a, 0x01)) as SonyResponse.Battery+        assertEquals(42, single.info.single.level)+        assertTrue(single.info.single.charging)++        val case = ResponseParsers.parse(mdr(0x23, 0x0a, 0x37, 0x00)) as SonyResponse.Battery+        assertEquals(55, case.info.case.level)+    }++    @Test+    fun parsesNcAsmAmbient() {+        val r = ResponseParsers.parse(mdr(0x69, 0x17, 0x01, 0x01, 0x01, 0x01, 0x0f))+        assertTrue(r is SonyResponse.NcAsm)+        val s = (r as SonyResponse.NcAsm).state+        assertEquals(NcAsmMode.AMBIENT_SOUND, s.mode)+        assertEquals(15, s.ambientLevel)+        assertTrue(s.voicePassthrough)+    }++    @Test+    fun parsesNcAsmOff() {+        val s = (ResponseParsers.parse(mdr(0x69, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00)) as SonyResponse.NcAsm).state+        assertEquals(NcAsmMode.OFF, s.mode)+    }++    @Test+    fun parsesNcAsmNoiseCancelling() {+        val s = (ResponseParsers.parse(mdr(0x69, 0x17, 0x01, 0x01, 0x00, 0x00, 0x00)) as SonyResponse.NcAsm).state+        assertEquals(NcAsmMode.NOISE_CANCELLING, s.mode)+    }++    @Test+    fun parsesEqPresetAndBands() {+        // Real "Bright" preset: 59 00 10 06 09 0a 0f 11 11 13+        val r = ResponseParsers.parse(mdr(0x59, 0x00, 0x10, 0x06, 0x09, 0x0a, 0x0f, 0x11, 0x11, 0x13))+        assertTrue(r is SonyResponse.Eq)+        val eq = r as SonyResponse.Eq+        assertEquals(EqPreset.BRIGHT, eq.preset)+        assertEquals(0x09, eq.bands.clearBass)+        assertEquals(listOf(0x0a, 0x0f, 0x11, 0x11, 0x13), eq.bands.bands)+    }++    @Test+    fun parsesAck() {+        val r = ResponseParsers.parse(SonyMessage(DataType.ACK, 1, ByteArray(0)))+        assertTrue(r is SonyResponse.Ack)+        assertEquals(1, (r as SonyResponse.Ack).sequenceNumber)+    }++    @Test+    fun parsesMultipointNtfy() {+        val on = ResponseParsers.parse(mdr(0xd9, 0xd2, 0x00, 0x00))+        assertTrue(on is SonyResponse.SimpleFeature)+        val onToggle = (on as SonyResponse.SimpleFeature).toggle+        assertEquals(Feature.MULTIPOINT, onToggle.feature)+        assertTrue(onToggle.enabled)++        val off = ResponseParsers.parse(mdr(0xd9, 0xd2, 0x00, 0x01)) as SonyResponse.SimpleFeature+        assertFalse(off.toggle.enabled)+    }++    @Test+    fun parsesPairedDeviceList() {+        // Real capture: two devices — "Pixel 7 Pro" (connected) and "Pixel 9 Pro XL" (registered).+        val hex = "39020230433a43343a31333a34343a43363a4430025a420c0b" ++            "506978656c20372050726f" ++            "43303a31433a36413a38443a36373a4645015a420c0e" ++            "506978656c20392050726f20584c01"+        val msg = SonyMessage(DataType.DATA_MDR_NO2, 0, hex.hexToByteArray())+        val r = ResponseParsers.parse(msg)+        assertTrue(r is SonyResponse.PairedDevices)+        val devices = (r as SonyResponse.PairedDevices).devices+        assertEquals(2, devices.size)+        assertEquals("0C:C4:13:44:C6:D0", devices[0].address)+        assertEquals("Pixel 7 Pro", devices[0].name)+        assertTrue(devices[0].connected)+        assertEquals("C0:1C:6A:8D:67:FE", devices[1].address)+        assertEquals("Pixel 9 Pro XL", devices[1].name)+        assertFalse(devices[1].connected)+    }++    @Test+    fun unknownOpcodeBecomesRaw() {+        val r = ResponseParsers.parse(mdr(0x7f, 0x01, 0x02))+        assertTrue(r is SonyResponse.Raw)+    }++    @Test+    fun endToEnd_frameAccumulateParse() {+        val wire = SonyFraming.frame(SonyMessage(DataType.DATA_MDR, 0, bytes(0x23, 0x09, 0x5a, 0x00, 0x5a, 0x00)))+        val msgs = FrameAccumulator().feed(wire)+        assertEquals(1, msgs.size)+        val r = ResponseParsers.parse(msgs[0]) as SonyResponse.Battery+        assertEquals(90, r.info.left.level)+        assertEquals(90, r.info.right.level)+    }+}
headphones/src/test/java/com/vayunmathur/headphones/protocol/SonyFramingTest.kt
diff --git a/headphones/src/test/java/com/vayunmathur/headphones/protocol/SonyFramingTest.kt b/headphones/src/test/java/com/vayunmathur/headphones/protocol/SonyFramingTest.ktnew file mode 100644index 0000000000..5e57d20cb5--- /dev/null+++ b/headphones/src/test/java/com/vayunmathur/headphones/protocol/SonyFramingTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.headphones.protocol++import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class SonyFramingTest {++    private fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }++    @Test+    fun checksum_isSumMod256() {+        assertEquals(0x06, SonyFraming.checksum(bytes(0x01, 0x02, 0x03)))+        assertEquals(0x00, SonyFraming.checksum(bytes(0x80, 0x80)))+        assertEquals(0xFF, SonyFraming.checksum(bytes(0xFF)))+    }++    @Test+    fun frame_producesExpectedBytesAndEscapesPayload() {+        // dataType=DATA_MDR_NO2 (0x0e), seq=0, payload=[0x3e] (a START byte -> must escape).+        val msg = SonyMessage(DataType.DATA_MDR_NO2, 0, bytes(0x3e))+        val framed = SonyFraming.frame(msg)+        // START | 0e 00 00 00 00 01 | 3d 2e (escaped 3e) | checksum 4d | END+        val expected = bytes(+            0x3e, // START+            0x0e, 0x00, 0x00, 0x00, 0x00, 0x01,+            0x3d, 0x2e, // escaped payload 0x3e+            0x4d, // checksum+            0x3c, // END+        )+        assertArrayEquals(expected, framed)+    }++    @Test+    fun frameThenAccumulate_roundTrips() {+        val msg = SonyMessage(DataType.DATA_MDR_NO2, 1, bytes(0x10, 0x09, 0x64, 0x00))+        val framed = SonyFraming.frame(msg)+        val out = FrameAccumulator().feed(framed)+        assertEquals(1, out.size)+        assertEquals(msg, out[0])+    }++    @Test+    fun escaping_roundTripsAllSpecialBytes() {+        // Payload full of bytes that require escaping.+        val msg = SonyMessage(+            DataType.DATA_MDR_NO2,+            0,+            bytes(SonyFraming.START, SonyFraming.END, SonyFraming.ESCAPE, 0x00, 0xFF),+        )+        val framed = SonyFraming.frame(msg)+        // No raw special bytes should appear inside the frame body (between first & last byte).+        for (i in 1 until framed.size - 1) {+            val v = framed[i].toInt() and 0xFF+            if (v == SonyFraming.START || v == SonyFraming.END) {+                // Only the ESCAPE marker itself is allowed; START/END must never appear inside.+                throw AssertionError("Unescaped special byte at index $i")+            }+        }+        val out = FrameAccumulator().feed(framed)+        assertEquals(1, out.size)+        assertEquals(msg, out[0])+    }++    @Test+    fun accumulator_handlesPartialReads() {+        val msg = SonyMessage(DataType.DATA_MDR_NO2, 0, bytes(0x66, 0x17, 0x01))+        val framed = SonyFraming.frame(msg)+        val acc = FrameAccumulator()+        val mid = framed.size / 2+        assertTrue(acc.feed(framed.copyOfRange(0, mid)).isEmpty())+        val out = acc.feed(framed.copyOfRange(mid, framed.size))+        assertEquals(1, out.size)+        assertEquals(msg, out[0])+    }++    @Test+    fun accumulator_handlesMultipleFramesInOneChunk() {+        val a = SonyMessage(DataType.DATA_MDR_NO2, 0, bytes(0x11, 0x00, 0x50, 0x01))+        val b = SonyMessage(DataType.ACK, 1, ByteArray(0))+        val chunk = SonyFraming.frame(a) + SonyFraming.frame(b)+        val out = FrameAccumulator().feed(chunk)+        assertEquals(2, out.size)+        assertEquals(a, out[0])+        assertEquals(b, out[1])+    }++    @Test+    fun accumulator_ignoresStrayBytesBeforeStart() {+        val msg = SonyMessage(DataType.DATA_MDR_NO2, 0, bytes(0x56, 0x00))+        val chunk = bytes(0x00, 0xAA, 0xBB) + SonyFraming.frame(msg)+        val out = FrameAccumulator().feed(chunk)+        assertEquals(1, out.size)+        assertEquals(msg, out[0])+    }++    @Test+    fun parse_rejectsBadChecksum() {+        val msg = SonyMessage(DataType.DATA_MDR_NO2, 0, bytes(0x10, 0x09))+        val framed = SonyFraming.frame(msg).copyOf()+        // Corrupt the checksum byte (second to last, before END).+        framed[framed.size - 2] = (framed[framed.size - 2] + 1).toByte()+        val out = FrameAccumulator().feed(framed)+        assertTrue(out.isEmpty())+    }++    @Test+    fun parse_rejectsDanglingEscape() {+        // START, ESCAPE, END — escape with nothing after it.+        val bad = bytes(SonyFraming.ESCAPE)+        assertNull(SonyFraming.parse(bad))+    }++    @Test+    fun hexHelpers_roundTrip() {+        val b = bytes(0x0c, 0x00, 0xFF, 0x3e)+        assertEquals("0c00ff3e", b.toHexString())+        assertArrayEquals(b, "0c 00 ff 3e".hexToByteArray())+        assertArrayEquals(b, "0x0c00FF3E".hexToByteArray())+    }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 66aac574d0..013834139e 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -69,3 +69,4 @@ include(":tools:holidaygen") include(":watch:shared") include(":watch:watch") include(":watch:phone")+include(":headphones")