Compare commits

..

No commits in common. "cc5f48f15cf6a07d7dfe8b2b3c956ce29717bce6" and "417965a1115fc1c7c212b9243e8787a111c33dde" have entirely different histories.

3 changed files with 123 additions and 171 deletions

View File

@ -1,19 +1,19 @@
import struct
import numpy as np
from PyQt5.QtCore import QRegExp, QByteArray
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtNetwork import QTcpSocket
from PyQt5.QtWidgets import (
QDialog, QLineEdit, QMessageBox,
QRadioButton, QButtonGroup, QFormLayout
QApplication, QDialog, QLabel, QLineEdit, QPushButton,QMessageBox,
QHBoxLayout, QVBoxLayout, QMainWindow, QWidget, QRadioButton, QButtonGroup,QGridLayout,QFormLayout
)
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtCore import QRegExp,QByteArray
import struct
from PyQt5.QtNetwork import QTcpSocket
import numpy as np
from numpy.ma.core import masked
from scipy.optimize import leastsq
import struct
HEADER_MAGIC = bytes([0xAA, 0x55, 0xAA])
HEADER_SIZE = 6 # PackgeHead除去data字段的大小(3+1+1+1)
class SamplingDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
@ -53,8 +53,6 @@ class SamplingDialog(QDialog):
rate_str = self.rate_combo.currentText()
rate_code = rate_code_map.get(rate_str, 0x00)
return rate_code, self.time_input.text()
class PackageHead:
@staticmethod
def parse(data: bytes):
@ -70,11 +68,8 @@ class PackageHead:
'result_code': result_code,
'data': data[6:]
}
class GetCoe:
def __init__(self, temp_ch1_1, temp_ch1_2, dc_ch1_1, dc_ch1_2, ac_ch1_1, ac_ch1_2, temp_ch2_1, temp_ch2_2, dc_ch2_1,
dc_ch2_2,
def __init__(self, temp_ch1_1, temp_ch1_2, dc_ch1_1, dc_ch1_2,ac_ch1_1,ac_ch1_2,temp_ch2_1,temp_ch2_2,dc_ch2_1,dc_ch2_2,
ac_ch2_1, ac_ch2_2):
self.temp_ch1_1 = temp_ch1_1
self.temp_ch1_2 = temp_ch1_2
@ -88,16 +83,12 @@ class GetCoe:
self.dc_ch2_2 = dc_ch2_2
self.ac_ch2_1 = ac_ch2_1
self.ac_ch2_2 = ac_ch2_2
class Eigenvalue:
def __init__(self, temp1, temp2, offset1, offset2):
self.temp1 = temp1
self.temp2 = temp2
self.offset1 = offset1
self.offset2 = offset2
class MacConfigDialog(QDialog):
def __init__(self, socket: QTcpSocket, parent=None):
super().__init__(parent)
@ -143,7 +134,7 @@ class MacConfigDialog(QDialog):
0xAA, 0x55, 0xAA,
0x0D, # cmd
0x01, # version
0x00 # result_code (发送时为0)
0x00 # result_code (发送时为0)
]) + struct.pack('2B', mac1, mac2)
self.socket.write(packet)
@ -168,7 +159,6 @@ class MacConfigDialog(QDialog):
else:
QMessageBox.warning(self, "失败", f"错误码: {pkg['result_code']}")
class IPConfigDialog(QDialog):
def __init__(self, socket: QTcpSocket, parent=None):
super().__init__(parent)
@ -245,7 +235,6 @@ class IPConfigDialog(QDialog):
if len(parts) != 4:
raise ValueError()
return [int(p) for p in parts]
if mode == 0:
packet = bytes([
0xAA, 0x55, 0xAA,
@ -268,6 +257,8 @@ class IPConfigDialog(QDialog):
0x00 # result_code (发送时为0)
]) + struct.pack('B', mode) + bytes(ip) + bytes(mask) + bytes(gw)
self.socket.write(packet)
if not self.socket.waitForBytesWritten(1000):
QMessageBox.critical(self, "错误", "发送失败")
@ -289,15 +280,12 @@ class IPConfigDialog(QDialog):
self.accept()
else:
QMessageBox.warning(self, "失败", f"错误码: {pkg['result_code']}")
from PyQt5.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QComboBox,
QGridLayout
QGridLayout, QApplication
)
from PyQt5.QtCore import Qt
class CalibrationDialog(QDialog):
def __init__(self, socket: QTcpSocket, parent=None):
super().__init__(parent)
@ -344,9 +332,9 @@ class CalibrationDialog(QDialog):
btn.clicked.connect(lambda _, index=i: self.fetch_voltage(index))
self.get_buttons.append(btn)
grid.addWidget(v_label, i + 1, 0)
grid.addWidget(val_label, i + 1, 1)
grid.addWidget(btn, i + 1, 2)
grid.addWidget(v_label, i+1, 0)
grid.addWidget(val_label, i+1, 1)
grid.addWidget(btn, i+1, 2)
self.update_voltage_points()
@ -411,7 +399,6 @@ class CalibrationDialog(QDialog):
# 发送给 MCU
self.socket.write(packet)
self.socket.waitForReadyRead()
def get_coe(self):
try:
self.socket.write(bytes(
@ -421,7 +408,6 @@ class CalibrationDialog(QDialog):
except Exception as e:
self.status_bar.showMessage(f"状态: 错误 - {str(e)}")
def calibrate(self):
try:
self.recv_state = ''
@ -456,15 +442,14 @@ class CalibrationDialog(QDialog):
group = self.type_cb.currentIndex() # 0=temp, 1=dc, 2=ac
print(f"ch:{ch},group:{group}")
header = bytes([0xAA, 0x55, 0xAA, 0x11, 0x01, 0x00]) # 可根据实际协议修改
header = bytes([0xAA, 0x55, 0xAA, 0x11,0x01,0x00]) # 可根据实际协议修改
payload = struct.pack('<BBff', ch, group, a, b)
packet = header + payload
# 发送给 MCU
self.socket.write(packet)
self.socket.waitForReadyRead()
def get_extremes(self, data):
def get_extremes(self,data):
"""获取最大和最小的10个值排序法"""
sorted_data = np.sort(data)
return {
@ -472,7 +457,7 @@ class CalibrationDialog(QDialog):
'top10_min': sorted_data[:10].tolist()
}
def mean_without_max_optimized(self, data):
def mean_without_max_optimized(self,data):
"""优化内存使用的版本"""
arr = np.array(data)
if len(arr) < 2:
@ -495,7 +480,6 @@ class CalibrationDialog(QDialog):
total = np.sum(arr) - min_val
count = len(arr) - 1
return total / count
def get_temp_dc(self):
try:
self.recv_state = ''
@ -503,8 +487,7 @@ class CalibrationDialog(QDialog):
[0xAA, 0x55, 0xAA, 0x0B, 0x01, 0x00])) # 发送数据
self.socket.waitForReadyRead()
except Exception as e:
QMessageBox.warning(self, "错误", f"{str(e)}")
QMessageBox.warning(self, "错误",f"{str(e)}")
def get_wave(self):
try:
self.recv_state = 'WAIT_HEADER'
@ -521,7 +504,7 @@ class CalibrationDialog(QDialog):
print(packet)
self.socket.waitForReadyRead()
except Exception as e:
QMessageBox.warning(self, "错误", f"{str(e)}")
QMessageBox.warning(self, "错误",f"{str(e)}")
def on_ready_read(self):
while self.socket.bytesAvailable():
@ -570,14 +553,13 @@ class CalibrationDialog(QDialog):
body_data = recv_data[HEADER_SIZE:HEADER_SIZE + body_size]
unpacked_data = struct.unpack(body_format, body_data)
value = Eigenvalue(*unpacked_data)
print(
f"温度1{value.temp1 / 1000},温度2{value.temp2 / 1000},偏置电压1{value.offset1 / 100},偏置电压2{value.offset2 / 100}")
print(f"温度1{value.temp1/1000},温度2{value.temp2/1000},偏置电压1{value.offset1/100},偏置电压2{value.offset2/100}")
if self.channel_cb.currentIndex() == 0 and self.type_cb.currentIndex() == 0:
self.value_labels[self.type_index].setText(str(value.temp1 / 1000))
self.value_labels[self.type_index].setText(str(value.temp1/1000))
elif self.channel_cb.currentIndex() == 0 and self.type_cb.currentIndex() == 1:
self.value_labels[self.type_index].setText(str(value.offset1 / 100))
elif self.channel_cb.currentIndex() == 1 and self.type_cb.currentIndex() == 0:
self.value_labels[self.type_index].setText(str(value.temp2 / 1000))
self.value_labels[self.type_index].setText(str(value.temp2/1000))
elif self.channel_cb.currentIndex() == 1 and self.type_cb.currentIndex() == 1:
self.value_labels[self.type_index].setText(str(value.offset2 / 100))
elif cmd == 0x11:
@ -598,11 +580,10 @@ class CalibrationDialog(QDialog):
f"{value.temp_ch1_1, value.temp_ch1_2, value.dc_ch1_1, value.dc_ch1_2, value.ac_ch1_1, value.ac_ch1_2}")
print(
f"{value.temp_ch2_1, value.temp_ch2_2, value.dc_ch2_1, value.dc_ch2_2, value.ac_ch2_1, value.ac_ch2_2}")
def process_wave_packet(self, wave_data):
def process_wave_packet(self,wave_data):
data = wave_data # 接收所有数据
data = np.frombuffer(data, dtype=np.int32) # 根据实际数据格式转换
LSB_32BIT = (2.8 / (2 ** 31)) * ((750 + 287) / 287) * 1000 / 10.2
LSB_32BIT = (2.8 / (2 ** 31)) * ((750 + 287) / 287) * 1000/10.2
self.scaled_data = data * LSB_32BIT
result = self.get_extremes(self.scaled_data)
@ -614,7 +595,7 @@ class CalibrationDialog(QDialog):
print(f"top10_min 去除最大的数据后的平均值2{mean_min}")
pp = mean_max - mean_min
if self.type_cb.currentIndex() == 2:
self.value_labels[self.type_index].setText(str(round(pp, 6)))
self.value_labels[self.type_index].setText(str(round(pp,6)))
print(f"pp :{mean_max - mean_min}")
def closeEvent(self, event):
@ -623,4 +604,4 @@ class CalibrationDialog(QDialog):
self.socket.readyRead.disconnect(self.on_ready_read)
except TypeError:
pass
super().closeEvent(event)
super().closeEvent(event)

