This project uses the ESPAsyncWebServer to implement all of its server functions. Its a truly wonderful library and is incredibly powerful.
However, after doing a few years of node + express + react programming, I found myself yearning for express-like middlewares. Rather than have to add redundant logic in each route manually for the webserver, I wanted to be able to declare a 'middleware' that would run for every request. So I created a small library to try it out!
For example, our esp32 server can really only handle one request at a time. Anything more, and the heap seems to leak, or watchdog timers timeout.
We can now create a middleware to send a 503 code if our server resources our low. This also prevents the esp32 from trying to process too many requests at once.
CREATE_MIDDLEWARE(monitorResources, {
size_t freeHeap = ESP.getFreeHeap();
const size_t criticalHeapThreshold = 170000;
if (freeHeap < criticalHeapThreshold) {
Serial.printf("Free Heap: %u bytes. Sending 503\n", freeHeap);
request->send(503, "text/plain", "Service Unavailable: Low Memory, Please Try Again Later");
return;
}
next();
});
And then later in our code we can literally:
AsyncWebServer server(80);
MiddlewareHandler app(server);
...
app.use(monitorResources);
This seems to be working well! And I am pretty happy with it!
However, the library does violoate one my rules for firmware: minimize/eliminate dynamic memory.
If ever there was a time to not get fancy, and just hard code routes, on a tiny microcontroller seems like the time.
You can learn more about the library here: https://github.com/diyaquanauts/BackcountryBeacon/tree/main/firmware/include
Better yet, suggest a better alternative method!
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.