115 lines
3.5 KiB
Python
Raw Normal View History

2025-03-14 15:46:15 +08:00
import serial
import serial.tools.list_ports
from PyQt5.QtWidgets import QDialog, QApplication
from serialUI import Ui_SerialSet
class UiSerial(QDialog, Ui_SerialSet):
def __init__(self):
super().__init__()
self.setupUi(self)
self.init()
def init(self):
self.port_check()
self.pushButtonTestSerial.clicked.connect(self.port_check)
def port_check(self):
try:
# 获取所有存在的串口
port_list = list(serial.tools.list_ports.comports())
except Exception as e:
print(f"Error fetching port list: {e}")
port_list = []
# 清空组合框
self.comboBoxSerial.clear()
if not port_list:
# 如果没有检测到任何串口,添加提示项
self.comboBoxSerial.addItem("无串口")
self.Com_Dict = {}
else:
# 将串口信息存储在字典中,并添加到组合框
self.Com_Dict = {port.device: port.description for port in port_list}
for port in port_list:
self.comboBoxSerial.addItem(port.device)
def get_port(self):
return self.comboBoxSerial.currentText()
def set_port(self, port_str):
self.comboBoxSerial.setCurrentText(port_str)
def get_baudrate(self):
return int(self.comboBoxBaudrate.currentText())
def set_baudrate(self, baudrate_str):
self.comboBoxBaudrate.setCurrentText(baudrate_str)
def get_bytesize(self):
flag_data = int(self.comboBoxDataBits.currentText()) # 数据位
if flag_data == 5:
bytesize = serial.FIVEBITS
elif flag_data == 6:
bytesize = serial.SIXBITS
elif flag_data == 7:
bytesize = serial.SEVENBITS
else:
bytesize = serial.EIGHTBITS
return bytesize
def get_parity(self):
flag_data = self.comboBoxCheckBit.currentText() # 校验位
if flag_data == "None":
parity = serial.PARITY_NONE
elif flag_data == "Odd":
parity = serial.PARITY_ODD
else:
parity = serial.PARITY_EVEN
return parity
def set_parity(self, parity_str):
if parity_str == "N":
self.comboBoxCheckBit.setCurrentIndex(0)
elif parity_str == "O":
self.comboBoxCheckBit.setCurrentIndex(1)
else:
self.comboBoxCheckBit.setCurrentIndex(2)
def get_stopbit(self):
flag_data = int(self.comboBoxStopBit.currentText()) # 停止位
if flag_data == 1:
stopbits = serial.STOPBITS_ONE
else:
stopbits = serial.STOPBITS_TWO
return stopbits
def get_flow(self):
flag_data = self.comboBoxFlow.currentText() # 流控
if flag_data == "No Ctrl Flow":
xonxoff = False # 软件流控
dsrdtr = False # 硬件流控 DTR
rtscts = False # 硬件流控 RTS
elif flag_data == "SW Ctrl Flow":
xonxoff = True # 软件流控
else:
if self.checkBoxDTR.isChecked():
self.ser.dsrdtr = True # 硬件流控 DTR
if self.checkBoxRTS.isChecked():
self.ser.rtscts = True # 硬件流控 RTS
def last_serial_info(self, port_str, bauterate_str):
self.set_port(port_str)
self.set_baudrate(bauterate_str)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
ui = UiSerial()
ui.show()
sys.exit(app.exec_())