Python mqtt client which tries to connect to broker when no internet

痴心易碎 提交于 2021-02-08 09:34:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!