mqttpahobroker

Mqtt Client disconnects immediately after connect


when I try to test to connect to my broker and publish it keeps connecting but then failing to stay connected an publish a test. does anyone see a problem in my code?

import paho.mqtt.client as mqtt
import time
broker = "*************"
port = ****

def on_log(client, userdata, level, buf):
    print(buf)

def on_connect(client,usedata,flags,rc):
    if rc == 0:
        client.connected_flag=True ##set flag
        print("client is connected")
        global connected
    else:
        print("connection failed")
        client.loop_stop()
def on_disconnect(client, userdata, rc):
    print("client disconnected ok")
def on_publish(client, userdata, mid):
    print("In on_pub callback mid= ", mid)

mqtt.Client.connected_flag=False #create flag in class
client = mqtt.Client("MyClient-01") #create new instance
client.on_log=on_log
client.on_connect=on_connect
client.on_disconnect=on_disconnect
client.on_publish=on_publish
client.connect(broker,port) #establish connection
client.loop_start()
while not client.connected_flag:
    print("in wait loop")
    time.sleep(1)
time.sleep(3)
print("publishing")
#client.loop()
ret=client.publish("house/bulb1","Test message 0",0)
time.sleep(3)
#client.loop()
ret=client.publish("house/bulb1","Test message 1",1)
time.sleep(3)
#client.loop()
ret=client.publish("house/bulb1","Test message 2",2)
time.sleep(3)
client.loop_stop()
client.disconnect()

and I get this log:

Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b'MyClient-01'
in wait loop
Received CONNACK (0, 5)
connection failed
client disconnected ok
in wait loop
in wait loop
in wait loop
in wait loop
in wait loop
in wait loop
in wait loop

It just stays in the loop to try and connect , broker is found with an ip and port should be the correct one.


Solution

  • The MQTT specification may be some of the clearest documentation I've ever had the pleasure to read, porbably because it is so simple. For version 3.1.1 and the CONNACK message you can find it here:

    http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033

    You configured the library to log and got this message printed:

    Received CONNACK (0, 5)
    

    CONNACK is your message type (response to your CONNECT message). 0 and 5 refer to the Conneck Acknowledge Flags and Connect Return code variables from the CONNACK variable header. 0 means that this is the beginning of a new session and 5 means that you are not authorized, as you figured out.