Export boot timestamp, update docs and examples to use it

This commit is contained in:
cpq committed 2026-06-01 14:35:06 +01:00
1 parent 987075189d
commit 5ae35e3812
11 files changed
+177 -207

No files matched your search

+9 -30
View File
@@ -8,8 +8,6 @@
static const char *s_web_dir = "/";
static const char *s_http_addr = "http://0.0.0.0:8000";
static const char *s_https_addr = "https://0.0.0.0:8443";
static time_t s_boot_timestamp = 0;
static struct mg_connection *s_sntp_conn = NULL;
// Event handler for the listening HTTP/HTTPS connection.
static void wcb(struct mg_connection *c, int ev, void *ev_data) {
@@ -42,31 +40,6 @@ static void wcb(struct mg_connection *c, int ev, void *ev_data) {
}
}
// example system time()-like function
time_t ourtime(time_t *tp) {
time_t t = s_boot_timestamp + mg_millis() / 1000;
if (tp != NULL) *tp = t;
return t;
}
// SNTP callback. Modifies s_boot_timestamp, to make ourtime() correct
static void sfn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_SNTP_TIME) {
int64_t t = *(int64_t *) ev_data;
MG_INFO(("Got SNTP time: %lld ms from epoch", t));
s_boot_timestamp = (time_t) ((t - mg_millis()) / 1000);
} else if (ev == MG_EV_CLOSE) {
s_sntp_conn = NULL;
}
}
// Periodic timer syncs time via SNTP
static void timer_fn(void *arg) {
struct mg_mgr *mgr = (struct mg_mgr *) arg;
if (s_sntp_conn == NULL) s_sntp_conn = mg_sntp_connect(mgr, NULL, sfn, NULL);
if (s_boot_timestamp < 9999) mg_sntp_request(s_sntp_conn);
}
// Zephyr: Define a semaphore and network management callback to be able to wait
// until our IP address is ready. The main function will start and block on this
// semaphore until this event handler releases it when the network is ready
@@ -97,14 +70,20 @@ int main(int argc, char *argv[]) {
mg_http_listen(&mgr, s_http_addr, wcb, NULL);
mg_http_listen(&mgr, s_https_addr, wcb, NULL);
mg_timer_add(&mgr, 5000, MG_TIMER_REPEAT | MG_TIMER_RUN_NOW, timer_fn, &mgr);
// Start infinite event loop
MG_INFO(("Mongoose version : v%s", MG_VERSION));
MG_INFO(("Listening on : %s", s_http_addr));
MG_INFO(("Listening on : %s", s_https_addr));
MG_INFO(("Web root : [%s]", s_web_dir));
for (;;) mg_mgr_poll(&mgr, 1000);
uint64_t sntp_timer = 0;
for (;;) {
uint64_t period = mg_boot_timestamp_ms == 0 ? 1000 : 24 * 3600 * 1000;
if (mg_timer_expired(&sntp_timer, period, mg_millis())) {
mg_sntp_connect(&mgr, NULL, NULL, NULL);
}
mg_mgr_poll(&mgr, 1000);
}
mg_mgr_free(&mgr);
return 0;
}