【问题标题】:MQTT paho not receiving messages when put into classMQTT paho 上课时收不到消息
【发布时间】:2020-09-04 21:08:21
【问题描述】:

我正在尝试在一个整洁的类中设置 paho MQTT 函数以用于项目。我写了一个看起来像这样的类:

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

【问题讨论】:

    标签: python networking mqtt paho


    【解决方案1】:

    你的 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
    

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多