WebServer.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #ifndef _WEBSERVER_H
  2. #define _WEBSERVER_H
  3. #include <Arduino.h>
  4. #include <ArduinoJson.h>
  5. #include <ESP8266WebServer.h>
  6. #include <Vector.h>
  7. struct PatternHandler {
  8. PatternHandler(const String& pattern, const HTTPMethod method, const ESP8266WebServer::THandlerFunction fn)
  9. : pattern(pattern),
  10. method(method),
  11. fn(fn)
  12. { }
  13. const String pattern;
  14. const HTTPMethod method;
  15. const ESP8266WebServer::THandlerFunction fn;
  16. };
  17. class WebServer : public ESP8266WebServer {
  18. public:
  19. WebServer(int port) :
  20. ESP8266WebServer(port) {
  21. ESP8266WebServer::onNotFound([&]() { checkPatterns(); });
  22. }
  23. ~WebServer() {
  24. delete buffer;
  25. }
  26. bool matchesPattern(const String& pattern, const String& url);
  27. void onPattern(const String& pattern, const HTTPMethod method, const THandlerFunction fn);
  28. String arg(String key) {
  29. if (pathMatches && pathMatches->containsKey(key)) {
  30. return pathMatches->get<String>(key);
  31. }
  32. return ESP8266WebServer::arg(key);
  33. }
  34. inline bool clientConnected() {
  35. return _currentClient && _currentClient.connected();
  36. }
  37. inline void onNotFound(THandlerFunction fn) {
  38. notFoundHandler = fn;
  39. }
  40. private:
  41. void resetPathMatches();
  42. void checkPatterns();
  43. DynamicJsonBuffer* buffer;
  44. JsonObject* pathMatches;
  45. Vector<PatternHandler*> handlers;
  46. THandlerFunction notFoundHandler;
  47. };
  48. #endif