Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
cba8b56
perf(applaunch): stage screen-off into panel sleep and idle silence
dbrhspyjkf-code Nov 26, 2026
fb67686
ci: trigger fork build
dbrhspyjkf-code Nov 26, 2026
41ff994
fix(applaunch): clear a stale deep-sleep state at boot
dbrhspyjkf-code Nov 26, 2026
fb43f56
feat(applaunch): replace the home carousel with a 3x2 app grid
dbrhspyjkf-code Nov 26, 2026
51b3c07
fix(applaunch): keep grid left/right moves inside the row
dbrhspyjkf-code Nov 26, 2026
8f4a53e
feat(applaunch): drop the grid side arrow buttons
dbrhspyjkf-code Nov 26, 2026
9a56b92
feat(applaunch): make the grid selection unmistakable
dbrhspyjkf-code Nov 26, 2026
3af8730
fix(applaunch): land row-edge flips on real apps and add I/O page flips
dbrhspyjkf-code Nov 26, 2026
9b90441
test(applaunch): pin I/O page flips and ragged-page emptiness
dbrhspyjkf-code Nov 26, 2026
00b6347
fix(applaunch): keep every grid card at full brightness
dbrhspyjkf-code Nov 26, 2026
dc16a78
feat(applaunch): power down Bluetooth during deep sleep and harden th…
dbrhspyjkf-code Nov 27, 2026
1b50c35
feat(applaunch): keep Bluetooth alive through deep sleep while music …
dbrhspyjkf-code Nov 29, 2026
767e7e7
feat(cp0): stage the backlight dark while an external app idles
dbrhspyjkf-code Nov 29, 2026
f96161a
fix(cp0): probe real audio energy, not the SDL silence pump
dbrhspyjkf-code Nov 29, 2026
5cff56e
fix(cp0): drop Wi-Fi power save while media renders
dbrhspyjkf-code Nov 30, 2026
cdf959f
fix(cp0): use iw's on/off keywords for the PSM toggle
dbrhspyjkf-code Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions ext_components/cp0_lvgl/include/cp0_lvgl_app.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,26 @@ cp0_battery_info_t cp0_battery_read(void);
int cp0_backlight_read(void);
int cp0_backlight_max(void);
int cp0_backlight_write(int val);
/* Red status LED staging for the screen-off state: suspend turns the trigger
* off and the led dark while remembering the previous trigger and brightness;
* restore brings them back. Both degrade to a no-op (negative return) when
* the sysfs nodes are missing or not writable. */
int cp0_status_led_suspend(void);
void cp0_status_led_restore(void);
/* CPU frequency staging: 1 pins the cpufreq governor to powersave, 0 restores
* the previously active governor. Negative when the node is not writable. */
int cp0_cpufreq_powersave_set(int enable);
/* Startup safety net: if the governor is still sitting on powersave from a
* previous process that died during the screen-off stage, restore the
* platform default (ondemand). Returns 1 when a stale pin was cleared. */
int cp0_cpufreq_wake_reset(void);
/* Bluetooth radio power for the screen-off staging: fire-and-forget async
* D-Bus call, safe from the LVGL thread. */
void cp0_bluetooth_power_set_async(int enabled);
/* LCD panel power through the framebuffer blanking ioctl: 1 blanks the panel
* (display off + MIPI sleep), 0 wakes it again and flushes the framebuffer
* back. 0 on success, negative when no framebuffer can be blanked. */
int cp0_panel_fb_blank(int blank);
void cp0_time_str(char *buf, int buf_size);

#ifdef __cplusplus
Expand Down
26 changes: 26 additions & 0 deletions ext_components/cp0_lvgl/include/cp0_status_pause.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD
*
* SPDX-License-Identifier: MIT
*/

#ifndef CP0_STATUS_PAUSE_H
#define CP0_STATUS_PAUSE_H

#ifdef __cplusplus
extern "C" {
#endif

/* Set while the launcher's screen-off state holds the panel dark. Periodic
* UI refreshers (top-bar clock/status, battery events) and the network status
* polling worker consult this and skip their work, so nothing redraws or
* probes the system bus while the screen is off. Wi-Fi itself stays
* connected; the flag only pauses observation. */
void cp0_status_pause_set(int paused);
int cp0_status_pause_get(void);

#ifdef __cplusplus
}
#endif

