GATTC的多设备连接

大家好。我在做ble的gattc多设备连接代码编写时出现了一些问题。当client和server连接后,terminal端并没有显示读取的数据,似乎回调函数并没有正常运行。请各位老哥帮忙看看。


#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include "nvs.h"
#include "nvs_flash.h"

#include "esp_bt.h"
#include "esp_gap_ble_api.h"
#include "esp_gattc_api.h"
#include "esp_gatt_defs.h"
#include "esp_bt_main.h"
#include "esp_gatt_common_api.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"

#include "esp_system.h"
#include "esp_bt_device.h"
#include "freertos/task.h"


#define GATTC_INCLUDED 
#define CONFIG_FREERTOS_HZ 100

#define GATTC_TAG "GATTC_MULTIPLE_DEMO"
#define REMOTE_SERVICE_UUID        0x00FF
#define REMOTE_NOTIFY_CHAR_UUID    0xFF01

/* register three profiles, each profile corresponds to one connection,
   which makes it easy to handle each connection event */
#define PROFILE_NUM 3
#define PROFILE_A_APP_ID 0
#define PROFILE_B_APP_ID 1
#define PROFILE_C_APP_ID 2
#define INVALID_HANDLE   0

//定义sensor功能
#define SUPPORT_SENSOR0
//枚举数据库
#ifdef SUPPORT_SENSOR0
enum{
    SPP_IDX_SVC,

    SPP_IDX_SPP_DATA_RECV_VAL,

    SPP_IDX_SPP_DATA_NTY_VAL,
    SPP_IDX_SPP_DATA_NTF_CFG,

    SPP_IDX_SPP_COMMAND_VAL,

    SPP_IDX_SPP_STATUS_VAL,
    SPP_IDX_SPP_STATUS_CFG,

//特征属性表下标
    TEST_0_VAL,
    TEST_0_CFG,            

    SPP_IDX_NB0,
};
#endif

#ifdef SUPPORT_SENSOR1
enum{
    SPP_IDX_SVC,

    SPP_IDX_SPP_DATA_RECV_VAL,

    SPP_IDX_SPP_DATA_NTY_VAL,
    SPP_IDX_SPP_DATA_NTF_CFG,

    SPP_IDX_SPP_COMMAND_VAL,

    SPP_IDX_SPP_STATUS_VAL,
    SPP_IDX_SPP_STATUS_CFG,

//特征属性表下标
    TEST_1_VAL,
    TEST_1_CFG,            

    SPP_IDX_NB1,
};
#endif

#ifdef SUPPORT_SENSOR2
enum{
    SPP_IDX_SVC,

    SPP_IDX_SPP_DATA_RECV_VAL,

    SPP_IDX_SPP_DATA_NTY_VAL,
    SPP_IDX_SPP_DATA_NTF_CFG,

    SPP_IDX_SPP_COMMAND_VAL,

    SPP_IDX_SPP_STATUS_VAL,
    SPP_IDX_SPP_STATUS_CFG,

//特征属性表下标
    TEST_2_VAL,
    TEST_2_CFG,            

    SPP_IDX_NB2,
};
#endif

#ifdef SUPPORT_SENSOR0
uint8_t s0_value;        
#endif

#ifdef SUPPORT_SENSOR1
uint8_t s1_value;        
#endif

#ifdef SUPPORT_SENSOR2
uint8_t s2_value;        
#endif

/* Declare static functions */
static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
static void gattc_profile_a_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
static void gattc_profile_b_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
static void gattc_profile_c_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);

static esp_bt_uuid_t remote_filter_service_uuid = {
    .len = ESP_UUID_LEN_16,
    .uuid = {.uuid16 = REMOTE_SERVICE_UUID,},
};

static esp_bt_uuid_t remote_filter_char_uuid = {
    .len = ESP_UUID_LEN_16,
    .uuid = {.uuid16 = REMOTE_NOTIFY_CHAR_UUID,},
};

static esp_bt_uuid_t notify_descr_uuid = {
    .len = ESP_UUID_LEN_16,
    .uuid = {.uuid16 = ESP_GATT_UUID_CHAR_CLIENT_CONFIG,},
};

static bool conn_device_a   = false;
static bool conn_device_b   = false;
static bool conn_device_c   = false;

static bool get_service_a   = false;
static bool get_service_b   = false;
static bool get_service_c   = false;

static bool Isconnecting    = false;
static bool stop_scan_done  = false;

static esp_gattc_char_elem_t  *char_elem_result_a   = NULL;
static esp_gattc_descr_elem_t *descr_elem_result_a  = NULL;
static esp_gattc_char_elem_t  *char_elem_result_b   = NULL;
static esp_gattc_descr_elem_t *descr_elem_result_b  = NULL;
static esp_gattc_char_elem_t  *char_elem_result_c   = NULL;
static esp_gattc_descr_elem_t *descr_elem_result_c  = NULL;

