ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
rp2_ble_tracker.cpp
Go to the documentation of this file.
1#ifdef USE_RP2
2
3#include "rp2_ble_tracker.h"
4
5#include <cinttypes>
6
8#include "esphome/core/log.h"
9
11
12ESPHOME_LOG_TAG(TAG, "rp2_ble_tracker");
13
14// Floor between controller start attempts; insurance against a failing
15// scan_start() being retried every loop.
16static constexpr uint32_t SCAN_START_RETRY_MS = 1000;
17
18// One BLE scan unit in milliseconds; the controller programs interval/window in these units.
19static constexpr float BLE_SCAN_UNIT_MS = 0.625f;
20
22 // Merged (and unmerged) frames go to the shared dispatcher; scan_continuous_
23 // is read at each delivery to decide unclaimed-device logging.
24 this->merger_.bind(&this->dispatcher_, &this->scan_continuous_, TAG);
25#ifdef USE_OTA_STATE_LISTENER
26 // Pause scanning while an OTA update is in flight — the BLE scan competes with
27 // the OTA download on the shared CYW43 radio. Mirrors esp32_ble_tracker.
28 ota::get_global_ota_callback()->add_global_state_listener(this);
29#endif
30 // An on_boot start_scan runs before setup(); parking here would strand it.
31 if (!this->scan_continuous_ && !this->scan_running_ && !this->pending_start_) {
32 // Nothing to do until an external start_scan(); the loop is re-enabled there.
33 this->disable_loop();
34 }
35}
36
37#ifdef USE_OTA_STATE_LISTENER
38void RP2BLETracker::on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) {
39 if (state == ota::OTA_STARTED) {
40 // Set before stop_scan(): its on_scan_end automations run synchronously and
41 // may call start_scan(), which must defer instead of resuming the radio.
42 this->ota_in_progress_ = true;
44 // A one-shot scan counts as pending when it is running, latched, or still
45 // retrying its start (loop enabled); captured before stop_scan() parks it.
47 !this->scan_continuous_ && (this->scan_running_ || this->pending_start_ || this->is_in_loop_state());
48 // The pause's own stop is not a user stop, so it must not clear the latches
49 // captured just above.
50 this->ota_pausing_ = true;
51 this->stop_scan();
52 this->ota_pausing_ = false;
53 } else if (state == ota::OTA_ERROR || state == ota::OTA_ABORT) {
54 this->ota_in_progress_ = false;
55 // On success the device reboots, so restore only on a failed/aborted update;
56 // loop()'s retry branch restarts the scan on its next iteration.
58 this->scan_continuous_before_ota_ = false;
59 this->scan_continuous_ = true;
60 this->enable_loop();
61 }
62 // A failed OTA does not reboot, so nothing else would restart a one-shot.
63 if (this->scan_pending_before_ota_) {
64 this->scan_pending_before_ota_ = false;
65 this->enable_loop();
66 }
67 }
68}
69#endif // USE_OTA_STATE_LISTENER
70
72#ifdef USE_OTA_STATE_LISTENER
73 // Keeps "no radio during an OTA" local instead of emergent from the
74 // parking sites.
75 if (this->ota_in_progress_)
76 return;
77#endif
79 if (this->pending_start_ && this->parent_->is_active()) {
80 // Latched start, applied once the stack is ACTIVE; earlier attempts would
81 // fail and arm the retry floor for nothing.
82 this->pending_start_ = false;
83 if (!this->scan_running_)
84 this->start_scan_();
85 }
86 // Deliver held scannable advertisements whose scan response never arrived —
87 // unmerged after the merger's timeout.
88 if (!this->merger_.empty())
89 this->merger_.sweep(now);
90 if (this->scan_running_ && !this->parent_->is_active()) {
91 // Stack disabled underneath us; reconcile so the retry branch takes over.
92 this->scan_running_ = false;
93 this->fire_scan_end_();
94 }
95 if (!this->scan_running_) {
96 // Should be scanning but is not: continuous until the start succeeds,
97 // one-shot only between start_scan() and a successful controller start.
98 if (!this->parent_->is_active()) {
99 // Stack not up: scan_start() cannot succeed yet.
100 return;
101 }
102 if (now - this->last_scan_start_attempt_ >= SCAN_START_RETRY_MS) {
103 this->start_scan_();
104 }
105 return;
106 }
107
108 if (this->scan_continuous_) {
109 // Period timer: fire on_scan_end() once per scan_duration_ window, mirroring
110 // esp32_ble_tracker::cleanup_scan_state_().
111 if (now - this->scan_period_start_ >= this->scan_duration_) {
112 this->fire_scan_end_();
113 this->scan_period_start_ = now;
114 }
115 return;
116 }
117
118 // Non-continuous mode: run for scan_duration_ ms, then stop and fire on_scan_end.
119 // Restart is driven externally (e.g. api: on_client_connected:).
120 if (now - this->scan_start_time_ >= this->scan_duration_) {
121 this->stop_scan_();
122 }
123}
124
126 ESP_LOGCONFIG(TAG,
127 "RP2 BLE Tracker:\n"
128 " Scan Duration: %" PRIu32 " s\n"
129 " Scan Interval: %.0f ms (%" PRIu32 " BLE units)\n"
130 " Scan Window: %.0f ms (%" PRIu32 " BLE units)\n"
131 " Scan Type: %s\n"
132 " Continuous Scanning: %s",
133 this->scan_duration_ / 1000, this->scan_interval_ * BLE_SCAN_UNIT_MS, this->scan_interval_,
134 this->scan_window_ * BLE_SCAN_UNIT_MS, this->scan_window_,
135 this->scan_active_ ? LOG_STR_LITERAL("ACTIVE") : LOG_STR_LITERAL("PASSIVE"),
136 YESNO(this->scan_continuous_));
138}
139
140// Core spec advertising report event types (BTstack headers stay out of this
141// TU). ADV_IND and ADV_SCAN_IND are the scannable ones.
142static constexpr uint8_t ADV_EVENT_TYPE_ADV_IND = 0;
143static constexpr uint8_t ADV_EVENT_TYPE_ADV_SCAN_IND = 2;
144static constexpr uint8_t ADV_EVENT_TYPE_SCAN_RSP = 4;
145
146// BTstack delivers the pair as separate reports; the merger holds a scannable
147// advertisement until its response arrives.
149 if (report.adv_event_type == ADV_EVENT_TYPE_SCAN_RSP) {
150 this->merger_.submit_scan_rsp(report.mac, report.rssi, report.addr_type, report.data, report.data_len);
151 return;
152 }
153 // Only while an active scan runs: nothing sweeps the merger after a stop.
154 if (this->scan_running_ && this->scan_active_ &&
155 (report.adv_event_type == ADV_EVENT_TYPE_ADV_IND || report.adv_event_type == ADV_EVENT_TYPE_ADV_SCAN_IND)) {
156 this->merger_.stash_adv(report.mac, report.rssi, report.addr_type, report.data, report.data_len,
158 return;
159 }
160 this->dispatcher_.dispatch(report.mac, report.rssi, report.addr_type, report.data, report.data_len,
161 /*raw_only=*/false, this->scan_continuous_ ? nullptr : TAG);
162}
163
165 // Mirrors esp32_ble_tracker::start_scan(): caller sets scan_continuous_ via
166 // set_scan_continuous() first, then calls start_scan() to begin scanning.
167#ifdef USE_OTA_STATE_LISTENER
168 if (this->ota_in_progress_) {
169 // Defer to the post-OTA resume path, carrying the requested mode. Not
170 // while ota_pausing_: scan_continuous_ is an artefact of the pause's own
171 // stop there, not intent.
172 if (!this->ota_pausing_) {
175 }
176 return;
177 }
178#endif
179 this->enable_loop();
180 if (!this->is_ready() || !this->parent_->is_active()) {
181 // Pre-setup or stack not ACTIVE: latch, loop() applies it.
182 this->pending_start_ = true;
183 return;
184 }
185 // bk72xx force semantics: a user start jumps the floor only while the
186 // controller is healthy. loop()'s retry branch picks the request up.
187 if (this->last_start_failed_ &&
188 App.get_loop_component_start_time() - this->last_scan_start_attempt_ < SCAN_START_RETRY_MS) {
189 return;
190 }
191 this->start_scan_();
192}
193
195 if (!this->scan_running_)
196 return; // start_scan_() anchors the clock itself on the next real start
197 // One-shot clock only (bk72xx parity); re-anchoring the period would let
198 // repeated actions starve on_scan_end. Same clock as loop()'s now.
200}
201
203 if (this->scan_active_ == active)
204 return true;
205 this->scan_active_ = active;
206 // V: the proxy's "Setting scanner mode" line already narrates this at D.
207 ESP_LOGV(TAG, "Scan mode %s", active ? "active" : "passive");
208 // Restart the controller scan only: the scan logically continues, so no
209 // on_scan_end and no period reset. An idle scanner applies it on next start.
210 if (this->scan_running_) {
211 this->parent_->scan_stop();
212 if (!this->controller_scan_start_()) {
213 // The controller really stopped: behave exactly like loop()'s
214 // reconciliation branch - notify listeners and let its retry recover.
215 this->scan_running_ = false;
216 this->fire_scan_end_();
217 }
218 }
219 return true;
220}
221
223 // Cancel a start latched before setup(); without this an on_boot
224 // start_scan/stop_scan pair would still start at the first loop().
225 this->pending_start_ = false;
226 this->scan_continuous_ = false;
227#ifdef USE_OTA_STATE_LISTENER
228 // A user stop during the OTA is the latest intent; the pause's own stop
229 // (ota_pausing_) is exempt - it armed that state.
230 if (this->ota_in_progress_ && !this->ota_pausing_) {
231 this->scan_pending_before_ota_ = false;
232 this->scan_continuous_before_ota_ = false;
233 }
234#endif
235 this->stop_scan_();
236 // stop_scan_() early-returns when idle, so park here too - once set up, and
237 // re-checked: its synchronous on_scan_end may have restarted the scan.
238 if (this->is_ready() && !this->scan_running_ && !this->pending_start_) {
239 this->disable_loop();
240 }
241}
242
243// Stamp-and-start for every controller scan attempt: the stamp keeps the
244// SCAN_START_RETRY_MS floor covering all callers, not only loop()'s retry.
247 const bool ok = this->parent_->scan_start(static_cast<uint16_t>(this->scan_interval_),
248 static_cast<uint16_t>(this->scan_window_), this->scan_active_);
249 this->last_start_failed_ = !ok;
250 return ok;
251}
252
254 if (this->scan_running_)
255 return;
256
257 if (!this->controller_scan_start_())
258 return;
259
260 this->scan_running_ = true;
261 // Symmetric with stop_scan_()'s stop log; asymmetry would read as the
262 // scanner failing to come back.
263 ESP_LOGD(TAG, "Scan started (%s, window=%.0fms, interval=%.0fms)",
264 this->scan_active_ ? LOG_STR_LITERAL("active") : LOG_STR_LITERAL("passive"),
265 this->scan_window_ * BLE_SCAN_UNIT_MS, this->scan_interval_ * BLE_SCAN_UNIT_MS);
266 // Anchor the period to the scan, not to boot, so a restart after a long gap
267 // does not fire on_scan_end immediately. Same clock as loop()'s now.
270}
271
273 if (!this->scan_running_)
274 return;
275 this->parent_->scan_stop();
276 this->scan_running_ = false;
277 ESP_LOGD(TAG, "Scan stopped");
278 this->fire_scan_end_();
279 // Reset the period clock so on_scan_end does not double-fire; same clock as loop().
281 // on_scan_end runs synchronously and may restart the scan; re-check before
282 // parking or that scan runs untimed.
283 if (!this->scan_continuous_ && !this->scan_running_ && !this->pending_start_) {
284 // Nothing left to time; start_scan() re-enables the loop.
285 this->disable_loop();
286 }
287}
288
290 // Deliver held advertisements whose scan response never came (unmerged)
291 // BEFORE on_scan_end fires.
292 this->merger_.flush();
293 this->dispatcher_.on_scan_end();
294}
295
296} // namespace esphome::rp2_ble_tracker
297
298#endif // USE_RP2
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
bool is_in_loop_state() const
Check if this component has completed setup and is in the loop state.
Definition component.h:210
bool is_ready() const
void enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
void dump_child_configs()
Print each listener's dump_child_config(); called from the tracker's dump_config().
void on_scan_end()
Fire listeners' on_scan_end and reset the per-scan discovered-log dedup.
void dispatch(const uint8_t *mac, int8_t rssi, uint8_t addr_type, const uint8_t *data, uint8_t data_len, bool raw_only, const char *log_unclaimed_tag)
Dispatch one (possibly merged) advertisement: the raw callback, and — unless raw_only — parsing for l...
void stash_adv(const uint8_t *mac, int8_t rssi, uint8_t addr_type, const uint8_t *data, uint8_t data_len, uint32_t now)
Hold a scannable advertisement, waiting for its scan response.
void sweep(uint32_t now)
Timeout flush (call from loop() with the stash_adv() clock): deliver held advertisements whose scan r...
void flush()
Deliver every held advertisement now (scan period/scan is ending, before on_scan_end fires): unmerged...
void submit_scan_rsp(const uint8_t *mac, int8_t rssi, uint8_t addr_type, const uint8_t *data, uint8_t data_len)
A scan response arrived: append it to the held advertisement from the same device and deliver the pai...
bool empty() const
Lets loop() skip the cross-TU sweep() call in the common case (empty: passive scan,...
void bind(AdvDispatcher *dispatcher, const bool *scan_continuous, const char *log_tag)
Wire the merger's output; call once in the tracker's setup().
void scan_stop()
Stop the controller scan (no-op when not scanning).
ble_device_base::AdvDispatcher dispatcher_
void on_scan_report(const rp2040_ble::BLEScanReport &report) override
ble_device_base::ScanResponseMerger merger_
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
bool state
Definition fan.h:2
OTAGlobalCallback * get_global_ota_callback()
ESPHOME_LOG_TAG(TAG, "rp2_ble_tracker")
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
One advertisement report from the controller.
Definition rp2040_ble.h:27
uint8_t mac[MAC_ADDRESS_SIZE]
Definition rp2040_ble.h:28