6#include <pico/stdlib.h>
7#include <pico/cyw43_arch.h>
8#include "pico/aon_timer.h"
9#include <lwip/apps/sntp.h>
22#if defined(PICO_RP2040)
23#include "hardware/rtc.h"
28#ifndef PICO_HTTP_ENABLE_LITTLEFS
29#include "FreeRTOS_time.h"
44 sntp_setoperatingmode(SNTP_OPMODE_POLL);
45 sntp_setservername(0,
"pool.ntp.org");
52 printf(
"[Time Manager] Waiting for NTP time sync...\n");
56 while (waited < timeoutSeconds)
61 if(aon_timer_get_time(&ts)){
62 if (ts.tv_sec > 1735689600)
64 printf(
"[Time Manager] NTP time acquired successfuly\n");
69 printf(
"[Time Manager] System time epoch is invalid: %ld\n", ts.tv_sec);
75 printf(
"[Time Manager] Failed to get system time from AON timer.\n");
79 vTaskDelay(pdMS_TO_TICKS(1000));
85 printf(
"[Time Manager] NTP sync failed and no valid time source available.\n");
91 printf(
"[Time Manager] NTP sync failed, but AON timer is running — time still valid.\n");
98 printf(
"[TimeManager] Setting system time from epoch: %u\n", epoch);
107 printf(
"[TimeManager] System time set to: %s\n", ctime(&ts.tv_sec));
123 printf(
"[TimeManager] Invalid timespec provided.\n");
128 if (!aon_timer_is_running()){
129 printf(
"[TimeManager] AON timer is not running, starting it...\n");
134 printf(
"[TimeManager] AON timer is running, syncing time...\n");
135 aon_timer_set_time(ts);
137 timespec currentTime;
138 if(!aon_timer_get_time(¤tTime))
140 printf(
"[TimeManager] Failed to get system time from AON timer.\n");
157 printf(
"[TimeManager] Timezone set to UTC %+d:00 (%s)\n",
158 offsetSeconds / 3600, stdName);
166 const std::string &body = res.
getBody();
169 printf(
"[TimeManager] Failed to get IP geolocation.\n");
174 size_t tzPos = body.find(
"\"timezone\":\"");
175 if (tzPos != std::string::npos)
177 tzPos += strlen(
"\"timezone\":\"");
178 size_t end = body.find(
'"', tzPos);
179 if (end != std::string::npos)
181 tzName = body.substr(tzPos, end - tzPos);
190 size_t latPos = body.find(
"\"lat\":");
191 size_t lonPos = body.find(
"\"lon\":");
192 if (latPos == std::string::npos || lonPos == std::string::npos)
194 printf(
"[TimeManager] lat/lon not found. Using defaults.\n");
200 lat = std::stof(body.substr(latPos + 6));
201 lon = std::stof(body.substr(lonPos + 6));
208 snprintf(url,
sizeof(url),
209 "http://api.open-meteo.com/v1/forecast?latitude=%.4f&longitude=%.4f¤t_weather=true&timezone=auto",
215 const std::string &body = res.
getBody();
216 TRACE(
"[TimeManager] Open-Meteo response: %s\n", body.c_str());
220 printf(
"[TimeManager] Open-Meteo response is empty.\n");
225 size_t offsetPos = body.find(
"\"utc_offset_seconds\":");
226 int offsetSeconds = 0;
227 if (offsetPos != std::string::npos)
229 offsetPos += strlen(
"\"utc_offset_seconds\":");
230 size_t end = body.find(
',', offsetPos);
231 if (end == std::string::npos)
233 offsetSeconds = std::stoi(body.substr(offsetPos, end - offsetPos));
235 TRACE(
"[TimeManager] Timezone: %s, UTC offset: %d sec\n", tzName.c_str(), offsetSeconds);
241 std::string tzName =
"UTC";
242 float lat = 0.0f, lon = 0.0f;
246 printf(
"[TimeManager] Location detected: lat=%.4f, lon=%.4f\n", lat, lon);
251 printf(
"[TimeManager] Could not determine location. Using default UTC.\n");
266 char timeBuf[16] = {0};
267 strftime(timeBuf,
sizeof(timeBuf),
"%H:%M:%S", &tmBuf);
271 char formatted[48] = {0};
272 snprintf(formatted,
sizeof(formatted),
"[%s %s]", timeBuf, zone);
273 return std::string(formatted);
Macro-based debug trace system with optional SD file logging.
#define TRACE_INIT(MODULE_NAME)
Declare trace usage in a source file for a given module.
#define TRACE(...)
Default trace (INFO level).
Event pub/sub manager for embedded applications using FreeRTOS.
struct tm * gmtime_r(const time_t *pxTime, struct tm *tmStruct)
Defines the HttpRequest class for handling HTTP requests: headers, method, path, query string,...
HTTP HttpResponse class for managing status, headers, body, and streaming support.
constexpr uint32_t eventMask(Enum e)
Helper function to create an event mask from an enum value.
Time utility functions for the Pico platform (RP2040/RP2350).
void sntp_set_system_time(uint32_t sec)
static constexpr std::uintptr_t getTypeKey()
Forward declaration for potential routing needs.
HttpResponse get()
Send a GETPOST/PUT/DEL request.
Represents an HTTP response object.
int getStatusCode() const
Get the response status code.
const std::string & getBody() const
Get the response body.
static time_t now()
Get the current epoch time using platform RTC or AON.
bool getLocationFromIp(std::string &tzName, float &lat, float &lon)
int timezoneOffsetSeconds
void applyFixedTimezoneOffset(int offsetSeconds, const char *stdName="UTC", const char *dstName="UTC")
Apply a fixed timezone offset.
void setTime(timespec *ts)
Set the system time using a timespec structure.
void detectAndApplyTimezone()
Detect and apply the timezone based on the current location or IP address.
void fetchAndApplyTimezoneFromOpenMeteo(float lat, float lon, const std::string &tzName)
Fetch and apply the timezone from OpenMeteo API using latitude and longitude.
void onNetworkReady()
hanles network ready event.
void setTimeFromEpoch(uint32_t epochSeconds)
Set the system time from an epoch timestamp (e.g. from SNTP)
void onHttpServerStarted()
bool syncTimeWithNtp(int timeoutSeconds=20)
Initialize the time manager.
std::string formatTimeWithZone(time_t rawTime=0) const
std::string currentTimeForTrace() const
Get the current time formatted as a string.
void start()
Start the time manager.
Delegates to user or system configuration.
#define NTP_TIMEOUT_SECONDS
This setting defines the retry timeout The default SNTP retry time is 15 seconds, we set it to 5 in l...
#define DETECT_LOCAL_TIMEZONE
Represents a framework event, optionally carrying payload data.
Notification notification
Notification identifier (system or user)