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
3 changes: 2 additions & 1 deletion phoenix/pico4-power/50-pico4-power.preset
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# The fan, the battery guard and the power key run from the start.
# The fan, the battery guard, the power key and the status LED run from the start.
enable pico4-fan.service
enable pico4-battery-guard.service
enable pico4-powerkey.service
enable pico4-status-led.service
24 changes: 14 additions & 10 deletions phoenix/pico4-power/PKGBUILD
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
# 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; in a sleep the fan is off, as on PICO OS (systemd-sleep's
# hook pico4-fan.sleep); the tests run in the build.
# the key alone); the status LED as PICO OS sets it (status-led). The preset enables the four 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.12.3
pkgrel=1
pkgdesc="PICO 4 fan control, battery guard and power key, as on PICO OS"
pkgrel=2
pkgdesc="PICO 4 fan control, battery guard, power key and status LED, 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 pico4-fan.sleep
battery-guard pico4-battery-guard.service
powerkey pico4-powerkey.service 50-pico4-power-key.conf
status-led pico4-status-led.service
50-pico4-power.preset
test_fan.py test_battery_guard.py test_power_key.py)
test_fan.py test_battery_guard.py test_power_key.py test_status_led.py)
sha256sums=('81899ac36a3ca784da208b1426e6e6f7fe777ebc6ece8c99eda84e97acf892cd'
'b90a8564bbec7d3c3e8b3a6d0c863a552578117e0f8e8967168a7d7f7e7fe03b'
'6280eb7a942af172c04bacadb2d04cfe559f4d8f63675d87db81dcce87a52676'
Expand All @@ -24,20 +25,23 @@ sha256sums=('81899ac36a3ca784da208b1426e6e6f7fe777ebc6ece8c99eda84e97acf892cd'
'b418cb19ac9ec4367e5a8e0661dda65688fb4e91c62d23e47c362069a04b2437'
'19f248403bfba342c224978e08895a450327c4d47d7aa7e1d8e201e406d53cf5'
'fccd2ff01aa3835c45a63fe7e2ef894b51d9008b04bf4f2214659a6788e6764d'
'96909ecb295fe2f72e5967f279a468d2670a9b514c261ee8fbdf42035dc98aa7'
'09cb202f462560346e18f63e8a09bb1c53d19189547ac8b60639913695851908'
'd2c226f50a1c3029888921ff44c135d265952e6cfd488b7d91b3503d3c4939b3'
'e9ca686d1b78eed2e1f7ee7efdbc65e996d59400d1e14a84c3bda892736251c6'
'f0557038297791bba0fde3efc28d25a565f7ef338dc38cd65ff4dbea0fdada59'
'5f5df141aef42f012da84adb920ac3db4e4a8620bc1dd0059d88fc8579f43251'
'e403426890c10267a02693e04e06ddbbfc0be30fd3130aa089e2b80c921d1886')
'e403426890c10267a02693e04e06ddbbfc0be30fd3130aa089e2b80c921d1886'
'630cae3a000e3aaea81105a54c9842a3236fe40ac606e0335231b8900b6552d0')

build() {
python3 -B -m unittest test_fan test_battery_guard test_power_key
python3 -B -m unittest test_fan test_battery_guard test_power_key test_status_led
}

