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
27 changes: 21 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,27 +46,42 @@ Tools/compilar.sh simulador # abre el simulador en este escritorio (X11)
- **Ajustes del sistema**: el sistema es la fuente de verdad. `packaging/zeropower-helper`
(bash, se instala en `/usr/lib/zeropower/`): `status` sin root; `set <ajuste> <valor>` y
`restore` con root, por `sudo -n` con el sudo sin contraseña que trae el usuario del aparato
(`bruno ALL=(ALL) NOPASSWD:ALL` en `90-cloud-init-users`, del Imager). **La tienda no deja
(`bruno ALL=(ALL) NOPASSWD:ALL` en `90-cloud-init-users`, del Imager). Si sudo pide
contraseña (`classify_sudo` en `src/model/sudo_password.h`), `SettingsScreen` la pide encima
de la lista y `PowerControl::apply` repite con `sudo -S -p ""`, pasándola por la entrada
estándar de `run_process` y borrándola al acabar (`SecretInput`, `wipe`). En el simulador se
prueba con `ZEROPOWER_SIMULATE_SUDO=<clave>`. Para teclearla, `linux_input` entiende Shift
y la capa Sym del Cardputer (lee `/usr/share/keymaps/tca8418_keypad_m5stack_keymap.map`), y
la T no cambia el tema mientras se escribe (`set_text_entry`). **La tienda no deja
instalar sudoers** (ni en `/etc/sudoers.d` ni desde los scripts: busca `/etc/sudoers`), ni
polkit. Guarda el original de cada ajuste en `/var/lib/zeropower/original/` y `restore`
(en el `prerm`) lo devuelve. **No hay servicio de root al arrancar** (la tienda rechaza
servicios de root): todo queda puesto en el sistema (servicios, regla de udev
`70-zeropower-ethernet.rules`, `config.txt`, la radio del wifi, un *drop-in* de journald).
servicios de root): todo queda puesto en el sistema (servicios, reglas de udev
`70-zeropower-ethernet.rules` y `70-zeropower-leds.rules`, `config.txt`, la radio del wifi,
un *drop-in* de journald). Las salidas de 5 V (`grove_5v_out`, `ext_5v_out`) y el LED `ACT`
son LEDs en `/sys/class/leds`; `restore` deja las de 5 V como estén y sólo quita su regla.
`cpu_max` escribe `scaling_max_freq` ya y `arm_freq` en `config.txt` para el arranque.
Los servicios van de uno en uno (`SERVICE_KEYS`, cada uno con sus unidades en
`service_units`); `extra_services` (todos a la vez, de la 0.1.3) ya no sale en `status`,
pero se acepta y `restore` lo deshace (`RESTORE_KEYS`).
- **`zeropowerd`** (`src/daemon/`): servicio **del sistema** en `/usr/lib/systemd/system/`
con `User=1000` y `XDG_RUNTIME_DIR=/run/user/1000` (la tienda sólo admite unidades ahí, con
el nombre del paquete y que no corran como root; una unidad de usuario en
`/usr/lib/systemd/user` la rechaza). Apagar: `systemctl poweroff` y, si polkit no lo deja
desde un servicio, `sudo -n`.
Opciones en `~/.config/zeropower/power.conf` (la app lo reescribe con temporal + rename; el
servicio mira el `mtime` cada 3 s). Duerme en `poll()` sobre el teclado (1 s de tope).
Pantalla apagada = `/sys/class/backlight/backlight/brightness` a 0 durante 5 s → `pactl`
mueve los flujos del lanzador a un `module-null-sink` y `SIGSTOP` al lanzador (no si tiene
Pantalla apagada = `/sys/class/backlight/backlight/brightness` a 0 durante `idle_delay` s →
`pactl` mueve los flujos del lanzador a un `module-null-sink` (`idle_audio`) y `SIGSTOP` al
lanzador (`idle_launcher`; el antiguo `idle_saver` aún se lee) (no si tiene
hijos vivos: una app abierta; los zombis no cuentan). Tecla o brillo > 0 → `SIGCONT` y el
audio vuelve. Con la pantalla encendida y `screen_timeout` s sin teclas, el servicio escribe
brillo 0 (el usuario está en el grupo `video`) y la tecla siguiente devuelve el que había.
Al pararse lo deja todo como estaba (salvo al apagar por batería: no enciende la pantalla).
- **App**: `SettingsScreen` es la misma lista para los tres grupos (Hardware, Services,
Power saving); lee y aplica en un hilo (`PowerControl`). `BatteryScreen`: media de 30 s y
Power saving): 5 filas a la vista y, con más, se desplaza con una barra a la derecha; la
pista añade *Needs restart* a los ajustes con `needs_reboot` (hoy sólo `gpu_mem`). Lee y
aplica en un hilo (`PowerControl`). `BatteryScreen`: media de 30 s y
barras del último minuto.
- `platform::run_process` lanza sin shell (lista de argumentos).