static const char remote_device_name[3][20] = {"ESP_GATTS_DEMO_a", "ESP_GATTS_DEMO_b", "ESP_GATTS_DEMO_c"};

//................................................................
#ifdef SUPPORT_SENSOR0
static uint16_t count0 = SPP_IDX_NB0;
static esp_gattc_db_elem_t *db0 = NULL;
#endif
#ifdef SUPPORT_SENSOR1
static uint16_t count1 = SPP_IDX_NB1;
static esp_gattc_db_elem_t *db1 = NULL;
#endif
#ifdef SUPPORT_SENSOR2
static uint16_t count2 = SPP_IDX_NB2;
static esp_gattc_db_elem_t *db2 = NULL;
#endif

static esp_ble_scan_params_t ble_scan_params = {
    .scan_type              = BLE_SCAN_TYPE_ACTIVE,
    .own_addr_type          = BLE_ADDR_TYPE_PUBLIC,
    .scan_filter_policy     = BLE_SCAN_FILTER_ALLOW_ALL,
    .scan_interval          = 0x50,
    .scan_window            = 0x30,
    .scan_duplicate         = BLE_SCAN_DUPLICATE_DISABLE
};

struct gattc_profile_inst {
    esp_gattc_cb_t gattc_cb;
    uint16_t gattc_if;
    uint16_t app_id;
    uint16_t conn_id;
    uint16_t service_start_handle;
    uint16_t service_end_handle;
    uint16_t char_handle;
    esp_bd_addr_t remote_bda;
};

