ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
ln882h_ble_tracker.cpp
Go to the documentation of this file.
1#ifdef USE_LIBRETINY
2
4
5#include <cinttypes>
6
7#include "esphome/core/hal.h"
8#include "esphome/core/log.h"
9
11
12ESPHOME_LOG_TAG(TAG, "ln882h_ble_tracker");
13
14static constexpr float BLE_SCAN_UNIT_MS = 0.625f;
15
16// ---------------------------------------------------------------------------
17// Component lifecycle
18// ---------------------------------------------------------------------------
19
21 // Merged (and unmerged) frames go to the shared dispatcher; scan_continuous_
22 // is read at each delivery to decide unclaimed-device logging.
23 this->merger_.bind(&this->dispatcher_, &this->scan_continuous_, TAG);
24 // scan_running_ check: an on_boot start_scan action (priority 600) runs
25 // before this setup() (200) and enable_loop() is a no-op pre-setup — parking
26 // the loop here would strand that already-running scan.
27 if (!this->scan_continuous_ && !this->scan_running_ && !this->pending_start_) {
28 // Say so once: with continuous: false nothing scans until an explicit
29 // start_scan() — silence here reads as a broken scanner.
30 ESP_LOGD(TAG, "Scanning not started (continuous: false) - waiting for an explicit start_scan()");
31 // Nothing to time until then; start_scan_() re-enables the loop.
32 this->disable_loop();
33 }
34#ifdef USE_OTA_STATE_LISTENER
35 // Pause scanning while an OTA update is in flight — on the single-core LN882H the
36 // BLE scan competes with the OTA flash writes. Mirrors esp32_ble_tracker.
37 ota::get_global_ota_callback()->add_global_state_listener(this);
38#endif
39}
40
41#ifdef USE_OTA_STATE_LISTENER
42void LN882HBLETracker::on_ota_global_state(ota::OTAState state, float progress, uint8_t error,
43 ota::OTAComponent *comp) {
44 if (state == ota::OTA_STARTED) {
47 this->stop_scan();
48 } else if (state == ota::OTA_ERROR || state == ota::OTA_ABORT) {
49 // On success the device reboots, so restore only on a failed/aborted
50 // update. Continuous mode resumes via loop()'s idle branch; a one-shot
51 // scan that was running is restarted explicitly (bk72xx sibling parity —
52 // stop_scan() cleared it and nothing else would bring it back).
54 this->scan_continuous_ = true;
55 this->enable_loop(); // stop_scan() disabled it; loop()'s idle branch restarts the scan
56 } else if (this->scan_running_before_ota_) {
57 this->start_scan();
58 }
59 this->scan_continuous_before_ota_ = false;
60 this->scan_running_before_ota_ = false;
61 }
62}
63#endif // USE_OTA_STATE_LISTENER
64
66 if (this->pending_start_) {
67 // A start_scan latched before the controller's setup(); safe now — loop()
68 // only runs after every component set up.
69 this->pending_start_ = false;
70 if (!this->scan_running_) {
71 this->start_scan_();
72 }
73 }
74 // Deliver held scannable advertisements whose scan response never arrived —
75 // unmerged after the merger's timeout. Main-task only, like every merger call.
76 const uint32_t now = millis();
77 if (!this->merger_.empty())
78 this->merger_.sweep(now);
79
80 if (this->scan_continuous_) {
81 if (!this->scan_running_) {
82 this->start_scan_();
83 // start_scan_() re-anchors scan_period_start_ from a later millis() than
84 // the cached `now`; resume the period timer next iteration.
85 return;
86 }
87 // Period timer: once per scan_duration_ window, restart the controller scan
88 // and fire on_scan_end(), mirroring esp32_ble_tracker::cleanup_scan_state_().
89 // The restart is the recovery path for the coexistence failure documented in
90 // the header. scan_start() re-enters cleanly on its own: it stops an
91 // in-flight scan and grants the controller's 10 ms GAPM settle before
92 // restarting — an explicit scan_stop() first would clear the controller's
93 // re-entry guard and skip that settle.
94 if (now - this->scan_period_start_ >= this->scan_duration_) {
95 ESP_LOGD(TAG, "Scan period elapsed - restarting scan");
96 this->parent_->scan_start(this->scan_interval_, this->scan_window_, this->scan_active_);
97 // Keep both clocks anchored to the restart: a runtime switch to
98 // non-continuous then times out the current period, not the whole run.
99 this->scan_start_time_ = now;
100 this->end_scan_period_(now);
101 }
102 return;
103 }
104
105 // Non-continuous mode: run for scan_duration_ ms, then stop and fire on_scan_end.
106 // Restart is driven externally (e.g. wifi: on_connect:).
107 if (this->scan_running_ && now - this->scan_start_time_ >= this->scan_duration_) {
108 this->stop_scan_();
109 }
110}
111
113 if (this->scan_active_ == active)
114 return true;
115 this->scan_active_ = active;
116 // V: the proxy's "Setting scanner mode" line already narrates this at D.
117 ESP_LOGV(TAG, "Scan mode %s", active ? "active" : "passive");
118 // scan_start() re-enters cleanly (stops + GAPM settle). No on_scan_end and
119 // no period reset: the scan logically continues, only the mode changes.
120 if (this->scan_running_) {
121 this->parent_->scan_start(this->scan_interval_, this->scan_window_, this->scan_active_);
122 }
123 return true;
124}
125
127 ESP_LOGCONFIG(TAG,
128 "LN882H BLE Tracker:\n"
129 " Scan Duration: %" PRIu32 " s\n"
130 " Scan Interval: %.0f ms (%" PRIu16 " BLE units)\n"
131 " Scan Window: %.0f ms (%" PRIu16 " BLE units)\n"
132 " Scan Type: %s\n"
133 " Continuous Scanning: %s",
134 this->scan_duration_ / 1000, this->scan_interval_ * BLE_SCAN_UNIT_MS, this->scan_interval_,
135 this->scan_window_ * BLE_SCAN_UNIT_MS, this->scan_window_, this->scan_active_ ? "ACTIVE" : "PASSIVE",
136 YESNO(this->scan_continuous_));
138}
139
140// ---------------------------------------------------------------------------
141// Adv/scan-response demux into the shared merger (ble_device_base): the LN
142// controller delivers the pair as separate reports; a scannable advertisement
143// is held until its scan response arrives and delivered as one merged frame.
144// ---------------------------------------------------------------------------
145
147 if (report.is_scan_response) {
148 this->merger_.submit_scan_rsp(report.mac, report.rssi, report.addr_type, report.data, report.data_len);
149 return;
150 }
151 // Stash only while the scan runs: after a one-shot stop the loop is
152 // disabled and nothing would sweep the merger, so a late report would
153 // surface minutes later as a fresh advertisement.
154 if (this->scan_running_ && this->scan_active_ && report.scannable) {
155 this->merger_.stash_adv(report.mac, report.rssi, report.addr_type, report.data, report.data_len, millis());
156 return;
157 }
158 this->dispatcher_.dispatch(report.mac, report.rssi, report.addr_type, report.data, report.data_len,
159 /*raw_only=*/false, this->scan_continuous_ ? nullptr : TAG);
160}
161
162// ---------------------------------------------------------------------------
163// Public scan actions
164// ---------------------------------------------------------------------------
165
167 // Mirrors esp32_ble_tracker::start_scan(): caller sets scan_continuous_ via
168 // set_scan_continuous() first, then calls start_scan() to begin scanning.
169 if (!this->parent_->is_ready()) {
170 // An on_boot automation (priority 600) runs before the controller's
171 // setup() has resolved the BLE MAC; scan_start() now would rw_init() the
172 // all-zero address and bring BLE up before WiFi. Latch; loop() applies
173 // the start once every setup() has run.
174 this->pending_start_ = true;
175 return;
176 }
177 if (!this->scan_running_) {
178 this->start_scan_();
179 }
180}
181
183 if (!this->scan_running_)
184 return;
185 // Re-anchor only the one-shot duration clock. scan_period_start_ (the
186 // continuous-mode on_scan_end period) is deliberately left alone: a
187 // start_scan action fired more often than scan_duration_ would otherwise
188 // suppress on_scan_end indefinitely — and absence detection (ble_rssi's NAN
189 // publish) rides on that period.
190 this->scan_start_time_ = millis();
191}
192
194 // Cancel a start latched before the controller's setup(); without this an
195 // on_boot start_scan/stop_scan pair would still start at the first loop().
196 this->pending_start_ = false;
197 this->scan_continuous_ = false;
198 this->stop_scan_();
199}
200
201// ---------------------------------------------------------------------------
202// Internal scan start / stop
203// ---------------------------------------------------------------------------
204
206 if (this->scan_running_)
207 return;
208
209 // The controller enables the stack on first use and owns the report queue;
210 // this call is all the SDK interaction the tracker ever needs.
211 this->parent_->scan_start(this->scan_interval_, this->scan_window_, this->scan_active_);
212 const uint32_t now = millis();
213 this->scan_running_ = true;
214 this->scan_start_time_ = now;
215 this->enable_loop(); // an idle non-continuous tracker disabled it in stop_scan_()
216 // Log every explicit start at DEBUG — stop_scan_() logs every stop at DEBUG, and
217 // in non-continuous mode each period is an explicit start, so asymmetric logging
218 // would read as the scanner failing to come back up.
219 ESP_LOGD(TAG, "BLE scan started (%s, window=%.0fms, interval=%.0fms)", this->scan_active_ ? "active" : "passive",
220 this->scan_window_ * BLE_SCAN_UNIT_MS, this->scan_interval_ * BLE_SCAN_UNIT_MS);
221 // Re-anchor the on_scan_end period to every successful start, so a restart
222 // later than scan_duration (e.g. a failed OTA restoring continuous mode)
223 // does not fire on_scan_end before an advertisement can arrive.
224 this->scan_period_start_ = now;
225}
226
228 if (!this->scan_running_)
229 return;
230 this->parent_->scan_stop();
231 this->scan_running_ = false;
232 // DEBUG like start_scan_() — a per-period stop at INFO would read as the
233 // scanner failing to come back up.
234 ESP_LOGD(TAG, "BLE scan stopped");
235 this->end_scan_period_(millis()); // also resets the period clock so on_scan_end does not double-fire
236 // scan_running_ re-check: an on_scan_end automation runs synchronously inside
237 // end_scan_period_() and may have called start_scan() — parking the loop then
238 // would leave the radio scanning with no period timing or pending-adv sweep.
239 if (!this->scan_continuous_ && !this->scan_running_) {
240 // Nothing left to time; start_scan_() re-enables the loop.
241 this->disable_loop();
242 }
243}
244
245// Close a scan period: deliver held advertisements whose scan response never
246// came (unmerged) BEFORE on_scan_end fires, then re-anchor the period clock.
248 this->merger_.flush();
249 this->dispatcher_.on_scan_end();
250 this->scan_period_start_ = now;
251}
252
253} // namespace esphome::ln882h_ble_tracker
254
255#endif // USE_LIBRETINY
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::ScanResponseMerger merger_
void restart_scan_duration()
Re-anchor the one-shot duration clock of a running scan to now — used when an action changes the scan...
void on_scan_report(const ln882h_ble::BLEScanReport &report) override
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "ln882h_ble_tracker")
OTAGlobalCallback * get_global_ota_callback()
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
One scan report from the controller, decoded from the SDK's rw-task event (RSSI already sign-correcte...
Definition ln882h_ble.h:25
uint8_t mac[MAC_ADDRESS_SIZE]
Definition ln882h_ble.h:26