WiFi re-connect problem

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
davef
Posts: 813
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

WiFi re-connect problem

Post by davef » Thu Apr 21, 2022 3:55 am

Have been trying to get an application to continue running even when the WiFi
fails to connect. v1.18 Generic.
Error message is:

Code: Select all

OSError: WiFi internal error (something like this as I can't repeat it)
If I run the following connect() and the WiFi does not connect I make
sta_if.active(False), but this still seems to leave the WiFi in limbo ... sometimes.

Only a hard-reset allows me to run the application again.

Code: Select all

import network
import utime
import machine
import config

sta_if = network.WLAN(network.STA_IF) # create station interface
ap_if = network.WLAN(network.AP_IF) #  create access-point interface

def connect():
    count = 0

 #  disconnects AP if it is up
    ap_if.active(False) #  de-activate the AP interface

    utime.sleep(1)

    if not sta_if.isconnected():
        print('connecting to hotspot...')
        sta_if.active(True)
        sta_if.ifconfig((config.WiFi_device, '255.255.255.0', config.gateway, '8.8.8.8'))
        sta_if.connect(config.hotspot, config.password)

        while (count < 5):
            count += 1

            if (sta_if.isconnected()):
                count = 0
                print (' network config:', sta_if.ifconfig())
                break

            print ('.', end = '')
            utime.sleep(1)


    if (count == 5):
     #  disconnect or you get errors
        if (sta_if.isconnected()): #  maybe not necessary
            sta_if.disconnect()

        sta_if.active(False) #  this is necessary

    count = 0 #  reset count

    utime.sleep(1)
Is there something else I can do to make sure that the WiFi is ready to try and reconnect
say one minute later?
Last edited by davef on Thu Apr 21, 2022 10:24 am, edited 1 time in total.

tepalia02
Posts: 99
Joined: Mon Mar 21, 2022 5:13 am

Re: WiFi re-connect problem

Post by tepalia02 » Thu Apr 21, 2022 9:44 am

I can see

Code: Select all

mport network
Have you missed the 'i' when typing?

davef
Posts: 813
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: WiFi re-connect problem

Post by davef » Thu Apr 21, 2022 10:24 am

Copy/paste problem :)

My only half-baked theory is that machine.reset() does not do as good a job as a hard-reset, ie the EN button, for getting the WiFi to its initial or default state.

Shards
Posts: 39
Joined: Fri Jun 25, 2021 5:14 pm
Location: Milton Keynes, UK

Re: WiFi re-connect problem

Post by Shards » Thu Apr 21, 2022 11:09 am

If you want the program to continue to run you need to trap the 'Wifi Internal Error' with a try: except: block. you can then ignore the error and try connecting again. Certainly not best practice but I fairly consistently get the error, sometimes multiple times, and the code below gets it connected. Once connected it seems reasonably stable. This is my basic test code:

Code: Select all

import network
from net_config import SSID, PSWD
from time import sleep

net = network.WLAN(network.STA_IF)
net.active(True)

while True:
	try:
		net.connect(SSID,PSWD)
	except OSError as e:
		print(e)
	sleep(1)
	if net.isconnected():
		print('Connected') 
		break

marcidy
Posts: 133
Joined: Sat Dec 12, 2020 11:07 pm

Re: WiFi re-connect problem

Post by marcidy » Thu Apr 21, 2022 4:56 pm

I would explicitly call disconnect() before calling active(False). disconnect() resets some internal micropython state, and stops the interface from making connection attempts.

what you have will never run if the station never connects:

Code: Select all

        if (sta_if.isconnected()): #  maybe not necessary
            sta_if.disconnect()
so just get rid of the "if" statement. "isconnected()" doesn't cover "trying to connect but not yet connected".

davef
Posts: 813
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: WiFi re-connect problem

Post by davef » Thu Apr 21, 2022 8:04 pm

Thank you. I will modify it as you suggest. My real connect() method has some error logging in it so I will be able to see if it improves the situation.

davef
Posts: 813
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: WiFi re-connect problem

Post by davef » Sun Apr 24, 2022 8:53 pm

Think I finally nailed this problem.

Running this test.py:

Code: Select all

import network
from wifi_functions import connect
from wifi_functions import disconnect
import utime


sta_if = network.WLAN(network.STA_IF)   #  create station interface

while True:
    connect()
    utime.sleep(5)
    disconnect()
    print ('disconnected')
    utime.sleep(5)
and my wifi_functions.py

Code: Select all

import network
import utime
import machine
import config


sta_if = network.WLAN(network.STA_IF) # create station interface
ap_if = network.WLAN(network.AP_IF) #  create access-point interface


def connect():
    count = 0


 #  disconnects AP if it is up
    ap_if.active(False) #  de-activate the AP interface

    utime.sleep(1)

    if not sta_if.isconnected():
        print('connecting to hotspot...')
        sta_if.active(True)
        sta_if.ifconfig((config.WiFi_device, '255.255.255.0', config.gateway, '8.8.8.8'))
        sta_if.connect(config.hotspot, config.password)


        while (count < 5):
            count += 1

            if (sta_if.isconnected()):
                count = 0
                print (' network config:', sta_if.ifconfig())
                break

            print ('.', end = '')
            utime.sleep(1)


    if (count == 5):
        try:
            with open('errors.txt', 'a') as outfile:
                outfile.write('failed to connect' + '\n')
        except OSError:
            pass

     #  disconnect or you get errors
        disconnect()

    count = 0 #  reset count

    utime.sleep(1)


def disconnect():

 #  disconnects STA, even if it is not connected
    sta_if.disconnect()  #  This is line 59
    sta_if.active(False)

    utime.sleep(1)
I would get this error:

Code: Select all

MPY: soft reboot
connecting to hotspot...
.....Traceback (most recent call last):
  File "main.py", line 2, in <module>
  File "test.py", line 12, in <module>
  File "wifi_functions.py", line 59, in disconnect
OSError: Wifi Not Started
MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information.
I guess it is not a surprise that trying to disconnect when you are NOT connected
might be an issue. Re-reading Shards response I thought I would put line 59
in a try ... except block.

Code: Select all

def disconnect():
    try:
     #  disconnects STA, even if it is not connected
        sta_if.disconnect()
    except:
        pass
    sta_if.active(False)        
    utime.sleep(1)
Voila!! No more ... OSError: Wifi Not Started

When running test.py if you do a Ctrl C during the connection attempt, then another
CtrlD I get:

Code: Select all

MPY: soft reboot
connecting to hotspot...
E (63083) wifi:sta is connecting, return error
Traceback (most recent call last):
  File "main.py", line 2, in <module>
  File "test.py", line 10, in <module>
  File "wifi_functions.py", line 24, in connect
OSError: Wifi Internal Error
MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information
.
This suggests that:

Code: Select all

sta_if.connect(config.hotspot, config.password)
should be a try ... except block. But that was what Shards recommended in the first place!!

I hope this is another step towards getting reliable WiFi access.

Thanks to both of you for your suggestions.

Post Reply