ESPHome  2022.12.8
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_ESP32
5 #include "lwip/apps/sntp.h"
6 #ifdef USE_ESP_IDF
7 #include "esp_sntp.h"
8 #endif
9 #endif
10 #ifdef USE_ESP8266
11 #include "sntp.h"
12 #endif
13 #ifdef USE_RP2040
14 #include "lwip/apps/sntp.h"
15 #endif
16 
17 // Yes, the server names are leaked, but that's fine.
18 #ifdef CLANG_TIDY
19 #define strdup(x) (const_cast<char *>(x))
20 #endif
21 
22 namespace esphome {
23 namespace sntp {
24 
25 static const char *const TAG = "sntp";
26 
28  ESP_LOGCONFIG(TAG, "Setting up SNTP...");
29 #ifdef USE_ESP32
30  if (sntp_enabled()) {
31  sntp_stop();
32  }
33  sntp_setoperatingmode(SNTP_OPMODE_POLL);
34 #endif
35 #ifdef USE_ESP8266
36  sntp_stop();
37 #endif
38 
39  sntp_setservername(0, strdup(this->server_1_.c_str()));
40  if (!this->server_2_.empty()) {
41  sntp_setservername(1, strdup(this->server_2_.c_str()));
42  }
43  if (!this->server_3_.empty()) {
44  sntp_setservername(2, strdup(this->server_3_.c_str()));
45  }
46 #ifdef USE_ESP_IDF
47  sntp_set_sync_interval(this->get_update_interval());
48 #endif
49 
50  sntp_init();
51 }
53  ESP_LOGCONFIG(TAG, "SNTP Time:");
54  ESP_LOGCONFIG(TAG, " Server 1: '%s'", this->server_1_.c_str());
55  ESP_LOGCONFIG(TAG, " Server 2: '%s'", this->server_2_.c_str());
56  ESP_LOGCONFIG(TAG, " Server 3: '%s'", this->server_3_.c_str());
57  ESP_LOGCONFIG(TAG, " Timezone: '%s'", this->timezone_.c_str());
58 }
60 #ifndef USE_ESP_IDF
61  // force resync
62  if (sntp_enabled()) {
63  sntp_stop();
64  this->has_time_ = false;
65  sntp_init();
66  }
67 #endif
68 }
70  if (this->has_time_)
71  return;
72 
73  auto time = this->now();
74  if (!time.is_valid())
75  return;
76 
77  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
78  time.minute, time.second);
79  this->time_sync_callback_.call();
80  this->has_time_ = true;
81 }
82 
83 } // namespace sntp
84 } // namespace esphome
ESPTime now()
Get the time in the currently defined timezone.
CallbackManager< void()> time_sync_callback_
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
Definition: component.cpp:191
Definition: a4988.cpp:4