ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
bk72xx_ble_tracker.cpp
Go to the documentation of this file.
1// bk72xx_ble_tracker.cpp
2//
3// BLE scan policy for the BK72xx BLE-5.x chips: parameters, duration/period
4// timers and the rate-limited start retry. All controller access (stack
5// bring-up, scan primitives, the BLE-task → main-task report queue) goes
6// through the bk72xx_ble component — no SDK calls and no cross-task state here.
7
8#ifdef USE_LIBRETINY
9
10#include "bk72xx_ble_tracker.h"
11
12#include <cinttypes>
13
15#include "esphome/core/log.h"
16
18
19ESPHOME_LOG_TAG(TAG, "bk72xx_ble_tracker");
20
21// Minimum interval between scan (re)start attempts, so a failing controller start
22// cannot be retried every main-loop iteration (single-core CPU starvation). The
23// interval doubles with consecutive failed starts (1 s up to 64 s) so a controller
24// that never comes up — the controller logs each failure at ERROR — settles into a
25// slow, quiet poll instead of an error line every second for the rest of uptime;
26// a single WARN is emitted when the retry interval first saturates.
27static constexpr uint32_t SCAN_START_RETRY_MS = 1000;
28static constexpr uint8_t SCAN_START_RETRY_MAX_DOUBLINGS = 6; // 1 s << 6 = 64 s
29// Stable-run time before the failure streak clears; reset-on-start would keep
30// a flapping controller at the 1 s gate.
31static constexpr uint32_t SCAN_STABLE_RESET_MS = 30000;
32
33// Radio-idle deadline for the bounded stop drain at OTA start.
34static constexpr uint32_t OTA_STOP_FLUSH_MS = 100;
35
36// 0.625 ms BLE units; integer math avoids soft-float on this FPU-less part.
37constexpr uint32_t ble_units_to_ms(uint32_t units) { return units * 5 / 8; }
38
39// ---------------------------------------------------------------------------
40// Component lifecycle
41// ---------------------------------------------------------------------------
42
44 // Merged (and unmerged) frames go to the shared dispatcher; unclaimed
45 // devices are logged only on one-shot scans (continuous would spam).
46 this->merger_.bind(&this->dispatcher_, &this->scan_continuous_, TAG);
47#ifdef USE_OTA_STATE_LISTENER
48 // Pause scanning while an OTA update is in flight — on the single-core BK72xx the
49 // BLE scan competes with the OTA flash writes. Mirrors esp32_ble_tracker.
50 ota::get_global_ota_callback()->add_global_state_listener(this);
51#endif
52 // scan_requested_ check: an on_boot start_scan latched before this setup()
53 // must keep the retry loop running (rp2/ln882h parity).
54 if (!this->scan_continuous_ && !this->scan_requested_) {
55 // Nothing to time until an explicit start_scan(); it re-enables the loop.
56 this->disable_loop();
57 }
58}
59
60#ifdef USE_OTA_STATE_LISTENER
61void BK72xxBLETracker::on_ota_global_state(ota::OTAState state, float progress, uint8_t error,
62 ota::OTAComponent *comp) {
63 if (state == ota::OTA_STARTED) {
66 this->stop_scan();
67 // The transfer starves the loop; a deferred stop would leave the radio
68 // scanning for the whole update, so drain it here, bounded.
69 if (!this->parent_->flush_pending_stop(OTA_STOP_FLUSH_MS)) {
70 ESP_LOGE(TAG, "Scan still stopping at OTA start; the radio may contend with the update");
71 }
72 } else if (state == ota::OTA_ERROR || state == ota::OTA_ABORT) {
73 // On success the device reboots, so restore only on a failed/aborted update;
74 // loop() restarts the scan on its next iteration (continuous idle branch).
76 this->scan_continuous_before_ota_ = false;
77 this->scan_continuous_ = true;
78 this->enable_loop(); // stop_scan() parked it
79 }
80 // A one-shot request that was still pending (latched, retrying) when the
81 // OTA paused scanning is re-latched, not dropped — loop() resumes the retry.
83 this->scan_requested_before_ota_ = false;
84 this->scan_requested_ = true;
85 this->enable_loop();
86 }
87 }
88}
89#endif // USE_OTA_STATE_LISTENER
90
93
94 // Deliver held scannable advertisements whose scan response never arrived —
95 // unmerged after the merger's timeout.
96 if (!this->merger_.empty())
97 this->merger_.sweep(now);
98
99 // Before the drop branch: a drop after a stable run starts a fresh streak.
100 if (this->scan_running_ && this->failed_start_count_ != 0 && now - this->scan_start_time_ >= SCAN_STABLE_RESET_MS)
101 this->failed_start_count_ = 0;
102
103 // A terminal failure while we report running recovers via the normal retry
104 // path; the drop charges the backoff so a flapping controller escalates.
106 ESP_LOGW(TAG, "Controller scan lost; retrying");
107 this->scan_requested_ = true;
108 this->count_failed_start_();
109 this->mark_scan_ended_(now);
110 }
111
112 if (this->scan_continuous_) {
113 if (!this->scan_running_) {
114 // One-iteration deferral; all stamps share this iteration's cached
115 // timestamp, so the period check below cannot underflow.
116 if (this->try_start_with_backoff_(now))
117 return;
118 }
119 // Period timer: fire on_scan_end() once per scan_duration_ window, mirroring
120 // esp32_ble_tracker::cleanup_scan_state_(). Gated on scan_started_once_ so a scan
121 // that never came up (start kept failing) does not fire spurious on_scan_end events.
122 if (this->scan_started_once_ && now - this->scan_period_start_ >= this->scan_duration_) {
123 this->fire_scan_end_();
124 this->scan_period_start_ = now;
125 }
126 return;
127 }
128
129 // Non-continuous mode: run for scan_duration_ ms, then stop and fire on_scan_end.
130 // Restart is driven externally (e.g. api: on_client_connected:).
131 //
132 // A requested start that failed (same controller failures the continuous branch
133 // absorbs) is retried with the same backoff — otherwise a failed one-shot start
134 // would be silent: the scan never runs, stop_scan_() is never reached and
135 // on_scan_end() never fires, leaving period-keyed consumers waiting forever.
136 if (this->scan_requested_ && !this->scan_running_) {
137 // Same one-iteration deferral as the continuous branch.
138 if (this->try_start_with_backoff_(now))
139 return;
140 }
141 if (this->scan_running_ && now - this->scan_start_time_ >= this->scan_duration_) {
142 // A full-duration run proves the controller healthy even when duration is
143 // shorter than SCAN_STABLE_RESET_MS.
144 this->failed_start_count_ = 0;
145 this->stop_scan_();
146 }
147}
148
150 // Rate-limit (re)start attempts. The controller start can fail (no idle activity
151 // handle, WiFi/BLE coexistence) and leave scan_running_ false; retrying every
152 // main-loop iteration would spin the single-core CPU and starve WiFi (device
153 // becomes unresponsive). The interval backs off with consecutive failures so a
154 // controller that never comes up polls slowly and quietly.
155 //
156 // force bypasses the gate for an explicit user start (start_scan()) — but
157 // only while the failure streak is clean. Once the controller is failing,
158 // even user-initiated attempts respect the backoff, so a start_scan() action
159 // on a short cadence cannot hammer a failing controller; the attempt stays
160 // inside the failure accounting below either way.
161 // Mid bring-up, observe instead of re-issuing (the hub self-advances). A
162 // SETTLED outcome completes immediately; only fresh attempts after FAILED
163 // are rate-limited.
164 const auto hub = this->parent_->last_scan_result();
166 return false;
168 if (this->start_attempt_open_) {
169 // Our bring-up gave up asynchronously; charge it to the backoff.
170 this->start_attempt_open_ = false;
171 this->count_failed_start_();
172 }
173 if ((!force || this->failed_start_count_ != 0) &&
174 now - this->last_scan_start_attempt_ < (SCAN_START_RETRY_MS << this->failed_start_count_))
175 return false;
176 }
177 this->start_scan_();
178 if (!this->scan_running_) {
180 this->start_attempt_open_ = true;
181 return false; // the controller is still bringing the scan up; not a failure
182 }
183 this->count_failed_start_();
184 }
185 return this->scan_running_;
186}
187
189 if (this->failed_start_count_ < SCAN_START_RETRY_MAX_DOUBLINGS) {
190 ++this->failed_start_count_;
191 if (this->failed_start_count_ == SCAN_START_RETRY_MAX_DOUBLINGS) {
192 ESP_LOGW(TAG, "Scan start keeps failing; retrying every %" PRIu32 " s",
193 (SCAN_START_RETRY_MS << SCAN_START_RETRY_MAX_DOUBLINGS) / 1000);
194 }
195 }
196}
197
199 ESP_LOGCONFIG(TAG,
200 "BK72xx BLE Tracker:\n"
201 " Scan Duration: %" PRIu32 " s\n"
202 " Scan Interval: %" PRIu32 " ms (%" PRIu32 " BLE units)\n"
203 " Scan Window: %" PRIu32 " ms (%" PRIu32 " BLE units)\n"
204 " Scan Type: %s (configured %s)\n"
205 " Continuous Scanning: %s",
207 ble_units_to_ms(this->scan_window_), this->scan_window_, this->scan_active_ ? "ACTIVE" : "PASSIVE",
208 this->scan_active_configured_ ? "ACTIVE" : "PASSIVE", YESNO(this->scan_continuous_));
210}
211
212// ---------------------------------------------------------------------------
213// Scan report — delivered by the controller's loop() on the ESPHome main task
214// (the controller queues reports from the BLE task), so publish_state() and
215// listener dispatch run in main-loop context with no cross-task handling here.
216// ---------------------------------------------------------------------------
217
218// GAPM report info byte (BLEScanReport::evt_type): bits 0-2 report type,
219// bit 5 scannable advertisement. Verified against both BDK stacks (5.1 and
220// 5.2 fill it from gapm_ext_adv_report_ind.info).
221static constexpr uint8_t GAPM_REPORT_TYPE_MASK = 0x07;
222static constexpr uint8_t GAPM_REPORT_TYPE_SCAN_RSP_EXT = 2;
223static constexpr uint8_t GAPM_REPORT_TYPE_SCAN_RSP_LEG = 3;
224static constexpr uint8_t GAPM_REPORT_INFO_SCAN_ADV_BIT = 1 << 5;
225
226// Demux advertisements vs scan responses into the shared merger: the BDK
227// delivers the pair as separate reports; a scannable advertisement is held
228// until its scan response arrives and delivered as one merged frame.
230 const uint8_t rtype = report.evt_type & GAPM_REPORT_TYPE_MASK;
231 if (rtype == GAPM_REPORT_TYPE_SCAN_RSP_LEG || rtype == GAPM_REPORT_TYPE_SCAN_RSP_EXT) {
232 this->merger_.submit_scan_rsp(report.mac, report.rssi, report.addr_type, report.data, report.data_len);
233 return;
234 }
235 // Stash only while an active scan runs: a passive scan never gets a
236 // response, and after a stop nothing would sweep the merger, so a late
237 // report would surface minutes later as a fresh advertisement.
238 if (this->scan_running_ && this->scan_active_ && (report.evt_type & GAPM_REPORT_INFO_SCAN_ADV_BIT)) {
239 this->merger_.stash_adv(report.mac, report.rssi, report.addr_type, report.data, report.data_len,
241 return;
242 }
243 this->dispatcher_.dispatch(report.mac, report.rssi, report.addr_type, report.data, report.data_len,
244 /*raw_only=*/false, this->scan_continuous_ ? nullptr : TAG);
245}
246
247// ---------------------------------------------------------------------------
248// Public scan control
249// ---------------------------------------------------------------------------
250
252 // Mirrors esp32_ble_tracker::start_scan(): caller sets scan_continuous_ via
253 // set_scan_continuous() first, then calls start_scan() to begin scanning.
254 //
255 // Nothing to do while a scan is already running: latching here would leave
256 // scan_requested_ set after that scan ends and silently restart a one-shot
257 // scan nobody asked for.
258 if (this->scan_running_)
259 return;
260
261 // The request is latched: if this immediate attempt fails (controller busy,
262 // WiFi/BLE coexistence), loop() keeps retrying it with backoff even in
263 // non-continuous mode, so a one-shot start cannot fail silently.
264 //
265 // Routed through the backoff helper (forced: the user asked for an immediate
266 // attempt) so a failure here still counts toward the backoff escalation and
267 // its WARN. The force bypass only applies while the failure streak is clean —
268 // against a failing controller, repeated start_scan() calls are rate-limited
269 // like any other attempt.
270 this->scan_requested_ = true;
271 this->enable_loop(); // an idle one-shot tracker parked it in stop_scan_()
273}
274
276 if (!this->scan_running_)
277 return;
278 // Re-anchor only the one-shot duration clock. scan_period_start_ (the
279 // continuous-mode on_scan_end period) is deliberately left alone: a
280 // start_scan action fired more often than scan_duration_ would otherwise
281 // suppress on_scan_end indefinitely — and absence detection (ble_rssi's NAN
282 // publish) rides on that period.
284}
285
287 this->scan_continuous_ = false;
288 this->scan_requested_ = false; // also cancels a pending (not yet successful) start
289 this->stop_scan_();
290}
291
292// ---------------------------------------------------------------------------
293// Internal scan start / stop
294// ---------------------------------------------------------------------------
295
298 return this->parent_->scan_start(static_cast<uint16_t>(this->scan_interval_),
299 static_cast<uint16_t>(this->scan_window_), this->scan_active_);
300}
301
303 if (this->scan_running_)
304 return;
305
307 return;
308
310 this->scan_running_ = true;
311 this->scan_requested_ = false; // the latched one-shot request is satisfied
312 this->start_attempt_open_ = false;
313 // failed_start_count_ deliberately not reset here; only a stable run clears it (loop()).
314 this->scan_start_time_ = now;
315 // Log every explicit start at DEBUG — stop_scan_() logs every stop at DEBUG, and
316 // in non-continuous mode each period is an explicit start, so asymmetric logging
317 // would read as the scanner failing to come back up.
318 ESP_LOGD(TAG, "Scan started (%s, window=%" PRIu32 "ms, interval=%" PRIu32 "ms)",
319 this->scan_active_ ? "active" : "passive", ble_units_to_ms(this->scan_window_),
321 // Re-anchor the on_scan_end period to every successful start — first start (so the
322 // period counts from the scan, not from boot) and every restart after a stop (so
323 // resuming after longer than scan_duration, e.g. a failed OTA restoring continuous
324 // mode 10 minutes later, does not fire on_scan_end before an advertisement can
325 // arrive). scan_started_once_ purely gates the period timer.
326 this->scan_period_start_ = now;
327 this->scan_started_once_ = true;
328}
329
330// Deliberate logical/physical split: on_scan_end() reports the tracker's
331// intent while the hub winds the radio down asynchronously; OTA is the one
332// path that must wait, and it flushes explicitly.
334 this->start_attempt_open_ = false; // an abandoned bring-up is not charged
335 this->parent_->scan_stop(); // idempotent: releases whatever the hub holds
336 if (this->scan_running_) {
337 ESP_LOGD(TAG, "Scan stopped");
339 }
340 // Park when idle (the hub drives its own teardown); re-check because an
341 // on_scan_end automation may have restarted the scan.
342 if (!this->scan_continuous_ && !this->scan_running_ && !this->scan_requested_)
343 this->disable_loop();
344}
345
346// The period re-anchor keeps on_scan_end from double-firing in one iteration.
348 this->scan_running_ = false;
349 this->fire_scan_end_();
350 this->scan_period_start_ = now;
351}
352
354 // Deliver held advertisements whose scan response never came (unmerged)
355 // BEFORE on_scan_end fires.
356 this->merger_.flush();
357 this->dispatcher_.on_scan_end();
358}
359
360// true = request latched, not applied: the reconciler applies it
361// asynchronously and loop() recovers a failed re-arm (ln882h parity).
363 if (this->scan_active_ == active)
364 return true;
365 this->scan_active_ = active;
366 // V: the proxy's "Setting scanner mode" line already narrates this at D.
367 ESP_LOGV(TAG, "Scan mode %s", active ? "active" : "passive");
368 // The controller reconciler restarts a running scan itself; the scan stays
369 // logically running. An idle scanner picks the mode up on its next start.
370 if (this->scan_running_)
372 return true;
373}
374
375} // namespace esphome::bk72xx_ble_tracker
376
377#endif // USE_LIBRETINY
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.
void enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
ScanOpResult last_scan_result() const
Last reconciliation outcome; on FAILED the consumer's retry policy owns recovery.
Definition bk72xx_ble.h:103
bool flush_pending_stop(uint32_t timeout_ms)
Drive a requested stop until the radio is observed idle, bounded by timeout_ms (for OTA).
void scan_stop()
Request the scanner stopped and the activity released; steps that cannot run yet are completed from l...
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
bool try_start_with_backoff_(uint32_t now, bool force=false)
Rate-limited (re)start; true when the scan is running (the caller must not reuse a now older than the...
void on_scan_report(const bk72xx_ble::BLEScanReport &report) override
void restart_scan_duration()
Re-anchor the one-shot duration clock of a running scan to now — used when an action changes the scan...
ble_device_base::ScanResponseMerger merger_
bk72xx_ble::ScanOpResult controller_scan_start_()
Stamp-and-start for every controller scan attempt, so the retry rate limit covers all callers.
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().
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "bk72xx_ble_tracker")
constexpr uint32_t ble_units_to_ms(uint32_t units)
ScanOpResult
Outcome of one reconciliation step.
Definition bk72xx_ble.h:25
@ SETTLED
The request is reached: scan observed running, or stopped with the activity fully released.
@ FAILED
The controller rejected a step; retry later.
@ PENDING
A step is in flight; loop() keeps advancing — call scan_start() again to learn the outcome.
OTAGlobalCallback * get_global_ota_callback()
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
One advertisement report from the controller.
Definition bk72xx_ble.h:42
uint8_t mac[MAC_ADDRESS_SIZE]
Definition bk72xx_ble.h:43