Introduce mg_timer_expired(). Adopt DHCP and link status to use it

This commit is contained in:
cpq committed 2022-09-03 09:45:19 +01:00
1 parent a113e344a1
commit f9272d0959
5 files changed
+54 -62

No files matched your search

+15 -16
View File
@@ -5,8 +5,8 @@
void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
unsigned flags, void (*fn)(void *), void *arg) {
struct mg_timer tmp = {0U, ms, 0U, 0U, flags, fn, arg, *head};
*t = tmp;
t->id = 0, t->period_ms = ms, t->expire = 0;
t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
*head = t;
}
@@ -15,27 +15,26 @@ void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
if (*head) *head = t->next;
}
// t: expiration time, prd: period, now: current time. Return true if expired
bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
if (*t == 0) *t = now + prd; // Firt poll? Set expiration
if (*t > now) return false; // Not expired yet, return
*t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
return true; // Expired, return true
}
void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
// If time goes back (wrapped around), reset timers
struct mg_timer *t, *tmp;
for (t = *head; t != NULL; t = tmp) {
bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
!(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
tmp = t->next;
if (t->prev_ms > now_ms) t->expire = 0; // Handle time wrap
t->prev_ms = now_ms;
if (t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
!(t->flags & MG_TIMER_CALLED)) {
// Handle MG_TIMER_NOW only once
} else if (t->expire == 0) {
t->expire = now_ms + t->period_ms;
}
if (t->expire > now_ms) continue;
if (!once && !expired) continue;
if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
t->fn(t->arg);
}
t->flags |= MG_TIMER_CALLED;
// Try to tick timers with the given period as accurate as possible,
// even if this polling function is called with some random period.
t->expire = now_ms - t->expire > t->period_ms ? now_ms + t->period_ms
: t->expire + t->period_ms;
}
}