Compare commits

...

2 Commits

Author SHA1 Message Date
cc5f48f15c fix send wave bug. 2025-06-21 17:24:51 +08:00
f7d3858765 format codes 2025-06-21 10:36:45 +08:00
3 changed files with 176 additions and 128 deletions

View File

@ -1,19 +1,19 @@
import struct
from PyQt5.QtWidgets import (
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 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
)
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,6 +53,8 @@ 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):
@ -68,8 +70,11 @@ 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
@ -83,12 +88,16 @@ 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)
@ -159,6 +168,7 @@ class MacConfigDialog(QDialog):
else:
QMessageBox.warning(self, "失败", f"错误码: {pkg['result_code']}")
class IPConfigDialog(QDialog):
def __init__(self, socket: QTcpSocket, parent=None):
super().__init__(parent)
@ -235,6 +245,7 @@ class IPConfigDialog(QDialog):
if len(parts) != 4:
raise ValueError()
return [int(p) for p in parts]
if mode == 0:
packet = bytes([
0xAA, 0x55, 0xAA,
@ -257,8 +268,6 @@ 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, "错误", "发送失败")
@ -280,12 +289,15 @@ class IPConfigDialog(QDialog):
self.accept()
else:
QMessageBox.warning(self, "失败", f"错误码: {pkg['result_code']}")
from PyQt5.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QComboBox,
QGridLayout, QApplication
QGridLayout
)
from PyQt5.QtCore import Qt
class CalibrationDialog(QDialog):
def __init__(self, socket: QTcpSocket, parent=None):
super().__init__(parent)
@ -399,6 +411,7 @@ class CalibrationDialog(QDialog):
# 发送给 MCU
self.socket.write(packet)
self.socket.waitForReadyRead()
def get_coe(self):
try:
self.socket.write(bytes(
@ -408,6 +421,7 @@ class CalibrationDialog(QDialog):
except Exception as e:
self.status_bar.showMessage(f"状态: 错误 - {str(e)}")
def calibrate(self):
try:
self.recv_state = ''
@ -449,6 +463,7 @@ class CalibrationDialog(QDialog):
# 发送给 MCU
self.socket.write(packet)
self.socket.waitForReadyRead()
def get_extremes(self, data):
"""获取最大和最小的10个值排序法"""
sorted_data = np.sort(data)
@ -480,6 +495,7 @@ 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 = ''
@ -488,6 +504,7 @@ class CalibrationDialog(QDialog):
self.socket.waitForReadyRead()
except Exception as e:
QMessageBox.warning(self, "错误", f"{str(e)}")
def get_wave(self):
try:
self.recv_state = 'WAIT_HEADER'
@ -553,7 +570,8 @@ 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))
elif self.channel_cb.currentIndex() == 0 and self.type_cb.currentIndex() == 1:
@ -580,6 +598,7 @@ 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):
data = wave_data # 接收所有数据
data = np.frombuffer(data, dtype=np.int32) # 根据实际数据格式转换

View File

@ -39,6 +39,8 @@ 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):
"""
@ -57,6 +59,8 @@ 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):
"""
@ -74,6 +78,7 @@ def fft_filter_low_pass(signal, lpf_low, fs):
y = 2 * real(fftpack.ifft(yy))
return y
# 希尔伯特变换
def hilbert_envelop(signal):
"""
@ -438,9 +443,6 @@ def calc_ylb_SWE(signal, fs):
return ylb_SWE
def calc_ylb_SWPE(signal, fs):
"""
:return ylb_SWPE: 脉冲能量
@ -732,9 +734,11 @@ 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:]

View File

