# deck-it - stats module # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """System stats: CPU, memory, GPU (Intel xe), network, uptime, pending updates. The Arc driver exposes temperature and fan through hwmon and no VRAM capacity; VRAM in use and engine busy cycles come from the DRM fdinfo scan, as quickshell's perf panel does. """ import json import os import platform import re import shlex import socket import subprocess import threading import time from pathlib import Path from ..module import Module UNITS = {"": 1, "K": 1024, "M": 1024 ** 2, "G": 1024 ** 3, "T": 1024 ** 4} def _read(path, default=""): try: return Path(path).read_text().strip() except OSError: return default def _parse_bytes(value): if isinstance(value, int): return value m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([KMGT]?)(?:i?B)?", str(value).strip(), re.I) if not m: return None return int(float(m[1]) * UNITS[m[2].upper()]) ENGINES = ("rcs", "ccs") # render (games) and compute (local LLMs) def _intel_fdinfo(root=Path("/proc")): """One pass over xe clients, each client id counted once. Returns (VRAM bytes, {engine: busy cycles summed}, {engine: GPU cycles}). """ seen, total, busy, clock = set(), 0, dict.fromkeys(ENGINES, 0), {} for fdinfo in root.glob("[0-9]*/fdinfo/*"): try: text = fdinfo.read_text() except OSError: continue fields = {} for line in text.splitlines(): key, sep, value = line.partition(":") if sep and key.startswith("drm-"): fields[key] = value.strip() client = fields.get("drm-client-id") if fields.get("drm-driver") != "xe" or not client or client in seen: continue seen.add(client) for e in ENGINES: if fields.get(f"drm-cycles-{e}", "").isdigit(): busy[e] += int(fields[f"drm-cycles-{e}"]) clock[e] = max(clock.get(e, 0), int(fields.get(f"drm-total-cycles-{e}", "0") or 0)) m = re.match(r"(\d+)\s*([KMGT]?)(?:i?B)?", fields.get("drm-resident-vram0", "")) if m: total += int(m[1]) * UNITS[m[2].upper()] return total, busy, clock def _gpu_util(before, after): """Busiest engine's percentage between two _intel_fdinfo samples, or None.""" if not before: return None pcts = [] for e in ENGINES: dt = after[2].get(e, 0) - before[2].get(e, 0) if dt > 0: # ponytail: a client exiting mid-sample takes its cycles with it, # so the delta can dip below zero; clamp rather than track clients. pcts.append(min(100, max(0, 100 * (after[1][e] - before[1][e]) / dt))) return round(max(pcts)) if pcts else None def _cpu_sensor(hw): names = {_read(h / "name"): h for h in Path("/sys/class/hwmon").glob("hwmon*")} want = hw.get("cpu_sensor", "auto") for name in ([want] if want != "auto" else ["k10temp", "zenpower", "coretemp", "cpu_thermal", "acpitz"]): if name in names: return names[name] / "temp1_input" return None def _battery(hw): want = hw.get("battery", "auto") if want != "auto": return Path("/sys/class/power_supply") / want for p in sorted(Path("/sys/class/power_supply").glob("*")): if _read(p / "type") == "Battery": return p return None def _cpu_name(cpuinfo): """'AMD Ryzen 7 9700X 8-Core Processor' -> 'AMD Ryzen 7 9700X'.""" for line in cpuinfo.splitlines(): if line.startswith("model name"): name = re.sub(r"\((R|TM)\)|\bCPU\b|@.*|\d+-Core|Processor", "", line.partition(":")[2]) return " ".join(name.split()) or None return None def _os(text): """/etc/os-release -> {"id", "name", "codename"}.""" f = {k: v.strip().strip('"') for k, _, v in (line.partition("=") for line in text.splitlines()) if v} name = " ".join(filter(None, (f.get("NAME"), f.get("VERSION_ID")))) return {"id": f.get("ID", "linux"), "name": name or "Linux", "codename": f.get("VERSION_CODENAME", "")} def _gpu_name(lspci): """lspci -mm's line -> 'Intel Arc B580': the vendor's first word, then the marketing name in brackets, else the whole device name.""" try: f = shlex.split(lspci) except ValueError: return None if len(f) < 4: return None m = re.search(r"\[(.+?)\]", f[3]) return f"{f[2].split()[0]} {m[1] if m else f[3]}" def _gpu(hw): if hw.get("gpu", "auto") == "none": return None for name in Path("/sys/class/hwmon").glob("hwmon*/name"): if _read(name) == "xe": slot = (name.parent / "device").resolve().name try: out = subprocess.run(["lspci", "-mm", "-s", slot], capture_output=True, text=True, timeout=2).stdout except (OSError, subprocess.TimeoutExpired): out = "" return {"hwmon": name.parent, "name": _gpu_name(out) or "GPU"} return None def _net_iface(hw): if hw.get("net", "auto") != "auto": return hw["net"] for line in _read("/proc/net/route").splitlines()[1:]: f = line.split() if f[1] == "00000000": return f[0] return None def _to_install(doc): """updatesctl's JSON -> what keystone's tile counts "to install".""" sw = doc.get("slackware", {}) return sum(len(sw.get(k, [])) for k in ("upgrade", "new", "removed")) + len(doc.get("upgrade", [])) def make(cfg: dict) -> Module: hw = cfg.get("hardware", {}) updatesctl = os.path.expanduser(cfg.get("dashboard", {}).get("updates", "")) upd = {"n": None, "t": 0, "busy": False} def read_updates(): try: out = subprocess.run([updatesctl], capture_output=True, text=True, timeout=30).stdout upd["n"] = _to_install(json.loads(out)) except (OSError, subprocess.TimeoutExpired, ValueError): pass upd.update(t=time.monotonic(), busy=False) def updates(): # ponytail: re-read every 5 min in a thread, so the NAS reads never stall the 1 s poll if updatesctl and not upd["busy"] and (not upd["t"] or time.monotonic() - upd["t"] > 300): upd["busy"] = True threading.Thread(target=read_updates, daemon=True).start() return upd["n"] cpu_sensor = _cpu_sensor(hw) battery = _battery(hw) gpu = _gpu(hw) cpu_name = _cpu_name(_read("/proc/cpuinfo")) or "CPU" os_info = {**_os(_read("/etc/os-release")), "kernel": platform.release()} gpu_total = _parse_bytes(hw.get("gpu_mem_total", "")) if gpu else None prev = {"cpu": None, "net": None, "t": None, "gpu_t": 0, "gpu_v": None, "gpu_s": None} def cpu_percent(): fields = list(map(int, _read("/proc/stat").splitlines()[0].split()[1:])) idle, total = fields[3] + fields[4], sum(fields) last, prev["cpu"] = prev["cpu"], (idle, total) if not last or total == last[1]: return 0 return round(100 * (1 - (idle - last[0]) / (total - last[1]))) def net_rates(now): iface = _net_iface(hw) for line in _read("/proc/net/dev").splitlines(): if iface and line.strip().startswith(iface + ":"): v = line.split(":")[1].split() cur = (iface, int(v[0]), int(v[8])) break else: return 0, 0 last, lt = prev["net"], prev["t"] prev["net"], prev["t"] = cur, now if not last or last[0] != iface or now == lt: return 0, 0 return round((cur[1] - last[1]) / (now - lt)), round((cur[2] - last[2]) / (now - lt)) def read_gpu(): if not gpu: return None # The fdinfo scan touches every process, so keep it to once every 2 s. if time.time() - prev["gpu_t"] < 2: return prev["gpu_v"] sample = _intel_fdinfo() temp = _read(gpu["hwmon"] / "temp2_input") fan = _read(gpu["hwmon"] / "fan1_input") v = { "name": gpu["name"], "util": _gpu_util(prev["gpu_s"], sample), "temp": round(int(temp) / 1000) if temp else None, "fan": int(fan) if fan else None, "memUsed": sample[0], "memTotal": gpu_total, } prev.update(gpu_t=time.time(), gpu_v=v, gpu_s=sample) return v def state(): now = time.monotonic() mem = {line.split(":")[0]: int(line.split()[1]) for line in _read("/proc/meminfo").splitlines()} down, up = net_rates(now) t = _read(cpu_sensor) if cpu_sensor else "" return { "host": socket.gethostname(), "os": os_info, "uptime": int(float(_read("/proc/uptime", "0").split()[0])), "cpu": cpu_percent(), "cpuName": cpu_name, "cpuTemp": round(int(t) / 1000) if t else None, "memUsed": mem["MemTotal"] - mem["MemAvailable"], "memTotal": mem["MemTotal"], "gpu": read_gpu(), "battery": {"level": int(_read(battery / "capacity", "0")), "status": _read(battery / "status")} if battery else None, "net": {"down": down, "up": up}, "updates": updates(), } return Module(name="stats", title="System", state=state)