Search code examples
pythonmqttpaho

Receiving messages without subscribing in python Paho MQTT library


I am working on a project where I need two computers to communicate through MQTT. To test it I created this code. I ran this code on my laptop:

import paho.mqtt.client as mqtt
import time
def on_connect(client,userdata,flags,rc):
    if rc == 0:
        print("connected OK")
    else:
        print("bad connection Returned code=",rc)
    client.subscribe('test/message')
def on_subscribe():
    print('hello')
def on_message(client,userdata,msg):
    message=str(msg.payload.decode())
    print(message)
broker = "10.49.12.253"
client = mqtt.Client("Get")
client.on_subscribe = on_subscribe
client.on_connect = on_connect
client.on_message = on_message
print("Connecting to broker ",broker)
client.connect(broker)
client.loop_forever()

After publishing a message from a different computer I got this output:

Connecting to broker  10.49.12.253
connected OK
Hello, world

The computer I sent the message from is also the broker. I am confused because the on_subscribe function is never called and I do not understand why as I still receive messages. What is going on here?


Solution

  • The problem is that your on_subscribe() function is missing the required number of arguments. It should be:

    ...
    def on_subscribe(client, userdata, mid, granted_qos):
      print("hello")
    ...
    

    Paho triggers the callbacks in a try/except block and is swallowing the error message that would be throw by the incorrect signature.

    Docs: https://www.eclipse.org/paho/index.php?page=clients/python/docs/index.php#on-subscribe