MicroPython: Wi-Fi Manager with ESP32 (ESP8266 compatible)

In this tutorial we’ll show you how to use Wi-Fi Manager with the ESP32 using MicroPython firmware. Wi-Fi Manager allows you to connect your ESP32 to different Access Points (different networks) without having to hard-code your credentials and upload new code to your board.

MicroPython: Wi-Fi Manager with ESP32 ESP8266 compatible

This guide is also fully compatible with the ESP8266 board. However, since Wi-Fi manager library uses quite a lot of memory you may encounter a memory error while saving the script to your board. From our experience, restarting the board after uploading the script, removes the error and makes the project work after that. We recommend using the ESP32, but you can also continue this tutorial using an ESP8266 board.

How Wi-Fi Manager Works

With the Wi-Fi Manager you no longer have to hard-code your network credentials (SSID and password). The ESP32 will set up an Access Point that you can use to configure the network credentials, or it will automatically join to a known saved network.

Wi-Fi Client Setup WiFi Manager MicroPython

Here’s how the process works:

  • When the ESP32 boots for the first time, it’s set as an Access Point;
  • You can connect to that Access Point by establishing a connection with the WiFiManager network and going to the IP address 192.164.4.1;
  • A web page opens that allows you to choose and configure a network;
  • The ESP32 saves those network credentials so that later it can connect to that network (Station mode);
  • Once a new SSID and password is set, the ESP32 reboots, it is set to Station mode and tries to connect to the previously saved network;
  • If it establishes a connection, the process is completed successfully. Otherwise, it will be set up as an Access Point for you to configure new network credentials.

To set up the Wi-Fi Manager on the ESP32 using MicroPython, we’ll use the WiFiManager library by tayfunulu. In the library GitHub page, you can find the following diagram that shows an overview on how everything works.

Prerequisites

To follow this tutorial you need MicroPython firmware installed in your ESP board. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:

Parts Required

For this tutorial you need an ESP32 (or ESP8266 board):

Learn more about MicroPython: Grab our MicroPython Programming with ESP32 and ESP8266 eBook.

WiFiManager MicroPython Library

The library to set up Wi-Fi Manager on the ESP32 isn’t part of the standard MicroPython library by default. So, you need to upload the following library to your ESP board (save it with this exact name wifimgr.py).

import network
import socket
import ure
import time

ap_ssid = "WifiManager"
ap_password = "tayfunulu"
ap_authmode = 3  # WPA2

NETWORK_PROFILES = 'wifi.dat'

wlan_ap = network.WLAN(network.AP_IF)
wlan_sta = network.WLAN(network.STA_IF)

server_socket = None


def get_connection():
    """return a working WLAN(STA_IF) instance or None"""

    # First check if there already is any connection:
    if wlan_sta.isconnected():
        return wlan_sta

    connected = False
    try:
        # ESP connecting to WiFi takes time, wait a bit and try again:
        time.sleep(3)
        if wlan_sta.isconnected():
            return wlan_sta

        # Read known network profiles from file
        profiles = read_profiles()

        # Search WiFis in range
        wlan_sta.active(True)
        networks = wlan_sta.scan()

        AUTHMODE = {0: "open", 1: "WEP", 2: "WPA-PSK", 3: "WPA2-PSK", 4: "WPA/WPA2-PSK"}
        for ssid, bssid, channel, rssi, authmode, hidden in sorted(networks, key=lambda x: x[3], reverse=True):
            ssid = ssid.decode('utf-8')
            encrypted = authmode > 0
            print("ssid: %s chan: %d rssi: %d authmode: %s" % (ssid, channel, rssi, AUTHMODE.get(authmode, '?')))
            if encrypted:
                if ssid in profiles:
                    password = profiles[ssid]
                    connected = do_connect(ssid, password)
                else:
                    print("skipping unknown encrypted network")
            else:  # open
                connected = do_connect(ssid, None)
            if connected:
                break

    except OSError as e:
        print("exception", str(e))

    # start web server for connection manager:
    if not connected:
        connected = start()

    return wlan_sta if connected else None


def read_profiles():
    with open(NETWORK_PROFILES) as f:
        lines = f.readlines()
    profiles = {}
    for line in lines:
        ssid, password = line.strip("\n").split(";")
        profiles[ssid] = password
    return profiles


