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 726e6ba..dfcbc90 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()) @@ -111,8 +117,32 @@ 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() + if (wirelessSocket == null) closeAccessory("the cable was unplugged", goodbye = false) + } + } + } + + /** 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") } } } @@ -154,6 +184,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 @@ -176,7 +208,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() { @@ -213,6 +245,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) } @@ -254,15 +287,20 @@ 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 CarAudio.onConsentRequested = null CarAudio.release() PhoneMirror.requestStop() - closeAccessory() + closeAccessory("Gearslip's screen on the phone closed") GearslipLog.flush() } @@ -364,11 +402,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 @@ -376,6 +467,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 @@ -387,7 +509,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 @@ -409,7 +531,10 @@ 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. - closeAccessory() + // The cable is here, so a cable-first wait for it is over. + cableWait?.let(mainHandler::removeCallbacks) + cableWait = null + closeAccessory("a new cable connection replaces it") describe(accessory) val manager = getSystemService(UsbManager::class.java) @@ -417,6 +542,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 @@ -436,7 +566,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() } @@ -477,11 +607,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 56c07ac..e3daeb5 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt @@ -23,6 +23,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 @@ -89,6 +90,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 @@ -211,7 +214,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() @@ -248,12 +262,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) @@ -319,7 +370,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) { @@ -330,6 +381,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. @@ -677,6 +729,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") }, @@ -690,6 +743,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. @@ -1382,6 +1439,8 @@ class GearslipRunner( projection.onSurfaceReady(surface, width, height, config.density, videoFrameRate) } SessionStatus.projecting() + screenShown = true + audioLink?.mayAskForSpeakers() BluetoothAudioCheck.onProjecting() LocationCheck.onProjecting() } @@ -1553,6 +1612,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() } @@ -1856,6 +1917,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/main/java/app/seb3thehacker/gearslip/audio/AudioLink.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/audio/AudioLink.kt index 6e186d1..15de186 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. */ @@ -387,7 +392,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 @@ -445,6 +476,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/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 44fabf8..caf2648 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 3549d1f..567fc92 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/ui/SettingsScreen.kt @@ -240,6 +240,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( @@ -280,6 +281,76 @@ private fun ConnectionSection() { } } +/** + * 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() { + 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)) } + 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), + ) + links.forEachIndexed { index, isCable -> + val on = if (isCable) cable else wireless + SettingsRow( + 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( + 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( + "${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) + } + }, + ) + } +} + /** * 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 afa5401..e1fc059 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/wireless/WirelessLink.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/wireless/WirelessLink.kt @@ -82,6 +82,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 @@ -143,7 +146,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 b2c7d19..83b4493 100644 --- a/gearslip/src/main/res/values/strings.xml +++ b/gearslip/src/main/res/values/strings.xml @@ -453,6 +453,20 @@ 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 + When the phone is plugged into the car + Off: the cable only charges, or Android Auto takes it + 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 + Gearslip tries these in order. Use the arrows to choose which comes first. + Move up + Move down + Voice: live words Voice: final words 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 + } +} 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 + } +}