4
votes

I'm using this python script to implement a basic Paho(MQTT) subscriber but under certain circumstances it doesn't invoke on_connect.

I tried the following, all with exactly the same code:

  • Running in a Raspbery pi, broker on desktop Pc (Ubuntu). Works.
  • Running in a Pc(Ubuntu), broker on the same Pc. Doesn't work.
  • Running in a Pc(Ubuntu), broker on other Pc(Ubuntu). Doesn't work.
  • Running in a Pc(Ubuntu), broker.hivemq.com as broker. Works.
  • Running in a Pc(Ubuntu), broker.hivemq.com (it's IP) as broker. Works.

I also usually do:

  • mosquitto_sub/pub in terminal in all previous combinations. Works.
  • Official C++ paho wrapper in all previous combinations. Works.

Also tried all setup methods listed in the official website. So python's paho library doesn't seem to be getting along with my local broker unless I run it from my raspberry. But using the same broker works well with c++'s paho library and if using MQTT from the terminal. Any ideas of what can be happening?

     import paho.mqtt.client as mqtt

     def on_connect(mqtt_client, obj, flags, rc):
         mqtt_client.subscribe("test")
         print "on_connect"

     def on_message(mqtt_client, obj, msg):
         print "on_message"

     mqtt_client = mqtt.Client()
     mqtt_client.on_connect = on_connect
     mqtt_client.on_message = on_message
     mqtt_client.connect("127.0.0.1",1883)
     mqtt_client.loop_forever()
1
Just checking, when you say exactly the same code, you are changing the ip address in the mqtt_client.connect function call as neededhardillb
Yes I'm changing it when neccesary. It shouldn't be that.Martin Ventura

1 Answers

14
votes

I had the same problem and changing the version of MQTT protocol in Client's constructor solved it.

mqtt_client = mqtt.Client("", True, None, mqtt.MQTTv31)

Since you do not specify the protocol, it uses the default one: MQTTv311.