1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-10 23:32:23 +01:00

Move esp32_ble_server to its own component (#1898)

This commit is contained in:
Jesse Hills
2021-06-12 08:31:15 +12:00
committed by GitHub
parent eb24da7c82
commit 5a2cfa2798
24 changed files with 192 additions and 146 deletions

View File

@@ -0,0 +1,39 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_MODEL, ESP_PLATFORM_ESP32
from esphome.components import esp32_ble
AUTO_LOAD = ["esp32_ble"]
CODEOWNERS = ["@jesserockz"]
CONFLICTS_WITH = ["esp32_ble_tracker", "esp32_ble_beacon"]
ESP_PLATFORMS = [ESP_PLATFORM_ESP32]
CONF_MANUFACTURER = "manufacturer"
CONF_BLE_ID = "ble_id"
esp32_ble_server_ns = cg.esphome_ns.namespace("esp32_ble_server")
BLEServer = esp32_ble_server_ns.class_("BLEServer", cg.Component)
BLEServiceComponent = esp32_ble_server_ns.class_("BLEServiceComponent")
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(BLEServer),
cv.GenerateID(CONF_BLE_ID): cv.use_id(esp32_ble.ESP32BLE),
cv.Optional(CONF_MANUFACTURER, default="ESPHome"): cv.string,
cv.Optional(CONF_MODEL): cv.string,
}
).extend(cv.COMPONENT_SCHEMA)
async def to_code(config):
parent = await cg.get_variable(config[CONF_BLE_ID])
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
cg.add(var.set_manufacturer(config[CONF_MANUFACTURER]))
if CONF_MODEL in config:
cg.add(var.set_model(config[CONF_MODEL]))
cg.add_define("USE_ESP32_BLE_SERVER")
cg.add(parent.set_server(var))

View File

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

View File

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

View File

@@ -0,0 +1,18 @@
#include "ble_2902.h"
#include "esphome/components/esp32_ble/ble_uuid.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble_server {
BLE2902::BLE2902() : BLEDescriptor(esp32_ble::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_server
} // namespace esphome
#endif

View File

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

View File

@@ -0,0 +1,306 @@
#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_server {
static const char *const TAG = "esp32_ble_server.characteristic";
BLECharacteristic::BLECharacteristic(const ESPBTUUID uuid, uint32_t properties) : uuid_(uuid) {
this->set_value_lock_ = xSemaphoreCreateBinary();
xSemaphoreGive(this->set_value_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(const std::string &value) {
this->set_value(std::vector<uint8_t>(value.begin(), value.end()));
}
void BLECharacteristic::set_value(const 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); }
void BLECharacteristic::do_create(BLEService *service) {
this->service_ = service;
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_RSP_BY_APP;
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;
}
this->state_ = CREATING;
}
bool BLECharacteristic::is_created() {
if (this->state_ == CREATED)
return true;
if (this->state_ != CREATING_DEPENDENTS)
return false;
bool created = true;
for (auto *descriptor : this->descriptors_) {
created &= descriptor->is_created();
}
if (created)
this->state_ = CREATED;
return this->state_ == CREATED;
}
bool BLECharacteristic::is_failed() {
if (this->state_ == FAILED)
return true;
bool failed = false;
for (auto *descriptor : this->descriptors_) {
failed |= descriptor->is_failed();
}
if (failed)
this->state_ = FAILED;
return this->state_ == FAILED;
}
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;
for (auto *descriptor : this->descriptors_) {
descriptor->do_create(this);
}
this->state_ = CREATING_DEPENDENTS;
}
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_server
} // namespace esphome
#endif

View File

@@ -0,0 +1,97 @@
#pragma once
#include "ble_descriptor.h"
#include "esphome/components/esp32_ble/ble_uuid.h"
#include <vector>
#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_server {
using namespace esp32_ble;
class BLEService;
class BLECharacteristic {
public:
BLECharacteristic(const ESPBTUUID uuid, uint32_t properties);
void set_value(const uint8_t *data, size_t length);
void set_value(std::vector<uint8_t> value);
void set_value(const 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);
void 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(const std::vector<uint8_t> &)> &&func) { this->on_write_ = std::move(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;
bool is_created();
bool is_failed();
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_;
std::vector<BLEDescriptor *> descriptors_;
std::function<void(const std::vector<uint8_t> &)> on_write_;
esp_gatt_perm_t permissions_ = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
enum State : uint8_t {
FAILED = 0x00,
INIT,
CREATING,
CREATING_DEPENDENTS,
CREATED,
} state_{INIT};
};
} // namespace esp32_ble_server
} // namespace esphome
#endif

