diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 1144f0d..3f6c5fd 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -2,6 +2,7 @@ set(SOURCES ws2812.cpp + ntp_client.cpp abfall.cpp ) diff --git a/src/abfall.cpp b/src/abfall.cpp index e861930..af10bcd 100644 --- a/src/abfall.cpp +++ b/src/abfall.cpp @@ -11,8 +11,8 @@ #include "pico/util/datetime.h" #include "lwip/apps/http_client.h" -#include "lwip/apps/sntp.h" +#include "ntp_client.h" #include "ws2812.h" using std::string; @@ -97,22 +97,7 @@ err_t body_callback(void *arg, struct altcp_pcb *conn, struct pbuf *p, err_t err return ERR_OK; } -// Called by lwip sntp in order to set the time -extern "C" void set_system_time(u32_t sec) { - time_t epoch = sec; - struct tm *utc = gmtime(&epoch); - datetime_t datetime; - datetime.year = utc->tm_year + 1900; - datetime.month = utc->tm_mon + 1; - datetime.day = utc->tm_mday; - datetime.hour = utc->tm_hour; - datetime.min = utc->tm_min; - datetime.sec = utc->tm_sec; - datetime.dotw = utc->tm_wday; - if (rtc_set_datetime(&datetime) == true) { - printf("RTC successfully set.\n"); - } -} + int main() { const string ssid{"Apis cerana"}; @@ -147,13 +132,7 @@ int main() { &settings, body_callback, nullptr, nullptr); // printf("Status %d\n", err); - sntp_setoperatingmode(SNTP_OPMODE_POLL); - sntp_init(); - - // It takes some time for the system to set the RTC. Wait, until the RTC runs properly. - while (!rtc_running()) { - sleep_ms(100); - } + NtpClient::setDateTime(); char datetime_buf[256]; char *datetime_str = &datetime_buf[0]; diff --git a/src/ntp_client.cpp b/src/ntp_client.cpp new file mode 100644 index 0000000..c6175db --- /dev/null +++ b/src/ntp_client.cpp @@ -0,0 +1,33 @@ +#include "ntp_client.h" + +#include "hardware/rtc.h" + +#include "pico/util/datetime.h" + + +// Called by lwip sntp in order to set the time +void set_system_time(u32_t sec) { + time_t epoch = sec; + struct tm *utc = gmtime(&epoch); + datetime_t datetime; + datetime.year = utc->tm_year + 1900; + datetime.month = utc->tm_mon + 1; + datetime.day = utc->tm_mday; + datetime.hour = utc->tm_hour; + datetime.min = utc->tm_min; + datetime.sec = utc->tm_sec; + datetime.dotw = utc->tm_wday; + if (rtc_set_datetime(&datetime) == true) { + printf("RTC successfully set.\n"); + } +} + +void NtpClient::setDateTime() { + sntp_setoperatingmode(SNTP_OPMODE_POLL); + sntp_init(); + + // It takes some time for the system to set the RTC. Wait, until the RTC runs properly. + while (!rtc_running()) { + sleep_ms(500); + } +} \ No newline at end of file diff --git a/src/ntp_client.h b/src/ntp_client.h new file mode 100644 index 0000000..3b9e94c --- /dev/null +++ b/src/ntp_client.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +#include "pico/stdlib.h" + +#include "lwip/apps/sntp.h" + +extern "C" void set_system_time(u32_t sec); + +class NtpClient { + public: + static void setDateTime(); + + private: + NtpClient() {} // Disallow creating an instance of this object +}; \ No newline at end of file