forked from Keralots/SmallOLED-PCMonitor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpc_stats_monitor_v2.py
More file actions
2523 lines (2155 loc) · 98 KB
/
Copy pathpc_stats_monitor_v2.py
File metadata and controls
2523 lines (2155 loc) · 98 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
"""
PC Stats Monitor v2.0 - Dynamic Sensor Selection
Flexible monitoring system with GUI configuration and up to 12 customizable metrics
"""
import psutil
import socket
import time
import json
import os
import sys
import argparse
from datetime import datetime
import tkinter as tk
from tkinter import ttk, messagebox
from urllib import request as urllib_request
from urllib import error as urllib_error
import re
# Try to import pystray for system tray support
try:
import pystray
from PIL import Image, ImageDraw
TRAY_AVAILABLE = True
except ImportError:
TRAY_AVAILABLE = False
# Try to import pythoncom for COM initialization (needed for WMI with pythonw.exe)
try:
import pythoncom
PYTHONCOM_AVAILABLE = True
except ImportError:
PYTHONCOM_AVAILABLE = False
# Configuration file path - use absolute path to work correctly from any working directory
# This fixes autostart issues where Windows ignores WorkingDirectory in shortcuts
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(SCRIPT_DIR, "monitor_config.json")
# Default configuration
DEFAULT_CONFIG = {
"version": "2.1",
"esp32_ip": "192.168.0.163",
"udp_port": 4210,
"update_interval": 3,
"metrics": []
}
# Maximum metrics supported by ESP32
MAX_METRICS = 20 # Increased from 12 to support companion metrics
# Global sensor database
sensor_database = {
"system": [], # psutil-based metrics (CPU%, RAM%, Disk%)
"temperature": [],
"fan": [],
"load": [],
"clock": [],
"power": [],
"data": [], # Network/disk data (uploaded/downloaded GB)
"throughput": [], # Network throughput (upload/download speed KB/s, MB/s)
"other": []
}
# Global variable for discovered WMI namespace (can be auto-detected)
discovered_wmi_namespace = "root\\LibreHardwareMonitor" # Default
# Global variables for REST API (alternative to WMI for LHM 0.9.5+)
rest_api_host = "localhost"
rest_api_port = 8085
use_rest_api = False # Auto-detected; True when WMI fails but REST API works
class LHMHealthMonitor:
"""
Monitors LibreHardwareMonitor REST API health.
Tracks consecutive failures and provides exponential backoff for recovery.
"""
def __init__(self):
self.consecutive_failures = 0
self.last_success_time = time.time()
self.is_healthy = True
self.last_warning_time = 0
def record_success(self):
"""Record a successful API call"""
if not self.is_healthy:
print(" ✓ LHM connection restored!")
self.consecutive_failures = 0
self.last_success_time = time.time()
self.is_healthy = True
def record_failure(self):
"""Record a failed API call"""
self.consecutive_failures += 1
if self.consecutive_failures >= 2: # Trigger faster (was 3)
if self.is_healthy:
print(" ⚠ LHM REST API unhealthy - entering recovery mode")
self.is_healthy = False
def get_retry_delay(self):
"""Exponential backoff: 3s, 6s, 12s, max 30s"""
if self.consecutive_failures <= 1:
return 3
delay = min(3 * (2 ** (self.consecutive_failures - 1)), 30)
return delay
def should_print_warning(self):
"""Limit warning messages to once per 30 seconds"""
now = time.time()
if now - self.last_warning_time >= 30:
self.last_warning_time = now
return True
return False
# Global health monitor instance
lhm_health_monitor = LHMHealthMonitor()
def is_lhm_process_running():
"""Check if LibreHardwareMonitor process is running"""
lhm_names = ["librehardwaremonitor", "libre hardware monitor"]
for proc in psutil.process_iter(['name']):
try:
proc_name = proc.info['name'].lower()
if any(name in proc_name for name in lhm_names):
return True
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return False
def discover_wmi_namespaces():
"""
Quick check for WMI namespace (simplified for 0.9.5+ compatibility)
Returns: (list_of_namespaces, working_namespace)
"""
print("\nChecking WMI namespace...")
namespace = "root\\LibreHardwareMonitor"
try:
import wmi
w = wmi.WMI(namespace=namespace)
sensors = list(w.Sensor())
if len(sensors) > 0:
print(f" ✓ WMI working with {len(sensors)} sensors")
return [namespace], namespace
else:
print(f" ⚠ WMI accessible but 0 sensors (LibreHardwareMonitor 0.9.5+ issue)")
print(f" → Will use REST API fallback")
return [], None
except Exception as e:
print(f" ✗ WMI not accessible: {str(e)[:60]}")
print(f" → Will use REST API fallback")
return [], None
def get_librehardwaremonitor_version():
"""
Try to detect LibreHardwareMonitor version
Returns: version string or None
"""
version = None
# Method 1: Check executable version
try:
import win32api
import win32con
import os
# Common installation paths
possible_paths = [
r"C:\Program Files\LibreHardwareMonitor\LibreHardwareMonitor.exe",
r"C:\Program Files (x86)\LibreHardwareMonitor\LibreHardwareMonitor.exe",
r"C:\Users\Public\Desktop\LibreHardwareMonitor.exe",
]
# Also check PATH
try:
import shutil
exe_path = shutil.which("LibreHardwareMonitor.exe")
if exe_path:
possible_paths.insert(0, exe_path)
except:
pass
for path in possible_paths:
if os.path.exists(path):
try:
info = win32api.GetFileVersionInfo(path, "\\")
ms = info['FileVersionMS']
ls = info['FileVersionLS']
version = f"{win32api.HIWORD(ms)}.{win32api.LOWORD(ms)}.{win32api.HIWORD(ls)}.{win32api.LOWORD(ls)}"
return version
except:
pass
except:
pass
# Method 2: Try to get version from WMI
try:
import wmi
w = wmi.WMI()
# Try to find LibreHardwareMonitor process and get its version
import psutil
for proc in psutil.process_iter(['name', 'exe']):
try:
if 'librehardwaremonitor' in proc.info['name'].lower():
exe_path = proc.info['exe']
if exe_path and os.path.exists(exe_path):
import win32api
info = win32api.GetFileVersionInfo(exe_path, "\\")
ms = info['FileVersionMS']
ls = info['FileVersionLS']
version = f"{win32api.HIWORD(ms)}.{win32api.LOWORD(ms)}.{win32api.HIWORD(ls)}.{win32api.LOWORD(ls)}"
return version
except:
pass
except:
pass
return None
def extract_sensors_from_tree(node, sensor_list=None, parent_hardware=None):
"""
Recursively extract all sensors from LibreHardwareMonitor REST API tree structure.
The API returns a hierarchical tree where actual sensors have a 'SensorId' field.
Tracks parent hardware name to provide better context for sensors.
"""
if sensor_list is None:
sensor_list = []
# Check if this node is a hardware device (has children but no SensorId)
# Hardware nodes have Text like "Intel Ethernet I219-V" or "NVIDIA GeForce RTX 3080"
current_hardware = parent_hardware
if "Children" in node and "SensorId" not in node:
# This might be a hardware node - use its name as parent for children
if node.get("Text") and node.get("Text") != "Sensor":
current_hardware = node.get("Text")
# If this node has a SensorId, it's an actual sensor
if "SensorId" in node:
# Add parent hardware name to sensor for better identification
sensor_copy = node.copy()
if current_hardware:
sensor_copy["_parent_hardware"] = current_hardware
sensor_list.append(sensor_copy)
# Recursively process children
if "Children" in node and isinstance(node["Children"], list):
for child in node["Children"]:
extract_sensors_from_tree(child, sensor_list, current_hardware)
return sensor_list
def check_rest_api_connectivity(host, port):
"""
Check if LibreHardwareMonitor REST API is accessible
Returns: (success, sensor_count, error_message)
"""
url = f"http://{host}:{port}/data.json"
try:
req = urllib_request.Request(url, method='GET')
req.add_header('User-Agent', 'PC-Stats-Monitor/2.0')
with urllib_request.urlopen(req, timeout=3) as response:
if response.status == 200:
data = response.read().decode('utf-8')
root = json.loads(data)
# Extract sensors from tree structure
sensors = extract_sensors_from_tree(root)
if len(sensors) > 0:
return True, len(sensors), None
else:
return False, 0, "REST API returned no sensors"
else:
return False, 0, f"HTTP {response.status}"
except urllib_error.HTTPError as e:
return False, 0, f"HTTP error {e.code}"
except urllib_error.URLError as e:
return False, 0, f"Connection failed: {e.reason}"
except json.JSONDecodeError as e:
return False, 0, f"Invalid JSON response: {e}"
except Exception as e:
return False, 0, f"Unexpected error: {e}"
def discover_sensors_via_http(host, port):
"""
Discover sensors via LibreHardwareMonitor REST API
This is used when WMI fails (LHM 0.9.5+)
"""
global sensor_database
url = f"http://{host}:{port}/data.json"
try:
req = urllib_request.Request(url, method='GET')
req.add_header('User-Agent', 'PC-Stats-Monitor/2.0')
with urllib_request.urlopen(req, timeout=5) as response:
if response.status != 200:
print(f" ✗ HTTP error {response.status}")
return False
data = response.read().decode('utf-8')
root = json.loads(data)
# Extract sensors from tree structure
sensors = extract_sensors_from_tree(root)
# Reset name tracker to ensure fresh unique names
reset_generated_names()
sensor_count = 0
for sensor in sensors:
# Map REST API fields to our sensor_database format
sensor_id = sensor.get("SensorId", "")
sensor_name = sensor.get("Text", "Unknown")
sensor_type = sensor.get("Type", "").lower()
sensor_value = sensor.get("Value", "0")
# Skip if missing critical fields
if not sensor_id or not sensor_name:
continue
# Parse value from string (e.g., "45.0 °C" -> 45.0)
original_value_str = str(sensor_value)
try:
# Extract numeric value from string like "45.0 °C" or "12.1 %"
value_match = re.search(r'[-+]?\d*\.?\d+', original_value_str)
if value_match:
sensor_value = float(value_match.group())
else:
sensor_value = 0
# Normalize throughput to KB/s for ESP32
if sensor_type == "throughput":
value_upper = original_value_str.upper()
if "GB/S" in value_upper:
# GB/s → KB/s: multiply by 1024*1024
sensor_value = sensor_value * 1024 * 1024
elif "MB/S" in value_upper:
# MB/s → KB/s: multiply by 1024
sensor_value = sensor_value * 1024
elif "KB/S" in value_upper:
# Already KB/s, no conversion needed
pass
elif "B/S" in value_upper or not any(x in value_upper for x in ['/', 'S']):
# B/s or raw bytes → KB/s: divide by 1024
sensor_value = sensor_value / 1024
# Multiply by 10 to preserve 1 decimal place (ESP32 will divide by 10)
sensor_value = sensor_value * 10
except:
sensor_value = 0
# Determine unit based on type
unit_map = {
"temperature": "C", # No degree symbol - OLED can't display it
"fan": "RPM",
"load": "%",
"clock": "MHz",
"power": "W",
"voltage": "V",
"data": "GB",
"smalldata": "MB",
"control": "%",
"level": "%",
"throughput": "KB/s",
}
sensor_unit = unit_map.get(sensor_type, "")
# Generate short name from sensor_id and sensor_name for uniqueness
short_name = generate_short_name_from_id(sensor_id, sensor_type, sensor_name)
# Build display name with device context
identifier_parts = sensor_id.split('/')
parent_hardware = sensor.get("_parent_hardware", "")
# For network sensors, use parent hardware name (actual NIC name)
if "nic" in sensor_id.lower() and parent_hardware:
# Use friendly NIC name instead of GUID
display_name = f"{sensor_name} [{parent_hardware}]"
elif len(identifier_parts) > 1:
device_info = identifier_parts[1]
if device_info.lower() not in sensor_name.lower():
display_name = f"{sensor_name} [{device_info}]"
else:
display_name = sensor_name
else:
display_name = sensor_name
# Check if this is an active network interface (has traffic)
is_active_nic = False
if "nic" in sensor_id.lower() and sensor_type == "throughput":
if sensor_value > 0:
is_active_nic = True
# Reclassify ambiguous types based on device context
# Memory metrics are tagged as "data" but should be in "system"
device_id_lower = sensor_id.lower()
sensor_name_lower = sensor_name.lower()
if sensor_type in ("data", "smalldata"):
# Check if this is memory-related (not network data)
if ("memory" in device_id_lower or "ram" in device_id_lower or
"vram" in device_id_lower or
("gpu" in device_id_lower and ("memory" in sensor_name_lower or "vram" in sensor_name_lower))):
# Reclassify memory as system metric
sensor_type = "memory"
sensor_info = {
"name": short_name,
"display_name": display_name,
"source": "wmi", # Keep as "wmi" for compatibility
"type": sensor_type,
"unit": sensor_unit,
"wmi_identifier": sensor_id,
"wmi_sensor_name": sensor_name,
"custom_label": "",
"current_value": int(sensor_value),
"is_active_nic": is_active_nic, # True if network interface has traffic
"parent_hardware": parent_hardware # Hardware name (useful for NICs)
}
# Categorize sensor
if sensor_type == "temperature":
sensor_database["temperature"].append(sensor_info)
elif sensor_type == "fan":
sensor_database["fan"].append(sensor_info)
elif sensor_type == "load":
sensor_database["load"].append(sensor_info)
elif sensor_type == "clock":
sensor_database["clock"].append(sensor_info)
elif sensor_type == "power":
sensor_database["power"].append(sensor_info)
elif sensor_type == "memory": # Reclassified memory metrics
sensor_database["system"].append(sensor_info)
elif sensor_type in ("data", "smalldata"): # Now only actual network data
sensor_database["data"].append(sensor_info)
elif sensor_type == "throughput":
sensor_database["throughput"].append(sensor_info)
else:
sensor_database["other"].append(sensor_info)
sensor_count += 1
if sensor_count > 0:
print(f" ✓ Found {sensor_count} hardware sensors via REST API:")
print(f" - Temperatures: {len(sensor_database['temperature'])}")
print(f" - Fans: {len(sensor_database['fan'])}")
print(f" - Loads: {len(sensor_database['load'])}")
print(f" - Clocks: {len(sensor_database['clock'])}")
print(f" - Power: {len(sensor_database['power'])}")
print(f" - Data: {len(sensor_database['data'])}")
print(f" - Throughput: {len(sensor_database['throughput'])}")
if len(sensor_database['other']) > 0:
print(f" - Other: {len(sensor_database['other'])}")
return True
else:
print(" ⚠ REST API returned 0 sensors")
return False
except urllib_error.HTTPError as e:
print(f" ✗ HTTP error {e.code}")
return False
except urllib_error.URLError as e:
print(f" ✗ Connection failed: {e.reason}")
return False
except Exception as e:
print(f" ✗ Error: {e}")
return False
def get_metric_value_via_http(metric_config, host, port):
"""
Get sensor value via LibreHardwareMonitor REST API
Used when use_rest_api = True
Returns: int value on success, None on failure (to distinguish from real zeros)
"""
global lhm_health_monitor
sensor_id = metric_config.get("wmi_identifier", "")
if not sensor_id:
return None
url = f"http://{host}:{port}/data.json"
is_throughput = metric_config.get("unit", "") == "KB/s"
try:
req = urllib_request.Request(url, method='GET')
req.add_header('User-Agent', 'PC-Stats-Monitor/2.0')
with urllib_request.urlopen(req, timeout=1) as response: # 1s timeout for fast failure detection
if response.status != 200:
lhm_health_monitor.record_failure()
return None
data = response.read().decode('utf-8')
root = json.loads(data)
# Extract sensors from tree structure
sensors = extract_sensors_from_tree(root)
# Find matching sensor by SensorId
for sensor in sensors:
if sensor.get("SensorId", "") == sensor_id:
value = sensor.get("Value", "0")
value_str = str(value)
# Parse value from string (e.g., "45.0 °C" -> 45.0)
try:
value_match = re.search(r'[-+]?\d*\.?\d+', value_str)
if value_match:
float_value = float(value_match.group())
# For throughput: multiply by 10 to preserve 1 decimal place
# ESP32 will divide by 10 when displaying
if is_throughput:
# Normalize throughput to KB/s for ESP32
value_upper = value_str.upper()
if "GB/S" in value_upper:
# GB/s → KB/s
float_value = float_value * 1024 * 1024
elif "MB/S" in value_upper:
# MB/s → KB/s
float_value = float_value * 1024
elif "KB/S" in value_upper:
# Already KB/s
pass
elif "B/S" in value_upper or not any(x in value_upper for x in ['/', 'S']):
# B/s or raw bytes → KB/s
float_value = float_value / 1024
float_value = float_value * 10
lhm_health_monitor.record_success()
return int(float_value)
except:
pass
# Sensor found but value parsing failed
lhm_health_monitor.record_success() # API is working
return 0
# Sensor not found in response
lhm_health_monitor.record_success() # API is working
return 0
except Exception:
lhm_health_monitor.record_failure()
return None
# Global tracker for generated names to ensure uniqueness
_generated_names = set()
def reset_generated_names():
"""Reset the name tracker - call before sensor discovery"""
global _generated_names
_generated_names = set()
def _make_unique_name(base_name):
"""Ensure name is unique by adding suffix if needed"""
global _generated_names
# Truncate base to max 10 chars
base_name = base_name[:10]
if base_name not in _generated_names:
_generated_names.add(base_name)
return base_name
# Add numeric suffix to make unique
for i in range(1, 100):
candidate = f"{base_name[:8]}{i}" if len(base_name) > 8 else f"{base_name}{i}"
candidate = candidate[:10]
if candidate not in _generated_names:
_generated_names.add(candidate)
return candidate
return base_name # Fallback
def _extract_context_suffix(sensor_name):
"""Extract context suffix from sensor name"""
name_lower = sensor_name.lower()
# Memory/data context
if "used" in name_lower:
return "_U"
elif "available" in name_lower or "avail" in name_lower:
return "_A"
elif "capacity" in name_lower:
return "_CAP"
elif "total" in name_lower:
return "_TOT"
elif "free" in name_lower:
return "_F"
# Temperature context
elif "core max" in name_lower:
return "_MAX"
elif "core avg" in name_lower or "average" in name_lower:
return "_AVG"
elif "hotspot" in name_lower:
return "_HOT"
elif "junction" in name_lower:
return "_JNC"
return ""
def generate_short_name_from_id(sensor_id, sensor_type, sensor_name=""):
"""
Generate unique short name from sensor_id and sensor_name (REST API format)
Uses sensor_name context to differentiate similar sensors
"""
parts = sensor_id.split('/')
name_lower = sensor_name.lower()
# Get context suffix from sensor name
context = _extract_context_suffix(sensor_name)
if len(parts) >= 4:
device = parts[1] # e.g., "intelcpu", "gpu-nvidia", "lpc", "nic"
device_lower = device.lower()
device_idx = parts[2] if len(parts) > 2 else "0"
sensor_idx = parts[-1] # Last part is usually the sensor index
# CPU sensors
if "cpu" in device_lower:
if sensor_type == "load":
if "total" in name_lower or sensor_idx == "0":
base = "CPU"
else:
base = f"CPU_C{sensor_idx}"
elif sensor_type == "temperature":
if "core max" in name_lower:
base = "CPU_MAX"
elif "core avg" in name_lower or "average" in name_lower:
base = "CPU_AVG"
elif "core" in name_lower and "p-core" not in name_lower and "e-core" not in name_lower:
base = f"CPUT{sensor_idx}"
elif "p-core" in name_lower:
base = f"CPUP{sensor_idx}"
elif "e-core" in name_lower:
base = f"CPUE{sensor_idx}"
elif "ccd" in name_lower:
base = f"CCD{sensor_idx}T"
else:
base = f"CPUT{sensor_idx}" if sensor_idx != "0" else "CPUT"
elif sensor_type == "power":
if "package" in name_lower:
base = "CPU_PKG"
elif "core" in name_lower:
base = "CPU_COR"
else:
base = f"CPUW{sensor_idx}" if sensor_idx != "0" else "CPUW"
elif sensor_type == "clock":
base = f"CPUCLK{sensor_idx}" if sensor_idx != "0" else "CPUCLK"
else:
base = f"CPU_{sensor_idx}"
return _make_unique_name(base)
# GPU sensors
elif "gpu" in device_lower or "nvidia" in device_lower or "amd" in device_lower:
gpu_idx = "" if device_idx == "0" else device_idx
if sensor_type == "load":
if "memory" in name_lower or "vram" in name_lower:
base = f"VRAM{gpu_idx}"
elif "core" in name_lower or sensor_idx == "0":
base = f"GPU{gpu_idx}"
else:
base = f"GPU{gpu_idx}_{sensor_idx}"
elif sensor_type == "temperature":
if "hotspot" in name_lower:
base = f"GPU{gpu_idx}_HOT"
elif "memory" in name_lower or "vram" in name_lower:
base = f"VRAM{gpu_idx}T"
else:
base = f"GPUT{gpu_idx}"
elif sensor_type == "power":
base = f"GPUW{gpu_idx}"
elif sensor_type == "clock":
if "memory" in name_lower:
base = f"VCLK{gpu_idx}"
else:
base = f"GCLK{gpu_idx}"
elif sensor_type == "fan":
base = f"GPUF{gpu_idx}_{sensor_idx}" if sensor_idx != "0" else f"GPUF{gpu_idx}"
elif sensor_type in ("data", "smalldata"):
# GPU memory data
base = f"VRAM{gpu_idx}{context}"
else:
base = f"GPU{gpu_idx}_{sensor_idx}"
return _make_unique_name(base)
# LPC/Motherboard sensors (VRM, PCH, System temps, etc.)
elif "lpc" in device_lower or "motherboard" in device_lower or "mainboard" in device_lower:
if sensor_type == "temperature":
if "vrm" in name_lower:
base = "VRM_T"
elif "mos" in name_lower:
base = "MOS_T"
elif "pch" in name_lower:
base = "PCH_T"
elif "cpu" in name_lower and "socket" in name_lower:
base = "CPUS_T"
elif "system" in name_lower:
base = f"SYS{sensor_idx}T"
elif "pcie" in name_lower or "pci" in name_lower:
base = f"PCIE{sensor_idx}T"
elif "m.2" in name_lower or "m2" in name_lower:
base = f"M2_{sensor_idx}T"
elif "chipset" in name_lower:
base = "CHIP_T"
else:
# Generic LPC temperature
base = f"MB{sensor_idx}T"
elif sensor_type == "fan":
if "cpu" in name_lower:
base = "CPUF"
elif "pump" in name_lower:
base = "PUMP"
elif "chassis" in name_lower:
base = f"CHS{sensor_idx}F"
elif "system" in name_lower:
# Extract fan number from name like "System Fan #1"
fan_match = re.search(r'#(\d+)', sensor_name)
if fan_match:
base = f"SYS{fan_match.group(1)}F"
else:
base = f"SYS{sensor_idx}F"
elif "aux" in name_lower:
base = f"AUX{sensor_idx}F"
else:
base = f"FAN{sensor_idx}"
elif sensor_type == "voltage":
if "vcore" in name_lower or "cpu" in name_lower:
base = "VCORE"
elif "vram" in name_lower or "memory" in name_lower:
base = "VMEM"
elif "+12v" in name_lower or "12v" in name_lower:
base = "V12"
elif "+5v" in name_lower or "5v" in name_lower:
base = "V5"
elif "+3.3v" in name_lower or "3.3v" in name_lower:
base = "V3_3"
else:
base = f"V{sensor_idx}"
elif sensor_type == "control":
base = f"CTL{sensor_idx}"
else:
base = f"LPC{sensor_idx}"
return _make_unique_name(base)
# Memory/RAM sensors
elif "memory" in device_lower or "ram" in device_lower:
if sensor_type in ("data", "smalldata", "memory"):
if "vram" in name_lower:
base = f"VRAM{context}"
elif "capacity" in name_lower:
base = f"RAM_CAP"
elif "used" in name_lower:
base = "RAM_U"
elif "available" in name_lower or "avail" in name_lower:
base = "RAM_A"
else:
base = f"RAM{context}" if context else f"RAM{sensor_idx}"
elif sensor_type == "load":
base = "RAM"
else:
base = f"RAM{sensor_idx}"
return _make_unique_name(base)
# Network sensors
elif "nic" in device_lower or "network" in device_lower:
net_idx = "" if device_idx == "0" else device_idx
if sensor_type == "throughput":
if "upload" in name_lower or "sent" in name_lower:
base = f"NET{net_idx}_U"
elif "download" in name_lower or "received" in name_lower:
base = f"NET{net_idx}_D"
else:
# Use sensor index: 0=upload, 1=download typically
if sensor_idx == "0":
base = f"NET{net_idx}_U"
else:
base = f"NET{net_idx}_D"
elif sensor_type == "data":
if "upload" in name_lower or "sent" in name_lower:
base = f"NTD{net_idx}_U"
elif "download" in name_lower or "received" in name_lower:
base = f"NTD{net_idx}_D"
else:
base = f"NTD{net_idx}_{sensor_idx}"
else:
base = f"NET{net_idx}_{sensor_idx}"
return _make_unique_name(base)
# Storage (HDD/SSD/NVMe)
elif "hdd" in device_lower or "ssd" in device_lower or "nvme" in device_lower:
drv_idx = "" if device_idx == "0" else device_idx
if "hdd" in device_lower:
prefix = f"HDD{drv_idx}"
elif "ssd" in device_lower:
prefix = f"SSD{drv_idx}"
else:
prefix = f"NVM{drv_idx}"
if sensor_type == "temperature":
base = f"{prefix}T"
elif sensor_type == "load":
base = f"{prefix}%"
elif sensor_type == "data":
base = f"{prefix}D"
else:
base = f"{prefix}_{sensor_idx}"
return _make_unique_name(base)
# Fallback: Create descriptive name from sensor_name + sensor_id
if sensor_name:
# Use first word of sensor name + type abbreviation
words = sensor_name.replace("-", " ").replace("_", " ").split()
if words:
base = words[0][:4].upper()
type_suffix = {"temperature": "T", "fan": "F", "load": "%",
"power": "W", "voltage": "V", "clock": "C"}.get(sensor_type, "")
base = f"{base}{type_suffix}"
return _make_unique_name(base)
# Last resort fallback
if len(parts) >= 2:
device = parts[1].replace("-", "")[:4].upper()
return _make_unique_name(f"{device}{sensor_idx}")
def check_wmi_connectivity():
"""
Diagnostics: Check if LibreHardwareMonitor WMI namespace is accessible
Returns: (success, error_message, suggestion)
"""
print("\n" + "-" * 60)
print("DIAGNOSTICS: Checking LibreHardwareMonitor connectivity...")
print("-" * 60)
# Check 1: Verify required modules are installed
print("\n[Check 1/4] Verifying required Python modules...")
try:
import wmi
print(" ✓ pywin32 and wmi modules are installed")
except ImportError as e:
missing = str(e).split("'")[1] if "'" in str(e) else "pywin32/wmi"
return False, f"Missing required module: {missing}", (
"FIX: Install required modules:\n"
" pip install pywin32 wmi\n\n"
" Or run: python -m pip install pywin32 wmi"
)
# Check 2: Verify LibreHardwareMonitor process is running
print("\n[Check 2/4] Checking if LibreHardwareMonitor is running...")
try:
import psutil
found_lhm = False
lhm_names = ["librehardwaremonitor", "libre hardware monitor",
"hwmonitor", "hardware monitor"]
for proc in psutil.process_iter(['name']):
try:
proc_name = proc.info['name'].lower()
if any(name in proc_name for name in lhm_names):
found_lhm = True
print(f" ✓ Found LibreHardwareMonitor process: {proc.info['name']}")
break
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
# Try to detect version if process is running
if found_lhm:
version = get_librehardwaremonitor_version()
if version:
print(f" → Detected LibreHardwareMonitor version: {version}")
# Check for known problematic versions
version_parts = version.split('.')
if len(version_parts) >= 2:
major = int(version_parts[0])
minor = int(version_parts[1])
# Version 0.9.5+ has known WMI issues
if major == 0 and minor >= 9 and len(version_parts) >= 3:
patch = int(version_parts[2])
if patch >= 5:
print("\n ⚠⚠⚠ WARNING: LibreHardwareMonitor 0.9.5+ has BROKEN WMI support! ⚠⚠⚠")
print(" → Version 0.9.5 introduced a bug that breaks WMI sensor reporting")
print(" → See: https://github.com/LibreHardwareMonitor/LibreHardwareMonitor/issues/2088")
print(" → RECOMMENDED: Downgrade to 0.9.4 from GitHub Releases page")
else:
print(f" → Could not detect version (please report this)")
if not found_lhm:
return False, "LibreHardwareMonitor is not running", (
"FIX: Start LibreHardwareMonitor first\n\n"
" 1. Launch LibreHardwareMonitor\n"
" 2. IMPORTANT: Right-click and select 'Run as Administrator'\n"
" 3. Keep it running while using this script"
)
except Exception as e:
print(f" ⚠ Could not check processes: {e}")
# Check 3: Auto-discover WMI namespace
print("\n[Check 3/4] Auto-discovering WMI namespace...")
global discovered_wmi_namespace
# Run auto-discovery
_found_namespaces, working_namespace = discover_wmi_namespaces()
if working_namespace:
# Update global namespace with the one that works
discovered_wmi_namespace = working_namespace
print(f"\n → Using namespace: {working_namespace}")
else:
# Auto-discovery failed - likely LibreHardwareMonitor 0.9.5+ with broken WMI
# Try REST API fallback before giving up (LHM 0.9.5+ workaround)
print(f"\n ⚠ No working WMI namespace found (LHM 0.9.5+ issue)")
print(f" → Trying REST API fallback...")
print(f" → Checking http://{rest_api_host}:{rest_api_port}/data.json")
global use_rest_api
rest_success, rest_count, rest_error = check_rest_api_connectivity(rest_api_host, rest_api_port)
# Debug: print REST API check result
if rest_error:
print(f" ✗ REST API failed: {rest_error}")
if rest_success and rest_count > 0:
# REST API works! Use it instead of WMI
use_rest_api = True
print(f"\n ✓✓✓ REST API WORKS! Using REST API instead of WMI ✓✓✓")
print(f" → Found {rest_count} sensors via REST API")
print(f" → This bypasses the WMI bug in LibreHardwareMonitor 0.9.5+")
print(f" → Make sure 'Remote Web Server' is enabled in LibreHardwareMonitor")
print(f" (Options → Remote Web Server → Run)")
# Skip remaining checks - REST API is working
return True, None, None
# REST API also failed - provide simplified troubleshooting
return False, "No working WMI namespace found", (
"FIX: LibreHardwareMonitor 0.9.5+ has broken WMI support.\n\n"
"SOLUTION (3 steps):\n\n"
"1. Enable REST API in LibreHardwareMonitor:\n"
" Options → Remote Web Server → Run (port 8085)\n\n"
"2. If that doesn't work, downgrade to 0.9.4:\n"
" https://github.com/LibreHardwareMonitor/LibreHardwareMonitor/releases\n\n"
"3. If still failing, add Windows Defender exclusion:\n"
" Add exclusion for LibreHardwareMonitor folder in Windows Security"
)
# Check 4: Verify we can actually read sensor data
print("\n[Check 4/4] Testing sensor data access...")
try:
import wmi
w = wmi.WMI(namespace=discovered_wmi_namespace)
sensors = list(w.Sensor())
if len(sensors) == 0:
# CRITICAL: Namespace exists but no sensors found
# Try REST API fallback before giving up (LHM 0.9.5+ workaround)
print(f" ⚠ WMI returned 0 sensors - trying REST API fallback...")
print(f" → Checking http://{rest_api_host}:{rest_api_port}/data.json")
rest_success, rest_count, rest_error = check_rest_api_connectivity(rest_api_host, rest_api_port)
if rest_success and rest_count > 0:
# REST API works! Use it instead of WMI
use_rest_api = True
print(f"\n ✓✓✓ REST API WORKS! Using REST API instead of WMI ✓✓✓")
print(f" → Found {rest_count} sensors via REST API")
print(f" → This bypasses the WMI bug in LibreHardwareMonitor 0.9.5+")
print(f" → Make sure 'Remote Web Server' is enabled in LibreHardwareMonitor")
print(f" (Options → Remote Web Server → Run)")
return True, None, None
# REST API also failed - show comprehensive error with all options
error_msg = "WMI namespace accessible but contains 0 sensors!"
if rest_error:
error_msg += f"\nREST API also failed: {rest_error}"
return False, error_msg, (
"FIX: LibreHardwareMonitor driver is not providing sensor data.\n\n"
"SOLUTION (3 steps):\n\n"
"1. Enable REST API in LibreHardwareMonitor:\n"
" Options → Remote Web Server → Run (port 8085)\n\n"
"2. If that doesn't work, downgrade to 0.9.4:\n"
" https://github.com/LibreHardwareMonitor/LibreHardwareMonitor/releases\n\n"
"3. If still failing, check for conflicts:\n"