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 <noreply@anthropic.com>
This commit is contained in:
Jim HavrillaandClaude Opus 5.5 committed 2026-11-16 20:30:18 -05:00
1 parent 4e3f8e6657
commit 962c083fe6
8 files changed
+316 -2

No files matched your search

@@ -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()
}
}
@@ -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()
}
@@ -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
@@ -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)) } },
)
}
}
@@ -388,6 +388,7 @@ private fun StatusCard(status: SessionStatus.Snapshot) {
if (!live) {
Spacer(Modifier.height(20.dp))
WirelessButton()
CableButton()
}
}
}
@@ -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
@@ -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()
}
}
}
+16
View File
@@ -419,6 +419,22 @@
<string name="wireless_wifi_off_body">The car connects over its own Wi-Fi, so turn on Wi-Fi to connect wirelessly.</string>
<string name="wireless_wifi_turn_on">Turn on Wi-Fi</string>
<!-- Cable, and which link comes first -->
<string name="cable_connect">Connect with cable</string>
<string name="cable_none_title">No car on the cable</string>
<string name="cable_none_body">Plug the phone into the car\'s USB port with a data cable, then try again.</string>
<string name="settings_cable">Connect over cable</string>
<string name="settings_cable_on">Gearslip answers the car\'s USB connection</string>
<string name="settings_cable_off">Off: the cable only charges, or Android Auto takes it</string>
<string name="settings_wireless_auto">Connect wirelessly on its own</string>
<string name="settings_wireless_auto_on">Starts when a car you\'ve connected to comes up on Bluetooth</string>
<string name="settings_wireless_auto_off">Off: the car\'s Bluetooth is left alone until you tap Connect wirelessly</string>
<string name="settings_order">Try first</string>
<string name="settings_order_cable">Cable. Gearslip waits a few seconds for one before going wireless.</string>
<string name="settings_order_wireless">Wireless. A cable plugged in later doesn\'t take over, but steps in if wireless fails.</string>
<string name="settings_order_cable_short">Cable</string>
<string name="settings_order_wireless_short">Wireless</string>
<!-- Voice models -->
<string name="voice_live_title">Voice: live words</string>
<string name="voice_final_title">Voice: final words</string>