diff --git a/src/main/CMakeLists.txt b/src/main/CMakeLists.txt index 99f6ef2..5ec8745 100644 --- a/src/main/CMakeLists.txt +++ b/src/main/CMakeLists.txt @@ -2,4 +2,5 @@ idf_component_register(SRCS "app_main.c" "network_mngr.c" "gpio.c" "counter.c" + "timesync.c" INCLUDE_DIRS ".") diff --git a/src/main/app_main.c b/src/main/app_main.c index bb9c0f1..78707d7 100644 --- a/src/main/app_main.c +++ b/src/main/app_main.c @@ -15,6 +15,7 @@ #include "gpio.h" #include "counter.h" +#include "timesync.h" @@ -36,9 +37,13 @@ void deviceInit() { void app_main(void) { deviceInit(); + + // it is important to initialize the counter before the gpios counterInit(); + gpioInit(); networkInit(isGpioForceProv()); + timesyncInit(); /* Start main application now */ while (1) { diff --git a/src/main/counter.c b/src/main/counter.c index b18c59c..7819109 100644 --- a/src/main/counter.c +++ b/src/main/counter.c @@ -1,6 +1,7 @@ #include #include "counter.h" +#include "timesync.h" #include #include @@ -33,7 +34,8 @@ static void counterZeroCrossingAveragerTask(void *arg) { if (currentCounterValue == QUEUE_MARKER) { if (counterCnt > 0) { uint32_t counterSecondAverage = ((uint32_t)(counterSum)) / ((uint32_t)(counterCnt)); - ESP_LOGI(TAG, "%u %u %u", (uint32_t)counterCnt, (uint32_t)counterSum, counterSecondAverage); + int ts = timesyncReady(); + ESP_LOGI(TAG, "%d %u %u %u", ts, (uint32_t)counterCnt, (uint32_t)counterSum, counterSecondAverage); } else { ESP_LOGW(TAG, "counterCnt is zero"); } diff --git a/src/main/timesync.c b/src/main/timesync.c new file mode 100644 index 0000000..cd67b55 --- /dev/null +++ b/src/main/timesync.c @@ -0,0 +1,29 @@ +#include "timesync.h>" +#include +#include +#include +#include +#include + +static const char *TAG = "ts"; + +static bool synchronized = false; + +void timesyncCallback(struct timeval *tv) { + ESP_LOGI(TAG, "time is synchronized now"); + synchronized = true; +} + +void timesyncInit() { + ESP_LOGI(TAG, "Initializiing SNTP"); + sntp_setoperatingmode(SNTP_OPMODE_POLL); + sntp_setservername(0, SNTP_SERVER); + sntp_set_time_sync_notification_cb(timesyncCallback); + sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED); + sntp_set_sync_interval(60*1000); // 1 minute + sntp_init(); +} + +bool timesyncReady() { + return synchronized; +} \ No newline at end of file diff --git a/src/main/timesync.h b/src/main/timesync.h new file mode 100644 index 0000000..7485911 --- /dev/null +++ b/src/main/timesync.h @@ -0,0 +1,16 @@ +#ifndef _TIMESYNC_H_ +#deifne _TIMESYNC_H_ + +#include + + +#define SNTP_SERVER "pool.ntp.org" + + +void timesyncInit(); +bool timesyncReady(); + +#endif // _TIMESYNC_H_ + + +