#endif /* CP0_STATUS_PAUSE_H */
251 changes: 246 additions & 5 deletions ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@
#include "cp0_esc_state.h"
#include "../cp0_external_process_group.hpp"
#include "cp0_process_commands.hpp"
#include "cp0_lvgl_app.h"
#include "hal_lvgl_bsp.h"
#include "../cp0_sync_signal.hpp"

#include <charconv>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <thread>

#if !defined(_WIN32)
Expand Down Expand Up @@ -46,6 +53,177 @@ std::uint64_t monotonic_ms()

} // namespace

#if !defined(_WIN32)
namespace {

/* ---- app-idle backlight staging ------------------------------------------
* The LVGL thread blocks inside ExecBlocking for the whole app lifetime, so
* the launcher's own screensaver cannot run while a child owns the screen.
* This supervision loop is the only launcher-side code that stays alive, so
* it carries the idle staging: after the configured dark_time with no key
* activity and no audio rendering, the backlight goes dark. Stage 1 only -
* deep sleep stays launcher-home-only, because the keyboard queue drops
* events while an app is foreground, so a deep-sleeping launcher could never
* be woken by a key. Audio actually rendering (radio/music/TV through the
* app) suppresses the staging entirely so the panel stays on for the
* session, and any key press lights the panel back up. */

constexpr std::uint64_t kSinkProbePeriodMs = 5000;

constexpr const char *kBacklightBrightness = "/sys/class/backlight/backlight/brightness";
constexpr const char *kBacklightMax = "/sys/class/backlight/backlight/max_brightness";

int read_int_sysfile(const char *path, int fallback)
{
FILE *f = std::fopen(path, "r");
if (!f) return fallback;
int value = fallback;
if (std::fscanf(f, "%d", &value) != 1) value = fallback;
std::fclose(f);
return value;
}

int backlight_read_raw()
{
return read_int_sysfile(kBacklightBrightness, -1);
}

int backlight_write_raw(int val)
{
if (val < 0) val = 0;
const int maximum = read_int_sysfile(kBacklightMax, 100);
if (val > maximum) val = maximum;
FILE *f = std::fopen(kBacklightBrightness, "w");
if (!f) return -1;
const int written = std::fprintf(f, "%d", val);
const int close_result = std::fclose(f);
return written > 0 && close_result == 0 ? val : -1;
}

/* One pactl spawn collects the sinks in the RUNNING state; for each one a
* short pw-record capture of the sink monitor (via stream.capture.sink)
* measures the real output energy. SDL and pygame keep their mixers open
* forever and pump digital silence, which holds a sink in RUNNING without
* any audible media, so only energy counts as "playing". A failed capture
* (no bytes at all) falls back to treating the sink as playing, so a broken
* probe can never sleep the panel in the middle of real media. */

constexpr int kAudioPeakThreshold = 200;
constexpr int kMaxProbeSinks = 3;

int monitor_peak(const char *sink_name)
{
char command[320];
std::snprintf(command, sizeof(command),
"timeout 0.45 pw-record -a -P \"stream.capture.sink=true\" "
"--target '%s' --rate 16000 --channels 1 --format s16 - 2>/dev/null",
sink_name);
FILE *capture = ::popen(command, "r");
if (!capture) return -1;
int peak = 0;
std::size_t bytes = 0;
for (;;) {
unsigned char sample[2] = {};
const std::size_t got = std::fread(sample, 1, 2, capture);
if (got < 2) {
bytes += got;
break;
}
bytes += 2;
const auto value = static_cast<std::int16_t>(
static_cast<std::uint16_t>(sample[0]) |
(static_cast<std::uint16_t>(sample[1]) << 8));
const int magnitude = value < 0 ? -static_cast<int>(value) : value;
if (magnitude > peak) peak = magnitude;
}
::pclose(capture);
if (bytes == 0) return -1;
return peak;
}

bool any_media_rendering()
{
bool playing = false;
FILE *sinks = ::popen("pactl list sinks 2>/dev/null", "r");
if (!sinks) return false;
char line[256] = {};
bool sink_running = false;
int probed = 0;
while (probed < kMaxProbeSinks && std::fgets(line, sizeof(line), sinks) != nullptr) {
if (std::strstr(line, "State: ") != nullptr) {
sink_running = std::strstr(line, "RUNNING") != nullptr;
} else if (sink_running && std::strstr(line, "Name: ") != nullptr) {
sink_running = false;
const char *value = std::strchr(line, ':');
if (!value) continue;
++value;
while (*value == ' ' || *value == '\t') ++value;
std::size_t len = std::strlen(value);
while (len > 0 && (value[len - 1] == '\n' || value[len - 1] == '\r'))
--len;
if (len == 0 || len >= 128) continue;
char sink_name[128];
std::snprintf(sink_name, sizeof(sink_name), "%.*s", static_cast<int>(len), value);
++probed;
const int peak = monitor_peak(sink_name);
if (peak < 0 || peak >= kAudioPeakThreshold) {
playing = true;
break;
}
}
}
::pclose(sinks);
return playing;
}

/* dark_time drives the screen-off staging on the launcher home; the same
* whitelist (0/10/30/60/300, 0 = disabled) applies here. The config service
* is mutex-guarded, so reading it from this supervision thread is safe. */
int app_dark_time_seconds()
{
constexpr int kDefaultSeconds = 30;
int value = kDefaultSeconds;
try {
cp0::signal::invoke_noexcept([&] {
cp0_signal_config_api({"GetInt", "dark_time", std::to_string(kDefaultSeconds)},
[&](int code, std::string data) {
if (code != 0) return;
int parsed = 0;
const char *begin = data.data();
const char *end = begin + data.size();
const auto result = std::from_chars(begin, end, parsed);
if (result.ec == std::errc{} && result.ptr == end &&
(parsed == 0 || parsed == 10 || parsed == 30 ||
parsed == 60 || parsed == 300))
value = parsed;
});
});
} catch (...) {
}
return value;
}

/* Wi-Fi power save amplifies the stall: with PSM on, the radio's periodic
* naps stall the streaming TCP fetch long enough that ffplay's reconnect
* kicks in (up to 5 s of audible gap through a Bluetooth speaker), and the
* busy 2.4 GHz coexistence between the Wi-Fi side and the Bluetooth side of
* the same CYW4343 combo adds transport pressure. While media actually
* renders, the fetch traffic keeps the radio awake anyway, so PSM saves
* nothing but costs the stalls - drop it for the playback period and
* restore it once idle. The image ships a narrow sudoers rule allowing
* exactly these two commands (see etc/sudoers.d/applaunch-wifi-psm); when
* the rule is missing the call fails silently and PSM simply stays on. */
void wifi_power_save_set(bool enable)
{
/* iw wants the on/off keywords, not 0/1. */
std::system(enable
? "sudo -n /usr/sbin/iw dev wlan0 set power_save on >/dev/null 2>&1"
: "sudo -n /usr/sbin/iw dev wlan0 set power_save off >/dev/null 2>&1");
}

} // namespace
#endif

