ESPHome  2023.8.3
ble_rssi_sensor.cpp
Go to the documentation of this file.
1 #include "ble_rssi_sensor.h"
2 #include "esphome/core/log.h"
4 #include "esphome/core/helpers.h"
6 
7 #ifdef USE_ESP32
8 
9 namespace esphome {
10 namespace ble_client {
11 
12 static const char *const TAG = "ble_rssi_sensor";
13 
15 
17  LOG_SENSOR("", "BLE Client RSSI Sensor", this);
18  ESP_LOGCONFIG(TAG, " MAC address : %s", this->parent()->address_str().c_str());
19  LOG_UPDATE_INTERVAL(this);
20 }
21 
22 void BLEClientRSSISensor::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
23  esp_ble_gattc_cb_param_t *param) {
24  switch (event) {
25  case ESP_GATTC_OPEN_EVT: {
26  if (param->open.status == ESP_GATT_OK) {
27  ESP_LOGI(TAG, "[%s] Connected successfully!", this->get_name().c_str());
28  break;
29  }
30  break;
31  }
32  case ESP_GATTC_DISCONNECT_EVT: {
33  ESP_LOGW(TAG, "[%s] Disconnected!", this->get_name().c_str());
34  this->status_set_warning();
35  this->publish_state(NAN);
36  break;
37  }
38  case ESP_GATTC_SEARCH_CMPL_EVT:
39  this->node_state = espbt::ClientState::ESTABLISHED;
40  break;
41  default:
42  break;
43  }
44 }
45 
46 void BLEClientRSSISensor::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
47  switch (event) {
48  // server response on RSSI request:
49  case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
50  if (param->read_rssi_cmpl.status == ESP_BT_STATUS_SUCCESS) {
51  int8_t rssi = param->read_rssi_cmpl.rssi;
52  ESP_LOGI(TAG, "ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT RSSI: %d", rssi);
53  this->publish_state(rssi);
54  }
55  break;
56  default:
57  break;
58  }
59 }
60 
62  if (this->node_state != espbt::ClientState::ESTABLISHED) {
63  ESP_LOGW(TAG, "[%s] Cannot poll, not connected", this->get_name().c_str());
64  return;
65  }
66 
67  ESP_LOGV(TAG, "requesting rssi from %s", this->parent()->address_str().c_str());
68  auto status = esp_ble_gap_read_rssi(this->parent()->get_remote_bda());
69  if (status != ESP_OK) {
70  ESP_LOGW(TAG, "esp_ble_gap_read_rssi error, address=%s, status=%d", this->parent()->address_str().c_str(), status);
71  this->status_set_warning();
72  this->publish_state(NAN);
73  }
74 }
75 
76 } // namespace ble_client
77 } // namespace esphome
78 #endif
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
void status_set_warning()
Definition: component.cpp:145
uint8_t status
Definition: bl0942.h:23
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
const StringRef & get_name() const
Definition: entity_base.cpp:10
espbt::ClientState node_state
Definition: ble_client.h:38