adding a timeout to wifi connexion

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
LukeVideo
Posts: 22
Joined: Thu May 09, 2019 3:59 pm

adding a timeout to wifi connexion

Post by LukeVideo » Tue Jul 30, 2019 1:05 pm

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.

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: adding a timeout to wifi connexion

Post by jimmo » Tue Jul 30, 2019 2:39 pm

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.

LukeVideo
Posts: 22
Joined: Thu May 09, 2019 3:59 pm

Re: adding a timeout to wifi connexion

Post by LukeVideo » Tue Jul 30, 2019 2:43 pm

That look like the way it's behaving.
I'll try that, thank you.

LukeVideo
Posts: 22
Joined: Thu May 09, 2019 3:59 pm

Re: adding a timeout to wifi connexion

Post by LukeVideo » Tue Aug 06, 2019 7:46 am

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.

Post Reply