package() {
install -Dm755 pico4-fan -t "$pkgdir/usr/bin"
install -Dm755 battery-guard powerkey -t "$pkgdir/usr/libexec/pico4"
install -Dm755 battery-guard powerkey status-led -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 \
install -Dm644 pico4-fan.service pico4-battery-guard.service pico4-powerkey.service pico4-status-led.service \
-t "$pkgdir/usr/lib/systemd/system"
install -Dm644 50-pico4-power-key.conf -t "$pkgdir/usr/lib/systemd/logind.conf.d"
install -Dm644 50-pico4-power.preset -t "$pkgdir/usr/lib/systemd/system-preset"
Expand Down
15 changes: 15 additions & 0 deletions phoenix/pico4-power/pico4-status-led.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# The status LED as PICO OS sets it (docs/internals/cooling.md#the-status-led): the battery's charge while
# charging, blue with the screen on, a red blink at a low or warm battery, a blue blink at shutdown.
[Unit]
Description=PICO 4 status LED
ConditionPathExists=/sys/class/leds/rgb:status

[Service]
ExecStart=/usr/libexec/pico4/status-led
# Only when the system is going down: PICO OS's shutdown blink.
ExecStop=/usr/libexec/pico4/status-led stop
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target
247 changes: 247 additions & 0 deletions phoenix/pico4-power/status-led
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
#!/usr/bin/python3
# SPDX-License-Identifier: Unlicense
"""The status LED as PICO OS sets it (docs/internals/cooling.md#the-status-led).

Two of PICO OS's services write the LED, and the last write wins; this does what they do, in their order,
on the same events:

- The battery service (ExtBatteryServiceImpl.updateLightsLocked), at every battery change: a red blink of
500 ms on, 2000 ms off while the battery is warm (45.0 to 57.9 °C) or at 0 °C or below; otherwise, while
charging or full, red up to 20 %, amber from 21 to 98 %, green from 99 %, steady.
- The power manager (ExtPowerManagerServiceImpl.notifyLedStatus): when the charger is unplugged, and at a
battery change that is not charging while plugged in or with the screen on (but not when full and plugged
in): a red blink of 500 ms on, 1000 ms off below 20 %, else blue with the screen on, else off. On battery,
the screen going off turns the LED off, and the screen coming on sets it again.
- Charger mode (the charger program): by the level alone, red below 21 %, amber below 99 %, else green,
and off when unplugged.
- At shutdown (init.picovr.rc): a blue blink of 500 ms on, 1000 ms off.

The screen is the panels' backlight, which standby switches (bl_power), as for battery-guard. A blink runs
at full brightness while on, as the stock driver's; a steady colour at PICO OS's 0-255 values, scaled to the
LED's range. The LED is the PM8150L's tri-colour LED, rgb:status in the LED class.

status-led [--dry-run] follow the battery, the charger and the screen
status-led stop the shutdown's blink when the system is going down, else nothing
"""

from __future__ import annotations

import argparse
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path

LED = "/sys/class/leds/rgb:status"
BATTERY = "/sys/class/power_supply/battery"
CHARGER = "/sys/class/power_supply/usb/online"
BACKLIGHT = "/sys/class/backlight/pico4-panel/bl_power"
CMDLINE = "/proc/cmdline"
POLL = 1.0 # s
WARM = 450 # 0.1 °C : checkBatteryStatus's warning from 45.0 °C ...
HOT = 580 # ... up to below 58.0 °C, where the shutdown warning takes over
COLD = 0 # 0.1 °C : and at 0 °C or below
LOW = 20 # % : notifyLedStatus blinks below it


@dataclass(frozen=True)
class Light:
"""One state of the LED: a colour (0-255 per channel) and a blink (ms on, ms off; 0 0 is steady)."""

red: int = 0
green: int = 0
blue: int = 0
on_ms: int = 0
off_ms: int = 0


OFF = Light()
BLUE = Light(blue=255)
LOW_BLINK = Light(red=255, on_ms=500, off_ms=1000)
TEMP_BLINK = Light(red=255, on_ms=500, off_ms=2000)
SHUTDOWN_BLINK = Light(blue=255, on_ms=500, off_ms=1000)
CHARGING_LOW = Light(red=80)
CHARGING = Light(red=80, green=80)
CHARGED = Light(green=80)


@dataclass(frozen=True)
class Inputs:
"""What PICO OS's services read: the battery's status, level and temperature, the charger and the screen."""

status: str
level: int
temp: int | None
plugged: bool
screen_on: bool


def read(path: str | Path) -> str | None:
"""Return a sysfs file's text, None when it is missing or unreadable."""
try:
return Path(path).read_text(encoding="ascii", errors="replace").strip()
except OSError:
return None


def number(text: str | None) -> int | None:
"""Return the integer in @p text, None without one."""
try:
return int(text) if text is not None else None
except ValueError:
return None


def sample(battery: str = BATTERY, charger: str = CHARGER, backlight: str = BACKLIGHT) -> Inputs | None:
"""Read the inputs; None while the battery has no level."""
level = number(read(f"{battery}/capacity"))
if level is None:
return None
return Inputs(
status=read(f"{battery}/status") or "Unknown",
level=level,
temp=number(read(f"{battery}/temp")),
plugged=read(charger) == "1",
screen_on=number(read(backlight)) == 0,
)


def battery_light(now: Inputs) -> Light | None:
"""Return what the battery service writes at a battery change, None when it leaves the LED alone."""
if now.temp is not None and (WARM <= now.temp < HOT or now.temp <= COLD):
return TEMP_BLINK
if now.status not in {"Charging", "Full"}:
return None
if now.level <= LOW:
return CHARGING_LOW
return CHARGING if now.level <= 98 else CHARGED # noqa: PLR2004 - updateLightsLocked's if-gt level, 98


def power_light(now: Inputs) -> Light:
"""Return notifyLedStatus's light for a screen that is on or off."""
if now.level < LOW:
return LOW_BLINK
return BLUE if now.screen_on else OFF


class Stock:
"""PICO OS's writers on the events they follow; the last light written stays."""

def __init__(self) -> None:
"""Start before the first battery change."""
self.last: Inputs | None = None

def step(self, now: Inputs) -> Light | None:
"""Return the light the events between the last inputs and @p now leave, None for no write."""
last, self.last = self.last, now
light: Light | None = None
changed = last is None or (last.status, last.level, last.temp, last.plugged) != (
now.status,
now.level,
now.temp,
now.plugged,
)
if changed:
light = battery_light(now)
if last is not None and last.plugged and not now.plugged:
light = power_light(now)
# The power manager's battery broadcast: not while charging, and full on the cable is the battery service's.
full_on_cable = now.plugged and now.status == "Full"
if changed and now.status != "Charging" and (now.plugged or now.screen_on) and not full_on_cable:
light = power_light(now)
if last is not None and last.screen_on != now.screen_on and not now.plugged:
# Going to sleep: off. Waking: notifyLedStatus runs before the screen is on, so stock shows blue at
# the next battery broadcast; here at once.
light = power_light(now) if now.screen_on else OFF
return light


class Charger:
"""The charger program in charger mode: the level's colour at each change, off when unplugged."""

def __init__(self) -> None:
"""Start before the first reading."""
self.last: Inputs | None = None

def step(self, now: Inputs) -> Light | None:
"""Return the light to write, None for no write."""
last, self.last = self.last, now
if not now.plugged:
return OFF if last is None or last.plugged else None
if last is not None and last.plugged and last.level == now.level:
return None
if now.level < 21: # noqa: PLR2004 - the charger's level < 21
return CHARGING_LOW
return CHARGING if now.level < 99 else CHARGED # noqa: PLR2004 - the charger's level < 99


class Led:
"""The multicolour LED's files: intensities, brightness and the timer trigger for a blink."""

def __init__(self, root: str = LED, *, dry_run: bool = False) -> None:
"""Keep the LED's folder; a dry run only prints what it would write."""
self.root = Path(root)
self.dry_run = dry_run

def write(self, name: str, value: str) -> None:
"""Write one of the LED's files."""
if self.dry_run:
print(f"{name} = {value}", flush=True)
return
(self.root / name).write_text(value, encoding="ascii")

def show(self, light: Light) -> None:
"""Set the LED to @p light."""
top = number(read(self.root / "max_brightness")) or 255
scaled = [round(c * top / 255) for c in (light.red, light.green, light.blue)]
self.write("trigger", "none")
self.write("multi_intensity", " ".join(str(c) for c in scaled))
self.write("brightness", str(top if any(scaled) else 0))
if light.on_ms and any(scaled):
self.write("trigger", "timer")
self.write("delay_on", str(light.on_ms))
self.write("delay_off", str(light.off_ms))


def charger_mode(cmdline: str = CMDLINE) -> bool:
"""Return whether the boot is charger mode (the bootloader's androidboot.mode=charger)."""
return "androidboot.mode=charger" in (read(cmdline) or "").split()


def cmd_run(args: argparse.Namespace) -> int:
"""Follow the inputs until stopped."""
led = Led(args.led, dry_run=args.dry_run)
writer = Charger() if charger_mode() else Stock()
shown: Light | None = None
while True:
now = sample()
light = writer.step(now) if now is not None else None
if light is not None and light != shown:
led.show(light)
shown = light
time.sleep(POLL)


def cmd_stop(args: argparse.Namespace) -> int:
"""Show the shutdown's blink when the system is going down; a restart of the service leaves the LED."""
state = subprocess.run(
["/usr/bin/systemctl", "is-system-running"], capture_output=True, text=True, check=False
).stdout.strip()
if state == "stopping":
Led(args.led, dry_run=args.dry_run).show(SHUTDOWN_BLINK)
return 0


def main(argv: list[str] | None = None) -> int:
"""Run or stop."""
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--dry-run", action="store_true", help="print the writes instead")
parser.add_argument("--led", default=LED, help=argparse.SUPPRESS)
parser.add_argument("command", nargs="?", choices=("run", "stop"), default="run")
args = parser.parse_args(argv)
return cmd_stop(args) if args.command == "stop" else cmd_run(args)


if __name__ == "__main__":
sys.exit(main())
Loading