Expand Down
42 changes: 33 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,35 @@ cuánto consume el aparato y **deshacerlo** todo igual de fácil.
- **Bluetooth**: radio y servicio.
- **HDMI desktop**: el escritorio para una pantalla HDMI (`lightdm`); apagado libera RAM y
CPU. El lanzador no depende de él.
- **Desk Mode unplug** (sólo con [Desk Mode](https://github.com/InstantComet/cz-desk-mode)):
cierra su escritorio HDMI cuando el HDMI lleva 1, 5, 15 o 30 minutos desconectado (~55 MB
de RAM). Lo que no se haya guardado en él se pierde: por defecto, *Keep desktop*.
- **GPU memory**: la RAM que se reserva para el firmware de la GPU. La pantalla interna es
un panel SPI que no la usa: con **16 MB** quedan 48 MB más para Linux. Vale tras reiniciar.
- **Services**: **Tailscale** (pide confirmar), **Background extras** (NFS, rpcbind, avahi y
los temporizadores de apt y man-db) y **Logs in RAM** (el journal en memoria: menos
escrituras en la tarjeta).
un panel SPI que no la usa: con **16 MB** quedan 48 MB más para Linux. Vale tras reiniciar
(la pista lo dice: *Needs restart*); es el único ajuste que lo necesita.
- **CPU max speed**: 1000 (de fábrica), 800 o 600 MHz. Vale ya mismo y tras reiniciar
(`arm_freq` en `config.txt`). Las apps van más lentas, pero los ratos de mucho trabajo
gastan menos; en reposo, a 600 MHz, sólo ~5 mA.
- **Status LED**: el LED verde de actividad del módulo CM0 (~4 mA).
- **Grove 5V** y **GPIO 5V**: los 5 V del puerto Grove y de los pines GPIO (para los Caps).
Al arrancar están apagados; una app para un Cap puede encender el de GPIO por su cuenta.
Si se encienden aquí, se quedan encendidos también tras reiniciar. Sin nada enchufado
gastan ~3 mA cada uno.
- **Services**, cada uno con su interruptor:
- **Tailscale** (pide confirmar).
- **NFS client**: `rpcbind` y `nfs-blkmap`, para carpetas compartidas por red.
- **Avahi (.local)**: el nombre `equipo.local` en la red; sin él, se entra por la IP.
- **Daily apt updates**: los temporizadores `apt-daily` y `apt-daily-upgrade`; `apt` a mano
sigue funcionando.
- **Man page index**: el temporizador diario de `man-db`.
- **Disk scrub timer**: `e2scrub_all`, que sólo revisa volúmenes LVM (la tarjeta no tiene).
- **Logs in RAM**: el journal en memoria (menos escrituras en la tarjeta).
- **Power saving** (lo hace el servicio `zeropowerd`):
- **Screen-off saver**: con la pantalla apagada, pausa el lanzador y aparca su audio para
que duerman la tarjeta de sonido y el amplificador. Una tecla lo despierta. Si hay una app
abierta no pausa nada.
- **Sleep sound card**: con la pantalla apagada, aparca el audio del lanzador para que
duerman la tarjeta de sonido y el amplificador (~40 mA).
- **Pause launcher**: con la pantalla apagada, pausa el lanzador, que no deja de repintar
(~30 mA). Una tecla lo despierta. Si hay una app abierta no pausa nada.
- **Saver delay**: cuánto tiene que llevar apagada la pantalla para los dos anteriores (3–60 s).
- **Quiet launcher**: el lanzador sin sonido de teclas, siempre.
- **Low battery off**: apaga ordenadamente al 5, 8, 10 o 15 % (tres lecturas seguidas).
- **Screen timeout**: si la pantalla sigue encendida tras 1, 2, 5 (por defecto) o 10 minutos
Expand Down Expand Up @@ -72,6 +92,7 @@ UART: LoRa, GPS, CC1101, NFC…) funcionan igual. ZeroPower lo enseña en la pan
| | `Z` / `C` en uno de varias opciones | Elegir valor (queda marcado con `•`) |
| | `ENTER` | Aplicar el valor elegido (sin elegir, pasa al siguiente) |
| | `Esc` | Descartar lo elegido / volver |
| Contraseña | letras, `Shift`, `Sym` · `ENTER` · `Esc` | Escribirla · confirmar · no cambiar nada |
| Battery | `R` | Empezar la media de cero |

## Cómo funciona
Expand All @@ -80,8 +101,11 @@ UART: LoRa, GPS, CC1101, NFC…) funcionan igual. ZeroPower lo enseña en la pan
`/usr/lib/zeropower/zeropower-helper status` (sin root).
- **Para cambiar algo** llama a `sudo -n /usr/lib/zeropower/zeropower-helper set <ajuste> <valor>`,
con el `sudo` sin contraseña que el usuario del aparato ya trae de fábrica (lo pone el
Raspberry Pi Imager). ZeroPower **no instala ningún fichero de sudoers** ni da permisos
nuevos; sin sudo sin contraseña, la app avisa y no cambia nada. El ayudante es un script de
Raspberry Pi Imager). Si tu usuario necesita contraseña para sudo, la app la pide en
pantalla y repite el cambio con `sudo -S`: la contraseña va por la entrada estándar (nunca
en la línea de órdenes), no se guarda y se borra de la memoria al acabar; sudo la recuerda
unos minutos, como en un terminal. ZeroPower **no instala ningún fichero de sudoers** ni da
permisos nuevos; un usuario sin sudo no puede cambiar nada. El ayudante es un script de
bash corto que acepta una lista cerrada de ajustes y valores; la primera vez que cambia
algo guarda su valor original en `/var/lib/zeropower/original/` para poder devolverlo
(`zeropower-helper restore`, que se ejecuta al desinstalar).
Expand Down
2 changes: 1 addition & 1 deletion app-builder.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"description": "Battery saver and power settings for the Cardputer Zero",
"store": {
"summary": "Battery saver: live power draw, turn off Ethernet, HDMI, BT, services",
"description": "Make the Cardputer Zero last longer. See the live power draw from the battery gauge, then turn off for good what a handheld does not need, and undo it just as easily.\n\n- Battery: average draw over the last 30 s, charge, voltage and time left, with the last minute as bars. R restarts the average, so you can see what each setting saves.\n- Hardware: internal USB Ethernet (On / Auto-suspend / Off, ~90 mA less), Wi-Fi, Bluetooth, the HDMI desktop (lightdm) and the GPU memory split (16 MB is enough for the built-in screen: 48 MB more RAM).\n- Services: Tailscale, background extras (NFS, rpcbind, avahi, apt timers) and system logs in RAM.\n- Power saving (zeropowerd, a service running as the device user, not root): screen off pauses the launcher and parks its audio (a key wakes it), quiet launcher (no key sounds), a clean power-off at low battery, and a screen timeout that turns the screen off after a few minutes without a key, as a safety net for when the launcher or an app leaves it on.\n\nSettings stay in the system itself and survive reboots. Uninstalling ZeroPower puts every changed setting back. System changes go through a small helper that accepts a fixed list of settings, run with the device user's passwordless sudo (as set up by Raspberry Pi Imager); no sudoers file is installed.\n\nMeasured on a Cardputer Zero with the screen off: 301 mA -> 209 mA just with Ethernet auto-suspend. Ideas and first measurements from cz-battery-saver by InstantComet (MIT).",
"description": "Make the Cardputer Zero last longer. See the live power draw from the battery gauge, then turn off for good what a handheld does not need, and undo it just as easily.\n\n- Battery: average draw over the last 30 s, charge, voltage and time left, with the last minute as bars. R restarts the average, so you can see what each setting saves.\n- Hardware: internal USB Ethernet (On / Auto-suspend / Off, ~90 mA less), Wi-Fi, Bluetooth, the HDMI desktop (lightdm), the GPU memory split (16 MB is enough for the built-in screen: 48 MB more RAM), a CPU speed cap, the status LED and the 5 V outputs of the Grove port and the GPIO header. With Desk Mode, its HDMI desktop can close itself once HDMI is unplugged.\n- Services, each on its own switch: Tailscale, NFS client (rpcbind), Avahi (.local names), daily apt updates, the man page index, the disk scrub timer and system logs in RAM.\n- Power saving (zeropowerd, a service running as the device user, not root): screen off sleeps the sound card and pauses the launcher (each one on its own switch) after a delay you choose (a key wakes it), quiet launcher (no key sounds), a clean power-off at low battery, and a screen timeout that turns the screen off after a few minutes without a key, as a safety net for when the launcher or an app leaves it on.\n\nSettings stay in the system itself and survive reboots. Uninstalling ZeroPower puts every changed setting back. System changes go through a small helper that accepts a fixed list of settings, run with the device user's sudo: passwordless as set up by Raspberry Pi Imager, or ZeroPower asks for the password on screen (never stored); no sudoers file is installed.\n\nMeasured on a Cardputer Zero with the screen off: 301 mA -> 209 mA just with Ethernet auto-suspend. Ideas and first measurements from cz-battery-saver by InstantComet (MIT).",
"categories": [
"System Tools"
],
Expand Down
146 changes: 144 additions & 2 deletions packaging/zeropower-helper
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,23 @@ JOURNAL_DROPIN=/etc/systemd/journald.conf.d/90-zeropower.conf
# El chip Ethernet USB interno (SR9900A, driver sr9800/r8152 según el kernel).
ETH_VENDOR=0fe6
ETH_PRODUCT=9900
LED_RULE=/etc/udev/rules.d/70-zeropower-leds.rules
LEDS=/sys/class/leds
CPUFREQ=/sys/devices/system/cpu/cpufreq
EXTRA_UNITS="rpcbind.service rpcbind.socket nfs-blkmap.service avahi-daemon.service avahi-daemon.socket apt-daily.timer apt-daily-upgrade.timer man-db.timer e2scrub_all.timer"
# Los mismos, de uno en uno (cada servicio con su socket). `extra_services` (todos a la vez)
# queda de la 0.1.3: se acepta y se deshace al desinstalar, pero ya no sale en `status`.
SERVICE_KEYS="nfs avahi apt_timers man_db e2scrub"

service_units() {
case "$1" in
nfs) echo "rpcbind.service rpcbind.socket nfs-blkmap.service" ;;
avahi) echo "avahi-daemon.service avahi-daemon.socket" ;;
apt_timers) echo "apt-daily.timer apt-daily-upgrade.timer" ;;
man_db) echo "man-db.timer" ;;
e2scrub) echo "e2scrub_all.timer" ;;
esac
}

