Files
CPY_DevController/mqtt_client.py
T

614 lines
24 KiB
Python

import paho.mqtt.client as mqtt
import json
import time
import base64
import socket
import httpx
from PySide6.QtCore import Signal, Slot,QObject,QMetaObject,Qt,QTimer
from Manager.product_manager import productManager
from Manager.history_manager import historyManager
#from PySide6.QtNetWork import *
# 定义主题常量
TOPICFIRST = "v1/cpy/"
TOPICINFOS = "/infos"
TOPICSTATUS = "/devstatus"
TOPICCAL = "/calculation"
TOPICCTRL = "/control"
TOPICREQUEST = "/request"
TOPICPRODUCT = "/product"
TOPICCOLLECT = "/collect"
TOPICRECEIVE = "/receive"
TOPICNOOP = "/noop"
DEVICE_CONTROL_TOPIC = "device/control"
class MQTTClient(QObject):
write_data = Signal(str, int)
update_direction = Signal(int, str)
update_motor_globaldev_info = Signal(dict)
update_motor_info = Signal(int, dict)
update_alu_info = Signal(int, dict)
update_wsu_info = Signal(int, dict)
update_osu_info = Signal(int, dict)
update_hsv_info = Signal(int, dict)
get_temperature = Signal(str, int)
calc_init = Signal()
def __init__(self, device_id):
super().__init__()
self.device_id = device_id
self.local_client = mqtt.Client(client_id = 'controller_' + self.random_string(6)) # 创建本地客户端
self.remote_client = mqtt.Client(client_id=device_id) # 创建远程客户端
self.device_client = mqtt.Client(client_id = 'controller_dev_' + self.random_string(6)) # 创建设备客户端
self.m_clienttimestamp = 0
# 设置回调函数
self.local_client.on_connect = self.on_connect
self.local_client.on_message = self.on_message
self.local_client.on_disconnect = self.on_disconnect
self.remote_client.on_connect = self.on_connect
self.remote_client.on_message = self.on_message
self.remote_client.on_disconnect = self.on_disconnect
self.device_client.on_connect = self.on_dev_connect
self.device_client.on_message = self.on_dev_message
self.device_client.on_disconnect = self.on_disconnect
self.local_client.username_pw_set(USER, PWD)
self.remote_client.username_pw_set("cpy_machine", "tgzz2025") # 设置用户名和密码
self.device_client.username_pw_set(USER, PWD) # 设置用户名和密码
self.sportModes = ["fast", "normal", "slow"]
self.sportIndex = 0
self.noop_timer = QTimer(self)
self.noop_timer.setInterval(10000)
self.noop_timer.timeout.connect(self.send_noop)
self.noop_timer.start()
self.conn_timer = QTimer(self)
self.conn_timer.setInterval(1000)
self.conn_timer.timeout.connect(self.connTimerHandler)
self.conn_timer.start()
print("mqtt client init")
def random_string(self, length=6):
import random
import string
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def get_emqx_status(self):
"""获取EMQX服务状态"""
try:
EMQX_API_KEY = "79df0d17e0a8d2e8"
EMQX_API_SECRET = "9Aaz8KuCxj0wjh7zMYzMioGyT5henEfSBJbx7K7hcFHO"
client = httpx.Client(
base_url='http://127.0.0.1:18083/api/v5',
auth=(EMQX_API_KEY, EMQX_API_SECRET),
timeout=1.0 # 设置超时时间为5秒
)
response = client.get("/nodes")
print("EMQX状态", response.status_code, response.text)
if response.status_code == 200:
nodes = response.json()
if nodes and len(nodes) > 0:
return True
else:
return False
else:
print(f"检查EMQX状态失败: {response.text}")
return False
except Exception as e:
print(f"检查EMQX状态失败: {e}")
return False
def checkRemoteServer(self, host = '127.0.0.1', port = 1883, timeout=1):
"""
Check if the TCP server is available
:param host: Server IP address or domain name
:param port: Server port number
:param timeout: Connection timeout in seconds
:return: True if the server is available, False otherwise
"""
print(f"Starting to check if {host}:{port} is available")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
result = sock.connect_ex((host, port))
if result == 0:
print(f"Successfully connected to {host}:{port}")
return True
else:
print(f"Failed to connect to {host}:{port}, error code: {result}")
return False
except Exception as e:
print(f"An exception occurred while connecting to {host}:{port}: {e}")
return False
finally:
sock.close()
def connTimerHandler(self):
print("check broker")
self.conn_timer.stop()
if self.get_emqx_status() and self.checkRemoteServer(host=LOCALBORKER,port=LOCALPORT):
print("mqtt brokeris ready")
self.connectToBroker()
else:
print("mqtt brokeris not ready")
self.conn_timer.start()
def connectToBroker(self):
try:
"""连接到 MQTT 代理"""
print("connect to broker local ")
self.local_client.connect(host=LOCALBORKER,port=LOCALPORT) # 连接本地 MQTT 服务器
time.sleep(0.5)
# print("connect to broker remote")
# self.remote_client.connect(host=BORKER,port=PORT) # 连接远程 MQTT 服务器
time.sleep(0.5)
print("connect to broker local dev")
self.device_client.connect(host=DEVICEBORKER,port=DEVICEPORT) # 连接设备 MQTT 服务器
time.sleep(0.5)
self.local_client.loop_start() # 开始循环以处理网络流量
# self.remote_client.loop_start() # 开始循环以处理网络流量
self.device_client.loop_start() # 开始循环以处理网络流量
except Exception as e:
print(e)
return
def on_connect(self, client, userdata, flags, rc):
"""连接成功时调用"""
print(f"client {client._client_id} connected to {client.host}")
command_topic = TOPICFIRST + self.device_id + TOPICCTRL
request_topic = TOPICFIRST + self.device_id + TOPICREQUEST
client.subscribe(command_topic) # 订阅命令主题
client.subscribe(request_topic) # 订阅命令主题
def on_disconnect(self, client, userdata, rc):
print(f"client {client._client_id} disconnect from {client.host}")
def on_dev_connect(self, client, userdata, flags, rc):
"""连接成功时调用"""
print(f"client {client._client_id} connected to {client.host}")
client.subscribe("device/status")
client.subscribe("service/status")
# self.write_alu_data("set_status", True)
def on_message(self, client, userdata, msg):
"""处理接收到的消息"""
# print(f"Message received on topic: {msg.topic} Message: {msg.payload.decode()}")
# 解析 JSON
try:
json_obj = json.loads(msg.payload.decode())
self.handle_message(json_obj)
except json.JSONDecodeError:
print("Failed to decode JSON")
def on_dev_message(self, client, userdata, msg):
"""处理接收到的消息"""
# print(f"Message received on topic: {msg.topic} Message: {msg.payload.decode()}")
# 解析 JSON
try:
json_obj = json.loads(msg.payload.decode())
if msg.topic == "device/status":
self.handle_dev_message(json_obj)
except json.JSONDecodeError:
print("Failed to decode JSON")
def handle_dev_status(self, code, status):
if code == "1#MTO":
self.update_motor_info.emit(1, status)
# if 'direction' in status:
# self.update_direction.emit(1, status['direction'])
if code == "2#MTO":
self.update_motor_info.emit(2, status)
# if 'direction' in status:
# self.update_direction.emit(2, status['direction'])
if code == "3#MTO":
self.update_motor_globaldev_info.emit(status)
if code == "1#ALU":
pass
# self.update_alu_info.emit(1, status)
if code == "1#WSU":
self.update_wsu_info.emit(1, status)
if code == "2#WSU":
self.update_wsu_info.emit(2, status)
if code == "1#OSU":
self.update_osu_info.emit(1, status)
if code == "2#OSU":
self.update_osu_info.emit(2, status)
if code == "1#HVS":
self.update_hsv_info.emit(1, status)
if code == "2#HVS":
self.update_hsv_info.emit(2, status)
def handle_dev_message(self, json_obj):
"""处理接收到的 JSON 消息"""
if isinstance(json_obj, dict):
code = json_obj.get("device_code", None)
status = json_obj.get("status", None)
if code and status:
self.handle_dev_status(code, status)
elif isinstance(json_obj, list):
for item in json_obj:
code = item.get("device_code", None)
status = item.get("status", None)
if code and status:
self.handle_dev_status(code, status)
def handle_message(self, json_obj):
"""处理接收到的 JSON 消息"""
print("----------------handle_message:",json_obj)
method = json_obj.get("method")
if method == "noop":
if json_obj.get("type") == "remote":
self.m_clienttimestamp = time.time()
elif method == "follow":
if json_obj.get("value") == "true":
cid = json_obj.get("cid")
print("Follow,",cid)
self.send_current_product(productManager.cur_product_id)
elif method == "input":
key = json_obj.get("key")
value = json_obj.get("value")
"""写入数据"""
self.write_data.emit(key, value)
elif method == "devinput":
dev = json_obj.get("dev")
dev_index = json_obj.get("dev_index")
scanner = json_obj.get("scanner")
if scanner == "scanner1":
dev_index = 1
elif scanner == "scanner2":
dev_index = 2
key = json_obj.get("key")
value = json_obj.get("value")
"""写入数据"""
if dev == "voltage":
print("voltage:",key,value)
self.write_voltage_data(dev_index, key, value)
elif dev == "xray" or dev == "power":
print("xray:",key,value)
self.write_voltage_data(dev_index, key, value)
elif dev == "motor":
self.write_motor_data(dev_index, key, value)
elif dev == "device":
self.write_global_dev_data(key, value)
elif method == "mode":
mode_value = json_obj.get("value")
if mode_value == 1:
self.start_ys(False)
elif mode_value == 2:
self.start_ys(True)
elif method == "loadProduct":
self.send_products()
elif method == "insertProduct":
info = json_obj.get("info")
productManager.create(info)
print(f"Inserting Info: {info}")
self.send_products()
elif method == "updateProduct":
id = json_obj.get("id")
info = json_obj.get("info")
productManager.update(id, info)
self.send_products()
elif method == "removeProduct":
id = json_obj.get("id")
productManager.delete(id)
self.send_products()
elif method == "currentProduct":
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")
date = json_obj.get("date")
hour = json_obj.get("hour")
print(f"loadHistoryList: {cid}, {date}, {hour}")
self.send_history_list(cid, date, hour)
elif method == "loadHistory":
cid = json_obj.get("cid")
filename = json_obj.get("file_name")
print(f"loadHistory: {cid}, {filename}")
self.send_history(cid, filename)
elif method == "trend":
cid = json_obj.get("cid")
duration = json_obj.get("duration")
filters = json_obj.get("filters")
# self.send_trend(cid, duration, filters)
elif method == "temperature":
cid = json_obj.get("cid")
duration = json_obj.get("duration")
self.get_temperature.emit(cid, duration)
elif method == "calc_init":
self.calc_init.emit()
elif method == "scan_control":
action = json_obj.get("action")
if action == "start":
self.start_device()
elif action == "stop":
self.pause_device()
def write_global_dev_data(self, key, value):
if key == "sports_mode":
self.sportIndex = (self.sportIndex + 1) % len(self.sportModes)
value = self.sportModes[self.sportIndex]
print("sports_mode:",value)
data = {
"device_id": 101,
"device_address": 3,
"device_code": "3#MTO",
"command": key,
"value": value
}
self.publish_device(DEVICE_CONTROL_TOPIC, data, 1)
def write_voltage_data(self, voltage_index, key, value):
print("value:", value)
value = True if value ==1 else False
data = {
"device_id": voltage_index,
"device_code": f"{voltage_index}#HVS",
"command": "hv_switch",
"value": value
}
print("write_voltage_data:",data)
self.publish_device("device/hvs/control", data, 1)
# self.write_alu_data("set_status", value)
def write_alu_data(self, key, value):
data = {
"device_id": '1',
"device_code": "1#ALU",
"command": key, # set_status
"value": value
}
print("write_voltage_data:",data)
self.publish_device("device/control", data, 1)
def write_motor_data(self, motor_index, key, value):
data = {
"device_address": motor_index,
"device_code": f"{motor_index}#MTO",
"command": key,
"value": value
}
print("write_motor_data:",data)
self.publish_device(DEVICE_CONTROL_TOPIC, data, 1)
@Slot()
def start_device(self):
self.write_motor_data(1, "switch", 1)
self.write_motor_data(2, "switch", 1)
self.write_voltage_data(1, "switch", 1)
time.sleep(0.1)
self.write_voltage_data(2, "switch", 1)
@Slot()
def pause_device(self):
self.write_motor_data(3, "switch", 0)
self.write_voltage_data(1, "switch", 0)
time.sleep(0.1)
self.write_voltage_data(2, "switch", 0)
@Slot()
def stop_device(self):
self.write_motor_data(1, "emergency_stop", 0)
self.write_motor_data(2, "emergency_stop", 0)
self.write_voltage_data(1, "switch", 0)
time.sleep(0.1)
self.write_voltage_data(2, "switch", 0)
def arr2Base64(self, arr):
obj = json.dumps(arr)
return base64.b64encode(obj.encode('utf-8')).decode('utf-8')
def send_temperature_data(self, cid, temp_data):
"""发送温度数据"""
temp_data["method"] = "temperature"
temp_data["datetime"] = self.arr2Base64(temp_data["datetime"])
temp_data["SCANNER1"] = self.arr2Base64(temp_data["SCANNER1"])
temp_data["SCANNER2"] = self.arr2Base64(temp_data["SCANNER2"])
self.publish_rev_cpy(cid, temp_data)
def safe_mean(self, lst):
non_zero = [x for x in lst if x != 0]
return sum(non_zero) / len(non_zero) if non_zero else 0
def send_trend(self, cid, duration, filters):
print("===filters",filters)
"""发送趋势数据"""
duration = 5000
obj = historyManager.getTrend(duration)
keys_to_extract = [
"WtOSC", "WtINS", "WtISC", "EccentricityINS",
"EccentricityOSC", "EccentricityISC", "DmALL", "DmCORE"
]
extracted_data = {key: [] for key in keys_to_extract}
datetime_list = []
for item in obj:
dt = item['datetime']
datetime_list.append(dt.strftime("%Y-%m-%d %H:%M:%S"))
info_dict = json.loads(item['info'])
for key in keys_to_extract:
value = info_dict[key]
if isinstance(value, list):
extracted_data[key].append(self.safe_mean(value))
else:
extracted_data[key].append(value)
data = dict()
data["method"] = "trend"
data["datetime"] = self.arr2Base64(datetime_list)
for key in keys_to_extract:
data[key] = self.arr2Base64(extracted_data[key])
self.publish_rev_cpy(cid, data)
def send_history_list(self, cid, date, hour):
"""发送历史记录列表"""
data = historyManager.getDateTimes(date, hour)
obj = dict()
obj["method"] = "loadHistoryList"
obj["filenames"] = data
self.publish_rev_cpy(cid, obj)
def send_history(self, cid, data_time_str):
data = historyManager.getInfoByDatetime(data_time_str)
print("====================",data)
"""发送历史记录"""
obj = dict()
obj["method"] = "loadHistory"
obj["info"] = data["info"]
self.publish_rev_cpy(cid, obj)
# obj["info"] = {
# "WtOSC": [0.93, 0.86, 0.84, 0.81, 0.88, 0.92, 0.87, 0.79],
# "WtISC": [0.82, 0.76, 1.03, 0.96, 1.05, 0.84, 0.77, 0.89],
# "WtINS": [6.96, 6.57, 11.33, 13.54, 11.27, 6.47, 5.88, 7.62],
# "WtALL": [8.50, 8.20, 13.20, 15.32, 13.21, 8.22, 7.52, 9.30],
# "AngOSC": [304.75, 225.00, 21.88],
# "AngINS": [205.50, 135.00, 274.23],
# "AngISC": [248.50, 78.75, 301.21],
# "AngALL": [248.50, 135.00, 286.10],
# "DmCORE": [18.69, 14.54, 18.85],
# "DmALL": [38.21, 40.16, 36.27],
# "DmCOREDeviation": 2,
# "DmALLDeviation": 3,
# "AvgINS": 8.82,
# "AvgOSC": 0.95,
# "AvgISC": 0.88,
# "AvgALL": 9.63,
# "MinISC": 0.96,
# "MinOSC": 0.82,
# "MinINS": 5.89,
# "MinALL": 7.51,
# "EccentricINS": 0.96,
# "EccentricOSC": 2.04,
# "EccentricISC": 3.22,
# "EccentricALL": 8.82,
# "EccentricityINS": 16.043,
# "EccentricityOSC": 21.136,
# "EccentricityISC": 43.253,
# "EccentricityALL": 43.223,
# "ConcentricityALL" : 21.15,
# "ConcentricityINS" : 21.35,
# "ConcentricityOSC" : 11.43,
# "ConcentricityISC" : 6.51,
# "ConcentricityDeviationALL": 21.26,
# "ConcentricityDeviationINS": 21.26,
# "ConcentricityDeviationOSC": 11.65,
# "ConcentricityDeviationISC": 6.55,
# "EllipticityDmCORE": 6.53,
# "EllipticityDmALL": 9.61,
# "Volatility": [0.291, 0.188, 0.414],
# "EdgesA": [42.53, 41.66, 52.93, 53.28, 72.88, 77.58, 88.97, 81.19],
# "EdgesB": [38.36, 43.58, 51.69, 57.92, 71.64, 77.23, 85.77, 82.01]
# }
def publish_device(self, topic, data, qos=1):
json_data = json.dumps(data) # 将数据转换为 JSON 字符串
self.device_client.publish(topic, json_data, qos) # 发布数据到本地
def publish_cpy_server(self, topicname, data, qos=0):
self.publish_local(topicname, data, qos) # 发布数据到本地
# if self.client_alive(): # 检查客户端是否存活
# self.publish_remote(topicname, data, qos) # 如果存活,发布数据到远程
def publish_cpy(self, topicname, data, qos=0):
topicname = TOPICFIRST + self.device_id + topicname # 构建完整的主题名称
self.publish_local(topicname, data, qos) # 发布数据到本地
# if self.client_alive(): # 检查客户端是否存活
# self.publish_remote(topicname, data, qos) # 如果存活,发布数据到远程
def publish_rev_cpy(self, cid, data, qos = 1):
topicname = TOPICFIRST + cid + TOPICRECEIVE # 构建完整的主题名称
# print("topicname:",topicname)
self.publish_local(topicname, data, qos) # 发布数据到本地
# if self.client_alive(): # 检查客户端是否存活
# self.publish_remote(topicname, data, qos) # 如果存活,发布数据到远程
# print("json_data:",data)
def publish_local(self, topic, data, qos = 0):
json_data = json.dumps(data) # 将数据转换为 JSON 字符串
self.local_client.publish(topic, json_data, qos) # 发布数据到本地
# print(f"Published to local: {topic} -> {json_data}")
def publish_remote(self, topic, data, qos = 0):
pass
# json_data = json.dumps(data) # 将数据转换为 JSON 字符串
# self.remote_client.publish(topic, json_data, qos) # 发布数据到远程
def send_collect_data(self, data):
self.publish_cpy(TOPICCOLLECT, data, 1) # 发布
def send_kneed(self, data):
# print("TOPICCAL:",data)
self.publish_cpy(TOPICCAL, data, 1) # 发布计算结果
def send_deviceinfo(self, data):
self.publish_cpy(TOPICINFOS, data) # 发布设备信息
def client_alive(self):
# 当前时间
current_time = time.time() # 获取当前时间戳(秒)
# 计算时间差(秒)
seconds_diff = current_time - self.m_clienttimestamp
# 判断时间差是否小于 1 分钟(60 秒)
return seconds_diff <= 60
def send_products(self):
"""发送产品信息"""
data = dict()
data["current_id"] = productManager.cur_product_id
data["method"] = "productList"
data["infos"] = productManager.getInfo()
print(f"Current product id: {productManager.cur_product_id}")
self.publish_cpy(TOPICPRODUCT, data, 1) # 发布设备信息
def start_ys(self, flag):
"""启动或停止某个功能"""
print(f"Starting YS: {flag}")
def send_current_product(self, id):
"""发送当前产品信息"""
data = productManager.getInfo(id)
if data:
data["method"] = "currentProduct"
self.publish_cpy(TOPICPRODUCT, data, 1) # 发布设备信息
def send_current_product_id(self, id):
"""发送当前产品ID"""
data = {"method": "currentProductId", "id": id}
self.publish_cpy(TOPICPRODUCT, data, 1) # 发布设备信息
def disconnect_broker(self):
print("disconnect_broker")
self.local_client.disconnect()
self.local_client.loop_stop()
self.remote_client.disconnect()
self.remote_client.loop_stop()
self.device_client.disconnect()
self.device_client.loop_stop()
def send_noop(self):
"""发送空指令"""
data = {
"running": "true",
"running_time": "1h15m" }
self.publish_cpy(TOPICNOOP, data, 1) # 发布设备信息