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.

77 lines
2.4 KiB

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