Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paho(MQTT) client can't connect

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()
like image 853
Martin Ventura Avatar asked Dec 08 '22 22:12

Martin Ventura


1 Answers

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.

like image 109
debihiga Avatar answered Dec 10 '22 12:12

debihiga