WLAN not connecting on first attempt

The official PYBD running MicroPython, and its accessories.
Target audience: Users with a PYBD
kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

WLAN not connecting on first attempt

Post by kevinkk525 » Mon May 03, 2021 10:14 am

I noticed a strange behaviour on the pyboard-D. My WLAN just won't connect on the first attempt. I have to manually call sta.disconnect() or just abort and connect(x,y) again and try again before it works:

Code: Select all

>>> import network
>>> ap=network.WLAN(network.AP_IF)
>>> ap.active(False)
>>> st=network.WLAN(network.STA_IF)
>>> st.active(True)
>>> st.isconnected()
False
>>> st.connect("red","red")
>>> import time
>>> while not st.isconnected():
...     print(".",end="")
...     time.sleep(1)
...
...
...
.................................................................................Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyboardInterrupt:
>>> st.disconnect() # not needed, just connecting again would work.
>>> st.connect("red","red")
>>> while not st.isconnected():
...     print(".",end="")
...     time.sleep(1)
...
...
...
>>> st.isconnected()
True
when using mqtt_as this also makes the first connection attempt fail and only succeeds on a consecutive connection attempt.
Calling connect(), waiting 5 seconds, then disconnecting() and/or connect() again also seems to work.
Last edited by kevinkk525 on Mon May 03, 2021 1:47 pm, edited 1 time in total.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

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

Re: WLAN not connecting on first attempt

Post by davef » Mon May 03, 2021 10:29 am

On the ESP32 and ESP8266 this is my connect():

Code: Select all

def connect():

 #  connect to the internet
    sta_if = network.WLAN(network.STA_IF)
    count = 0

    if not sta_if.isconnected():
        print('connecting to hotspot...')
        sta_if.active(True)
        sta_if.ifconfig(('192.168.10.99', '255.255.255.0', '192.168.10.1', '8.8.8.8'))
        sta_if.connect('HUAWEI-E8231-c4fd', 'my_password')

        while (count < 5):
            count += 1

            status = sta_if.status()

            try:
                with open('errors.txt', 'a') as outfile:
                    outfile.write('connect status = ' + str(status) + '\n')
            except OSError:
                print('oops')

            if (sta_if.isconnected()):
                count = 0
                break

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

    if (count == 5):
        count = 0

        try:
            with open('errors.txt', 'a') as outfile:
                outfile.write('did NOT connect to internet' + '\n')
        except OSError:
            print('oops')

        machine.reset()


    print(' network config:', sta_if.ifconfig())
Often tries 5 times, machine.reset() and then usually on the 2nd try on the 2nd round it connects. I have spent many hours trying to connect reliably.

Maybe try it on the pyboard D
Good luck

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: WLAN not connecting on first attempt

Post by kevinkk525 » Mon May 03, 2021 10:34 am

I can connect reliably on the esp8266 and esp32 without doing machine resets and that's not quite a solution imho.

I'd like to solve the reason for this pyboard-D problem. Maybe the wifi chip isn't ready that quickly and the first connect() just gets ignored? Doing a short waiting time also doesn't solve it, maybe it needs some time? But even waiting 5 seconds with active interface doesn't solve the problem. The 2nd connection attempt always works immediately.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

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

Re: WLAN not connecting on first attempt

Post by davef » Mon May 03, 2021 10:37 am

Could you post your code? I am keen to do it in a better way.

Thanks

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: WLAN not connecting on first attempt

Post by kevinkk525 » Mon May 03, 2021 10:40 am

I just let mqtt_as handle the wifi connection and run that connect method in a loop so it tries again if the 1st attempt fails: https://github.com/peterhinch/micropyth ... as.py#L465
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

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

Re: WLAN not connecting on first attempt

Post by davef » Mon May 03, 2021 10:46 am

Thanks. I have read through that before and sometime when I need to make the jump into uasyncio I will try to put in the effort.

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

Re: WLAN not connecting on first attempt

Post by davef » Tue May 04, 2021 10:08 pm

I have read more carefully through https://github.com/peterhinch/micropyth ... as.py#L465 and have certainly gained an impression about how difficult this must have been. I see that some of my attempts are perhaps a crude way of getting some measure of reliable connections.

Comments like
BUSY_ERRORS = [EINPROGRESS, ETIMEDOUT, 118, 119] # Add in weird ESP32 errors
suggest that there are more things hidden that I have no appreciation of.

It makes me wonder how professionals can develop products using these parts. Are there some specific "connect to the internet" ESP32 application notes floating around somewhere?

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: WLAN not connecting on first attempt

Post by kevinkk525 » Wed May 05, 2021 5:09 am

davef wrote:
Tue May 04, 2021 10:08 pm
Are there some specific "connect to the internet" ESP32 application notes floating around somewhere?
Not that I'm aware of. Some platforms (especially those with RTOS) might just have a few more error messages.

Overall, handling reliable and resilient socket connections on a low level like with micropython is a lot more difficult than one would expect when coming from python, but just as difficult (or probably easier) than handling them with C++.

But for simply connecting to your wifi, you shouldn't need complicated code :D
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

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

Re: WLAN not connecting on first attempt

Post by davef » Wed May 05, 2021 6:34 am

But connecting reliably ... thanks for your comments anyhow.

Quinten
Posts: 1
Joined: Fri Jul 08, 2022 3:35 pm

Re: WLAN not connecting on first attempt

Post by Quinten » Fri Jul 08, 2022 3:46 pm

I was also having this issue and it seems that the .connect method is actually not blocking. So you have to wait after .connect until your connected.

This worked for me:

Code: Select all

import network
import time
wlan = network.WLAN(network.STA_IF) 

def do_connect(ssid: str, key: str):
    wlan.active(True) # activate the interface
    if not wlan.isconnected(): # check if the station is connected to an AP
        print('Connecting to network...') 
        wlan.connect(ssid, key) # connect to an AP
        while not wlan.isconnected(): # wait till we are really connected
            print('.', end='')
            time.sleep(0.1) #  you can also just put pass here
        print()
        print('Connected:', wlan.isconnected())
    else:
        print("Already connected!")
    # get the interface's IP/netmask/gw/DNS addresses
    print(network_info())
This works well for me. Also make sure to actually disconnect before trying to connect again.

Post Reply