Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.
Add :adb module: LAN scan, connect, live stats, safe actions
jesse-agent-362ae03779c3a66
diff --git a/README.md b/README.mdindex 46a130f..1b6dc43 100644--- a/README.md+++ b/README.md@@ -30,6 +30,7 @@ Debloating a TV can break it if done carelessly. Tellyscope is built around thes|---|---|| `:app` | The Android phone app. Kotlin, Jetpack Compose, Material 3 Expressive. Package `app.tellyscope`. || `:adb` | Pure Kotlin/JVM library on top of [Kadb](https://github.com/flyfishxu/Kadb): connecting, pairing and running commands on a TV. Unit-testable without a device. |+| `:cli` | Desktop smoke test for `:adb` against a real TV (`./gradlew :cli:run --args="stats <tv-ip>"`). Not shipped. |## Buildingdiff --git a/adb/build.gradle.kts b/adb/build.gradle.ktsindex f73078e..de79636 100644--- a/adb/build.gradle.kts+++ b/adb/build.gradle.kts@@ -21,5 +21,9 @@ kotlin {dependencies {api(libs.kadb)+ api(libs.kadb.mdns)+ api(libs.kotlinx.coroutines.core)testImplementation(libs.junit)+ testImplementation(libs.kotlin.test.junit)+ testImplementation(libs.kotlinx.coroutines.test)}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt b/adb/src/main/kotlin/app/tellyscope/adb/Actions.ktnew file mode 100644index 0000000..1494ecf--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt@@ -0,0 +1,64 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/**+ * The only changes Tellyscope makes. There is no uninstall, by design. Undo for [STOP] is+ * [OPEN] ("open again"); a real undo isn't possible.+ */+enum class Action { STOP, DISABLE, ENABLE, OPEN }++sealed interface ActionResult {+ data class Done(val undo: Action?) : ActionResult+ data class Refused(val reason: ProtectedReason) : ActionResult+ data class Failed(val output: String) : ActionResult+}++class Actions(private val shell: AdbShell) {++ suspend fun run(action: Action, pkg: String): ActionResult {+ require(PACKAGE.matches(pkg)) { "not a package name: $pkg" } // it goes into a shell line+ if (action != Action.ENABLE && action != Action.OPEN) {+ Protected.reason(pkg, homePackages())?.let { return ActionResult.Refused(it) }+ }+ return when (action) {+ Action.STOP -> exec("am force-stop $pkg", Action.OPEN)+ Action.DISABLE -> exec("pm disable-user --user 0 $pkg", Action.ENABLE) { "disabled-user" in it }+ Action.ENABLE -> exec("pm enable --user 0 $pkg", Action.DISABLE) { "enabled" in it }+ Action.OPEN -> open(pkg)+ }+ }++ /**+ * Launchers to protect: the default one, or every installed launcher when there's no default+ * (then resolve-activity answers with the system chooser, package `android`).+ */+ suspend fun homePackages(): Set<String> {+ val current = packagesIn(shell.shell(Commands.HOME_ACTIVITY).output) - "android"+ return current.ifEmpty { packagesIn(shell.shell(Commands.HOME_ACTIVITIES).output) - "android" }+ }++ private fun packagesIn(brief: String): Set<String> =+ brief.lineSequence().map(String::trim).filter { '/' in it && ' ' !in it }.map { it.substringBefore('/') }.toSet()++ /** TV apps register under LEANBACK_LAUNCHER only; phone-style apps under LAUNCHER. Try both. */+ private suspend fun open(pkg: String): ActionResult {+ var last = ""+ for (category in listOf("android.intent.category.LEANBACK_LAUNCHER", "android.intent.category.LAUNCHER")) {+ val r = shell.shell("monkey -p $pkg -c $category 1 2>&1")+ if (r.exitCode == 0 && "No activities found" !in r.output && "aborted" !in r.output) {+ return ActionResult.Done(undo = null)+ }+ last = r.output+ }+ return ActionResult.Failed(last.trim())+ }++ private suspend fun exec(command: String, undo: Action, ok: (String) -> Boolean = { true }): ActionResult {+ val r = shell.shell("$command 2>&1")+ return if (r.exitCode == 0 && ok(r.output)) ActionResult.Done(undo) else ActionResult.Failed(r.output.trim())+ }++ private companion object {+ val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+|android")+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.ktnew file mode 100644index 0000000..0552d04--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt@@ -0,0 +1,13 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/** The one thing collectors and actions need from a connection. Faked in tests. */+fun interface AdbShell {+ /** Runs [command] on the device and returns stdout. Throws [java.io.IOException] if the link is gone. */+ suspend fun shell(command: String): ShellResult+}++data class ShellResult(val output: String, val exitCode: Int)++/** An open connection to one device. */+interface AdbSession : AdbShell, AutoCloseablediff --git a/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt b/adb/src/main/kotlin/app/tellyscope/adb/Commands.ktnew file mode 100644index 0000000..bbe8158--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt@@ -0,0 +1,33 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/**+ * Shell snippets, batched so one tier costs one ADB round trip. Sections are split on [SEP].+ */+internal object Commands {+ const val SEP = "@@tellyscope@@"++ const val THERMAL =+ "for z in /sys/class/thermal/thermal_zone*; do echo \"$(cat \$z/type 2>/dev/null)=$(cat \$z/temp 2>/dev/null)\"; done"++ /** Every 2 s: CPU counters and memory. */+ val FAST = listOf("cat /proc/stat", "cat /proc/meminfo").batch()++ /** Every 60 s and on open: identity, storage, uptime, temperature. */+ val SLOW = listOf(+ "getprop",+ "df -k /data",+ "cat /proc/uptime",+ THERMAL,+ ).batch()++ const val PROCESSES = "top -b -n 1 -o PID,USER,RES,%CPU,NAME"+ const val PACKAGES = "pm list packages -U"+ const val HOME_ACTIVITY = "cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME"+ const val HOME_ACTIVITIES = "cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME"++ private fun List<String>.batch() = joinToString("; echo $SEP; ") { "$it 2>/dev/null" }++ fun split(output: String, expected: Int): List<String> =+ output.split("$SEP\n", SEP).let { parts -> List(expected) { parts.getOrElse(it) { "" } } }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.ktnew file mode 100644index 0000000..e19cdf6--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt@@ -0,0 +1,100 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import com.flyfishxu.kadb.Kadb+import com.flyfishxu.kadb.cert.KadbCert+import com.flyfishxu.kadb.cert.KadbCertPolicy+import com.flyfishxu.kadb.cert.OkioFilePrivateKeyStore+import com.flyfishxu.kadb.exception.AdbPairAuthException+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runInterruptible+import okio.Path.Companion.toPath+import java.io.File+import java.io.IOException+import java.io.InterruptedIOException+import java.net.InetSocketAddress+import java.net.Socket+import java.nio.channels.InterruptedByTimeoutException++sealed interface ConnectResult {+ class Online(val session: AdbSession) : ConnectResult+ /** Port answered but the TV never accepted our key within the wait. */+ data object NotAllowed : ConnectResult+ /** Wireless debugging port that doesn't know our key yet: pair with the 6-digit code first. */+ data object NeedsPairing : ConnectResult+ data class Unreachable(val reason: String) : ConnectResult+}++/**+ * Opens ADB connections with one persisted host key, so the TV's "always allow" survives restarts.+ * Call [init] once per process before anything else.+ */+object Connector {+ const val ALLOW_WAIT_MS = 60_000+ private const val TCP_TIMEOUT_MS = 3_000++ fun init(keyFile: File) {+ keyFile.parentFile?.mkdirs()+ KadbCert.configure(+ store = OkioFilePrivateKeyStore(privateKeyPath = keyFile.absolutePath.toPath()),+ policy = KadbCertPolicy(),+ additionalPrivateKeysPem = emptyList(),+ )+ KadbCert.ensureReady()+ }++ /**+ * Connects to [host]:[port]. The call blocks while the Allow prompt is on the TV, up to+ * [allowWaitMs]; the UI shows WAITING for that whole time. Cancelling it closes the attempt.+ */+ suspend fun connect(host: String, port: Int, allowWaitMs: Int = ALLOW_WAIT_MS): ConnectResult {+ // Probe TCP first: a refused or silent port is "unreachable", not "not allowed".+ try {+ runInterruptible(Dispatchers.IO) { Socket().use { it.connect(InetSocketAddress(host, port), TCP_TIMEOUT_MS) } }+ } catch (e: IOException) {+ return ConnectResult.Unreachable(e.message ?: e.javaClass.simpleName)+ }+ val kadb = Kadb.create(host, port, connectTimeout = TCP_TIMEOUT_MS, socketTimeout = allowWaitMs)+ return try {+ val out = runInterruptible(Dispatchers.IO) { kadb.shell("echo ok").output }+ if (out.trim() != "ok") throw IOException("unexpected probe output")+ ConnectResult.Online(KadbSession(kadb))+ } catch (e: CancellationException) {+ kadb.close()+ throw e+ } catch (e: AdbPairAuthException) {+ kadb.close()+ ConnectResult.NeedsPairing+ } catch (e: Exception) {+ // Kadb also throws IllegalStateException on protocol surprises; never let it escape.+ kadb.close()+ // No answer times out; Deny makes adbd drop the socket. Both read as "not allowed".+ if (e.isAuthFailure()) ConnectResult.NotAllowed else ConnectResult.Unreachable(e.message ?: e.javaClass.simpleName)+ }+ }++ /** Android 11+ wireless debugging: pair once with the 6-digit code, then [connect] to the connect port. */+ suspend fun pair(host: String, pairingPort: Int, code: String) {+ require(code.length == 6 && code.all(Char::isDigit)) { "pairing code must be 6 digits" }+ Kadb.pair(host, pairingPort, code)+ }++ private fun Throwable.isAuthFailure(): Boolean =+ generateSequence(this) { it.cause }.any {+ it is java.io.EOFException || it is InterruptedIOException || it is InterruptedByTimeoutException+ }+}++internal class KadbSession(private val kadb: Kadb) : AdbSession {+ /**+ * Kadb blocks the calling thread while it waits for the reply; that wait is interruptible, so+ * cancelling one call (a closed screen, a timeout) ends only that stream, not the connection.+ */+ override suspend fun shell(command: String): ShellResult {+ val r = runInterruptible(Dispatchers.IO) { kadb.shell(command) }+ return ShellResult(r.output, r.exitCode)+ }++ override fun close() = kadb.close()+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.ktnew file mode 100644index 0000000..56c9ca8--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt@@ -0,0 +1,96 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlin.time.Duration+import kotlin.time.Duration.Companion.seconds++/**+ * One device's connection lifecycle: connect, stream stats while online, reconnect on its own+ * after the TV sleeps or drops off Wi-Fi. NOT_ALLOWED and NEEDS_PAIRING stop the loop until+ * [connect] is called again; a device that was online before keeps retrying instead, since a TV+ * waking up can stall the handshake exactly like an unanswered prompt.+ */+class DeviceLink(+ val host: String,+ val port: Int,+ private val scope: CoroutineScope,+ private val retryEvery: Duration = 5.seconds,+ private val monitorFor: (AdbShell) -> MonitorSource = { DeviceMonitor(it) },+ private val open: suspend (String, Int) -> ConnectResult = { h, p -> Connector.connect(h, p) },+) {+ private val _state = MutableStateFlow(DeviceState.FOUND)+ val state: StateFlow<DeviceState> = _state.asStateFlow()++ /** Last reading; kept while offline so the page can show it greyed out with "last seen". */+ private val _stats = MutableStateFlow<Stats?>(null)+ val stats: StateFlow<Stats?> = _stats.asStateFlow()++ @Volatile var session: AdbSession? = null+ private set+ @Volatile var lastSeenMillis: Long? = null+ private set++ private var job: Job? = null++ fun connect() {+ job?.cancel()+ job = scope.launch { loop() }+ }++ fun disconnect() {+ job?.cancel()+ job = null+ _state.value = _state.value.on(DeviceEvent.Disconnected)+ }++ private suspend fun loop() {+ _state.value = _state.value.on(DeviceEvent.Connect)+ var wasOnline = false+ while (true) {+ when (val r = open(host, port)) {+ is ConnectResult.NotAllowed -> if (!wasOnline) {+ _state.value = _state.value.on(DeviceEvent.AuthTimedOut)+ return+ }+ is ConnectResult.NeedsPairing -> {+ _state.value = _state.value.on(DeviceEvent.NeedsPairing)+ return+ }+ is ConnectResult.Unreachable -> _state.value = _state.value.on(DeviceEvent.Unreachable)+ is ConnectResult.Online -> {+ wasOnline = true+ online(r.session)+ _state.value = _state.value.on(DeviceEvent.Lost)+ }+ }+ delay(retryEvery)+ }+ }++ /** Streams stats until the link drops. The session is closed on every exit, cancellation included. */+ private suspend fun online(s: AdbSession) {+ session = s+ _state.value = _state.value.on(DeviceEvent.Authorized)+ try {+ monitorFor(s).stats().collect {+ _stats.value = it+ lastSeenMillis = System.currentTimeMillis()+ }+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ // Link dropped mid-read: the caller marks it offline and retries.+ } finally {+ session = null+ s.close()+ }+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.ktnew file mode 100644index 0000000..b92d93f--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt@@ -0,0 +1,85 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.withTimeoutOrNull+import java.io.IOException+import kotlin.time.Duration+import kotlin.time.Duration.Companion.seconds+import kotlin.time.TimeSource++/** One reading for the stat strip. Null fields mean "this TV doesn't report it". */+data class Stats(+ val cpuPercent: Double?,+ val memory: Parsers.Memory?,+ val storage: Parsers.Storage? = null,+ val uptimeSeconds: Long? = null,+ val temperatureC: Double? = null,+ val model: String? = null,+ val manufacturer: String? = null,+ val androidVersion: String? = null,+ val sdk: Int? = null,+)++/** Where [DeviceLink] gets readings from; [DeviceMonitor] in the app, a fake in tests. */+fun interface MonitorSource {+ fun stats(): Flow<Stats>+}++/**+ * Live stats on two tiers: CPU/RAM every [fast], identity/storage/uptime/temperature every [slow].+ * The first emission comes after one fast interval, since CPU % needs two samples.+ * Shell failures and reads slower than [readTimeout] throw [IOException], so the caller can mark+ * the device offline instead of waiting out the socket timeout.+ */+class DeviceMonitor(+ private val shell: AdbShell,+ private val fast: Duration = 2.seconds,+ private val slow: Duration = 60.seconds,+ private val readTimeout: Duration = 10.seconds,+) : MonitorSource {+ override fun stats(): Flow<Stats> = flow {+ var slowStats = readSlow()+ var lastSlow = TimeSource.Monotonic.markNow()+ var prevCpu = readFast().first++ while (true) {+ delay(fast)+ if (lastSlow.elapsedNow() >= slow) {+ slowStats = readSlow()+ lastSlow = TimeSource.Monotonic.markNow()+ }+ val (cpu, mem) = readFast()+ val pct = if (prevCpu != null && cpu != null) Parsers.cpuPercent(prevCpu, cpu) else null+ prevCpu = cpu+ emit(slowStats.copy(cpuPercent = pct, memory = mem))+ }+ }++ private suspend fun run(command: String): String =+ withTimeoutOrNull(readTimeout) { shell.shell(command).output }+ ?: throw IOException("no answer in $readTimeout")++ private suspend fun readFast(): Pair<Parsers.CpuTimes?, Parsers.Memory?> {+ val (stat, meminfo) = Commands.split(run(Commands.FAST), 2)+ return Parsers.cpuTimes(stat) to Parsers.memory(meminfo)+ }++ private suspend fun readSlow(): Stats {+ val (getprop, df, uptime, thermal) = Commands.split(run(Commands.SLOW), 4)+ val props = Parsers.props(getprop)+ return Stats(+ cpuPercent = null,+ memory = null,+ storage = Parsers.storage(df),+ uptimeSeconds = Parsers.uptimeSeconds(uptime),+ temperatureC = Parsers.temperatureC(thermal),+ model = props["ro.product.model"],+ manufacturer = props["ro.product.manufacturer"],+ androidVersion = props["ro.build.version.release"],+ sdk = props["ro.build.version.sdk"]?.toIntOrNull(),+ )+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceState.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceState.ktnew file mode 100644index 0000000..b63e7fb--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceState.kt@@ -0,0 +1,36 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/**+ * Connection state shown for a device. ADB reports "denied" and "not answered yet" the same way+ * (no CNXN after our key), so a device that never answers the Allow prompt is [NOT_ALLOWED], never+ * "denied".+ */+enum class DeviceState { FOUND, WAITING, ONLINE, OFFLINE, NOT_ALLOWED, NEEDS_PAIRING }++sealed interface DeviceEvent {+ /** User pressed connect, or an offline device answered on its port again. */+ data object Connect : DeviceEvent+ data object Authorized : DeviceEvent+ data object AuthTimedOut : DeviceEvent+ /** Wireless debugging port that doesn't know our key: ask for the 6-digit code. */+ data object NeedsPairing : DeviceEvent+ /** User or app closed the connection on purpose. */+ data object Disconnected : DeviceEvent+ data object Unreachable : DeviceEvent+ data object Lost : DeviceEvent+}++/** Pure transition table; anything not listed leaves the state unchanged. */+fun DeviceState.on(event: DeviceEvent): DeviceState = when (event) {+ DeviceEvent.Connect -> if (this == DeviceState.ONLINE) this else DeviceState.WAITING+ DeviceEvent.Authorized -> DeviceState.ONLINE+ DeviceEvent.AuthTimedOut -> if (this == DeviceState.ONLINE) this else DeviceState.NOT_ALLOWED+ DeviceEvent.Unreachable -> when (this) {+ DeviceState.FOUND, DeviceState.NOT_ALLOWED -> this+ else -> DeviceState.OFFLINE+ }+ DeviceEvent.Lost -> if (this == DeviceState.ONLINE) DeviceState.OFFLINE else this+ DeviceEvent.NeedsPairing -> DeviceState.NEEDS_PAIRING+ DeviceEvent.Disconnected -> DeviceState.FOUND+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/LanScanner.kt b/adb/src/main/kotlin/app/tellyscope/adb/LanScanner.ktnew file mode 100644index 0000000..6938079--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/LanScanner.kt@@ -0,0 +1,116 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import com.flyfishxu.kadb.mdns.KadbMdns+import com.flyfishxu.kadb.mdns.MdnsServiceType+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.channels.ProducerScope+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.channelFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Semaphore+import kotlinx.coroutines.sync.withPermit+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import java.net.Inet4Address+import java.net.InetAddress+import java.net.InetSocketAddress+import java.net.NetworkInterface+import java.net.Socket+import kotlin.time.Duration+import kotlin.time.Duration.Companion.milliseconds+import kotlin.time.Duration.Companion.seconds++/** A device answering on the LAN, before any ADB handshake. */+data class ScanHit(+ val host: String,+ val port: Int,+ val kind: Kind,+ /** mDNS service name, else reverse DNS; null when neither answers. */+ val name: String?,+) {+ enum class Kind {+ /** `adb tcpip` / network debugging on a fixed port (usually 5555). */+ CLASSIC,+ /** Android 11+ wireless debugging, already paired: connect port from `_adb-tls-connect`. */+ WIRELESS,+ /** Wireless debugging with the "pair with code" box open: needs the 6-digit code. */+ PAIRING,+ }+}++/**+ * Finds ADB on the local /24s: a TCP sweep of [port] plus, if given, mDNS for wireless debugging.+ * MAC/maker lookup is left out: Android 10+ apps can't read the ARP table.+ */+class LanScanner(+ private val mdns: KadbMdns? = null,+ private val port: Int = 5555,+ private val probeTimeout: Duration = 400.milliseconds,+ private val mdnsWindow: Duration = 3.seconds,+ private val parallelism: Int = 64,+) {+ /** Emits each hit as soon as it answers; completes when the sweep and the mDNS window end. */+ fun scan(hosts: List<String> = localSubnetHosts()): Flow<ScanHit> = channelFlow {+ launch { sweep(hosts) }+ mdns?.let { launch { browse(it) } }+ }++ private suspend fun ProducerScope<ScanHit>.sweep(hosts: List<String>) {+ val gate = Semaphore(parallelism)+ hosts.forEach { host ->+ launch(Dispatchers.IO) {+ gate.withPermit {+ if (isOpen(host)) send(ScanHit(host, port, ScanHit.Kind.CLASSIC, reverseName(host)))+ }+ }+ }+ }++ private suspend fun ProducerScope<ScanHit>.browse(mdns: KadbMdns) {+ withContext(Dispatchers.IO) { mdns.start() } // JmDNS setup blocks+ try {+ val seen = mutableSetOf<Pair<String, Int>>()+ withTimeoutOrNull(mdnsWindow) {+ mdns.state.collect { state ->+ for (e in state.allDevices) {+ if (!seen.add(e.host to e.port)) continue+ val kind = when (e.serviceType) {+ MdnsServiceType.TLS_PAIRING -> ScanHit.Kind.PAIRING+ MdnsServiceType.TLS_CONNECT -> ScanHit.Kind.WIRELESS+ else -> ScanHit.Kind.CLASSIC+ }+ send(ScanHit(e.host, e.port, kind, e.name))+ }+ }+ }+ } finally {+ withContext(NonCancellable + Dispatchers.IO) { mdns.stop() }+ }+ }++ private fun isOpen(host: String): Boolean = try {+ Socket().use { it.connect(InetSocketAddress(host, port), probeTimeout.inWholeMilliseconds.toInt()); true }+ } catch (_: Exception) {+ false+ }++ private fun reverseName(host: String): String? =+ runCatching { InetAddress.getByName(host).canonicalHostName }.getOrNull()?.takeIf { it != host }++ companion object {+ /** Every other address in the /24 of each up, non-loopback IPv4 interface. */+ fun localSubnetHosts(): List<String> =+ NetworkInterface.getNetworkInterfaces().toList()+ .filter { it.isUp && !it.isLoopback }+ .flatMap { it.inetAddresses.toList() }+ .filterIsInstance<Inet4Address>()+ .flatMap { addr ->+ val b = addr.address+ val prefix = "${b[0].toUByte()}.${b[1].toUByte()}.${b[2].toUByte()}"+ (1..254).map { "$prefix.$it" }.filter { it != addr.hostAddress }+ }+ .distinct()+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt b/adb/src/main/kotlin/app/tellyscope/adb/Parsers.ktnew file mode 100644index 0000000..0240514--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt@@ -0,0 +1,115 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/** Parsers for raw shell output. Pure functions; every one returns null rather than guessing. */+object Parsers {++ /** Aggregate `cpu` line of /proc/stat. */+ data class CpuTimes(val busy: Long, val total: Long)++ fun cpuTimes(procStat: String): CpuTimes? {+ val line = procStat.lineSequence().firstOrNull { it.startsWith("cpu ") } ?: return null+ val f = line.trim().split(Regex("\\s+")).drop(1).mapNotNull(String::toLongOrNull)+ if (f.size < 4) return null+ val total = f.take(8).sum() // user nice system idle iowait irq softirq steal; guest is already in user+ val idle = f[3] + f.getOrElse(4) { 0 }+ return CpuTimes(total - idle, total)+ }++ /** CPU use between two samples, 0..100, or null if the counters didn't move. */+ fun cpuPercent(prev: CpuTimes, now: CpuTimes): Double? {+ val dt = now.total - prev.total+ if (dt <= 0) return null+ return ((now.busy - prev.busy).toDouble() / dt * 100).coerceIn(0.0, 100.0)+ }++ data class Memory(val totalKb: Long, val availableKb: Long)++ fun memory(meminfo: String): Memory? {+ val kv = meminfo.lineSequence().mapNotNull { line ->+ val name = line.substringBefore(':', "").takeIf { it.isNotEmpty() } ?: return@mapNotNull null+ line.substringAfter(':').trim().split(Regex("\\s+")).firstOrNull()?.toLongOrNull()?.let { name to it }+ }.toMap()+ val total = kv["MemTotal"] ?: return null+ // MemAvailable exists since kernel 3.14; older TVs get a rough free+cached.+ val avail = kv["MemAvailable"] ?: ((kv["MemFree"] ?: return null) + (kv["Cached"] ?: 0))+ return Memory(total, avail)+ }++ data class Storage(val totalKb: Long, val usedKb: Long)++ /** `df -k /data`. Toybox may wrap a long filesystem name onto its own line. */+ fun storage(df: String): Storage? {+ val nums = df.lineSequence().drop(1).joinToString(" ").trim().split(Regex("\\s+"))+ .mapNotNull(String::toLongOrNull)+ if (nums.size < 2) return null+ return Storage(totalKb = nums[0], usedKb = nums[1])+ }++ fun uptimeSeconds(procUptime: String): Long? =+ procUptime.trim().substringBefore(' ').toDoubleOrNull()?.toLong()++ /**+ * Output of [Commands.THERMAL]: `type=millidegrees` lines. Prefers a CPU/SoC zone, otherwise+ * the hottest plausible one. Null when nothing readable, so the UI shows a dash, never 0.+ */+ fun temperatureC(thermal: String): Double? {+ val zones = thermal.lineSequence().mapNotNull { line ->+ val type = line.substringBefore('=', "").trim().lowercase()+ val raw = line.substringAfter('=', "").trim().toDoubleOrNull() ?: return@mapNotNull null+ val c = if (raw > 1000) raw / 1000 else raw // some kernels report whole degrees+ if (c in 1.0..150.0) type to c else null+ }.toList()+ if (zones.isEmpty()) return null+ val cpu = zones.filter { (t, _) -> listOf("cpu", "soc", "tsens", "core").any { t.contains(it) } }+ return (cpu.ifEmpty { zones }).maxOf { it.second }+ }++ data class Package(val name: String, val uid: Int?)++ /** `pm list packages -U`: `package:com.foo uid:10023` (uid list may be comma-separated). */+ fun packages(pmList: String): List<Package> = pmList.lineSequence().mapNotNull { line ->+ val l = line.trim()+ if (!l.startsWith("package:")) return@mapNotNull null+ val name = l.removePrefix("package:").substringBefore(' ')+ val uid = l.substringAfter(" uid:", "").substringBefore(',').toIntOrNull()+ Package(name, uid).takeIf { name.isNotEmpty() }+ }.toList()++ data class Process(val pid: Int, val user: String, val rssKb: Long, val cpuPercent: Double, val name: String)++ /**+ * `top -b -n 1 -o PID,USER,RES,%CPU,NAME`. Header and summary lines are skipped by requiring a+ * numeric first column. RES carries K/M/G suffixes.+ */+ fun processes(top: String): List<Process> = top.lineSequence().mapNotNull { line ->+ val f = line.trim().split(Regex("\\s+"), limit = 5)+ if (f.size < 5) return@mapNotNull null+ val pid = f[0].toIntOrNull() ?: return@mapNotNull null+ val rss = sizeKb(f[2]) ?: return@mapNotNull null+ val cpu = f[3].toDoubleOrNull() ?: return@mapNotNull null+ Process(pid, f[1], rss, cpu, f[4])+ }.toList()++ /** `u0_a123` → 10123, `system` etc. → null. */+ fun appUid(user: String): Int? {+ val m = Regex("u(\\d+)_a(\\d+)").matchEntire(user) ?: return null+ return m.groupValues[1].toInt() * 100_000 + 10_000 + m.groupValues[2].toInt()+ }++ internal fun sizeKb(s: String): Long? {+ val n = s.dropLast(1).toDoubleOrNull()+ return when (s.lastOrNull()?.uppercaseChar()) {+ 'K' -> n?.toLong()+ 'M' -> n?.let { (it * 1024).toLong() }+ 'G' -> n?.let { (it * 1024 * 1024).toLong() }+ else -> s.toLongOrNull()?.let { it / 1024 } // bare bytes+ }+ }++ /** `getprop` lines: `[ro.product.model]: [XK03H]`. */+ fun props(getprop: String): Map<String, String> = getprop.lineSequence().mapNotNull { line ->+ val m = Regex("""\[(.+?)]: \[(.*)]""").matchEntire(line.trim()) ?: return@mapNotNull null+ m.groupValues[1] to m.groupValues[2]+ }.toMap()+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Protected.kt b/adb/src/main/kotlin/app/tellyscope/adb/Protected.ktnew file mode 100644index 0000000..93803d6--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Protected.kt@@ -0,0 +1,63 @@+// SPDX-License-Identifier: GPL-3.0-only+// CORE and CORE_OK follow cleanyourtv's tools/disable.sh (MIT, Copyright (c) 2026 Gathin), see NOTICE.+package app.tellyscope.adb++/** Why a package may not be stopped or disabled. The UI shows the matching copy. */+enum class ProtectedReason { HOME_SCREEN, SYSTEM, SETTINGS, PLAY_SERVICES, KEYBOARD, TV_INPUTS_REMOTE, SETUP_WIZARD }++/**+ * Packages Tellyscope never stops or disables. Over-matching is fine: a protected package just+ * stays on. Sources: cleanyourtv's core-package rule (a Mi TV Stick never booted again without+ * these, cleanyourtv#884), its "never disable what the TV needs" list (inputs/tuner, source menu,+ * remote and Bluetooth, keyboard, Play), and the package list of an Android TV 11 XGIMI projector.+ */+object Protected {+ /** Android can stop booting without these. */+ private val CORE = Regex(+ "android|com\\.android\\.systemui|com\\.android\\.shell|com\\.android\\.phone|" ++ "com\\.(google\\.)?android\\.(permissioncontroller|packageinstaller|ext\\.services|ext\\.shared|modulemetadata)|" ++ "com\\.google\\.android\\.overlay\\.modules.*|com\\.android\\.providers\\..*",+ )+ /** Providers no TV feature uses; tested lists turn them off. */+ private val CORE_OK = Regex("com\\.android\\.providers\\.(calendar|contacts|userdictionary|blockednumber)")++ private val EXACT: Map<String, ProtectedReason> = mapOf(+ "com.android.settings" to ProtectedReason.SETTINGS,+ "com.android.tv.settings" to ProtectedReason.SETTINGS,+ "com.android.vending" to ProtectedReason.PLAY_SERVICES,+ "com.google.android.gms" to ProtectedReason.PLAY_SERVICES,+ "com.google.android.gsf" to ProtectedReason.PLAY_SERVICES,+ // Every app that shows a web page needs the WebView provider.+ "com.google.android.webview" to ProtectedReason.SYSTEM,+ "com.android.webview" to ProtectedReason.SYSTEM,+ )++ /** Name fragments, checked in order; manufacturer names vary, so these match loosely. */+ private val PATTERNS: List<Pair<String, ProtectedReason>> = listOf(+ "networkstack" to ProtectedReason.SYSTEM, // Wi-Fi and Ethernet setup; we'd cut our own link+ "inputmethod" to ProtectedReason.KEYBOARD,+ "keyboard" to ProtectedReason.KEYBOARD,+ ".ime" to ProtectedReason.KEYBOARD,+ "inputdevices" to ProtectedReason.KEYBOARD,+ "tvinput" to ProtectedReason.TV_INPUTS_REMOTE,+ "tv.input" to ProtectedReason.TV_INPUTS_REMOTE,+ "hdmi" to ProtectedReason.TV_INPUTS_REMOTE,+ "tuner" to ProtectedReason.TV_INPUTS_REMOTE,+ "bluetooth" to ProtectedReason.TV_INPUTS_REMOTE,+ "remote" to ProtectedReason.TV_INPUTS_REMOTE,+ "rcu" to ProtectedReason.TV_INPUTS_REMOTE,+ "setupwizard" to ProtectedReason.SETUP_WIZARD,+ "setupwraith" to ProtectedReason.SETUP_WIZARD,+ "bootwizard" to ProtectedReason.SETUP_WIZARD,+ "provision" to ProtectedReason.SETUP_WIZARD,+ )++ /** [homePackages] are the device's launchers, read live; they are protected whatever their name. */+ fun reason(pkg: String, homePackages: Set<String> = emptySet()): ProtectedReason? {+ if (pkg in homePackages) return ProtectedReason.HOME_SCREEN+ EXACT[pkg]?.let { return it }+ if (CORE.matches(pkg) && !CORE_OK.matches(pkg)) return ProtectedReason.SYSTEM+ val lower = pkg.lowercase()+ return PATTERNS.firstOrNull { (fragment, _) -> fragment in lower }?.second+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.ktnew file mode 100644index 0000000..b500f1e--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt@@ -0,0 +1,71 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.test.runTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class ActionsTest {+ private val home = "cmd package resolve-activity" to ok("priority=0 preferredOrder=0\ncom.google.android.tvlauncher/.MainActivity\n")++ @Test fun disableReturnsEnableAsUndo() = runTest {+ val sh = FakeShell(mapOf(home, "pm disable-user" to ok("Package com.foo.ads new state: disabled-user\n")))+ assertEquals(ActionResult.Done(Action.ENABLE), Actions(sh).run(Action.DISABLE, "com.foo.ads"))+ assertTrue(sh.ran.contains("pm disable-user --user 0 com.foo.ads 2>&1"))+ }++ @Test fun stopUndoIsOpenAgain() = runTest {+ val sh = FakeShell(mapOf(home))+ assertEquals(ActionResult.Done(Action.OPEN), Actions(sh).run(Action.STOP, "com.google.android.youtube.tv"))+ }++ @Test fun refusesCurrentLauncherWhateverItsName() = runTest {+ val sh = FakeShell(mapOf("cmd package resolve-activity" to ok("com.example.customhome/.Home\n")))+ assertEquals(ActionResult.Refused(ProtectedReason.HOME_SCREEN), Actions(sh).run(Action.DISABLE, "com.example.customhome"))+ assertTrue(sh.ran.none { it.startsWith("pm ") })+ }++ @Test fun noDefaultLauncherProtectsEveryLauncher() = runTest {+ val sh = FakeShell(mapOf(+ "cmd package resolve-activity" to ok("priority=0\nandroid/com.android.internal.app.ResolverActivity\n"),+ "cmd package query-activities" to ok("com.google.android.tvlauncher/.MainActivity\ncom.spocky.projengmenu/.Main\n"),+ ))+ assertEquals(setOf("com.google.android.tvlauncher", "com.spocky.projengmenu"), Actions(sh).homePackages())+ assertEquals(ActionResult.Refused(ProtectedReason.HOME_SCREEN), Actions(sh).run(Action.DISABLE, "com.spocky.projengmenu"))+ }++ @Test fun refusesProtectedPackages() = runTest {+ val a = Actions(FakeShell(mapOf(home)))+ assertEquals(ActionResult.Refused(ProtectedReason.PLAY_SERVICES), a.run(Action.DISABLE, "com.google.android.gms"))+ assertEquals(ActionResult.Refused(ProtectedReason.KEYBOARD), a.run(Action.STOP, "com.google.android.leanback.ime"))+ assertEquals(ActionResult.Refused(ProtectedReason.TV_INPUTS_REMOTE), a.run(Action.DISABLE, "com.xgimi.hdmiinput"))+ }++ @Test fun enablingProtectedIsAllowed() = runTest {+ val sh = FakeShell(mapOf(home, "pm enable" to ok("Package com.android.vending new state: enabled\n")))+ assertEquals(ActionResult.Done(Action.DISABLE), Actions(sh).run(Action.ENABLE, "com.android.vending"))+ }++ @Test fun pmErrorIsFailure() = runTest {+ val sh = FakeShell(mapOf(home, "pm disable-user" to ok("Error: java.lang.SecurityException: Shell cannot change component state\n")))+ assertTrue(Actions(sh).run(Action.DISABLE, "com.foo") is ActionResult.Failed)+ }++ @Test fun openFallsBackToPhoneLauncher() = runTest {+ val sh = FakeShell(mapOf(+ "monkey -p com.foo -c android.intent.category.LEANBACK_LAUNCHER" to ok("** No activities found to run, monkey aborted.\n"),+ "monkey -p com.foo -c android.intent.category.LAUNCHER" to ok("Events injected: 1\n"),+ ))+ assertEquals(ActionResult.Done(null), Actions(sh).run(Action.OPEN, "com.foo"))+ assertEquals(2, sh.ran.count { it.startsWith("monkey") })+ }++ @Test fun rejectsShellInjection() = runTest {+ val sh = FakeShell()+ assertFailsWith<IllegalArgumentException> { Actions(sh).run(Action.STOP, "com.foo; reboot") }+ assertFailsWith<IllegalArgumentException> { Actions(sh).run(Action.STOP, "\$(reboot)") }+ assertTrue(sh.ran.isEmpty())+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.ktnew file mode 100644index 0000000..020a6f2--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt@@ -0,0 +1,95 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.test.advanceTimeBy+import kotlinx.coroutines.test.runCurrent+import kotlinx.coroutines.test.runTest+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+class DeviceLinkTest {+ private val reading = Stats(cpuPercent = 10.0, memory = Parsers.Memory(2, 1))++ @Test fun notAllowedStopsRetrying() = runTest {+ var calls = 0+ val link = DeviceLink("tv", 5555, backgroundScope, open = { _, _ -> calls++; ConnectResult.NotAllowed })+ link.connect(); runCurrent()+ assertEquals(DeviceState.NOT_ALLOWED, link.state.value)+ advanceTimeBy(60_000)+ assertEquals(1, calls)+ }++ @Test fun dropsToOfflineThenReconnects() = runTest {+ val sessions = mutableListOf<FakeShell>()+ var reachable = true+ var failNext = true+ val link = DeviceLink(+ "tv", 5555, backgroundScope,+ monitorFor = { fakeMonitor(failFirst = failNext.also { failNext = false }) },+ open = { _, _ ->+ if (reachable) ConnectResult.Online(FakeShell().also { sessions += it }) else ConnectResult.Unreachable("no route")+ },+ )+ link.connect(); runCurrent()+ // first session's monitor throws after one reading+ assertEquals(DeviceState.OFFLINE, link.state.value)+ assertEquals(reading, link.stats.value) // last reading kept for the greyed page+ assertTrue(sessions[0].closed)++ reachable = false+ advanceTimeBy(5_001)+ assertEquals(DeviceState.OFFLINE, link.state.value)++ reachable = true+ advanceTimeBy(5_001)+ assertEquals(DeviceState.ONLINE, link.state.value)+ assertEquals(2, sessions.size)+ }++ @Test fun needsPairingStopsRetrying() = runTest {+ var calls = 0+ val link = DeviceLink("tv", 37011, backgroundScope, open = { _, _ -> calls++; ConnectResult.NeedsPairing })+ link.connect(); runCurrent()+ advanceTimeBy(60_000)+ assertEquals(DeviceState.NEEDS_PAIRING, link.state.value)+ assertEquals(1, calls)+ }++ @Test fun stalledHandshakeAfterSleepKeepsRetrying() = runTest {+ var calls = 0+ val link = DeviceLink(+ "tv", 5555, backgroundScope,+ monitorFor = { fakeMonitor(failFirst = true) },+ open = { _, _ -> if (calls++ == 0) ConnectResult.Online(FakeShell()) else ConnectResult.NotAllowed },+ )+ link.connect(); runCurrent()+ advanceTimeBy(20_001)+ assertEquals(DeviceState.OFFLINE, link.state.value)+ assertTrue(calls >= 4)+ }++ @Test fun disconnectClosesSessionAndResets() = runTest {+ val shell = FakeShell()+ val link = DeviceLink("tv", 5555, backgroundScope, monitorFor = { fakeMonitor(failFirst = false) },+ open = { _, _ -> ConnectResult.Online(shell) })+ link.connect(); runCurrent()+ assertEquals(DeviceState.ONLINE, link.state.value)+ link.disconnect(); runCurrent()+ assertEquals(DeviceState.FOUND, link.state.value)+ assertTrue(shell.closed)+ assertEquals(null, link.session)+ }++ private fun fakeMonitor(failFirst: Boolean) = object : MonitorSource {+ override fun stats() = flow {+ emit(reading)+ if (failFirst) throw IOException("gone")+ kotlinx.coroutines.awaitCancellation()+ }+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.ktnew file mode 100644index 0000000..f43a84b--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt@@ -0,0 +1,50 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.take+import kotlinx.coroutines.flow.toList+import kotlinx.coroutines.test.runTest+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith++class DeviceMonitorTest {+ private val sep = "\n@@tellyscope@@\n"++ /** Each FAST call advances the CPU counters by busy +25 / total +100. */+ private fun device(): AdbShell {+ var tick = 0L+ return AdbShell { cmd ->+ if (cmd.startsWith("cat /proc/stat")) {+ tick+++ ok("cpu ${tick * 25} 0 0 ${tick * 75} 0 0 0 0\n${sep}MemTotal: 2000 kB\nMemAvailable: 500 kB\n")+ } else {+ ok("[ro.product.model]: [XK03H]\n[ro.build.version.sdk]: [30]\n$sep" ++ "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/x 16000 9800 6200 62% /data\n$sep" ++ "300.5 100.0\n$sep" + "cpu-thermal=52000\n")+ }+ }+ }++ @Test fun firstReadingHasEverything() = runTest {+ val s = DeviceMonitor(device()).stats().first()+ assertEquals(25.0, s.cpuPercent)+ assertEquals(Parsers.Memory(2000, 500), s.memory)+ assertEquals(Parsers.Storage(16000, 9800), s.storage)+ assertEquals(300L, s.uptimeSeconds)+ assertEquals(52.0, s.temperatureC)+ assertEquals("XK03H", s.model)+ assertEquals(30, s.sdk)+ }++ @Test fun keepsEmitting() = runTest {+ assertEquals(3, DeviceMonitor(device()).stats().take(3).toList().size)+ }++ @Test fun silentDeviceThrowsIo() = runTest {+ val hung = AdbShell { kotlinx.coroutines.awaitCancellation() }+ assertFailsWith<IOException> { DeviceMonitor(hung).stats().first() }+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceStateTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceStateTest.ktnew file mode 100644index 0000000..408f615--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceStateTest.kt@@ -0,0 +1,18 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import app.tellyscope.adb.DeviceEvent.*+import app.tellyscope.adb.DeviceState.*+import kotlin.test.Test+import kotlin.test.assertEquals++class DeviceStateTest {+ @Test fun happyPath() = assertEquals(ONLINE, FOUND.on(Connect).on(Authorized))+ @Test fun noAnswerIsNotAllowed() = assertEquals(NOT_ALLOWED, FOUND.on(Connect).on(AuthTimedOut))+ @Test fun dropAndComeBack() = assertEquals(ONLINE, ONLINE.on(Lost).also { assertEquals(OFFLINE, it) }.on(Authorized))+ @Test fun unreachableWhileWaitingIsOffline() = assertEquals(OFFLINE, WAITING.on(Unreachable))+ @Test fun foundStaysFoundWhenUnreachable() = assertEquals(FOUND, FOUND.on(Unreachable))+ @Test fun connectWhileOnlineIsNoop() = assertEquals(ONLINE, ONLINE.on(Connect))+ @Test fun pairingThenDisconnect() = assertEquals(FOUND, WAITING.on(NeedsPairing).also { assertEquals(NEEDS_PAIRING, it) }.on(Disconnected))+ @Test fun retryAfterNotAllowedWaitsAgain() = assertEquals(WAITING, NOT_ALLOWED.on(Connect))+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.ktnew file mode 100644index 0000000..fb7222b--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt@@ -0,0 +1,19 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/** Answers by the first matching command prefix and records what ran. */+class FakeShell(private val answers: Map<String, ShellResult> = emptyMap()) : AdbSession {+ val ran = mutableListOf<String>()+ var closed = false+ var failWith: Exception? = null++ override suspend fun shell(command: String): ShellResult {+ failWith?.let { throw it }+ ran += command+ return answers.entries.firstOrNull { command.startsWith(it.key) }?.value ?: ShellResult("", 0)+ }++ override fun close() { closed = true }+}++fun ok(output: String) = ShellResult(output, 0)diff --git a/adb/src/test/kotlin/app/tellyscope/adb/LanScannerTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/LanScannerTest.ktnew file mode 100644index 0000000..c1c1e8c--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/LanScannerTest.kt@@ -0,0 +1,19 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.flow.toList+import kotlinx.coroutines.runBlocking+import java.net.InetAddress+import java.net.ServerSocket+import kotlin.test.Test+import kotlin.test.assertEquals++class LanScannerTest {+ @Test fun findsOnlyOpenPorts() = runBlocking {+ ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")).use { server ->+ val hits = LanScanner(port = server.localPort).scan(listOf("127.0.0.1", "127.0.0.2")).toList()+ assertEquals(listOf("127.0.0.1"), hits.map { it.host })+ assertEquals(ScanHit.Kind.CLASSIC, hits.single().kind)+ }+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ParsersTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ParsersTest.ktnew file mode 100644index 0000000..dfeeb75--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/ParsersTest.kt@@ -0,0 +1,75 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class ParsersTest {+ @Test fun cpuPercentFromTwoSamples() {+ val a = Parsers.cpuTimes("cpu 100 0 100 700 100 0 0 0 0 0\ncpu0 1 2 3 4\n")!!+ val b = Parsers.cpuTimes("cpu 150 0 150 750 150 0 0 0 0 0\n")!!+ // busy +100 of total +200+ assertEquals(50.0, Parsers.cpuPercent(a, b))+ assertNull(Parsers.cpuPercent(b, b))+ assertNull(Parsers.cpuTimes("cpu0 1 2 3 4"))+ }++ @Test fun memoryPrefersMemAvailable() {+ val m = Parsers.memory("MemTotal: 2048000 kB\nMemFree: 100000 kB\nMemAvailable: 900000 kB\nCached: 5 kB\n")+ assertEquals(Parsers.Memory(2048000, 900000), m)+ assertEquals(Parsers.Memory(10, 7), Parsers.memory("MemTotal: 10 kB\nMemFree: 4 kB\nCached: 3 kB\n"))+ assertNull(Parsers.memory(""))+ }++ @Test fun storageHandlesWrappedFilesystemName() {+ val plain = "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/block/dm-5 16000000 9800000 6200000 62% /data\n"+ val wrapped = "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/block/bootdevice/by-name/userdata\n 16000000 9800000 6200000 62% /data\n"+ assertEquals(Parsers.Storage(16000000, 9800000), Parsers.storage(plain))+ assertEquals(Parsers.Storage(16000000, 9800000), Parsers.storage(wrapped))+ assertNull(Parsers.storage("df: /data: Permission denied\n"))+ }++ @Test fun temperaturePrefersCpuZoneAndScales() {+ assertEquals(52.0, Parsers.temperatureC("battery=30000\ncpu-thermal=52000\ngpu=61000\n"))+ assertEquals(61.0, Parsers.temperatureC("battery=30000\ngpu=61000\n"))+ assertEquals(45.0, Parsers.temperatureC("soc_thermal=45\n"))+ assertNull(Parsers.temperatureC("=\ncpu=\nx=-40000\n"))+ }++ @Test fun packagesWithUid() {+ val out = "package:com.google.android.youtube.tv uid:10087\npackage:android uid:1000\npackage:com.shared uid:10050,10051\njunk\n"+ assertEquals(+ listOf(+ Parsers.Package("com.google.android.youtube.tv", 10087),+ Parsers.Package("android", 1000),+ Parsers.Package("com.shared", 10050),+ ),+ Parsers.packages(out),+ )+ }++ @Test fun processesSkipHeaders() {+ val top = """+ Tasks: 210 total, 1 running, 209 sleeping+ Mem: 2000000K total+ PID USER RES %CPU NAME+ 512 system 120M 9.0 system_server+ 2201 u0_a87 312M 3.5 com.google.android.youtube.tv+ 33 root 2.5K 0.0 kworker/0:1 extra+ """.trimIndent()+ val p = Parsers.processes(top)+ assertEquals(3, p.size)+ assertEquals(Parsers.Process(2201, "u0_a87", 312 * 1024, 3.5, "com.google.android.youtube.tv"), p[1])+ assertEquals("kworker/0:1 extra", p[2].name)+ assertEquals(10087, Parsers.appUid("u0_a87"))+ assertNull(Parsers.appUid("system"))+ }++ @Test fun propsAndUptime() {+ val p = Parsers.props("[ro.product.model]: [XK03H]\n[ro.build.version.sdk]: [30]\n[empty]: []\n")+ assertEquals("XK03H", p["ro.product.model"])+ assertEquals("", p["empty"])+ assertEquals(273600L, Parsers.uptimeSeconds("273600.52 1000000.00\n"))+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ProtectedTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ProtectedTest.ktnew file mode 100644index 0000000..0efeae8--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/ProtectedTest.kt@@ -0,0 +1,31 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class ProtectedTest {+ @Test fun coreRuleWithSpareProviders() {+ assertEquals(ProtectedReason.SYSTEM, Protected.reason("com.google.android.permissioncontroller"))+ assertEquals(ProtectedReason.SYSTEM, Protected.reason("com.android.providers.tv"))+ assertEquals(ProtectedReason.SYSTEM, Protected.reason("com.google.android.overlay.modules.ext.services"))+ assertNull(Protected.reason("com.android.providers.calendar"))+ }++ /** Package names from an Android TV 11 XGIMI projector. */+ @Test fun xgimiPackages() {+ assertEquals(ProtectedReason.TV_INPUTS_REMOTE, Protected.reason("com.xgimi.tvinput"))+ assertEquals(ProtectedReason.TV_INPUTS_REMOTE, Protected.reason("com.xgimi.bluetoothservice"))+ assertEquals(ProtectedReason.TV_INPUTS_REMOTE, Protected.reason("com.google.android.tv.remote.service"))+ assertEquals(ProtectedReason.KEYBOARD, Protected.reason("com.google.android.inputmethod.latin"))+ assertEquals(ProtectedReason.SETUP_WIZARD, Protected.reason("com.google.android.tungsten.setupwraith"))+ assertEquals(ProtectedReason.SETUP_WIZARD, Protected.reason("com.xgimi.overseas.xgimiatvbootwizard"))+ assertEquals(ProtectedReason.SYSTEM, Protected.reason("com.android.networkstack.tethering.inprocess"))+ assertEquals(ProtectedReason.SETTINGS, Protected.reason("com.android.tv.settings"))+ // Debloat targets stay allowed.+ assertNull(Protected.reason("com.google.android.katniss"))+ assertNull(Protected.reason("com.google.android.tvrecommendations"))+ assertNull(Protected.reason("com.amazon.amazonvideo.livingroom"))+ }+}diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 9099dda..7901e6d 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -1,6 +1,13 @@<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- ADB to the TV over Wi-Fi. -->+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <!-- Android 17 blocks every connection to LAN addresses (and mDNS) for apps targeting 37+ without this runtime permission. The UI must request it before the first scan. -->+ <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />+<applicationandroid:allowBackup="false"android:dataExtractionRules="@xml/data_extraction_rules"diff --git a/cli/build.gradle.kts b/cli/build.gradle.ktsnew file mode 100644index 0000000..f896d2d--- /dev/null+++ b/cli/build.gradle.kts@@ -0,0 +1,16 @@+// SPDX-License-Identifier: GPL-3.0-only++plugins {+ alias(libs.plugins.kotlin.jvm)+ application+}++// Desktop smoke test for :adb against a real TV; not shipped.+dependencies {+ implementation(project(":adb"))+ runtimeOnly(libs.conscrypt.openjdk.uber) // Kadb pairing on the JVM+}++application {+ mainClass = "app.tellyscope.cli.MainKt"+}diff --git a/cli/src/main/kotlin/app/tellyscope/cli/Main.kt b/cli/src/main/kotlin/app/tellyscope/cli/Main.ktnew file mode 100644index 0000000..69e6e01--- /dev/null+++ b/cli/src/main/kotlin/app/tellyscope/cli/Main.kt@@ -0,0 +1,34 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.cli++import app.tellyscope.adb.Connector+import app.tellyscope.adb.DeviceLink+import app.tellyscope.adb.LanScanner+import com.flyfishxu.kadb.mdns.KadbMdnsJvm+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.onEach+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import java.io.File++/**+ * Smoke test for :adb from a desktop on the TV's LAN.+ * scan list ADB devices+ * stats <host> [port] connect (press Allow on the TV) and print live stats+ * pair <host> <port> <code>+ */+fun main(args: Array<String>) = runBlocking {+ Connector.init(File(System.getProperty("user.home"), ".tellyscope/adbkey.pem"))+ when (args.firstOrNull()) {+ "scan" -> LanScanner(KadbMdnsJvm()).scan().collect { println("${it.host}:${it.port} ${it.kind} ${it.name ?: "-"}") }+ "pair" -> Connector.pair(args[1], args[2].toInt(), args[3]).also { println("paired") }+ "stats" -> {+ val link = DeviceLink(args[1], args.getOrNull(2)?.toInt() ?: 5555, this)+ launch { link.state.collect { println("state: $it") } }+ launch { link.stats.filterNotNull().onEach { println(it) }.collect() }+ link.connect()+ }+ else -> println("usage: scan | stats <host> [port] | pair <host> <port> <code>")+ }+}diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 479ee24..49c5ebc 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -8,6 +8,10 @@ activity-compose = "1.13.0"core-ktx = "1.19.1"lifecycle = "2.11.0"kadb = "2.1.5"+# kadb-mdns stops at 2.1.4; 2.1.5 was not published for it.+kadb-mdns = "2.1.4"+coroutines = "1.11.0"+conscrypt = "2.5.2"junit = "4.13.2"[libraries]@@ -20,6 +24,11 @@ compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }compose-material3 = { module = "androidx.compose.material3:material3", version.ref = "material3" }kadb = { module = "com.flyfishxu:kadb", version.ref = "kadb" }+kadb-mdns = { module = "com.flyfishxu:kadb-mdns", version.ref = "kadb-mdns" }+kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }+kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }+kotlin-test-junit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }+conscrypt-openjdk-uber = { module = "org.conscrypt:conscrypt-openjdk-uber", version.ref = "conscrypt" }junit = { module = "junit:junit", version.ref = "junit" }[plugins]diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 441782a..ef6920f 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -22,4 +22,4 @@ dependencyResolutionManagement {}rootProject.name = "tellyscope"-include(":app", ":adb")+include(":app", ":adb", ":cli")