Python mqtt客户端,当没有互联网时试图连接到代理

时间:2016-12-29 11:08:50

标签: python python-2.7 python-3.x mqtt paho

我家里的网络有点不稳定。我在raspberry pi上运行了pyhon代码,试图连接到" test.mosquitto.com"代理。

下面是我编写的python代码

import time
import paho.mqtt.client as mqtt
bConnected = False

def on_disconnect(client, userdata, msg):
    print "Disonnected from broker"
    global bConnected
    bConnected = False

def on_connect(client, userdata, msg):
    print "Connected to broker"
    global bConnected
    bConnected = True

def worker_thread():
    """Creates mqtt client which check connection between pi and mqtt broker"""
    client = mqtt.Client()
    client.on_disconnect = on_disconnect
    client.on_connect = on_connect
    global bConnected
    while not bConnected:
        try:
            print "Trying to connect broker"
            client.connect("test.mosquitto.org", 1883, 5)
            client.loop_forever()
            time.sleep(5)

        except:
            bConnected = False

对我来说很好。 请让我知道是否有另一种有效的方法。(我想应该有另一种方式)。 提前谢谢。

0 个答案:

没有答案