ESPHome 2025.9.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 {
10namespace ble_client {
11
12static const char *const TAG = "ble_rssi_sensor";
13
15 // Parent BLEClientNode has a loop() method, but this component uses
16 // polling via update() and BLE GAP callbacks so loop isn't needed
17 this->disable_loop();
18}
19
21 LOG_SENSOR("", "BLE Client RSSI Sensor", this);
22 ESP_LOGCONFIG(TAG, " MAC address : %s", this->parent()->address_str().c_str());
23 LOG_UPDATE_INTERVAL(this);
24}
25
26void BLEClientRSSISensor::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
27 esp_ble_gattc_cb_param_t *param) {
28 switch (event) {
29 case ESP_GATTC_CLOSE_EVT: {
30 this->status_set_warning();
31 this->publish_state(NAN);
32 break;
33 }
34 case ESP_GATTC_SEARCH_CMPL_EVT: {
35 this->node_state = espbt::ClientState::ESTABLISHED;
36 if (this->should_update_) {
37 this->should_update_ = false;
38 this->get_rssi_();
39 }
40 break;
41 }
42 default:
43 break;
44 }
45}
46
47void BLEClientRSSISensor::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
48 switch (event) {
49 // server response on RSSI request:
50 case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
51 if (param->read_rssi_cmpl.status == ESP_BT_STATUS_SUCCESS) {
52 int8_t rssi = param->read_rssi_cmpl.rssi;
53 ESP_LOGI(TAG, "ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT RSSI: %d", rssi);
55 this->publish_state(rssi);
56 }
57 break;
58 default:
59 break;
60 }
61}
62
64 if (this->node_state != espbt::ClientState::ESTABLISHED) {
65 ESP_LOGW(TAG, "[%s] Cannot poll, not connected", this->get_name().c_str());
66 this->should_update_ = true;
67 return;
68 }
69 this->get_rssi_();
70}
72 ESP_LOGV(TAG, "requesting rssi from %s", this->parent()->address_str().c_str());
73 auto status = esp_ble_gap_read_rssi(this->parent()->get_remote_bda());
74 if (status != ESP_OK) {
75 ESP_LOGW(TAG, "esp_ble_gap_read_rssi error, address=%s, status=%d", this->parent()->address_str().c_str(), status);
76 this->status_set_warning();
77 this->publish_state(NAN);
78 }
79}
80
81} // namespace ble_client
82} // namespace esphome
83#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:45
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7