die() {
echo "zeropower-helper: $*" >&2
Expand Down Expand Up @@ -106,10 +122,39 @@ get_extra_services() {
echo off
}

get_service() { # get_service <ajuste>: on si alguna de sus unidades está habilitada
local u found=
for u in $(service_units "$1"); do
unit_exists "$u" || continue
found=1
unit_enabled "$u" && { echo on; return; }
done
[ -n "$found" ] && echo off || echo absent
}

get_journal_ram() {
[ -f "$JOURNAL_DROPIN" ] && echo on || echo off
}

# Las salidas de 5 V (Grove y la de los pines GPIO) son «LEDs» del expansor de E/S: al
# arrancar están apagadas. Se lee cómo están ahora (una app para un Cap puede encender la de
# GPIO por su cuenta).
get_rail() { # get_rail <led>
[ -f "$LEDS/$1/brightness" ] || { echo absent; return; }
[ "$(cat "$LEDS/$1/brightness")" -gt 0 ] && echo on || echo off
}

get_status_led() {
[ -f "$LEDS/ACT/trigger" ] || { echo absent; return; }
grep -q '\[none\]' "$LEDS/ACT/trigger" && [ "$(cat "$LEDS/ACT/brightness")" -eq 0 ] && echo off || echo on
}

get_cpu_max() {
local v
v=$(grep -E '^[[:space:]]*arm_freq=' "$(config_txt)" 2>/dev/null | tail -1 | cut -d= -f2 | tr -dc 0-9)
echo "${v:-1000}"
}

get_value() {
case "$1" in
ethernet) get_ethernet ;;
Expand All @@ -120,11 +165,17 @@ get_value() {
tailscale) get_tailscale ;;
extra_services) get_extra_services ;;
journal_ram) get_journal_ram ;;
nfs|avahi|apt_timers|man_db|e2scrub) get_service "$1" ;;
cpu_max) get_cpu_max ;;
status_led) get_status_led ;;
grove_5v) get_rail grove_5v_out ;;
gpio_5v) get_rail ext_5v_out ;;
*) die "unknown setting: $1" ;;
esac
}

