DeterministicESPAsyncWebServer v6.28.0
Zero-allocation, bounded-execution async HTTP server for ESP32
Loading...
Searching...
No Matches
sleep_sched.h
Go to the documentation of this file.
1// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/**
5 * @file sleep_sched.h
6 * @brief Dynamic sleep-cycle scheduler (DETWS_ENABLE_SLEEP_SCHED).
7 *
8 * Decides, from the time since the last activity, whether a low-power device should sleep between
9 * requests and for how long - so a battery / solar node idles most of the time yet still serves. It is
10 * a pure decision core (`detws_sleep_next`): given `now`, the last-activity timestamp, and a config, it
11 * returns the number of milliseconds to sleep (0 = stay awake). The device stays awake until it has
12 * been idle for `idle_ms`, then sleeps in windows that ramp from `min_ms` up to `max_ms` the longer the
13 * idle streak runs (so a briefly-idle device wakes often and responsively, a long-idle one sleeps deep).
14 *
15 * Pure, zero heap, no stdlib, and takes an explicit `now`, so it is fully host-testable with a synthetic
16 * clock. The scheduler only decides the window; the app applies it per its own policy (an
17 * `esp_light_sleep_start()` with a timer wakeup, modem sleep, or deep sleep). It sits beside
18 * services/radio_power (modem sleep): that trims radio power while awake, this schedules the sleep.
19 */
20
21#ifndef DETERMINISTICESPASYNCWEBSERVER_SLEEP_SCHED_H
22#define DETERMINISTICESPASYNCWEBSERVER_SLEEP_SCHED_H
23
24#include "ServerConfig.h"
25#include <stddef.h>
26#include <stdint.h>
27
28#if DETWS_ENABLE_SLEEP_SCHED
29
30/** @brief Scheduler configuration (all times in ms). */
31struct DetwsSleepCfg
32{
33 uint32_t idle_ms; ///< stay fully awake until idle at least this long.
34 uint32_t min_ms; ///< first sleep window once idle (also the floor).
35 uint32_t max_ms; ///< longest single sleep window (the ceiling as the idle streak grows).
36 uint32_t ramp_ms; ///< every additional `ramp_ms` of idle doubles the window (0 => jump to max_ms).
37};
38
39/**
40 * @brief Milliseconds to sleep given the idle duration, or 0 to stay awake.
41 *
42 * @param now current time (detws_millis units).
43 * @param last_active_ms timestamp of the last activity (a request, a send, app work).
44 * @param cfg thresholds.
45 *
46 * Wrap-safe: uses the unsigned delta `now - last_active_ms`, correct across a millis() rollover. Returns
47 * 0 while idle < `idle_ms`; otherwise a window clamped to [min_ms, max_ms] that grows with the idle
48 * streak (doubling every `cfg.ramp_ms`, or straight to `max_ms` when `ramp_ms` is 0). If `max_ms` <
49 * `min_ms` the result is clamped to `min_ms`.
50 */
51uint32_t detws_sleep_next(uint32_t now, uint32_t last_active_ms, const DetwsSleepCfg *cfg);
52
53#endif // DETWS_ENABLE_SLEEP_SCHED
54#endif // DETERMINISTICESPASYNCWEBSERVER_SLEEP_SCHED_H
User-facing configuration for DeterministicESPAsyncWebServer.