ESPHome  2024.3.1
sntp_component.cpp
Go to the documentation of this file.
1 #include "sntp_component.h"
2 #include "esphome/core/log.h"
3 
4 #if defined(USE_ESP32) || defined(USE_LIBRETINY)
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 #ifndef USE_HOST
29  ESP_LOGCONFIG(TAG, "Setting up SNTP...");
30 #if defined(USE_ESP32) || defined(USE_LIBRETINY)
31  if (sntp_enabled()) {
32  sntp_stop();
33  }
34  sntp_setoperatingmode(SNTP_OPMODE_POLL);
35 #endif
36 #ifdef USE_ESP8266
37  sntp_stop();
38 #endif
39 
40  sntp_setservername(0, strdup(this->server_1_.c_str()));
41  if (!this->server_2_.empty()) {
42  sntp_setservername(1, strdup(this->server_2_.c_str()));
43  }
44  if (!this->server_3_.empty()) {
45  sntp_setservername(2, strdup(this->server_3_.c_str()));
46  }
47 #ifdef USE_ESP_IDF
48  sntp_set_sync_interval(this->get_update_interval());
49 #endif
50 
51  sntp_init();
52 #endif
53 }
55  ESP_LOGCONFIG(TAG, "SNTP Time:");
56  ESP_LOGCONFIG(TAG, " Server 1: '%s'", this->server_1_.c_str());
57  ESP_LOGCONFIG(TAG, " Server 2: '%s'", this->server_2_.c_str());
58  ESP_LOGCONFIG(TAG, " Server 3: '%s'", this->server_3_.c_str());
59  ESP_LOGCONFIG(TAG, " Timezone: '%s'", this->timezone_.c_str());
60 }
62 #if !defined(USE_ESP_IDF) && !defined(USE_HOST)
63  // force resync
64  if (sntp_enabled()) {
65  sntp_stop();
66  this->has_time_ = false;
67  sntp_init();
68  }
69 #endif
70 }
72  if (this->has_time_)
73  return;
74 
75  auto time = this->now();
76  if (!time.is_valid())
77  return;
78 
79  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
80  time.minute, time.second);
81  this->time_sync_callback_.call();
82  this->has_time_ = true;
83 }
84 
85 } // namespace sntp
86 } // 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:223
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7