MQTT paho 在放入 class 时未收到消息

MQTT paho not receiving messages when put into class

我正在尝试以简洁的方式设置 paho MQTT 功能 class 以用于项目。我写了一个 class 看起来像这样:

import paho.mqtt.client as mqtt
import time
import threading
class Messages(threading.Thread):
    def __init__(self,clientname,broker="10.49.12.253",topic = "test/message"):
        super().__init__()
        self.broker = broker
        self.topic = topic
        self.clientname = clientname
        self.client = mqtt.Client(self.clientname)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_subscibe = self.on_subscribe
        self.received = ''
    def on_connect(self,client,userdata,flags,rc):
        if rc == 0:
            print("Drone Connection Established")
        else:
            print("bad connection Returned code=",rc)
        self.client.subscribe(topic)
    def on_subscribe(self,client, userdata, mid, granted_qos):
        print("Subscription complete")
    def on_message(self,client,userdata,msg):
        print('got a message')
        self.received = str(msg.payload.decode())
        print(self.received)
    def begin(self):
        print('Setting up connection')
        self.client.connect(self.broker)
        self.client.loop_forever()
    def end(self):
        time.sleep(1)
        print('Ending Connection')
        self.client.loop_stop()
        self.client.disconnect()
    def send(self,msg,topic=None):
        if topic is None:
            topic = self.topic
        self.client.publish(topic,msg)

当我在另一台电脑上运行这段代码时:

import Messages
remote = Messages(clientname = 'Get',broker = "10.49.12.253", topic = "test/message")
remote.begin()

然后使用命令 mosquitto_pub -h 10.49.12.253 -t "test/message" -m "Hello, world"

从我的笔记本电脑发送消息

打印的输出很简单:

Setting up connection
Drone Connection Established

on_message 函数未被调用。这对我来说很奇怪,因为当我使用 class 之外的代码执行此操作时,它工作正常。发送功能也可以正常工作。我已经看了几天了,但看不出有什么问题。有人有想法吗?

您的 on_connect 方法看起来有问题;您正在调用 self.client.subscribe(topic) 但范围内没有名为 topic 的变量。也许你的意思是 self.topic?

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Drone Connection Established")
        else:
            print("bad connection Returned code=", rc)

        self.client.subscribe(self.topic)

有了这个改变,它似乎奏效了。当我向 test/message 主题发布消息时,您的代码输出如下:

Setting up connection
Drone Connection Established
got a message
this is a test