1 修改了发送框不发送的bug 2 增加了大数据模式,以 end 或5000结尾

This commit is contained in:
wangxibao 2024-09-24 11:39:44 +08:00
parent 5823199abe
commit 2c9ecfe26f
7 changed files with 189 additions and 10 deletions

View File

@ -0,0 +1,56 @@
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QGridLayout, QApplication,QMainWindow
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from PyQt5.QtCore import Qt
class MyFigureCanvas(FigureCanvas):
def __init__(self, parent=None):
self.figure = Figure()
super(MyFigureCanvas, self).__init__(self.figure)
self.setParent(parent)
class ChartDialog(QDialog):
def __init__(self, data=None, title="Line Chart", xlabel="X", ylabel="Y", parent=None):
super(ChartDialog, self).__init__(parent)
self.setWindowFlags(Qt.Window)
self.data = data if data is not None else (range(2, 26, 2), [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15])
self.title = title
self.xlabel = xlabel
self.ylabel = ylabel
self.initUI()
def initUI(self):
self.setWindowTitle(self.title) # 确保标题被设置
layout = QGridLayout()
self.figureCanvas = MyFigureCanvas(self)
self.draw_figure()
self.navigationToolbar = NavigationToolbar2QT(self.figureCanvas, self)
layout.addWidget(self.navigationToolbar, 0, 0, 1, 1)
layout.addWidget(self.figureCanvas, 1, 0, 1, 1)
self.setLayout(layout)
#self.setGeometry(300, 300, 600, 400)
def draw_figure(self):
self.figureCanvas.figure.clear() # 清除整个 Figure
self.axes = self.figureCanvas.figure.add_subplot(111) # 添加新的 Axes
self.axes.set_title(self.title)
self.axes.set_xlabel(self.xlabel)
self.axes.set_ylabel(self.ylabel)
x, y = self.data
self.axes.plot(x, y, color='red')
self.figureCanvas.figure.canvas.draw_idle() # 更新画布上的绘图
def tans_data(self,data):
self.data = data
def main():
app = QApplication([])
dialog = ChartDialog()
dialog.show()
app.exec_()
if __name__ == "__main__":
main()

Binary file not shown.

View File

