ESPHome  2024.11.1
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 // Yes, the server names are leaked, but that's fine.
13 #ifdef CLANG_TIDY
14 #define strdup(x) (const_cast<char *>(x))
15 #endif
16 
17 namespace esphome {
18 namespace sntp {
19 
20 static const char *const TAG = "sntp";
21 
23  ESP_LOGCONFIG(TAG, "Setting up SNTP...");
24 #if defined(USE_ESP_IDF)
25  if (esp_sntp_enabled()) {
26  esp_sntp_stop();
27  }
28  esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL);
29 #else
30  sntp_stop();
31  sntp_setoperatingmode(SNTP_OPMODE_POLL);
32 #endif
33 
34  sntp_setservername(0, strdup(this->server_1_.c_str()));
35  if (!this->server_2_.empty()) {
36  sntp_setservername(1, strdup(this->server_2_.c_str()));
37  }
38  if (!this->server_3_.empty()) {
39  sntp_setservername(2, strdup(this->server_3_.c_str()));
40  }
41 #ifdef USE_ESP_IDF
42  esp_sntp_set_sync_interval(this->get_update_interval());
43 #endif
44 
45  sntp_init();
46 }
48  ESP_LOGCONFIG(TAG, "SNTP Time:");
49  ESP_LOGCONFIG(TAG, " Server 1: '%s'", this->server_1_.c_str());
50  ESP_LOGCONFIG(TAG, " Server 2: '%s'", this->server_2_.c_str());
51  ESP_LOGCONFIG(TAG, " Server 3: '%s'", this->server_3_.c_str());
52  ESP_LOGCONFIG(TAG, " Timezone: '%s'", this->timezone_.c_str());
53 }
55 #if !defined(USE_ESP_IDF)
56  // force resync
57  if (sntp_enabled()) {
58  sntp_stop();
59  this->has_time_ = false;
60  sntp_init();
61  }
62 #endif
63 }
65  if (this->has_time_)
66  return;
67 
68  auto time = this->now();
69  if (!time.is_valid())
70  return;
71 
72  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
73  time.minute, time.second);
74  this->time_sync_callback_.call();
75  this->has_time_ = true;
76 }
77 
78 } // namespace sntp
79 } // 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:228
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7