PyCharm pyqt5 python串口通信封装类SerialCommunication
生活随笔
收集整理的这篇文章主要介绍了
PyCharm pyqt5 python串口通信封装类SerialCommunication
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
"""
pyqt5串口通信文件SerialCommunication.py
"""
import binascii
import os
import serial
import serial.tools.list_ports
from PyQt5.QtGui import QPixmap# 全局变量,串口是否创建成功标志
Ret = False
# 串口列表串口号
port_list_number = []
# 串口列表名称
port_list_name = []
# 获取“串口指示灯亮”图片文件路径
imgLedOff = os.path.join(os.getcwd() + "\\images\\light_off.png")
# 获取“串口指示灯灭”图片文件路径
imgLedOn = os.path.join(os.getcwd() + "\\images\\light_on.png")class Communication(object):"""Python串口通信封装类"""# 初始化def __init__(self, com, bps, timeout):self.port = com # 串口号self.bps = bps # 波特率self.timeout = timeout # 超时溢出self.main_engine = None # 全局串口通信对象global RetRet = Falseself.data = Noneself.b_c_text = Nonetry:# 打开串口,并得到串口对象self.main_engine = serial.Serial(self.port, self.bps, timeout=self.timeout)# 判断是否打开成功if self.main_engine.is_open:Ret = Trueexcept Exception as e:print("---异常---:", e)# 打印设备基本信息def Print_Name(self):"""打印设备基本信息"""print(self.main_engine.name) # 设备名字print(self.main_engine.port) # 读或者写端口print(self.main_engine.baudrate) # 波特率print(self.main_engine.bytesize) # 字节大小print(self.main_engine.parity) # 校验位print(self.main_engine.stopbits) # 停止位print(self.main_engine.timeout) # 读超时设置print(self.main_engine.writeTimeout) # 写超时print(self.main_engine.xonxoff) # 软件流控print(self.main_engine.rtscts) # 软件流控print(self.main_engine.dsrdtr) # 硬件流控print(self.main_engine.interCharTimeout) # 字符间隔超时# 打开串口def Open_Engine(self):"""打开串口"""global Ret# 如果串口没有打开,则打开串口if not self.main_engine.is_open:self.main_engine.open()Ret = True# 关闭串口def Close_Engine(self):"""关闭串口"""global Ret# print(self.main_engine.is_open) # 检验串口是否打开# 判断是否打开if self.main_engine.is_open:self.main_engine.close() # 关闭串口Ret = False# 打印可用串口列表@staticmethoddef Print_Used_Com():"""打印可用串口列表"""port_list_name.clear()port_list_number.clear()port_list = list(serial.tools.list_ports.comports())if len(port_list) <= 0:print("The Serial port can't find!")else:for each_port in port_list:port_list_number.append(each_port[0])port_list_name.append(each_port[1])print(port_list_number)print(port_list_name)# 接收指定大小的数据# 从串口读size个字节。如果指定超时,则可能在超时后返回较少的字节;如果没有指定超时,则会一直等到收完指定的字节数。def Read_Size(self, size):"""接收指定大小的数据:param size::return:"""return self.main_engine.read(size=size)# 接收一行数据# 使用readline()时应该注意:打开串口时应该指定超时,否则如果串口没有收到新行,则会一直等待。# 如果没有超时,readline会报异常。def Read_Line(self):"""接收一行数据:return:"""return self.main_engine.readline()# 发数据def Send_data(self, data):"""发数据:param data:"""self.main_engine.write(data)# 更多示例# self.main_engine.write(bytes(listData)) # 发送列表数据listData = [0x01, 0x02, 0xFD]或listData = [1, 2, 253]# self.main_engine.write(chr(0x06).encode("utf-8")) # 十六制发送一个数据# print(self.main_engine.read().hex()) # # 十六进制的读取读一个字节# print(self.main_engine.read())#读一个字节# print(self.main_engine.read(10).decode("gbk"))#读十个字节# print(self.main_engine.readline().decode("gbk"))#读一行# print(self.main_engine.readlines())#读取多行,返回列表,必须匹配超时(timeout)使用# print(self.main_engine.in_waiting)#获取输入缓冲区的剩余字节数# print(self.main_engine.out_waiting)#获取输出缓冲区的字节数# print(self.main_engine.readall())#读取全部字符。# 接收数据# 一个整型数据占两个字节# 一个字符占一个字节def Receive_data(self, way):"""接收数据:param way:"""# 循环接收数据,此为死循环,可用线程实现print("开始接收数据:")bWaitRec = Truewhile bWaitRec:try:# 一个字节一个字节的接收if self.main_engine.in_waiting:if way == 0:for i in range(self.main_engine.in_waiting):print("接收ascii数据:" + str(self.Read_Size(1)))data1 = self.Read_Size(1).hex() # 转为十六进制data2 = int(data1, 16) # 转为十进制print("收到数据十六进制:"+data1+" 收到数据十进制:"+str(data2))if way == 1:# 整体接收# self.data = self.main_engine.read(self.main_engine.in_waiting).decode("utf-8") # 方式一self.data = self.main_engine.read_all() # 方式二print("接收ascii数据:", self.data)self.b_c_text = binascii.hexlify(self.data) # 16进制Bytes转Bytes,例:b'\x01\x06\xaa\x92\x12'转b'0106aa9212'print("Bytes数据:", self.b_c_text)# 如果data不为空,则退出接收死循环if self.data.strip() != '':bWaitRec = Falseexcept Exception as e:print("异常报错:", e)print("接收数据完毕!")
"""
pyqt5主对话框文件main.py
"""import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QPixmap
import SerialCommunication # module SerialCommunication.py# myPyMainForm # 主窗口对象
# labIndicator # label控件对象class MyPyQTMainForm(QMainWindow, BitmapFontCreate.Ui_MainWindow):"""主界面"""def __init__(self):super(MyPyQTMainForm, self).__init__()self.setupUi(self)# 保存全局串口通信Communication对象self.myEngine = Noneself.strComNum = None # 保存串口号def ComLedIndicator(self, comboIndex):"""串口状态用LED指示灯指示。串口打开LED亮;串口关闭LED灭;"""if comboIndex >= 0:# 计算串口号COMxself.strComNum = SerialCommunication.port_list_number[comboIndex]# 创建串口通信对象myEngineself.myEngine = SerialCommunication.Communication(self.strComNum, 9600, 0.5)else:self.myEngine = Noneif SerialCommunication.Ret:# 利用label显示图片,串口指示灯亮icoLedOn = QPixmap(SerialCommunication.imgLedOn)myPyMainForm.labIndicator.setPixmap(icoLedOn)myPyMainForm.labIndicator.setScaledContents(True)else:# 利用label显示图片,串口指示灯灭icoLedOff = QPixmap(SerialCommunication.imgLedOff)myPyMainForm.labIndicator.setPixmap(icoLedOff)myPyMainForm.labIndicator.setScaledContents(True)def ComScan(self):"""串口扫描"""# 串口重新扫描前,首先关闭串口if self.myEngine:self.myEngine.Close_Engine()# 清空串口组合框myPyMainForm.comboComNum.clearEditText()myPyMainForm.comboComNum.clear()# 打印可用串口列表SerialCommunication.Communication.Print_Used_Com()# 向串口号组合框添加可用的串口号myPyMainForm.comboComNum.addItems(SerialCommunication.port_list_name)"""
主函数
"""
if __name__ == '__main__':app = QApplication(sys.argv)myPyMainForm = MyPyQTMainForm()# 禁止最大化按钮myPyMainForm.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)# 禁止拉伸窗口大小myPyMainForm.setFixedSize(myPyMainForm.width(), myPyMainForm.height())# 清空串口号组合框myPyMainForm.comboComNum.clear()# 打印可用串口列表SerialCommunication.Communication.Print_Used_Com()# 向串口号组合框添加可用的串口号myPyMainForm.comboComNum.addItems(SerialCommunication.port_list_name)# 显示主界面myPyMainForm.show()sys.exit(app.exec_())
总结
以上是生活随笔为你收集整理的PyCharm pyqt5 python串口通信封装类SerialCommunication的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: SQL事务控制语言(TCL)
- 下一篇: Python 3深度置信网络(DBN)在