ESPHome 2025.12.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 uint16_t index_to_remove = 0;
42 // Iterate over the services to start
43 for (unsigned i = 0; i < this->services_to_start_.size(); i++) {
44 BLEService *service = this->services_to_start_[i];
45 if (service->is_created()) {
46 service->start(); // Needs to be called once per characteristic in the service
47 } else {
48 index_to_remove = i + 1;
49 }
50 }
51 // Remove the services that have been started
52 if (index_to_remove > 0) {
53 this->services_to_start_.erase(this->services_to_start_.begin(),
54 this->services_to_start_.begin() + index_to_remove - 1);
55 }
56 }
57 break;
58 }
59 case INIT: {
60 esp_err_t err = esp_ble_gatts_app_register(0);
61 if (err != ESP_OK) {
62 ESP_LOGE(TAG, "esp_ble_gatts_app_register failed: %d", err);
63 this->mark_failed();
64 return;
65 }
66 this->state_ = REGISTERING;
67 break;
68 }
69 case REGISTERING: {
70 if (this->registered_) {
71 // Create the device information service first so
72 // it is at the top of the GATT table
74 // Create all services previously created
75 for (auto &entry : this->services_) {
76 if (entry.service == this->device_information_service_) {
77 continue;
78 }
79 entry.service->do_create(this);
80 }
81 this->state_ = STARTING_SERVICE;
82 }
83 break;
84 }
85 case STARTING_SERVICE: {
87 this->state_ = RUNNING;
89 ESP_LOGD(TAG, "BLE server setup successfully");
90 } else if (this->device_information_service_->is_created()) {
92 }
93 break;
94 }
95 }
96}
97
98bool BLEServer::is_running() { return this->parent_->is_active() && this->state_ == RUNNING; }
99
100bool BLEServer::can_proceed() { return this->is_running() || !this->parent_->is_active(); }
101
103 if (this->is_running()) {
104 this->parent_->advertising_set_manufacturer_data(this->manufacturer_data_);
105 }
106}
107
108BLEService *BLEServer::create_service(ESPBTUUID uuid, bool advertise, uint16_t num_handles) {
109 ESP_LOGV(TAG, "Creating BLE service - %s", uuid.to_string().c_str());
110 // Calculate the inst_id for the service
111 uint8_t inst_id = 0;
112 for (; inst_id < 0xFF; inst_id++) {
113 if (this->get_service(uuid, inst_id) == nullptr) {
114 break;
115 }
116 }
117 if (inst_id == 0xFF) {
118 ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", uuid.to_string().c_str());
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 ESP_LOGV(TAG, "Removing BLE service - %s %d", uuid.to_string().c_str(), inst_id);
132 for (auto it = this->services_.begin(); it != this->services_.end(); ++it) {
133 if (it->uuid == uuid && it->inst_id == inst_id) {
134 it->service->do_delete();
135 delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
136 this->services_.erase(it);
137 return;
138 }
139 }
140 ESP_LOGW(TAG, "BLE service %s %d does not exist", uuid.to_string().c_str(), inst_id);
141}
142
144 for (auto &entry : this->services_) {
145 if (entry.uuid == uuid && entry.inst_id == inst_id) {
146 return entry.service;
147 }
148 }
149 return nullptr;
150}
151
153 for (auto &entry : this->callbacks_) {
154 if (entry.type == type) {
155 entry.callback(conn_id);
156 }
157 }
158}
159
160void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
161 esp_ble_gatts_cb_param_t *param) {
162 switch (event) {
163 case ESP_GATTS_CONNECT_EVT: {
164 ESP_LOGD(TAG, "BLE Client connected");
165 this->add_client_(param->connect.conn_id);
166 this->dispatch_callbacks_(CallbackType::ON_CONNECT, param->connect.conn_id);
167 break;
168 }
169 case ESP_GATTS_DISCONNECT_EVT: {
170 ESP_LOGD(TAG, "BLE Client disconnected");
171 this->remove_client_(param->disconnect.conn_id);
172 this->parent_->advertising_start();
173 this->dispatch_callbacks_(CallbackType::ON_DISCONNECT, param->disconnect.conn_id);
174 break;
175 }
176 case ESP_GATTS_REG_EVT: {
177 this->gatts_if_ = gatts_if;
178 this->registered_ = true;
179 break;
180 }
181 default:
182 break;
183 }
184
185 for (auto &entry : this->services_) {
186 entry.service->gatts_event_handler(event, gatts_if, param);
187 }
188}
189
190int8_t BLEServer::find_client_index_(uint16_t conn_id) const {
191 for (uint8_t i = 0; i < this->client_count_; i++) {
192 if (this->clients_[i] == conn_id)
193 return i;
194 }
195 return -1;
196}
197
198void BLEServer::add_client_(uint16_t conn_id) {
199 // Check if already in list
200 if (this->find_client_index_(conn_id) >= 0)
201 return;
202 // Add if there's space
203 if (this->client_count_ < USE_ESP32_BLE_MAX_CONNECTIONS) {
204 this->clients_[this->client_count_++] = conn_id;
205 } else {
206 // This should never happen since max clients is known at compile time
207 ESP_LOGE(TAG, "Client array full");
208 }
209}
210
211void BLEServer::remove_client_(uint16_t conn_id) {
212 int8_t index = this->find_client_index_(conn_id);
213 if (index >= 0) {
214 // Replace with last element and decrement count (client order not preserved)
215 this->clients_[index] = this->clients_[--this->client_count_];
216 }
217}
218
220 // Delete all clients
221 this->client_count_ = 0;
222 // Delete all services
223 for (auto &entry : this->services_) {
224 entry.service->do_delete();
225 }
226 this->registered_ = false;
227 this->state_ = INIT;
228}
229
231
232void BLEServer::dump_config() { ESP_LOGCONFIG(TAG, "ESP32 BLE Server:"); }
233
234BLEServer *global_ble_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
235
236} // namespace esp32_ble_server
237} // namespace esphome
238
239#endif
virtual void mark_failed()
Mark this component as failed.
std::string to_string() const
Definition ble_uuid.cpp:146
std::vector< CallbackEntry > callbacks_
Definition ble_server.h:90
void ble_before_disabled_event_handler() override
std::vector< uint8_t > manufacturer_data_
Definition ble_server.h:92
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)
BLEService * get_service(ESPBTUUID uuid, uint8_t inst_id=0)
std::vector< BLEService * > services_to_start_
Definition ble_server.h:99
BLEService * create_service(ESPBTUUID uuid, bool advertise=false, uint16_t num_handles=15)
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) override
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:98
uint16_t clients_[USE_ESP32_BLE_MAX_CONNECTIONS]
Definition ble_server.h:96
int8_t find_client_index_(uint16_t conn_id) const
void do_create(BLEServer *server)
uint16_t type
const float AFTER_BLUETOOTH
Definition component.cpp:62
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7