优化固件升级
This commit is contained in:
parent
345de6a942
commit
14066cb7ac
110
mainwindow.py
110
mainwindow.py
@ -1,6 +1,8 @@
|
|||||||
import sys
|
import sys
|
||||||
import socket
|
import socket
|
||||||
import os
|
import os
|
||||||
|
from time import sleep
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from scipy.fft import fft, fftfreq
|
from scipy.fft import fft, fftfreq
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
@ -86,8 +88,10 @@ class SocketClientApp(QMainWindow):
|
|||||||
self.connect_button = QPushButton("连接")
|
self.connect_button = QPushButton("连接")
|
||||||
self.get_data_button = QPushButton("获取数据")
|
self.get_data_button = QPushButton("获取数据")
|
||||||
self.upgrade_button = QPushButton("更新固件")
|
self.upgrade_button = QPushButton("更新固件")
|
||||||
|
self.upgrade_button_test = QPushButton("更新固件2")
|
||||||
self.get_data_button.setEnabled(False) # 初始状态不可点击
|
self.get_data_button.setEnabled(False) # 初始状态不可点击
|
||||||
self.upgrade_button.setEnabled(False) # 初始状态不可点击
|
self.upgrade_button.setEnabled(False) # 初始状态不可点击
|
||||||
|
self.upgrade_button_test.setEnabled(False) # 初始状态不可点击
|
||||||
self.ip_input.setText("192.168.0.200")
|
self.ip_input.setText("192.168.0.200")
|
||||||
self.port_input.setText("12345")
|
self.port_input.setText("12345")
|
||||||
|
|
||||||
@ -121,6 +125,7 @@ class SocketClientApp(QMainWindow):
|
|||||||
button_layout.addWidget(self.connect_button)
|
button_layout.addWidget(self.connect_button)
|
||||||
button_layout.addWidget(self.get_data_button)
|
button_layout.addWidget(self.get_data_button)
|
||||||
button_layout.addWidget(self.upgrade_button)
|
button_layout.addWidget(self.upgrade_button)
|
||||||
|
button_layout.addWidget(self.upgrade_button_test)
|
||||||
main_layout.addLayout(button_layout)
|
main_layout.addLayout(button_layout)
|
||||||
|
|
||||||
# 添加分割线
|
# 添加分割线
|
||||||
@ -161,10 +166,42 @@ class SocketClientApp(QMainWindow):
|
|||||||
self.connect_button.clicked.connect(self.connect_to_server)
|
self.connect_button.clicked.connect(self.connect_to_server)
|
||||||
self.get_data_button.clicked.connect(self.on_button_clicked)
|
self.get_data_button.clicked.connect(self.on_button_clicked)
|
||||||
self.upgrade_button.clicked.connect(self.on_button_upgrade)
|
self.upgrade_button.clicked.connect(self.on_button_upgrade)
|
||||||
|
self.upgrade_button_test.clicked.connect(self.on_button_upgrade_test)
|
||||||
|
|
||||||
# 设置布局策略,确保控件大小随窗口调整
|
# 设置布局策略,确保控件大小随窗口调整
|
||||||
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
|
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
|
||||||
|
|
||||||
|
def get_extremes(self,data):
|
||||||
|
"""获取最大和最小的10个值(排序法)"""
|
||||||
|
sorted_data = np.sort(data)
|
||||||
|
return {
|
||||||
|
'top10_max': sorted_data[-10:][::-1].tolist(), # 降序排列
|
||||||
|
'top10_min': sorted_data[:10].tolist()
|
||||||
|
}
|
||||||
|
|
||||||
|
def mean_without_max_optimized(self,data):
|
||||||
|
"""优化内存使用的版本"""
|
||||||
|
arr = np.array(data)
|
||||||
|
if len(arr) < 2:
|
||||||
|
return np.nan
|
||||||
|
|
||||||
|
max_val = np.max(arr)
|
||||||
|
# 计算总和和计数时直接排除最大值
|
||||||
|
total = np.sum(arr) - max_val
|
||||||
|
count = len(arr) - 1
|
||||||
|
return total / count
|
||||||
|
|
||||||
|
def mean_without_min_optimized(self, data):
|
||||||
|
"""优化内存使用的版本"""
|
||||||
|
arr = np.array(data)
|
||||||
|
if len(arr) < 2:
|
||||||
|
return np.nan
|
||||||
|
|
||||||
|
min_val = np.min(arr)
|
||||||
|
# 计算总和和计数时直接排除最大值
|
||||||
|
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"""
|
||||||
crc = 0
|
crc = 0
|
||||||
@ -173,25 +210,26 @@ class SocketClientApp(QMainWindow):
|
|||||||
return crc & 0xFF # 只保留最低字节
|
return crc & 0xFF # 只保留最低字节
|
||||||
def connect_to_server(self):
|
def connect_to_server(self):
|
||||||
""" 连接到服务器 """
|
""" 连接到服务器 """
|
||||||
ip = self.ip_input.text()
|
self.ip = self.ip_input.text()
|
||||||
port = self.port_input.text()
|
self.port = self.port_input.text()
|
||||||
|
|
||||||
if not ip or not port:
|
if not self.ip or not self.port:
|
||||||
self.status_bar.showMessage("状态: 请输入有效的 IP 和端口号")
|
self.status_bar.showMessage("状态: 请输入有效的 IP 和端口号")
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
port = int(port)
|
self.port = int(self.port)
|
||||||
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
self.socket.settimeout(2)
|
self.socket.settimeout(2)
|
||||||
# 设置 keep-alive 选项
|
# 设置 keep-alive 选项
|
||||||
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
||||||
self.socket.connect((ip, port))
|
self.socket.connect((self.ip, self.port))
|
||||||
|
|
||||||
self.get_data_button.setEnabled(True) # 连接成功,启用获取数据按钮
|
self.get_data_button.setEnabled(True) # 连接成功,启用获取数据按钮
|
||||||
self.upgrade_button.setEnabled(True)
|
self.upgrade_button.setEnabled(True)
|
||||||
self.status_bar.showMessage(f"状态: 连接成功! 服务器 {ip}:{port}")
|
self.upgrade_button_test.setEnabled(True)
|
||||||
|
self.status_bar.showMessage(f"状态: 连接成功! 服务器 {self.ip}:{self.port}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status_bar.showMessage(f"状态: 连接失败 - {str(e)}")
|
self.status_bar.showMessage(f"状态: 连接失败 - {str(e)}")
|
||||||
@ -274,7 +312,7 @@ class SocketClientApp(QMainWindow):
|
|||||||
""" 获取数据并绘制 """
|
""" 获取数据并绘制 """
|
||||||
try:
|
try:
|
||||||
self.status_bar.showMessage("状态: 正在获取数据...")
|
self.status_bar.showMessage("状态: 正在获取数据...")
|
||||||
self.socket.sendall(bytes([0xAA, 0x55, 0xAA,0x01])) # 发送数据
|
self.socket.sendall(bytes([0xAA,0x55,0xAA,0x01,0x00,0x00,0x01,0x00,0x77,0x01,0x00,0x01,0x00,0x00,0x00])) # 发送数据
|
||||||
data = self.process_packet() # 接收所有数据
|
data = self.process_packet() # 接收所有数据
|
||||||
data = np.frombuffer(data, dtype=np.int32) # 根据实际数据格式转换
|
data = np.frombuffer(data, dtype=np.int32) # 根据实际数据格式转换
|
||||||
for i in range(min(100, len(data))): # 确保不超过数据长度
|
for i in range(min(100, len(data))): # 确保不超过数据长度
|
||||||
@ -285,6 +323,14 @@ class SocketClientApp(QMainWindow):
|
|||||||
for i in range(min(100, len(scaled_data))): # 确保不超过数据长度
|
for i in range(min(100, len(scaled_data))): # 确保不超过数据长度
|
||||||
print(f"{scaled_data[i]:2f}", end=" ")
|
print(f"{scaled_data[i]:2f}", end=" ")
|
||||||
print() # 换行
|
print() # 换行
|
||||||
|
result = self.get_extremes(scaled_data)
|
||||||
|
print("最大的10个值:", result['top10_max'])
|
||||||
|
print("最小的10个值:", result['top10_min'])
|
||||||
|
mean_max = self.mean_without_max_optimized(result['top10_max'])
|
||||||
|
print(f"top10_max 去除最大的数据后的平均值1:{mean_max}")
|
||||||
|
mean_min = self.mean_without_min_optimized(result['top10_min'])
|
||||||
|
print(f"top10_min 去除最大的数据后的平均值2:{mean_min}")
|
||||||
|
print(f"pp :{mean_max - mean_min}")
|
||||||
self.canvas.plot_data(scaled_data) # 在 Qt 界面中绘图
|
self.canvas.plot_data(scaled_data) # 在 Qt 界面中绘图
|
||||||
self.status_bar.showMessage("状态: 数据绘制完成")
|
self.status_bar.showMessage("状态: 数据绘制完成")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -338,6 +384,56 @@ class SocketClientApp(QMainWindow):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Upgrade failed: {str(e)}")
|
print(f"Upgrade failed: {str(e)}")
|
||||||
|
|
||||||
|
def on_button_upgrade_test(self):
|
||||||
|
"""打开文件选择对话框"""
|
||||||
|
file_path, _ = QFileDialog.getOpenFileName(
|
||||||
|
self, "选择升级文件", "", "二进制文件 (*.bin);;所有文件 (*)"
|
||||||
|
)
|
||||||
|
|
||||||
|
if file_path:
|
||||||
|
file_name = os.path.basename(file_path)
|
||||||
|
self.status_bar.showMessage(f"已选择: {file_name}")
|
||||||
|
try:
|
||||||
|
print("Starting upgrade process...")
|
||||||
|
|
||||||
|
if not os.path.exists(file_path):
|
||||||
|
raise FileNotFoundError(f"Upgrade file {file_path} not found")
|
||||||
|
|
||||||
|
with open(file_path, "rb") as f:
|
||||||
|
package_data = f.read()
|
||||||
|
|
||||||
|
if not package_data:
|
||||||
|
raise ValueError("Upgrade file is empty")
|
||||||
|
|
||||||
|
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
|
||||||
|
result_code = 0
|
||||||
|
|
||||||
|
package_head = struct.pack("<3sBBB", header_magic, cmd, version, result_code)
|
||||||
|
full_packet = package_head + upgrade_req
|
||||||
|
|
||||||
|
print("Full packet prepared:")
|
||||||
|
print(f"Header magic: {package_head[:3].hex()}")
|
||||||
|
print(f"Command: {cmd}, Version: {version}")
|
||||||
|
print(f"Upgrade length: {upgrade_len}, CRC: {crc}")
|
||||||
|
print(f"Total packet size: {len(full_packet)} bytes")
|
||||||
|
|
||||||
|
self.socket.sendall(full_packet)
|
||||||
|
sleep(15)
|
||||||
|
self.socket.close()
|
||||||
|
self.connect_to_server()
|
||||||
|
self.socket.sendall(full_packet)
|
||||||
|
print("Upgrade packet ready to send (commented out actual send code)")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Upgrade failed: {str(e)}")
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app = QApplication(sys.argv)
|
app = QApplication(sys.argv)
|
||||||
window = SocketClientApp()
|
window = SocketClientApp()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user