ESPHome  2023.3.1
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 
30 struct ServiceData {
33 };
34 
36  public:
37  ESPBLEiBeacon() { memset(&this->beacon_data_, 0, sizeof(this->beacon_data_)); }
38  ESPBLEiBeacon(const uint8_t *data);
39  static optional<ESPBLEiBeacon> from_manufacturer_data(const ServiceData &data);
40 
41  uint16_t get_major() { return ((this->beacon_data_.major & 0xFF) << 8) | (this->beacon_data_.major >> 8); }
42  uint16_t get_minor() { return ((this->beacon_data_.minor & 0xFF) << 8) | (this->beacon_data_.minor >> 8); }
43  int8_t get_signal_power() { return this->beacon_data_.signal_power; }
44  ESPBTUUID get_uuid() { return ESPBTUUID::from_raw(this->beacon_data_.proximity_uuid); }
45 
46  protected:
47  struct {
48  uint8_t sub_type;
49  uint8_t length;
50  uint8_t proximity_uuid[16];
51  uint16_t major;
52  uint16_t minor;
53  int8_t signal_power;
54  } PACKED beacon_data_;
55 };
56 
57 class ESPBTDevice {
58  public:
59  void parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
60 
61  std::string address_str() const;
62 
63  uint64_t address_uint64() const;
64 
65  const uint8_t *address() const { return address_; }
66 
67  esp_ble_addr_type_t get_address_type() const { return this->address_type_; }
68  int get_rssi() const { return rssi_; }
69  const std::string &get_name() const { return this->name_; }
70 
71  const std::vector<int8_t> &get_tx_powers() const { return tx_powers_; }
72 
73  const optional<uint16_t> &get_appearance() const { return appearance_; }
74  const optional<uint8_t> &get_ad_flag() const { return ad_flag_; }
75  const std::vector<ESPBTUUID> &get_service_uuids() const { return service_uuids_; }
76 
77  const std::vector<ServiceData> &get_manufacturer_datas() const { return manufacturer_datas_; }
78 
79  const std::vector<ServiceData> &get_service_datas() const { return service_datas_; }
80 
81  const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &get_scan_result() const { return scan_result_; }
82 
84  for (auto &it : this->manufacturer_datas_) {
86  if (res.has_value())
87  return *res;
88  }
89  return {};
90  }
91 
92  protected:
93  void parse_adv_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
94 
95  esp_bd_addr_t address_{
96  0,
97  };
98  esp_ble_addr_type_t address_type_{BLE_ADDR_TYPE_PUBLIC};
99  int rssi_{0};
100  std::string name_{};
101  std::vector<int8_t> tx_powers_{};
102  optional<uint16_t> appearance_{};
103  optional<uint8_t> ad_flag_{};
104  std::vector<ESPBTUUID> service_uuids_{};
105  std::vector<ServiceData> manufacturer_datas_{};
106  std::vector<ServiceData> service_datas_{};
107  esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_result_{};
108 };
109 
110 class ESP32BLETracker;
111 
113  public:
114  virtual void on_scan_end() {}
115  virtual bool parse_device(const ESPBTDevice &device) = 0;
116  void set_parent(ESP32BLETracker *parent) { parent_ = parent; }
117 
118  protected:
119  ESP32BLETracker *parent_{nullptr};
120 };
121 
122 enum class ClientState {
123  // Connection is allocated
124  INIT,
125  // Client is disconnecting
127  // Connection is idle, no device detected.
128  IDLE,
129  // Searching for device.
130  SEARCHING,
131  // Device advertisement found.
132  DISCOVERED,
133  // Device is discovered and the scanner is stopped
135  // Connection in progress.
136  CONNECTING,
137  // Initial connection established.
138  CONNECTED,
139  // The client and sub-clients have completed setup.
140  ESTABLISHED,
141 };
142 
143 enum class ConnectionType {
144  // The default connection type, we hold all the services in ram
145  // for the duration of the connection.
146  V1,
147  // The client has a cache of the services and mtu so we should not
148  // fetch them again
150  // The client does not need the services and mtu once we send them
151  // so we should wipe them from memory as soon as we send them
153 };
154 
156  public:
157  virtual bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
158  esp_ble_gattc_cb_param_t *param) = 0;
159  virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
160  virtual void connect() = 0;
161  virtual void set_state(ClientState st) { this->state_ = st; }
162  ClientState state() const { return state_; }
163  int app_id;
164 
165  protected:
167 };
168 
169 class ESP32BLETracker : public Component, public GAPEventHandler, public GATTcEventHandler, public Parented<ESP32BLE> {
170  public:
171  void set_scan_duration(uint32_t scan_duration) { scan_duration_ = scan_duration; }
172  void set_scan_interval(uint32_t scan_interval) { scan_interval_ = scan_interval; }
173  void set_scan_window(uint32_t scan_window) { scan_window_ = scan_window; }
174  void set_scan_active(bool scan_active) { scan_active_ = scan_active; }
175  void set_scan_continuous(bool scan_continuous) { scan_continuous_ = scan_continuous; }
176 
178  void setup() override;
179  void dump_config() override;
180  float get_setup_priority() const override;
181 
182  void loop() override;
183 
185  listener->set_parent(this);
186  this->listeners_.push_back(listener);
187  }
188 
189  void register_client(ESPBTClient *client);
190 
191  void print_bt_device_info(const ESPBTDevice &device);
192 
193  void start_scan();
194  void stop_scan();
195 
196  void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
197  esp_ble_gattc_cb_param_t *param) override;
198  void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
199 
200  protected:
202  void start_scan_(bool first);
204  void end_of_scan_();
206  void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
208  void gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param);
210  void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param);
212  void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param);
213 
214  int app_id_;
215 
217  std::vector<uint64_t> already_discovered_;
218  std::vector<ESPBTDeviceListener *> listeners_;
220  std::vector<ESPBTClient *> clients_;
222  esp_ble_scan_params_t scan_params_;
224  uint32_t scan_duration_;
225  uint32_t scan_interval_;
226  uint32_t scan_window_;
231  SemaphoreHandle_t scan_result_lock_;
232  SemaphoreHandle_t scan_end_lock_;
233  size_t scan_result_index_{0};
234 #if CONFIG_SPIRAM
235  const static u_int8_t SCAN_RESULT_BUFFER_SIZE = 32;
236 #else
237  const static u_int8_t SCAN_RESULT_BUFFER_SIZE = 16;
238 #endif // CONFIG_SPIRAM
239  esp_ble_gap_cb_param_t::ble_scan_result_evt_param *scan_result_buffer_;
240  esp_bt_status_t scan_start_failed_{ESP_BT_STATUS_SUCCESS};
241  esp_bt_status_t scan_set_param_failed_{ESP_BT_STATUS_SUCCESS};
242 };
243 
244 // NOLINTNEXTLINE
246 
247 } // namespace esp32_ble_tracker
248 } // namespace esphome
249 
250 #endif
void setup()
optional< ESPBLEiBeacon > get_ibeacon() const
void loop()
struct esphome::sen5x::Sen5xBaselines PACKED
void register_listener(ESPBTDeviceListener *listener)
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
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.
Definition: a4988.cpp:4
void set_scan_duration(uint32_t scan_duration)
static ESPBTUUID from_raw(const uint8_t *data)
Definition: ble_uuid.cpp:27
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:505
const optional< uint8_t > & get_ad_flag() const