KEYS="ethernet wifi bluetooth hdmi_desktop gpu_mem tailscale extra_services journal_ram"
KEYS="ethernet wifi bluetooth hdmi_desktop gpu_mem tailscale $SERVICE_KEYS journal_ram cpu_max status_led grove_5v gpio_5v"
RESTORE_KEYS="$KEYS extra_services"

status() {
local k
Expand Down Expand Up @@ -241,6 +292,19 @@ set_extra_services() {
esac
}

set_service() { # set_service <ajuste> on|off
local u units=
for u in $(service_units "$1"); do
unit_exists "$u" && units="$units $u"
done
[ -n "$units" ] || die "$1: not installed"
case "$2" in
off) systemctl disable --now $units ;;
on) systemctl enable --now $units ;;
*) die "$1: on|off" ;;
esac
}

set_journal_ram() {
case "$1" in
on)
Expand Down Expand Up @@ -271,6 +335,75 @@ set_gpu_mem() {
sync
}

# Las reglas de LEDs (estado al arrancar) van todas en un fichero, una línea por LED.
set_led_rule() { # set_led_rule <led> [<regla sin el KERNEL==…>]
local tmp
mkdir -p "$(dirname "$LED_RULE")"
tmp=$(mktemp)
[ -f "$LED_RULE" ] && grep -v -e '^#' -e "KERNEL==\"$1\"" "$LED_RULE" > "$tmp"
[ $# -ge 2 ] && echo "ACTION==\"add\", SUBSYSTEM==\"leds\", KERNEL==\"$1\", $2" >> "$tmp"
if [ -s "$tmp" ]; then
{ echo "# ZeroPower: LEDs and 5 V outputs at boot"; cat "$tmp"; } > "$LED_RULE"
else
rm -f "$LED_RULE"
fi
rm -f "$tmp"
udevadm control --reload 2>/dev/null
}

set_rail() { # set_rail <led> on|off
[ -f "$LEDS/$1/brightness" ] || die "$1: not present"
case "$2" in
on) set_led_rule "$1" 'ATTR{brightness}="255"'; echo 255 > "$LEDS/$1/brightness" ;;
off) set_led_rule "$1"; echo 0 > "$LEDS/$1/brightness" ;;
*) die "$1: on|off" ;;
esac
}

