提交现有代码
This commit is contained in:
Executable
+396
@@ -0,0 +1,396 @@
|
||||
# The `HttpClient` class is a Python class that handles HTTP requests, sends commands to a server,
|
||||
# processes server responses, and calculates various results based on received data.
|
||||
from PySide6.QtCore import QObject, Signal, Slot, QTimer
|
||||
from datetime import datetime
|
||||
import random
|
||||
import gzip
|
||||
from io import BytesIO
|
||||
from Manager.history_manager import historyManager
|
||||
import json
|
||||
from config import *
|
||||
import requests
|
||||
import logging
|
||||
|
||||
# 配置日志记录
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger('HttpClient')
|
||||
class HttpClient(QObject):
|
||||
reciveData = Signal(dict)
|
||||
|
||||
def __init__(self, address, port, connection_name, psk=None):
|
||||
super().__init__()
|
||||
self.name = connection_name
|
||||
self.init = 1
|
||||
self.file_name = ""
|
||||
self.device_name = ""
|
||||
self.address = address
|
||||
self.port = port
|
||||
self.tempIndex = 0
|
||||
self.base_url = f"http://{address}:{port}/api"
|
||||
logger.info(f"HttpClient initialized with base URL: {self.base_url}")
|
||||
|
||||
# 定时器
|
||||
self.debug_timer = QTimer(self)
|
||||
self.debug_timer.setInterval(5000)
|
||||
self.debug_timer.timeout.connect(self.debug_info)
|
||||
if YSMODE:
|
||||
self.debug_timer.start()
|
||||
logger.info("Debug mode enabled")
|
||||
|
||||
def debug_info(self):
|
||||
if self.tempIndex == 0:
|
||||
self.device_name = "scanner1"
|
||||
self.tempIndex = 1
|
||||
elif self.tempIndex == 1:
|
||||
self.device_name = "scanner2"
|
||||
self.tempIndex = 0
|
||||
self.reciveData.emit({
|
||||
"device": self.device_name,
|
||||
"WtOSC": [random.uniform(0.80,0.82), 0.799, 0.819, 0.837, 0.83, 0.815, 0.812, 0.81],
|
||||
"WtINS": [random.uniform(10.498,10.520), 10.525, 10.512, 10.488, 10.485, 10.486, 10.471, 10.468],
|
||||
"WtISC": [0.973, 0.965, 0.94, 0.924, 0.935, 0.957, 0.968, 0.97],
|
||||
"WtALL": [12.271, 12.288, 12.271, 12.249, 12.25, 12.258, 12.25, 12.248],
|
||||
"AngOSC": [0, 90, 346.656],
|
||||
"AngINS": [270, 0, 253.233],
|
||||
"AngISC": [90, 315, 144.457],
|
||||
"AngALL": [270, 0, 226.029],
|
||||
"DmCORE": [random.uniform(14,14.3), 14.2, 14.1],
|
||||
"DmALL": [random.uniform(37,37.2), 37.1, 37.2],
|
||||
"EccentricityINS": random.uniform(0.30, 0.60),
|
||||
"EccentricityOSC": 4.540023894862595,
|
||||
"EccentricityISC": 5.035971223021576,
|
||||
"Volatility": [0.021, 0.021, 0.028],
|
||||
"EllipticityDmALL": -0.0,
|
||||
"EllipticityDmCORE": -0.0,
|
||||
"AvgALL": 12.260625000000001,
|
||||
"AvgISC": 0.954, "AvgOSC": 0.81525, "AvgINS": 10.491625, "MinALL": 12.248, "MinISC": 0.924, "MinOSC": 0.799, "MinINS": 10.468,
|
||||
"ConcentricityALL": 99.83697424193022, "ConcentricityISC": 97.4169741697417, "ConcentricityOSC": 97.67726161369193, "ConcentricityINS": 99.72848092221216,
|
||||
"EccentricALL": 0.020000000000000462, "EccentricISC": 0.024499999999999966, "EccentricOSC": 0.01899999999999996, "EccentricINS": 0.028500000000000192,
|
||||
"EccentricityALL": 0.32552083333334086,"EdgesA": [41.53, 42.66, 54.93, 56.28, 75.88, 76.58, 86.97, 88.19], "EdgesB": [39.36, 40.58, 52.69, 53.92, 73.64, 74.23, 84.77, 86.01]})
|
||||
|
||||
# self.reciveData.emit({
|
||||
# "device": self.device_name,
|
||||
# "WtOSC": [0.83, 0.86, 0.84, 0.81, 0.88, 0.92, 0.87, 0.79],
|
||||
# "WtISC": [0.72, 0.76, 1.03, 0.96, 1.05, 0.84, 0.77, 0.89],
|
||||
# "WtINS": [5.96, 6.57, 11.33, 13.54, 11.27, 6.47, 5.88, 7.62],
|
||||
# "WtALL": [7.50, 8.20, 13.20, 15.32, 13.21, 8.22, 7.52, 9.30],
|
||||
# "AngOSC": [303.75, 225.00, 21.88],
|
||||
# "AngINS": [202.50, 135.00, 274.23],
|
||||
# "AngISC": [247.50, 78.75, 301.21],
|
||||
# "AngALL": [247.50, 135.00, 286.10],
|
||||
# "DmCORE": [16.69, 14.54, 18.85],
|
||||
# "DmALL": [37.21, 39.16, 35.27],
|
||||
# "DmCOREDeviation": 1,
|
||||
# "DmALLDeviation": 2,
|
||||
# "AvgINS": 8.82,
|
||||
# "AvgOSC": 0.95,
|
||||
# "AvgISC": 0.88,
|
||||
# "AvgALL": 9.63,
|
||||
# "MinISC": 0.95,
|
||||
# "MinOSC": 0.81,
|
||||
# "MinINS": 5.88,
|
||||
# "MinALL": 7.50,
|
||||
# "EccentricINS": 0.95,
|
||||
# "EccentricOSC": 2.03,
|
||||
# "EccentricISC": 3.22,
|
||||
# "EccentricALL": 8.82,
|
||||
# "EccentricityINS": 16.003,
|
||||
# "EccentricityOSC": 21.126,
|
||||
# "EccentricityISC": 43.283,
|
||||
# "EccentricityALL": 43.283,
|
||||
# "ConcentricityALL" : 21.25,
|
||||
# "ConcentricityINS" : 21.25,
|
||||
# "ConcentricityOSC" : 11.63,
|
||||
# "ConcentricityISC" : 6.53,
|
||||
# "ConcentricityDeviationALL": 21.25,
|
||||
# "ConcentricityDeviationINS": 21.25,
|
||||
# "ConcentricityDeviationOSC": 11.63,
|
||||
# "ConcentricityDeviationISC": 6.53,
|
||||
# "EllipticityDmCORE": 6.51,
|
||||
# "EllipticityDmALL": 9.68,
|
||||
# "Volatility": [0.290, 0.088, 0.314],
|
||||
# "EdgesA": [41.53, 42.66, 54.93, 56.28, 75.88, 76.58, 86.97, 88.19],
|
||||
# "EdgesB": [39.36, 40.58, 52.69, 53.92, 73.64, 74.23, 84.77, 86.01]
|
||||
# })
|
||||
|
||||
def start_handshake(self):
|
||||
# HTTP客户端不需要握手,可以直接发送请求
|
||||
logger.info(f"{self.name}: HTTP client ready to send requests to {self.address}:{self.port}")
|
||||
|
||||
def check_server_status(self):
|
||||
"""检查服务器状态"""
|
||||
try:
|
||||
url = f"{self.base_url}/status"
|
||||
response = requests.get(url, timeout=5)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
logger.error(f"Failed to get server status, status code: {response.status_code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Error checking server status: {e}")
|
||||
return None
|
||||
|
||||
|
||||
@Slot()
|
||||
def handle_timeout(self):
|
||||
# HTTP客户端不需要重连,重试请求即可
|
||||
logger.info(f"{self.name}: HTTP request timeout, ready to retry")
|
||||
|
||||
@Slot()
|
||||
def udp_socket_connected(self):
|
||||
# 兼容原有接口,HTTP客户端不需要UDP连接
|
||||
pass
|
||||
|
||||
@Slot()
|
||||
def readyRead(self):
|
||||
# 兼容原有接口,HTTP客户端不需要监听接收数据
|
||||
pass
|
||||
|
||||
def send_command(self, command, params=None):
|
||||
"""发送命令到服务器"""
|
||||
try:
|
||||
url = f"{self.base_url}/command"
|
||||
data = {"command": command}
|
||||
if params:
|
||||
data.update(params)
|
||||
|
||||
response = requests.post(url, json=data, timeout=10)
|
||||
if response.status_code == 200:
|
||||
logger.info(f"Command '{command}' sent successfully")
|
||||
return response.json()
|
||||
else:
|
||||
logger.error(f"Failed to send command '{command}', status code: {response.status_code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending command '{command}': {e}")
|
||||
return None
|
||||
|
||||
@Slot()
|
||||
def handshake_timeout(self):
|
||||
# HTTP客户端不需要处理握手超时
|
||||
pass
|
||||
|
||||
@Slot(bytearray)
|
||||
def write_data(self, data):
|
||||
"""发送二进制数据到服务器"""
|
||||
try:
|
||||
url = f"{self.base_url}/data"
|
||||
files = {'file': ('binary_data', data, 'application/octet-stream')}
|
||||
response = requests.post(url, files=files, timeout=10)
|
||||
|
||||
if response.status_code == 200:
|
||||
logger.info('Data sent successfully')
|
||||
result = response.json()
|
||||
if result:
|
||||
self.reciveData.emit(self.calResult(json.dumps(result)))
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Failed to send data, status code: {response.status_code}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending data: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def compress_file_with_params(self, file_content):
|
||||
compressed_data = None
|
||||
try:
|
||||
# 使用BytesIO来创建一个可写的文件对象
|
||||
compressed_file = BytesIO()
|
||||
with gzip.GzipFile(fileobj=compressed_file, mode='wb') as gzf:
|
||||
gzf.write(file_content)
|
||||
|
||||
# 读取压缩后的文件内容
|
||||
compressed_data = compressed_file.getvalue()
|
||||
return compressed_data
|
||||
except Exception as e:
|
||||
logger.error(f'Error compressing file: {e}')
|
||||
return None
|
||||
|
||||
@Slot(int, bytearray,str, int)
|
||||
def start_cal(self, motor_index, file_content, direction, row_count):
|
||||
"""开始计算,通过HTTP发送文件数据"""
|
||||
logger.info(f"Starting calculation with motor_index: {motor_index}, direction: {direction}")
|
||||
if direction == "":
|
||||
return
|
||||
|
||||
direction_value = 0
|
||||
if direction == "UP":
|
||||
direction_value = 1
|
||||
elif direction == "DOWN":
|
||||
direction_value = 2
|
||||
|
||||
current_time = datetime.now()
|
||||
compress_file_content = self.compress_file_with_params(file_content)
|
||||
if not compress_file_content:
|
||||
logger.error("Failed to compress file content")
|
||||
return
|
||||
|
||||
self.device_name = f"scanner{motor_index}"
|
||||
self.file_name = f'{current_time.strftime("%Y-%m-%d_%H_%M_%S_%f")[:-3]}_direction_{direction_value}_device{motor_index}.csv'
|
||||
|
||||
try:
|
||||
url = f"{self.base_url}/data"
|
||||
|
||||
# 准备表单数据
|
||||
form_data = {
|
||||
"init": str(self.init),
|
||||
"device_id": str(motor_index),
|
||||
"device_name": DEVICENAME,
|
||||
"version": "2",
|
||||
"offset": "0",
|
||||
"scale": "1",
|
||||
"file_type": "raw",
|
||||
"compress": "gz",
|
||||
"row_count": str(row_count),
|
||||
"direction": direction
|
||||
}
|
||||
|
||||
# 准备文件数据
|
||||
files = {
|
||||
'file': (f'{self.file_name}.gz', compress_file_content, 'application/gzip')
|
||||
}
|
||||
|
||||
self.init = 0
|
||||
logger.info(f"Sending file: {self.file_name}.gz with size: {len(compress_file_content)} bytes")
|
||||
|
||||
# 发送HTTP POST请求
|
||||
response = requests.post(url, data=form_data, files=files, timeout=30)
|
||||
|
||||
if response.status_code == 200:
|
||||
logger.info("Calculation request sent successfully")
|
||||
try:
|
||||
result = response.json()
|
||||
if result:
|
||||
# 添加设备名称到结果中
|
||||
result['device'] = self.device_name
|
||||
# 计算额外的结果数据
|
||||
processed_result = self.calResult(json.dumps(result))
|
||||
self.reciveData.emit(processed_result)
|
||||
except json.JSONDecodeError:
|
||||
logger.error("Failed to parse server response as JSON")
|
||||
else:
|
||||
logger.error(f"Failed to send calculation request, status code: {response.status_code}")
|
||||
logger.error(f"Response content: {response.text}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending calculation request: {e}")
|
||||
|
||||
@Slot()
|
||||
def set_init(self):
|
||||
self.init = 1
|
||||
logger.info(f"=====set init==== {self.init}")
|
||||
|
||||
def calResult(self, r_str):
|
||||
"""处理服务器返回的计算结果"""
|
||||
try:
|
||||
robj = json.loads(r_str)
|
||||
|
||||
# 安全地获取结果中的数据,如果不存在则使用默认空列表
|
||||
DmALL = robj.get("DmALL", [])
|
||||
DmCORE = robj.get("DmCORE", [])
|
||||
WtOSC = robj.get("WtOSC", [])
|
||||
WtINS = robj.get("WtINS", [])
|
||||
WtISC = robj.get("WtISC", [])
|
||||
WtALL = robj.get("WtALL", [])
|
||||
|
||||
# 设置设备名称
|
||||
robj["device"] = self.device_name
|
||||
|
||||
# 计算椭圆度
|
||||
if len(DmALL) >= 3:
|
||||
robj["EllipticityDmALL"] = 2*abs(DmALL[1]-DmALL[2])/(DmALL[1] + DmALL[2]) if (DmALL[1] + DmALL[2]) != 0 else 0
|
||||
else:
|
||||
robj["EllipticityDmALL"] = 0
|
||||
|
||||
if len(DmCORE) >= 3:
|
||||
robj["EllipticityDmCORE"] = 2*abs(DmCORE[1]-DmCORE[2])/(DmCORE[1] + DmCORE[2]) if (DmCORE[1] + DmCORE[2]) != 0 else 0
|
||||
else:
|
||||
robj["EllipticityDmCORE"] = 0
|
||||
|
||||
# 计算平均值
|
||||
robj["AvgALL"] = self.avg(WtALL)
|
||||
robj["AvgISC"] = self.avg(WtISC)
|
||||
robj["AvgOSC"] = self.avg(WtOSC)
|
||||
robj["AvgINS"] = self.avg(WtINS)
|
||||
|
||||
# 计算最小值
|
||||
if WtALL:
|
||||
robj["MinALL"] = min(WtALL)
|
||||
robj["ConcentricityALL"] = 200*min(WtALL)/(min(WtALL)+max(WtALL)) if (min(WtALL)+max(WtALL)) != 0 else 0
|
||||
robj["EccentricALL"] = (max(WtALL) - min(WtALL))/2
|
||||
robj["EccentricityALL"] = (max(WtALL) - min(WtALL))*100/max(WtALL) if max(WtALL) != 0 else 0
|
||||
else:
|
||||
robj["MinALL"] = 0
|
||||
robj["ConcentricityALL"] = 0
|
||||
robj["EccentricALL"] = 0
|
||||
robj["EccentricityALL"] = 0
|
||||
|
||||
if WtISC:
|
||||
robj["MinISC"] = min(WtISC)
|
||||
robj["ConcentricityISC"] = 200*min(WtISC)/(min(WtISC)+max(WtISC)) if (min(WtISC)+max(WtISC)) != 0 else 0
|
||||
robj["EccentricISC"] = (max(WtISC) - min(WtISC))/2
|
||||
robj["EccentricityISC"] = (max(WtISC) - min(WtISC))*100/max(WtISC) if max(WtISC) != 0 else 0
|
||||
else:
|
||||
robj["MinISC"] = 0
|
||||
robj["ConcentricityISC"] = 0
|
||||
robj["EccentricISC"] = 0
|
||||
robj["EccentricityISC"] = 0
|
||||
|
||||
if WtOSC:
|
||||
robj["MinOSC"] = min(WtOSC)
|
||||
robj["ConcentricityOSC"] = 200*min(WtOSC)/(min(WtOSC)+max(WtOSC)) if (min(WtOSC)+max(WtOSC)) != 0 else 0
|
||||
robj["EccentricOSC"] = (max(WtOSC) - min(WtOSC))/2
|
||||
robj["EccentricityOSC"] = (max(WtOSC) - min(WtOSC))*100/max(WtOSC) if max(WtOSC) != 0 else 0
|
||||
else:
|
||||
robj["MinOSC"] = 0
|
||||
robj["ConcentricityOSC"] = 0
|
||||
robj["EccentricOSC"] = 0
|
||||
robj["EccentricityOSC"] = 0
|
||||
|
||||
if WtINS:
|
||||
robj["MinINS"] = min(WtINS)
|
||||
robj["ConcentricityINS"] = 200*min(WtINS)/(min(WtINS)+max(WtINS)) if (min(WtINS)+max(WtINS)) != 0 else 0
|
||||
robj["EccentricINS"] = (max(WtINS) - min(WtINS))/2
|
||||
robj["EccentricityINS"] = (max(WtINS) - min(WtINS))*100/max(WtINS) if max(WtINS) != 0 else 0
|
||||
else:
|
||||
robj["MinINS"] = 0
|
||||
robj["ConcentricityINS"] = 0
|
||||
robj["EccentricINS"] = 0
|
||||
robj["EccentricityINS"] = 0
|
||||
|
||||
# 保存到历史记录
|
||||
try:
|
||||
historyManager.create(robj)
|
||||
except Exception as hist_error:
|
||||
logger.error(f"Error saving to history: {hist_error}")
|
||||
|
||||
return robj
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing calculation result: {e}")
|
||||
return {}
|
||||
|
||||
def avg(self, data):
|
||||
"""计算平均值"""
|
||||
if len(data) == 0:
|
||||
return 0
|
||||
if len(data) == 1:
|
||||
return data[0]
|
||||
try:
|
||||
mean_value = sum(data) / len(data)
|
||||
return mean_value
|
||||
except TypeError:
|
||||
logger.error("Error calculating average: data contains non-numeric values")
|
||||
return 0
|
||||
|
||||
@Slot(object)
|
||||
def psk_required(self, auth):
|
||||
# HTTP客户端不需要PSK认证
|
||||
pass
|
||||
|
||||
# 为了保持向后兼容性,可以继续使用原类名
|
||||
CalcHttpClient = HttpClient
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user