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