Compare commits

8 changed files with 297 additions and 235 deletions

No files matched your search

@@ -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

@@ -1,32 +0,0 @@
# Temperature Monitor — monitor (Python)
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 deterministic demo data is dropped at startup with
`MonitorWidget.clear()`.
## Run
```sh
PYTHONPATH=. python3 examples/monitor_temperature_monitor/main.py
```
Esc, `q`, or closing the window quits.
## Source
- App: `examples/monitor_temperature_monitor/main.py`
- Widget: `lightgui/xframe/monitor.py`
- Repo: https://github.com/cnmcdee/lightgui_python
@@ -1,168 +0,0 @@
#!/usr/bin/env python3
"""Temperature Monitor - monitor (Python).
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 deterministic demo
data 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 with:
PYTHONPATH=/root/monitor-wt/temperature-monitor/lightgui_python python3 \\
examples/monitor_temperature_monitor/main.py
(or from the repo root with PYTHONPATH=. )
"""
import glob
import os
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
_TITLE = "Temperature Monitor - monitor"
_DESIGN_SIZE = (1024, 768)
_BACKGROUND = ""
_WIDGETS = []
_AREA = []
_HAD_ZONES = [False]
_NO_ZONES_TITLE = "Temperature history -- no thermal zones found"
def _read_first_line(path):
try:
with open(path) as f:
return f.readline().strip()
except (OSError, ValueError):
return ""
def _read_temp_c(path):
try:
return int(_read_first_line(path)) / 1000.0
except (OSError, ValueError):
return None
def _scan_zones():
"""All temperature inputs the kernel exposes, thermal zones first.
Each zone is (name, temp-path). Millidegree files that do not
parse are skipped, so a half-populated sysfs still yields the
zones that do read.
"""
zones = []
for temp_path in sorted(glob.glob("/sys/class/thermal/thermal_zone*/temp")):
if _read_temp_c(temp_path) is None:
continue
base = os.path.dirname(temp_path)
label = _read_first_line(os.path.join(base, "type"))
zones.append((label or os.path.basename(base), temp_path))
for temp_path in sorted(glob.glob("/sys/class/hwmon/hwmon*/temp*_input")):
if _read_temp_c(temp_path) is None:
continue
base = os.path.dirname(temp_path)
chip = _read_first_line(os.path.join(base, "name")) or \
os.path.basename(base)
stem = os.path.basename(temp_path)[:-len("_input")]
label = _read_first_line(os.path.join(base, stem + "_label"))
zones.append((("%s %s" % (chip, label)) if label else chip,
temp_path))
return zones
def _build_widgets():
"""Create every placed widget with its props."""
temp = create("XTempHistory", "TempHistory_001", 16, 16, 992, 736)
temp.set_prop("label", _NO_ZONES_TITLE)
temp.set_prop("threshold", "80")
# Drop the deterministic demo data: with no live source the
# honest state is an empty graph, not a fake warm-up curve.
temp.clear()
return [temp]
def _apply_scan():
"""Re-scan sysfs and feed the first zone's live reading (if any)."""
(temp,) = _WIDGETS
zones = _scan_zones()
if not zones:
if _HAD_ZONES[0]:
_HAD_ZONES[0] = False
temp.clear()
temp.set_prop("label", _NO_ZONES_TITLE)
return
name, path = zones[0]
if not _HAD_ZONES[0]:
_HAD_ZONES[0] = True
temp.set_prop("label", "Temperature history -- %s" % name)
value = _read_temp_c(path)
if value is not None:
temp.push(value)
def _tick():
"""2 s tick: re-scan sysfs, then redraw."""
_apply_scan()
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):
if event.keyval in (Gdk.KEY_Escape, Gdk.KEY_q):
Gtk.main_quit()
return True
return False
def main():
window = Gtk.Window(title=_TITLE)
window.set_default_size(*_DESIGN_SIZE)
window.set_resizable(False)
window.connect("destroy", Gtk.main_quit)
window.connect("key-press-event", _on_key_press)
area = Gtk.DrawingArea()
area.set_hexpand(True)
area.set_vexpand(True)
area.connect("draw", _on_draw)
window.add(area)
_WIDGETS.extend(_build_widgets())
_AREA.append(area)
# First scan before the first paint, so the title already tells
# the truth on screen one.
_apply_scan()
GLib.timeout_add(2000, _tick)
window.show_all()
Gtk.main()
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

+4 -22
View File
@@ -501,19 +501,6 @@ class MonitorWidget(Widget):
return list(self._series[series])
return list(self._plot_series()[series])
def clear(self):
"""Drop every sample from the 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 deterministic demo series.
Later push() calls fill the kept slots again as usual."""
if self._series is not None:
self._series = [[] for _ in self._series]
else:
self._series = [[]]
self._peak = 0.0
self._mark_dirty()
def series_count(self):
"""Number of series this widget plots."""
if self._series is not None:
@@ -996,15 +983,10 @@ class MonitorWidget(Widget):
threshold = _prop_float(self, "threshold", 80.0)
values = self._single_series(58.0, 24.0, 0.0, 120.0)
lo, hi = 0.0, max(100.0, threshold + 20.0)
if values:
cur = values[-1]
cur_rgb = _RED if cur > threshold else _TEXT
_wtext(cr, self, "%.1f C" % cur, self.width - 8, 15, size=14,
rgb=cur_rgb, align="right", bold=True)
else:
# Honest empty state: no samples, no reading to show.
_wtext(cr, self, "no data", self.width - 8, 15, size=14,
rgb=_DIM, align="right", bold=True)
cur = values[-1] if values else 0.0
cur_rgb = _RED if cur > threshold else _TEXT
_wtext(cr, self, "%.1f C" % cur, self.width - 8, 15, size=14,
rgb=cur_rgb, align="right", bold=True)
plot_x, plot_y = 34, top + 2
plot_w = max(1, self.width - 40)
plot_h = max(1, self.height - plot_y - 20)
-13
View File
@@ -162,19 +162,6 @@ class HistoryDataTests(unittest.TestCase):
graph.push(42.0)
self.assertEqual(graph.get_series(0), [42.0])
def test_clear_drops_demo_series(self):
# clear() empties the history so a widget with no live source
# shows its honest empty state instead of the demo series.
temp = core.create("XTempHistory", "XTempHistory_001")
self.assertEqual(
len(temp._single_series(58.0, 24.0, 0.0, 120.0)), 60)
temp.clear()
self.assertEqual(temp._single_series(58.0, 24.0, 0.0, 120.0), [])
_draw(temp) # empty state draws without error
temp.push(42.0)
self.assertEqual(
temp._single_series(58.0, 24.0, 0.0, 120.0), [42.0])
def test_push_trims_to_window(self):
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
graph.set_prop("window", 5)