Skip to main content

m5stack_core/driver/radio/
ble.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! BLE radio driver wrapper around `esp-radio`.
3//!
4//! Initializes the ESP32/ESP32-S3 radio coprocessor and returns a
5//! `BleConnector` for use with the `trouble-host` BLE stack.
6//!
7//! Ref: <https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/index.html>
8use esp_hal::peripherals::BT;
9use esp_radio::ble::{
10    Config, InvalidConfigError,
11    controller::{BleConnector, BleInitError},
12};
13use thiserror_no_std::Error;
14
15#[derive(Debug, Error)]
16pub enum RadioError {
17    #[error("Failed to initialize BLE controller")]
18    BleInitError(#[from] BleInitError),
19
20    #[error("Failed to initialize BLE controller")]
21    BleConfigError(#[from] InvalidConfigError),
22}
23
24pub struct BleRadio {
25    pub ble_connector: BleConnector<'static>,
26}
27
28/// What the stack runs on the controller at once, beyond its scan.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub struct BleUse {
31    /// An advertising set next to the scan.
32    pub advertise: bool,
33    /// Simultaneous connections.
34    pub connections: u8,
35}
36
37impl BleUse {
38    /// esp-radio's `max_connections` for this use. ESP32 feeds it to
39    /// `ble_max_conn`, ESP32-S3 to `ble_max_act`: one pool for the scan, every
40    /// advertising set and every connection, so an advert needs its own slot.
41    pub const fn max_connections(self) -> u8 {
42        let connections = if self.connections == 0 {
43            1
44        } else {
45            self.connections
46        };
47        if cfg!(feature = "cores3") {
48            1 + self.advertise as u8 + self.connections
49        } else {
50            connections
51        }
52    }
53}
54
55impl BleRadio {
56    /// Initialize BLE in scan-only mode with minimal buffer footprint.
57    ///
58    /// esp-radio's `Config::default()` sizes the BT-controller blob for
59    /// `max_connections=6` and `scan_duplicate_list_count=100`. On ESP32-S3
60    /// that defaults to ~36 KB of heap, which doesn't fit alongside LVGL on
61    /// cores3 (56 KB heap). Our use case is passive scanning of Victron
62    /// advertisements — we never open a connection, and only a handful of
63    /// distinct advertisers exist on the bus.
64    ///
65    /// `max_connections=1` is the minimum the controller accepts. Setting
66    /// it to 1 shrinks the per-connection static state. Combined with a
67    /// 10-entry duplicate-filter (the spec minimum, range 10–1000), this
68    /// frees ~10 KB on ESP32-S3 and a smaller amount on ESP32.
69    pub fn new(bt: BT<'static>) -> Result<Self, RadioError> {
70        Self::with_use(bt, BleUse::default())
71    }
72
73    /// Like [`new`](Self::new), sized for `ble_use` on top of the scan. On
74    /// ESP32-S3 an advertiser on the scan-only controller gets HCI Memory
75    /// Capacity Exceeded from every `LE Set Advertising Parameters`.
76    pub fn with_use(bt: BT<'static>, ble_use: BleUse) -> Result<Self, RadioError> {
77        // task_stack_size: BLE controller's own task stack (esp-radio default
78        // is 4096 B). The HIL hit a stack-guard watchpoint in
79        // `ld_sscan_frm_cbk` (controller's scan-frame callback): SP within
80        // 32 B of the per-task guard while a `r_rwbtdm_isr_wrapper` was
81        // nesting on top. Sized so the controller's deepest ISR-nested path
82        // has room without resizing the main task stack region (pinned at
83        // [28, 80] KB by ESP_HAL_CONFIG_MAIN_STACK_*).
84        //
85        // 10 KB, not 8: a consumer measured 7120 B of 8272 on fire27, leaving
86        // 1152 B before that guard. 10 KB restores the ~69% the 8 KB choice
87        // had when it was made. Not more, because it costs heap, and fire27
88        // already fails LVGL pool allocations on contiguity, not capacity.
89        let cfg = Config::default()
90            .with_task_priority(10)
91            .with_max_connections(ble_use.max_connections())
92            .with_scan_duplicate_list_count(10)
93            .with_task_stack_size(10240);
94        let ble_connector = BleConnector::new(bt, cfg)?;
95
96        Ok(Self { ble_connector })
97    }
98}