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.

64 lines
2.4 KiB

  1. #include <NTPSettingsService.h>
  2. NTPSettingsService::NTPSettingsService(AsyncWebServer* server, FS* fs, SecurityManager* securityManager) :
  3. _httpEndpoint(NTPSettings::serialize,
  4. NTPSettings::deserialize,
  5. this,
  6. server,
  7. NTP_SETTINGS_SERVICE_PATH,
  8. securityManager),
  9. _fsPersistence(NTPSettings::serialize, NTPSettings::deserialize, this, fs, NTP_SETTINGS_FILE) {
  10. #ifdef ESP32
  11. WiFi.onEvent(
  12. std::bind(&NTPSettingsService::onStationModeDisconnected, this, std::placeholders::_1, std::placeholders::_2),
  13. WiFiEvent_t::SYSTEM_EVENT_STA_DISCONNECTED);
  14. WiFi.onEvent(std::bind(&NTPSettingsService::onStationModeGotIP, this, std::placeholders::_1, std::placeholders::_2),
  15. WiFiEvent_t::SYSTEM_EVENT_STA_GOT_IP);
  16. #elif defined(ESP8266)
  17. _onStationModeDisconnectedHandler = WiFi.onStationModeDisconnected(
  18. std::bind(&NTPSettingsService::onStationModeDisconnected, this, std::placeholders::_1));
  19. _onStationModeGotIPHandler =
  20. WiFi.onStationModeGotIP(std::bind(&NTPSettingsService::onStationModeGotIP, this, std::placeholders::_1));
  21. #endif
  22. addUpdateHandler([&](const String& originId) { configureNTP(); }, false);
  23. }
  24. void NTPSettingsService::begin() {
  25. _fsPersistence.readFromFS();
  26. configureNTP();
  27. }
  28. #ifdef ESP32
  29. void NTPSettingsService::onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info) {
  30. Serial.println(F("Got IP address, starting NTP Synchronization"));
  31. configureNTP();
  32. }
  33. void NTPSettingsService::onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
  34. Serial.println(F("WiFi connection dropped, stopping NTP."));
  35. configureNTP();
  36. }
  37. #elif defined(ESP8266)
  38. void NTPSettingsService::onStationModeGotIP(const WiFiEventStationModeGotIP& event) {
  39. Serial.println(F("Got IP address, starting NTP Synchronization"));
  40. configureNTP();
  41. }
  42. void NTPSettingsService::onStationModeDisconnected(const WiFiEventStationModeDisconnected& event) {
  43. Serial.println(F("WiFi connection dropped, stopping NTP."));
  44. configureNTP();
  45. }
  46. #endif
  47. void NTPSettingsService::configureNTP() {
  48. if (WiFi.isConnected() && _state.enabled) {
  49. Serial.println(F("Starting NTP..."));
  50. #ifdef ESP32
  51. configTzTime(_state.tzFormat.c_str(), _state.server.c_str());
  52. #elif defined(ESP8266)
  53. configTime(_state.tzFormat.c_str(), _state.server.c_str());
  54. #endif
  55. } else {
  56. sntp_stop();
  57. }
  58. }