加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Base.py 3.77 KB
一键复制 编辑 原始数据 按行查看 历史
wytmxutao 提交于 2022-05-09 21:45 . change some files location.
from PyQt5.QtGui import*
from PyQt5.QtCore import*
from PyQt5.QtWidgets import*
import time,sys,serial,threading
#实现一些串口功能的接口
class Serial():
def __init__(self, port, baudrate=115200, timeout=5, bytesize=8, parity='N', stopbits=1):
#相关参数的设定
self.port = port
self.baudrate = baudrate
self.timeout = timeout
self.bytesize = bytesize
self.parity = parity
self.stopbits = stopbits
#串口存在与否标准
self.serial_existed = False
#连接是否建立标志
self.isConnected = False
#主要流程实现,初始化应该实现的部分
self.ports = serial.tools.list_ports.comports()
self.ports_name = [port.name for port in self.ports]
if self.ports:
print("串口的信息如下{}".format(self.ports_name))
self.serial_existed = True
try:
self._serial_connect()
print("串口连接成功......")
except Exception as e:
print("未连接成功,可能是未开启系统!",e)
else:
print("未检测到串口!")
def _serial_connect(self):
self._serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout,
bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits)
self._serial.flushInput()
if self._serial.isOpen():
self.isConnected = True
def get_data(self, *args, **kwargs):
if self.isConnected:
while True:
data_count = self._serial.inWaiting()
if data_count != 0:
receiver = self._serial.read(self._serial.in_waiting).decode('gbk')
serial_time = time.time()
time.sleep(0.1)
if args[0]:
if args[1]:
return (">>"+receiver+'\n'+time.strftime("%H:%M:%S",time.localtime(serial_time))+' 接收到: '+receiver)
else:
return (time.strftime("%H:%M:%S",time.localtime(serial_time))+' 接收到: '+receiver)
else:
if args[1]:
return ">>"+receiver+'\n'+receiver
else:
return receiver
else:
return "当前串口未建立连接!"
def send_data(self, *args, **kwargs):
if self.isConnected:
if len(args) == 1:
self._serial.write(args[0].encode(encoding='utf-8'))
else:
pass
else:
return "当前串口未建立连接!"
class SerialHandleThread(threading.Thread):
def __init__(self, func, args, name = ''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
self.result = self.func(*self.args)
def get_return_value(self):
try:
return self.result
except Exception:
return None
class QTitleLabel(QLabel):
"""
新建标题栏标签类
"""
def __init__(self, *args):
super(QTitleLabel, self).__init__(*args)
self.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.setFixedHeight(30)
class QTitleButton(QPushButton):
"""
新建标题栏按钮类
"""
def __init__(self, *args):
super(QTitleButton, self).__init__(*args)
self.setFont(QFont("Webdings")) # 特殊字体以不借助图片实现最小化最大化和关闭按钮
self.setFixedWidth(40)
class serial_thread(QThread):
_signal = pyqtSignal(str)
def __init__(self):
super(serial_thread,self).__init__()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化