ESPHome 2025.10.3
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
10namespace esphome {
11namespace esp32_ble_server {
12
13static const char *const TAG = "esp32_ble_server.characteristic";
14
16 for (auto *descriptor : this->descriptors_) {
17 delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
18 }
19 vSemaphoreDelete(this->set_value_lock_);
20}
21
22BLECharacteristic::BLECharacteristic(const ESPBTUUID uuid, uint32_t properties) : uuid_(uuid) {
23 this->set_value_lock_ = xSemaphoreCreateBinary();
24 xSemaphoreGive(this->set_value_lock_);
25
26 this->properties_ = (esp_gatt_char_prop_t) 0;
27
28 this->set_broadcast_property((properties & PROPERTY_BROADCAST) != 0);
29 this->set_indicate_property((properties & PROPERTY_INDICATE) != 0);
30 this->set_notify_property((properties & PROPERTY_NOTIFY) != 0);
31 this->set_read_property((properties & PROPERTY_READ) != 0);
32 this->set_write_property((properties & PROPERTY_WRITE) != 0);
33 this->set_write_no_response_property((properties & PROPERTY_WRITE_NR) != 0);
34}
35
37
38void BLECharacteristic::set_value(const std::vector<uint8_t> &buffer) {
39 xSemaphoreTake(this->set_value_lock_, 0L);
40 this->value_ = buffer;
41 xSemaphoreGive(this->set_value_lock_);
42}
43void BLECharacteristic::set_value(const std::string &buffer) {
44 this->set_value(std::vector<uint8_t>(buffer.begin(), buffer.end()));
45}
46
48 if (this->service_ == nullptr || this->service_->get_server() == nullptr ||
49 this->service_->get_server()->get_connected_client_count() == 0)
50 return;
51
52 const uint16_t *clients = this->service_->get_server()->get_clients();
53 uint8_t client_count = this->service_->get_server()->get_client_count();
54
55 for (uint8_t i = 0; i < client_count; i++) {
56 uint16_t client = clients[i];
57 size_t length = this->value_.size();
58 // Find the client in the list of clients to notify
59 auto *entry = this->find_client_in_notify_list_(client);
60 if (entry == nullptr)
61 continue;
62 bool require_ack = entry->indicate;
63 // TODO: Remove this block when INDICATE acknowledgment is supported
64 if (require_ack) {
65 ESP_LOGW(TAG, "INDICATE acknowledgment is not yet supported (i.e. it works as a NOTIFY)");
66 require_ack = false;
67 }
68 esp_err_t err = esp_ble_gatts_send_indicate(this->service_->get_server()->get_gatts_if(), client, this->handle_,
69 length, this->value_.data(), require_ack);
70 if (err != ESP_OK) {
71 ESP_LOGE(TAG, "esp_ble_gatts_send_indicate failed %d", err);
72 return;
73 }
74 }
75}
76
78 // If the descriptor is the CCCD descriptor, listen to its write event to know if the client wants to be notified
79 if (descriptor->get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
80 descriptor->on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
81 if (value.size() != 2)
82 return;
83 uint16_t cccd = encode_uint16(value[1], value[0]);
84 bool notify = (cccd & 1) != 0;
85 bool indicate = (cccd & 2) != 0;
86 // Remove existing entry if present
88 // Add new entry if needed
89 if (notify || indicate) {
90 this->clients_to_notify_.push_back({conn_id, indicate});
91 }
92 });
93 }
94 this->descriptors_.push_back(descriptor);
95}
96
98 this->descriptors_.erase(std::remove(this->descriptors_.begin(), this->descriptors_.end(), descriptor),
99 this->descriptors_.end());
100}
101
103 this->service_ = service;
104 esp_attr_control_t control;
105 control.auto_rsp = ESP_GATT_RSP_BY_APP;
106
107 ESP_LOGV(TAG, "Creating characteristic - %s", this->uuid_.to_string().c_str());
108
109 esp_bt_uuid_t uuid = this->uuid_.get_uuid();
110 esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
111 this->properties_, nullptr, &control);
112
113 if (err != ESP_OK) {
114 ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
115 return;
116 }
117
118 this->state_ = CREATING;
119}
120
122 if (this->state_ == CREATED)
123 return true;
124
125 if (this->state_ != CREATING_DEPENDENTS)
126 return false;
127
128 for (auto *descriptor : this->descriptors_) {
129 if (!descriptor->is_created())
130 return false;
131 }
132 // All descriptors are created if we reach here
133 this->state_ = CREATED;
134 return true;
135}
136
138 if (this->state_ == FAILED)
139 return true;
140
141 for (auto *descriptor : this->descriptors_) {
142 if (descriptor->is_failed()) {
143 this->state_ = FAILED;
144 return true;
145 }
146 }
147 return false;
148}
149
150void BLECharacteristic::set_property_bit_(esp_gatt_char_prop_t bit, bool value) {
151 if (value) {
152 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | bit);
153 } else {
154 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~bit);
155 }
156}
157
159 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_BROADCAST, value);
160}
162 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_INDICATE, value);
163}
165 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_NOTIFY, value);
166}
167void BLECharacteristic::set_read_property(bool value) { this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_READ, value); }
168void BLECharacteristic::set_write_property(bool value) { this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_WRITE, value); }
170 this->set_property_bit_(ESP_GATT_CHAR_PROP_BIT_WRITE_NR, value);
171}
172
173void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
174 esp_ble_gatts_cb_param_t *param) {
175 switch (event) {
176 case ESP_GATTS_ADD_CHAR_EVT: {
177 if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
178 this->handle_ = param->add_char.attr_handle;
179
180 for (auto *descriptor : this->descriptors_) {
181 descriptor->do_create(this);
182 }
183
184 this->state_ = CREATING_DEPENDENTS;
185 }
186 break;
187 }
188 case ESP_GATTS_READ_EVT: {
189 if (param->read.handle != this->handle_)
190 break; // Not this characteristic
191
192 if (!param->read.need_rsp)
193 break; // For some reason you can request a read but not want a response
194
195 if (this->on_read_callback_) {
196 (*this->on_read_callback_)(param->read.conn_id);
197 }
198
199 uint16_t max_offset = 22;
200
201 esp_gatt_rsp_t response;
202 if (param->read.is_long) {
203 if (this->value_.size() - this->value_read_offset_ < max_offset) {
204 // Last message in the chain
205 response.attr_value.len = this->value_.size() - this->value_read_offset_;
206 response.attr_value.offset = this->value_read_offset_;
207 memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
208 this->value_read_offset_ = 0;
209 } else {
210 response.attr_value.len = max_offset;
211 response.attr_value.offset = this->value_read_offset_;
212 memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
213 this->value_read_offset_ += max_offset;
214 }
215 } else {
216 response.attr_value.offset = 0;
217 if (this->value_.size() + 1 > max_offset) {
218 response.attr_value.len = max_offset;
219 this->value_read_offset_ = max_offset;
220 } else {
221 response.attr_value.len = this->value_.size();
222 }
223 memcpy(response.attr_value.value, this->value_.data(), response.attr_value.len);
224 }
225
226 response.attr_value.handle = this->handle_;
227 response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
228
229 esp_err_t err =
230 esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &response);
231 if (err != ESP_OK) {
232 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
233 }
234 break;
235 }
236 case ESP_GATTS_WRITE_EVT: {
237 if (this->handle_ != param->write.handle)
238 break;
239
240 if (param->write.is_prep) {
241 this->value_.insert(this->value_.end(), param->write.value, param->write.value + param->write.len);
242 this->write_event_ = true;
243 } else {
244 this->set_value(ByteBuffer::wrap(param->write.value, param->write.len));
245 }
246
247 if (param->write.need_rsp) {
248 esp_gatt_rsp_t response;
249
250 response.attr_value.len = param->write.len;
251 response.attr_value.handle = this->handle_;
252 response.attr_value.offset = param->write.offset;
253 response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
254 memcpy(response.attr_value.value, param->write.value, param->write.len);
255
256 esp_err_t err =
257 esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, &response);
258
259 if (err != ESP_OK) {
260 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
261 }
262 }
263
264 if (!param->write.is_prep) {
265 if (this->on_write_callback_) {
266 (*this->on_write_callback_)(this->value_, param->write.conn_id);
267 }
268 }
269
270 break;
271 }
272
273 case ESP_GATTS_EXEC_WRITE_EVT: {
274 if (!this->write_event_)
275 break;
276 this->write_event_ = false;
277 if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) {
278 if (this->on_write_callback_) {
279 (*this->on_write_callback_)(this->value_, param->exec_write.conn_id);
280 }
281 }
282 esp_err_t err =
283 esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, nullptr);
284 if (err != ESP_OK) {
285 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
286 }
287 break;
288 }
289 default:
290 break;
291 }
292
293 for (auto *descriptor : this->descriptors_) {
294 descriptor->gatts_event_handler(event, gatts_if, param);
295 }
296}
297
299 // Since we typically have very few clients (often just 1), we can optimize
300 // for the common case by swapping with the last element and popping
301 for (size_t i = 0; i < this->clients_to_notify_.size(); i++) {
302 if (this->clients_to_notify_[i].conn_id == conn_id) {
303 // Swap with last element and pop (safe even when i is the last element)
304 this->clients_to_notify_[i] = this->clients_to_notify_.back();
305 this->clients_to_notify_.pop_back();
306 return;
307 }
308 }
309}
310
312 for (auto &entry : this->clients_to_notify_) {
313 if (entry.conn_id == conn_id) {
314 return &entry;
315 }
316 }
317 return nullptr;
318}
319
320} // namespace esp32_ble_server
321} // namespace esphome
322
323#endif
A class modelled on the Java ByteBuffer class.
Definition bytebuffer.h:38
std::vector< uint8_t > get_data()
Definition bytebuffer.h:300
static ByteBuffer wrap(T value, Endian endianness=LITTLE)
Definition bytebuffer.h:156
std::string to_string() const
Definition ble_uuid.cpp:146
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid)
Definition ble_uuid.cpp:84
static ESPBTUUID from_uint16(uint16_t uuid)
Definition ble_uuid.cpp:17
esp_bt_uuid_t get_uuid() const
Definition ble_uuid.cpp:145
ClientNotificationEntry * find_client_in_notify_list_(uint16_t conn_id)
void remove_descriptor(BLEDescriptor *descriptor)
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)
BLECharacteristic(ESPBTUUID uuid, uint32_t properties)
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:50
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
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:198
uint16_t length
Definition tt21100.cpp:0