MQTT - 有没有办法检查客户端是否仍然连接

时间:2016-03-18 19:49:33

标签: python mqtt

有没有办法检查客户端是否仍然连接到MQTT代理?

这样的东西
if client.isConnected(): # for example
    # if True then do stuff

编辑:有一个实例,我的Raspberry Pi停止从客户端接收,虽然它仍然(从它的外观,代码仍然显示更新的结果)运行。

这是代码,因为我可能做错了什么:

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

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

事情是我离开了,所以我甚至不确定它为什么停止了!只有当我重新启动我的经纪人时,它才会再次开始接收。

5 个答案:

答案 0 :(得分:5)

您可以在on_connect中激活一个标志,并在on_disconnect中将其停用。通过这种方式,您可以知道客户端是否已连接。

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

答案 1 :(得分:3)

我在doc中看不到一个,但有on_disconnect on_connect个回调可以用来设置你自己的状态变量

编辑:

您需要调用其中一个loop函数来为客户端周期处理网络操作:

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

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

答案 2 :(得分:0)

In python you can add members to any object. So like @hardib said, you can do something like this:

def on_connect(client, ...):
    client.is_connected = True

def on_disconnect(client, ...):
    client.is_connected = False

client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
...
client.connect()
if client.is_connected:
    do something

Didn't test this though. For unrelated reasons I only used mqtt clients with the client object defined as global, so I assigned the value there. This should work regardless.

答案 3 :(得分:0)

您可以使用 will 消息来执行此操作。

client=mqtt.Client()
client.will_set('will_message_topic',payload=time.time(),qos=2,retain=True)
client.connect(address,1883,60)
client.publish('will_message_topic',payload='I am alive',qos=2,retain=True)
client.loop_start()#this line is important
while 1:#faster than while True
    you loop

通过留下 will 消息,您可以使用另一个客户端来确定该客户端是否在线。

答案 4 :(得分:-2)

不确定是否还有人想要回答这个,我知道我做了,因此环顾四周,发现mqtt paho有这样的功能来检查客户端是否仍然连接到代理。

它是这样的:

MqttClient client = new MqttClient("tcp://broker.mqttdashboard.com:1883", //URI 
MqttClient.generateClientId(), //ClientId 
new MemoryPersistence()); //Persistence
client.connect();
client.isConnected();

干杯!