/* One gatt-based profile one app_id and one gattc_if, this array will store the gattc_if returned by ESP_GATTS_REG_EVT */
static struct gattc_profile_inst gl_profile_tab[PROFILE_NUM] = {
    [PROFILE_A_APP_ID] = {
        .gattc_cb = gattc_profile_a_event_handler,
        .gattc_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
    [PROFILE_B_APP_ID] = {
        .gattc_cb = gattc_profile_b_event_handler,
        .gattc_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
    [PROFILE_C_APP_ID] = {
        .gattc_cb = gattc_profile_c_event_handler,
        .gattc_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },

};

static void start_scan(void)
{
    stop_scan_done = false;
    Isconnecting = false;
    uint32_t duration = 30;
    esp_ble_gap_start_scanning(duration);
}
static void gattc_profile_a_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{

    esp_ble_gattc_cb_param_t *p_data = (esp_ble_gattc_cb_param_t *)param;

    switch (event) {
    case ESP_GATTC_REG_EVT:
        ESP_LOGI(GATTC_TAG, "REG_EVT");
        esp_err_t scan_ret = esp_ble_gap_set_scan_params(&ble_scan_params);
        if (scan_ret){
            ESP_LOGE(GATTC_TAG, "set scan params error, error code = %x", scan_ret);
        }
        break;
    /* one device connect successfully, all profiles callback function will get the ESP_GATTC_CONNECT_EVT,
     so must compare the mac address to check which device is connected, so it is a good choice to use ESP_GATTC_OPEN_EVT. */
    case ESP_GATTC_CONNECT_EVT:
        break;
    case ESP_GATTC_OPEN_EVT:
        if (p_data->open.status != ESP_GATT_OK){
            //open failed, ignore the first device, connect the second device
            ESP_LOGE(GATTC_TAG, "connect device failed, status %d", p_data->open.status);
            conn_device_a = false;
            //start_scan();
            break;
        }
        //................................................................
        conn_device_a = true;
        printf("ESP_GATTC_CONNECT_EVT is running\r\n");
        memcpy(gl_profile_tab[PROFILE_A_APP_ID].remote_bda, p_data->open.remote_bda, 6);
        gl_profile_tab[PROFILE_A_APP_ID].conn_id = p_data->open.conn_id;
        ESP_LOGI(GATTC_TAG, "ESP_GATTC_OPEN_EVT conn_id %d, if %d, status %d, mtu %d", p_data->open.conn_id, gattc_if, p_data->open.status, p_data->open.mtu);
        ESP_LOGI(GATTC_TAG, "REMOTE BDA:");
        esp_log_buffer_hex(GATTC_TAG, p_data->open.remote_bda, sizeof(esp_bd_addr_t));
        esp_err_t mtu_ret = esp_ble_gattc_send_mtu_req (gattc_if, p_data->open.conn_id);
        if (mtu_ret){
            ESP_LOGE(GATTC_TAG, "config MTU error, error code = %x", mtu_ret);
        }
        break;
//..........................................................................................
    case ESP_GATTC_CFG_MTU_EVT:
        if (param->cfg_mtu.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG,"Config mtu failed");
        }
        ESP_LOGI(GATTC_TAG, "Status %d, MTU %d, conn_id %d", param->cfg_mtu.status, param->cfg_mtu.mtu, param->cfg_mtu.conn_id);
        esp_ble_gattc_search_service(gattc_if, param->cfg_mtu.conn_id, &remote_filter_service_uuid);

        db0 = (esp_gattc_db_elem_t *)malloc(count0*sizeof(esp_gattc_db_elem_t));
        if(db0 == NULL){
            ESP_LOGE(GATTC_TAG,"%s:malloc db0 falied\n",__func__);
            break;
        }
        if(esp_ble_gattc_get_db(gattc_if, param->cfg_mtu.conn_id, p_data->search_res.start_handle, p_data->search_res.end_handle, db0, &count0) != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG,"%s:get db0 falied\n",__func__);
            break;
        }
        
        
        
        break;
    case ESP_GATTC_SEARCH_RES_EVT: {
        ESP_LOGI(GATTC_TAG, "SEARCH RES: conn_id = %x is primary service %d", p_data->search_res.conn_id, p_data->search_res.is_primary);
        ESP_LOGI(GATTC_TAG, "start handle %d end handle %d current handle value %d", p_data->search_res.start_handle, p_data->search_res.end_handle, p_data->search_res.srvc_id.inst_id);
        if (p_data->search_res.srvc_id.uuid.len == ESP_UUID_LEN_16 && p_data->search_res.srvc_id.uuid.uuid.uuid16 == REMOTE_SERVICE_UUID) {
            ESP_LOGI(GATTC_TAG, "UUID16: %x", p_data->search_res.srvc_id.uuid.uuid.uuid16);
            get_service_a = true;
            gl_profile_tab[PROFILE_A_APP_ID].service_start_handle = p_data->search_res.start_handle;
            gl_profile_tab[PROFILE_A_APP_ID].service_end_handle = p_data->search_res.end_handle;
        }
        break;
    }
    case ESP_GATTC_SEARCH_CMPL_EVT:
        if (p_data->search_cmpl.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "search service failed, error status = %x", p_data->search_cmpl.status);
            break;
        }
        if (get_service_a){
            uint16_t count = 0;
            esp_gatt_status_t status = esp_ble_gattc_get_attr_count( gattc_if,
                                                                     p_data->search_cmpl.conn_id,
                                                                     ESP_GATT_DB_CHARACTERISTIC,
                                                                     gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
                                                                     gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
                                                                     INVALID_HANDLE,
                                                                     &count);
            if (status != ESP_GATT_OK){
                ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_attr_count error");
            }
            if (count > 0) {
                char_elem_result_a = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * count);
                if (!char_elem_result_a){
                    ESP_LOGE(GATTC_TAG, "gattc no mem");
                }else {
                    status = esp_ble_gattc_get_char_by_uuid( gattc_if,
                                                             p_data->search_cmpl.conn_id,
                                                             gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
                                                             gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
                                                             remote_filter_char_uuid,
                                                             char_elem_result_a,
                                                             &count);
                    if (status != ESP_GATT_OK){
                        ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_char_by_uuid error");
                    }

                    /*  Every service have only one char in our 'ESP_GATTS_DEMO' demo, so we used first 'char_elem_result' */
                    if (count > 0 && (char_elem_result_a[0].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY)){
                        gl_profile_tab[PROFILE_A_APP_ID].char_handle = char_elem_result_a[0].char_handle;
                        esp_ble_gattc_register_for_notify (gattc_if, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, char_elem_result_a[0].char_handle);
                    }
                }
                /* free char_elem_result */
                free(char_elem_result_a);
            }else {
                ESP_LOGE(GATTC_TAG, "no char found");
            }
        }
        break;
    case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
        if (p_data->reg_for_notify.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "reg notify failed, error status =%x", p_data->reg_for_notify.status);
            break;
        }
        uint16_t count = 0;
        uint16_t notify_en = 1;
        esp_gatt_status_t ret_status = esp_ble_gattc_get_attr_count( gattc_if,
                                                                     gl_profile_tab[PROFILE_A_APP_ID].conn_id,
                                                                     ESP_GATT_DB_DESCRIPTOR,
                                                                     gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
                                                                     gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
                                                                     gl_profile_tab[PROFILE_A_APP_ID].char_handle,
                                                                     &count);
        if (ret_status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_attr_count error");
        }
        if (count > 0){
            descr_elem_result_a = (esp_gattc_descr_elem_t *)malloc(sizeof(esp_gattc_descr_elem_t) * count);
            if (!descr_elem_result_a){
                ESP_LOGE(GATTC_TAG, "malloc error, gattc no mem");
            }else{
                ret_status = esp_ble_gattc_get_descr_by_char_handle( gattc_if,
                                                                     gl_profile_tab[PROFILE_A_APP_ID].conn_id,
                                                                     p_data->reg_for_notify.handle,
                                                                     notify_descr_uuid,
                                                                     descr_elem_result_a,
                                                                     &count);
                if (ret_status != ESP_GATT_OK){
                    ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_descr_by_char_handle error");
                }

                /* Every char has only one descriptor in our 'ESP_GATTS_DEMO' demo, so we used first 'descr_elem_result' */
                if (count > 0 && descr_elem_result_a[0].uuid.len == ESP_UUID_LEN_16 && descr_elem_result_a[0].uuid.uuid.uuid16 == ESP_GATT_UUID_CHAR_CLIENT_CONFIG){
                    ret_status = esp_ble_gattc_write_char_descr( gattc_if,
                                                                 gl_profile_tab[PROFILE_A_APP_ID].conn_id,
                                                                 descr_elem_result_a[0].handle,
                                                                 sizeof(notify_en),
                                                                 (uint8_t *)&notify_en,
                                                                 ESP_GATT_WRITE_TYPE_RSP,
                                                                 ESP_GATT_AUTH_REQ_NONE);
                }

                if (ret_status != ESP_GATT_OK){
                    ESP_LOGE(GATTC_TAG, "esp_ble_gattc_write_char_descr error");
                }

                /* free descr_elem_result */
                free(descr_elem_result_a);
            }
        }
        else{
            ESP_LOGE(GATTC_TAG, "decsr not found");
        }
        break;
    }
    case ESP_GATTC_NOTIFY_EVT:
        ESP_LOGI(GATTC_TAG, "ESP_GATTC_NOTIFY_EVT, Receive notify value:");
        esp_log_buffer_hex(GATTC_TAG, p_data->notify.value, p_data->notify.value_len);
        break;
    case ESP_GATTC_WRITE_DESCR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "write descr failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGI(GATTC_TAG, "write descr success");
        uint8_t write_char_data[35];
        for (int i = 0; i < sizeof(write_char_data); ++i)
        {
            write_char_data[i] = i % 256;
        }
        esp_ble_gattc_write_char( gattc_if,
                                  gl_profile_tab[PROFILE_A_APP_ID].conn_id,
                                  gl_profile_tab[PROFILE_A_APP_ID].char_handle,
                                  sizeof(write_char_data),
                                  write_char_data,
                                  ESP_GATT_WRITE_TYPE_RSP,
                                  ESP_GATT_AUTH_REQ_NONE);
        break;
    case ESP_GATTC_WRITE_CHAR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "write char failed, error status = %x", p_data->write.status);
        }else{
            ESP_LOGI(GATTC_TAG, "write char success");
        }
        start_scan();
        break;

