问题
I have somewhat unstable wifi network at home. I have pyhon code running on raspberry pi which tries to connect to "test.mosquitto.com" broker.
Below is the python code which I have written
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
It works fine for me. Please let me know is there another efficient way to do this.(I guess there should be another way). Thanks in advance.
来源:https://stackoverflow.com/questions/41378490/python-mqtt-client-which-tries-to-connect-to-broker-when-no-internet