ESPHome 2026.9.1
Loading...
Searching...
No Matches
ble_client_base.h
Go to the documentation of this file.
1#pragma once
2
3#ifdef USE_ESP32
4
7
8#ifdef USE_ESP32_BLE_DEVICE
9#include "ble_service.h"
10#endif
11
12#include <array>
13#include <vector>
14
15#include <esp_bt_defs.h>
16#include <esp_gap_ble_api.h>
17#include <esp_gatt_common_api.h>
18#include <esp_gattc_api.h>
19
21
23
24static const int UNSET_CONN_ID = 0xFFFF;
25
27 public:
28 void setup() override;
29 void loop() override;
30 float get_setup_priority() const override;
31 void dump_config() override;
32
33 void run_later(std::function<void()> &&f); // NOLINT
34#ifdef USE_ESP32_BLE_DEVICE
35 bool parse_device(const espbt::ESPBTDevice &device) override;
36#endif
37 void on_scan_end() override {}
38 bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
39 esp_ble_gattc_cb_param_t *param) override;
40 void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
41 void connect() override;
42 esp_err_t pair();
43 void disconnect() override;
46 void release_services();
47
49 esp_err_t register_for_notify(uint16_t char_handle);
50
52 bool notify_registration_pending() const { return this->pending_notify_regs_ > 0; }
53
54 bool connected() { return this->state() == espbt::ClientState::ESTABLISHED; }
55
56 void set_auto_connect(bool auto_connect) { this->auto_connect_ = auto_connect; }
57
58 virtual void set_address(uint64_t address) {
59 this->address_ = address;
60 this->remote_bda_[0] = (address >> 40) & 0xFF;
61 this->remote_bda_[1] = (address >> 32) & 0xFF;
62 this->remote_bda_[2] = (address >> 24) & 0xFF;
63 this->remote_bda_[3] = (address >> 16) & 0xFF;
64 this->remote_bda_[4] = (address >> 8) & 0xFF;
65 this->remote_bda_[5] = (address >> 0) & 0xFF;
66 if (address == 0) {
67 this->address_str_[0] = '\0';
68 } else {
70 }
71 }
72 const char *address_str() const { return this->address_str_; }
73
74#ifdef USE_ESP32_BLE_DEVICE
76 BLEService *get_service(uint16_t uuid);
78 BLECharacteristic *get_characteristic(uint16_t service, uint16_t chr);
81 BLEDescriptor *get_descriptor(uint16_t service, uint16_t chr, uint16_t descr);
83 // Get the configuration descriptor for the given characteristic handle.
85#endif
86
87 float parse_char_value(uint8_t *value, uint16_t length);
88
89 int get_gattc_if() const { return this->gattc_if_; }
90 uint8_t *get_remote_bda() { return this->remote_bda_; }
91 esp_ble_addr_type_t get_remote_addr_type() const { return this->remote_addr_type_; }
92 void set_remote_addr_type(esp_ble_addr_type_t address_type) { this->remote_addr_type_ = address_type; }
93 uint16_t get_conn_id() const { return this->conn_id_; }
94 uint64_t get_address() const { return this->address_; }
95 bool is_paired() const { return this->paired_; }
96 // The proxy clears this when a bond is removed while the link is up.
97 void set_unpaired() { this->paired_ = false; }
98
99 uint8_t get_connection_index() const { return this->connection_index_; }
100
101 virtual void set_connection_type(espbt::ConnectionType ct) { this->connection_type_ = ct; }
102
103 bool check_addr(esp_bd_addr_t &addr) { return memcmp(addr, this->remote_bda_, sizeof(esp_bd_addr_t)) == 0; }
104
105 void set_state(espbt::ClientState st) override;
106
107 protected:
108 // Memory optimized layout for 32-bit systems
109 // Group 1: 8-byte types
110 uint64_t address_{0};
111
112 // Group 2: Container types (grouped for memory optimization)
113#ifdef USE_ESP32_BLE_DEVICE
114 std::vector<BLEService *> services_;
115#endif
116
117 // Group 3: 4-byte types
118 int gattc_if_{ESP_GATT_IF_NONE};
119 esp_gatt_status_t status_{ESP_GATT_OK};
120
121 // Group 4: Arrays
122 char address_str_[MAC_ADDRESS_PRETTY_BUFFER_SIZE]{};
123 esp_bd_addr_t remote_bda_; // 6 bytes
124
125 // Group 5: 4-byte types
127
128 // Group 6: 2-byte types
129 uint16_t conn_id_{UNSET_CONN_ID};
130 uint16_t mtu_{23};
131
132 // Group 7: 1-byte types and small enums
133 esp_ble_addr_type_t remote_addr_type_{BLE_ADDR_TYPE_PUBLIC};
134 espbt::ConnectionType connection_type_{espbt::ConnectionType::V1};
136 uint8_t service_count_{0}; // ESP32 has max handles < 255, typical devices have < 50 services
137 // Outstanding register_for_notify() requests
138 // A count, not per-request state, so a raw esp_ble_gattc_register_for_notify() on the same client can retire one
139 // services_released_ is the backstop if that ever lets the release run early
141 bool auto_connect_{false};
142 bool paired_{false};
143 // Set by release_services() on RAM-cache builds; the stack's GATT database must not be walked after it
145 // 8 bytes used, no padding
146
147 void log_event_(const char *name);
148 void log_gattc_lifecycle_event_(const char *name);
149 void log_gattc_data_event_(const char *name);
150 esp_err_t update_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout,
151 const char *param_type);
152 void set_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout,
153 const char *param_type);
154 void log_gattc_warning_(const char *operation, esp_gatt_status_t status);
155 void log_gattc_warning_(const char *operation, esp_err_t err);
156 void log_connection_params_(const char *param_type);
157 void handle_connection_result_(esp_err_t ret);
164 virtual void on_disconnect_complete(esp_err_t reason) {}
166 void set_idle_() {
167 this->set_state(espbt::ClientState::IDLE);
168 this->conn_id_ = UNSET_CONN_ID;
169 }
173 this->set_state(espbt::ClientState::DISCONNECTING);
174 // BluetoothConnection::loop() disables the component loop after service discovery
175 // completes, so the DISCONNECTING timeout check in loop() would never run if CLOSE_EVT
176 // gets lost. Re-enable the loop so the 10s safety timeout can force IDLE.
177 this->enable_loop();
178 }
179 // Compact error logging helpers to reduce flash usage
180 void log_error_(const char *message);
181 void log_error_(const char *message, int code);
182 void log_warning_(const char *message);
183};
184
185} // namespace esphome::esp32_ble_client
186
187#endif // USE_ESP32
uint8_t address
Definition bl0906.h:4
void enable_loop()
Enable this component's loop.
Definition component.h:246
std::vector< BLEService * > services_
char address_str_[MAC_ADDRESS_PRETTY_BUFFER_SIZE]
bool notify_registration_pending() const
True while a register_for_notify() request has not completed.
void log_gattc_warning_(const char *operation, esp_gatt_status_t status)
void log_connection_params_(const char *param_type)
BLEDescriptor * get_descriptor(espbt::ESPBTUUID service, espbt::ESPBTUUID chr, espbt::ESPBTUUID descr)
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
void set_state(espbt::ClientState st) override
esp_err_t register_for_notify(uint16_t char_handle)
Register for notifications, holding the service release until the registration completes.
esp_err_t update_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout, const char *param_type)
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
virtual void set_address(uint64_t address)
esp_ble_addr_type_t get_remote_addr_type() const
void set_idle_()
Transition to IDLE and reset conn_id — call when the connection is fully dead.
void run_later(std::function< void()> &&f)
virtual void on_disconnect_complete(esp_err_t reason)
Hook called once a connection has been fully torn down (after release_services() and set_idle_()): CL...
BLEService * get_service(espbt::ESPBTUUID uuid)
void set_disconnecting_()
Transition to DISCONNECTING and start the safety timeout.
bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
bool parse_device(const espbt::ESPBTDevice &device) override
virtual void set_connection_type(espbt::ConnectionType ct)
float parse_char_value(uint8_t *value, uint16_t length)
BLEDescriptor * get_config_descriptor(uint16_t handle)
void set_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout, const char *param_type)
void set_remote_addr_type(esp_ble_addr_type_t address_type)
Base class for BLE GATT clients that connect to remote devices.
const LogString * message
Definition component.cpp:35
int ret
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1536
static void uint32_t
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle