增加通过ini配置 头和 正则表达

This commit is contained in:
wangxibao 2024-07-12 08:52:27 +08:00
parent 88ed558663
commit 33506c78bb
13 changed files with 417 additions and 65 deletions

2
.gitignore vendored
View File

@ -160,3 +160,5 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder. # option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/ #.idea/
*.txt
*.csv

5
OtherData.ini Normal file
View File

@ -0,0 +1,5 @@
[OtherData_config]
regular = \+?-?\d+(?:\.\d+)?
headstr = A+
rowtitle = time,DATA1,DATA2

View File

@ -0,0 +1,5 @@
[OtherData_config]
regular = \+?-?\d+(?:\.\d+)?
headstr = A+
rowtitle = time,DATA1,DATA2

View File

@ -6,7 +6,7 @@ Created on Mon May 27 14:31:38 2024
""" """
import sys import sys
import serial,csv import serial
import serial.tools.list_ports import serial.tools.list_ports
import time,datetime import time,datetime
@ -15,10 +15,11 @@ from PyQt5.Qt import QPainter
from PyQt5.QtWidgets import QMessageBox ,QFileDialog from PyQt5.QtWidgets import QMessageBox ,QFileDialog
from PyQt5.QtCore import QTimer from PyQt5.QtCore import QTimer
from PyUartUi import Ui_UartAssistant from PyUartUi import Ui_UartAssistant
from UartDataPolt import QChartViewPlot,UpdateDataThread,GetDataQX 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
class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant): class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
# %%初始化程序 # %%初始化程序
def __init__(self): def __init__(self):
@ -27,13 +28,18 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.update_data_thread = UpdateDataThread() # 创建更新波形数据线程 self.update_data_thread = UpdateDataThread() # 创建更新波形数据线程
self.get_data_qx = GetDataQX() self.get_data_qx = GetDataQX()
self.get_data_qx.IndOfReturn(0) #根据数据特点给一个初始值 self.get_data_qx.IndOfReturn(0) #根据数据特点给一个初始值
self.get_data_tf = GetDataTF()
self.get_data_tf.IndOfReturn(0) #根据数据特点给一个初始值
self.get_data_other = GetDataOther()
self.get_data_other.IndOfReturn(0) #根据数据特点给一个初始值
self.init() self.init()
self.ser = serial.Serial() #创建一个空对象 self.ser = serial.Serial() #创建一个空对象
self.port_check() self.port_check()
# 设置Logo和标题 # 设置Logo和标题
self.setWindowIcon(QIcon('D:/workspace/py/PyUartAssistant/favicon.png')) self.setWindowIcon(QIcon('./favicon.ico'))
self.setWindowTitle("调试助手") self.setWindowTitle("调试助手")
# 设置禁止拉伸窗口大小 # 设置禁止拉伸窗口大小
self.setFixedSize(self.width(), self.height()) self.setFixedSize(self.width(), self.height())
@ -65,7 +71,11 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
# 用于暂存接收的串口数据 # 用于暂存接收的串口数据
self.buffer = b'' self.buffer = b''
# ============================================================================= # 用于暂存解码数据
self.lineUtf8 = ""
# 用于标志是否开始存CSV
self.CsvFlag = 0
# =============================================================================
# def wheelEvent(self, event): # def wheelEvent(self, event):
# if self.plot_view.underMouse: # if self.plot_view.underMouse:
# # 鼠标滚轮:缩放Qchart波形 # # 鼠标滚轮:缩放Qchart波形
@ -276,49 +286,11 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.data_num_received += num self.data_num_received += num
self.lineEditReceiveNum.setText(str(self.data_num_received)) self.lineEditReceiveNum.setText(str(self.data_num_received))
try: # 自动保存日志
lines = self.buffer.split(b'\n') # 或者使用 b'\r\n' 根据你的需要 if self.checkBoxAutoSaveLog.isChecked():
# 最后一个元素可能不包含完整的行,所以将其保留作为新的缓存 self.AutoSaveLog()
self.buffer = lines.pop()
# 处理每一行数据
for line in lines:
# 注意:每行数据可能不包含结尾的换行符,所以在处理前检查一下
if line.endswith(b'\r'):
line = line[:-1] # 移除回车
# 写入当前日期的文件,打开文件,如果文件不存在则创建,如果存在则追加内容
if self.checkBoxAutoSaveLog.isChecked():
with open(self.filename, 'a', encoding='utf-8',newline='') as file:
#print (data.decode('utf-8'))
lineUtf8 = line.decode('utf-8')
saveData = (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + " " + lineUtf8 + "\r\n"
#print("saveData:",saveData)
file.write(saveData) # 写入内容
if lineUtf8[:2]=="A+":
print(lineUtf8)
dataSplit = self.get_data_qx.Transdata(lineUtf8)
self.filenameCsv= self.file + ".csv"
if self.checkBoxAutoSaveCsv.isChecked(): #写入CSV文件
try:
self.get_data_qx.SaveCsv(self.filenameCsv)
except:
print("写入CSV失败")
pass
self.update_data_thread.SetFlag(1)
self.update_data_thread.SetReceiveData(dataSplit)
#更新当前数据
self.lineEditCurrentValue.setText(str(round(dataSplit,3)))
self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3)))
self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3)))
#print(dataSplit)
#print("接收发数",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
except:
print("预处理数据有问题")
pass
except: except:
QMessageBox.critical(self, '串口异常', '串口接收数据异常,请重新连接设备!') QMessageBox.critical(self, '串口异常', '串口接收数据异常,请重新连接设备!')
@ -398,7 +370,6 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.data_num_sended += num self.data_num_sended += num
self.lineEditSendNum.setText(str(self.data_num_sended)) self.lineEditSendNum.setText(str(self.data_num_sended))
else: else:
pass pass
@ -429,6 +400,105 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
#webbrowser.open('https://blog.csdn.net/m0_38106923') #webbrowser.open('https://blog.csdn.net/m0_38106923')
# %%清除发送数据显示 # %%清除发送数据显示
# 自动保存日志 log he csv
def AutoSaveLog(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] # 移除回车
# 写入当前日期的文件,打开文件,如果文件不存在则创建,如果存在则追加内容
with open(self.filename, 'a', encoding='utf-8',newline='') as file:
#print (data.decode('utf-8'))
self.lineUtf8 = line.decode('utf-8')
saveData = (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + " " + self.lineUtf8 + "\r\n"
#print("saveData:",saveData)
file.write(saveData) # 写入内容
#判断选择的何种格式数据
if self.radioButtonCH4QX.isChecked() and self.lineUtf8[:2]=="A+":
print(self.lineUtf8)
dataSplit = self.get_data_qx.Transdata(self.lineUtf8)
self.filenameCsv= self.file + ".csv"
if self.checkBoxAutoSaveCsv.isChecked() and self.CsvFlag: #写入CSV文件
try:
self.get_data_qx.SaveCsv(self.filenameCsv)
except:
print("写入CSV失败")
pass
self.update_data_thread.SetFlag(1)
self.update_data_thread.SetReceiveData(dataSplit)
#更新当前数据
self.lineEditCurrentValue.setText(str(round(dataSplit,3)))
self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3)))
self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3)))
#print(dataSplit)
#print("接收发数",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
elif self.radioButtonCH4TF.isChecked() :
print(self.lineUtf8)
dataSplit = self.get_data_tf.Transdata(self.lineUtf8)
#print("dataSplit",type(dataSplit))
if isinstance(dataSplit, (float, int)):
self.filenameCsv= self.file + ".csv"
if self.checkBoxAutoSaveCsv.isChecked() and self.CsvFlag: #写入CSV文件
try:
self.get_data_tf.SaveCsv(self.filenameCsv)
except:
print("写入CSV失败")
pass
self.update_data_thread.SetFlag(1)
#print("dataSplit",dataSplit)
self.update_data_thread.SetReceiveData(dataSplit)
#更新当前数据
self.lineEditCurrentValue.setText(str(round(dataSplit,3)))
self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3)))
self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3)))
else:
print("dataSplit type:",type(dataSplit))
elif self.radioButtonOtherData.isChecked() :
print(self.lineUtf8)
dataSplit = self.get_data_other.Transdata(self.lineUtf8)
#print("dataSplit",type(dataSplit))
if isinstance(dataSplit, (float, int)):
self.filenameCsv= self.file + ".csv"
if self.checkBoxAutoSaveCsv.isChecked() and self.CsvFlag: #写入CSV文件
try:
self.get_data_other.SaveCsv(self.filenameCsv)
except:
print("写入CSV失败")
pass
self.update_data_thread.SetFlag(1)
#print("dataSplit",dataSplit)
self.update_data_thread.SetReceiveData(dataSplit)
#更新当前数据
self.lineEditCurrentValue.setText(str(round(dataSplit,3)))
self.lineEditWindowMean.setText (str(round(self.plot_qchart.windowAverage,3)))
self.lineEditWindowMSE.setText (str(round(self.plot_qchart.windowStd,3)))
else:
print("dataSplit type:",type(dataSplit))
except Exception as e:
print(f"Error reading configuration: {e}")
print("自动保存日志失败")
pass
def send_data_clear(self): def send_data_clear(self):
self.textEditSend.setText("") self.textEditSend.setText("")
@ -477,16 +547,27 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.pushButtonStopPlot.setEnabled(True) self.pushButtonStopPlot.setEnabled(True)
self.radioButtonCH4QX.setEnabled(False) self.radioButtonCH4QX.setEnabled(False)
self.radioButtonCH4TF.setEnabled(False) self.radioButtonCH4TF.setEnabled(False)
self.radioButtonOtherData.setEnabled(False)
self.checkBoxAutoSaveCsv.setEnabled(True) self.checkBoxAutoSaveCsv.setEnabled(True)
if self.radioButtonCH4QX.isChecked():
self.comboBoxPlot.addItems(["甲烷浓度","环境温度","激光器温度","激光强度"])
self.comboBoxPlot.setCurrentText("甲烷浓度")
self.get_data_qx.IndOfReturn(0)
elif self.radioButtonCH4TF.isChecked():
iterm = self.get_data_tf.rowTitle[1:]
print("iterm",iterm)
self.comboBoxPlot.addItems(iterm)
elif self.radioButtonOtherData.isChecked():
iterm = self.get_data_other.rowTitle[1:]
print("iterm",iterm)
self.comboBoxPlot.addItems(iterm)
self.comboBoxPlot.addItems(["甲烷浓度","环境温度","激光器温度","激光强度"])
self.comboBoxPlot.setCurrentText("甲烷浓度")
#self.update_data_thread.SetPlotItem(0) #self.update_data_thread.SetPlotItem(0)
self.get_data_qx.IndOfReturn(0)
self.update_data_thread.restart() self.update_data_thread.restart()
self.CsvFlag = 1
@ -497,8 +578,10 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
self.pushButtonStopPlot.setEnabled(False) self.pushButtonStopPlot.setEnabled(False)
self.radioButtonCH4QX.setEnabled(True) self.radioButtonCH4QX.setEnabled(True)
self.radioButtonCH4TF.setEnabled(True) self.radioButtonCH4TF.setEnabled(True)
self.radioButtonOtherData.setEnabled(True)
self.checkBoxAutoSaveCsv.setEnabled(False) self.checkBoxAutoSaveCsv.setEnabled(False)
self.comboBoxPlot.clear() self.comboBoxPlot.clear()
self.CsvFlag = 0
def update_data_thread_slot(self, data): def update_data_thread_slot(self, data):
# 线程回调函数 # 线程回调函数
@ -512,6 +595,8 @@ class PyQt5Serial(QtWidgets.QWidget,Ui_UartAssistant):
#self.update_data_thread.SetPlotItem(index) #self.update_data_thread.SetPlotItem(index)
self.get_data_qx.IndOfReturn(index) self.get_data_qx.IndOfReturn(index)
#self.plot_qchart.series.replace([]) #self.plot_qchart.series.replace([])
self.get_data_tf.IndOfReturn(index)
self.get_data_other.IndOfReturn(index)
def plot_reset(self): def plot_reset(self):
self.plot_qchart.zoomReset() self.plot_qchart.zoomReset()

