ESPHome  2024.10.2
ble_rssi_sensor.cpp
Go to the documentation of this file.
1 #include "ble_rssi_sensor.h"
4 #include "esphome/core/helpers.h"
5 #include "esphome/core/log.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_CLOSE_EVT: {
26  this->status_set_warning();
27  this->publish_state(NAN);
28  break;
29  }
30  case ESP_GATTC_SEARCH_CMPL_EVT: {
31  this->node_state = espbt::ClientState::ESTABLISHED;
32  if (this->should_update_) {
33  this->should_update_ = false;
34  this->get_rssi_();
35  }
36  break;
37  }
38  default:
39  break;
40  }
41 }
42 
43 void BLEClientRSSISensor::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
44  switch (event) {
45  // server response on RSSI request:
46  case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
47  if (param->read_rssi_cmpl.status == ESP_BT_STATUS_SUCCESS) {
48  int8_t rssi = param->read_rssi_cmpl.rssi;
49  ESP_LOGI(TAG, "ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT RSSI: %d", rssi);
50  this->status_clear_warning();
51  this->publish_state(rssi);
52  }
53  break;
54  default:
55  break;
56  }
57 }
58 
60  if (this->node_state != espbt::ClientState::ESTABLISHED) {
61  ESP_LOGW(TAG, "[%s] Cannot poll, not connected", this->get_name().c_str());
62  this->should_update_ = true;
63  return;
64  }
65  this->get_rssi_();
66 }
68  ESP_LOGV(TAG, "requesting rssi from %s", this->parent()->address_str().c_str());
69  auto status = esp_ble_gap_read_rssi(this->parent()->get_remote_bda());
70  if (status != ESP_OK) {
71  ESP_LOGW(TAG, "esp_ble_gap_read_rssi error, address=%s, status=%d", this->parent()->address_str().c_str(), status);
72  this->status_set_warning();
73  this->publish_state(NAN);
74  }
75 }
76 
77 } // namespace ble_client
78 } // namespace esphome
79 #endif
void status_set_warning(const char *message="unspecified")
Definition: component.cpp:151
void status_clear_warning()
Definition: component.cpp:166
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
uint8_t status
Definition: bl0942.h:74
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
const StringRef & get_name() const
Definition: entity_base.cpp:10
espbt::ClientState node_state
Definition: ble_client.h:38