@ -18,6 +18,7 @@ from PyUartUi import Ui_UartAssistant
from UartDataPolt import QChartViewPlot,UpdateDataThread,GetDataQX,GetDataTF,GetDataOther from UartDataPolt import QChartViewPlot,UpdateDataThread,GetDataQX,GetDataTF,GetDataOther
from PyQt5.QtChart import QChartView from PyQt5.QtChart import QChartView
from PyQt5.QtGui import QIcon from PyQt5.QtGui import QIcon
from BigData_Plot import ChartDialog
class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant): class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
@ -33,7 +34,9 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.get_data_other = GetDataOther() self.get_data_other = GetDataOther()
self.get_data_other.IndOfReturn(0) #根据数据特点给一个初始值 self.get_data_other.IndOfReturn(0) #根据数据特点给一个初始值
self.chart_dialog = ChartDialog()
self.init() self.init()
self.ser = serial.Serial() #创建一个空对象 self.ser = serial.Serial() #创建一个空对象
self.port_check() self.port_check()
@ -90,6 +93,10 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.lineUtf8 = "" self.lineUtf8 = ""
# 用于标志是否开始存CSV # 用于标志是否开始存CSV
self.CsvFlag = 0 self.CsvFlag = 0
#用于暂存大数据
self.bigdata=[]
#开启大数据模式标志位
self.flag_bigdata =0
# ============================================================================= # =============================================================================
# def wheelEvent(self, event): # def wheelEvent(self, event):
# if self.plot_view.underMouse: # if self.plot_view.underMouse:
@ -151,7 +158,7 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.checkBoxReapitSend.stateChanged.connect(self.data_send_timer) self.checkBoxReapitSend.stateChanged.connect(self.data_send_timer)
# 发送数据按钮 # 发送数据按钮
self.pushButtonSend.clicked.connect(self.data_send) self.pushButtonSend.clicked.connect(lambda: self.data_send(text_quick=None)) #此处处理默认 传递text_quick=false
# 保存日志 # 保存日志
self.pushButtonLogSave.clicked.connect(self.savefiles) self.pushButtonLogSave.clicked.connect(self.savefiles)
@ -180,7 +187,7 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
# 快捷指令扩展区域 # 快捷指令扩展区域
self.pushButton_expend.clicked.connect(self.adjust_sidebar) self.pushButton_expend.clicked.connect(self.adjust_sidebar)
# 创建一个通用的槽函数来处理所有按钮 # 创建一个通用的槽函数来处理所有按钮
# 例如使用lambda表达式传递额外的参数 # 例如使用lambda表达式传递额外的参数
for i in range(1, 21): # 假设有20个按钮 for i in range(1, 21): # 假设有20个按钮
# getattr(self, f'pushButtonQuick_{i}').clicked.connect( # getattr(self, f'pushButtonQuick_{i}').clicked.connect(
# lambda checked, line_edit=f'lineEditQuick_{i}': self.onPushButtonQuickClicked(line_edit) # lambda checked, line_edit=f'lineEditQuick_{i}': self.onPushButtonQuickClicked(line_edit)
@ -194,6 +201,8 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
button_id = f'pushButtonQuick_{i}' button_id = f'pushButtonQuick_{i}'
button.setContextMenuPolicy(Qt.CustomContextMenu) button.setContextMenuPolicy(Qt.CustomContextMenu)
button.customContextMenuRequested.connect(lambda position, button_id=button_id: self.onButtonRightClicked(button_id)) button.customContextMenuRequested.connect(lambda position, button_id=button_id: self.onButtonRightClicked(button_id))
#大数据模式
self.pushButton_bigdata.clicked.connect(self.bigdata_show)
# %% 串口检测 # %% 串口检测
def port_check(self): def port_check(self):
@ -336,6 +345,8 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
# 自动保存日志 # 自动保存日志
if self.checkBoxAutoSaveLog.isChecked(): if self.checkBoxAutoSaveLog.isChecked():
self.AutoSaveLog() self.AutoSaveLog()
if self.flag_bigdata == 1:
self.BigDataPlot()
@ -380,9 +391,9 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
QMessageBox.critical(self, '定时发送数据异常', '请设置正确的数值类型!') QMessageBox.critical(self, '定时发送数据异常', '请设置正确的数值类型!')
# %%发送数据 # %%发送数据
def data_send(self,text_quick = None): def data_send(self,text_quick=None):
if self.ser.isOpen(): if self.ser.isOpen():
if text_quick== None: if text_quick is None:
input_s = self.textEditSend.toPlainText() input_s = self.textEditSend.toPlainText()
else: else:
input_s = text_quick input_s = text_quick
@ -486,7 +497,7 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
# 写入当前日期的文件,打开文件,如果文件不存在则创建,如果存在则追加内容 # 写入当前日期的文件,打开文件,如果文件不存在则创建,如果存在则追加内容
with open(self.filename, 'a', encoding='utf-8',newline='') as file: with open(self.filename, 'a', encoding='utf-8',newline='') as file:
#print (data.decode('utf-8'))
self.lineUtf8 = line.decode('utf-8') self.lineUtf8 = line.decode('utf-8')
saveData = (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + " " + self.lineUtf8 + "\r\n" saveData = (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + " " + self.lineUtf8 + "\r\n"
@ -537,7 +548,8 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3))) self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3)))
self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3))) self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3)))
else: else:
print("dataSplit type:",type(dataSplit)) #print("dataSplit type:",type(dataSplit))
return None
elif self.radioButtonOtherData.isChecked() : elif self.radioButtonOtherData.isChecked() :
print(self.lineUtf8) print(self.lineUtf8)
@ -561,14 +573,40 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3))) self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3)))
self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3))) self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3)))
else: else:
print("dataSplit type:",type(dataSplit)) #print("dataSplit type:",type(dataSplit))
return None
except Exception as e: except Exception as e:
print(f"Error reading configuration: {e}") print(f"Error reading configuration: {e}")
print("自动保存日志失败") print("自动保存日志失败")
pass pass
def BigDataPlot(self):
try:
lines = self.buffer.split(b'\n') # 或者使用 b'\r\n' 根据你的需要
# 最后一个元素可能不包含完整的行,所以将其保留作为新的缓存
self.buffer = lines.pop()
# 处理每一行数据
for line in lines:
# 注意:每行数据可能不包含结尾的换行符,所以在处理前检查一下
if line.endswith(b'\r'):
line = line[:-1] # 移除回车
lineUtf8 = line.decode('utf-8')
if "end" in lineUtf8.lower() or len(self.bigdata)>4999:
tansData = (range(len(self.bigdata)),self.bigdata)
self.chart_dialog.tans_data(tansData)
self.chart_dialog.draw_figure()
self.bigdata = []
elif lineUtf8.isdigit():
self.bigdata.append(float(lineUtf8))
#print(f'bigdata length:{len(self.bigdata)}')
except:
return None
def send_data_clear(self): def send_data_clear(self):
self.textEditSend.setText("") self.textEditSend.setText("")
@ -619,6 +657,7 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.radioButtonCH4TF.setEnabled(False) self.radioButtonCH4TF.setEnabled(False)
self.radioButtonOtherData.setEnabled(False) self.radioButtonOtherData.setEnabled(False)
self.checkBoxAutoSaveCsv.setEnabled(True) self.checkBoxAutoSaveCsv.setEnabled(True)
self.pushButton_bigdata.setEnabled(False)
if self.radioButtonCH4QX.isChecked(): if self.radioButtonCH4QX.isChecked():
self.comboBoxPlot.addItems(["甲烷浓度","环境温度","激光器温度","激光强度"]) self.comboBoxPlot.addItems(["甲烷浓度","环境温度","激光器温度","激光强度"])
@ -650,6 +689,7 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.radioButtonCH4TF.setEnabled(True) self.radioButtonCH4TF.setEnabled(True)
self.radioButtonOtherData.setEnabled(True) self.radioButtonOtherData.setEnabled(True)
self.checkBoxAutoSaveCsv.setEnabled(False) self.checkBoxAutoSaveCsv.setEnabled(False)
self.pushButton_bigdata.setEnabled(True)
self.comboBoxPlot.clear() self.comboBoxPlot.clear()
self.CsvFlag = 0 self.CsvFlag = 0
@ -690,6 +730,16 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
if ok and new_name: if ok and new_name:
button.setText(new_name) button.setText(new_name)
def bigdata_show(self):
if self.flag_bigdata == 0:
self.chart_dialog.show()
self.flag_bigdata = 1
self.checkBoxAutoSaveLog.setChecked(False)
else:
self.chart_dialog.close()
self.flag_bigdata = 0
self.checkBoxAutoSaveLog.setChecked(True)
#执行 #执行
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -362,6 +362,9 @@ class Ui_UartAssistant(object):
self.comboBoxPlot.setSizePolicy(sizePolicy) self.comboBoxPlot.setSizePolicy(sizePolicy)
self.comboBoxPlot.setObjectName("comboBoxPlot") self.comboBoxPlot.setObjectName("comboBoxPlot")
self.horizontalLayout_8.addWidget(self.comboBoxPlot) self.horizontalLayout_8.addWidget(self.comboBoxPlot)
self.pushButton_bigdata = QtWidgets.QPushButton(self.widget_2)
self.pushButton_bigdata.setGeometry(QtCore.QRect(330, 40, 75, 20))
self.pushButton_bigdata.setObjectName("pushButton_bigdata")
self.verticalLayout_4.addWidget(self.widget_2) self.verticalLayout_4.addWidget(self.widget_2)
self.plot_view = QChartView(self.tab_2) self.plot_view = QChartView(self.tab_2)
self.plot_view.setEnabled(True) self.plot_view.setEnabled(True)
@ -713,6 +716,7 @@ class Ui_UartAssistant(object):
self.radioButtonOtherData.setText(_translate("UartAssistant", "其他数据")) self.radioButtonOtherData.setText(_translate("UartAssistant", "其他数据"))
self.checkBoxAutoSaveCsv.setText(_translate("UartAssistant", "自动保存Csv")) self.checkBoxAutoSaveCsv.setText(_translate("UartAssistant", "自动保存Csv"))
self.pushButtonStopPlot.setText(_translate("UartAssistant", "停止绘图")) self.pushButtonStopPlot.setText(_translate("UartAssistant", "停止绘图"))
self.pushButton_bigdata.setText(_translate("UartAssistant", "大数据模式"))
self.pushButtonResetPlot.setText(_translate("UartAssistant", "重置图形")) self.pushButtonResetPlot.setText(_translate("UartAssistant", "重置图形"))
self.label_SendNum_2.setText(_translate("UartAssistant", "当前数值")) self.label_SendNum_2.setText(_translate("UartAssistant", "当前数值"))
self.label_SendNum_3.setText(_translate("UartAssistant", "窗口均值")) self.label_SendNum_3.setText(_translate("UartAssistant", "窗口均值"))

