ESP32 实例分析:\bluetooth\bluedroid\ble\gatt_server
参考:
frameworks\esp-idf-v4.4.2\examples\bluetooth\bluedroid\ble\gatt_server
1 简介
该实例展示如何在BLE模式下,建立一个GATT服务并添加对应attribute的过程。
新建2个应用profile,对应profile建立一个service,每个service建立characteritstic。
2 工程文件组成
sdkconfig.defaults : 为适应工程,需要额外打开的系统配置;
Kconfig.projbuild : 工程自定义的,系统配置选项;
gatts_demo.c : 实例代码文件;
3 文件详解
3.1 sdkconfig.defaults
CONFIG_BT_ENABLED=y * 打开蓝牙开关
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y * 只支持BLE模式
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n * 只支持传统蓝牙模式
CONFIG_BTDM_CTRL_MODE_BTDM=n * BLE+传统蓝牙 二合一模式
3.2 Kconfig.projbuild
menu “Example ‘GATT SERVER’ Config” * 配置顶层增加目录
config SET_RAW_ADV_DATA * 增加工程使用的配置项
bool “Use raw 。。。 data” * 配置项属性
help * 帮助和说明文字
3.3 gatts_demo.c
3.3.1 BLE 蓝牙初始化
ret = nvs_flash_init();
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ret = esp_bt_controller_init(&bt_cfg);
ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
ret = esp_bluedroid_init();
ret = esp_bluedroid_enable();
本部分代码基本,每个用到的蓝牙BLE功能的都一样。使用默认配置参数配置蓝牙。
3.3.1 GATT 实验代码
- 注册GATT相关的events处理函数
ret = esp_ble_gatts_register_callback(gatts_event_handler); - 注册GAP相关的events处理函数
ret = esp_ble_gap_register_callback(gap_event_handler); - 注册第一个GATT profile,ID = PROFILE_A_APP_ID = 0
ret = esp_ble_gatts_app_register(PROFILE_A_APP_ID); - 注册第二个GATT profile,ID = PROFILE_B_APP_ID = 1
ret = esp_ble_gatts_app_register(PROFILE_B_APP_ID); - 设置MTU长度为500
esp_err_t local_mtu_ret = esp_ble_gatt_set_local_mtu(500);
3.3.3 gatts_event_handler()
实验代码中调用
ret = esp_ble_gatts_app_register(PROFILE_A_APP_ID);
ret = esp_ble_gatts_app_register(PROFILE_B_APP_ID);
注册profile时,会触发ESP_GATTS_REG_EVT,同时2个参数被传递过来:
esp_gatt_status_t status;
uint16_t app_id;
该函数是注册的gatts相关event的入口函数。
/* If event is register event, store the gatts_if for each profile */
if (event == ESP_GATTS_REG_EVT) {
if (param->reg.status == ESP_GATT_OK) {
gl_profile_tab[param->reg.app_id].gatts_if = gatts_if;
} else {
ESP_LOGI(GATTS_TAG, "Reg app failed, app_id %04x, status %d\n",
param->reg.app_id,
param->reg.status);
return;
}
}
/* If the gatts_if equal to profile A, call profile A cb handler,
* so here call each profile's callback */
do {