gpt4 book ai didi

python - Django 在引发异常后停止接收/发送 MQTT 消息

转载 作者:行者123 更新时间:2023-12-02 05:46:34 27 4
gpt4 key购买 nike

我正在尝试在 Django 上实现 Paho MQTT,但 Django 在引发任何类型的异常后停止接收/发送 MQTT 消息。

我正在使用 Paho MQTT 客户端 1.3.0 以及 Django 1.10.8、Python 3.6.2

这是我的 MQTT 设置:

mqtt.py

from django.conf import settings

import paho.mqtt.client as mqtt

SUB_TOPICS = ("device/vlt", "device/auth", "device/cfg", "device/hlt", "device/etracker", "device/pi")
RECONNECT_DELAY_SECS = 2


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))

# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
for topic in SUB_TOPICS:
client.subscribe(topic, qos=0)


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))


def on_publish(mosq, obj, mid):
print("mid: " + str(mid))


def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))


def on_log(mosq, obj, level, string):
print(string)


def on_disconnect(client, userdata, rc):
client.loop_stop(force=False)
if rc != 0:
print("Unexpected disconnection: rc:" + str(rc))
else:
print("Disconnected: rc:" + str(rc))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish
client.on_subscribe = on_subscribe
client.on_disconnect = on_disconnect

client.username_pw_set(username, password)
client.connect(<settings>)

apps.py

class CoreConfig(AppConfig):
name = 'untitled.core'
verbose_name = "Core"

def ready(self):
from . import mqtt
mqtt.client.loop_start()

代码灵感:Paho MQTT client connection reliability (reconnect on disconnection)

最佳答案

我的团队碰巧也面临这个问题,我们通过创建一个继承自 mqtt.ClientCustomMqttClient 并覆盖 _handle_on_message(self,消息) 函数。

class CustomMqttClient(mqtt.Client):

def _handle_on_message(self, message):
try:
super(ChatqMqttClient, self)._handle_on_message(message)
except Exception as e:
error = {"exception": str(e.__class__.__name__), "message": str(e)}
self.publish("device/exception", json.dumps(error))

然后,我们不使用 mqtt.Client(),而是这样做:

client = CustomMqttClient()
client.on_connect = on_connect
client.on_message = on_message

这会捕获所有异常并将其实际发布到我们的主题device/exception。我们的其他服务实际上可以订阅它并从中获取一些有用的信息。

关于python - Django 在引发异常后停止接收/发送 MQTT 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48294599/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com