ESPHome  2023.9.1
ble_client_base.cpp
Go to the documentation of this file.
1 #include "ble_client_base.h"
2 
3 #include "esphome/core/helpers.h"
4 #include "esphome/core/log.h"
5 
6 #ifdef USE_ESP32
7 
8 namespace esphome {
9 namespace esp32_ble_client {
10 
11 static const char *const TAG = "esp32_ble_client";
12 static const esp_bt_uuid_t NOTIFY_DESC_UUID = {
13  .len = ESP_UUID_LEN_16,
14  .uuid =
15  {
16  .uuid16 = ESP_GATT_UUID_CHAR_CLIENT_CONFIG,
17  },
18 };
19 
21  static uint8_t connection_index = 0;
22  this->connection_index_ = connection_index++;
23 
24  auto ret = esp_ble_gattc_app_register(this->app_id);
25  if (ret) {
26  ESP_LOGE(TAG, "gattc app register failed. app_id=%d code=%d", this->app_id, ret);
27  this->mark_failed();
28  }
30 }
31 
33  // READY_TO_CONNECT means we have discovered the device
34  // and the scanner has been stopped by the tracker.
35  if (this->state_ == espbt::ClientState::READY_TO_CONNECT) {
36  this->connect();
37  }
38 }
39 
41 
43  if (this->address_ == 0 || device.address_uint64() != this->address_)
44  return false;
45  if (this->state_ != espbt::ClientState::IDLE && this->state_ != espbt::ClientState::SEARCHING)
46  return false;
47 
48  ESP_LOGD(TAG, "[%d] [%s] Found device", this->connection_index_, this->address_str_.c_str());
49  this->set_state(espbt::ClientState::DISCOVERED);
50 
51  auto addr = device.address_uint64();
52  this->remote_bda_[0] = (addr >> 40) & 0xFF;
53  this->remote_bda_[1] = (addr >> 32) & 0xFF;
54  this->remote_bda_[2] = (addr >> 24) & 0xFF;
55  this->remote_bda_[3] = (addr >> 16) & 0xFF;
56  this->remote_bda_[4] = (addr >> 8) & 0xFF;
57  this->remote_bda_[5] = (addr >> 0) & 0xFF;
58  this->remote_addr_type_ = device.get_address_type();
59  return true;
60 }
61 
63  ESP_LOGI(TAG, "[%d] [%s] 0x%02x Attempting BLE connection", this->connection_index_, this->address_str_.c_str(),
64  this->remote_addr_type_);
65  this->paired_ = false;
66  auto ret = esp_ble_gattc_open(this->gattc_if_, this->remote_bda_, this->remote_addr_type_, true);
67  if (ret) {
68  ESP_LOGW(TAG, "[%d] [%s] esp_ble_gattc_open error, status=%d", this->connection_index_, this->address_str_.c_str(),
69  ret);
71  } else {
72  this->set_state(espbt::ClientState::CONNECTING);
73  }
74 }
75 
76 esp_err_t BLEClientBase::pair() { return esp_ble_set_encryption(this->remote_bda_, ESP_BLE_SEC_ENCRYPT); }
77 
79  if (this->state_ == espbt::ClientState::IDLE || this->state_ == espbt::ClientState::DISCONNECTING)
80  return;
81  ESP_LOGI(TAG, "[%d] [%s] Disconnecting.", this->connection_index_, this->address_str_.c_str());
82  auto err = esp_ble_gattc_close(this->gattc_if_, this->conn_id_);
83  if (err != ESP_OK) {
84  ESP_LOGW(TAG, "[%d] [%s] esp_ble_gattc_close error, err=%d", this->connection_index_, this->address_str_.c_str(),
85  err);
86  }
87 
88  if (this->state_ == espbt::ClientState::SEARCHING || this->state_ == espbt::ClientState::READY_TO_CONNECT ||
89  this->state_ == espbt::ClientState::DISCOVERED) {
90  this->set_address(0);
92  } else {
93  this->set_state(espbt::ClientState::DISCONNECTING);
94  }
95 }
96 
98  for (auto &svc : this->services_)
99  delete svc; // NOLINT(cppcoreguidelines-owning-memory)
100  this->services_.clear();
101 #ifndef CONFIG_BT_GATTC_CACHE_NVS_FLASH
102  esp_ble_gattc_cache_clean(this->remote_bda_);
103 #endif
104 }
105 
106 bool BLEClientBase::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t esp_gattc_if,
107  esp_ble_gattc_cb_param_t *param) {
108  if (event == ESP_GATTC_REG_EVT && this->app_id != param->reg.app_id)
109  return false;
110  if (event != ESP_GATTC_REG_EVT && esp_gattc_if != ESP_GATT_IF_NONE && esp_gattc_if != this->gattc_if_)
111  return false;
112 
113  ESP_LOGV(TAG, "[%d] [%s] gattc_event_handler: event=%d gattc_if=%d", this->connection_index_,
114  this->address_str_.c_str(), event, esp_gattc_if);
115 
116  switch (event) {
117  case ESP_GATTC_REG_EVT: {
118  if (param->reg.status == ESP_GATT_OK) {
119  ESP_LOGV(TAG, "[%d] [%s] gattc registered app id %d", this->connection_index_, this->address_str_.c_str(),
120  this->app_id);
121  this->gattc_if_ = esp_gattc_if;
122  } else {
123  ESP_LOGE(TAG, "[%d] [%s] gattc app registration failed id=%d code=%d", this->connection_index_,
124  this->address_str_.c_str(), param->reg.app_id, param->reg.status);
125  }
126  break;
127  }
128  case ESP_GATTC_OPEN_EVT: {
129  ESP_LOGV(TAG, "[%d] [%s] ESP_GATTC_OPEN_EVT", this->connection_index_, this->address_str_.c_str());
130  this->conn_id_ = param->open.conn_id;
131  this->service_count_ = 0;
132  if (param->open.status != ESP_GATT_OK && param->open.status != ESP_GATT_ALREADY_OPEN) {
133  ESP_LOGW(TAG, "[%d] [%s] Connection failed, status=%d", this->connection_index_, this->address_str_.c_str(),
134  param->open.status);
136  break;
137  }
138  auto ret = esp_ble_gattc_send_mtu_req(this->gattc_if_, param->open.conn_id);
139  if (ret) {
140  ESP_LOGW(TAG, "[%d] [%s] esp_ble_gattc_send_mtu_req failed, status=%x", this->connection_index_,
141  this->address_str_.c_str(), ret);
142  }
143  if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE) {
144  ESP_LOGI(TAG, "[%d] [%s] Connected", this->connection_index_, this->address_str_.c_str());
146  this->state_ = espbt::ClientState::ESTABLISHED;
147  break;
148  }
149  esp_ble_gattc_search_service(esp_gattc_if, param->cfg_mtu.conn_id, nullptr);
150  break;
151  }
152  case ESP_GATTC_CFG_MTU_EVT: {
153  if (param->cfg_mtu.status != ESP_GATT_OK) {
154  ESP_LOGW(TAG, "[%d] [%s] cfg_mtu failed, mtu %d, status %d", this->connection_index_,
155  this->address_str_.c_str(), param->cfg_mtu.mtu, param->cfg_mtu.status);
157  break;
158  }
159  ESP_LOGV(TAG, "[%d] [%s] cfg_mtu status %d, mtu %d", this->connection_index_, this->address_str_.c_str(),
160  param->cfg_mtu.status, param->cfg_mtu.mtu);
161  this->mtu_ = param->cfg_mtu.mtu;
162  break;
163  }
164  case ESP_GATTC_DISCONNECT_EVT: {
165  if (memcmp(param->disconnect.remote_bda, this->remote_bda_, 6) != 0)
166  return false;
167  ESP_LOGV(TAG, "[%d] [%s] ESP_GATTC_DISCONNECT_EVT, reason %d", this->connection_index_,
168  this->address_str_.c_str(), param->disconnect.reason);
169  this->release_services();
171  break;
172  }
173  case ESP_GATTC_SEARCH_RES_EVT: {
174  this->service_count_++;
175  if (this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
176  // V3 clients don't need services initialized since
177  // they only request by handle after receiving the services.
178  break;
179  }
180  BLEService *ble_service = new BLEService(); // NOLINT(cppcoreguidelines-owning-memory)
181  ble_service->uuid = espbt::ESPBTUUID::from_uuid(param->search_res.srvc_id.uuid);
182  ble_service->start_handle = param->search_res.start_handle;
183  ble_service->end_handle = param->search_res.end_handle;
184  ble_service->client = this;
185  this->services_.push_back(ble_service);
186  break;
187  }
188  case ESP_GATTC_SEARCH_CMPL_EVT: {
189  ESP_LOGV(TAG, "[%d] [%s] ESP_GATTC_SEARCH_CMPL_EVT", this->connection_index_, this->address_str_.c_str());
190  for (auto &svc : this->services_) {
191  ESP_LOGV(TAG, "[%d] [%s] Service UUID: %s", this->connection_index_, this->address_str_.c_str(),
192  svc->uuid.to_string().c_str());
193  ESP_LOGV(TAG, "[%d] [%s] start_handle: 0x%x end_handle: 0x%x", this->connection_index_,
194  this->address_str_.c_str(), svc->start_handle, svc->end_handle);
195  }
196  ESP_LOGI(TAG, "[%d] [%s] Connected", this->connection_index_, this->address_str_.c_str());
198  this->state_ = espbt::ClientState::ESTABLISHED;
199  break;
200  }
201  case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
202  if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE ||
203  this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
204  // Client is responsible for flipping the descriptor value
205  // when using the cache
206  break;
207  }
208  esp_gattc_descr_elem_t desc_result;
209  uint16_t count = 1;
210  esp_gatt_status_t descr_status =
211  esp_ble_gattc_get_descr_by_char_handle(this->gattc_if_, this->connection_index_, param->reg_for_notify.handle,
212  NOTIFY_DESC_UUID, &desc_result, &count);
213  if (descr_status != ESP_GATT_OK) {
214  ESP_LOGW(TAG, "[%d] [%s] esp_ble_gattc_get_descr_by_char_handle error, status=%d", this->connection_index_,
215  this->address_str_.c_str(), descr_status);
216  break;
217  }
218  esp_gattc_char_elem_t char_result;
219  esp_gatt_status_t char_status =
220  esp_ble_gattc_get_all_char(this->gattc_if_, this->connection_index_, param->reg_for_notify.handle,
221  param->reg_for_notify.handle, &char_result, &count, 0);
222  if (char_status != ESP_GATT_OK) {
223  ESP_LOGW(TAG, "[%d] [%s] esp_ble_gattc_get_all_char error, status=%d", this->connection_index_,
224  this->address_str_.c_str(), char_status);
225  break;
226  }
227 
228  /*
229  1 = notify
230  2 = indicate
231  */
232  uint16_t notify_en = char_result.properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY ? 1 : 2;
233  esp_err_t status =
234  esp_ble_gattc_write_char_descr(this->gattc_if_, this->conn_id_, desc_result.handle, sizeof(notify_en),
235  (uint8_t *) &notify_en, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE);
236  if (status) {
237  ESP_LOGW(TAG, "[%d] [%s] esp_ble_gattc_write_char_descr error, status=%d", this->connection_index_,
238  this->address_str_.c_str(), status);
239  }
240  break;
241  }
242 
243  default:
244  break;
245  }
246  return true;
247 }
248 
249 void BLEClientBase::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
250  switch (event) {
251  // This event is sent by the server when it requests security
252  case ESP_GAP_BLE_SEC_REQ_EVT:
253  if (memcmp(param->ble_security.auth_cmpl.bd_addr, this->remote_bda_, 6) != 0)
254  break;
255  ESP_LOGV(TAG, "[%d] [%s] ESP_GAP_BLE_SEC_REQ_EVT %x", this->connection_index_, this->address_str_.c_str(), event);
256  esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true);
257  break;
258  // This event is sent once authentication has completed
259  case ESP_GAP_BLE_AUTH_CMPL_EVT:
260  if (memcmp(param->ble_security.auth_cmpl.bd_addr, this->remote_bda_, 6) != 0)
261  break;
262  esp_bd_addr_t bd_addr;
263  memcpy(bd_addr, param->ble_security.auth_cmpl.bd_addr, sizeof(esp_bd_addr_t));
264  ESP_LOGI(TAG, "[%d] [%s] auth complete. remote BD_ADDR: %s", this->connection_index_, this->address_str_.c_str(),
265  format_hex(bd_addr, 6).c_str());
266  if (!param->ble_security.auth_cmpl.success) {
267  ESP_LOGE(TAG, "[%d] [%s] auth fail reason = 0x%x", this->connection_index_, this->address_str_.c_str(),
268  param->ble_security.auth_cmpl.fail_reason);
269  } else {
270  this->paired_ = true;
271  ESP_LOGV(TAG, "[%d] [%s] auth success. address type = %d auth mode = %d", this->connection_index_,
272  this->address_str_.c_str(), param->ble_security.auth_cmpl.addr_type,
273  param->ble_security.auth_cmpl.auth_mode);
274  }
275  break;
276  // There are other events we'll want to implement at some point to support things like pass key
277  // https://github.com/espressif/esp-idf/blob/cba69dd088344ed9d26739f04736ae7a37541b3a/examples/bluetooth/bluedroid/ble/gatt_security_client/tutorial/Gatt_Security_Client_Example_Walkthrough.md
278  default:
279  break;
280  }
281 }
282 
283 // Parse GATT values into a float for a sensor.
284 // Ref: https://www.bluetooth.com/specifications/assigned-numbers/format-types/
285 float BLEClientBase::parse_char_value(uint8_t *value, uint16_t length) {
286  // A length of one means a single octet value.
287  if (length == 0)
288  return 0;
289  if (length == 1)
290  return (float) ((uint8_t) value[0]);
291 
292  switch (value[0]) {
293  case 0x1: // boolean.
294  case 0x2: // 2bit.
295  case 0x3: // nibble.
296  case 0x4: // uint8.
297  return (float) ((uint8_t) value[1]);
298  case 0x5: // uint12.
299  case 0x6: // uint16.
300  if (length > 2) {
301  return (float) encode_uint16(value[1], value[2]);
302  }
303  // fall through
304  case 0x7: // uint24.
305  if (length > 3) {
306  return (float) encode_uint24(value[1], value[2], value[3]);
307  }
308  // fall through
309  case 0x8: // uint32.
310  if (length > 4) {
311  return (float) encode_uint32(value[1], value[2], value[3], value[4]);
312  }
313  // fall through
314  case 0xC: // int8.
315  return (float) ((int8_t) value[1]);
316  case 0xD: // int12.
317  case 0xE: // int16.
318  if (length > 2) {
319  return (float) ((int16_t) (value[1] << 8) + (int16_t) value[2]);
320  }
321  // fall through
322  case 0xF: // int24.
323  if (length > 3) {
324  return (float) ((int32_t) (value[1] << 16) + (int32_t) (value[2] << 8) + (int32_t) (value[3]));
325  }
326  // fall through
327  case 0x10: // int32.
328  if (length > 4) {
329  return (float) ((int32_t) (value[1] << 24) + (int32_t) (value[2] << 16) + (int32_t) (value[3] << 8) +
330  (int32_t) (value[4]));
331  }
332  }
333  ESP_LOGW(TAG, "[%d] [%s] Cannot parse characteristic value of type 0x%x length %d", this->connection_index_,
334  this->address_str_.c_str(), value[0], length);
335  return NAN;
336 }
337 
339  for (auto *svc : this->services_) {
340  if (svc->uuid == uuid)
341  return svc;
342  }
343  return nullptr;
344 }
345 
347 
349  auto *svc = this->get_service(service);
350  if (svc == nullptr)
351  return nullptr;
352  return svc->get_characteristic(chr);
353 }
354 
355 BLECharacteristic *BLEClientBase::get_characteristic(uint16_t service, uint16_t chr) {
357 }
358 
360  for (auto *svc : this->services_) {
361  if (!svc->parsed)
362  svc->parse_characteristics();
363  for (auto *chr : svc->characteristics) {
364  if (chr->handle == handle)
365  return chr;
366  }
367  }
368  return nullptr;
369 }
370 
372  auto *chr = this->get_characteristic(handle);
373  if (chr != nullptr) {
374  if (!chr->parsed)
375  chr->parse_descriptors();
376  for (auto &desc : chr->descriptors) {
377  if (desc->uuid.get_uuid().uuid.uuid16 == ESP_GATT_UUID_CHAR_CLIENT_CONFIG)
378  return desc;
379  }
380  }
381  return nullptr;
382 }
383 
385  auto *svc = this->get_service(service);
386  if (svc == nullptr)
387  return nullptr;
388  auto *ch = svc->get_characteristic(chr);
389  if (ch == nullptr)
390  return nullptr;
391  return ch->get_descriptor(descr);
392 }
393 
394 BLEDescriptor *BLEClientBase::get_descriptor(uint16_t service, uint16_t chr, uint16_t descr) {
397 }
398 
400  for (auto *svc : this->services_) {
401  if (!svc->parsed)
402  svc->parse_characteristics();
403  for (auto *chr : svc->characteristics) {
404  if (!chr->parsed)
405  chr->parse_descriptors();
406  for (auto *desc : chr->descriptors) {
407  if (desc->handle == handle)
408  return desc;
409  }
410  }
411  }
412  return nullptr;
413 }
414 
415 } // namespace esp32_ble_client
416 } // namespace esphome
417 
418 #endif // USE_ESP32
BLEDescriptor * get_descriptor(espbt::ESPBTUUID service, espbt::ESPBTUUID chr, espbt::ESPBTUUID descr)
BLEService * get_service(espbt::ESPBTUUID uuid)
std::string format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
Definition: helpers.cpp:338
std::vector< BLEService * > services_
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition: helpers.h:186
const float AFTER_BLUETOOTH
Definition: component.cpp:21
BLEDescriptor * get_config_descriptor(uint16_t handle)
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid)
Definition: ble_uuid.cpp:91
virtual void set_state(ClientState st)
static ESPBTUUID from_uint16(uint16_t uuid)
Definition: ble_uuid.cpp:16
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition: helpers.h:191
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition: helpers.h:182
esp_ble_addr_type_t get_address_type() const
uint8_t status
Definition: bl0942.h:23
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:112
uint16_t length
Definition: tt21100.cpp:12
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
bool parse_device(const espbt::ESPBTDevice &device) override
bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
float parse_char_value(uint8_t *value, uint16_t length)