Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit af84f40

Browse files
committed
Merge branch 'feature/refactor_lwip_sntp_example' into 'master'
refactor(sntp): add lwip sntp example See merge request sdk/ESP8266_RTOS_SDK!496
2 parents c4f2a58 + 6e359c3 commit af84f40

File tree

5 files changed

+233
-0
lines changed

5 files changed

+233
-0
lines changed

examples/protocols/sntp/Makefile

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#
2+
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
3+
# project subdirectory.
4+
#
5+
6+
PROJECT_NAME := sntp
7+
8+
include $(IDF_PATH)/make/project.mk
9+

examples/protocols/sntp/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Example: using LwIP SNTP module and time functions
2+
3+
This example demonstrates the use of LwIP SNTP module to obtain time from Internet servers. See the README.md file in the upper level 'examples' directory for more information about examples.
4+
5+
## Obtaining time using LwIP SNTP module
6+
7+
ESP8266 connects to WiFi and obtains time using SNTP.
8+
See `initialize_sntp` function for details.
9+
10+
## Working with time
11+
12+
To get current time, [`gettimeofday`](http://man7.org/linux/man-pages/man2/gettimeofday.2.html) function may be used. Additionally the following [standard C library functions](https://en.cppreference.com/w/cpp/header/ctime) can be used to obtain time and manipulate it:
13+
14+
gettimeofday
15+
time
16+
asctime
17+
clock
18+
ctime
19+
difftime
20+
gmtime
21+
localtime
22+
mktime
23+
strftime
24+
25+
To set time, [`settimeofday`](http://man7.org/linux/man-pages/man2/settimeofday.2.html) POSIX function can be used. It is used internally in LwIP SNTP library to set current time when response from NTP server is received.
26+
27+
## Timezones
28+
29+
To set local timezone, use [`setenv`](http://man7.org/linux/man-pages/man3/setenv.3.html) and [`tzset`](http://man7.org/linux/man-pages/man3/tzset.3.html) POSIX functions. First, call `setenv` to set `TZ` environment variable to the correct value depending on device location. Format of the time string is described in [libc documentation](https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html). Next, call `tzset` to update C library runtime data for the new time zone. Once these steps are done, `localtime` function will return correct local time, taking time zone offset and daylight saving time into account.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
menu "Example Configuration"
2+
3+
config WIFI_SSID
4+
string "WiFi SSID"
5+
default "myssid"
6+
help
7+
SSID (network name) for the example to connect to.
8+
9+
config WIFI_PASSWORD
10+
string "WiFi Password"
11+
default "mypassword"
12+
help
13+
WiFi password (WPA or WPA2) for the example to use.
14+
15+
Can be left blank if the network has no security set.
16+
17+
endmenu
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#
2+
# "main" pseudo-component makefile.
3+
#
4+
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
/* LwIP SNTP example
2+
3+
This example code is in the Public Domain (or CC0 licensed, at your option.)
4+
5+
Unless required by applicable law or agreed to in writing, this
6+
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7+
CONDITIONS OF ANY KIND, either express or implied.
8+
*/
9+
#include <stdlib.h>
10+
#include <string.h>
11+
#include <time.h>
12+
13+
#include "freertos/FreeRTOS.h"
14+
#include "freertos/task.h"
15+
#include "freertos/event_groups.h"
16+
17+
#include "esp_system.h"
18+
#include "esp_wifi.h"
19+
#include "esp_event_loop.h"
20+
#include "esp_log.h"
21+
22+
#include "nvs_flash.h"
23+
24+
#include "lwip/apps/sntp.h"
25+
26+
/* The examples use simple WiFi configuration that you can set via
27+
'make menuconfig'.
28+
29+
If you'd rather not, just change the below entries to strings with
30+
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
31+
*/
32+
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
33+
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
34+
35+
/* FreeRTOS event group to signal when we are connected & ready to make a request */
36+
static EventGroupHandle_t wifi_event_group;
37+
38+
/* The event group allows multiple bits for each event,
39+
but we only care about one event - are we connected
40+
to the AP with an IP? */
41+
const int CONNECTED_BIT = BIT0;
42+
43+
static const char *TAG = "sntp_example";
44+
45+
static void initialize_sntp(void)
46+
{
47+
ESP_LOGI(TAG, "Initializing SNTP");
48+
sntp_setoperatingmode(SNTP_OPMODE_POLL);
49+
sntp_setservername(0, "pool.ntp.org");
50+
sntp_init();
51+
}
52+
53+
static void obtain_time(void)
54+
{
55+
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
56+
false, true, portMAX_DELAY);
57+
initialize_sntp();
58+
59+
// wait for time to be set
60+
time_t now = 0;
61+
struct tm timeinfo = { 0 };
62+
int retry = 0;
63+
const int retry_count = 10;
64+
65+
while (timeinfo.tm_year < (2016 - 1900) && ++retry < retry_count) {
66+
ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
67+
vTaskDelay(2000 / portTICK_PERIOD_MS);
68+
time(&now);
69+
localtime_r(&now, &timeinfo);
70+
}
71+
}
72+
73+
static esp_err_t event_handler(void *ctx, system_event_t *event)
74+
{
75+
switch (event->event_id) {
76+
case SYSTEM_EVENT_STA_START:
77+
esp_wifi_connect();
78+
break;
79+
80+
case SYSTEM_EVENT_STA_GOT_IP:
81+
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
82+
break;
83+
84+
case SYSTEM_EVENT_STA_DISCONNECTED:
85+
/* This is a workaround as ESP8266 WiFi libs don't currently
86+
auto-reassociate. */
87+
esp_wifi_connect();
88+
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
89+
break;
90+
91+
default:
92+
break;
93+
}
94+
95+
return ESP_OK;
96+
}
97+
98+
static void sntp_example_task(void *arg)
99+
{
100+
time_t now;
101+
struct tm timeinfo;
102+
char strftime_buf[64];
103+
104+
time(&now);
105+
localtime_r(&now, &timeinfo);
106+
107+
// Is time set? If not, tm_year will be (1970 - 1900).
108+
if (timeinfo.tm_year < (2016 - 1900)) {
109+
ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
110+
obtain_time();
111+
}
112+
113+
// Set timezone to Eastern Standard Time and print local time
114+
// setenv("TZ", "EST5EDT,M3.2.0/2,M11.1.0", 1);
115+
// tzset();
116+
117+
// Set timezone to China Standard Time
118+
setenv("TZ", "CST-8", 1);
119+
tzset();
120+
121+
while (1) {
122+
// update 'now' variable with current time
123+
time(&now);
124+
localtime_r(&now, &timeinfo);
125+
126+
if (timeinfo.tm_year < (2016 - 1900)) {
127+
ESP_LOGE(TAG, "The current date/time error");
128+
} else {
129+
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
130+
ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
131+
}
132+
133+
ESP_LOGI(TAG, "Free heap size: %d\n", esp_get_free_heap_size());
134+
vTaskDelay(1000 / portTICK_RATE_MS);
135+
}
136+
}
137+
138+
static void initialise_wifi(void)
139+
{
140+
tcpip_adapter_init();
141+
wifi_event_group = xEventGroupCreate();
142+
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
143+
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
144+
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
145+
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
146+
wifi_config_t wifi_config = {
147+
.sta = {
148+
.ssid = EXAMPLE_WIFI_SSID,
149+
.password = EXAMPLE_WIFI_PASS,
150+
},
151+
};
152+
ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
153+
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
154+
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
155+
ESP_ERROR_CHECK(esp_wifi_start());
156+
}
157+
158+
void app_main()
159+
{
160+
//Initialize NVS
161+
esp_err_t ret = nvs_flash_init();
162+
163+
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
164+
ESP_ERROR_CHECK(nvs_flash_erase());
165+
ret = nvs_flash_init();
166+
}
167+
168+
ESP_ERROR_CHECK(ret);
169+
170+
initialise_wifi();
171+
172+
// SNTP service uses LwIP, please allocate large stack space.
173+
xTaskCreate(sntp_example_task, "sntp_example_task", 2048, NULL, 10, NULL);
174+
}

0 commit comments

Comments
 (0)