ESPHome  2024.4.0
esp32_ble_tracker.h
Go to the documentation of this file.
1 #pragma once
2 
5 #include "esphome/core/helpers.h"
6 
7 #include <array>
8 #include <string>
9 #include <vector>
10 
11 #ifdef USE_ESP32
12 
13 #include <esp_gap_ble_api.h>
14 #include <esp_gattc_api.h>
15 #include <esp_bt_defs.h>
16 
17 #include <freertos/FreeRTOS.h>
18 #include <freertos/semphr.h>
19 
22 
23 namespace esphome {
24 namespace esp32_ble_tracker {
25 
26 using namespace esp32_ble;
27 
28 using adv_data_t = std::vector<uint8_t>;
29 
33 };
34 
35 struct ServiceData {
38 };
39 
41  public:
42  ESPBLEiBeacon() { memset(&this->beacon_data_, 0, sizeof(this->beacon_data_)); }
43  ESPBLEiBeacon(const uint8_t *data);
44  static optional<ESPBLEiBeacon> from_manufacturer_data(const ServiceData &data);
45 
46  uint16_t get_major() { return ((this->beacon_data_.major & 0xFF) << 8) | (this->beacon_data_.major >> 8); }
47  uint16_t get_minor() { return ((this->beacon_data_.minor & 0xFF) << 8) | (this->beacon_data_.minor >> 8); }
48  int8_t get_signal_power() { return this->beacon_data_.signal_power; }
49  ESPBTUUID get_uuid() { return ESPBTUUID::from_raw(this->beacon_data_.proximity_uuid); }
50 
51  protected:
52  struct {
53  uint8_t sub_type;
54  uint8_t length;
55  uint8_t proximity_uuid[16];
56  uint16_t major;
57  uint16_t minor;
58  int8_t signal_power;
59  } PACKED beacon_data_;
60 };
61 
62 class ESPBTDevice {
63  public:
64  void parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
65 
66  std::string address_str() const;
67 
68  uint64_t address_uint64() const;
69 
70  const uint8_t *address() const { return address_; }
71 
72  esp_ble_addr_type_t get_address_type() const { return this->address_type_; }
73  int get_rssi() const { return rssi_; }
74  const std::string &get_name() const { return this->name_; }
75 
76  const std::vector<int8_t> &get_tx_powers() const { return tx_powers_; }
77 
78  const optional<uint16_t> &get_appearance() const { return appearance_; }
79  const optional<uint8_t> &get_ad_flag() const { return ad_flag_; }
80  const std::vector<ESPBTUUID> &get_service_uuids() const { return service_uuids_; }
81 
82  const std::vector<ServiceData> &get_manufacturer_datas() const { return manufacturer_datas_; }
83 
84  const std::vector<ServiceData> &get_service_datas() const { return service_datas_; }
85 
86  const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &get_scan_result() const { return scan_result_; }
87 
89  for (auto &it : this->manufacturer_datas_) {
91  if (res.has_value())
92  return *res;
93  }
94  return {};
95  }
96 
97  protected:
98  void parse_adv_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
99 
100  esp_bd_addr_t address_{
101  0,
102  };
103  esp_ble_addr_type_t address_type_{BLE_ADDR_TYPE_PUBLIC};
104  int rssi_{0};
105  std::string name_{};
106  std::vector<int8_t> tx_powers_{};
107  optional<uint16_t> appearance_{};
108  optional<uint8_t> ad_flag_{};
109  std::vector<ESPBTUUID> service_uuids_{};
110  std::vector<ServiceData> manufacturer_datas_{};
111  std::vector<ServiceData> service_datas_{};
112  esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_result_{};
113 };
114 
115 class ESP32BLETracker;
116 
118  public:
119  virtual void on_scan_end() {}
120  virtual bool parse_device(const ESPBTDevice &device) = 0;
121  virtual bool parse_devices(esp_ble_gap_cb_param_t::ble_scan_result_evt_param *advertisements, size_t count) {
122  return false;
123  };
126  };
127  void set_parent(ESP32BLETracker *parent) { parent_ = parent; }
128 
129  protected:
130  ESP32BLETracker *parent_{nullptr};
131 };
132 
133 enum class ClientState {
134  // Connection is allocated
135  INIT,
136  // Client is disconnecting
138  // Connection is idle, no device detected.
139  IDLE,
140  // Searching for device.
141  SEARCHING,
142  // Device advertisement found.
143  DISCOVERED,
144  // Device is discovered and the scanner is stopped
146  // Connection in progress.
147  CONNECTING,
148  // Initial connection established.
149  CONNECTED,
150  // The client and sub-clients have completed setup.
151  ESTABLISHED,
152 };
153 
154 enum class ConnectionType {
155  // The default connection type, we hold all the services in ram
156  // for the duration of the connection.
157  V1,
158  // The client has a cache of the services and mtu so we should not
159  // fetch them again
161  // The client does not need the services and mtu once we send them
162  // so we should wipe them from memory as soon as we send them
164 };
165 
167  public:
168  virtual bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
169  esp_ble_gattc_cb_param_t *param) = 0;
170  virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
171  virtual void connect() = 0;
172  virtual void set_state(ClientState st) { this->state_ = st; }
173  ClientState state() const { return state_; }
174  int app_id;
175 
176  protected:
178 };
179 
180 class ESP32BLETracker : public Component,
181  public GAPEventHandler,
182  public GATTcEventHandler,
183  public BLEStatusEventHandler,
184  public Parented<ESP32BLE> {
185  public:
186  void set_scan_duration(uint32_t scan_duration) { scan_duration_ = scan_duration; }
187  void set_scan_interval(uint32_t scan_interval) { scan_interval_ = scan_interval; }
188  void set_scan_window(uint32_t scan_window) { scan_window_ = scan_window; }
189  void set_scan_active(bool scan_active) { scan_active_ = scan_active; }
190  void set_scan_continuous(bool scan_continuous) { scan_continuous_ = scan_continuous; }
191 
193  void setup() override;
194  void dump_config() override;
195  float get_setup_priority() const override;
196 
197  void loop() override;
198 
199  void register_listener(ESPBTDeviceListener *listener);
200  void register_client(ESPBTClient *client);
201  void recalculate_advertisement_parser_types();
202 
203  void print_bt_device_info(const ESPBTDevice &device);
204 
205  void start_scan();
206  void stop_scan();
207 
208  void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
209  esp_ble_gattc_cb_param_t *param) override;
210  void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
211  void ble_before_disabled_event_handler() override;
212 
213  protected:
214  void stop_scan_();
216  void start_scan_(bool first);
218  void end_of_scan_();
220  void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
222  void gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param);
224  void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param);
226  void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param);
227 
228  int app_id_;
229 
231  std::vector<uint64_t> already_discovered_;
232  std::vector<ESPBTDeviceListener *> listeners_;
234  std::vector<ESPBTClient *> clients_;
236  esp_ble_scan_params_t scan_params_;
238  uint32_t scan_duration_;
239  uint32_t scan_interval_;
240  uint32_t scan_window_;
245  bool ble_was_disabled_{true};
246  bool raw_advertisements_{false};
247  bool parse_advertisements_{false};
248  SemaphoreHandle_t scan_result_lock_;
249  SemaphoreHandle_t scan_end_lock_;
250  size_t scan_result_index_{0};
251 #if CONFIG_SPIRAM
252  const static u_int8_t SCAN_RESULT_BUFFER_SIZE = 32;
253 #else
254  const static u_int8_t SCAN_RESULT_BUFFER_SIZE = 16;
255 #endif // CONFIG_SPIRAM
256  esp_ble_gap_cb_param_t::ble_scan_result_evt_param *scan_result_buffer_;
257  esp_bt_status_t scan_start_failed_{ESP_BT_STATUS_SUCCESS};
258  esp_bt_status_t scan_set_param_failed_{ESP_BT_STATUS_SUCCESS};
259 };
260 
261 // NOLINTNEXTLINE
263 
264 } // namespace esp32_ble_tracker
265 } // namespace esphome
266 
267 #endif
void setup()
optional< ESPBLEiBeacon > get_ibeacon() const
void loop()
struct esphome::sen5x::Sen5xBaselines PACKED
const std::vector< int8_t > & get_tx_powers() const
const optional< uint16_t > & get_appearance() const
const std::vector< ServiceData > & get_manufacturer_datas() const
const std::vector< ESPBTUUID > & get_service_uuids() const
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
ESP32BLETracker * global_esp32_ble_tracker
virtual void set_state(ClientState st)
esp_ble_gap_cb_param_t::ble_scan_result_evt_param * scan_result_buffer_
const std::vector< ServiceData > & get_service_datas() const
esp_ble_addr_type_t get_address_type() const
const esp_ble_gap_cb_param_t::ble_scan_result_evt_param & get_scan_result() const
virtual AdvertisementParserType get_advertisement_parser_type()
uint32_t scan_duration_
The interval in seconds to perform scans.
std::vector< uint8_t > adv_data_t
std::vector< uint64_t > already_discovered_
Vector of addresses that have already been printed in print_bt_device_info.
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
virtual bool parse_devices(esp_ble_gap_cb_param_t::ble_scan_result_evt_param *advertisements, size_t count)
void set_scan_duration(uint32_t scan_duration)
static ESPBTUUID from_raw(const uint8_t *data)
Definition: ble_uuid.cpp:28
const std::string & get_name() const
void set_scan_interval(uint32_t scan_interval)
static optional< ESPBLEiBeacon > from_manufacturer_data(const ServiceData &data)
void set_scan_continuous(bool scan_continuous)
std::vector< ESPBTDeviceListener * > listeners_
std::vector< ESPBTClient * > clients_
Client parameters.
Helper class to easily give an object a parent of type T.
Definition: helpers.h:515
const optional< uint8_t > & get_ad_flag() const