Making ESPUI a captive portal on ESP8266/ESP32

There's a really nice UI for making basic interactive web applications using the Arduino IDE on ESP microcontrollers, ESPUI. This is a real shortcut to usability for very basic "push a button a on web page and something happens" projects as it works asynchronously and does all the behind the scenes dirty work for you.

It does have one dull limitation though, it doesn't by default work as a captive portal. You can bodge a fix to this with the following steps.

First, find the line in ESPUI.c

server->onNotFound([](AsyncWebServerRequest* request) { request->send(404); });

Then comment it out and add the code

server->onNotFound([](AsyncWebServerRequest* request) { request->redirect("/")});

This means any time a request for an unexpected URL hits the Web Server on the ESP it will redirect to the root of the server. You can change this to some other URL by changing the "/".

Now this still won't get all requests to hit the ESP, you need to add the following bits into the rest of the sketch. This assumes your ESP is acting as an AP on the usual IP address, but you can see how it's easily changed.

<near the top of the sketch>
#include <DNSServer.h>
IPAddress apIP(192, 168, 4, 1);
DNSServer dnsServer;

void setup()
    <rest of your setup stuff>
    dnsServer.start(53, "*", apIP);
void loop()
    <rest of your loop stuff>

I really should submit a more complete solution as a pull request and new example to the library.

Now when most devices hit the ESP they will take you straight to the page asking you to "sign in" etc. and it doesn't stop you manually going to the page.

No comments: