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
