DeterministicESPAsyncWebServer v6.28.0
Zero-allocation, bounded-execution async HTTP server for ESP32
Loading...
Searching...
No Matches
mdns_adaptive.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 mdns_adaptive.cpp
6 * @brief Adaptive mDNS beacon scheduling (see mdns_adaptive.h).
7 */
8
10
11#if DETWS_ENABLE_MDNS_ADAPTIVE
12
13uint32_t detws_mdns_refresh_interval(uint32_t ttl_s)
14{
15 // Half the TTL, in ms; guard the *1000 against overflow.
16 uint64_t half_ms = (uint64_t)ttl_s * 1000 / 2;
17 return half_ms > 0xFFFFFFFFu ? 0xFFFFFFFFu : (uint32_t)half_ms;
18}
19
20void detws_mdns_beacon_init(MdnsBeacon *b, uint32_t base_ms, uint32_t max_ms, uint16_t hi_thresh)
21{
22 if (!b)
23 return;
24 b->base_ms = base_ms;
25 b->max_ms = max_ms < base_ms ? base_ms : max_ms;
26 b->cur_ms = base_ms;
27 b->hi_thresh = hi_thresh ? hi_thresh : 1;
28}
29
30uint32_t detws_mdns_beacon_adapt(MdnsBeacon *b, uint16_t contention)
31{
32 if (!b)
33 return 0;
34 if (contention >= b->hi_thresh)
35 {
36 uint32_t up = b->cur_ms << 1;
37 if (up < b->cur_ms || up > b->max_ms) // overflow or past ceiling
38 up = b->max_ms;
39 b->cur_ms = up;
40 }
41 else if (contention == 0)
42 {
43 uint32_t down = b->cur_ms >> 1;
44 if (down < b->base_ms)
45 down = b->base_ms;
46 b->cur_ms = down;
47 }
48 return b->cur_ms;
49}
50
51bool detws_mdns_beacon_due(const MdnsBeacon *b, uint32_t last_ms, uint32_t now_ms)
52{
53 if (!b)
54 return false;
55 uint32_t elapsed = now_ms - last_ms; // wrap-safe modular subtraction
56 return elapsed >= b->cur_ms;
57}
58
59bool detws_mdns_beacon_presleep_due(const MdnsBeacon *b, uint32_t last_ms, uint32_t now_ms, uint32_t sleep_ms)
60{
61 if (!b)
62 return false;
63 uint32_t elapsed = now_ms - last_ms;
64 // Would the record lapse during the sleep? Compute in 64-bit so elapsed + sleep_ms cannot wrap.
65 uint64_t after = (uint64_t)elapsed + sleep_ms;
66 return after >= b->cur_ms;
67}
68
69#endif // DETWS_ENABLE_MDNS_ADAPTIVE
Adaptive mDNS beacon scheduling: RF-aware backoff, TTL refresher, auto-sleep beacon (DETWS_ENABLE_MDN...