ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
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 "esp_sntp.h"
6#elif USE_ESP8266
7#include "sntp.h"
8#else
9#include "lwip/apps/sntp.h"
10#endif
11
12namespace esphome {
13namespace sntp {
14
15static const char *const TAG = "sntp";
16
18#if defined(USE_ESP32)
19 if (esp_sntp_enabled()) {
20 esp_sntp_stop();
21 }
22 esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL);
23 size_t i = 0;
24 for (auto &server : this->servers_) {
25 esp_sntp_setservername(i++, server.c_str());
26 }
27 esp_sntp_set_sync_interval(this->get_update_interval());
28 esp_sntp_init();
29#else
30 sntp_stop();
31 sntp_setoperatingmode(SNTP_OPMODE_POLL);
32
33 size_t i = 0;
34 for (auto &server : this->servers_) {
35 sntp_setservername(i++, server.c_str());
36 }
37 sntp_init();
38#endif
39}
41 ESP_LOGCONFIG(TAG, "SNTP Time:");
42 size_t i = 0;
43 for (auto &server : this->servers_) {
44 ESP_LOGCONFIG(TAG, " Server %zu: '%s'", i++, server.c_str());
45 }
46}
48#if !defined(USE_ESP32)
49 // force resync
50 if (sntp_enabled()) {
51 sntp_stop();
52 this->has_time_ = false;
53 sntp_init();
54 }
55#endif
56}
58 if (this->has_time_)
59 return;
60
61 auto time = this->now();
62 if (!time.is_valid())
63 return;
64
65 ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
66 time.minute, time.second);
67 this->time_sync_callback_.call();
68 this->has_time_ = true;
69
70#ifdef USE_ESP_IDF
71 // On ESP-IDF, time sync is permanent and update() doesn't force resync
72 // Time is now synchronized, no need to check anymore
73 this->disable_loop();
74#endif
75}
76
77} // namespace sntp
78} // namespace esphome
void disable_loop()
Disable this component's loop.
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
std::vector< std::string > servers_
CallbackManager< void()> time_sync_callback_
ESPTime now()
Get the time in the currently defined timezone.
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7