From d6cd916d20fd02e07b40d217c83e71e7d22e6f75 Mon Sep 17 00:00:00 2001 From: irrlicht Date: Mon, 2 Nov 2026 23:51:41 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20Systemauslastung=20statt=20Lautst=C3=A4?= =?UTF-8?q?rke=20und=20Temperatur=20anzeigen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Die Lautstärke-Anzeige (samt SIGUSR1-Handling und signal-hook) und die Temperatur entfallen. Neu angezeigt werden CPU-, RAM-, GPU- und VRAM-Auslastung sowie der Füllstand der Root-Partition. Als GPU wird die mit dem meisten VRAM gewählt, also die dedizierte Karte statt der iGPU. Der Netzwerk-Traffic wird jetzt in gerundeten Kbit/s ohne Einheit angezeigt, um Platz zu sparen. Die Polling-Threads laufen über eine gemeinsame Hilfsfunktion spawn_poller. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 41 +-------- Cargo.toml | 2 +- src/main.rs | 243 +++++++++++++++++++++++++++++++--------------------- 3 files changed, 145 insertions(+), 141 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index db5e919..78d81ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -58,16 +58,6 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys", -] - [[package]] name = "find-msvc-tools" version = "0.1.11" @@ -196,26 +186,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" -[[package]] -name = "signal-hook" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" -dependencies = [ - "libc", - "signal-hook-registry", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - [[package]] name = "slab" version = "0.4.12" @@ -227,7 +197,7 @@ name = "statusline" version = "0.1.0" dependencies = [ "chrono", - "signal-hook", + "libc", ] [[package]] @@ -350,12 +320,3 @@ checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ "windows-link", ] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] diff --git a/Cargo.toml b/Cargo.toml index 90342ee..79ed427 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,4 +5,4 @@ edition = "2024" [dependencies] chrono = "0.4" -signal-hook = "0.3" +libc = "0.2" diff --git a/src/main.rs b/src/main.rs index f3b3219..6a39435 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,84 +1,110 @@ +use std::ffi::CString; use std::io::{self, Write}; -use std::process::Command; use std::sync::mpsc; use std::time::Duration; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use chrono::Local; -use signal_hook::consts::SIGUSR1; -use signal_hook::iterator::Signals; enum Update { Clock(String), - Volume(String), - Temp(String), + Cpu(String), + Ram(String), + Gpu(String), + Disk(String), Net(String), } -fn query_volume() -> String { - let output = Command::new("wpctl") - .args(["get-volume", "@DEFAULT_AUDIO_SINK@"]) - .output(); +// Returns (busy, total) jiffies summed over all CPUs from the first line of +// /proc/stat. +fn read_cpu_times() -> Option<(u64, u64)> { + let content = fs::read_to_string("/proc/stat").ok()?; + let line = content.lines().next()?; + // Layout: "cpu user nice system idle iowait irq softirq steal guest guest_nice". + // guest/guest_nice are already included in user/nice, so only the first + // eight fields count towards the total. + let fields: Vec = line + .split_whitespace() + .skip(1) + .take(8) + .filter_map(|s| s.parse().ok()) + .collect(); + if fields.len() < 8 { + return None; + } + let total: u64 = fields.iter().sum(); + let idle = fields[3] + fields[4]; + Some((total - idle, total)) +} - let text = match output { - Ok(out) => String::from_utf8_lossy(&out.stdout).trim().to_string(), - Err(_) => return "vol:?".to_string(), +fn query_ram() -> String { + let content = match fs::read_to_string("/proc/meminfo") { + Ok(c) => c, + Err(_) => return "ram:?".to_string(), }; - let muted = text.contains("[MUTED]"); - let percent = text - .split_whitespace() - .nth(1) - .and_then(|s| s.parse::().ok()) - .map(|v| (v * 100.0).round() as i64); + let field = |name: &str| { + content + .lines() + .find(|l| l.starts_with(name)) + .and_then(|l| l.split_whitespace().nth(1)) + .and_then(|v| v.parse::().ok()) + }; - match (percent, muted) { - (Some(p), true) => format!("vol:{p}% [muted]"), - (Some(p), false) => format!("vol:{p}%"), - (None, _) => "vol:?".to_string(), + match (field("MemTotal:"), field("MemAvailable:")) { + (Some(total), Some(avail)) if total > 0 => { + format!("ram:{:>3}%", (total - avail) * 100 / total) + } + _ => "ram:?".to_string(), } } -fn query_cpu_temp() -> String { - let mut max_temp: Option = None; - let hwmon_path = Path::new("/sys/class/hwmon"); +fn read_u64(path: &Path) -> Option { + fs::read_to_string(path).ok()?.trim().parse().ok() +} - let hwmon_dirs = match fs::read_dir(hwmon_path) { - Ok(d) => d, - Err(_) => return "temp:?".to_string(), - }; +// Picks the amdgpu device with the most VRAM, i.e. the dedicated card rather +// than the iGPU, independent of the order the cards were enumerated in. +fn find_gpu() -> Option { + fs::read_dir("/sys/class/drm") + .ok()? + .flatten() + .map(|e| e.path().join("device")) + .filter(|d| d.join("gpu_busy_percent").exists()) + .max_by_key(|d| read_u64(&d.join("mem_info_vram_total")).unwrap_or(0)) +} - for dir_entry in hwmon_dirs.flatten() { - let dir_path = dir_entry.path(); - let entries = match fs::read_dir(&dir_path) { - Ok(e) => e, - Err(_) => continue, - }; +fn query_gpu(device: &Path) -> String { + let busy = read_u64(&device.join("gpu_busy_percent")); + let used = read_u64(&device.join("mem_info_vram_used")); + let total = read_u64(&device.join("mem_info_vram_total")); - for entry in entries.flatten() { - let filename = entry.file_name(); - let filename_str = filename.to_string_lossy(); - - if filename_str.starts_with("temp") && filename_str.ends_with("_input") { - let file_path = entry.path(); - if let Ok(content) = fs::read_to_string(&file_path) { - if let Ok(temp_milli) = content.trim().parse::() { - let temp_c = temp_milli / 1000; - max_temp = Some(match max_temp { - Some(current_max) => current_max.max(temp_c), - None => temp_c, - }); - } - } - } + match (busy, used, total) { + (Some(b), Some(u), Some(t)) if t > 0 => { + format!("gpu:{b:>3}% vram:{:>3}%", u * 100 / t) } + _ => "gpu:?".to_string(), + } +} + +// Fill level of the root filesystem, computed like df: blocks reserved for +// root count neither as used nor as available. +fn query_disk() -> String { + let path = CString::new("/").unwrap(); + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(path.as_ptr(), &mut st) } != 0 { + return "disk:?".to_string(); } - match max_temp { - Some(t) => format!("temp:{}°C", t), - None => "temp:?".to_string(), + let used = (st.f_blocks - st.f_bfree) as u64; + let avail = st.f_bavail as u64; + if used + avail == 0 { + return "disk:?".to_string(); } + // Round up, as df does, so a nearly full disk never shows as less full. + let percent = (used * 100).div_ceil(used + avail); + format!("disk:{percent:>3}%") } // Sums rx/tx byte counters across physical interfaces only. Virtual ones @@ -112,70 +138,84 @@ fn read_net_bytes() -> (u64, u64) { (down, up) } -// Fixed-width, fixed-unit (Mbit/s, decimal like ISP rates) formatting so the -// bar doesn't change size as traffic fluctuates. +// Rounded decimal Kbit/s without a unit to save space. Fixed width so the bar +// doesn't change size as traffic fluctuates (up to 99999, i.e. ~100 Mbit/s). fn format_net(down_bytes_per_sec: u64, up_bytes_per_sec: u64) -> String { - let to_mbps = |b: u64| b as f64 * 8.0 / 1_000_000.0; - let down = to_mbps(down_bytes_per_sec); - let up = to_mbps(up_bytes_per_sec); - format!("net:↓{down:>5.1} ↑{up:>5.1} Mbit/s") + let to_kbps = |b: u64| (b * 8 + 500) / 1000; + let down = to_kbps(down_bytes_per_sec); + let up = to_kbps(up_bytes_per_sec); + format!("net:↓{down:>5} ↑{up:>5}") +} + +// Runs `poll` immediately and then every `interval`, forwarding each result. +fn spawn_poller(tx: &mpsc::Sender, interval: Duration, mut poll: F) +where + F: FnMut() -> Update + Send + 'static, +{ + let tx = tx.clone(); + std::thread::spawn(move || loop { + tx.send(poll()).unwrap(); + std::thread::sleep(interval); + }); } fn main() { let (tx, rx) = mpsc::channel::(); + spawn_poller(&tx, Duration::from_secs(1), || { + Update::Clock(Local::now().format("%Y-%m-%d %H:%M:%S").to_string()) + }); + { - let tx = tx.clone(); - std::thread::spawn(move || loop { - let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string(); - tx.send(Update::Clock(now)).unwrap(); - std::thread::sleep(Duration::from_secs(1)); + let mut prev = read_cpu_times(); + spawn_poller(&tx, Duration::from_secs(1), move || { + let now = read_cpu_times(); + let text = match (prev, now) { + (Some((prev_busy, prev_total)), Some((busy, total))) if total > prev_total => { + let percent = (busy - prev_busy) * 100 / (total - prev_total); + format!("cpu:{percent:>3}%") + } + _ => "cpu: 0%".to_string(), + }; + prev = now; + Update::Cpu(text) }); } - { - let tx = tx.clone(); - std::thread::spawn(move || { - tx.send(Update::Volume(query_volume())).unwrap(); + spawn_poller(&tx, Duration::from_secs(2), || Update::Ram(query_ram())); - let mut signals = - Signals::new([SIGUSR1]).expect("failed to register signal handler"); - for _ in signals.forever() { - tx.send(Update::Volume(query_volume())).unwrap(); - } + { + let gpu = find_gpu(); + spawn_poller(&tx, Duration::from_secs(2), move || { + Update::Gpu(match &gpu { + Some(device) => query_gpu(device), + None => "gpu:?".to_string(), + }) }); } - { - let tx = tx.clone(); - std::thread::spawn(move || loop { - tx.send(Update::Temp(query_cpu_temp())).unwrap(); - std::thread::sleep(Duration::from_secs(5)); - }); - } + spawn_poller(&tx, Duration::from_secs(30), || Update::Disk(query_disk())); { - let tx = tx.clone(); - std::thread::spawn(move || { - const INTERVAL: Duration = Duration::from_secs(1); - let (mut prev_down, mut prev_up) = read_net_bytes(); - loop { - std::thread::sleep(INTERVAL); - let (down, up) = read_net_bytes(); - let down_rate = down.saturating_sub(prev_down) / INTERVAL.as_secs(); - let up_rate = up.saturating_sub(prev_up) / INTERVAL.as_secs(); - tx.send(Update::Net(format_net(down_rate, up_rate))).unwrap(); - prev_down = down; - prev_up = up; - } + const INTERVAL: Duration = Duration::from_secs(1); + let (mut prev_down, mut prev_up) = read_net_bytes(); + spawn_poller(&tx, INTERVAL, move || { + let (down, up) = read_net_bytes(); + let down_rate = down.saturating_sub(prev_down) / INTERVAL.as_secs(); + let up_rate = up.saturating_sub(prev_up) / INTERVAL.as_secs(); + prev_down = down; + prev_up = up; + Update::Net(format_net(down_rate, up_rate)) }); } drop(tx); let mut clock = String::new(); - let mut volume = String::new(); - let mut temp = String::new(); + let mut cpu = String::new(); + let mut ram = String::new(); + let mut gpu = String::new(); + let mut disk = String::new(); let mut net = String::new(); let stdout = io::stdout(); let mut handle = stdout.lock(); @@ -183,11 +223,14 @@ fn main() { for update in rx { match update { Update::Clock(s) => clock = s, - Update::Volume(s) => volume = s, - Update::Temp(s) => temp = s, + Update::Cpu(s) => cpu = s, + Update::Ram(s) => ram = s, + Update::Gpu(s) => gpu = s, + Update::Disk(s) => disk = s, Update::Net(s) => net = s, } - writeln!(handle, "{volume} | {net} | {temp} | {clock}").expect("failed to write to stdout"); + writeln!(handle, "{cpu} | {ram} | {gpu} | {disk} | {net} | {clock}") + .expect("failed to write to stdout"); handle.flush().expect("failed to flush stdout"); } }