From 962c083fe6b381873e0d64b9bbe8b45152c13799 Mon Sep 17 00:00:00 2001 From: Jim Havrilla <6568964+jimhavrilla@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:30:18 -0500 Subject: [PATCH 1/4] Let the driver choose cable or wireless first, and switch each off Settings > Connection gains three rows: Connect over cable, Connect wirelessly on its own, and Try first (Cable or Wireless). - Cable first waits a few seconds for a cable when a known car comes up over Bluetooth, then goes wireless. - Wireless first keeps a running wireless start-up or session when a cable is plugged in, and opens the cable if wireless gives up. - A cable that fails falls back to wireless for a car seen over Bluetooth. - Turning wireless auto-connect off leaves the car's Bluetooth alone. - Home gets a Connect with cable button under Connect wirelessly. Co-Authored-By: Claude Opus 5.5 --- .../app/seb3thehacker/gearslip/AppSettings.kt | 40 +++++- .../app/seb3thehacker/gearslip/CableLink.kt | 20 +++ .../gearslip/GearslipActivity.kt | 130 ++++++++++++++++++ .../seb3thehacker/gearslip/ui/CableButton.kt | 50 +++++++ .../seb3thehacker/gearslip/ui/HomeScreen.kt | 1 + .../gearslip/ui/SettingsScreen.kt | 53 +++++++ .../gearslip/wireless/WirelessLink.kt | 8 +- gearslip/src/main/res/values/strings.xml | 16 +++ 8 files changed, 316 insertions(+), 2 deletions(-) create mode 100644 gearslip/src/main/java/app/seb3thehacker/gearslip/CableLink.kt create mode 100644 gearslip/src/main/java/app/seb3thehacker/gearslip/ui/CableButton.kt diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/AppSettings.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/AppSettings.kt index bf4608d..54ee8c6 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/AppSettings.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/AppSettings.kt @@ -12,6 +12,12 @@ object AppSettings { private const val KEY_SKIPPED_CERT_SETUP = "skipped_cert_setup" private const val KEY_SEEN_PERMISSIONS_SETUP = "seen_permissions_setup" private const val KEY_GEARSLIP_ENABLED = "gearslip_enabled" + private const val KEY_CABLE_ENABLED = "cable_enabled" + private const val KEY_WIRELESS_AUTO = "wireless_auto_connect" + private const val KEY_CONNECTION_ORDER = "connection_order" + + /** Which link Gearslip reaches for first when the car offers both. */ + enum class ConnectionOrder { CABLE_FIRST, WIRELESS_FIRST } private fun prefs(context: Context) = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) @@ -70,7 +76,7 @@ object AppSettings { * Only the alias changes: the driver's "always open with Gearslip" choice for the car is kept. */ fun applyGearslipEnabled(context: Context) { - val value = gearslipEnabled(context) + val value = gearslipEnabled(context) && cableEnabled(context) val appContext = context.applicationContext // The class name comes from the code's namespace, not the package: a debug build installs // as ".dev", but the alias is still app.seb3thehacker.gearslip.GearslipUsbAccessory. @@ -85,4 +91,36 @@ object AppSettings { runCatching { pm.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP) } .onFailure { GearslipLog.e("could not switch the USB connection ${if (value) "on" else "off"}", it) } } + + /** + * Whether Gearslip answers the car's USB connection. Off, the cable is left to stock Android + * Auto (or just charges), while wireless keeps working. On by default. + */ + fun cableEnabled(context: Context): Boolean = + prefs(context).getBoolean(KEY_CABLE_ENABLED, true) + + fun setCableEnabled(context: Context, value: Boolean) { + prefs(context).edit().putBoolean(KEY_CABLE_ENABLED, value).apply() + applyGearslipEnabled(context) + } + + /** + * Whether a known car coming up over Bluetooth starts wireless by itself. Off, the car's own + * Bluetooth (calls, music) is left alone until the driver taps Connect wirelessly. On by default. + */ + fun wirelessAutoConnect(context: Context): Boolean = + prefs(context).getBoolean(KEY_WIRELESS_AUTO, true) + + fun setWirelessAutoConnect(context: Context, value: Boolean) { + prefs(context).edit().putBoolean(KEY_WIRELESS_AUTO, value).apply() + } + + /** Cable first by default, which is how Gearslip has always behaved. */ + fun connectionOrder(context: Context): ConnectionOrder = + runCatching { ConnectionOrder.valueOf(prefs(context).getString(KEY_CONNECTION_ORDER, null)!!) } + .getOrDefault(ConnectionOrder.CABLE_FIRST) + + fun setConnectionOrder(context: Context, value: ConnectionOrder) { + prefs(context).edit().putString(KEY_CONNECTION_ORDER, value.name).apply() + } } diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/CableLink.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/CableLink.kt new file mode 100644 index 0000000..a929a77 --- /dev/null +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/CableLink.kt @@ -0,0 +1,20 @@ +package app.seb3thehacker.gearslip + +import android.content.Context +import android.hardware.usb.UsbAccessory +import android.hardware.usb.UsbManager + +/** + * The cable, seen from outside the activity. Android hands the car's USB connection to Gearslip + * when it's plugged in; this lets Home ask for it again by hand, for instance after the driver + * dismissed the first try or wireless came up first. + */ +object CableLink { + + /** Set by the activity: opens the attached car's USB connection, asking Android if it must. */ + @Volatile var connect: (() -> Unit)? = null + + /** The car on the cable, if one is plugged in and talking Android Auto. */ + fun attached(context: Context): UsbAccessory? = + runCatching { context.getSystemService(UsbManager::class.java)?.accessoryList?.firstOrNull() }.getOrNull() +} diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt index bcac7bd..55aaaab 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt @@ -44,6 +44,12 @@ import java.io.FileOutputStream * rotation or theme change from recreating it and dropping the connection. */ class GearslipActivity : ComponentActivity(), Projection { + private companion object { + const val ACTION_CABLE_PERMISSION = "app.seb3thehacker.gearslip.CABLE_PERMISSION" + /** Cable first: how long a car seen over Bluetooth waits for a cable before going wireless. */ + const val CABLE_GRACE_MS = 6_000L + } + private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper()) @@ -110,12 +116,36 @@ class GearslipActivity : ComponentActivity(), Projection { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == UsbManager.ACTION_USB_ACCESSORY_DETACHED) { GearslipLog.w("accessory detached") + deferredAccessory = null // A wireless session has no accessory to lose; leave it running. if (wirelessSocket == null) closeAccessory() } } } + /** A cable the car offered while wireless came first; opened if wireless gives up. */ + private var deferredAccessory: UsbAccessory? = null + + /** The last known car seen over Bluetooth, for falling back to wireless when the cable fails. */ + private var nearbyCar: String? = null + + /** Cable first: the wait for a cable before a car seen over Bluetooth goes wireless. */ + private var cableWait: Runnable? = null + + /** Android's answer to [requestCable]: open the cable if the driver allowed it. */ + private val cablePermissionReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action != ACTION_CABLE_PERMISSION) return + val accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY, UsbAccessory::class.java) + if (accessory != null && intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { + GearslipLog.i("cable: allowed") + start(accessory) + } else { + GearslipLog.w("cable: Android's dialog was declined") + } + } + } + /** Android's one-time "Allow" for a car to connect by itself; see [WirelessAuto]. */ private var approvingCar: String? = null @@ -152,6 +182,8 @@ class GearslipActivity : ComponentActivity(), Projection { runOnUiThread { startWireless(socket) } } app.seb3thehacker.gearslip.wireless.WirelessLink.sessionWaiting = { runner?.waitingForVersion == true } + app.seb3thehacker.gearslip.wireless.WirelessLink.onGaveUp = { runOnUiThread { fallBackToCable() } } + CableLink.connect = { runOnUiThread { connectCableByHand() } } app.seb3thehacker.gearslip.wireless.WirelessAuto.showApproval = { chooser, address -> runOnUiThread { approvingCar = address @@ -210,6 +242,7 @@ class GearslipActivity : ComponentActivity(), Projection { CarAudio.onConsentRequested = { runOnUiThread { requestAudioCapture() } } registerReceiver(detachReceiver, IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED), RECEIVER_NOT_EXPORTED) + registerReceiver(cablePermissionReceiver, IntentFilter(ACTION_CABLE_PERMISSION), RECEIVER_NOT_EXPORTED) handleIntent(intent) } @@ -251,8 +284,13 @@ class GearslipActivity : ComponentActivity(), Projection { super.onDestroy() app.seb3thehacker.gearslip.wireless.WirelessLink.onConnected = null app.seb3thehacker.gearslip.wireless.WirelessLink.sessionWaiting = null + app.seb3thehacker.gearslip.wireless.WirelessLink.onGaveUp = null + CableLink.connect = null + cableWait?.let(mainHandler::removeCallbacks) + cableWait = null app.seb3thehacker.gearslip.wireless.WirelessAuto.showApproval = null runCatching { unregisterReceiver(detachReceiver) } + runCatching { unregisterReceiver(cablePermissionReceiver) } PhoneMirror.onStartRequested = null PhoneMirror.onTokenReady = null PhoneMirror.onEnded = null @@ -361,11 +399,64 @@ class GearslipActivity : ComponentActivity(), Projection { SessionStatus.failed("Accessory missing", "The system reported a USB attach but did not include the accessory.") return } + if (!AppSettings.cableEnabled(this)) { + GearslipLog.i("accessory attached, but the cable is switched off - not connecting") + return + } GearslipLog.i("accessory attached by the system - permission is implicit on this path") + if (AppSettings.connectionOrder(this) == AppSettings.ConnectionOrder.WIRELESS_FIRST && wirelessActive()) { + GearslipLog.i("wireless comes first and is on it - holding the cable back") + deferredAccessory = accessory + return + } stepAsideOnVideo = !shownOnPhone start(accessory) } + /** A wireless session, or its start-up, is under way. */ + private fun wirelessActive(): Boolean = + wirelessSocket != null || app.seb3thehacker.gearslip.wireless.WirelessLink.busy + + /** Wireless gave up before reaching the car: use the cable if there is one. */ + private fun fallBackToCable() { + if (!AppSettings.gearslipEnabled(this) || !AppSettings.cableEnabled(this)) return + if (descriptor != null || wirelessSocket != null) return + val accessory = deferredAccessory ?: CableLink.attached(this) ?: return + deferredAccessory = null + GearslipLog.i("wireless gave up - trying the cable") + openCable(accessory) + } + + /** Home's Connect with cable. */ + private fun connectCableByHand() { + if (!AppSettings.gearslipEnabled(this)) return + val accessory = deferredAccessory ?: CableLink.attached(this) + if (accessory == null) { + GearslipLog.w("cable: nothing is plugged in") + return + } + deferredAccessory = null + GearslipLog.i("cable: connecting by hand") + openCable(accessory) + } + + /** Opens [accessory], first asking Android when the car didn't hand it over itself. */ + private fun openCable(accessory: UsbAccessory) { + val manager = getSystemService(UsbManager::class.java) + if (manager.hasPermission(accessory)) { + start(accessory) + return + } + GearslipLog.i("cable: asking Android for the car's USB connection") + val reply = android.app.PendingIntent.getBroadcast( + this, + 0, + Intent(ACTION_CABLE_PERMISSION).setPackage(packageName), + android.app.PendingIntent.FLAG_MUTABLE or android.app.PendingIntent.FLAG_UPDATE_CURRENT, + ) + manager.requestPermission(accessory, reply) + } + /** A known car came up over Bluetooth: connect wirelessly, unless USB or another try is already on it. */ private fun connectToNearbyCar(address: String?) { if (address == null) return @@ -373,6 +464,37 @@ class GearslipActivity : ComponentActivity(), Projection { GearslipLog.i("auto-connect: Gearslip is switched off - not connecting") return } + nearbyCar = address + if (!AppSettings.wirelessAutoConnect(this)) { + GearslipLog.i("auto-connect: wireless auto-connect is off - leaving the car's Bluetooth alone") + return + } + if (descriptor != null) { + GearslipLog.i("auto-connect: the car is on USB already - staying on USB") + return + } + // Cable first: give a cable the car may be bringing up a moment to show, and take it if it does. + if (AppSettings.connectionOrder(this) == AppSettings.ConnectionOrder.CABLE_FIRST && AppSettings.cableEnabled(this)) { + CableLink.attached(this)?.let { cable -> + GearslipLog.i("auto-connect: cable first, and one is plugged in - using it") + openCable(cable) + return + } + cableWait?.let(mainHandler::removeCallbacks) + val wait = Runnable { + cableWait = null + connectWireless(address) + } + cableWait = wait + GearslipLog.i("auto-connect: cable first - waiting ${CABLE_GRACE_MS / 1000} s for one") + mainHandler.postDelayed(wait, CABLE_GRACE_MS) + return + } + connectWireless(address) + } + + /** The wireless half of [connectToNearbyCar], also reached after the cable-first wait. */ + private fun connectWireless(address: String) { if (descriptor != null) { GearslipLog.i("auto-connect: the car is on USB already - staying on USB") return @@ -406,6 +528,9 @@ class GearslipActivity : ComponentActivity(), Projection { // point anyway (its read loop already died when the head unit dropped the transport), // but the accessory it opened was never explicitly closed, which is what actually blocks // a re-open - a dead thread does not release the file descriptor on its own. + // The cable is here, so a cable-first wait for it is over. + cableWait?.let(mainHandler::removeCallbacks) + cableWait = null closeAccessory() describe(accessory) @@ -414,6 +539,11 @@ class GearslipActivity : ComponentActivity(), Projection { if (pfd == null) { GearslipLog.e("openAccessory returned null - the session was claimed by someone else") SessionStatus.failed("Accessory unavailable", "Another app claimed the USB accessory before Gearslip could open it.") + // The cable didn't work out; a known car nearby can still go wireless. + nearbyCar?.takeIf { AppSettings.wirelessAutoConnect(this) }?.let { + GearslipLog.i("cable failed - trying wireless") + connectWireless(it) + } return } descriptor = pfd diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/CableButton.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/CableButton.kt new file mode 100644 index 0000000..392826f --- /dev/null +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/CableButton.kt @@ -0,0 +1,50 @@ +package app.seb3thehacker.gearslip.ui + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import app.seb3thehacker.gearslip.AppSettings +import app.seb3thehacker.gearslip.CableLink +import app.seb3thehacker.gearslip.R + +/** + * Wired Android Auto by hand, under the wireless button: opens the car on the cable, for when + * wireless came up first or the car's first try was dismissed. Hidden with the cable switched off. + */ +@Composable +internal fun CableButton() { + val context = LocalContext.current + if (!remember { AppSettings.cableEnabled(context) }) return + var nothingPlugged by remember { mutableStateOf(false) } + FilledTonalButton( + onClick = { + if (CableLink.attached(context) == null) nothingPlugged = true else CableLink.connect?.invoke() + }, + modifier = Modifier.fillMaxWidth().padding(top = 12.dp).height(56.dp), + ) { + Text(stringResource(R.string.cable_connect), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + } + if (nothingPlugged) { + AlertDialog( + onDismissRequest = { nothingPlugged = false }, + title = { Text(stringResource(R.string.cable_none_title)) }, + text = { Text(stringResource(R.string.cable_none_body)) }, + confirmButton = { TextButton(onClick = { nothingPlugged = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HomeScreen.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HomeScreen.kt index a3caa3b..e8da7c7 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HomeScreen.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/HomeScreen.kt @@ -388,6 +388,7 @@ private fun StatusCard(status: SessionStatus.Snapshot) { if (!live) { Spacer(Modifier.height(20.dp)) WirelessButton() + CableButton() } } } diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt index 7b20cc6..04be6ea 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt @@ -239,6 +239,7 @@ private fun ConnectionSection() { icon = Icons.Filled.Settings, trailing = { Switch(checked = enabled, onCheckedChange = null) }, ) + ConnectionOrderRows() // For a head unit or a tablet on the dash: the car UI becomes the device's home screen. var launcher by remember { mutableStateOf(LauncherMode.enabled(context)) } SettingsRow( @@ -279,6 +280,58 @@ private fun ConnectionSection() { } } +/** + * Cable and wireless, each switchable on its own, and which one Gearslip tries first when the + * car offers both. Wireless auto-connect off keeps Gearslip from fighting the car's Bluetooth. + */ +@Composable +private fun ConnectionOrderRows() { + val context = LocalContext.current + var cable by remember { mutableStateOf(AppSettings.cableEnabled(context)) } + var wireless by remember { mutableStateOf(AppSettings.wirelessAutoConnect(context)) } + var order by remember { mutableStateOf(AppSettings.connectionOrder(context)) } + SettingsRow( + stringResource(R.string.settings_cable), + Modifier.toggleable(cable, role = Role.Switch) { + cable = it + AppSettings.setCableEnabled(context, it) + }, + subtitle = stringResource(if (cable) R.string.settings_cable_on else R.string.settings_cable_off), + icon = Icons.Filled.Settings, + trailing = { Switch(checked = cable, onCheckedChange = null) }, + ) + SettingsRow( + stringResource(R.string.settings_wireless_auto), + Modifier.toggleable(wireless, role = Role.Switch) { + wireless = it + AppSettings.setWirelessAutoConnect(context, it) + }, + subtitle = stringResource(if (wireless) R.string.settings_wireless_auto_on else R.string.settings_wireless_auto_off), + icon = Icons.Filled.Refresh, + trailing = { Switch(checked = wireless, onCheckedChange = null) }, + ) + // An order only matters when both can start. + if (cable && wireless) { + val cableFirst = order == AppSettings.ConnectionOrder.CABLE_FIRST + SettingsRow( + stringResource(R.string.settings_order), + Modifier.clickable { + order = if (cableFirst) AppSettings.ConnectionOrder.WIRELESS_FIRST else AppSettings.ConnectionOrder.CABLE_FIRST + AppSettings.setConnectionOrder(context, order) + }, + subtitle = stringResource(if (cableFirst) R.string.settings_order_cable else R.string.settings_order_wireless), + icon = Icons.Filled.KeyboardArrowUp, + trailing = { + Text( + stringResource(if (cableFirst) R.string.settings_order_cable_short else R.string.settings_order_wireless_short), + color = MaterialTheme.colorScheme.primary, + fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, + ) + }, + ) + } +} + /** * Where the car's sound comes from: Bluetooth, or through Gearslip over the car link. Takes * effect at once when a car is connected. The chosen pill is filled in the main colour, the diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/wireless/WirelessLink.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/wireless/WirelessLink.kt index 80290c5..d2d29b6 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/wireless/WirelessLink.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/wireless/WirelessLink.kt @@ -80,6 +80,9 @@ object WirelessLink { /** Set by the activity: starts a session on the car's socket. */ @Volatile var onConnected: ((Socket) -> Unit)? = null + /** Set by the activity: a start-up ended without reaching the car, so the cable can have a go. */ + @Volatile var onGaveUp: (() -> Unit)? = null + /** Set by the activity: whether the session on the socket still waits for the car's first message. */ @Volatile var sessionWaiting: (() -> Boolean)? = null @@ -141,7 +144,10 @@ object WirelessLink { tryAndRetry(context, device, me) } finally { // A newer start-up has the service now; stop() already ended this one's. - if (worker === me) WirelessKeepAlive.stop(context) + if (worker === me) { + WirelessKeepAlive.stop(context) + if (!handedOver) onGaveUp?.invoke() + } } } diff --git a/gearslip/src/main/res/values/strings.xml b/gearslip/src/main/res/values/strings.xml index 6a4225c..a4470f3 100644 --- a/gearslip/src/main/res/values/strings.xml +++ b/gearslip/src/main/res/values/strings.xml @@ -419,6 +419,22 @@ The car connects over its own Wi-Fi, so turn on Wi-Fi to connect wirelessly. Turn on Wi-Fi + + Connect with cable + No car on the cable + Plug the phone into the car\'s USB port with a data cable, then try again. + Connect over cable + Gearslip answers the car\'s USB connection + Off: the cable only charges, or Android Auto takes it + Connect wirelessly on its own + Starts when a car you\'ve connected to comes up on Bluetooth + Off: the car\'s Bluetooth is left alone until you tap Connect wirelessly + Try first + Cable. Gearslip waits a few seconds for one before going wireless. + Wireless. A cable plugged in later doesn\'t take over, but steps in if wireless fails. + Cable + Wireless + Voice: live words Voice: final words From 095141ad075a18628c27531f8c1b0119bae99cb7 Mon Sep 17 00:00:00 2001 From: Jim Havrilla <6568964+jimhavrilla@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:30:18 -0500 Subject: [PATCH 2/4] Show cable and wireless as a list ordered by priority Each link gets a number, an arrow to move it, and its own switch, in place of a separate Try first row. Co-Authored-By: Claude Opus 5.5 --- .../gearslip/ui/SettingsScreen.kt | 84 +++++++++++-------- gearslip/src/main/res/values/strings.xml | 14 ++-- 2 files changed, 57 insertions(+), 41 deletions(-) diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt index 04be6ea..d5887d3 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt @@ -281,8 +281,8 @@ private fun ConnectionSection() { } /** - * Cable and wireless, each switchable on its own, and which one Gearslip tries first when the - * car offers both. Wireless auto-connect off keeps Gearslip from fighting the car's Bluetooth. + * Cable and wireless as a short list in the order Gearslip tries them: arrows move a link up or + * down, and each has its own switch. Wireless off keeps Gearslip from fighting the car's Bluetooth. */ @Composable private fun ConnectionOrderRows() { @@ -290,44 +290,62 @@ private fun ConnectionOrderRows() { var cable by remember { mutableStateOf(AppSettings.cableEnabled(context)) } var wireless by remember { mutableStateOf(AppSettings.wirelessAutoConnect(context)) } var order by remember { mutableStateOf(AppSettings.connectionOrder(context)) } - SettingsRow( - stringResource(R.string.settings_cable), - Modifier.toggleable(cable, role = Role.Switch) { - cable = it - AppSettings.setCableEnabled(context, it) - }, - subtitle = stringResource(if (cable) R.string.settings_cable_on else R.string.settings_cable_off), - icon = Icons.Filled.Settings, - trailing = { Switch(checked = cable, onCheckedChange = null) }, + val links = if (order == AppSettings.ConnectionOrder.CABLE_FIRST) listOf(true, false) else listOf(false, true) + fun swap() { + order = if (order == AppSettings.ConnectionOrder.CABLE_FIRST) AppSettings.ConnectionOrder.WIRELESS_FIRST + else AppSettings.ConnectionOrder.CABLE_FIRST + AppSettings.setConnectionOrder(context, order) + } + Text( + stringResource(R.string.settings_order_hint), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 4.dp), ) - SettingsRow( - stringResource(R.string.settings_wireless_auto), - Modifier.toggleable(wireless, role = Role.Switch) { - wireless = it - AppSettings.setWirelessAutoConnect(context, it) - }, - subtitle = stringResource(if (wireless) R.string.settings_wireless_auto_on else R.string.settings_wireless_auto_off), - icon = Icons.Filled.Refresh, - trailing = { Switch(checked = wireless, onCheckedChange = null) }, - ) - // An order only matters when both can start. - if (cable && wireless) { - val cableFirst = order == AppSettings.ConnectionOrder.CABLE_FIRST + links.forEachIndexed { index, isCable -> + val on = if (isCable) cable else wireless SettingsRow( - stringResource(R.string.settings_order), - Modifier.clickable { - order = if (cableFirst) AppSettings.ConnectionOrder.WIRELESS_FIRST else AppSettings.ConnectionOrder.CABLE_FIRST - AppSettings.setConnectionOrder(context, order) + stringResource(if (isCable) R.string.settings_cable else R.string.settings_wireless_auto), + Modifier.toggleable(on, role = Role.Switch) { + if (isCable) { + cable = it + AppSettings.setCableEnabled(context, it) + } else { + wireless = it + AppSettings.setWirelessAutoConnect(context, it) + } }, - subtitle = stringResource(if (cableFirst) R.string.settings_order_cable else R.string.settings_order_wireless), - icon = Icons.Filled.KeyboardArrowUp, - trailing = { + subtitle = stringResource( + when { + isCable && on -> R.string.settings_cable_on + isCable -> R.string.settings_cable_off + on -> R.string.settings_wireless_auto_on + else -> R.string.settings_wireless_auto_off + }, + ), + leading = { Text( - stringResource(if (cableFirst) R.string.settings_order_cable_short else R.string.settings_order_wireless_short), - color = MaterialTheme.colorScheme.primary, + "${index + 1}", + style = MaterialTheme.typography.titleLarge, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, + color = if (on) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, ) }, + trailing = { + androidx.compose.foundation.layout.Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) { + // With two links, moving either one swaps them. + if (index > 0) { + IconButton(onClick = ::swap) { + Icon(Icons.Filled.KeyboardArrowUp, contentDescription = stringResource(R.string.settings_order_up)) + } + } else { + IconButton(onClick = ::swap) { + Icon(Icons.Filled.KeyboardArrowDown, contentDescription = stringResource(R.string.settings_order_down)) + } + } + Switch(checked = on, onCheckedChange = null) + } + }, ) } } diff --git a/gearslip/src/main/res/values/strings.xml b/gearslip/src/main/res/values/strings.xml index a4470f3..bdb7f4b 100644 --- a/gearslip/src/main/res/values/strings.xml +++ b/gearslip/src/main/res/values/strings.xml @@ -424,16 +424,14 @@ No car on the cable Plug the phone into the car\'s USB port with a data cable, then try again. Connect over cable - Gearslip answers the car\'s USB connection + When the phone is plugged into the car Off: the cable only charges, or Android Auto takes it - Connect wirelessly on its own - Starts when a car you\'ve connected to comes up on Bluetooth + Connect wirelessly + On its own, when a car you\'ve used comes up on Bluetooth Off: the car\'s Bluetooth is left alone until you tap Connect wirelessly - Try first - Cable. Gearslip waits a few seconds for one before going wireless. - Wireless. A cable plugged in later doesn\'t take over, but steps in if wireless fails. - Cable - Wireless + Gearslip tries these in order. Use the arrows to choose which comes first. + Move up + Move down Voice: live words From 5055e39ed2b4af943b058fb6f8a97e39034bef37 Mon Sep 17 00:00:00 2001 From: Jim Havrilla <6568964+jimhavrilla@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:46:27 -0500 Subject: [PATCH 3/4] Music starts on every cable connection without flipping the audio setting - The music asks the car for its speakers only once the car shows Gearslip's screen. A head unit answered LOSS within 2 ms to every ask made before that, and Gearslip took it as final: a cable plugged back in quickly played nothing. A car keeping its own screen is asked when the wait for the screen runs out, as before. - Capture is asked for whenever the car opens its music channel with music through Gearslip. The only ask was the car screen's, once per screen, so a reconnect to a screen kept from the drive before played nothing until the driver flipped the audio setting. Co-Authored-By: Claude Opus 5.5 --- .../seb3thehacker/gearslip/GearslipRunner.kt | 11 +++ .../seb3thehacker/gearslip/audio/AudioLink.kt | 33 +++++++ .../gearslip/audio/AudioLinkFocusTest.kt | 96 +++++++++++++++++++ 3 files changed, 140 insertions(+) create mode 100644 gearslip/src/test/java/app/seb3thehacker/gearslip/audio/AudioLinkFocusTest.kt diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt index 46b0e4b..35cd52e 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt @@ -87,6 +87,8 @@ class GearslipRunner( private var selectedConfigIndex: Int? = null private var vehicleProfile: VehicleProfile? = null @Volatile private var videoStarted = false + /** The car shows Gearslip's screen: the music asks for its speakers only from here on. */ + @Volatile private var screenShown = false /** The car's screen has been asked for once, so asking again is in order. */ @Volatile private var focusAsked = false private var videoSource: VideoSource? = null @@ -636,6 +638,7 @@ class GearslipRunner( media, sendOnChannel = { id, body -> send(id, body, encrypted = true, channel = media.serviceId) }, sendControl = { id, body -> send(id, body, encrypted = true) }, + screenUp = { screenShown }, // The driver picked the radio or another source on the car: pause the phone's music // as Android Auto does, instead of letting it play on to no one. onTakenBack = { CarServices.pausePhoneMedia("the car switched to another source") }, @@ -647,6 +650,10 @@ class GearslipRunner( if (CarSettings.pipesNow) { if (!CarSettings.pipeAudio.value) log.i("this car turns Bluetooth music off, so music goes through Gearslip") openChannel(media.serviceId) + // Asked for here, on every connection. The car screen's own ask runs once per screen, + // and a screen kept from the drive before never asked again: a reconnect played + // nothing for minutes, until the driver flipped the audio setting. + CarAudio.request() } else { // Many cars switch their source to Android Auto the moment this channel opens, which // cut off music the driver chose to play over Bluetooth. Open it only if they switch. @@ -1269,6 +1276,8 @@ class GearslipRunner( projection.onSurfaceReady(surface, width, height, config.density) } SessionStatus.projecting() + screenShown = true + audioLink?.mayAskForSpeakers() BluetoothAudioCheck.onProjecting() LocationCheck.onProjecting() } @@ -1422,6 +1431,8 @@ class GearslipRunner( // Give the car the channels' open responses before it hears the request again. if (open != null || toldBluetooth) Thread.sleep(1_000) if (running && !videoStarted) requestProjectedFocus(withDisplay = true) + // A car keeping its own screen may still play the music: stop holding it back. + if (running && !screenShown) audioLink?.mayAskForSpeakers(screenOrNot = true) }, "gearslip-focus-fallback").apply { isDaemon = true }.start() } diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/audio/AudioLink.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/audio/AudioLink.kt index d59687a..6f61c1e 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/audio/AudioLink.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/audio/AudioLink.kt @@ -32,6 +32,11 @@ class AudioLink( * through [askForSpeakers], and only when the music isn't already ours. */ private val asksFocus: Boolean = true, + /** + * Whether the car shows Gearslip's screen. A head unit answered LOSS within 2 ms to every ask + * that came before it did, and GAIN to every one after, so the ask waits; see [mayAskForSpeakers]. + */ + private val screenUp: () -> Boolean = { true }, private val onReady: (AudioLink) -> Unit = { CarAudio.attach(it) }, private val onClose: (AudioLink) -> Unit = { CarAudio.detach(it) }, /** The car took the sound back after giving it, as when the driver switches to the radio. */ @@ -352,7 +357,33 @@ class AudioLink( /** Silence for [ms], whole frames of this sink's format. */ private fun silence(ms: Int): ByteArray = ByteArray(sampleRate * ms / 1000 * channels * 2) + /** The capture wants to play, but the car isn't showing Gearslip yet; the ask waits for it. */ + @Volatile private var waitingForScreen = false + + /** + * The car shows Gearslip's screen now ([screenOrNot] false), or has kept its own for so long + * that the music shouldn't wait any more (true): a music start that was held goes ahead. + */ + fun mayAskForSpeakers(screenOrNot: Boolean = false) { + if (!waitingForScreen) return + if (!screenOrNot && !screenUp()) return + waitingForScreen = false + GearslipLog.i("$tag: ${if (screenOrNot) "the car is keeping its own screen" else "the car shows Gearslip"} - asking for the speakers now") + askAndStart() + } + override fun start() { + if (!ready || started) return + if (asksFocus && !focusRequested && !screenUp()) { + // Asked now, the car says LOSS at once and the music never plays: wait for the screen. + if (!waitingForScreen) GearslipLog.i("$tag: the car isn't showing Gearslip yet - holding the music until it does") + waitingForScreen = true + return + } + askAndStart() + } + + private fun askAndStart() { if (!ready || started) return if (asksFocus && !focusRequested) { focusRequested = true @@ -407,6 +438,8 @@ class AudioLink( } override fun stop() { + // A held start is dropped too: the capture stopped before the screen came. + waitingForScreen = false synchronized(startLock) { stopLocked() } } diff --git a/gearslip/src/test/java/app/seb3thehacker/gearslip/audio/AudioLinkFocusTest.kt b/gearslip/src/test/java/app/seb3thehacker/gearslip/audio/AudioLinkFocusTest.kt new file mode 100644 index 0000000..0f629a0 --- /dev/null +++ b/gearslip/src/test/java/app/seb3thehacker/gearslip/audio/AudioLinkFocusTest.kt @@ -0,0 +1,96 @@ +package app.seb3thehacker.gearslip.audio + +import app.seb3thehacker.gearslip.Protobuf +import app.seb3thehacker.gearslip.ServiceDiscovery +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.util.Collections + +/** + * A head unit answered LOSS within 2 ms whenever the music asked for its speakers before it showed + * Gearslip's screen, and GAIN every time the ask came after. Gearslip took the LOSS as final, so a + * cable plugged back in quickly, with the capture still running, played nothing until the driver + * flipped the audio setting. The music should hold its ask until the screen is up. + */ +class AudioLinkFocusTest { + + private val sink = ServiceDiscovery.AudioService( + serviceId = 4, + streamType = 3, + codecType = ServiceDiscovery.CODEC_PCM, + configs = listOf(ServiceDiscovery.AudioConfig(48_000, 16, 2)), + ) + + /** A media link whose car has set the sink up, and the control and channel messages it sent. */ + private fun readyLink(screenUp: () -> Boolean): Triple, MutableList> { + val control = Collections.synchronizedList(mutableListOf()) + val channel = Collections.synchronizedList(mutableListOf()) + val link = AudioLink( + sink, + sendOnChannel = { id, _ -> channel += id }, + sendControl = { id, _ -> control += id }, + screenUp = screenUp, + onReady = {}, + onClose = {}, + ) + link.onMessage( + MSG_CONFIG, + Protobuf.varintField(1, 2) + Protobuf.varintField(2, 4) + Protobuf.varintField(3, 0), + ) + return Triple(link, control, channel) + } + + @Test + fun beforeTheScreenIsUpTheMusicDoesNotAskForTheSpeakers() { + val (link, control, channel) = readyLink(screenUp = { false }) + link.start() + assertTrue("no focus request yet: $control", AudioLink.MSG_FOCUS_REQUEST !in control) + assertTrue("no Start yet: $channel", MSG_START !in channel) + assertEquals(false, link.streaming) + } + + @Test + fun onceTheScreenIsUpTheHeldAskGoesOut() { + var up = false + val (link, control, channel) = readyLink(screenUp = { up }) + link.start() + up = true + link.mayAskForSpeakers() + assertEquals(listOf(AudioLink.MSG_FOCUS_REQUEST), control) + assertTrue("Start sent: $channel", MSG_START in channel) + assertTrue(link.streaming) + link.stop() + } + + @Test + fun aCarKeepingItsScreenStillGetsAskedWhenTheWaitIsOver() { + // A car that keeps its own screen never shows Gearslip's; the runner gives up waiting + // and lets the music ask anyway, as it always did. + val (link, control, _) = readyLink(screenUp = { false }) + link.start() + link.mayAskForSpeakers(screenOrNot = true) + assertEquals(listOf(AudioLink.MSG_FOCUS_REQUEST), control) + link.stop() + } + + @Test + fun withTheScreenAlreadyUpTheMusicAsksAtOnce() { + val (link, control, _) = readyLink(screenUp = { true }) + link.start() + assertEquals(listOf(AudioLink.MSG_FOCUS_REQUEST), control) + link.stop() + } + + @Test + fun nothingHeldMeansNothingToSend() { + val (link, control, _) = readyLink(screenUp = { true }) + link.mayAskForSpeakers() + assertTrue("never started, so nothing asked: $control", control.isEmpty()) + } + + private companion object { + const val MSG_START = 32769 + const val MSG_CONFIG = 32771 + } +} From 9549cf0a65bc32eff6be4168f5ba7d20280455d5 Mon Sep 17 00:00:00 2001 From: Jim Havrilla <6568964+jimhavrilla@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:41:19 -0500 Subject: [PATCH 4/4] Gearslip says goodbye when it ends a cable connection, and ends a car's stale one A head unit kept sending into a connection Gearslip had closed without telling it. Connect with cable then opened a new one that never got its VersionRequest, and only pulling the cable got the car to start over. - Gearslip ends a session the way Android Auto does: ByeByeRequest, then a short wait for the car's ByeByeResponse. Not when the cable is unplugged. - A car sending encrypted frames before this connection has said hello is told, in the clear and at most three times, that the earlier connection is over. This connection then waits for the car to start again. - Every session Gearslip ends itself logs why: Disconnect pressed, a new cable connection, wireless taking over, the screen closing. Co-Authored-By: Claude Opus 5.5 --- .../gearslip/GearslipActivity.kt | 24 ++--- .../seb3thehacker/gearslip/GearslipRunner.kt | 62 ++++++++++++- .../seb3thehacker/gearslip/StaleCarTest.kt | 88 +++++++++++++++++++ 3 files changed, 160 insertions(+), 14 deletions(-) create mode 100644 gearslip/src/test/java/app/seb3thehacker/gearslip/StaleCarTest.kt diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt index 55aaaab..5637cd1 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt @@ -118,7 +118,7 @@ class GearslipActivity : ComponentActivity(), Projection { GearslipLog.w("accessory detached") deferredAccessory = null // A wireless session has no accessory to lose; leave it running. - if (wirelessSocket == null) closeAccessory() + if (wirelessSocket == null) closeAccessory("the cable was unplugged", goodbye = false) } } } @@ -206,7 +206,7 @@ class GearslipActivity : ComponentActivity(), Projection { setContent { GearslipTheme { - GearslipApp(onDisconnect = { closeAccessory() }, onRequestCallScreening = ::requestCallScreeningRole) + GearslipApp(onDisconnect = { closeAccessory("Disconnect was pressed on the phone") }, onRequestCallScreening = ::requestCallScreeningRole) val offer by offerBluetooth.collectAsState() if (offer) { fun close() { @@ -297,7 +297,7 @@ class GearslipActivity : ComponentActivity(), Projection { CarAudio.onConsentRequested = null CarAudio.release() PhoneMirror.requestStop() - closeAccessory() + closeAccessory("Gearslip's screen on the phone closed") GearslipLog.flush() } @@ -506,7 +506,7 @@ class GearslipActivity : ComponentActivity(), Projection { GearslipLog.i("auto-connect: a session is already running") return } - if (runner != null) closeAccessory(stopWireless = false) + if (runner != null) closeAccessory("a wireless connection takes over", stopWireless = false) if (checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED) { GearslipLog.w("auto-connect: needs the Nearby devices permission") return @@ -531,7 +531,7 @@ class GearslipActivity : ComponentActivity(), Projection { // The cable is here, so a cable-first wait for it is over. cableWait?.let(mainHandler::removeCallbacks) cableWait = null - closeAccessory() + closeAccessory("a new cable connection replaces it") describe(accessory) val manager = getSystemService(UsbManager::class.java) @@ -563,7 +563,7 @@ class GearslipActivity : ComponentActivity(), Projection { /** A wireless session: the same runner, on the socket [WirelessLink] opened to the car. */ private fun startWireless(socket: java.net.Socket) { - closeAccessory(stopWireless = false) + closeAccessory("a wireless connection replaces it", stopWireless = false) if (!AppSettings.gearslipEnabled(this)) { GearslipLog.i("wireless: Gearslip is switched off - not connecting") runCatching { socket.close() } @@ -604,11 +604,13 @@ class GearslipActivity : ComponentActivity(), Projection { GearslipLog.i(" version=${accessory.version} description=${accessory.description}") } - private fun closeAccessory() = closeAccessory(stopWireless = true) - - /** Ends the session, wired or wireless. [stopWireless] also drops the car's Bluetooth and Wi-Fi. */ - private fun closeAccessory(stopWireless: Boolean) { - runner?.stop() + /** + * Ends the session, wired or wireless, for [why], which goes to the log. [goodbye] tells a car + * still in the session first (see [GearslipRunner.stop]); [stopWireless] also drops the car's + * Bluetooth and Wi-Fi. + */ + private fun closeAccessory(why: String, goodbye: Boolean = true, stopWireless: Boolean = true) { + runner?.stop(why, goodbye) SessionReport.print() runCatching { descriptor?.close() } descriptor = null diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt index 35cd52e..718fcc0 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt @@ -21,6 +21,7 @@ import java.io.IOException import app.seb3thehacker.gearslip.protocol.InputProtocol import java.io.InputStream import java.io.OutputStream +import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.FutureTask import java.util.concurrent.RejectedExecutionException @@ -193,7 +194,18 @@ class GearslipRunner( } } - fun stop() { + /** + * Ends the session from the phone's side, for [why]. With [goodbye], a car in the middle of a + * session is told first, as Android Auto does: a head unit that wasn't kept on sending into + * the next connection, which then never got its VersionRequest until the cable was pulled. + * No goodbye when the cable is already gone: there is nobody to tell. + */ + fun stop(why: String = "Gearslip ended it", goodbye: Boolean = true) { + if (goodbye && running && !stopped && (state == State.DONE || state == State.WAIT_SDR)) { + sayGoodbye(why) + } else { + log.i("ending the session: $why") + } stopped = true running = false writer.shutdownNow() @@ -230,12 +242,49 @@ class GearslipRunner( SessionStatus.disconnected() } + /** Set while [sayGoodbye] waits for the car's ByeByeResponse. */ + @Volatile private var goodbyeAnswer: CountDownLatch? = null + + /** ByeByeRequest(USER_SELECTION), then a short wait for the car to close its side. */ + private fun sayGoodbye(why: String) { + val answer = CountDownLatch(1) + goodbyeAnswer = answer + log.i("-> ByeByeRequest(USER_SELECTION): $why") + send(MSG_BYEBYE_REQUEST, Protobuf.varintField(1, BYEBYE_USER_SELECTION), encrypted = true) + val answered = answer.await(GOODBYE_WAIT_MS, TimeUnit.MILLISECONDS) + goodbyeAnswer = null + log.i(if (answered) "<- ByeByeResponse: the car closed its side" else "no ByeByeResponse after ${GOODBYE_WAIT_MS}ms - closing anyway") + } + + /** Frames from a connection before this one, and the goodbyes sent to end it. */ + private var staleFrames = 0 + private var staleGoodbyes = 0 + private var lastStaleGoodbyeAt = 0L + + /** + * Encrypted frames before this connection has said hello: the car is still in an older one, + * closed on the phone without telling it. Its keys are gone, so the car is told in the clear + * that it's over, a few times at most, and this connection waits for the VersionRequest the + * car sends when it starts again. Unplugging did the same, and an app can't unplug the cable. + */ + private fun onStaleFrame() { + staleFrames++ + if (staleFrames == 1) log.w("the car is still talking in an earlier connection - telling it that one is over") + val now = System.currentTimeMillis() + if (staleGoodbyes >= MAX_STALE_GOODBYES || now - lastStaleGoodbyeAt < STALE_GOODBYE_GAP_MS) return + staleGoodbyes++ + lastStaleGoodbyeAt = now + send(MSG_BYEBYE_REQUEST, Protobuf.varintField(1, BYEBYE_USER_SELECTION), encrypted = false) + log.i("-> ByeByeRequest(USER_SELECTION) in the clear, for the earlier connection ($staleGoodbyes of $MAX_STALE_GOODBYES, $staleFrames old frames so far)") + } + private fun handleFrame(frame: Frames.Frame) { // A rejected handshake cannot consume later messages as if authentication succeeded. if (authenticationFailed || stopped || !running) return val payload = if (frame.encrypted) { if (!tls.handshakeComplete) { - log.w("encrypted frame arrived before the handshake finished - ignoring") + if (state == State.WAIT_VERSION) onStaleFrame() + else log.w("encrypted frame arrived before the handshake finished - ignoring") return } tls.decrypt(frame.payload) @@ -301,7 +350,7 @@ class GearslipRunner( return } if (messageId !in setOf(MSG_VERSION_REQUEST, MSG_ENCAPSULATED_SSL, MSG_AUTH_COMPLETE, - MSG_BYEBYE_REQUEST, MSG_UNEXPECTED_MESSAGE, MSG_FRAMING_ERROR) && + MSG_BYEBYE_REQUEST, MSG_BYEBYE_RESPONSE, MSG_UNEXPECTED_MESSAGE, MSG_FRAMING_ERROR) && (!frame.encrypted || state != State.DONE && state != State.WAIT_SDR)) return when (messageId) { @@ -312,6 +361,7 @@ class GearslipRunner( MSG_PING_REQUEST -> onPingRequest(body) MSG_PING_RESPONSE -> onPingResponse() MSG_BYEBYE_REQUEST -> onByeByeRequest(body) + MSG_BYEBYE_RESPONSE -> goodbyeAnswer?.countDown() ?: log.i("<- ByeByeResponse") MSG_UNEXPECTED_MESSAGE, MSG_FRAMING_ERROR -> onProtocolError(messageId) AudioLink.MSG_FOCUS_RESPONSE -> { // One answer for both sinks: it is the directions' while they wait on one. @@ -1720,6 +1770,12 @@ class GearslipRunner( private const val PING_LOG_EVERY = 60 const val MSG_BYEBYE_REQUEST = 15 const val MSG_BYEBYE_RESPONSE = 16 + const val BYEBYE_USER_SELECTION = 1L + /** How long a goodbye waits for the car's answer; the phone's screen waits with it. */ + const val GOODBYE_WAIT_MS = 400L + /** Goodbyes to a car stuck in an earlier connection, and the gap between them. */ + const val MAX_STALE_GOODBYES = 3 + const val STALE_GOODBYE_GAP_MS = 3_000L const val MSG_VOICE_SESSION_NOTIFICATION = 17 const val MSG_UNEXPECTED_MESSAGE = 255 const val MSG_FRAMING_ERROR = 65535 diff --git a/gearslip/src/test/java/app/seb3thehacker/gearslip/StaleCarTest.kt b/gearslip/src/test/java/app/seb3thehacker/gearslip/StaleCarTest.kt new file mode 100644 index 0000000..10bff3a --- /dev/null +++ b/gearslip/src/test/java/app/seb3thehacker/gearslip/StaleCarTest.kt @@ -0,0 +1,88 @@ +package app.seb3thehacker.gearslip + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A head unit kept sending encrypted frames from a connection Gearslip had closed without telling + * it, and the new connection waited for a VersionRequest that never came, until the cable was + * pulled. Gearslip should tell the car the old connection is over, once and in the clear, as the + * old one's keys are gone, and carry on as normal when the car starts again. + */ +class StaleCarTest { + + private fun message(id: Int, body: ByteArray = byteArrayOf(), encrypted: Boolean = false) = Frames.build( + Frames.CHANNEL_CONTROL, encrypted, byteArrayOf((id ushr 8).toByte(), id.toByte()) + body, + ) + + /** Frames from the old connection: encrypted, and meaningless to a new one. */ + private fun stale(count: Int) = (1..count).fold(byteArrayOf()) { all, i -> + all + Frames.build(3, true, ByteArray(32) { (it + i).toByte() }) + } + + private val version = message(1, byteArrayOf(0, 1, 0, 3)) + + private fun identity(): CertProvider.Identity { + val generated = SelfSignedCert.generate() + return CertProvider.Identity(generated.keyStore, generated.certificate, SelfSignedCert.PASSWORD, "test") + } + + /** Runs a connection on [input] and returns the messages Gearslip sent, as (id, encrypted, body). */ + private fun sent(input: ByteArray, also: (GearslipRunner) -> Unit = {}): List> { + val output = ByteArrayOutputStream() + val runner = GearslipRunner(ByteArrayInputStream(input), output, ::identity) + // Let what was sent reach the output before the connection closes. + GearslipRunner::class.java.getDeclaredField("drainWriterOnExit").apply { isAccessible = true }.setBoolean(runner, true) + also(runner) + runner.run() + val parser = Frames.Parser() + parser.append(output.toByteArray(), output.size()) + return generateSequence { parser.next() }.map { f -> + val id = ((f.payload[0].toInt() and 0xFF) shl 8) or (f.payload[1].toInt() and 0xFF) + Triple(id, f.encrypted, f.payload.copyOfRange(2, f.payload.size)) + }.toList() + } + + @Test + fun aCarStillInTheOldConnectionIsToldItIsOver() { + val out = sent(stale(5)) + val bye = out.single { it.first == MSG_BYEBYE_REQUEST } + assertFalse("sent in the clear: the old connection's keys are gone", bye.second) + assertEquals(1L, Protobuf.readInt32Field(bye.third, 1)?.toLong()) + } + + @Test + fun manyOldFramesGetOneGoodbyeNotOneEach() { + val out = sent(stale(200)) + assertEquals(1, out.count { it.first == MSG_BYEBYE_REQUEST }) + } + + @Test + fun theCarStartingOverAfterTheGoodbyeConnectsAsNormal() { + val out = sent(stale(5) + version) + assertTrue("goodbye first: $out", out.first().first == MSG_BYEBYE_REQUEST) + assertTrue("then the version answer: ${out.map { it.first }}", out.any { it.first == MSG_VERSION_RESPONSE }) + } + + @Test + fun aFreshCarGetsNoGoodbye() { + val out = sent(version) + assertTrue(out.none { it.first == MSG_BYEBYE_REQUEST }) + } + + @Test + fun endingAConnectionTheCarNeverStartedSaysNoGoodbye() { + // Before the secure session is up there is nothing for the car to close. + val out = sent(byteArrayOf()) { it.stop("a test ended it") } + assertTrue(out.none { it.first == MSG_BYEBYE_REQUEST }) + } + + private companion object { + const val MSG_VERSION_RESPONSE = 2 + const val MSG_BYEBYE_REQUEST = 15 + } +}