Repository navigation
Expand file tree
/
Copy pathSerialGUI.py
More file actions
958 lines (840 loc) · 39.4 KB
/
Copy pathSerialGUI.py
File metadata and controls
958 lines (840 loc) · 39.4 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
import ctypes
import math
import queue
import threading
import time
import tkinter as tk
from collections import deque
from datetime import datetime
from tkinter import ttk, scrolledtext, messagebox, font as tkfont
import serial
import serial.tools.list_ports
# ==================== DPI Awareness ====================
try:
ctypes.windll.user32.SetProcessDpiAwarenessContext(-4) # PER_MONITOR_AWARE_V2
except Exception:
pass
try:
from hidpi_tk import DPIAwareTk
except ImportError:
DPIAwareTk = tk.Tk
# ==================== matplotlib (optional) ====================
CHART_OK = True
CHART_ERROR = ''
try:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
matplotlib.rcParams['font.sans-serif'] = ['Segoe UI', 'Arial', 'DejaVu Sans']
matplotlib.rcParams['axes.unicode_minus'] = False
except Exception as exc: # noqa: BLE001
CHART_OK = False
CHART_ERROR = str(exc)
# ==================== Protocol Definitions ====================
HEADER1 = 0xAA
HEADER2 = 0x55
CMD_SET_DUTY = 0x01
CMD_QUERY_TEMP = 0x02
CMD_QUERY_DUTY = 0x03
CMD_QUERY_LED = 0x04
CMD_QUERY_FAN = 0x05
CMD_MORSE = 0x06
CMD_SET_FAN_MODE = 0x07
CMD_SET_TEMP_TH = 0x08
CMD_QUERY_TEMP_TH = 0x09
CMD_REPORT_TEMP = 0x81
CMD_RESP_TEMP = 0x82
CMD_RESP_DUTY = 0x83
CMD_RESP_LED = 0x84
CMD_RESP_FAN = 0x85
CMD_RESP_TEMP_TH = 0x86
DATA_LEN = {
CMD_SET_DUTY: 2,
CMD_QUERY_TEMP: 0,
CMD_QUERY_DUTY: 0,
CMD_QUERY_LED: 0,
CMD_QUERY_FAN: 0,
CMD_SET_FAN_MODE: 1,
CMD_SET_TEMP_TH: 4,
CMD_QUERY_TEMP_TH: 0,
CMD_REPORT_TEMP: 4,
CMD_RESP_TEMP: 2,
CMD_RESP_DUTY: 2,
CMD_RESP_LED: 4,
CMD_RESP_FAN: 3,
CMD_RESP_TEMP_TH: 4,
}
# 灯效模式(与固件 LedMode_t 对应)
LED_MODE_NAMES = ('solid', 'blink', 'breathe', 'temp', 'marquee')
LED_COLORS = ('red', 'blue', 'yellow')
LED_COLOR_RGB = {'red': '#e04040', 'blue': '#4060e0', 'yellow': '#e0c040'}
SHOW_LED_CANVAS = False # 三灯图形化动画(按要求停用;想恢复改成 True 即可)
SHOW_MCU_AUTO = False # GUI 上的 MCU 温控开关(按要求隐藏;固件 0x07 命令仍可用)
LED_ANIM_PERIOD_MS = 50
LED_BREATH_STEPS = 100 # 一个完整呼吸 100 步(与固件呼吸表一致)
LED_BREATH_STEP_MS = 20
MORSE_TEXT_MAX = 16
def build_frame(cmd: int, data: bytes = b'') -> bytes:
"""Build a HEX frame with header and XOR checksum."""
frame = bytearray([HEADER1, HEADER2, cmd])
frame.extend(data)
checksum = cmd
for b in data:
checksum ^= b
frame.append(checksum)
return bytes(frame)
def parse_frames(buf: bytes) -> tuple[list[bytes], bytes]:
"""Parse all complete frames from the byte stream.
Returns a tuple of (list of complete frames, remaining buffer).
"""
frames: list[bytes] = []
while True:
idx = buf.find(bytes([HEADER1, HEADER2]))
if idx < 0:
return frames, buf[-1:] if len(buf) > 0 else b''
if idx > 0:
buf = buf[idx:]
if len(buf) < 4:
return frames, buf
cmd = buf[2]
if cmd not in DATA_LEN:
buf = buf[2:]
continue
total = 3 + DATA_LEN[cmd] + 1
if len(buf) < total:
return frames, buf
frame = buf[:total]
checksum = cmd
for i in range(3, 3 + DATA_LEN[cmd]):
checksum ^= frame[i]
if checksum == frame[-1]:
frames.append(frame)
buf = buf[total:]
else:
buf = buf[2:]
def frame_to_hex(frame: bytes) -> str:
"""Convert a byte frame to an uppercase hex string."""
return ' '.join(f'{b:02X}' for b in frame)
# ==================== GUI Application ====================
class SerialApp:
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.root.title("STM32 Fan Controller & Temperature Monitor")
self._setup_window()
self._setup_fonts()
self._setup_ttk_styles()
self.ser: serial.Serial | None = None
self.rx_buf = b''
self.rx_queue: queue.Queue = queue.Queue()
self.rx_thread: threading.Thread | None = None
self.running = False
self.temp_history: deque[tuple[float, float]] = deque(maxlen=600)
self.duty_history: deque[tuple[float, float]] = deque(maxlen=600)
self.t0 = time.time()
self.rx_count = 0
self.tx_count = 0
self.last_rx_time: datetime | None = None
self.last_temp: float | None = None
self.last_auto_duty: int | None = None
# 夜灯状态(0x84)与三灯动画
self.lamp = {'mode': 0, 'color': 0, 'flags': 0x01, 'phase': 0xFF}
self.lamp_anim_t0 = time.time()
self.lamp_anim_step = 0
# 温度显示阈值(0x86),默认与固件一致
self.th_yellow = 25.0
self.th_blue = 40.0
# MCU 温控风扇(0x85)
self.mcu_fan_mode = 0
self.mcu_fan_target = 0
self._build_ui()
self._refresh_ports()
self._update_chart()
self.root.after(30, self._poll_rx)
self.root.after(1000, self._update_clock)
if SHOW_LED_CANVAS:
self.root.after(LED_ANIM_PERIOD_MS, self._update_led_canvas)
# ---------- Window Setup ----------
def _setup_window(self) -> None:
"""Center the window and set it to 85% of the screen size."""
self.root.update_idletasks()
sw = self.root.winfo_screenwidth()
sh = self.root.winfo_screenheight()
win_w = int(sw * 0.85)
win_h = int(sh * 0.85)
x = (sw - win_w) // 2
y = (sh - win_h) // 2
self.root.geometry(f"{win_w}x{win_h}+{x}+{y}")
self.root.minsize(int(sw * 0.55), int(sh * 0.55))
# ---------- Fonts ----------
def _setup_fonts(self) -> None:
"""Configure default named fonts."""
for name in ('TkDefaultFont', 'TkTextFont', 'TkMenuFont',
'TkHeadingFont', 'TkTooltipFont'):
try:
f = tkfont.nametofont(name)
f.configure(family='Segoe UI', size=10)
except Exception:
pass
try:
f = tkfont.nametofont('TkFixedFont')
f.configure(family='Consolas', size=10)
except Exception:
pass
# ---------- ttk Styles ----------
def _setup_ttk_styles(self) -> None:
"""Use the clam theme to avoid blurriness on high-DPI displays."""
style = ttk.Style()
style.theme_use('clam')
base = ('Segoe UI', 10)
bold = ('Segoe UI', 10, 'bold')
style.configure('.', font=base)
style.configure('TButton', font=base, padding=4)
style.configure('TCombobox', font=base, padding=3)
style.configure('TEntry', font=base, padding=3)
style.configure('TLabel', font=base)
style.configure('TCheckbutton', font=base)
style.configure('TLabelframe', borderwidth=1, relief='solid')
style.configure('TLabelframe.Label', font=bold, foreground='#333333')
style.configure('TSeparator', background='#c8c8c8')
style.map('TButton',
background=[('active', '#e5f1fb'), ('pressed', '#cce4f7')])
# ---------- UI Construction ----------
def _build_ui(self) -> None:
# ===== Top: Serial Connection =====
top = ttk.LabelFrame(self.root, text="Serial Connection", padding=8)
top.pack(fill='x', padx=10, pady=6)
ttk.Label(top, text="Port:").pack(side='left')
self.port_var = tk.StringVar()
self.port_combo = ttk.Combobox(top, textvariable=self.port_var,
width=20, state='readonly')
self.port_combo.pack(side='left', padx=5)
ttk.Label(top, text="Baud Rate:").pack(side='left', padx=(15, 0))
self.baud_var = tk.StringVar(value='115200')
ttk.Combobox(top, textvariable=self.baud_var, width=10, state='readonly',
values=['9600', '19200', '38400', '57600',
'115200', '230400', '460800']
).pack(side='left', padx=5)
ttk.Button(top, text="Refresh",
command=self._refresh_ports).pack(side='left', padx=5)
self.btn_open = ttk.Button(top, text="Open Port",
command=self._toggle_serial)
self.btn_open.pack(side='left', padx=5)
self.lbl_status = ttk.Label(top, text="Disconnected", foreground='red')
self.lbl_status.pack(side='left', padx=15)
# ===== Main Area =====
main = ttk.Frame(self.root)
main.pack(fill='both', expand=True, padx=10, pady=6)
# ---- Left: Commands ----
left = ttk.LabelFrame(main, text="Commands", padding=8)
left.pack(side='left', fill='y', padx=(0, 6))
btn_w = 22
ttk.Button(left, text="Set Duty 50%", width=btn_w,
command=lambda: self._send_preset('duty50')).pack(pady=3)
ttk.Button(left, text="Set Duty 100%", width=btn_w,
command=lambda: self._send_preset('duty100')).pack(pady=3)
ttk.Button(left, text="Stop Fan (0%)", width=btn_w,
command=lambda: self._send_preset('duty0')).pack(pady=3)
ttk.Separator(left, orient='horizontal').pack(fill='x', pady=8)
ttk.Button(left, text="Query Temperature", width=btn_w,
command=lambda: self._send_preset('query_temp')).pack(pady=3)
ttk.Button(left, text="Query Duty Cycle", width=btn_w,
command=lambda: self._send_preset('query_duty')).pack(pady=3)
ttk.Button(left, text="Query Lamp State", width=btn_w,
command=lambda: self._send_preset('query_led')).pack(pady=3)
ttk.Separator(left, orient='horizontal').pack(fill='x', pady=8)
ttk.Label(left, text="Manual HEX Send:").pack(anchor='w')
self.manual_entry = ttk.Entry(left, width=24)
self.manual_entry.pack(pady=3)
self.manual_entry.insert(0, 'AA 55 02 02')
ttk.Button(left, text="Send", width=btn_w,
command=self._send_manual).pack(pady=3)
ttk.Separator(left, orient='horizontal').pack(fill='x', pady=8)
ttk.Label(left, text="Morse Text (blink on LEDs):").pack(anchor='w')
self.morse_entry = ttk.Entry(left, width=24)
self.morse_entry.insert(0, 'HRT')
self.morse_entry.pack(pady=3)
ttk.Button(left, text="Send Morse", width=btn_w,
command=self._send_morse).pack(pady=3)
ttk.Separator(left, orient='horizontal').pack(fill='x', pady=8)
ttk.Button(left, text="Clear Log & Chart", width=btn_w,
command=self._clear_all).pack(pady=3)
ttk.Button(left, text="Save Log", width=btn_w,
command=self._save_log).pack(pady=3)
# ---- Right: Values + Chart + Log ----
right = ttk.Frame(main)
right.pack(side='left', fill='both', expand=True)
# Live values
info = ttk.LabelFrame(right, text="Live Values", padding=8)
info.pack(fill='x', pady=(0, 6))
ttk.Label(info, text="Temperature:",
font=('Segoe UI', 11, 'bold')).pack(side='left', padx=5)
self.lbl_temp = ttk.Label(info, text="--.- °C",
font=('Segoe UI', 18, 'bold'),
foreground='blue')
self.lbl_temp.pack(side='left', padx=5)
ttk.Label(info, text="Duty Cycle:",
font=('Segoe UI', 11, 'bold')).pack(side='left', padx=(30, 5))
self.lbl_duty = ttk.Label(info, text="-- %",
font=('Segoe UI', 18, 'bold'),
foreground='green')
self.lbl_duty.pack(side='left', padx=5)
ttk.Label(info, text="Auto Target:",
font=('Segoe UI', 11, 'bold')).pack(side='left', padx=(30, 5))
self.lbl_target = ttk.Label(info, text="off",
font=('Segoe UI', 18, 'bold'),
foreground='purple')
self.lbl_target.pack(side='left', padx=5)
# MCU 端温度闭环的显示/开关(按要求默认隐藏)
if SHOW_MCU_AUTO:
ttk.Label(info, text="MCU Fan:",
font=('Segoe UI', 11, 'bold')).pack(side='left', padx=(30, 5))
self.lbl_mcu_fan = ttk.Label(info, text="manual",
font=('Segoe UI', 14, 'bold'),
foreground='#555555')
self.lbl_mcu_fan.pack(side='left', padx=5)
# ---- Night Lamp:状态 + 温度显示阈值 ----
lamp = ttk.LabelFrame(right, text="Night Lamp (Task A)", padding=8)
lamp.pack(fill='x', pady=(0, 6))
# 三灯图形化动画已按要求停用(想恢复:SHOW_LED_CANVAS 改 True)
if SHOW_LED_CANVAS:
self.led_canvas = tk.Canvas(lamp, width=210, height=64, bg='#1e1e1e',
highlightthickness=1, highlightbackground='#666666')
self.led_canvas.pack(side='left', padx=(0, 12))
ttk.Label(lamp, text="State:", font=('Segoe UI', 11, 'bold')).pack(side='left')
self.lbl_lamp = ttk.Label(lamp, text="--", font=('Segoe UI', 13, 'bold'),
foreground='#b8860b')
self.lbl_lamp.pack(side='left', padx=(5, 20))
ttk.Label(lamp, text="Temp LED:", font=('Segoe UI', 10, 'bold')).pack(side='left')
ttk.Label(lamp, text="yellow ≤").pack(side='left', padx=(8, 2))
self.ent_th_yellow = ttk.Entry(lamp, width=5)
self.ent_th_yellow.insert(0, '25')
self.ent_th_yellow.pack(side='left')
ttk.Label(lamp, text="°C blue ≤").pack(side='left', padx=(2, 2))
self.ent_th_blue = ttk.Entry(lamp, width=5)
self.ent_th_blue.insert(0, '40')
self.ent_th_blue.pack(side='left')
ttk.Label(lamp, text="°C").pack(side='left', padx=(2, 8))
ttk.Button(lamp, text="Apply", width=7,
command=self._send_temp_thresholds).pack(side='left', padx=2)
ttk.Button(lamp, text="Query", width=7,
command=self._query_temp_thresholds).pack(side='left', padx=2)
# ---- Auto mapping panel ----
auto = ttk.LabelFrame(right, text="Auto Mapping (Temperature -> Duty)", padding=8)
auto.pack(fill='x', pady=(0, 6))
self.auto_enabled = tk.BooleanVar(value=False)
ttk.Checkbutton(auto, text="Enable Auto", variable=self.auto_enabled,
command=self._on_auto_toggle).pack(side='left', padx=(0, 15))
ttk.Label(auto, text="Temp low:").pack(side='left')
self.ent_t_low = ttk.Entry(auto, width=6)
self.ent_t_low.insert(0, '25')
self.ent_t_low.pack(side='left', padx=(3, 0))
ttk.Label(auto, text="°C").pack(side='left', padx=(2, 12))
ttk.Label(auto, text="Duty low:").pack(side='left')
self.ent_d_low = ttk.Entry(auto, width=5)
self.ent_d_low.insert(0, '30')
self.ent_d_low.pack(side='left', padx=(3, 0))
ttk.Label(auto, text="%").pack(side='left', padx=(2, 12))
ttk.Label(auto, text="Temp high:").pack(side='left')
self.ent_t_high = ttk.Entry(auto, width=6)
self.ent_t_high.insert(0, '60')
self.ent_t_high.pack(side='left', padx=(3, 0))
ttk.Label(auto, text="°C").pack(side='left', padx=(2, 12))
ttk.Label(auto, text="Duty high:").pack(side='left')
self.ent_d_high = ttk.Entry(auto, width=5)
self.ent_d_high.insert(0, '100')
self.ent_d_high.pack(side='left', padx=(3, 0))
ttk.Label(auto, text="%").pack(side='left', padx=(2, 12))
ttk.Label(auto,
text="(below low temp -> low duty, above high temp -> high duty)",
foreground='gray').pack(side='left', padx=10)
# 第二行:MCU 端温度闭环(与上面的 GUI 映射互斥;按要求默认隐藏)
self.mcu_auto_enabled = tk.BooleanVar(value=False)
if SHOW_MCU_AUTO:
auto_row2 = ttk.Frame(auto)
auto_row2.pack(fill='x', pady=(6, 0))
ttk.Checkbutton(auto_row2, text="MCU Auto Fan (temperature closed-loop on board)",
variable=self.mcu_auto_enabled,
command=self._on_mcu_auto_toggle).pack(side='left')
ttk.Label(auto_row2, text="30℃ 以下停转 / 30~60℃ 线性 30%~100% / 60℃ 以上满速",
foreground='gray').pack(side='left', padx=10)
# Chart area
chart_frame = ttk.LabelFrame(right,
text="Real-time Curves (Last 30 seconds)",
padding=4)
chart_frame.pack(fill='both', expand=True, pady=(0, 6))
self.chart_ok = CHART_OK
self.canvas = None
if self.chart_ok:
try:
screen_dpi = self.root.winfo_fpixels('1i')
except Exception:
screen_dpi = 96
self.fig = Figure(figsize=(10, 3), dpi=screen_dpi)
self.ax_temp = self.fig.add_subplot(131)
self.ax_duty = self.fig.add_subplot(132)
self.ax_map = self.fig.add_subplot(133)
self.canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
self.canvas.get_tk_widget().pack(fill='both', expand=True)
else:
ttk.Label(chart_frame,
text=f"matplotlib unavailable: {CHART_ERROR}",
foreground='red').pack(expand=True)
# Log area
log_frame = ttk.LabelFrame(right, text="Communication Log", padding=4)
log_frame.pack(fill='both', expand=True)
self.log = scrolledtext.ScrolledText(log_frame, height=10,
font=('Consolas', 10))
self.log.pack(fill='both', expand=True)
self.log.tag_config('tx', foreground='blue')
self.log.tag_config('rx', foreground='green')
self.log.tag_config('err', foreground='red')
self.log.tag_config('info', foreground='gray')
self.log.tag_config('auto', foreground='purple')
# Status bar
self.statusbar = ttk.Label(self.root, text="Ready",
anchor='w', relief='sunken')
self.statusbar.pack(fill='x', side='bottom')
# ---------- Serial Operations ----------
def _refresh_ports(self) -> None:
ports = [p.device for p in serial.tools.list_ports.comports()]
self.port_combo['values'] = ports
if ports and not self.port_var.get():
self.port_var.set(ports[0])
self._log(f"Found {len(ports)} serial port(s): {', '.join(ports)}", 'info')
def _toggle_serial(self) -> None:
if self.ser and self.ser.is_open:
self._close_serial()
else:
self._open_serial()
def _open_serial(self) -> None:
port = self.port_var.get()
if not port:
messagebox.showwarning("Warning", "Please select a serial port first.")
return
try:
self.ser = serial.Serial(port, int(self.baud_var.get()), timeout=0.1)
self.running = True
self.rx_thread = threading.Thread(target=self._rx_loop, daemon=True)
self.rx_thread.start()
self.btn_open.config(text="Close Port")
self.lbl_status.config(text=f"Connected: {port}", foreground='green')
self._log(f"Opened {port} @ {self.baud_var.get()}", 'info')
# 连接后同步一次板子状态(灯效 / 温度阈值 / 风扇模式)
sync_cmds = [CMD_QUERY_LED, CMD_QUERY_TEMP_TH]
if SHOW_MCU_AUTO:
sync_cmds.append(CMD_QUERY_FAN)
for cmd in sync_cmds:
self.ser.write(build_frame(cmd))
except Exception as e:
messagebox.showerror("Error", f"Failed to open port: {e}")
self._log(f"Failed to open port: {e}", 'err')
def _close_serial(self) -> None:
self.running = False
if self.ser:
try:
self.ser.close()
except Exception:
pass
self.ser = None
if self.rx_thread and self.rx_thread.is_alive():
self.rx_thread.join(timeout=0.5)
self.rx_thread = None
self.btn_open.config(text="Open Port")
self.lbl_status.config(text="Disconnected", foreground='red')
self._log("Serial port closed", 'info')
# ---------- RX path: worker thread only pushes bytes into a queue ----------
def _rx_loop(self) -> None:
while self.running and self.ser and self.ser.is_open:
try:
data = self.ser.read(256)
except Exception as e:
if self.running:
self.rx_queue.put(('err', f"RX error: {e}"))
break
if data:
self.rx_queue.put(('data', bytes(data)))
def _poll_rx(self) -> None:
"""Runs on the Tk main thread: drain the queue and refresh the UI."""
try:
while True:
kind, payload = self.rx_queue.get_nowait()
if kind == 'err':
self._log(payload, 'err')
elif kind == 'data':
# rx_buf 必须保持 bytes:parse_frames 返回的剩余缓冲也是 bytes
frames, self.rx_buf = parse_frames(self.rx_buf + payload)
for f in frames:
self._handle_frame(f)
except queue.Empty:
pass
finally:
self.root.after(30, self._poll_rx)
def _handle_frame(self, frame: bytes) -> None:
try:
cmd = frame[2]
now = time.time() - self.t0
self.rx_count += 1
self.last_rx_time = datetime.now()
if cmd in (CMD_REPORT_TEMP, CMD_RESP_TEMP):
temp_raw = (frame[3] << 8) | frame[4]
if temp_raw & 0x8000:
temp_raw -= 0x10000
temp = temp_raw / 10.0
self.last_temp = temp
self.lbl_temp.config(text=f"{temp:.1f} °C")
self.temp_history.append((now, temp))
extra = ""
if cmd == CMD_REPORT_TEMP:
duty_raw = (frame[5] << 8) | frame[6]
duty_pct = duty_raw * 100.0 / 65535
self.lbl_duty.config(text=f"{duty_pct:.1f} %")
self.duty_history.append((now, duty_pct))
extra = f" PWM={duty_pct:.1f}%"
self._log(f"RX: {frame_to_hex(frame)} -> Temp={temp:.1f}°C{extra}", 'rx')
self._apply_auto_mapping(temp)
elif cmd == CMD_RESP_DUTY:
duty_raw = (frame[3] << 8) | frame[4]
duty_pct = duty_raw * 100.0 / 65535
self.lbl_duty.config(text=f"{duty_pct:.1f} %")
self.duty_history.append((now, duty_pct))
self._log(f"RX: {frame_to_hex(frame)} -> Duty={duty_pct:.1f}%", 'rx')
elif cmd == CMD_RESP_LED:
mode, color, flags, phase = frame[3], frame[4], frame[5], frame[6]
self.lamp.update(mode=mode, color=color, flags=flags, phase=phase)
self.lamp_anim_t0 = time.time() # 与板子重新对齐动画相位
if mode == 2 and phase != 0xFF:
self.lamp_anim_t0 -= (phase % 4) * 2.0 # 相位已知时直接跳到对应段
mode_s = LED_MODE_NAMES[mode] if mode < len(LED_MODE_NAMES) else f'mode{mode}'
color_s = LED_COLORS[color] if color < 3 else f'color{color}'
if mode == 2:
phase_s = ('red', 'blue', 'yellow', 'all')[phase] if phase < 4 else '?'
state_s = f"breathe -> {phase_s} " + ('ON' if flags & 0x01 else 'OFF')
elif mode == 3:
state_s = f"temp {color_s} " + ('ON' if flags & 0x01 else 'OFF')
elif mode == 4:
state_s = "marquee " + ('ON' if flags & 0x01 else 'OFF')
else:
state_s = f"{mode_s} {color_s} " + ('ON' if flags & 0x01 else 'OFF')
if flags & 0x02:
state_s += ' ALARM'
self.lbl_lamp.config(text=state_s)
self._log(f"RX: {frame_to_hex(frame)} -> Lamp={state_s}", 'rx')
elif cmd == CMD_RESP_FAN:
self.mcu_fan_mode = frame[3]
self.mcu_fan_target = (frame[4] << 8) | frame[5]
pct = self.mcu_fan_target * 100.0 / 65535
if SHOW_MCU_AUTO and getattr(self, 'lbl_mcu_fan', None) is not None:
if self.mcu_fan_mode == 1:
self.lbl_mcu_fan.config(text=f"auto {pct:.0f}%", foreground='#b8860b')
else:
self.lbl_mcu_fan.config(text=f"manual {pct:.0f}%", foreground='#555555')
self._log(f"RX: {frame_to_hex(frame)} -> MCU Fan mode={self.mcu_fan_mode} target={pct:.1f}%", 'rx')
elif cmd == CMD_RESP_TEMP_TH:
th_y = (frame[3] << 8) | frame[4]
th_b = (frame[5] << 8) | frame[6]
self.th_yellow = th_y / 10.0
self.th_blue = th_b / 10.0
self.ent_th_yellow.delete(0, 'end')
self.ent_th_yellow.insert(0, f'{self.th_yellow:g}')
self.ent_th_blue.delete(0, 'end')
self.ent_th_blue.insert(0, f'{self.th_blue:g}')
self._log(f"RX: {frame_to_hex(frame)} -> TempLED: yellow≤{self.th_yellow:g}°C, blue≤{self.th_blue:g}°C", 'rx')
else:
self._log(f"RX: {frame_to_hex(frame)}", 'rx')
self._update_statusbar()
except Exception as e:
self._log(f"Frame handling error: {e}", 'err')
# ---------- Auto Mapping ----------
def _mapping_params(self) -> tuple[float, float, float, float]:
def num(entry, default):
try:
return float(entry.get())
except Exception:
return default
return (num(self.ent_t_low, 25.0), num(self.ent_t_high, 60.0),
num(self.ent_d_low, 30.0), num(self.ent_d_high, 100.0))
def _on_auto_toggle(self) -> None:
self.last_auto_duty = None
if self.auto_enabled.get():
if SHOW_MCU_AUTO and self.mcu_auto_enabled.get(): # 与 MCU 闭环互斥
self.mcu_auto_enabled.set(False)
self._send_bytes(build_frame(CMD_SET_FAN_MODE, bytes([0])))
self._log("Auto mapping enabled", 'info')
if self.last_temp is not None:
self._apply_auto_mapping(self.last_temp)
else:
self.lbl_target.config(text="-- %")
else:
self.lbl_target.config(text="off")
self._log("Auto mapping disabled", 'info')
def _apply_auto_mapping(self, temp: float) -> None:
if not self.auto_enabled.get():
return
t_low, t_high, d_low, d_high = self._mapping_params()
if t_high <= t_low:
return
ratio = (temp - t_low) / (t_high - t_low)
ratio = max(0.0, min(1.0, ratio))
duty = int(round(d_low + (d_high - d_low) * ratio))
duty = max(0, min(100, duty))
self.lbl_target.config(text=f"{duty} %")
if duty == self.last_auto_duty:
return
self.last_auto_duty = duty
if self.ser and self.ser.is_open:
self._send_duty_percent(duty, auto=True)
else:
self._log(f"Auto: would set duty {duty}% (port closed)", 'info')
# ---------- Chart Update ----------
def _update_chart(self) -> None:
"""Refresh charts every 400 ms."""
if self.chart_ok:
try:
# Temperature chart
self.ax_temp.clear()
self.ax_temp.set_title('Temperature', fontsize=11)
self.ax_temp.set_xlabel('Time (s)', fontsize=9)
self.ax_temp.set_ylabel('Temp (°C)', fontsize=9)
self.ax_temp.tick_params(labelsize=8)
self.ax_temp.grid(True, alpha=0.3)
if len(self.temp_history) > 1:
xs, ys = zip(*self.temp_history)
self.ax_temp.plot(xs, ys, color='tab:blue', linewidth=1.5)
self.ax_temp.fill_between(xs, ys, min(ys) - 1,
color='tab:blue', alpha=0.1)
if xs[-1] > 30:
self.ax_temp.set_xlim(xs[-1] - 30, xs[-1] + 1)
else:
self.ax_temp.set_xlim(0, 30)
ymin, ymax = min(ys), max(ys)
margin = max(1.0, (ymax - ymin) * 0.2)
self.ax_temp.set_ylim(ymin - margin, ymax + margin)
else:
self.ax_temp.set_xlim(0, 30)
self.ax_temp.set_ylim(0, 50)
# Duty cycle chart
self.ax_duty.clear()
self.ax_duty.set_title('Duty Cycle', fontsize=11)
self.ax_duty.set_xlabel('Time (s)', fontsize=9)
self.ax_duty.set_ylabel('Duty (%)', fontsize=9)
self.ax_duty.tick_params(labelsize=8)
self.ax_duty.grid(True, alpha=0.3)
if len(self.duty_history) > 1:
xs, ys = zip(*self.duty_history)
self.ax_duty.plot(xs, ys, color='tab:green', linewidth=1.5)
self.ax_duty.fill_between(xs, ys, 0, color='tab:green', alpha=0.1)
if xs[-1] > 30:
self.ax_duty.set_xlim(xs[-1] - 30, xs[-1] + 1)
else:
self.ax_duty.set_xlim(0, 30)
else:
self.ax_duty.set_xlim(0, 30)
self.ax_duty.set_ylim(-5, 105)
# Auto mapping chart
t_low, t_high, d_low, d_high = self._mapping_params()
self.ax_map.clear()
self.ax_map.set_title('Auto Mapping', fontsize=11)
self.ax_map.set_xlabel('Temp (°C)', fontsize=9)
self.ax_map.set_ylabel('Duty (%)', fontsize=9)
self.ax_map.tick_params(labelsize=8)
self.ax_map.grid(True, alpha=0.3)
if t_high > t_low:
enabled = self.auto_enabled.get()
self.ax_map.plot([t_low, t_high], [d_low, d_high],
linewidth=2,
color='tab:orange' if enabled else 'silver')
if self.last_temp is not None and self.auto_enabled.get():
tgt = self.last_auto_duty if self.last_auto_duty is not None else 0
self.ax_map.plot([self.last_temp], [tgt], marker='o',
color='tab:red', markersize=7)
self.fig.tight_layout()
self.canvas.draw_idle()
except Exception as e:
print(f"Chart refresh error: {e}")
self.root.after(400, self._update_chart)
# ---------- 三灯实时动画(与板子 0x84 状态同步) ----------
def _temp_led_index(self) -> int:
"""按当前温度与阈值返回应亮的灯:0=红 1=蓝 2=黄"""
t = self.last_temp
if t is None:
return 2
if t < self.th_yellow:
return 2
if t < self.th_blue:
return 1
return 0
@staticmethod
def _blend(hex_color: str, brightness: float) -> str:
"""按亮度把颜色混向深灰,模拟 LED 明暗"""
brightness = max(0.0, min(1.0, brightness))
r = int(hex_color[1:3], 16) * brightness + 0x20 * (1 - brightness)
g = int(hex_color[3:5], 16) * brightness + 0x20 * (1 - brightness)
b = int(hex_color[5:7], 16) * brightness + 0x20 * (1 - brightness)
return f'#{int(r):02x}{int(g):02x}{int(b):02x}'
def _led_brightness(self, index: int, elapsed: float) -> float:
"""返回某盏灯当前亮度 0~1(index:0=红 1=蓝 2=黄)"""
st = self.lamp
mode, color, flags = st['mode'], st['color'], st['flags']
if not (flags & 0x01):
return 0.0
if flags & 0x02:
return 1.0 # 报警:三灯全亮
if mode == 0: # 常亮
return 1.0 if index == color else 0.0
if mode == 1: # 闪烁(500ms)
on = (int(elapsed * 1000) // LED_BLINK_INTERVAL_MS) % 2 == 0
return 1.0 if (on and index == color) else 0.0
if mode == 2: # 呼吸(相位由 0x84 对齐)
step = int(elapsed * 1000 / LED_BREATH_STEP_MS) % LED_BREATH_STEPS
duty = (1 - math.cos(2 * math.pi * step / LED_BREATH_STEPS)) / 2
phase = st['phase']
if phase == 3:
return duty
return duty if index == phase else 0.0
if mode == 3: # 温度显示
return 1.0 if index == self._temp_led_index() else 0.0
if mode == 4: # 跑马灯(与固件相同的错相波)
step = int(elapsed * 1000 / LED_BREATH_STEP_MS) % LED_BREATH_STEPS
s = (step + (0, 33, 66)[index]) % LED_BREATH_STEPS
return (1 - math.cos(2 * math.pi * s / LED_BREATH_STEPS)) / 2
return 0.0
def _update_led_canvas(self) -> None:
if not SHOW_LED_CANVAS:
return
if getattr(self, 'led_canvas', None) is not None:
try:
elapsed = time.time() - self.lamp_anim_t0
self.led_canvas.delete('all')
for i, name in enumerate(LED_COLORS):
b = self._led_brightness(i, elapsed)
cx = 38 + i * 67
self.led_canvas.create_oval(cx - 24, 4, cx + 24, 52,
fill=self._blend(LED_COLOR_RGB[name], b),
outline='#888888')
self.led_canvas.create_text(cx, 62, text=name.upper(),
fill='#aaaaaa', font=('Segoe UI', 7))
except Exception:
pass
self.root.after(LED_ANIM_PERIOD_MS, self._update_led_canvas)
# ---------- Send ----------
def _send_bytes(self, data: bytes, tag: str = 'tx', prefix: str = 'TX') -> bool:
if not (self.ser and self.ser.is_open):
messagebox.showwarning("Warning", "Please open the serial port first.")
return False
try:
self.ser.write(data)
self.tx_count += 1
ts = datetime.now().strftime('%H:%M:%S.%f')[:-3]
self._log(f"[{ts}] {prefix}: {frame_to_hex(data)}", tag)
self._update_statusbar()
return True
except Exception as e:
self._log(f"TX error: {e}", 'err')
return False
def _send_duty_percent(self, percent: int, auto: bool = False) -> None:
percent = max(0, min(100, int(percent)))
raw = percent * 65535 // 100
frame = build_frame(CMD_SET_DUTY, raw.to_bytes(2, 'big'))
self._send_bytes(frame, tag='auto' if auto else 'tx',
prefix='AUTO SET_DUTY' if auto else 'TX')
def _send_preset(self, kind: str) -> None:
if self.auto_enabled.get() and kind.startswith('duty'):
self._log("Auto mapping is ON, manual duty will be overridden", 'info')
match kind:
case 'duty50':
self._send_duty_percent(50)
case 'duty100':
self._send_duty_percent(100)
case 'duty0':
self._send_duty_percent(0)
case 'query_temp':
self._send_bytes(build_frame(CMD_QUERY_TEMP))
case 'query_duty':
self._send_bytes(build_frame(CMD_QUERY_DUTY))
case 'query_led':
self._send_bytes(build_frame(CMD_QUERY_LED))
case _:
return
def _send_morse(self) -> None:
text = self.morse_entry.get()
if not text:
return
data = text.encode('ascii', 'ignore')
if not data:
return
for i in range(0, len(data), MORSE_TEXT_MAX):
chunk = data[i:i + MORSE_TEXT_MAX]
self._send_bytes(build_frame(CMD_MORSE, bytes([len(chunk)]) + chunk))
self._log(f"Morse queued: {text!r}", 'info')
def _send_temp_thresholds(self) -> None:
try:
th_y = int(round(float(self.ent_th_yellow.get()) * 10))
th_b = int(round(float(self.ent_th_blue.get()) * 10))
except ValueError:
messagebox.showerror("Format Error", "Threshold must be numbers, e.g. 25 and 40")
return
if not (0 <= th_y < th_b <= 1000):
messagebox.showerror("Range Error", "Require 0 ≤ yellow < blue ≤ 100 °C")
return
self._send_bytes(build_frame(CMD_SET_TEMP_TH,
bytes([(th_y >> 8) & 0xFF, th_y & 0xFF,
(th_b >> 8) & 0xFF, th_b & 0xFF])))
def _query_temp_thresholds(self) -> None:
self._send_bytes(build_frame(CMD_QUERY_TEMP_TH))
def _on_mcu_auto_toggle(self) -> None:
if not SHOW_MCU_AUTO:
return
enable = self.mcu_auto_enabled.get()
if enable and self.auto_enabled.get(): # 与 GUI 映射互斥
self.auto_enabled.set(False)
self._on_auto_toggle()
self._send_bytes(build_frame(CMD_SET_FAN_MODE, bytes([1 if enable else 0])))
def _send_manual(self) -> None:
text = self.manual_entry.get().strip()
if not text:
return
try:
hexs = text.replace(',', ' ').split()
data = bytes(int(h, 16) for h in hexs)
except Exception as e:
messagebox.showerror("Format Error", f"Invalid HEX format: {e}")
return
self._send_bytes(data)
# ---------- Log / Status ----------
def _log(self, msg: str, tag: str | None = None) -> None:
self.log.insert('end', msg + '\n', tag)
self.log.see('end')
def _update_statusbar(self) -> None:
last = self.last_rx_time.strftime('%H:%M:%S') if self.last_rx_time else '--'
self.statusbar.config(
text=f"RX frames: {self.rx_count} | last RX: {last} | TX frames: {self.tx_count}")
def _update_clock(self) -> None:
"""Keep the status bar alive even when no frame arrives."""
self._update_statusbar()
self.root.after(1000, self._update_clock)
def _clear_all(self) -> None:
self.log.delete('1.0', 'end')
self.temp_history.clear()
self.duty_history.clear()
self.lbl_temp.config(text="--.- °C")
self.lbl_duty.config(text="-- %")
self._log("Cleared log and chart data", 'info')
def _save_log(self) -> None:
ts = datetime.now().strftime('%Y%m%d_%H%M%S')
fname = f"serial_log_{ts}.txt"
try:
with open(fname, 'w', encoding='utf-8') as f:
f.write(self.log.get('1.0', 'end'))
messagebox.showinfo("Saved", f"Log saved to:\n{fname}")
except Exception as e:
messagebox.showerror("Error", f"Save failed: {e}")
# ---------- Close ----------
def on_close(self) -> None:
self._close_serial()
self.root.destroy()
if __name__ == '__main__':
root = DPIAwareTk()
app = SerialApp(root)
root.protocol("WM_DELETE_WINDOW", app.on_close)
root.mainloop()