maauto: USB + wireless transports, MAOS role, pairing UX
- Commit
620e4478240dfda4e30916d00fcddd23e8a663bf- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 21:20 UTC (2 months ago)
- Parents
81a71e0
Diff
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/DisplayRoutePolicy.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/DisplayRoutePolicy.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/DisplayRoutePolicy.ktnew file mode 100644index 0000000000..45b7160176--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/DisplayRoutePolicy.kt@@ -0,0 +1,36 @@+package com.vayunmathur.auto.protocol++/**+ * Which display the car UI renders on.+ *+ * Today `CarDisplay` builds a *private* virtual display, which needs no permission —+ * that is why the DHU test works on a stock phone. Launching *other apps'* activities+ * onto the car display needs a trusted display (`ADD_TRUSTED_DISPLAY`), which arrives+ * with the `SYSTEM_AUTOMOTIVE_PROJECTION` role; input injection needs+ * `CREATE_VIRTUAL_DEVICE`, from the same role. See HANDOFF.md §8.+ */+enum class DisplayRouteKind {+ /** `VIRTUAL_DISPLAY_FLAG_PRESENTATION` on a private display. No permission needed. */+ PRIVATE_VIRTUAL,++ /** Trusted display: other apps' activities may be launched onto it. Needs the role. */+ TRUSTED,+}++/**+ * Decides which display route a session uses.+ *+ * Pure policy so it stays host-testable: private until the MAOS role grants the+ * trusted-display permission, then trusted so Maps / Music / dialer activities can+ * be launched onto the car screen instead of mirrored. The video path itself+ * (`CarDisplay` → `VideoEncoder` → ch2) is unchanged either way.+ */+object DisplayRoutePolicy {++ /**+ * @param holdsProjectionRole whether this package currently holds+ * `android.app.role.SYSTEM_AUTOMOTIVE_PROJECTION`.+ */+ fun routeFor(holdsProjectionRole: Boolean): DisplayRouteKind =+ if (holdsProjectionRole) DisplayRouteKind.TRUSTED else DisplayRouteKind.PRIVATE_VIRTUAL+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MaosRole.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MaosRole.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MaosRole.ktnew file mode 100644index 0000000000..91d074ae91--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MaosRole.kt@@ -0,0 +1,51 @@+package com.vayunmathur.auto.protocol++/**+ * The MAOS system-role integration, as pure policy + constants.+ *+ * Gearhead holds `android.app.role.SYSTEM_AUTOMOTIVE_PROJECTION` (FINDINGS.md §1):+ * exclusive, static, systemOnly, no user picker — a build-time assignment pinned via+ * a `roles.xml` `defaultHolders="config_systemAutomotiveProjection"` entry plus a+ * privapp-permissions allowlist for the ~58 permissions the role itself does not+ * grant (`MANAGE_USB`, `MODIFY_AUDIO_ROUTING`, ...). Both halves are boot-fatal if+ * wrong, so they land one at a time on MAOS builds; on stock phones (including the+ * DHU loopback path) the role is simply absent and everything keeps working+ * degraded — private display, no trusted launch, no input injection.+ *+ * This file owns the strings both sides must agree on. The Android side+ * (`MaosRole`) only reads the platform state — `RoleManager.isRoleHeld()` — and+ * reports it here; the boot receiver re-starts the projection service after reboot.+ */+object MaosRole {++ /** The role MA Auto takes; MA Cast moves to `COMPANION_DEVICE_APP_STREAMING`. */+ const val PROJECTION_ROLE = "android.app.role.SYSTEM_AUTOMOTIVE_PROJECTION"++ /** The role config name the `roles.xml` patch pins via `defaultHolders`. */+ const val PROJECTION_ROLE_CONFIG = "config_systemAutomotiveProjection"++ /** Package name of the MAOS build this role work targets. */+ const val PACKAGE_NAME = "com.vayunmathur.auto"++ /**+ * What the role unlocks, so the UI can explain degraded state on stock phones.+ * Each maps to the permission set the role carries (FINDINGS.md §1).+ */+ enum class Capability {+ /** Launch other apps' activities onto the car display (`ADD_TRUSTED_DISPLAY`). */+ TRUSTED_DISPLAY,++ /** Inject head-unit input into the car display (`CREATE_VIRTUAL_DEVICE`). */+ INPUT_INJECTION,++ /** Read phone state / SMS / notifications for car templates. */+ PROJECTION_DATA,+ }++ /**+ * @param holdsRole whether the platform reports this package as the role holder.+ * @return the capabilities available in this install.+ */+ fun capabilities(holdsRole: Boolean): Set<Capability> =+ if (holdsRole) Capability.entries.toSet() else emptySet()+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportKind.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportKind.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportKind.ktnew file mode 100644index 0000000000..c9955a35fd--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportKind.kt@@ -0,0 +1,23 @@+package com.vayunmathur.auto.protocol++/**+ * How the GAL bytes reach the head unit.+ *+ * Every transport reduces to a [GalTransport]: USB is a `UsbAccessory` opened as a+ * `ParcelFileDescriptor` and read as an ordinary file descriptor+ * (`carsetup/setup/UsbConnectionHelper.java`), wireless is a TCP socket after the+ * Bluetooth RFCOMM bootstrap hands over the credentials, and TCP loopback is the+ * Desktop Head Unit over `adb forward`. Nothing above [GalConnection] knows which it has —+ * version negotiation, TLS and the whole bring-up are transport-agnostic.+ */+enum class TransportKind {+ /** Android Open Accessory Protocol over a USB cable. */+ USB,++ /** WiFi Direct (or AP) link after the Bluetooth bootstrap; TLS is reused unchanged. */+ WIRELESS,++ /** TCP loopback on [HeadUnitServer.DHU_PORT][com.vayunmathur.auto.network.HeadUnitServer.DHU_PORT].+ * Dev fallback only: the Desktop Head Unit over an adb forward. */+ TCP_LOOPBACK,+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportSelector.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportSelector.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportSelector.ktnew file mode 100644index 0000000000..0d8375ca50--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TransportSelector.kt@@ -0,0 +1,29 @@+package com.vayunmathur.auto.protocol++/**+ * Picks which transport a session runs on when more than one is available.+ *+ * Priority is physical first: USB beats wireless beats the TCP dev fallback, because a+ * cable is unambiguous proof of which car the user means, while wireless needs the+ * Bluetooth association to disambiguate. The loopback fallback exists only in dev builds+ * so a release phone never projects to whatever happens to listen on localhost.+ *+ * Pure policy: the drivers report readiness, this answers with an order. It owns no+ * retry or backoff — that stays with the reconnect owner in `ProjectionService`.+ */+object TransportSelector {++ /**+ * @param usbReady a granted, opened USB accessory is waiting.+ * @param wirelessReady a WiFi link with negotiated socket params is up.+ * @param devBuild whether the TCP loopback fallback is allowed ([BuildConfig.DEV_BUILD]).+ * @return the winning transport, or null when nothing may be used yet.+ */+ fun select(usbReady: Boolean, wirelessReady: Boolean, devBuild: Boolean): TransportKind? =+ when {+ usbReady -> TransportKind.USB+ wirelessReady -> TransportKind.WIRELESS+ devBuild -> TransportKind.TCP_LOOPBACK+ else -> null+ }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/UsbSession.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/UsbSession.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/UsbSession.ktnew file mode 100644index 0000000000..757c39ef64--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/UsbSession.kt@@ -0,0 +1,110 @@+package com.vayunmathur.auto.protocol++/** Where a USB accessory connection has got to. */+enum class UsbSessionState {+ /** No accessory announced itself yet. */+ DETACHED,++ /** Attached, waiting on the user's permission grant. */+ AWAITING_PERMISSION,++ /** Permission denied; stays here until detach or a re-request. */+ PERMISSION_DENIED,++ /** Granted and opened: bytes may flow into [GalConnection]. */+ CONNECTED,++ /** The accessory went away (or open failed) after having been seen. */+ DISCONNECTED,+}++/**+ * The Android Open Accessory Protocol bring-up, as a pure state machine.+ *+ * On a real car the head unit puts the phone into accessory mode itself and Android+ * delivers `USB_ACCESSORY_ATTACHED` to whoever matches the accessory filter; on the+ * DHU path there is no USB at all and this never leaves [UsbSessionState.DETACHED].+ * The Android side owns the `UsbManager` calls — request permission, open the+ * accessory, hand the file descriptor over as a [StreamTransport] — and reports the+ * outcomes here. This only tracks what those outcomes mean for the session.+ *+ * No threads, no I/O, no retry: the reconnect owner (`ProjectionService`) decides+ * whether a [UsbSessionState.DISCONNECTED] is worth re-accepting on.+ */+class UsbSession {++ var state: UsbSessionState = UsbSessionState.DETACHED+ private set++ /**+ * The USB manufacturer/model the accessory announced, from the attach intent+ * (`UsbAccessory.getManufacturer()/getModel()`). Empty until attached. Used by+ * the pairing UI to name the car while USB is the active transport.+ */+ var accessoryLabel: String? = null+ private set++ /**+ * Set when the session ends abnormally — open failure, permission denial —+ * for the trace log. Null on clean detach.+ */+ var failure: String? = null+ private set++ /** The accessory filter match fired: an AOAP head unit is on the cable. */+ fun onAttached(manufacturer: String?, model: String?) {+ accessoryLabel = listOfNotNull(manufacturer, model)+ .filter { it.isNotBlank() }+ .joinToString(" ")+ .ifEmpty { null }+ failure = null+ state = UsbSessionState.AWAITING_PERMISSION+ }++ /**+ * Whether `UsbManager.hasPermission()` is already true at attach time. When it+ * is, the driver skips the permission round-trip and calls [onPermissionGranted]+ * directly; a persisted grant across replugs lands here.+ */+ fun onAttachedWithPermission(manufacturer: String?, model: String?, hasPermission: Boolean) {+ onAttached(manufacturer, model)+ if (hasPermission) onPermissionGranted()+ }++ /** The user granted accessory access: the driver may now open the accessory. */+ fun onPermissionGranted() {+ if (state != UsbSessionState.AWAITING_PERMISSION) return+ failure = null+ state = UsbSessionState.CONNECTED+ }++ /** The user denied accessory access: projection over this cable is refused. */+ fun onPermissionDenied() {+ if (state != UsbSessionState.AWAITING_PERMISSION) return+ failure = "USB accessory permission denied"+ state = UsbSessionState.PERMISSION_DENIED+ }++ /** Opening the accessory failed after a grant (fd null, ioctl error, ...). */+ fun onOpenFailed(reason: String) {+ failure = reason.ifBlank { "USB accessory open failed" }+ state = UsbSessionState.DISCONNECTED+ }++ /** The cable was unplugged, or the accessory otherwise went away. */+ fun onDetached() {+ accessoryLabel = null+ // A clean unplug after a good session is not a failure; a denial that ends+ // in unplug keeps its explanation only while the denial row is showing.+ if (state != UsbSessionState.PERMISSION_DENIED) failure = null+ state = UsbSessionState.DETACHED+ }++ /** Re-request permission after a denial without a physical replug. */+ fun retryPermission(): Boolean {+ if (state != UsbSessionState.PERMISSION_DENIED) return false+ failure = null+ state = UsbSessionState.AWAITING_PERMISSION+ return true+ }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/WirelessSession.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/WirelessSession.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/WirelessSession.ktnew file mode 100644index 0000000000..f25635efc4--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/WirelessSession.kt@@ -0,0 +1,111 @@+package com.vayunmathur.auto.protocol++/** Where the wireless bring-up has got to. */+enum class WirelessSessionState {+ /** Bluetooth discovery / association has not produced a peer yet. */+ IDLE,++ /** Associated over Bluetooth, negotiating the WiFi link (group, band, credentials). */+ NEGOTIATING_WIFI,++ /** WiFi link parameters are agreed; the socket is not connected yet. */+ WIFI_READY,++ /** Socket connected: bytes may flow into [GalConnection] with TLS reused unchanged. */+ CONNECTED,++ /** The link dropped or setup failed after having started. */+ DISCONNECTED,+}++/**+ * The parameters the Bluetooth bootstrap hands over once WiFi is negotiated.+ *+ * Mirrors what gearhead's `WirelessSetupSharedService` + `BT_START` → RFCOMM+ * handshake produces before the stack falls through to a plain TCP socket: which+ * host to connect to, on which port, over which network. The GAL handshake itself+ * is untouched — TLS runs over this socket exactly as over USB or loopback.+ *+ * @param host the head unit's address on the WiFi link (group owner or AP).+ * @param port the GAL port the head unit listens on.+ * @param networkRequestId opaque handle the Android side uses to bind the socket+ * to the WiFi network (so it does not go out over mobile data); interpreted+ * only by the `WifiP2pConnector`, never parsed here.+ */+data class WirelessLinkParams(+ val host: String,+ val port: Int,+ val networkRequestId: Long = 0L,+)++/**+ * The wireless projection bring-up, as a pure state machine.+ *+ * Order follows gearhead: Bluetooth association first (driven by the companion-device+ * profile / `BT_START`), an RFCOMM handshake that yields WiFi credentials, then a+ * plain TCP socket to the head unit over WiFi. Everything at and above the socket —+ * GAL framing, TLS, the control session — is transport-agnostic and reused verbatim.+ *+ * No threads, no I/O, no retry: the Android side owns `BluetoothAdapter` /+ * `WifiP2pManager` calls and reports outcomes here; the reconnect owner+ * (`ProjectionService`) decides whether a [WirelessSessionState.DISCONNECTED] retries.+ */+class WirelessSession {++ var state: WirelessSessionState = WirelessSessionState.IDLE+ private set++ /** Agreed link parameters; null until [onWifiNegotiated]. */+ var linkParams: WirelessLinkParams? = null+ private set++ /**+ * Set when the session ends abnormally — association rejected, WiFi setup+ * failed, socket refused — for the trace log. Null on clean teardown.+ */+ var failure: String? = null+ private set++ /** Bluetooth association completed; WiFi negotiation starts. */+ fun onBluetoothAssociated() {+ if (state != WirelessSessionState.IDLE && state != WirelessSessionState.DISCONNECTED) return+ failure = null+ state = WirelessSessionState.NEGOTIATING_WIFI+ }++ /** WiFi credentials arrived over RFCOMM; the driver may now open the socket. */+ fun onWifiNegotiated(params: WirelessLinkParams) {+ if (state != WirelessSessionState.NEGOTIATING_WIFI) return+ linkParams = params+ failure = null+ state = WirelessSessionState.WIFI_READY+ }++ /** WiFi negotiation failed (timeout, rejected credentials, group formation lost). */+ fun onWifiFailed(reason: String) {+ if (state != WirelessSessionState.NEGOTIATING_WIFI) return+ failure = reason.ifBlank { "wireless WiFi negotiation failed" }+ linkParams = null+ state = WirelessSessionState.DISCONNECTED+ }++ /** The socket connected: GAL may start over it. */+ fun onSocketConnected() {+ if (state != WirelessSessionState.WIFI_READY) return+ failure = null+ state = WirelessSessionState.CONNECTED+ }++ /** The socket failed or the WiFi link dropped. */+ fun onDisconnected(reason: String) {+ failure = reason.ifBlank { "wireless link lost" }+ state = WirelessSessionState.DISCONNECTED+ }++ /** Clean teardown (user disabled wireless, car unpaired): forgets everything. */+ fun reset() {+ linkParams = null+ failure = null+ state = WirelessSessionState.IDLE+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TransportPolicyTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TransportPolicyTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TransportPolicyTest.ktnew file mode 100644index 0000000000..7eeb450405--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TransportPolicyTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.auto.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Transport priority and the display/role policy the pairing UI renders. */+class TransportPolicyTest {++ @Test+ fun `usb beats wireless beats loopback`() {+ assertEquals(+ TransportKind.USB,+ TransportSelector.select(usbReady = true, wirelessReady = true, devBuild = true),+ )+ assertEquals(+ TransportKind.WIRELESS,+ TransportSelector.select(usbReady = false, wirelessReady = true, devBuild = true),+ )+ assertEquals(+ TransportKind.TCP_LOOPBACK,+ TransportSelector.select(usbReady = false, wirelessReady = false, devBuild = true),+ )+ }++ @Test+ fun `release builds never fall back to loopback`() {+ assertNull(+ TransportSelector.select(usbReady = false, wirelessReady = false, devBuild = false),+ )+ // ...but a real transport still wins on release.+ assertEquals(+ TransportKind.WIRELESS,+ TransportSelector.select(usbReady = false, wirelessReady = true, devBuild = false),+ )+ }++ @Test+ fun `the display goes trusted only with the role`() {+ assertEquals(+ DisplayRouteKind.PRIVATE_VIRTUAL,+ DisplayRoutePolicy.routeFor(holdsProjectionRole = false),+ )+ assertEquals(+ DisplayRouteKind.TRUSTED,+ DisplayRoutePolicy.routeFor(holdsProjectionRole = true),+ )+ }++ @Test+ fun `capabilities follow the role`() {+ assertTrue(MaosRole.capabilities(holdsRole = false).isEmpty())+ assertEquals(+ MaosRole.Capability.entries.toSet(),+ MaosRole.capabilities(holdsRole = true),+ )+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/UsbSessionTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/UsbSessionTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/UsbSessionTest.ktnew file mode 100644index 0000000000..24d065c509--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/UsbSessionTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.auto.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The USB bring-up walked end to end: attach → permission → connected → detach,+ * plus the denial and open-failure branches the pairing UI must render.+ */+class UsbSessionTest {++ @Test+ fun `attach then grant connects`() {+ val session = UsbSession()+ assertEquals(UsbSessionState.DETACHED, session.state)++ session.onAttached("Android", "Android Auto")+ assertEquals(UsbSessionState.AWAITING_PERMISSION, session.state)+ assertEquals("Android Android Auto", session.accessoryLabel)++ session.onPermissionGranted()+ assertEquals(UsbSessionState.CONNECTED, session.state)+ assertNull(session.failure)+ }++ @Test+ fun `a persisted grant skips the permission round-trip`() {+ val session = UsbSession()++ session.onAttachedWithPermission("Android", "Android Auto", hasPermission = true)++ assertEquals(UsbSessionState.CONNECTED, session.state)+ }++ @Test+ fun `without a grant it waits on the user`() {+ val session = UsbSession()++ session.onAttachedWithPermission("Android", "Android Auto", hasPermission = false)++ assertEquals(UsbSessionState.AWAITING_PERMISSION, session.state)+ }++ @Test+ fun `denial is recorded and retryable without replug`() {+ val session = UsbSession()+ session.onAttached("Android", "Android Auto")++ session.onPermissionDenied()+ assertEquals(UsbSessionState.PERMISSION_DENIED, session.state)+ assertTrue(session.failure!!.contains("denied"))++ // Stray grants outside the permission window change nothing.+ session.onPermissionGranted()+ assertEquals(UsbSessionState.PERMISSION_DENIED, session.state)++ assertTrue(session.retryPermission())+ assertEquals(UsbSessionState.AWAITING_PERMISSION, session.state)+ assertNull(session.failure)+ }++ @Test+ fun `retry is refused outside a denial`() {+ val session = UsbSession()++ assertFalse(session.retryPermission())+ assertEquals(UsbSessionState.DETACHED, session.state)+ }++ @Test+ fun `open failure disconnects with a reason`() {+ val session = UsbSession()+ session.onAttached("Android", "Android Auto")+ session.onPermissionGranted()++ session.onOpenFailed("ParcelFileDescriptor was null")++ assertEquals(UsbSessionState.DISCONNECTED, session.state)+ assertEquals("ParcelFileDescriptor was null", session.failure)+ }++ @Test+ fun `detach clears the label and returns to detached`() {+ val session = UsbSession()+ session.onAttached("Android", "Android Auto")+ session.onPermissionGranted()++ session.onDetached()++ assertEquals(UsbSessionState.DETACHED, session.state)+ assertNull(session.accessoryLabel)+ assertNull(session.failure)+ }++ @Test+ fun `a blank accessory announcement still attaches`() {+ val session = UsbSession()++ session.onAttached(null, null)++ assertEquals(UsbSessionState.AWAITING_PERMISSION, session.state)+ assertNull(session.accessoryLabel)+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/WirelessSessionTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/WirelessSessionTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/WirelessSessionTest.ktnew file mode 100644index 0000000000..c70a52a4ae--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/WirelessSessionTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.auto.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The wireless bring-up walked end to end: Bluetooth association → WiFi+ * negotiation → socket, plus the negotiation-failure and link-loss branches.+ */+class WirelessSessionTest {++ private val params = WirelessLinkParams(host = "192.168.49.1", port = 5277)++ @Test+ fun `association then negotiation then socket connects`() {+ val session = WirelessSession()+ assertEquals(WirelessSessionState.IDLE, session.state)++ session.onBluetoothAssociated()+ assertEquals(WirelessSessionState.NEGOTIATING_WIFI, session.state)++ session.onWifiNegotiated(params)+ assertEquals(WirelessSessionState.WIFI_READY, session.state)+ assertEquals(params, session.linkParams)++ session.onSocketConnected()+ assertEquals(WirelessSessionState.CONNECTED, session.state)+ assertNull(session.failure)+ }++ @Test+ fun `negotiation failure disconnects with a reason`() {+ val session = WirelessSession()+ session.onBluetoothAssociated()++ session.onWifiFailed("group formation timed out")++ assertEquals(WirelessSessionState.DISCONNECTED, session.state)+ assertEquals("group formation timed out", session.failure)+ assertNull(session.linkParams)+ }++ @Test+ fun `link loss disconnects with a reason`() {+ val session = WirelessSession()+ session.onBluetoothAssociated()+ session.onWifiNegotiated(params)+ session.onSocketConnected()++ session.onDisconnected("socket refused")++ assertEquals(WirelessSessionState.DISCONNECTED, session.state)+ assertTrue(session.failure!!.contains("socket refused"))+ }++ @Test+ fun `out-of-order events are ignored`() {+ val session = WirelessSession()++ // Socket and WiFi answers with no negotiation in flight change nothing.+ session.onSocketConnected()+ session.onWifiNegotiated(params)+ session.onWifiFailed("late")+ assertEquals(WirelessSessionState.IDLE, session.state)+ assertNull(session.linkParams)+ assertNull(session.failure)++ // A second association while negotiating does not reset the attempt.+ session.onBluetoothAssociated()+ session.onBluetoothAssociated()+ assertEquals(WirelessSessionState.NEGOTIATING_WIFI, session.state)+ }++ @Test+ fun `reset forgets the link and returns to idle`() {+ val session = WirelessSession()+ session.onBluetoothAssociated()+ session.onWifiNegotiated(params)+ session.onSocketConnected()++ session.reset()++ assertEquals(WirelessSessionState.IDLE, session.state)+ assertNull(session.linkParams)+ assertNull(session.failure)+ }++ @Test+ fun `association after a drop starts a fresh attempt`() {+ val session = WirelessSession()+ session.onBluetoothAssociated()+ session.onWifiFailed("timeout")++ session.onBluetoothAssociated()++ assertEquals(WirelessSessionState.NEGOTIATING_WIFI, session.state)+ assertNull(session.failure)+ }+}
auto/src/main/java/com/vayunmathur/auto/network/TransportIntake.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/network/TransportIntake.kt b/auto/src/main/java/com/vayunmathur/auto/network/TransportIntake.ktnew file mode 100644index 0000000000..34f6038005--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/network/TransportIntake.kt@@ -0,0 +1,35 @@+package com.vayunmathur.auto.network++import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.TransportKind++/**+ * Where freshly-opened non-TCP transports wait for the pump loop.+ *+ * `HeadUnitServer.accept()` blocks for the TCP loopback path, but USB hands back an+ * already-open accessory file descriptor and WiFi Direct an already-connected socket —+ * neither can block-accept. The connectors wrap those in a [GalTransport] and park them+ * here; `ProjectionService.serve()` drains the queue before blocking on TCP, so the+ * reconnect/backoff ownership stays in one place and every transport runs the same+ * session body. TLS and the whole GAL bring-up are transport-agnostic, so nothing+ * downstream knows which intake won.+ */+object TransportIntake {++ /** An opened transport plus how the phone UI should name the car. */+ data class Pending(+ val transport: GalTransport,+ val carName: String,+ val kind: TransportKind,+ )++ private val queue = ArrayDeque<Pending>()++ @Synchronized+ fun offer(pending: Pending) {+ queue.addLast(pending)+ }++ @Synchronized+ fun take(): Pending? = queue.removeFirstOrNull()+}
auto/src/main/java/com/vayunmathur/auto/network/UsbConnector.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/network/UsbConnector.kt b/auto/src/main/java/com/vayunmathur/auto/network/UsbConnector.ktnew file mode 100644index 0000000000..e69937694a--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/network/UsbConnector.kt@@ -0,0 +1,145 @@+package com.vayunmathur.auto.network++import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.hardware.usb.UsbAccessory+import android.hardware.usb.UsbManager+import android.os.ParcelFileDescriptor+import android.util.Log+import com.vayunmathur.auto.platform.TransportState+import com.vayunmathur.auto.protocol.StreamTransport+import com.vayunmathur.auto.protocol.TransportKind+import com.vayunmathur.auto.protocol.UsbSession++/**+ * The USB (AOAP) bring-up: accessory attach → permission → open → intake.+ *+ * On a real car the head unit puts the phone into accessory mode itself and Android+ * delivers `USB_ACCESSORY_ATTACHED` to `MainActivity` (manifest filter), which forwards+ * the intent here via `onAccessoryIntent`, including re-delivery through `onNewIntent`.+ * The DHU path has no USB at all: this never fires there and TCP loopback is untouched.+ *+ * Bring-up state lives in a [UsbSession] (pure, JVM-tested) mirrored to+ * [TransportState] for the pairing UI. The opened file descriptor becomes a+ * [StreamTransport] — an accessory fd reads as an ordinary fd+ * (`carsetup/setup/UsbConnectionHelper.java`) — parked in [TransportIntake] for the+ * service loop. No retry of its own: a dropped cable surfaces as end-of-stream in the+ * session, owned by the reconnect logic.+ */+object UsbConnector {++ /** Broadcast action for the accessory-permission round-trip; see [UsbReceiver]. */+ const val ACTION_USB_PERMISSION = "com.vayunmathur.auto.USB_PERMISSION"++ private val session = UsbSession()+ private var lastAccessory: UsbAccessory? = null++ /**+ * Handles accessory intents forwarded from `MainActivity`.+ *+ * @return true when the intent was an accessory attach/detach this consumed.+ */+ @Suppress("DEPRECATION")+ fun onAccessoryIntent(context: Context, intent: Intent): Boolean {+ when (intent.action) {+ UsbManager.ACTION_USB_ACCESSORY_ATTACHED -> {+ val accessory =+ intent.getParcelableExtra<UsbAccessory>(UsbManager.EXTRA_ACCESSORY)+ ?: return false+ onAttached(context, accessory)+ return true+ }+ UsbManager.ACTION_USB_ACCESSORY_DETACHED -> {+ lastAccessory = null+ session.onDetached()+ TransportState.publishUsb(session)+ Log.i(TAG, "USB accessory detached")+ return true+ }+ else -> return false+ }+ }++ /**+ * Handles the permission answer from [UsbReceiver].+ *+ * @return true when the intent was the permission answer this consumed.+ */+ @Suppress("DEPRECATION")+ fun onPermissionResult(context: Context, intent: Intent): Boolean {+ if (intent.action != ACTION_USB_PERMISSION) return false+ val accessory = intent.getParcelableExtra<UsbAccessory>(UsbManager.EXTRA_ACCESSORY)+ val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)+ if (granted && accessory != null) {+ open(context, accessory)+ } else {+ session.onPermissionDenied()+ TransportState.publishUsb(session)+ Log.i(TAG, "USB accessory permission denied")+ }+ return true+ }++ /** Re-requests permission after a denial without a physical replug. */+ fun retryPermission(context: Context) {+ val accessory = lastAccessory ?: return+ if (!session.retryPermission()) return+ TransportState.publishUsb(session)+ requestPermission(context, accessory)+ }++ private fun onAttached(context: Context, accessory: UsbAccessory) {+ lastAccessory = accessory+ val manager = context.getSystemService(UsbManager::class.java)+ session.onAttachedWithPermission(+ accessory.manufacturer,+ accessory.model,+ hasPermission = manager?.hasPermission(accessory) == true,+ )+ TransportState.publishUsb(session)+ Log.i(TAG, "USB accessory attached: ${session.accessoryLabel}")+ val granted = manager?.hasPermission(accessory) == true+ if (granted) open(context, accessory) else requestPermission(context, accessory)+ }++ private fun requestPermission(context: Context, accessory: UsbAccessory) {+ val manager = context.getSystemService(UsbManager::class.java) ?: return+ val intent = Intent(ACTION_USB_PERMISSION).setPackage(context.packageName)+ // Mutable: the system fills in the grant answer on delivery (required on S+).+ val pending = PendingIntent.getBroadcast(+ context,+ 0,+ intent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,+ )+ manager.requestPermission(accessory, pending)+ }++ private fun open(context: Context, accessory: UsbAccessory) {+ val manager = context.getSystemService(UsbManager::class.java) ?: return+ val fd: ParcelFileDescriptor = runCatching { manager.openAccessory(accessory) }+ .getOrNull() ?: run {+ session.onOpenFailed("could not open ${accessory.model}")+ TransportState.publishUsb(session)+ return+ }+ val transport = StreamTransport(+ ParcelFileDescriptor.AutoCloseInputStream(fd),+ ParcelFileDescriptor.AutoCloseOutputStream(fd),+ )+ TransportIntake.offer(+ TransportIntake.Pending(+ transport = transport,+ carName = session.accessoryLabel ?: accessory.model ?: CAR_NAME_FALLBACK,+ kind = TransportKind.USB,+ ),+ )+ session.onPermissionGranted()+ TransportState.publishUsb(session)+ Log.i(TAG, "USB accessory open, transport parked for the service loop")+ }++ private const val TAG = "MaAuto.Usb"+ private const val CAR_NAME_FALLBACK = "Car"+}
auto/src/main/java/com/vayunmathur/auto/network/WifiDirectConnector.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/network/WifiDirectConnector.kt b/auto/src/main/java/com/vayunmathur/auto/network/WifiDirectConnector.ktnew file mode 100644index 0000000000..34ede44809--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/network/WifiDirectConnector.kt@@ -0,0 +1,268 @@+package com.vayunmathur.auto.network++import android.annotation.SuppressLint+import android.content.Context+import android.content.Intent+import android.net.ConnectivityManager+import android.net.Network+import android.net.NetworkCapabilities+import android.net.NetworkRequest+import android.net.NetworkInfo+import android.net.wifi.p2p.WifiP2pConfig+import android.net.wifi.p2p.WifiP2pManager+import android.os.Looper+import android.util.Log+import com.vayunmathur.auto.platform.TransportState+import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.StreamTransport+import com.vayunmathur.auto.protocol.TransportKind+import com.vayunmathur.auto.protocol.WirelessLinkParams+import com.vayunmathur.auto.protocol.WirelessSession+import com.vayunmathur.auto.protocol.WirelessSessionState+import java.io.IOException+import java.net.InetSocketAddress+import java.net.Socket+import kotlin.concurrent.thread++/**+ * The wireless bring-up: association consent → WiFi Direct → socket → intake.+ *+ * Order follows gearhead (`WirelessSetupSharedService` + `BT_START` → RFCOMM+ * handshake → TCP socket): the Bluetooth half is future work (companion-device+ * association driving the trigger per the FINDINGS.md phenotype checklist), and for+ * this first version the pairing screen's "Look for cars" tap stands in for the+ * association consent — the user pointing at a car is the disambiguation either way.+ * Everything from WiFi Direct group formation on is real: this owns group bring-up+ * through the connected socket. GAL over that socket is byte-identical to USB or+ * loopback — TLS is reused unchanged — so the socket becomes a [StreamTransport]+ * parked in [TransportIntake] for the same service loop.+ *+ * Bring-up state lives in a [WirelessSession] (pure, JVM-tested) mirrored to+ * [TransportState] for the pairing UI. No retry of its own: a dropped link surfaces+ * as end-of-stream in the session, owned by the reconnect logic.+ */+object WifiDirectConnector {++ private val session = WirelessSession()+ private var worker: Thread? = null+ @Volatile private var cancelled = false++ private var appContext: Context? = null+ private var manager: WifiP2pManager? = null+ private var channel: WifiP2pManager.Channel? = null++ /**+ * Starts WiFi Direct discovery toward the associated head unit. Call after the+ * nearby-devices permission is granted; the tap is the association consent.+ */+ fun start(context: Context) {+ cancelled = false+ appContext = context.applicationContext+ session.onBluetoothAssociated()+ TransportState.publishWireless(session)+ discover()+ }++ /** Cancels an in-flight bring-up; safe to call when idle. */+ fun cancel() {+ cancelled = true+ worker?.interrupt()+ worker = null+ session.reset()+ TransportState.publishWireless(session)+ }++ /**+ * Handles `WIFI_P2P_CONNECTION_CHANGED_ACTION` from the pairing screen's+ * listener: on connect, resolves the group owner's address into the GAL socket.+ */+ @Suppress("MissingPermission")+ fun onConnectionChanged(intent: Intent) {+ if (cancelled) return+ @Suppress("DEPRECATION")+ val networkInfo: NetworkInfo? =+ intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO)+ if (networkInfo?.isConnected != true) return+ val manager = manager+ val channel = channel+ if (manager == null || channel == null) return+ // Nearby-devices permission was granted to reach start(); the framework+ // enforces it again here, hence the suppression rather than a re-check.+ manager.requestConnectionInfo(channel) { info ->+ info?.groupOwnerAddress?.hostAddress?.let(::onGroupAddress)+ }+ }++ @SuppressLint("MissingPermission")+ private fun discover() {+ val context = appContext ?: run {+ fail("no application context for WiFi Direct")+ return+ }+ // Nearby-devices permission is granted before start() by the pairing+ // screen; the framework enforces it on every call below.+ val manager = context.getSystemService(WifiP2pManager::class.java) ?: run {+ fail("no WiFi Direct service")+ return+ }+ val channel = manager.initialize(context, Looper.getMainLooper(), null)+ this.manager = manager+ this.channel = channel+ manager.discoverPeers(+ channel,+ object : WifiP2pManager.ActionListener {+ override fun onSuccess() = requestGroup(manager, channel)+ override fun onFailure(reason: Int) = fail("peer discovery failed: $reason")+ },+ )+ }++ @SuppressLint("MissingPermission")+ private fun requestGroup(manager: WifiP2pManager, channel: WifiP2pManager.Channel) {+ if (cancelled) return+ manager.requestGroupInfo(+ channel,+ ) { group ->+ if (cancelled) return@requestGroupInfo+ val owner = group?.owner+ if (group == null || !group.isGroupOwner || owner == null) {+ connect(manager, channel)+ } else {+ onGroupAddress(owner.deviceAddress)+ }+ }+ }++ @SuppressLint("MissingPermission")+ private fun connect(manager: WifiP2pManager, channel: WifiP2pManager.Channel) {+ // Group owner unknown yet: connect to the associated peer and let the group form.+ // The head unit drives the persistent-group invitation on its side after the+ // Bluetooth association; an empty config joins whatever it offers.+ manager.connect(+ channel,+ WifiP2pConfig(),+ object : WifiP2pManager.ActionListener {+ override fun onSuccess() {+ // Connection info arrives via the framework broadcast, which the+ // pairing screen forwards to onConnectionChanged above.+ }+ override fun onFailure(reason: Int) = fail("WiFi Direct connect failed: $reason")+ },+ )+ }++ /**+ * Opens the GAL socket to the group owner on a worker thread so no thread that+ * matters ever blocks on connect.+ */+ private fun onGroupAddress(hostAddress: String) {+ if (cancelled) return+ session.onWifiNegotiated(WirelessLinkParams(host = hostAddress, port = GAL_PORT))+ TransportState.publishWireless(session)+ worker = thread(name = "ma-auto-wireless") {+ openSocket(hostAddress)+ }+ }++ private fun openSocket(hostAddress: String) {+ val params = session.linkParams ?: return+ bindToWifiNetwork()+ // NOT `use {}`: the service loop takes ownership of these streams and closes+ // the transport at session end. Closing here would hand it dead streams.+ val socket = Socket()+ try {+ socket.tcpNoDelay = true+ socket.connect(InetSocketAddress(params.host, params.port), CONNECT_TIMEOUT_MS)+ } catch (e: IOException) {+ runCatching { socket.close() }+ fail(e.message ?: "wireless socket failed")+ return+ }+ val transport = LeasedSocketTransport(+ StreamTransport(socket.getInputStream(), socket.getOutputStream()),+ socket,+ )+ TransportIntake.offer(+ TransportIntake.Pending(+ transport = transport,+ carName = CAR_NAME_FALLBACK,+ kind = TransportKind.WIRELESS,+ ),+ )+ if (!cancelled) {+ session.onSocketConnected()+ TransportState.publishWireless(session)+ Log.i(TAG, "wireless socket connected to $hostAddress, parked for the service loop")+ } else {+ runCatching { transport.close() }+ }+ }++ /**+ * Binds process traffic to the WiFi Direct network so the GAL socket does not go+ * out over mobile data. Best-effort: a missing network keeps the bring-up going on+ * the default route rather than failing it.+ */+ private fun bindToWifiNetwork() {+ runCatching {+ val context = appContext ?: return+ val connectivity = context.getSystemService(ConnectivityManager::class.java)+ ?: return+ val request = NetworkRequest.Builder()+ .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)+ .build()+ connectivity.requestNetwork(+ request,+ object : ConnectivityManager.NetworkCallback() {+ override fun onAvailable(network: Network) {+ connectivity.bindProcessToNetwork(network)+ connectivity.unregisterNetworkCallback(this)+ }+ },+ )+ }.onFailure { Log.w(TAG, "could not bind to the WiFi network", it) }+ }++ private fun fail(reason: String) {+ Log.w(TAG, reason)+ if (session.state == WirelessSessionState.NEGOTIATING_WIFI) {+ session.onWifiFailed(reason)+ } else {+ session.onDisconnected(reason)+ }+ TransportState.publishWireless(session)+ }++ /**+ * A socket-backed transport whose close also releases the socket. The streams are+ * owned by the inner [StreamTransport]; closing both in order leaks nothing.+ */+ private class LeasedSocketTransport(+ private val inner: StreamTransport,+ private val socket: Socket,+ ) : GalTransport {+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int =+ inner.read(buffer, offset, length)++ override fun write(bytes: ByteArray, offset: Int, length: Int) =+ inner.write(bytes, offset, length)++ override fun flush() = inner.flush()++ override fun close() {+ try {+ inner.close()+ } finally {+ socket.close()+ }+ }+ }++ private const val TAG = "MaAuto.Wireless"++ /** GAL port on the head unit's WiFi link; same number as the loopback fallback. */+ private const val GAL_PORT = 5277++ private const val CONNECT_TIMEOUT_MS = 10_000+ private const val CAR_NAME_FALLBACK = "Car"+}
auto/src/main/java/com/vayunmathur/auto/platform/BootReceiver.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/BootReceiver.kt b/auto/src/main/java/com/vayunmathur/auto/platform/BootReceiver.ktnew file mode 100644index 0000000000..d3b02e33f7--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/BootReceiver.kt@@ -0,0 +1,22 @@+package com.vayunmathur.auto.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.auto.service.ProjectionService++/**+ * Re-starts projection after a reboot so the phone listens again without being opened.+ *+ * The session is bound to the cable or the wireless link, not to an activity, so+ * boot persistence means the listener — not a UI — comes back. Refreshes the role+ * read while at it: an OTA could have changed the holder without the app running.+ */+class BootReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action != Intent.ACTION_BOOT_COMPLETED) return+ TransportState.publishRole(MaosRoleStatus.isProjectionRoleHeld(context))+ ProjectionService.start(context)+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/MaosRoleStatus.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MaosRoleStatus.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MaosRoleStatus.ktnew file mode 100644index 0000000000..2152db1361--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MaosRoleStatus.kt@@ -0,0 +1,22 @@+package com.vayunmathur.auto.platform++import android.app.role.RoleManager+import android.content.Context+import com.vayunmathur.auto.protocol.MaosRole++/**+ * Reads whether this package holds the projection role.+ *+ * On MAOS builds the `roles.xml` patch pins `SYSTEM_AUTOMOTIVE_PROJECTION` to+ * this package; on stock phones (including the DHU loopback path) the role is+ * simply absent and the session runs degraded — private display, no trusted+ * launch, no input injection. A missing service or any failure reads as+ * not-held rather than crashing the caller.+ */+object MaosRoleStatus {++ fun isProjectionRoleHeld(context: Context): Boolean = runCatching {+ context.getSystemService(RoleManager::class.java)+ ?.isRoleHeld(MaosRole.PROJECTION_ROLE) == true+ }.getOrDefault(false)+}
auto/src/main/java/com/vayunmathur/auto/platform/PairingViewModel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/PairingViewModel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/PairingViewModel.ktnew file mode 100644index 0000000000..8dfad12d3f--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/PairingViewModel.kt@@ -0,0 +1,38 @@+package com.vayunmathur.auto.platform++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.auto.protocol.TransportKind+import com.vayunmathur.auto.protocol.UsbSessionState+import com.vayunmathur.auto.protocol.WirelessSessionState+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.stateIn++/**+ * What the pairing screen shows, driven by the transport connectors.+ *+ * The connectors publish to [TransportState] from whatever thread they run on;+ * this ViewModel only re-exposes those flows on a scope the UI can collect. It+ * never writes — mirroring [AutoViewModel].+ */+class PairingViewModel : ViewModel() {+ val usbState: StateFlow<UsbSessionState> = TransportState.usbState+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), UsbSessionState.DETACHED)++ val usbLabel: StateFlow<String?> = TransportState.usbLabel+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++ val wirelessState: StateFlow<WirelessSessionState> = TransportState.wirelessState+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), WirelessSessionState.IDLE)++ val roleHeld: StateFlow<Boolean> = TransportState.roleHeld+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), false)++ val selected: StateFlow<TransportKind?> = TransportState.selected+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++ private companion object {+ const val STOP_TIMEOUT_MS = 5_000L+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/TransportState.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/TransportState.kt b/auto/src/main/java/com/vayunmathur/auto/platform/TransportState.ktnew file mode 100644index 0000000000..0a2d937966--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/TransportState.kt@@ -0,0 +1,68 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.BuildConfig+import com.vayunmathur.auto.protocol.TransportKind+import com.vayunmathur.auto.protocol.TransportSelector+import com.vayunmathur.auto.protocol.UsbSession+import com.vayunmathur.auto.protocol.UsbSessionState+import com.vayunmathur.auto.protocol.WirelessSession+import com.vayunmathur.auto.protocol.WirelessSessionState+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * What the pairing screen shows: USB + wireless bring-up state, the MAOS role,+ * and which transport won.+ *+ * Mirrors [AutoSessionState]: the connectors and receivers publish from whatever+ * thread they run on, and setting a [MutableStateFlow] value is thread-safe, so+ * these flows are the only thing shared with the UI. Selection itself is pure+ * ([TransportSelector]) over the published readiness — USB connected wins, then+ * wireless, then the TCP loopback fallback in dev builds only.+ */+object TransportState {+ private val _usbState = MutableStateFlow(UsbSessionState.DETACHED)+ val usbState: StateFlow<UsbSessionState> = _usbState.asStateFlow()++ /** Manufacturer + model the accessory announced; null until attached. */+ private val _usbLabel = MutableStateFlow<String?>(null)+ val usbLabel: StateFlow<String?> = _usbLabel.asStateFlow()++ private val _wirelessState = MutableStateFlow(WirelessSessionState.IDLE)+ val wirelessState: StateFlow<WirelessSessionState> = _wirelessState.asStateFlow()++ /** Whether this package currently holds `SYSTEM_AUTOMOTIVE_PROJECTION`. */+ private val _roleHeld = MutableStateFlow(false)+ val roleHeld: StateFlow<Boolean> = _roleHeld.asStateFlow()++ /** The winning transport; null when nothing may be used yet. */+ private val _selected = MutableStateFlow<TransportKind?>(null)+ val selected: StateFlow<TransportKind?> = _selected.asStateFlow()++ /** Mirrors a [UsbSession] after one of its transitions. */+ fun publishUsb(session: UsbSession) {+ _usbState.value = session.state+ _usbLabel.value = session.accessoryLabel+ refreshSelection()+ }++ /** Mirrors a [WirelessSession] after one of its transitions. */+ fun publishWireless(session: WirelessSession) {+ _wirelessState.value = session.state+ refreshSelection()+ }++ /** Records the platform role check; see `MaosRoleStatus`. */+ fun publishRole(held: Boolean) {+ _roleHeld.value = held+ }++ private fun refreshSelection() {+ _selected.value = TransportSelector.select(+ usbReady = _usbState.value == UsbSessionState.CONNECTED,+ wirelessReady = _wirelessState.value == WirelessSessionState.CONNECTED,+ devBuild = BuildConfig.DEV_BUILD,+ )+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/UsbReceiver.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/UsbReceiver.kt b/auto/src/main/java/com/vayunmathur/auto/platform/UsbReceiver.ktnew file mode 100644index 0000000000..853f203507--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/UsbReceiver.kt@@ -0,0 +1,29 @@+package com.vayunmathur.auto.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.hardware.usb.UsbManager+import com.vayunmathur.auto.network.UsbConnector++/**+ * Receives the USB permission answer and accessory detach while no activity is up.+ *+ * The permission round-trip outlives the tap that started it — the user may grant from+ * the system dialog while the app is backgrounded — so the answer lands here rather+ * than in `MainActivity`. Both outcomes funnel into [UsbConnector], which owns the+ * [com.vayunmathur.auto.protocol.UsbSession] and mirrors it to the pairing UI.+ */+class UsbReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action != UsbConnector.ACTION_USB_PERMISSION &&+ intent.action != UsbManager.ACTION_USB_ACCESSORY_DETACHED+ ) {+ return+ }+ if (!UsbConnector.onPermissionResult(context, intent)) {+ UsbConnector.onAccessoryIntent(context, intent)+ }+ }+}
auto/src/main/java/com/vayunmathur/auto/ui/PairingScreen.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/PairingScreen.kt b/auto/src/main/java/com/vayunmathur/auto/ui/PairingScreen.ktnew file mode 100644index 0000000000..bde74eabee--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/PairingScreen.kt@@ -0,0 +1,221 @@+package com.vayunmathur.auto.ui++import android.Manifest+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.net.wifi.p2p.WifiP2pManager+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.core.content.ContextCompat+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.auto.R+import com.vayunmathur.auto.network.UsbConnector+import com.vayunmathur.auto.network.WifiDirectConnector+import com.vayunmathur.auto.platform.PairingViewModel+import com.vayunmathur.auto.protocol.TransportKind+import com.vayunmathur.auto.protocol.UsbSessionState+import com.vayunmathur.auto.protocol.WirelessSessionState+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberMultiplePermissionRequest++/** How the phone attaches to a car: USB cable, wireless, and what the install allows. */+@Composable+fun PairingScreen(viewModel: PairingViewModel, onNavigateBack: () -> Unit) {+ val context = LocalContext.current+ val usbState by viewModel.usbState.collectAsStateWithLifecycle()+ val usbLabel by viewModel.usbLabel.collectAsStateWithLifecycle()+ val wirelessState by viewModel.wirelessState.collectAsStateWithLifecycle()+ val roleHeld by viewModel.roleHeld.collectAsStateWithLifecycle()+ val selected by viewModel.selected.collectAsStateWithLifecycle()++ // The framework announces group formation on a broadcast; forward it so the+ // connector can resolve the group owner's address into the GAL socket.+ DisposableEffect(context) {+ val receiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ WifiDirectConnector.onConnectionChanged(intent)+ }+ }+ val filter = IntentFilter(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)+ ContextCompat.registerReceiver(+ context,+ receiver,+ filter,+ ContextCompat.RECEIVER_NOT_EXPORTED,+ )+ onDispose { context.unregisterReceiver(receiver) }+ }++ val requestNearby = rememberMultiplePermissionRequest(+ permissions = arrayOf(+ Manifest.permission.ACCESS_FINE_LOCATION,+ Manifest.permission.NEARBY_WIFI_DEVICES,+ ),+ onResult = { granted ->+ if (granted) WifiDirectConnector.start(context)+ },+ )+ val scrollBehavior = appBarScrollBehavior()+ AppScaffold(+ title = stringResource(R.string.pairing_title),+ onNavigateBack = onNavigateBack,+ scrollBehavior = scrollBehavior,+ ) { padding ->+ Column(+ Modifier+ .padding(padding)+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 16.dp),+ ) {+ UsbRow(+ state = usbState,+ label = usbLabel,+ onRetry = remember(context) { { UsbConnector.retryPermission(context) } },+ modifier = Modifier.padding(top = 16.dp),+ )+ WirelessRow(+ state = wirelessState,+ onSearch = requestNearby,+ onCancel = remember { { WifiDirectConnector.cancel() } },+ modifier = Modifier.padding(top = 16.dp),+ )+ TransportRow(selected = selected, modifier = Modifier.padding(top = 16.dp))+ RoleRow(held = roleHeld, modifier = Modifier.padding(top = 16.dp))+ Text(+ text = stringResource(R.string.pairing_hint),+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.padding(vertical = 16.dp),+ )+ }+ }+}++/** USB cable state with a retry action after a denial. */+@Composable+private fun UsbRow(+ state: UsbSessionState,+ label: String?,+ onRetry: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val line = when (state) {+ UsbSessionState.DETACHED -> stringResource(R.string.pairing_usb_detached)+ UsbSessionState.AWAITING_PERMISSION ->+ stringResource(R.string.pairing_usb_permission, label ?: "")+ UsbSessionState.PERMISSION_DENIED -> stringResource(R.string.pairing_usb_denied)+ UsbSessionState.CONNECTED ->+ stringResource(R.string.pairing_usb_connected, label ?: "")+ UsbSessionState.DISCONNECTED -> stringResource(R.string.pairing_usb_lost)+ }+ Card(modifier.fillMaxWidth()) {+ Column {+ ListItem(+ headlineContent = { Text(stringResource(R.string.pairing_usb)) },+ supportingContent = { Text(line.trim()) },+ )+ if (state == UsbSessionState.PERMISSION_DENIED) {+ OutlinedButton(+ onClick = onRetry,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),+ ) {+ Text(stringResource(R.string.pairing_usb_retry))+ }+ }+ }+ }+}++/** Wireless bring-up state with search / cancel actions. */+@Composable+private fun WirelessRow(+ state: WirelessSessionState,+ onSearch: () -> Unit,+ onCancel: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val line = when (state) {+ WirelessSessionState.IDLE -> stringResource(R.string.pairing_wireless_idle)+ WirelessSessionState.NEGOTIATING_WIFI -> stringResource(R.string.pairing_wireless_searching)+ WirelessSessionState.WIFI_READY -> stringResource(R.string.pairing_wireless_ready)+ WirelessSessionState.CONNECTED -> stringResource(R.string.pairing_wireless_connected)+ WirelessSessionState.DISCONNECTED -> stringResource(R.string.pairing_wireless_lost)+ }+ Card(modifier.fillMaxWidth()) {+ Column {+ ListItem(+ headlineContent = { Text(stringResource(R.string.pairing_wireless)) },+ supportingContent = { Text(line) },+ )+ when (state) {+ WirelessSessionState.IDLE, WirelessSessionState.DISCONNECTED -> Button(+ onClick = onSearch,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),+ ) {+ Text(stringResource(R.string.pairing_wireless_search))+ }+ WirelessSessionState.NEGOTIATING_WIFI, WirelessSessionState.WIFI_READY -> OutlinedButton(+ onClick = onCancel,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),+ ) {+ Text(stringResource(R.string.pairing_wireless_cancel))+ }+ WirelessSessionState.CONNECTED -> Unit+ }+ }+ }+}++/** Which transport the session would run on; the loopback row only exists in dev. */+@Composable+private fun TransportRow(selected: TransportKind?, modifier: Modifier = Modifier) {+ val line = when (selected) {+ TransportKind.USB -> stringResource(R.string.pairing_transport_usb)+ TransportKind.WIRELESS -> stringResource(R.string.pairing_transport_wireless)+ TransportKind.TCP_LOOPBACK -> stringResource(R.string.pairing_transport_loopback)+ null -> stringResource(R.string.pairing_transport_none)+ }+ Card(modifier.fillMaxWidth()) {+ ListItem(+ headlineContent = { Text(stringResource(R.string.pairing_transport)) },+ supportingContent = { Text(line) },+ )+ }+}++/** Whether this install holds the projection role, and what that unlocks. */+@Composable+private fun RoleRow(held: Boolean, modifier: Modifier = Modifier) {+ Card(modifier.fillMaxWidth()) {+ ListItem(+ headlineContent = { Text(stringResource(R.string.pairing_role)) },+ supportingContent = {+ Text(+ stringResource(+ if (held) R.string.pairing_role_held+ else R.string.pairing_role_missing,+ ),+ )+ },+ )+ }+}