This module provides the lwIP SNTP integration documentation.
The lwIP SNTP library can be used to synchronize system time in a network by exchanging packets regularly. The documentation for the library can be found at the following link: lwIPSNTP.
This is a basic example of minimal use of the lwIP SNTP APIs in an application.
#include <time.h>
#include "lwip/timeouts.h"
#include "lwip/ip_addr.h"
#include "lwip/init.h"
#include "lwip/apps/sntp.h"
#define LWIP_SNTP_EXAMPLE_SECONDS_PER_HOUR (60 * 60)
#define LWIP_SNTP_EXAMPLE_TIMEZONE_UTC_PLUS (7) // This may need to be updated for your timezone
#define LWIP_SNTP_EXAMPLE_RETRY_CONNECT (5U)
#define LWIP_SNTP_EXAMPLE_SERVER_NAME "time1.google.com"
#define LWIP_SNTP_EXAMPLE_SERVER_ADDRESS "216.239.35.0"
void lwip_sntp_example_set_time(u32_t sec);
uint8_t g_lwip_sntp_example_count;
bool g_lwip_sntp_example_flag;
void lwip_sntp_example () {
struct netif netif;
ip_addr_t ipaddr;
ip_addr_t netmask;
ip_addr_t gw;
lwip_init();
IP4_ADDR(&ipaddr, 192, 168, 10, 4);
IP4_ADDR(&netmask, 255, 255, 255, 0);
IP4_ADDR(&gw, 192, 168, 10, 1);
netif_add(&netif, &ipaddr, &netmask, &gw, &g_lwip_ether0_instance,
rm_lwip_ether_init, netif_input);
netif_set_default(&netif);
netif_set_up(&netif);
netif_set_link_up(&netif);
sntp_setoperatingmode(SNTP_OPMODE_POLL);
#if SNTP_SERVER_DNS && LWIP_DNS
sntp_setservername(0, LWIP_SNTP_EXAMPLE_SERVER_NAME);
#else
ip_addr_t sntp_ip;
ipaddr_aton(LWIP_SNTP_EXAMPLE_SERVER_ADDRESS, &sntp_ip);
sntp_setserver(0, &sntp_ip);
#endif
sntp_init();
while (true)
{
sys_check_timeouts();
if (true == g_lwip_sntp_example_flag)
{
g_lwip_sntp_example_count++;
if (LWIP_SNTP_EXAMPLE_RETRY_CONNECT == g_lwip_sntp_example_count)
{
break;
}
}
g_lwip_sntp_example_flag = false;
}
if (sntp_enabled())
{
sntp_stop();
}
}
void lwip_sntp_example_set_time (u32_t sec)
{
g_lwip_sntp_example_flag = true;
sec += (LWIP_SNTP_EXAMPLE_TIMEZONE_UTC_PLUS * LWIP_SNTP_EXAMPLE_SECONDS_PER_HOUR);
time_t time = (time_t) sec;
struct tm * timeinfo;
timeinfo = localtime(&time);
char strftime_buf[32];
strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", timeinfo);
printf("Current UTC+%d time is: %s\n", LWIP_SNTP_EXAMPLE_TIMEZONE_UTC_PLUS, strftime_buf);
}