Page 1 of 1

adding a timeout to wifi connexion

Posted: Tue Jul 30, 2019 1:05 pm
by LukeVideo
Hy, I'm using the sample from the documentation to connect my esp32 boards.

Code: Select all

def connect():
    import network
    from utils.conf import ip, subnet, gateway, dns, ssid, password


    station = network.WLAN(network.STA_IF)

    if station.isconnected() == True:
        print("Already connected")
        return

    station.active(True)
    station.ifconfig((ip,subnet,gateway,dns))
    station.connect(ssid, password)

    while station.isconnected() == False:
        pass


    print("Connection successful")
    print(station.ifconfig())

def disconnect():
    import network
    station = network.WLAN(network.STA_IF)
    station.disconnect()
    station.active(False)
i am trying to add a way to handle the absence of my AP ( a raspberry Pi that might be out of range or turned off) but this just loops forever:

Code: Select all

try:
    connect()
except:
    print("no connectWifi")
    disconnect()
and it spams the console with :

Code: Select all

no AP found
I (64636) wifi: STA_DISCONNECTED, reason:201
no AP found
I (66696) wifi: STA_DISCONNECTED, reason:201
Any idea how to handle this ? I need my program to run even if the connection is down.

Re: adding a timeout to wifi connexion

Posted: Tue Jul 30, 2019 2:39 pm
by jimmo
I haven't used ESP32, but my memory from ESP8266 is that connect() returns immediately then connects in the background (so you can poll with isconnected or status).

So if ESP32 is the same, then your code will be stuck in the `while station.isconnected()` loop. In which case use utime.ticks_ms() before the loop, then utime.ticks_diff() inside the loop to figure out how much time has passed and break out of the loop after enough time has elapsed.

Re: adding a timeout to wifi connexion

Posted: Tue Jul 30, 2019 2:43 pm
by LukeVideo
That look like the way it's behaving.
I'll try that, thank you.

Re: adding a timeout to wifi connexion

Posted: Tue Aug 06, 2019 7:46 am
by LukeVideo
i added this to the connection routine

Code: Select all

    while station.isconnected() == False:
        presentTime = time.ticks_ms()
        duration = presentTime - startTime
        if duration > 5000:
            break
        pass
Works like a charm.