3 #include "automation.h" 5 #include <esp_bt_defs.h> 6 #include <esp_gap_ble_api.h> 7 #include <esp_gattc_api.h> 12 namespace ble_client {
13 static const char *
const TAG =
"ble_client.automation";
16 if (this->
node_state != espbt::ClientState::ESTABLISHED) {
17 ESP_LOGW(TAG,
"Cannot write to BLE characteristic - not connected");
19 }
else if (this->ble_char_handle_ == 0) {
20 ESP_LOGW(TAG,
"Cannot write to BLE characteristic - characteristic not found");
23 esp_gatt_write_type_t write_type;
24 if (this->char_props_ & ESP_GATT_CHAR_PROP_BIT_WRITE) {
25 write_type = ESP_GATT_WRITE_TYPE_RSP;
26 ESP_LOGD(TAG,
"Write type: ESP_GATT_WRITE_TYPE_RSP");
27 }
else if (this->char_props_ & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) {
28 write_type = ESP_GATT_WRITE_TYPE_NO_RSP;
29 ESP_LOGD(TAG,
"Write type: ESP_GATT_WRITE_TYPE_NO_RSP");
31 ESP_LOGE(TAG,
"Characteristic %s does not allow writing", this->char_uuid_.
to_string().c_str());
34 ESP_LOGVV(TAG,
"Will write %d bytes: %s", value.size(),
format_hex_pretty(value).c_str());
36 esp_ble_gattc_write_char(this->
parent()->get_gattc_if(), this->
parent()->get_conn_id(), this->ble_char_handle_,
37 value.size(),
const_cast<uint8_t *
>(value.data()), write_type, ESP_GATT_AUTH_REQ_NONE);
39 ESP_LOGE(TAG,
"Error writing to characteristic: %s!", esp_err_to_name(err));
44 esp_ble_gattc_cb_param_t *param) {
46 case ESP_GATTC_REG_EVT:
48 case ESP_GATTC_OPEN_EVT:
49 this->
node_state = espbt::ClientState::ESTABLISHED;
50 ESP_LOGD(TAG,
"Connection established with %s", ble_client_->
address_str().c_str());
52 case ESP_GATTC_SEARCH_CMPL_EVT: {
55 ESP_LOGW(
"ble_write_action",
"Characteristic %s was not found in service %s",
59 this->ble_char_handle_ = chr->handle;
60 this->char_props_ = chr->properties;
61 this->
node_state = espbt::ClientState::ESTABLISHED;
62 ESP_LOGD(TAG,
"Found characteristic %s on device %s", this->char_uuid_.
to_string().c_str(),
66 case ESP_GATTC_DISCONNECT_EVT:
68 this->ble_char_handle_ = 0;
69 ESP_LOGD(TAG,
"Disconnected from %s", ble_client_->
address_str().c_str());
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
std::string to_string() const
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
Implementation of SPI Controller mode.
espbt::ClientState node_state