MQTT-有没有办法检查客户端是否仍然连接 [英] MQTT - Is there a way to check if the client is still connected

查看:1730
本文介绍了MQTT-有没有办法检查客户端是否仍然连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检查客户端是否仍连接到MQTT代理?

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

类似

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

有一个实例,尽管我的Raspberry Pi仍在运行(从外观上看,代码仍在显示更新的结果),但它停止从客户端接收消息.

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.

推荐答案

您可以在on_connect中激活一个标志,而在on_disconnect中禁用它.通过这种方式,您可以知道客户端是否已连接.

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

这篇关于MQTT-有没有办法检查客户端是否仍然连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