I am trying to setup the paho MQTT functions in a neat class to use for a project. I wrote a class that looks like this:
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)
When I run this code on another computer:
import Messages
remote = Messages(clientname = 'Get',broker = "10.49.12.253", topic = "test/message")
remote.begin()
and then send a message from my laptop using the command mosquitto_pub -h 10.49.12.253 -t "test/message" -m "Hello, world"
The output that is printed is simply:
Setting up connection
Drone Connection Established
The on_message function is not called. It is strange to me because when I do this with code outside of a class it works fine. The send function also works fine. I have been looking at this for a few days now and I can't see what's wrong. Does anyone have an idea?
Your on_connect method looks broken; you're calling self.client.subscribe(topic) but there is no variable named topic in scope. Maybe you mean 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)
With this change, it seems to work. When I publish messages to the test/message
topic, the output from your code looks like:
Setting up connection
Drone Connection Established
got a message
this is a test