//.......................................................................................
     case ESP_GATTC_READ_CHAR_EVT:
          ESP_LOGI(GATTC_TAG,"ESP_GATTC_READ_CHAR_EVT\n");
//.........................................................................................................................................................
#ifdef SUPPORT_SENSOR0
        //判断是否读取成功
        if(p_data->read.status == ESP_GATT_OK)
        {
            //判断属性句柄句柄
            if(p_data->read.handle == (db0+TEST_0_VAL)->attribute_handle)
            {
                printf("sensor0 value = %d,len = %d\r\n",*p_data->read.value,p_data->read.value_len);
                //记录通知状态
                memcpy(&s0_value,p_data->read.value,p_data->read.value_len);
            }
            
        }
        else
            printf("read faild, status = %d\r\n",p_data->read.status);
            
#endif

    case ESP_GATTC_SRVC_CHG_EVT: {
        esp_bd_addr_t bda;
        memcpy(bda, p_data->srvc_chg.remote_bda, sizeof(esp_bd_addr_t));
        ESP_LOGI(GATTC_TAG, "ESP_GATTC_SRVC_CHG_EVT, bd_addr:%08x%04x",(bda[0] << 24) + (bda[1] << 16) + (bda[2] << 8) + bda[3],
                 (bda[4] << 8) + bda[5]);
        break;
    }
    case ESP_GATTC_DISCONNECT_EVT:
        //Start scanning again
        start_scan();
        if (memcmp(p_data->disconnect.remote_bda, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, 6) == 0){
            ESP_LOGI(GATTC_TAG, "device a disconnect");
            conn_device_a = false;
            get_service_a = false;
        }
        break;
    default:
        break;
    }
}

static void gattc_profile_b_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{
  
}

static void gattc_profile_c_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{
   
}