def write_profiles(profiles):
    lines = []
    for ssid, password in profiles.items():
        lines.append("%s;%s\n" % (ssid, password))
    with open(NETWORK_PROFILES, "w") as f:
        f.write(''.join(lines))


def do_connect(ssid, password):
    wlan_sta.active(True)
    if wlan_sta.isconnected():
        return None
    print('Trying to connect to %s...' % ssid)
    wlan_sta.connect(ssid, password)
    for retry in range(100):
        connected = wlan_sta.isconnected()
        if connected:
            break
        time.sleep(0.1)
        print('.', end='')
    if connected:
        print('\nConnected. Network config: ', wlan_sta.ifconfig())
    else:
        print('\nFailed. Not Connected to: ' + ssid)
    return connected


def send_header(client, status_code=200, content_length=None ):
    client.sendall("HTTP/1.0 {} OK\r\n".format(status_code))
    client.sendall("Content-Type: text/html\r\n")
    if content_length is not None:
      client.sendall("Content-Length: {}\r\n".format(content_length))
    client.sendall("\r\n")


def send_response(client, payload, status_code=200):
    content_length = len(payload)
    send_header(client, status_code, content_length)
    if content_length > 0:
        client.sendall(payload)
    client.close()


def handle_root(client):
    wlan_sta.active(True)
    ssids = sorted(ssid.decode('utf-8') for ssid, *_ in wlan_sta.scan())
    send_header(client)
    client.sendall("""\
        <html>
            <h1 style="color: #5e9ca0; text-align: center;">
                <span style="color: #ff0000;">
                    Wi-Fi Client Setup
                </span>
            </h1>
            <form action="configure" method="post">
                <table style="margin-left: auto; margin-right: auto;">
                    <tbody>
    """)
    while len(ssids):
        ssid = ssids.pop(0)
        client.sendall("""\
                        <tr>
                            <td colspan="2">
                                <input type="radio" name="ssid" value="{0}" />{0}
                            </td>
                        </tr>
        """.format(ssid))
    client.sendall("""\
                        <tr>
                            <td>Password:</td>
                            <td><input name="password" type="password" /></td>
                        </tr>
                    </tbody>
                </table>
                <p style="text-align: center;">
                    <input type="submit" value="Submit" />
                </p>
            </form>
            <p>&nbsp;</p>
            <hr />
            <h5>
                <span style="color: #ff0000;">
                    Your ssid and password information will be saved into the
                    "%(filename)s" file in your ESP module for future usage.
                    Be careful about security!
                </span>
            </h5>
            <hr />
            <h2 style="color: #2e6c80;">
                Some useful infos:
            </h2>
            <ul>
                <li>
                    Original code from <a href="https://github.com/cpopp/MicroPythonSamples"
                        target="_blank" rel="noopener">cpopp/MicroPythonSamples</a>.
                </li>
                <li>
                    This code available at <a href="https://github.com/tayfunulu/WiFiManager"
                        target="_blank" rel="noopener">tayfunulu/WiFiManager</a>.
                </li>
            </ul>
        </html>
    """ % dict(filename=NETWORK_PROFILES))
    client.close()


def handle_configure(client, request):
    match = ure.search("ssid=([^&]*)&password=(.*)", request)

    if match is None:
        send_response(client, "Parameters not found", status_code=400)
        return False
    # version 1.9 compatibility
    try:
        ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace("%21", "!")
        password = match.group(2).decode("utf-8").replace("%3F", "?").replace("%21", "!")
    except Exception:
        ssid = match.group(1).replace("%3F", "?").replace("%21", "!")
        password = match.group(2).replace("%3F", "?").replace("%21", "!")

    if len(ssid) == 0:
        send_response(client, "SSID must be provided", status_code=400)
        return False

    if do_connect(ssid, password):
        response = """\
            <html>
                <center>
                    <br><br>
                    <h1 style="color: #5e9ca0; text-align: center;">
                        <span style="color: #ff0000;">
                            ESP successfully connected to WiFi network %(ssid)s.
                        </span>
                    </h1>
                    <br><br>
                </center>
            </html>
        """ % dict(ssid=ssid)
        send_response(client, response)
        try:
            profiles = read_profiles()
        except OSError:
            profiles = {}
        profiles[ssid] = password
        write_profiles(profiles)

        time.sleep(5)

        return True
    else:
        response = """\
            <html>
                <center>
                    <h1 style="color: #5e9ca0; text-align: center;">
                        <span style="color: #ff0000;">
                            ESP could not connect to WiFi network %(ssid)s.
                        </span>
                    </h1>
                    <br><br>
                    <form>
                        <input type="button" value="Go back!" onclick="history.back()"></input>
                    </form>
                </center>
            </html>
        """ % dict(ssid=ssid)
        send_response(client, response)
        return False