View File

@ -39,8 +39,6 @@ def fft_filter(signal, lpf1, lpf2, fs):
yy[i] = 0
y = 2 * real(fftpack.ifft(yy))
return y
# 高通滤波
def fft_filter_high_pass(signal, lpf_high, fs):
"""
@ -59,8 +57,6 @@ def fft_filter_high_pass(signal, lpf_high, fs):
yy[i] = 0
y = real(fftpack.ifft(yy))
return y
# 低通滤波
def fft_filter_low_pass(signal, lpf_low, fs):
"""
@ -78,7 +74,6 @@ def fft_filter_low_pass(signal, lpf_low, fs):
y = 2 * real(fftpack.ifft(yy))
return y
# 希尔伯特变换
def hilbert_envelop(signal):
"""
@ -134,9 +129,9 @@ def calc_vel_pass_rms(signal, fs):
fs: 采样频率
:return: 通频速度有效值10-1000Hz
"""
# x1 = fft_filter(signal, 10, 1000, fs)
#x1 = fft_filter(signal, 10, 1000, fs)
x2, x3 = acc2dis(signal, fs)
# x4 = fft_filter(x2, 10, 1000, fs)
#x4 = fft_filter(x2, 10, 1000, fs)
vel_pass_rms = np.sqrt(np.mean(x2 ** 2))
return vel_pass_rms
@ -163,7 +158,7 @@ def calc_acc_rms(signal, fs):
Return
a_rms: 加速度有效值
"""""
# x1 = fft_filter(signal, 3,10000, fs)
#x1 = fft_filter(signal, 3,10000, fs)
acc_rms = np.sqrt(np.mean(signal ** 2))
return acc_rms
@ -176,7 +171,7 @@ def calc_acc_p(signal, fs):
Return
a_p: 加速度有效值
"""""
# x1 = fft_filter(signal, 3,10000, fs)
#x1 = fft_filter(signal, 3,10000, fs)
x2 = sorted(abs(signal), reverse=True)
x3 = x2[0:100]
acc_p = np.mean(x3)
@ -236,7 +231,7 @@ def calc_vel_p(signal, fs):
Return
vel_p: 速度峰值
"""""
# x1 = fft_filter(signal, 10, 1000, fs)
#x1 = fft_filter(signal, 10, 1000, fs)
x2, x3 = acc2dis(signal, fs)
x4 = sorted(abs(x2), reverse=True)
x5 = x4[0:100]
@ -443,6 +438,9 @@ def calc_ylb_SWE(signal, fs):
return ylb_SWE
def calc_ylb_SWPE(signal, fs):
"""
:return ylb_SWPE: 脉冲能量
@ -492,8 +490,8 @@ def calc_ylb_SWPA(signal, fs):
dt_x = [j for j in range(len(signal_dt)) if signal_dt[j] == -1]
signal_ylb_SWPA = np.linspace(0, 0, len(dt_s)) # 应力波脉冲能量峰值(SWPA)赋初值0
for i in range(len(dt_s)):
signal_ylb_SWPA[i] = max(signal_envelope[dt_s[i] + 1:dt_x[i] + 1])
ylb_SWPA = max(signal_ylb_SWPA) # 最大峰高 SWPA
signal_ylb_SWPA[i] = max(signal_envelope[dt_s[i]+1:dt_x[i]+1])
ylb_SWPA = max(signal_ylb_SWPA) # 最大峰高 SWPA
return ylb_SWPA
@ -522,11 +520,11 @@ def calc_fea_ylb(signal):
signal_ylb_SWPA = np.linspace(0, 0, len(dt_s)) # 应力波脉冲能量峰值(SWPA)赋初值0
signal_ylb_SWPE = np.linspace(0, 0, len(dt_s)) # 应力波脉冲能量值(SWPE)赋初值0
for i in range(len(dt_s)):
signal_ylb_SWPA[i] = max(signal_envelope[dt_s[i] + 1:dt_x[i] + 1])
signal_ylb_SWPA[i] = max(signal_envelope[dt_s[i]+1:dt_x[i]+1])
signal_ylb_SWPE[i] = sum(signal_envelope[dt_s[i] + 1:dt_x[i] + 1] - L_Limit)
ylb_SWE = sum(signal_envelope[signal_envelope > 0])
ylb_SWPE = sum(signal_ylb_SWPE)
ylb_SWPA = max(signal_ylb_SWPA) # 最大峰高 SWPA
ylb_SWPA = max(signal_ylb_SWPA) # 最大峰高 SWPA
return ylb_SWE, ylb_SWPE, ylb_SWPA
@ -703,7 +701,7 @@ def calc_fea_HCR(fft_data, cf, sf, sp, f_st, f_ord):
except ValueError:
Hb1 = 0
try:
Hb2 = sum([x ** 2 for x in xb2]) # 上边带能量和
Hb2 = sum([x ** 2 for x in xb2]) # 上边带能量和
except ValueError:
Hb2 = 0
xc = calc_multiple_frequency(fft_data, i * cf, sp) # 给定中心频率幅值
@ -734,17 +732,15 @@ def calc_HCR(fft_data, cf, sf, sp, f_st, f_ord):
HCR = sqrt(sum(array(fea_HCR) ** 2))
return HCR
if __name__ == "__main__":
freq = 8192
data = np.loadtxt(r"E:\Workspace\Software\Python\无线传感器算法\特征值计算\09f07f1800158d00-Y.csv", delimiter=',',
usecols=(0))
data = np.loadtxt(r"E:\Workspace\Software\Python\无线传感器算法\特征值计算\09f07f1800158d00-Y.csv", delimiter=',', usecols=(0))
data_list = data.tolist()
data_list = data_list[1:]
print("数据长度:", len(data_list))
# 速度有效值
#速度有效值
speed_rms_value = calc_vel_pass_rms(data_list, freq)
print("速度有效值:", speed_rms_value)
# 速度峰值

