1 #include "automation.h" 3 #include <esp_bt_defs.h> 4 #include <esp_gap_ble_api.h> 5 #include <esp_gattc_api.h> 10 namespace ble_client {
11 static const char *
const TAG =
"ble_client.automation";
14 if (this->
node_state != espbt::ClientState::ESTABLISHED) {
15 ESP_LOGW(TAG,
"Cannot write to BLE characteristic - not connected");
17 }
else if (this->ble_char_handle_ == 0) {
18 ESP_LOGW(TAG,
"Cannot write to BLE characteristic - characteristic not found");
21 esp_gatt_write_type_t write_type;
22 if (this->char_props_ & ESP_GATT_CHAR_PROP_BIT_WRITE) {
23 write_type = ESP_GATT_WRITE_TYPE_RSP;
24 ESP_LOGD(TAG,
"Write type: ESP_GATT_WRITE_TYPE_RSP");
25 }
else if (this->char_props_ & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) {
26 write_type = ESP_GATT_WRITE_TYPE_NO_RSP;
27 ESP_LOGD(TAG,
"Write type: ESP_GATT_WRITE_TYPE_NO_RSP");
29 ESP_LOGE(TAG,
"Characteristic %s does not allow writing", this->char_uuid_.
to_string().c_str());
32 ESP_LOGVV(TAG,
"Will write %d bytes: %s", value.size(),
format_hex_pretty(value).c_str());
34 esp_ble_gattc_write_char(this->
parent()->get_gattc_if(), this->
parent()->get_conn_id(), this->ble_char_handle_,
35 value.size(),
const_cast<uint8_t *
>(value.data()), write_type, ESP_GATT_AUTH_REQ_NONE);
37 ESP_LOGE(TAG,
"Error writing to characteristic: %s!", esp_err_to_name(err));
42 esp_ble_gattc_cb_param_t *param) {
44 case ESP_GATTC_REG_EVT:
46 case ESP_GATTC_OPEN_EVT:
47 this->
node_state = espbt::ClientState::ESTABLISHED;
48 ESP_LOGD(TAG,
"Connection established with %s", ble_client_->
address_str().c_str());
50 case ESP_GATTC_SEARCH_CMPL_EVT: {
53 ESP_LOGW(
"ble_write_action",
"Characteristic %s was not found in service %s",
57 this->ble_char_handle_ = chr->handle;
58 this->char_props_ = chr->properties;
59 this->
node_state = espbt::ClientState::ESTABLISHED;
60 ESP_LOGD(TAG,
"Found characteristic %s on device %s", this->char_uuid_.
to_string().c_str(),
64 case ESP_GATTC_DISCONNECT_EVT:
66 this->ble_char_handle_ = 0;
67 ESP_LOGD(TAG,
"Disconnected from %s", ble_client_->
address_str().c_str());
std::string to_string() const
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
void write(const std::vector< uint8_t > &value)
std::string address_str() const
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
espbt::ClientState node_state