def handle_not_found(client, url):
    send_response(client, "Path not found: {}".format(url), status_code=404)


def stop():
    global server_socket

    if server_socket:
        server_socket.close()
        server_socket = None


def start(port=80):
    global server_socket

    addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]

    stop()

    wlan_sta.active(True)
    wlan_ap.active(True)

    wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)

    server_socket = socket.socket()
    server_socket.bind(addr)
    server_socket.listen(1)

    print('Connect to WiFi ssid ' + ap_ssid + ', default password: ' + ap_password)
    print('and access the ESP via your favorite web browser at 192.168.4.1.')
    print('Listening on:', addr)

    while True:
        if wlan_sta.isconnected():
            return True

        client, addr = server_socket.accept()
        print('client connected from', addr)
        try:
            client.settimeout(5.0)

            request = b""
            try:
                while "\r\n\r\n" not in request:
                    request += client.recv(512)
            except OSError:
                pass

            print("Request is: {}".format(request))
            if "HTTP" not in request:  # skip invalid requests
                continue

            # version 1.9 compatibility
            try:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).decode("utf-8").rstrip("/")
            except Exception:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).rstrip("/")
            print("URL is {}".format(url))

            if url == "":
                handle_root(client)
            elif url == "configure":
                handle_configure(client, request)
            else:
                handle_not_found(client, url)

        finally:
            client.close()

View raw code

Follow the next set of instructions for the IDE you’re using:

  • A. Upload WiFiManager library with uPyCraft IDE
  • B. Upload WiFiManager library with Thonny IDE

A. Upload WiFiManager library with uPyCraft IDE

This section shows how to upload a library using uPyCraft IDE. If you’re using Thonny IDE, read the next section.

1. Create a new file by pressing the New File button.

2. Copy the WiFiManager library code into that file. The WiFiManager library code can be copied here.

3. After copying the code, save the file by pressing the Save button.

Uploading wifmgr Library using upycraft IDE MicroPython

4. Name this new file “wifimgr.py” and press ok.

Saving wifimgr.py library in upycraft IDE

5. Click the Download and Run button.

Install BME280 library MicroPython ESP32 ESP8266 uPyCraft IDE step 3

The file should be saved on the device folder with the name “wifimgr.py” as highlighted in the following figure.

wifimngr Library Successfully Uploaded to ESP32

Now, you can use the library functionalities in your code by importing the library.

B. Upload WiFiManager library with Thonny IDE

If you’re using Thonny IDE, follow the next steps:

1. Copy the library code to a new file. The WiFiManager library code can be copied here.

2. Save that file as wifimgr.py.

3. Go to Device Upload current script with the current name.

Uploading wifmgr Library using Thonny IDE MicroPython

And that’s it. The library was uploaded to your board. To make sure that it was uploaded successfully, in the Shell you can type:

%lsdevice

It should return the files currently saved on your board. One of them should be the wifimgr.py file.

wifimgr.py Library successfully saved on ESP32 MicroPython

After uploading the library to your board, you can use the library functionalities in your code by importing the library.

Code – Setting Up Wi-Fi Manager with the ESP32

The following code implementes Wi-Fi Manager on the ESP32. We’ll add Wi-Fi Manager capabilities to a previous MicroPython Web Server project. By the end of the tutorial, you should be able to implement Wi-Fi Manager in your won projects.

Create a main.py file and copy the following code.

# Complete project details at https://RandomNerdTutorials.com

import wifimgr
from time import sleep
import machine

try:
  import usocket as socket
except:
  import socket

led = machine.Pin(2, machine.Pin.OUT)

wlan = wifimgr.get_connection()
if wlan is None:
    print("Could not initialize the network connection.")
    while True:
        pass  # you shall not pass :D

# Main Code goes here, wlan is a working network.WLAN(STA_IF) instance.
print("ESP OK")

