forked from akadatalimited/liquidgui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.py
More file actions
executable file
·1277 lines (995 loc) · 42.9 KB
/
Copy pathmonitor.py
File metadata and controls
executable file
·1277 lines (995 loc) · 42.9 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
#!/usr/bin/env python3
#
# (C) 2024-2026 AKADATA LIMITED - Andrew Smalley
# Released under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""LiquidGUI runtime, sensor discovery, curve storage, and Tk interface."""
import argparse
import json
import math
import stat
import signal
import subprocess
import sys
import time
import tkinter as tk
from dataclasses import dataclass
from pathlib import Path
from tkinter import messagebox, ttk
HWMON_ROOT = Path("/sys/class/hwmon")
WATCH_FILES = ("liquidgui", "monitor.py")
REFRESH_SECONDS = 3
TEMP_MIN = 20
TEMP_MAX = 90
TEMP_HARD_MIN = 0
TEMP_HARD_MAX = 110
CONFIG_PATH = Path.home() / ".config" / "liquidgui_curves.json"
LEGACY_CONFIG_PATH = Path.home() / ".config" / "liquidctl_curves.json"
SUDO_PREFIX = ["sudo"]
@dataclass
class TempSensor:
"""A readable temperature sensor exposed through hwmon."""
chip: str
label: str
path: str
value_c: float | None
@dataclass
class FanSensor:
"""A readable fan RPM sensor exposed through hwmon."""
chip: str
label: str
path: str
rpm: int | None
@dataclass
class ControlChannel:
"""A writable control target backed by liquidctl or hwmon PWM."""
chip: str
label: str
kind: str
identifier: str
duty: int | None
min_duty: int = 0
max_duty: int = 100
@property
def key(self):
"""Return the persistent storage key for this control channel."""
return f"{self.kind}:{self.identifier}"
@dataclass
class CurveConfig:
"""Saved Bezier control points and enabled state for one control."""
points: list[tuple[int, int]]
enabled: bool = True
class LiquidGUIError(RuntimeError):
"""Application-level error raised for discovery or control failures."""
pass
def is_generic_hwmon_label(label):
"""Return True when a hwmon label is only a generic fan or pwm name."""
if not label:
return True
lowered = label.strip().lower()
return lowered.startswith("fan") or lowered.startswith("pwm")
def is_writable_hwmon_pwm(path):
"""Return True when a hwmon PWM node is writable by the driver."""
try:
mode = Path(path).stat().st_mode
except OSError:
return False
return bool(mode & stat.S_IWUSR)
def read_text(path):
"""Read a sysfs-style text file and return None on read failure."""
try:
return Path(path).read_text(encoding="utf-8").strip()
except OSError:
return None
def read_int(path):
"""Read an integer file and return None on missing or invalid content."""
text = read_text(path)
if text is None:
return None
try:
return int(text)
except ValueError:
return None
def celsius_from_millidegrees(value):
"""Convert a millidegree reading to a rounded Celsius float."""
if value is None:
return None
return round(value / 1000.0, 1)
def default_curve_for(control):
"""Return the default curve for a newly discovered control."""
base = [(30, 30), (40, 38), (50, 50), (60, 72), (72, 100)]
if "pump" in control.label.lower():
return [(30, 70), (40, 78), (50, 86), (60, 94), (72, 100)]
return base
def normalize_curve_points(points):
"""Clamp and normalize curve points into valid temperature and duty ranges."""
normalized = []
for point in points:
temp = int(point[0])
duty = int(point[1])
if normalized:
temp = max(normalized[-1][0], temp)
temp = max(TEMP_HARD_MIN, min(TEMP_HARD_MAX, temp))
duty = max(0, min(100, duty))
normalized.append((temp, duty))
return normalized
def cubic_bezier_point(p0, p1, p2, p3, t):
"""Sample a cubic Bezier segment at the normalized position ``t``."""
inv = 1.0 - t
inv2 = inv * inv
t2 = t * t
x = (
(inv2 * inv * p0[0])
+ (3.0 * inv2 * t * p1[0])
+ (3.0 * inv * t2 * p2[0])
+ (t2 * t * p3[0])
)
y = (
(inv2 * inv * p0[1])
+ (3.0 * inv2 * t * p1[1])
+ (3.0 * inv * t2 * p2[1])
+ (t2 * t * p3[1])
)
return (x, max(0.0, min(100.0, y)))
def bezier_curve_samples(points, samples_per_segment=32):
"""Sample a smooth interpolating Bezier path through the control points."""
if not points:
return []
if len(points) == 1:
return [tuple(points[0])]
samples = [tuple(points[0])]
for index in range(len(points) - 1):
p0 = points[index - 1] if index > 0 else points[index]
p1 = points[index]
p2 = points[index + 1]
p3 = points[index + 2] if index + 2 < len(points) else points[index + 1]
b0 = p1
b1 = (
p1[0] + ((p2[0] - p0[0]) / 6.0),
p1[1] + ((p2[1] - p0[1]) / 6.0),
)
b2 = (
p2[0] - ((p3[0] - p1[0]) / 6.0),
p2[1] - ((p3[1] - p1[1]) / 6.0),
)
b3 = p2
for step in range(1, samples_per_segment + 1):
t = step / samples_per_segment
samples.append(cubic_bezier_point(b0, b1, b2, b3, t))
return samples
def curve_samples(points):
"""Return sampled points for the rendered and evaluated control curve."""
return bezier_curve_samples(points)
def duty_from_curve(points, temp_c):
"""Evaluate the curve at the provided temperature and return duty percent."""
samples = curve_samples(points)
if not samples:
return 0
if temp_c <= samples[0][0]:
return int(round(samples[0][1]))
if temp_c >= samples[-1][0]:
return int(round(samples[-1][1]))
best = samples[-1][1]
for left, right in zip(samples, samples[1:]):
min_x = min(left[0], right[0])
max_x = max(left[0], right[0])
if min_x <= temp_c <= max_x:
span = right[0] - left[0]
if abs(span) < 1e-9:
best = max(left[1], right[1])
continue
ratio = (temp_c - left[0]) / span
duty = left[1] + ((right[1] - left[1]) * ratio)
return int(round(max(0, min(100, duty))))
return int(round(best))
class SensorBackend:
"""Discover sensors and apply control changes through liquidctl or hwmon."""
def discover(self):
"""Return the current snapshot of temperatures, fans, and controls."""
liquidctl = self._liquidctl_status()
snapshot = {
"temps": self._discover_temps(),
"fans": self._discover_fans(),
"controls": self._discover_controls(liquidctl),
"liquidctl": liquidctl,
}
snapshot["cpu_temp_c"] = self._pick_cpu_temp(snapshot["temps"])
return snapshot
def apply_control(self, control, duty_percent):
"""Apply a duty percentage to a single control channel."""
if control.kind == "liquidctl":
self._apply_liquidctl(control.identifier, duty_percent)
return
if control.kind == "hwmon":
self._apply_hwmon(control.identifier, duty_percent)
return
raise LiquidGUIError(f"Unsupported control kind: {control.kind}")
def _discover_temps(self):
"""Enumerate readable temperature sensors from hwmon."""
temps = []
for hwmon in sorted(HWMON_ROOT.glob("hwmon*")):
chip = read_text(hwmon / "name") or hwmon.name
for input_path in sorted(hwmon.glob("temp*_input")):
index = input_path.stem.split("_")[0][4:]
label = read_text(hwmon / f"temp{index}_label") or f"temp{index}"
value_c = celsius_from_millidegrees(read_int(input_path))
temps.append(TempSensor(chip=chip, label=label, path=str(input_path), value_c=value_c))
return temps
def _discover_fans(self):
"""Enumerate readable fan RPM sensors from hwmon."""
fans = []
for hwmon in sorted(HWMON_ROOT.glob("hwmon*")):
chip = read_text(hwmon / "name") or hwmon.name
for input_path in sorted(hwmon.glob("fan*_input")):
index = input_path.stem.split("_")[0][3:]
label = read_text(hwmon / f"fan{index}_label") or f"fan{index}"
fans.append(FanSensor(chip=chip, label=label, path=str(input_path), rpm=read_int(input_path)))
return fans
def _discover_controls(self, liquidctl):
"""Enumerate writable AIO and motherboard fan controls."""
controls = []
if liquidctl:
for channel in liquidctl["channels"]:
controls.append(
ControlChannel(
chip=liquidctl["device"],
label=channel["label"],
kind="liquidctl",
identifier=channel["name"],
duty=channel["duty"],
)
)
motherboard_index = 1
for hwmon in sorted(HWMON_ROOT.glob("hwmon*")):
chip = read_text(hwmon / "name") or hwmon.name
if chip == "kraken2023":
continue
for pwm_path in sorted(hwmon.glob("pwm[0-9]")):
if not is_writable_hwmon_pwm(pwm_path):
continue
suffix = pwm_path.name[3:]
fan_label = read_text(hwmon / f"fan{suffix}_label")
label = "" #f"{motherboard_index}"
if fan_label and not is_generic_hwmon_label(fan_label):
label = f"{label} ({fan_label})"
pwm_raw = read_int(pwm_path)
duty = None if pwm_raw is None else round((pwm_raw / 255.0) * 100)
controls.append(
ControlChannel(
chip=chip,
label=label,
kind="hwmon",
identifier=str(pwm_path),
duty=duty,
)
)
motherboard_index += 1
return controls
def _pick_cpu_temp(self, temps):
"""Choose the best CPU temperature source for curve evaluation."""
package_sensor = next(
(
sensor
for sensor in temps
if sensor.chip == "coretemp" and sensor.label.lower() == "package id 0"
),
None,
)
if package_sensor is not None:
return package_sensor.value_c
coretemp_sensor = next((sensor for sensor in temps if sensor.chip == "coretemp"), None)
if coretemp_sensor is not None:
return coretemp_sensor.value_c
return next((sensor.value_c for sensor in temps if sensor.value_c is not None), None)
def _liquidctl_status(self):
"""Read liquidctl status output and normalize it into channel data."""
try:
result = subprocess.run(
["liquidctl", "status"],
capture_output=True,
text=True,
check=False,
)
except FileNotFoundError:
return None
if result.returncode != 0:
return None
device = None
channels = []
telemetry = {}
for raw_line in result.stdout.splitlines():
line = raw_line.strip()
if not line:
continue
is_tree_line = line.startswith("├──") or line.startswith("└──")
if is_tree_line:
line = line[3:].strip()
elif device is None:
device = line
continue
parts = line.split()
if len(parts) < 3:
continue
name = " ".join(parts[:-2])
value = parts[-2]
unit = parts[-1]
try:
numeric = float(value)
except ValueError:
continue
key = name.lower()
telemetry[key] = {"value": numeric, "unit": unit}
if key == "fan duty":
channels.append({"name": "fan", "label": "AIO fan", "duty": round(numeric)})
if key == "pump duty":
channels.append({"name": "pump", "label": "AIO pump", "duty": round(numeric)})
if not device:
return None
return {"device": device, "channels": channels, "telemetry": telemetry}
def _apply_liquidctl(self, channel, duty_percent):
"""Apply a duty percentage to a liquidctl-backed control channel."""
result = subprocess.run(
SUDO_PREFIX + ["liquidctl", "set", channel, "speed", str(int(duty_percent))],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
return
detail = (result.stderr or result.stdout).strip()
if not detail:
detail = f"liquidctl exited with status {result.returncode}"
if "insufficient permissions" in detail.lower():
detail += "\nGrant device access with your existing udev rule or run the app with the privileges needed for liquidctl control."
raise LiquidGUIError(detail)
def _apply_hwmon(self, pwm_path, duty_percent):
"""Apply a duty percentage to a hwmon PWM control node."""
pwm = Path(pwm_path)
enable = pwm.with_name(f"{pwm.name}_enable")
raw_value = str(max(0, min(255, round((duty_percent / 100.0) * 255))))
try:
if enable.exists():
self._sudo_write_text(enable, "1\n")
self._sudo_write_text(pwm, f"{raw_value}\n")
except OSError as exc:
raise LiquidGUIError(str(exc)) from exc
def _sudo_write_text(self, path, value):
"""Write text to a privileged file path using ``sudo tee``."""
result = subprocess.run(
SUDO_PREFIX + ["tee", str(path)],
input=value,
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
detail = (result.stderr or result.stdout).strip()
if not detail:
detail = f"sudo tee exited with status {result.returncode}"
raise LiquidGUIError(detail)
class CurveStore:
"""Load, migrate, and persist per-control curve configuration."""
def __init__(self):
self.path = CONFIG_PATH
self.selected_key = None
self.auto_apply = False
self.curves = {}
self._load()
def _load(self):
"""Load the current curve store or migrate the legacy config format."""
data = None
if self.path.exists():
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
data = None
elif LEGACY_CONFIG_PATH.exists():
data = self._load_legacy()
if not data:
return
self.selected_key = data.get("selected_key")
self.auto_apply = bool(data.get("auto_apply", False))
curves = data.get("curves", {})
for key, item in curves.items():
points = item.get("points", [])
if points:
self.curves[key] = CurveConfig(
points=normalize_curve_points(points),
enabled=bool(item.get("enabled", True)),
)
def _load_legacy(self):
"""Translate the old liquidctl curve file into the new storage shape."""
try:
data = json.loads(LEGACY_CONFIG_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
curves = {}
fan_points = data.get("fan")
pump_points = data.get("pump")
if fan_points:
curves["liquidctl:fan"] = {"points": fan_points, "enabled": True}
if pump_points:
curves["liquidctl:pump"] = {"points": pump_points, "enabled": True}
return {
"selected_key": "liquidctl:fan" if fan_points else "liquidctl:pump",
"auto_apply": False,
"curves": curves,
}
def save(self):
"""Persist the current curve configuration to disk."""
self.path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"selected_key": self.selected_key,
"auto_apply": self.auto_apply,
"curves": {
key: {
"points": config.points,
"enabled": config.enabled,
}
for key, config in self.curves.items()
},
}
self.path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
def get_curve(self, control):
"""Return the saved curve for a control, creating a default if needed."""
config = self.curves.get(control.key)
if config is None:
config = CurveConfig(points=default_curve_for(control))
self.curves[control.key] = config
return config
class LiquidGUI:
"""Tk application for editing and applying Bezier fan curves."""
def __init__(self, root, backend):
self.root = root
self.backend = backend
self.snapshot = None
self.controls = {}
self.fan_map = {}
self.curves = CurveStore()
self.selected_key = None
self.drag_index = None
self.last_auto_apply_at = 0.0
self.auto_apply_var = tk.BooleanVar(value=self.curves.auto_apply)
self.info_var = tk.StringVar(value="")
self.cpu_var = tk.StringVar(value="CPU package: n/a")
self.status_text = None
self.status_columns = []
self.control_list = None
self.canvas = None
self.details_var = tk.StringVar(value="")
self.auto_status_var = tk.StringVar(value="Auto apply disabled\n")
self.pane_ratio = 0.34
self.pane_resize_after_id = None
self.root.title("LiquidGUI")
self.root.geometry("900x620")
self.root.minsize(760, 520)
self._build_ui()
self._refresh_loop()
self.root.protocol("WM_DELETE_WINDOW", self.close)
def _build_ui(self):
"""Create the application layout and bind the interactive widgets."""
self.root.grid_rowconfigure(1, weight=1)
self.root.grid_columnconfigure(0, weight=1)
header = ttk.Frame(self.root, padding=(10, 10, 10, 6))
header.grid(row=0, column=0, sticky="ew")
header.grid_columnconfigure(1, weight=1)
ttk.Label(header, textvariable=self.cpu_var, font=("TkDefaultFont", 12, "bold")).grid(row=0, column=0, sticky="w")
ttk.Checkbutton(
header,
text="Auto apply curves",
variable=self.auto_apply_var,
command=self._toggle_auto_apply,
).grid(row=0, column=1, sticky="e")
self.auto_status_label = ttk.Label(
header,
textvariable=self.auto_status_var,
justify=tk.LEFT,
anchor="w",
)
self.auto_status_label.grid(row=1, column=0, columnspan=2, sticky="w", pady=(4, 0))
main = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
main.grid(row=1, column=0, sticky="nsew", padx=10, pady=(0, 10))
left = ttk.Frame(main, padding=8, width=320)
left.grid_columnconfigure(0, weight=1)
left.grid_rowconfigure(1, weight=1)
main.add(left, weight=1)
ttk.Label(left, text="Detected controls").grid(row=0, column=0, sticky="w")
self.control_list = tk.Listbox(left, exportselection=False, height=10, width=34)
self.control_list.grid(row=1, column=0, sticky="nsew", pady=(6, 8))
self.control_list.bind("<<ListboxSelect>>", self._on_control_selected)
button_row = ttk.Frame(left)
button_row.grid(row=2, column=0, sticky="ew")
button_row.grid_columnconfigure(0, weight=1)
button_row.grid_columnconfigure(1, weight=1)
ttk.Button(button_row, text="Apply selected", command=self._apply_selected_curve).grid(row=0, column=0, sticky="ew", padx=(0, 4))
ttk.Button(button_row, text="Apply all", command=self._apply_all_curves).grid(row=0, column=1, sticky="ew", padx=(4, 0))
ttk.Button(left, text="Reset selected curve", command=self._reset_selected_curve).grid(row=3, column=0, sticky="ew", pady=(8, 0))
self.selected_enabled = tk.BooleanVar(value=True)
self.selected_enabled_button = ttk.Checkbutton(
left,
text="Selected curve enabled",
variable=self.selected_enabled,
command=self._toggle_selected_curve,
)
self.selected_enabled_button.grid(row=4, column=0, sticky="w", pady=(8, 0))
right = ttk.Frame(main, padding=8)
right.grid_rowconfigure(1, weight=1)
right.grid_columnconfigure(0, weight=1)
main.add(right, weight=2)
main.bind("<Configure>", lambda _event: self._schedule_pane_ratio(main))
self.root.after(150, lambda: self._apply_pane_ratio(main))
ttk.Label(right, textvariable=self.info_var, justify=tk.LEFT).grid(row=0, column=0, sticky="ew")
self.canvas = tk.Canvas(right, background="#101214", height=260, highlightthickness=0)
self.canvas.grid(row=1, column=0, sticky="nsew", pady=(8, 8))
self.canvas.bind("<Configure>", lambda _event: self._draw_curve())
self.canvas.bind("<ButtonPress-1>", self._on_canvas_press)
self.canvas.bind("<B1-Motion>", self._on_canvas_drag)
self.canvas.bind("<ButtonRelease-1>", self._on_canvas_release)
details = ttk.Label(right, textvariable=self.details_var, justify=tk.LEFT)
details.grid(row=2, column=0, sticky="ew")
status_frame = ttk.LabelFrame(self.root, text="Sensor summary", padding=8)
status_frame.grid(row=2, column=0, sticky="nsew", padx=10, pady=(0, 10))
status_frame.grid_rowconfigure(0, weight=1)
self.status_columns = []
for column in range(3):
status_frame.grid_columnconfigure(column, weight=1, uniform="status")
text = tk.Text(
status_frame,
height=10,
state=tk.DISABLED,
wrap=tk.NONE,
width=1,
font=("TkFixedFont", 9),
)
text.grid(
row=0,
column=column,
sticky="nsew",
padx=(0 if column == 0 else 6, 0),
)
self.status_columns.append(text)
def _schedule_pane_ratio(self, paned):
"""Debounce pane resize handling so the left/right split remains stable."""
if self.pane_resize_after_id is not None:
self.root.after_cancel(self.pane_resize_after_id)
self.pane_resize_after_id = self.root.after(
80,
lambda: self._apply_pane_ratio(paned),
)
def _apply_pane_ratio(self, paned):
"""Keep the PanedWindow split at the configured left/right ratio."""
self.pane_resize_after_id = None
paned.update_idletasks()
width = paned.winfo_width()
if width < 300:
return
paned.sashpos(0, int(width * self.pane_ratio))
def _refresh_loop(self):
"""Refresh sensor state and optionally auto-apply curves on a timer."""
try:
snapshot = self.backend.discover()
self.snapshot = snapshot
self._render(snapshot)
if self.auto_apply_var.get():
self._auto_apply_if_needed()
except Exception as exc:
self._set_status_text(f"Refresh failed:\n{exc}")
self.root.after(REFRESH_SECONDS * 1000, self._refresh_loop)
def _render(self, snapshot):
"""Render a fresh sensor/control snapshot into the UI."""
cpu = snapshot["cpu_temp_c"]
if cpu is None:
self.cpu_var.set("CPU package: n/a")
else:
self.cpu_var.set(f"CPU package: {cpu:.1f} C")
self.controls = {control.key: control for control in snapshot["controls"]}
self.fan_map = {f"{fan.chip}:{fan.label}": fan for fan in snapshot["fans"]}
self._sync_control_list()
self._render_status_text(snapshot)
self._update_editor_labels()
self._draw_curve()
def _sync_control_list(self):
"""Rebuild the control list while preserving the current selection."""
previous = self.selected_key or self.curves.selected_key
items = list(self.controls.values())
self.control_list.delete(0, tk.END)
for control in items:
current = "n/a" if control.duty is None else f"{control.duty}%"
enabled = "on" if self.curves.get_curve(control).enabled else "off"
self.control_list.insert(tk.END, f"{control.label} [{current}] curve {enabled}")
if not items:
self.selected_key = None
self.curves.selected_key = None
self.info_var.set("No writable fan or pump controls were detected.")
self.selected_enabled.set(False)
return
if previous not in self.controls:
previous = items[0].key
self.selected_key = previous
self.curves.selected_key = previous
self.curves.save()
for index, control in enumerate(items):
if control.key == previous:
self.control_list.selection_clear(0, tk.END)
self.control_list.selection_set(index)
self.control_list.see(index)
break
self.selected_enabled.set(self.curves.get_curve(self.controls[self.selected_key]).enabled)
def _render_status_text(self, snapshot):
"""Render the sensor summary panel across three columns."""
temp_lines = []
for sensor in snapshot["temps"]:
value = "n/a" if sensor.value_c is None else f"{sensor.value_c:.1f} C"
temp_lines.append(f"{sensor.chip}: {sensor.label} = {value}")
fan_lines = []
for sensor in snapshot["fans"]:
value = "n/a" if sensor.rpm is None else f"{sensor.rpm} RPM"
fan_lines.append(f"{sensor.chip}: {sensor.label} = {value}")
control_lines = []
for control in snapshot["controls"]:
value = "n/a" if control.duty is None else f"{control.duty}%"
control_lines.append(f"{control.chip}: {control.label} = {value}")
midpoint = (len(temp_lines) + 1) // 2
first_column = ["Temperatures"] + [f" {line}" for line in temp_lines[:midpoint]]
second_column = []
if temp_lines[midpoint:]:
second_column = ["Temperatures"] + [f" {line}" for line in temp_lines[midpoint:]]
third_column = ["Fans"] + [f" {line}" for line in fan_lines]
if control_lines:
third_column.extend(["", "Controls"])
third_column.extend(f" {line}" for line in control_lines)
if not any(control.kind == "hwmon" for control in snapshot["controls"]):
third_column.extend(["", "No motherboard PWM controls are currently exposed by hwmon on this machine."])
self._set_status_columns(
[
"\n".join(first_column),
"\n".join(second_column),
"\n".join(third_column),
]
)
def _selected_control(self):
"""Return the currently selected control channel, if any."""
if self.selected_key is None:
return None
return self.controls.get(self.selected_key)
def _selected_curve(self):
"""Return the curve configuration for the selected control."""
control = self._selected_control()
if control is None:
return None
return self.curves.get_curve(control)
def _toggle_auto_apply(self):
"""Persist and display the current auto-apply setting."""
self.curves.auto_apply = self.auto_apply_var.get()
self.curves.save()
self._set_auto_status("Auto apply enabled" if self.auto_apply_var.get() else "Auto apply disabled")
def _toggle_selected_curve(self):
"""Enable or disable the currently selected control curve."""
curve = self._selected_curve()
if curve is None:
return
curve.enabled = self.selected_enabled.get()
self.curves.save()
self._sync_control_list()
self._draw_curve()
def _on_control_selected(self, _event):
"""Update editor state when the selected control changes."""
selection = self.control_list.curselection()
if not selection:
return
control = list(self.controls.values())[selection[0]]
self.selected_key = control.key
self.curves.selected_key = control.key
self.selected_enabled.set(self.curves.get_curve(control).enabled)
self.curves.save()
self._update_editor_labels()
self._draw_curve()
def _reset_selected_curve(self):
"""Reset the selected curve back to its default control profile."""
control = self._selected_control()
if control is None:
return
config = self.curves.get_curve(control)
config.points = default_curve_for(control)
config.enabled = True
self.selected_enabled.set(True)
self.curves.save()
self._sync_control_list()
self._update_editor_labels()
self._draw_curve()
def _update_editor_labels(self):
"""Refresh the curve editor header and instructional text."""
control = self._selected_control()
curve = self._selected_curve()
if control is None or curve is None:
self.info_var.set("Select a control to edit its curve.")
self.details_var.set("")
return
cpu_temp = None if self.snapshot is None else self.snapshot.get("cpu_temp_c")
predicted = "n/a" if cpu_temp is None else f"{duty_from_curve(curve.points, cpu_temp)}%"
current = "n/a" if control.duty is None else f"{control.duty}%"
self.info_var.set(
f"{control.chip} / {control.label}\nCurrent duty: {current} Predicted at CPU temp: {predicted}"
)
self.details_var.set(
"Drag the orange points directly on the Bezier curve. Raising a point pushes later points up on the Y axis, and lowering a point on the right pulls earlier points down to match. Curves are saved automatically."
)
self._set_auto_status("Auto apply enabled" if self.auto_apply_var.get() else "Auto apply disabled")
def _curve_geometry(self):
"""Return the current canvas dimensions and drawing margins."""
width = max(self.canvas.winfo_width(), 320)
height = max(self.canvas.winfo_height(), 220)
margin = {"left": 46, "right": 18, "top": 18, "bottom": 32}
return width, height, margin
def _curve_temp_bounds(self):
"""Return the active temperature range for the selected curve."""
curve = self._selected_curve()
if curve is None or not curve.points:
return TEMP_MIN, TEMP_MAX
start = curve.points[0][0]
end = curve.points[-1][0]
if end - start < 10:
end = start + 10
return start, end
def _point_to_canvas(self, temp, duty):
"""Convert a curve-space point into canvas coordinates."""
width, height, margin = self._curve_geometry()
start, end = self._curve_temp_bounds()
usable_width = width - margin["left"] - margin["right"]
usable_height = height - margin["top"] - margin["bottom"]
x = margin["left"] + ((temp - start) / (end - start)) * usable_width
y = margin["top"] + ((100 - duty) / 100.0) * usable_height
return x, y
def _canvas_to_point(self, x, y):
"""Convert canvas coordinates back into curve-space values."""
width, height, margin = self._curve_geometry()
start, end = self._curve_temp_bounds()
usable_width = width - margin["left"] - margin["right"]
usable_height = height - margin["top"] - margin["bottom"]
temp = start + ((x - margin["left"]) / usable_width) * (end - start)
duty = 100 - (((y - margin["top"]) / usable_height) * 100)
return int(round(temp)), int(round(duty))
def _draw_curve(self):
"""Redraw the current Bezier curve, grid, and draggable control points."""
self.canvas.delete("all")
curve = self._selected_curve()
if curve is None:
self.canvas.create_text(20, 20, anchor="nw", fill="#f0f0f0", text="No control selected")
return
width, height, margin = self._curve_geometry()
right = width - margin["right"]
bottom = height - margin["bottom"]
start, end = self._curve_temp_bounds()
temp_step = max(2, int(round((end - start) / 5)))
for temp in range(start, end + 1, temp_step):
x, _y = self._point_to_canvas(temp, 0)
self.canvas.create_line(x, margin["top"], x, bottom, fill="#24272d")
self.canvas.create_text(x, bottom + 14, text=str(temp), fill="#c5c8cf", font=("TkDefaultFont", 8))
for duty in range(0, 101, 20):
_x, y = self._point_to_canvas(TEMP_MIN, duty)
self.canvas.create_line(margin["left"], y, right, y, fill="#24272d")
self.canvas.create_text(margin["left"] - 20, y, text=str(duty), fill="#c5c8cf", font=("TkDefaultFont", 8))
self.canvas.create_rectangle(margin["left"], margin["top"], right, bottom, outline="#626a76")
curve_points = []
for temp, duty in curve_samples(curve.points):