set_status_led() {
[ -f "$LEDS/ACT/trigger" ] || die "status_led: not present"
case "$1" in
off)
set_led_rule ACT 'ATTR{trigger}="none", ATTR{brightness}="0"'
echo none > "$LEDS/ACT/trigger"
echo 0 > "$LEDS/ACT/brightness"
;;
on)
# Sin la regla, al arrancar vuelve el disparador de fábrica (actividad de la tarjeta).
set_led_rule ACT
echo actpwr > "$LEDS/ACT/trigger" 2>/dev/null || echo mmc0 > "$LEDS/ACT/trigger"
;;
*) die "status_led: on|off" ;;
esac
}

set_cpu_max() {
local cfg p
case "$1" in
600|800|1000) ;;
*) die "cpu_max: 600|800|1000" ;;
esac
# Ya mismo (cpufreq) y al arrancar (arm_freq en config.txt).
for p in "$CPUFREQ"/policy*; do
[ -f "$p/scaling_max_freq" ] && echo "$(($1 * 1000))" > "$p/scaling_max_freq"
done
cfg=$(config_txt)
[ -f "$cfg" ] || die "no config.txt"
mkdir -p "$STATE_DIR"
[ -f "$STATE_DIR/config.txt.orig" ] || cp -a "$cfg" "$STATE_DIR/config.txt.orig"
# 1000 MHz es lo de fábrica: se quita el bloque que añadió ZeroPower (si lo hay) y, sin
# línea que cambiar, no hace falta añadirla.
if [ "$1" = 1000 ]; then
sed -i -E '/^# ZeroPower$/{N;N;/\n\[all\]\narm_freq=[0-9]+$/d}' "$cfg"
fi
if grep -qE '^[[:space:]]*arm_freq=' "$cfg"; then
sed -i -E "s/^[[:space:]]*arm_freq=.*/arm_freq=$1/" "$cfg"
elif [ "$1" != 1000 ]; then
printf '\n# ZeroPower\n[all]\narm_freq=%s\n' "$1" >> "$cfg"
fi
sync
}

