简体   繁体   中英

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.

  • 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM