Django Python MQTT订阅消息被执行了两次

dbf7pr2w  于 2023-02-11  发布在  Python
关注(0)|答案(1)|浏览(269)

我有我的Mosquitto MQTT代理,我创建了一个简单的Django应用程序,它订阅了主题$SYS/broker/uptime,如下所示

from django.apps import AppConfig
from threading import Thread
import paho.mqtt.client as mqtt

class MqttClient(Thread):
    def __init__(self, broker, port, timeout, topics):
        super(MqttClient, self).__init__()
        self.client = mqtt.Client()
        self.broker = broker
        self.port = port
        self.timeout = timeout
        self.topics = topics
        self.total_messages = 0

    #  run method override from Thread class

    def run(self):
        self.connect_to_broker()

    def connect_to_broker(self):
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.connect(self.broker, self.port, self.timeout)
        self.client.loop_forever()

    # The callback for when a PUBLISH message is received from the server.

    def on_message(self, client, userdata, msg):
        self.total_messages = self.total_messages + 1
        print(str(msg.payload) + "Total: {}".format(self.total_messages))

    # The callback for when the client receives a CONNACK response from the server.

    def on_connect(self, client, userdata, flags, rc):
        #  Subscribe to a list of topics using a lock to guarantee that a topic is only subscribed once
        for topic in self.topics:
            client.subscribe(topic)

class AppMqtteConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'app_mqtt'

    def ready(self):
        MqttClient("localhost", 1883, 60, ["$SYS/broker/uptime"]).start()

由于某种原因,on_message回调函数上的print语句被执行了两次,至少我在控制台上看到的是这样。

zf2sa74q

zf2sa74q1#

事实证明,在某些情况下,特别是在测试中,ready方法可能会被多次调用,正如Documentation中所建议的那样。
如本answer中所述,在使用ready方法之前,使用if os.environ.get('RUN_MAIN'):解决了该问题

相关问题