set_value() {
remember_original "$1"
case "$1" in
Expand All @@ -282,6 +415,11 @@ set_value() {
tailscale) set_tailscale "$2" ;;
extra_services) set_extra_services "$2" ;;
journal_ram) set_journal_ram "$2" ;;
nfs|avahi|apt_timers|man_db|e2scrub) set_service "$1" "$2" ;;
cpu_max) set_cpu_max "$2" ;;
status_led) set_status_led "$2" ;;
grove_5v) set_rail grove_5v_out "$2" ;;
gpio_5v) set_rail ext_5v_out "$2" ;;
*) die "unknown setting: $1" ;;
esac
}
Expand All @@ -294,9 +432,13 @@ restore() {
k=$(basename "$f")
v=$(cat "$f")
case "$v" in absent) continue ;; esac
case " $KEYS " in *" $k "*) ;; *) continue ;; esac
case " $RESTORE_KEYS " in *" $k "*) ;; *) continue ;; esac
# Las salidas de 5 V se quedan como estén ahora: sólo se quita su regla (abajo).
case "$k" in grove_5v|gpio_5v) continue ;; esac
[ "$(get_value "$k")" = "$v" ] || set_value "$k" "$v"
done
rm -f "$LED_RULE"
udevadm control --reload 2>/dev/null
rm -rf "$STATE_DIR"
}

Expand Down
Loading