【发布时间】: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