Can't connect to mqtt broker

10,196

You can force the paho client to use the 3.1 level of the protocol by adding an option to the mqtt.Client constuctor:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    client.publish("test_mqtt", "test")
    client.subscribe("test")

def on_disconnect(client, userdata, rc):
    print("Disconnect, reason: " + str(rc))
    print("Disconnect, reason: " + str(client))

client = mqtt.Client("testclient", protocol=mqtt.MQTTv31)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.connect("192.168.1.20", 1883, 60)
client.loop_forever()
Share:
10,196
Jason94
Author by

Jason94

Feed me technology!

Updated on June 09, 2022

Comments

  • Jason94
    Jason94 almost 2 years

    I installed MQTT broker Mosquitto on my pi and are having some problems getting it to work with boxes in my network. Locally, if I putty in to the RPi running the Mosquitto MQTT broker everything is OK. I can use the client commands (mosquitto_sub, mosquitto_pub) to subscribe and publish to topics, no problem. BUT, if I try to connect from another box, Win2k12 server with a python script it states it cant connect.

    • I've tried turning the firewall off in my router
    • I've tried turning the firewall off on my Win2k12 server
    • I've added TCP 1883 to allowed ports outbound from my Win2k12 server

    The Python script:

    import paho.mqtt.client as mqtt
    
    def on_connect(client, userdata, flags, rc):
        client.publish("test_mqtt", "test")
        client.subscribe("test")
    
    def on_disconnect(client, userdata, rc):
        print("Disconnect, reason: " + str(rc))
        print("Disconnect, reason: " + str(client))
    
    client = mqtt.Client("testclient")
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.connect("192.168.1.20", 1883, 60)
    client.loop_forever()
    

    The output here is

    Disconnect, reason: <paho.mqtt.client.Client object at 0x01F41EF0>
    Disconnect, reason: 1
    

    I've tried to have a look at the documentation but it only mentioned the flags, not defining what they are.

    The raspberry pi that is running Mosquitto is also running Node-red. It has no problem connecting to the MQTT broker (both of them are running on the same rpi)

    Has enyone set up MQTT on Raspberry Pi and got it to work with other devices? I want it to work with a NodeMCU thingy, but when I had problems I started working on a python script to further debug the problem.