ESPHome 2025.6.2
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 for (auto &client : this->service_->get_server()->get_clients()) {
53 size_t length = this->value_.size();
54 // If the client is not in the list of clients to notify, skip it
55 if (this->clients_to_notify_.count(client) == 0)
56 continue;
57 // If the client is in the list of clients to notify, check if it requires an ack (i.e. INDICATE)
58 bool require_ack = this->clients_to_notify_[client];
59 // TODO: Remove this block when INDICATE acknowledgment is supported
60 if (require_ack) {
61 ESP_LOGW(TAG, "INDICATE acknowledgment is not yet supported (i.e. it works as a NOTIFY)");
62 require_ack = false;
63 }
64 esp_err_t err = esp_ble_gatts_send_indicate(this->service_->get_server()->get_gatts_if(), client, this->handle_,
65 length, this->value_.data(), require_ack);
66 if (err != ESP_OK) {
67 ESP_LOGE(TAG, "esp_ble_gatts_send_indicate failed %d", err);
68 return;
69 }
70 }
71}
72
74 // If the descriptor is the CCCD descriptor, listen to its write event to know if the client wants to be notified
75 if (descriptor->get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
76 descriptor->on(BLEDescriptorEvt::VectorEvt::ON_WRITE, [this](const std::vector<uint8_t> &value, uint16_t conn_id) {
77 if (value.size() != 2)
78 return;
79 uint16_t cccd = encode_uint16(value[1], value[0]);
80 bool notify = (cccd & 1) != 0;
81 bool indicate = (cccd & 2) != 0;
82 if (notify || indicate) {
83 this->clients_to_notify_[conn_id] = indicate;
84 } else {
85 this->clients_to_notify_.erase(conn_id);
86 }
87 });
88 }
89 this->descriptors_.push_back(descriptor);
90}
91
93 this->descriptors_.erase(std::remove(this->descriptors_.begin(), this->descriptors_.end(), descriptor),
94 this->descriptors_.end());
95}
96
98 this->service_ = service;
99 esp_attr_control_t control;
100 control.auto_rsp = ESP_GATT_RSP_BY_APP;
101
102 ESP_LOGV(TAG, "Creating characteristic - %s", this->uuid_.to_string().c_str());
103
104 esp_bt_uuid_t uuid = this->uuid_.get_uuid();
105 esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
106 this->properties_, nullptr, &control);
107
108 if (err != ESP_OK) {
109 ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
110 return;
111 }
112
113 this->state_ = CREATING;
114}
115
117 if (this->state_ == CREATED)
118 return true;
119
120 if (this->state_ != CREATING_DEPENDENTS)
121 return false;
122
123 bool created = true;
124 for (auto *descriptor : this->descriptors_) {
125 created &= descriptor->is_created();
126 }
127 if (created)
128 this->state_ = CREATED;
129 return this->state_ == CREATED;
130}
131
133 if (this->state_ == FAILED)
134 return true;
135
136 bool failed = false;
137 for (auto *descriptor : this->descriptors_) {
138 failed |= descriptor->is_failed();
139 }
140 if (failed)
141 this->state_ = FAILED;
142 return this->state_ == FAILED;
143}
144
146 if (value) {
147 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | ESP_GATT_CHAR_PROP_BIT_BROADCAST);
148 } else {
149 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST);
150 }
151}
153 if (value) {
154 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | ESP_GATT_CHAR_PROP_BIT_INDICATE);
155 } else {
156 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_INDICATE);
157 }
158}
160 if (value) {
161 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | ESP_GATT_CHAR_PROP_BIT_NOTIFY);
162 } else {
163 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_NOTIFY);
164 }
165}
167 if (value) {
168 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | ESP_GATT_CHAR_PROP_BIT_READ);
169 } else {
170 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_READ);
171 }
172}
174 if (value) {
175 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | ESP_GATT_CHAR_PROP_BIT_WRITE);
176 } else {
177 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_WRITE);
178 }
179}
181 if (value) {
182 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ | ESP_GATT_CHAR_PROP_BIT_WRITE_NR);
183 } else {
184 this->properties_ = (esp_gatt_char_prop_t) (this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_WRITE_NR);
185 }
186}
187
188void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
189 esp_ble_gatts_cb_param_t *param) {
190 switch (event) {
191 case ESP_GATTS_ADD_CHAR_EVT: {
192 if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
193 this->handle_ = param->add_char.attr_handle;
194
195 for (auto *descriptor : this->descriptors_) {
196 descriptor->do_create(this);
197 }
198
199 this->state_ = CREATING_DEPENDENTS;
200 }
201 break;
202 }
203 case ESP_GATTS_READ_EVT: {
204 if (param->read.handle != this->handle_)
205 break; // Not this characteristic
206
207 if (!param->read.need_rsp)
208 break; // For some reason you can request a read but not want a response
209
211 param->read.conn_id);
212
213 uint16_t max_offset = 22;
214
215 esp_gatt_rsp_t response;
216 if (param->read.is_long) {
217 if (this->value_.size() - this->value_read_offset_ < max_offset) {
218 // Last message in the chain
219 response.attr_value.len = this->value_.size() - this->value_read_offset_;
220 response.attr_value.offset = this->value_read_offset_;
221 memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
222 this->value_read_offset_ = 0;
223 } else {
224 response.attr_value.len = max_offset;
225 response.attr_value.offset = this->value_read_offset_;
226 memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
227 this->value_read_offset_ += max_offset;
228 }
229 } else {
230 response.attr_value.offset = 0;
231 if (this->value_.size() + 1 > max_offset) {
232 response.attr_value.len = max_offset;
233 this->value_read_offset_ = max_offset;
234 } else {
235 response.attr_value.len = this->value_.size();
236 }
237 memcpy(response.attr_value.value, this->value_.data(), response.attr_value.len);
238 }
239
240 response.attr_value.handle = this->handle_;
241 response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
242
243 esp_err_t err =
244 esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &response);
245 if (err != ESP_OK) {
246 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
247 }
248 break;
249 }
250 case ESP_GATTS_WRITE_EVT: {
251 if (this->handle_ != param->write.handle)
252 break;
253
254 if (param->write.is_prep) {
255 this->value_.insert(this->value_.end(), param->write.value, param->write.value + param->write.len);
256 this->write_event_ = true;
257 } else {
258 this->set_value(ByteBuffer::wrap(param->write.value, param->write.len));
259 }
260
261 if (param->write.need_rsp) {
262 esp_gatt_rsp_t response;
263
264 response.attr_value.len = param->write.len;
265 response.attr_value.handle = this->handle_;
266 response.attr_value.offset = param->write.offset;
267 response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
268 memcpy(response.attr_value.value, param->write.value, param->write.len);
269
270 esp_err_t err =
271 esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, &response);
272
273 if (err != ESP_OK) {
274 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
275 }
276 }
277
278 if (!param->write.is_prep) {
280 BLECharacteristicEvt::VectorEvt::ON_WRITE, this->value_, param->write.conn_id);
281 }
282
283 break;
284 }
285
286 case ESP_GATTS_EXEC_WRITE_EVT: {
287 if (!this->write_event_)
288 break;
289 this->write_event_ = false;
290 if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) {
292 BLECharacteristicEvt::VectorEvt::ON_WRITE, this->value_, param->exec_write.conn_id);
293 }
294 esp_err_t err =
295 esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, nullptr);
296 if (err != ESP_OK) {
297 ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
298 }
299 break;
300 }
301 default:
302 break;
303 }
304
305 for (auto *descriptor : this->descriptors_) {
306 descriptor->gatts_event_handler(event, gatts_if, param);
307 }
308}
309
310} // namespace esp32_ble_server
311} // namespace esphome
312
313#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:171
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid)
Definition ble_uuid.cpp:97
static ESPBTUUID from_uint16(uint16_t uuid)
Definition ble_uuid.cpp:16
esp_bt_uuid_t get_uuid() const
Definition ble_uuid.cpp:170
void remove_descriptor(BLEDescriptor *descriptor)
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::unordered_map< uint16_t, bool > clients_to_notify_
std::vector< BLEDescriptor * > descriptors_
void add_descriptor(BLEDescriptor *descriptor)
const std::unordered_set< uint16_t > & get_clients()
Definition ble_server.h:61
EventEmitterListenerID on(EvtType event, std::function< void(Args...)> listener)
void emit_(EvtType event, Args... args)
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:192
uint16_t length
Definition tt21100.cpp:0