2020-08-21 12:43:46 +02:00
|
|
|
#include <DNSServer.h>
|
2024-02-06 17:39:53 +01:00
|
|
|
#ifdef ESP32
|
2024-07-02 20:06:33 +02:00
|
|
|
#include <AsyncTCP.h>
|
|
|
|
#include <WiFi.h>
|
2024-02-06 17:39:53 +01:00
|
|
|
#elif defined(ESP8266)
|
2024-07-02 20:06:33 +02:00
|
|
|
#include <ESP8266WiFi.h>
|
|
|
|
#include <ESPAsyncTCP.h>
|
|
|
|
#elif defined(TARGET_RP2040)
|
|
|
|
#include <WebServer.h>
|
|
|
|
#include <WiFi.h>
|
2024-02-06 17:39:53 +01:00
|
|
|
#endif
|
|
|
|
#include "ESPAsyncWebServer.h"
|
2020-08-21 12:43:46 +02:00
|
|
|
|
|
|
|
DNSServer dnsServer;
|
|
|
|
AsyncWebServer server(80);
|
|
|
|
|
|
|
|
class CaptiveRequestHandler : public AsyncWebHandler {
|
2024-07-02 20:06:33 +02:00
|
|
|
public:
|
|
|
|
CaptiveRequestHandler() {}
|
|
|
|
virtual ~CaptiveRequestHandler() {}
|
|
|
|
|
|
|
|
bool canHandle(__unused AsyncWebServerRequest* request) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
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());
|
2024-09-02 06:59:11 +02:00
|
|
|
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
2024-07-02 20:06:33 +02:00
|
|
|
response->printf("<p>Try opening <a href='http://%s'>this link</a> instead</p>", WiFi.softAPIP().toString().c_str());
|
2024-09-02 06:59:11 +02:00
|
|
|
#endif
|
2024-07-02 20:06:33 +02:00
|
|
|
response->print("</body></html>");
|
|
|
|
request->send(response);
|
|
|
|
}
|
2020-08-21 12:43:46 +02:00
|
|
|
};
|
|
|
|
|
2024-07-02 20:06:33 +02:00
|
|
|
void setup() {
|
2024-05-14 13:21:01 +02:00
|
|
|
Serial.begin(115200);
|
|
|
|
Serial.println();
|
|
|
|
Serial.println("Configuring access point...");
|
|
|
|
|
2024-09-02 06:59:11 +02:00
|
|
|
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
2024-05-14 13:21:01 +02:00
|
|
|
if (!WiFi.softAP("esp-captive")) {
|
|
|
|
Serial.println("Soft AP creation failed.");
|
2024-07-02 20:06:33 +02:00
|
|
|
while (1)
|
|
|
|
;
|
2024-05-14 13:21:01 +02:00
|
|
|
}
|
|
|
|
|
2020-08-21 12:43:46 +02:00
|
|
|
dnsServer.start(53, "*", WiFi.softAPIP());
|
2024-09-02 06:59:11 +02:00
|
|
|
#endif
|
|
|
|
|
2024-07-02 20:06:33 +02:00
|
|
|
server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER); // only when requested from AP
|
|
|
|
// more handlers...
|
2020-08-21 12:43:46 +02:00
|
|
|
server.begin();
|
|
|
|
}
|
|
|
|
|
2024-07-02 20:06:33 +02:00
|
|
|
void loop() {
|
2020-08-21 12:43:46 +02:00
|
|
|
dnsServer.processNextRequest();
|
2024-02-06 17:39:53 +01:00
|
|
|
}
|