ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
ble_server.cpp
Go to the documentation of this file.
1#include "ble_server.h"
2
4#include "esphome/core/log.h"
7
8#ifdef USE_ESP32
9
10#include <nvs_flash.h>
11#include <freertos/FreeRTOSConfig.h>
12#include <esp_bt_main.h>
13#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
14#include <esp_bt.h>
15#endif
16#include <freertos/task.h>
17#include <esp_gap_ble_api.h>
18
19namespace esphome {
20namespace esp32_ble_server {
21
22static const char *const TAG = "esp32_ble_server";
23
25 if (this->parent_->is_failed()) {
26 this->mark_failed();
27 ESP_LOGE(TAG, "BLE Server was marked failed by ESP32BLE");
28 return;
29 }
30 global_ble_server = this;
31}
32
34 if (!this->parent_->is_active()) {
35 return;
36 }
37 switch (this->state_) {
38 case RUNNING: {
39 // Start all services that are pending to start
40 if (!this->services_to_start_.empty()) {
41 size_t write_idx = 0;
42 for (auto *service : this->services_to_start_) {
43 if (service->is_created()) {
44 service->start(); // Needs to be called once per characteristic in the service
45 }
46 // Remove services that have started or are starting
47 if (!service->is_starting() && !service->is_running()) {
48 this->services_to_start_[write_idx++] = service;
49 }
50 }
51 this->services_to_start_.erase(this->services_to_start_.begin() + write_idx, this->services_to_start_.end());
52 }
53 break;
54 }
55 case INIT: {
56 esp_err_t err = esp_ble_gatts_app_register(0);
57 if (err != ESP_OK) {
58 ESP_LOGE(TAG, "esp_ble_gatts_app_register failed: %d", err);
59 this->mark_failed();
60 return;
61 }
62 this->state_ = REGISTERING;
63 break;
64 }
65 case REGISTERING: {
66 if (this->registered_) {
67 // Create the device information service first so
68 // it is at the top of the GATT table
70 // Create all services previously created
71 for (auto &entry : this->services_) {
72 if (entry.service == this->device_information_service_) {
73 continue;
74 }
75 entry.service->do_create(this);
76 }
77 this->state_ = STARTING_SERVICE;
78 }
79 break;
80 }
81 case STARTING_SERVICE: {
83 this->state_ = RUNNING;
85 ESP_LOGD(TAG, "BLE server setup successfully");
86 } else if (this->device_information_service_->is_created()) {
88 }
89 break;
90 }
91 }
92}
93
94bool BLEServer::can_proceed() { return this->is_running() || !this->parent_->is_active(); }
95
97 if (this->is_running()) {
98 this->parent_->advertising_set_manufacturer_data(this->manufacturer_data_);
99 }
100}
101
102BLEService *BLEServer::create_service(ESPBTUUID uuid, bool advertise, uint16_t num_handles) {
103#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
104 char uuid_buf[esp32_ble::UUID_STR_LEN];
105 uuid.to_str(uuid_buf);
106 ESP_LOGV(TAG, "Creating BLE service - %s", uuid_buf);
107#endif
108 // Calculate the inst_id for the service
109 uint8_t inst_id = 0;
110 for (; inst_id < 0xFF; inst_id++) {
111 if (this->get_service(uuid, inst_id) == nullptr) {
112 break;
113 }
114 }
115 if (inst_id == 0xFF) {
116 char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
117 uuid.to_str(warn_uuid_buf);
118 ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
119 return nullptr;
120 }
121 BLEService *service = // NOLINT(cppcoreguidelines-owning-memory)
122 new BLEService(uuid, num_handles, inst_id, advertise);
123 this->services_.push_back({uuid, inst_id, service});
124 if (this->parent_->is_active() && this->registered_) {
125 service->do_create(this);
126 }
127 return service;
128}
129
130void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
131#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
132 char uuid_buf[esp32_ble::UUID_STR_LEN];
133 uuid.to_str(uuid_buf);
134 ESP_LOGV(TAG, "Removing BLE service - %s %d", uuid_buf, inst_id);
135#endif
136 for (auto it = this->services_.begin(); it != this->services_.end(); ++it) {
137 if (it->uuid == uuid && it->inst_id == inst_id) {
138 it->service->do_delete();
139 delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
140 this->services_.erase(it);
141 return;
142 }
143 }
144 char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
145 uuid.to_str(warn_uuid_buf);
146 ESP_LOGW(TAG, "BLE service %s %d does not exist", warn_uuid_buf, inst_id);
147}
148
150 for (auto &entry : this->services_) {
151 if (entry.uuid == uuid && entry.inst_id == inst_id) {
152 return entry.service;
153 }
154 }
155 return nullptr;
156}
157
159 for (auto &entry : this->callbacks_) {
160 if (entry.type == type) {
161 entry.callback(conn_id);
162 }
163 }
164}
165
166void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
167 esp_ble_gatts_cb_param_t *param) {
168 switch (event) {
169 case ESP_GATTS_CONNECT_EVT: {
170 ESP_LOGD(TAG, "BLE Client connected");
171 this->add_client_(param->connect.conn_id);
172 // Resume advertising so additional clients can discover and connect
174 this->parent_->advertising_start();
175 }
176 this->dispatch_callbacks_(CallbackType::ON_CONNECT, param->connect.conn_id);
177 break;
178 }
179 case ESP_GATTS_DISCONNECT_EVT: {
180 ESP_LOGD(TAG, "BLE Client disconnected");
181 this->remove_client_(param->disconnect.conn_id);
182 this->parent_->advertising_start();
183 this->dispatch_callbacks_(CallbackType::ON_DISCONNECT, param->disconnect.conn_id);
184 break;
185 }
186 case ESP_GATTS_REG_EVT: {
187 this->gatts_if_ = gatts_if;
188 this->registered_ = true;
189 break;
190 }
191 default:
192 break;
193 }
194
195 for (auto &entry : this->services_) {
196 entry.service->gatts_event_handler(event, gatts_if, param);
197 }
198}
199
200int8_t BLEServer::find_client_index_(uint16_t conn_id) const {
201 for (uint8_t i = 0; i < this->client_count_; i++) {
202 if (this->clients_[i] == conn_id)
203 return i;
204 }
205 return -1;
206}
207
208void BLEServer::add_client_(uint16_t conn_id) {
209 // Check if already in list
210 if (this->find_client_index_(conn_id) >= 0)
211 return;
212 // Add if there's space
213 if (this->client_count_ < USE_ESP32_BLE_MAX_CONNECTIONS) {
214 this->clients_[this->client_count_++] = conn_id;
215 } else {
216 // This should never happen since max clients is known at compile time
217 ESP_LOGE(TAG, "Client array full");
218 }
219}
220
221void BLEServer::remove_client_(uint16_t conn_id) {
222 int8_t index = this->find_client_index_(conn_id);
223 if (index >= 0) {
224 // Replace with last element and decrement count (client order not preserved)
225 this->clients_[index] = this->clients_[--this->client_count_];
226 }
227}
228
230 // Delete all clients
231 this->client_count_ = 0;
232 // Delete all services
233 for (auto &entry : this->services_) {
234 entry.service->do_delete();
235 }
236 this->registered_ = false;
237 this->state_ = INIT;
238}
239
241
243 ESP_LOGCONFIG(TAG,
244 "ESP32 BLE Server:\n"
245 " Max clients: %u",
246 this->max_clients_);
247}
248
249BLEServer *global_ble_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
250
251} // namespace esp32_ble_server
252} // namespace esphome
253
254#endif
void mark_failed()
Mark this component as failed.
ESPDEPRECATED("Use to_str() instead. Removed in 2026.8.0", "2026.2.0") std const char * to_str(std::span< char, UUID_STR_LEN > output) const
Definition ble_uuid.cpp:146
std::vector< CallbackEntry > callbacks_
Definition ble_server.h:92
std::vector< uint8_t > manufacturer_data_
Definition ble_server.h:94
void remove_client_(uint16_t conn_id)
float get_setup_priority() const override
enum esphome::esp32_ble_server::BLEServer::State INIT
void dispatch_callbacks_(CallbackType type, uint16_t conn_id)
ESPHOME_ALWAYS_INLINE bool is_running()
Definition ble_server.h:35
BLEService * get_service(ESPBTUUID uuid, uint8_t inst_id=0)
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
std::vector< BLEService * > services_to_start_
Definition ble_server.h:102
BLEService * create_service(ESPBTUUID uuid, bool advertise=false, uint16_t num_handles=15)
void remove_service(ESPBTUUID uuid, uint8_t inst_id=0)
void add_client_(uint16_t conn_id)
std::vector< ServiceEntry > services_
Definition ble_server.h:101
uint16_t clients_[USE_ESP32_BLE_MAX_CONNECTIONS]
Definition ble_server.h:98
int8_t find_client_index_(uint16_t conn_id) const
void do_create(BLEServer *server)
uint16_t type
constexpr float AFTER_BLUETOOTH
Definition component.h:46
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7