Network Monitor app (Stage 2): live /proc/net/dev monitor - XNetGraph + 2x XSysBox + XHistoryGraph + XUsageBar

This commit is contained in:
Muse committed 2026-12-05 20:15:48 +00:00
1 parent 03065d35bf
commit 0934970206
3 files changed
+273

No files matched your search

@@ -0,0 +1,50 @@
# Network Monitor — monitor (Python)
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 once a second:
- **XNetGraph** (top) — up/down graph in bytes/s, current rates plus
session totals in the legend.
- **XSysBox** (middle, x2) — Download / Upload big-number boxes in
KiB/s, each with its own history sparkline and usage bar. The range
tracks the session peak (x1.15, floor 100 KiB/s).
- **XHistoryGraph** — down/up rate history in KiB/s, 60 s window,
current / min / max / average per series.
- **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 draw deterministic demo data until live samples are
pushed; `push()` / `push_net()` start a fresh live series (the demo
is never extended), so everything on screen after the first tick is
measured traffic. The 1 s tick matches `push_net()`, which
accumulates one second of totals per push.
## Run
```sh
PYTHONPATH=. python3 examples/monitor_network_monitor/main.py
# quit by closing the window
```
## Tests
```sh
DISPLAY=:99 python3 -m unittest discover -s tests
```
## 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)
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env python3
"""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 once a second:
XNetGraph up/down graph, current rates + session totals
XSysBox x2 Download / Upload big-number boxes (KiB/s + history)
XHistoryGraph rate history, down/up in KiB/s (60 s window)
XUsageBar total throughput as % of the link speed
The widgets draw deterministic demo data until live samples are
pushed; push()/push_net() start a fresh live series (the demo is
never extended), so everything on screen after the first tick is
measured traffic. The 1 s tick matches push_net(), which accumulates
one second of totals per push.
Run with:
PYTHONPATH=/root/monitor-wt/network-monitor/lightgui_python \\
python3 examples/monitor_network_monitor/main.py
(or from the repo root with PYTHONPATH=.)
Quit: close the window.
"""
import os
import sys
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import GLib, Gtk # noqa: E402
from lightgui.xframe.core import create, parse_color # noqa: E402
TITLE = "Network Monitor - monitor"
WIN_W, WIN_H = 1024, 768
def read_counters(iface):
"""(rx_bytes, tx_bytes) for iface from /proc/net/dev, or None."""
try:
with open("/proc/net/dev") as f:
lines = f.readlines()
except OSError:
return None
for line in lines:
if ":" not in line:
continue
name, rest = line.split(":", 1)
if name.strip() != iface:
continue
fields = rest.split()
if len(fields) < 9:
return None
try:
return (int(fields[0]), int(fields[8]))
except ValueError:
return None
return None
def pick_iface():
"""Prefer enp3s0; else the first non-loopback interface with traffic."""
if read_counters("enp3s0") is not None:
return "enp3s0"
try:
with open("/proc/net/dev") as f:
lines = f.readlines()
except OSError:
return "enp3s0"
fallback = "enp3s0"
for line in lines:
if ":" not in line:
continue
name, rest = line.split(":", 1)
name = name.strip()
if not name or name == "lo":
continue
if fallback == "enp3s0":
fallback = name
fields = rest.split()
try:
rx = int(fields[0]) if fields else 0
tx = int(fields[8]) if len(fields) > 8 else 0
except ValueError:
continue
if rx > 0 or tx > 0:
return name
return fallback
def link_speed_bps(iface):
"""Link speed in bits/s from /sys/class/net/<iface>/speed (Mbit/s)."""
try:
with open("/sys/class/net/%s/speed" % iface) as f:
mbps = int(f.read().strip())
if mbps > 0:
return mbps * 1e6
except (OSError, ValueError):
pass
return 1e9 # unknown: assume 1 Gb/s
IFACE = pick_iface()
LINK_BPS = link_speed_bps(IFACE)
_WIDGETS = []
_AREA = []
_PREV = [None, None] # (rx, tx) counters from the previous tick
_PEAK = [100.0, 100.0] # peak down/up KiB/s (floor 100), tracks x1.15
def _build_widgets():
"""Create the five monitor widgets with live-data props."""
widgets = []
net = create("XNetGraph", "NetworkMonitor_001", 12, 12, 1000, 300)
net.set_prop("label", "Network - %s" % IFACE)
widgets.append(net)
down = create("XSysBox", "NetworkMonitor_002", 12, 324, 492, 180)
down.set_prop("label", "Download - %s" % IFACE)
down.set_prop("unit", " KiB/s")
down.set_prop("minimum", "0")
down.set_prop("maximum", "100")
down.set_prop("value", "0")
widgets.append(down)
up = create("XSysBox", "NetworkMonitor_003", 520, 324, 492, 180)
up.set_prop("label", "Upload - %s" % IFACE)
up.set_prop("unit", " KiB/s")
up.set_prop("minimum", "0")
up.set_prop("maximum", "100")
up.set_prop("value", "0")
widgets.append(up)
hist = create("XHistoryGraph", "NetworkMonitor_004", 12, 516, 1000, 172)
hist.set_prop("label", "Rate history (KiB/s)")
hist.set_prop("series-names", "Down KiB/s|Up KiB/s")
hist.set_prop("minimum", "0")
hist.set_prop("maximum", "100")
widgets.append(hist)
usage = create("XUsageBar", "NetworkMonitor_005", 12, 700, 1000, 44)
usage.set_prop("label", "Link use - %s (%.0f Gb/s)"
% (IFACE, LINK_BPS / 1e9))
usage.set_prop("minimum", "0")
usage.set_prop("maximum", "100")
usage.set_prop("value", "0")
widgets.append(usage)
return widgets
def _on_draw(area, cr):
bg = parse_color("", None)
if bg is None:
bg = (1.0, 1.0, 1.0)
cr.set_source_rgb(*bg)
cr.paint()
for widget in _WIDGETS:
widget.draw(cr)
return False
def _tick():
"""One live sample per second: difference /proc/net/dev, push, redraw."""
now = read_counters(IFACE)
if now is None:
return True
prev = _PREV[0]
_PREV[0] = now
if prev is None:
return True
down_bps = float(now[0] - prev[0]) if now[0] >= prev[0] else 0.0
up_bps = float(now[1] - prev[1]) if now[1] >= prev[1] else 0.0
down_kb = down_bps / 1024.0
up_kb = up_bps / 1024.0
_PEAK[0] = max(_PEAK[0], down_kb * 1.15)
_PEAK[1] = max(_PEAK[1], up_kb * 1.15)
net, down, up, hist, usage = _WIDGETS
net.push_net(down_bps, up_bps)
down.set_prop("maximum", "%.1f" % _PEAK[0])
down.set_prop("value", "%.1f" % down_kb)
down.push(down_kb)
up.set_prop("maximum", "%.1f" % _PEAK[1])
up.set_prop("value", "%.1f" % up_kb)
up.push(up_kb)
hist.set_prop("maximum", "%.1f" % max(_PEAK[0], _PEAK[1]))
hist.push(down_kb, series=0)
hist.push(up_kb, series=1)
usage.set_prop("value", "%.1f"
% min(100.0, (down_bps + up_bps) / LINK_BPS * 100.0))
if _AREA:
_AREA[0].queue_draw()
return True
def main():
window = Gtk.Window(title=TITLE)
window.set_default_size(WIN_W, WIN_H)
window.set_resizable(False)
window.connect("destroy", Gtk.main_quit)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
window.add(vbox)
area = Gtk.DrawingArea()
area.set_hexpand(True)
area.set_vexpand(True)
area.connect("draw", _on_draw)
vbox.pack_start(area, True, True, 0)
_WIDGETS.extend(_build_widgets())
_AREA.append(area)
_PREV[0] = read_counters(IFACE) # baseline; first tick differences it
GLib.timeout_add(1000, _tick)
window.show_all()
Gtk.main()
return 0
if __name__ == "__main__":
sys.exit(main())
Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB