docs: Add System time chapter and for sntp a description about using CONFIG_LWIP_SNTP_UPDATE_DELAY option

Closes: https://github.com/espressif/esp-idf/issues/4386
Closes: IDFGH-2237
Closes: IDF-1199
This commit is contained in:
KonstantinKondrashov 2019-11-25 15:03:38 +08:00 committed by Angus Gratton
parent 1fd7f21d8c
commit c23549c04f
6 changed files with 142 additions and 1 deletions

View file

@ -138,6 +138,8 @@ INPUT = \
../../components/mqtt/esp-mqtt/include/mqtt_client.h \
## ICMP-ECHO
../../components/lwip/include/apps/ping/ping_sock.h \
## SNTP
../../components/lwip/include/apps/sntp/sntp.h \
## mDNS
../../components/mdns/include/mdns.h \
../../components/esp_http_client/include/esp_http_client.h \

View file

@ -17,7 +17,7 @@ Adapted APIs
Some common lwIP "app" APIs are supported indirectly by ESP-IDF:
- DHCP Server & Client are supported indirectly via the :doc:`/api-reference/network/esp_netif` functionality
- Simple Network Time Protocol (SNTP) is supported via the :component_file:`lwip/include/apps/esp_sntp.h` functions (see also :example:`protocols/sntp`)
- Simple Network Time Protocol (SNTP) is supported via the :component_file:`lwip/include/apps/sntp/sntp.h` :component_file:`lwip/lwip/src/inlude/lwip/apps/sntp.h` functions (see also :ref:`system-time-sntp-sync`)
- ICMP Ping is supported using a variation on the lwIP ping API. See :doc:`/api-reference/protocols/icmp_echo`.
- NetBIOS lookup is available using the standard lwIP API. :example:`protocols/http_server/restful_server` has an option to demonstrate using NetBIOS to look up a host on the LAN.
- mDNS uses a different implementation to the lwIP default mDNS (see :doc:`/api-reference/protocols/mdns`), but lwIP can look up mDNS hosts using standard APIs such as ``gethostbyname()`` and the convention ``hostname.local``, provided the :ref:`CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES` setting is enabled.

View file

@ -27,6 +27,7 @@ System API
Power Management <power_management>
Sleep Modes <sleep_modes>
Watchdogs <wdts>
System Time <system_time>
Code examples for this API section are provided in the :example:`system` directory of ESP-IDF examples.

View file

