Fork of the excellent esp8266-react - https://github.com/rjwats/esp8266-react
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.4 KiB

  1. #ifndef SettingsService_h
  2. #define SettingsService_h
  3. #ifdef ESP32
  4. #include <WiFi.h>
  5. #include <AsyncTCP.h>
  6. #elif defined(ESP8266)
  7. #include <ESP8266WiFi.h>
  8. #include <ESPAsyncTCP.h>
  9. #endif
  10. #include <ArduinoJson.h>
  11. #include <AsyncJson.h>
  12. #include <AsyncJsonCallbackResponse.h>
  13. #include <AsyncJsonWebHandler.h>
  14. #include <ESPAsyncWebServer.h>
  15. #include <SecurityManager.h>
  16. #include <SettingsPersistence.h>
  17. /*
  18. * Abstraction of a service which stores it's settings as JSON in a file system.
  19. */
  20. class SettingsService : public SettingsPersistence {
  21. public:
  22. SettingsService(AsyncWebServer* server, FS* fs, char const* servicePath, char const* filePath) :
  23. SettingsPersistence(fs, filePath),
  24. _servicePath(servicePath) {
  25. server->on(_servicePath, HTTP_GET, std::bind(&SettingsService::fetchConfig, this, std::placeholders::_1));
  26. _updateHandler.setUri(servicePath);
  27. _updateHandler.setMethod(HTTP_POST);
  28. _updateHandler.setMaxContentLength(MAX_SETTINGS_SIZE);
  29. _updateHandler.onRequest(
  30. std::bind(&SettingsService::updateConfig, this, std::placeholders::_1, std::placeholders::_2));
  31. server->addHandler(&_updateHandler);
  32. }
  33. virtual ~SettingsService() {
  34. }
  35. void begin() {
  36. // read the initial data from the file system
  37. readFromFS();
  38. }
  39. protected:
  40. char const* _servicePath;
  41. AsyncJsonWebHandler _updateHandler;
  42. virtual void fetchConfig(AsyncWebServerRequest* request) {
  43. // handle the request
  44. AsyncJsonResponse* response = new AsyncJsonResponse(false, MAX_SETTINGS_SIZE);
  45. JsonObject jsonObject = response->getRoot();
  46. writeToJsonObject(jsonObject);
  47. response->setLength();
  48. request->send(response);
  49. }
  50. virtual void updateConfig(AsyncWebServerRequest* request, JsonDocument& jsonDocument) {
  51. // handle the request
  52. if (jsonDocument.is<JsonObject>()) {
  53. JsonObject newConfig = jsonDocument.as<JsonObject>();
  54. readFromJsonObject(newConfig);
  55. writeToFS();
  56. // write settings back with a callback to reconfigure the wifi
  57. AsyncJsonCallbackResponse* response =
  58. new AsyncJsonCallbackResponse([this]() { onConfigUpdated(); }, false, MAX_SETTINGS_SIZE);
  59. JsonObject jsonObject = response->getRoot();
  60. writeToJsonObject(jsonObject);
  61. response->setLength();
  62. request->send(response);
  63. } else {
  64. request->send(400);
  65. }
  66. }
  67. // implement to perform action when config has been updated
  68. virtual void onConfigUpdated() {
  69. }
  70. };
  71. #endif // end SettingsService