summaryrefslogtreecommitdiff
path: root/components/sntp/time_sntp.c
blob: 90cc1d1dc85f0089137dda8762b0cda58ad11370 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "time_sntp.h"

void set_tz(char* tz){
    setenv("TZ", tz, 1); // Zürich tz
    tzset();
}

void obtain_time(char t[4])
{
    time_t now;
    struct tm timeinfo;
    time(&now);  // Get the current time
    localtime_r(&now, &timeinfo);
    strftime(t, sizeof(t)+sizeof(char), "%H%M", &timeinfo); // Seems to require +1 char size to do it correctly
    ESP_LOGI(SNTP_TAG, "The local time is: %s", t);
}

void sync_time(void)
{
    ESP_ERROR_CHECK(esp_netif_init());

    ESP_LOGI(SNTP_TAG, "Initializing and starting SNTP");
    /*
     * This is the basic default config with one server and starting the service
     */
    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(CONFIG_SNTP_TIME_SERVER);

    esp_netif_sntp_init(&config);
    // wait for time to be set
    int retry = 0;
    const int retry_count = 15;
    while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count) {
        ESP_LOGI(SNTP_TAG, "Waiting for system time to be synched... (%d/%d)", retry, retry_count);
    }
    esp_netif_sntp_deinit();
}