1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-06 05:12:21 +01:00

Improv - BLE WiFi provisioning (#1807)

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
Jesse Hills
2021-06-08 11:56:21 +12:00
committed by GitHub
parent 33625e2dd3
commit a70a205ace
40 changed files with 2422 additions and 42 deletions

View File

@@ -0,0 +1,44 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_MODEL, ESP_PLATFORM_ESP32
ESP_PLATFORMS = [ESP_PLATFORM_ESP32]
CODEOWNERS = ["@jesserockz"]
CONF_MANUFACTURER = "manufacturer"
CONF_SERVER = "server"
esp32_ble_ns = cg.esphome_ns.namespace("esp32_ble")
ESP32BLE = esp32_ble_ns.class_("ESP32BLE", cg.Component)
BLEServer = esp32_ble_ns.class_("BLEServer", cg.Component)
BLEServiceComponent = esp32_ble_ns.class_("BLEServiceComponent")
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(ESP32BLE),
cv.Optional(CONF_SERVER): cv.Schema(
{
cv.GenerateID(): cv.declare_id(BLEServer),
cv.Optional(CONF_MANUFACTURER, default="ESPHome"): cv.string,
cv.Optional(CONF_MODEL): cv.string,
}
),
}
).extend(cv.COMPONENT_SCHEMA)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
if CONF_SERVER in config:
conf = config[CONF_SERVER]
server = cg.new_Pvariable(conf[CONF_ID])
await cg.register_component(server, conf)
cg.add(server.set_manufacturer(conf[CONF_MANUFACTURER]))
if CONF_MODEL in conf:
cg.add(server.set_model(conf[CONF_MODEL]))
cg.add_define("USE_ESP32_BLE_SERVER")
cg.add(var.set_server(server))

View File

