PsychicHttp icon indicating copy to clipboard operation
PsychicHttp copied to clipboard

captive portal added in main.cpp PsychicHttp example

Open 06GitHub opened this issue 9 months ago • 2 comments

Thanks for the great job done on PsychicHttp 👍

1) SUMMARY

For my project, there is a need for captive portal, ie web page which opens automatically when user connects Wifi network (eg "PsychitHttp").

Captiveportal is implemented in ESPAsyncWebServer https://github.com/me-no-dev/ESPAsyncWebServer/blob/master/examples/CaptivePortal/CaptivePortal.ino and in arduino-esp32 examples https://github.com/espressif/arduino-esp32/blob/master/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino

This feature can be implemented with Psychichttp with a dedicated handler, as shown in updated "main.cpp" example.

If needed, captive portal could be added in "main.cpp" PsychicHttp example.

Thanks

Code is added below for reference.

2) CODE

Definitions

// captiveportal
// credits https://github.com/me-no-dev/ESPAsyncWebServer/blob/master/examples/CaptivePortal/CaptivePortal.ino
//https://github.com/espressif/arduino-esp32/blob/master/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino
#include <DNSServer.h> 
DNSServer dnsServer;            
//PsychicWebHandler captiverequest;
class CaptiveRequestHandler : public PsychicWebHandler { // handler 
public:
  CaptiveRequestHandler() {};
  virtual ~CaptiveRequestHandler() {};
  bool canHandle(PsychicRequest*request){
    // ... if needed some tests ... return(false);
    return true;  // activate captive portal
  }
  esp_err_t handleRequest(PsychicRequest *request) {   
   //PsychicFileResponse response(request, LittleFS, "/captiveportal.html"); // captive portal page, if any
   //return response.send();                                                 // return captive portal page
   return request->reply(200,"text/html","Welcome to captive portal !");  // simple text, comment if captive portal page
  }
};
CaptiveRequestHandler *captivehandler=NULL;             // handler for captive portal

setup()

    // captive portal
    dnsServer.start(53, "*", WiFi.softAPIP());                    // DNS requests are executed over port 53 (standard)     
    captivehandler= new CaptiveRequestHandler();                 // create captive portal handler, important : after server.on since handlers are triggered on a first created/first trigerred basis
    server.addHandler(captivehandler);                           // captive portal handler (last handler) 

loop() dnsServer.processNextRequest(); // captive portal

result (web page opened automatically) captiveportal

06GitHub avatar May 14 '24 17:05 06GitHub