static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
    uint8_t *adv_name = NULL;
    uint8_t adv_name_len = 0;
    switch (event) {
    case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT:
         ESP_LOGI(GATTC_TAG, "update connection params status = %d, min_int = %d, max_int = %d,conn_int = %d,latency = %d, timeout = %d",
                  param->update_conn_params.status,
                  param->update_conn_params.min_int,
                  param->update_conn_params.max_int,
                  param->update_conn_params.conn_int,
                  param->update_conn_params.latency,
                  param->update_conn_params.timeout);
        break;
    case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: {
        //the unit of the duration is second
        uint32_t duration = 30;
        esp_ble_gap_start_scanning(duration);
        break;
    }
    case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
        //scan start complete event to indicate scan start successfully or failed
        if (param->scan_start_cmpl.status == ESP_BT_STATUS_SUCCESS) {
            ESP_LOGI(GATTC_TAG, "Scan start success");
        }else{
            ESP_LOGE(GATTC_TAG, "Scan start failed");
        }
        break;
    case ESP_GAP_BLE_SCAN_RESULT_EVT: {
        esp_ble_gap_cb_param_t *scan_result = (esp_ble_gap_cb_param_t *)param;
        switch (scan_result->scan_rst.search_evt) {
        case ESP_GAP_SEARCH_INQ_RES_EVT:
            esp_log_buffer_hex(GATTC_TAG, scan_result->scan_rst.bda, 6);
            ESP_LOGI(GATTC_TAG, "Searched Adv Data Len %d, Scan Response Len %d", scan_result->scan_rst.adv_data_len, scan_result->scan_rst.scan_rsp_len);
            adv_name = esp_ble_resolve_adv_data(scan_result->scan_rst.ble_adv,
                                                ESP_BLE_AD_TYPE_NAME_CMPL, &adv_name_len);
            ESP_LOGI(GATTC_TAG, "Searched Device Name Len %d", adv_name_len);
            esp_log_buffer_char(GATTC_TAG, adv_name, adv_name_len);
            ESP_LOGI(GATTC_TAG, "\n");
            if (Isconnecting){
                break;
            }
            if (conn_device_a && conn_device_b && conn_device_c && !stop_scan_done){
                stop_scan_done = true;
                esp_ble_gap_stop_scanning();
                ESP_LOGI(GATTC_TAG, "all devices are connected");
                break;
            }
            if (adv_name != NULL) {

                if (strlen(remote_device_name[0]) == adv_name_len && strncmp((char *)adv_name, remote_device_name[0], adv_name_len) == 0) {
                    if (conn_device_a == false) {
                        conn_device_a = true;
                        ESP_LOGI(GATTC_TAG, "Searched device %s", remote_device_name[0]);
                        esp_ble_gap_stop_scanning();
                        esp_ble_gattc_open(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, scan_result->scan_rst.bda, scan_result->scan_rst.ble_addr_type, true);
                        Isconnecting = true;
                    }
                    break;
                }
                else if (strlen(remote_device_name[1]) == adv_name_len && strncmp((char *)adv_name, remote_device_name[1], adv_name_len) == 0) {
                    if (conn_device_b == false) {
                        conn_device_b = true;
                        ESP_LOGI(GATTC_TAG, "Searched device %s", remote_device_name[1]);
                        esp_ble_gap_stop_scanning();
                        esp_ble_gattc_open(gl_profile_tab[PROFILE_B_APP_ID].gattc_if, scan_result->scan_rst.bda, scan_result->scan_rst.ble_addr_type, true);
                        Isconnecting = true;

                    }
                }
                else if (strlen(remote_device_name[2]) == adv_name_len && strncmp((char *)adv_name, remote_device_name[2], adv_name_len) == 0) {
                    if (conn_device_c == false) {
                        conn_device_c = true;
                        ESP_LOGI(GATTC_TAG, "Searched device %s", remote_device_name[2]);
                        esp_ble_gap_stop_scanning();
                        esp_ble_gattc_open(gl_profile_tab[PROFILE_C_APP_ID].gattc_if, scan_result->scan_rst.bda, scan_result->scan_rst.ble_addr_type, true);
                        Isconnecting = true;
                    }
                    break;
                }

            }
            break;
        case ESP_GAP_SEARCH_INQ_CMPL_EVT:
            break;
        default:
            break;
        }
        break;
    }

    case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
        if (param->scan_stop_cmpl.status != ESP_BT_STATUS_SUCCESS){
            ESP_LOGE(GATTC_TAG, "Scan stop failed");
            break;
        }
        ESP_LOGI(GATTC_TAG, "Stop scan successfully");

        break;

    case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT:
        if (param->adv_stop_cmpl.status != ESP_BT_STATUS_SUCCESS){
            ESP_LOGE(GATTC_TAG, "Adv stop failed");
            break;
        }
        ESP_LOGI(GATTC_TAG, "Stop adv successfully");
        break;

    default:
        break;
    }
}

