Handling WLAN and MQTT disconnects



  • Hello. Before I start coding it up I was wondering if anyone has a good base model for detecting WiFi and mqtt failures and reconnecting?

    Thanks
    Chris



  • @cmisztur To check if you are connected to wifi you can use the isconnected() as show below

    from network import WLAN
    import time
    
    
    class WifiMonitor:
    
        def __init__(self):
            self.conn_timeout = 20
            self.wlan = WLAN(mode=WLAN.STA)
    
        def _connect(self, ssid, pswd):
            if not self.wlan.isconnected():
                print("Connecting to Wifi SSID: {} PASS: {}".format(ssid, pswd))
                self.wlan.connect(ssid, auth=(WLAN.WPA2, pswd))
    
                count_10ms = 0
                while count_10ms <= self.conn_timeout * 100 and not self.wlan.isconnected():
                    count_10ms += 1
                    time.sleep(0.01)
    
            if self.wlan.isconnected():
                print("WiFi connected: {}".format(self.wlan.ifconfig()))
    
        def connect_loop(self, ssid, pswd):
            while True:
                try:
                    self._connect(ssid, pswd)
                except Exception as e:
                    print("WIFI connection error: {}".format(e))
                    pass
                time.sleep(10)
    
    WIFI_SSID = 'my ssid'
    WIFI_PASS = 'my pass'
    
    wifi = WifiMonitor()
    wifi.connect_loop(WIFI_SSID, WIFI_PASS)
    

    For MQTT you can send a ping to the MQTT server


Log in to reply
 

Pycom on Twitter