View File

@ -15,6 +15,9 @@ class Ui_UartAssistant(object):
def setupUi(self, UartAssistant): def setupUi(self, UartAssistant):
UartAssistant.setObjectName("UartAssistant") UartAssistant.setObjectName("UartAssistant")
UartAssistant.resize(1121, 714) UartAssistant.resize(1121, 714)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
UartAssistant.setWindowIcon(icon)
self.groupBox = QtWidgets.QGroupBox(UartAssistant) self.groupBox = QtWidgets.QGroupBox(UartAssistant)
self.groupBox.setGeometry(QtCore.QRect(30, 20, 241, 281)) self.groupBox.setGeometry(QtCore.QRect(30, 20, 241, 281))
self.groupBox.setObjectName("groupBox") self.groupBox.setObjectName("groupBox")
@ -236,10 +239,11 @@ class Ui_UartAssistant(object):
self.radioButtonCH4QX.setToolTipDuration(1) self.radioButtonCH4QX.setToolTipDuration(1)
self.radioButtonCH4QX.setStatusTip("") self.radioButtonCH4QX.setStatusTip("")
self.radioButtonCH4QX.setAutoFillBackground(False) self.radioButtonCH4QX.setAutoFillBackground(False)
self.radioButtonCH4QX.setChecked(True) self.radioButtonCH4QX.setChecked(False)
self.radioButtonCH4QX.setObjectName("radioButtonCH4QX") self.radioButtonCH4QX.setObjectName("radioButtonCH4QX")
self.radioButtonCH4TF = QtWidgets.QRadioButton(self.tab_2) self.radioButtonCH4TF = QtWidgets.QRadioButton(self.tab_2)
self.radioButtonCH4TF.setGeometry(QtCore.QRect(250, 10, 51, 16)) self.radioButtonCH4TF.setGeometry(QtCore.QRect(250, 10, 51, 16))
self.radioButtonCH4TF.setChecked(True)
self.radioButtonCH4TF.setObjectName("radioButtonCH4TF") self.radioButtonCH4TF.setObjectName("radioButtonCH4TF")
self.pushButtonStartPlot = QtWidgets.QPushButton(self.tab_2) self.pushButtonStartPlot = QtWidgets.QPushButton(self.tab_2)
self.pushButtonStartPlot.setGeometry(QtCore.QRect(60, 10, 75, 23)) self.pushButtonStartPlot.setGeometry(QtCore.QRect(60, 10, 75, 23))
@ -251,7 +255,7 @@ class Ui_UartAssistant(object):
self.comboBoxPlot.setGeometry(QtCore.QRect(180, 40, 191, 22)) self.comboBoxPlot.setGeometry(QtCore.QRect(180, 40, 191, 22))
self.comboBoxPlot.setObjectName("comboBoxPlot") self.comboBoxPlot.setObjectName("comboBoxPlot")
self.checkBoxAutoSaveCsv = QtWidgets.QCheckBox(self.tab_2) self.checkBoxAutoSaveCsv = QtWidgets.QCheckBox(self.tab_2)
self.checkBoxAutoSaveCsv.setGeometry(QtCore.QRect(400, 10, 121, 16)) self.checkBoxAutoSaveCsv.setGeometry(QtCore.QRect(460, 10, 121, 16))
self.checkBoxAutoSaveCsv.setChecked(True) self.checkBoxAutoSaveCsv.setChecked(True)
self.checkBoxAutoSaveCsv.setObjectName("checkBoxAutoSaveCsv") self.checkBoxAutoSaveCsv.setObjectName("checkBoxAutoSaveCsv")
self.layoutWidget4 = QtWidgets.QWidget(self.tab_2) self.layoutWidget4 = QtWidgets.QWidget(self.tab_2)
@ -290,6 +294,10 @@ class Ui_UartAssistant(object):
self.pushButtonResetPlot = QtWidgets.QPushButton(self.tab_2) self.pushButtonResetPlot = QtWidgets.QPushButton(self.tab_2)
self.pushButtonResetPlot.setGeometry(QtCore.QRect(70, 620, 61, 23)) self.pushButtonResetPlot.setGeometry(QtCore.QRect(70, 620, 61, 23))
self.pushButtonResetPlot.setObjectName("pushButtonResetPlot") self.pushButtonResetPlot.setObjectName("pushButtonResetPlot")
self.radioButtonOtherData = QtWidgets.QRadioButton(self.tab_2)
self.radioButtonOtherData.setGeometry(QtCore.QRect(310, 10, 71, 16))
self.radioButtonOtherData.setChecked(False)
self.radioButtonOtherData.setObjectName("radioButtonOtherData")
self.tabWidget.addTab(self.tab_2, "") self.tabWidget.addTab(self.tab_2, "")
self.tabWidget.raise_() self.tabWidget.raise_()
self.groupBox.raise_() self.groupBox.raise_()
@ -377,5 +385,6 @@ class Ui_UartAssistant(object):
self.label_SendNum_3.setText(_translate("UartAssistant", "窗口均值")) self.label_SendNum_3.setText(_translate("UartAssistant", "窗口均值"))
self.label_SendNum_4.setText(_translate("UartAssistant", "窗口标准差")) self.label_SendNum_4.setText(_translate("UartAssistant", "窗口标准差"))
self.pushButtonResetPlot.setText(_translate("UartAssistant", "重置图形")) self.pushButtonResetPlot.setText(_translate("UartAssistant", "重置图形"))
self.radioButtonOtherData.setText(_translate("UartAssistant", "其他数据"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("UartAssistant", "曲线绘制")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("UartAssistant", "曲线绘制"))
from PyQt5.QtChart import QChartView from PyQt5.QtChart import QChartView

View File

@ -13,6 +13,10 @@
<property name="windowTitle"> <property name="windowTitle">
<string>串口助手py版</string> <string>串口助手py版</string>
</property> </property>
<property name="windowIcon">
<iconset>
<normaloff>favicon.ico</normaloff>favicon.ico</iconset>
</property>
<widget class="QGroupBox" name="groupBox"> <widget class="QGroupBox" name="groupBox">
<property name="geometry"> <property name="geometry">
<rect> <rect>
@ -712,7 +716,7 @@
<string>CH4QX</string> <string>CH4QX</string>
</property> </property>
<property name="checked"> <property name="checked">
<bool>true</bool> <bool>false</bool>
</property> </property>
</widget> </widget>
<widget class="QRadioButton" name="radioButtonCH4TF"> <widget class="QRadioButton" name="radioButtonCH4TF">
@ -727,6 +731,9 @@
<property name="text"> <property name="text">
<string>CH4TF</string> <string>CH4TF</string>
</property> </property>
<property name="checked">
<bool>true</bool>
</property>
</widget> </widget>
<widget class="QPushButton" name="pushButtonStartPlot"> <widget class="QPushButton" name="pushButtonStartPlot">
<property name="geometry"> <property name="geometry">
@ -767,7 +774,7 @@
<widget class="QCheckBox" name="checkBoxAutoSaveCsv"> <widget class="QCheckBox" name="checkBoxAutoSaveCsv">
<property name="geometry"> <property name="geometry">
<rect> <rect>
<x>400</x> <x>460</x>
<y>10</y> <y>10</y>
<width>121</width> <width>121</width>
<height>16</height> <height>16</height>
@ -847,6 +854,22 @@
<string>重置图形</string> <string>重置图形</string>
</property> </property>
</widget> </widget>
<widget class="QRadioButton" name="radioButtonOtherData">
<property name="geometry">
<rect>
<x>310</x>
<y>10</y>
<width>71</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>其他数据</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</widget> </widget>
</widget> </widget>
<zorder>tabWidget</zorder> <zorder>tabWidget</zorder>

View File

@ -11,12 +11,11 @@ Created on Tue May 28 15:40:48 2024
import time,math,os import time,math,os
import re,csv,datetime import re,csv,datetime
import sys
from PyQt5.QtCore import QThread, pyqtSignal,Qt from PyQt5.QtCore import QThread, pyqtSignal,Qt
from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtChart import QChart, QValueAxis, QSplineSeries,QLineSeries from PyQt5.QtChart import QChart, QValueAxis, QSplineSeries,QLineSeries
from PyQt5.QtGui import QPen from PyQt5.QtGui import QPen
from configparser import ConfigParser
# 波形显示 # 波形显示
class QChartViewPlot(QChart): class QChartViewPlot(QChart):
@ -134,7 +133,7 @@ class UpdateDataThread(QThread):
#data = self.setReceiveData #data = self.setReceiveData
#print("发数",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) #print("发数",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
#print("data receive ",data) print("data receive ",self.setReceiveData)
# print(f"{data:.3f}") # print(f"{data:.3f}")
try: try:
@ -173,10 +172,11 @@ class UpdateDataThread(QThread):
class GetDataQX(): #读取请芯数据 class GetDataQX(): #读取请芯数据
def __init__(self, parent=None): def __init__(self, parent=None):
super().__init__() super().__init__()
self.regex = re.compile(r'(A\+|B\+|\s)+') # 编译正则表达式 self.indOfReturn =0
self.regexQx = re.compile(r'(A\+|B\+|\s)+') # 编译正则表达式
self.TIME_FORMAT = "%Y-%m-%d %H:%M:%S" self.TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
def Transdata(self,data): def Transdata(self,data):
parts = re.split(self.regex,data) parts = re.split(self.regexQx,data)
# 过滤掉空字符串 # 过滤掉空字符串
parts = [part for part in parts if part] parts = [part for part in parts if part]
#print(parts) #print(parts)
@ -216,3 +216,168 @@ class GetDataQX(): #读取请芯数据
def IndOfReturn(self,ind): def IndOfReturn(self,ind):
self.indOfReturn = ind self.indOfReturn = ind
class GetDataTF(): #读取费加罗或者自定义数据
def __init__(self, parent=None):
super().__init__()
self.indOfReturn =0
#self.regex = re.compile(r'(A\+|B\+|\s)+') # 编译正则表达式
self.TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
self.regularIniPath = "regular.ini" # 配置文件默认路径
self.headStr = ""
self.rowTitle=[]
self.CheckCfgIniData() # 初始化配置文件
def Transdata(self,data):
if data[:2] ==self.headStr:
# parts = re.split(self.regex,data)
# # 过滤掉空字符串
# parts = [part for part in parts if part]
#print(parts)
# methane = float(parts[1])
# airTemp = float(parts[3])
# laserTemp = float( parts[5])/1
# laerIntensity = float(parts[7])*10
# self.data2csv =[(timeCrvt,methane,airTemp,laserTemp,laerIntensity)]
self.data2csv = self.regex.findall(data)
#print(self.data2csv)
# if self.indOfReturn == 0:
# returnData = methane
# elif self.indOfReturn == 1:
# returnData = airTemp
# elif self.indOfReturn == 2:
# returnData = laserTemp
# elif self.indOfReturn == 3:
# returnData = laerIntensity
returnData = float(self.data2csv[self.indOfReturn])
print("returnData",returnData)
return returnData
else:
return "noNum"
def SaveCsv(self,filenameCsv):
# 打开一个文件用于写入,如果文件不存在则创建
if os.path.isfile(filenameCsv) == 0:
# 文件为空,需要写入表头
with open(filenameCsv, mode='w', newline='') as file:
writer = csv.writer(file)
#writer.writerow(('time', 'Methane', 'Air Temp', 'Laser Temp', 'Laser Intensity'))
writer.writerow(self.rowTitle)
else:
with open(filenameCsv, mode='a', newline='') as file:
# 创建一个写入器对象
writer = csv.writer(file)
# 写入数据行
timeCrvt=time.strftime(self.TIME_FORMAT, time.localtime())
self.data2csv.insert(0, timeCrvt)
print(self.data2csv)
writer.writerows([self.data2csv])
def IndOfReturn(self,ind):
self.indOfReturn = ind
def CheckCfgIniData(self):
if not os.path.exists(self.regularIniPath):
config = ConfigParser()
config.add_section('TF_config')
config.set('TF_config', 'regular', '\+?-?\d+(?:\.\d+)?')
#config.set('TF_config', 'regular', '(A\+|B\+|\s)+')
config.set('TF_config', 'headStr', 'A+')
config.set('TF_config', 'rowTitle', 'time,Methane,Air Temp,Laser Temp,Laser Intensity,amplification,NL,ND,Sinal,SNR,PEAK,Best Piont')
with open(self.regularIniPath, 'w') as f:
config.write(f)
config = ConfigParser()
config.read(self.regularIniPath, encoding='utf-8')
try:
self.headStr = config.get('TF_config', 'headStr')
self.regex = re.compile(config.get('TF_config', 'regular'))
self.rowTitleStr = config.get('TF_config', 'rowTitle')
self.rowTitle = self.rowTitleStr.split(',')
print(type(self.rowTitle))
print(f"Configuration read successfully: {self.headStr}, {self.regex}, {self.rowTitle}")
except Exception as e:
print(f"Error reading configuration: {e}")
class GetDataOther(): #读取费加罗或者自定义数据
def __init__(self, parent=None):
super().__init__()
self.indOfReturn =0
#self.regex = re.compile(r'(A\+|B\+|\s)+') # 编译正则表达式
self.TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
self.OtherIniPath = "OtherData.ini" # 配置文件默认路径
self.headStr = ""
self.rowTitle=[]
self.CheckCfgIniData() # 初始化配置文件
def Transdata(self,data):
if data[:2] ==self.headStr:
self.data2csv = self.regex.findall(data)
returnData = float(self.data2csv[self.indOfReturn])
print("returnData",returnData)
return returnData
else:
return "noNum"
def SaveCsv(self,filenameCsv):
# 打开一个文件用于写入,如果文件不存在则创建
if os.path.isfile(filenameCsv) == 0:
# 文件为空,需要写入表头
with open(filenameCsv, mode='w', newline='') as file:
writer = csv.writer(file)
#writer.writerow(('time', 'Methane', 'Air Temp', 'Laser Temp', 'Laser Intensity'))
writer.writerow(self.rowTitle)
else:
with open(filenameCsv, mode='a', newline='') as file:
# 创建一个写入器对象
writer = csv.writer(file)
# 写入数据行
timeCrvt=time.strftime(self.TIME_FORMAT, time.localtime())
self.data2csv.insert(0, timeCrvt)
print(self.data2csv)
writer.writerows([self.data2csv])
def IndOfReturn(self,ind):
self.indOfReturn = ind
def CheckCfgIniData(self):
if not os.path.exists(self.OtherIniPath):
config = ConfigParser()
config.add_section('OtherData_config')
config.set('OtherData_config', 'regular', '\+?-?\d+(?:\.\d+)?')
#config.set('TF_config', 'regular', '(A\+|B\+|\s)+')
config.set('OtherData_config', 'headStr', 'A+')
config.set('OtherData_config', 'rowTitle', 'time,DATA1,DATA2')
with open(self.OtherIniPath, 'w') as f:
config.write(f)
config = ConfigParser()
config.read(self.OtherIniPath, encoding='utf-8')
try:
self.headStr = config.get('OtherData_config', 'headStr')
self.regex = re.compile(config.get('OtherData_config', 'regular'))
self.rowTitleStr = config.get('OtherData_config', 'rowTitle')
self.rowTitle = self.rowTitleStr.split(',')
print(type(self.rowTitle))
print(f"Configuration read successfully: {self.headStr}, {self.regex}, {self.rowTitle}")
except Exception as e:
print(f"Error reading configuration: {e}")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,5 @@
[TF_config]
regular = \+?-?\d+(?:\.\d+)?
headstr = A+
rowtitle = time,Methane,Air Temp,Laser Temp,Laser Intensity,amplification,NL,ND,Sinal,SNR,PEAK,Best Piont

View File

@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 10:17:34 2024
@author: WANGXIBAO
"""
import re,os,csv
data = "A+000.00 +31.5 0057.92 +00.442 B+010 NL00.195 ND00.000 S00.313 SNR 02.04 P168 B250 1A"
regex = re.compile(r'\+?-?\d+(?:\.\d+)?') # 编译正则表达式
parts = re.split(regex,data)
parts2 = [part for part in parts if part]
# 使用 findall 方法找到所有匹配的数字
numbers = regex.findall(data)
# 输出结果
print(numbers)
filenameCsv = "TTTTTTTTTTTTtest.csv"
if os.path.isfile(filenameCsv) == 0:
# 文件为空,需要写入表头
with open(filenameCsv, mode='w', newline='') as file:
writer = csv.writer(file)
steee = "'time', 'Methane', 'Air Temp', 'Laser Temp', 'Laser Intensity'"
stlist = steee.split(',')
writer.writerow(stlist)
#writer.writerow(self.rowTitle)
else:
with open(filenameCsv, mode='a', newline='') as file:
# 创建一个写入器对象
writer = csv.writer(file)
# 写入数据行
writer.writerows([numbers])

View File

@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 13:36:48 2024
@author: WANGXIBAO
"""
my_list = ['1',' 2', '3',' 4',' 5']
my_list.pop(0) # 移除第一个元素
print(my_list) # 输出: [2, 3, 4, 5]

5
regular.ini Normal file
View File

@ -0,0 +1,5 @@
[TF_config]
regular = (A\+|B\+|\s)+
headstr = A+
rowtitle = time,Methane,Air Temp,Laser Temp,Laser Intensity