Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions phoenix/pico4-power/PKGBUILD
Original file line number Diff line number Diff line change
@@ -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'
'f0557038297791bba0fde3efc28d25a565f7ef338dc38cd65ff4dbea0fdada59'
'5f5df141aef42f012da84adb920ac3db4e4a8620bc1dd0059d88fc8579f43251'
'e403426890c10267a02693e04e06ddbbfc0be30fd3130aa089e2b80c921d1886')

Expand All @@ -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"
Expand Down
98 changes: 95 additions & 3 deletions phoenix/pico4-power/pico4-fan
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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."""
Expand All @@ -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:
Expand Down Expand Up @@ -776,13 +837,40 @@ 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()
log_stderr(f"stopped; the fan stays at {daemon.sent} %")
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()
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion phoenix/pico4-power/pico4-fan.service
Original file line number Diff line number Diff line change
@@ -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
Expand Down
9 changes: 9 additions & 0 deletions phoenix/pico4-power/pico4-fan.sleep
Original file line number Diff line number Diff line change
@@ -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
Loading