View File

@ -1,19 +1,23 @@
import csv
import os
import sys
import time
import socket
import os
from time import sleep
from typing import Tuple, Optional
import matplotlib
import matplotlib.pyplot as plt
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QFrame, QStatusBar, QSizePolicy, QFileDialog, QApplication, QMainWindow, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT
import numpy as np
from scipy.fft import fft, fftfreq
from SamplingDialog import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget,QMessageBox, QPushButton, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QFrame, QGridLayout, QStatusBar, QSizePolicy, QFileDialog
from PyQt5.QtCore import Qt, QTimer, pyqtSlot, QByteArray
from PyQt5.QtNetwork import QTcpSocket, QAbstractSocket
import matplotlib
import struct
import time
from typing import Tuple, Optional
from feauture_calculate import *
from SamplingDialog import *
import csv
import pandas as pd
# 启用高DPI支持
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
@ -36,10 +40,8 @@ class Eigenvalue:
self.offset1 = offset1
self.offset2 = offset2
class MatplotlibCanvas(FigureCanvas):
""" 用于在 Qt 界面中嵌入 Matplotlib 绘图 """
def __init__(self, parent=None):
self.fig, self.axs = plt.subplots(2, 2, figsize=(10, 5)) # 2 个子图(时域 + 频域)
self.fig.subplots_adjust(hspace=0.6) # 增大时域图和频域图的间距
@ -49,17 +51,15 @@ class MatplotlibCanvas(FigureCanvas):
def init_plot(self):
""" 初始化默认图像(占位提示) """
self.axs[0, 0].set_title("加速度时域信号", fontsize=12, fontweight='bold')
self.axs[0, 0].set_xlabel("采样点")
self.axs[0, 0].set_ylabel("幅度(m/s2)")
self.axs[0, 0].text(0.5, 0.5, "暂无数据", fontsize=12, ha='center', va='center',
transform=self.axs[0, 0].transAxes)
self.axs[0,0].set_title("加速度时域信号", fontsize=12, fontweight='bold')
self.axs[0,0].set_xlabel("采样点")
self.axs[0,0].set_ylabel("幅度(m/s2)")
self.axs[0,0].text(0.5, 0.5, "暂无数据", fontsize=12, ha='center', va='center', transform=self.axs[0,0].transAxes)
self.axs[0, 1].set_title("加速度频域信号", fontsize=12, fontweight='bold')
self.axs[0, 1].set_xlabel("频率 (Hz)")
self.axs[0, 1].set_ylabel("幅度(m/s2)")
self.axs[0, 1].text(0.5, 0.5, "暂无数据", fontsize=12, ha='center', va='center',
transform=self.axs[0, 1].transAxes)
self.axs[0,1].set_title("加速度频域信号", fontsize=12, fontweight='bold')
self.axs[0,1].set_xlabel("频率 (Hz)")
self.axs[0,1].set_ylabel("幅度(m/s2)")
self.axs[0,1].text(0.5, 0.5, "暂无数据", fontsize=12, ha='center', va='center', transform=self.axs[0,1].transAxes)
self.axs[1, 0].set_title("速度时域信号", fontsize=12, fontweight='bold')
self.axs[1, 0].set_xlabel("采样点")
@ -75,16 +75,16 @@ class MatplotlibCanvas(FigureCanvas):
self.draw() # 更新绘图
def plot_data(self, data, sample):
def plot_data(self, data,sample):
""" 绘制时域和频域图 """
self.axs[0, 0].clear()
self.axs[0, 1].clear()
self.axs[0,0].clear()
self.axs[0,1].clear()
# 时域信号
self.axs[0, 0].plot(data, color='blue')
self.axs[0, 0].set_title("加速度时域信号", fontsize=12, fontweight='bold')
self.axs[0, 0].set_xlabel("采样点")
self.axs[0, 0].set_ylabel("幅度(m/s2)")
self.axs[0,0].plot(data, color='blue')
self.axs[0,0].set_title("加速度时域信号", fontsize=12, fontweight='bold')
self.axs[0,0].set_xlabel("采样点")
self.axs[0,0].set_ylabel("幅度(m/s2)")
# 频域信号
N = len(data)
@ -96,25 +96,25 @@ class MatplotlibCanvas(FigureCanvas):
# yf = yf[:4000]
# xf = xf[:4000]
self.axs[0, 1].plot(xf, 2.0 / N * np.abs(yf), lw=0.2, color='black')
self.axs[0, 1].plot(xf, 2.0 / N * np.abs(yf), '.', lw=0.3, color='red')
self.axs[0,1].plot(xf, 2.0 / N * np.abs(yf), lw=0.2, color='black')
self.axs[0,1].plot(xf, 2.0 / N * np.abs(yf), '.', lw=0.3, color='red')
self.axs[0, 1].set_title("加速度频域信号", fontsize=12, fontweight='bold')
self.axs[0, 1].set_xlabel("频率 (Hz)")
self.axs[0, 1].set_ylabel("幅度(m/s2)")
self.axs[0,1].set_title("加速度频域信号", fontsize=12, fontweight='bold')
self.axs[0,1].set_xlabel("频率 (Hz)")
self.axs[0,1].set_ylabel("幅度(m/s2)")
self.draw() # 更新绘图
def plot_data_vel(self, data, sample):
def plot_data_vel(self, data,sample):
""" 绘制时域和频域图 """
self.axs[1, 0].clear()
self.axs[1, 1].clear()
self.axs[1,0].clear()
self.axs[1,1].clear()
# 时域信号
self.axs[1, 0].plot(data, color='blue')
self.axs[1, 0].set_title("速度时域信号", fontsize=12, fontweight='bold')
self.axs[1, 0].set_xlabel("采样点")
self.axs[1, 0].set_ylabel("幅度(mm/s)")
self.axs[1,0].plot(data, color='blue')
self.axs[1,0].set_title("速度时域信号", fontsize=12, fontweight='bold')
self.axs[1,0].set_xlabel("采样点")
self.axs[1,0].set_ylabel("幅度(mm/s)")
# 频域信号
N = len(data)
@ -126,16 +126,15 @@ class MatplotlibCanvas(FigureCanvas):
yf = yf[:1000]
xf = xf[:1000]
self.axs[1, 1].plot(xf, 2.0 / N * np.abs(yf), lw=0.2, color='black')
self.axs[1, 1].plot(xf, 2.0 / N * np.abs(yf), '.', lw=0.3, color='red')
self.axs[1,1].plot(xf, 2.0 / N * np.abs(yf), lw=0.2, color='black')
self.axs[1,1].plot(xf, 2.0 / N * np.abs(yf), '.', lw=0.3, color='red')
self.axs[1, 1].set_title("速度频域信号", fontsize=12, fontweight='bold')
self.axs[1, 1].set_xlabel("频率 (Hz)")
self.axs[1, 1].set_ylabel("幅度(mm/s)")
self.axs[1,1].set_title("速度频域信号", fontsize=12, fontweight='bold')
self.axs[1,1].set_xlabel("频率 (Hz)")
self.axs[1,1].set_ylabel("幅度(mm/s)")
self.draw() # 更新绘图
class SocketClientApp(QMainWindow):
def __init__(self):
super().__init__()
@ -189,7 +188,7 @@ class SocketClientApp(QMainWindow):
self.ipv4_config_button.setEnabled(False)
self.calibration_config_button.setEnabled(False)
self.get_version_button.setEnabled(False)
self.ip_input.setText("192.168.0.191")
self.ip_input.setText("192.168.0.199")
self.port_input.setText("12345")
# 预留绘图区域
@ -294,7 +293,7 @@ class SocketClientApp(QMainWindow):
# 设置布局策略,确保控件大小随窗口调整
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
def get_extremes(self, data):
def get_extremes(self,data):
"""获取最大和最小的10个值排序法"""
sorted_data = np.sort(data)
return {
@ -302,7 +301,7 @@ class SocketClientApp(QMainWindow):
'top10_min': sorted_data[:10].tolist()
}
def mean_without_max_optimized(self, data):
def mean_without_max_optimized(self,data):
"""优化内存使用的版本"""
arr = np.array(data)
if len(arr) < 2:
@ -325,8 +324,7 @@ class SocketClientApp(QMainWindow):
total = np.sum(arr) - min_val
count = len(arr) - 1
return total / count
def calculate_crc(self, data: bytes) -> int:
def calculate_crc(self,data: bytes) -> int:
"""计算数据的累加和CRC"""
crc = 0
for byte in data:
@ -334,7 +332,7 @@ class SocketClientApp(QMainWindow):
return crc & 0xFF # 只保留最低字节
def connect_to_server(self):
# self.process_wave_packet('')
#self.process_wave_packet('')
if self.connect_button.text() == "断开":
self.connect_button.setText("连接")
self.socket.disconnectFromHost()
@ -394,7 +392,6 @@ class SocketClientApp(QMainWindow):
self.status_bar.showMessage("状态: 重新连接成功")
self.get_data_button.setEnabled(True)
self.reconnect_timer.stop()
def on_button_save_csv(self):
file_path = QFileDialog.getExistingDirectory(
None,
@ -427,12 +424,10 @@ class SocketClientApp(QMainWindow):
"保存失败",
f"保存文件时出错:\n{str(e)}"
)
def on_button_samping_set(self):
dialog = SamplingDialog(self)
if dialog.exec_() == QDialog.Accepted:
self.rate_code, self.time_str = dialog.get_values()
def on_ready_read(self):
while self.socket.bytesAvailable():
if self.recv_state == 'WAIT_HEADER':
@ -470,8 +465,8 @@ class SocketClientApp(QMainWindow):
end_time = time.time()
execution_time = end_time - self.start_time
print(f"结束时间戳: {end_time}")
print(f"代码执行时间: {round(execution_time, 3)}")
print(f"speed :{round((self.sampling_rate * 4 * 8) / execution_time, 3)} Kbps")
print(f"代码执行时间: {execution_time}")
print(f"speed :{round((self.sampling_rate * 4 * 8) / execution_time,3)} Kbps")
self.process_wave_packet(bytes(self.partial_data))
self.recv_state = 'WAIT_HEADER'
self.partial_data.clear()
@ -488,9 +483,8 @@ class SocketClientApp(QMainWindow):
body_data = recv_data[HEADER_SIZE:HEADER_SIZE + body_size]
unpacked_data = struct.unpack(body_format, body_data)
value = Eigenvalue(*unpacked_data)
print(
f"温度1{value.temp1 / 1000},温度2{value.temp2 / 1000},偏置电压1{value.offset1 / 100},偏置电压2{value.offset2 / 100}")
self.temp1_label.setText(f"温度1{value.temp1 / 1000} v")
print(f"温度1{value.temp1/1000},温度2{value.temp2/1000},偏置电压1{value.offset1/100},偏置电压2{value.offset2/100}")
self.temp1_label.setText(f"温度1{value.temp1/1000} v")
self.temp2_label.setText(f"温度2{value.temp2 / 1000} v")
self.offset1_label.setText(f"偏置电压1{value.offset1 / 100} v")
self.offset2_label.setText(f"偏置电压2{value.offset2 / 100} v")
@ -502,6 +496,7 @@ class SocketClientApp(QMainWindow):
print(f"version{unpacked_data}")
QMessageBox.information(self, "版本", f"{unpacked_data[0]}.{unpacked_data[1]}")
def receive_data(self, length: int):
while len(self.buffer) < length:
if not self.socket.waitForReadyRead(1000):
@ -510,7 +505,7 @@ class SocketClientApp(QMainWindow):
self.buffer = self.buffer[length:]
return bytes(data)
def parse_package_head(self, data: bytes) -> Tuple[Optional[dict], Optional[bytes]]:
def parse_package_head(self,data: bytes) -> Tuple[Optional[dict], Optional[bytes]]:
"""
解析包头部
返回: (header_dict, remaining_data)
@ -530,14 +525,13 @@ class SocketClientApp(QMainWindow):
'version': version,
'result_code': result_code
}, data[HEADER_SIZE:]
def process_wave_packet(self, wave_data):
def process_wave_packet(self,wave_data):
data = wave_data # 接收所有数据
data = np.frombuffer(data, dtype=np.int32) # 根据实际数据格式转换
for i in range(min(5, len(data))): # 确保不超过数据长度
print(f"{data[i]:.3f}", end=" ")
for i in range(min(100, len(data))): # 确保不超过数据长度
print(f"{data[i]:1f}", end=" ")
print() # 换行
LSB_32BIT = (2.8 / (2 ** 31)) * ((750 + 287) / 287) * 1000 / 10.2
LSB_32BIT = (2.8 / (2 ** 31)) * ((750 + 287) / 287) * 1000/10.2
# LSB_32BIT = (2.8 / (2 ** 31)) * ((750 + 287) / 287) * 1000
self.scaled_data = data * LSB_32BIT
# for i in range(min(100, len(self.scaled_data))): # 确保不超过数据长度
@ -553,28 +547,28 @@ class SocketClientApp(QMainWindow):
# print(f"pp :{mean_max - mean_min}")
print(f"采样率: {self.sampling_rate}")
# self.sampling_rate = 48000 # 假设采样率为 48000 Hz
self.canvas.plot_data(self.scaled_data, self.sampling_rate) # 在 Qt 界面中绘图
data_filter = fft_filter(self.scaled_data, 10, 1000, self.sampling_rate)
data_vel1, data_vel2 = acc2dis(data_filter, self.sampling_rate)
self.canvas.plot_data_vel(data_vel1, self.sampling_rate) # 在 Qt 界面中绘图
self.canvas.plot_data(self.scaled_data,self.sampling_rate) # 在 Qt 界面中绘图
data_filter = fft_filter(self.scaled_data, 10, 1000,self.sampling_rate)
data_vel1,data_vel2 = acc2dis(data_filter,self.sampling_rate)
self.canvas.plot_data_vel(data_vel1,self.sampling_rate) # 在 Qt 界面中绘图
self.status_bar.showMessage("状态: 数据绘制完成")
# 速度有效值
speed_rms_value = calc_vel_pass_rms(self.scaled_data, self.sampling_rate)
print("速度有效值:", round(speed_rms_value, 1))
print("速度有效值:", speed_rms_value)
# 速度峰值
speed_vel_p = calc_vel_p(self.scaled_data, self.sampling_rate)
print("速度峰值:", round(speed_vel_p, 1))
print("速度峰值:", speed_vel_p)
# 加速度有效值
acc_rms = calc_acc_rms(self.scaled_data, self.sampling_rate)
print("加速度有效值:", round(acc_rms, 1))
print("加速度有效值:", acc_rms)
# 加速度峰值
acc_p = calc_acc_p(self.scaled_data, self.sampling_rate)
print("加速度峰值:", round(acc_p, 1))
self.acceleration_label_rms.setText(f"加速度有效值:{round(acc_rms, 3)} m/s^2")
self.acceleration_label_pp.setText(f"加速度峰值:{round(acc_p, 3)} m/s^2")
self.velocity_label_rms.setText(f"速度有效值:{round(speed_rms_value, 3)} mm/s")
self.velocity_label_pp.setText(f"速度峰值:{round(speed_vel_p, 3)} mm/s")
print("加速度峰值:", acc_p)
self.acceleration_label_rms.setText(f"加速度有效值:{round(acc_rms,3)} m/s^2")
self.acceleration_label_pp.setText(f"加速度峰值:{round(acc_p,3)} m/s^2")
self.velocity_label_rms.setText(f"速度有效值:{round(speed_rms_value,3)} mm/s")
self.velocity_label_pp.setText(f"速度峰值:{round(speed_vel_p,3)} mm/s")
def on_button_clicked(self):
try:
@ -595,7 +589,6 @@ class SocketClientApp(QMainWindow):
self.socket.waitForReadyRead()
except Exception as e:
self.status_bar.showMessage(f"状态: 错误 - {str(e)}")
def on_button_clicked2(self):
""" 获取数据并绘制 """
try:
@ -615,7 +608,6 @@ class SocketClientApp(QMainWindow):
self.socket.waitForReadyRead()
except Exception as e:
self.status_bar.showMessage(f"状态: 错误 - {str(e)}")
def on_button_upgrade(self):
"""打开文件选择对话框"""
file_path, _ = QFileDialog.getOpenFileName(
@ -639,10 +631,12 @@ class SocketClientApp(QMainWindow):
print(f"Read upgrade package, size: {len(package_data)} bytes")
upgrade_len = len(package_data)
crc = self.calculate_crc(package_data)
upgrade_req = struct.pack("<IB", upgrade_len, crc) + package_data
header_magic = bytes([0xAA, 0x55, 0xAA])
cmd = 0x05
version = 1
@ -657,23 +651,7 @@ class SocketClientApp(QMainWindow):
print(f"Upgrade length: {upgrade_len}, CRC: {crc}")
print(f"Total packet size: {len(full_packet)} bytes")
# 分包处理每包最大1500字节
max_packet_size = 1500
total_size = len(full_packet)
num_packets = (total_size // max_packet_size) + (1 if total_size % max_packet_size != 0 else 0)
print(f"Total packets: {num_packets}, each up to {max_packet_size} bytes")
# 分包并发送
for i in range(num_packets):
start_index = i * max_packet_size
end_index = min((i + 1) * max_packet_size, total_size)
packet_chunk = full_packet[start_index:end_index]
print(f"Sending packet {i + 1}/{num_packets}, size: {len(packet_chunk)} bytes")
self.socket.write(packet_chunk)
print(f"Packet {i + 1} sent successfully")
time.sleep(0.05)
self.socket.write(full_packet)
print("Upgrade packet ready to send (commented out actual send code)")
except Exception as e:
print(f"Upgrade failed: {str(e)}")
@ -727,11 +705,10 @@ class SocketClientApp(QMainWindow):
print("Upgrade packet ready to send (commented out actual send code)")
except Exception as e:
print(f"Upgrade failed: {str(e)}")
def on_button_temp(self):
try:
self.recv_state = ''
self.status_bar.showMessage("状态: 正在获取数据...", 3000)
self.status_bar.showMessage("状态: 正在获取数据...",3000)
self.socket.write(bytes(
[0xAA, 0x55, 0xAA, 0x0B, 0x01, 0x00])) # 发送数据
self.socket.waitForReadyRead()
@ -758,18 +735,16 @@ class SocketClientApp(QMainWindow):
dialog = CalibrationDialog(self.socket, self)
dialog.exec_()
self.socket.readyRead.connect(self.on_ready_read)
def on_button_get_version(self):
try:
self.recv_state = ''
self.status_bar.showMessage("状态: 正在获取数据...", 3000)
self.status_bar.showMessage("状态: 正在获取数据...",3000)
self.socket.write(bytes(
[0xAA, 0x55, 0xAA, 0x0F, 0x01, 0x00])) # 发送数据
self.socket.waitForReadyRead()
except Exception as e:
self.status_bar.showMessage(f"状态: 错误 - {str(e)}")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = SocketClientApp()