#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#include <sstream>
#include "BLERemoteDescriptor.h"
#include "GeneralUtils.h"
#include <esp_log.h>
#ifdef ARDUINO_ARCH_ESP32
#include "esp32-hal-log.h"
#endif
static const char* LOG_TAG = "BLERemoteDescriptor";
BLERemoteDescriptor::BLERemoteDescriptor(
uint16_t handle,
BLEUUID uuid,
BLERemoteCharacteristic* pRemoteCharacteristic) {
m_handle = handle;
m_uuid = uuid;
m_pRemoteCharacteristic = pRemoteCharacteristic;
}
uint16_t BLERemoteDescriptor::getHandle() {
return m_handle;
}
BLEUUID BLERemoteDescriptor::getUUID() {
return m_uuid;
}
std::string BLERemoteDescriptor::readValue(void) {
m_semaphoreReadDescrEvt.take("readValue");
esp_err_t errRc = ::esp_ble_gattc_read_char_descr(
m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(),
m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(),
getHandle(),
ESP_GATT_AUTH_REQ_NONE);
if (errRc != ESP_OK) {
ESP_LOGE(LOG_TAG, "esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
return "";
}
m_semaphoreReadDescrEvt.wait("readValue");
ESP_LOGD(LOG_TAG, "<< readValue(): length: %d", m_value.length());
return m_value;
return "";
}
uint8_t BLERemoteDescriptor::readUInt8(void) {
std::string value = readValue();
if (value.length() >= 1) {
return (uint8_t)value[0];
}
return 0;
}
uint16_t BLERemoteDescriptor::readUInt16(void) {
std::string value = readValue();
if (value.length() >= 2) {
return *(uint16_t*)(value.data());
}
return 0;
}
uint32_t BLERemoteDescriptor::readUInt32(void) {
std::string value = readValue();
if (value.length() >= 4) {
return *(uint32_t*)(value.data());
}
return 0;
}
std::string BLERemoteDescriptor::toString(void) {
std::stringstream ss;
ss << "handle: " << getHandle() << ", uuid: " << getUUID().toString();
return ss.str();
}
void BLERemoteDescriptor::writeValue(
uint8_t* data,
size_t length,
bool response) {
ESP_LOGD(LOG_TAG, ">> writeValue: %s", toString().c_str());
esp_err_t errRc = ::esp_ble_gattc_write_char_descr(
m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(),
m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(),
getHandle(),
length,
data,
ESP_GATT_WRITE_TYPE_NO_RSP,
ESP_GATT_AUTH_REQ_NONE
);
if (errRc != ESP_OK) {
ESP_LOGE(LOG_TAG, "esp_ble_gattc_write_char_descr: %d", errRc);
}
ESP_LOGD(LOG_TAG, "<< writeValue");
}
void BLERemoteDescriptor::writeValue(
std::string newValue,
bool response) {
writeValue(newValue.data(), newValue.length());
}
void BLERemoteDescriptor::writeValue(
uint8_t newValue,
bool response) {
writeValue(&newValue, 1, response);
}
#endif