6 changed files with 293 additions and 273 deletions

No files matched your search

@@ -1,50 +0,0 @@
# 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
@@ -1,223 +0,0 @@
#!/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.

Before

Width:  |  Height:  |  Size: 46 KiB

@@ -0,0 +1,37 @@
# System Overview — monitor app
A system overview in one 1024x768 window, in the btop style: four
`XSysBox` composite boxes (CPU / MEM / NET / DISK), one `XLoadBadge`
(live load averages + uptime), two `XDonutGauge`s (CPU, Disk) and three
`XUsageBar`s (Memory, Disk, Network). All values are read live from
`/proc` (`stat`, `meminfo`, `net/dev`, `loadavg`, `uptime`) and
`statvfs("/")`, refreshed every 500 ms. No seeded demo data is shown:
the SysBox history graphs are flushed with live ticks before the
screenshot is taken (60 samples at 500 ms ≈ 30 s of run time).
Window title: `System Overview - monitor`.
## Widgets used
- `XSysBox` × 4 — CPU, MEM, NET (KB/s), DISK /
- `XLoadBadge` × 1 — 1 / 5 / 15 min load averages + uptime
- `XDonutGauge` × 2 — CPU, Disk /
- `XUsageBar` × 3 — Memory, Disk /, Network KB/s
## Build and run
```sh
make # builds ./system-overview
./system-overview # needs an X display; Esc / q / window-close quits
```
## Source
- C: `examples/monitor/system-overview/main.cpp` in
https://github.com/cnmcdee/lightgui
- Rust: `crates/xframe-demo/examples/monitor_system_overview.rs` in
https://github.com/cnmcdee/lightgui_rust
- Python: `examples/monitor_system_overview/main.py` in
https://github.com/cnmcdee/lightgui_python
Walkthrough: https://www.lightgui.com/monitor-system-overview/
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/env python3
"""System Overview - monitor app (Stage 2, btop-widget project).
One 1024x768 window: four XSysBox composites (CPU / MEM / NET / DISK),
one XLoadBadge (live load averages + uptime), two XDonutGauges (CPU,
Disk) and three XUsageBars (Memory, Disk, Network). All values are read
live from /proc (stat, meminfo, net/dev, loadavg, uptime) and
shutil.disk_usage("/"), refreshed every 500 ms. push() starts a fresh
series, so the SysBox graphs show live ticks only -- no seeded demo
data.
Run with the LightGUI Python package on PYTHONPATH:
PYTHONPATH=/root/monitor-wt/system-overview/lightgui_python \
python3 examples/monitor_system_overview/main.py
Press Esc / q or close the window to quit.
"""
import os
import shutil
import sys
import time
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, GLib, Gtk # noqa: E402
from lightgui.xframe.core import create, parse_color # noqa: E402
# ---------------------------------------------------------------------------
# Live data from /proc
# ---------------------------------------------------------------------------
class Sampler:
def __init__(self):
self.prev_idle = 0
self.prev_total = 0
self.prev_rx = 0
self.prev_t = None
def cpu(self):
try:
with open("/proc/stat") as f:
fields = f.readline().split()[1:9]
nums = [int(v) for v in fields]
except (OSError, ValueError):
return None
idle = nums[3] + nums[4]
total = sum(nums)
if self.prev_total == 0:
self.prev_idle, self.prev_total = idle, total
return None
d_total = total - self.prev_total
d_idle = idle - self.prev_idle
self.prev_idle, self.prev_total = idle, total
if d_total == 0:
return None
return 100.0 * (1.0 - d_idle / d_total)
def mem(self):
total = avail = 0
try:
with open("/proc/meminfo") as f:
for line in f:
parts = line.split()
if parts[0] == "MemTotal:":
total = int(parts[1])
elif parts[0] == "MemAvailable:":
avail = int(parts[1])
except (OSError, ValueError):
return None
if total == 0:
return None
return 100.0 * (1.0 - avail / total)
def net_kbps(self):
rx_total = 0
try:
with open("/proc/net/dev") as f:
lines = f.readlines()[2:]
for line in lines:
iface, rest = line.split(":", 1)
if iface.strip() == "lo":
continue
rx_total += int(rest.split()[0])
except (OSError, ValueError):
return None
now = time.time()
if self.prev_t is None:
self.prev_rx, self.prev_t = rx_total, now
return None
dt = now - self.prev_t
delta = rx_total - self.prev_rx
self.prev_rx, self.prev_t = rx_total, now
if dt <= 0:
return None
return delta / dt / 1024.0
@staticmethod
def disk():
try:
du = shutil.disk_usage("/")
except OSError:
return None
if du.total == 0:
return None
return 100.0 * (1.0 - du.free / du.total)
SAMPLER = Sampler()
DATA = {"cpu": 0.0, "mem": 0.0, "net": 0.0, "disk": 0.0}
def sample():
v = SAMPLER.cpu()
if v is not None:
DATA["cpu"] = v
v = SAMPLER.mem()
if v is not None:
DATA["mem"] = v
v = SAMPLER.net_kbps()
if v is not None:
DATA["net"] = v
v = SAMPLER.disk()
if v is not None:
DATA["disk"] = v
# ---------------------------------------------------------------------------
# App shell (same pattern as the generated widget examples: GTK window +
# DrawingArea, widgets drawn via widget.draw(cr))
# ---------------------------------------------------------------------------
_DESIGN_SIZE = (1024, 768)
_BACKGROUND = ""
_WIDGETS = []
_AREA = []
def _build_widgets():
widgets = []
badge = create("XLoadBadge", "badge", 16, 12, 992, 84)
widgets.append(badge)
cpu = create("XSysBox", "cpu", 16, 108, 488, 200)
cpu.set_prop("label", "CPU")
cpu.set_prop("unit", "%")
cpu.set_prop("maximum", "100")
widgets.append(cpu)
mem = create("XSysBox", "mem", 520, 108, 488, 200)
mem.set_prop("label", "MEM")
mem.set_prop("unit", "%")
mem.set_prop("maximum", "100")
widgets.append(mem)
net = create("XSysBox", "net", 16, 320, 488, 200)
net.set_prop("label", "NET")
net.set_prop("unit", " KB/s")
net.set_prop("maximum", "1000")
widgets.append(net)
disk = create("XSysBox", "disk", 520, 320, 488, 200)
disk.set_prop("label", "DISK /")
disk.set_prop("unit", "%")
disk.set_prop("maximum", "100")
widgets.append(disk)
donut_cpu = create("XDonutGauge", "donut_cpu", 16, 532, 180, 180)
donut_cpu.set_prop("label", "CPU")
donut_cpu.set_prop("unit", "CPU")
widgets.append(donut_cpu)
donut_disk = create("XDonutGauge", "donut_disk", 212, 532, 180, 180)
donut_disk.set_prop("label", "Disk /")
donut_disk.set_prop("unit", "Disk /")
widgets.append(donut_disk)
bar_mem = create("XUsageBar", "bar_mem", 408, 532, 600, 44)
bar_mem.set_prop("label", "Memory")
bar_mem.set_prop("maximum", "100")
widgets.append(bar_mem)
bar_disk = create("XUsageBar", "bar_disk", 408, 596, 600, 44)
bar_disk.set_prop("label", "Disk /")
bar_disk.set_prop("maximum", "100")
widgets.append(bar_disk)
# UsageBar prints its raw value with a "%" sign, so feed it the
# percent-of-1000-KB/s-max, with maximum 100, to keep text + fill true.
bar_net = create("XUsageBar", "bar_net", 408, 660, 600, 44)
bar_net.set_prop("label", "Network KB/s")
bar_net.set_prop("maximum", "100")
widgets.append(bar_net)
return widgets
def _push(widgets):
by_name = {w.name: w for w in widgets}
by_name["badge"].refresh_load()
for name, key in (("cpu", "cpu"), ("mem", "mem"),
("net", "net"), ("disk", "disk")):
w = by_name[name]
w.push(DATA[key])
w.set_value(DATA[key])
by_name["donut_cpu"].set_value(DATA["cpu"])
by_name["donut_disk"].set_value(DATA["disk"])
by_name["bar_mem"].set_value(DATA["mem"])
by_name["bar_disk"].set_value(DATA["disk"])
by_name["bar_net"].set_value(DATA["net"] / 10.0)
def _tick():
sample()
_push(_WIDGETS)
if _AREA:
_AREA[0].queue_draw()
return True
def _on_draw(area, cr):
bg = parse_color(_BACKGROUND, 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 _on_key_press(window, event):
key = Gdk.keyval_name(event.keyval)
if key in ("Escape", "q", "Q"):
Gtk.main_quit()
return True
return False
def main():
window = Gtk.Window(title="System Overview - monitor")
window.set_default_size(1024, 768)
window.connect("destroy", Gtk.main_quit)
window.connect("key-press-event", _on_key_press)
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)
sample()
_push(_WIDGETS)
GLib.timeout_add(500, _tick)
window.show_all()
Gtk.main()
return 0
if __name__ == "__main__":
sys.exit(main())
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB