初始提交

This commit is contained in:
2026-08-24 15:49:57 +08:00
commit 4569284de2
181 changed files with 246421 additions and 0 deletions
+253
View File
@@ -0,0 +1,253 @@
import socket
import base64
import json
import time
import psutil
import struct
import csv
from config import *
from x_ray_data_processor import processor
from PySide6.QtCore import QObject, Signal, Slot, QThread,QTimer
# 定义adcDataUnitDef结构体
class adcDataUnitDef:
def __init__(self):
self.ucCmd = 0
self.ucAddr = 0
self.usData = 0
class UdpServer(QThread):
start_cal = Signal(int, bytearray, str, int) # 信号:接收到消息,包含数据、发送者地址和端口
send_collect_data = Signal(dict) #
update_acquisition_info = Signal(int, dict)
def __init__(self, ip="0.0.0.0", port=50009, parent=None):
super(UdpServer, self).__init__(parent)
self.kill_udp_port(port)
self.ip = ip
self.port = port
self.server_socket = None
self.running = True
self.motor1_direction = ""
self.motor2_direction = ""
self.collect_object1 = {
"method" : "scanner1",
"channelA_data" :"base64",
"channelB_data" :"base64",
"intensityA" : 98,
"intensityB" : 98
}
self.collect_object2 = {
"method" : "scanner2",
"channelA_data" :"base64",
"channelB_data" :"base64",
"intensityA" : 98,
"intensityB" : 98
}
self.debug_timer = QTimer(self)
self.debug_timer.timeout.connect(self.update_debug_timer)
if YSMODE:
self.debug_timer.start(1000)
def update_debug_timer(self):
import random
channelA = [random.randint(1, 1000) for _ in range(3000)]
channelB = [random.randint(1, 1000) for _ in range(3000)]
self.collect_object1['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode()
self.collect_object1['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode()
self.collect_object2['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode()
self.collect_object2['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode()
self.send_collect_data.emit(self.collect_object1)
self.send_collect_data.emit(self.collect_object2)
def kill_udp_port(self, port):
for proc in psutil.process_iter():
try:
for conn in proc.connections(kind='udp'):
if conn.laddr.port == port:
print(f" PID={proc.pid}, procname={proc.name()}")
proc.kill()
except psutil.AccessDenied:
continue
def packet_crc(self, data):
usSum = 0
for byte in data:
usSum += byte
return usSum & 0xFFFF # 确保返回值为16位
def handle_sample_data(self, data):
# 确保数据长度是4的倍数
if len(data) % 4 != 0:
raise ValueError("Data length must be a multiple of 4")
# 使用列表推导式来简化代码
unpacked_data = [struct.unpack_from('<H', data[i:i+2])[0] for i in range(0, len(data), 2)]
# 将数据分为两组
data_list1 = unpacked_data[::2] # 取偶数索引的元素
data_list2 = unpacked_data[1::2] # 取奇数索引的元素
# 打印数据长度,用于调试
print(f"Data contains {len(unpacked_data) // 2} pairs of values")
# print(data_list1)
# print("=======================================")
# print(data_list2)
file_content = bytearray()
datalen = len(data_list2)
for i in range (datalen):
file_content.extend(struct.pack('<ff', data_list1[i], data_list2[i]))
return data_list1,data_list2,file_content,datalen
# @Slot(int, str)
# def update_direction(self, motor_index, direction):
# if motor_index == 1:
# self.motor1_direction = direction
# elif motor_index == 2:
# self.motor2_direction = direction
def parse_packet(self, base64_data):
binary_data = base64.b64decode(base64_data)
channel_A = []
channel_B = []
header_a = struct.unpack('<H', binary_data[0:2])[0]
header_b = struct.unpack('<H', binary_data[2:4])[0]
queue_remain = struct.unpack('<H', binary_data[4:6])[0]
data_len = struct.unpack('<H', binary_data[6:8])[0]
if header_a != 0xAA55 or header_b != 0x55CC:
print("unknown packet header",hex(header_a), hex(header_b))
return None
data_points = []
offset = 8
for _ in range(data_len):
if offset + 4 > len(binary_data):
print("offset:", offset, "data_len:", len(data_points))
break
channel_A.append(struct.unpack('<H', binary_data[offset:offset+2])[0])
channel_B.append(struct.unpack('<H', binary_data[offset+2:offset+4])[0])
offset += 12
file_content = bytearray()
for i in range (data_len):
file_content.extend(struct.pack('<ff', channel_A[i], channel_B[i]))
# 解析数据单元
return channel_A, channel_B,file_content, data_len
def run(self):
"""启动 UDP 服务器"""
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.server_socket.bind((self.ip, self.port))
# 增加接收缓冲区大小
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536) # 设置为 64KB
print(f"UDP server is running on {self.ip}:{self.port}")
while self.running:
try:
while True: # 循环接收数据
try:
data, addr = self.server_socket.recvfrom(65536) # 接收最多 64KB 数据
msg = json.loads(data.decode())
msg_type = msg.get('type')
if msg_type == "dev_discovery":
self.handle_dev_discovery(msg, addr[0])
if msg_type == "data_points":
self.handle_data_point(msg, addr[0])
except json.JSONDecodeError:
print(f"Error decoding JSON data: {data.decode()}")
except OSError as e:
print(f"Error receiving data: {e}") # 记录错误信息
# finally:
# self.stop()
def correct_data(self, filename):
# 加载数据
processor.load_data(filename)
filename = filename[0:-4] +"_corrected.csv"
# 自动选择圆弧区间
if processor.auto_select_arcs():
# 拟合数据
if processor.fit_data():
# 校正数据
corrected = processor.correct_data()
# 保存校正后的数据,去掉头尾各200个点
channel_A,channel_B,corrected = processor.save_corrected_data(
corrected,
filename,
trim_edges=True,
trim_amount=0
)
return channel_A,channel_B,corrected
return None,None,None
def handle_dev_discovery(self, msg, ip_address):
if msg.get("name") == "daq":
status = msg.get("status")
if status:
# temp = status.get("temp", 0) / 10
# speed = status.get("speed", 0)
if ip_address == "192.168.100.236":
self.update_acquisition_info.emit(1, status)
elif ip_address == "192.168.100.237":
self.update_acquisition_info.emit(2, status)
def handle_data_point(self, msg, ip_address):
try:
print("handle data from", ip_address)
direction = ""
if msg.get("direction") == "up":
direction = "UP"
elif msg.get("direction") == "down":
direction = "DOWN"
if msg.get("name") == "daq":
channelA, channelB,file_content, row_count =self.parse_packet(msg.get("data","") )
index_col = [i for i in range(row_count)]
#save data to csv file
filename = f'/home/admin/PythonPro/TGX_PYSERVER/datas/data{time.strftime("%Y%m%d%H%M%S")}.csv'
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['INDEX', 'CH1', 'CH2'])
writer.writerows(zip(index_col, channelA, channelB))
if COREECTMODE:
channelA,channelB,corrected = self.correct_data(filename)
if corrected:
file_content = corrected
channelA_json = json.dumps(channelA)
channelB_json = json.dumps(channelB)
channelA_bytes = channelA_json.encode('utf-8')
channelB_bytes = channelB_json.encode('utf-8')
if ip_address == "192.168.100.236":
self.collect_object1["method"] = "scanner1"
self.start_cal.emit(1, file_content, direction, row_count)
print("====emit direction[1]:", direction)
self.collect_object1['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8')
self.collect_object1['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8')
self.send_collect_data.emit(self.collect_object1)
elif ip_address == "192.168.100.237":
self.collect_object2["method"] = "scanner2"
self.start_cal.emit(2, file_content, direction, row_count)
print("====emit direction[2]:", direction)
self.collect_object2['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8')
self.collect_object2['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8')
self.send_collect_data.emit(self.collect_object2)
except OSError as e:
print(f"Error handle_data_point: {e}") # 记录错误信息
def stop(self):
"""停止 UDP 服务器"""
self.running = False
if self.server_socket:
self.server_socket.close()
self.wait() # 等待线程结束
def send_message(self, message, ip, port):
"""发送消息到指定的 IP 和端口"""
if self.server_socket:
self.server_socket.sendto(message.encode(), (ip, port))
def __del__(self):
self.stop() # 确保在对象销毁时停止服务器