/* LwIP SNTP example
This example code is in the Public Domain (or
CC0 licensed, at your option.)
Unless required by applicable law or agreed
to in writing, this
software is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or
implied.
*/
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "protocol_examples_common.h"
#include "esp_sntp.h"
static const char *TAG = "example";
void time_sync_notification_cb(struct timeval *tv)
{
ESP_LOGI(TAG,
"Notification of a time synchronization event");
// update 'now'
variable with current time
time_t now;
time(&now);
int timezone =
9;
now = now +
(timezone*60*60);
struct tm
timeinfo;
localtime_r(&now, &timeinfo);
char
strftime_buf[64];
strftime(strftime_buf, sizeof(strftime_buf), "%c",
&timeinfo);
ESP_LOGI(TAG,
"The current date/time is: %s", strftime_buf);
}
static void initialize_sntp(void)
{
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, CONFIG_SNTP_TIME_SERVER);
sntp_set_time_sync_notification_cb(time_sync_notification_cb);
uint32_t
interval = sntp_get_sync_interval();
ESP_LOGI(TAG,
"interval=%d", interval);
//sntp_set_sync_interval(60000);
sntp_init();
}
static void obtain_time(void)
{
ESP_LOGI(TAG,
"initialize_sntp");
initialize_sntp();
// wait for
time to be set
int retry = 0;
const int
retry_count = 15;
while
(sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET
&& ++retry < retry_count) {
ESP_LOGI(TAG, "Waiting for system time to be set...
(%d/%d)", retry, retry_count);
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}
void app_main(void)
{
ESP_ERROR_CHECK( nvs_flash_init() );
ESP_ERROR_CHECK( esp_netif_init() );
ESP_ERROR_CHECK( esp_event_loop_create_default() );
ESP_ERROR_CHECK( example_connect() );
time_t now;
time(&now);
struct tm
timeinfo;
localtime_r(&now, &timeinfo);
char
strftime_buf[64];
strftime(strftime_buf, sizeof(strftime_buf), "%c",
&timeinfo);
ESP_LOGI(TAG,
"The first date/time is: %s", strftime_buf);
obtain_time();
}
|