From 129a2650c22915bc789b6bdbc9d360bd97059e2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Gassmann?= Date: Sat, 28 Sep 2024 18:05:02 +0200 Subject: [+] WiFi with dpp on first setup + SNTP --- components/sntp/CMakeLists.txt | 3 +++ components/sntp/time_sntp.c | 36 ++++++++++++++++++++++++++++++++++++ components/sntp/time_sntp.h | 18 ++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 components/sntp/CMakeLists.txt create mode 100644 components/sntp/time_sntp.c create mode 100644 components/sntp/time_sntp.h (limited to 'components/sntp') diff --git a/components/sntp/CMakeLists.txt b/components/sntp/CMakeLists.txt new file mode 100644 index 0000000..fc734f5 --- /dev/null +++ b/components/sntp/CMakeLists.txt @@ -0,0 +1,3 @@ +idf_component_register(SRCS "time_sntp.c" + INCLUDE_DIRS "." + PRIV_REQUIRES esp_system esp_netif esp_event) diff --git a/components/sntp/time_sntp.c b/components/sntp/time_sntp.c new file mode 100644 index 0000000..90cc1d1 --- /dev/null +++ b/components/sntp/time_sntp.c @@ -0,0 +1,36 @@ +#include "time_sntp.h" + +void set_tz(char* tz){ + setenv("TZ", tz, 1); // Zürich tz + tzset(); +} + +void obtain_time(char t[4]) +{ + time_t now; + struct tm timeinfo; + time(&now); // Get the current time + localtime_r(&now, &timeinfo); + strftime(t, sizeof(t)+sizeof(char), "%H%M", &timeinfo); // Seems to require +1 char size to do it correctly + ESP_LOGI(SNTP_TAG, "The local time is: %s", t); +} + +void sync_time(void) +{ + ESP_ERROR_CHECK(esp_netif_init()); + + ESP_LOGI(SNTP_TAG, "Initializing and starting SNTP"); + /* + * This is the basic default config with one server and starting the service + */ + esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(CONFIG_SNTP_TIME_SERVER); + + esp_netif_sntp_init(&config); + // wait for time to be set + int retry = 0; + const int retry_count = 15; + while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count) { + ESP_LOGI(SNTP_TAG, "Waiting for system time to be synched... (%d/%d)", retry, retry_count); + } + esp_netif_sntp_deinit(); +} diff --git a/components/sntp/time_sntp.h b/components/sntp/time_sntp.h new file mode 100644 index 0000000..a8a894e --- /dev/null +++ b/components/sntp/time_sntp.h @@ -0,0 +1,18 @@ +#ifndef SNTP_H +#define SNTP_H + +#include +#include +#include "esp_system.h" +#include "esp_event.h" +#include "esp_log.h" +#include "esp_netif.h" +#include "esp_netif_sntp.h" +#include "esp_sntp.h" + +static const char *SNTP_TAG = "SNTP"; + +void set_tz(char* tz); +void obtain_time(char t[4]); +void sync_time(void); +#endif \ No newline at end of file -- cgit v1.2.3