Files
esphome-dev/esphome/components/sntp/sntp_component.cpp
T
Jimmy Hedman b8d2a6f574 [sntp] fix for ESP-IDF > 5.0 (#6769)
* Make sntp work with ESP-IDF >= 5.0

* Set operatingmode on other than ESP-IDF

---------

Co-authored-by: Keith Burzinski <kbx81x@gmail.com>
2024-06-02 22:23:49 -05:00

82 lines
1.9 KiB
C++

#include "sntp_component.h"
#include "esphome/core/log.h"
#ifdef USE_ESP_IDF
#include "esp_sntp.h"
#elif USE_ESP8266
#include "sntp.h"
#else
#include "lwip/apps/sntp.h"
#endif
// Yes, the server names are leaked, but that's fine.
#ifdef CLANG_TIDY
#define strdup(x) (const_cast<char *>(x))
#endif
namespace esphome {
namespace sntp {
static const char *const TAG = "sntp";
void SNTPComponent::setup() {
#ifndef USE_HOST
ESP_LOGCONFIG(TAG, "Setting up SNTP...");
#if defined(USE_ESP_IDF)
if (esp_sntp_enabled()) {
esp_sntp_stop();
}
esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL);
#else
sntp_stop();
sntp_setoperatingmode(SNTP_OPMODE_POLL);
#endif
sntp_setservername(0, strdup(this->server_1_.c_str()));
if (!this->server_2_.empty()) {
sntp_setservername(1, strdup(this->server_2_.c_str()));
}
if (!this->server_3_.empty()) {
sntp_setservername(2, strdup(this->server_3_.c_str()));
}
#ifdef USE_ESP_IDF
esp_sntp_set_sync_interval(this->get_update_interval());
#endif
sntp_init();
#endif
}
void SNTPComponent::dump_config() {
ESP_LOGCONFIG(TAG, "SNTP Time:");
ESP_LOGCONFIG(TAG, " Server 1: '%s'", this->server_1_.c_str());
ESP_LOGCONFIG(TAG, " Server 2: '%s'", this->server_2_.c_str());
ESP_LOGCONFIG(TAG, " Server 3: '%s'", this->server_3_.c_str());
ESP_LOGCONFIG(TAG, " Timezone: '%s'", this->timezone_.c_str());
}
void SNTPComponent::update() {
#if !defined(USE_ESP_IDF) && !defined(USE_HOST)
// force resync
if (sntp_enabled()) {
sntp_stop();
this->has_time_ = false;
sntp_init();
}
#endif
}
void SNTPComponent::loop() {
if (this->has_time_)
return;
auto time = this->now();
if (!time.is_valid())
return;
ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
time.minute, time.second);
this->time_sync_callback_.call();
this->has_time_ = true;
}
} // namespace sntp
} // namespace esphome