//................................................................................
#ifdef SUPPORT_SENSOR0
//开启读取功能
void read_task_0(void * arg)
{
    for(;;) 
    {
        
        printf("TEST_0_VAL = %d\r\n",TEST_0_VAL);
        //判断连接状态、数据库、权限
        if((conn_device_a == true) && (db0 != NULL) && ((db0+TEST_0_VAL)->properties & ESP_GATT_CHAR_PROP_BIT_READ ))
        {
            //vTaskDelay(4000 / portTICK_PERIOD_MS);
            //读取特征值
            printf("all is ok");
            esp_ble_gattc_read_char(gl_profile_tab[0].gattc_if,gl_profile_tab[0].conn_id,(db0+TEST_0_VAL)->attribute_handle,ESP_GATT_AUTH_REQ_NONE);
        
        }
        printf("conn_device_a=%d\r\n",conn_device_a);
            
        printf("all is not ok\r\n");
        vTaskDelay(5000 / portTICK_PERIOD_MS);
        
    }

}
#endif

#ifdef SUPPORT_SENSOR1
//开启读取功能
void read_task_1(void * arg)
{
    for(;;) 
    {
        
        printf("TEST_1_VAL = %d\r\n",TEST_1_VAL);
        //判断连接状态、数据库、权限
        if((conn_device_b == true) && (db1 != NULL) && ((db1+TEST_1_VAL)->properties & ESP_GATT_CHAR_PROP_BIT_READ ))
        {
            //vTaskDelay(4000 / portTICK_PERIOD_MS);
            //读取LI特征值
            esp_ble_gattc_read_char(gl_profile_tab[1].gattc_if,gl_profile_tab[1].conn_id,(db1+TEST_1_VAL)->attribute_handle,ESP_GATT_AUTH_REQ_NONE);
        
        }
        
        vTaskDelay(5000 / portTICK_PERIOD_MS);
        
    }

}
#endif

#ifdef SUPPORT_SENSOR2
//开启读取功能
void read_task_2(void * arg)
{
    for(;;) 
    {
        
        printf("TEST_2_VAL = %d\r\n",TEST_2_VAL);
        //判断连接状态、数据库、权限
        if((conn_device_c == true) && (db3 != NULL) && ((db3+TEST_3_VAL)->properties & ESP_GATT_CHAR_PROP_BIT_READ ))
        {
            //vTaskDelay(4000 / portTICK_PERIOD_MS);
            //读取LI特征值
            esp_ble_gattc_read_char(gl_profile_tab[2].gattc_if,gl_profile_tab[2].conn_id,(db3+TEST_1_VAL)->attribute_handle,ESP_GATT_AUTH_REQ_NONE);
        
        }
        
        vTaskDelay(5000 / portTICK_PERIOD_MS);
        
    }

}
#endif
//....................................................................

void ble_client_appRegister(void)
{
   
//创建任务
#ifdef SUPPORT_SENSOR0
    xTaskCreate(read_task_0, "read_task_0", 2048, NULL, 10, NULL);
#endif

#ifdef SUPPORT_SENSOR1
    xTaskCreate(read_task_1, "read_task_1", 2048, NULL, 10, NULL);
#endif

#ifdef SUPPORT_SENSOR2
    xTaskCreate(read_task_2, "read_task_2", 2048, NULL, 10, NULL);
#endif
    
}


static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{
    //ESP_LOGI(GATTC_TAG, "EVT %d, gattc if %d, app_id %d", event, gattc_if, param->reg.app_id);

    /* If event is register event, store the gattc_if for each profile */
    if (event == ESP_GATTC_REG_EVT) {
        if (param->reg.status == ESP_GATT_OK) {
            gl_profile_tab[param->reg.app_id].gattc_if = gattc_if;
        } else {
            ESP_LOGI(GATTC_TAG, "Reg app failed, app_id %04x, status %d",
                    param->reg.app_id,
                    param->reg.status);
            return;
        }
    }

    /* If the gattc_if equal to profile A, call profile A cb handler,
     * so here call each profile's callback */
    do {
        int idx;
        for (idx = 0; idx < PROFILE_NUM; idx++) {
            if (gattc_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
                    gattc_if == gl_profile_tab[idx].gattc_if) {
                if (gl_profile_tab[idx].gattc_cb) {
                    gl_profile_tab[idx].gattc_cb(event, gattc_if, param);
                    ESP_LOGI(GATTC_TAG, "test test test");
                }
            }
        }
    } while (0);
}

