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.
JavaScript
x
11
11
1
import paho.mqtt.client as mqtt
2
3
Broker = "192.168.43.246"
4
5
def on_connect(client, userdata, flages, rc):
6
print("Connected with result code=",rc)
7
8
client = mqtt.Client(client_id="Client123", clean_session=False, userdata=None)
9
client.on_connect = on_connect
10
client.connect(Broker, 1883, 60)
11
Here i attached a snap of event log also.
Advertisement
Answer
@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
JavaScript
1
16
16
1
import paho.mqtt.client as mqtt
2
import time
3
4
Broker = "192.168.43.246"
5
6
def on_connect(client, userdata, flages, rc):
7
print("Connected with result code=",rc)
8
9
client = mqtt.Client(client_id="Client123", clean_session=False, userdata=None)
10
client.on_connect = on_connect
11
client.connect(Broker, 1883, 60)
12
client.loop_start() # starts network loop on separate thread
13
time.sleep(10) # optionally wait some time
14
client.disconnect() # disconnect gracefully
15
client.loop_stop() # stops network loop
16
If you want to stay connected forever (or until killed) then you have 2 options
JavaScript
1
4
1
2
client.connect(Broker, 1883, 60)
3
client.loop_forever()
4
This will start the network loop in the foreground (and as such block until killed).
Or
JavaScript
1
6
1
2
client.connect(Broker, 1883, 60)
3
while True:
4
client.loop() # runs one iteration of the network loop
5
# do something else
6
Or
JavaScript
1
6
1
2
client.connect(Broker, 1883, 60)
3
client.loop_start()
4
while True:
5
# do something else
6