ISP_Controller/src/main.py

339 lines
12 KiB
Python

import customtkinter as ctk
import messagebox
import serial
import serial.tools
import serial.tools.list_ports as ls_ports
from typing import Optional, Any
import functools
class App(ctk.CTk):
__window_width = 1280
__window_height = 1350
__column_weight = [1, 9, 3]
serial_status = False
serial_baudrate = 9600
gain_default = [1.30, 0.70, 1.10, 2.20, 0.50]
gain_values = gain_default.copy()
gain_values_store = gain_default.copy()
gain_enable = [True for i in range(5)]
def __init__(self) -> None:
super().__init__()
self.__windowInit(self.__window_width, self.__window_height)
self.__data_frame()
def __windowInit(self, width: int, height: int) -> None:
self.title("ISP上位机")
# appearance and font
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("dark-blue")
self.font = ctk.CTkFont(family="", size=17)
# get the screen dimension
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
# high dpi support
if screen_width >= 3840 and screen_height >= 2160:
ctk.set_widget_scaling(2.0)
messagebox.isHighDIP = True
else:
ctk.set_window_scaling(0.8)
# find the center point
center_x = int(screen_width / 2 - width / 2)
center_y = int(screen_height / 2 - height / 2)
# set the position of the self to the center of the screen
self.geometry(f"{width}x{height}+{center_x}+{center_y}")
# create gain_frame
top_frame = ctk.CTkFrame(self)
top_frame.pack(side="top", fill=ctk.X, padx=10)
top_frame.columnconfigure(0, weight=self.__column_weight[0])
top_frame.columnconfigure(1, weight=self.__column_weight[1])
top_frame.columnconfigure(2, weight=self.__column_weight[2])
# Serial Port
# create label
self.serial_label = ctk.CTkLabel(top_frame, text="串口:", font=self.font)
self.serial_label.grid(column=0, row=0, sticky=ctk.EW, pady=10, padx=10)
# create combobox
self.serial_combobox = ctk.CTkComboBox(
top_frame,
state="readonly",
command=self.selectSerial,
font=self.font,
dropdown_font=self.font,
)
self.serial_combobox.bind("<Button>", self.updateSerial)
self.updateSerial()
self.serial_combobox.grid(column=1, row=0, sticky=ctk.EW, pady=10, padx=20)
# create button
self.serial_button = ctk.CTkButton(
top_frame,
command=self.connectSerial,
font=self.font,
)
self.serial_button_text = ctk.StringVar(self.serial_button, "连接")
self.serial_button.configure(textvariable=self.serial_button_text)
self.serial_button.grid(column=2, row=0, sticky=ctk.EW, pady=10, padx=10)
# Serial Baudrate
# create label
self.baud_label = ctk.CTkLabel(top_frame, text="波特率:", font=self.font)
self.baud_label.grid(column=0, row=1, sticky=ctk.EW, pady=10, padx=10)
# create combobox
self.baud_combobox = ctk.CTkComboBox(
top_frame,
values=[str(9600), str(19200), str(38400), str(57600), str(115200)],
command=self.setBaudrate,
font=self.font,
dropdown_font=self.font,
)
self.baud_combobox.grid(column=1, row=1, sticky=ctk.EW, pady=10, padx=20)
# create Set Button
self.send_button = ctk.CTkButton(
top_frame, text="应用", font=self.font, command=self.setISP
)
self.send_button.grid(column=2, row=1, sticky=ctk.EW, pady=10, padx=10)
return None
def __data_frame(self) -> None:
def setGain(value, i: int, stringVar: ctk.StringVar) -> None:
self.gain_values[i] = value
stringVar.set(f"{value:.2f}")
return None
def switchSlider(i: int, slider: ctk.CTkSlider, value: ctk.StringVar) -> None:
if slider.cget("state") == "normal":
self.gain_values[i] = self.gain_default[i]
self.gain_values_store[i] = slider.get()
value.set(f"{self.gain_default[i]:.2f}")
slider.set(self.gain_default[i])
slider.configure(button_color="grey")
slider.configure(state="disabled")
else:
self.gain_values[i] = slider.get()
value.set(f"{self.gain_values_store[i]:.2f}")
slider.set(self.gain_values_store[i])
slider.configure(button_color="#1f538d")
slider.configure(state="normal")
return None
def switchCorrection(i: int, slider: ctk.CTkSlider) -> None:
if self.gain_enable[i]:
self.gain_enable[i] = False
slider.configure(button_color="grey")
slider.configure(state="disabled")
else:
self.gain_enable[i] = True
slider.configure(button_color="#1f538d")
slider.configure(state="normal")
return None
text = [
"红色校正系数",
"绿色校正系数",
"蓝色校正系数",
"伽马校正系数",
"饱和度调整系数",
]
gain_min = [0.0, 0.0, 0.0, 0.0, -1.0]
gain_max = [2.0, 2.0, 2.0, 5.0, 1.0]
fg_clolor = [
"#4d140b",
"#005f50",
"#456789",
"#596062",
"#596062",
]
data_frame = ctk.CTkFrame(self)
data_frame.pack(side="top", fill=ctk.X, pady=10)
data_frame.columnconfigure(0, weight=10)
data_frame.columnconfigure(1, weight=3)
gain_frame = []
gain_str = []
gain_label = []
gain_slider = []
gain_button = []
gain_checkbox = []
for i in range(5):
# gain_frame
gain_frame.append(ctk.CTkFrame(data_frame, fg_color=fg_clolor[i]))
gain_frame[i].grid(column=0, sticky=ctk.EW, pady=10, padx=20, ipady=10)
# label
if i < 3:
ctk.CTkLabel(gain_frame[i], text=text[i], font=self.font).pack(
side="top", ipady=10
)
else:
gain_checkbox.append(
ctk.CTkCheckBox(
gain_frame[i],
text=text[i],
font=self.font,
)
)
gain_checkbox[i - 3].select()
gain_checkbox[i - 3].pack(side="top", ipady=10)
# slider
gain_slider.append(
ctk.CTkSlider(gain_frame[i], from_=gain_min[i], to=gain_max[i])
)
gain_slider[i].set(self.gain_default[i])
gain_slider[i].pack(side="top", fill=ctk.X, padx=10)
gain_str.append(
ctk.StringVar(gain_slider[i], f"{self.gain_default[i]:.2f}")
)
# set command
gain_slider[i].configure(
command=functools.partial(setGain, i=i, stringVar=gain_str[i])
)
if i >= 3:
gain_checkbox[i - 3].configure(
command=functools.partial(switchCorrection, i, gain_slider[i])
)
# gain value
ctk.CTkLabel(gain_frame[i], text=str(gain_min[i]), font=self.font).pack(
side="left", padx=10
)
ctk.CTkLabel(gain_frame[i], text=str(gain_max[i]), font=self.font).pack(
side="right", padx=10
)
gain_label.append(
ctk.CTkLabel(
gain_frame[i],
textvariable=gain_str[i],
font=self.font,
)
)
gain_label[i].pack(side="top")
# button
gain_button.append(
ctk.CTkButton(
data_frame,
text="使用推荐配置",
command=functools.partial(
switchSlider, i=i, slider=gain_slider[i], value=gain_str[i]
),
font=self.font,
)
)
gain_button[i].grid(column=1, row=i, sticky=ctk.NSEW, pady=10, padx=20)
return None
def updateSerial(self, event: Optional[Any] = None):
print("Update Serial Ports")
port_list = []
for info in ls_ports.comports():
port, desc, hwid = info
port_list.append(port + " " + desc)
self.serial_combobox.configure(values=port_list)
def selectSerial(self, port_info: Optional[Any] = None):
print("Select Serial port")
try:
self.select_port = port_info.split()[0]
except Exception:
print("Get None")
finally:
print(self.select_port)
def connectSerial(self, info: Optional[Any] = None):
try:
print(self.select_port)
except AttributeError:
print("Please Select Serial Port")
messagebox.showError("Please Select Serial Port")
else:
if not self.serial_status:
try:
self.serial = serial.Serial(self.select_port, self.serial_baudrate)
except AttributeError:
print("Please Select Serial Port")
messagebox.showError("Please Select Serial Port")
except serial.serialutil.SerialException:
print("Can't Control the Serial Port")
messagebox.showError("Can't Control the Serial Port")
else:
self.serial_status = True
self.serial_button_text.set("断开连接")
print("Select Serial Port:")
print(self.select_port)
else:
try:
self.serial.close()
except Exception:
print("Failed to Close Serial")
messagebox.showError("Failed to Close Serial")
else:
self.serial_status = False
self.serial_button_text.set("连接")
print("Succeed to Close Serial")
def setBaudrate(self, baudrate: Optional[Any] = None):
self.serial_baudrate = int(baudrate)
if self.serial_status:
try:
self.serial.close()
self.serial = serial.Serial(self.select_port, self.serial_baudrate)
self.serial.open()
except Exception:
print("Failed to Set Serial Baudrate")
messagebox.showError("Failed to Set Serial Baudrate")
else:
print("Succeed to Set Serial Baudrate")
else:
print("Please Connect to Serial")
def setISP(self, event: Optional[Any] = None):
def switchSign(i: int) -> str:
match i:
case 0:
return "cmdr"
case 1:
return "cmdg"
case 2:
return "cmdb"
case 3:
return "cmda"
case 4:
return "cmds"
case _:
return "error"
def toAscii(num: float) -> str:
return chr(int(num))
if self.serial_status:
for i in range(5):
if self.gain_enable[i]:
bytes = f"{switchSign(i)}{toAscii(self.gain_values[i])}{toAscii(self.gain_values[i] % 1 * 256)}"
print(f"Send:{bytes}")
self.serial.write(bytes.encode())
else:
print("Please Connect to Serial")
def run(self):
self.mainloop()
if __name__ == "__main__":
app = App()
app.run()