View File

@@ -0,0 +1,77 @@
#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_server {
static const char *const TAG = "esp32_ble_server.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);
}
BLEDescriptor::~BLEDescriptor() { free(this->value_.attr_value); }
void BLEDescriptor::do_create(BLECharacteristic *characteristic) {
this->characteristic_ = characteristic;
esp_attr_control_t control;
control.auto_rsp = ESP_GATT_AUTO_RSP;
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);
this->state_ = FAILED;
return;
}
this->state_ = CREATING;
}
void BLEDescriptor::set_value(const std::string &value) { this->set_value((uint8_t *) value.data(), value.length()); }
void BLEDescriptor::set_value(const 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;
this->state_ = CREATED;
}
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_server
} // namespace esphome
#endif

View File

@@ -0,0 +1,51 @@
#pragma once
#include "esphome/components/esp32_ble/ble_uuid.h"
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gatt_defs.h>
#include <esp_gatts_api.h>
namespace esphome {
namespace esp32_ble_server {
using namespace esp32_ble;
class BLECharacteristic;
class BLEDescriptor {
public:
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len = 100);
virtual ~BLEDescriptor();
void do_create(BLECharacteristic *characteristic);
void set_value(const std::string &value);
void set_value(const 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);
bool is_created() { return this->state_ == CREATED; }
bool is_failed() { return this->state_ == FAILED; }
protected:
BLECharacteristic *characteristic_{nullptr};
ESPBTUUID uuid_;
uint16_t handle_{0xFFFF};
esp_attr_value_t value_;
esp_gatt_perm_t permissions_ = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
enum State : uint8_t {
FAILED = 0x00,
INIT,
CREATING,
CREATED,
} state_{INIT};
};
} // namespace esp32_ble_server
} // namespace esphome
#endif

View File

@@ -0,0 +1,168 @@
#include "ble_server.h"
#include "esphome/components/esp32_ble/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_server {
static const char *const 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;
}
void BLEServer::loop() {
switch (this->state_) {
case RUNNING:
return;
case INIT: {
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;
}
this->state_ = REGISTERING;
break;
}
case REGISTERING: {
if (this->registered_) {
this->device_information_service_ = this->create_service(DEVICE_INFORMATION_SERVICE_UUID);
this->create_device_characteristics_();
this->state_ = STARTING_SERVICE;
}
break;
}
case STARTING_SERVICE: {
if (!this->device_information_service_->is_created()) {
break;
}
if (this->device_information_service_->is_running()) {
this->state_ = RUNNING;
this->can_proceed_ = true;
ESP_LOGD(TAG, "BLE server setup successfully");
} else if (!this->device_information_service_->is_starting()) {
this->device_information_service_->start();
}
break;
}
}
}
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) {
esp32_ble::global_ble->get_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_--;
esp32_ble::global_ble->get_advertising()->start();
for (auto *component : this->service_components_) {
component->on_client_disconnect();
}
break;
}
case ESP_GATTS_REG_EVT: {
this->gatts_if_ = gatts_if;
this->registered_ = true;
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_server
} // namespace esphome
#endif

View File

