# Example: online Demonstrates `time_service` with **SNTP synchronization over WiFi**. The component initializes from the build timestamp, connects to WiFi using the ESP-IDF `protocol_examples_common` helper, then requests an SNTP sync explicitly. The sync result is delivered via a callback showing the exact time correction applied. A logging loop runs continuously, printing a human-readable timestamp every two seconds. --- ## What This Example Shows - Standard initialization sequence: NVS → netif → event loop → WiFi → `time_service_init()` - Using `time_service_sync_async()` to request SNTP sync after network is ready - Handling the sync callback — inspecting `success`, `delta_sec`, old and new timestamps - Continuous timestamp logging with `time_service_now_str()` before and after sync --- ## Expected Output ``` I (4121) online_example: WiFi connected I (4131) online_example: Initialized, origin=2 (build time baseline) I (6141) online_example: Time: 2026-04-14 16:21:17 +0500 I (8141) online_example: Time: 2026-04-14 16:21:19 +0500 I (14141) online_example: Time synced — jump: 3 sec (old=1776087799 new=1776087802) I (14141) online_example: Time: 2026-04-14 16:21:21 +0500 I (16141) online_example: Time: 2026-04-14 16:21:23 +0500 ``` The log shows timestamps running from build time before sync completes, then the jump notification, then corrected timestamps continuing seamlessly. --- ## Build and Flash ```bash cd examples/online idf.py build flash monitor ``` Configure your WiFi credentials before building: ```bash idf.py menuconfig # → Example Connection Configuration → WiFi SSID / Password ``` --- ## Configuration **Timezone offset** — defined at the top of `main.c`: ```c #define TIMEZONE_OFFSET_SEC (5 * 3600) // UTC+5 Pakistan Standard Time ``` **SNTP servers** — configurable via menuconfig: ```bash idf.py menuconfig # → Time Service Configuration → SNTP Server 0 / 1 / 2 ``` **SNTP timeout** — if sync fails consistently, increase the timeout: ```bash idf.py menuconfig # → Time Service Configuration → SNTP sync timeout ``` --- ## Why the 2-Second Delay Before Sync `example_connect()` returns as soon as an IP address is acquired, but DNS resolution may not be fully stable at that exact moment. The 2-second delay before `sync_async()` gives the network stack time to settle. If you see sync failures on first attempt, try increasing this delay or implement a retry. --- ## Dependencies This example uses `protocol_examples_common` from the ESP-IDF examples directory. It is available automatically when building within the ESP-IDF environment.
To create a project from this example, run:
idf.py create-project-from-example "embedblocks/time-service=1.0.3:online"