-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2670 lines (2398 loc) · 116 KB
/
Copy pathapp.py
File metadata and controls
2670 lines (2398 loc) · 116 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ctypes
import ctypes.wintypes
import csv
import json
import logging
import math
import os
import socket
import shutil
import tempfile
import subprocess
import sys
import threading
import time
import tkinter as tk
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from tkinter import ttk
from dataclasses import asdict, dataclass
from collections import deque
from pathlib import Path
from typing import Dict, Optional
import psutil
try:
import winreg
except Exception:
winreg = None
try:
import pythonnet # type: ignore
pythonnet.load()
import clr # type: ignore
if not hasattr(clr, "AddReference"):
clr = None
except Exception:
clr = None
APP_NAME = "Hardware Monitoring"
AUTOSTART_VALUE_NAME = APP_NAME
LEGACY_AUTOSTART_VALUE_NAME = "HardwareMonitorMini"
def runtime_data_dir() -> Path:
root = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA")
return Path(root) / APP_NAME if root else Path.home() / "AppData" / "Local" / APP_NAME
def setup_logger(app_dir: Path) -> logging.Logger:
logger = logging.getLogger("hardware_monitor")
if logger.handlers:
return logger
logger.setLevel(logging.INFO)
log_path = app_dir / "hardware_monitor.log"
try:
app_dir.mkdir(parents=True, exist_ok=True)
handler = logging.FileHandler(log_path, encoding="utf-8")
except Exception:
fallback = Path(tempfile.gettempdir()) / "hardware_monitor.log"
handler = logging.FileHandler(fallback, encoding="utf-8")
log_path = fallback
formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("Log file path: %s", str(log_path))
return logger
DEFAULT_CONFIG = {
"refresh_interval_ms": 1000,
"window_opacity": 0.96,
"always_on_top": False,
"minimize_to_tray": True,
"theme": "深色蓝",
"ui_language": "zh",
"font_scale": 1.0,
"display_mode": "标准",
"compact_mode": False,
"show_group_titles": True,
"fps_enabled": False,
"fps_target_process": "",
"lan_dashboard_enabled": False,
"lan_dashboard_port": 8765,
"show_cpu_usage": True,
"show_memory_usage": True,
"show_gpu_usage": True,
"show_vram_usage": True,
"show_cpu_temperature": True,
"show_gpu_temperature": True,
"show_cpu_fan": False,
"show_gpu_fan": False,
"show_cpu_power": False,
"show_gpu_power": False,
"show_cpu_freq": True,
"show_gpu_freq": True,
"show_vram_freq": False,
"show_memory_freq": False,
"show_ssd_temperature": False,
"show_network_latency": False,
"show_disk_speed": True,
"show_network_speed": True,
"show_disk_read": False,
"show_disk_write": False,
"show_net_up": False,
"show_net_down": False,
"show_battery": False,
"show_fps": True,
"show_fps_low_1": True,
"show_target_process": True,
"metric_order": [],
"autostart": False,
"close_action": "exit",
"log_level": "INFO",
}
THEMES = {
"深色蓝": {"bg": "#0f1115", "panel": "#151b28", "border": "#2b3550", "text": "#f5f7fa", "sub": "#cfd6e6", "hint": "#8190ac", "accent": "#4f8cff"},
"苹果浅色": {"bg": "#f5f7fb", "panel": "#ffffff", "border": "#d5dcea", "text": "#1f2937", "sub": "#475569", "hint": "#64748b", "accent": "#2f7cff"},
"石墨灰": {"bg": "#171717", "panel": "#242424", "border": "#3a3a3a", "text": "#f1f5f9", "sub": "#d4d4d8", "hint": "#a1a1aa", "accent": "#6ea8fe"},
"炫彩红": {"bg": "#1a0a0a", "panel": "#2a1010", "border": "#4a2020", "text": "#fff0f0", "sub": "#e8c0c0", "hint": "#a87070", "accent": "#ff4040"},
"极光绿": {"bg": "#0a1a0f", "panel": "#102a18", "border": "#204a30", "text": "#f0fff5", "sub": "#c0e8d0", "hint": "#70a880", "accent": "#40ff80"},
}
THEME_EN_LABEL = {
"深色蓝": "Deep Blue",
"苹果浅色": "Light",
"石墨灰": "Graphite",
"炫彩红": "Vibrant Red",
"极光绿": "Aurora Green",
}
METRIC_LAYOUT = [
("游戏", "fps", "FPS", "show_fps"),
("游戏", "fps_low_1", "1% Low", "show_fps_low_1"),
("游戏", "target_process", "目标进程", "show_target_process"),
("系统", "cpu_usage", "CPU", "show_cpu_usage"),
("系统", "memory_usage", "内存", "show_memory_usage"),
("显卡", "gpu_usage", "GPU", "show_gpu_usage"),
("显卡", "gpu_memory", "显存", "show_vram_usage"),
("温度与功耗", "cpu_temp", "CPU 温度", "show_cpu_temperature"),
("温度与功耗", "gpu_temp", "GPU 温度", "show_gpu_temperature"),
("温度与功耗", "cpu_fan", "CPU 风扇", "show_cpu_fan"),
("温度与功耗", "gpu_fan", "GPU 风扇", "show_gpu_fan"),
("温度与功耗", "cpu_power", "CPU 功耗", "show_cpu_power"),
("温度与功耗", "gpu_power", "GPU 功耗", "show_gpu_power"),
("温度与功耗", "ssd_temp", "SSD 温度", "show_ssd_temperature"),
("频率", "cpu_freq", "CPU 频率", "show_cpu_freq"),
("频率", "gpu_clock", "GPU 频率", "show_gpu_freq"),
("频率", "vram_freq", "显存频率", "show_vram_freq"),
("频率", "memory_freq", "内存频率", "show_memory_freq"),
("系统状态", "disk_speed", "磁盘", "show_disk_speed"),
("系统状态", "disk_read", "磁盘读取", "show_disk_read"),
("系统状态", "disk_write", "磁盘写入", "show_disk_write"),
("系统状态", "network_speed", "网络", "show_network_speed"),
("系统状态", "network_latency", "网络延迟", "show_network_latency"),
("系统状态", "network_up", "网络上传", "show_net_up"),
("系统状态", "network_down", "网络下载", "show_net_down"),
("系统状态", "battery_status", "电池", "show_battery"),
]
METRIC_MAP = {key: (group, label, cfg_key) for group, key, label, cfg_key in METRIC_LAYOUT}
DEFAULT_METRIC_ORDER = [key for _, key, _, _ in METRIC_LAYOUT]
METRIC_LABEL_EN = {
"fps": "FPS",
"fps_low_1": "1% Low",
"target_process": "Target",
"cpu_usage": "CPU",
"memory_usage": "Memory",
"gpu_usage": "GPU",
"gpu_memory": "VRAM",
"cpu_temp": "CPU Temp",
"gpu_temp": "GPU Temp",
"cpu_fan": "CPU Fan",
"gpu_fan": "GPU Fan",
"cpu_power": "CPU Power",
"gpu_power": "GPU Power",
"cpu_freq": "CPU Clock",
"gpu_clock": "GPU Clock",
"vram_freq": "VRAM Clock",
"memory_freq": "Memory Clock",
"disk_speed": "Disk",
"disk_read": "Disk Read",
"disk_write": "Disk Write",
"network_speed": "Network",
"network_latency": "Latency",
"ssd_temp": "SSD Temp",
"network_up": "Upload",
"network_down": "Download",
"battery_status": "Battery",
}
GROUP_LABEL_EN = {
"游戏": "Game",
"系统": "System",
"显卡": "GPU",
"温度与功耗": "Thermal/Power",
"频率": "Clocks",
"系统状态": "System Status",
}
@dataclass
class Metrics:
cpu_usage: str = "N/A"
cpu_freq: str = "N/A"
cpu_temp: str = "N/A"
gpu_usage: str = "N/A"
gpu_temp: str = "N/A"
cpu_fan: str = "--"
gpu_fan: str = "--"
gpu_clock: str = "N/A"
vram_freq: str = "--"
gpu_memory: str = "N/A"
memory_usage: str = "N/A"
memory_freq: str = "N/A"
cpu_power: str = "--"
gpu_power: str = "--"
disk_speed: str = "--"
disk_read: str = "--"
disk_write: str = "--"
network_speed: str = "--"
network_up: str = "--"
network_down: str = "--"
battery_status: str = "--"
fps: str = "--"
fps_low_1: str = "--"
target_process: str = "--"
ssd_temp: str = "--"
network_latency: str = "--"
temp_hint: str = ""
source_status: str = ""
class _DashboardHTTPServer(ThreadingHTTPServer):
allow_reuse_address = False
class LanDashboardService:
"""Small read-only HTTP server for a LAN dashboard."""
_PAGE = """<!doctype html><html lang=zh-CN><meta name=viewport content="width=device-width,initial-scale=1"><title>Hardware Monitoring</title><style>body{margin:0;background:#0c1018;color:#e8eef8;font:17px system-ui,sans-serif}main{max-width:760px;margin:auto;padding:16px}.status{color:#8ed0ff}.bad{color:#ff8f8f}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(145px,1fr));gap:10px}.card{background:#151d2b;border:1px solid #29364d;border-radius:9px;padding:12px}.k{color:#aebbd0;font-size:14px}.v{font-size:21px;margin-top:5px;word-break:break-word}@media(max-width:380px){body{font-size:16px}.v{font-size:19px}}</style><main><h2>Hardware Monitoring</h2><div id=s class=status>连接中…</div><p id=u>最后更新:--</p><div class=grid id=g></div><script>const fields=[['cpu_usage','CPU 使用率'],['cpu_temp','CPU 温度'],['cpu_freq','CPU 频率'],['cpu_power','CPU 功耗'],['gpu_usage','GPU 使用率'],['gpu_temp','GPU 温度'],['gpu_clock','GPU 频率'],['gpu_power','GPU 功耗'],['memory_usage','内存'],['gpu_memory','显存'],['disk_speed','磁盘活动'],['network_up','网络上传'],['network_down','网络下载'],['fps','FPS'],['fps_low_1','1% Low'],['source_status','采样状态']];const g=document.querySelector('#g');g.innerHTML=fields.map(x=>`<div class=card><div class=k>${x[1]}</div><div class=v id=${x[0]}>--</div></div>`).join('');async function tick(){try{let r=await fetch('/api/metrics',{cache:'no-store'});if(!r.ok)throw 0;let d=await r.json(),m=d.metrics;fields.forEach(x=>document.getElementById(x[0]).textContent=m[x[0]]??'--');let stale=!d.updated_at||Date.now()-Date.parse(d.updated_at)>5000;document.querySelector('#u').textContent='最后更新:'+(d.updated_at||'--');document.querySelector('#s').textContent=stale?'数据已过期':'电脑运行中';document.querySelector('#s').className=stale?'bad':'status'}catch(e){document.querySelector('#s').textContent='连接中断 / 数据已过期';document.querySelector('#s').className='bad'}}setInterval(tick,1000);tick();</script></main>"""
def __init__(self, snapshot_provider, updated_at_provider, logger: Optional[logging.Logger] = None) -> None:
self._snapshot_provider = snapshot_provider
self._updated_at_provider = updated_at_provider
self._logger = logger or logging.getLogger("hardware_monitor")
self._lock = threading.Lock()
self._server: Optional[ThreadingHTTPServer] = None
self._thread: Optional[threading.Thread] = None
self.port = 0
@staticmethod
def _safe_json_value(value):
if isinstance(value, float) and not math.isfinite(value):
return None
if isinstance(value, dict):
return {str(key): LanDashboardService._safe_json_value(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [LanDashboardService._safe_json_value(item) for item in value]
return value
@property
def is_running(self) -> bool:
with self._lock:
return self._server is not None
@property
def is_alive(self) -> bool:
with self._lock:
return bool(self._thread and self._thread.is_alive())
def start(self, port: int = 8765) -> bool:
with self._lock:
if self._server is not None:
return False
service = self
class Handler(BaseHTTPRequestHandler):
def log_message(self, _format, *_args) -> None:
return
def _send(self, code: int, body: bytes, content_type: str) -> None:
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self) -> None:
if len(self.path) > 2048:
self._send(414, b"Request URI Too Long", "text/plain; charset=utf-8")
elif self.path.split("?", 1)[0] == "/":
self._send(200, service._PAGE.encode("utf-8"), "text/html; charset=utf-8")
elif self.path.split("?", 1)[0] == "/healthz":
self._send(200, b'{"status":"ok"}', "application/json; charset=utf-8")
elif self.path.split("?", 1)[0] == "/api/metrics":
try:
payload = {"status": "ok", "updated_at": service._updated_at_provider(), "metrics": service._snapshot_provider()}
body = json.dumps(service._safe_json_value(payload), ensure_ascii=False, allow_nan=False).encode("utf-8")
self._send(200, body, "application/json; charset=utf-8")
except Exception:
self._send(503, b'{"status":"unavailable"}', "application/json; charset=utf-8")
else:
self._send(404, b"Not Found", "text/plain; charset=utf-8")
def do_POST(self) -> None:
self._send(405, b"Method Not Allowed", "text/plain; charset=utf-8")
do_PUT = do_POST
do_DELETE = do_POST
do_PATCH = do_POST
try:
server = _DashboardHTTPServer(("0.0.0.0", int(port)), Handler)
server.daemon_threads = True
except (OSError, ValueError) as exc:
self._logger.warning("LAN dashboard did not start on port %s: %s", port, exc)
return False
self._server = server
self.port = server.server_address[1]
self._thread = threading.Thread(target=server.serve_forever, name="lan-dashboard", daemon=True)
self._thread.start()
return True
def stop(self) -> None:
with self._lock:
server, thread = self._server, self._thread
self._server = None
self._thread = None
self.port = 0
if server is not None:
server.shutdown()
server.server_close()
if thread is not None and thread is not threading.current_thread():
thread.join(timeout=2)
class SensorReader:
class _CoreTempSharedData(ctypes.Structure):
_pack_ = 4
_fields_ = [
("uiLoad", ctypes.c_uint32 * 256),
("uiTjMax", ctypes.c_uint32 * 128),
("uiCoreCnt", ctypes.c_uint32),
("uiCPUCnt", ctypes.c_uint32),
("fTemp", ctypes.c_float * 256),
("fVID", ctypes.c_float),
("fCPUSpeed", ctypes.c_float),
("fFSBSpeed", ctypes.c_float),
("fMultiplier", ctypes.c_float),
("sCPUName", ctypes.c_char * 100),
("ucFahrenheit", ctypes.c_ubyte),
("ucDeltaToTjMax", ctypes.c_ubyte),
]
class _CoreTempSharedDataEx(ctypes.Structure):
_pack_ = 4
_fields_ = [
("uiLoad", ctypes.c_uint32 * 256),
("uiTjMax", ctypes.c_uint32 * 128),
("uiCoreCnt", ctypes.c_uint32),
("uiCPUCnt", ctypes.c_uint32),
("fTemp", ctypes.c_float * 256),
("fVID", ctypes.c_float),
("fCPUSpeed", ctypes.c_float),
("fFSBSpeed", ctypes.c_float),
("fMultiplier", ctypes.c_float),
("sCPUName", ctypes.c_char * 100),
("ucFahrenheit", ctypes.c_ubyte),
("ucDeltaToTjMax", ctypes.c_ubyte),
("ucTdpSupported", ctypes.c_ubyte),
("ucPowerSupported", ctypes.c_ubyte),
("uiStructVersion", ctypes.c_uint32),
("uiTdp", ctypes.c_uint32 * 128),
("fPower", ctypes.c_float * 128),
("fMultipliers", ctypes.c_float * 256),
]
def __init__(self) -> None:
self._lhm_computer = None
self._lhm_hardware = None
self._lhm_error = ""
self._lhm_retry_count = 0
self._last_fallback_ts = 0.0
self._fallback_cache: Dict[str, Optional[float]] = {
"cpu_coretemp": None,
"cpu_temp": None,
"gpu_temp": None,
"memory_freq": None,
}
self._last_status: Dict[str, str] = {}
self._external_lhm_proc = None
self._last_disk = None
self._last_net = None
self._last_io_ts = 0.0
self._ping_cache: Optional[float] = None
self._ping_cache_ts = 0.0
self._nvidia_smi = shutil.which("nvidia-smi")
self._init_lhm()
def _runtime_base_dir(self) -> Path:
if getattr(sys, "frozen", False):
return Path(sys._MEIPASS) # type: ignore[attr-defined]
return Path(__file__).resolve().parent
def _app_dir(self) -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent
def _init_lhm(self) -> None:
if clr is None:
self._lhm_error = "pythonnet 未加载"
return
candidates = [
self._runtime_base_dir() / "libs" / "LibreHardwareMonitorLib.dll",
self._app_dir() / "_internal" / "libs" / "LibreHardwareMonitorLib.dll",
self._app_dir() / "libs" / "LibreHardwareMonitorLib.dll",
]
dll_path = next((path for path in candidates if path.exists()), candidates[0])
if not dll_path.exists():
self._lhm_error = f"缺少 DLL: {dll_path}"
logging.getLogger("hardware_monitor").warning("LibreHardwareMonitor DLL missing: %s", dll_path)
return
try:
clr.AddReference(str(dll_path))
from LibreHardwareMonitor import Hardware # type: ignore
computer = Hardware.Computer()
computer.IsCpuEnabled = True
computer.IsGpuEnabled = True
computer.IsMemoryEnabled = True
computer.IsMotherboardEnabled = True
computer.IsControllerEnabled = False
computer.IsStorageEnabled = True
computer.Open()
self._lhm_computer = computer
self._lhm_hardware = Hardware
except Exception:
self._lhm_computer = None
self._lhm_hardware = None
self._lhm_error = "LHM 初始化失败(运行库兼容性或驱动限制)"
logging.getLogger("hardware_monitor").exception("LibreHardwareMonitor initialization failed")
def _start_external_lhm_if_available(self) -> None:
base = self._app_dir()
candidates = [
base / "tools" / "LibreHardwareMonitor" / "LibreHardwareMonitor.exe",
base / "LibreHardwareMonitor.exe",
]
for exe in candidates:
if not exe.exists():
continue
try:
self._external_lhm_proc = subprocess.Popen(
[str(exe)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=0x08000000,
)
break
except Exception:
self._external_lhm_proc = None
def close(self) -> None:
try:
if self._lhm_computer is not None:
self._lhm_computer.Close()
except Exception:
pass
try:
if self._external_lhm_proc is not None and self._external_lhm_proc.poll() is None:
self._external_lhm_proc.terminate()
except Exception:
pass
def _walk_sensors(self):
if self._lhm_computer is None:
return []
entries = []
for hw in self._lhm_computer.Hardware:
hw.Update()
entries.append(hw)
for sub_hw in hw.SubHardware:
sub_hw.Update()
entries.append(sub_hw)
return entries
@staticmethod
def _pick_max(current: Optional[float], candidate: float) -> Optional[float]:
if not math.isfinite(candidate):
return current
if current is None:
return candidate
return max(current, candidate)
def _read_coretemp_shared_memory(self) -> Optional[float]:
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
file_map_read = 0x0004
names = [
("CoreTempMappingObjectEx", self._CoreTempSharedDataEx),
("Global\\CoreTempMappingObjectEx", self._CoreTempSharedDataEx),
("CoreTempMappingObject", self._CoreTempSharedData),
("Global\\CoreTempMappingObject", self._CoreTempSharedData),
]
kernel32.OpenFileMappingW.argtypes = [ctypes.c_uint32, ctypes.c_bool, ctypes.c_wchar_p]
kernel32.OpenFileMappingW.restype = ctypes.c_void_p
kernel32.MapViewOfFile.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_size_t]
kernel32.MapViewOfFile.restype = ctypes.c_void_p
kernel32.UnmapViewOfFile.argtypes = [ctypes.c_void_p]
kernel32.UnmapViewOfFile.restype = ctypes.c_bool
kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
kernel32.CloseHandle.restype = ctypes.c_bool
for mapping_name, struct_type in names:
handle = kernel32.OpenFileMappingW(file_map_read, False, mapping_name)
if not handle:
continue
view = None
try:
view = kernel32.MapViewOfFile(handle, file_map_read, 0, 0, ctypes.sizeof(struct_type))
if not view:
continue
data = struct_type.from_address(view)
core_count = int(data.uiCoreCnt) * max(1, int(data.uiCPUCnt))
core_count = min(core_count, 256)
temps = []
for idx in range(core_count):
val = float(data.fTemp[idx])
if data.ucFahrenheit:
val = (val - 32.0) * 5.0 / 9.0
if data.ucDeltaToTjMax:
tjmax = float(data.uiTjMax[idx % 128])
val = tjmax - val
if 0 < val < 130:
temps.append(val)
if temps:
return max(temps)
except Exception:
continue
finally:
if view:
kernel32.UnmapViewOfFile(view)
kernel32.CloseHandle(handle)
return None
def _read_lhm_values(self) -> Dict[str, Optional[float]]:
values: Dict[str, Optional[float]] = {
"cpu_usage": None,
"cpu_freq": None,
"cpu_temp": None,
"gpu_usage": None,
"gpu_temp": None,
"gpu_clock": None,
"gpu_memory_used": None,
"gpu_memory_total": None,
"memory_freq": None,
"cpu_power": None,
"gpu_power": None,
"vram_freq": None,
"cpu_fan": None,
"gpu_fan": None,
"ssd_temp": None,
}
if self._lhm_computer is None or self._lhm_hardware is None:
if self._lhm_retry_count < 3:
self._lhm_retry_count += 1
self._init_lhm()
return values
sensor_type = self._lhm_hardware.SensorType
cpu_fallback: Optional[float] = None
gpu_fallback: Optional[float] = None
try:
for hw in self._walk_sensors():
hw_type_name = str(hw.HardwareType)
for sensor in hw.Sensors:
if sensor.Value is None:
continue
s_name = str(sensor.Name).lower()
sensor_value = float(sensor.Value)
if not math.isfinite(sensor_value):
continue
if sensor.SensorType == sensor_type.Load and "Cpu" in hw_type_name:
if "total" in s_name:
values["cpu_usage"] = sensor_value
elif sensor.SensorType == sensor_type.Load and "Gpu" in hw_type_name:
if s_name == "gpu core":
values["gpu_usage"] = sensor_value
if sensor.SensorType == sensor_type.Temperature:
if "Cpu" in hw_type_name:
if "tctl" in s_name or "tdie" in s_name or "package" in s_name:
values["cpu_temp"] = self._pick_max(values["cpu_temp"], sensor_value)
else:
cpu_fallback = self._pick_max(cpu_fallback, sensor_value)
elif "Gpu" in hw_type_name:
if "core" in s_name and "hot" not in s_name:
values["gpu_temp"] = self._pick_max(values["gpu_temp"], sensor_value)
else:
gpu_fallback = self._pick_max(gpu_fallback, sensor_value)
elif "Storage" in hw_type_name or "Hdd" in hw_type_name:
values["ssd_temp"] = self._pick_max(values.get("ssd_temp"), sensor_value)
else:
if values["cpu_temp"] is None and "cpu" in s_name:
values["cpu_temp"] = sensor_value
if values["gpu_temp"] is None and "gpu" in s_name:
values["gpu_temp"] = sensor_value
if sensor.SensorType == sensor_type.Clock:
if "Cpu" in hw_type_name and s_name.startswith("core #"):
values["cpu_freq"] = self._pick_max(values["cpu_freq"], sensor_value)
elif "Gpu" in hw_type_name and s_name == "gpu core":
values["gpu_clock"] = sensor_value
elif "Gpu" in hw_type_name and "memory" in s_name:
values["vram_freq"] = self._pick_max(values["vram_freq"], sensor_value)
elif "Memory" in hw_type_name and "memory" in s_name:
values["memory_freq"] = self._pick_max(values["memory_freq"], sensor_value)
if str(sensor.SensorType) == "Power":
if "Cpu" in hw_type_name and ("package" in s_name or "cpu" in s_name):
values["cpu_power"] = self._pick_max(values["cpu_power"], sensor_value)
elif "Gpu" in hw_type_name and ("package" in s_name or "total" in s_name or "gpu" in s_name):
values["gpu_power"] = self._pick_max(values["gpu_power"], sensor_value)
if str(sensor.SensorType) == "Fan":
if "Cpu" in hw_type_name:
values["cpu_fan"] = self._pick_max(values["cpu_fan"], sensor_value)
elif "Gpu" in hw_type_name:
values["gpu_fan"] = self._pick_max(values["gpu_fan"], sensor_value)
if str(sensor.SensorType) in ("SmallData", "Data") and "Gpu" in hw_type_name:
if s_name == "gpu memory used":
values["gpu_memory_used"] = sensor_value
elif s_name == "gpu memory total":
values["gpu_memory_total"] = sensor_value
except Exception:
return values
if values["cpu_temp"] is None:
values["cpu_temp"] = cpu_fallback
if values["gpu_temp"] is None:
values["gpu_temp"] = gpu_fallback
return values
@staticmethod
def _run_cmd(cmd: list[str], timeout: float = 0.8) -> str:
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, creationflags=0x08000000)
if result.returncode != 0:
return ""
return result.stdout.strip()
except Exception:
return ""
def _fallback_cpu_temp(self) -> Optional[float]:
out = self._run_cmd([
"powershell",
"-NoProfile",
"-Command",
"Get-CimInstance -Namespace root/wmi -ClassName MSAcpi_ThermalZoneTemperature | Select-Object -ExpandProperty CurrentTemperature",
])
if not out:
return None
temps = []
for line in out.splitlines():
line = line.strip()
if not line.isdigit():
continue
raw = int(line)
celsius = (raw / 10.0) - 273.15
if 0 < celsius < 130:
temps.append(celsius)
return max(temps) if temps else None
def _fallback_ohm_wmi_cpu_temp(self) -> Optional[float]:
out = self._run_cmd([
"powershell",
"-NoProfile",
"-Command",
"Get-CimInstance -Namespace root/OpenHardwareMonitor -ClassName Sensor | Where-Object { $_.SensorType -eq 'Temperature' -and ($_.Name -like '*CPU*' -or $_.Identifier -like '*cpu*') } | Select-Object -ExpandProperty Value",
])
if not out:
return None
temps = []
for line in out.splitlines():
line = line.strip().replace(",", ".")
try:
val = float(line)
except Exception:
continue
if 0 < val < 130:
temps.append(val)
return max(temps) if temps else None
def _fallback_lhm_wmi_cpu_temp(self) -> Optional[float]:
out = self._run_cmd([
"powershell",
"-NoProfile",
"-Command",
"Get-CimInstance -Namespace root/LibreHardwareMonitor -ClassName Sensor | Where-Object { $_.SensorType -eq 'Temperature' -and ($_.Name -like '*CPU*' -or $_.Identifier -like '*cpu*') } | Select-Object -ExpandProperty Value",
])
if not out:
return None
temps = []
for line in out.splitlines():
line = line.strip().replace(",", ".")
try:
val = float(line)
except Exception:
continue
if 0 < val < 130:
temps.append(val)
return max(temps) if temps else None
def _fallback_gpu_temp(self) -> Optional[float]:
if not self._nvidia_smi:
return None
out = self._run_cmd([
self._nvidia_smi,
"--query-gpu=temperature.gpu",
"--format=csv,noheader,nounits",
])
if not out:
return None
temps = []
for line in out.splitlines():
line = line.strip()
if line.isdigit():
val = float(line)
if 0 < val < 130:
temps.append(val)
return max(temps) if temps else None
def _fallback_gpu_vram(self) -> Optional[dict]:
if not self._nvidia_smi:
return None
out = self._run_cmd([
self._nvidia_smi,
"--query-gpu=memory.used,memory.total",
"--format=csv,noheader,nounits",
])
if not out:
return None
parts = out.split(",")
if len(parts) >= 2:
try:
return {"used": float(parts[0].strip()), "total": float(parts[1].strip())}
except ValueError:
return None
return None
def _fallback_ohm_wmi_gpu_temp(self) -> Optional[float]:
out = self._run_cmd([
"powershell",
"-NoProfile",
"-Command",
"Get-CimInstance -Namespace root/OpenHardwareMonitor -ClassName Sensor | Where-Object { $_.SensorType -eq 'Temperature' -and ($_.Name -like '*GPU*' -or $_.Identifier -like '*gpu*') } | Select-Object -ExpandProperty Value",
])
if not out:
return None
temps = []
for line in out.splitlines():
line = line.strip().replace(",", ".")
try:
val = float(line)
except Exception:
continue
if 0 < val < 130:
temps.append(val)
return max(temps) if temps else None
def _fallback_lhm_wmi_gpu_temp(self) -> Optional[float]:
out = self._run_cmd([
"powershell",
"-NoProfile",
"-Command",
"Get-CimInstance -Namespace root/LibreHardwareMonitor -ClassName Sensor | Where-Object { $_.SensorType -eq 'Temperature' -and ($_.Name -like '*GPU*' -or $_.Identifier -like '*gpu*') } | Select-Object -ExpandProperty Value",
])
if not out:
return None
temps = []
for line in out.splitlines():
line = line.strip().replace(",", ".")
try:
val = float(line)
except Exception:
continue
if 0 < val < 130:
temps.append(val)
return max(temps) if temps else None
def _fallback_memory_freq(self) -> Optional[float]:
out = self._run_cmd([
"powershell",
"-NoProfile",
"-Command",
"Get-CimInstance Win32_PhysicalMemory | Select-Object -ExpandProperty Speed",
])
if not out:
return None
speeds = []
for line in out.splitlines():
line = line.strip()
if line.isdigit():
val = float(line)
if 100 < val < 10000:
speeds.append(val)
return max(speeds) if speeds else None
def _read_ping(self) -> Optional[float]:
out = self._run_cmd(["ping", "-n", "1", "-w", "500", "8.8.8.8"])
if not out:
return None
import re
m = re.search(r"(?:time|时间)[=<](\d+)ms", out)
if m:
return float(m.group(1))
return None
def _read_fallback_values(self, lhm: Dict[str, Optional[float]], config: dict) -> Dict[str, Optional[float]]:
now = time.time()
needs_cpu_temp = bool(config.get("show_cpu_temperature", True)) and lhm.get("cpu_temp") is None
needs_gpu_temp = bool(config.get("show_gpu_temperature", True)) and lhm.get("gpu_temp") is None
needs_memory_freq = bool(config.get("show_memory_freq", False)) and lhm.get("memory_freq") is None
needs_vram = bool(config.get("show_vram_usage", True)) and (lhm.get("gpu_memory_used") is None or lhm.get("gpu_memory_total") is None)
needs_fallback = needs_cpu_temp or needs_gpu_temp or needs_memory_freq or needs_vram
if not needs_fallback:
return self._fallback_cache
if now - self._last_fallback_ts < 10:
return self._fallback_cache
self._last_fallback_ts = now
cpu_coretemp = self._read_coretemp_shared_memory() if needs_cpu_temp else None
cpu_ohm = self._fallback_ohm_wmi_cpu_temp() if needs_cpu_temp and cpu_coretemp is None else None
cpu_lhm_wmi = self._fallback_lhm_wmi_cpu_temp() if needs_cpu_temp and cpu_coretemp is None and cpu_ohm is None else None
cpu_wmi = self._fallback_cpu_temp() if needs_cpu_temp and cpu_coretemp is None and cpu_ohm is None and cpu_lhm_wmi is None else None
gpu_smi = self._fallback_gpu_temp() if needs_gpu_temp else None
gpu_ohm = self._fallback_ohm_wmi_gpu_temp() if needs_gpu_temp and gpu_smi is None else None
gpu_lhm_wmi = self._fallback_lhm_wmi_gpu_temp() if needs_gpu_temp and gpu_smi is None and gpu_ohm is None else None
mem_wmi = self._fallback_memory_freq() if needs_memory_freq else None
gpu_vram = self._fallback_gpu_vram() if needs_vram else None
self._fallback_cache = {
"cpu_coretemp": cpu_coretemp,
"cpu_temp": cpu_coretemp if cpu_coretemp is not None else (cpu_ohm if cpu_ohm is not None else cpu_lhm_wmi),
"gpu_temp": gpu_smi if gpu_smi is not None else (gpu_ohm if gpu_ohm is not None else gpu_lhm_wmi),
"memory_freq": mem_wmi,
"gpu_vram": gpu_vram,
}
acpi_status = "失败"
if cpu_wmi is not None:
acpi_status = f"{cpu_wmi:.1f}C(系统热区,非核心温度)"
self._last_status = {
"LHM": "OK" if self._lhm_computer is not None else f"不可用({self._lhm_error})",
"外部LHM": "已禁用(避免弹出驱动安装提示)",
"CoreTemp共享内存": "OK" if cpu_coretemp is not None else "未运行/未开放",
"ACPI热区": acpi_status,
"CPU共享WMI": "OK" if cpu_ohm is not None else "失败",
"CPU-LHM-WMI": "OK" if cpu_lhm_wmi is not None else "失败",
"GPU nvidia-smi": "OK" if gpu_smi is not None else "失败",
"GPU共享WMI": "OK" if gpu_ohm is not None else "失败",
"GPU-LHM-WMI": "OK" if gpu_lhm_wmi is not None else "失败",
"内存频率WMI": "OK" if mem_wmi is not None else "失败",
}
return self._fallback_cache
def read_metrics(self, config: Optional[dict] = None) -> Metrics:
config = config or DEFAULT_CONFIG
metrics = Metrics()
try:
metrics.cpu_usage = f"{psutil.cpu_percent(interval=0.15):.0f}%"
vm = psutil.virtual_memory()
used_gb = (vm.total - vm.available) / (1024.0 ** 3)
total_gb = vm.total / (1024.0 ** 3)
metrics.memory_usage = f"{used_gb:.1f} / {total_gb:.1f} GB"
cpu_freq = psutil.cpu_freq()
if cpu_freq and cpu_freq.current:
metrics.cpu_freq = f"{cpu_freq.current:.0f} MHz"
except Exception:
pass
lhm = self._read_lhm_values()
fb = self._read_fallback_values(lhm, config)
if lhm.get("cpu_usage") is not None:
metrics.cpu_usage = f"{lhm['cpu_usage']:.0f}%"
if lhm.get("cpu_freq") is not None and lhm["cpu_freq"] > 1000:
metrics.cpu_freq = f"{lhm['cpu_freq']:.0f} MHz"
if lhm.get("gpu_usage") is not None:
metrics.gpu_usage = f"{lhm['gpu_usage']:.0f}%"
if lhm.get("gpu_clock") is not None:
metrics.gpu_clock = f"{lhm['gpu_clock']:.0f} MHz"
if lhm.get("vram_freq") is not None:
metrics.vram_freq = f"{lhm['vram_freq']:.0f} MHz"
if lhm.get("gpu_memory_used") is not None and lhm.get("gpu_memory_total") is not None:
used_gb = lhm["gpu_memory_used"] / 1024.0
total_gb = lhm["gpu_memory_total"] / 1024.0
metrics.gpu_memory = f"{used_gb:.1f}/{total_gb:.1f} GB"
elif fb.get("gpu_vram") is not None:
vram = fb["gpu_vram"]
metrics.gpu_memory = f"{vram['used']/1024:.1f}/{vram['total']/1024:.1f} GB"
if lhm.get("cpu_power") is not None:
metrics.cpu_power = f"{lhm['cpu_power']:.1f} W"
if lhm.get("gpu_power") is not None:
metrics.gpu_power = f"{lhm['gpu_power']:.1f} W"
if lhm.get("cpu_fan") is not None:
metrics.cpu_fan = f"{lhm['cpu_fan']:.0f} RPM"
if lhm.get("gpu_fan") is not None:
metrics.gpu_fan = f"{lhm['gpu_fan']:.0f} RPM"
if lhm.get("ssd_temp") is not None:
metrics.ssd_temp = f"{lhm['ssd_temp']:.1f} °C"
cpu_temp = lhm["cpu_temp"] if lhm["cpu_temp"] is not None else fb["cpu_temp"]
gpu_temp = lhm["gpu_temp"] if lhm["gpu_temp"] is not None else fb["gpu_temp"]
memory_freq = lhm["memory_freq"] if lhm["memory_freq"] is not None else fb["memory_freq"]
if cpu_temp is not None:
metrics.cpu_temp = f"{cpu_temp:.1f} °C"
if gpu_temp is not None:
metrics.gpu_temp = f"{gpu_temp:.1f} °C"
if memory_freq is not None:
metrics.memory_freq = f"{memory_freq:.0f} MHz"
if metrics.cpu_temp == "N/A" and metrics.gpu_temp == "N/A":
metrics.temp_hint = "未拿到核心温度(驱动/接口受限)"
elif metrics.cpu_temp == "N/A":
metrics.temp_hint = "CPU核心温度接口不可用"
try:
now = time.time()
disk = psutil.disk_io_counters()
net = psutil.net_io_counters()
if self._last_disk is not None and self._last_net is not None and self._last_io_ts > 0:
dt = max(0.1, now - self._last_io_ts)
disk_bps = ((disk.read_bytes - self._last_disk.read_bytes) + (disk.write_bytes - self._last_disk.write_bytes)) / dt
read_bps = (disk.read_bytes - self._last_disk.read_bytes) / dt
write_bps = (disk.write_bytes - self._last_disk.write_bytes) / dt
up_bps = (net.bytes_sent - self._last_net.bytes_sent) / dt
down_bps = (net.bytes_recv - self._last_net.bytes_recv) / dt
metrics.disk_speed = f"{disk_bps / (1024.0 * 1024.0):.1f} MB/s"
metrics.disk_read = f"{read_bps / (1024.0 * 1024.0):.1f} MB/s"
metrics.disk_write = f"{write_bps / (1024.0 * 1024.0):.1f} MB/s"
metrics.network_speed = f"↑ {up_bps / (1024.0 * 1024.0):.1f} MB/s ↓ {down_bps / (1024.0 * 1024.0):.1f} MB/s"
metrics.network_up = f"{up_bps / (1024.0 * 1024.0):.1f} MB/s"
metrics.network_down = f"{down_bps / (1024.0 * 1024.0):.1f} MB/s"
self._last_disk = disk
self._last_net = net
self._last_io_ts = now
except Exception:
pass
try:
batt = psutil.sensors_battery()
if batt is not None:
state = "充电中" if batt.power_plugged else "使用中"
metrics.battery_status = f"{int(round(batt.percent))}% ({state})"
except Exception:
pass
# Network latency (cached for 2 seconds)
try:
now = time.time()
if not bool(config.get("show_network_latency", False)):
self._ping_cache = None
elif now - self._ping_cache_ts >= 10:
self._ping_cache = self._read_ping()
self._ping_cache_ts = now
if self._ping_cache is not None:
metrics.network_latency = f"{self._ping_cache:.0f} ms"
except Exception:
pass
metrics.source_status = " | ".join([f"{k}:{v}" for k, v in self._last_status.items()])
return metrics
class FpsService:
def __init__(self, app_dir: Path, runtime_base_dir: Path, logger: logging.Logger) -> None:
self._app_dir = app_dir
self._runtime_base_dir = runtime_base_dir
self._logger = logger
self._enabled = False
self._target_process = ""
self._stop_event = threading.Event()
self._worker_thread: Optional[threading.Thread] = None
self._proc: Optional[subprocess.Popen] = None
self._lock = threading.Lock()
self._display_text = "关闭"