void app_main(void)
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK( ret );

    ESP_ERROR_CHECK(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);
    if (ret) {
        ESP_LOGE(GATTC_TAG, "%s initialize controller failed: %s\n", __func__, esp_err_to_name(ret));
        return;
    }

    ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
    if (ret) {
        ESP_LOGE(GATTC_TAG, "%s enable controller failed: %s\n", __func__, esp_err_to_name(ret));
        return;
    }

    ret = esp_bluedroid_init();
    if (ret) {
        ESP_LOGE(GATTC_TAG, "%s init bluetooth failed: %s\n", __func__, esp_err_to_name(ret));
        return;
    }

    ret = esp_bluedroid_enable();
    if (ret) {
        ESP_LOGE(GATTC_TAG, "%s enable bluetooth failed: %s\n", __func__, esp_err_to_name(ret));
        return;
    }

    //register the  callback function to the gap module
    ret = esp_ble_gap_register_callback(esp_gap_cb);
    if (ret){
        ESP_LOGE(GATTC_TAG, "gap register error, error code = %x", ret);
        return;
    }

    //register the callback function to the gattc module
    ret = esp_ble_gattc_register_callback(esp_gattc_cb);
    if(ret){
        ESP_LOGE(GATTC_TAG, "gattc register error, error code = %x", ret);
        return;
    }

    ret = esp_ble_gattc_app_register(PROFILE_A_APP_ID);
    if (ret){
        ESP_LOGE(GATTC_TAG, "gattc app register error, error code = %x", ret);
        return;
    }

    ret = esp_ble_gattc_app_register(PROFILE_B_APP_ID);
    if (ret){
        ESP_LOGE(GATTC_TAG, "gattc app register error, error code = %x", ret);
        return;
    }

    ret = esp_ble_gattc_app_register(PROFILE_C_APP_ID);
    if (ret){
        ESP_LOGE(GATTC_TAG, "gattc app register error, error code = %x", ret);
        return;
    }
    ret = esp_ble_gatt_set_local_mtu(200);
    if (ret){
        ESP_LOGE(GATTC_TAG, "set local  MTU failed, error code = %x", ret);
    }
    ble_client_appRegister();

}


参考gpt:
结合自己分析给你如下建议:
发现了一个GATT Client Multi-connection Example Walkthrough,它是一个使用ESP32作为GATT客户端,同时连接三个不同的GATT服务端的示例。它详细介绍了初始化、扫描、连接、读写等步骤,并且提供了完整的代码和注释。
根据这个示例,我发现可能导致你的问题的原因有以下几个:
1.你没有正确设置GATT客户端的回调函数。你需要使用esp_ble_gattc_register_callback函数来注册一个回调函数,用来处理GATT客户端的事件,扫描结果、连接状态、读写操作等。你可以参考示例中的gattc_profile_event_handler函数来实现你自己的回调函数。
2.你没有正确打开GATT客户端的通知或者指示功能。如果你想要接收GATT服务端主动发送的数据,你需要使用esp_ble_gattc_write_char_descr函数来写入一个使能位到GATT服务端的Client Characteristic Configuration Descriptor(CCCD),用来开启通知或者指示功能。你可以参考示例中的write_char_descr函数来实现这个功能。
3.你没有正确处理GATT客户端的读写事件。如果你想要主动读取或者写入GATT服务端的数据,你需要使用esp_ble_gattc_read_char或者esp_ble_gattc_write_char函数来发起一个读写请求,并且在回调函数中处理相应的事件,如ESP_GATTC_READ_CHAR_EVT或者ESP_GATTC_WRITE_CHAR_EVT。你可以参考示例中的read_char和write_char函数来实现这个功能。

有的case好像没有break,你确认一下

【以下回答由 GPT 生成】

问题解决方法:

由于代码中涉及到很多细节和特殊的配置,我无法直接提供完整的解决方案。不过我可以给出一些常见的解决方法,帮助你识别并解决问题:

  1. 检查UUID和handle:确保远程服务UUID和通知特征UUID与目标设备的配置匹配。另外,检查句柄(handle)是否正确设置。

  2. 检查连接状态:在连接成功后,可以使用esp_ble_gattc_get_attr_count()esp_ble_gattc_get_all_char()函数来检查连接状态、获取特征数量和特征属性。

  3. 检查回调函数:回调函数 esp_ble_gattc_cb_t 可以作为参数传递给 esp_ble_gattc_app_register() 函数来注册GATTC的回调函数。确保回调函数已正确实现,并进行了适当的错误处理。

  4. 检查权限:某些情况下,可能存在权限问题,导致无法读取数据。在回调函数中,可以使用esp_ble_gattc_read_char()函数来请求读取特定特征的值。

  5. 检查其他问题:可能存在其他问题,例如连接断开、设备未响应等。可以使用 esp_ble_gattc_close()函数来关闭连接,然后尝试重新连接。

