Page 1 of 1

Try Multiple WIFI Connections

Posted: Tue Sep 08, 2020 8:33 pm
by Expert
I would like to keep trying a list of WIFI connections until the ESP32 connects to one. Here is what I have but I keep getting the no AP found error. If I just use one of them it connects fine. I know there is a better way. Any help is appreciated.

Code: Select all

import esp32
from machine import Pin, ADC, reset

SSID1 = "firstAP"
PASSWORD1 = "letmein"
SSID2 = "secondAp"
PASSWORD2 = "letmein"
SSID3 = "thirdAP"
PASSWORD3 = "letmein"
SSID4 = "fourthAP"
PASSWORD4 = "letmein"

def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)        
        sta_if.connect(SSID1, PASSWORD1)
        while not sta_if.isconnected():
            pass  
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)        
        sta_if.connect(SSID2, PASSWORD2)
        while not sta_if.isconnected():
            pass  
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)        
        sta_if.connect(SSID3, PASSWORD3)
        while not sta_if.isconnected():
            pass  
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)        
        sta_if.connect(SSID4, PASSWORD4)
        while not sta_if.isconnected():
            pass  
    print('network config:', sta_if.ifconfig())

do_connect()

Re: Try Multiple WIFI Connections

Posted: Tue Sep 08, 2020 9:13 pm
by dhylands
Just looking at the logic, if it doesn't connect to the first AP, then it's going to get stuck at the while pass loop at the end of connecting to the first AP. You probably need a timeout, and if it fails to connect after say 10 seconds (or whatever is appropriate) then continue on to try the next SSID/password.

Rather than duplicating the logic, I'd probably create an array of SSIDs and passwords and use a loop to iterate over the list of SSID and passwords.

Re: Try Multiple WIFI Connections

Posted: Tue Sep 08, 2020 11:05 pm
by Expert
I'll give it a try. Thanks.

Re: Try Multiple WIFI Connections

Posted: Fri Oct 16, 2020 7:07 am
by Divergentti
I have strugled with this too and tried to solve multiple WIFI AP problem with this type of boot.py https://github.com/divergentti/kotiauto ... in/boot.py

This works mostly OK, but sometimes ESP boots several times and during boot I see error "I (4408) wifi: STA_DISCONNECTED, reason:202 authentication failed". I have no idea why that happens, because credentials are the same all the time and authentication works anyways after reboot (which my script does if connection fails).

MODIFY: I figured this out. I had to check what was boot reason and if reason was 1, 2 or 4, then skip WiFi setups, because we are already connected.