feat(droiddeckctl): thermal and wait cool

Nothing in droiddeckctl reported temperature, so a before/after
comparison could start one run hot and the next cold.

`thermal` reads the battery temperature from dumpsys battery, the
thermal status from dumpsys thermalservice, and each CPU policy's
scaling_max_freq against cpuinfo_max_freq (capped when lower), all
readable over plain adb. `wait cool --below <C>` polls it every 10 s
until the battery is under that temperature, or exits 5 at --timeout.
This commit is contained in:
angelrenefm committed 2026-11-04 00:13:31 +01:00
1 parent f3650d3d37
commit 8e480d0e84
3 files changed
+126 -3

No files matched your search

+55 -2
View File
@@ -362,6 +362,50 @@ def pacing(adb: str, serial: str, seconds: float) -> dict:
return {"ok": True, "command": "pacing", "seconds": round(elapsed, 1), **summary}
THERMAL_STATUS = ["NONE", "LIGHT", "MODERATE", "SEVERE", "CRITICAL", "EMERGENCY", "SHUTDOWN"]
CPUFREQ = "/sys/devices/system/cpu/cpufreq"
def thermal_summary(battery: str, service: str, cpufreq: str) -> dict:
tenths = re.search(r"^\s*temperature:\s*(-?\d+)", battery, re.M)
status = re.search(r"^\s*Thermal Status:\s*(\d+)", service, re.M)
level = int(status.group(1)) if status else None
cpu: dict[str, dict] = {}
for policy, name, khz in re.findall(r"/(policy\d+)/(scaling_max_freq|cpuinfo_max_freq):(\d+)", cpufreq):
cpu.setdefault(policy, {})["maxKHz" if name == "scaling_max_freq" else "hardwareMaxKHz"] = int(khz)
for limits in cpu.values():
if "maxKHz" in limits and "hardwareMaxKHz" in limits:
limits["capped"] = limits["maxKHz"] < limits["hardwareMaxKHz"]
return {
"batteryC": int(tenths.group(1)) / 10 if tenths else None,
"status": level,
"statusName": THERMAL_STATUS[level] if level is not None and level < len(THERMAL_STATUS) else None,
"cpu": dict(sorted(cpu.items(), key=lambda item: int(item[0][6:]))),
}
def thermal(adb: str, serial: str) -> dict:
def shell(*command: str) -> str:
return run_adb(adb, serial, "shell", *command).stdout.decode(errors="replace")
summary = thermal_summary(shell("dumpsys", "battery"), shell("dumpsys", "thermalservice"),
shell("grep", ".", f"{CPUFREQ}/policy*/scaling_max_freq", f"{CPUFREQ}/policy*/cpuinfo_max_freq"))
return {"ok": True, "command": "thermal", **summary}
def wait_cool(adb: str, serial: str, below: float, timeout: float) -> dict:
started = time.monotonic()
while True:
reading = thermal(adb, serial)
if reading["batteryC"] is None:
raise ControlError("dumpsys battery reports no temperature", "THERMAL_FAILED")
if reading["batteryC"] < below:
return {**reading, "command": "wait", "waitedSeconds": round(time.monotonic() - started, 1)}
remaining = started + timeout - time.monotonic()
if remaining <= 0:
raise ControlError(f"Battery still at {reading['batteryC']:g} °C after {timeout:g} s, wanted below {below:g}",
"TIMEOUT")
time.sleep(min(10.0, remaining))
def start_session(adb: str, serial: str, request: dict) -> dict:
if request.get("mode") == "run":
@@ -531,6 +575,10 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
"sessionId": session.get("id"), "phase": session.get("phase")}, serial)
if command == "wait":
if args.phase == "cool":
if args.below is None:
raise ControlError("wait cool needs --below <°C>", "INVALID_ARGUMENTS")
return add_serial(wait_cool(adb, serial, args.below, args.timeout), serial)
if args.phase == "focused":
if args.app_id is None:
raise ControlError("wait focused needs an app id", "INVALID_ARGUMENTS")
@@ -704,6 +752,9 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if command == "pacing":
return add_serial(pacing(adb, serial, args.seconds), serial)
if command == "thermal":
return add_serial(thermal(adb, serial), serial)
if command == "wake":
run_adb(adb, serial, "shell", "input", "keyevent", "KEYCODE_WAKEUP")
run_adb(adb, serial, "shell", "wm", "dismiss-keyguard")
@@ -739,9 +790,10 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("program")
run.add_argument("arguments", nargs=argparse.REMAINDER)
wait = commands.add_parser("wait", help="wait for a session phase, or for a game to have focus")
wait.add_argument("phase", choices=["ready", "idle", "failed", "focused", "game"])
wait = commands.add_parser("wait", help="wait for a session phase, for a game to have focus, or for the battery to cool")
wait.add_argument("phase", choices=["ready", "idle", "failed", "focused", "game", "cool"])
wait.add_argument("app_id", nargs="?", type=int, help="with focused: the Steam app id")
wait.add_argument("--below", type=float, help="with cool: the battery temperature to get under, in °C")
wait.add_argument("--timeout", type=float, default=90)
stop = commands.add_parser("stop", help="stop the session and wait for IDLE")
@@ -906,6 +958,7 @@ def build_parser() -> argparse.ArgumentParser:
pace = commands.add_parser("pacing", help="frames that reached the screen and their intervals (SurfaceFlinger)")
pace.add_argument("--seconds", type=float, default=30)
commands.add_parser("thermal", help="battery temperature, thermal status and CPU frequency caps")
commands.add_parser("displays", help="the device's displays and their capture ids")
commands.add_parser("wake", help="wake the device and dismiss the keyguard")
return parser
+63
View File
@@ -60,6 +60,16 @@ FAKE_ADB = textwrap.dedent('''\
print(config.get("timestats", ""))
elif args[:2] == ["exec-out", "screencap"]:
sys.stdout.buffer.write(b"\\x89PNG fake")
elif args[:3] == ["shell", "dumpsys", "battery"]:
temperatures = config.get("battery", [""])
count = config.setdefault("counts", {}).get("battery", 0)
config["counts"]["battery"] = count + 1
json.dump(config, open(config_path, "w"))
print(temperatures[min(count, len(temperatures) - 1)])
elif args[:3] == ["shell", "dumpsys", "thermalservice"]:
print(config.get("thermalservice", ""))
elif args[:3] == ["shell", "grep", "."]:
print(config.get("cpufreq", ""))
with open(config["log"], "a") as log:
log.write(json.dumps(entry) + "\\n")
''')
@@ -103,6 +113,25 @@ TIMESTATS_SURFACEVIEW = "SurfaceFlinger TimeStats:\n" + "".join([
])
THERMALSERVICE = textwrap.dedent('''\
IsStatusOverride: false
Thermal Status: 2
Cached temperatures:
\tTemperature{mValue=41.3, mType=3, mName=skin, mStatus=2}
''')
CPUFREQ = textwrap.dedent('''\
/sys/devices/system/cpu/cpufreq/policy0/scaling_max_freq:3532800
/sys/devices/system/cpu/cpufreq/policy6/scaling_max_freq:2918400
/sys/devices/system/cpu/cpufreq/policy0/cpuinfo_max_freq:3532800
/sys/devices/system/cpu/cpufreq/policy6/cpuinfo_max_freq:4473600
''')
def battery(tenths):
return f"Current Battery Service state:\n level: 80\n temperature: {tenths}\n technology: Li-poly"
def state(phase="READY", focused=None, focusable=()):
focus = None if focused is None else {"focusedApp": focused, "focusableApps": list(focusable),
"baselayerAppIds": [], "seq": 1, "t": 0}
@@ -445,6 +474,40 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual(7, code)
self.assertFalse([c for c in self.calls() if c["args"][:1] == ["push"]])
def test_thermal_reads_battery_status_and_cpu_caps(self):
self.configure({}, battery=[battery(386)], thermalservice=THERMALSERVICE, cpufreq=CPUFREQ)
code, out = self.run_ctl("thermal")
self.assertEqual(0, code, out)
self.assertEqual(38.6, out["batteryC"])
self.assertEqual([2, "MODERATE"], [out["status"], out["statusName"]])
self.assertEqual({"policy0": {"maxKHz": 3532800, "hardwareMaxKHz": 3532800, "capped": False},
"policy6": {"maxKHz": 2918400, "hardwareMaxKHz": 4473600, "capped": True}}, out["cpu"])
def test_thermal_without_readings_answers_nulls(self):
code, out = self.run_ctl("thermal")
self.assertEqual(0, code, out)
self.assertEqual([None, None, None, {}], [out["batteryC"], out["status"], out["statusName"], out["cpu"]])
def test_wait_cool_polls_until_the_battery_is_below(self):
self.configure({}, battery=[battery(412), battery(395), battery(379)], thermalservice=THERMALSERVICE)
with unittest.mock.patch.object(ctl.time, "sleep") as slept:
code, out = self.run_ctl("wait", "cool", "--below", "38", "--timeout", "600")
self.assertEqual(0, code, out)
self.assertEqual(["wait", 37.9], [out["command"], out["batteryC"]])
self.assertEqual(2, slept.call_count)
def test_wait_cool_times_out_with_exit_5(self):
self.configure({}, battery=[battery(412)])
code, out = self.run_ctl("wait", "cool", "--below", "38", "--timeout", "0")
self.assertEqual(5, code)
self.assertIn("41.2", out["error"]["message"])
def test_wait_cool_needs_below_and_a_battery_temperature(self):
code, out = self.run_ctl("wait", "cool")
self.assertEqual(["INVALID_ARGUMENTS", 2], [out["error"]["code"], code])
code, out = self.run_ctl("wait", "cool", "--below", "38")
self.assertEqual("THERMAL_FAILED", out["error"]["code"])
class ScenarioTest(FakeAdbTest):
def write(self, body):