ESPAsyncWebServer/examples/CaptivePortal/CaptivePortal.ino

55 lines
1.5 KiB
Arduino
Raw Normal View History

#include <DNSServer.h>
2024-02-06 17:39:53 +01:00
#ifdef ESP32
#include <WiFi.h>
2024-02-06 17:39:53 +01:00
#include <AsyncTCP.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include "ESPAsyncWebServer.h"
DNSServer dnsServer;
AsyncWebServer server(80);
class CaptiveRequestHandler : public AsyncWebHandler {
2024-02-06 17:39:53 +01:00
public:
CaptiveRequestHandler() {}
virtual ~CaptiveRequestHandler() {}
2024-02-06 17:39:53 +01:00
bool canHandle(AsyncWebServerRequest *request){
//request->addInterestingHeader("ANY");
return true;
}
2024-02-06 17:39:53 +01:00
void handleRequest(AsyncWebServerRequest *request) {
AsyncResponseStream *response = request->beginResponseStream("text/html");
response->print("<!DOCTYPE html><html><head><title>Captive Portal</title></head><body>");
response->print("<p>This is out captive portal front page.</p>");
response->printf("<p>You were trying to reach: http://%s%s</p>", request->host().c_str(), request->url().c_str());
response->printf("<p>Try opening <a href='http://%s'>this link</a> instead</p>", WiFi.softAPIP().toString().c_str());
response->print("</body></html>");
request->send(response);
}
};
2024-02-06 17:39:53 +01:00
void setup(){
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
if (!WiFi.softAP("esp-captive")) {
Serial.println("Soft AP creation failed.");
while (1);
}
dnsServer.start(53, "*", WiFi.softAPIP());
2024-02-06 17:39:53 +01:00
server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);//only when requested from AP
//more handlers...
server.begin();
}
2024-02-06 17:39:53 +01:00
void loop(){
dnsServer.processNextRequest();
2024-02-06 17:39:53 +01:00
}