Connecting an ESP32 board to a public Wi-Fi network with a captive portal that requires user interaction can be a bit tricky. Your ESP32 does not have any user-driven interaction possibilities and each captive portal offers different steps for users to consent. Sometimes its a single page with terms of use and a simple accpet button but it could also be a completely different flow.
Nevertheless, here’s one approach that might work:
- Connect to the Wi-Fi network using the ESP32’s built-in Wi-Fi capabilities. You can use the following code to do this:
import network
ssid = 'YOUR_WIFI_SSID'
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid)
- Once you’re connected to the Wi-Fi network, the ESP32 will typically be redirected to the captive portal page. However, since the ESP32 does not have a web browser, you cannot simply click the button to connect.
- Instead, you can use the
urequests
module to send an HTTP POST request to the captive portal page, pretending that you have clicked the button. Here’s an example code snippet that sends a POST request to the captive portal URL:
import urequests
url = 'http://captive.portal.url'
data = {'button': 'clicked'}
response = urequests.post(url, json=data)
Note that the exact URL and data format may vary depending on the specific captive portal implementation.
- Finally, you can use the
socket
module to check if you are connected to the internet. Here’s an example code snippet that waits for internet connectivity:
import socket
while True:
try:
addr = socket.getaddrinfo('google.com', 80)[0][-1]
s = socket.socket()
s.connect(addr)
print('Connected to the internet!')
break
except OSError:
print('Waiting for internet connectivity...')
This code repeatedly tries to connect to google.com
until it succeeds, indicating that you are connected to the internet. Once you have internet connectivity, you can proceed with whatever application you want to run on the ESP32 board.