config wifi channel in STA mode

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
MMliam
Posts: 121
Joined: Mon May 07, 2018 1:08 pm

config wifi channel in STA mode

Post by MMliam » Sat Jun 25, 2022 9:35 pm

I've been hoping to reduce wifi re-connection time after recovery from deep-sleep by configuration of the wifi channel prior to connection. Unfortunately, every microPython build seems to limit that function to AP mode; leaving STA mode to scan wifi channels to reconnect upon recovery from deep-sleep.

For my application deep-sleep is a necessity to preserve battery-life. Does anyone know of a microPython build that would permit configuration of the wifi channel in STA mode?

Mike

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

Re: config wifi channel in STA mode

Post by davef » Sat Jun 25, 2022 11:06 pm

Does a scan process occur before the connect if you do an ifconfig:

Code: Select all

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)
or is the issue that you don't know what the "config.WiFi_device" IP is?

Not a solution for your current setup, but would ESP-Now give a lower over-all current consumption?

MMliam
Posts: 121
Joined: Mon May 07, 2018 1:08 pm

Re: config wifi channel in STA mode

Post by MMliam » Sat Jun 25, 2022 11:44 pm

There can be no connection until the scan finds the channel the router is on, and no IP can be assigned until connected to the router and it's assigned via DHCP.

I always have the Router set to a fixed channel; I wanted the ESP module STA to simply set the same fixed channel, rather than wasting time trying to scan for it.

KJM
Posts: 158
Joined: Sun Nov 18, 2018 10:53 pm
Location: Sydney AU

Re: config wifi channel in STA mode

Post by KJM » Sun Jun 26, 2022 2:17 am

I assume you're running something like....

Code: Select all

if not sta.isconnected(): print('connecting to '+AP, end=' '); sta.connect(AP, pwd)
      for i in range(10):
        if sta.isconnected():
ESP32 generally get a connect within a couple of seconds from wakeup (with RSSIs around -80dbm, I haven't locked the router to a particular channel) & haven't bothered trying to improve it because opening a socket & connecting to my server takes at least twice as long and I have to do it twice (once for downloads then later for the uploads). Considering my Curtains PC takes 8-10s to find the router I figured it wasn't worth trying to chase it down any further.

I read somewhere recently that 8286 will auto reconnect to the router they were last on but I can't remember, for the moment, what forum I was on.

MMliam
Posts: 121
Joined: Mon May 07, 2018 1:08 pm

Re: config wifi channel in STA mode

Post by MMliam » Sun Jun 26, 2022 2:49 am

Hi KJM,

As they say, 'timing is every thing'. For my application more than one device will be reconnecting and the timing between those re-connections is important to determine a sequence, and order of events. As you can imagine, connection will also vary with signal strength, which can also be a function of distance. I have a work-around to normalize timing, but minimizing re-connection time improves overall system performance.

I have a work-around that appears to allow me to fix the STA mode channel, but I would prefer it if it were as simple as fixing a channel in AP mode. I've raised this issue months ago; I'm simply returning to it now to see if any progress has be made to incorporate the AP mode capability into the the STA mode.

I found this article on wifi autoconnect: https://randomnerdtutorials.com/wifiman ... -password/

Is this the article you recall?
A brief read of the WiFi-Manager doesn't appear to offer any advantage for re-connection to the last connected channel, but I need further investigation.

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

Re: config wifi channel in STA mode

Post by davef » Sun Jun 26, 2022 4:58 am

Before the code snippet I posted I have been doing:

Code: Select all

    if sta_if.isconnected():
        sta_if.disconnect()
        print ('started in the connected state')
        print ('but now it is disconnected')
    else:
        print ('started in the disconnected state')

    utime.sleep(1)
for the last 6 months and seem to get a connection much quicker, like 1-2 seconds. Without it I would often get 5 attempts, a machine.reset() (in my code) and then another few attempts.

Unlike the ESP8266 the ESP32 is not suppose to remember who he was connected to, but appears it sometimes doesn't remember that it was told to disconnect().

Care to share your work-around?

MMliam
Posts: 121
Joined: Mon May 07, 2018 1:08 pm

Re: config wifi channel in STA mode

Post by MMliam » Sun Jun 26, 2022 3:59 pm

davef,

If I understand your latest code snippet; you're saying that prior to a programmed connect attempt, but just after you create the sta_if object you test to determine whether the station object was already connected?

Also, if that actually occurred, did you ever get a your print message ('started in the connected state'), confirming that it was connected right after object creation?

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

Re: config wifi channel in STA mode

Post by davef » Sun Jun 26, 2022 7:22 pm

Yes, my guess was 10-20% of the attempts would print message ('started in the connected state'). Maybe, it depends on how long you wait between attempts or other factors that I am not aware of.

Over the last almost 2 years of working with the ESP32 I would say I have spent more time trying to ensure a reliable connection then any other problem. Maybe, it was my situation connecting to two Huwaei hotspots for sending daily logs.

My complete wifi-functions.py

Code: Select all

import network
import utime
import machine
import config


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


def connect():
    count = 0


    if sta_if.isconnected():
        sta_if.disconnect()
        print ('started in the connected state')
        print ('but now it is disconnected')
    else:
        print ('started in the disconnected state')

    utime.sleep(1) #  maybe try reducing this

    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'))

        try:
            sta_if.connect(config.hotspot, config.password)
        except OSError as error:
            try:
                with open('errors.txt', 'a') as outfile:
                    outfile.write(str(error) + '\n')
            except OSError:
                pass


        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 after 5 tries' + '\n')
        except OSError:
            pass

        disconnect() # or you could get errors

        machine.reset() #  start again
        
    try:
        rssi = sta_if.status('rssi')
        print ('RSSI = ' + str(rssi) + 'dBm')
    except:
        print ('signal level too low')

    count = 0 #  reset count

    utime.sleep(1)


def disconnect():

    try:
     #  disconnects STA, even if it is not connected
        sta_if.disconnect()
    except:
        pass

    sta_if.active(False)

    utime.sleep(1)

MMliam
Posts: 121
Joined: Mon May 07, 2018 1:08 pm

Re: config wifi channel in STA mode

Post by MMliam » Sun Jun 26, 2022 7:50 pm

That's really strange. I'm using ESP8286 modules, not the ESP32.

I may try that code snippet as a test, to see if I get a connected status after a Reset, then STA object creation.

The work around to fix the STA channel involves creating both STA & AP objects. Activate the AP object, set the channel, then activate the STA object, and deactivate the AP object. Because there is only one radio, that appears to fix the channel for the STA object. That seems to cut the connect time in half.

BTW: There apparently is an AutoConnect feature using the WiFi Manager. Here an example article for the ESP32: https://randomnerdtutorials.com/micropy ... 2-esp8266/

I don't understand how a connection after STA/AP Object creation can happen without specifying the appropriate credentials; but the WiFi Manager can store them for a reconnect. Perhaps that is what you've experienced; I have no experience to date with the WiFi Manager.
Last edited by MMliam on Sun Jun 26, 2022 11:11 pm, edited 1 time in total.

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

Re: config wifi channel in STA mode

Post by davef » Sun Jun 26, 2022 9:10 pm

As far as I am aware the ESP8266 does remember who he was last connected to last. Possibly one of the reasons I stopped playing with them about 1 year ago.

I had looked at that code and thought, perhaps incorrectly, that it was "way over the top" for my use case.

Thanks for posting your work-around, I will file that in my things-to-try folder.

Post Reply