@@ -0,0 +1,178 @@
#include "ble.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
#include <nvs_flash.h>
#include <freertos/FreeRTOSConfig.h>
#include <esp_bt_main.h>
#include <esp_bt.h>
#include <freertos/task.h>
#include <esp_gap_ble_api.h>
namespace esphome {
namespace esp32_ble {
static const char *TAG = "esp32_ble";
void ESP32BLE::setup() {
global_ble = this;
ESP_LOGCONFIG(TAG, "Setting up BLE...");
xTaskCreatePinnedToCore(ESP32BLE::ble_core_task_,
"ble_task", // name
10000, // stack size
nullptr, // input params
1, // priority
nullptr, // handle, not needed
0 // core
);
}
void ESP32BLE::mark_failed() {
Component::mark_failed();
if (this->server_ != nullptr) {
this->server_->mark_failed();
}
}
bool ESP32BLE::can_proceed() { return this->ready_; }
void ESP32BLE::ble_core_task_(void *params) {
if (!ble_setup_()) {
ESP_LOGE(TAG, "BLE could not be set up");
global_ble->mark_failed();
return;
}
global_ble->ready_ = true;
ESP_LOGD(TAG, "BLE Setup complete");
while (true) {
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
bool ESP32BLE::ble_setup_() {
esp_err_t err = nvs_flash_init();
if (err != ESP_OK) {
ESP_LOGE(TAG, "nvs_flash_init failed: %d", err);
return false;
}
if (!btStart()) {
ESP_LOGE(TAG, "btStart failed: %d", esp_bt_controller_get_status());
return false;
}
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
err = esp_bluedroid_init();
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_bluedroid_init failed: %d", err);
return false;
}
err = esp_bluedroid_enable();
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_bluedroid_enable failed: %d", err);
return false;
}
err = esp_ble_gap_register_callback(ESP32BLE::gap_event_handler);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_register_callback failed: %d", err);
return false;
}
if (global_ble->has_server()) {
err = esp_ble_gatts_register_callback(ESP32BLE::gatts_event_handler);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_register_callback failed: %d", err);
return false;
}
}
if (global_ble->has_client()) {
err = esp_ble_gattc_register_callback(ESP32BLE::gattc_event_handler);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gattc_register_callback failed: %d", err);
return false;
}
}
err = esp_ble_gap_set_device_name(App.get_name().c_str());
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_set_device_name failed: %d", err);
return false;
}
esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE;
err = esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_set_security_param failed: %d", err);
return false;
}
// BLE takes some time to be fully set up, 200ms should be more than enough
delay(200); // NOLINT
return true;
}
void ESP32BLE::loop() {
BLEEvent *ble_event = this->ble_events_.pop();
while (ble_event != nullptr) {
switch (ble_event->type_) {
case ble_event->GATTS:
this->real_gatts_event_handler_(ble_event->event_.gatts.gatts_event, ble_event->event_.gatts.gatts_if,
&ble_event->event_.gatts.gatts_param);
break;
case ble_event->GAP:
this->real_gap_event_handler_(ble_event->event_.gap.gap_event, &ble_event->event_.gap.gap_param);
break;
default:
break;
}
delete ble_event;
ble_event = this->ble_events_.pop();
}
}
void ESP32BLE::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
global_ble->real_gap_event_handler_(event, param);
}
void ESP32BLE::real_gap_event_handler_(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
ESP_LOGV(TAG, "(BLE) gap_event_handler - %d", event);
switch (event) {
default:
break;
}
}
void ESP32BLE::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param) {
global_ble->real_gatts_event_handler_(event, gatts_if, param);
}
void ESP32BLE::real_gatts_event_handler_(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param) {
ESP_LOGV(TAG, "(BLE) gatts_event [esp_gatt_if: %d] - %d", gatts_if, event);
this->server_->gatts_event_handler(event, gatts_if, param);
}
void ESP32BLE::real_gattc_event_handler_(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
esp_ble_gattc_cb_param_t *param) {
// this->client_->gattc_event_handler(event, gattc_if, param);
}
float ESP32BLE::get_setup_priority() const { return setup_priority::BLUETOOTH; }
void ESP32BLE::dump_config() { ESP_LOGCONFIG(TAG, "ESP32 BLE:"); }
ESP32BLE *global_ble = nullptr;
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,62 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "ble_server.h"
#include "queue.h"
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gap_ble_api.h>
#include <esp_gatts_api.h>
#include <esp_gattc_api.h>
namespace esphome {
namespace esp32_ble {
typedef struct {
void *peer_device;
bool connected;
uint16_t mtu;
} conn_status_t;
class ESP32BLE : public Component {
public:
void setup() override;
void loop() override;
void dump_config() override;
float get_setup_priority() const override;
void mark_failed() override;
bool can_proceed() override;
bool has_server() { return this->server_ != nullptr; }
bool has_client() { return false; }
bool is_ready() { return this->ready_; }
void set_server(BLEServer *server) { this->server_ = server; }
protected:
static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
static void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
void real_gatts_event_handler_(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
void real_gattc_event_handler_(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
void real_gap_event_handler_(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
static void ble_core_task_(void *params);
static bool ble_setup_();
bool ready_{false};
BLEServer *server_{nullptr};
Queue<BLEEvent> ble_events_;
};
extern ESP32BLE *global_ble;
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,18 @@
#include "ble_2901.h"
#include "ble_uuid.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
BLE2901::BLE2901(const std::string value) : BLE2901((uint8_t *) value.data(), value.length()) {}
BLE2901::BLE2901(uint8_t *data, size_t length) : BLEDescriptor(ESPBTUUID::from_uint16(0x2901)) {
this->set_value(data, length);
this->permissions_ = ESP_GATT_PERM_READ;
}
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,19 @@
#pragma once
#include "ble_descriptor.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
class BLE2901 : public BLEDescriptor {
public:
BLE2901(const std::string value);
BLE2901(uint8_t *data, size_t length);
};
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,18 @@
#include "ble_2902.h"
#include "ble_uuid.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
BLE2902::BLE2902() : BLEDescriptor(ESPBTUUID::from_uint16(0x2902)) {
this->value_.attr_len = 2;
uint8_t data[2] = {0, 0};
memcpy(this->value_.attr_value, data, 2);
}
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,18 @@
#pragma once
#include "ble_descriptor.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
class BLE2902 : public BLEDescriptor {
public:
BLE2902();
};
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,97 @@
#include "ble_advertising.h"
#ifdef ARDUINO_ARCH_ESP32
#include "ble_uuid.h"
namespace esphome {
namespace esp32_ble {
BLEAdvertising::BLEAdvertising() {
this->advertising_data_.set_scan_rsp = false;
this->advertising_data_.include_name = true;
this->advertising_data_.include_txpower = true;
this->advertising_data_.min_interval = 0x20;
this->advertising_data_.max_interval = 0x40;
this->advertising_data_.appearance = 0x00;
this->advertising_data_.manufacturer_len = 0;
this->advertising_data_.p_manufacturer_data = nullptr;
this->advertising_data_.service_data_len = 0;
this->advertising_data_.p_service_data = nullptr;
this->advertising_data_.service_uuid_len = 0;
this->advertising_data_.p_service_uuid = nullptr;
this->advertising_data_.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
this->advertising_params_.adv_int_min = 0x20;
this->advertising_params_.adv_int_max = 0x40;
this->advertising_params_.adv_type = ADV_TYPE_IND;
this->advertising_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
this->advertising_params_.channel_map = ADV_CHNL_ALL;
this->advertising_params_.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY;
this->advertising_params_.peer_addr_type = BLE_ADDR_TYPE_PUBLIC;
}
void BLEAdvertising::add_service_uuid(ESPBTUUID uuid) { this->advertising_uuids_.push_back(uuid); }
void BLEAdvertising::start() {
int num_services = this->advertising_uuids_.size();
if (num_services == 0) {
this->advertising_data_.service_uuid_len = 0;
} else {
this->advertising_data_.service_uuid_len = 16 * num_services;
this->advertising_data_.p_service_uuid = new uint8_t[this->advertising_data_.service_uuid_len];
uint8_t *p = this->advertising_data_.p_service_uuid;
for (int i = 0; i < num_services; i++) {
ESPBTUUID uuid = this->advertising_uuids_[i];
memcpy(p, uuid.as_128bit().get_uuid().uuid.uuid128, 16);
p += 16;
}
}
esp_err_t err;
this->advertising_data_.set_scan_rsp = false;
this->advertising_data_.include_name = !this->scan_response_;
this->advertising_data_.include_txpower = !this->scan_response_;
err = esp_ble_gap_config_adv_data(&this->advertising_data_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_config_adv_data failed (Advertising): %d", err);
return;
}
memcpy(&this->scan_response_data_, &this->advertising_data_, sizeof(esp_ble_adv_data_t));
this->scan_response_data_.set_scan_rsp = true;
this->scan_response_data_.include_name = true;
this->scan_response_data_.include_txpower = true;
this->scan_response_data_.appearance = 0;
this->scan_response_data_.flag = 0;
err = esp_ble_gap_config_adv_data(&this->scan_response_data_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_config_adv_data failed (Scan response): %d", err);
return;
}
if (this->advertising_data_.service_uuid_len > 0) {
delete[] this->advertising_data_.p_service_uuid;
this->advertising_data_.p_service_uuid = nullptr;
}
err = esp_ble_gap_start_advertising(&this->advertising_params_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_start_advertising failed: %d", err);
return;
}
}
void BLEAdvertising::stop() {
esp_err_t err = esp_ble_gap_stop_advertising();
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_stop_advertising failed: %d", err);
return;
}
}
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,37 @@
#pragma once
#include <vector>
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gap_ble_api.h>
#include <esp_gatts_api.h>
namespace esphome {
namespace esp32_ble {
class ESPBTUUID;
class BLEAdvertising {
public:
BLEAdvertising();
void add_service_uuid(ESPBTUUID uuid);
void set_scan_response(bool scan_response) { this->scan_response_ = scan_response; }
void set_min_preferred_interval(uint16_t interval) { this->advertising_data_.min_interval = interval; }
void start();
void stop();
protected:
bool scan_response_;
esp_ble_adv_data_t advertising_data_;
esp_ble_adv_data_t scan_response_data_;
esp_ble_adv_params_t advertising_params_;
std::vector<ESPBTUUID> advertising_uuids_;
};
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,280 @@
#include "ble_characteristic.h"
#include "ble_server.h"
#include "ble_service.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
static const char *TAG = "esp32_ble.characteristic";
BLECharacteristic::BLECharacteristic(const ESPBTUUID uuid, uint32_t properties) : uuid_(uuid) {
this->set_value_lock_ = xSemaphoreCreateBinary();
this->create_lock_ = xSemaphoreCreateBinary();
xSemaphoreGive(this->set_value_lock_);
xSemaphoreGive(this->create_lock_);
this->properties_ = (esp_gatt_char_prop_t) 0;
this->set_broadcast_property((properties & PROPERTY_BROADCAST) != 0);
this->set_indicate_property((properties & PROPERTY_INDICATE) != 0);
this->set_notify_property((properties & PROPERTY_NOTIFY) != 0);
this->set_read_property((properties & PROPERTY_READ) != 0);
this->set_write_property((properties & PROPERTY_WRITE) != 0);
this->set_write_no_response_property((properties & PROPERTY_WRITE_NR) != 0);
}
void BLECharacteristic::set_value(std::vector<uint8_t> value) {
xSemaphoreTake(this->set_value_lock_, 0L);
this->value_ = value;
xSemaphoreGive(this->set_value_lock_);
}
void BLECharacteristic::set_value(std::string value) {
this->set_value(std::vector<uint8_t>(value.begin(), value.end()));
}
void BLECharacteristic::set_value(uint8_t *data, size_t length) {
this->set_value(std::vector<uint8_t>(data, data + length));
}
void BLECharacteristic::set_value(uint8_t &data) {
uint8_t temp[1];
temp[0] = data;
this->set_value(temp, 1);
}
void BLECharacteristic::set_value(uint16_t &data) {
uint8_t temp[2];
temp[0] = data;
temp[1] = data >> 8;
this->set_value(temp, 2);
}
void BLECharacteristic::set_value(uint32_t &data) {
uint8_t temp[4];
temp[0] = data;
temp[1] = data >> 8;
temp[2] = data >> 16;
temp[3] = data >> 24;
this->set_value(temp, 4);
}
void BLECharacteristic::set_value(int &data) {
uint8_t temp[4];
temp[0] = data;
temp[1] = data >> 8;
temp[2] = data >> 16;
temp[3] = data >> 24;
this->set_value(temp, 4);
}
void BLECharacteristic::set_value(float &data) {
float temp = data;
this->set_value((uint8_t *) &temp, 4);
}
void BLECharacteristic::set_value(double &data) {
double temp = data;
this->set_value((uint8_t *) &temp, 8);
}
void BLECharacteristic::set_value(bool &data) {
uint8_t temp[1];
temp[0] = data;
this->set_value(temp, 1);
}
void BLECharacteristic::notify(bool notification) {
if (!notification) {
ESP_LOGW(TAG, "notification=false is not yet supported");
// TODO: Handle when notification=false
}
if (this->service_->get_server()->get_connected_client_count() == 0)
return;
for (auto &client : this->service_->get_server()->get_clients()) {
size_t length = this->value_.size();
esp_err_t err = esp_ble_gatts_send_indicate(this->service_->get_server()->get_gatts_if(), client.first,
this->handle_, length, this->value_.data(), false);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_indicate failed %d", err);
return;
}
}
}
void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) { this->descriptors_.push_back(descriptor); }
bool BLECharacteristic::do_create(BLEService *service) {
this->service_ = service;
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_RSP_BY_APP;
xSemaphoreTake(this->create_lock_, SEMAPHORE_MAX_DELAY);
ESP_LOGV(TAG, "Creating characteristic - %s", this->uuid_.to_string().c_str());
esp_bt_uuid_t uuid = this->uuid_.get_uuid();
esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
this->properties_, nullptr, &control);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
return false;
}
xSemaphoreWait(this->create_lock_, SEMAPHORE_MAX_DELAY);
for (auto *descriptor : this->descriptors_) {
descriptor->do_create(this);
}
return true;
}
void BLECharacteristic::set_broadcast_property(bool value) {
if (value)
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_BROADCAST);
else
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST);
}
void BLECharacteristic::set_indicate_property(bool value) {
if (value)
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_INDICATE);
else
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_INDICATE);
}
void BLECharacteristic::set_notify_property(bool value) {
if (value)
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_NOTIFY);
else
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_NOTIFY);
}
void BLECharacteristic::set_read_property(bool value) {
if (value)
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_READ);
else
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_READ);
}
void BLECharacteristic::set_write_property(bool value) {
if (value)
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_WRITE);
else
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_WRITE);
}
void BLECharacteristic::set_write_no_response_property(bool value) {
if (value)
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ | ESP_GATT_CHAR_PROP_BIT_WRITE_NR);
else
this->properties_ = (esp_gatt_char_prop_t)(this->properties_ & ~ESP_GATT_CHAR_PROP_BIT_WRITE_NR);
}
void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param) {
switch (event) {
case ESP_GATTS_ADD_CHAR_EVT: {
if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
this->handle_ = param->add_char.attr_handle;
xSemaphoreGive(this->create_lock_);
}
break;
}
case ESP_GATTS_READ_EVT: {
if (param->read.handle != this->handle_)
break; // Not this characteristic
if (!param->read.need_rsp)
break; // For some reason you can request a read but not want a response
uint16_t max_offset = 22;
esp_gatt_rsp_t response;
if (param->read.is_long) {
if (this->value_.size() - this->value_read_offset_ < max_offset) {
// Last message in the chain
response.attr_value.len = this->value_.size() - this->value_read_offset_;
response.attr_value.offset = this->value_read_offset_;
memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
this->value_read_offset_ = 0;
} else {
response.attr_value.len = max_offset;
response.attr_value.offset = this->value_read_offset_;
memcpy(response.attr_value.value, this->value_.data() + response.attr_value.offset, response.attr_value.len);
this->value_read_offset_ += max_offset;
}
} else {
response.attr_value.offset = 0;
if (this->value_.size() + 1 > max_offset) {
response.attr_value.len = max_offset;
this->value_read_offset_ = max_offset;
} else {
response.attr_value.len = this->value_.size();
}
memcpy(response.attr_value.value, this->value_.data(), response.attr_value.len);
}
response.attr_value.handle = this->handle_;
response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
esp_err_t err =
esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &response);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
}
break;
}
case ESP_GATTS_WRITE_EVT: {
if (this->handle_ != param->write.handle)
return;
if (param->write.is_prep) {
this->value_.insert(this->value_.end(), param->write.value, param->write.value + param->write.len);
this->write_event_ = true;
} else {
this->set_value(param->write.value, param->write.len);
}
if (param->write.need_rsp) {
esp_gatt_rsp_t response;
response.attr_value.len = param->write.len;
response.attr_value.handle = this->handle_;
response.attr_value.offset = param->write.offset;
response.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
memcpy(response.attr_value.value, param->write.value, param->write.len);
esp_err_t err =
esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, &response);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
}
}
if (!param->write.is_prep) {
this->on_write_(this->value_);
}
break;
}
case ESP_GATTS_EXEC_WRITE_EVT: {
if (!this->write_event_)
break;
this->write_event_ = false;
if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) {
this->on_write_(this->value_);
}
esp_err_t err =
esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, nullptr);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_send_response failed: %d", err);
}
break;
}
default:
break;
}
for (auto *descriptor : this->descriptors_) {
descriptor->gatts_event_handler(event, gatts_if, param);
}
}
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,85 @@
#pragma once
#include <vector>
#include "ble_uuid.h"
#include "ble_descriptor.h"
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gap_ble_api.h>
#include <esp_gatt_defs.h>
#include <esp_gattc_api.h>
#include <esp_gatts_api.h>
#include <esp_bt_defs.h>
namespace esphome {
namespace esp32_ble {
class BLEService;
class BLECharacteristic {
public:
BLECharacteristic(const ESPBTUUID uuid, uint32_t properties);
void set_value(uint8_t *data, size_t length);
void set_value(std::vector<uint8_t> value);
void set_value(std::string value);
void set_value(uint8_t &data);
void set_value(uint16_t &data);
void set_value(uint32_t &data);
void set_value(int &data);
void set_value(float &data);
void set_value(double &data);
void set_value(bool &data);
void set_broadcast_property(bool value);
void set_indicate_property(bool value);
void set_notify_property(bool value);
void set_read_property(bool value);
void set_write_property(bool value);
void set_write_no_response_property(bool value);
void notify(bool notification = true);
bool do_create(BLEService *service);
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
void on_write(const std::function<void(std::vector<uint8_t> &)> &func) { this->on_write_ = func; }
void add_descriptor(BLEDescriptor *descriptor);
BLEService *get_service() { return this->service_; }
ESPBTUUID get_uuid() { return this->uuid_; }
std::vector<uint8_t> &get_value() { return this->value_; }
static const uint32_t PROPERTY_READ = 1 << 0;
static const uint32_t PROPERTY_WRITE = 1 << 1;
static const uint32_t PROPERTY_NOTIFY = 1 << 2;
static const uint32_t PROPERTY_BROADCAST = 1 << 3;
static const uint32_t PROPERTY_INDICATE = 1 << 4;
static const uint32_t PROPERTY_WRITE_NR = 1 << 5;
protected:
bool write_event_{false};
BLEService *service_;
ESPBTUUID uuid_;
esp_gatt_char_prop_t properties_;
uint16_t handle_{0xFFFF};
uint16_t value_read_offset_{0};
std::vector<uint8_t> value_;
SemaphoreHandle_t set_value_lock_;
SemaphoreHandle_t create_lock_;
std::vector<BLEDescriptor *> descriptors_;
std::function<void(std::vector<uint8_t> &)> on_write_;
esp_gatt_perm_t permissions_ = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
};
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,82 @@
#include "ble_descriptor.h"
#include "ble_characteristic.h"
#include "ble_service.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
static const char *TAG = "esp32_ble.descriptor";
BLEDescriptor::BLEDescriptor(ESPBTUUID uuid, uint16_t max_len) {
this->uuid_ = uuid;
this->value_.attr_len = 0;
this->value_.attr_max_len = max_len;
this->value_.attr_value = (uint8_t *) malloc(max_len);
this->create_lock_ = xSemaphoreCreateBinary();
xSemaphoreGive(this->create_lock_);
}
BLEDescriptor::~BLEDescriptor() { free(this->value_.attr_value); }
bool BLEDescriptor::do_create(BLECharacteristic *characteristic) {
this->characteristic_ = characteristic;
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_AUTO_RSP;
xSemaphoreTake(this->create_lock_, SEMAPHORE_MAX_DELAY);
ESP_LOGV(TAG, "Creating descriptor - %s", this->uuid_.to_string().c_str());
esp_bt_uuid_t uuid = this->uuid_.get_uuid();
esp_err_t err = esp_ble_gatts_add_char_descr(this->characteristic_->get_service()->get_handle(), &uuid,
this->permissions_, &this->value_, &control);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_add_char_descr failed: %d", err);
return false;
}
xSemaphoreWait(this->create_lock_, SEMAPHORE_MAX_DELAY);
return true;
}
void BLEDescriptor::set_value(const std::string value) { this->set_value((uint8_t *) value.data(), value.length()); }
void BLEDescriptor::set_value(uint8_t *data, size_t length) {
if (length > this->value_.attr_max_len) {
ESP_LOGE(TAG, "Size %d too large, must be no bigger than %d", length, this->value_.attr_max_len);
return;
}
this->value_.attr_len = length;
memcpy(this->value_.attr_value, data, length);
}
void BLEDescriptor::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param) {
switch (event) {
case ESP_GATTS_ADD_CHAR_DESCR_EVT: {
if (this->characteristic_ != nullptr && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
this->characteristic_->get_service()->get_handle() == param->add_char_descr.service_handle &&
this->characteristic_ == this->characteristic_->get_service()->get_last_created_characteristic()) {
this->handle_ = param->add_char_descr.attr_handle;
xSemaphoreGive(this->create_lock_);
}
break;
}
case ESP_GATTS_WRITE_EVT: {
if (this->handle_ == param->write.handle) {
this->value_.attr_len = param->write.len;
memcpy(this->value_.attr_value, param->write.value, param->write.len);
}
break;
}
default:
break;
}
}
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,40 @@
#pragma once
#include "ble_uuid.h"
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gatt_defs.h>
#include <esp_gatts_api.h>
namespace esphome {
namespace esp32_ble {
class BLECharacteristic;
class BLEDescriptor {
public:
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len = 100);
virtual ~BLEDescriptor();
bool do_create(BLECharacteristic *characteristic);
void set_value(const std::string value);
void set_value(uint8_t *data, size_t length);
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
protected:
BLECharacteristic *characteristic_{nullptr};
ESPBTUUID uuid_;
uint16_t handle_{0xFFFF};
SemaphoreHandle_t create_lock_;
esp_attr_value_t value_;
esp_gatt_perm_t permissions_ = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
};
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,158 @@
#include "ble_server.h"
#include "ble.h"
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#include "esphome/core/version.h"
#ifdef ARDUINO_ARCH_ESP32
#include <nvs_flash.h>
#include <freertos/FreeRTOSConfig.h>
#include <esp_bt_main.h>
#include <esp_bt.h>
#include <freertos/task.h>
#include <esp_gap_ble_api.h>
namespace esphome {
namespace esp32_ble {
static const char *TAG = "esp32_ble.server";
static const uint16_t DEVICE_INFORMATION_SERVICE_UUID = 0x180A;
static const uint16_t MODEL_UUID = 0x2A24;
static const uint16_t VERSION_UUID = 0x2A26;
static const uint16_t MANUFACTURER_UUID = 0x2A29;
void BLEServer::setup() {
if (this->is_failed()) {
ESP_LOGE(TAG, "BLE Server was marked failed by ESP32BLE");
return;
}
ESP_LOGD(TAG, "Setting up BLE Server...");
global_ble_server = this;
this->register_lock_ = xSemaphoreCreateBinary();
xSemaphoreGive(this->register_lock_);
this->advertising_ = new BLEAdvertising();
this->setup_server_();
for (auto *component : this->service_components_) {
component->setup_service();
}
ESP_LOGD(TAG, "BLE Server set up complete...");
}
void BLEServer::setup_server_() {
xSemaphoreTake(this->register_lock_, SEMAPHORE_MAX_DELAY);
esp_err_t err = esp_ble_gatts_app_register(0);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_app_register failed: %d", err);
this->mark_failed();
return;
}
xSemaphoreWait(this->register_lock_, SEMAPHORE_MAX_DELAY);
this->device_information_service = this->create_service(DEVICE_INFORMATION_SERVICE_UUID);
this->create_device_characteristics_();
this->advertising_->set_scan_response(true);
this->advertising_->set_min_preferred_interval(0x06);
this->advertising_->start();
this->device_information_service->start();
}
bool BLEServer::create_device_characteristics_() {
if (this->model_.has_value()) {
BLECharacteristic *model =
this->device_information_service->create_characteristic(MODEL_UUID, BLECharacteristic::PROPERTY_READ);
model->set_value(this->model_.value());
} else {
#ifdef ARDUINO_BOARD
BLECharacteristic *model =
this->device_information_service->create_characteristic(MODEL_UUID, BLECharacteristic::PROPERTY_READ);
model->set_value(ARDUINO_BOARD);
#endif
}
BLECharacteristic *version =
this->device_information_service->create_characteristic(VERSION_UUID, BLECharacteristic::PROPERTY_READ);
version->set_value("ESPHome " ESPHOME_VERSION);
BLECharacteristic *manufacturer =
this->device_information_service->create_characteristic(MANUFACTURER_UUID, BLECharacteristic::PROPERTY_READ);
manufacturer->set_value(this->manufacturer_);
return true;
}
BLEService *BLEServer::create_service(const uint8_t *uuid, bool advertise) {
return this->create_service(ESPBTUUID::from_raw(uuid), advertise);
}
BLEService *BLEServer::create_service(uint16_t uuid, bool advertise) {
return this->create_service(ESPBTUUID::from_uint16(uuid), advertise);
}
BLEService *BLEServer::create_service(const std::string uuid, bool advertise) {
return this->create_service(ESPBTUUID::from_raw(uuid), advertise);
}
BLEService *BLEServer::create_service(ESPBTUUID uuid, bool advertise, uint16_t num_handles, uint8_t inst_id) {
ESP_LOGV(TAG, "Creating service - %s", uuid.to_string().c_str());
BLEService *service = new BLEService(uuid, num_handles, inst_id);
this->services_.push_back(service);
if (advertise) {
this->advertising_->add_service_uuid(uuid);
}
service->do_create(this);
return service;
}
void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param) {
switch (event) {
case ESP_GATTS_CONNECT_EVT: {
ESP_LOGD(TAG, "BLE Client connected");
this->add_client_(param->connect.conn_id, (void *) this);
this->connected_clients_++;
for (auto *component : this->service_components_) {
component->on_client_connect();
}
break;
}
case ESP_GATTS_DISCONNECT_EVT: {
ESP_LOGD(TAG, "BLE Client disconnected");
if (this->remove_client_(param->disconnect.conn_id))
this->connected_clients_--;
this->advertising_->start();
for (auto *component : this->service_components_) {
component->on_client_disconnect();
}
break;
}
case ESP_GATTS_REG_EVT: {
this->gatts_if_ = gatts_if;
xSemaphoreGive(this->register_lock_);
break;
}
default:
break;
}
for (auto *service : this->services_) {
service->gatts_event_handler(event, gatts_if, param);
}
}
float BLEServer::get_setup_priority() const { return setup_priority::BLUETOOTH - 10; }
void BLEServer::dump_config() { ESP_LOGCONFIG(TAG, "ESP32 BLE Server:"); }
BLEServer *global_ble_server = nullptr;
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,84 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/preferences.h"
#include "ble_service.h"
#include "ble_characteristic.h"
#include "ble_uuid.h"
#include "ble_advertising.h"
#include <map>
#include "queue.h"
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gap_ble_api.h>
#include <esp_gatts_api.h>
namespace esphome {
namespace esp32_ble {
class BLEServiceComponent {
public:
virtual void setup_service();
virtual void on_client_connect(){};
virtual void on_client_disconnect(){};
};
class BLEServer : public Component {
public:
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void teardown();
void set_manufacturer(const std::string manufacturer) { this->manufacturer_ = manufacturer; }
void set_model(const std::string model) { this->model_ = model; }
BLEService *create_service(const uint8_t *uuid, bool advertise = false);
BLEService *create_service(uint16_t uuid, bool advertise = false);
BLEService *create_service(const std::string uuid, bool advertise = false);
BLEService *create_service(ESPBTUUID uuid, bool advertise = false, uint16_t num_handles = 15, uint8_t inst_id = 0);
esp_gatt_if_t get_gatts_if() { return this->gatts_if_; }
uint32_t get_connected_client_count() { return this->connected_clients_; }
std::map<uint16_t, void *> get_clients() { return this->clients_; }
BLEAdvertising *get_advertising() { return this->advertising_; }
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
void register_service_component(BLEServiceComponent *component) { this->service_components_.push_back(component); }
protected:
bool create_device_characteristics_();
void setup_server_();
void add_client_(uint16_t conn_id, void *client) {
this->clients_.insert(std::pair<uint16_t, void *>(conn_id, client));
}
bool remove_client_(uint16_t conn_id) { return this->clients_.erase(conn_id) > 0; }
std::string manufacturer_;
optional<std::string> model_;
esp_gatt_if_t gatts_if_{0};
BLEAdvertising *advertising_;
uint32_t connected_clients_{0};
std::map<uint16_t, void *> clients_;
std::vector<BLEService *> services_;
BLEService *device_information_service;
std::vector<BLEServiceComponent *> service_components_;
SemaphoreHandle_t register_lock_;
};
extern BLEServer *global_ble_server;
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,129 @@
#include "ble_service.h"
#include "ble_server.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
static const char *TAG = "esp32_ble.service";
BLEService::BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id)
: uuid_(uuid), num_handles_(num_handles), inst_id_(inst_id) {
this->create_lock_ = xSemaphoreCreateBinary();
this->start_lock_ = xSemaphoreCreateBinary();
this->stop_lock_ = xSemaphoreCreateBinary();
xSemaphoreGive(this->create_lock_);
xSemaphoreGive(this->start_lock_);
xSemaphoreGive(this->stop_lock_);
}
BLEService::~BLEService() {
for (auto &chr : this->characteristics_)
delete chr;
}
BLECharacteristic *BLEService::get_characteristic(ESPBTUUID uuid) {
for (auto *chr : this->characteristics_)
if (chr->get_uuid() == uuid)
return chr;
return nullptr;
}
BLECharacteristic *BLEService::get_characteristic(uint16_t uuid) {
return this->get_characteristic(ESPBTUUID::from_uint16(uuid));
}
BLECharacteristic *BLEService::create_characteristic(uint16_t uuid, esp_gatt_char_prop_t properties) {
return create_characteristic(ESPBTUUID::from_uint16(uuid), properties);
}
BLECharacteristic *BLEService::create_characteristic(const std::string uuid, esp_gatt_char_prop_t properties) {
return create_characteristic(ESPBTUUID::from_raw(uuid), properties);
}
BLECharacteristic *BLEService::create_characteristic(ESPBTUUID uuid, esp_gatt_char_prop_t properties) {
BLECharacteristic *characteristic = new BLECharacteristic(uuid, properties);
this->characteristics_.push_back(characteristic);
return characteristic;
}
bool BLEService::do_create(BLEServer *server) {
this->server_ = server;
xSemaphoreTake(this->create_lock_, SEMAPHORE_MAX_DELAY);
esp_gatt_srvc_id_t srvc_id;
srvc_id.is_primary = true;
srvc_id.id.inst_id = this->inst_id_;
srvc_id.id.uuid = this->uuid_.get_uuid();
esp_err_t err = esp_ble_gatts_create_service(server->get_gatts_if(), &srvc_id, this->num_handles_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_create_service failed: %d", err);
return false;
}
xSemaphoreWait(this->create_lock_, SEMAPHORE_MAX_DELAY);
return true;
}
void BLEService::start() {
for (auto *characteristic : this->characteristics_) {
this->last_created_characteristic_ = characteristic;
characteristic->do_create(this);
}
xSemaphoreTake(this->start_lock_, SEMAPHORE_MAX_DELAY);
esp_err_t err = esp_ble_gatts_start_service(this->handle_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_start_service failed: %d", err);
return;
}
xSemaphoreWait(this->start_lock_, SEMAPHORE_MAX_DELAY);
}
void BLEService::stop() {
xSemaphoreTake(this->stop_lock_, SEMAPHORE_MAX_DELAY);
esp_err_t err = esp_ble_gatts_stop_service(this->handle_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gatts_stop_service failed: %d", err);
return;
}
xSemaphoreWait(this->stop_lock_, SEMAPHORE_MAX_DELAY);
}
void BLEService::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
esp_ble_gatts_cb_param_t *param) {
switch (event) {
case ESP_GATTS_CREATE_EVT: {
if (this->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
this->inst_id_ == param->create.service_id.id.inst_id) {
this->handle_ = param->create.service_handle;
xSemaphoreGive(this->create_lock_);
}
break;
}
case ESP_GATTS_START_EVT: {
if (param->start.service_handle == this->handle_) {
xSemaphoreGive(this->start_lock_);
}
break;
}
case ESP_GATTS_STOP_EVT: {
if (param->start.service_handle == this->handle_) {
xSemaphoreGive(this->stop_lock_);
}
break;
}
default:
break;
}
for (auto *characteristic : this->characteristics_) {
characteristic->gatts_event_handler(event, gatts_if, param);
}
}
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,61 @@
#pragma once
#include "ble_uuid.h"
#include "ble_characteristic.h"
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gap_ble_api.h>
#include <esp_gatt_defs.h>
#include <esp_gattc_api.h>
#include <esp_gatts_api.h>
#include <esp_bt_defs.h>
namespace esphome {
namespace esp32_ble {
class BLEServer;
class BLEService {
public:
BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id);
~BLEService();
BLECharacteristic *get_characteristic(ESPBTUUID uuid);
BLECharacteristic *get_characteristic(uint16_t uuid);
BLECharacteristic *create_characteristic(const std::string uuid, esp_gatt_char_prop_t properties);
BLECharacteristic *create_characteristic(uint16_t uuid, esp_gatt_char_prop_t properties);
BLECharacteristic *create_characteristic(ESPBTUUID uuid, esp_gatt_char_prop_t properties);
ESPBTUUID get_uuid() { return this->uuid_; }
BLECharacteristic *get_last_created_characteristic() { return this->last_created_characteristic_; }
uint16_t get_handle() { return this->handle_; }
BLEServer *get_server() { return this->server_; }
bool do_create(BLEServer *server);
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
void start();
void stop();
protected:
bool errored_{false};
std::vector<BLECharacteristic *> characteristics_;
BLECharacteristic *last_created_characteristic_{nullptr};
BLEServer *server_;
ESPBTUUID uuid_;
uint16_t num_handles_;
uint16_t handle_{0xFFFF};
uint8_t inst_id_;
SemaphoreHandle_t create_lock_;
SemaphoreHandle_t start_lock_;
SemaphoreHandle_t stop_lock_;
};
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,184 @@
#include "ble_uuid.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble {
ESPBTUUID::ESPBTUUID() : uuid_() {}
ESPBTUUID ESPBTUUID::from_uint16(uint16_t uuid) {
ESPBTUUID ret;
ret.uuid_.len = ESP_UUID_LEN_16;
ret.uuid_.uuid.uuid16 = uuid;
return ret;
}
ESPBTUUID ESPBTUUID::from_uint32(uint32_t uuid) {
ESPBTUUID ret;
ret.uuid_.len = ESP_UUID_LEN_32;
ret.uuid_.uuid.uuid32 = uuid;
return ret;
}
ESPBTUUID ESPBTUUID::from_raw(const uint8_t *data) {
ESPBTUUID ret;
ret.uuid_.len = ESP_UUID_LEN_128;
for (size_t i = 0; i < ESP_UUID_LEN_128; i++)
ret.uuid_.uuid.uuid128[i] = data[i];
return ret;
}
ESPBTUUID ESPBTUUID::from_raw(const std::string data) {
ESPBTUUID ret;
if (data.length() == 4) {
ret.uuid_.len = ESP_UUID_LEN_16;
ret.uuid_.uuid.uuid16 = 0;
for (int i = 0; i < data.length();) {
uint8_t MSB = data.c_str()[i];
uint8_t LSB = data.c_str()[i + 1];
if (MSB > '9')
MSB -= 7;
if (LSB > '9')
LSB -= 7;
ret.uuid_.uuid.uuid16 += (((MSB & 0x0F) << 4) | (LSB & 0x0F)) << (2 - i) * 4;
i += 2;
}
} else if (data.length() == 8) {
ret.uuid_.len = ESP_UUID_LEN_32;
ret.uuid_.uuid.uuid32 = 0;
for (int i = 0; i < data.length();) {
uint8_t MSB = data.c_str()[i];
uint8_t LSB = data.c_str()[i + 1];
if (MSB > '9')
MSB -= 7;
if (LSB > '9')
LSB -= 7;
ret.uuid_.uuid.uuid32 += (((MSB & 0x0F) << 4) | (LSB & 0x0F)) << (6 - i) * 4;
i += 2;
}
} else if (data.length() == 16) { // how we can have 16 byte length string reprezenting 128 bit uuid??? needs to be
// investigated (lack of time)
ret.uuid_.len = ESP_UUID_LEN_128;
memcpy(ret.uuid_.uuid.uuid128, (uint8_t *) data.data(), 16);
} else if (data.length() == 36) {
// If the length of the string is 36 bytes then we will assume it is a long hex string in
// UUID format.
ret.uuid_.len = ESP_UUID_LEN_128;
int n = 0;
for (int i = 0; i < data.length();) {
if (data.c_str()[i] == '-')
i++;
uint8_t MSB = data.c_str()[i];
uint8_t LSB = data.c_str()[i + 1];
if (MSB > '9')
MSB -= 7;
if (LSB > '9')
LSB -= 7;
ret.uuid_.uuid.uuid128[15 - n++] = ((MSB & 0x0F) << 4) | (LSB & 0x0F);
i += 2;
}
} else {
ESP_LOGE(TAG, "ERROR: UUID value not 2, 4, 16 or 36 bytes - %s", data.c_str());
}
return ret;
}
ESPBTUUID ESPBTUUID::from_uuid(esp_bt_uuid_t uuid) {
ESPBTUUID ret;
ret.uuid_.len = uuid.len;
ret.uuid_.uuid.uuid16 = uuid.uuid.uuid16;
ret.uuid_.uuid.uuid32 = uuid.uuid.uuid32;
for (size_t i = 0; i < ESP_UUID_LEN_128; i++)
ret.uuid_.uuid.uuid128[i] = uuid.uuid.uuid128[i];
return ret;
}
ESPBTUUID ESPBTUUID::as_128bit() const {
if (this->uuid_.len == ESP_UUID_LEN_128) {
return *this;
}
uint8_t data[] = {0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint32_t uuid32;
if (this->uuid_.len == ESP_UUID_LEN_32) {
uuid32 = this->uuid_.uuid.uuid32;
} else {
uuid32 = this->uuid_.uuid.uuid16;
}
for (uint8_t i = 0; i < this->uuid_.len; i++) {
data[12 + i] = ((uuid32 >> i * 8) & 0xFF);
}
return ESPBTUUID::from_raw(data);
}
bool ESPBTUUID::contains(uint8_t data1, uint8_t data2) const {
if (this->uuid_.len == ESP_UUID_LEN_16) {
return (this->uuid_.uuid.uuid16 >> 8) == data2 && (this->uuid_.uuid.uuid16 & 0xFF) == data1;
} else if (this->uuid_.len == ESP_UUID_LEN_32) {
for (uint8_t i = 0; i < 3; i++) {
bool a = ((this->uuid_.uuid.uuid32 >> i * 8) & 0xFF) == data1;
bool b = ((this->uuid_.uuid.uuid32 >> (i + 1) * 8) & 0xFF) == data2;
if (a && b)
return true;
}
} else {
for (uint8_t i = 0; i < 15; i++) {
if (this->uuid_.uuid.uuid128[i] == data1 && this->uuid_.uuid.uuid128[i + 1] == data2)
return true;
}
}
return false;
}
bool ESPBTUUID::operator==(const ESPBTUUID &uuid) const {
if (this->uuid_.len == uuid.uuid_.len) {
switch (this->uuid_.len) {
case ESP_UUID_LEN_16:
if (uuid.uuid_.uuid.uuid16 == this->uuid_.uuid.uuid16) {
return true;
}
break;
case ESP_UUID_LEN_32:
if (uuid.uuid_.uuid.uuid32 == this->uuid_.uuid.uuid32) {
return true;
}
break;
case ESP_UUID_LEN_128:
for (int i = 0; i < ESP_UUID_LEN_128; i++) {
if (uuid.uuid_.uuid.uuid128[i] != this->uuid_.uuid.uuid128[i]) {
return false;
}
}
return true;
break;
}
} else {
return this->as_128bit() == uuid.as_128bit();
}
return false;
}
esp_bt_uuid_t ESPBTUUID::get_uuid() { return this->uuid_; }
std::string ESPBTUUID::to_string() {
char sbuf[64];
switch (this->uuid_.len) {
case ESP_UUID_LEN_16:
sprintf(sbuf, "0x%02X%02X", this->uuid_.uuid.uuid16 >> 8, this->uuid_.uuid.uuid16 & 0xff);
break;
case ESP_UUID_LEN_32:
sprintf(sbuf, "0x%02X%02X%02X%02X", this->uuid_.uuid.uuid32 >> 24, (this->uuid_.uuid.uuid32 >> 16 & 0xff),
(this->uuid_.uuid.uuid32 >> 8 & 0xff), this->uuid_.uuid.uuid32 & 0xff);
break;
default:
case ESP_UUID_LEN_128:
char *bpos = sbuf;
for (int8_t i = 15; i >= 0; i--) {
sprintf(bpos, "%02X", this->uuid_.uuid.uuid128[i]);
bpos += 2;
if (i == 6 || i == 8 || i == 10 || i == 12)
sprintf(bpos++, "-");
}
sbuf[47] = '\0';
break;
}
return sbuf;
}
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,45 @@
#pragma once
#include "esphome/core/helpers.h"
#ifdef ARDUINO_ARCH_ESP32
#include <string>
#include <esp_bt_defs.h>
namespace esphome {
namespace esp32_ble {
class ESPBTUUID {
public:
ESPBTUUID();
static ESPBTUUID from_uint16(uint16_t uuid);
static ESPBTUUID from_uint32(uint32_t uuid);
static ESPBTUUID from_raw(const uint8_t *data);
static ESPBTUUID from_raw(const std::string data);
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid);
ESPBTUUID as_128bit() const;
bool contains(uint8_t data1, uint8_t data2) const;
bool operator==(const ESPBTUUID &uuid) const;
bool operator!=(const ESPBTUUID &uuid) const { return !(*this == uuid); }
esp_bt_uuid_t get_uuid();
std::string to_string();
protected:
esp_bt_uuid_t uuid_;
};
} // namespace esp32_ble
} // namespace esphome
#endif

View File

@@ -0,0 +1,114 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include <queue>
#include <mutex>
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gap_ble_api.h>
#include <esp_gatts_api.h>
#include <esp_gattc_api.h>
/*
* BLE events come in from a separate Task (thread) in the ESP32 stack. Rather
* than trying to deal wth various locking strategies, all incoming GAP and GATT
* events will simply be placed on a semaphore guarded queue. The next time the
* component runs loop(), these events are popped off the queue and handed at
* this safer time.
*/
namespace esphome {
namespace esp32_ble {
template<class T> class Queue {
public:
Queue() { m = xSemaphoreCreateMutex(); }
void push(T *element) {
if (element == nullptr)
return;
if (xSemaphoreTake(m, 5L / portTICK_PERIOD_MS)) {
q.push(element);
xSemaphoreGive(m);
}
}
T *pop() {
T *element = nullptr;
if (xSemaphoreTake(m, 5L / portTICK_PERIOD_MS)) {
if (!q.empty()) {
element = q.front();
q.pop();
}
xSemaphoreGive(m);
}
return element;
}
protected:
std::queue<T *> q;
SemaphoreHandle_t m;
};
// Received GAP and GATTC events are only queued, and get processed in the main loop().
// This class stores each event in a single type.
class BLEEvent {
public:
BLEEvent(esp_gap_ble_cb_event_t e, esp_ble_gap_cb_param_t *p) {
this->event_.gap.gap_event = e;
memcpy(&this->event_.gap.gap_param, p, sizeof(esp_ble_gap_cb_param_t));
this->type_ = GAP;
};
BLEEvent(esp_gattc_cb_event_t e, esp_gatt_if_t i, esp_ble_gattc_cb_param_t *p) {
this->event_.gattc.gattc_event = e;
this->event_.gattc.gattc_if = i;
memcpy(&this->event_.gattc.gattc_param, p, sizeof(esp_ble_gattc_cb_param_t));
// Need to also make a copy of notify event data.
if (e == ESP_GATTC_NOTIFY_EVT) {
memcpy(this->event_.gattc.notify_data, p->notify.value, p->notify.value_len);
this->event_.gattc.gattc_param.notify.value = this->event_.gattc.notify_data;
}
this->type_ = GATTC;
};
BLEEvent(esp_gatts_cb_event_t e, esp_gatt_if_t i, esp_ble_gatts_cb_param_t *p) {
this->event_.gatts.gatts_event = e;
this->event_.gatts.gatts_if = i;
memcpy(&this->event_.gatts.gatts_param, p, sizeof(esp_ble_gatts_cb_param_t));
this->type_ = GATTS;
};
union {
struct gap_event {
esp_gap_ble_cb_event_t gap_event;
esp_ble_gap_cb_param_t gap_param;
} gap;
struct gattc_event {
esp_gattc_cb_event_t gattc_event;
esp_gatt_if_t gattc_if;
esp_ble_gattc_cb_param_t gattc_param;
uint8_t notify_data[64];
} gattc;
struct gatts_event {
esp_gatts_cb_event_t gatts_event;
esp_gatt_if_t gatts_if;
esp_ble_gatts_cb_param_t gatts_param;
} gatts;
} event_;
enum ble_event_t : uint8_t {
GAP,
GATTC,
GATTS,
} type_;
};
} // namespace esp32_ble
} // namespace esphome
#endif