ProtoCore v0.0.2
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
sleep_sched.cpp
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.cpp
6 * @brief Dynamic sleep-cycle scheduler decision core (see sleep_sched.h).
7 */
8
10
11#if PC_ENABLE_SLEEP_SCHED
12
13uint32_t pc_sleep_next(uint32_t now, uint32_t last_active_ms, const pc_sleep_cfg *cfg)
14{
15 if (!cfg)
16 {
17 return 0;
18 }
19
20 uint32_t idle = (uint32_t)(now - last_active_ms); // wrap-safe unsigned delta
21 if (idle < cfg->idle_ms)
22 {
23 return 0; // active recently: stay awake
24 }
25
26 uint32_t ceil_ms = cfg->max_ms < cfg->min_ms ? cfg->min_ms : cfg->max_ms;
27 if (cfg->ramp_ms == 0)
28 {
29 return ceil_ms; // no ramp: go straight to the deepest window
30 }
31
32 // Grow the window by doubling for every ramp_ms of idle past the threshold, clamped to the ceiling.
33 // The pre-shift ceiling check keeps the doubling from overflowing.
34 uint32_t doublings = (idle - cfg->idle_ms) / cfg->ramp_ms;
35 uint32_t window = cfg->min_ms ? cfg->min_ms : 1;
36 for (uint32_t i = 0; i < doublings; i++)
37 {
38 if (window >= ceil_ms || window > ceil_ms / 2)
39 {
40 window = ceil_ms;
41 break;
42 }
43 window <<= 1;
44 }
45 if (window > ceil_ms)
46 {
47 window = ceil_ms;
48 }
49 // GCOVR_EXCL_START unreachable: ceil_ms = max(min_ms, max_ms) (see above), so ceil_ms >= min_ms
50 // always. window starts at min_ms (or 1 when min_ms is 0, itself >= min_ms since min_ms is then
51 // 0), and every later change to it either doubles it (strictly increasing) or clamps it to
52 // exactly ceil_ms (the loop-break above, or the post-loop check on the previous line) - never to
53 // anything below ceil_ms >= min_ms. So window can never fall below min_ms. Kept as a defensive
54 // floor.
55 if (window < cfg->min_ms)
56 {
57 window = cfg->min_ms;
58 }
59 // GCOVR_EXCL_STOP
60 return window;
61}
62
63#endif // PC_ENABLE_SLEEP_SCHED
Dynamic sleep-cycle scheduler (PC_ENABLE_SLEEP_SCHED).