ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
ble_rssi_sensor.cpp
Go to the documentation of this file.
1#include "ble_rssi_sensor.h"
5#include "esphome/core/log.h"
6
7#ifdef USE_ESP32
8
9namespace esphome::ble_client {
10
11static const char *const TAG = "ble_rssi_sensor";
12
14 // Parent BLEClientNode has a loop() method, but this component uses
15 // polling via update() and BLE GAP callbacks so loop isn't needed
16 this->disable_loop();
17}
18
20 LOG_SENSOR("", "BLE Client RSSI Sensor", this);
21 ESP_LOGCONFIG(TAG, " MAC address : %s", this->parent()->address_str());
22 LOG_UPDATE_INTERVAL(this);
23}
24
25void BLEClientRSSISensor::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
26 esp_ble_gattc_cb_param_t *param) {
27 switch (event) {
28 case ESP_GATTC_CLOSE_EVT: {
29 this->status_set_warning();
30 this->publish_state(NAN);
31 break;
32 }
33 case ESP_GATTC_SEARCH_CMPL_EVT: {
34 this->node_state = espbt::ClientState::ESTABLISHED;
35 if (this->should_update_) {
36 this->should_update_ = false;
37 this->get_rssi_();
38 }
39 break;
40 }
41 default:
42 break;
43 }
44}
45
46void 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 (!this->parent()->check_addr(param->read_rssi_cmpl.remote_addr))
51 return;
52 if (param->read_rssi_cmpl.status == ESP_BT_STATUS_SUCCESS) {
53 int8_t rssi = param->read_rssi_cmpl.rssi;
54 ESP_LOGI(TAG, "ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT RSSI: %d", rssi);
56 this->publish_state(rssi);
57 }
58 break;
59 default:
60 break;
61 }
62}
63
65 if (this->node_state != espbt::ClientState::ESTABLISHED) {
66 ESP_LOGW(TAG, "[%s] Cannot poll, not connected", this->get_name().c_str());
67 this->should_update_ = true;
68 return;
69 }
70 this->get_rssi_();
71}
73 ESP_LOGV(TAG, "requesting rssi from %s", this->parent()->address_str());
74 auto status = esp_ble_gap_read_rssi(this->parent()->get_remote_bda());
75 if (status != ESP_OK) {
76 ESP_LOGW(TAG, "esp_ble_gap_read_rssi error, address=%s, status=%d", this->parent()->address_str(), status);
77 this->status_set_warning();
78 this->publish_state(NAN);
79 }
80}
81
82} // namespace esphome::ble_client
83#endif
uint8_t status
Definition bl0942.h:8
void disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:306
const StringRef & get_name() const
Definition entity_base.h:71
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68