Files
SikoraDaqReader/PyApp/main.py
T
2026-08-16 11:57:44 +08:00

371 lines
13 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SikoraDaqReader 上位机
======================
通过 USB 虚拟串口与 STM32 板卡通讯,解析双通道 uint16 数据并实时绘制曲线。
板卡通讯协议:
下发命令: 55 AA XX YY CC
XX YY = 采集时间(ms, 小端); 时间>0 启动采集, 时间=0 强制停止
上传数据: AA BB d0 d1 d2 d3
d0d1 = 通道1 (小端 uint16), d2d3 = 通道2 (小端 uint16)
操作说明:
- 选择串口 -> 连接
- 开始采集: 持续下发启动命令(保活), 板卡持续回传数据
- 停止采集: 下发停止命令(时间=0)
- 曲线可拖动(左键)、可缩放(滚轮/右键框选)、可清空(按钮)
- 勾选"自动跟随"则X轴滚动显示最新数据; 取消勾选后可自由拖动缩放查看历史
"""
import sys
import queue
from collections import deque
import serial
import serial.tools.list_ports
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot, QTimer
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QComboBox, QPushButton, QLabel, QCheckBox, QMessageBox,
)
import pyqtgraph as pg
# ---------------- 协议常量 ----------------
HEADER = b"\xAA\xBB" # 板卡上传数据帧头
CMD_START_TIME_MS = 10000 # 下发的采集时长(ms), 板卡据此持续采集
KEEPALIVE_INTERVAL_MS = 2000 # 定时重发启动命令, 防止板卡超时自动停止
MAX_POINTS = 100000 # 曲线最多保留的采样点数
FOLLOW_WINDOW = 2000 # "自动跟随"时显示的最新点数
def build_command(time_ms: int) -> bytes:
"""组装下发命令 55 AA XX YY CC, XX YY 为时长小端"""
lo = time_ms & 0xFF
hi = (time_ms >> 8) & 0xFF
return bytes([0x55, 0xAA, lo, hi, 0xCC])
# ---------------- 串口接收线程 ----------------
class ReaderThread(QThread):
"""在独立线程中读写串口: 解析上传帧并通过信号投递双通道数据"""
data_received = pyqtSignal(int, int) # (ch1, ch2)
error_occurred = pyqtSignal(str)
frame_raw = pyqtSignal(bytes) # 每收到一帧(不含帧头的4字节原始数据)就投递, 供UI侧决定是否作为温度帧
def __init__(self, port: str, baudrate: int = 115200):
super().__init__()
self.port = port
self.baudrate = baudrate
self.serial = None
self._running = False
self.cmd_queue: "queue.Queue[bytes]" = queue.Queue()
def send_command(self, data: bytes) -> None:
"""主线程调用: 投递待发送命令(线程安全)"""
self.cmd_queue.put(data)
def stop(self) -> None:
self._running = False
def run(self) -> None:
try:
self.serial = serial.Serial(self.port, self.baudrate, timeout=0.05)
except Exception as e:
self.error_occurred.emit(f"打开串口失败: {e}")
return
self._running = True
buf = bytearray()
while True:
# 先发送待发命令(含停止命令, 确保断开前能发出)
self._drain_commands()
if not self._running:
break
try:
chunk = self.serial.read(256)
except Exception as e:
self.error_occurred.emit(f"读取串口失败: {e}")
break
if chunk:
buf.extend(chunk)
self._parse(buf)
try:
self.serial.close()
except Exception:
pass
def _drain_commands(self) -> None:
while True:
try:
cmd = self.cmd_queue.get_nowait()
except queue.Empty:
return
try:
self.serial.write(cmd)
except Exception as e:
self.error_occurred.emit(f"发送命令失败: {e}")
def _parse(self, buf: bytearray) -> None:
"""从缓冲区提取完整帧 AA BB d0 d1 d2 d3, 解析为两通道 uint16"""
while True:
idx = buf.find(HEADER)
if idx == -1:
# 保留可能是帧头首字节的 0xAA, 避免跨包漏帧
if buf and buf[-1] == 0xAA:
del buf[:-1]
else:
buf.clear()
return
if idx > 0:
del buf[:idx] # 丢弃帧头前的杂散字节
if len(buf) < 6:
return # 帧不完整, 等待更多数据
data = bytes(buf[2:6])
del buf[:6]
ch1 = data[0] | (data[1] << 8)
ch2 = data[2] | (data[3] << 8)
self.frame_raw.emit(data) # 先投递原始4字节, UI侧判断是否为温度帧
self.data_received.emit(ch1, ch2)
# ---------------- 主窗口 ----------------
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Sikora DAQ Reader 双通道采集")
self.resize(1000, 640)
self.thread: ReaderThread = None
self.keepalive_timer = QTimer(self)
self.keepalive_timer.timeout.connect(self._send_start_keepalive)
# 显示刷新定时器(独立于数据到达, 固定刷新率以降低CPU占用)
self.display_timer = QTimer(self)
self.display_timer.timeout.connect(self._refresh_plot)
self.display_timer.start(30)
# 数据缓冲(滚动窗口)
self.sample_index = 0
self.x = deque(maxlen=MAX_POINTS)
self.y1 = deque(maxlen=MAX_POINTS)
self.y2 = deque(maxlen=MAX_POINTS)
# 采集状态: True 表示下一个到达的帧视为"采集后第一帧", 用于识别温度帧
self._first_frame = False
self._build_ui()
self._refresh_ports()
# ---- 界面构建 ----
def _build_ui(self):
central = QWidget()
self.setCentralWidget(central)
root = QVBoxLayout(central)
bar = QHBoxLayout()
bar.addWidget(QLabel("串口:"))
self.port_combo = QComboBox()
self.port_combo.setMinimumWidth(200)
bar.addWidget(self.port_combo)
self.refresh_btn = QPushButton("刷新串口")
self.refresh_btn.clicked.connect(self._refresh_ports)
bar.addWidget(self.refresh_btn)
self.connect_btn = QPushButton("连接")
self.connect_btn.setCheckable(True)
self.connect_btn.clicked.connect(self._on_connect)
bar.addWidget(self.connect_btn)
self.start_btn = QPushButton("开始采集")
self.start_btn.setEnabled(False)
self.start_btn.clicked.connect(self._on_start)
bar.addWidget(self.start_btn)
self.stop_btn = QPushButton("停止采集")
self.stop_btn.setEnabled(False)
self.stop_btn.clicked.connect(self._on_stop)
bar.addWidget(self.stop_btn)
self.clear_btn = QPushButton("清空曲线")
self.clear_btn.clicked.connect(self._on_clear)
bar.addWidget(self.clear_btn)
self.follow_chk = QCheckBox("自动跟随")
self.follow_chk.setChecked(True)
bar.addWidget(self.follow_chk)
bar.addStretch()
self.temp_lbl = QLabel("温度: -- ℃")
self.temp_lbl.setMinimumWidth(110)
bar.addWidget(self.temp_lbl)
self.status_lbl = QLabel("未连接")
self.status_lbl.setMinimumWidth(120)
bar.addWidget(self.status_lbl)
root.addLayout(bar)
# 绘图区
pg.setConfigOptions(antialias=False)
self.plot = pg.PlotWidget()
self.plot.setLabel("bottom", "采样点")
self.plot.setLabel("left", "数值")
self.plot.showGrid(x=True, y=True, alpha=0.3)
self.plot.addLegend(offset=(10, 10))
self.curve1 = self.plot.plot(pen=pg.mkPen("c", width=1), name="CH1")
self.curve2 = self.plot.plot(pen=pg.mkPen("y", width=1), name="CH2")
# 性能优化: 自动降采样
self.curve1.setDownsampling(method="peak", auto=True)
self.curve2.setDownsampling(method="peak", auto=True)
root.addWidget(self.plot)
# ---- 串口列表 ----
def _refresh_ports(self):
self.port_combo.clear()
for info in serial.tools.list_ports.comports():
self.port_combo.addItem(f"{info.device} - {info.description}", info.device)
# ---- 连接 / 断开 ----
def _on_connect(self, checked: bool):
if checked:
port = self.port_combo.currentData()
if not port:
QMessageBox.warning(self, "提示", "请先选择串口")
self.connect_btn.setChecked(False)
return
self._connect(port)
else:
self._disconnect()
def _connect(self, port: str):
self.thread = ReaderThread(port)
self.thread.data_received.connect(self._on_data)
self.thread.frame_raw.connect(self._on_frame_raw)
self.thread.error_occurred.connect(self._on_reader_error)
self.thread.start()
self.connect_btn.setText("断开")
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.port_combo.setEnabled(False)
self.refresh_btn.setEnabled(False)
self.status_lbl.setText(f"已连接 {port}")
self.temp_lbl.setText("温度: -- ℃")
def _disconnect(self):
self._stop_keepalive()
if self.thread is not None:
self.thread.stop()
self.thread.wait(2000)
self.thread = None
self.connect_btn.setText("连接")
self.connect_btn.setChecked(False)
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(False)
self.port_combo.setEnabled(True)
self.refresh_btn.setEnabled(True)
self.status_lbl.setText("未连接")
def _on_reader_error(self, msg: str):
self.status_lbl.setText(f"错误: {msg}")
# ---- 采集控制 ----
def _on_start(self):
if self.thread is None:
return
self._first_frame = True # 标记下一帧为"采集后第一帧", 用于识别温度帧
self._send_start_keepalive() # 立即发送一次启动命令
self.keepalive_timer.start(KEEPALIVE_INTERVAL_MS) # 周期保活
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.status_lbl.setText("采集中...")
self.temp_lbl.setText("温度: -- ℃")
def _on_stop(self):
self._stop_keepalive()
if self.thread is not None:
self.thread.send_command(build_command(0)) # 时间=0 强制停止
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.status_lbl.setText("已停止")
def _send_start_keepalive(self):
if self.thread is not None:
self.thread.send_command(build_command(CMD_START_TIME_MS))
def _stop_keepalive(self):
if self.keepalive_timer.isActive():
self.keepalive_timer.stop()
# ---- 数据 / 绘图 ----
@pyqtSlot(bytes)
def _on_frame_raw(self, raw: bytes):
"""原始4字节(不含帧头)回调。
采集后第一帧如满足 data[0]+data[2]==0xFF 则视作温度帧,不绘制。
"""
if not self._first_frame:
return
self._first_frame = False
if len(raw) == 4 and (raw[0] + raw[2]) & 0xFF == 0xFF:
# 满足温度帧校验, 记录温度并抑制后续绘制
t_raw = raw[0]
self.temp_lbl.setText(f"温度: {t_raw} ℃")
setattr(self, "_skip_next_data", True) # 跳过紧随其后的 data_received
@pyqtSlot(int, int)
def _on_data(self, ch1: int, ch2: int):
# frame_raw 先于 data_received 发出; 若被标记为温度帧则跳过绘制
if getattr(self, "_skip_next_data", False):
self._skip_next_data = False
return
self.x.append(self.sample_index)
self.y1.append(ch1)
self.y2.append(ch2)
self.sample_index += 1
def _refresh_plot(self):
if not self.x:
return
self.curve1.setData(self.x, self.y1)
self.curve2.setData(self.x, self.y2)
if self.follow_chk.isChecked() and self.sample_index > 0:
last = self.sample_index - 1
lo = last - FOLLOW_WINDOW
if lo < 0:
lo = 0
self.plot.setXRange(lo, last, padding=0.0)
def _on_clear(self):
self.x.clear()
self.y1.clear()
self.y2.clear()
self.sample_index = 0
self.curve1.setData([], [])
self.curve2.setData([], [])
self.plot.autoRange() # 重置视图
# ---- 关闭清理 ----
def closeEvent(self, event):
self._disconnect()
super().closeEvent(event)
def main():
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()