Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
fix(bench): avoid replaying actions after lost ADB responses
Sandiv Dathunarachchi69073ddcf116
diff --git a/tests/test_bench_accessibility.py b/tests/test_bench_accessibility.pyindex b71b3a607..7f1203060 100644--- a/tests/test_bench_accessibility.py+++ b/tests/test_bench_accessibility.py@@ -32,7 +32,7 @@ class FakeTV:self.setting = settingself.commands = []- def shell(self, command, read_timeout_s=None):+ def shell(self, command, read_timeout_s=None, *, retry=False):self.commands.append(command)if command.startswith("settings get secure enabled_accessibility_services"):return self.setting@@ -82,17 +82,17 @@ class ColdStartOrderTest(unittest.TestCase):order = []original_shell = tv.shell- def spy(command, read_timeout_s=None):+ def spy(command, read_timeout_s=None, *, retry=False):if command.startswith("settings put secure enabled_accessibility_services"):order.append("restore")elif command.startswith("am start -W ") and command.endswith("-n com.gathin.tvhome/.MainActivity"):order.append("measure")- return original_shell(command, read_timeout_s)+ return original_shell(command, read_timeout_s, retry=retry)tv.shell = spy# `am start -W` has to answer something with a WaitTime.- def shell_with_start(command, read_timeout_s=None):- out = spy(command, read_timeout_s)+ def shell_with_start(command, read_timeout_s=None, *, retry=False):+ out = spy(command, read_timeout_s, retry=retry)if command.startswith("am start -W"):return "WaitTime: 420"return outdiff --git a/tests/test_bench_connection.py b/tests/test_bench_connection.pyindex 62c2e8819..a422d95d8 100644--- a/tests/test_bench_connection.py+++ b/tests/test_bench_connection.py@@ -4,7 +4,7 @@ It used to start tools/tv.py for every shell command: a new Python, a new TCP coADB handshake, several times per key, plus the whole main log pulled back for every key (about100 MB on a TCL C755, 41 s a read). Through arelay one full run took over 45 minutes. Now the TV class connects once with tools/tv.py's client-and reuses it, reopening it once if it drops; only the log's newest lines are read, filtered on the+and reuses it, reopening it once for a safe query; only the log's newest lines are read, filtered on theTV, and not at all once the first keys show the TV doesn't log them; and the key loop looks up Home once. --host also has to reach the client: the old subprocesses only read TV_HOST. It reaches it as TV_HOST/TV_PORT, and the target the run keeps is the one tools/tv.py made of those two (it splits `host:port` and checks the range), not the arguments again.A TV that cannot be reached is the other half, and the run's first connect is also the one it reopens@@ -112,7 +112,7 @@ class OneConnectionTest(unittest.TestCase):def test_a_dropped_connection_is_reopened_once(self):first, second = FakeDevice(fail_first=True), FakeDevice({"echo": b"ok"})tv, client = self.tv_with(first, second)- self.assertEqual(tv.shell("echo ok"), "ok")+ self.assertEqual(tv.shell("echo ok", retry=True), "ok")self.assertEqual(client.connects, 2)self.assertTrue(first.closed)@@ -135,7 +135,7 @@ class FakeTV:self.log = logself.commands = []- def shell(self, command):+ def shell(self, command, *, retry=False):self.commands.append(command)if "framestats" in command:return "Uptime: 2000\n"diff --git a/tests/test_bench_counts.py b/tests/test_bench_counts.pyindex 9eeba1e71..db6cc4d21 100644--- a/tests/test_bench_counts.py+++ b/tests/test_bench_counts.py@@ -71,7 +71,7 @@ class FakeTV:def focused_window(self):return "u0 com.gathin.tvhome/.MainActivity"- def shell(self, command):+ def shell(self, command, *, retry=False):self.commands.append(command)if command.startswith("pidof"):return "1234\n"diff --git a/tests/test_bench_framestats.py b/tests/test_bench_framestats.pyindex 9297e2f6e..f78492477 100644--- a/tests/test_bench_framestats.py+++ b/tests/test_bench_framestats.py@@ -70,7 +70,7 @@ class FrameStatsTest(unittest.TestCase):tv = mock.Mock()tv.home_component.return_value = "com.gathin.tvhome/.MainActivity"tv.package_of.return_value = "com.gathin.tvhome"- tv.shell.side_effect = answers.__getitem__+ tv.shell.side_effect = lambda command, *, retry=False: answers[command]with mock.patch.object(bench.time, "sleep"):self.assertEqual(bench.measure_key(tv, 22), (20.0, 20.0, 2, 0))diff --git a/tests/test_bench_home.py b/tests/test_bench_home.pyindex c6bb49cdf..88ea3381e 100644--- a/tests/test_bench_home.py+++ b/tests/test_bench_home.py@@ -33,7 +33,7 @@ class LogTV:self.logs = iter(logs)self.commands = []- def shell(self, command):+ def shell(self, command, *, retry=False):self.commands.append(command)if command.startswith("logcat -d "):logcat, separator, grep = command.partition(" | grep ")diff --git a/tests/test_bench_other_app.py b/tests/test_bench_other_app.pyindex 8dd8d929b..c852ad241 100644--- a/tests/test_bench_other_app.py+++ b/tests/test_bench_other_app.py@@ -31,7 +31,7 @@ class AnsweringTV:def package_of(self, component):return component.split("/", 1)[0]- def shell(self, command):+ def shell(self, command, *, retry=False):return next((v for k, v in self.answers.items() if k in command), "")diff --git a/tests/test_bench_pss.py b/tests/test_bench_pss.pyindex 7903b0591..cfbfbe9be 100644--- a/tests/test_bench_pss.py+++ b/tests/test_bench_pss.py@@ -7,7 +7,7 @@ from tools import benchclass PssSummaryTest(unittest.TestCase):def read(self, output):- return bench.pss_of(SimpleNamespace(shell=lambda command: output), "com.gathin.tvhome")+ return bench.pss_of(SimpleNamespace(shell=lambda command, *, retry=False: output), "com.gathin.tvhome")def test_android_8_summary(self):# ActivityThread.java, android-8.0.0_r1, lines 2547-2554.diff --git a/tests/test_bench_replay.py b/tests/test_bench_replay.pynew file mode 100644index 000000000..1ef0e2ca9--- /dev/null+++ b/tests/test_bench_replay.py@@ -0,0 +1,316 @@+"""Lost ADB responses must not replay benchmark actions; all transports and effects are offline."""+from collections import Counter+import contextlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+import types+import unittest+from unittest import mock++from tests import test_bench_framestats as frames+from tests import test_bench_home as home+from tools import bench++PACKAGE = 'com.gathin.tvhome'+COMPONENT = PACKAGE + '/.MainActivity'+OTHER = 'com.android.tv.settings/.MainSettings'+SERVICE = PACKAGE + '/.KeyRemapService'+START = 'am start -W -a android.intent.action.MAIN -c android.intent.category.HOME -n ' + COMPONENT+++class ReplayState:+ def __init__(self, fail=None, phase='after'):+ self.fail, self.phase = fail, phase+ self.dropped = False+ self.effects = Counter()+ self.events = []+ self.connects = self.closes = self.focus = 0+ self.running = True+ self.services = SERVICE++ def execute(self, command):+ self.effects[command] += 1+ self.events.append('executed: ' + command)+ if command == 'input keyevent 22':+ self.focus += 1+ if command.startswith('am force-stop '):+ self.running = False+ self.services = ''+ if command == START:+ wait = 3 if self.running else 80+ self.running = True+ return 'WaitTime: ' + str(wait)+ if command.startswith('am start '):+ return 'WaitTime: 5'+ if command == 'settings get secure enabled_accessibility_services':+ return self.services+ if command.startswith('settings put secure enabled_accessibility_services '):+ self.services = command.split(' ', 4)[4]+ if 'resolve-activity' in command:+ return COMPONENT+ if command.startswith('dumpsys package '):+ return 'versionName=fixture'+ if command == 'dumpsys window':+ return 'mCurrentFocus=Window{abc u0 ' + COMPONENT + '}'+ if command.endswith(' framestats'):+ header = frames.HEADERS['android-14']+ return ('Uptime: 2000\nTotal frames rendered: 1\nJanky frames: 0\n'+ + frames.profile(header, frames.frame(header)))+ if command.startswith('dumpsys gfxinfo '):+ return 'Uptime: 1000\n'+ if command.startswith('logcat -d -b main -b events'):+ return home.home() + '\n' + home.resume()+ if command.startswith('logcat -d '):+ return 'injectKeyEvent action=ACTION_DOWN KEYCODE_DPAD_RIGHT eventTime=1000'+ if command.startswith('head -1 /proc/stat'):+ return 'cpu 1000 0 1000 8000 0 0 0 0 0 0\n'+ if command.startswith('dumpsys meminfo '):+ return 'TOTAL PSS: 65536'+ if command.startswith(('input keyevent ', 'am force-stop ', 'settings put secure ',+ 'logcat -c ', 'getprop ', 'pidof ')):+ return ''+ raise AssertionError(f'unexpected fake command: {command}')++ def snapshot(self):+ return dict(effects=dict(self.effects), events=self.events, connects=self.connects,+ closes=self.closes, focus=self.focus, running=self.running, services=self.services)+++class Device:+ def __init__(self, state):+ self.state = state++ def shell(self, command, read_timeout_s=None, decode=True):+ state = self.state+ drop = command == state.fail and not state.dropped+ if drop:+ state.dropped = True+ if state.phase == 'before':+ state.events.append('lost before execution: ' + command)+ raise ConnectionResetError('lost command response')+ reply = state.execute(command)+ if drop:+ state.events.append('acknowledgement lost: ' + command)+ raise ConnectionResetError('lost command response')+ return reply.encode('utf-8')++ def close(self):+ self.state.closes += 1++def fake_client(state):+ client = types.ModuleType('tv')+ client.HOST, client.PORT = 'fake-tv', 5555+ client.connect_error = lambda error: None+ def connect():+ state.connects += 1+ state.events.append('connect ' + str(state.connects))+ return Device(state)+ client.connect = connect+ return client+++def connected(state):+ client = fake_client(state)+ with mock.patch.dict(sys.modules, {"tv": client}), mock.patch.dict(os.environ):+ tv = bench.TV("fake-tv")+ try:+ yield tv, client+ finally:+ tv.close()+++class RetryPolicyTest(unittest.TestCase):+ def test_commands_with_unknown_completion_are_not_replayed(self):+ commands = ("input keyevent 22", "input keyevent 3", START,+ "am force-stop " + PACKAGE,+ "settings put secure enabled_accessibility_services " + SERVICE,+ "settings put secure accessibility_enabled 1", "logcat -c -b main",+ "dumpsys gfxinfo " + PACKAGE + " reset")+ for command in commands:+ for phase in ("before", "after"):+ with self.subTest(command=command, phase=phase):+ state = ReplayState(command, phase)+ with connected(state) as (tv, client):+ error = None+ try:+ tv.shell(command)+ except ConnectionResetError as failure:+ error = failure+ self.assertEqual(state.effects[command], int(phase == "after"))+ if command == "input keyevent 22":+ self.assertEqual(state.focus, int(phase == "after"))+ self.assertIsInstance(error, ConnectionResetError)+ self.assertEqual(state.connects, 1)+ self.assertEqual(state.closes, 1)+ self.assertIsNone(tv.client)++ def test_read_queries_retry_and_reuse_the_reopened_connection(self):+ command = "dumpsys package " + PACKAGE+ for phase in ("before", "after"):+ with self.subTest(phase=phase):+ state = ReplayState(command, phase)+ with connected(state) as (tv, client):+ self.assertEqual(tv.version_of(PACKAGE), "fixture")+ self.assertEqual(tv.version_of(PACKAGE), "fixture")+ tv.shell("input keyevent 22")+ self.assertEqual(state.connects, 2)+ self.assertEqual(state.effects[command], 2 + int(phase == "after"))+ self.assertEqual(state.focus, 1)++ def test_a_later_read_connects_without_replaying_the_failed_action(self):+ state = ReplayState("input keyevent 22")+ with connected(state) as (tv, client):+ error = None+ try:+ tv.shell("input keyevent 22")+ except ConnectionResetError as failure:+ error = failure+ self.assertEqual(state.focus, 1)+ self.assertIsInstance(error, ConnectionResetError)+ self.assertEqual(tv.version_of(PACKAGE), "fixture")+ self.assertEqual(state.connects, 2)+ self.assertEqual(state.effects["input keyevent 22"], 1)++ def test_a_connect_failure_retries_before_submitting_the_command(self):+ state = ReplayState()+ with connected(state) as (tv, client):+ with mock.patch.object(client, "connect", side_effect=[+ ConnectionResetError("handshake failed"), Device(state)]) as connect:+ tv.shell("input keyevent 22")+ self.assertEqual(connect.call_count, 2)+ self.assertEqual(state.focus, 1)+ self.assertEqual(state.effects["input keyevent 22"], 1)++ def test_read_retry_exhaustion_closes_and_propagates_the_error(self):+ command = "dumpsys package " + PACKAGE+ state = ReplayState(command)+ with connected(state) as (tv, client):+ original_connect = client.connect++ def connect():+ state.dropped = False+ return original_connect()++ client.connect = connect+ with self.assertRaises(ConnectionResetError):+ tv.version_of(PACKAGE)+ self.assertEqual(state.effects[command], 2)+ self.assertEqual(state.connects, 2)+ self.assertEqual(state.closes, 2)+ self.assertIsNone(tv.client)++ def test_actual_measurements_abort_and_cold_cleanup_still_restores_services(self):+ cases = (+ ("reset", "dumpsys gfxinfo " + PACKAGE + " reset",+ lambda tv: bench.measure_key(tv, 22, package=PACKAGE)),+ ("key", "input keyevent 22", lambda tv: bench.measure_key(tv, 22, package=PACKAGE)),+ ("cold", START, lambda tv: bench.cold_start(tv, COMPONENT, 1)),+ ("stop", "am force-stop " + PACKAGE, lambda tv: bench.cold_start(tv, COMPONENT, 1)),+ ("home", "input keyevent 3", lambda tv: bench.return_to_home(tv, COMPONENT, 1)),+ ("restore", "settings put secure enabled_accessibility_services " + SERVICE,+ lambda tv: bench.restore_accessibility(tv, PACKAGE, [SERVICE])),+ )+ for label, command, measure in cases:+ with self.subTest(operation=label):+ state = ReplayState(command)+ if label == "restore":+ state.services = ""+ with connected(state) as (tv, client), mock.patch.object(bench.time, "sleep"):+ tv._other_app = OTHER+ error = None+ try:+ measure(tv)+ except ConnectionResetError as failure:+ error = failure+ self.assertEqual(state.effects[command], 1)+ self.assertIsInstance(error, ConnectionResetError)+ if label in ("cold", "stop", "restore"):+ self.assertEqual(state.services, SERVICE)+ if label == "home":+ self.assertEqual(state.effects[+ "logcat -d -b main -b events -v epoch | grep -e injectKeyEvent "+ "-e am_on_resume_called -e wm_on_resume_called"], 0)++ def test_retrying_a_frame_read_does_not_inject_another_key(self):+ command = "dumpsys gfxinfo " + PACKAGE + " framestats"+ state = ReplayState(command)+ with connected(state) as (tv, client), mock.patch.object(bench.time, "sleep"):+ self.assertEqual(bench.measure_key(tv, 22, package=PACKAGE), (20.0, 20.0, 1, 0))+ self.assertEqual(state.effects[command], 2)+ self.assertEqual(state.effects["input keyevent 22"], 1)+ self.assertEqual(state.focus, 1)+++CLI = """from pathlib import Path+import json,runpy,sys+from unittest import mock+root,script,folder,command,phase,state_path=sys.argv[1:]+sys.path.insert(0,root)+sys.path.insert(0,str(Path(root)/'tests'))+from test_bench_replay import ReplayState,fake_client+state=ReplayState(command or None,phase)+sys.argv=[script,'--host','fake-tv','--out-dir',folder,'--app','com.android.tv.settings/.MainSettings','--keys','1','--series','1','--cold','1','--returns','1','--idle','1']+with mock.patch.dict(sys.modules,{'tv':fake_client(state)}),mock.patch('time.sleep'):+ try:runpy.run_path(script,run_name='__main__')+ finally:Path(state_path).write_text(json.dumps(state.snapshot()),encoding='utf-8')+"""+++class BenchmarkReplayCLITest(unittest.TestCase):+ def run_benchmark(self, folder, command="", phase="after", existing=False):+ root = Path(__file__).resolve().parents[1]+ script = folder / "bench.py"+ shutil.copyfile(root / "tools" / "bench.py", script)+ result = folder / "output" / "result.json"+ previous = b'{"previous_run": true}\n'+ if existing:+ result.parent.mkdir()+ result.write_bytes(previous)+ state_path = folder / "state.json"+ run = subprocess.run([sys.executable, "-B", "-c", CLI, str(root), str(script),+ str(result.parent), command, phase, str(state_path)],+ capture_output=True, text=True, timeout=60)+ return run, json.loads(state_path.read_text(encoding="utf-8")), result, previous++ def test_normal_benchmark_keeps_one_key_and_a_cold_start(self):+ with tempfile.TemporaryDirectory() as tmp:+ run, state, result, _ = self.run_benchmark(Path(tmp))+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)+ self.assertEqual(run.stderr, "")+ self.assertIn("Written:", run.stdout)+ data = json.loads(result.read_text(encoding="utf-8"))+ self.assertEqual(data["keys"], {"series": 1, "per_series": 1, "measured": 1, "lost": 0})+ self.assertEqual(data["response_ms"]["p50"], 20)+ self.assertEqual(data["cold_start_ms"]["p50"], 80)+ self.assertEqual(state["focus"], 1)+ self.assertEqual(state["connects"], 1)+ self.assertEqual(state["services"], SERVICE)++ def test_ambiguous_execution_cannot_publish_a_successful_result(self):+ for command in ("input keyevent 22", START):+ for phase in ("before", "after"):+ for existing in (False, True):+ with self.subTest(command=command, phase=phase, existing=existing):+ with tempfile.TemporaryDirectory() as tmp:+ run, state, result, previous = self.run_benchmark(+ Path(tmp), command, phase, existing)+ self.assertEqual(state["effects"].get(command, 0), int(phase == "after"))+ self.assertEqual(run.returncode, 1, run.stdout + run.stderr)+ self.assertIn("ConnectionResetError", run.stderr)+ self.assertNotIn("Written:", run.stdout)+ if existing:+ self.assertEqual(result.read_bytes(), previous)+ else:+ self.assertFalse(result.exists())+ self.assertEqual(sorted(p.name for p in result.parent.iterdir()),+ ["result.json"] if existing else [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/bench.py b/tools/bench.pyindex a5f97fa10..5d79934be 100644--- a/tools/bench.py+++ b/tools/bench.py@@ -147,20 +147,25 @@ class TV:raise SystemExit(2) from errorreturn self.client- def shell(self, command):+ def shell(self, command, *, retry=False):"""Run one shell command on the TV and return its output; bytes that aren't UTF-8 become U+FFFD.- A dropped connection (the TV went to standby for a moment) is reopened once.+ A connection failure before submission is retried once. After a command is attempted,+ only queries explicitly marked retry=True may be replayed: a missing response does not+ mean the TV did not execute the command."""for attempt in (1, 2):+ command_started = Falsetry:- out = self._connect().shell(command, read_timeout_s=120.0, decode=False)+ client = self._connect()+ command_started = True+ out = client.shell(command, read_timeout_s=120.0, decode=False)return out.decode("utf-8", "replace") if isinstance(out, bytes) else (out or "")except SystemExit:raiseexcept Exception:self.close()- if attempt == 2:+ if attempt == 2 or (command_started and not retry):raisedef close(self):@@ -178,7 +183,7 @@ class TV:"""The component that answers HOME, e.g. com.gathin.tvhome/.MainActivity."""out = self.shell("cmd package resolve-activity --brief -a android.intent.action.MAIN "- "-c android.intent.category.HOME")+ "-c android.intent.category.HOME", retry=True)lines = [line.strip() for line in out.splitlines() if "/" in line]return lines[-1] if lines else None@@ -188,7 +193,7 @@ class TV:The dump has several "mCurrentFocus"/"mFocusedApp" lines; only the one that names awindow counts, and a popup (a menu left open) is a window of its own."""- out = self.shell("dumpsys window")+ out = self.shell("dumpsys window", retry=True)for line in out.splitlines():match = re.search(r"mCurrentFocus=Window\{[^}]*\s(\S+?)\}", line)if match:@@ -209,7 +214,7 @@ class TV:return component.split("/", 1)[0]def version_of(self, package):- out = self.shell(f"dumpsys package {package}")+ out = self.shell(f"dumpsys package {package}", retry=True)match = re.search(r"versionName=(\S+)", out)return match.group(1) if match else "?"@@ -243,7 +248,7 @@ def key_event_time(tv, keycode, binary=None):state = vars(tv).setdefault("_key_log", {"seen": False, "misses": 0})if not state["seen"] and state["misses"] >= KEY_LOG_PROBES:return None- out = tv.shell("logcat -d -b main -t 2000 | grep injectKeyEvent")+ out = tv.shell("logcat -d -b main -t 2000 | grep injectKeyEvent", retry=True)name = KEYCODE_NAMES.get(keycode, f"keyCode={keycode}")for line in reversed(out.splitlines()):if "injectKeyEvent" in line and "action=ACTION_DOWN" in line and name in line:@@ -261,7 +266,7 @@ def android_uptime(tv, package=None, binary=None):clock: it counts the time the device spent suspended, so it runs hours ahead of the frames."""what = f"dumpsys gfxinfo {package}" if package else "dumpsys gfxinfo"- out = tv.shell(what)+ out = tv.shell(what, retry=True)match = re.search(r"^Uptime:\s*(\d+)", out, re.M)return int(match.group(1)) if match else None@@ -278,7 +283,7 @@ def measure_key(tv, keycode, binary=None, package=None):t_before = int(match.group(1))tv.shell(f"input keyevent {keycode}")time.sleep(1.0)- stats = tv.shell(f"dumpsys gfxinfo {package} framestats")+ stats = tv.shell(f"dumpsys gfxinfo {package} framestats", retry=True)t_after = Nonematch = re.search(r"^Uptime:\s*(\d+)", stats, re.M)if match:@@ -366,9 +371,10 @@ def other_app(tv):if tv._other_app:return tv._other_applauncher = tv.package_of(tv.home_component() or "")- candidates = tv.shell("cmd package resolve-activity --brief -a android.settings.SETTINGS").splitlines()+ candidates = tv.shell(+ "cmd package resolve-activity --brief -a android.settings.SETTINGS", retry=True).splitlines()candidates += tv.shell("cmd package query-activities --brief -a android.intent.action.MAIN "- "-c android.intent.category.LEANBACK_LAUNCHER").splitlines()+ "-c android.intent.category.LEANBACK_LAUNCHER", retry=True).splitlines()for line in candidates:line = line.strip()if COMPONENT.match(line) and not line.startswith(("android/", launcher + "/")) \@@ -380,7 +386,7 @@ def other_app(tv):def accessibility_services(tv, package):"""The accessibility services enabled for a package, as the setting holds them."""- out = tv.shell("settings get secure enabled_accessibility_services")+ out = tv.shell("settings get secure enabled_accessibility_services", retry=True)return [part.strip() for part in out.split(":") if part.strip().startswith(package + "/")]@@ -409,7 +415,7 @@ def restore_accessibility(tv, package, services):"""if not services:return- current = tv.shell("settings get secure enabled_accessibility_services").strip()+ current = tv.shell("settings get secure enabled_accessibility_services", retry=True).strip()if current == "null":current = ""merged = [part for part in current.split(":") if part]@@ -481,7 +487,7 @@ def return_to_home(tv, component, repeats):tv.shell("input keyevent 3")time.sleep(3)out = tv.shell("logcat -d -b main -b events -v epoch | grep -e injectKeyEvent "- "-e am_on_resume_called -e wm_on_resume_called")+ "-e am_on_resume_called -e wm_on_resume_called", retry=True)key_at = resume_at = Nonefor line in out.splitlines():# The log indents its lines, so the timestamp is not at the start of the line.@@ -505,7 +511,7 @@ def return_to_home(tv, component, repeats):def launcher_pid(tv, package):"""The pid of the launcher process, or None."""- out = tv.shell(f"pidof {package}").strip()+ out = tv.shell(f"pidof {package}", retry=True).strip()if not out:return Nonereturn out.split()[0]@@ -514,7 +520,7 @@ def launcher_pid(tv, package):def idle_cpu(tv, package, seconds):"""The CPU of the whole device and of the launcher, over `seconds`, from /proc/stat."""def sample():- return tv.shell("head -1 /proc/stat; cat /proc/[0-9]*/stat 2>/dev/null").splitlines()+ return tv.shell("head -1 /proc/stat; cat /proc/[0-9]*/stat 2>/dev/null", retry=True).splitlines()def parse(lines):for line in lines:@@ -555,7 +561,7 @@ def idle_cpu(tv, package, seconds):def pss_of(tv, package):- out = tv.shell(f"dumpsys meminfo {package}")+ out = tv.shell(f"dumpsys meminfo {package}", retry=True)match = re.search(r"^\s*TOTAL(?: PSS)?:\s+(\d+)\b", out, re.M)return int(match.group(1)) // 1024 if match else None@@ -773,10 +779,10 @@ def main():"launcher": component, "version": version, "package": package,"host": args.host,"environment": {- "android_release": tv.shell("getprop ro.build.version.release").strip(),- "sdk": tv.shell("getprop ro.build.version.sdk").strip(),- "model": tv.shell("getprop ro.product.model").strip(),- "fingerprint": tv.shell("getprop ro.build.fingerprint").strip(),+ "android_release": tv.shell("getprop ro.build.version.release", retry=True).strip(),+ "sdk": tv.shell("getprop ro.build.version.sdk", retry=True).strip(),+ "model": tv.shell("getprop ro.product.model", retry=True).strip(),+ "fingerprint": tv.shell("getprop ro.build.fingerprint", retry=True).strip(),},"keys": {"series": args.series, "per_series": args.keys,"measured": len(measured), "lost": len(samples) - len(measured)},