188 lines
7.2 KiB
Python
188 lines
7.2 KiB
Python
import socket
|
|
from threading import Timer
|
|
import paho.mqtt.client as mqtt
|
|
import json
|
|
import threading
|
|
import paho.mqtt.client as mqtt
|
|
from config import *
|
|
# 确保config.py中包含MQTT_USERNAME和MQTT_PASSWORD配置
|
|
from datetime import datetime
|
|
from device_status import device_status_manager
|
|
from service_status import service_status_manager
|
|
import time
|
|
from database import get_db
|
|
import models
|
|
from sqlalchemy.orm import joinedload
|
|
|
|
class MQTTClient:
|
|
def __init__(self):
|
|
self.client = mqtt.Client(client_id = 'backend_' + self.random_string(6)) # 创建本地客户端
|
|
self.client.on_connect = self.on_connect
|
|
self.client.on_message = self.on_message
|
|
self.client.on_disconnect = self.on_disconnect
|
|
self.connected = False
|
|
self.reconnect_delay = 1
|
|
self.max_reconnect_delay = 60
|
|
|
|
def random_string(self, length=6):
|
|
import random
|
|
import string
|
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
|
|
|
def is_connected(self):
|
|
return self.connected
|
|
|
|
def publish(self, topic, payload):
|
|
try:
|
|
self.client.publish(topic, payload)
|
|
except Exception as e:
|
|
print(f"发送 MQTT 消息失败: {e}")
|
|
self.schedule_reconnect()
|
|
|
|
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():
|
|
print("local mqtt broker is ready")
|
|
self.__connect()
|
|
else:
|
|
print("local mqtt brokeris not ready")
|
|
|
|
Timer(1, self.connTimerHandler).start()
|
|
|
|
def connect(self):
|
|
Timer(1, self.connTimerHandler).start()
|
|
|
|
def __connect(self):
|
|
try:
|
|
self.client.username_pw_set(username=USER,password=PWD)
|
|
self.client.connect(BROKER, PORT, 60)
|
|
self.client.loop_start()
|
|
print("MQTT 客户端已启动")
|
|
|
|
except Exception as e:
|
|
print(f"MQTT 连接失败: {e}")
|
|
self.schedule_reconnect()
|
|
|
|
def disconnect(self):
|
|
self.client.loop_stop()
|
|
self.client.disconnect()
|
|
self.connected = False
|
|
print("MQTT 客户端已停止")
|
|
|
|
def on_connect(self, client, userdata, flags, rc):
|
|
if rc == 0:
|
|
self.connected = True
|
|
self.reconnect_delay = 1
|
|
print("MQTT 已连接")
|
|
self.client.subscribe("device/status")
|
|
self.client.subscribe("service/status")
|
|
self.client.subscribe("api/devices/#")
|
|
self.client.subscribe("api/interfaces")
|
|
else:
|
|
print(f"MQTT 连接失败,错误码: {rc}")
|
|
self.schedule_reconnect()
|
|
|
|
def on_disconnect(self, client, userdata, rc):
|
|
self.connected = False
|
|
print("MQTT 已断开连接")
|
|
self.schedule_reconnect()
|
|
|
|
def update_device_status(self, device_code, status):
|
|
device_status_manager.update_status(device_code, status)
|
|
|
|
def on_message(self, client, userdata, msg):
|
|
try:
|
|
topic = msg.topic
|
|
payload = json.loads(msg.payload.decode())
|
|
if topic.startswith("api/devices"):
|
|
print(f"接收到 MQTT 消息: {topic} - {payload}")
|
|
# 验证payload是否为字典类型
|
|
if not (isinstance(payload, dict) or isinstance(payload, list)):
|
|
print("payload", payload)
|
|
print(f"MQTT消息格式错误: 预期字典类型, 实际为{type(payload)}")
|
|
print(f"MQTT消息内容: {json.dumps(payload)}")
|
|
return
|
|
# print(f"接收到 MQTT 消息: {topic} - {payload}")
|
|
if topic == "device/status":
|
|
if isinstance(payload, list):
|
|
for item in payload:
|
|
device_code = item.get("device_code")
|
|
status = item.get("status", {})
|
|
if device_code is not None:
|
|
self.update_device_status(device_code, status)
|
|
else:
|
|
device_code = payload.get("device_code")
|
|
status = payload.get("status", {})
|
|
|
|
if device_code is not None:
|
|
self.update_device_status(device_code, status)
|
|
print(f"设备 {device_code} 状态已更新: {status}")
|
|
elif topic == "service/status":
|
|
service_name = payload.get("service_name")
|
|
status = payload.get("status", {})
|
|
|
|
if service_name is not None:
|
|
service_status_manager.update_status(service_name, status)
|
|
# print(f"服务 {service_name} 状态已更新: {status}")
|
|
elif topic == "api/interfaces":
|
|
print("接收到接口请求")
|
|
db = next(get_db())
|
|
interfaces = db.query(models.Interface).all()
|
|
print(f"查询到接口: {interfaces}")
|
|
self.publish("api/interfaces/response", json.dumps([interface.to_dict() for interface in interfaces]))
|
|
db.close()
|
|
except Exception as e:
|
|
print(f"处理 MQTT 消息时出错: {e}")
|
|
|
|
def schedule_reconnect(self):
|
|
if not self.connected:
|
|
print(f"尝试重新连接 MQTT,延迟: {self.reconnect_delay} 秒")
|
|
|
|
def attempt_reconnect():
|
|
self.client.loop_stop()
|
|
# 确保重连时重新设置用户名密码
|
|
self.client.username_pw_set(username=USER, password=PWD)
|
|
# 等待延迟时间后再重连
|
|
time.sleep(self.reconnect_delay)
|
|
try:
|
|
self.client.connect(BROKER, PORT, 60)
|
|
self.client.loop_start()
|
|
print("MQTT 重连已启动")
|
|
except Exception as e:
|
|
print(f"重连失败: {e}")
|
|
# 重连失败后,启动新的重连尝试
|
|
self.reconnect_delay = min(self.reconnect_delay * 2, self.max_reconnect_delay)
|
|
threading.Timer(self.reconnect_delay, attempt_reconnect).start()
|
|
|
|
# 在单独的线程中执行重连,避免阻塞主线程
|
|
threading.Thread(target=attempt_reconnect).start()
|
|
|
|
def ensure_connected(self):
|
|
"""确保 MQTT 客户端已连接"""
|
|
if not self.connected:
|
|
print("MQTT 未连接,尝试重新连接")
|
|
self.connect()
|
|
# 等待连接完成
|
|
time.sleep(1)
|
|
return self.connected
|
|
|
|
# 创建全局 MQTT 客户端实例
|
|
mqtt_client = MQTTClient() |