int run(const char *command, bool keep_root)
{
#if defined(_WIN32)
Expand Down Expand Up @@ -92,17 +270,38 @@ int run(const char *command, bool keep_root)
bool leader_reaped = false;
int status = 0;

const int dark_time_seconds = app_dark_time_seconds();
const bool staging_enabled = dark_time_seconds > 0;
std::uint64_t last_activity_ms = monotonic_ms();
std::uint64_t last_probe_ms = 0;
bool staged = false;
int staged_prev_raw = -1;
bool wifi_psm_off = false;
auto restore_stage = [&]() {
if (!staged) return;
if (staged_prev_raw > 0) (void)backlight_write_raw(staged_prev_raw);
staged = false;
staged_prev_raw = -1;
(void)cp0_status_led_restore();
};

while (true) {
cp0_process_group::reap_available(pid, pid, status, leader_reaped);
if (!cp0_process_group::exists(pid)) break;

struct input_event event;
while (read(keyboard_fd, &event, sizeof(event)) == static_cast<ssize_t>(sizeof(event))) {
if (event.type == EV_KEY && event.code == KEY_ESC) {
if (event.value == 1)
cp0_esc_state_write(1);
else if (event.value == 0)
cp0_esc_state_write(0);
if (event.type == EV_KEY) {
if (event.code == KEY_ESC) {
if (event.value == 1)
cp0_esc_state_write(1);
else if (event.value == 0)
cp0_esc_state_write(0);
}
if (event.value == 1) {
last_activity_ms = monotonic_ms();
restore_stage();
}
}
}

Expand All @@ -118,9 +317,51 @@ int run(const char *command, bool keep_root)
std::fprintf(stderr, "[process] grace timeout: SIGKILL pgid=%d\n", static_cast<int>(pid));
killpg(pid, SIGKILL);
}

/* The media probe drives both the staging and the Wi-Fi PSM toggle,
* so it runs even when the dim staging is disabled (dark_time = 0):
* streaming radio/music must keep the stall-free PSM-off period
* regardless of whether the panel is allowed to go dark. */
{
const std::uint64_t now_ms = monotonic_ms();
if (now_ms - last_probe_ms >= kSinkProbePeriodMs) {
last_probe_ms = now_ms;
if (any_media_rendering()) {
/* Radio/music/TV actually audible: media suppresses the
* sleep staging, so the panel stays on for the session. */
last_activity_ms = now_ms;
restore_stage();
if (!wifi_psm_off) {
wifi_power_save_set(false);
wifi_psm_off = true;
}
} else {
if (wifi_psm_off) {
wifi_power_save_set(true);
wifi_psm_off = false;
}
if (staging_enabled && !staged &&
now_ms - last_activity_ms >=
static_cast<std::uint64_t>(dark_time_seconds) * 1000ULL) {
const int previous = backlight_read_raw();
if (previous > 0 && backlight_write_raw(0) == 0) {
staged_prev_raw = previous;
staged = true;
(void)cp0_status_led_suspend();
}
}
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}

restore_stage();
/* The app left the media probe behind; never leave PSM off after it. */
if (wifi_psm_off) {
wifi_power_save_set(true);
wifi_psm_off = false;
}
if (esc_policy.finish().hide_hint) ui_external_esc_hint(0);
cp0_process_group::reap_available(pid, pid, status, leader_reaped);
std::fprintf(stderr,
Expand Down
7 changes: 7 additions & 0 deletions ext_components/cp0_lvgl/src/cp0/cp0_lvgl_bluetooth.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,10 @@ int remove(const char *address)
}

} // namespace cp0_bluetooth_backend

extern "C" void cp0_bluetooth_power_set_async(int enabled)
{
/* Fire-and-forget: the screen-off staging calls this on the LVGL thread
* and must never wait on D-Bus. */
cp0_bluez_dbus::set_power_async(enabled, nullptr);
}
12 changes: 12 additions & 0 deletions ext_components/cp0_lvgl/src/cp0/cp0_lvgl_network.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "cp0_lvgl_app.h"
#include "keyboard_input.h" // LVGL_RUN_FLAGE
#include "hal_lvgl_bsp.h"
#include "cp0_status_pause.h" // screen-off polling hold
#include "../cp0_app_internal_utils.h"
#include "../cp0_network_api_contract.hpp"
#include "../cp0_callback_result.hpp"
Expand Down Expand Up @@ -503,6 +504,17 @@ class WifiSystem
auto last_refresh = std::chrono::steady_clock::time_point{};
while (running_.load()) {
const auto now = std::chrono::steady_clock::now();
if (cp0_status_pause_get()) {
/* The panel is dark: hold all status polling instead of the
* 60 s hidden backstop. Wi-Fi itself stays connected; the
* cache refreshes right after the flag clears (last_refresh
* reset below makes the first awake iteration refresh). */
last_refresh = std::chrono::steady_clock::time_point{};
std::unique_lock<std::mutex> lock(wake_mutex_);
wake_.wait_for(lock, kVisiblePollInterval,
[this] { return !running_.load(); });
continue;
}
if (last_refresh == std::chrono::steady_clock::time_point{} || status_visible() ||
now - last_refresh >= kHiddenPollInterval) {
update_status_cache();
Expand Down
Loading