Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

python - MQTT - Is there a way to check if the client is still connected

Is there a way to check if the client is still connected to the MQTT broker?

Something like

if client.isConnected(): # for example
    # if True then do stuff

Edit: There was instance where my Raspberry Pi stopped receiving from the client although it was still (from the look of it, the code was still showing updated results) running.

Here is the code since I may be doing something wrong:

client = mqtt.Client()
client.connect(address, 1883, 60)

while True:
    data = getdata()
    client.publish("$ahmed/",data,0)
    time.sleep(0.2)

The thing is that I was away, so I am not even sure why it stopped! Only if I restart my broker then it will start receiving again.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can activate a flag in on_connect and deactivate it in on_disconnect. In this way you can know if the client is connected or not.

import paho.mqtt.client as mqtt

flag_connected = 0

def on_connect(client, userdata, flags, rc):
   global flag_connected
   flag_connected = 1

def on_disconnect(client, userdata, rc):
   global flag_connected
   flag_connected = 0

client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.connect(server,port)
client.loop_forever()
if flag_connected == 1:
   # Publish message
else:
   # Wait to reconnect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...