Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
## [4.7.3](https://github.com/sds100/KeyMapper/releases/tag/v4.7.3)

#### TO BE RELEASED

## Fixed

- #2237 Expert Mode can be set up and auto started on Android TV without pairing wireless debugging. If network ADB (port 5555) is turned on, Key Mapper uses it and the TV asks once whether to allow debugging.
- Expert Mode auto starts after booting if the storage takes a while to become available. It used to give up straight away.

## [4.7.2](https://github.com/sds100/KeyMapper/releases/tag/v4.7.2)

#### 25 November 2026
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,15 @@ class SystemBridgeAutoStarter @Inject constructor(
*/
private var canQuickRetry: Boolean = false

companion object {
/**
* The shared storage that the starter files are copied to can still be unavailable
* just after booting. It usually becomes available within a minute.
*/
private const val STORAGE_AVAILABLE_ATTEMPTS = 6
private const val STORAGE_AVAILABLE_RETRY_DELAY_MS = 10000L
}

/**
* This must only be called once in the application lifecycle
*/
Expand Down Expand Up @@ -305,6 +314,26 @@ class SystemBridgeAutoStarter @Inject constructor(
}
}

/**
* Auto starting usually happens just after booting, when the shared storage may not be
* available yet. Nothing triggers auto starting again when it becomes available so wait
* for it here.
*/
private suspend fun awaitStorageAvailable(): Boolean {
repeat(STORAGE_AVAILABLE_ATTEMPTS) { attempt ->
if (attempt > 0) {
Timber.i("Storage is unavailable. Waiting before auto starting the system bridge.")
delay(STORAGE_AVAILABLE_RETRY_DELAY_MS)
}

if (connectionManager.canStartSystemBridge()) {
return true
}
}

return false
}

