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.

80 lines
2.5 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 <AsyncJson.h>
  16. #include <AsyncJsonCallbackResponse.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): SettingsPersistence(fs, filePath), _servicePath(servicePath) {
  23. server->on(_servicePath, HTTP_GET, std::bind(&SettingsService::fetchConfig, this, std::placeholders::_1));
  24. _updateHandler.setUri(servicePath);
  25. _updateHandler.setMethod(HTTP_POST);
  26. _updateHandler.setMaxContentLength(MAX_SETTINGS_SIZE);
  27. _updateHandler.onRequest(std::bind(&SettingsService::updateConfig, this, std::placeholders::_1, std::placeholders::_2));
  28. server->addHandler(&_updateHandler);
  29. }
  30. virtual ~SettingsService() {}
  31. void begin() {
  32. // read the initial data from the file system
  33. readFromFS();
  34. }
  35. protected:
  36. char const* _servicePath;
  37. AsyncJsonWebHandler _updateHandler;
  38. virtual void fetchConfig(AsyncWebServerRequest *request) {
  39. // handle the request
  40. AsyncJsonResponse * response = new AsyncJsonResponse(false, MAX_SETTINGS_SIZE);
  41. JsonObject jsonObject = response->getRoot();
  42. writeToJsonObject(jsonObject);
  43. response->setLength();
  44. request->send(response);
  45. }
  46. virtual void updateConfig(AsyncWebServerRequest *request, JsonDocument &jsonDocument) {
  47. // handle the request
  48. if (jsonDocument.is<JsonObject>()){
  49. JsonObject newConfig = jsonDocument.as<JsonObject>();
  50. readFromJsonObject(newConfig);
  51. writeToFS();
  52. // write settings back with a callback to reconfigure the wifi
  53. AsyncJsonCallbackResponse * response = new AsyncJsonCallbackResponse([this] () {onConfigUpdated();}, false, MAX_SETTINGS_SIZE);
  54. JsonObject jsonObject = response->getRoot();
  55. writeToJsonObject(jsonObject);
  56. response->setLength();
  57. request->send(response);
  58. } else {
  59. request->send(400);
  60. }
  61. }
  62. // implement to perform action when config has been updated
  63. virtual void onConfigUpdated(){}
  64. };
  65. #endif // end SettingsService