I have this code but don’t work, I thinking ESP_ERROR_CHECK(esp_netif_init());
inside in SDK does not linker full. someone its has one example of SNTP?
/**
time_ntp.c
Módulo de sincronización de hora vía SNTP
*/
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "esp_system.h"
#include "esp_log.h"
#include "esp_netif_sntp.h"
#include "esp_sntp.h"
/* ========= CONFIGURACIÓN ========= */
#define SNTP_MAX_RETRY 5 // reintentos máximos
#define SNTP_BACKOFF_BASE_MS 1000 // 1s exponencial
#define NTP_RESYNC_INTERVAL_HOURS 1 // resincronización automática cada N horas
#define DEFAULT_TZ "EST5" // Bogotá (-5 sin DST)
/* ========= ESTADO ========= */
static const char *TAG = "SNTP";
static bool s_time_synced = false;
/* ========= CALLBACK ========= */
static void SNTP_TimeSyncCallback(struct timeval *tv)
{
s_time_synced = true;
time_t now;
struct tm timeinfo;
char buf[64];
time(&now);
gmtime_r(&now, &timeinfo);
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &timeinfo);
ESP_LOGI(TAG, "Tiempo sincronizado: %s (UTC)", buf);
}
/* ========= API ========= */
void time_ntp_init(void)
{
ESP_LOGI(TAG, "Inicializando SNTP...");
esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(
3,
ESP_SNTP_SERVER_LIST("pool.ntp.org", "co.pool.ntp.org", "south-america.pool.ntp.org"));
config.sync_cb = SNTP_TimeSyncCallback;
config.smooth_sync = true;
esp_netif_sntp_init(&config);
// Configura resincronización automática
esp_sntp_set_sync_interval(NTP_RESYNC_INTERVAL_HOURS * 3600 * 1000);
// Zona horaria global
setenv("TZ", DEFAULT_TZ, 1);
tzset();
}
bool time_ntp_wait_for_sync(void)
{
int retry = 0;
while (!s_time_synced && retry < SNTP_MAX_RETRY)
{
int backoff = SNTP_BACKOFF_BASE_MS << retry;
ESP_LOGW(TAG, "Esperando sincronización... intento %d/%d (espera %d ms)", retry + 1, SNTP_MAX_RETRY, backoff);
vTaskDelay(pdMS_TO_TICKS(backoff));
retry++;
}
return s_time_synced;
}
bool time_ntp_is_synced(void)
{
return s_time_synced;
}
void time_ntp_print(void)
{
time_t now;
struct tm timeinfo;
char buf[64];
time(&now);
// UTC
gmtime_r(&now, &timeinfo);
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &timeinfo);
ESP_LOGI(TAG, "UTC: %s", buf);
// Local
localtime_r(&now, &timeinfo);
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S (%Z)", &timeinfo);
ESP_LOGI(TAG, "Local: %s", buf);
}
/* ========= TASK ========= */
void time_ntp_task(void *pvParameters)
{
time_ntp_init();
if (!time_ntp_wait_for_sync())
{
ESP_LOGE(TAG, "No se pudo sincronizar con servidores NTP");
vTaskDelete(NULL);
}
// Loop infinito: imprime cada 10s
while (1)
{
time_ntp_print();
vTaskDelay(pdMS_TO_TICKS(10000)); // cada 10s
}
}