View File

@ -670,7 +670,7 @@
<bool>false</bool> <bool>false</bool>
</property> </property>
<property name="currentIndex"> <property name="currentIndex">
<number>1</number> <number>0</number>
</property> </property>
<widget class="QWidget" name="tab"> <widget class="QWidget" name="tab">
<attribute name="title"> <attribute name="title">
@ -912,6 +912,19 @@
</item> </item>
</layout> </layout>
</widget> </widget>
<widget class="QPushButton" name="pushButton_bigdata">
<property name="geometry">
<rect>
<x>330</x>
<y>40</y>
<width>75</width>
<height>20</height>
</rect>
</property>
<property name="text">
<string>大数据模式</string>
</property>
</widget>
</widget> </widget>
</item> </item>
<item> <item>

View File

@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 09:34:24 2024
@author: WANGXIBAO
"""
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QVBoxLayout, QDialog, QDialogButtonBox, QMessageBox
class RenameDialog(QDialog):
def __init__(self, old_name, parent=None):
super().__init__(parent)
self.old_name = old_name
self.init_ui()
def init_ui(self):
layout = QVBoxLayout(self)
self.lineEdit = QLineEdit(self.old_name)
layout.addWidget(self.lineEdit)
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
layout.addWidget(self.buttonBox)
def get_new_name(self):
return self.lineEdit.text()
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
layout = QVBoxLayout(self)
self.pushButton = QPushButton('Click or Double Click to Rename')
self.pushButton.setFixedSize(200, 50)
self.pushButton.clicked.connect(self.rename_button)
layout.addWidget(self.pushButton)
self.setLayout(layout)
def rename_button(self):
clicked_button = self.sender()
if clicked_button:
dialog = RenameDialog(clicked_button.text(), self)
if dialog.exec_():
new_name = dialog.get_new_name()
if new_name: # 确保新名称不为空
clicked_button.setText(new_name)
else:
QMessageBox.warning(self, "Rename Error", "The new name cannot be empty.")
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()

View File

@ -11,7 +11,7 @@ button03 = write 3,0|B*1000
button04 = write 4,0|可调电阻 button04 = write 4,0|可调电阻
button05 = write 5,30|电阻抽头 button05 = write 5,30|电阻抽头
button06 = write 6,0|输出温度 button06 = write 6,0|输出温度
button07 = write 7,0|输出激光 button07 = write 7,1|输出激光
button08 = write 8,1|输出状态 button08 = write 8,1|输出状态
button09 = write 9,0|激光温补 button09 = write 9,0|激光温补
button10 = write 10,100|噪声长度 button10 = write 10,100|噪声长度