pyqt6Dashboard/qtDash/monitor_data.py

74 lines
2.4 KiB
Python

# monitor_data.py
import psutil
import subprocess
import GPUtil
import time
def format_uptime():
uptime_seconds = time.time() - psutil.boot_time()
days = int(uptime_seconds // 86400)
hours = int((uptime_seconds % 86400) // 3600)
minutes = int((uptime_seconds % 3600) // 60)
return f"{days}d {hours:02d}h {minutes:02d}m" if days > 0 else f"{hours:02d}h {minutes:02d}m"
def get_cpu_temp():
try:
output = subprocess.check_output(['sensors'], universal_newlines=True)
for line in output.splitlines():
if "Package id 0:" in line or "Core 0:" in line:
temp_str = line.split(":")[1].strip().split("°")[0]
return f"{float(temp_str)}°C"
except Exception:
return "---"
def get_gpu_temp():
try:
gpus = GPUtil.getGPUs()
return f"{gpus[0].temperature}°C" if gpus else "---"
except Exception:
return "---"
def get_gpu_usage():
try:
gpus = GPUtil.getGPUs()
return f"{gpus[0].load * 100:.1f}%" if gpus else "---"
except Exception:
return "---"
def get_net_speed(interface='enp0s31f6', interval=1):
try:
start = psutil.net_io_counters(pernic=True)[interface]
time.sleep(interval)
end = psutil.net_io_counters(pernic=True)[interface]
download = (end.bytes_recv - start.bytes_recv) / 1024 / interval
upload = (end.bytes_sent - start.bytes_sent) / 1024 / interval
return f"{download:.2f} KB/s", f"{upload:.2f} KB/s"
except Exception:
return "---", "---"
def check_alive(ip="192.168.0.101"):
try:
result = subprocess.run(["ping", "-c", "1", "-W", "1", ip],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return "True" if result.returncode == 0 else "False"
except Exception:
return "---"
def get_monitor_data():
download, upload = get_net_speed()
return {
"cpu": f"{psutil.cpu_percent()}%",
"ram": f"{psutil.virtual_memory().percent}%",
"disk": f"{psutil.disk_usage('/').percent}%",
"uptime": format_uptime(),
"cpu_temp": get_cpu_temp(),
"gpu_temp": get_gpu_temp(),
"gpu_usage": get_gpu_usage(),
"swap": f"{psutil.swap_memory().percent}%",
"download": download,
"upload": upload,
"alive": check_alive(),
"processes": str(len(psutil.pids()))
}