import paho.mqtt.client as mqtt import json import socket import logging from datetime import datetime import time import socket from threading import Timer from config import * from typing import Dict, Any, List, Optional, Callable import requests logger = logging.getLogger(__name__) class MQTTClient(): def __init__(self, broker: str, port: int = 1883, client_id: str = None): self.client = mqtt.Client(client_id = 'hv_service_' + self.random_string(6)) # 创建本地客户端 self.client.username_pw_set(USER,PWD) self.broker = broker self.port = port self.callbacks: Dict[str, Callable] = {} self.received_messages = {} self.message_events = {} self.is_connected = False # 设置回调函数 self.client.on_connect = self._on_connect self.client.on_message = self._on_message self.client.on_disconnect = self._on_disconnect Timer(1, self.connTimerHandler).start() def random_string(self, length=6): """生成随机字符串""" import random import string return ''.join(random.choices(string.ascii_letters + string.digits, k=length)) def stop(self): """停止服务""" self.client.loop_stop() self.client.disconnect() def checkLocalServer(self): host = '127.0.0.1' port = 1883 timeout = 1 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) try: result = sock.connect_ex((host, port)) if result == 0: return True else: return False except Exception as e: print(e) return False finally: sock.close() def connTimerHandler(self): print("mqtt conn timer handler") if self.checkLocalServer(): self.client.connect(BROKER, MQTT_PORT) # 连接本地 MQTT 服务器 self.client.loop_start() # 开始循环以处理网络流量 else: print("local mqtt brokeris not ready") Timer(1, self.connTimerHandler).start() def connect(self): """连接到MQTT代理并处理连接错误""" try: self.client.connect(self.broker, self.port) self.client.loop_start() logger.info(f"成功连接到MQTT代理: {self.broker}:{self.port}") return True except socket.gaierror: logger.error(f"MQTT代理地址解析失败: {self.broker}") except ConnectionRefusedError: logger.error(f"MQTT代理拒绝连接: {self.broker}:{self.port}") except Exception as e: logger.error(f"MQTT连接失败: {str(e)}") return False def disconnect(self): """断开MQTT连接""" self.client.loop_stop() self.client.disconnect() def subscribe(self, topic: str, callback: Callable): """订阅主题并设置回调函数""" self.callbacks[topic] = callback def publish(self, topic: str, message: Dict[str, Any]): """发布消息到指定主题""" payload = json.dumps(message) self.client.publish(topic, payload) def control_xray_light(self, value): msg = { "device_code" : "1#ALU", "command" : "set_status", "status" : value } # print("publish", DEVICE_CONTROL_TOPIC, msg) self.publish(DEVICE_CONTROL_TOPIC, msg) # 发布数据到本地 def _on_connect(self, client, userdata, flags, rc): """连接回调""" print(f"已连接到MQTT代理: {self.broker}") for topic in self.callbacks: self.client.subscribe(topic) self.is_connected = True def _on_message(self, client, userdata, msg): """消息接收回调""" print("mqtt msg:", msg.topic, msg.payload) topic = msg.topic try: payload = json.loads(msg.payload.decode()) if topic in self.callbacks: self.callbacks[topic](topic, payload) # 存储接收到的消息 self.received_messages[topic] = msg # 触发等待事件 if topic in self.message_events: event = self.message_events.pop(topic) event.set() except json.JSONDecodeError: print(f"无法解析消息: {msg.payload}") def _on_disconnect(self, client, userdata, rc): """断开连接回调""" print(f"已断开与MQTT代理的连接: {self.broker}") self.is_connected= False def wait_for_message(self, topic: str, timeout: float = 5.0) -> Optional[mqtt.MQTTMessage]: """等待接收指定主题的消息 Args: topic: 要等待的主题 timeout: 超时时间(秒) Returns: 接收到的消息对象,如果超时则返回None """ import threading # 检查是否已经有缓存的消息 if topic in self.received_messages: return self.received_messages.pop(topic) # 创建事件对象 event = threading.Event() self.message_events[topic] = event # 等待事件触发或超时 event.wait(timeout) # 移除事件对象 if topic in self.message_events: self.message_events.pop(topic) # 返回接收到的消息 return self.received_messages.pop(topic, None) mqtt_client = MQTTClient(broker=BROKER, port=MQTT_PORT)