From d296f500bf8aea93238be4d0940782dafc0f72d3 Mon Sep 17 00:00:00 2001 From: Xenolphthalein <21215869+Xenolphthalein@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:21:50 +0100 Subject: [PATCH 1/2] fix: pico4-power turns the fan off for a sleep and gives control back after the wake, as PICO OS does systemd-sleep's hook tells pico4-fan before the sleep (duty 0, no sensor reads) and after the wake (the table's duty at once, from the means as they were); a daemon that runs a minute after a sleep without a wake takes control back. For overpressure/phoenix#182 --- phoenix/pico4-power/PKGBUILD | 15 ++- phoenix/pico4-power/pico4-fan | 98 +++++++++++++++- phoenix/pico4-power/pico4-fan.service | 3 +- phoenix/pico4-power/pico4-fan.sleep | 9 ++ phoenix/pico4-power/test_fan.py | 163 ++++++++++++++++++++++++++ 5 files changed, 278 insertions(+), 10 deletions(-) create mode 100755 phoenix/pico4-power/pico4-fan.sleep diff --git a/phoenix/pico4-power/PKGBUILD b/phoenix/pico4-power/PKGBUILD index f0e4126..39f9555 100644 --- a/phoenix/pico4-power/PKGBUILD +++ b/phoenix/pico4-power/PKGBUILD @@ -1,29 +1,31 @@ # The PICO 4's power and heat as PICO OS handles them: the fan on the lens-motor MCU, driven from the CPU # and GPU sensors with PICO OS's table (pico4-fan); the power-off at a low or hot battery (battery-guard); # the power key, a short press to suspend and a 2 s hold to power off (powerkey, with logind leaving -# the key alone). The preset enables the three services; the tests run in the build. +# the key alone). The preset enables the three services; in a sleep the fan is off, as on PICO OS (systemd-sleep's +# hook pico4-fan.sleep); the tests run in the build. pkgname=pico4-power -pkgver=2026.11.25 +pkgver=2026.12.3 pkgrel=1 pkgdesc="PICO 4 fan control, battery guard and power key, as on PICO OS" arch=(any) url="https://github.com/overpressure/phoenix/blob/main/docs/cooling.md" license=(Unlicense) depends=(python systemd) -source=(pico4-fan pico4-fan.service +source=(pico4-fan pico4-fan.service pico4-fan.sleep battery-guard pico4-battery-guard.service powerkey pico4-powerkey.service 50-pico4-power-key.conf 50-pico4-power.preset test_fan.py test_battery_guard.py test_power_key.py) -sha256sums=('6872e1f676719082d78ed17d9f9d16618a73412722c7b6f1bba4cb0c5acfea59' - '2d337cfee38033e97eafbbe0fa9a27b445b32b91c1f59b77d1f0358c6dfbcc93' +sha256sums=('81899ac36a3ca784da208b1426e6e6f7fe777ebc6ece8c99eda84e97acf892cd' + 'b90a8564bbec7d3c3e8b3a6d0c863a552578117e0f8e8967168a7d7f7e7fe03b' + '6280eb7a942af172c04bacadb2d04cfe559f4d8f63675d87db81dcce87a52676' '9956f154529309f757d0501dcb5387c735b046dff87539b7bb15a216c51c3a9f' 'a2533cfaec6db8847244dc641eeef5fbc11b962be8cc52ba3c86950868003f13' 'b418cb19ac9ec4367e5a8e0661dda65688fb4e91c62d23e47c362069a04b2437' '19f248403bfba342c224978e08895a450327c4d47d7aa7e1d8e201e406d53cf5' 'fccd2ff01aa3835c45a63fe7e2ef894b51d9008b04bf4f2214659a6788e6764d' '96909ecb295fe2f72e5967f279a468d2670a9b514c261ee8fbdf42035dc98aa7' - '2385dd5a7fdda2e73e3246e9cf531d2c58d142e92a6dde40fc66d91c710d07ef' + 'a1e565775231ae758209d687ca43e37c7685242627560add9f236acf0b5e06a3' '5f5df141aef42f012da84adb920ac3db4e4a8620bc1dd0059d88fc8579f43251' 'e403426890c10267a02693e04e06ddbbfc0be30fd3130aa089e2b80c921d1886') @@ -34,6 +36,7 @@ build() { package() { install -Dm755 pico4-fan -t "$pkgdir/usr/bin" install -Dm755 battery-guard powerkey -t "$pkgdir/usr/libexec/pico4" + install -Dm755 pico4-fan.sleep "$pkgdir/usr/lib/systemd/system-sleep/pico4-fan" install -Dm644 pico4-fan.service pico4-battery-guard.service pico4-powerkey.service \ -t "$pkgdir/usr/lib/systemd/system" install -Dm644 50-pico4-power-key.conf -t "$pkgdir/usr/lib/systemd/logind.conf.d" diff --git a/phoenix/pico4-power/pico4-fan b/phoenix/pico4-power/pico4-fan index 249d7f8..63755b4 100644 --- a/phoenix/pico4-power/pico4-fan +++ b/phoenix/pico4-power/pico4-fan @@ -14,7 +14,10 @@ bytes before. PICO OS's pxrfanservice sets the duty with SetFanSpeed (0x0E, - the hottest mean picks the duty from a six-step table. On the way down a duty holds until the temperature falls one more step; between the two lowest thresholds nothing changes; -- an unchanged duty is sent again every 10 s. +- an unchanged duty is sent again every 10 s; +- when the headset goes to sleep (its VR mode stops) it sets the duty to 0 and stops reading + the sensors; when it wakes, the MCU is woken and the table's duty sent at once, from the + means as they were. PICO OS has two tables for the PICO 4 and picks one by the production batch in the serial number ("early" and "late" here). This daemon runs the early table by @@ -26,6 +29,10 @@ thing for a fan that does not cool, for which PICO OS has no reaction: where PIC shows its overheating notice (a hottest mean of 95.1 °C for 2 minutes), a silent MCU or a stalled fan powers the headset off. +Sleep: systemd-sleep's hook (pico4-fan.sleep) tells the running daemon before the sleep +(pico4-fan sleep, SIGUSR1) and after it (pico4-fan wake, SIGUSR2), and waits until its state file +says so. A daemon that was told of a sleep and runs a minute without a wake takes control back. + F1: gd32ipdservice wakes the MCU as the screen comes on (wakeUp): SetBrightness with the configured level (sys_brt_level; 63 below 30 or without a configuration), every 10 ms, up to 50 times, until it answers 79. This tool does the same, with 63, @@ -106,6 +113,8 @@ ERROR_REPEAT = 60.0 # s between repeated error messages STATE_EVERY = 1.0 # s between state file updates STATE_STALE = 5.0 # s: an older state file is from a daemon that stopped STATE_FIELDS = ("profile", "duty", "reason", "boost", "rpm", "hottest", "hottest_mean_c", "error") +SLEEP_GUARD = 60.0 # s of running (CLOCK_MONOTONIC stops in the sleep) without a wake before control resumes +SLEEP_CONFIRM = 2.0 # s the sleep hook waits for the daemon's state file STALL_READS = 3 # RPM readings of 0 at a duty of STALL_DUTY or more before a warning STALL_DUTY = 30 # %: from this duty up the fan must turn ZONE_MAX = 200000 # m°C; disabled zones read placeholders such as 274 °C @@ -541,10 +550,21 @@ class Daemon: self.errors = 0 self.state_at = never self.last: dict = {} + self.wanted = False # the sleep hook's last word: True from "sleep" until "wake" + self.asleep = False + self.asleep_at = never def cycle(self) -> dict: """Run one period: read, step, send when due, watch for overheating; return the state.""" now = self.clock() + if self.wanted != self.asleep: + self.switch(now, asleep=self.wanted) + if self.asleep and now - self.asleep_at >= SLEEP_GUARD: + self.log(f"no wake {SLEEP_GUARD:.0f} s after the sleep: control resumes") + self.wanted = False + self.switch(now, asleep=False) + if self.asleep: + return self.doze(now) for s in self.sensors: s.add(self.read(s.path)) means = [(m, s.name) for s in self.sensors for m in [s.mean()] if m is not None] @@ -575,12 +595,52 @@ class Daemon: "hottest_now_c": c(hottest_now), "rpm": self.rpm, "error": self.error or None, + "sleep": False, "sensors": {s.name: {"now_c": c(s.now), "mean_c": c(s.mean())} for s in self.sensors}, } + self.keep_state(now) + return self.last + + def switch(self, now: float, *, asleep: bool) -> None: + """Go to sleep or wake up; the state file says so at once.""" + self.asleep, self.state_at = asleep, float("-inf") + if asleep: + self.asleep_at = now + self.log("sleep: the fan off, as PICO OS's") + else: + # The table's duty at once, from the means as they were before the sleep. + self.sent_at = self.failed_at = float("-inf") + self.log("wake: control resumes") + + def doze(self, now: float) -> dict: + """Run one period asleep: the fan off, as PICO OS's, and no sensor reads.""" + self.rpm = None + if self.fan is not None and self.sent != 0 and now - self.failed_at >= RETRY: + self.send(0, "sleep", None, None, now) + if self.sent == 0: + self.state_at = float("-inf") + elif self.fan is None and self.sent != 0: + self.sent = 0 + self.log("duty 0 % (sleep) [dry run]") + self.last = { + **self.last, + "pid": os.getpid(), + "time": round(time.time(), 1), + "duty": self.sent, + "target": 0, + "reason": "sleep", + "rpm": None, # not read in the sleep + "error": self.error or None, + "sleep": True, + } + self.keep_state(now) + return self.last + + def keep_state(self, now: float) -> None: + """Write the state file every STATE_EVERY, and at once after a switch.""" if self.state_path is not None and now - self.state_at >= STATE_EVERY: self.state_at = now self.write_state() - return self.last def send(self, duty: int, reason: str, hottest_mean: int | None, hottest: str | None, now: float) -> None: """Send the duty and log a change; a failure is retried after RETRY.""" @@ -596,7 +656,8 @@ class Daemon: changed = duty != self.sent self.sent, self.sent_at = duty, now if changed: - self.log(f"duty {duty} % ({reason}; hottest mean {c(hottest_mean)} °C, {hottest})") + why = reason if hottest is None else f"{reason}; hottest mean {c(hottest_mean)} °C, {hottest}" + self.log(f"duty {duty} % ({why})") self.recovered() def read_rpm(self, now: float) -> None: @@ -776,6 +837,8 @@ def cmd_run(args: argparse.Namespace) -> int: stop: list[bool] = [] for sig in (signal.SIGTERM, signal.SIGINT): signal.signal(sig, lambda *_: stop.append(True)) + signal.signal(signal.SIGUSR1, lambda *_: setattr(daemon, "wanted", True)) + signal.signal(signal.SIGUSR2, lambda *_: setattr(daemon, "wanted", False)) daemon.run(lambda: bool(stop)) if state is not None: daemon.write_state() @@ -783,6 +846,31 @@ def cmd_run(args: argparse.Namespace) -> int: return 0 +def cmd_sleep(args: argparse.Namespace, state: Path = STATE) -> int: + """Tell the daemon of a sleep or a wake (systemd-sleep's hook) and wait until its state file says so. + + Without a daemon there is nothing to tell; a daemon that does not confirm in time is reported and the + sleep goes on, as the hook's failure does not stop it. + """ + asleep = args.command == "sleep" + pid = daemon_pid(state) + if pid is None: + print(f"pico4-fan: no daemon runs; the fan keeps its duty through the {args.command}", file=sys.stderr) + return 0 + os.kill(pid, signal.SIGUSR1 if asleep else signal.SIGUSR2) + deadline = time.monotonic() + args.timeout + while True: + with contextlib.suppress(OSError, ValueError, AttributeError): + current = json.loads(state.read_text()) + if current.get("sleep") is asleep and (not asleep or current.get("duty") == 0): + return 0 + if time.monotonic() >= deadline: + break + time.sleep(0.05) + print(f"pico4-fan: the daemon did not confirm the {args.command} within {args.timeout:g} s", file=sys.stderr) + return 1 + + def busy(args: argparse.Namespace) -> bool: """Tell (and say) whether the daemon runs, so a manual command would fight it.""" pid = daemon_pid() @@ -945,6 +1033,10 @@ def main(argv: list[str] | None = None) -> int: "state", help="the daemon's duty, RPM and hottest mean as one JSON line (null if it is not running)" ) state.set_defaults(func=cmd_state) + for word, what in (("sleep", "the fan off for a sleep"), ("wake", "control back after a sleep")): + hook = sub.add_parser(word, help=f"{what} (systemd-sleep's hook tells the daemon)") + hook.add_argument("--timeout", type=float, default=SLEEP_CONFIRM, help=argparse.SUPPRESS) + hook.set_defaults(func=cmd_sleep) batch = sub.add_parser("batch", help="early or late, from a serial number file (- for stdin); prints only the word") batch.add_argument("serial") batch.set_defaults(func=cmd_batch) diff --git a/phoenix/pico4-power/pico4-fan.service b/phoenix/pico4-power/pico4-fan.service index f125bcc..20d0a2e 100644 --- a/phoenix/pico4-power/pico4-fan.service +++ b/phoenix/pico4-power/pico4-fan.service @@ -1,7 +1,8 @@ # Fan control (docs/cooling.md): the fan on the lens-motor MCU (ttyHS1), driven # from the CPU and GPU sensors with PICO OS's table, plus full speed from # 95 °C. Settings (PICO4_FAN_PROFILE, PICO4_FAN_TABLE, PICO4_FAN_BOOST) go in -# /etc/pico4/fan.conf. When the service stops, the fan keeps its duty. +# /etc/pico4/fan.conf. When the service stops, the fan keeps its duty. In a sleep +# the fan is off, as on PICO OS (systemd-sleep's hook pico4-fan.sleep tells the daemon). # The condition is the fan's UART, by its sysfs entry. [Unit] Description=PICO 4 fan control diff --git a/phoenix/pico4-power/pico4-fan.sleep b/phoenix/pico4-power/pico4-fan.sleep new file mode 100755 index 0000000..33e7662 --- /dev/null +++ b/phoenix/pico4-power/pico4-fan.sleep @@ -0,0 +1,9 @@ +#!/bin/bash +# systemd-sleep's hook (docs/cooling.md): the fan off before the sleep, as PICO OS's fan service +# does when the headset sleeps, and its control back after the wake. A failure never stops the sleep. +set -euo pipefail + +case "${1-}" in +pre) exec pico4-fan sleep ;; +post) exec pico4-fan wake ;; +esac diff --git a/phoenix/pico4-power/test_fan.py b/phoenix/pico4-power/test_fan.py index fa56d9c..8110c2e 100644 --- a/phoenix/pico4-power/test_fan.py +++ b/phoenix/pico4-power/test_fan.py @@ -3,17 +3,21 @@ from __future__ import annotations +import argparse import contextlib import importlib.machinery import importlib.util import io import json import os +import shutil +import subprocess import sys import tempfile import threading import unittest from pathlib import Path +from typing import Callable from unittest import mock PATH = Path(__file__).resolve().parent / "pico4-fan" @@ -642,6 +646,165 @@ def test_dry_run_never_touches_the_mcu(self): self.assertEqual(self.mcu.frames, []) +class SleepTest(unittest.TestCase): + """PICO OS's fan service in a sleep: the duty 0 at once, no sensor reads, the table's duty at once on the wake.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.clock = Clock() + self.mcu = FakeMcu() + self.temps = {name: mc(73) for name in STOCK_SENSORS} + self.reads = [] + self.logs = [] + self.state = Path(self.tmp.name) / "state.json" + self.daemon = fan.Daemon( + fan.Controller(LATE), + [fan.Sensor(name, name) for name in STOCK_SENSORS], + fan.Fan(self.mcu), + self.read, + clock=self.clock, + log=self.logs.append, + state_path=self.state, + profile="late", + ) + + def tearDown(self): + self.tmp.cleanup() + + def read(self, path: str) -> int | None: + self.reads.append(path) + return self.temps.get(path) + + def advance(self, seconds: float) -> None: + for _ in range(round(seconds / fan.PERIOD)): + self.daemon.cycle() + self.clock.ticks += 1 + + def written(self) -> dict: + return json.loads(self.state.read_text()) + + def test_the_fan_is_off_at_once_and_the_sensors_are_left_alone(self): + self.advance(12) + self.assertEqual(self.mcu.duty, 35) + self.daemon.wanted = True + reads, sets = len(self.reads), len(self.mcu.sets()) + self.advance(0.2) + self.assertEqual(self.mcu.sets()[sets:], [0]) + self.assertEqual(self.mcu.duty, 0) + state = self.written() # at once, not after STATE_EVERY + self.assertEqual((state["sleep"], state["duty"], state["reason"], state["rpm"]), (True, 0, "sleep", None)) + self.advance(30) + self.assertEqual(len(self.reads), reads) + self.assertEqual(self.mcu.sets()[sets:], [0]) # no refresh in the sleep + self.assertIn("sleep: the fan off, as PICO OS's", self.logs) + self.assertIn("duty 0 % (sleep)", self.logs) + + def test_the_wake_sends_the_table_at_once_from_the_means_as_they_were(self): + self.advance(12) + self.daemon.wanted = True + self.advance(5) + for name in self.temps: + self.temps[name] = mc(40) # cooler after the sleep; the means still hold 73 °C + self.daemon.wanted = False + sets = len(self.mcu.sets()) + self.advance(0.2) + self.assertEqual(self.mcu.sets()[sets:], [35]) + self.assertFalse(self.written()["sleep"]) + self.assertIn("wake: control resumes", self.logs) + + def test_a_failed_send_in_the_sleep_is_retried_each_second(self): + self.advance(12) + self.daemon.wanted = True + self.mcu.fail = 1 + self.advance(0.2) + self.assertNotEqual(self.mcu.duty, 0) + self.assertNotEqual(self.written()["duty"], 0) + self.advance(1) + self.assertEqual(self.mcu.duty, 0) + self.assertEqual(self.written()["duty"], 0) + + def test_without_a_wake_control_resumes_after_a_minute(self): + self.advance(12) + self.daemon.wanted = True + self.advance(fan.SLEEP_GUARD - 0.2) + self.assertEqual(self.mcu.duty, 0) + self.advance(0.4) + self.assertEqual(self.mcu.duty, 35) + self.assertFalse(self.daemon.wanted) + self.assertIn("no wake 60 s after the sleep: control resumes", self.logs) + + def test_dry_run_sleeps_without_the_mcu(self): + daemon = fan.Daemon( + fan.Controller(LATE), + [fan.Sensor("cpu-0-0-usr", "x")], + None, + {"x": mc(73)}.get, + clock=self.clock, + log=self.logs.append, + state_path=None, + ) + daemon.cycle() + daemon.wanted = True + daemon.cycle() + self.assertEqual(daemon.sent, 0) + self.assertEqual(self.mcu.frames, []) + + def hook( + self, word: str, daemon_pid: int | None, kill: Callable[[int, int], None] | None = None, timeout: float = 0.5 + ) -> tuple[int, mock.MagicMock, str]: + err = io.StringIO() + with ( + mock.patch.object(fan, "daemon_pid", return_value=daemon_pid), + mock.patch.object(fan.os, "kill", side_effect=kill) as killed, + contextlib.redirect_stderr(err), + ): + code = fan.cmd_sleep(argparse.Namespace(command=word, timeout=timeout), state=self.state) + return code, killed, err.getvalue() + + def test_the_hook_signals_the_daemon_and_waits_for_its_state(self): + def daemon(_pid: int, sig: int) -> None: + self.daemon.wanted = sig == fan.signal.SIGUSR1 + self.advance(0.2) + + code, killed, err = self.hook("sleep", 4321, daemon) + self.assertEqual((code, err), (0, "")) + killed.assert_called_once_with(4321, fan.signal.SIGUSR1) + self.assertEqual(self.mcu.duty, 0) + code, killed, err = self.hook("wake", 4321, daemon) + self.assertEqual((code, err), (0, "")) + killed.assert_called_once_with(4321, fan.signal.SIGUSR2) + + def test_the_hook_without_a_daemon_lets_the_sleep_go_on(self): + code, killed, err = self.hook("sleep", None) + self.assertEqual(code, 0) + killed.assert_not_called() + self.assertIn("no daemon runs", err) + + def test_the_hook_reports_a_daemon_that_does_not_confirm(self): + self.advance(1) # a state file without the sleep + code, _killed, err = self.hook("sleep", 4321, lambda *_: None, timeout=0.1) + self.assertEqual(code, 1) + self.assertIn("did not confirm the sleep", err) + + def test_systemd_sleep_s_hook(self): + bash = shutil.which("bash") + if bash is None: + self.skipTest("no bash") + bin_dir = Path(self.tmp.name) / "bin" + bin_dir.mkdir() + calls = Path(self.tmp.name) / "calls" + stand_in = bin_dir / "pico4-fan" + stand_in.write_bytes(f'#!/bin/sh\necho "$*" >> {calls}\n'.encode()) + stand_in.chmod(0o755) + env = {**os.environ, "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}"} + hook = PATH.with_name("pico4-fan.sleep") + for args in (("pre", "suspend"), ("post", "suspend"), ("pre", "hibernate", "x")): + subprocess.run([bash, str(hook), *args], env=env, check=True) # noqa: S603 # the recipe's own hook + self.assertEqual(calls.read_text().splitlines(), ["sleep", "wake", "sleep"]) + subprocess.run([bash, str(hook)], env=env, check=True) # noqa: S603 # no argument: nothing + self.assertEqual(len(calls.read_text().splitlines()), 3) + + def synthetic_serial(ninth: str, code: str = "000", seventeenth: str = "0") -> bytes: """Return a made-up serial number: FanControl reads only its 9th character, the three after it and the 17th.""" return f"00000000{ninth}{code}0000{seventeenth}00".encode() From ffd043ed5c861bd6671f32c79652ac434241c0a4 Mon Sep 17 00:00:00 2001 From: Xenolphthalein <21215869+Xenolphthalein@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:23:52 +0100 Subject: [PATCH 2/2] fix: pico4-power's sums after the tests' formatting --- phoenix/pico4-power/PKGBUILD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phoenix/pico4-power/PKGBUILD b/phoenix/pico4-power/PKGBUILD index 39f9555..0294b12 100644 --- a/phoenix/pico4-power/PKGBUILD +++ b/phoenix/pico4-power/PKGBUILD @@ -25,7 +25,7 @@ sha256sums=('81899ac36a3ca784da208b1426e6e6f7fe777ebc6ece8c99eda84e97acf892cd' '19f248403bfba342c224978e08895a450327c4d47d7aa7e1d8e201e406d53cf5' 'fccd2ff01aa3835c45a63fe7e2ef894b51d9008b04bf4f2214659a6788e6764d' '96909ecb295fe2f72e5967f279a468d2670a9b514c261ee8fbdf42035dc98aa7' - 'a1e565775231ae758209d687ca43e37c7685242627560add9f236acf0b5e06a3' + 'f0557038297791bba0fde3efc28d25a565f7ef338dc38cd65ff4dbea0fdada59' '5f5df141aef42f012da84adb920ac3db4e4a8620bc1dd0059d88fc8579f43251' 'e403426890c10267a02693e04e06ddbbfc0be30fd3130aa089e2b80c921d1886')