ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ble_characteristic.cpp
Go to the documentation of this file.
2#include "ble_server.h"
3#include "ble_service.h"
4
6#include "esphome/core/log.h"
7
8#ifdef USE_ESP32
9
11
12ESPHOME_LOG_TAG(TAG, "esp32_ble_server.characteristic");
13
15 for (auto *descriptor : this->descriptors_) {
16 delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
17 }
18}
19
20BLECharacteristic::BLECharacteristic(const ESPBTUUID uuid, uint32_t properties, esp_gatt_perm_t permissions)
21 : uuid_(uuid), permissions_(permissions) {
22 this->properties_ = (esp_gatt_char_prop_t) 0;
23
24 this->set_broadcast_property((properties & PROPERTY_BROADCAST) != 0);
25 this->set_indicate_property((properties & PROPERTY_INDICATE) != 0);
26 this->set_notify_property((properties & PROPERTY_NOTIFY) != 0);
27 this->set_read_property((properties & PROPERTY_READ) != 0);
28 this->set_write_property((properties & PROPERTY_WRITE) != 0);
29 this->set_write_no_response_property((properties & PROPERTY_WRITE_NR) != 0);
30}
31
33
34void BLECharacteristic::set_value(const uint8_t *data, size_t length) {
35 if (length == 0) { // An empty constant is a nullptr table
36 this->value_.clear();
37 return;
38 }
39 this->value_.assign(data, data + length);
40}
41
42void BLECharacteristic::set_value(std::vector<uint8_t> &&buffer) { this->value_ = std::move(buffer); }
43
44void BLECharacteristic::set_value(std::initializer_list<uint8_t> data) {
45 this->set_value(std::vector<uint8_t>(data)); // Delegate to move overload
46}
47
48void BLECharacteristic::set_value(const std::string &buffer) {
49 this->set_value(std::vector<uint8_t>(buffer.begin(), buffer.end())); // Delegate to move overload
50}
51
53 if (this->service_ == nullptr || this->service_->get_server() == nullptr ||
54 this->service_->get_server()->get_connected_client_count() == 0)
55 return;
56
57 const uint16_t *clients = this->service_->get_server()->get_clients();
58 uint8_t client_count = this->service_->get_server()->get_client_count();
59
60 for (uint8_t i = 0; i < client_count; i++) {
61 uint16_t client = clients[i];
62 size_t length = this->value_.size();
63 // Find the client in the list of clients to notify
64 auto *entry = this->find_client_in_notify_list_(client);
65 if (entry == nullptr)
66 continue;
67 bool require_ack = entry->indicate;
68 // TODO: Remove this block when INDICATE acknowledgment is supported
69 if (require_ack) {
70 ESP_LOGW(TAG, "INDICATE acknowledgment is not yet supported (i.e. it works as a NOTIFY)");
71 require_ack = false;
72 }
73 esp_err_t err = esp_ble_gatts_send_indicate(this->service_->get_server()->get_gatts_if(), client, this->handle_,
74 length, this->value_.data(), require_ack);
75 if (err != ESP_OK) {
76 ESP_LOGE(TAG, "esp_ble_gatts_send_indicate failed %d", err);
77 return;
78 }
79 }
80}
81
83 // If the descriptor is the CCCD descriptor, listen to its write event to know if the client wants to be notified
84 if (descriptor->get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
85 descriptor->on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
86 if (value.size() != 2)
87 return;
88 uint16_t cccd = encode_uint16(value[1], value[0]);
89 bool notify = (cccd & 1) != 0;
90 bool indicate = (cccd & 2) != 0;
91 // Remove existing entry if present
93 // Add new entry if needed
94 if (notify || indicate) {
95 this->clients_to_notify_.push_back({conn_id, indicate});
96 }
97 });
98 }
99 this->descriptors_.push_back(descriptor);
100}
101
103 this->descriptors_.erase(std::remove(this->descriptors_.begin(), this->descriptors_.end(), descriptor),
104 this->descriptors_.end());
105}
106
108 this->service_ = service;
109 esp_attr_control_t control;
110 control.auto_rsp = ESP_GATT_RSP_BY_APP;
111
112#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
113 char uuid_buf[esp32_ble::UUID_STR_LEN];
114 this->uuid_.to_str(uuid_buf);
115 ESP_LOGV(TAG, "Creating characteristic - %s", uuid_buf);
116#endif
117
118 esp_bt_uuid_t uuid = this->uuid_.get_uuid();
119 esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
120 this->properties_, nullptr, &control);
121
122 if (err != ESP_OK) {
123 ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
124 return;
125 }
126
127 this->state_ = CREATING;
128}
129
131 if (this->state_ == CREATED)
132 return true;
133
134 if (this->state_ != CREATING_DEPENDENTS)
135 return false;
136
137 for (auto *descriptor : this->descriptors_) {
138 if (!descriptor->is_created())
139 return false;
140 }
141 // All descriptors are created if we reach here
142 this->state_ = CREATED;
143 return true;
144}
145
147 if (this->state_ == FAILED)
148 return true;
149
150 for (auto *descriptor : this->descriptors_) {
151 if (descriptor->is_failed()) {
152 this->state_ = FAILED;
153 return true;
154 }
155 }
156 return false;
157}
158
159void BLECharacteristic::set_property_bit_(esp_gatt_char_prop_t bit, bool value) {
160 if (value) {
161 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | bit);
162 } else {
163 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~bit);
164 }
165}
166
168 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_BROADCAST, value);
169}
171 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_INDICATE, value);
172}
174 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_NOTIFY, value);
175}
176void BLECharacteristic::set_read_property(bool value) { this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_READ, value); }
177void BLECharacteristic::set_write_property(bool value) { this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_WRITE, value); }
179 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_WRITE_NR, value);
180}
181
182void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
183 esp_ble_gatts_cb_param_t *param) {
184 switch (event) {
185 case ESP_GATTS_DISCONNECT_EVT: {
186 // A later connection can get the same id; it subscribes again with its own security
187 this->remove_client_from_notify_list_(param->disconnect.conn_id);
188 break;
189 }
190 case ESP_GATTS_ADD_CHAR_EVT: {
191 if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
192 this->handle_ = param->add_char.attr_handle;
193
194 for (auto *descriptor : this->descriptors_) {
195 descriptor->do_create(this);
196 }
197
198 this->state_ = CREATING_DEPENDENTS;
199 }
200 break;
201 }
202 case ESP_GATTS_READ_EVT: {
203 if (param->read.handle != this->handle_)
204 break; // Not this characteristic
205
206 if (!param->read.need_rsp)
207 break; // For some reason you can request a read but not want a response
208
209 if (this->on_read_callback_) {
210 (*this->on_read_callback_)(param->read.conn_id);
211 }
212
213 // Use the client-supplied offset for long reads; short reads always start at 0.
214 // The Bluedroid stack truncates ATT_READ_RSP / ATT_READ_BLOB_RSP to MTU-1, so we
215 // just provide as much data as we have from the requested offset and let the stack
216 // handle framing. The client issues subsequent blob reads with increasing offsets
217 // until it has received the whole value.
218 const uint16_t offset = param->read.is_long ? param->read.offset : 0;
219 esp_gatt_status_t status = ESP_GATT_OK;
220 esp_gatt_rsp_t response;
221 response.attr_value.offset = offset;
222
223 if (offset > this->value_.size()) {
224 status = ESP_GATT_INVALID_OFFSET;
225 response.attr_value.len = 0;
226 } else {
227 size_t remaining = this->value_.size() - offset;
228 if (remaining > ESP_GATT_MAX_ATTR_LEN) {
229 ESP_LOGW(TAG, "Characteristic length %u exceeds buffer size of %u, truncating",
230 static_cast<unsigned>(remaining), ESP_GATT_MAX_ATTR_LEN);
231 remaining = ESP_GATT_MAX_ATTR_LEN;
232 }
233 response.attr_value.len = remaining;
234 memcpy(response.attr_value.value, this->value_.data() + offset, remaining);
235 }
236
237 response.attr_value.handle = this->handle_;
238 response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
239
240 esp_err_t err =
241 esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, status, &response);
242 if (err != ESP_OK) {
243 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
244 }
245 break;
246 }
247 case ESP_GATTS_WRITE_EVT: {
248 if (this->handle_ != param->write.handle)
249 break;
250
251 esp_gatt_status_t status = ESP_GATT_OK;
252
253 if (param->write.is_prep) {
254 const size_t offset = param->write.offset;
255 const size_t write_len = param->write.len;
256 const size_t new_size = offset + write_len;
257 // Clean the buffer on the first prepared write event
258 if (offset == 0) {
259 this->value_.clear();
260 }
261
262 if (offset != this->value_.size()) {
263 status = ESP_GATT_INVALID_OFFSET;
264 } else if (new_size > ESP_GATT_MAX_ATTR_LEN) {
265 status = ESP_GATT_INVALID_ATTR_LEN;
266 } else {
267 if (this->value_.size() < new_size) {
268 this->value_.resize(new_size);
269 }
270 memcpy(this->value_.data() + offset, param->write.value, write_len);
271 }
272 } else {
273 this->set_value(ByteBuffer::wrap(param->write.value, param->write.len));
274 }
275
276 if (param->write.need_rsp) {
277 esp_gatt_rsp_t response;
278
279 response.attr_value.len = param->write.len;
280 response.attr_value.handle = this->handle_;
281 response.attr_value.offset = param->write.offset;
282 response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
283 memcpy(response.attr_value.value, param->write.value, param->write.len);
284
285 esp_err_t err =
286 esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, status, &response);
287
288 if (err != ESP_OK) {
289 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
290 }
291 }
292
293 if (!param->write.is_prep) {
294 if (this->on_write_callback_) {
295 (*this->on_write_callback_)(this->value_, param->write.conn_id);
296 }
297 }
298
299 break;
300 }
301
302 case ESP_GATTS_EXEC_WRITE_EVT: {
303 // BLE stack will guarantee that ESP_GATTS_EXEC_WRITE_EVT is only received after prepared writes
304 if (this->value_.empty())
305 break;
306 if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) {
307 if (this->on_write_callback_) {
308 (*this->on_write_callback_)(this->value_, param->exec_write.conn_id);
309 }
310 }
311 esp_err_t err = esp_ble_gatts_send_response(gatts_if, param->exec_write.conn_id, param->exec_write.trans_id,
312 ESP_GATT_OK, nullptr);
313 if (err != ESP_OK) {
314 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
315 }
316 break;
317 }
318 default:
319 break;
320 }
321
322 for (auto *descriptor : this->descriptors_) {
323 descriptor->gatts_event_handler(event, gatts_if, param);
324 }
325}
326
328 // Since we typically have very few clients (often just 1), we can optimize
329 // for the common case by swapping with the last element and popping
330 for (size_t i = 0; i < this->clients_to_notify_.size(); i++) {
331 if (this->clients_to_notify_[i].conn_id == conn_id) {
332 // Swap with last element and pop (safe even when i is the last element)
333 this->clients_to_notify_[i] = this->clients_to_notify_.back();
334 this->clients_to_notify_.pop_back();
335 return;
336 }
337 }
338}
339
341 for (auto &entry : this->clients_to_notify_) {
342 if (entry.conn_id == conn_id) {
343 return &entry;
344 }
345 }
346 return nullptr;
347}
348
349} // namespace esphome::esp32_ble_server
350
351#endif
uint8_t status
Definition bl0942.h:8
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid)
Source compatibility with the historical esp32_ble API (esp32 builds only).
static ESPBTUUID from_uint16(uint16_t uuid)
A class modelled on the Java ByteBuffer class.
Definition bytebuffer.h:37
std::vector< uint8_t > get_data()
Definition bytebuffer.h:299
static ByteBuffer wrap(T value, Endian endianness=LITTLE)
Definition bytebuffer.h:155
ClientNotificationEntry * find_client_in_notify_list_(uint16_t conn_id)
void remove_descriptor(BLEDescriptor *descriptor)
BLECharacteristic(ESPBTUUID uuid, uint32_t properties, esp_gatt_perm_t permissions)
std::unique_ptr< std::function< void(std::span< const uint8_t >, uint16_t)> > on_write_callback_
void set_property_bit_(esp_gatt_char_prop_t bit, bool value)
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< BLEDescriptor * > descriptors_
void add_descriptor(BLEDescriptor *descriptor)
std::vector< ClientNotificationEntry > clients_to_notify_
std::unique_ptr< std::function< void(uint16_t)> > on_read_callback_
void on_write(std::function< void(std::span< const uint8_t >, uint16_t)> &&callback)
const uint16_t * get_clients() const
Definition ble_server.h:59
uint32_t buffer
Definition gif.cpp:50
ESPHOME_LOG_TAG(TAG, "esp32_ble")
uint32_t value
Definition hal.cpp:41
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1043
static void uint32_t
uint16_t length
Definition tt21100.cpp:0