-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem_bridge.py
More file actions
432 lines (362 loc) · 13.3 KB
/
Copy pathsystem_bridge.py
File metadata and controls
432 lines (362 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
"""
system_bridge.py - raccoglie statistiche di sistema (CPU, RAM, GPU, disco, rete,
batteria) e le invia all'Arduino multi-dashboard via seriale.
Usage:
python system_bridge.py # auto-detect porta, 2 Hz
python system_bridge.py --port COM5
python system_bridge.py --rate 1.0
python system_bridge.py --dry-run # stampa frame su stdout
python system_bridge.py --list-ports
Frame: tag-value pairs separati da ';', terminato \\n
CU:75;CT:65;CF:3600;RU:60;RT:158;RR:320;GU:45;GT:72;GV:81;GA:163;
DR:1024;DW:512;DD:80;NI:2048;NO:512;BP:78;BR:165;BC:0
"""
from __future__ import annotations
import argparse
import os
import signal
import sys
import time
from typing import Optional
import psutil
import serial
from serial.tools import list_ports
BAUD = 115200
# -- CoreTemp shared memory (sorgente preferita per temp + freq real-time) --
try:
import coretemp_shared as _coretemp
except Exception:
_coretemp = None
# -- PDH performance counter Windows (fallback per freq real-time) ----------
# Counter: \Processor Information(_Total)\% Processor Performance
# Restituisce la % rispetto alla frequenza base (es. 145 = boost 1.45x).
_PDH_AVAILABLE = False
_pdh_query = None
_pdh_counter = None
_BASE_MHZ = 0
if os.name == "nt":
try:
import ctypes
from ctypes import wintypes
class _PDH_FMT_COUNTERVALUE(ctypes.Structure):
_fields_ = [
("CStatus", wintypes.DWORD),
("doubleValue", ctypes.c_double),
]
_pdh = ctypes.windll.pdh
PDH_FMT_DOUBLE = 0x00000200
_pdh_query = wintypes.HANDLE()
if _pdh.PdhOpenQueryW(None, 0, ctypes.byref(_pdh_query)) == 0:
_pdh_counter = wintypes.HANDLE()
path = "\\Processor Information(_Total)\\% Processor Performance"
if _pdh.PdhAddCounterW(_pdh_query, path, 0,
ctypes.byref(_pdh_counter)) == 0:
_pdh.PdhCollectQueryData(_pdh_query) # primo sample
_PDH_AVAILABLE = True
# frequenza base in MHz (per moltiplicare la %)
f = psutil.cpu_freq()
if f:
_BASE_MHZ = int(f.max if f.max else f.current)
except Exception:
_PDH_AVAILABLE = False
def _pdh_freq_mhz() -> int:
if not _PDH_AVAILABLE or _BASE_MHZ <= 0:
return -1
try:
_pdh.PdhCollectQueryData(_pdh_query)
val = _PDH_FMT_COUNTERVALUE()
rc = _pdh.PdhGetFormattedCounterValue(
_pdh_counter, PDH_FMT_DOUBLE, None, ctypes.byref(val))
if rc != 0:
return -1
return int(_BASE_MHZ * val.doubleValue / 100.0)
except Exception:
return -1
def _current_cpu_mhz() -> int:
"""Frequenza istantanea. Priorità: CoreTemp SM → PDH counter → psutil base."""
if _coretemp is not None:
r = _coretemp.read()
if r and r.get("cpu_speed_mhz", 0) > 0:
return int(r["cpu_speed_mhz"])
f = _pdh_freq_mhz()
if f > 0:
return f
fr = psutil.cpu_freq()
return int(fr.current) if fr else -1
def _current_cpu_temp() -> int:
"""Temperatura CPU. Priorità: CoreTemp SM → psutil → -1."""
if _coretemp is not None:
r = _coretemp.read()
if r and r.get("cpu_temp_c", -1) >= 0:
return int(r["cpu_temp_c"])
try:
sensors = psutil.sensors_temperatures
except AttributeError:
return -1
try:
temps = sensors()
if not temps:
return -1
for key in ("coretemp", "k10temp", "cpu_thermal", "cpu-thermal"):
if key in temps and temps[key]:
return int(temps[key][0].current)
for entries in temps.values():
if entries:
return int(entries[0].current)
except Exception:
pass
return -1
# -- catena fallback GPU ----------------------------------------------------
_GPU_BACKEND = "none"
_pynvml = None
_GPUtil = None
try:
import pynvml as _pynvml
_pynvml.nvmlInit()
if _pynvml.nvmlDeviceGetCount() > 0:
_GPU_BACKEND = "nvml"
else:
_pynvml = None
except Exception:
_pynvml = None
if _GPU_BACKEND == "none":
try:
import GPUtil as _GPUtil
if _GPUtil.getGPUs():
_GPU_BACKEND = "gputil"
else:
_GPUtil = None
except Exception:
_GPUtil = None
# -- EMA smoothing per dischi/rete ------------------------------------------
EMA_ALPHA = 0.4
_ema: dict[str, float] = {}
def _smooth(key: str, value: float) -> int:
if key not in _ema:
_ema[key] = value
else:
_ema[key] = EMA_ALPHA * value + (1.0 - EMA_ALPHA) * _ema[key]
return int(_ema[key])
# -- serial port helpers (pattern riusato da acc_bridge.py) -----------------
def find_arduino_port() -> Optional[str]:
candidates = list(list_ports.comports())
keywords = ("arduino", "ch340", "ch341", "usb-serial", "usb serial", "wch")
for p in candidates:
desc = (p.description or "").lower()
if any(k in desc for k in keywords):
return p.device
if len(candidates) == 1:
return candidates[0].device
return None
def open_serial(port: str) -> serial.Serial:
return serial.Serial(port, BAUD, timeout=0, write_timeout=0.5)
# -- collectors -------------------------------------------------------------
def collect_cpu() -> dict:
pct = int(psutil.cpu_percent(interval=None))
return {
"CU": pct,
"CT": _current_cpu_temp(),
"CF": _current_cpu_mhz(),
}
_GIB = 1024 ** 3 # GiB binari (Windows mostra così)
def collect_ram() -> dict:
vm = psutil.virtual_memory()
# decimi di GiB binari: byte * 10 / 1024^3
used_dgb = int(vm.used * 10 / _GIB)
total_dgb = int(vm.total * 10 / _GIB)
return {"RU": int(vm.percent), "RT": used_dgb, "RR": total_dgb}
def collect_gpu() -> dict:
if _GPU_BACKEND == "nvml":
try:
h = _pynvml.nvmlDeviceGetHandleByIndex(0)
util = _pynvml.nvmlDeviceGetUtilizationRates(h)
mem = _pynvml.nvmlDeviceGetMemoryInfo(h)
try:
tmp = int(_pynvml.nvmlDeviceGetTemperature(h, _pynvml.NVML_TEMPERATURE_GPU))
except Exception:
tmp = -1
return {
"GU": int(util.gpu),
"GT": tmp,
"GV": int(mem.used * 10 / (1024**3)),
"GA": int(mem.total * 10 / (1024**3)),
}
except Exception:
return {"GU": -1, "GT": -1, "GV": -1, "GA": -1}
if _GPU_BACKEND == "gputil":
try:
gpus = _GPUtil.getGPUs()
if not gpus:
return {"GU": -1, "GT": -1, "GV": -1, "GA": -1}
g = gpus[0]
tmp = -1
try: tmp = int(g.temperature)
except Exception: pass
return {
"GU": int(g.load * 100),
"GT": tmp,
# memoryUsed/Total in MB → decimi di GB: MB * 10 / 1024
"GV": int(g.memoryUsed * 10 / 1024),
"GA": int(g.memoryTotal * 10 / 1024),
}
except Exception:
return {"GU": -1, "GT": -1, "GV": -1, "GA": -1}
return {"GU": -1, "GT": -1, "GV": -1, "GA": -1}
_DISK_PATH = "C:\\" if os.name == "nt" else "/"
_last_disk = None
_last_disk_t = None
def collect_disk() -> dict:
global _last_disk, _last_disk_t
now = time.monotonic()
cur = psutil.disk_io_counters()
try:
usage_pct = int(psutil.disk_usage(_DISK_PATH).percent)
except Exception:
usage_pct = 0
if cur is None:
return {"DR": 0, "DW": 0, "DD": usage_pct}
if _last_disk is None or _last_disk_t is None:
_last_disk, _last_disk_t = cur, now
return {"DR": 0, "DW": 0, "DD": usage_pct}
dt = max(now - _last_disk_t, 0.001)
rd = max(0.0, (cur.read_bytes - _last_disk.read_bytes) / dt / 1024.0)
wr = max(0.0, (cur.write_bytes - _last_disk.write_bytes) / dt / 1024.0)
_last_disk, _last_disk_t = cur, now
return {"DR": _smooth("DR", rd), "DW": _smooth("DW", wr), "DD": usage_pct}
_last_net = None
_last_net_t = None
def collect_net() -> dict:
global _last_net, _last_net_t
now = time.monotonic()
cur = psutil.net_io_counters()
if cur is None:
return {"NI": 0, "NO": 0}
if _last_net is None or _last_net_t is None:
_last_net, _last_net_t = cur, now
return {"NI": 0, "NO": 0}
dt = max(now - _last_net_t, 0.001)
ni = max(0.0, (cur.bytes_recv - _last_net.bytes_recv) / dt / 1024.0)
no = max(0.0, (cur.bytes_sent - _last_net.bytes_sent) / dt / 1024.0)
_last_net, _last_net_t = cur, now
return {"NI": _smooth("NI", ni), "NO": _smooth("NO", no)}
def collect_battery() -> dict:
try:
b = psutil.sensors_battery()
except Exception:
b = None
if b is None:
return {"BP": -1, "BR": -1, "BC": 0}
pct = int(b.percent)
if b.power_plugged:
rem = -1
else:
secs = b.secsleft
if secs in (psutil.POWER_TIME_UNLIMITED, psutil.POWER_TIME_UNKNOWN) or secs < 0:
rem = -1
else:
rem = secs // 60
return {"BP": pct, "BR": rem, "BC": 1 if b.power_plugged else 0}
# -- frame builder ----------------------------------------------------------
TAG_ORDER = ["CU","CT","CF","RU","RT","RR",
"GU","GT","GV","GA",
"DR","DW","DD","NI","NO",
"BP","BR","BC"]
def build_frame() -> str:
data = {}
data.update(collect_cpu())
data.update(collect_ram())
data.update(collect_gpu())
data.update(collect_disk())
data.update(collect_net())
data.update(collect_battery())
parts = [f"{t}:{data[t]}" for t in TAG_ORDER if t in data]
return ";".join(parts) + "\n"
# -- main loop --------------------------------------------------------------
def run(port: Optional[str], rate_hz: float, dry_run: bool) -> int:
period = 1.0 / max(0.1, rate_hz)
ser: Optional[serial.Serial] = None
stop = {"flag": False}
def _sig(_a, _b): stop["flag"] = True
signal.signal(signal.SIGINT, _sig)
if hasattr(signal, "SIGTERM"):
signal.signal(signal.SIGTERM, _sig)
# priming cpu_percent
psutil.cpu_percent(interval=0.1)
# diagnostica sorgenti
ct_status = "ON" if (_coretemp and _coretemp.read()) else "off"
pdh_status = "ON" if _PDH_AVAILABLE else "off"
print(f"[bridge] starting (rate={rate_hz}Hz, dry_run={dry_run}, "
f"gpu={_GPU_BACKEND}, coretemp={ct_status}, pdh={pdh_status})")
last_log = 0.0
frames = 0
while not stop["flag"]:
if not dry_run and ser is None:
chosen = port or find_arduino_port()
if not chosen:
print("[waiting for Arduino COM port]", end="\r", flush=True)
time.sleep(1.0)
continue
try:
ser = open_serial(chosen)
print(f"\n[bridge] serial open on {chosen} @ {BAUD}")
except (serial.SerialException, OSError) as e:
print(f"[bridge] serial open failed ({e}); retry in 1s")
time.sleep(1.0)
continue
try:
frame = build_frame()
except Exception as e:
print(f"\n[bridge] collector error ({e})")
time.sleep(0.5)
continue
if dry_run:
sys.stdout.write(frame)
sys.stdout.flush()
else:
try:
ser.write(frame.encode("ascii"))
except (serial.SerialException, OSError) as e:
print(f"\n[bridge] write failed ({e}); reopening")
try: ser.close()
except Exception: pass
ser = None
time.sleep(0.5)
continue
frames += 1
now = time.time()
if now - last_log >= 2.0:
# estrai velocemente CPU/RAM/GPU dal frame appena costruito
short = frame.strip().split(";")
kv = {p.split(":")[0]: p.split(":")[1] for p in short if ":" in p}
print(f"[bridge] {frames} frames "
f"CPU={kv.get('CU','?'):>3}% "
f"RAM={kv.get('RU','?'):>3}% "
f"GPU={kv.get('GU','?'):>3}% "
f"NETin={kv.get('NI','?')}KB/s",
end="\r", flush=True)
last_log = now
time.sleep(period)
print("\n[bridge] shutting down")
if ser is not None:
try: ser.flush(); ser.close()
except Exception: pass
if _pynvml is not None:
try: _pynvml.nvmlShutdown()
except Exception: pass
return 0
def main() -> int:
ap = argparse.ArgumentParser(description="System monitor → Arduino bridge")
ap.add_argument("--port", help="serial port (e.g. COM5). Auto-detect if omitted.")
ap.add_argument("--rate", type=float, default=2.0, help="frames per second (default 2.0)")
ap.add_argument("--dry-run", action="store_true",
help="print frames to stdout instead of opening the serial port")
ap.add_argument("--list-ports", action="store_true",
help="list available COM ports and exit")
args = ap.parse_args()
if args.list_ports:
for p in list_ports.comports():
print(f"{p.device:10s} {p.description}")
return 0
return run(args.port, args.rate, args.dry_run)
if __name__ == "__main__":
sys.exit(main())