@@ -0,0 +1,95 @@
#pragma once
#include "ble_service.h"
#include "ble_characteristic.h"
#include "esphome/components/esp32_ble/ble_advertising.h"
#include "esphome/components/esp32_ble/ble_uuid.h"
#include "esphome/components/esp32_ble/queue.h"
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/preferences.h"
#include <map>
#ifdef ARDUINO_ARCH_ESP32
#include <esp_gap_ble_api.h>
#include <esp_gatts_api.h>
namespace esphome {
namespace esp32_ble_server {
using namespace esp32_ble;
class BLEServiceComponent {
public:
virtual void on_client_connect(){};
virtual void on_client_disconnect(){};
virtual void start();
virtual void stop();
};
class BLEServer : public Component {
public:
void setup() override;
void loop() override;
void dump_config() override;
float get_setup_priority() const override;
bool can_proceed() override { return this->can_proceed_; }
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_; }
const std::map<uint16_t, void *> &get_clients() { return this->clients_; }
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 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; }
bool can_proceed_{false};
std::string manufacturer_;
optional<std::string> model_;
esp_gatt_if_t gatts_if_{0};
bool registered_{false};
uint32_t connected_clients_{0};
std::map<uint16_t, void *> clients_;
std::vector<BLEService *> services_;
BLEService *device_information_service_;
std::vector<BLEServiceComponent *> service_components_;
enum State : uint8_t {
INIT = 0x00,
REGISTERING,
STARTING_SERVICE,
RUNNING,
} state_{INIT};
};
extern BLEServer *global_ble_server;
} // namespace esp32_ble_server
} // namespace esphome
#endif

View File

@@ -0,0 +1,142 @@
#include "ble_service.h"
#include "ble_server.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace esp32_ble_server {
static const char *const TAG = "esp32_ble_server.service";
BLEService::BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id)
: uuid_(uuid), num_handles_(num_handles), inst_id_(inst_id) {}
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;
}
void BLEService::do_create(BLEServer *server) {
this->server_ = server;
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);
this->init_state_ = FAILED;
return;
}
this->init_state_ = CREATING;
}
bool BLEService::do_create_characteristics_() {
if (this->created_characteristic_count_ >= this->characteristics_.size() &&
(this->last_created_characteristic_ == nullptr || this->last_created_characteristic_->is_created()))
return false; // Signifies there are no characteristics, or they are all finished being created.
if (this->last_created_characteristic_ != nullptr && !this->last_created_characteristic_->is_created())
return true; // Signifies that the previous characteristic is still being created.
auto *characteristic = this->characteristics_[this->created_characteristic_count_++];
this->last_created_characteristic_ = characteristic;
characteristic->do_create(this);
return true;
}
void BLEService::start() {
if (this->do_create_characteristics_())
return;
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;
}
this->running_state_ = STARTING;
}
void BLEService::stop() {
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;
}
this->running_state_ = STOPPING;
}
bool BLEService::is_created() { return this->init_state_ == CREATED; }
bool BLEService::is_failed() {
if (this->init_state_ == FAILED)
return true;
bool failed = false;
for (auto *characteristic : this->characteristics_)
failed |= characteristic->is_failed();
if (failed)
this->init_state_ = FAILED;
return this->init_state_ == FAILED;
}
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;
this->init_state_ = CREATED;
}
break;
}
case ESP_GATTS_START_EVT: {
if (param->start.service_handle == this->handle_) {
this->running_state_ = RUNNING;
}
break;
}
case ESP_GATTS_STOP_EVT: {
if (param->start.service_handle == this->handle_) {
this->running_state_ = STOPPED;
}
break;
}
default:
break;
}
for (auto *characteristic : this->characteristics_) {
characteristic->gatts_event_handler(event, gatts_if, param);
}
}
} // namespace esp32_ble_server
} // namespace esphome
#endif

View File

@@ -0,0 +1,81 @@
#pragma once
#include "ble_characteristic.h"
#include "esphome/components/esp32_ble/ble_uuid.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_server {
class BLEServer;
using namespace esp32_ble;
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_; }
void 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();
bool is_created();
bool is_failed();
bool is_running() { return this->running_state_ == RUNNING; }
bool is_starting() { return this->running_state_ == STARTING; }
protected:
std::vector<BLECharacteristic *> characteristics_;
BLECharacteristic *last_created_characteristic_{nullptr};
uint32_t created_characteristic_count_{0};
BLEServer *server_;
ESPBTUUID uuid_;
uint16_t num_handles_;
uint16_t handle_{0xFFFF};
uint8_t inst_id_;
bool do_create_characteristics_();
enum InitState : uint8_t {
FAILED = 0x00,
INIT,
CREATING,
CREATING_DEPENDENTS,
CREATED,
} init_state_{INIT};
enum RunningState : uint8_t {
STARTING,
RUNNING,
STOPPING,
STOPPED,
} running_state_{STOPPED};
};
} // namespace esp32_ble_server
} // namespace esphome
#endif