CaptivePortal.ino 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <DNSServer.h>
  2. #ifdef ESP32
  3. #include <WiFi.h>
  4. #include <AsyncTCP.h>
  5. #elif defined(ESP8266)
  6. #include <ESP8266WiFi.h>
  7. #include <ESPAsyncTCP.h>
  8. #endif
  9. #include "ESPAsyncWebServer.h"
  10. DNSServer dnsServer;
  11. AsyncWebServer server(80);
  12. class CaptiveRequestHandler : public AsyncWebHandler {
  13. public:
  14. CaptiveRequestHandler() {}
  15. virtual ~CaptiveRequestHandler() {}
  16. bool canHandle(AsyncWebServerRequest *request){
  17. //request->addInterestingHeader("ANY");
  18. return true;
  19. }
  20. void handleRequest(AsyncWebServerRequest *request) {
  21. AsyncResponseStream *response = request->beginResponseStream("text/html");
  22. response->print("<!DOCTYPE html><html><head><title>Captive Portal</title></head><body>");
  23. response->print("<p>This is out captive portal front page.</p>");
  24. response->printf("<p>You were trying to reach: http://%s%s</p>", request->host().c_str(), request->url().c_str());
  25. response->printf("<p>Try opening <a href='http://%s'>this link</a> instead</p>", WiFi.softAPIP().toString().c_str());
  26. response->print("</body></html>");
  27. request->send(response);
  28. }
  29. };
  30. void setup(){
  31. //your other setup stuff...
  32. WiFi.softAP("esp-captive");
  33. dnsServer.start(53, "*", WiFi.softAPIP());
  34. server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);//only when requested from AP
  35. //more handlers...
  36. server.begin();
  37. }
  38. void loop(){
  39. dnsServer.processNextRequest();
  40. }