以上是一些建议,请尝试逐步排查并解决问题。如果需要更具体的帮助,请提供更多的代码细节和错误日志,以便我能够更好地帮助你解决问题。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

主要还是你这个代码中涉及多个变量和回调函数,以及一些UUID的定义。很容易出现问题,建议优化下代码

有的case好像没有break,你确认一下

你这代码不能再优化了吗?

首先,您需要确保您的设备成功连接到GATT服务器,并且已经对特定的GATT特征做出了读取请求。如果您的代码编写正确,而且连接和读取请求也没有问题,但是回调函数没有按照您的预期工作,那么您可以尝试以下几种方法:

  1. 检查回调函数的注册和声明是否正确。回调函数应该被正确地注册到您的代码中,并且在指定的特定事件触发时被调用。

  2. 检查您的设备和服务器之间的信号强度是否足够。如果信号强度很弱,那么设备可能无法及时接收到来自服务器的响应。

  3. 检查是否存在网络延迟或流量拥堵的问题。如果您的网络连接存在延迟或存在流量拥堵,那么您的设备可能无法接收到服务器发送的数据。

  4. 检查您的设备和服务器之间的数据传输协议是否完全匹配。如果您的设备和服务器之间的协议不匹配,那么您的设备可能无法正确地解析服务器发送的数据。

  5. 检查您的代码是否正确地处理来自回调函数的数据。如果您的代码不能正确地处理来自回调函数的数据,那么您的设备将无法读取服务器发送的数据。

希望以上建议对您有所帮助。如果问题依然存在,您可以提供更多详细信息,以便我们更好地了解您的问题,并为您提供更好的解决方案。

Android蓝牙源码分析——Gatt连接(一)
可以参考下


https://www.codenong.com/45773666/

确保回调函数已正确注册并正在接收数据。
检查读取操作是否正确。
确保数据显示逻辑正确。需要确保在读取到数据后正确地将其转换为字符串或字节数组,并使用适当的终端显示方式(如打印到控制台或显示在GUI界面上)。
检查设备是否正确连接。

回调函数检查一下,有没有问题

回调函数有点问题

多设备连接是指使用一台设备(例如手机、平板电脑或电脑)同时连接多个设备(例如蓝牙耳机、智能手表或无线音响)的功能。在当前的智能生活中,多设备连接已经成为了一种方便而实用的技术,可以为用户提供更加丰富的体验。下面将详细介绍多设备连接的相关内容。

一、多设备连接的实现方式

多设备连接通常通过蓝牙、Wi-Fi或NFC等方式实现。其中,蓝牙是最常见的连接方式。蓝牙连接的优点是耗电低、稳定性好,而且可以在较远距离内传输数据。Wi-Fi连接的优点是传输速度更快,可以支持更多的设备连接,但是相对来说耗电量更高。NFC连接的优点是连接速度非常快,但是只能支持两个设备之间的连接。

二、多设备连接的应用场景

  1. 音频设备

多设备连接最常见的应用场景是连接音频设备。例如,可以使用一台手机连接多个蓝牙耳机、无线音响或智能音箱,让多个人同时分享音乐或观看影片。

  1. 智能手表

智能手表可以与其他智能设备进行连接,例如连接手机可以接收短信、电话和社交媒体通知,还可以控制音乐播放、拍照等功能。

  1. 智能家居

多设备连接也可以用于智能家居系统中,例如连接多个智能灯泡、空调、电视和门锁等设备,可以通过智能手机或语音助手来控制这些设备,实现智能生活。

  1. 游戏控制器

多设备连接也可以用于游戏控制器中,例如连接多个游戏手柄、虚拟现实头盔或其他控制器,让多个人同时玩游戏或观看游戏内容。

三、多设备连接的优点

  1. 方便快捷

使用多设备连接可以避免频繁地更换设备,同时也可以快速连接多个设备。

  1. 增强使用体验

使用多设备连接可以实现多设备之间的互动和控制,增强用户的使用体验。

  1. 节省成本

使用一台设备连接多个设备可以节省成本,不需要购买多个设备来满足不同的需求。

四、多设备连接的注意事项

  1. 设备兼容性

多设备连接需要考虑设备的兼容性,不同的设备之间可能存在连接问题。

  1. 安全性

多设备连接需要考虑安全性,避免未经授权的设备连接,保护用户的个人信息和隐私。

  1. 能耗问题

多设备连接需要考虑设备的能耗问题,特别是在连接多个设备时,会对电池寿命造成影响。

综上所述,多设备连接是一种方便实用的技术,可以为用户带来更加丰富的体验。在使用多设备连接时需要注意设备兼容性、安全性和能耗问题等因素。