Skip to content

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.

Show real processes, screen state, connections and data use

jesse-agent-2320a88e00c1fdd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af6f9d2..2e99ede 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,3 +16,5 @@ until this file has a section for its version.
- **New:** Send files to the TV's Download or Movies folder, and save them back. [#9](../../pull/9)
- **New:** Suggested apps to disable, from a tested list for your TV. [#11](../../pull/11)
- **New:** A remote: D-pad, volume, Play / Pause, typing, Sleep and Restart. [#12](../../pull/12)
+- **Fixed:** Processes, screen state, connections and data used now show on real TVs. [#17](../../pull/17)
+- **Fixed:** A TV on Wi-Fi no longer shows its connection as Ethernet. [#17](../../pull/17)
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt b/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt
index bbe8158..42f815d 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt
@@ -19,9 +19,21 @@ internal object Commands {
"df -k /data",
"cat /proc/uptime",
THERMAL,
+ PACKAGES,
).batch()
- const val PROCESSES = "top -b -n 1 -o PID,USER,RES,%CPU,NAME"
+ /** Every 10 s and on open: processes and whether the screen is on. */
+ val MEDIUM = listOf(
+ "top -b -n 1 -o PID,USER,RES,%CPU,NAME",
+ "dumpsys power | grep -E 'mWakefulness=|mScreenOn='",
+ ).batch()
+
+ /** Open TCP connections, IPv4 and IPv6. */
+ const val SOCKETS = "cat /proc/net/tcp /proc/net/tcp6"
+
+ /** Bytes per app since boot; xt_qtaguid answers on kernels from before Android 10's eBPF accounting. */
+ val TRAFFIC = listOf("dumpsys netstats --uid", "cat /proc/net/xt_qtaguid/stats").batch()
+
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"
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt
index b92d93f..ba814de 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt
@@ -21,15 +21,23 @@ data class Stats(
val manufacturer: String? = null,
val androidVersion: String? = null,
val sdk: Int? = null,
+ /** Uid → packages, from the slow tier; empty where `pm` can't list uids. */
+ val packages: Map<Int, List<String>> = emptyMap(),
+ val processes: List<AppProcess> = emptyList(),
+ val screenOn: Boolean? = null,
)
+/** One process and the package it belongs to; null for native daemons. */
+data class AppProcess(val pid: Int, val name: String, val packageName: String?, val cpuPercent: Double, val rssKb: Long)
+
/** 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].
+ * Live stats on three tiers: CPU/RAM every [fast], processes and screen state every [medium],
+ * identity/storage/uptime/temperature/packages 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.
@@ -37,12 +45,15 @@ fun interface MonitorSource {
class DeviceMonitor(
private val shell: AdbShell,
private val fast: Duration = 2.seconds,
+ private val medium: Duration = 10.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 mediumStats = readMedium(slowStats.packages)
+ var lastMedium = TimeSource.Monotonic.markNow()
var prevCpu = readFast().first
while (true) {
@@ -51,10 +62,14 @@ class DeviceMonitor(
slowStats = readSlow()
lastSlow = TimeSource.Monotonic.markNow()
}
+ if (lastMedium.elapsedNow() >= medium) {
+ mediumStats = readMedium(slowStats.packages)
+ lastMedium = 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))
+ emit(slowStats.copy(cpuPercent = pct, memory = mem, processes = mediumStats.first, screenOn = mediumStats.second))
}
}
@@ -67,8 +82,17 @@ class DeviceMonitor(
return Parsers.cpuTimes(stat) to Parsers.memory(meminfo)
}
+ private suspend fun readMedium(packages: Map<Int, List<String>>): Pair<List<AppProcess>, Boolean?> {
+ val (top, power) = Commands.split(run(Commands.MEDIUM), 2)
+ val known = packages.values.flatten().toSet()
+ val procs = Parsers.processes(top).map { p ->
+ AppProcess(p.pid, p.name, Parsers.owner(p, packages, known), p.cpuPercent, p.rssKb)
+ }
+ return procs to Parsers.screenOn(power)
+ }
+
private suspend fun readSlow(): Stats {
- val (getprop, df, uptime, thermal) = Commands.split(run(Commands.SLOW), 4)
+ val (getprop, df, uptime, thermal, pm) = Commands.split(run(Commands.SLOW), 5)
val props = Parsers.props(getprop)
return Stats(
cpuPercent = null,
@@ -80,6 +104,7 @@ class DeviceMonitor(
manufacturer = props["ro.product.manufacturer"],
androidVersion = props["ro.build.version.release"],
sdk = props["ro.build.version.sdk"]?.toIntOrNull(),
+ packages = Parsers.byUid(Parsers.packages(pm)),
)
}
}
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/NetworkStats.kt b/adb/src/main/kotlin/app/tellyscope/adb/NetworkStats.kt
new file mode 100644
index 0000000..31583f1
--- /dev/null
+++ b/adb/src/main/kotlin/app/tellyscope/adb/NetworkStats.kt
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package app.tellyscope.adb
+
+/** Who the TV is talking to, and how much each uid has sent and received since boot. */
+class NetworkStats(private val shell: AdbShell) {
+ /** Live connections to somewhere off the TV; listeners and finished ones are left out. */
+ suspend fun connections(): List<Parsers.TcpSocket> =
+ Parsers.tcpSockets(shell.shell(Commands.SOCKETS).output).filter { it.open }
+
+ /** Bytes per uid; empty when the TV reports neither source. */
+ suspend fun traffic(): Map<Int, Parsers.Traffic> {
+ val (netstats, qtaguid) = Commands.split(shell.shell(Commands.TRAFFIC).output, 2)
+ return Parsers.netstatsTraffic(netstats).ifEmpty { Parsers.qtaguidTraffic(qtaguid) }
+ }
+}
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt b/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt
index fafb5b3..c5b25c7 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt
@@ -101,6 +101,126 @@ object Parsers {
return m.groupValues[1].toInt() * 100_000 + 10_000 + m.groupValues[2].toInt()
}
+ /**
+ * The package a process belongs to, from [byUid] (`pm list packages -U`). The process name wins
+ * (`com.foo:remote` is com.foo, even under the shared system uid); otherwise the app uid's package
+ * whose name starts the process name, else its first. Null for native daemons.
+ */
+ fun owner(p: Process, byUid: Map<Int, List<String>>, known: Set<String> = byUid.values.flatten().toSet()): String? {
+ val base = p.name.substringBefore(':')
+ if (base in known) return base
+ val pkgs = appUid(p.user)?.let { byUid[it] }.orEmpty()
+ return pkgs.firstOrNull { p.name.startsWith(it) } ?: pkgs.firstOrNull()
+ }
+
+ /** Uid → its packages; shared uids hold several. */
+ fun byUid(packages: List<Package>): Map<Int, List<String>> =
+ packages.filter { it.uid != null }.groupBy({ it.uid!! }, { it.name })
+
+ /**
+ * `dumpsys power`, or just its wakefulness lines. Dreaming is a screensaver, so the screen is on.
+ * Null when neither line is there.
+ */
+ fun screenOn(power: String): Boolean? {
+ Regex("mWakefulness=(\\w+)").find(power)?.let { return it.groupValues[1] in setOf("Awake", "Dreaming") }
+ return Regex("mScreenOn=(true|false)").find(power)?.groupValues?.get(1)?.toBooleanStrict()
+ }
+
+ data class TcpSocket(val uid: Int, val remoteIp: String, val remotePort: Int, val state: Int) {
+ /** Loopback or unconnected: nothing leaves the TV. */
+ val local get() = remotePort == 0 || remoteIp.startsWith("127.") || remoteIp == "0:0:0:0:0:0:0:1"
+
+ /** Talking to another machine now: not listening, and not already closed (TIME_WAIT has lost its uid). */
+ val open get() = !local && state != LISTEN && state != TIME_WAIT && state != CLOSE
+
+ val remote get() = if (':' in remoteIp) "[$remoteIp]:$remotePort" else "$remoteIp:$remotePort"
+
+ companion object {
+ /** Kernel TCP states, as /proc/net/tcp numbers them. */
+ const val ESTABLISHED = 0x01
+ const val SYN_SENT = 0x02
+ const val SYN_RECV = 0x03
+ const val TIME_WAIT = 0x06
+ const val CLOSE = 0x07
+ const val LISTEN = 0x0A
+ }
+ }
+
+ /**
+ * `/proc/net/tcp` and `tcp6` rows: `sl local rem st queues timers retrnsmt uid ...`. Addresses are
+ * hex in the kernel's byte order (each 32-bit word little-endian); IPv4-mapped IPv6 comes out as IPv4.
+ */
+ fun tcpSockets(procNet: String): List<TcpSocket> = procNet.lineSequence().mapNotNull { line ->
+ val f = line.trim().split(Regex("\\s+"))
+ if (f.size < 8 || !f[0].endsWith(':')) return@mapNotNull null
+ val remote = f[2].split(':').takeIf { it.size == 2 } ?: return@mapNotNull null
+ val ip = hexIp(remote[0]) ?: return@mapNotNull null
+ val port = remote[1].toIntOrNull(16) ?: return@mapNotNull null
+ val state = f[3].toIntOrNull(16) ?: return@mapNotNull null
+ val uid = f[7].toIntOrNull() ?: return@mapNotNull null
+ TcpSocket(uid, ip, port, state)
+ }.toList()
+
+ private fun hexIp(hex: String): String? {
+ if (hex.length != 8 && hex.length != 32) return null
+ val bytes = hex.chunked(8).flatMap { word ->
+ word.chunked(2).map { it.toIntOrNull(16) ?: return null }.reversed()
+ }
+ val v4 = when {
+ bytes.size == 4 -> bytes
+ bytes.take(10).all { it == 0 } && bytes[10] == 0xff && bytes[11] == 0xff -> bytes.drop(12)
+ else -> null
+ }
+ if (v4 != null) return v4.joinToString(".")
+ return java.net.InetAddress.getByAddress(ByteArray(16) { bytes[it].toByte() }).hostAddress?.substringBefore('%')
+ }
+
+ data class Traffic(val rxBytes: Long, val txBytes: Long)
+
+ /**
+ * Bytes per uid from the `UID stats:` section of `dumpsys netstats --uid`: `ident=... uid=N ...`
+ * lines, each followed by `st=... rb=... tb=...` buckets that add up.
+ */
+ fun netstatsTraffic(dump: String): Map<Int, Traffic> {
+ val out = mutableMapOf<Int, Traffic>()
+ var inUid = false
+ var uid: Int? = null
+ for (line in dump.lineSequence()) {
+ if (line.isNotEmpty() && !line[0].isWhitespace()) {
+ inUid = line.trim() == "UID stats:"
+ uid = null
+ continue
+ }
+ if (!inUid) continue
+ val ident = Regex("\\buid=(-?\\d+)").find(line)
+ if (ident != null) {
+ uid = ident.groupValues[1].toInt()
+ continue
+ }
+ val u = uid ?: continue
+ val rb = Regex("\\brb=(\\d+)").find(line)?.groupValues?.get(1)?.toLong() ?: continue
+ val tb = Regex("\\btb=(\\d+)").find(line)?.groupValues?.get(1)?.toLong() ?: 0
+ val t = out[u] ?: Traffic(0, 0)
+ out[u] = Traffic(t.rxBytes + rb, t.txBytes + tb)
+ }
+ return out
+ }
+
+ /** `/proc/net/xt_qtaguid/stats`, untagged rows only (tagged ones are already in them). */
+ fun qtaguidTraffic(stats: String): Map<Int, Traffic> {
+ val out = mutableMapOf<Int, Traffic>()
+ stats.lineSequence().drop(1).forEach { line ->
+ val f = line.trim().split(Regex("\\s+"))
+ if (f.size < 8 || f[2] != "0x0") return@forEach
+ val uid = f[3].toIntOrNull() ?: return@forEach
+ val rx = f[5].toLongOrNull() ?: return@forEach
+ val tx = f[7].toLongOrNull() ?: return@forEach
+ val t = out[uid] ?: Traffic(0, 0)
+ out[uid] = Traffic(t.rxBytes + rx, t.txBytes + tx)
+ }
+ return out
+ }
+
internal fun sizeKb(s: String): Long? {
val n = s.dropLast(1).toDoubleOrNull()
return when (s.lastOrNull()?.uppercaseChar()) {
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt
index f43a84b..5e0244f 100644
--- a/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt
+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt
@@ -47,4 +47,27 @@ class DeviceMonitorTest {
val hung = AdbShell { kotlinx.coroutines.awaitCancellation() }
assertFailsWith<IOException> { DeviceMonitor(hung).stats().first() }
}
+
+ @Test fun processesCarryTheirPackageAndScreenState() = runTest {
+ val tv = AdbShell { cmd ->
+ when {
+ cmd.startsWith("cat /proc/stat") -> ok("cpu 25 0 0 75 0 0 0 0\n${sep}MemTotal: 2000 kB\nMemAvailable: 500 kB\n")
+ cmd.startsWith("top") -> ok(
+ "PID USER RES %CPU NAME\n2201 u0_a87 312M 3.5 com.google.android.youtube.tv\n512 system 120M 9.0 system_server\n" +
+ "$sep mWakefulness=Asleep\n",
+ )
+ else -> ok("$sep$sep$sep${sep}package:com.google.android.youtube.tv uid:10087\n")
+ }
+ }
+ val s = DeviceMonitor(tv).stats().first()
+ assertEquals(
+ listOf(
+ AppProcess(2201, "com.google.android.youtube.tv", "com.google.android.youtube.tv", 3.5, 312 * 1024),
+ AppProcess(512, "system_server", null, 9.0, 120 * 1024),
+ ),
+ s.processes,
+ )
+ assertEquals(false, s.screenOn)
+ assertEquals(mapOf(10087 to listOf("com.google.android.youtube.tv")), s.packages)
+ }
}
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ParsersTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ParsersTest.kt
index dfeeb75..5bb0bad 100644
--- a/adb/src/test/kotlin/app/tellyscope/adb/ParsersTest.kt
+++ b/adb/src/test/kotlin/app/tellyscope/adb/ParsersTest.kt
@@ -72,4 +72,97 @@ class ParsersTest {
assertEquals("", p["empty"])
assertEquals(273600L, Parsers.uptimeSeconds("273600.52 1000000.00\n"))
}
+
+ @Test fun ownersPreferTheProcessNameThenTheUid() {
+ val byUid = Parsers.byUid(
+ Parsers.packages(
+ "package:com.google.android.youtube.tv uid:10087\npackage:android uid:1000\n" +
+ "package:com.android.settings uid:1000\npackage:com.google.android.gsf uid:10050\n" +
+ "package:com.google.android.gms uid:10050\n",
+ ),
+ )
+ fun owner(user: String, name: String) = Parsers.owner(Parsers.Process(1, user, 1, 0.0, name), byUid)
+ assertEquals("com.google.android.youtube.tv", owner("u0_a87", "com.google.android.youtube.tv:service"))
+ assertEquals("com.android.settings", owner("system", "com.android.settings"))
+ assertEquals("com.google.android.gms", owner("u0_a50", "com.google.android.gms.persistent"))
+ assertEquals("com.google.android.gsf", owner("u0_a50", "com.google.process.gapps"))
+ assertNull(owner("system", "system_server"))
+ assertNull(owner("mediacodec", "media.codec"))
+ }
+
+ @Test fun screenOnFromPower() {
+ assertEquals(true, Parsers.screenOn(" mWakefulness=Awake\n mWakefulnessChanging=false\n"))
+ assertEquals(false, Parsers.screenOn(" mWakefulness=Asleep\n"))
+ assertEquals(false, Parsers.screenOn(" mWakefulness=Dozing\n"))
+ assertEquals(true, Parsers.screenOn(" mWakefulness=Dreaming\n"))
+ assertEquals(false, Parsers.screenOn(" mScreenOn=false\n"))
+ assertNull(Parsers.screenOn(""))
+ }
+
+ @Test fun tcpSocketsDecodeKernelByteOrder() {
+ val tcp = """
+ sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
+ 0: 00000000:1388 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 23456 1
+ 1: 1400000A:B3F2 057100CB:01BB 01 00000000:00000000 02:000A7D8C 00000000 10087 0 34567 2
+ 2: 0100007F:13AD 0100007F:9C40 01 00000000:00000000 00:00000000 00000000 10050 0 45678 1
+ 3: 1400000A:B3F4 057100CB:01BB 06 00000000:00000000 03:00000F9A 00000000 0 0 0 3
+ sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
+ 0: 0000000000000000FFFF00001400000A:C350 0000000000000000FFFF0000057100CB:0050 01 00000000:00000000 00:00000000 00000000 10050 0 56789 1
+ 1: 00000000000000000000000001000000:A000 B80D0120000000000000000001000000:01BB 02 00000000:00000000 00:00000000 00000000 10087 0 67890 1
+ 2: 00000000000000000000000001000000:A002 00000000000000000000000001000000:1F90 01 00000000:00000000 00:00000000 00000000 10087 0 78901 1
+ """.trimIndent()
+ val remote = listOf(203, 0, 113, 5).joinToString(".") // built, so it reads as a sample address
+ val all = Parsers.tcpSockets(tcp)
+ assertEquals(7, all.size)
+ assertEquals(Parsers.TcpSocket(10087, remote, 443, Parsers.TcpSocket.ESTABLISHED), all[1])
+ assertEquals(Parsers.TcpSocket(10050, remote, 80, Parsers.TcpSocket.ESTABLISHED), all[4])
+ assertEquals("2001:db8:0:0:0:0:0:1", all[5].remoteIp)
+ assertEquals("[2001:db8:0:0:0:0:0:1]:443", all[5].remote)
+ // The listener, both loopbacks and the TIME_WAIT row aren't open connections.
+ assertEquals(listOf(10087, 10050, 10087), all.filter { it.open }.map { it.uid })
+ }
+
+ @Test fun netstatsSumsUidBucketsOnly() {
+ val dump = """
+ Dev stats:
+ History since boot:
+ ident=[{type=WIFI, subType=COMBINED}] uid=-1 set=ALL tag=0x0
+ NetworkStatsHistory: bucketDuration=3600
+ st=1697990400 rb=999 rp=1 tb=999 tp=1 op=0
+ UID stats:
+ Pending bytes: 0
+ History since boot:
+ ident=[{type=WIFI, subType=COMBINED}] uid=10087 set=DEFAULT tag=0x0
+ NetworkStatsHistory: bucketDuration=7200
+ st=1697990400 rb=1048576 rp=900 tb=2048 tp=10 op=0
+ st=1697997600 rb=1048576 rp=900 tb=0 tp=0 op=0
+ ident=[{type=WIFI, subType=COMBINED}] uid=10087 set=FOREGROUND tag=0x0
+ NetworkStatsHistory: bucketDuration=7200
+ st=1697990400 rb=100 rp=1 tb=100 tp=1 op=0
+ ident=[{type=1, ratType=COMBINED}] uid=1000 set=DEFAULT tag=0x0
+ NetworkStatsHistory: bucketDuration=7200
+ st=1697990400 rb=5 rp=1 tb=6 tp=1 op=0
+ UID tag stats:
+ History since boot:
+ ident=[{type=WIFI}] uid=10087 set=DEFAULT tag=0xffffff01
+ NetworkStatsHistory: bucketDuration=7200
+ st=1697990400 rb=777 rp=1 tb=777 tp=1 op=0
+ """.trimIndent()
+ assertEquals(
+ mapOf(10087 to Parsers.Traffic(2_097_252, 2_148), 1000 to Parsers.Traffic(5, 6)),
+ Parsers.netstatsTraffic(dump),
+ )
+ assertEquals(emptyMap(), Parsers.netstatsTraffic("Can't find service: netstats\n"))
+ }
+
+ @Test fun qtaguidSkipsTaggedRows() {
+ val stats = """
+ idx iface acct_tag_hex uid_tag_int cnt_set rx_bytes rx_packets tx_bytes tx_packets
+ 2 wlan0 0x0 10087 0 1000 10 200 2
+ 3 wlan0 0x0 10087 1 500 5 100 1
+ 4 wlan0 0x3e800000000 10087 0 999 9 999 9
+ 5 eth0 0x0 0 0 40 1 60 1
+ """.trimIndent()
+ assertEquals(mapOf(10087 to Parsers.Traffic(1500, 300), 0 to Parsers.Traffic(40, 60)), Parsers.qtaguidTraffic(stats))
+ }
}
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index 57d1fe5..d0a9319 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -18,6 +18,7 @@ import app.tellyscope.adb.Connector
import app.tellyscope.adb.DeviceLink
import app.tellyscope.adb.LabelHelper
import app.tellyscope.adb.LanScanner
+import app.tellyscope.adb.NetworkStats
import app.tellyscope.adb.Parsers
import app.tellyscope.adb.Protected
import app.tellyscope.adb.ProtectedReason
@@ -48,10 +49,8 @@ import app.tellyscope.adb.DeviceState as AdbState
import app.tellyscope.adb.ScanHit as AdbHit
/**
- * [DeviceSource] on real TVs through `:adb`. Device id is the TV's IP. Known devices live for the
- * app process only (persisting them is a later slice), and `procs` / network details beyond the
- * IP are empty for now: slice 1 is scan → connect → live CPU/RAM. App names and icons come from
- * the label helper through [AppNames].
+ * [DeviceSource] on real TVs through `:adb`. Device id is the TV's IP. Wi-Fi name, signal, MAC and
+ * link speed are empty for now. App names and icons come from the label helper through [AppNames].
*/
class AdbDeviceSource(context: Context) : DeviceSource {
private val appContext = context.applicationContext
@@ -240,8 +239,8 @@ class AdbDeviceSource(context: Context) : DeviceSource {
storageTotalGb = s.storage?.let { it.totalKb / 1_048_576.0 },
tempC = s.temperatureC?.toInt(),
uptimeSeconds = s.uptimeSeconds ?: 0,
- screenOn = null,
- procs = emptyList(),
+ screenOn = s.screenOn,
+ procs = s.processes.map { Proc(it.pid, it.name, it.packageName, it.cpuPercent, (it.rssKb / 1024).toInt()) },
)
}
}
@@ -283,17 +282,40 @@ class AdbDeviceSource(context: Context) : DeviceSource {
}
override suspend fun network(deviceId: String): NetworkInfo {
- val out = session(deviceId).shell("ip -o -4 addr show").output
+ val shell = session(deviceId)
+ val out = shell.shell("ip -o -4 addr show").output
val line = out.lineSequence().firstOrNull { "inet " in it && " lo " !in it }
val f = line?.trim()?.split(Regex("\\s+")).orEmpty()
+ val packages = links[deviceId]?.stats?.value?.packages.orEmpty()
return NetworkInfo(
iface = f.getOrElse(1) { "" },
ip = f.getOrNull(3)?.substringBefore('/') ?: deviceId,
mac = null, ssid = null, rssi = null, linkMbps = null,
- sockets = emptyList(), traffic = emptyList(),
+ sockets = NetworkStats(shell).connections().map { Socket(uidLabel(it.uid, packages), it.remote, tcpState(it.state)) },
+ traffic = traffic(deviceId, packages),
)
}
+ /** `dumpsys netstats` is long, so data used is read at most once a minute per TV. */
+ private val trafficCache = ConcurrentHashMap<String, Pair<Long, List<AppTraffic>>>()
+
+ private suspend fun traffic(deviceId: String, packages: Map<Int, List<String>>): List<AppTraffic> {
+ val now = System.currentTimeMillis()
+ trafficCache[deviceId]?.takeIf { now - it.first < 60_000 }?.let { return it.second }
+ val list = NetworkStats(session(deviceId)).traffic().filterKeys { it >= 0 }.entries
+ .groupBy({ uidLabel(it.key, packages) }, { it.value })
+ .map { (app, ts) -> AppTraffic(app, (ts.sumOf { it.rxBytes } shr 20).toInt(), (ts.sumOf { it.txBytes } shr 20).toInt()) }
+ .filter { it.rxMb + it.txMb > 0 }
+ trafficCache[deviceId] = now to list
+ return list
+ }
+
+ /** An app's name for a uid; system uids and unknown ones read as Android system. */
+ private fun uidLabel(uid: Int, packages: Map<Int, List<String>>): String {
+ val pkg = packages[uid]?.takeIf { uid % 100_000 >= 10_000 }?.firstOrNull() ?: return AppNames.SYSTEM
+ return labels[pkg] ?: AppNames.fallback(pkg)
+ }
+
override suspend fun act(deviceId: String, action: Action, packageName: String, undoing: Long?): HistoryEntry {
val shell = session(deviceId)
// Before the first change on a TV, note what was already off: Restore must leave those alone.
@@ -449,6 +471,12 @@ class AdbDeviceSource(context: Context) : DeviceSource {
)
}
+ private fun tcpState(st: Int) = when (st) {
+ Parsers.TcpSocket.ESTABLISHED -> "established"
+ Parsers.TcpSocket.SYN_SENT, Parsers.TcpSocket.SYN_RECV -> "connecting"
+ else -> "closing"
+ }
+
/** Copy from the protected-apps table in the UX copy doc. */
private fun reasonText(r: ProtectedReason) = when (r) {
ProtectedReason.HOME_SCREEN -> "this is your home screen"
diff --git a/app/src/main/java/app/tellyscope/data/AppNames.kt b/app/src/main/java/app/tellyscope/data/AppNames.kt
index 76aeb59..511fbae 100644
--- a/app/src/main/java/app/tellyscope/data/AppNames.kt
+++ b/app/src/main/java/app/tellyscope/data/AppNames.kt
@@ -63,6 +63,9 @@ class AppNames(private val dir: File) {
*/
fun fallback(pkg: String): String = KnownLabels[pkg] ?: humanise(pkg)
+ /** What native daemons and system uids are listed as, in place of an app name. */
+ const val SYSTEM = "Android system"
+
private val GENERIC = setOf("com", "net", "org", "io", "co", "android", "google", "tv", "app", "apps")
/** Makers whose name isn't simply capitalised. */
diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.kt
index 923bd34..3edde23 100644
--- a/app/src/main/java/app/tellyscope/ui/Copy.kt
+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt
@@ -6,6 +6,7 @@ import app.tellyscope.adb.InstallKind
import app.tellyscope.adb.InstallRefusal
import app.tellyscope.adb.TvFolder
import app.tellyscope.data.Action
+import app.tellyscope.data.AppNames
import app.tellyscope.data.DeviceState
import app.tellyscope.data.Snapshot
@@ -81,7 +82,7 @@ object Copy {
else -> "Disabled $done of $of apps; the TV refused the rest. Undo any of them from History."
}
- const val ANDROID_SYSTEM = "Android system"
+ const val ANDROID_SYSTEM = AppNames.SYSTEM
/** The word next to the status dot, so the state never rests on colour alone. */
fun state(s: DeviceState) = when (s) {
diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
index d47e6a5..2e97b4e 100644
--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
@@ -768,7 +768,7 @@ private fun ProcessTable(procs: List<Proc>, apps: List<AppInfo>, q: String) {
@Composable
private fun NetworkBlock(n: NetworkInfo, q: String) {
if (q.isEmpty()) {
- KeyValue("Connection", listOfNotNull(if (n.iface == "wifi") "Wi-Fi" else "Ethernet", n.ssid).joinToString(" · "))
+ KeyValue("Connection", listOfNotNull(if (n.iface == "wifi" || n.iface.startsWith("wlan")) "Wi-Fi" else "Ethernet", n.ssid).joinToString(" · "))
n.rssi?.let { r -> KeyValue("Signal", signalWord(r).replaceFirstChar(Char::uppercase)) }
Details(
listOfNotNull(