Skip to content

Commit

Permalink
Merge branch 'master' into lwipintfdev_move_compat_methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mcspr authored Jun 15, 2024
2 parents 4bfbc45 + 338b625 commit b2d52b1
Show file tree
Hide file tree
Showing 11 changed files with 330 additions and 44 deletions.
21 changes: 20 additions & 1 deletion libraries/ESP8266WebServer/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ Client request handlers

.. code:: cpp
void on();
RequestHandler<ServerType>& on();
bool removeRoute();
void addHandler();
bool removeHandler();
void onNotFound();
void onFileUpload();
Expand All @@ -64,9 +66,26 @@ Client request handlers
.. code:: cpp
server.on("/", handlerFunction);
server.removeRoute("/"); // Removes any route which points to "/" and has HTTP_ANY attribute
server.removeRoute("/", HTTP_GET); // Removes any route which points to "/" and has HTTP_GET attribute
server.onNotFound(handlerFunction); // called when handler is not assigned
server.onFileUpload(handlerFunction); // handle file uploads
Client request filters
^^^^^^^^^^^^^^^^^^^^^^

.. code:: cpp
RequestHandler<ServerType>& setFilter();
*Example:*

More details about this in `Filters.ino` example.

.. code:: cpp
server.on("/", handlerFunction).setFilter(ON_AP_FILTER)
Sending responses to the client
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
101 changes: 101 additions & 0 deletions libraries/ESP8266WebServer/examples/Filters/Filters.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

// Your STA WiFi Credentials
// ( This is the AP your ESP will connect to )
const char *ssid = "...";
const char *password = "...";

// Your AP WiFi Credentials
// ( This is the AP your ESP will broadcast )
const char *ap_ssid = "ESP8266_Demo";
const char *ap_password = "";

ESP8266WebServer server(80);

const int led = 13;

// ON_STA_FILTER - Only accept requests coming from STA interface
bool ON_STA_FILTER(ESP8266WebServer &server) {
return WiFi.localIP() == server.client().localIP();
}

// ON_AP_FILTER - Only accept requests coming from AP interface
bool ON_AP_FILTER(ESP8266WebServer &server) {
return WiFi.softAPIP() == server.client().localIP();
}

void handleNotFound() {
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}

void setup(void) {
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(115200);
WiFi.mode(WIFI_AP_STA);
// Connect to STA
WiFi.begin(ssid, password);
// Start AP
WiFi.softAP(ap_ssid, ap_password);
Serial.println("");

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}

// This route will be accessible by STA clients only
server.on("/", [&]() {
digitalWrite(led, 1);
server.send(200, "text/plain", "Hi!, This route is accessible for STA clients only");
digitalWrite(led, 0);
})
.setFilter(ON_STA_FILTER);

// This route will be accessible by AP clients only
server.on("/", [&]() {
digitalWrite(led, 1);
server.send(200, "text/plain", "Hi!, This route is accessible for AP clients only");
digitalWrite(led, 0);
})
.setFilter(ON_AP_FILTER);

server.on("/inline", []() {
server.send(200, "text/plain", "this works as well");
});

server.onNotFound(handleNotFound);

server.begin();
Serial.println("HTTP server started");
}

void loop(void) {
server.handleClient();
}
14 changes: 6 additions & 8 deletions libraries/ESP8266WebServer/examples/WebServer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ It features
* Only files in the root folder are supported for simplicity - no directories.




## Implementing a web server

The ESP8266WebServer library offers a simple path to implement a web server on a ESP8266 board.
Expand Down Expand Up @@ -90,7 +88,7 @@ that actually has only one line of functionality by sending a string as result t
> });
> ```
Here the text from a static String with html code is returned instead of a file from the filesystem.
Here the text from a static string with html code is returned instead of a file from the filesystem.
The content of this string can be found in the file `builtinfiles.h`. It contains a small html+javascript implementation
that allows uploading new files into the empty filesystem.
Expand All @@ -100,14 +98,14 @@ Just open <http://webserver/$upload.htm> and drag some files from the data folde
## Registering a function to handle requests to the server without a path
Often servers are addressed by using the base URL like <http://webserver/> where no further path details is given.
Of course we like the user to be redirected to something usable. Therefore the `handleRoot()` function is registered:
Of course we like the user to be redirected to something usable. Therefore the `handleRedirect()` function is registered:
> ```CPP
> server.on("/$upload.htm", handleRoot);
> server.on("/", HTTP_GET, handleRedirect);
> ```
The `handleRoot()` function checks the filesystem for the file named **/index.htm** and creates a redirect to this file when the file exists.
Otherwise the redirection goes to the built-in **/$upload.htm** web page.
The `handleRedirect()` function checks the filesystem for the file named **/index.htm** and creates a redirect
response to this file when the file exists. Otherwise the redirection goes to the built-in **/$upload.htm** web page.
Expand All @@ -122,7 +120,7 @@ The **serveStatic** plug in is part of the library and handles delivering files
> ```
### Cross-Origin Ressource Sharing (CORS)
### Cross-Origin Resource Sharing (CORS)
The `enableCORS(true)` function adds a `Access-Control-Allow-Origin: *` http-header to all responses to the client
to inform that it is allowed to call URLs and services on this server from other web sites.
Expand Down
4 changes: 2 additions & 2 deletions libraries/ESP8266WebServer/examples/WebServer/WebServer.ino
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ void handleRedirect() {
TRACE("Redirect...");
String url = "/index.htm";

if (!LittleFS.exists(url)) { url = "/$update.htm"; }
if (!LittleFS.exists(url)) { url = "/$upload.htm"; }

server.redirect(url);
} // handleRedirect()
Expand Down Expand Up @@ -104,7 +104,7 @@ public:

