esp8266-react-framework/lib/framework/SimpleService.h

88 lines
2.5 KiB
C
Raw Normal View History

2018-03-29 08:54:02 +00:00
#ifndef Service_h
#define Service_h
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
2018-03-29 08:54:02 +00:00
#include <ArduinoJson.h>
#include <AsyncJson.h>
#include <AsyncJsonCallbackResponse.h>
#include <AsyncJsonWebHandler.h>
#include <ESPAsyncWebServer.h>
2018-03-29 08:54:02 +00:00
/**
* At the moment, not expecting services to have to deal with large JSON
* files this could be made configurable fairly simply, it's exposed on
* AsyncJsonWebHandler with a setter.
*/
2018-03-29 08:54:02 +00:00
#define MAX_SETTINGS_SIZE 1024
/*
* Abstraction of a service which reads and writes data from an endpoint.
*
* Not currently used, but indended for use by features which do not
* require setting persistance.
*/
2018-03-29 08:54:02 +00:00
class SimpleService {
private:
2019-05-18 18:35:27 +00:00
AsyncJsonWebHandler _updateHandler;
2018-03-29 08:54:02 +00:00
void fetchConfig(AsyncWebServerRequest* request) {
AsyncJsonResponse* response = new AsyncJsonResponse(false, MAX_SETTINGS_SIZE);
JsonObject jsonObject = response->getRoot();
writeToJsonObject(jsonObject);
2018-03-29 08:54:02 +00:00
response->setLength();
request->send(response);
}
void updateConfig(AsyncWebServerRequest* request, JsonDocument& jsonDocument) {
2019-07-14 21:13:26 +00:00
if (jsonDocument.is<JsonObject>()) {
JsonObject newConfig = jsonDocument.as<JsonObject>();
2018-03-29 08:54:02 +00:00
readFromJsonObject(newConfig);
2018-03-29 08:54:02 +00:00
// write settings back with a callback to reconfigure the wifi
AsyncJsonCallbackResponse* response =
new AsyncJsonCallbackResponse([this]() { onConfigUpdated(); }, false, MAX_SETTINGS_SIZE);
JsonObject jsonObject = response->getRoot();
writeToJsonObject(jsonObject);
2018-03-29 08:54:02 +00:00
response->setLength();
request->send(response);
} else {
2018-03-29 08:54:02 +00:00
request->send(400);
}
}
protected:
// reads the local config from the
virtual void readFromJsonObject(JsonObject& root) {
}
virtual void writeToJsonObject(JsonObject& root) {
}
2018-03-29 08:54:02 +00:00
// implement to perform action when config has been updated
virtual void onConfigUpdated() {
}
2018-03-29 08:54:02 +00:00
public:
SimpleService(AsyncWebServer* server, char const* servicePath) {
server->on(servicePath, HTTP_GET, std::bind(&SimpleService::fetchConfig, this, std::placeholders::_1));
_updateHandler.setUri(servicePath);
_updateHandler.setMethod(HTTP_POST);
_updateHandler.setMaxContentLength(MAX_SETTINGS_SIZE);
_updateHandler.onRequest(
std::bind(&SimpleService::updateConfig, this, std::placeholders::_1, std::placeholders::_2));
server->addHandler(&_updateHandler);
}
2018-03-29 08:54:02 +00:00
virtual ~SimpleService() {
}
2018-03-29 08:54:02 +00:00
};
#endif // end SimpleService