-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpc_stats_monitor_v2_linux.py
More file actions
1619 lines (1345 loc) · 56.5 KB
/
pc_stats_monitor_v2_linux.py
File metadata and controls
1619 lines (1345 loc) · 56.5 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 - Linux Edition
Dynamic Sensor Selection with GUI Configuration
Uses psutil for hardware sensor discovery
"""
import psutil
import socket
import time
import json
import os
import sys
import argparse
from datetime import datetime
# Tkinter is imported conditionally only when GUI mode is needed
# This allows the script to run on headless systems without tkinter
# Configuration file path
CONFIG_FILE = "monitor_config_linux.json"
# Default configuration
DEFAULT_CONFIG = {
"version": "2.0-linux",
"esp32_ip": "192.168.1.197",
"udp_port": 4210,
"update_interval": 3,
"metrics": []
}
# Maximum metrics supported by ESP32
MAX_METRICS = 20
# Global sensor database
sensor_database = {
"system": [], # psutil-based metrics (CPU%, RAM%, Disk%)
"temperature": [], # Hardware temperatures
"fan": [], # Fan speeds
"data": [], # Network data (total uploaded/downloaded)
"throughput": [], # Network throughput (current upload/download speed)
"other": []
}
# Network tracking for speed calculation
network_last_sample = {}
network_last_time = None
def discover_sensors():
"""
Discover all available sensors from psutil on Linux
"""
print("=" * 60)
print("PC STATS MONITOR v2.0 - LINUX EDITION - SENSOR DISCOVERY")
print("=" * 60)
# Add psutil system metrics
print("\n[1/3] Discovering system metrics (psutil)...")
# Warm up psutil for accurate readings
psutil.cpu_percent(interval=0.1)
sensor_database["system"].append({
"name": "CPU",
"display_name": "CPU Usage",
"source": "psutil",
"type": "percent",
"unit": "%",
"psutil_method": "cpu_percent",
"custom_label": "",
"current_value": int(psutil.cpu_percent(interval=0))
})
sensor_database["system"].append({
"name": "RAM",
"display_name": "RAM Usage",
"source": "psutil",
"type": "percent",
"unit": "%",
"psutil_method": "virtual_memory.percent",
"custom_label": "",
"current_value": int(psutil.virtual_memory().percent)
})
sensor_database["system"].append({
"name": "RAM_GB",
"display_name": "RAM Used (GB)",
"source": "psutil",
"type": "memory",
"unit": "GB",
"psutil_method": "virtual_memory.used",
"custom_label": "",
"current_value": int(psutil.virtual_memory().used / (1024**3))
})
sensor_database["system"].append({
"name": "DISK",
"display_name": "Disk / Usage",
"source": "psutil",
"type": "percent",
"unit": "%",
"psutil_method": "disk_usage",
"custom_label": "",
"current_value": int(psutil.disk_usage('/').percent)
})
print(f" Found {len(sensor_database['system'])} system metrics")
# Discover hardware sensors (temperatures)
print("\n[2/3] Discovering hardware sensors (temperatures & fans)...")
sensor_count = 0
try:
# Temperature sensors
if hasattr(psutil, "sensors_temperatures"):
temps = psutil.sensors_temperatures()
for sensor_name, entries in temps.items():
for entry in entries:
# Generate short name
short_name = generate_short_name_linux(entry.label, "temperature", sensor_name)
# Generate display name
display_name = f"{entry.label} [{sensor_name}]" if entry.label else f"Sensor [{sensor_name}]"
# Get current value
try:
current_value = int(entry.current) if entry.current else 0
except:
current_value = 0
sensor_info = {
"name": short_name,
"display_name": display_name,
"source": "psutil_temp",
"type": "temperature",
"unit": "C",
"sensor_key": sensor_name,
"sensor_label": entry.label,
"custom_label": "",
"current_value": current_value
}
sensor_database["temperature"].append(sensor_info)
sensor_count += 1
# Fan sensors
if hasattr(psutil, "sensors_fans"):
fans = psutil.sensors_fans()
for sensor_name, entries in fans.items():
for entry in entries:
# Generate short name
short_name = generate_short_name_linux(entry.label, "fan", sensor_name)
# Generate display name
display_name = f"{entry.label} [{sensor_name}]" if entry.label else f"Fan [{sensor_name}]"
# Get current value
try:
current_value = int(entry.current) if entry.current else 0
except:
current_value = 0
sensor_info = {
"name": short_name,
"display_name": display_name,
"source": "psutil_fan",
"type": "fan",
"unit": "RPM",
"sensor_key": sensor_name,
"sensor_label": entry.label,
"custom_label": "",
"current_value": current_value
}
sensor_database["fan"].append(sensor_info)
sensor_count += 1
print(f" Found {sensor_count} hardware sensors:")
print(f" - Temperatures: {len(sensor_database['temperature'])}")
print(f" - Fans: {len(sensor_database['fan'])}")
except Exception as e:
print(f" WARNING: Could not access hardware sensors: {e}")
# Discover network metrics
print("\n[3/3] Discovering network metrics...")
net_count = 0
try:
net_io = psutil.net_io_counters(pernic=True)
for interface, stats in net_io.items():
# Skip loopback
if interface == "lo":
continue
# Total Data Uploaded
sensor_database["data"].append({
"name": f"{interface[:7]}_U",
"display_name": f"Data Uploaded - {interface}",
"source": "psutil_net",
"type": "data",
"unit": "MB",
"interface": interface,
"metric": "bytes_sent",
"custom_label": "",
"current_value": int(stats.bytes_sent / (1024**2)) # MB
})
# Total Data Downloaded
sensor_database["data"].append({
"name": f"{interface[:7]}_D",
"display_name": f"Data Downloaded - {interface}",
"source": "psutil_net",
"type": "data",
"unit": "MB",
"interface": interface,
"metric": "bytes_recv",
"custom_label": "",
"current_value": int(stats.bytes_recv / (1024**2)) # MB
})
# Upload Speed (will be calculated dynamically)
sensor_database["throughput"].append({
"name": f"{interface[:7]}_U",
"display_name": f"Upload Speed - {interface}",
"source": "psutil_net_speed",
"type": "throughput",
"unit": "MB/s",
"interface": interface,
"metric": "bytes_sent",
"custom_label": "",
"current_value": 0 # Will be calculated
})
# Download Speed (will be calculated dynamically)
sensor_database["throughput"].append({
"name": f"{interface[:7]}_D",
"display_name": f"Download Speed - {interface}",
"source": "psutil_net_speed",
"type": "throughput",
"unit": "MB/s",
"interface": interface,
"metric": "bytes_recv",
"custom_label": "",
"current_value": 0 # Will be calculated
})
net_count += 4
print(f" Found {net_count} network metrics:")
print(f" - Data: {len(sensor_database['data'])}")
print(f" - Throughput: {len(sensor_database['throughput'])}")
except Exception as e:
print(f" WARNING: Could not access network stats: {e}")
print("\n" + "=" * 60)
print("\nℹ NOTE: Sensor values in GUI are static (captured at launch time)")
print(" This helps you identify active sensors and their typical readings.")
def generate_short_name_linux(label, sensor_type, sensor_key=""):
"""
Generate a short name (max 10 chars) for ESP32 display - Linux version
"""
# Start with label or sensor key
name = label if label else sensor_key
# Add prefixes based on sensor key
if sensor_type == "temperature":
if "coretemp" in sensor_key.lower():
if "package" in label.lower():
name = "CPU_PKG"
elif "core" in label.lower():
# Extract core number
import re
match = re.search(r'core (\d+)', label.lower())
if match:
name = f"CPU_C{match.group(1)}"
else:
name = "CPU_Temp"
else:
name = "CPU_Temp"
elif "k10temp" in sensor_key.lower():
name = "CPU_Tctl" if "tctl" in label.lower() else "CPU_Temp"
elif "nvidia" in sensor_key.lower() or "gpu" in sensor_key.lower():
name = "GPU_Temp"
elif "nvme" in sensor_key.lower():
name = "NVMe_Temp"
else:
name = label[:10] if label else "TEMP"
elif sensor_type == "fan":
if "fan" in label.lower():
import re
match = re.search(r'(\d+)', label)
if match:
name = f"FAN{match.group(1)}"
else:
name = "FAN"
else:
name = label[:10] if label else "FAN"
# Clean up
name = name.replace(" ", "_").replace("-", "_")
# Truncate if too long
if len(name) > 10:
name = name[:10]
return name if name else "SENSOR"
# ============================================================================
# CLI Helper Functions - Validation
# ============================================================================
def validate_ip(ip: str) -> str:
"""
Validate IPv4 address format
"""
if not ip:
raise ValueError("IP address cannot be empty")
parts = ip.split('.')
if len(parts) != 4:
raise ValueError("Invalid IP format (must be xxx.xxx.xxx.xxx)")
for part in parts:
try:
num = int(part)
if num < 0 or num > 255:
raise ValueError("IP octets must be 0-255")
except ValueError:
raise ValueError("IP octets must be numbers")
return ip
def validate_port(port_str: str) -> int:
"""
Validate UDP port number
"""
try:
port = int(port_str)
if port < 1 or port > 65535:
raise ValueError("Port must be between 1 and 65535")
return port
except ValueError:
raise ValueError("Port must be a valid number (1-65535)")
def validate_interval(interval_str: str) -> float:
"""
Validate update interval
"""
try:
interval = float(interval_str)
if interval < 0.5:
raise ValueError("Interval must be at least 0.5 seconds")
return interval
except ValueError:
raise ValueError("Interval must be a valid number (>= 0.5)")
# ============================================================================
# CLI Helper Functions - Input
# ============================================================================
def prompt_with_default(prompt: str, default: str, validator=None) -> str:
"""
Prompt user with a default value
Returns default if user presses Enter, otherwise validates and returns input
"""
while True:
try:
user_input = input(f"{prompt} [{default}]: ").strip()
# Use default if empty
if not user_input:
value = default
else:
value = user_input
# Validate if validator provided
if validator:
return str(validator(value))
else:
return value
except ValueError as e:
print(f" ✗ Error: {e}")
continue
except KeyboardInterrupt:
print("\n\nConfiguration cancelled.")
return None
def parse_number_list(input_str: str, max_num: int) -> list:
"""
Parse comma-separated list of numbers with validation
Returns list of integers or raises ValueError
"""
if not input_str.strip():
raise ValueError("Please enter at least one metric number")
# Split by comma and parse
numbers = []
for part in input_str.split(','):
try:
num = int(part.strip())
if num < 1 or num > max_num:
raise ValueError(f"Number {num} is out of range (1-{max_num})")
numbers.append(num)
except ValueError as e:
if "invalid literal" in str(e):
raise ValueError(f"'{part.strip()}' is not a valid number")
else:
raise
# Check for duplicates
if len(numbers) != len(set(numbers)):
raise ValueError("Duplicate numbers detected")
# Check max limit
if len(numbers) > MAX_METRICS:
raise ValueError(f"Too many metrics selected (max {MAX_METRICS})")
return numbers
def load_config():
"""
Load configuration from file
"""
if not os.path.exists(CONFIG_FILE):
return None
try:
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
print(f"\n✓ Loaded configuration from {CONFIG_FILE}")
print(f" Selected metrics: {len(config.get('metrics', []))}")
return config
except Exception as e:
print(f"\n✗ Error loading config: {e}")
return None
def save_config(config):
"""
Save configuration to file
"""
try:
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=2)
print(f"\n✓ Configuration saved to {CONFIG_FILE}")
return True
except Exception as e:
print(f"\n✗ Error saving config: {e}")
return False
def setup_autostart_systemd(enable=True):
"""
Setup systemd service for autostart on Linux
"""
import subprocess
service_name = "pc-monitor"
service_file = f"{service_name}.service"
user_service_dir = os.path.expanduser("~/.config/systemd/user")
service_path = os.path.join(user_service_dir, service_file)
script_path = os.path.abspath(__file__)
script_dir = os.path.dirname(script_path)
if enable:
# Create systemd user service directory if it doesn't exist
os.makedirs(user_service_dir, exist_ok=True)
# Generate service file content
service_content = f"""[Unit]
Description=PC Stats Monitor for ESP32
After=network.target
[Service]
Type=simple
WorkingDirectory={script_dir}
ExecStart={sys.executable} {script_path}
Restart=on-failure
RestartSec=10
[Install]
WantedBy=default.target
"""
try:
# Write service file
with open(service_path, 'w') as f:
f.write(service_content)
# Reload systemd daemon
subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
# Enable service
subprocess.run(["systemctl", "--user", "enable", service_name], check=True)
# Start service
subprocess.run(["systemctl", "--user", "start", service_name], check=True)
print(f"\n✓ Autostart enabled via systemd!")
print(f" Service file: {service_path}")
print(f" Service name: {service_name}")
print(f"\nUseful commands:")
print(f" Check status: systemctl --user status {service_name}")
print(f" View logs: journalctl --user -u {service_name} -f")
print(f" Stop service: systemctl --user stop {service_name}")
return True
except subprocess.CalledProcessError as e:
print(f"\n✗ Error setting up systemd service: {e}")
print(" Make sure systemd is available on your system")
return False
except Exception as e:
print(f"\n✗ Error: {e}")
return False
else:
# Disable autostart
try:
# Stop service
subprocess.run(["systemctl", "--user", "stop", service_name],
stderr=subprocess.DEVNULL)
# Disable service
subprocess.run(["systemctl", "--user", "disable", service_name],
stderr=subprocess.DEVNULL)
# Remove service file
if os.path.exists(service_path):
os.remove(service_path)
# Reload systemd daemon
subprocess.run(["systemctl", "--user", "daemon-reload"],
stderr=subprocess.DEVNULL)
print(f"\n✓ Autostart disabled!")
print(f" Service stopped and removed: {service_name}")
return True
except Exception as e:
print(f"\n✗ Error removing service: {e}")
return False
def check_autostart_status():
"""
Check if autostart is enabled
"""
import subprocess
service_name = "pc-monitor"
try:
result = subprocess.run(
["systemctl", "--user", "is-enabled", service_name],
capture_output=True,
text=True
)
return result.returncode == 0 and "enabled" in result.stdout.lower()
except:
return False
# ============================================================================
# GUI Configuration Mode (requires tkinter)
# ============================================================================
class MetricSelectorGUI:
"""
Tkinter GUI for selecting metrics and configuring settings - Linux version
Note: tkinter is imported when this class is instantiated (see main())
"""
def __init__(self, root, existing_config=None):
self.root = root
self.root.title("PC Monitor v2.0 - Linux Configuration")
self.root.geometry("1200x850")
self.root.resizable(False, False)
self.selected_metrics = []
self.checkboxes = []
self.label_entries = {}
# Load existing config if available
if existing_config:
self.config = existing_config
else:
self.config = DEFAULT_CONFIG.copy()
self.create_widgets()
# Load existing selections if editing
if existing_config and existing_config.get("metrics"):
self.load_existing_metrics(existing_config["metrics"])
def create_widgets(self):
# Title
title_frame = tk.Frame(self.root, bg="#1e1e1e", height=60)
title_frame.pack(fill=tk.X)
title_frame.pack_propagate(False)
title_label = tk.Label(
title_frame,
text="PC Monitor Configuration - Linux",
font=("Arial", 18, "bold"),
bg="#1e1e1e",
fg="#00d4ff"
)
title_label.pack(pady=15)
# Settings frame (ESP IP, Port, Interval)
settings_frame = tk.Frame(self.root, bg="#2d2d2d")
settings_frame.pack(fill=tk.X, padx=10, pady=5)
# ESP IP
tk.Label(settings_frame, text="ESP32 IP:", bg="#2d2d2d", fg="#ffffff", font=("Arial", 10)).grid(row=0, column=0, padx=10, pady=5, sticky="e")
self.ip_var = tk.StringVar(value=self.config.get("esp32_ip", "192.168.1.197"))
tk.Entry(settings_frame, textvariable=self.ip_var, width=20).grid(row=0, column=1, padx=5, pady=5, sticky="w")
# UDP Port
tk.Label(settings_frame, text="UDP Port:", bg="#2d2d2d", fg="#ffffff", font=("Arial", 10)).grid(row=0, column=2, padx=10, pady=5, sticky="e")
self.port_var = tk.StringVar(value=str(self.config.get("udp_port", 4210)))
tk.Entry(settings_frame, textvariable=self.port_var, width=10).grid(row=0, column=3, padx=5, pady=5, sticky="w")
# Update Interval
tk.Label(settings_frame, text="Update Interval (seconds):", bg="#2d2d2d", fg="#ffffff", font=("Arial", 10)).grid(row=0, column=4, padx=10, pady=5, sticky="e")
self.interval_var = tk.StringVar(value=str(self.config.get("update_interval", 3)))
tk.Entry(settings_frame, textvariable=self.interval_var, width=10).grid(row=0, column=5, padx=5, pady=5, sticky="w")
# Autostart section (second row)
tk.Label(settings_frame, text="Systemd Autostart:", bg="#2d2d2d", fg="#ffffff", font=("Arial", 10)).grid(row=1, column=0, padx=10, pady=5, sticky="e")
autostart_frame = tk.Frame(settings_frame, bg="#2d2d2d")
autostart_frame.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky="w")
self.autostart_status = tk.Label(
autostart_frame,
text=self.get_autostart_status_text(),
bg="#2d2d2d",
fg=self.get_autostart_status_color(),
font=("Arial", 10, "bold")
)
self.autostart_status.pack(side=tk.LEFT, padx=5)
enable_btn = tk.Button(
autostart_frame,
text="Enable",
command=self.enable_autostart,
bg="#00d4ff",
fg="#000000",
font=("Arial", 9),
relief=tk.FLAT,
padx=10,
pady=2
)
enable_btn.pack(side=tk.LEFT, padx=5)
disable_btn = tk.Button(
autostart_frame,
text="Disable",
command=self.disable_autostart,
bg="#ff6666",
fg="#000000",
font=("Arial", 9),
relief=tk.FLAT,
padx=10,
pady=2
)
disable_btn.pack(side=tk.LEFT, padx=5)
# Counter frame
counter_frame = tk.Frame(self.root, bg="#2d2d2d", height=50)
counter_frame.pack(fill=tk.X)
counter_frame.pack_propagate(False)
self.counter_label = tk.Label(
counter_frame,
text=f"Selected: 0/{MAX_METRICS}",
font=("Arial", 12),
bg="#2d2d2d",
fg="#ffffff"
)
self.counter_label.pack(side=tk.LEFT, padx=20, pady=10)
# Search box
search_label = tk.Label(counter_frame, text="Search:", bg="#2d2d2d", fg="#ffffff")
search_label.pack(side=tk.LEFT, padx=(50, 5))
self.search_var = tk.StringVar()
self.search_var.trace_add('write', lambda *_: self.on_search())
search_entry = tk.Entry(counter_frame, textvariable=self.search_var, width=20)
search_entry.pack(side=tk.LEFT, padx=5)
# Info note about static values
info_label = tk.Label(
counter_frame,
text="ℹ Values are static from GUI launch",
bg="#2d2d2d",
fg="#888888",
font=("Arial", 9, "italic")
)
info_label.pack(side=tk.LEFT, padx=(20, 0))
# Buttons
clear_btn = tk.Button(
counter_frame,
text="Clear All",
command=self.clear_all,
bg="#444444",
fg="#ffffff",
relief=tk.FLAT,
padx=10
)
clear_btn.pack(side=tk.RIGHT, padx=20)
# Main scrollable frame
main_frame = tk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
canvas = tk.Canvas(main_frame, bg="#ffffff")
scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
scrollable_frame = tk.Frame(canvas, bg="#ffffff")
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# Create checkboxes by category
row = 0
col = 0
categories = [
("SYSTEM METRICS", "system"),
("TEMPERATURES", "temperature"),
("FANS & COOLING", "fan"),
("NETWORK DATA", "data"),
("NETWORK THROUGHPUT", "throughput")
]
for cat_title, cat_key in categories:
if not sensor_database.get(cat_key):
continue
# Category header
cat_frame = tk.Frame(scrollable_frame, bg="#f0f0f0", relief=tk.RIDGE, borderwidth=2)
cat_frame.grid(row=row, column=col, sticky="nsew", padx=5, pady=5)
cat_label = tk.Label(
cat_frame,
text=cat_title,
font=("Arial", 11, "bold"),
bg="#f0f0f0",
fg="#333333"
)
cat_label.pack(pady=5)
# Sensors in category
for sensor in sensor_database[cat_key]:
var = tk.BooleanVar()
# Create sensor row frame
sensor_frame = tk.Frame(cat_frame, bg="#f0f0f0")
sensor_frame.pack(fill=tk.X, padx=10, pady=2)
# Checkbox with current value
value_text = f" - {sensor['current_value']}{sensor['unit']}" if sensor.get('current_value') is not None else ""
cb = tk.Checkbutton(
sensor_frame,
text=f"{sensor['display_name']} ({sensor['name']}){value_text}",
variable=var,
bg="#f0f0f0",
anchor="w",
command=lambda s=sensor, v=var: self.on_checkbox_toggle(s, v)
)
cb.pack(side=tk.TOP, fill=tk.X)
# Custom label entry (small, below checkbox)
label_frame = tk.Frame(sensor_frame, bg="#f0f0f0")
label_frame.pack(side=tk.TOP, fill=tk.X, padx=20)
tk.Label(label_frame, text="Label:", bg="#f0f0f0", fg="#666", font=("Arial", 8)).pack(side=tk.LEFT)
label_entry = tk.Entry(label_frame, width=15, font=("Arial", 8))
label_entry.pack(side=tk.LEFT, padx=5)
# Store reference to label entry
sensor_key = f"{sensor['source']}_{sensor['name']}"
self.label_entries[sensor_key] = label_entry
self.checkboxes.append((cb, sensor, var, sensor_frame))
col += 1
if col >= 3:
col = 0
row += 1
# Preview frame
preview_frame = tk.Frame(self.root, bg="#2d2d2d", height=80)
preview_frame.pack(fill=tk.X)
preview_frame.pack_propagate(False)
preview_label = tk.Label(
preview_frame,
text="SELECTED PREVIEW (names sent to ESP32):",
font=("Arial", 9, "bold"),
bg="#2d2d2d",
fg="#888888"
)
preview_label.pack(anchor="w", padx=10, pady=(10, 0))
self.preview_text = tk.Label(
preview_frame,
text="",
font=("Courier", 9),
bg="#2d2d2d",
fg="#00ff00",
anchor="w",
justify=tk.LEFT
)
self.preview_text.pack(fill=tk.X, padx=10, pady=(0, 10))
# Bottom buttons
button_frame = tk.Frame(self.root, bg="#1e1e1e", height=60)
button_frame.pack(fill=tk.X)
button_frame.pack_propagate(False)
cancel_btn = tk.Button(
button_frame,
text="Cancel",
command=self.root.quit,
bg="#666666",
fg="#ffffff",
font=("Arial", 12),
relief=tk.FLAT,
padx=20,
pady=5
)
cancel_btn.pack(side=tk.LEFT, padx=20, pady=10)
save_btn = tk.Button(
button_frame,
text="Save & Start Monitoring",
command=self.save_and_start,
bg="#00d4ff",
fg="#000000",
font=("Arial", 12, "bold"),
relief=tk.FLAT,
padx=20,
pady=5
)
save_btn.pack(side=tk.RIGHT, padx=20, pady=10)
# Update counter
self.update_counter()
def load_existing_metrics(self, metrics):
"""Load existing metric selections when editing config"""
for metric in metrics:
# Find matching sensor and check it
for cb, sensor, var, frame in self.checkboxes:
sensor_key = f"{sensor['source']}_{sensor['name']}"
metric_key = f"{metric['source']}_{metric['name']}"
if sensor_key == metric_key:
var.set(True)
self.selected_metrics.append(sensor)
# Set custom label if exists
if metric.get('custom_label') and sensor_key in self.label_entries:
self.label_entries[sensor_key].insert(0, metric['custom_label'])
break
self.update_counter()
def on_checkbox_toggle(self, sensor, var):
if var.get():
if len(self.selected_metrics) >= MAX_METRICS:
messagebox.showwarning(
"Limit Reached",
f"Maximum {MAX_METRICS} metrics allowed!\nDeselect some metrics first."
)
var.set(False)
return
self.selected_metrics.append(sensor)
else:
if sensor in self.selected_metrics:
self.selected_metrics.remove(sensor)
self.update_counter()
def update_counter(self):
count = len(self.selected_metrics)
self.counter_label.config(text=f"Selected: {count}/{MAX_METRICS}")
if count >= MAX_METRICS:
self.counter_label.config(fg="#ff6666")
else:
self.counter_label.config(fg="#ffffff")
# Update preview
preview = " | ".join([f"{i+1}. {m['name']}" for i, m in enumerate(self.selected_metrics[:MAX_METRICS])])
self.preview_text.config(text=preview if preview else "(none selected)")
def clear_all(self):
for cb, sensor, var, frame in self.checkboxes:
var.set(False)
self.selected_metrics.clear()
self.update_counter()
def on_search(self, *args):
search_term = self.search_var.get().lower()
for cb, sensor, var, frame in self.checkboxes:
if search_term in sensor['display_name'].lower() or search_term in sensor['name'].lower():
cb.config(bg="#ffffcc")
frame.config(bg="#ffffcc")
else:
cb.config(bg="#f0f0f0")
frame.config(bg="#f0f0f0")
def get_autostart_status_text(self):
"""Check if autostart is enabled"""
if check_autostart_status():
return "✓ Enabled"
else:
return "✗ Disabled"
def get_autostart_status_color(self):
"""Get color for autostart status"""
status = self.get_autostart_status_text()
if "Enabled" in status:
return "#00ff00"
elif "Disabled" in status:
return "#ff6666"
else:
return "#888888"
def update_autostart_status(self):
"""Update the autostart status label"""
self.autostart_status.config(
text=self.get_autostart_status_text(),
fg=self.get_autostart_status_color()
)
def enable_autostart(self):
"""Enable autostart via systemd"""
try:
success = setup_autostart_systemd(enable=True)
if success:
self.update_autostart_status()
messagebox.showinfo("Success", "Autostart enabled!\n\nThe service will start automatically on system boot.\n\nUseful commands:\n• Check status: systemctl --user status pc-monitor\n• View logs: journalctl --user -u pc-monitor -f")
else:
messagebox.showerror("Error", "Failed to enable autostart.\nCheck console for details.")
except Exception as e:
messagebox.showerror("Error", f"Failed to enable autostart:\n{str(e)}\n\nMake sure systemd is available on your system.")
def disable_autostart(self):
"""Disable autostart via systemd"""
try:
success = setup_autostart_systemd(enable=False)
if success:
self.update_autostart_status()
messagebox.showinfo("Success", "Autostart disabled!\n\nThe service has been stopped and removed.")
else:
messagebox.showwarning("Warning", "Could not disable autostart.\nCheck console for details.")
except Exception as e:
messagebox.showerror("Error", f"Failed to disable autostart:\n{str(e)}")
def save_and_start(self):
if len(self.selected_metrics) == 0:
messagebox.showwarning("No Selection", "Please select at least one metric!")
return
# Validate settings
try:
esp_ip = self.ip_var.get().strip()
udp_port = int(self.port_var.get())
update_interval = float(self.interval_var.get())
if not esp_ip:
raise ValueError("ESP32 IP cannot be empty")