@ -0,0 +1,133 @@
System Time
===========
Overview
--------
System time can be kept using either one time source or two time sources simultaneously. The choice depends on the application purpose and accuracy requirements for system time.
There are the following two time sources:
- **RTC timer**: Allows keeping the system time during any resets and sleep modes, only the power-up reset leads to resetting the RTC timer. The frequency deviation depends on an `RTC Clock Source`_ and affects accuracy only in sleep modes, in which case the time will be measured at 6.6667 us resolution.
- **High-resolution timer**: Not available during any reset and sleep modes. The reason for using this timer is to achieve greater accuracy. It uses the APB_CLK clock source (typically 80 MHz), which has a frequency deviation of less than ±10 ppm. Time will be measured at 1 us resolution.
The settings for the system time source are as follows:
- RTC and high-resolution timer (default)
- RTC
- High-resolution timer
- None
It is recommended to stick to the default setting which provides maximum accuracy. If you want to choose a different timer, configure :ref:`CONFIG_ESP32_TIME_SYSCALL` in project configuration.
RTC Clock Source
----------------
The RTC timer has the following clock sources:
- ``Internal 150kHz RC oscillator`` (default): Features lowest deep sleep current consumption and no dependence on any external components. However, as frequency stability is affected by temperature fluctuations, time may drift in both Deep and Light sleep modes.
- ``External 32kHz crystal``: Requires a 32kHz crystal to be connected to the 32K_XP and 32K_NP pins. Provides better frequency stability at the expense of slightly higher (by 1 uA) Deep sleep current consumption.
- ``External 32kHz oscillator at 32K_XP pin``: Allows using 32kHz clock generated by an external circuit. The external clock signal must be connected to the 32K_XP pin. The amplitude should be less than 1.2 V for sine wave signal and less than 1 V for square wave signal. Common mode voltage should be in the range of 0.1 < Vcm < 0.5xVamp, where Vamp is signal amplitude. Additionally, a 1 nF capacitor must be placed between the 32K_XN pin and ground. In this case, the 32K_XN pin cannot be used as a GPIO pin.
- ``Internal 8.5MHz oscillator, divided by 256 (~33kHz)``. Provides better frequency stability than the ``internal 150kHz RC oscillator`` at the expense of higher (by 5 uA) deep sleep current consumption. It also does not require external components.
The choice depends on your requirements for system time accuracy and power consumption in sleep modes. To modify the RTC clock source, set :ref:`CONFIG_ESP32_RTC_CLK_SRC` in project configuration.
More details on wiring requirements for the ``External 32kHz crystal`` and ``External 32kHz oscillator at 32K_XP pin`` sources can be found in Section 2.1.4 *Crystal Oscillator* of `Hardware Design Guidelines <https://www.espressif.com/sites/default/files/documentation/esp32_hardware_design_guidelines_en.pdf#page=10>`_.
Get Current Time
----------------
To get the current time, use the POSIX function ``gettimeofday()``. Additionally, you can use the following standard C library functions to obtain time and manipulate it:
.. code-block:: bash
gettimeofday
time
asctime
clock
ctime
difftime
gmtime
localtime
mktime
strftime
adjtime*
\* To stop smooth time adjustment and update the current time immediately, use the POSIX function ``settimeofday()``.
If you need to obtain time with one second resolution, use the following method:
.. code-block:: c
time_t now;
char strftime_buf[64];
struct tm timeinfo;
time(&now);
// Set timezone to China Standard Time
setenv("TZ", "CST-8", 1);
tzset();
localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
If you need to obtain time with one microsecond resolution, use the code snippet below:
.. code-block:: c
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
int64_t time_us = (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec;
.. _system-time-sntp-sync:
SNTP Time Synchronization
-------------------------
To set the current time, you can use the POSIX functions ``settimeofday()`` and ``adjtime()``. They are used internally in the lwIP SNTP library to set current time when a response from the NTP server is received. These functions can also be used separately from the lwIP SNTP library.
A function to use inside the lwIP SNTP library depends on a sync mode for system time. Use the function :cpp:func:`sntp_set_sync_mode` to set one of the following sync modes:
- ``SNTP_SYNC_MODE_IMMED`` (default) updates system time immediately upon receiving a response from the SNTP server after using ``settimeofday()``.
- ``SNTP_SYNC_MODE_SMOOTH`` updates time smoothly by gradually reducing time error using the funcion ``adjtime()``. If the difference between the SNTP response time and system time is more than 35 minutes, update system time immediately by using ``settimeofday()``.
The lwIP SNTP library has API functions for setting a callback function for a certain event. You might need the following functions:
- ``sntp_set_time_sync_notification_cb()`` - use it for setting a callback function that will notify of the time synchronization process
- ``sntp_get_sync_status()`` and ``sntp_set_sync_status()`` - use it to get/set time synchronization status
To start synchronization via SNTP, just call the following three functions.
.. code-block:: c
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, "pool.ntp.org");
sntp_init();
An application with this initialization code will periodically synchronize the time. The time synchronization period is determined by :envvar:`CONFIG_LWIP_SNTP_UPDATE_DELAY` (default value is one hour). To modify the variable, set :ref:`CONFIG_LWIP_SNTP_UPDATE_DELAY` in project configuration.
A code example that demonstrates the implementation of time synchronization based on the lwIP SNTP library is provided in :example:`protocols/sntp` directory.
Timezones
---------
To set local timezone, use the following POSIX functions:
1. Call ``setenv()`` to set the ``TZ`` environment variable to the correct value depending on the device location. The format of the time string is the same as described in the `GNU libc documentation <https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html>`_ (although the implementation is different).
2. Call ``tzset()`` to update C library runtime data for the new time zone.
Once these steps are completed, call the standard C library function ``localtime()``, and it will return correct local time taking into account the time zone offset and daylight saving time.
API Reference
-------------
.. include:: /_build/inc/sntp.inc

View file

@ -0,0 +1 @@
.. include:: ../../../en/api-reference/system/system_time.rst

View file

@ -8,6 +8,10 @@ Open the project configuration menu (`idf.py menuconfig`):
* Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu. See "Establishing Wi-Fi or Ethernet Connection" section in [examples/protocols/README.md](../README.md) for more details.
* Select one method to synchronize time out of the three available in `CONFIG_SNTP_TIME_SYNC_METHOD` (default `update time immediately when received`).
* The time synchronization period is defined by `CONFIG_LWIP_SNTP_UPDATE_DELAY`. This option allows you to set the time synchronization period (default is one hour). This option does not affect this example because after synchronization the program goes into deep sleep for 10 seconds. If you modify this example or use the code from this example, keep in mind that this option will trigger time synchronization. You can change it in `Component config-->LWIP-->SNTP-->Request interval to update time (ms)` menu.
* When using Make build system, set `Default serial port` under `Serial flasher config`.
## Obtaining time using LwIP SNTP module