Network Monitor app (Stage 2): live /proc/net/dev monitor - XNetGraph + 2x XSysBox + XHistoryGraph + XUsageBar
This commit is contained in:
1 parent
9e6f882575
commit
77d9446d2a
3 files changed
+471
No files matched your search
@@ -0,0 +1,41 @@
|
||||
# Network Monitor — monitor (Rust)
|
||||
|
||||
A live network monitor in one 1024x768 window, built only from the
|
||||
LightGUI XFrame monitor widgets (Stage 2 of the btop-widget project).
|
||||
|
||||
## What it shows
|
||||
|
||||
Live traffic for the main interface (`enp3s0` on hot_dallas, otherwise
|
||||
the first non-loopback interface with traffic), read from
|
||||
`/proc/net/dev` and differenced every 500 ms:
|
||||
|
||||
- **XNetGraph** (top) — up/down graph in KB/s, current rates plus
|
||||
session totals in the legend.
|
||||
- **XSysBox** (middle, x2) — Download / Upload big-number boxes in
|
||||
KB/s, each with its own history sparkline and usage bar. The range
|
||||
tracks the session peak (x1.15, floor 100 KB/s).
|
||||
- **XHistoryGraph** — down/up rate history in KB/s, 60 s window.
|
||||
- **XUsageBar** (bottom) — total throughput as a percentage of the
|
||||
link speed (from `/sys/class/net/<iface>/speed`, 1 Gb/s fallback).
|
||||
|
||||
## Live data, not demo data
|
||||
|
||||
The widgets seed deterministic demo series in the constructor. The
|
||||
app clears them (`series.clear()` + `add_series`) before the first
|
||||
draw, so everything on screen is measured traffic.
|
||||
|
||||
## Build and run
|
||||
|
||||
```sh
|
||||
bash -lc "cargo run -p xframe-demo --example monitor_network_monitor"
|
||||
# quit with q, Escape, or window close
|
||||
```
|
||||
|
||||
## Source
|
||||
|
||||
- C: `examples/monitor/network-monitor/main.cpp` in
|
||||
[lightgui](https://github.com/cnmcdee/lightgui)
|
||||
- Rust: `crates/xframe-demo/examples/monitor_network_monitor/main.rs` in
|
||||
[lightgui_rust](https://github.com/cnmcdee/lightgui_rust)
|
||||
- Python: `examples/monitor_network_monitor/main.py` in
|
||||
[lightgui_python](https://github.com/cnmcdee/lightgui_python)
|
||||
@@ -0,0 +1,430 @@
|
||||
//! Network Monitor - monitor (Stage 2, btop-widget project).
|
||||
//!
|
||||
//! One 1024x768 window showing LIVE traffic for the main interface
|
||||
//! (`enp3s0` on hot_dallas, else the first non-loopback interface with
|
||||
//! traffic), read from `/proc/net/dev` and differenced every 500 ms:
|
||||
//!
|
||||
//! * `XNetGraph` (top) — up/down graph, current rates + session totals.
|
||||
//! * `XSysBox` (middle, x2) — Download / Upload big-number boxes in
|
||||
//! KB/s, each with its own history sparkline and usage bar.
|
||||
//! * `XHistoryGraph` — down/up rate history in KB/s, 60 s window.
|
||||
//! * `XUsageBar` (bottom) — total throughput as % of the link speed.
|
||||
//!
|
||||
//! The widgets seed deterministic demo series in the constructor;
|
||||
//! the app clears them (`series.clear()` + `add_series`) before the
|
||||
//! first draw, so everything on screen is measured traffic.
|
||||
//!
|
||||
//! Run from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_network_monitor
|
||||
//! Quit: Esc / `q` / window close.
|
||||
|
||||
use std::fs;
|
||||
use std::process::ExitCode;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::EventMask;
|
||||
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_demo::register_styles;
|
||||
use xframe_widgets::monitor::MonitorWidget;
|
||||
use xframe_widgets::Widget;
|
||||
|
||||
const WIN_W: u16 = 1024;
|
||||
const WIN_H: u16 = 768;
|
||||
const KEY_ESCAPE: u32 = 0xff1b;
|
||||
|
||||
/// (rx_bytes, tx_bytes) for `iface` from /proc/net/dev.
|
||||
fn read_counters(iface: &str) -> Option<(u64, u64)> {
|
||||
let text = fs::read_to_string("/proc/net/dev").ok()?;
|
||||
for line in text.lines() {
|
||||
let Some((name, rest)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
if name.trim() != iface {
|
||||
continue;
|
||||
}
|
||||
let f: Vec<&str> = rest.split_whitespace().collect();
|
||||
if f.len() < 9 {
|
||||
return None;
|
||||
}
|
||||
return Some((f[0].parse().ok()?, f[8].parse().ok()?));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Prefer enp3s0; else the first non-loopback interface with traffic.
|
||||
fn pick_iface() -> String {
|
||||
if read_counters("enp3s0").is_some() {
|
||||
return "enp3s0".to_string();
|
||||
}
|
||||
if let Ok(text) = fs::read_to_string("/proc/net/dev") {
|
||||
let mut fallback = "enp3s0".to_string();
|
||||
for line in text.lines() {
|
||||
let Some((name, rest)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let name = name.trim();
|
||||
if name == "lo" || name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if fallback == "enp3s0" {
|
||||
fallback = name.to_string();
|
||||
}
|
||||
let f: Vec<&str> = rest.split_whitespace().collect();
|
||||
let rx: u64 = f.first().and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
let tx: u64 = f.get(8).and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
if rx > 0 || tx > 0 {
|
||||
return name.to_string();
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
"enp3s0".to_string()
|
||||
}
|
||||
|
||||
/// Link speed in bits/s from /sys/class/net/<iface>/speed (Mbit/s);
|
||||
/// unknown/unreadable -> assume 1 Gbit/s.
|
||||
fn link_speed_bps(iface: &str) -> f64 {
|
||||
let path = format!("/sys/class/net/{}/speed", iface);
|
||||
if let Ok(s) = fs::read_to_string(path) {
|
||||
if let Ok(mbps) = s.trim().parse::<i64>() {
|
||||
if mbps > 0 {
|
||||
return mbps as f64 * 1e6;
|
||||
}
|
||||
}
|
||||
}
|
||||
1e9
|
||||
}
|
||||
|
||||
fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let iface = pick_iface();
|
||||
let link_bps = link_speed_bps(&iface);
|
||||
|
||||
let x = X11::connect()?;
|
||||
let font = x.open_font(&[FONT_DEFAULT, "fixed"])?;
|
||||
let title = "Network Monitor - monitor".to_string();
|
||||
let event_mask = EventMask::EXPOSURE
|
||||
| EventMask::KEY_PRESS
|
||||
| EventMask::STRUCTURE_NOTIFY
|
||||
| EventMask::BUTTON_PRESS
|
||||
| EventMask::BUTTON_RELEASE
|
||||
| EventMask::POINTER_MOTION;
|
||||
let (win, gc) = x.create_window(100, 100, WIN_W, WIN_H, &title, event_mask)?;
|
||||
|
||||
let mut styles = StyleManager::new();
|
||||
register_styles(&mut styles);
|
||||
|
||||
// Widgets: seeded demo series are cleared below before first draw.
|
||||
let mut net = MonitorWidget::new(
|
||||
&format!("Network - {}", iface),
|
||||
"NetGraph",
|
||||
12,
|
||||
12,
|
||||
1000,
|
||||
300,
|
||||
);
|
||||
net.series.clear();
|
||||
net.add_series("Down");
|
||||
net.add_series("Up");
|
||||
net.unit = "KB/s".to_string();
|
||||
net.totals = (0.0, 0.0);
|
||||
net.state.min = 0.0;
|
||||
net.state.max = 0.0; // auto-range from the data
|
||||
|
||||
let mut down_box = MonitorWidget::new(
|
||||
"Download",
|
||||
"SysBox",
|
||||
12,
|
||||
324,
|
||||
492,
|
||||
180,
|
||||
);
|
||||
down_box.title = format!("Download - {}", iface);
|
||||
down_box.unit = " KB/s".to_string();
|
||||
down_box.state.min = 0.0;
|
||||
down_box.state.max = 100.0;
|
||||
down_box.series.clear();
|
||||
down_box.add_series("Download");
|
||||
|
||||
let mut up_box = MonitorWidget::new("Upload", "SysBox", 520, 324, 492, 180);
|
||||
up_box.title = format!("Upload - {}", iface);
|
||||
up_box.unit = " KB/s".to_string();
|
||||
up_box.state.min = 0.0;
|
||||
up_box.state.max = 100.0;
|
||||
up_box.series.clear();
|
||||
up_box.add_series("Upload");
|
||||
|
||||
let mut hist = MonitorWidget::new("Rate history (KB/s)", "HistoryGraph", 12, 516, 1000, 172);
|
||||
hist.series.clear();
|
||||
hist.add_series("Down KB/s");
|
||||
hist.add_series("Up KB/s");
|
||||
hist.state.min = 0.0;
|
||||
hist.state.max = 0.0; // auto-range from the data
|
||||
|
||||
let mut usage = MonitorWidget::new("Link use", "UsageBar", 12, 700, 1000, 44);
|
||||
usage.set_text(&format!(
|
||||
"Link use - {} ({:.0} Gb/s)",
|
||||
iface,
|
||||
link_bps / 1e9
|
||||
));
|
||||
usage.state.min = 0.0;
|
||||
usage.state.max = 100.0;
|
||||
usage.state.value = 0.0;
|
||||
|
||||
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_network_monitor: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
// First live rate (two reads 500 ms apart).
|
||||
let (rx0, tx0) = read_counters(&iface).unwrap_or((0, 0));
|
||||
thread::sleep(Duration::from_millis(500));
|
||||
let (mut prev_rx, mut prev_tx) = read_counters(&iface).unwrap_or((rx0, tx0));
|
||||
let mut prev_time = Instant::now();
|
||||
let mut down_bps = if prev_rx >= rx0 {
|
||||
(prev_rx - rx0) as f64 / 0.5
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let mut up_bps = if prev_tx >= tx0 {
|
||||
(prev_tx - tx0) as f64 / 0.5
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let mut peak_down = (down_bps / 1024.0 * 1.15).max(100.0);
|
||||
let mut peak_up = (up_bps / 1024.0 * 1.15).max(100.0);
|
||||
|
||||
// Feed one live sample into every widget, then draw.
|
||||
let push_sample = |net: &mut MonitorWidget,
|
||||
down_box: &mut MonitorWidget,
|
||||
up_box: &mut MonitorWidget,
|
||||
hist: &mut MonitorWidget,
|
||||
usage: &mut MonitorWidget,
|
||||
down_bps: f64,
|
||||
up_bps: f64,
|
||||
dt: f64,
|
||||
peak_down: f64,
|
||||
peak_up: f64,
|
||||
link_bps: f64| {
|
||||
let down_kb = down_bps / 1024.0;
|
||||
let up_kb = up_bps / 1024.0;
|
||||
net.push_samples(&[down_kb, up_kb]);
|
||||
net.totals.0 += down_bps * dt;
|
||||
net.totals.1 += up_bps * dt;
|
||||
hist.push_samples(&[down_kb, up_kb]);
|
||||
down_box.state.max = peak_down;
|
||||
up_box.state.max = peak_up;
|
||||
down_box.state.value = down_kb;
|
||||
up_box.state.value = up_kb;
|
||||
down_box.push_value(down_kb);
|
||||
up_box.push_value(up_kb);
|
||||
usage.state.value = ((down_bps + up_bps) / link_bps * 100.0).min(100.0);
|
||||
};
|
||||
push_sample(
|
||||
&mut net,
|
||||
&mut down_box,
|
||||
&mut up_box,
|
||||
&mut hist,
|
||||
&mut usage,
|
||||
down_bps,
|
||||
up_bps,
|
||||
0.5,
|
||||
peak_down,
|
||||
peak_up,
|
||||
link_bps,
|
||||
);
|
||||
|
||||
let redraw = |net: &MonitorWidget,
|
||||
down_box: &MonitorWidget,
|
||||
up_box: &MonitorWidget,
|
||||
hist: &MonitorWidget,
|
||||
usage: &MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
net.draw(target, styles);
|
||||
down_box.draw(target, styles);
|
||||
up_box.draw(target, styles);
|
||||
hist.draw(target, styles);
|
||||
usage.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target, &mut styles,
|
||||
);
|
||||
|
||||
let mut last_tick = Instant::now();
|
||||
loop {
|
||||
match x.conn.poll_for_event()? {
|
||||
Some(ev) => {
|
||||
let mut handled = false;
|
||||
match ev {
|
||||
Event::Expose(_) => {
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target,
|
||||
&mut styles,
|
||||
);
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = net.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || down_box.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || up_box.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || hist.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || usage.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = net.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || down_box.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || up_box.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || hist.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || usage.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = net.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| down_box.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| up_box.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| hist.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| usage.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
|
||||
};
|
||||
handled = net.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || down_box.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || up_box.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || hist.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || usage.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
);
|
||||
}
|
||||
Event::ClientMessage(ev)
|
||||
if ev.type_ == x.wm_protocols
|
||||
&& ev.data.as_data32()[0] == x.wm_delete =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if handled {
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target,
|
||||
&mut styles,
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
// Live tick every 500 ms.
|
||||
if last_tick.elapsed() >= Duration::from_millis(500) {
|
||||
last_tick = Instant::now();
|
||||
let now = Instant::now();
|
||||
if let Some((rx, tx)) = read_counters(&iface) {
|
||||
let dt = now.duration_since(prev_time).as_secs_f64();
|
||||
prev_time = now;
|
||||
if dt > 0.0 {
|
||||
down_bps = if rx >= prev_rx {
|
||||
(rx - prev_rx) as f64 / dt
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
up_bps = if tx >= prev_tx {
|
||||
(tx - prev_tx) as f64 / dt
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
prev_rx = rx;
|
||||
prev_tx = tx;
|
||||
peak_down = peak_down.max(down_bps / 1024.0 * 1.15);
|
||||
peak_up = peak_up.max(up_bps / 1024.0 * 1.15);
|
||||
push_sample(
|
||||
&mut net,
|
||||
&mut down_box,
|
||||
&mut up_box,
|
||||
&mut hist,
|
||||
&mut usage,
|
||||
down_bps,
|
||||
up_bps,
|
||||
dt,
|
||||
peak_down,
|
||||
peak_up,
|
||||
link_bps,
|
||||
);
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target,
|
||||
&mut styles,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_network_monitor: {}", e);
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.2 KiB |
Reference in new issue
Block a user