From aedc4e872023701c7c6fdd9ab572a26a2eb800d3 Mon Sep 17 00:00:00 2001 From: Z3R0C1PH3R Date: Tue, 24 Nov 2026 23:45:58 +0530 Subject: [PATCH 1/8] =?UTF-8?q?Contrase=C3=B1a=20de=20sudo=20en=20pantalla?= =?UTF-8?q?=20en=20vez=20de=20exigir=20sudo=20sin=20contrase=C3=B1a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Si `sudo -n` dice que hace falta contraseña, la lista de ajustes la pide encima («Password required») y repite el cambio con `sudo -S -p ""`. La contraseña va por la entrada estándar (run_process admite ahora entrada), nunca en la línea de órdenes; no se guarda y se borra de la memoria al acabar (SecretInput, wipe). Si no vale, se vuelve a pedir con el aviso en rojo. Sudo la recuerda unos minutos. - model/sudo_password: classify_sudo (mensajes de sudo con LC_ALL=C) y SecretInput, con pruebas en power_model_test. - linux_input: Shift (mayúsculas y signos de un teclado de PC) y la capa Sym del Cardputer, leída de su mapa de teclas; al soltar sale la misma tecla que al pulsar. - La T no cambia el tema mientras se escribe la contraseña. - Simulador: ZEROPOWER_SIMULATE_SUDO= para probar la pantalla. --- CLAUDE.md | 8 +- README.md | 7 +- app-builder.json | 2 +- src/model/sudo_password.cpp | 95 +++++++++++++ src/model/sudo_password.h | 61 +++++++++ src/platform/linux_input.cpp | 137 ++++++++++++++++++- src/platform/power_control.cpp | 56 +++++++- src/platform/power_control.h | 15 ++- src/platform/process.cpp | 41 +++++- src/platform/process.h | 4 +- src/view/screens/settings_screen.cpp | 193 ++++++++++++++++++++++++++- src/view/screens/settings_screen.h | 29 ++++ src/viewmodel/base_viewmodel.cpp | 5 +- src/viewmodel/base_viewmodel.h | 7 + tests/power_model_test.cpp | 36 +++++ 15 files changed, 667 insertions(+), 29 deletions(-) create mode 100644 src/model/sudo_password.cpp create mode 100644 src/model/sudo_password.h diff --git a/CLAUDE.md b/CLAUDE.md index e067a62..1dca289 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,7 +46,13 @@ 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 ` 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=`. 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 diff --git a/README.md b/README.md index 68124c9..303aa5c 100644 --- a/README.md +++ b/README.md @@ -62,8 +62,11 @@ volver a aplicarlo. **Al desinstalar ZeroPower, todo lo que cambió vuelve a com `/usr/lib/zeropower/zeropower-helper status` (sin root). - **Para cambiar algo** llama a `sudo -n /usr/lib/zeropower/zeropower-helper set `, 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). diff --git a/app-builder.json b/app-builder.json index 4c060a3..7bcd4ec 100644 --- a/app-builder.json +++ b/app-builder.json @@ -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) 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 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" ], diff --git a/src/model/sudo_password.cpp b/src/model/sudo_password.cpp new file mode 100644 index 0000000..5311f6c --- /dev/null +++ b/src/model/sudo_password.cpp @@ -0,0 +1,95 @@ +/* + * SPDX-License-Identifier: MIT + */ + +#include "sudo_password.h" + +namespace power { +namespace { + +bool contains(const std::string& text, const char* what) { + return text.find(what) != std::string::npos; +} + +} // namespace + +SudoOutcome classify_sudo(int exit_code, const std::string& output) { + if (exit_code == 0) { + return SudoOutcome::Ok; + } + // "Sorry, try again." sale en cuanto una contraseña falla, aunque luego diga otra cosa. + if (contains(output, "incorrect password") || contains(output, "Sorry, try again")) { + return SudoOutcome::WrongPassword; + } + if (contains(output, "a password is required") || contains(output, "no password was provided")) { + return SudoOutcome::NeedsPassword; + } + if (contains(output, "is not in the sudoers") || contains(output, "is not allowed to") || + contains(output, "may not run sudo")) { + return SudoOutcome::NotAllowed; + } + return SudoOutcome::Failed; +} + +void wipe(std::string& text) { + volatile char* p = text.empty() ? nullptr : &text[0]; + for (std::size_t i = 0; i < text.size(); ++i) { + p[i] = '\0'; + } + text.clear(); +} + +SecretInput::SecretInput() { + text_.reserve(kMaxLength + 1); // +1: el salto de línea de take_line() +} + +SecretInput::~SecretInput() { + clear(); +} + +bool SecretInput::add(std::uint32_t ch) { + if (ch < 0x20 || ch > 0x7E || text_.size() >= kMaxLength) { + return false; + } + text_.push_back(static_cast(ch)); + return true; +} + +bool SecretInput::backspace() { + if (text_.empty()) { + return false; + } + text_.back() = '\0'; + text_.pop_back(); + return true; +} + +void SecretInput::clear() { + wipe(text_); +} + +std::string SecretInput::masked(std::size_t max_dots) const { + std::string out; + std::size_t dots = text_.size(); + if (dots > max_dots) { + out = "\u2026"; + dots = max_dots; + } + for (std::size_t i = 0; i < dots; ++i) { + out += "\u2022"; + } + return out; +} + +std::string SecretInput::take_line() { + // Siempre en el montón (más de lo que cabe dentro del propio std::string): al moverla de + // un sitio a otro se pasa el puntero y no quedan copias sueltas. + std::string line; + line.reserve(kMaxLength + 1); + line = text_; + line.push_back('\n'); + clear(); + return line; +} + +} // namespace power diff --git a/src/model/sudo_password.h b/src/model/sudo_password.h new file mode 100644 index 0000000..2aca8fa --- /dev/null +++ b/src/model/sudo_password.h @@ -0,0 +1,61 @@ +/* + * SPDX-License-Identifier: MIT + */ + +#pragma once + +#include +#include +#include + +namespace power { + +// Qué ha pasado con una orden lanzada con sudo, según su código de salida y lo que dice +// (sudo se lanza con LC_ALL=C: los mensajes llegan en inglés). +enum class SudoOutcome { + Ok, // la orden se ejecutó y acabó bien + NeedsPassword, // `sudo -n` sin contraseña guardada: hay que pedirla + WrongPassword, // la contraseña no vale + NotAllowed, // el usuario no puede usar sudo para esto + Failed, // la orden se ejecutó y falló, o sudo falló por otra cosa +}; + +SudoOutcome classify_sudo(int exit_code, const std::string& output); + +// Borra el contenido de verdad (el compilador no puede quitarse la escritura de encima) y +// deja la cadena vacía. +void wipe(std::string& text); + +// Lo que se teclea en la pantalla de la contraseña. Reserva la memoria de una vez, para +// que al crecer no queden copias de la contraseña por el montón, y la borra al limpiar. +class SecretInput { +public: + static constexpr std::size_t kMaxLength = 128; + + SecretInput(); + ~SecretInput(); + SecretInput(const SecretInput&) = delete; + SecretInput& operator=(const SecretInput&) = delete; + + bool add(std::uint32_t ch); // sólo ASCII imprimible; false si no cabe o no vale + bool backspace(); + void clear(); + + std::size_t size() const { + return text_.size(); + } + bool empty() const { + return text_.empty(); + } + // Un punto por carácter, para enseñarla sin enseñarla. Si son más de `max_dots`, sólo + // los últimos, detrás de «…». + std::string masked(std::size_t max_dots = kMaxLength) const; + // Lo tecleado seguido de un salto de línea (lo que espera `sudo -S`), y se borra de aquí. + // Quien lo recibe tiene que borrarlo con wipe() al acabar. + std::string take_line(); + +private: + std::string text_; +}; + +} // namespace power diff --git a/src/platform/linux_input.cpp b/src/platform/linux_input.cpp index ee9ab8d..89867f5 100644 --- a/src/platform/linux_input.cpp +++ b/src/platform/linux_input.cpp @@ -51,6 +51,11 @@ struct EvdevKeypad { bool router_event_pending{false}; uint32_t router_key{0}; bool router_pressed{false}; + bool cardputer{false}; // el teclado del Cardputer (tca8418), con su capa Sym + bool shift{false}; + // Lo que dio cada tecla al pulsarla: al soltarla tiene que salir lo mismo aunque + // entretanto se haya soltado Shift, o se quedaría pulsada. + std::array pressed_as{}; }; #endif @@ -242,10 +247,118 @@ uint32_t map_evdev_char(uint16_t code) { return 0; } -uint32_t map_evdev_key(uint16_t code) { +// Teclado de PC (distribución de EE. UU.): lo que dan los números y signos con Shift, y los +// signos que map_evdev_char no trae (sólo hacen falta para escribir la contraseña). +uint32_t map_us_symbol(uint16_t code, bool shift) { + static constexpr struct { + uint16_t code; + char plain; + char shifted; + } kSymbols[] = { + {KEY_1, '1', '!'}, {KEY_2, '2', '@'}, {KEY_3, '3', '#'}, + {KEY_4, '4', '$'}, {KEY_5, '5', '%'}, {KEY_6, '6', '^'}, + {KEY_7, '7', '&'}, {KEY_8, '8', '*'}, {KEY_9, '9', '('}, + {KEY_0, '0', ')'}, {KEY_MINUS, '-', '_'}, {KEY_EQUAL, '=', '+'}, + {KEY_LEFTBRACE, '[', '{'}, {KEY_RIGHTBRACE, ']', '}'}, {KEY_SEMICOLON, ';', ':'}, + {KEY_APOSTROPHE, '\'', '"'}, {KEY_GRAVE, '`', '~'}, {KEY_BACKSLASH, '\\', '|'}, + {KEY_COMMA, ',', '<'}, {KEY_DOT, '.', '>'}, {KEY_SLASH, '/', '?'}, + {KEY_KPASTERISK, '*', '*'}, {KEY_KPSLASH, '/', '/'}, {KEY_KPDOT, '.', '.'}, + }; + for (const auto& entry : kSymbols) { + if (entry.code == code) { + return static_cast(shift ? entry.shifted : entry.plain); + } + } + return 0; +} + +// La capa Sym del Cardputer: el teclado manda códigos propios para cada signo, que no son +// los de un teclado de PC (el 51, la coma de un PC, aquí es «&»). Se leen de su mapa de +// teclas, que trae el sistema, y si no está, los de la versión que hay ahora. +constexpr const char* kCardputerKeymap = "/usr/share/keymaps/tca8418_keypad_m5stack_keymap.map"; + +uint32_t keysym_char(const std::string& name) { + static constexpr struct { + const char* name; + char ch; + } kNames[] = { + {"exclam", '!'}, {"at", '@'}, {"numbersign", '#'}, {"dollar", '$'}, + {"percent", '%'}, {"asciicircum", '^'}, {"ampersand", '&'}, {"asterisk", '*'}, + {"parenleft", '('}, {"parenright", ')'}, {"asciitilde", '~'}, {"grave", '`'}, + {"underscore", '_'}, {"minus", '-'}, {"plus", '+'}, {"equal", '='}, + {"bracketleft", '['}, {"bracketright", ']'}, {"braceleft", '{'}, {"braceright", '}'}, + {"semicolon", ';'}, {"colon", ':'}, {"apostrophe", '\''}, {"quotedbl", '"'}, + {"less", '<'}, {"greater", '>'}, {"backslash", '\\'}, {"bar", '|'}, + {"comma", ','}, {"period", '.'}, {"slash", '/'}, {"question", '?'}, + }; + for (const auto& entry : kNames) { + if (name == entry.name) { + return static_cast(entry.ch); + } + } + return 0; +} + +const std::array& cardputer_symbols() { + static const std::array table = [] { + std::array t{}; + bool loaded = false; + if (FILE* f = std::fopen(kCardputerKeymap, "r")) { + char line[160]; + while (std::fgets(line, sizeof(line), f)) { + unsigned code = 0; + char name[48] = {}; + if (std::sscanf(line, " keycode %u = %47s", &code, name) == 2 && code < KEY_CNT) { + if (const uint32_t ch = keysym_char(name)) { + t[code] = ch; + loaded = true; + } + } + } + std::fclose(f); + } + if (!loaded) { + static constexpr struct { + uint16_t code; + char ch; + } kDefault[] = { + {26, '!'}, {27, '@'}, {39, '#'}, {40, '$'}, {41, '%'}, {43, '^'}, {51, '&'}, + {52, '*'}, {53, '('}, {94, ')'}, {55, '~'}, {69, '`'}, {70, '_'}, {71, '-'}, + {72, '+'}, {73, '='}, {74, '['}, {75, ']'}, {76, '{'}, {77, '}'}, {79, ';'}, + {80, ':'}, {81, '\''}, {82, '"'}, {83, '<'}, {85, '>'}, {86, '\\'}, {89, '|'}, + {90, ','}, {91, '.'}, {92, '/'}, {93, '?'}, + }; + for (const auto& entry : kDefault) { + t[entry.code] = static_cast(entry.ch); + } + } + return t; + }(); + return table; +} + +uint32_t map_evdev_key(uint16_t code, const EvdevKeypad& keypad) { + if (keypad.cardputer && code < KEY_CNT) { + if (const uint32_t ch = cardputer_symbols()[code]) { + return ch; + } + } if (const uint32_t ch = map_evdev_char(code)) { + if (keypad.shift && ch >= 'a' && ch <= 'z') { + return ch - 'a' + 'A'; + } + if (!keypad.cardputer && keypad.shift) { + if (const uint32_t sym = map_us_symbol(code, true)) { + return sym; + } + } return ch; } + if (!keypad.cardputer) { + if (const uint32_t sym = map_us_symbol(code, keypad.shift)) { + return sym; + } + } switch (code) { case KEY_ESC: return LV_KEY_ESC; @@ -309,12 +422,24 @@ void evdev_read_cb(lv_indev_t* indev, lv_indev_data_t* data) { input_event input{}; while (read(keypad->fd, &input, sizeof(input)) == sizeof(input)) { - if (input.type != EV_KEY) { + if (input.type != EV_KEY || input.value == 2 || input.code >= KEY_CNT) { + continue; + } + if (input.code == KEY_LEFTSHIFT || input.code == KEY_RIGHTSHIFT) { + keypad->shift = input.value != 0; continue; } - const auto key = map_evdev_key(input.code); - if (!key || input.value == 2) { + uint32_t key = 0; + if (input.value) { + key = map_evdev_key(input.code, *keypad); + keypad->pressed_as[input.code] = key; + } + else { + key = keypad->pressed_as[input.code]; + keypad->pressed_as[input.code] = 0; + } + if (!key) { continue; } @@ -347,6 +472,10 @@ void evdev_delete_cb(lv_event_t* event) { lv_indev_t* create_keypad_from_fd(int fd) { auto* keypad = new EvdevKeypad; keypad->fd = fd; + char name[64] = {}; + if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), name) >= 0) { + keypad->cardputer = std::strncmp(name, "tca8418", 7) == 0; + } auto* indev = lv_indev_create(); if (!indev) { diff --git a/src/platform/power_control.cpp b/src/platform/power_control.cpp index c9b9612..8deb4d1 100644 --- a/src/platform/power_control.cpp +++ b/src/platform/power_control.cpp @@ -6,6 +6,7 @@ #include "power_settings.h" #include "process.h" +#include "sudo_password.h" #include #include @@ -48,6 +49,11 @@ PowerControl::PowerControl() { } } fake_system_["gpu_mem_active"] = "64"; + const char* fake = std::getenv("ZEROPOWER_SIMULATE_SUDO"); + if (fake && *fake) { + fake_sudo_password_ = std::string(fake) + "\n"; + fake_sudo_ok_ = false; + } } } @@ -75,7 +81,15 @@ std::map PowerControl::read_all() { return values; } -PowerControl::Result PowerControl::apply(const std::string& key, const std::string& value) { +PowerControl::Result PowerControl::apply(const std::string& key, const std::string& value, + std::string password_line) { + struct Wiper { + std::string& s; + ~Wiper() { + power::wipe(s); + } + } wiper{password_line}; + Result result; const power::SettingInfo* info = power::find_setting(key); if (!info || power::option_index(*info, value) < 0) { @@ -112,15 +126,33 @@ PowerControl::Result PowerControl::apply(const std::string& key, const std::stri if (simulated_) { std::this_thread::sleep_for(std::chrono::milliseconds(400)); // como si tardara + if (!fake_sudo_ok_) { + if (password_line.empty()) { + result.needs_password = true; + return result; + } + if (password_line != fake_sudo_password_) { + result.wrong_password = true; + result.message = "Wrong password"; + return result; + } + fake_sudo_ok_ = true; + } fake_system_[key] = value; result.ok = true; result.value = value; return result; } - const auto r = run_process({"sudo", "-n", kHelper, "set", key, value}); + // LC_ALL=C: los mensajes de sudo, en inglés, para poder entenderlos. + // -p "": sin el texto "[sudo] password for…" mezclado con la respuesta del ayudante. + const auto r = password_line.empty() + ? run_process({"env", "LC_ALL=C", "sudo", "-n", kHelper, "set", key, value}) + : run_process({"env", "LC_ALL=C", "sudo", "-S", "-p", "", kHelper, "set", key, value}, + password_line); const std::string line = last_line(r.output); - if (r.exit_code == 0) { + switch (power::classify_sudo(r.exit_code, r.output)) { + case power::SudoOutcome::Ok: { const auto kv = power::parse_key_values(line); const auto it = kv.find(key); result.value = it != kv.end() ? it->second : value; @@ -128,10 +160,22 @@ PowerControl::Result PowerControl::apply(const std::string& key, const std::stri if (!result.ok) { result.message = "Now: " + power::option_label(*info, result.value); } - } else if (line.find("password") != std::string::npos || line.find("sudo") != std::string::npos) { - result.message = "Needs passwordless sudo"; - } else { + break; + } + case power::SudoOutcome::NeedsPassword: + result.needs_password = true; + result.message = "Password required"; + break; + case power::SudoOutcome::WrongPassword: + result.wrong_password = true; + result.message = "Wrong password"; + break; + case power::SudoOutcome::NotAllowed: + result.message = "This user can't use sudo"; + break; + case power::SudoOutcome::Failed: result.message = line.empty() ? "Failed" : line; + break; } return result; } diff --git a/src/platform/power_control.h b/src/platform/power_control.h index 578eca5..fdacef5 100644 --- a/src/platform/power_control.h +++ b/src/platform/power_control.h @@ -31,16 +31,25 @@ class PowerControl { struct Result { bool ok = false; - std::string value; // el valor que queda puesto - std::string message; // por qué falló + std::string value; // el valor que queda puesto + std::string message; // por qué falló + bool needs_password = false; // sudo pide la contraseña: hay que preguntarla y repetir + bool wrong_password = false; // la que se le dio no vale }; - Result apply(const std::string& key, const std::string& value); + // Sin `password_line`, prueba `sudo -n` (sin contraseña, o con la que sudo recuerda de + // hace poco). Con ella (la contraseña y un salto de línea) se la pasa a `sudo -S` por la + // entrada estándar, y la borra al acabar. Nunca se guarda ni va en la línea de órdenes. + Result apply(const std::string& key, const std::string& value, std::string password_line = ""); private: std::map read_daemon_values() const; bool simulated_ = false; std::map fake_system_; + // Para probar la pantalla de la contraseña en el simulador: ZEROPOWER_SIMULATE_SUDO= + // hace que el sistema simulado la pida (una vez, como sudo, que luego la recuerda). + std::string fake_sudo_password_; + bool fake_sudo_ok_ = true; }; } // namespace platform diff --git a/src/platform/process.cpp b/src/platform/process.cpp index 05f78d3..a5ad78b 100644 --- a/src/platform/process.cpp +++ b/src/platform/process.cpp @@ -4,6 +4,7 @@ #include "process.h" +#include #include #include @@ -13,7 +14,7 @@ namespace platform { -ProcessResult run_process(const std::vector& argv) { +ProcessResult run_process(const std::vector& argv, const std::string& input) { ProcessResult result; if (argv.empty()) { return result; @@ -22,6 +23,16 @@ ProcessResult run_process(const std::vector& argv) { if (::pipe2(pipefd, O_CLOEXEC) != 0) { return result; } + int infd[2] = {-1, -1}; + if (!input.empty()) { + // Si el hijo sale sin leer la entrada, escribir daría SIGPIPE y mataría la app. + ::signal(SIGPIPE, SIG_IGN); + if (::pipe2(infd, O_CLOEXEC) != 0) { + ::close(pipefd[0]); + ::close(pipefd[1]); + return result; + } + } // Todo lo que reserva memoria, antes del fork (la app tiene hilos). std::vector args; args.reserve(argv.size() + 1); @@ -34,19 +45,41 @@ ProcessResult run_process(const std::vector& argv) { if (pid < 0) { ::close(pipefd[0]); ::close(pipefd[1]); + if (infd[0] >= 0) { + ::close(infd[0]); + ::close(infd[1]); + } return result; } if (pid == 0) { + ::signal(SIGPIPE, SIG_DFL); // un SIG_IGN se heredaría a través de exec ::dup2(pipefd[1], STDOUT_FILENO); ::dup2(pipefd[1], STDERR_FILENO); - const int devnull = ::open("/dev/null", O_RDONLY); - if (devnull >= 0) { - ::dup2(devnull, STDIN_FILENO); + if (infd[0] >= 0) { + ::dup2(infd[0], STDIN_FILENO); + } else { + const int devnull = ::open("/dev/null", O_RDONLY); + if (devnull >= 0) { + ::dup2(devnull, STDIN_FILENO); + } } ::execvp(args[0], args.data()); ::_exit(127); } ::close(pipefd[1]); + if (infd[0] >= 0) { + // Cabe de sobra en el búfer de la tubería: se escribe entero antes de leer la salida. + ::close(infd[0]); + std::size_t done = 0; + while (done < input.size()) { + const ssize_t w = ::write(infd[1], input.data() + done, input.size() - done); + if (w <= 0) { + break; + } + done += static_cast(w); + } + ::close(infd[1]); + } char buf[512]; ssize_t n; while ((n = ::read(pipefd[0], buf, sizeof(buf))) > 0) { diff --git a/src/platform/process.h b/src/platform/process.h index 398a1fa..3145ef1 100644 --- a/src/platform/process.h +++ b/src/platform/process.h @@ -16,7 +16,9 @@ struct ProcessResult { // Lanza `argv[0]` (buscándolo en el PATH) con esos argumentos, sin shell: nada de lo que va // en los argumentos se interpreta. Espera a que acabe y devuelve su salida. -ProcessResult run_process(const std::vector& argv); +// `input` va a su entrada estándar (vacío: /dev/null). Así llega la contraseña a `sudo -S` +// sin aparecer en la línea de órdenes, que cualquiera ve en /proc. +ProcessResult run_process(const std::vector& argv, const std::string& input = ""); // Lee un fichero de texto entero ("" si no se puede). std::string read_text_file(const std::string& path); diff --git a/src/view/screens/settings_screen.cpp b/src/view/screens/settings_screen.cpp index 30fdfa6..a152f80 100644 --- a/src/view/screens/settings_screen.cpp +++ b/src/view/screens/settings_screen.cpp @@ -8,8 +8,12 @@ #include "theme.h" #include +#include #include +#include +#include + namespace screen { namespace { @@ -37,6 +41,18 @@ void set_text(lv_obj_t* label, const std::string& text) { } } +// La contraseña que pide sudo es la del usuario con el que corre la app. +std::string user_name() { + if (const passwd* pw = ::getpwuid(::geteuid())) { + return pw->pw_name; + } + const char* user = std::getenv("USER"); + return user ? user : "this user"; +} + +// Los puntos que caben en la casilla de la contraseña. +constexpr std::size_t kMaxDots = 34; + } // namespace SettingsScreen::SettingsScreen(viewmodel::BaseViewModel& view_model, app::AssetManager& assets, @@ -45,6 +61,18 @@ SettingsScreen::SettingsScreen(viewmodel::BaseViewModel& view_model, app::AssetM init(); this->view_model().set_page_handlers(this, [this](uint32_t key) { return handle_key(key); }, [this]() { + // ESC en la contraseña: no se cambia nada (mientras + // sudo la comprueba no se puede deshacer: espera). + if (prompt_open_) { + if (!prompt_checking_) { + close_password_prompt(); + std::lock_guard lock(mutex_); + message_ = "Not changed"; + message_error_ = false; + } + refresh(); + return true; + } // ESC con un valor elegido sin aplicar: se descarta // y se queda; otro ESC vuelve al menú. if (!pending_.empty() || !confirm_key_.empty()) { @@ -124,6 +152,49 @@ void SettingsScreen::build_content(lv_obj_t* content) { lv_obj_set_width(status_, kW - 2 * kMargin - 6); lv_obj_align(status_, LV_ALIGN_BOTTOM_LEFT, kMargin + 3, -2); + // La contraseña: tapa la lista entera mientras se pide. + prompt_ = lv_obj_create(content); + lv_obj_remove_style_all(prompt_); + lv_obj_set_size(prompt_, LV_PCT(100), LV_PCT(100)); + lv_obj_set_style_bg_opa(prompt_, LV_OPA_COVER, 0); + lv_obj_remove_flag(prompt_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(prompt_, LV_OBJ_FLAG_HIDDEN); + + prompt_title_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_title_, title_font ? title_font : &lv_font_montserrat_12, 0); + lv_obj_set_pos(prompt_title_, kMargin + 3, kTop + 2); + lv_label_set_text(prompt_title_, "Password required"); + + prompt_text_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_text_, small ? small : &lv_font_montserrat_12, 0); + lv_label_set_long_mode(prompt_text_, LV_LABEL_LONG_WRAP); + lv_obj_set_width(prompt_text_, kW - 2 * kMargin - 6); + lv_obj_set_pos(prompt_text_, kMargin + 3, kTop + 22); + + prompt_field_ = lv_obj_create(prompt_); + lv_obj_remove_style_all(prompt_field_); + lv_obj_set_size(prompt_field_, kW - 2 * kMargin, 22); + lv_obj_set_pos(prompt_field_, kMargin, kTop + 56); + lv_obj_set_style_radius(prompt_field_, 3, 0); + lv_obj_set_style_border_width(prompt_field_, 1, 0); + lv_obj_set_style_bg_opa(prompt_field_, LV_OPA_COVER, 0); + lv_obj_remove_flag(prompt_field_, LV_OBJ_FLAG_SCROLLABLE); + + prompt_dots_ = lv_label_create(prompt_field_); + lv_obj_set_style_text_font(prompt_dots_, value_font ? value_font : &lv_font_montserrat_12, 0); + lv_label_set_long_mode(prompt_dots_, LV_LABEL_LONG_CLIP); + lv_obj_set_width(prompt_dots_, kW - 2 * kMargin - 12); + lv_obj_align(prompt_dots_, LV_ALIGN_LEFT_MID, 6, 0); + + prompt_error_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_error_, small ? small : &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(prompt_error_, kErrorColor, 0); + lv_obj_set_pos(prompt_error_, kMargin + 3, kTop + 82); + + prompt_footer_ = lv_label_create(prompt_); + lv_obj_set_style_text_font(prompt_footer_, small ? small : &lv_font_montserrat_12, 0); + lv_obj_align(prompt_footer_, LV_ALIGN_BOTTOM_LEFT, kMargin + 3, -2); + lv_subject_add_observer_obj(view_model().dark_mode_subject(), theme_observer_cb, content, this); timer_ = lv_timer_create(timer_cb, 150, this); refresh(); @@ -144,6 +215,9 @@ void SettingsScreen::start_job(std::function job) { } bool SettingsScreen::handle_key(uint32_t key) { + if (prompt_open_) { + return handle_password_key(key); + } if (settings_.empty()) { return false; } @@ -226,16 +300,36 @@ void SettingsScreen::apply_value(const power::SettingInfo& info, const std::stri } confirm_key_.clear(); pending_.erase(info.key); - applying_key_ = info.key; + run_apply(info.key, target, ""); +} + +void SettingsScreen::run_apply(const std::string& key, const std::string& target, std::string password_line) { + const power::SettingInfo* info = power::find_setting(key); + if (!info || busy_) { + power::wipe(password_line); + return; + } + applying_key_ = key; applying_value_ = target; - const std::string key_name = info.key; { std::lock_guard lock(mutex_); - message_ = "Applying " + std::string(info.title) + "…"; + message_ = "Applying " + std::string(info->title) + "…"; message_error_ = false; } - start_job([this, key_name, target]() { - const auto result = control_.apply(key_name, target); + // La contraseña se mueve al hilo y PowerControl::apply la borra al acabar. + start_job([this, key_name = key, target, line = std::move(password_line)]() mutable { + const auto result = control_.apply(key_name, target, std::move(line)); + power::wipe(line); + if (result.needs_password || result.wrong_password) { + std::lock_guard lock(mutex_); + password_wanted_ = true; + password_wrong_ = result.wrong_password; + password_key_ = key_name; + password_value_ = target; + message_.clear(); + message_error_ = false; + return; + } auto values = control_.read_all(); std::lock_guard lock(mutex_); values_ = std::move(values); @@ -253,6 +347,74 @@ void SettingsScreen::apply_value(const power::SettingInfo& info, const std::stri }); } +bool SettingsScreen::handle_password_key(uint32_t key) { + if (prompt_checking_) { + return true; // sudo la está comprobando: se espera + } + switch (key) { + case LV_KEY_ENTER: + case '\r': + // El espacio no: puede ir en la contraseña. + if (!password_.empty() && !busy_) { + prompt_checking_ = true; + run_apply(prompt_key_, prompt_value_, password_.take_line()); + } + break; + case LV_KEY_BACKSPACE: + password_.backspace(); + prompt_wrong_ = false; + break; + default: + if (password_.add(key)) { + prompt_wrong_ = false; + } + break; + } + refresh(); + return true; // con la contraseña abierta ninguna tecla hace otra cosa +} + +void SettingsScreen::open_password_prompt(bool wrong) { + password_.clear(); + prompt_open_ = true; + prompt_checking_ = false; + prompt_wrong_ = wrong; + view_model().set_text_entry(true); +} + +void SettingsScreen::close_password_prompt() { + password_.clear(); + prompt_open_ = false; + prompt_checking_ = false; + prompt_wrong_ = false; + prompt_key_.clear(); + prompt_value_.clear(); + view_model().set_text_entry(false); +} + +void SettingsScreen::refresh_password_prompt(const view::ThemePalette& colors) { + if (!prompt_open_) { + lv_obj_add_flag(prompt_, LV_OBJ_FLAG_HIDDEN); + return; + } + lv_obj_remove_flag(prompt_, LV_OBJ_FLAG_HIDDEN); + lv_obj_set_style_bg_color(prompt_, colors.background, 0); + lv_obj_set_style_text_color(prompt_title_, colors.text, 0); + lv_obj_set_style_text_color(prompt_text_, colors.text_disabled, 0); + lv_obj_set_style_text_color(prompt_footer_, prompt_checking_ ? colors.text_disabled : colors.text, 0); + lv_obj_set_style_text_color(prompt_dots_, colors.text, 0); + lv_obj_set_style_bg_color(prompt_field_, colors.surface, 0); + lv_obj_set_style_border_color(prompt_field_, prompt_wrong_ ? kErrorColor : colors.primary, 0); + + const power::SettingInfo* info = power::find_setting(prompt_key_); + const std::string what = info ? std::string(info->title) + " → " + power::option_label(*info, prompt_value_) + : std::string("this setting"); + set_text(prompt_text_, "Changing " + what + " needs root. Enter the sudo password for " + user_name() + "."); + set_text(prompt_dots_, password_.masked(kMaxDots) + (prompt_checking_ ? "" : "_")); + set_text(prompt_error_, prompt_wrong_ ? "Wrong password, try again" : ""); + set_text(prompt_footer_, prompt_checking_ ? "Checking password…" : "ENTER confirm ESC cancel"); +} + void SettingsScreen::refresh() { if (!status_) { return; @@ -262,13 +424,34 @@ void SettingsScreen::refresh() { bool loaded; std::string message; bool message_error; + bool password_wanted; + bool password_wrong; + std::string password_key; + std::string password_value; + // Antes que lo demás: el hilo deja su resultado y luego baja `busy_`, así que si aquí ya + // no trabaja, lo que se lea a continuación es lo último. + const bool busy = busy_; { std::lock_guard lock(mutex_); values = values_; loaded = loaded_; message = message_; message_error = message_error_; + password_wanted = password_wanted_; + password_wrong = password_wrong_; + password_key = password_key_; + password_value = password_value_; + password_wanted_ = false; + } + + if (password_wanted) { + open_password_prompt(password_wrong); + prompt_key_ = password_key; + prompt_value_ = password_value; + } else if (prompt_open_ && prompt_checking_ && !busy) { + close_password_prompt(); // la aceptó: el resultado sale abajo, como siempre } + refresh_password_prompt(colors); for (int i = 0; i < kMaxRows; ++i) { if (i >= static_cast(settings_.size())) { diff --git a/src/view/screens/settings_screen.h b/src/view/screens/settings_screen.h index 4ef19fb..8c36ba9 100644 --- a/src/view/screens/settings_screen.h +++ b/src/view/screens/settings_screen.h @@ -7,6 +7,8 @@ #include "base_screen.h" #include "power_control.h" #include "power_settings.h" +#include "sudo_password.h" +#include "theme.h" #include #include @@ -24,6 +26,9 @@ namespace screen { * interruptor (como en iOS) que ENTER, Z o C cambian y aplican al momento; los de varias * opciones se eligen con Z/C (queda pendiente, marcado) y ENTER los aplica. Leer el estado y aplicar se hace en otro hilo: el * ayudante tarda unas décimas y la pantalla no se queda congelada. + * + * Si sudo pide contraseña, se pide encima de la lista y el cambio se repite con ella. Sudo + * la recuerda unos minutos: los cambios siguientes ya no la piden. */ class SettingsScreen : public BaseScreen { public: @@ -37,9 +42,14 @@ class SettingsScreen : public BaseScreen { static constexpr int kMaxRows = 6; bool handle_key(uint32_t key); + bool handle_password_key(uint32_t key); void start_job(std::function job); void apply_value(const power::SettingInfo& info, const std::string& target); + void run_apply(const std::string& key, const std::string& target, std::string password_line); + void open_password_prompt(bool wrong); + void close_password_prompt(); void refresh(); + void refresh_password_prompt(const view::ThemePalette& colors); static void timer_cb(lv_timer_t* timer); static void theme_observer_cb(lv_observer_t* observer, lv_subject_t* subject); @@ -60,9 +70,28 @@ class SettingsScreen : public BaseScreen { bool loaded_ = false; std::string message_; bool message_error_ = false; + bool password_wanted_ = false; // el último cambio necesita contraseña + bool password_wrong_ = false; // ... porque la que se dio no valía + std::string password_key_; // el cambio que hay que repetir con ella + std::string password_value_; std::atomic busy_{false}; std::thread worker_; + // La pantalla de la contraseña (sólo en el hilo de LVGL). + power::SecretInput password_; + bool prompt_open_ = false; + bool prompt_checking_ = false; // sudo la está comprobando + bool prompt_wrong_ = false; + std::string prompt_key_; + std::string prompt_value_; + lv_obj_t* prompt_ = nullptr; + lv_obj_t* prompt_title_ = nullptr; + lv_obj_t* prompt_text_ = nullptr; + lv_obj_t* prompt_field_ = nullptr; + lv_obj_t* prompt_dots_ = nullptr; + lv_obj_t* prompt_error_ = nullptr; + lv_obj_t* prompt_footer_ = nullptr; + std::array row_boxes_{}; std::array row_titles_{}; std::array row_values_{}; diff --git a/src/viewmodel/base_viewmodel.cpp b/src/viewmodel/base_viewmodel.cpp index 4553dcb..b3f50a6 100644 --- a/src/viewmodel/base_viewmodel.cpp +++ b/src/viewmodel/base_viewmodel.cpp @@ -123,11 +123,12 @@ void BaseViewModel::clear_page_handlers(const void* owner) { page_handlers_owner_ = nullptr; page_key_handler_ = nullptr; page_back_handler_ = nullptr; + text_entry_ = false; } bool BaseViewModel::handle_key(uint32_t key) { - // El tema se cambia desde cualquier pantalla. - if (key == 't' || key == 'T') { + // El tema se cambia desde cualquier pantalla (menos mientras se escribe). + if ((key == 't' || key == 'T') && !text_entry_) { toggle_dark_mode(); return true; } diff --git a/src/viewmodel/base_viewmodel.h b/src/viewmodel/base_viewmodel.h index eb1f821..9f1dd3c 100644 --- a/src/viewmodel/base_viewmodel.h +++ b/src/viewmodel/base_viewmodel.h @@ -67,6 +67,12 @@ class BaseViewModel { void set_page_handlers(const void* owner, KeyHandler key_handler, BackHandler back_handler); void clear_page_handlers(const void* owner); + // Mientras una pantalla pide texto (la contraseña) todas las letras son suyas: la T no + // cambia el tema. + void set_text_entry(bool active) { + text_entry_ = active; + } + private: void move_selection(int delta); // Página que corresponde a la entrada `index` del menú Home. @@ -81,6 +87,7 @@ class BaseViewModel { const void* page_handlers_owner_ = nullptr; KeyHandler page_key_handler_; BackHandler page_back_handler_; + bool text_entry_ = false; }; } // namespace viewmodel diff --git a/tests/power_model_test.cpp b/tests/power_model_test.cpp index a40bd80..0919fe3 100644 --- a/tests/power_model_test.cpp +++ b/tests/power_model_test.cpp @@ -4,6 +4,7 @@ #include "power_logic.h" #include "power_settings.h" +#include "sudo_password.h" #include #include @@ -164,6 +165,40 @@ void test_screen_timeout() { CHECK(v.update(1000, -1, false, 60) == A::None); } +void test_sudo_password() { + using power::SudoOutcome; + CHECK(power::classify_sudo(0, "ethernet=off\n") == SudoOutcome::Ok); + CHECK(power::classify_sudo(1, "sudo: a password is required\n") == SudoOutcome::NeedsPassword); + CHECK(power::classify_sudo(1, "Sorry, try again.\nsudo: no password was provided\n" + "sudo: 1 incorrect password attempt\n") == SudoOutcome::WrongPassword); + CHECK(power::classify_sudo(1, "sudo: no password was provided\n") == SudoOutcome::NeedsPassword); + CHECK(power::classify_sudo(1, "pi is not in the sudoers file.\n") == SudoOutcome::NotAllowed); + CHECK(power::classify_sudo(1, "Sorry, user pi is not allowed to execute '/usr/lib/zeropower/zeropower-helper " + "set ethernet off' as root on cpz.\n") == SudoOutcome::NotAllowed); + CHECK(power::classify_sudo(2, "invalid value\n") == SudoOutcome::Failed); + + power::SecretInput in; + CHECK(in.empty() && in.masked().empty()); + CHECK(in.add('p') && in.add('W') && in.add('!') && in.add(' ')); + CHECK(!in.add('\n') && !in.add(0x7F) && !in.add(0xE9)); // control y no ASCII: fuera + CHECK(in.size() == 4); + CHECK(in.masked() == "\u2022\u2022\u2022\u2022"); + CHECK(in.masked(2) == "\u2026\u2022\u2022"); + CHECK(in.backspace() && in.size() == 3); + std::string line = in.take_line(); + CHECK(line == "pW!\n"); + CHECK(in.empty() && !in.backspace()); + power::wipe(line); + CHECK(line.empty()); + + for (std::size_t i = 0; i < power::SecretInput::kMaxLength; ++i) { + CHECK(in.add('a')); + } + CHECK(!in.add('a')); + in.clear(); + CHECK(in.empty()); +} + } // namespace int main() { @@ -173,6 +208,7 @@ int main() { test_low_battery_guard(); test_idle_tracker(); test_screen_timeout(); + test_sudo_password(); if (failures == 0) { std::printf("power_model_test: todo bien\n"); } From 8be44fe486f062bb6f1f75909658b0db9f9f3890 Mon Sep 17 00:00:00 2001 From: Z3R0C1PH3R Date: Wed, 25 Nov 2026 00:07:44 +0530 Subject: [PATCH 2/8] =?UTF-8?q?Avisos=20de=20la=20app=20en=20ingl=C3=A9s?= =?UTF-8?q?=20(salir=20con=20ESC,=20captura=20de=20pantalla)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El resto de la interfaz ya estaba en inglés: «Mantén ESC para salir», «Guardada en» y «No se pudo capturar» se habían quedado en español. Co-authored-by: Cursor --- src/app/app.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/app.cpp b/src/app/app.cpp index 68ec314..cd5675a 100644 --- a/src/app/app.cpp +++ b/src/app/app.cpp @@ -154,7 +154,7 @@ class ShortcutController { const auto result = platform::screenshot::capture_active_screen(); if (result.success) { LOG_INFO("screenshot saved: {}", result.path); - toast_->show_highlighted("Guardada en ", + toast_->show_highlighted("Saved to ", result.path, "", view::widgets::ToastTone::Success, @@ -163,7 +163,7 @@ class ShortcutController { } else { LOG_WARN("screenshot failed: {}", result.error); - toast_->show("No se pudo capturar: " + result.error, + toast_->show("Screenshot failed: " + result.error, view::widgets::ToastTone::Error, 3200); } @@ -230,7 +230,7 @@ class ShortcutController { if (!view_model_.back()) { // Ya no hay adónde volver: se recuerda cómo se sale en vez de salir con // una pulsación que pudo ser de más. - toast_->show_highlighted("Mantén ", "ESC", " para salir", view::widgets::ToastTone::Warning, 2200); + toast_->show_highlighted("Hold ", "ESC", " to exit", view::widgets::ToastTone::Warning, 2200); } } From cc9326deefd4b4d6c041d3cb8688ef91d92f5c43 Mon Sep 17 00:00:00 2001 From: Z3R0C1PH3R Date: Wed, 25 Nov 2026 00:30:31 +0530 Subject: [PATCH 3/8] =?UTF-8?q?Ayuda=20(Fn+H)=20en=20ingl=C3=A9s:=20=C2=AB?= =?UTF-8?q?Keys=C2=BB=20y=20=C2=ABclose=20/=20screenshot=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- src/view/widgets/help_popup.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/view/widgets/help_popup.cpp b/src/view/widgets/help_popup.cpp index 10b596f..cffd476 100644 --- a/src/view/widgets/help_popup.cpp +++ b/src/view/widgets/help_popup.cpp @@ -98,7 +98,7 @@ void HelpPopup::build() { lv_obj_add_flag(panel_, LV_OBJ_FLAG_CLICKABLE); title_ = lv_label_create(panel_); - lv_label_set_text(title_, "Teclas"); + lv_label_set_text(title_, "Keys"); auto* title_font = assets_.load_standard_font(15); lv_obj_set_style_text_font(title_, title_font ? title_font : &lv_font_montserrat_14, 0); lv_obj_align(title_, LV_ALIGN_TOP_LEFT, 12, 9); @@ -144,7 +144,7 @@ void HelpPopup::build() { } footer_ = lv_label_create(panel_); - lv_label_set_text(footer_, "Fn+H / ESC cerrar Fn+J captura"); + lv_label_set_text(footer_, "Fn+H / ESC close Fn+J screenshot"); lv_label_set_long_mode(footer_, LV_LABEL_LONG_CLIP); auto* footer_font = assets_.load_standard_font(10); lv_obj_set_style_text_font(footer_, footer_font ? footer_font : &lv_font_montserrat_10, 0); From 450da29229c24e3d17947fd9980beabebde7bed7 Mon Sep 17 00:00:00 2001 From: Z3R0C1PH3R Date: Wed, 25 Nov 2026 00:07:44 +0530 Subject: [PATCH 4/8] =?UTF-8?q?Lo=20que=20faltaba=20de=20cz-battery-saver:?= =?UTF-8?q?=20elegir=20qu=C3=A9=20hace=20el=20ahorro=20con=20la=20pantalla?= =?UTF-8?q?=20apagada,=20su=20retardo=20y=20cerrar=20Desk=20Mode=20al=20de?= =?UTF-8?q?sconectar=20el=20HDMI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Screen-off saver: Both / Sound card / Launcher / Off (idle_saver=on|audio|launcher|off; «on» sigue siendo las dos cosas, así que los power.conf de antes valen igual). - Saver delay: 3, 5, 10, 30 o 60 s con la pantalla apagada antes de empezar (antes, 5 fijos). - Desk Mode unplug (Hardware): con cz-desk-mode instalado, zeropowerd para su escritorio HDMI (unidad de usuario cz-desk-mode-desktop.service) tras 1, 5, 15 o 30 min con el HDMI desconectado. Por defecto Keep desktop, porque se pierde lo no guardado. Sin Desk Mode sale como «not installed». - UnplugTimer en power_logic, con pruebas; IdleTracker::set_delay. - Con 6 filas (Hardware) las filas miden 15 px para que la pista no tape la línea de estado. Co-authored-by: Cursor --- README.md | 10 ++++- app-builder.json | 2 +- src/daemon/zeropowerd.cpp | 58 ++++++++++++++++++++++++---- src/model/power_logic.cpp | 21 ++++++++++ src/model/power_logic.h | 18 +++++++++ src/model/power_settings.cpp | 35 +++++++++++++++-- src/model/power_settings.h | 15 ++++++- src/platform/power_control.cpp | 6 ++- src/view/screens/settings_screen.cpp | 9 +++-- tests/power_model_test.cpp | 41 ++++++++++++++++---- 10 files changed, 189 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 303aa5c..ee73d52 100644 --- a/README.md +++ b/README.md @@ -22,15 +22,20 @@ 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). - **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 + - **Screen-off saver**: con la pantalla apagada, aparca el audio del lanzador para que + duerman la tarjeta de sonido y el amplificador (~40 mA) y pausa el lanzador (~30 mA): + *Both*, sólo *Sound card*, sólo *Launcher* u *Off*. Una tecla lo despierta. Si hay una app abierta no pausa nada. + - **Saver delay**: cuánto tiene que llevar apagada la pantalla para lo anterior (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 @@ -54,6 +59,7 @@ volver a aplicarlo. **Al desinstalar ZeroPower, todo lo que cambió vuelve a com | | `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 diff --git a/app-builder.json b/app-builder.json index 7bcd4ec..a762414 100644 --- a/app-builder.json +++ b/app-builder.json @@ -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 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).", + "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). With Desk Mode, its HDMI desktop can close itself once HDMI is unplugged.\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 sleeps the sound card and/or pauses the launcher 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" ], diff --git a/src/daemon/zeropowerd.cpp b/src/daemon/zeropowerd.cpp index cf3dbef..9d882f9 100644 --- a/src/daemon/zeropowerd.cpp +++ b/src/daemon/zeropowerd.cpp @@ -5,14 +5,17 @@ // zeropowerd: lo que ZeroPower hace mientras usas el aparato. Es un servicio del sistema que // corre como el usuario del aparato (User=1000, el del lanzador), no como root: // -// - Pantalla apagada (brillo 0) durante 5 s: pausa el lanzador (SIGSTOP) y aparca su audio -// en un sumidero nulo para que el amplificador y la tarjeta de sonido duerman. Una tecla o +// - Pantalla apagada (brillo 0) durante `idle_delay` s (5 por defecto): pausa el lanzador +// (SIGSTOP) y aparca su audio en un sumidero nulo para que el amplificador y la tarjeta de +// sonido duerman (las dos cosas, o sólo una, según `idle_saver`). Una tecla o // la pantalla encendida lo despiertan. Si hay una app abierta desde el lanzador, no se // pausa nada (la app seguiría sin pantalla, pero quizá sonando o grabando). // - «Quiet launcher»: el audio del lanzador aparcado siempre (sin sonido de teclas). // - Batería baja: apaga ordenadamente tras tres lecturas seguidas en el umbral. // - Tiempo de pantalla: si la pantalla sigue encendida tras `screen_timeout` sin teclas (el // lanzador no la ha apagado, o hay una app abierta), la apaga él; una tecla la enciende. +// - Con Desk Mode: cierra su escritorio HDMI (una unidad de usuario) cuando el HDMI lleva +// `desktop_unplug` minutos desconectado. // // Las ideas (y las medidas de cuánto ahorra cada una) son de cz-battery-saver // (github.com/InstantComet/cz-battery-saver, MIT); el código es propio. @@ -235,6 +238,32 @@ bool drain_keys(int fd) { return pressed; } +// Algún conector HDMI con pantalla (card*-HDMI-A-*/status = connected). +bool hdmi_connected() { + DIR* dir = ::opendir("/sys/class/drm"); + if (!dir) { + return false; + } + bool connected = false; + while (auto* entry = ::readdir(dir)) { + const std::string name = entry->d_name; + if (name.rfind("card", 0) == 0 && name.find("-HDMI-A-") != std::string::npos) { + std::string status = platform::read_text_file("/sys/class/drm/" + name + "/status"); + if (status.rfind("connected", 0) == 0) { + connected = true; + break; + } + } + } + ::closedir(dir); + return connected; +} + +bool desk_mode_installed() { + std::error_code ec; + return fs::exists(power::kDeskModeDir, ec); +} + } // namespace int main() { @@ -250,6 +279,7 @@ int main() { power::DaemonConfig config; long long config_mtime = -1; power::IdleTracker idle(5.0); + power::UnplugTimer unplug; power::LowBatteryGuard low(3); power::ScreenTimeout screen; std::string app_name; // la app abierta desde el lanzador, para el registro @@ -278,6 +308,7 @@ int main() { if (mtime != config_mtime) { config_mtime = mtime; config = power::daemon_config_from(power::parse_key_values(platform::read_text_file(conf))); + idle.set_delay(config.idle_delay_s); } } @@ -338,14 +369,19 @@ int main() { app_name = app; } const bool app_open = !app.empty(); - const bool idle_enabled = config.idle_saver && launcher > 0 && !app_open && brightness >= 0; + const bool idle_enabled = (config.idle_audio || config.idle_launcher) && launcher > 0 && !app_open && + brightness >= 0; switch (idle.update(now_s(), brightness, key, idle_enabled)) { case power::IdleTracker::Action::Sleep: - audio.park(launcher); - if (::kill(launcher, SIGSTOP) == 0) { + if (config.idle_audio) { + audio.park(launcher); + } + if (config.idle_launcher && ::kill(launcher, SIGSTOP) == 0) { launcher_stopped = true; - say("screen off: launcher paused"); } + say("screen off: %s", config.idle_audio && launcher_stopped ? "sound card asleep, launcher paused" + : launcher_stopped ? "launcher paused" + : "sound card asleep"); break; case power::IdleTracker::Action::Wake: // Por qué: si un día se queda despierto sin motivo, que quede en el registro. @@ -369,9 +405,17 @@ int main() { } } - // Batería baja. + // Batería baja (y, de paso, el HDMI de Desk Mode). if (t >= next_battery) { next_battery = t + 20; + if (unplug.update(t, hdmi_connected(), config.desktop_unplug_min) && desk_mode_installed()) { + const auto active = platform::run_process({"systemctl", "--user", "is-active", power::kDeskModeUnit}); + if (active.output.rfind("active", 0) == 0) { + say("HDMI unplugged for %s min: closing the Desk Mode desktop", + std::to_string(config.desktop_unplug_min)); + platform::run_process({"systemctl", "--user", "stop", power::kDeskModeUnit}); + } + } const auto b = platform::read_battery(battery_dir); if (b.present && low.update(b.discharging(), b.capacity, config.low_battery_percent)) { say("battery at %s %%: powering off", std::to_string(b.capacity)); diff --git a/src/model/power_logic.cpp b/src/model/power_logic.cpp index 6e519c3..994b72f 100644 --- a/src/model/power_logic.cpp +++ b/src/model/power_logic.cpp @@ -87,6 +87,27 @@ IdleTracker::Action IdleTracker::update(double now_s, int brightness, bool key_p return Action::None; } +bool UnplugTimer::update(double now_s, bool connected, int minutes) { + if (connected || minutes <= 0) { + counting_ = false; + fired_ = false; + return false; + } + if (fired_) { + return false; // una vez por desconexión + } + if (!counting_) { + counting_ = true; + since_ = now_s; + return false; + } + if (now_s - since_ >= minutes * 60.0) { + fired_ = true; + return true; + } + return false; +} + ScreenTimeout::Action ScreenTimeout::update(double now_s, int brightness, bool key_pressed, double timeout_s) { if (!started_) { diff --git a/src/model/power_logic.h b/src/model/power_logic.h index 68a491c..a2cf568 100644 --- a/src/model/power_logic.h +++ b/src/model/power_logic.h @@ -74,6 +74,9 @@ class IdleTracker { bool sleeping() const { return sleeping_; } + void set_delay(double delay_s) { + delay_s_ = delay_s; + } private: double delay_s_; @@ -82,6 +85,21 @@ class IdleTracker { double dark_since_ = 0.0; }; +// --- HDMI desconectado --- + +// Cuenta cuánto lleva desconectado el HDMI y avisa una vez al pasar `minutes` (0 = nunca). +// Un cable flojo que vuelve antes de tiempo pone la cuenta a cero. +class UnplugTimer { +public: + // true: es el momento de cerrar el escritorio. + bool update(double now_s, bool connected, int minutes); + +private: + bool counting_ = false; + bool fired_ = false; + double since_ = 0.0; +}; + // --- Tiempo de pantalla --- // Red de seguridad: la pantalla la apaga el lanzador (su salvapantallas), pero si no lo hace diff --git a/src/model/power_settings.cpp b/src/model/power_settings.cpp index db662cf..d37490a 100644 --- a/src/model/power_settings.cpp +++ b/src/model/power_settings.cpp @@ -39,6 +39,9 @@ const std::vector& all_settings() { "Radio and service off. Small saving, frees some RAM.", kOnOff, "on"}, {"hdmi_desktop", Group::Hardware, Applier::System, "HDMI desktop", "Desktop for an HDMI screen (lightdm). Off frees ~25 MB RAM and CPU.", kOnOff, "on"}, + {"desktop_unplug", Group::Hardware, Applier::Daemon, "Desk Mode unplug", + "Close the Desk Mode desktop after HDMI is unplugged this long. Unsaved work is lost.", + {{"0", "Keep desktop"}, {"1", "1 min"}, {"5", "5 min"}, {"15", "15 min"}, {"30", "30 min"}}, "0"}, {"gpu_mem", Group::Hardware, Applier::System, "GPU memory", "RAM kept for the GPU firmware. 16 MB is enough for the built-in screen.", {{"16", "16 MB"}, {"32", "32 MB"}, {"64", "64 MB"}, {"128", "128 MB"}}, "64", true}, @@ -52,8 +55,11 @@ const std::vector& all_settings() { "System journal in RAM (16 MB): fewer SD card writes. Lost on reboot.", kOnOff, "off"}, // --- Power saving (zeropowerd) --- {"idle_saver", Group::Saving, Applier::Daemon, "Screen-off saver", - "Screen off: pause the launcher and its audio (~70 mA). A key wakes it.", kOnOff, - "on"}, + "Screen off: sleep the sound card (~40 mA) and pause the launcher (~30 mA). A key wakes it.", + {{"on", "Both"}, {"audio", "Sound card"}, {"launcher", "Launcher"}, {"off", "Off"}}, "on"}, + {"idle_delay", Group::Saving, Applier::Daemon, "Saver delay", + "How long the screen must be off before the screen-off saver starts.", + {{"3", "3 s"}, {"5", "5 s"}, {"10", "10 s"}, {"30", "30 s"}, {"60", "60 s"}}, "5"}, {"quiet_launcher", Group::Saving, Applier::Daemon, "Quiet launcher", "No launcher key sounds, so the audio amp can sleep (~35 mA).", kOnOff, "off"}, {"low_battery", Group::Saving, Applier::Daemon, "Low battery off", @@ -142,7 +148,14 @@ DaemonConfig daemon_config_from(const std::map& values } }; flag("quiet_launcher", config.quiet_launcher); - flag("idle_saver", config.idle_saver); + const auto idle = values.find("idle_saver"); + if (idle != values.end()) { + const std::string& v = idle->second; + if (v == "on" || v == "audio" || v == "launcher" || v == "off") { + config.idle_audio = v == "on" || v == "audio"; + config.idle_launcher = v == "on" || v == "launcher"; + } + } auto number = [&](const char* key, int& out) { const auto it = values.find(key); const SettingInfo* info = find_setting(key); @@ -150,18 +163,32 @@ DaemonConfig daemon_config_from(const std::map& values out = std::atoi(it->second.c_str()); } }; + number("idle_delay", config.idle_delay_s); number("low_battery", config.low_battery_percent); number("screen_timeout", config.screen_timeout_s); + number("desktop_unplug", config.desktop_unplug_min); return config; } +std::string idle_saver_value(const DaemonConfig& config) { + if (config.idle_audio && config.idle_launcher) { + return "on"; + } + if (config.idle_audio) { + return "audio"; + } + return config.idle_launcher ? "launcher" : "off"; +} + std::string daemon_config_text(const DaemonConfig& config) { std::ostringstream out; out << "# ZeroPower: options for zeropowerd (changed from the app)\n"; - out << "idle_saver=" << (config.idle_saver ? "on" : "off") << "\n"; + out << "idle_saver=" << idle_saver_value(config) << "\n"; + out << "idle_delay=" << config.idle_delay_s << "\n"; out << "quiet_launcher=" << (config.quiet_launcher ? "on" : "off") << "\n"; out << "low_battery=" << config.low_battery_percent << "\n"; out << "screen_timeout=" << config.screen_timeout_s << "\n"; + out << "desktop_unplug=" << config.desktop_unplug_min << "\n"; return out.str(); } diff --git a/src/model/power_settings.h b/src/model/power_settings.h index 5dd1737..8a64559 100644 --- a/src/model/power_settings.h +++ b/src/model/power_settings.h @@ -54,13 +54,26 @@ std::map parse_key_values(const std::string& text); // Opciones del servicio, con sus valores por defecto si faltan o no son válidos. struct DaemonConfig { bool quiet_launcher = false; // el audio del lanzador siempre aparcado (sin sonido de teclas) - bool idle_saver = true; // con la pantalla apagada: lanzador en pausa y su audio aparcado + // Con la pantalla apagada: su audio aparcado (la tarjeta de sonido duerme) y el lanzador + // en pausa. En el fichero, idle_saver=on|audio|launcher|off. + bool idle_audio = true; + bool idle_launcher = true; + int idle_delay_s = 5; // segundos con la pantalla apagada antes de lo anterior int low_battery_percent = 0; // 0 = no apagar + // Con Desk Mode (cz-desk-mode): cerrar su escritorio HDMI tras estos minutos con el HDMI + // desconectado (0 = nunca). Lo que no se haya guardado en él se pierde. + int desktop_unplug_min = 0; // Segundos sin tocar una tecla con la pantalla encendida para apagarla el propio servicio // (0 = nunca). Es la red de seguridad por si el lanzador o una app la dejan encendida. int screen_timeout_s = 300; }; +// Desk Mode (github.com/InstantComet/cz-desk-mode): su escritorio HDMI es esta unidad de +// usuario. +constexpr const char* kDeskModeDir = "/usr/lib/cz-desk-mode"; +constexpr const char* kDeskModeUnit = "cz-desk-mode-desktop.service"; + DaemonConfig daemon_config_from(const std::map& values); +std::string idle_saver_value(const DaemonConfig& config); // on|audio|launcher|off std::string daemon_config_text(const DaemonConfig& config); } // namespace power diff --git a/src/platform/power_control.cpp b/src/platform/power_control.cpp index 8deb4d1..8013465 100644 --- a/src/platform/power_control.cpp +++ b/src/platform/power_control.cpp @@ -60,11 +60,15 @@ PowerControl::PowerControl() { std::map PowerControl::read_daemon_values() const { // Lo que no esté en el fichero vale lo de por defecto de zeropowerd. const auto config = power::daemon_config_from(power::parse_key_values(read_text_file(daemon_config_path()))); + std::error_code ec; return { - {"idle_saver", config.idle_saver ? "on" : "off"}, + {"idle_saver", power::idle_saver_value(config)}, + {"idle_delay", std::to_string(config.idle_delay_s)}, {"quiet_launcher", config.quiet_launcher ? "on" : "off"}, {"low_battery", std::to_string(config.low_battery_percent)}, {"screen_timeout", std::to_string(config.screen_timeout_s)}, + // Sin Desk Mode no hay escritorio que cerrar: la fila sale como «not installed». + {"desktop_unplug", fs::exists(power::kDeskModeDir, ec) ? std::to_string(config.desktop_unplug_min) : "absent"}, }; } diff --git a/src/view/screens/settings_screen.cpp b/src/view/screens/settings_screen.cpp index a152f80..4ae2abb 100644 --- a/src/view/screens/settings_screen.cpp +++ b/src/view/screens/settings_screen.cpp @@ -20,6 +20,8 @@ namespace { constexpr int32_t kW = view::kScreenWidth; constexpr int32_t kMargin = 6; constexpr int32_t kRowH = 17; +// Con 6 filas, a 17 la pista de dos líneas se montaría con la línea de estado. +constexpr int32_t kRowHCompact = 15; constexpr int32_t kTop = 3; const lv_color_t kWarnColor = lv_color_hex(0xF9A825); @@ -107,11 +109,12 @@ void SettingsScreen::build_content(lv_obj_t* content) { const lv_font_t* value_font = assets().load_standard_font(13, app::StandardFontWeight::Regular); const lv_font_t* small = assets().load_standard_font(11, app::StandardFontWeight::Regular); + const int32_t row_h = settings_.size() > 5 ? kRowHCompact : kRowH; for (int i = 0; i < kMaxRows; ++i) { auto* box = lv_obj_create(content); lv_obj_remove_style_all(box); - lv_obj_set_size(box, kW - 2 * kMargin, kRowH); - lv_obj_set_pos(box, kMargin, kTop + i * kRowH); + lv_obj_set_size(box, kW - 2 * kMargin, row_h); + lv_obj_set_pos(box, kMargin, kTop + i * row_h); lv_obj_set_style_radius(box, 3, 0); lv_obj_remove_flag(box, LV_OBJ_FLAG_SCROLLABLE); row_boxes_[i] = box; @@ -144,7 +147,7 @@ void SettingsScreen::build_content(lv_obj_t* content) { lv_label_set_long_mode(hint_, LV_LABEL_LONG_WRAP); lv_obj_set_width(hint_, kW - 2 * kMargin - 6); // Justo debajo de la última fila (como mucho 5 por grupo). - lv_obj_set_pos(hint_, kMargin + 3, kTop + static_cast(settings_.size()) * kRowH + 4); + lv_obj_set_pos(hint_, kMargin + 3, kTop + static_cast(settings_.size()) * row_h + 4); status_ = lv_label_create(content); lv_obj_set_style_text_font(status_, small ? small : &lv_font_montserrat_12, 0); diff --git a/tests/power_model_test.cpp b/tests/power_model_test.cpp index 0919fe3..f0d478f 100644 --- a/tests/power_model_test.cpp +++ b/tests/power_model_test.cpp @@ -29,8 +29,8 @@ void test_catalog() { CHECK(power::find_setting(info.key) == &info); } CHECK(power::find_setting("nope") == nullptr); - CHECK(power::settings_in(power::Group::Hardware).size() == 5); - CHECK(power::settings_in(power::Group::Saving).size() == 4); + CHECK(power::settings_in(power::Group::Hardware).size() == 6); + CHECK(power::settings_in(power::Group::Saving).size() == 5); const auto* eth = power::find_setting("ethernet"); CHECK(eth && power::step_option(*eth, "on", 1) == "auto"); @@ -52,25 +52,34 @@ void test_key_values_and_daemon_config() { CHECK(kv.at("gpu_mem") == "16"); auto config = power::daemon_config_from({}); - CHECK(config.idle_saver && !config.quiet_launcher && config.low_battery_percent == 0); + CHECK(config.idle_audio && config.idle_launcher && !config.quiet_launcher && config.low_battery_percent == 0); + CHECK(config.idle_delay_s == 5 && config.desktop_unplug_min == 0); CHECK(config.screen_timeout_s == 300); CHECK(power::daemon_config_from({{"screen_timeout", "60"}}).screen_timeout_s == 60); CHECK(power::daemon_config_from({{"screen_timeout", "0"}}).screen_timeout_s == 0); CHECK(power::daemon_config_from({{"screen_timeout", "7"}}).screen_timeout_s == 300); // no es opción config = power::daemon_config_from( {{"idle_saver", "off"}, {"quiet_launcher", "on"}, {"low_battery", "8"}}); - CHECK(!config.idle_saver && config.quiet_launcher && config.low_battery_percent == 8); + CHECK(!config.idle_audio && !config.idle_launcher && config.quiet_launcher && config.low_battery_percent == 8); + config = power::daemon_config_from({{"idle_saver", "audio"}, {"idle_delay", "30"}, {"desktop_unplug", "5"}}); + CHECK(config.idle_audio && !config.idle_launcher && config.idle_delay_s == 30 && config.desktop_unplug_min == 5); + config = power::daemon_config_from({{"idle_saver", "launcher"}, {"idle_delay", "7"}}); + CHECK(!config.idle_audio && config.idle_launcher && config.idle_delay_s == 5); // Valores no válidos: se quedan los de por defecto. config = power::daemon_config_from({{"idle_saver", "maybe"}, {"low_battery", "50"}}); - CHECK(config.idle_saver && config.low_battery_percent == 0); + CHECK(config.idle_audio && config.idle_launcher && config.low_battery_percent == 0); // Ida y vuelta por el texto. power::DaemonConfig c; - c.idle_saver = false; + c.idle_audio = false; + c.idle_delay_s = 10; + c.desktop_unplug_min = 15; c.quiet_launcher = true; c.low_battery_percent = 10; c.screen_timeout_s = 120; const auto back = power::daemon_config_from(power::parse_key_values(power::daemon_config_text(c))); - CHECK(!back.idle_saver && back.quiet_launcher && back.low_battery_percent == 10); + CHECK(!back.idle_audio && back.idle_launcher && back.quiet_launcher && back.low_battery_percent == 10); + CHECK(power::idle_saver_value(back) == "launcher"); + CHECK(back.idle_delay_s == 10 && back.desktop_unplug_min == 15); CHECK(back.screen_timeout_s == 120); } @@ -165,6 +174,23 @@ void test_screen_timeout() { CHECK(v.update(1000, -1, false, 60) == A::None); } +void test_unplug_timer() { + power::UnplugTimer u; + CHECK(!u.update(0, true, 1)); + CHECK(!u.update(10, false, 1)); // empieza a contar + CHECK(!u.update(69, false, 1)); + CHECK(u.update(70, false, 1)); // un minuto desconectado + CHECK(!u.update(200, false, 1)); // una vez por desconexión + CHECK(!u.update(210, true, 1)); // se vuelve a conectar + CHECK(!u.update(220, false, 1)); + CHECK(!u.update(250, true, 1)); // cable flojo: vuelve antes de tiempo + CHECK(!u.update(260, false, 1)); + CHECK(!u.update(300, false, 1)); + CHECK(u.update(320, false, 1)); + power::UnplugTimer never; + CHECK(!never.update(0, false, 0) && !never.update(100000, false, 0)); +} + void test_sudo_password() { using power::SudoOutcome; CHECK(power::classify_sudo(0, "ethernet=off\n") == SudoOutcome::Ok); @@ -208,6 +234,7 @@ int main() { test_low_battery_guard(); test_idle_tracker(); test_screen_timeout(); + test_unplug_timer(); test_sudo_password(); if (failures == 0) { std::printf("power_model_test: todo bien\n"); From 4a26a6edbffb379e2aa15bc6bb1688c8c316945a Mon Sep 17 00:00:00 2001 From: Z3R0C1PH3R Date: Wed, 25 Nov 2026 00:30:31 +0530 Subject: [PATCH 5/8] =?UTF-8?q?Ajustes:=20la=20pista=20ya=20no=20tapa=20la?= =?UTF-8?q?=20l=C3=ADnea=20de=20estado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - La pista va justo debajo de la última fila y con las líneas un poco más juntas: con dos líneas rozaba la línea de estado. - Desk Mode unplug sólo sale con Desk Mode instalado (si no, Hardware se queda en 5 filas). - Con 6 filas: filas de 16 px (a 15 los interruptores se tocaban) y la pista y el estado comparten el sitio; el estado sólo se enseña si tiene algo que decir y, al moverse, se quita el resultado del último cambio para que se vea la pista de la fila nueva. Probado en el aparato pulsando teclas y leyendo /dev/fb0, también con 6 filas (Desk Mode simulado) y en tema claro. Co-authored-by: Cursor --- src/view/screens/settings_screen.cpp | 49 +++++++++++++++++++++++++--- src/view/screens/settings_screen.h | 2 ++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/view/screens/settings_screen.cpp b/src/view/screens/settings_screen.cpp index 4ae2abb..2af146f 100644 --- a/src/view/screens/settings_screen.cpp +++ b/src/view/screens/settings_screen.cpp @@ -7,9 +7,11 @@ #include "asset_manager.h" #include "theme.h" +#include #include #include #include +#include #include #include @@ -20,8 +22,9 @@ namespace { constexpr int32_t kW = view::kScreenWidth; constexpr int32_t kMargin = 6; constexpr int32_t kRowH = 17; -// Con 6 filas, a 17 la pista de dos líneas se montaría con la línea de estado. -constexpr int32_t kRowHCompact = 15; +// Con 6 filas no caben las filas, la pista de dos líneas y la línea de estado: las filas +// encogen un poco y la pista y el estado comparten el sitio (ver `shared_bottom_`). +constexpr int32_t kRowHCompact = 16; constexpr int32_t kTop = 3; const lv_color_t kWarnColor = lv_color_hex(0xF9A825); @@ -60,6 +63,15 @@ constexpr std::size_t kMaxDots = 34; SettingsScreen::SettingsScreen(viewmodel::BaseViewModel& view_model, app::AssetManager& assets, power::Group group) : BaseScreen(view_model, assets), group_(group), settings_(power::settings_in(group)) { + // Sin Desk Mode instalado, su ajuste no pinta nada: ni se enseña. + std::error_code ec; + if (!std::filesystem::exists(power::kDeskModeDir, ec)) { + settings_.erase(std::remove_if(settings_.begin(), settings_.end(), + [](const power::SettingInfo* info) { + return std::strcmp(info->key, "desktop_unplug") == 0; + }), + settings_.end()); + } init(); this->view_model().set_page_handlers(this, [this](uint32_t key) { return handle_key(key); }, [this]() { @@ -109,12 +121,15 @@ void SettingsScreen::build_content(lv_obj_t* content) { const lv_font_t* value_font = assets().load_standard_font(13, app::StandardFontWeight::Regular); const lv_font_t* small = assets().load_standard_font(11, app::StandardFontWeight::Regular); - const int32_t row_h = settings_.size() > 5 ? kRowHCompact : kRowH; + const bool compact = settings_.size() > 5; + const int32_t row_h = compact ? kRowHCompact : kRowH; + const int32_t top = compact ? kTop - 1 : kTop; + shared_bottom_ = compact; for (int i = 0; i < kMaxRows; ++i) { auto* box = lv_obj_create(content); lv_obj_remove_style_all(box); lv_obj_set_size(box, kW - 2 * kMargin, row_h); - lv_obj_set_pos(box, kMargin, kTop + i * row_h); + lv_obj_set_pos(box, kMargin, top + i * row_h); lv_obj_set_style_radius(box, 3, 0); lv_obj_remove_flag(box, LV_OBJ_FLAG_SCROLLABLE); row_boxes_[i] = box; @@ -147,7 +162,8 @@ void SettingsScreen::build_content(lv_obj_t* content) { lv_label_set_long_mode(hint_, LV_LABEL_LONG_WRAP); lv_obj_set_width(hint_, kW - 2 * kMargin - 6); // Justo debajo de la última fila (como mucho 5 por grupo). - lv_obj_set_pos(hint_, kMargin + 3, kTop + static_cast(settings_.size()) * row_h + 4); + lv_obj_set_style_text_line_space(hint_, -2, 0); + lv_obj_set_pos(hint_, kMargin + 3, top + static_cast(settings_.size()) * row_h + 1); status_ = lv_label_create(content); lv_obj_set_style_text_font(status_, small ? small : &lv_font_montserrat_12, 0); @@ -240,12 +256,14 @@ bool SettingsScreen::handle_key(uint32_t key) { case 'F': row_ = (row_ + n - 1) % n; confirm_key_.clear(); + forget_message(); break; case LV_KEY_DOWN: case 'x': case 'X': row_ = (row_ + 1) % n; confirm_key_.clear(); + forget_message(); break; case LV_KEY_LEFT: case 'z': @@ -350,6 +368,15 @@ void SettingsScreen::run_apply(const std::string& key, const std::string& target }); } +void SettingsScreen::forget_message() { + // Con pista y estado compartiendo sitio, el resultado del último cambio se quita al + // moverse, para que se vea la pista de la fila nueva. + if (shared_bottom_ && !busy_) { + std::lock_guard lock(mutex_); + message_.clear(); + } +} + bool SettingsScreen::handle_password_key(uint32_t key) { if (prompt_checking_) { return true; // sudo la está comprobando: se espera @@ -525,6 +552,7 @@ void SettingsScreen::refresh() { std::string status; lv_color_t status_color = colors.text_disabled; + bool idle_status = false; // sólo el recordatorio de teclas, nada que contar if (!confirm_key_.empty()) { status = "Remote access will be lost. Press again to turn off."; status_color = kWarnColor; @@ -540,9 +568,20 @@ void SettingsScreen::refresh() { status_color = message_error ? kErrorColor : colors.text_disabled; } else { status = control_.simulated() ? "Simulated system (no helper)" : "F/X choose ENTER switch / apply"; + idle_status = true; } set_text(status_, status); lv_obj_set_style_text_color(status_, status_color, 0); + if (shared_bottom_) { + // Pista y estado en el mismo sitio: si el estado tiene algo que decir, manda él. + if (idle_status) { + lv_obj_add_flag(status_, LV_OBJ_FLAG_HIDDEN); + lv_obj_remove_flag(hint_, LV_OBJ_FLAG_HIDDEN); + } else { + lv_obj_remove_flag(status_, LV_OBJ_FLAG_HIDDEN); + lv_obj_add_flag(hint_, LV_OBJ_FLAG_HIDDEN); + } + } } void SettingsScreen::timer_cb(lv_timer_t* timer) { diff --git a/src/view/screens/settings_screen.h b/src/view/screens/settings_screen.h index 8c36ba9..0b3acc8 100644 --- a/src/view/screens/settings_screen.h +++ b/src/view/screens/settings_screen.h @@ -43,6 +43,7 @@ class SettingsScreen : public BaseScreen { bool handle_key(uint32_t key); bool handle_password_key(uint32_t key); + void forget_message(); void start_job(std::function job); void apply_value(const power::SettingInfo& info, const std::string& target); void run_apply(const std::string& key, const std::string& target, std::string password_line); @@ -59,6 +60,7 @@ class SettingsScreen : public BaseScreen { platform::PowerControl control_; int row_ = 0; + bool shared_bottom_ = false; // 6 filas: la pista y la línea de estado se turnan std::map pending_; // valor elegido y aún sin aplicar std::string confirm_key_; // segundo ENTER pendiente (acceso remoto) std::string applying_key_; // el interruptor ya se ve en su nuevo valor From 0813a0e87411c663e608705ad11365dc426e8048 Mon Sep 17 00:00:00 2001 From: Z3R0C1PH3R Date: Wed, 25 Nov 2026 01:07:59 +0530 Subject: [PATCH 6/8] Ahorro de pantalla en dos interruptores; Grove 5V, GPIO 5V, LED y tope de CPU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Power saving: «Sleep sound card» y «Pause launcher» por separado (idle_audio, idle_launcher); el antiguo idle_saver se sigue leyendo. - Hardware: CPU max speed (cpufreq ya y arm_freq al arrancar), Status LED y las salidas de 5 V del puerto Grove y de los pines GPIO, con regla de udev para el arranque. Medido con la pantalla apagada: LED ~4 mA, cada salida de 5 V ~3 mA sin nada enchufado, 600 MHz ~5 mA en reposo. - La lista se desplaza: 5 filas a la vista y barra a la derecha, en vez de encoger. - La pista de los ajustes que piden reiniciar (GPU memory) dice «Needs restart». Co-authored-by: Cursor --- CLAUDE.md | 16 +++-- README.md | 21 ++++-- app-builder.json | 2 +- packaging/zeropower-helper | 101 ++++++++++++++++++++++++++- src/daemon/zeropowerd.cpp | 2 +- src/model/power_settings.cpp | 44 ++++++------ src/model/power_settings.h | 3 +- src/platform/power_control.cpp | 3 +- src/view/screens/settings_screen.cpp | 88 ++++++++++++----------- src/view/screens/settings_screen.h | 8 ++- tests/power_model_test.cpp | 12 ++-- 11 files changed, 214 insertions(+), 86 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 1dca289..5277d74 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,8 +56,11 @@ Tools/compilar.sh simulador # abre el simulador en este escritorio (X11) 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. - **`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 @@ -65,14 +68,17 @@ Tools/compilar.sh simulador # abre el simulador en este escritorio (X11) 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). diff --git a/README.md b/README.md index ee73d52..f65c114 100644 --- a/README.md +++ b/README.md @@ -26,16 +26,25 @@ cuánto consume el aparato y **deshacerlo** todo igual de fácil. 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. + 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**: **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). - **Power saving** (lo hace el servicio `zeropowerd`): - - **Screen-off saver**: con la pantalla apagada, aparca el audio del lanzador para que - duerman la tarjeta de sonido y el amplificador (~40 mA) y pausa el lanzador (~30 mA): - *Both*, sólo *Sound card*, sólo *Launcher* u *Off*. Una tecla lo despierta. Si hay una app - abierta no pausa nada. - - **Saver delay**: cuánto tiene que llevar apagada la pantalla para lo anterior (3–60 s). + - **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 diff --git a/app-builder.json b/app-builder.json index a762414..d31f351 100644 --- a/app-builder.json +++ b/app-builder.json @@ -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). With Desk Mode, its HDMI desktop can close itself once HDMI is unplugged.\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 sleeps the sound card and/or pauses the launcher 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).", + "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: 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 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" ], diff --git a/packaging/zeropower-helper b/packaging/zeropower-helper index e32bc24..9bf40a3 100755 --- a/packaging/zeropower-helper +++ b/packaging/zeropower-helper @@ -24,6 +24,9 @@ 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" die() { @@ -110,6 +113,25 @@ 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 + [ -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 ;; @@ -120,11 +142,15 @@ get_value() { tailscale) get_tailscale ;; extra_services) get_extra_services ;; journal_ram) get_journal_ram ;; + 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 extra_services journal_ram cpu_max status_led grove_5v gpio_5v" status() { local k @@ -271,6 +297,71 @@ 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 [] + 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 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: sin línea que cambiar no hace falta añadirla. + 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 @@ -282,6 +373,10 @@ set_value() { tailscale) set_tailscale "$2" ;; extra_services) set_extra_services "$2" ;; journal_ram) set_journal_ram "$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 } @@ -295,8 +390,12 @@ restore() { v=$(cat "$f") case "$v" in absent) continue ;; esac case " $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" } diff --git a/src/daemon/zeropowerd.cpp b/src/daemon/zeropowerd.cpp index 9d882f9..f161864 100644 --- a/src/daemon/zeropowerd.cpp +++ b/src/daemon/zeropowerd.cpp @@ -7,7 +7,7 @@ // // - Pantalla apagada (brillo 0) durante `idle_delay` s (5 por defecto): pausa el lanzador // (SIGSTOP) y aparca su audio en un sumidero nulo para que el amplificador y la tarjeta de -// sonido duerman (las dos cosas, o sólo una, según `idle_saver`). Una tecla o +// sonido duerman (cada cosa con su ajuste: `idle_launcher`, `idle_audio`). Una tecla o // la pantalla encendida lo despiertan. Si hay una app abierta desde el lanzador, no se // pausa nada (la app seguiría sin pantalla, pero quizá sonando o grabando). // - «Quiet launcher»: el audio del lanzador aparcado siempre (sin sonido de teclas). diff --git a/src/model/power_settings.cpp b/src/model/power_settings.cpp index d37490a..118db34 100644 --- a/src/model/power_settings.cpp +++ b/src/model/power_settings.cpp @@ -45,6 +45,16 @@ const std::vector& all_settings() { {"gpu_mem", Group::Hardware, Applier::System, "GPU memory", "RAM kept for the GPU firmware. 16 MB is enough for the built-in screen.", {{"16", "16 MB"}, {"32", "32 MB"}, {"64", "64 MB"}, {"128", "128 MB"}}, "64", true}, + {"cpu_max", Group::Hardware, Applier::System, "CPU max speed", + "Caps the CPU clock: apps get slower, busy moments draw less. Idle: ~5 mA at 600 MHz.", + {{"1000", "1000 MHz"}, {"800", "800 MHz"}, {"600", "600 MHz"}}, "1000"}, + {"status_led", Group::Hardware, Applier::System, "Status LED", + "The green activity LED of the CM0 module (~4 mA).", kOnOff, "on"}, + {"grove_5v", Group::Hardware, Applier::System, "Grove 5V", + "5 V on the Grove port, for sensors and modules. ~3 mA with nothing plugged in.", kOnOff, "off"}, + {"gpio_5v", Group::Hardware, Applier::System, "GPIO 5V", + "5 V on the GPIO header, for Caps (~3 mA with nothing plugged in). Cap apps may turn it on.", kOnOff, + "off"}, // --- Services --- {"tailscale", Group::Services, Applier::System, "Tailscale", "VPN daemon. Off saves CPU and RAM, but no remote access through it.", kOnOff, "on", @@ -54,11 +64,13 @@ const std::vector& all_settings() { {"journal_ram", Group::Services, Applier::System, "Logs in RAM", "System journal in RAM (16 MB): fewer SD card writes. Lost on reboot.", kOnOff, "off"}, // --- Power saving (zeropowerd) --- - {"idle_saver", Group::Saving, Applier::Daemon, "Screen-off saver", - "Screen off: sleep the sound card (~40 mA) and pause the launcher (~30 mA). A key wakes it.", - {{"on", "Both"}, {"audio", "Sound card"}, {"launcher", "Launcher"}, {"off", "Off"}}, "on"}, + {"idle_audio", Group::Saving, Applier::Daemon, "Sleep sound card", + "Screen off: park the launcher's audio so the sound card sleeps (~40 mA).", kOnOff, "on"}, + {"idle_launcher", Group::Saving, Applier::Daemon, "Pause launcher", + "Screen off: pause the launcher, which keeps redrawing (~30 mA). A key wakes it.", kOnOff, + "on"}, {"idle_delay", Group::Saving, Applier::Daemon, "Saver delay", - "How long the screen must be off before the screen-off saver starts.", + "How long the screen must be off before the two above start.", {{"3", "3 s"}, {"5", "5 s"}, {"10", "10 s"}, {"30", "30 s"}, {"60", "60 s"}}, "5"}, {"quiet_launcher", Group::Saving, Applier::Daemon, "Quiet launcher", "No launcher key sounds, so the audio amp can sleep (~35 mA).", kOnOff, "off"}, @@ -148,14 +160,13 @@ DaemonConfig daemon_config_from(const std::map& values } }; flag("quiet_launcher", config.quiet_launcher); + // Hasta 0.1.3 era un solo ajuste, idle_saver=on|off: vale mientras no estén los nuevos. const auto idle = values.find("idle_saver"); - if (idle != values.end()) { - const std::string& v = idle->second; - if (v == "on" || v == "audio" || v == "launcher" || v == "off") { - config.idle_audio = v == "on" || v == "audio"; - config.idle_launcher = v == "on" || v == "launcher"; - } + if (idle != values.end() && (idle->second == "on" || idle->second == "off")) { + config.idle_audio = config.idle_launcher = idle->second == "on"; } + flag("idle_audio", config.idle_audio); + flag("idle_launcher", config.idle_launcher); auto number = [&](const char* key, int& out) { const auto it = values.find(key); const SettingInfo* info = find_setting(key); @@ -170,20 +181,11 @@ DaemonConfig daemon_config_from(const std::map& values return config; } -std::string idle_saver_value(const DaemonConfig& config) { - if (config.idle_audio && config.idle_launcher) { - return "on"; - } - if (config.idle_audio) { - return "audio"; - } - return config.idle_launcher ? "launcher" : "off"; -} - std::string daemon_config_text(const DaemonConfig& config) { std::ostringstream out; out << "# ZeroPower: options for zeropowerd (changed from the app)\n"; - out << "idle_saver=" << idle_saver_value(config) << "\n"; + out << "idle_audio=" << (config.idle_audio ? "on" : "off") << "\n"; + out << "idle_launcher=" << (config.idle_launcher ? "on" : "off") << "\n"; out << "idle_delay=" << config.idle_delay_s << "\n"; out << "quiet_launcher=" << (config.quiet_launcher ? "on" : "off") << "\n"; out << "low_battery=" << config.low_battery_percent << "\n"; diff --git a/src/model/power_settings.h b/src/model/power_settings.h index 8a64559..c18b39d 100644 --- a/src/model/power_settings.h +++ b/src/model/power_settings.h @@ -55,7 +55,7 @@ std::map parse_key_values(const std::string& text); struct DaemonConfig { bool quiet_launcher = false; // el audio del lanzador siempre aparcado (sin sonido de teclas) // Con la pantalla apagada: su audio aparcado (la tarjeta de sonido duerme) y el lanzador - // en pausa. En el fichero, idle_saver=on|audio|launcher|off. + // en pausa (idle_audio, idle_launcher; antes, los dos juntos en idle_saver). bool idle_audio = true; bool idle_launcher = true; int idle_delay_s = 5; // segundos con la pantalla apagada antes de lo anterior @@ -73,7 +73,6 @@ constexpr const char* kDeskModeDir = "/usr/lib/cz-desk-mode"; constexpr const char* kDeskModeUnit = "cz-desk-mode-desktop.service"; DaemonConfig daemon_config_from(const std::map& values); -std::string idle_saver_value(const DaemonConfig& config); // on|audio|launcher|off std::string daemon_config_text(const DaemonConfig& config); } // namespace power diff --git a/src/platform/power_control.cpp b/src/platform/power_control.cpp index 8013465..b692f93 100644 --- a/src/platform/power_control.cpp +++ b/src/platform/power_control.cpp @@ -62,7 +62,8 @@ std::map PowerControl::read_daemon_values() const { const auto config = power::daemon_config_from(power::parse_key_values(read_text_file(daemon_config_path()))); std::error_code ec; return { - {"idle_saver", power::idle_saver_value(config)}, + {"idle_audio", config.idle_audio ? "on" : "off"}, + {"idle_launcher", config.idle_launcher ? "on" : "off"}, {"idle_delay", std::to_string(config.idle_delay_s)}, {"quiet_launcher", config.quiet_launcher ? "on" : "off"}, {"low_battery", std::to_string(config.low_battery_percent)}, diff --git a/src/view/screens/settings_screen.cpp b/src/view/screens/settings_screen.cpp index 2af146f..e3ff636 100644 --- a/src/view/screens/settings_screen.cpp +++ b/src/view/screens/settings_screen.cpp @@ -22,9 +22,9 @@ namespace { constexpr int32_t kW = view::kScreenWidth; constexpr int32_t kMargin = 6; constexpr int32_t kRowH = 17; -// Con 6 filas no caben las filas, la pista de dos líneas y la línea de estado: las filas -// encogen un poco y la pista y el estado comparten el sitio (ver `shared_bottom_`). -constexpr int32_t kRowHCompact = 16; +// Barra de desplazamiento, a la derecha de las filas, cuando no caben todas. +constexpr int32_t kBarW = 3; +constexpr int32_t kBarGap = 3; constexpr int32_t kTop = 3; const lv_color_t kWarnColor = lv_color_hex(0xF9A825); @@ -121,15 +121,15 @@ void SettingsScreen::build_content(lv_obj_t* content) { const lv_font_t* value_font = assets().load_standard_font(13, app::StandardFontWeight::Regular); const lv_font_t* small = assets().load_standard_font(11, app::StandardFontWeight::Regular); - const bool compact = settings_.size() > 5; - const int32_t row_h = compact ? kRowHCompact : kRowH; - const int32_t top = compact ? kTop - 1 : kTop; - shared_bottom_ = compact; + const int n = static_cast(settings_.size()); + const int visible = n < kMaxRows ? n : kMaxRows; + const bool scrolls = n > kMaxRows; + const int32_t row_w = kW - 2 * kMargin - (scrolls ? kBarW + kBarGap : 0); for (int i = 0; i < kMaxRows; ++i) { auto* box = lv_obj_create(content); lv_obj_remove_style_all(box); - lv_obj_set_size(box, kW - 2 * kMargin, row_h); - lv_obj_set_pos(box, kMargin, top + i * row_h); + lv_obj_set_size(box, row_w, kRowH); + lv_obj_set_pos(box, kMargin, kTop + i * kRowH); lv_obj_set_style_radius(box, 3, 0); lv_obj_remove_flag(box, LV_OBJ_FLAG_SCROLLABLE); row_boxes_[i] = box; @@ -157,13 +157,30 @@ void SettingsScreen::build_content(lv_obj_t* content) { row_switches_[i] = sw; } + if (scrolls) { + scroll_track_ = lv_obj_create(content); + lv_obj_remove_style_all(scroll_track_); + lv_obj_set_size(scroll_track_, kBarW, visible * kRowH); + lv_obj_set_pos(scroll_track_, kW - kMargin - kBarW, kTop); + lv_obj_set_style_radius(scroll_track_, kBarW / 2 + 1, 0); + lv_obj_set_style_bg_opa(scroll_track_, LV_OPA_COVER, 0); + lv_obj_remove_flag(scroll_track_, LV_OBJ_FLAG_SCROLLABLE); + + scroll_thumb_ = lv_obj_create(scroll_track_); + lv_obj_remove_style_all(scroll_thumb_); + lv_obj_set_size(scroll_thumb_, kBarW, visible * kRowH * kMaxRows / n); + lv_obj_set_style_radius(scroll_thumb_, kBarW / 2 + 1, 0); + lv_obj_set_style_bg_opa(scroll_thumb_, LV_OPA_COVER, 0); + } + hint_ = lv_label_create(content); lv_obj_set_style_text_font(hint_, small ? small : &lv_font_montserrat_12, 0); lv_label_set_long_mode(hint_, LV_LABEL_LONG_WRAP); lv_obj_set_width(hint_, kW - 2 * kMargin - 6); - // Justo debajo de la última fila (como mucho 5 por grupo). + // Justo debajo de la última fila que se ve, con las líneas un poco juntas: con dos líneas + // tiene que caber encima de la línea de estado. lv_obj_set_style_text_line_space(hint_, -2, 0); - lv_obj_set_pos(hint_, kMargin + 3, top + static_cast(settings_.size()) * row_h + 1); + lv_obj_set_pos(hint_, kMargin + 3, kTop + visible * kRowH + 1); status_ = lv_label_create(content); lv_obj_set_style_text_font(status_, small ? small : &lv_font_montserrat_12, 0); @@ -256,14 +273,12 @@ bool SettingsScreen::handle_key(uint32_t key) { case 'F': row_ = (row_ + n - 1) % n; confirm_key_.clear(); - forget_message(); break; case LV_KEY_DOWN: case 'x': case 'X': row_ = (row_ + 1) % n; confirm_key_.clear(); - forget_message(); break; case LV_KEY_LEFT: case 'z': @@ -358,7 +373,7 @@ void SettingsScreen::run_apply(const std::string& key, const std::string& target if (result.ok) { message_ = std::string(applied->title) + ": " + power::option_label(*applied, result.value); if (applied->needs_reboot) { - message_ += " (reboot to apply)"; + message_ += " (restart to apply)"; } message_error_ = false; } else { @@ -368,15 +383,6 @@ void SettingsScreen::run_apply(const std::string& key, const std::string& target }); } -void SettingsScreen::forget_message() { - // Con pista y estado compartiendo sitio, el resultado del último cambio se quita al - // moverse, para que se vea la pista de la fila nueva. - if (shared_bottom_ && !busy_) { - std::lock_guard lock(mutex_); - message_.clear(); - } -} - bool SettingsScreen::handle_password_key(uint32_t key) { if (prompt_checking_) { return true; // sudo la está comprobando: se espera @@ -483,13 +489,29 @@ void SettingsScreen::refresh() { } refresh_password_prompt(colors); + // Ventana de filas que se ven: la elegida siempre dentro. + const int n = static_cast(settings_.size()); + if (row_ < first_) { + first_ = row_; + } else if (row_ >= first_ + kMaxRows) { + first_ = row_ - kMaxRows + 1; + } + if (scroll_track_) { + lv_obj_set_style_bg_color(scroll_track_, colors.border, 0); + lv_obj_set_style_bg_color(scroll_thumb_, colors.text_disabled, 0); + const int32_t track_h = lv_obj_get_height(scroll_track_); + const int32_t thumb_h = lv_obj_get_height(scroll_thumb_); + lv_obj_set_y(scroll_thumb_, (track_h - thumb_h) * first_ / (n - kMaxRows)); + } + for (int i = 0; i < kMaxRows; ++i) { - if (i >= static_cast(settings_.size())) { + const int index = first_ + i; + if (index >= n) { lv_obj_add_flag(row_boxes_[i], LV_OBJ_FLAG_HIDDEN); continue; } - const power::SettingInfo& info = *settings_[static_cast(i)]; - const bool selected = i == row_; + const power::SettingInfo& info = *settings_[static_cast(index)]; + const bool selected = index == row_; lv_obj_remove_flag(row_boxes_[i], LV_OBJ_FLAG_HIDDEN); lv_obj_set_style_bg_opa(row_boxes_[i], selected ? LV_OPA_COVER : LV_OPA_TRANSP, 0); lv_obj_set_style_bg_color(row_boxes_[i], colors.primary, 0); @@ -546,13 +568,12 @@ void SettingsScreen::refresh() { if (!settings_.empty()) { const power::SettingInfo& info = *settings_[static_cast(row_)]; - set_text(hint_, info.hint); + set_text(hint_, info.needs_reboot ? std::string(info.hint) + " Needs restart." : std::string(info.hint)); lv_obj_set_style_text_color(hint_, colors.text_disabled, 0); } std::string status; lv_color_t status_color = colors.text_disabled; - bool idle_status = false; // sólo el recordatorio de teclas, nada que contar if (!confirm_key_.empty()) { status = "Remote access will be lost. Press again to turn off."; status_color = kWarnColor; @@ -568,20 +589,9 @@ void SettingsScreen::refresh() { status_color = message_error ? kErrorColor : colors.text_disabled; } else { status = control_.simulated() ? "Simulated system (no helper)" : "F/X choose ENTER switch / apply"; - idle_status = true; } set_text(status_, status); lv_obj_set_style_text_color(status_, status_color, 0); - if (shared_bottom_) { - // Pista y estado en el mismo sitio: si el estado tiene algo que decir, manda él. - if (idle_status) { - lv_obj_add_flag(status_, LV_OBJ_FLAG_HIDDEN); - lv_obj_remove_flag(hint_, LV_OBJ_FLAG_HIDDEN); - } else { - lv_obj_remove_flag(status_, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(hint_, LV_OBJ_FLAG_HIDDEN); - } - } } void SettingsScreen::timer_cb(lv_timer_t* timer) { diff --git a/src/view/screens/settings_screen.h b/src/view/screens/settings_screen.h index 0b3acc8..82d0827 100644 --- a/src/view/screens/settings_screen.h +++ b/src/view/screens/settings_screen.h @@ -39,11 +39,11 @@ class SettingsScreen : public BaseScreen { void build_content(lv_obj_t* content) override; private: - static constexpr int kMaxRows = 6; + // Filas que se ven a la vez; con más, la lista se desplaza (con su barra a la derecha). + static constexpr int kMaxRows = 5; bool handle_key(uint32_t key); bool handle_password_key(uint32_t key); - void forget_message(); void start_job(std::function job); void apply_value(const power::SettingInfo& info, const std::string& target); void run_apply(const std::string& key, const std::string& target, std::string password_line); @@ -60,7 +60,7 @@ class SettingsScreen : public BaseScreen { platform::PowerControl control_; int row_ = 0; - bool shared_bottom_ = false; // 6 filas: la pista y la línea de estado se turnan + int first_ = 0; // primera fila que se ve std::map pending_; // valor elegido y aún sin aplicar std::string confirm_key_; // segundo ENTER pendiente (acceso remoto) std::string applying_key_; // el interruptor ya se ve en su nuevo valor @@ -98,6 +98,8 @@ class SettingsScreen : public BaseScreen { std::array row_titles_{}; std::array row_values_{}; std::array row_switches_{}; + lv_obj_t* scroll_track_ = nullptr; + lv_obj_t* scroll_thumb_ = nullptr; lv_obj_t* hint_ = nullptr; lv_obj_t* status_ = nullptr; lv_timer_t* timer_ = nullptr; diff --git a/tests/power_model_test.cpp b/tests/power_model_test.cpp index f0d478f..5ad5b86 100644 --- a/tests/power_model_test.cpp +++ b/tests/power_model_test.cpp @@ -29,8 +29,8 @@ void test_catalog() { CHECK(power::find_setting(info.key) == &info); } CHECK(power::find_setting("nope") == nullptr); - CHECK(power::settings_in(power::Group::Hardware).size() == 6); - CHECK(power::settings_in(power::Group::Saving).size() == 5); + CHECK(power::settings_in(power::Group::Hardware).size() == 10); + CHECK(power::settings_in(power::Group::Saving).size() == 6); const auto* eth = power::find_setting("ethernet"); CHECK(eth && power::step_option(*eth, "on", 1) == "auto"); @@ -61,10 +61,11 @@ void test_key_values_and_daemon_config() { config = power::daemon_config_from( {{"idle_saver", "off"}, {"quiet_launcher", "on"}, {"low_battery", "8"}}); CHECK(!config.idle_audio && !config.idle_launcher && config.quiet_launcher && config.low_battery_percent == 8); - config = power::daemon_config_from({{"idle_saver", "audio"}, {"idle_delay", "30"}, {"desktop_unplug", "5"}}); + config = power::daemon_config_from({{"idle_launcher", "off"}, {"idle_delay", "30"}, {"desktop_unplug", "5"}}); CHECK(config.idle_audio && !config.idle_launcher && config.idle_delay_s == 30 && config.desktop_unplug_min == 5); - config = power::daemon_config_from({{"idle_saver", "launcher"}, {"idle_delay", "7"}}); - CHECK(!config.idle_audio && config.idle_launcher && config.idle_delay_s == 5); + // El ajuste de antes (idle_saver) vale, y los nuevos mandan si están. + config = power::daemon_config_from({{"idle_saver", "off"}, {"idle_audio", "on"}, {"idle_delay", "7"}}); + CHECK(config.idle_audio && !config.idle_launcher && config.idle_delay_s == 5); // Valores no válidos: se quedan los de por defecto. config = power::daemon_config_from({{"idle_saver", "maybe"}, {"low_battery", "50"}}); CHECK(config.idle_audio && config.idle_launcher && config.low_battery_percent == 0); @@ -78,7 +79,6 @@ void test_key_values_and_daemon_config() { c.screen_timeout_s = 120; const auto back = power::daemon_config_from(power::parse_key_values(power::daemon_config_text(c))); CHECK(!back.idle_audio && back.idle_launcher && back.quiet_launcher && back.low_battery_percent == 10); - CHECK(power::idle_saver_value(back) == "launcher"); CHECK(back.idle_delay_s == 10 && back.desktop_unplug_min == 15); CHECK(back.screen_timeout_s == 120); } From c2a99e67af2bd147341c71107520106cbbdaf02a Mon Sep 17 00:00:00 2001 From: Z3R0C1PH3R Date: Wed, 25 Nov 2026 01:19:57 +0530 Subject: [PATCH 7/8] =?UTF-8?q?Services:=20un=20interruptor=20por=20servic?= =?UTF-8?q?io=20en=20vez=20de=20=C2=ABBackground=20extras=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NFS client (rpcbind, nfs-blkmap), Avahi, actualizaciones diarias de apt, índice de man y e2scrub, cada uno con sus unidades. extra_services se sigue aceptando y deshaciendo al desinstalar, para quien lo cambió con la 0.1.3. Co-authored-by: Cursor --- CLAUDE.md | 3 +++ README.md | 12 +++++++--- app-builder.json | 2 +- packaging/zeropower-helper | 43 ++++++++++++++++++++++++++++++++++-- src/model/power_settings.cpp | 13 +++++++++-- tests/power_model_test.cpp | 1 + 6 files changed, 66 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5277d74..55f8bf6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -61,6 +61,9 @@ Tools/compilar.sh simulador # abre el simulador en este escritorio (X11) 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 diff --git a/README.md b/README.md index f65c114..cb6e66a 100644 --- a/README.md +++ b/README.md @@ -36,9 +36,15 @@ cuánto consume el aparato y **deshacerlo** todo igual de fácil. 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**: **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). +- **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`): - **Sleep sound card**: con la pantalla apagada, aparca el audio del lanzador para que duerman la tarjeta de sonido y el amplificador (~40 mA). diff --git a/app-builder.json b/app-builder.json index d31f351..9332295 100644 --- a/app-builder.json +++ b/app-builder.json @@ -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), 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: 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 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).", + "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" ], diff --git a/packaging/zeropower-helper b/packaging/zeropower-helper index 9bf40a3..6317184 100755 --- a/packaging/zeropower-helper +++ b/packaging/zeropower-helper @@ -28,6 +28,19 @@ 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 @@ -109,6 +122,16 @@ get_extra_services() { echo off } +get_service() { # get_service : 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 } @@ -142,6 +165,7 @@ 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 ;; @@ -150,7 +174,8 @@ get_value() { esac } -KEYS="ethernet wifi bluetooth hdmi_desktop gpu_mem tailscale extra_services journal_ram cpu_max status_led grove_5v gpio_5v" +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 @@ -267,6 +292,19 @@ set_extra_services() { esac } +set_service() { # set_service 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) @@ -373,6 +411,7 @@ 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" ;; @@ -389,7 +428,7 @@ 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" diff --git a/src/model/power_settings.cpp b/src/model/power_settings.cpp index 118db34..94909ba 100644 --- a/src/model/power_settings.cpp +++ b/src/model/power_settings.cpp @@ -59,8 +59,17 @@ const std::vector& all_settings() { {"tailscale", Group::Services, Applier::System, "Tailscale", "VPN daemon. Off saves CPU and RAM, but no remote access through it.", kOnOff, "on", false, true}, - {"extra_services", Group::Services, Applier::System, "Background extras", - "NFS, rpcbind, avahi, apt/man-db timers: unused on a handheld.", kOnOff, "on"}, + {"nfs", Group::Services, Applier::System, "NFS client", + "rpcbind and nfs-blkmap, for network file shares. Unused on a handheld.", kOnOff, "on"}, + {"avahi", Group::Services, Applier::System, "Avahi (.local)", + "Finds the device as hostname.local on the network. Off: use its IP address.", kOnOff, + "on"}, + {"apt_timers", Group::Services, Applier::System, "Daily apt updates", + "Background package list refresh and upgrades. apt by hand still works.", kOnOff, "on"}, + {"man_db", Group::Services, Applier::System, "Man page index", + "Rebuilds the manual page index every day.", kOnOff, "on"}, + {"e2scrub", Group::Services, Applier::System, "Disk scrub timer", + "Weekly check of ext4 on LVM volumes: the SD card has none.", kOnOff, "on"}, {"journal_ram", Group::Services, Applier::System, "Logs in RAM", "System journal in RAM (16 MB): fewer SD card writes. Lost on reboot.", kOnOff, "off"}, // --- Power saving (zeropowerd) --- diff --git a/tests/power_model_test.cpp b/tests/power_model_test.cpp index 5ad5b86..aae5d00 100644 --- a/tests/power_model_test.cpp +++ b/tests/power_model_test.cpp @@ -31,6 +31,7 @@ void test_catalog() { CHECK(power::find_setting("nope") == nullptr); CHECK(power::settings_in(power::Group::Hardware).size() == 10); CHECK(power::settings_in(power::Group::Saving).size() == 6); + CHECK(power::settings_in(power::Group::Services).size() == 7); const auto* eth = power::find_setting("ethernet"); CHECK(eth && power::step_option(*eth, "on", 1) == "auto"); From 9584deb56e708078d43ea134af0edd861eb0ce41 Mon Sep 17 00:00:00 2001 From: Bruno <82467708+baltamir1978@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:17:17 +0100 Subject: [PATCH 8/8] CPU max a 1000 quita el bloque de config.txt; la pista de GPIO 5V avisa de los Caps Co-Authored-By: Claude Opus 5.5 --- packaging/zeropower-helper | 6 +++++- src/model/power_settings.cpp | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packaging/zeropower-helper b/packaging/zeropower-helper index 6317184..d4ce374 100755 --- a/packaging/zeropower-helper +++ b/packaging/zeropower-helper @@ -391,7 +391,11 @@ set_cpu_max() { [ -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: sin línea que cambiar no hace falta añadirla. + # 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 diff --git a/src/model/power_settings.cpp b/src/model/power_settings.cpp index 94909ba..3876232 100644 --- a/src/model/power_settings.cpp +++ b/src/model/power_settings.cpp @@ -53,7 +53,7 @@ const std::vector& all_settings() { {"grove_5v", Group::Hardware, Applier::System, "Grove 5V", "5 V on the Grove port, for sensors and modules. ~3 mA with nothing plugged in.", kOnOff, "off"}, {"gpio_5v", Group::Hardware, Applier::System, "GPIO 5V", - "5 V on the GPIO header, for Caps (~3 mA with nothing plugged in). Cap apps may turn it on.", kOnOff, + "5 V on the GPIO header for Caps (~3 mA idle). Off cuts power to a plugged-in Cap.", kOnOff, "off"}, // --- Services --- {"tailscale", Group::Services, Applier::System, "Tailscale",