esp32 gatt_server_service_table 创建多个service
时间: 2025-06-28 14:07:01 浏览: 18
### 创建多个GATT服务
在ESP32上创建BLE GATT服务器并支持多个服务可以通过调用特定API来实现。每个GATT服务由唯一的服务UUID标识,并可以包含一个或多个特征值(characteristics)[^1]。
为了创建带有多个服务的GATT服务器,需按照如下方式编写代码:
#### 初始化BLE环境
首先初始化BLE库,并设置设备名称以及角色为GATT服务器:
```c++
#include <Arduino.h>
#include <esp_bt.h>
#include <esp_gap_ble_api.h>
#include <esp_gatts_api.h>
#include <esp_bt_main.h>
// 定义BLE事件处理函数原型声明
void handleGapEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
void handleGattServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param);
// 设置BLE设备名和初始参数
#define DEVICE_NAME "ESP32-GATT-SERVER"
#define SERVICE_UUID_1 0x180A // 设备信息服务UUID示例
#define SERVICE_UUID_2 0x180F // 身体传感器位置服务UUID示例
extern "C" void app_main(void){
// 初始化NVS闪存分区
esp_err_t ret = nvs_flash_init();
// 注册GAP层回调函数
esp_ble_gap_register_callback(handleGapEvent);
}
```
#### 添加第一个GATT服务
通过`esp_ble_gatts_create_service()`方法注册新的GATT服务到GATT数据库中:
```c++
static uint16_t service_handle_1;
void addServiceOne(){
const esp_gatts_attr_db_t service_one[] ={
/* Service Declaration */
{
.attr_cmpl =
{
.uuid.len= ESP_UUID_LEN_16,
.uuid.uuid.uuid16 = PRIMARY_SERVICE_UUID,
.perm = ESP_GATT_PERM_READ,
.value_len = sizeof(uint16_t),
.value = &SERVICE_UUID_1,
}
},
// 特征定义...
};
esp_ble_gatts_create_service(gatts_if, (const esp_uuid_t *)&service_one[0].attr_cmpl.uuid.uuid.uuid16, ARRAY_SIZE(service_one));
}
// 处理服务创建完成后的响应
if(event == ESP_GATTS_CREATE_EVT && param->create.status == ESP_GATT_OK){
service_handle_1 = param->create.service_handle;
esp_ble_gatts_start_service(param->create.service_handle);
}
```
#### 添加第二个GATT服务
同样地,使用相同的方式添加另一个独立的服务实例至GATT表单内:
```c++
static uint16_t service_handle_2;
void addServiceTwo(){
const esp_gatts_attr_db_t service_two[]={
/* Service Declaration */
{
.attr_cmpl=
{
.uuid.len= ESP_UUID_LEN_16,
.uuid.uuid.uuid16 = PRIMARY_SERVICE_UUID,
.perm = ESP_GATT_PERM_READ,
.value_len = sizeof(uint16_t),
.value = &SERVICE_UUID_2,
}
},
// 更多特性定义...
};
esp_ble_gatts_create_service(gatts_if, (const esp_uuid_t *)&service_two[0].attr_cmpl.uuid.uuid.uuid16, ARRAY_SIZE(service_two));
}
// 同样处理该服务创建完成后启动它
if(event == ESP_GATTS_CREATE_EVT && param->create.status == ESP_GATT_OK){
service_handle_2 = param->create.service_handle;
esp_ble_gatts_start_service(param->create.service_handle);
}
```
上述过程展示了如何在一个ESP32应用程序里配置两个不同的GATT服务。需要注意的是,在实际应用开发过程中还需要考虑错误处理逻辑和服务间交互等问题。
阅读全文
相关推荐













