我家里的网络有点不稳定。我在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
对我来说很好。 请让我知道是否有另一种有效的方法。(我想应该有另一种方式)。 提前谢谢。