MojoScale Forum
Login Sign up

How do I handle Wi-Fi disconnects and connection failures?

Asked 3 weeks, 6 days ago in Firmware by Mojo Scale
Ask Question
1 Answers
40 Views
0 Comments

My ESP32 connects to Wi-Fi fine with wifi.connect(), but I don't want the application to silently fail if the network goes down or the credentials are wrong.

Is there a way to detect when Wi-Fi connects/disconnects and handle connection errors separately?

Answered updated 3 weeks, 6 days ago
Log in to comment.
1 Answer
OK Accepted

Yes. The wifi module provides callbacks for connection state and common failure conditions, so you don't need to continuously poll wifi.is_connected().

A simple setup looks like this:

import wifi

def connected():
    print("Wi-Fi connected")
    print("IP:", wifi.get_ip())

def disconnected():
    print("Wi-Fi disconnected")

def connection_failed():
    print("Could not connect to Wi-Fi")

wifi.on_connect(connected)
wifi.on_disconnect(disconnected)
wifi.on_connection_failed(connection_failed)

wifi.connect("MyNetwork", "MyPassword")

Now the appropriate callback runs as the Wi-Fi state changes.

You can also distinguish common connection problems. For example:

import wifi

def network_missing():
    print("Wi-Fi network not found")

def wrong_password():
    print("Wi-Fi password is incorrect")

wifi.on_network_not_found(network_missing)
wifi.on_password_incorrect(wrong_password)

wifi.connect("MyNetwork", "MyPassword")

That's useful if the device needs to react differently depending on *why* it couldn't connect—for example, showing a setup screen when the configured network can't be found rather than treating every failure as the same generic error.

If you only need to check the current state at a particular point in your program, you can still use:

if wifi.is_connected():
    print(wifi.get_ip())

But for an application that's expected to stay running, the callbacks are generally a cleaner way to react to connectivity changes than repeatedly checking Wi-Fi state yourself.

There are also more specific callbacks available for authentication failures, incorrect SSIDs, generic Wi-Fi errors, and status changes, so you can make connection handling as simple or as detailed as your application needs.

answered by Mojo Scale 3 weeks, 6 days ago edited 3 weeks, 6 days ago
Your Answer
Log in to answer this question.