def web_page():
  if led.value() == 1:
    gpio_state="ON"
  else:
    gpio_state="OFF"
  
  html = """<html><head> <title>ESP Web Server</title> <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="data:,"> <style>html{font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;}
  h1{color: #0F3376; padding: 2vh;}p{font-size: 1.5rem;}.button{display: inline-block; background-color: #e7bd3b; border: none; 
  border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
  .button2{background-color: #4286f4;}</style></head><body> <h1>ESP Web Server</h1> 
  <p>GPIO state: <strong>""" + gpio_state + """</strong></p><p><a href="/?led=on"><button class="button">ON</button></a></p>
  <p><a href="/?led=off"><button class="button button2">OFF</button></a></p></body></html>"""
  return html
  
try:
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind(('', 80))
  s.listen(5)
except OSError as e:
  machine.reset()

while True:
  try:
    if gc.mem_free() < 102000:
      gc.collect()
    conn, addr = s.accept()
    conn.settimeout(3.0)
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    conn.settimeout(None)
    request = str(request)
    print('Content = %s' % request)
    led_on = request.find('/?led=on')
    led_off = request.find('/?led=off')
    if led_on == 6:
      print('LED ON')
      led.value(1)
    if led_off == 6:
      print('LED OFF')
      led.value(0)
    response = web_page()
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    conn.sendall(response)
    conn.close()
  except OSError as e:
    conn.close()
    print('Connection closed')

View raw code

How the Code Works

This code is based on a previous ESP32/ESP8266 MicroPython web server project. We’ve just made a few modifications to add the Wi-Fi Manager.

To add the Wi-Fi Manager, you need to import the library you’ve previously uploaded to your board.

import wifimgr

The following lines of code, handle the Wi-Fi Manager for you:

wlan = wifimgr.get_connection()
if wlan is None:
    print("Could not initialize the network connection.")
    while True:
        pass  # you shall not pass :D

wlan is a working network.WLAN(STA_IF) instance that is initialized by the library. So, you don’t need to include that to set your ESP32 as a Station.

When the ESP32 is first set as an Access Point, it leaves a socket open, which results in an error and makes the ESP32 crash. To make sure that doesn’t happen, we initialize and bind the socket inside try and except statements.

try:
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind(('', 80))
  s.listen(5)
except OSError as e:
  machine.reset()

In case, there’s a socket left open, we’ll get an OS error, and reset the ESP32 with machine.reset(). This will “forget” the open socket.

When the code runs the second time, the network credentials are already saved, so the ESP32 is not set as an Access Point, there isn’t any problem with open sockets, and the code proceeds smoothly.

Testing the WiFiManager

Upload the main.py file to your ESP32. After that, press the ESP32 on-board RST (EN) button to start running the program.

On the Python Shell, you should get a similar message.

WiFiManager Set Up ESP32 MicroPython

That means that the ESP32 was successfully set as an Access Point. Now, you can connect to that Access Point to choose your network and type your credentials. To do that, follow the next steps.

In your computer, or smartphone, open the Wi-Fi settings and connect to the WifiManager network.

Connect to WiFiManager Network ESP32 MicroPython

The password is tayfunulu. You can change the default SSID and password on the library code.

Enter network password wifimanager

Once you’re successfully connected to the WiFiManager network, open a browser and type 192.168.4.1. The following page should load:

Selecting Wi-Fi Network - WiFiManager MicroPython ESP32

Select your network, type the password and click Submit. After a few seconds, you should receive a success message.

ESP32 successfully connected to Wifi Network - WiFiManager

This message means that your ESP32 is set up as a Wi-Fi Station and it is connected to your local network. Now, to access the ESP32, go again to your Wi-Fi settings in your computer or smartphone and connect again to your network.

In the Python shell, the ESP32 IP address should be printed.

ESP32 Station IP Address - WiFiManager MicroPython

Note: in a real world scenario, you’ll probably won’t have access to the Python shell. In that situation, we recommend printing the IP address on an OLED display.

Open your browser and type that IP address. You’ll get access to the following web server and you can control the ESP32 GPIO.

ESP32 Web Server Control Outputs MicroPython - WiFiManager

Wrapping Up

With the WiFiManager library you no longer have to hard-code your network credentials. The ESP32 sets an Access Point that displays the available Wi-Fi networks. You just need to choose your network and enter your password to set the ESP32 as a Wi-Fi Station.

We hope you’ve found this tutorial useful. You may also like:

Learn more about MicroPython with our eBook: MicroPython Programming with ESP32 and ESP8266

Thanks for reading.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

2 thoughts on “MicroPython: Wi-Fi Manager with ESP32 (ESP8266 compatible)”

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.