ESPHome  2024.12.2
sntp_component.cpp
Go to the documentation of this file.
1 #include "sntp_component.h"
2 #include "esphome/core/log.h"
3 
4 #ifdef USE_ESP_IDF
5 #include "esp_sntp.h"
6 #elif USE_ESP8266
7 #include "sntp.h"
8 #else
9 #include "lwip/apps/sntp.h"
10 #endif
11 
12 namespace esphome {
13 namespace sntp {
14 
15 static const char *const TAG = "sntp";
16 
18  ESP_LOGCONFIG(TAG, "Setting up SNTP...");
19 #if defined(USE_ESP_IDF)
20  if (esp_sntp_enabled()) {
21  esp_sntp_stop();
22  }
23  esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL);
24  size_t i = 0;
25  for (auto &server : this->servers_) {
26  esp_sntp_setservername(i++, server.c_str());
27  }
28  esp_sntp_set_sync_interval(this->get_update_interval());
29  esp_sntp_init();
30 #else
31  sntp_stop();
32  sntp_setoperatingmode(SNTP_OPMODE_POLL);
33 
34  size_t i = 0;
35  for (auto &server : this->servers_) {
36  sntp_setservername(i++, server.c_str());
37  }
38  sntp_init();
39 #endif
40 }
42  ESP_LOGCONFIG(TAG, "SNTP Time:");
43  size_t i = 0;
44  for (auto &server : this->servers_) {
45  ESP_LOGCONFIG(TAG, " Server %zu: '%s'", i++, server.c_str());
46  }
47 }
49 #if !defined(USE_ESP_IDF)
50  // force resync
51  if (sntp_enabled()) {
52  sntp_stop();
53  this->has_time_ = false;
54  sntp_init();
55  }
56 #endif
57 }
59  if (this->has_time_)
60  return;
61 
62  auto time = this->now();
63  if (!time.is_valid())
64  return;
65 
66  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
67  time.minute, time.second);
68  this->time_sync_callback_.call();
69  this->has_time_ = true;
70 }
71 
72 } // namespace sntp
73 } // namespace esphome
ESPTime now()
Get the time in the currently defined timezone.
std::vector< std::string > servers_
CallbackManager< void()> time_sync_callback_
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
Definition: component.cpp:228
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7