ESPHome 2025.12.1
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 (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);
54 this->publish_state(rssi);
55 }
56 break;
57 default:
58 break;
59 }
60}
61
63 if (this->node_state != espbt::ClientState::ESTABLISHED) {
64 ESP_LOGW(TAG, "[%s] Cannot poll, not connected", this->get_name().c_str());
65 this->should_update_ = true;
66 return;
67 }
68 this->get_rssi_();
69}
71 ESP_LOGV(TAG, "requesting rssi from %s", this->parent()->address_str());
72 auto status = esp_ble_gap_read_rssi(this->parent()->get_remote_bda());
73 if (status != ESP_OK) {
74 ESP_LOGW(TAG, "esp_ble_gap_read_rssi error, address=%s, status=%d", this->parent()->address_str(), status);
75 this->status_set_warning();
76 this->publish_state(NAN);
77 }
78}
79
80} // namespace esphome::ble_client
81#endif
uint8_t status
Definition bl0942.h:8
void status_set_warning(const char *message=nullptr)
void disable_loop()
Disable this component's loop.
void status_clear_warning()
const StringRef & get_name() const
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:77