This commit is contained in:
2026-07-09 06:55:01 +08:00
7 changed files with 139 additions and 44 deletions
+30
View File
@@ -1,8 +1,38 @@
from models import Product, Session
import uuid
from config import *
class ProductManager:
def __init__(self, parent=None):
super().__init__()
self.cur_product_id = ""
config = read_config()
if config.get('product_id', '') == "":
try:
products = self.getInfo("all")
if products == []:
print("no product found in database")
else:
config.update(product_id = products[0]["id"])
save_config(config)
except:
pass
else:
self.cur_product_id = config.get('product_id', '')
def setCurProductId(self, id):
self.cur_product_id = id
config = read_config()
if config.get('product_id', '') == id:
return
config.update(product_id = id)
save_config(config)
def getCurProductId(self):
return self.cur_product_id
def getCurrentProduct(self):
return self.getInfo(self.cur_product_id)
def create(self, info):
data = {
+15
View File
@@ -1,3 +1,5 @@
import json
LOCALBORKER = "127.0.0.1"
LOCALPORT = 1883
DEVICEBORKER = "127.0.0.1"
@@ -11,3 +13,16 @@ YSMODE = False
COREECTMODE = True
def read_config():
config = {}
path = "/home/admin/.config/cpy/config.json"
with open(path, "r") as f:
config = json.load(f)
return config
return None
def save_config(config):
path = "/home/admin/.config/cpy/config.json"
with open(path, "w", encoding='utf-8') as f:
json.dump(config, f, indent=4)
+16 -1
View File
@@ -6,6 +6,7 @@ import os
import gzip
from io import BytesIO
from Manager.history_manager import historyManager
from Manager.product_manager import productManager
import json
from config import *
import logging
@@ -406,7 +407,21 @@ class CpyMqttClient(QObject):
"row_count": str(row_count),
"direction": direction
}
try:
product_info = json.loads(productManager.getCurrentProduct().get("info", "{}"))
if product_info:
pinfo = {}
pinfo["OSC"] = float(product_info["WtOSC"]["bcz"])
pinfo["INS"] = float(product_info["WtINS"]["bcz"])
pinfo["ISC"] = float(product_info["WtISC"]["bcz"])
if pinfo["OSC"] > 0.1 or pinfo["INS"] > 0.1 or pinfo["ISC"] > 0.1:
info["product_info"] = pinfo
except Exception as e:
logger.error(f"Error in getCurrentProduct: {e}")
logger.info(f"info: {info}")
# 重置init标志
self.init = 0
+10 -10
View File
@@ -378,7 +378,7 @@ class HttpServerEnhanced(QThread):
if channelA is None or channelB is None:
print("invalid data packet")
return
if len(channelA) > 100:
#gause filter
channelA_filtered = gaussian_filter1d(channelA, 0.1)
@@ -388,20 +388,20 @@ class HttpServerEnhanced(QThread):
#save data to csv file
chop_num = 300
if ip_address == "192.168.100.236" or msg.get("id","") == "1#SCANNER":
dev_name = "Scanner1"
chop_num = 200
chop_num = 1
elif ip_address == "192.168.100.237" or msg.get("id","") == "2#SCANNER":
dev_name = "Scanner2"
chop_num = 200
chop_num = 1
if direction == "UP":
channelA = channelA[chop_num:-200]
channelB = channelB[chop_num:-200]
channelA = channelA[chop_num:-1]
channelB = channelB[chop_num:-1]
elif direction == "DOWN":
channelA = channelA[200:-chop_num]
channelB = channelB[200:-chop_num]
channelA = channelA[1:-chop_num]
channelB = channelB[1:-chop_num]
save_filename = f'{time.strftime("%Y%m%d_%H%M%S")}_{dev_name}_{direction}.csv'
data_path = self.save_data_to_csv(save_filename, channelA, channelB)
@@ -409,7 +409,7 @@ class HttpServerEnhanced(QThread):
channelA_average = np.mean(channelA)
channelB_average = np.mean(channelB)
#COREECTMODE = False
# COREECTMODE = False
corrected_name = None
if COREECTMODE and channelA_average > 5000 and channelB_average > 5000:
try:
@@ -453,7 +453,7 @@ class HttpServerEnhanced(QThread):
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}") # 记录错误信息
+10 -12
View File
@@ -13,6 +13,11 @@ import time
import sqlite3
import sys
import json
from Manager.product_manager import productManager
from x_ray_data_processor import processor
def import_sql_to_database(db_path, table_bame):
conn = sqlite3.connect(db_path)
@@ -41,18 +46,6 @@ def get_cpu_serial():
return serial
def read_config():
config = {}
path = "/home/admin/.config/cpy/config.json"
with open(path, "r") as f:
config = json.load(f)
return config
return None
def save_config(config):
path = "/home/admin/.config/cpy/config.json"
with open(path, "w", encoding='utf-8') as f:
json.dump(config, f, indent=4)
if __name__ == "__main__":
app = QCoreApplication(sys.argv)
@@ -91,6 +84,11 @@ if __name__ == "__main__":
config.update(sn = device_id)
save_config(config)
if 'mid_pipe_diameter' in config:
val = float(config['mid_pipe_diameter'])
if val >= 100 and val <= 200:
processor.set_pipe_diameter(val)
ip = "101.200.29.204"
port = 18003
try:
+11 -8
View File
@@ -4,7 +4,9 @@ import time
import base64
import socket
import httpx
from config import *
from PySide6.QtCore import Signal, Slot,QObject,QMetaObject,Qt,QTimer
from Manager.product_manager import productManager
from Manager.history_manager import historyManager
@@ -41,7 +43,7 @@ class MQTTClient(QObject):
self.local_client = mqtt.Client(client_id = 'controller_' + self.random_string(6)) # 创建本地客户端
self.device_client = mqtt.Client(client_id = 'controller_dev_' + self.random_string(6)) # 创建设备客户端
self.m_clienttimestamp = 0
self.cur_product_id = "C8111D73-F387-981D-18D5-849816E1793C"
# 设置回调函数
self.local_client.on_connect = self.on_connect
self.local_client.on_message = self.on_message
@@ -212,7 +214,7 @@ class MQTTClient(QObject):
if json_obj.get("value") == "true":
cid = json_obj.get("cid")
print("Follow,",cid)
self.send_current_product(self.cur_product_id)
self.send_current_product(productManager.cur_product_id)
elif method == "input":
key = json_obj.get("key")
value = json_obj.get("value")
@@ -269,10 +271,11 @@ class MQTTClient(QObject):
self.send_products()
elif method == "currentProduct":
self.cur_product_id = json_obj.get("id")
print(f"Current product id: {self.cur_product_id}")
self.send_current_product(self.cur_product_id)
self.send_current_product_id(self.cur_product_id)
cur_product_id = json_obj.get("id")
print(f"Current product id: {cur_product_id}")
self.send_current_product(cur_product_id)
self.send_current_product_id(cur_product_id)
productManager.setCurProductId(cur_product_id)
elif method == "loadHistoryList":
cid = json_obj.get("cid")
@@ -525,10 +528,10 @@ class MQTTClient(QObject):
def send_products(self):
"""发送产品信息"""
data = dict()
data["current_id"] = self.cur_product_id
data["current_id"] = productManager.cur_product_id
data["method"] = "productList"
data["infos"] = productManager.getInfo()
print(f"Current product id: {self.cur_product_id}")
print(f"Current product id: {productManager.cur_product_id}")
self.publish_cpy(TOPICPRODUCT, data, 1) # 发布设备信息
def start_ys(self, flag):
+47 -13
View File
@@ -23,6 +23,11 @@ class XRayDataProcessor:
self.derivative_data = None
self.results = None
self.selected_spans = {'CH1': [], 'CH2': []}
self.pipe_diameter = 130
def set_pipe_diameter(self, diameter):
"""设置管道直径"""
self.pipe_diameter = diameter
def load_data(self, filepath):
"""加载CSV数据文件"""
@@ -70,6 +75,31 @@ class XRayDataProcessor:
print(f"计算平滑数据和导数出错: {str(e)}")
return False
def find_outer_peak(self, data, sigma=2.0, peak_threshold=0.15):
"""
找到一阶导数绝对值的主要极值点,作为圆弧的外侧
"""
# 1. 平滑数据,消除噪声
smoothed = gaussian_filter1d(data, sigma=sigma)
# 2. 从头开始,若第data[k] - data[k + 50] > data[k] * 0.2,说明k是外侧极值点
if len(data) < 1000:
return [0, 0]
outer_peaks = [0, 0]
for k in range(len(data) - 50):
if smoothed[k] - smoothed[k + 50] > smoothed[k] * peak_threshold:
outer_peaks[0] = k
break
# 3. 从尾开始,若第data[k] - data[k - 50] > data[k] * 0.2,说明k是外侧极值点
for k in range(len(data) - 50, 0, -1):
if smoothed[k] - smoothed[k - 50] > smoothed[k] * peak_threshold:
outer_peaks[1] = k
break
return outer_peaks
def find_derivative_peaks(self, deriv_data, sigma=5, peak_threshold=0.3):
"""
精准找出一阶导数绝对值的主要极值点
@@ -123,6 +153,9 @@ class XRayDataProcessor:
# 为两个通道分别寻找区间
ch1_spans = self._find_spans_for_channel('CH1')
ch2_spans = self._find_spans_for_channel('CH2')
if ch1_spans == [] or ch2_spans == []:
return False
# 为每个通道存储各自的区间
success_count = 0
@@ -150,23 +183,24 @@ class XRayDataProcessor:
def _find_spans_for_channel(self, channel):
"""为指定通道寻找合适的区间"""
derivative = self.derivative_data[channel]
data = self.channel_data[channel]
n = len(self.index_data)
abs_derivative = np.abs(derivative)
potential_extremes = self.find_derivative_peaks(abs_derivative)
potential_extremes = self.find_outer_peak(data)
# 至少有两个极值点,选择第一个和最后一个
p1 = potential_extremes[0]
p2 = potential_extremes[-1]
if p1 == 0 and p2 == 0:
return []
# 计算区间边界: [p1*0.2, p1*0.9], [(n-p2)*0.1+p2, (n-p2)*0.7+p2]
left_start_idx = max(0, int(p1 * 0.1))
left_end_idx = min(n-1, int(p1 * 0.99))
left_start_idx = max(0, int(p1 * 0.01))
left_end_idx = min(n-1, int(p1))
right_start_idx = min(n-1, int((n - p2) * 0.01 + p2))
right_end_idx = min(n-1, int(n - (n - p2) * 0.1))
right_start_idx = min(n-1, p2)
right_end_idx = min(n-1, int(n - (n - p2) * 0.01))
# 转换为INDEX值
left_span = (self.index_data[left_start_idx], self.index_data[left_end_idx])
@@ -256,11 +290,11 @@ class XRayDataProcessor:
def _model(self, index, Q0, mu, offset):
"""X光束衰减模型"""
R = 65.0
R = self.pipe_diameter / 2
t = 0.8
factor = 0.04
X = factor * (index - offset)
X_clip = np.clip(X, -64.0, 64.0)
X_clip = np.clip(X, -(R-1), R-1)
term1 = np.sqrt((R + t)**2 - X_clip**2)
term2 = np.sqrt(R**2 - X_clip**2)
L = 2 * (term1 - term2)
@@ -269,10 +303,10 @@ class XRayDataProcessor:
def _analyze_channel(self, channel_name, Q_data, index_data):
"""分析单个通道的数据"""
# 参数设置
initial_guess = [np.max(Q_data)*1.5, 0.4, np.max(index_data) * 0.5]
initial_guess = [np.max(Q_data)*2, 0.4, np.max(index_data) * 0.5]
bounds = (
[np.max(Q_data), 0.3, np.max(index_data) * 0.2],
[2*np.max(Q_data), 0.5, np.max(index_data) * 0.8]
[3*np.max(Q_data), 0.5, np.max(index_data) * 0.8]
)
# 执行拟合
@@ -296,7 +330,7 @@ class XRayDataProcessor:
for ch in ['CH1', 'CH2']:
p = self.results[ch]['params_opt']
e = np.sqrt(np.diag(self.results[ch]['params_cov']))
print(f"\n{ch}通道:")
print(f"\n{ch}通道 {self.pipe_diameter}:")
print(f"Q0 = {p[0]:.1f} ± {e[0]:.1f}")
print(f"μ = {p[1]:.6f} ± {e[1]:.6f} mm⁻¹")
print(f"offset = {p[2]:.1f} ± {e[2]:.1f}")