Jason94
Jason94

Reputation: 13610

Can't connect to mqtt broker

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.

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.

Upvotes: 3

Views: 12737

Answers (2)

Mehdi
Mehdi

Reputation: 196

First you have to make sure that you can connect to the Raspberry Pi. You can try using libraries other than Paho or using one MQTT client: http://www.hivemq.com/blog/seven-best-mqtt-client-tools

The other thing you can try is setting both client and broker to use port 80 to see if they can communicate through that port.

Upvotes: 0

hardillb
hardillb

Reputation: 59628

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()

Upvotes: 5

Related Questions