From c2880b04b83609f2b6286aa66f5e08e2d2b38b26 Mon Sep 17 00:00:00 2001 From: Riko Date: Sun, 29 Nov 2026 08:16:40 -0800 Subject: [PATCH] CarLife USB: reopen the accessory after a session ends without a detach A head unit can end the CarLife session and restart it on a cable that was never touched, and Android delivers the accessory attach intent only to a foreground activity. The lease stayed recorded after its streams had closed, so every later scan saw the same accessory as connected and never opened it again until the app restarted. - A lease is live only while its streams are open. When Stream closes them, the lease opened at that generation is released and usb_lease_lost is reported; a newer lease is never dropped. - While no lease is live, the inventory is swept every 3 s on the accessory worker. A lost lease waits for the next sweep, so a head unit that ends every session at once is retried at that interval. - ACCESSORY_ATTACHED is also registered on the receiver (usb_attached). - SecurityException from openAccessory, a grant revoked by a detach while the old entry is listed, is retried on the next sweep instead of stopping with usb_error. Tests end sessions explicitly through an attach seam and drive sweeps with a manual timer, so they stay deterministic. --- .../direlay/carlife/AccessoryAttachment.kt | 11 ++ .../carlife/AndroidCarlifeAccessory.kt | 99 +++++++++++--- .../carlife/AccessoryAttachmentTest.kt | 21 +++ .../direlay/carlife/CarlifeUsbEventsTest.kt | 122 ++++++++++++++++-- 4 files changed, 221 insertions(+), 32 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/carlife/AccessoryAttachment.kt b/android/app/src/main/java/org/openxplay/direlay/carlife/AccessoryAttachment.kt index b354b82..04690a8 100644 --- a/android/app/src/main/java/org/openxplay/direlay/carlife/AccessoryAttachment.kt +++ b/android/app/src/main/java/org/openxplay/direlay/carlife/AccessoryAttachment.kt @@ -15,6 +15,7 @@ internal class AccessoryAttachment : Closeable { @Synchronized fun generation(): Long = epoch @Synchronized fun isCurrent(generation: Long): Boolean = !closed && epoch == generation @Synchronized fun contains(device: T): Boolean = current?.first == device + val live: Boolean @Synchronized get() = current != null fun install(device: T, generation: Long, lease: Closeable): Boolean { val accepted = synchronized(this) { @@ -34,6 +35,16 @@ internal class AccessoryAttachment : Closeable { return previous != null } + /** Drops the lease installed at [generation] when its streams ended; a newer lease is kept. */ + fun release(generation: Long): Boolean { + val previous = synchronized(this) { + if (current == null || epoch != generation) null + else { epoch++; current.also { current = null } } + } + previous?.second?.close() + return previous != null + } + override fun close() { synchronized(this) { closed = true } clear() diff --git a/android/app/src/main/java/org/openxplay/direlay/carlife/AndroidCarlifeAccessory.kt b/android/app/src/main/java/org/openxplay/direlay/carlife/AndroidCarlifeAccessory.kt index e292be9..c36f212 100644 --- a/android/app/src/main/java/org/openxplay/direlay/carlife/AndroidCarlifeAccessory.kt +++ b/android/app/src/main/java/org/openxplay/direlay/carlife/AndroidCarlifeAccessory.kt @@ -16,20 +16,39 @@ import org.openxplay.stream.carlife.CarlifeOutput import java.io.BufferedInputStream import java.io.Closeable import java.io.InputStream +import java.io.OutputStream import java.util.concurrent.Executors import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.ScheduledExecutorService +import java.util.concurrent.TimeUnit + +/** Schedules the next inventory sweep; the returned handle cancels it. */ +internal fun interface CarlifeSweepTimer { + fun schedule(task: Runnable): Closeable +} /** Android supplies the accessory role; Stream owns all CarLife bytes and channel multiplexing. */ -class AndroidCarlifeAccessory( +class AndroidCarlifeAccessory internal constructor( context: Context, - private val output: CarlifeOutput, - private val report: (String) -> Unit = {}, + private val attach: (InputStream, OutputStream, Closeable) -> Closeable, + sweepTimer: CarlifeSweepTimer?, + private val report: (String) -> Unit, ) : Closeable { + constructor(context: Context, output: CarlifeOutput, report: (String) -> Unit = {}) : + this(context, output::attachAccessory, null, report) + private val context = context.applicationContext private val manager = this.context.getSystemService(UsbManager::class.java) - private val worker = Executors.newSingleThreadExecutor { task -> + private val worker: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "carlife-accessory").apply { isDaemon = true } } + // Attach intents reach only a foreground activity, and a head unit can restart CarLife + // without a detach, so the inventory is swept again while no lease is live. + private val timer = sweepTimer ?: CarlifeSweepTimer { task -> + val future = worker.schedule(task, SWEEP_INTERVAL_MS, TimeUnit.MILLISECONDS) + Closeable { future.cancel(false) } + } + @Volatile private var sweep: Closeable? = null private val lifecycle = AccessoryAttachment() private val permissionAction = "${this.context.packageName}.CARLIFE_USB_PERMISSION" private var registered = false @@ -41,6 +60,7 @@ class AndroidCarlifeAccessory( // The detach extra identifies the old lease. A new open still requires live inventory and permission. when (intent.action) { permissionAction -> refresh(permissionResult = true) + UsbManager.ACTION_USB_ACCESSORY_ATTACHED -> refresh(permissionResult = false, attached = true) UsbManager.ACTION_USB_ACCESSORY_DETACHED -> refresh(permissionResult = false, detached = detachedAccessory(intent)) } } @@ -52,6 +72,7 @@ class AndroidCarlifeAccessory( if (registered || lifecycle.closed) return val filter = IntentFilter().apply { addAction(permissionAction) + addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED) addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED) } if (Build.VERSION.SDK_INT >= 33) context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) @@ -72,26 +93,49 @@ class AndroidCarlifeAccessory( else intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY) @Synchronized - private fun refresh(permissionResult: Boolean, detached: UsbAccessory? = null) { + private fun refresh(permissionResult: Boolean, detached: UsbAccessory? = null, attached: Boolean = false) { if (!registered || lifecycle.closed) return + submit { + if (attached) observe("usb_attached") + if (detached != null) { + if (requested == detached) requested = null + if (lifecycle.contains(detached) && lifecycle.clear()) report("usb_detached") + } + reconcile(permissionResult) + } + } + + /** The streams of the lease opened at [generation] closed: the session ended with or without a detach. */ + private fun streamsClosed(generation: Long) { + // Wait for the next sweep instead of reopening at once, so a head unit that ends every + // session immediately is retried at the sweep interval rather than in a tight loop. + submit(scan = false) { + if (lifecycle.release(generation)) { + lastObservation = "usb_lease_lost" + report("usb_lease_lost") + } + } + } + + private fun submit(scan: Boolean = true, work: () -> Unit) { try { worker.execute { if (lifecycle.closed) return@execute - runCatching { - if (detached != null) { - if (requested == detached) requested = null - if (lifecycle.contains(detached) && lifecycle.clear()) report("usb_detached") - } - reconcile(permissionResult) - }.onFailure { failure -> + runCatching { work() }.onFailure { failure -> observe("usb_error:${failure.javaClass.simpleName}") } + if (scan || !lifecycle.live) rearm() } } catch (_: RejectedExecutionException) { - // A detach or permission broadcast can race shutdown. + // A broadcast or stream teardown can race shutdown. } } + private fun rearm() { + sweep?.close() + sweep = if (lifecycle.closed || lifecycle.live) null else timer.schedule { refresh() } + } + private fun observe(message: String) { if (lastObservation != message) { lastObservation = message @@ -124,18 +168,23 @@ class AndroidCarlifeAccessory( return } val generation = lifecycle.generation() - val descriptor = usb.openAccessory(accessory) ?: run { + val descriptor = try { usb.openAccessory(accessory) } catch (_: SecurityException) { + // A detach revoked the grant while the old entry is still listed; ask again next sweep. + requested = null + observe("usb_permission_revoked") + return + } ?: run { observe("usb_unavailable") return } - val streams = try { AccessoryStreams(descriptor) } + val streams = try { AccessoryStreams(descriptor) { streamsClosed(generation) } } catch (failure: Exception) { descriptor.close(); throw failure } try { if (!lifecycle.isCurrent(generation)) { streams.close() return } - val attachment = output.attachAccessory(streams.input, streams.output, streams) + val attachment = attach(streams.input, streams.output, streams) val lease = Closeable { runCatching { attachment.close() } streams.close() @@ -153,6 +202,8 @@ class AndroidCarlifeAccessory( @Synchronized override fun close() { lifecycle.close() + sweep?.close() + sweep = null if (registered) runCatching { context.unregisterReceiver(receiver) } registered = false permission?.cancel() @@ -161,6 +212,8 @@ class AndroidCarlifeAccessory( } } +private const val SWEEP_INTERVAL_MS = 3_000L + internal fun carlifeAccessoryMatches(manufacturer: String?, model: String?): Boolean = manufacturer == "Baidu" && model == "CarLife" @@ -168,7 +221,10 @@ internal fun carlifeAccessoryMatches(manufacturer: String?, model: String?): Boo internal fun bufferAccessoryInput(input: InputStream): InputStream = BufferedInputStream(input, 16_384) /** Each direction owns a duplicate, so closing a stream cannot close a reused descriptor number. */ -private class AccessoryStreams(private val descriptor: ParcelFileDescriptor) : Closeable { +private class AccessoryStreams( + private val descriptor: ParcelFileDescriptor, + private val onClosed: () -> Unit, +) : Closeable { val input = bufferAccessoryInput( ParcelFileDescriptor.AutoCloseInputStream(ParcelFileDescriptor.dup(descriptor.fileDescriptor))) val output = try { @@ -177,13 +233,14 @@ private class AccessoryStreams(private val descriptor: ParcelFileDescriptor) : C input.close() throw failure } - private var closed = false - @Synchronized + private val closed = java.util.concurrent.atomic.AtomicBoolean(false) + + // No monitor is held while closing: the reader thread can end the session during this teardown. override fun close() { - if (closed) return - closed = true + if (!closed.compareAndSet(false, true)) return runCatching { descriptor.close() } runCatching { input.close() } runCatching { output.close() } + onClosed() } } diff --git a/android/app/src/test/java/org/openxplay/direlay/carlife/AccessoryAttachmentTest.kt b/android/app/src/test/java/org/openxplay/direlay/carlife/AccessoryAttachmentTest.kt index 07ac561..802a715 100644 --- a/android/app/src/test/java/org/openxplay/direlay/carlife/AccessoryAttachmentTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/carlife/AccessoryAttachmentTest.kt @@ -83,4 +83,25 @@ class AccessoryAttachmentTest { lifecycle.close() assertEquals(2, second) } + + @Test fun releaseDropsOnlyTheLeaseOfItsGeneration() { + val lifecycle = AccessoryAttachment() + var first = 0 + var second = 0 + val opened = lifecycle.generation() + assertTrue(lifecycle.install("first", opened, Closeable { first++ })) + assertTrue(lifecycle.live) + assertTrue(lifecycle.release(opened)) + assertFalse(lifecycle.live) + assertEquals(1, first) + assertFalse(lifecycle.release(opened)) + + val reopened = lifecycle.generation() + assertTrue(lifecycle.install("second", reopened, Closeable { second++ })) + assertFalse(lifecycle.release(opened)) + assertTrue(lifecycle.contains("second")) + assertEquals(0, second) + lifecycle.close() + assertEquals(1, second) + } } diff --git a/android/app/src/test/java/org/openxplay/direlay/carlife/CarlifeUsbEventsTest.kt b/android/app/src/test/java/org/openxplay/direlay/carlife/CarlifeUsbEventsTest.kt index f9cd5df..811157d 100644 --- a/android/app/src/test/java/org/openxplay/direlay/carlife/CarlifeUsbEventsTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/carlife/CarlifeUsbEventsTest.kt @@ -18,9 +18,6 @@ import java.util.concurrent.TimeUnit import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith -import org.openxplay.stream.carlife.CarlifeConfig -import org.openxplay.stream.carlife.CarlifeOutput -import org.openxplay.stream.core.* import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment @@ -42,6 +39,7 @@ class CarlifeUsbEventsTest { var scans = 0 var requests = 0 var unavailable = false + var revokeOnce = false val ioThreads = mutableListOf() @Implementation @@ -56,6 +54,7 @@ class CarlifeUsbEventsTest { opens++ ioThreads += Thread.currentThread() if (unavailable) return null + if (revokeOnce) { revokeOnce = false; throw SecurityException("revoked") } // Robolectric's dup shadow requires a seekable file descriptor. return super.openAccessory(accessory) } @@ -72,19 +71,34 @@ class CarlifeUsbEventsTest { val manager = context.getSystemService(UsbManager::class.java) val usb = Shadow.extract(manager) val reports = CopyOnWriteArrayList() - val output = CarlifeOutput(CarlifeConfig(tcp = false, discovery = false)) - val adapter = AndroidCarlifeAccessory(context, output, reports::add) + // Stream closes the accessory streams when a session ends; tests end sessions explicitly. + val sessions = CopyOnWriteArrayList() + val sweeps = CopyOnWriteArrayList() + private val timer = CarlifeSweepTimer { task -> + sweeps += task + Closeable { sweeps.remove(task) } + } + val adapter = AndroidCarlifeAccessory(context, { _, _, streams -> + sessions += streams + Closeable { streams.close() } + }, timer, reports::add) val activity = Robolectric.buildActivity(ComponentActivity::class.java).setup() init { - output.open(object : OutputHost { - override fun capabilities(capabilities: OutputCapabilities) = Unit - override fun control(event: ControlEvent) = Unit - override fun stats(stats: OutputStats) = Unit - }) activity.get().observeCarlifeUsb(adapter::refresh) } + fun sweep() { + val due = sweeps.toList() + sweeps.clear() + due.forEach { it.run() } + drain() + } + fun endSession() { + sessions.last().close() + drain() + } + fun start() { adapter.start(); drain() } fun attached() { activity.newIntent(Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED)) @@ -108,7 +122,6 @@ class CarlifeUsbEventsTest { override fun close() { activity.pause().stop().destroy() adapter.close() - output.close() } } @@ -235,6 +248,93 @@ class CarlifeUsbEventsTest { } } + @Test fun aSessionEndingWithoutDetachReopensOnTheNextSweep() { + Harness().use { h -> + val car = accessory() + h.usb.setAttachedUsbAccessory(car) + h.usb.grantPermission(car) + h.start() + assertEquals(1, h.usb.opens) + assertTrue(h.sweeps.isEmpty()) + + h.endSession() + assertEquals(listOf("usb_connected", "usb_lease_lost"), h.reports.toList()) + assertEquals(1, h.usb.opens) + assertEquals(1, h.sweeps.size) + + h.sweep() + assertEquals(2, h.usb.opens) + assertEquals(listOf("usb_connected", "usb_lease_lost", "usb_connected"), h.reports.toList()) + assertTrue(h.sweeps.isEmpty()) + } + } + + @Test fun closingADetachedLeaseDoesNotReportItLostOrDropTheNextOne() { + Harness().use { h -> + val car = accessory() + h.usb.setAttachedUsbAccessory(car) + h.usb.grantPermission(car) + h.start() + val first = h.sessions.single() + h.broadcast(UsbManager.ACTION_USB_ACCESSORY_DETACHED, car) + h.attached() + assertEquals(2, h.usb.opens) + first.close() + h.drain() + h.attached() + assertEquals(2, h.usb.opens) + assertEquals(listOf("usb_connected", "usb_detached", "usb_connected"), h.reports.toList()) + } + } + + @Test fun sweepsRunOnlyWhileNoLeaseIsLive() { + Harness().use { h -> + h.start() + assertEquals(1, h.sweeps.size) + val scans = h.usb.scans + h.sweep() + assertEquals(scans + 1, h.usb.scans) + assertEquals(listOf("usb_scan state=absent count=0"), h.reports.toList()) + + val car = accessory() + h.usb.setAttachedUsbAccessory(car) + h.usb.grantPermission(car) + h.sweep() + assertEquals(1, h.usb.opens) + assertTrue(h.sweeps.isEmpty()) + + h.adapter.close() + assertTrue(h.sweeps.isEmpty()) + } + } + + @Test fun aRevokedGrantIsRetriedOnTheNextSweep() { + Harness().use { h -> + val car = accessory() + h.usb.setAttachedUsbAccessory(car) + h.usb.grantPermission(car) + h.usb.revokeOnce = true + h.start() + assertEquals(listOf("usb_permission_revoked"), h.reports.toList()) + assertEquals(1, h.sweeps.size) + h.sweep() + assertEquals(2, h.usb.opens) + assertEquals(listOf("usb_permission_revoked", "usb_connected"), h.reports.toList()) + } + } + + @Test fun anAttachedBroadcastRescansTheInventory() { + Harness().use { h -> + h.start() + val car = accessory() + h.usb.setAttachedUsbAccessory(car) + h.usb.grantPermission(car) + h.broadcast(UsbManager.ACTION_USB_ACCESSORY_ATTACHED) + assertEquals(1, h.usb.opens) + assertEquals(listOf("usb_scan state=absent count=0", "usb_attached", "usb_connected"), h.reports.toList()) + } + } + @Test fun lateAttachAfterOutputCloseDoesNotScanOrRequestPermission() { Harness().use { h -> h.start()