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.

59 lines
2.3 KiB

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