dashboard/app/collect/cpu.py

64 lines
1.5 KiB
Python

import glob
import psutil
_temp_path: str | None = None
_temp_checked = False
def _read(path: str) -> str | None:
try:
with open(path) as f:
return f.read().strip()
except OSError:
return None
def _find_temp_path() -> str | None:
for hwmon in sorted(glob.glob("/sys/class/hwmon/hwmon*")):
name = (_read(f"{hwmon}/name") or "").lower()
if name in ("k10temp", "coretemp", "cpu_thermal"):
for t in sorted(glob.glob(f"{hwmon}/temp*_input")):
return t
return None
for zone in sorted(glob.glob("/sys/class/thermal/thermal_zone*")):
if (_read(f"{zone}/type") or "").lower() == "acpitz":
return f"{zone}/temp"
return None
def temp() -> float | None:
global _temp_path, _temp_checked
if not _temp_checked:
_temp_checked = True
_temp_path = _find_temp_path()
if _temp_path is None:
return None
v = _read(_temp_path)
if not v:
return None
try:
n = float(v)
except ValueError:
return None
return round(n / 1000.0, 1)
def prime() -> None:
_ = psutil.cpu_percent(None)
def core_count() -> int:
return psutil.cpu_count(logical=True) or 1
def sample() -> dict[str, float]:
out: dict[str, float] = {"cpu": psutil.cpu_percent(None)}
t = temp()
if t is not None:
out["cpu_temp"] = t
l1, l5, l15 = psutil.getloadavg()
out["load1"] = l1
out["load5"] = l5
out["load15"] = l15
return out