@ -1,23 +1,19 @@
import sys
import socket
import os
from time import sleep
import numpy as np
from scipy.fft import fft, fftfreq
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
import os
import sys
import time
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
from scipy.fft import fft, fftfreq
from SamplingDialog import *
from feauture_calculate import *
# 启用高DPI支持
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
@ -40,8 +36,10 @@ 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) # 增大时域图和频域图的间距
@ -54,12 +52,14 @@ class MatplotlibCanvas(FigureCanvas):
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].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].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("采样点")
@ -135,6 +135,7 @@ class MatplotlibCanvas(FigureCanvas):
self.draw() # 更新绘图
class SocketClientApp(QMainWindow):
def __init__(self):
super().__init__()
@ -188,7 +189,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.199")
self.ip_input.setText("192.168.0.191")
self.port_input.setText("12345")
# 预留绘图区域
@ -324,6 +325,7 @@ class SocketClientApp(QMainWindow):
total = np.sum(arr) - min_val
count = len(arr) - 1
return total / count
def calculate_crc(self, data: bytes) -> int:
"""计算数据的累加和CRC"""
crc = 0
@ -392,6 +394,7 @@ 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,
@ -424,10 +427,12 @@ 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':
@ -465,7 +470,7 @@ class SocketClientApp(QMainWindow):
end_time = time.time()
execution_time = end_time - self.start_time
print(f"结束时间戳: {end_time}")
print(f"代码执行时间: {execution_time}")
print(f"代码执行时间: {round(execution_time, 3)}")
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'
@ -483,7 +488,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}")
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")
@ -496,7 +502,6 @@ 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):
@ -525,11 +530,12 @@ class SocketClientApp(QMainWindow):
'version': version,
'result_code': result_code
}, data[HEADER_SIZE:]
def process_wave_packet(self, wave_data):
data = wave_data # 接收所有数据
data = np.frombuffer(data, dtype=np.int32) # 根据实际数据格式转换
for i in range(min(100, len(data))): # 确保不超过数据长度
print(f"{data[i]:1f}", end=" ")
for i in range(min(5, len(data))): # 确保不超过数据长度
print(f"{data[i]:.3f}", end=" ")
print() # 换行
LSB_32BIT = (2.8 / (2 ** 31)) * ((750 + 287) / 287) * 1000 / 10.2
# LSB_32BIT = (2.8 / (2 ** 31)) * ((750 + 287) / 287) * 1000
@ -555,16 +561,16 @@ class SocketClientApp(QMainWindow):
# 速度有效值
speed_rms_value = calc_vel_pass_rms(self.scaled_data, self.sampling_rate)
print("速度有效值:", speed_rms_value)
print("速度有效值:", round(speed_rms_value, 1))
# 速度峰值
speed_vel_p = calc_vel_p(self.scaled_data, self.sampling_rate)
print("速度峰值:", speed_vel_p)
print("速度峰值:", round(speed_vel_p, 1))
# 加速度有效值
acc_rms = calc_acc_rms(self.scaled_data, self.sampling_rate)
print("加速度有效值:", acc_rms)
print("加速度有效值:", round(acc_rms, 1))
# 加速度峰值
acc_p = calc_acc_p(self.scaled_data, self.sampling_rate)
print("加速度峰值:", acc_p)
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")
@ -589,6 +595,7 @@ class SocketClientApp(QMainWindow):
self.socket.waitForReadyRead()
except Exception as e:
self.status_bar.showMessage(f"状态: 错误 - {str(e)}")
def on_button_clicked2(self):
""" 获取数据并绘制 """
try:
@ -608,6 +615,7 @@ 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(
@ -631,12 +639,10 @@ 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
@ -651,7 +657,23 @@ class SocketClientApp(QMainWindow):
print(f"Upgrade length: {upgrade_len}, CRC: {crc}")
print(f"Total packet size: {len(full_packet)} bytes")
self.socket.write(full_packet)
# 分包处理每包最大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)
print("Upgrade packet ready to send (commented out actual send code)")
except Exception as e:
print(f"Upgrade failed: {str(e)}")
@ -705,6 +727,7 @@ 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 = ''
@ -735,6 +758,7 @@ 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 = ''
@ -745,6 +769,7 @@ class SocketClientApp(QMainWindow):
except Exception as e:
self.status_bar.showMessage(f"状态: 错误 - {str(e)}")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = SocketClientApp()