Wi-Fi with LTE Fallback Not Working



  • I am trying to write some code which will try to connect to a specified Wi-Fi network, but will fallback to LTE-M1 if the Wi-Fi network is or becomes unavailable and then keep reattempting to connect to the Wi-Fi network. I am currently using my phone's hotspot so I can control the Wi-Fi signal.

    Here is the main loop:

    while True:
        if not wlan.isconnected():
            connection=connectWiFi()
            print(connection)
            if connection=="WiFi" and lte.isconnected():
                lte.disconnect()
        utime.sleep(1)
    

    Here is the connectWiFi() function:

    def connectWiFi():
        global wlan
        print("Scan Beginning")
        connection=wlan.scan(ssid=WIFI_SSID,channel=1)
        if connection:
            try:
                wlan.connect(WIFI_SSID,auth=(WLAN.WPA2,WIFI_PASSWORD),timeout=2000)
                while not wlan.isconnected():
                    machine.idle()
                pycom.rgbled(GREEN_LIGHT)
                return "WiFi"
            except Exception:
                return connectLTE()
        else:
            return connectLTE()
    

    Before the main loop, all I do is define global variables (including wlan and lte), call connectWifi() the first time, and then (assuming successful connection to Wi-Fi or LTE) connect to an MQTT client (but never reference it again). connectLTE() either returns "LTE," if the device connects or was already connected to LTE, or "Failure" otherwise.

    The following scenarios work as expected:

    • Connecting to either Wi-Fi or LTE upon startup, depending on whether the Wi-Fi is on or not.
    • If the Wi-Fi starts off, but is turned on later, it will switch from LTE (disconnecting) to Wi-Fi.

    The issue comes if the device was connected to Wi-Fi (either initially or after some time connected to LTE) and then I turn off the Hotspot. As expected, connectWiFi() is called again, but I get the following output:

    Scan Beginning
    Traceback (most recent call last):
      File "main.py", line 92, in <module>
      File "main.py", line 64, in connectWiFi
    OSError: Scan operation Failed!
    

    Why would the scan operation fail if it didn't in the other cases? I tried detaching and disconnecting from LTE prior to the scan, but that didn't change anything.


Log in to reply
 

Pycom on Twitter