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.

83 lines
2.3 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 <SettingsPersistence.h>
  11. #include <ESPAsyncWebServer.h>
  12. #include <AsyncJson.h>
  13. #include <ArduinoJson.h>
  14. #include <AsyncJsonRequestWebHandler.h>
  15. #include <AsyncJsonCallbackResponse.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. private:
  21. AsyncJsonRequestWebHandler _updateHandler;
  22. void fetchConfig(AsyncWebServerRequest *request){
  23. AsyncJsonResponse * response = new AsyncJsonResponse();
  24. writeToJsonObject(response->getRoot());
  25. response->setLength();
  26. request->send(response);
  27. }
  28. void updateConfig(AsyncWebServerRequest *request, JsonVariant &json){
  29. if (json.is<JsonObject>()){
  30. JsonObject& newConfig = json.as<JsonObject>();
  31. readFromJsonObject(newConfig);
  32. writeToFS();
  33. // write settings back with a callback to reconfigure the wifi
  34. AsyncJsonCallbackResponse * response = new AsyncJsonCallbackResponse([this] () {onConfigUpdated();});
  35. writeToJsonObject(response->getRoot());
  36. response->setLength();
  37. request->send(response);
  38. } else{
  39. request->send(400);
  40. }
  41. }
  42. protected:
  43. // will serve setting endpoints from here
  44. AsyncWebServer* _server;
  45. // implement to perform action when config has been updated
  46. virtual void onConfigUpdated(){}
  47. public:
  48. SettingsService(AsyncWebServer* server, FS* fs, char const* servicePath, char const* filePath):
  49. SettingsPersistence(fs, servicePath, filePath), _server(server) {
  50. // configure fetch config handler
  51. _server->on(servicePath, HTTP_GET, std::bind(&SettingsService::fetchConfig, this, std::placeholders::_1));
  52. // configure update settings handler
  53. _updateHandler.setUri(servicePath);
  54. _updateHandler.setMethod(HTTP_POST);
  55. _updateHandler.setMaxContentLength(MAX_SETTINGS_SIZE);
  56. _updateHandler.onRequest(std::bind(&SettingsService::updateConfig, this, std::placeholders::_1, std::placeholders::_2));
  57. _server->addHandler(&_updateHandler);
  58. }
  59. virtual ~SettingsService() {}
  60. virtual void begin() {
  61. readFromFS();
  62. }
  63. };
  64. #endif // end SettingsService