Search code examples
pythonmqtt

MQTT Python-Client disconnect ungracefully


I wrote basic MQTT python-client. But it disconnect ungracefully without giving any error. When i look event log file i found it's connected and same time is disconnected ungracefully.

import paho.mqtt.client as mqtt

Broker = "192.168.43.246"

def on_connect(client, userdata, flages, rc):
        print("Connected with result code=",rc)

client = mqtt.Client(client_id="Client123", clean_session=False, userdata=None)
client.on_connect = on_connect
client.connect(Broker, 1883, 60)

Here i attached a snap of event log also.

event log


Solution

  • @MikeScotty's answer is not right. What's missing is starting the MQTT network loop. The loop needs to be started to handle sending keep alive packets, doing multi leg handshakes for QoS 1/2 messages and to handle incoming subscriptions.

    If you just want to stay connected or 10 seconds then something like this will work

    import paho.mqtt.client as mqtt
    import time
    
    Broker = "192.168.43.246"
    
    def on_connect(client, userdata, flages, rc):
            print("Connected with result code=",rc)
    
    client = mqtt.Client(client_id="Client123", clean_session=False, userdata=None)
    client.on_connect = on_connect
    client.connect(Broker, 1883, 60)
    client.loop_start() # starts network loop on separate thread
    time.sleep(10) # optionally wait some time
    client.disconnect() # disconnect gracefully
    client.loop_stop() # stops network loop
    

    If you want to stay connected forever (or until killed) then you have 2 options

    ...
    client.connect(Broker, 1883, 60)
    client.loop_forever()
    

    This will start the network loop in the foreground (and as such block until killed).

    Or

    ...
    client.connect(Broker, 1883, 60)
    while True:
      client.loop() # runs one iteration of the network loop
      # do something else
    

    Or

    ...
    client.connect(Broker, 1883, 60)
    client.loop_start()
    while True:
      # do something else