private suspend fun autoStart(type: AutoStartType) {
if (connectionManager.isConnected()) {
Timber.i("Not auto starting with $type because already connected.")
Expand All @@ -313,7 +342,7 @@ class SystemBridgeAutoStarter @Inject constructor(

// Return before setting the auto start time, otherwise the cooldown would block
// auto starting again once the storage becomes available.
if (!connectionManager.canStartSystemBridge()) {
if (!awaitStorageAvailable()) {
Timber.w("Not auto starting with $type because the storage is unavailable.")
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,9 @@ class SystemBridgeSetupUseCaseImpl @Inject constructor(
}

@RequiresApi(Build.VERSION_CODES.R)
private fun getNextStepFlow(): Flow<SystemBridgeSetupStep> =
private fun getNextStepFlow(): Flow<SystemBridgeSetupStep> = flow {
emit(systemBridgeSetupController.isNetworkAdbAvailable())
}.flatMapLatest { isNetworkAdbAvailable ->
accessibilityServiceAdapter.state.flatMapLatest { accessibilityServiceState ->
combine(hasSamsungAutoBlocker, isSamsungAutoBlockerDismissed) {
hasAutoBlocker,
Expand Down Expand Up @@ -201,10 +203,12 @@ class SystemBridgeSetupUseCaseImpl @Inject constructor(
isDeveloperOptionsEnabled = isDeveloperOptionsEnabled,
isWifiConnected = isWifiConnected,
isWirelessDebuggingEnabled = isWirelessDebuggingEnabled,
isNetworkAdbAvailable = isNetworkAdbAvailable,
)
}
}
}
}

override val isRootGranted: Flow<Boolean> = suAdapter.isRootGranted.map { it ?: false }

Expand Down Expand Up @@ -370,6 +374,7 @@ class SystemBridgeSetupUseCaseImpl @Inject constructor(
isDeveloperOptionsEnabled: Boolean,
isWifiConnected: Boolean,
isWirelessDebuggingEnabled: Boolean,
isNetworkAdbAvailable: Boolean,
): SystemBridgeSetupStep {
return when {
accessibilityServiceState != AccessibilityServiceState.ENABLED ->
Expand All @@ -382,6 +387,10 @@ class SystemBridgeSetupUseCaseImpl @Inject constructor(

needsSamsungAutoBlockerStep -> SystemBridgeSetupStep.SAMSUNG_AUTO_BLOCKER

// Android TV can not pair wireless debugging so start with network ADB instead.
// The TV asks whether to allow debugging the first time it connects.
isNetworkAdbAvailable -> SystemBridgeSetupStep.START_SERVICE

// Wireless debugging can not be enabled without developer options being enabled.
// Check both because the developer options setting can be redacted. See #2289.
!isDeveloperOptionsEnabled && !isWirelessDebuggingEnabled ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,20 @@ class SystemBridgeAutoStarterTest {
)
}

@Test
fun `auto start once the storage becomes available after booting`() = runTest(testDispatcher) {
advanceTimeBy(1_000_000L)
whenever(mockConnectionManager.canStartSystemBridge()).thenReturn(false, false, true)
isRootGrantedFlow.value = true
fakePreferences.set(Keys.isSystemBridgeEmergencyKilled, false)
fakePreferences.set(Keys.isSystemBridgeUsed, true)

systemBridgeAutoStarter.init()
advanceUntilIdle()

verify(mockConnectionManager).startWithRoot()
}

@Test
fun `auto start with root`() = runTest(testDispatcher) {
advanceTimeBy(1_000_000L)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
Expand All @@ -50,7 +51,9 @@ class SystemBridgeSetupUseCaseTest {
fun init() {
fakePreferences = FakePreferenceRepository()
mockSuAdapter = mock()
mockSystemBridgeSetupController = mock()
mockSystemBridgeSetupController = mock {
onBlocking { isNetworkAdbAvailable() } doReturn false
}
mockSystemBridgeConnectionManager = mock()
mockShizukuAdapter = mock()
mockPermissionAdapter = mock()
Expand Down Expand Up @@ -218,6 +221,18 @@ class SystemBridgeSetupUseCaseTest {
assertThat(useCase.nextSetupStep.first(), `is`(SystemBridgeSetupStep.WIFI_NETWORK))
}

@Test
fun `next step is START_SERVICE when network ADB is available on Android TV`() = runTest {
whenever(mockSystemBridgeSetupController.isNetworkAdbAvailable()).thenReturn(true)

val useCase = createUseCaseAfterLocalNetworkStep(
isDeveloperOptionsEnabled = false,
isWirelessDebuggingEnabled = false,
)

assertThat(useCase.nextSetupStep.first(), `is`(SystemBridgeSetupStep.START_SERVICE))
}

/**
* Create a use case where every step before developer options is complete and WiFi
* is not connected.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
package io.github.sds100.keymapper.sysbridge.adb

import android.app.UiModeManager
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.preference.PreferenceManager
import androidx.annotation.RequiresApi
import androidx.core.content.getSystemService
import dagger.hilt.android.qualifiers.ApplicationContext
import io.github.sds100.keymapper.common.utils.KMError
import io.github.sds100.keymapper.common.utils.KMResult
import io.github.sds100.keymapper.common.utils.Success
import io.github.sds100.keymapper.common.utils.success
import io.github.sds100.keymapper.common.utils.then
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.Dispatchers
Expand All @@ -24,6 +30,44 @@ class AdbManagerImpl @Inject constructor(@ApplicationContext private val ctx: Co
AdbManager {
companion object {
private const val LOCALHOST = "127.0.0.1"

/**
* The port used by network ADB ("adb tcpip 5555"). Some Android TV devices keep it
* turned on after rebooting, such as the Xiaomi TV Box S (3rd gen).
*/
private const val NETWORK_ADB_PORT = 5555
private const val NETWORK_ADB_CONNECT_TIMEOUT_MS = 500
}

private val isTvDevice: Boolean by lazy {
ctx.getSystemService<UiModeManager>()?.currentModeType ==
Configuration.UI_MODE_TYPE_TELEVISION
}

/**
* Wireless debugging can not be paired on Android TV because the pairing code
* is only accepted while the pairing screen is open, and there is no heads up notification
* to type it into. Network ADB does not need pairing. The first connection shows the
* "Allow debugging?" prompt on the TV instead.
*/
override suspend fun isNetworkAdbAvailable(): Boolean {
if (!isTvDevice) {
return false
}

return withContext(Dispatchers.IO) {
try {
Socket().use { socket ->
socket.connect(
InetSocketAddress(LOCALHOST, NETWORK_ADB_PORT),
NETWORK_ADB_CONNECT_TIMEOUT_MS,
)
}
true
} catch (_: IOException) {
false
}
}
}

private val commandMutex: Mutex = Mutex()
Expand All @@ -37,7 +81,11 @@ class AdbManagerImpl @Inject constructor(@ApplicationContext private val ctx: Co

val result = withContext(Dispatchers.IO) {
return@withContext commandMutex.withLock {
val port = adbConnectMdns.discoverPort()
val port = if (isNetworkAdbAvailable()) {
NETWORK_ADB_PORT
} else {
adbConnectMdns.discoverPort()
}

if (port == null || port == -1) {
return@withLock AdbError.ServerNotFound
Expand Down Expand Up @@ -124,4 +172,10 @@ interface AdbManager {

@RequiresApi(Build.VERSION_CODES.R)
suspend fun pair(code: String): KMResult<Unit>

/**
* Whether ADB commands are run over network ADB instead of wireless debugging. This
* is only used on Android TV.
*/
suspend fun isNetworkAdbAvailable(): Boolean
}
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,14 @@ class SystemBridgeSetupControllerImpl @Inject constructor(
// setting so it always reads as disabled. See issue #2289.
withTimeoutOrNull(5000L.milliseconds) { isDeveloperOptionsEnabled.first { it } }

if (isAdbPaired()) {
if (adbManager.isNetworkAdbAvailable()) {
// Android TV uses network ADB so wireless debugging is not needed.
if (isAdbPaired()) {
connectionManager.startWithAdb()
} else {
Timber.e("Autostart failed. Network ADB connection was not allowed.")
}
} else if (isAdbPaired()) {
// This is IMPORTANT. First turn on ADB before enabling wireless debugging because
// turning on developer options just before can cause the Shell to be killed once
// the system bridge is started.
Expand Down Expand Up @@ -322,6 +329,10 @@ class SystemBridgeSetupControllerImpl @Inject constructor(
Timber.w("Failed to enable USB debugging over ADB.")
}

override suspend fun isNetworkAdbAvailable(): Boolean {
return adbManager.isNetworkAdbAvailable()
}

@RequiresApi(Build.VERSION_CODES.R)
override suspend fun isAdbPaired(): Boolean {
// Sometimes multiple calls to this function can happen in a short space of time
Expand All @@ -332,8 +343,11 @@ class SystemBridgeSetupControllerImpl @Inject constructor(

Timber.d("Launching isAdbPaired job")
isAdbPairedJob = coroutineScope.launch {
Timber.d("Enabling wireless ADB")
SettingsUtils.putGlobalSetting(ctx, ADB_WIRELESS_SETTING, 1)
// Network ADB on Android TV does not need wireless debugging.
if (!adbManager.isNetworkAdbAvailable()) {
Timber.d("Enabling wireless ADB")
SettingsUtils.putGlobalSetting(ctx, ADB_WIRELESS_SETTING, 1)
}

// Try running a command to see if the pairing is working correctly.
// This will execute the "exit" command in the shell so it immediately closes
Expand Down Expand Up @@ -504,6 +518,12 @@ interface SystemBridgeSetupController {
@RequiresApi(Build.VERSION_CODES.R)
suspend fun isAdbPaired(): Boolean

/**
* Whether the system bridge is started over network ADB instead of wireless debugging.
* This is only used on Android TV, which can not pair wireless debugging.
*/
suspend fun isNetworkAdbAvailable(): Boolean

@RequiresApi(Build.VERSION_CODES.R)
suspend fun pairWirelessAdb(code: String): KMResult<Unit>

Expand Down