MQTT Python-Client disconnect ungracefully

Question:

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

Asked By: prince

||

Answers:

@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
Answered By: hardillb
def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %dn", rc)
    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client
Answered By: G chaitu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.