ESPHome  2024.5.5
bluetooth_proxy.cpp
Go to the documentation of this file.
1 #include "bluetooth_proxy.h"
2 
3 #include "esphome/core/log.h"
4 #include "esphome/core/macros.h"
5 
6 #ifdef USE_ESP32
7 
8 namespace esphome {
9 namespace bluetooth_proxy {
10 
11 static const char *const TAG = "bluetooth_proxy";
12 static const int DONE_SENDING_SERVICES = -2;
13 
14 std::vector<uint64_t> get_128bit_uuid_vec(esp_bt_uuid_t uuid_source) {
15  esp_bt_uuid_t uuid = espbt::ESPBTUUID::from_uuid(uuid_source).as_128bit().get_uuid();
16  return std::vector<uint64_t>{((uint64_t) uuid.uuid.uuid128[15] << 56) | ((uint64_t) uuid.uuid.uuid128[14] << 48) |
17  ((uint64_t) uuid.uuid.uuid128[13] << 40) | ((uint64_t) uuid.uuid.uuid128[12] << 32) |
18  ((uint64_t) uuid.uuid.uuid128[11] << 24) | ((uint64_t) uuid.uuid.uuid128[10] << 16) |
19  ((uint64_t) uuid.uuid.uuid128[9] << 8) | ((uint64_t) uuid.uuid.uuid128[8]),
20  ((uint64_t) uuid.uuid.uuid128[7] << 56) | ((uint64_t) uuid.uuid.uuid128[6] << 48) |
21  ((uint64_t) uuid.uuid.uuid128[5] << 40) | ((uint64_t) uuid.uuid.uuid128[4] << 32) |
22  ((uint64_t) uuid.uuid.uuid128[3] << 24) | ((uint64_t) uuid.uuid.uuid128[2] << 16) |
23  ((uint64_t) uuid.uuid.uuid128[1] << 8) | ((uint64_t) uuid.uuid.uuid128[0])};
24 }
25 
27 
29  if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr || this->raw_advertisements_)
30  return false;
31 
32  ESP_LOGV(TAG, "Proxying packet from %s - %s. RSSI: %d dB", device.get_name().c_str(), device.address_str().c_str(),
33  device.get_rssi());
34  this->send_api_packet_(device);
35  return true;
36 }
37 
38 bool BluetoothProxy::parse_devices(esp_ble_gap_cb_param_t::ble_scan_result_evt_param *advertisements, size_t count) {
39  if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr || !this->raw_advertisements_)
40  return false;
41 
43  for (size_t i = 0; i < count; i++) {
44  auto &result = advertisements[i];
46  adv.address = esp32_ble::ble_addr_to_uint64(result.bda);
47  adv.rssi = result.rssi;
48  adv.address_type = result.ble_addr_type;
49 
50  uint8_t length = result.adv_data_len + result.scan_rsp_len;
51  adv.data.reserve(length);
52  for (uint16_t i = 0; i < length; i++) {
53  adv.data.push_back(result.ble_adv[i]);
54  }
55 
56  resp.advertisements.push_back(std::move(adv));
57  }
58  ESP_LOGV(TAG, "Proxying %d packets", count);
60  return true;
61 }
64  resp.address = device.address_uint64();
65  resp.address_type = device.get_address_type();
66  if (!device.get_name().empty())
67  resp.name = device.get_name();
68  resp.rssi = device.get_rssi();
69  for (auto uuid : device.get_service_uuids()) {
70  resp.service_uuids.push_back(uuid.to_string());
71  }
72  for (auto &data : device.get_service_datas()) {
73  api::BluetoothServiceData service_data;
74  service_data.uuid = data.uuid.to_string();
75  service_data.data.assign(data.data.begin(), data.data.end());
76  resp.service_data.push_back(std::move(service_data));
77  }
78  for (auto &data : device.get_manufacturer_datas()) {
79  api::BluetoothServiceData manufacturer_data;
80  manufacturer_data.uuid = data.uuid.to_string();
81  manufacturer_data.data.assign(data.data.begin(), data.data.end());
82  resp.manufacturer_data.push_back(std::move(manufacturer_data));
83  }
85 }
86 
88  ESP_LOGCONFIG(TAG, "Bluetooth Proxy:");
89  ESP_LOGCONFIG(TAG, " Active: %s", YESNO(this->active_));
90 }
91 
93  int free = 0;
94  for (auto *connection : this->connections_) {
95  if (connection->address_ == 0) {
96  free++;
97  ESP_LOGV(TAG, "[%d] Free connection", connection->get_connection_index());
98  } else {
99  ESP_LOGV(TAG, "[%d] Used connection by [%s]", connection->get_connection_index(),
100  connection->address_str().c_str());
101  }
102  }
103  return free;
104 }
105 
107  if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr) {
108  for (auto *connection : this->connections_) {
109  if (connection->get_address() != 0) {
110  connection->disconnect();
111  }
112  }
113  return;
114  }
115  for (auto *connection : this->connections_) {
116  if (connection->send_service_ == connection->service_count_) {
117  connection->send_service_ = DONE_SENDING_SERVICES;
118  this->send_gatt_services_done(connection->get_address());
119  if (connection->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE ||
120  connection->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
121  connection->release_services();
122  }
123  } else if (connection->send_service_ >= 0) {
124  esp_gattc_service_elem_t service_result;
125  uint16_t service_count = 1;
126  esp_gatt_status_t service_status =
127  esp_ble_gattc_get_service(connection->get_gattc_if(), connection->get_conn_id(), nullptr, &service_result,
128  &service_count, connection->send_service_);
129  connection->send_service_++;
130  if (service_status != ESP_GATT_OK) {
131  ESP_LOGE(TAG, "[%d] [%s] esp_ble_gattc_get_service error at offset=%d, status=%d",
132  connection->get_connection_index(), connection->address_str().c_str(), connection->send_service_ - 1,
133  service_status);
134  continue;
135  }
136  if (service_count == 0) {
137  ESP_LOGE(TAG, "[%d] [%s] esp_ble_gattc_get_service missing, service_count=%d",
138  connection->get_connection_index(), connection->address_str().c_str(), service_count);
139  continue;
140  }
142  resp.address = connection->get_address();
143  api::BluetoothGATTService service_resp;
144  service_resp.uuid = get_128bit_uuid_vec(service_result.uuid);
145  service_resp.handle = service_result.start_handle;
146  uint16_t char_offset = 0;
147  esp_gattc_char_elem_t char_result;
148  while (true) { // characteristics
149  uint16_t char_count = 1;
150  esp_gatt_status_t char_status = esp_ble_gattc_get_all_char(
151  connection->get_gattc_if(), connection->get_conn_id(), service_result.start_handle,
152  service_result.end_handle, &char_result, &char_count, char_offset);
153  if (char_status == ESP_GATT_INVALID_OFFSET || char_status == ESP_GATT_NOT_FOUND) {
154  break;
155  }
156  if (char_status != ESP_GATT_OK) {
157  ESP_LOGE(TAG, "[%d] [%s] esp_ble_gattc_get_all_char error, status=%d", connection->get_connection_index(),
158  connection->address_str().c_str(), char_status);
159  break;
160  }
161  if (char_count == 0) {
162  break;
163  }
164  api::BluetoothGATTCharacteristic characteristic_resp;
165  characteristic_resp.uuid = get_128bit_uuid_vec(char_result.uuid);
166  characteristic_resp.handle = char_result.char_handle;
167  characteristic_resp.properties = char_result.properties;
168  char_offset++;
169  uint16_t desc_offset = 0;
170  esp_gattc_descr_elem_t desc_result;
171  while (true) { // descriptors
172  uint16_t desc_count = 1;
173  esp_gatt_status_t desc_status =
174  esp_ble_gattc_get_all_descr(connection->get_gattc_if(), connection->get_conn_id(),
175  char_result.char_handle, &desc_result, &desc_count, desc_offset);
176  if (desc_status == ESP_GATT_INVALID_OFFSET || desc_status == ESP_GATT_NOT_FOUND) {
177  break;
178  }
179  if (desc_status != ESP_GATT_OK) {
180  ESP_LOGE(TAG, "[%d] [%s] esp_ble_gattc_get_all_descr error, status=%d", connection->get_connection_index(),
181  connection->address_str().c_str(), desc_status);
182  break;
183  }
184  if (desc_count == 0) {
185  break;
186  }
187  api::BluetoothGATTDescriptor descriptor_resp;
188  descriptor_resp.uuid = get_128bit_uuid_vec(desc_result.uuid);
189  descriptor_resp.handle = desc_result.handle;
190  characteristic_resp.descriptors.push_back(std::move(descriptor_resp));
191  desc_offset++;
192  }
193  service_resp.characteristics.push_back(std::move(characteristic_resp));
194  }
195  resp.services.push_back(std::move(service_resp));
197  }
198  }
199 }
200 
202  if (this->raw_advertisements_)
205 }
206 
207 BluetoothConnection *BluetoothProxy::get_connection_(uint64_t address, bool reserve) {
208  for (auto *connection : this->connections_) {
209  if (connection->get_address() == address)
210  return connection;
211  }
212 
213  if (!reserve)
214  return nullptr;
215 
216  for (auto *connection : this->connections_) {
217  if (connection->get_address() == 0) {
218  connection->send_service_ = DONE_SENDING_SERVICES;
219  connection->set_address(address);
220  // All connections must start at INIT
221  // We only set the state if we allocate the connection
222  // to avoid a race where multiple connection attempts
223  // are made.
224  connection->set_state(espbt::ClientState::INIT);
225  return connection;
226  }
227  }
228 
229  return nullptr;
230 }
231 
233  switch (msg.request_type) {
237  auto *connection = this->get_connection_(msg.address, true);
238  if (connection == nullptr) {
239  ESP_LOGW(TAG, "No free connections available");
240  this->send_device_connection(msg.address, false);
241  return;
242  }
243  if (connection->state() == espbt::ClientState::CONNECTED ||
244  connection->state() == espbt::ClientState::ESTABLISHED) {
245  ESP_LOGW(TAG, "[%d] [%s] Connection already established", connection->get_connection_index(),
246  connection->address_str().c_str());
247  this->send_device_connection(msg.address, true);
248  this->send_connections_free();
249  return;
250  } else if (connection->state() == espbt::ClientState::SEARCHING) {
251  ESP_LOGW(TAG, "[%d] [%s] Connection request ignored, already searching for device",
252  connection->get_connection_index(), connection->address_str().c_str());
253  return;
254  } else if (connection->state() == espbt::ClientState::DISCOVERED) {
255  ESP_LOGW(TAG, "[%d] [%s] Connection request ignored, device already discovered",
256  connection->get_connection_index(), connection->address_str().c_str());
257  return;
258  } else if (connection->state() == espbt::ClientState::READY_TO_CONNECT) {
259  ESP_LOGW(TAG, "[%d] [%s] Connection request ignored, waiting in line to connect",
260  connection->get_connection_index(), connection->address_str().c_str());
261  return;
262  } else if (connection->state() == espbt::ClientState::CONNECTING) {
263  ESP_LOGW(TAG, "[%d] [%s] Connection request ignored, already connecting", connection->get_connection_index(),
264  connection->address_str().c_str());
265  return;
266  } else if (connection->state() == espbt::ClientState::DISCONNECTING) {
267  ESP_LOGW(TAG, "[%d] [%s] Connection request ignored, device is disconnecting",
268  connection->get_connection_index(), connection->address_str().c_str());
269  return;
270  } else if (connection->state() != espbt::ClientState::INIT) {
271  ESP_LOGW(TAG, "[%d] [%s] Connection already in progress", connection->get_connection_index(),
272  connection->address_str().c_str());
273  return;
274  }
276  connection->set_connection_type(espbt::ConnectionType::V3_WITH_CACHE);
277  ESP_LOGI(TAG, "[%d] [%s] Connecting v3 with cache", connection->get_connection_index(),
278  connection->address_str().c_str());
280  connection->set_connection_type(espbt::ConnectionType::V3_WITHOUT_CACHE);
281  ESP_LOGI(TAG, "[%d] [%s] Connecting v3 without cache", connection->get_connection_index(),
282  connection->address_str().c_str());
283  } else {
284  connection->set_connection_type(espbt::ConnectionType::V1);
285  ESP_LOGI(TAG, "[%d] [%s] Connecting v1", connection->get_connection_index(), connection->address_str().c_str());
286  }
287  if (msg.has_address_type) {
288  uint64_to_bd_addr(msg.address, connection->remote_bda_);
289  connection->set_remote_addr_type(static_cast<esp_ble_addr_type_t>(msg.address_type));
290  connection->set_state(espbt::ClientState::DISCOVERED);
291  } else {
292  connection->set_state(espbt::ClientState::SEARCHING);
293  }
294  this->send_connections_free();
295  break;
296  }
298  auto *connection = this->get_connection_(msg.address, false);
299  if (connection == nullptr) {
300  this->send_device_connection(msg.address, false);
301  this->send_connections_free();
302  return;
303  }
304  if (connection->state() != espbt::ClientState::IDLE) {
305  connection->disconnect();
306  } else {
307  connection->set_address(0);
308  this->send_device_connection(msg.address, false);
309  this->send_connections_free();
310  }
311  break;
312  }
314  auto *connection = this->get_connection_(msg.address, false);
315  if (connection != nullptr) {
316  if (!connection->is_paired()) {
317  auto err = connection->pair();
318  if (err != ESP_OK) {
319  this->send_device_pairing(msg.address, false, err);
320  }
321  } else {
322  this->send_device_pairing(msg.address, true);
323  }
324  }
325  break;
326  }
328  esp_bd_addr_t address;
329  uint64_to_bd_addr(msg.address, address);
330  esp_err_t ret = esp_ble_remove_bond_device(address);
331  this->send_device_pairing(msg.address, ret == ESP_OK, ret);
332  break;
333  }
335  esp_bd_addr_t address;
336  uint64_to_bd_addr(msg.address, address);
337  esp_err_t ret = esp_ble_gattc_cache_clean(address);
339  call.address = msg.address;
340  call.success = ret == ESP_OK;
341  call.error = ret;
342 
344 
345  break;
346  }
347  }
348 }
349 
351  auto *connection = this->get_connection_(msg.address, false);
352  if (connection == nullptr) {
353  ESP_LOGW(TAG, "Cannot read GATT characteristic, not connected");
354  this->send_gatt_error(msg.address, msg.handle, ESP_GATT_NOT_CONNECTED);
355  return;
356  }
357 
358  auto err = connection->read_characteristic(msg.handle);
359  if (err != ESP_OK) {
360  this->send_gatt_error(msg.address, msg.handle, err);
361  }
362 }
363 
365  auto *connection = this->get_connection_(msg.address, false);
366  if (connection == nullptr) {
367  ESP_LOGW(TAG, "Cannot write GATT characteristic, not connected");
368  this->send_gatt_error(msg.address, msg.handle, ESP_GATT_NOT_CONNECTED);
369  return;
370  }
371 
372  auto err = connection->write_characteristic(msg.handle, msg.data, msg.response);
373  if (err != ESP_OK) {
374  this->send_gatt_error(msg.address, msg.handle, err);
375  }
376 }
377 
379  auto *connection = this->get_connection_(msg.address, false);
380  if (connection == nullptr) {
381  ESP_LOGW(TAG, "Cannot read GATT descriptor, not connected");
382  this->send_gatt_error(msg.address, msg.handle, ESP_GATT_NOT_CONNECTED);
383  return;
384  }
385 
386  auto err = connection->read_descriptor(msg.handle);
387  if (err != ESP_OK) {
388  this->send_gatt_error(msg.address, msg.handle, err);
389  }
390 }
391 
393  auto *connection = this->get_connection_(msg.address, false);
394  if (connection == nullptr) {
395  ESP_LOGW(TAG, "Cannot write GATT descriptor, not connected");
396  this->send_gatt_error(msg.address, msg.handle, ESP_GATT_NOT_CONNECTED);
397  return;
398  }
399 
400  auto err = connection->write_descriptor(msg.handle, msg.data, true);
401  if (err != ESP_OK) {
402  this->send_gatt_error(msg.address, msg.handle, err);
403  }
404 }
405 
407  auto *connection = this->get_connection_(msg.address, false);
408  if (connection == nullptr || !connection->connected()) {
409  ESP_LOGW(TAG, "Cannot get GATT services, not connected");
410  this->send_gatt_error(msg.address, 0, ESP_GATT_NOT_CONNECTED);
411  return;
412  }
413  if (!connection->service_count_) {
414  ESP_LOGW(TAG, "[%d] [%s] No GATT services found", connection->connection_index_, connection->address_str().c_str());
415  this->send_gatt_services_done(msg.address);
416  return;
417  }
418  if (connection->send_service_ ==
419  DONE_SENDING_SERVICES) // Only start sending services if we're not already sending them
420  connection->send_service_ = 0;
421 }
422 
424  auto *connection = this->get_connection_(msg.address, false);
425  if (connection == nullptr) {
426  ESP_LOGW(TAG, "Cannot notify GATT characteristic, not connected");
427  this->send_gatt_error(msg.address, msg.handle, ESP_GATT_NOT_CONNECTED);
428  return;
429  }
430 
431  auto err = connection->notify_characteristic(msg.handle, msg.enable);
432  if (err != ESP_OK) {
433  this->send_gatt_error(msg.address, msg.handle, err);
434  }
435 }
436 
438  if (this->api_connection_ != nullptr) {
439  ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
440  return;
441  }
442  this->api_connection_ = api_connection;
445 }
446 
448  if (this->api_connection_ != api_connection) {
449  ESP_LOGV(TAG, "API connection is not subscribed");
450  return;
451  }
452  this->api_connection_ = nullptr;
453  this->raw_advertisements_ = false;
455 }
456 
457 void BluetoothProxy::send_device_connection(uint64_t address, bool connected, uint16_t mtu, esp_err_t error) {
458  if (this->api_connection_ == nullptr)
459  return;
461  call.address = address;
462  call.connected = connected;
463  call.mtu = mtu;
464  call.error = error;
466 }
468  if (this->api_connection_ == nullptr)
469  return;
471  call.free = this->get_bluetooth_connections_free();
472  call.limit = this->get_bluetooth_connections_limit();
474 }
475 
477  if (this->api_connection_ == nullptr)
478  return;
480  call.address = address;
482 }
483 
484 void BluetoothProxy::send_gatt_error(uint64_t address, uint16_t handle, esp_err_t error) {
485  if (this->api_connection_ == nullptr)
486  return;
488  call.address = address;
489  call.handle = handle;
490  call.error = error;
492 }
493 
494 void BluetoothProxy::send_device_pairing(uint64_t address, bool paired, esp_err_t error) {
496  call.address = address;
497  call.paired = paired;
498  call.error = error;
499 
501 }
502 
503 void BluetoothProxy::send_device_unpairing(uint64_t address, bool success, esp_err_t error) {
505  call.address = address;
506  call.success = success;
507  call.error = error;
508 
510 }
511 
512 BluetoothProxy *global_bluetooth_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
513 
514 } // namespace bluetooth_proxy
515 } // namespace esphome
516 
517 #endif // USE_ESP32
void send_device_pairing(uint64_t address, bool paired, esp_err_t error=ESP_OK)
std::vector< BluetoothGATTCharacteristic > characteristics
Definition: api_pb2.h:1452
BluetoothConnection * get_connection_(uint64_t address, bool reserve)
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
Definition: ble.cpp:383
bool parse_devices(esp_ble_gap_cb_param_t::ble_scan_result_evt_param *advertisements, size_t count) override
std::vector< BluetoothGATTService > services
Definition: api_pb2.h:1465
std::vector< BluetoothLERawAdvertisement > advertisements
Definition: api_pb2.h:1373
void send_device_unpairing(uint64_t address, bool success, esp_err_t error=ESP_OK)
bool send_bluetooth_gatt_error_response(const BluetoothGATTErrorResponse &msg)
std::vector< BluetoothServiceData > service_data
Definition: api_pb2.h:1344
bool send_bluetooth_device_connection_response(const BluetoothDeviceConnectionResponse &msg)
const std::vector< ServiceData > & get_manufacturer_datas() const
const std::vector< ESPBTUUID > & get_service_uuids() const
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition: util.cpp:15
void bluetooth_device_request(const api::BluetoothDeviceRequest &msg)
BluetoothProxy * global_bluetooth_proxy
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid)
Definition: ble_uuid.cpp:91
std::vector< BluetoothGATTDescriptor > descriptors
Definition: api_pb2.h:1438
std::vector< uint64_t > uuid
Definition: api_pb2.h:1423
bool send_bluetooth_gatt_get_services_response(const BluetoothGATTGetServicesResponse &msg)
esp32_ble_tracker::AdvertisementParserType get_advertisement_parser_type() override
bool send_bluetooth_device_unpairing_response(const BluetoothDeviceUnpairingResponse &msg)
void bluetooth_gatt_read(const api::BluetoothGATTReadRequest &msg)
void send_device_connection(uint64_t address, bool connected, uint16_t mtu=0, esp_err_t error=ESP_OK)
static void uint64_to_bd_addr(uint64_t address, esp_bd_addr_t bd_addr)
enums::BluetoothDeviceRequestType request_type
Definition: api_pb2.h:1385
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override
void bluetooth_gatt_write(const api::BluetoothGATTWriteRequest &msg)
std::vector< uint64_t > get_128bit_uuid_vec(esp_bt_uuid_t uuid_source)
const std::vector< ServiceData > & get_service_datas() const
void bluetooth_gatt_write_descriptor(const api::BluetoothGATTWriteDescriptorRequest &msg)
const uint32_t flags
Definition: stm32flash.h:85
esp_ble_addr_type_t get_address_type() const
void unsubscribe_api_connection(api::APIConnection *api_connection)
void bluetooth_gatt_notify(const api::BluetoothGATTNotifyRequest &msg)
bool send_bluetooth_connections_free_response(const BluetoothConnectionsFreeResponse &msg)
std::vector< BluetoothConnection * > connections_
std::vector< uint64_t > uuid
Definition: api_pb2.h:1450
void send_api_packet_(const esp32_ble_tracker::ESPBTDevice &device)
uint16_t length
Definition: tt21100.cpp:12
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
void bluetooth_gatt_read_descriptor(const api::BluetoothGATTReadDescriptorRequest &msg)
void send_gatt_error(uint64_t address, uint16_t handle, esp_err_t error)
std::vector< BluetoothServiceData > manufacturer_data
Definition: api_pb2.h:1345
const std::string & get_name() const
std::vector< std::string > service_uuids
Definition: api_pb2.h:1343
void subscribe_api_connection(api::APIConnection *api_connection, uint32_t flags)
bool send_bluetooth_device_pairing_response(const BluetoothDevicePairingResponse &msg)
bool send_bluetooth_gatt_get_services_done_response(const BluetoothGATTGetServicesDoneResponse &msg)
ESPBTUUID as_128bit() const
Definition: ble_uuid.cpp:103
bool send_bluetooth_device_clear_cache_response(const BluetoothDeviceClearCacheResponse &msg)
bool send_bluetooth_le_advertisement(const BluetoothLEAdvertisementResponse &msg)
bool send_bluetooth_le_raw_advertisements_response(const BluetoothLERawAdvertisementsResponse &msg)
APIServer * global_api_server
Definition: api_server.cpp:339
void bluetooth_gatt_send_services(const api::BluetoothGATTGetServicesRequest &msg)
esp_bt_uuid_t get_uuid() const
Definition: ble_uuid.cpp:164