Initial commit: 上传完整代码
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
import paho.mqtt.client as mqtt
|
||||
import json
|
||||
from datetime import datetime
|
||||
import time
|
||||
import socket
|
||||
from threading import Timer
|
||||
from config import *
|
||||
from PySide6.QtCore import *
|
||||
from PySide6.QtCore import QTimer
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
#from PySide6.QtNetWork import *
|
||||
# 定义主题常量
|
||||
TOPICFIRST = "v1/cpy/"
|
||||
TOPICDEVICE = "/device"
|
||||
TOPICSTATUS = "/devstatus"
|
||||
TOPICCAL = "/calculation"
|
||||
TOPICCTRL = "/control"
|
||||
TOPICPRODUCT = "/product"
|
||||
TOPICCOLLECT = "/collect"
|
||||
startTime = time.time()
|
||||
|
||||
# 定义MQTT主题
|
||||
DEVICE_STATUS_TOPIC = "device/status"
|
||||
DEVICE_CONTROL_TOPIC = "device/control"
|
||||
SERVICE_STATUS_TOPIC = "service/status"
|
||||
DEVICE_API_TOPIC = "api/devices/response"
|
||||
|
||||
class MQTTClient(QObject):
|
||||
|
||||
write_motor_data = Signal(int, str, int)
|
||||
write_motor_globaldev_data = Signal(int, str, str)
|
||||
def __init__(self ):
|
||||
super().__init__()
|
||||
self.mqtt_client = mqtt.Client(client_id = 'scanner_service_' + self.random_string(6)) # 创建本地客户端
|
||||
self.mqtt_client.username_pw_set(USER, PWD)
|
||||
|
||||
# 设置回调函数
|
||||
self.mqtt_client.on_connect = self.on_connect
|
||||
self.mqtt_client.on_message = self.on_message
|
||||
self.mqtt_client.on_disconnect = self.on_disconnect
|
||||
self.is_connected = False
|
||||
self.conn_timer = QTimer(self)
|
||||
self.conn_timer.setInterval(1000)
|
||||
self.conn_timer.timeout.connect(self.connTimerHandler)
|
||||
self.conn_timer.start()
|
||||
|
||||
def random_string(self, length=6):
|
||||
"""生成随机字符串"""
|
||||
import random
|
||||
import string
|
||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||
|
||||
def checkLocalServer(self):
|
||||
host = '127.0.0.1'
|
||||
port = 1883
|
||||
timeout = 1
|
||||
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("mqtt connect timer")
|
||||
self.conn_timer.stop()
|
||||
if self.checkLocalServer():
|
||||
self.mqtt_client.connect(BROKER, PORT) # 连接本地 MQTT 服务器
|
||||
self.mqtt_client.loop_start() # 开始循环以处理网络流量
|
||||
else:
|
||||
print("local mqtt brokeris not ready")
|
||||
self.conn_timer.start()
|
||||
|
||||
def quit(self):
|
||||
self.mqtt_client.loop_stop() # 停止循环
|
||||
self.mqtt_client.disconnect()
|
||||
|
||||
def on_connect(self, client, userdata, flags, rc):
|
||||
"""连接成功时调用"""
|
||||
print(f"Connected to MQTT broker with result code {rc}")
|
||||
client.subscribe(DEVICE_CONTROL_TOPIC) # 订阅命令主题
|
||||
|
||||
self.is_connected = True
|
||||
|
||||
def on_disconnect(self, client, userdata, rc):
|
||||
self.is_connected = False
|
||||
print("MQTT 已断开连接")
|
||||
|
||||
|
||||
def on_message(self, client, userdata, msg):
|
||||
"""处理接收到的消息"""
|
||||
if not 'MTO' in msg.payload.decode():
|
||||
return
|
||||
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_CONTROL_TOPIC:
|
||||
self.handle_message(json_obj)
|
||||
except json.JSONDecodeError:
|
||||
print("Failed to decode JSON")
|
||||
|
||||
|
||||
def handle_message(self, json_obj):
|
||||
"""处理接收到的 JSON 消息"""
|
||||
motor_index = -1
|
||||
device_code = json_obj.get("device_code")
|
||||
device_id = json_obj.get("device_id")
|
||||
device_address = int(json_obj.get("device_address", 0))
|
||||
command = json_obj.get("command")
|
||||
if not 'MTO' in device_code:
|
||||
return
|
||||
print("device_code", device_code, "device_id", device_id, "device_address", device_address, "command", command)
|
||||
if device_code == "1#MTO" or device_code == "2#MTO" or device_code == "3#MTO":
|
||||
value = json_obj.get("value")
|
||||
if device_address == 1:
|
||||
print("motor",device_address, command, value)
|
||||
self.write_motor_data.emit(1, command, value)
|
||||
elif device_address == 2:
|
||||
print("motor",device_address, command, value)
|
||||
self.write_motor_data.emit(2, command, value)
|
||||
if device_address == 3:
|
||||
print("motor",device_address, command, value)
|
||||
self.write_motor_globaldev_data.emit(3, command, str(value))
|
||||
|
||||
def publish_msg(self, topic, msg):
|
||||
if isinstance(msg, dict):
|
||||
msg = json.dumps(msg)
|
||||
# print("publish_msg", topic, msg)
|
||||
self.mqtt_client.publish(topic, msg, qos=0)
|
||||
|
||||
def pusblish_service_status(self):
|
||||
global startTime
|
||||
runningTime = time.time() - startTime
|
||||
message = {
|
||||
"service_name" : "motor_service",
|
||||
"status": {
|
||||
"available": True,
|
||||
"running_time": runningTime
|
||||
}
|
||||
}
|
||||
self.publish_msg(SERVICE_STATUS_TOPIC, message)
|
||||
|
||||
def send_motor_status(self, motor_index, status):
|
||||
device_id = ""
|
||||
device_code = ""
|
||||
# print("send_motor_status", motor_index, status)
|
||||
|
||||
device_code = f"{motor_index}#MTO"
|
||||
self.publish_msg(DEVICE_STATUS_TOPIC, {
|
||||
"device_code": device_code, # 添加设备编码
|
||||
"status": status,
|
||||
"timestamp": datetime.now().isoformat()
|
||||
})
|
||||
|
||||
if hasattr(self, 'last_status_update'):
|
||||
if time.time() - self.last_status_update < 3.0:
|
||||
return
|
||||
self.last_status_update = time.time()
|
||||
self.pusblish_service_status()
|
||||
|
||||
def publish_cpy(self, topicname, data):
|
||||
topic = TOPICFIRST + self.device_id + topicname # 构建完整的主题名称
|
||||
json_data = json.dumps(data) # 将数据转换为 JSON 字符串
|
||||
self.mqtt_client.publish(topic, json_data) # 发布数据到本地
|
||||
|
||||
|
||||
Reference in New Issue
Block a user