// @brief check incoming request. Can handle POST for uploads and DELETE.
// @param requestMethod method of the http request line.
// @param requestUri request ressource from the http request line.
// @param requestUri request resource from the http request line.
// @return true when method can be handled.
bool canHandle(HTTPMethod requestMethod, const String UNUSED &_uri) override {
return ((requestMethod == HTTP_POST) || (requestMethod == HTTP_DELETE));
Expand Down
4 changes: 2 additions & 2 deletions libraries/ESP8266WebServer/examples/WebServer/builtinfiles.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ R"==(
static const char notFoundContent[] PROGMEM = R"==(
<html>
<head>
<title>Ressource not found</title>
<title>Resource not found</title>
</head>
<body>
<p>The ressource was not found.</p>
<p>The resource was not found.</p>
<p><a href="/">Start again</a></p>
</body>
)==";
87 changes: 81 additions & 6 deletions libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -230,25 +230,73 @@ void ESP8266WebServerTemplate<ServerType>::requestAuthentication(HTTPAuthMethod
}

template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, ESP8266WebServerTemplate<ServerType>::THandlerFunction handler) {
on(uri, HTTP_ANY, handler);
RequestHandler<ServerType>& ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, ESP8266WebServerTemplate<ServerType>::THandlerFunction handler) {
return on(uri, HTTP_ANY, handler);
}

template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn) {
on(uri, method, fn, _fileUploadHandler);
RequestHandler<ServerType>& ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn) {
return on(uri, method, fn, _fileUploadHandler);
}

template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn, ESP8266WebServerTemplate<ServerType>::THandlerFunction ufn) {
_addRequestHandler(new FunctionRequestHandler<ServerType>(fn, ufn, uri, method));
RequestHandler<ServerType>& ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn, ESP8266WebServerTemplate<ServerType>::THandlerFunction ufn) {
RequestHandler<ServerType> *handler = new FunctionRequestHandler<ServerType>(fn, ufn, uri, method);
_addRequestHandler(handler);
return *handler;
}

template <typename ServerType>
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const char *uri) {
return removeRoute(String(uri), HTTP_ANY);
}

template <typename ServerType>
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const char *uri, HTTPMethod method) {
return removeRoute(String(uri), method);
}

template <typename ServerType>
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const String &uri) {
return removeRoute(uri, HTTP_ANY);
}

template <typename ServerType>
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const String &uri, HTTPMethod method) {
bool anyHandlerRemoved = false;
RequestHandlerType *handler = _firstHandler;
RequestHandlerType *previousHandler = nullptr;

while (handler) {
if (handler->canHandle(method, uri)) {
if (_removeRequestHandler(handler)) {
anyHandlerRemoved = true;
// Move to the next handler
if (previousHandler) {
handler = previousHandler->next();
} else {
handler = _firstHandler;
}
continue;
}
}
previousHandler = handler;
handler = handler->next();
}

return anyHandlerRemoved;
}

template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::addHandler(RequestHandlerType* handler) {
_addRequestHandler(handler);
}

template <typename ServerType>
bool ESP8266WebServerTemplate<ServerType>::removeHandler(RequestHandlerType *handler) {
return _removeRequestHandler(handler);
}

template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::_addRequestHandler(RequestHandlerType* handler) {
if (!_lastHandler) {
Expand All @@ -261,6 +309,33 @@ void ESP8266WebServerTemplate<ServerType>::_addRequestHandler(RequestHandlerType
}
}

template <typename ServerType>
bool ESP8266WebServerTemplate<ServerType>::_removeRequestHandler(RequestHandlerType *handler) {
RequestHandlerType *current = _firstHandler;
RequestHandlerType *previous = nullptr;

while (current != nullptr) {
if (current == handler) {
if (previous == nullptr) {
_firstHandler = current->next();
} else {
previous->next(current->next());
}

if (current == _lastHandler) {
_lastHandler = previous;
}

// Delete 'matching' handler
delete current;
return true;
}
previous = current;
current = current->next();
}
return false;
}

template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header) {
bool is_file = false;
Expand Down
15 changes: 11 additions & 4 deletions libraries/ESP8266WebServer/src/ESP8266WebServer.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,17 @@ class ESP8266WebServerTemplate

typedef std::function<void(void)> THandlerFunction;
typedef std::function<String(FS &fs, const String &fName)> ETagFunction;

void on(const Uri &uri, THandlerFunction handler);
void on(const Uri &uri, HTTPMethod method, THandlerFunction fn);
void on(const Uri &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn);
typedef std::function<bool(ESP8266WebServerTemplate<ServerType> &server)> FilterFunction;

RequestHandler<ServerType>& on(const Uri &uri, THandlerFunction handler);
RequestHandler<ServerType>& on(const Uri &uri, HTTPMethod method, THandlerFunction fn);
RequestHandler<ServerType>& on(const Uri &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn);
bool removeRoute(const char *uri);
bool removeRoute(const char *uri, HTTPMethod method);
bool removeRoute(const String &uri);
bool removeRoute(const String &uri, HTTPMethod method);
void addHandler(RequestHandlerType* handler);
bool removeHandler(RequestHandlerType* handler);
void serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_header = NULL );
void onNotFound(THandlerFunction fn); //called when handler is not assigned
void onFileUpload(THandlerFunction fn); //handle file uploads
Expand Down Expand Up @@ -306,6 +312,7 @@ class ESP8266WebServerTemplate

protected:
void _addRequestHandler(RequestHandlerType* handler);
bool _removeRequestHandler(RequestHandlerType *handler);
void _handleRequest();
void _finalizeResponse();
ClientFuture _parseRequest(ClientType& client);
Expand Down
Loading

0 comments on commit b2d52b1

Please sign in to comment.