Temperature Monitor app: honest zero-sensor state + MonitorWidget.clear()
Single-widget monitor app (XTempHistory, 80 C threshold) reading /sys/class/thermal + /sys/class/hwmon every 2 s. hot_dallas has no thermal sensors, so the app shows the widget empty state (no data, no fake readings) with a title that says so. Adds additive MonitorWidget::clear() and an empty-state readout.
This commit is contained in:
1 parent
9e6f882575
commit
8fe131c1ee
4 files changed
+369
-5
No files matched your search
@@ -0,0 +1,38 @@
|
||||
# Temperature Monitor — monitor (Rust)
|
||||
|
||||
A btop-style temperature monitor in one 1024x768 window, built only
|
||||
from LightGUI XFrame monitor widgets:
|
||||
|
||||
- **XTempHistory** — temperature history of the first thermal zone,
|
||||
with an 80 °C threshold line (readings above it draw red)
|
||||
|
||||
Live data comes from `/sys/class/thermal/thermal_zone*/temp` and
|
||||
`/sys/class/hwmon/hwmon*/temp*_input`, re-scanned every 2 s. On a
|
||||
machine with sensors the history fills with live readings; on this
|
||||
machine (hot_dallas, a VPS with no thermal sensors at all — only
|
||||
cooling devices under `/sys/class/thermal/`, no `thermal_zone*/temp`
|
||||
files, an empty `/sys/class/hwmon/`) the app shows the widget's
|
||||
honest empty state: an empty graph, "no data" in the legend, and a
|
||||
title that says no thermal zones were found. No mock or demo
|
||||
temperatures: the seeded demo series is dropped at startup with
|
||||
`MonitorWidget::clear()`.
|
||||
|
||||
## Run
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_temperature_monitor
|
||||
```
|
||||
|
||||
Pass a hold time in seconds to exit on its own (screenshots):
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_temperature_monitor -- 8
|
||||
```
|
||||
|
||||
Esc, `q`, or closing the window quits.
|
||||
|
||||
## Source
|
||||
|
||||
- App: `crates/xframe-demo/examples/monitor_temperature_monitor/main.rs`
|
||||
- Widget: `crates/xframe-widgets/src/monitor.rs`
|
||||
- Repo: https://github.com/cnmcdee/lightgui_rust
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Temperature Monitor — monitor (Rust).
|
||||
//!
|
||||
//! A btop-style temperature monitor in one 1024x768 window, built
|
||||
//! only from LightGUI XFrame monitor widgets (`XTempHistory`):
|
||||
//! the first thermal zone's temperature history with an 80 °C
|
||||
//! threshold line, re-scanned every 2 s from
|
||||
//! `/sys/class/thermal/thermal_zone*/temp` and
|
||||
//! `/sys/class/hwmon/hwmon*/temp*_input`.
|
||||
//!
|
||||
//! On this machine (hot_dallas, a VPS) there are NO thermal sensors
|
||||
//! at all: `/sys/class/thermal/` holds only cooling devices, there
|
||||
//! are no `thermal_zone*/temp` files, `/sys/class/hwmon/` is empty
|
||||
//! and `sensors` is not installed. So the app shows the widget's
|
||||
//! honest empty state ("no data", no line, no fake 0.0 °C reading)
|
||||
//! and says so in the title. No mock or demo temperatures, ever:
|
||||
//! the seeded demo series is dropped at startup with
|
||||
//! `MonitorWidget::clear()`. If sensors ever appear (e.g. on a
|
||||
//! machine that has them) the rescan picks them up and the history
|
||||
//! starts filling with live readings.
|
||||
//!
|
||||
//! Run it from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_temperature_monitor
|
||||
//! Pass a hold time in seconds to exit on its own (screenshots):
|
||||
//! cargo run -p xframe-demo --example monitor_temperature_monitor -- 8
|
||||
//! Esc / `q` / window-close quits.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::*;
|
||||
use x11rb::protocol::Event;
|
||||
use xframe_common::style::FONT_DEFAULT;
|
||||
use xframe_common::target::CtxTarget;
|
||||
use xframe_common::x11::{DrawCtx, X11};
|
||||
use xframe_core::StyleManager;
|
||||
use xframe_widgets::{MonitorWidget, Widget};
|
||||
|
||||
const WIN_W: u16 = 1024;
|
||||
const WIN_H: u16 = 768;
|
||||
const KEY_ESCAPE: u32 = 0xff1b;
|
||||
const NO_ZONES_TITLE: &str = "Temperature history -- no thermal zones found";
|
||||
|
||||
/// One temperature input the kernel exposes.
|
||||
struct Zone {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
fn read_first_line(path: &Path) -> Option<String> {
|
||||
fs::read_to_string(path)
|
||||
.ok()?
|
||||
.lines()
|
||||
.next()
|
||||
.map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
fn read_temp_c(path: &Path) -> Option<f64> {
|
||||
read_first_line(path)?.parse::<f64>().ok().map(|m| m / 1000.0)
|
||||
}
|
||||
|
||||
/// All temperature inputs the kernel exposes, thermal zones first.
|
||||
fn scan_zones() -> Vec<Zone> {
|
||||
let mut zones = Vec::new();
|
||||
if let Ok(thermal) = fs::read_dir("/sys/class/thermal") {
|
||||
for ent in thermal.flatten() {
|
||||
let name = ent.file_name().to_string_lossy().into_owned();
|
||||
if !name.starts_with("thermal_zone") {
|
||||
continue;
|
||||
}
|
||||
let base = ent.path();
|
||||
let temp_path = base.join("temp");
|
||||
if read_temp_c(&temp_path).is_none() {
|
||||
continue;
|
||||
}
|
||||
let label = read_first_line(&base.join("type")).unwrap_or(name.clone());
|
||||
zones.push(Zone {
|
||||
name: if label.is_empty() { name } else { label },
|
||||
path: temp_path,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Ok(hwmon) = fs::read_dir("/sys/class/hwmon") {
|
||||
for ent in hwmon.flatten() {
|
||||
let name = ent.file_name().to_string_lossy().into_owned();
|
||||
if !name.starts_with("hwmon") {
|
||||
continue;
|
||||
}
|
||||
let base = ent.path();
|
||||
let chip = read_first_line(&base.join("name")).unwrap_or(name.clone());
|
||||
let chip = if chip.is_empty() { name } else { chip };
|
||||
if let Ok(dir) = fs::read_dir(&base) {
|
||||
for f in dir.flatten() {
|
||||
let fname = f.file_name().to_string_lossy().into_owned();
|
||||
if !fname.starts_with("temp") || !fname.ends_with("_input") {
|
||||
continue;
|
||||
}
|
||||
let temp_path = f.path();
|
||||
if read_temp_c(&temp_path).is_none() {
|
||||
continue;
|
||||
}
|
||||
let stem = fname.trim_end_matches("_input");
|
||||
let label = read_first_line(&base.join(format!("{}_label", stem)))
|
||||
.unwrap_or_default();
|
||||
zones.push(Zone {
|
||||
name: if label.is_empty() {
|
||||
chip.clone()
|
||||
} else {
|
||||
format!("{} {}", chip, label)
|
||||
},
|
||||
path: temp_path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
zones
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let hold = std::env::args()
|
||||
.nth(1)
|
||||
.and_then(|a| a.parse::<u64>().ok());
|
||||
|
||||
let x = match X11::connect() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let font = match x.open_font(&[FONT_DEFAULT, "fixed"]) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let title = "Temperature Monitor - monitor";
|
||||
let event_mask = EventMask::EXPOSURE
|
||||
| EventMask::KEY_PRESS
|
||||
| EventMask::STRUCTURE_NOTIFY
|
||||
| EventMask::BUTTON_PRESS
|
||||
| EventMask::BUTTON_RELEASE
|
||||
| EventMask::POINTER_MOTION;
|
||||
let (win, gc) = match x.create_window(100, 100, WIN_W, WIN_H, title, event_mask) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut styles = StyleManager::new();
|
||||
xframe_demo::register_styles(&mut styles);
|
||||
|
||||
let mut temp = MonitorWidget::new(NO_ZONES_TITLE, "TempHistory", 16, 16, 992, 736);
|
||||
temp.set_text(NO_ZONES_TITLE);
|
||||
temp.threshold = 80.0;
|
||||
// Drop the seeded demo series: with no live source the honest
|
||||
// state is an empty graph, not a fake warm-up curve.
|
||||
temp.clear();
|
||||
|
||||
let ctx = DrawCtx::new(&x, win, gc, font);
|
||||
ctx.bind_font();
|
||||
let mut target = CtxTarget::new(&ctx);
|
||||
if !styles.resolve_font("default", &mut target)
|
||||
&& !styles.resolve_font("dark", &mut target)
|
||||
{
|
||||
eprintln!("monitor_temperature_monitor: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
let redraw = |temp: &MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
temp.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
|
||||
// First scan before the first paint, so the title already tells
|
||||
// the truth on screen one.
|
||||
let mut zones = scan_zones();
|
||||
let mut had_zones = false;
|
||||
if let Some(z) = zones.first() {
|
||||
had_zones = true;
|
||||
let t = format!("Temperature history -- {}", z.name);
|
||||
temp.state.name = t.clone();
|
||||
temp.set_text(&t);
|
||||
if let Some(v) = read_temp_c(&z.path) {
|
||||
temp.push_value(v);
|
||||
}
|
||||
}
|
||||
redraw(&temp, &ctx, &mut target, &mut styles);
|
||||
|
||||
let deadline = hold.map(|s| Instant::now() + Duration::from_secs(s));
|
||||
let mut last_tick = Instant::now();
|
||||
loop {
|
||||
if let Some(d) = deadline {
|
||||
if Instant::now() >= d {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match x.conn.poll_for_event() {
|
||||
Ok(Some(ev)) => {
|
||||
let mut handled = false;
|
||||
match ev {
|
||||
Event::Expose(_) => {
|
||||
redraw(&temp, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = temp.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = temp.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = temp.on_motion(ev.event_x as i32, ev.event_y as i32);
|
||||
}
|
||||
Event::KeyPress(ev) => {
|
||||
let keysym = x.keysym_for_keycode(ev.detail);
|
||||
if keysym == KEY_ESCAPE || keysym == b'q' as u32 {
|
||||
break;
|
||||
}
|
||||
let text = if (0x20..0x7f).contains(&keysym) {
|
||||
Some(keysym as u8 as char)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let key = xframe_widgets::Key::from_keysym(keysym, text);
|
||||
handled = temp.on_key(key, text);
|
||||
}
|
||||
Event::ClientMessage(ev)
|
||||
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if handled {
|
||||
redraw(&temp, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("monitor_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
// 2 s tick: re-scan sysfs (sensors can appear on other
|
||||
// machines) and push the first zone's live reading.
|
||||
if last_tick.elapsed() >= Duration::from_secs(2) {
|
||||
last_tick = Instant::now();
|
||||
zones = scan_zones();
|
||||
if zones.is_empty() {
|
||||
if had_zones {
|
||||
had_zones = false;
|
||||
temp.clear();
|
||||
temp.state.name = NO_ZONES_TITLE.to_string();
|
||||
temp.set_text(NO_ZONES_TITLE);
|
||||
}
|
||||
} else if let Some(z) = zones.first() {
|
||||
if !had_zones {
|
||||
had_zones = true;
|
||||
let t = format!("Temperature history -- {}", z.name);
|
||||
temp.state.name = t.clone();
|
||||
temp.set_text(&t);
|
||||
}
|
||||
if let Some(v) = read_temp_c(&z.path) {
|
||||
temp.push_value(v);
|
||||
}
|
||||
}
|
||||
redraw(&temp, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
ExitCode::from(0)
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.1 KiB |
@@ -658,6 +658,18 @@ impl MonitorWidget {
|
||||
self.push_sample(0, v);
|
||||
}
|
||||
|
||||
/// Drop every sample from every history series (and reset the
|
||||
/// peak hold), keeping the series slots: a host app that found
|
||||
/// no live data yet shows the widget's honest empty state
|
||||
/// ("no data") instead of the seeded demo series. Later
|
||||
/// push_* calls fill the kept slots again as usual.
|
||||
pub fn clear(&mut self) {
|
||||
for s in &mut self.series {
|
||||
s.values.clear();
|
||||
}
|
||||
self.peak = f64::NEG_INFINITY;
|
||||
}
|
||||
|
||||
// -- stack bar -----------------------------------------------------------
|
||||
|
||||
pub fn set_segments(&mut self, segments: Vec<Segment>) {
|
||||
@@ -1051,11 +1063,22 @@ impl MonitorWidget {
|
||||
// under-measures the ° glyph and the label clips at the border.
|
||||
let tlabel = format!("{:.0}°C limit", self.threshold);
|
||||
draw_text_colored(target, style, plot.x + 4, ty - 2, &tlabel, RED);
|
||||
// Current value, red when over the threshold.
|
||||
let cur = self.series.first().map(|s| s.last()).unwrap_or(0.0);
|
||||
let col = if cur > self.threshold { RED } else { INK };
|
||||
let line = format!("now {:.1}°C threshold {:.0}°C", cur, self.threshold);
|
||||
draw_text_colored(target, style, b.x + 6, b.y + b.h - 8, &line, col);
|
||||
// Current value, red when over the threshold. Empty (no
|
||||
// samples pushed, e.g. no thermal zones found): say so
|
||||
// honestly instead of a 0.0 °C reading that never happened.
|
||||
let has_data = self
|
||||
.series
|
||||
.first()
|
||||
.map(|s| !s.values.is_empty())
|
||||
.unwrap_or(false);
|
||||
if has_data {
|
||||
let cur = self.series.first().map(|s| s.last()).unwrap_or(0.0);
|
||||
let col = if cur > self.threshold { RED } else { INK };
|
||||
let line = format!("now {:.1}°C threshold {:.0}°C", cur, self.threshold);
|
||||
draw_text_colored(target, style, b.x + 6, b.y + b.h - 8, &line, col);
|
||||
} else {
|
||||
draw_text_colored(target, style, b.x + 6, b.y + b.h - 8, "no data", INK);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_usage_bar(&self, target: &mut dyn DrawTarget, style: &Style) {
|
||||
@@ -1847,6 +1870,19 @@ mod tests {
|
||||
assert!(m.over_temp());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_clear_drops_demo_series() {
|
||||
let mut m = MonitorWidget::new("TempHistory", "TempHistory", 0, 0, 320, 200);
|
||||
assert!(!m.series.is_empty());
|
||||
assert!(!m.series[0].values.is_empty()); // seeded demo
|
||||
m.clear();
|
||||
assert!(m.series[0].values.is_empty());
|
||||
assert!(!m.over_temp());
|
||||
// A later live sample still lands in the kept series slot.
|
||||
m.push_value(42.0);
|
||||
assert_eq!(m.series[0].last(), 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_grid_polls_all_buttons() {
|
||||
let m = MonitorWidget::new("MonitorGrid", "MonitorGrid", 0, 0, 420, 200);
|
||||
|
||||
Reference in new issue
Block a user