ESP32蓝牙主机nus服务

b9db3fcf722444b1a7c75fa414696dc8.png

宏定义是 一个数组 成员是1个 也就是1  0 我把全局的加进去

 

TX RX齐活了!

 

发送函数 不要额外的变量了 就是全局的 放进去!

91ec4d37ddf547c8b753425264d42380.png

 

代码

/*
 * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */



/****************************************************************************
*
* This demo showcases BLE GATT client. It can scan BLE devices and connect to one device.
* Run the gatt_server demo, the client demo will automatically connect to the gatt_server demo.
* Client demo will enable gatt_server's notify after connection. The two devices will then exchange
* data.
*
****************************************************************************/

#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include "esp_timer.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"

/***个性化***/
//typedef uint8_t esp_bd_addr_t[ESP_BD_ADDR_LEN];

char* stringMac(esp_bd_addr_t Arr)
{
    static char mac[13]={0};
    sprintf(mac,"%02X%02X%02X%02X%02X%02X",Arr[0],Arr[1],Arr[2],Arr[3],Arr[4],Arr[5]);
    return mac;
}
esp_timer_handle_t timer1;
volatile int jiucai=0;
volatile char timerworking=0;
volatile int hexdatacount=0;



#define HCI_TAG "KOSON"

long scancount =0;
long yescount =0;
long nocount =0;

int rxdatacount =0;
long rxdatanumber =0;
/***个性化***/
#define GATTC_TAG "GATTC_DEMO"
//#define REMOTE_SERVICE_UUID        0x00FF
#define REMOTE_SERVICE_UUID      {0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x01, 0x00, 0x40, 0x6E}
//#define REMOTE_NOTIFY_CHAR_UUID    0xFF01
#define REMOTE_NOTIFY_CHAR_UUID  {0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x03, 0x00, 0x40, 0x6E}
#define REMOTE_RX_CHAR_UUID      {0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x02, 0x00, 0x40, 0x6E}
 
#define PROFILE_NUM      1
#define PROFILE_A_APP_ID 0
#define INVALID_HANDLE   0

/*时间*/
char strftime_buf[64];
#include <time.h>
#include <sys/time.h>
//houyawei
void setTime(int sc, int mn, int hr, int dy, int mt, int yr) {
    // seconds, minute, hour, day, month, year $ microseconds(optional)
    // ie setTime(20, 34, 8, 1, 4, 2021) = 8:34:20 1/4/2021
    struct tm t = {0};        // Initalize to all 0's
    t.tm_year = yr - 1900;    // This is year-1900, so 121 = 2021
    t.tm_mon = mt ;
    t.tm_mday = dy;
    t.tm_hour = hr;
    t.tm_min = mn;
    t.tm_sec = sc;
    time_t timeSinceEpoch = mktime(&t);
    ESP_LOGE(HCI_TAG, "Setting time: %s", asctime(&t));
    struct timeval now = { .tv_sec = timeSinceEpoch };
    settimeofday(&now, NULL);
}
 

 
void showtime(void){    
    time_t now;
    struct tm timeinfo;
    time(&now);
    // Set timezone to China Standard Time
    //setenv("TZ", "CST-8", 1);
    //tzset();
 
    localtime_r(&now, &timeinfo);
    strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
    ESP_LOGI(GATTC_TAG, "The current date/time in Shanghai is: %s", strftime_buf);
ESP_LOGI(GATTC_TAG, "%d-%d-%d-[%d]-%d-%d-%d",(timeinfo.tm_year-100) ,\
timeinfo.tm_mon ,\
timeinfo.tm_mday ,\
timeinfo.tm_wday,\
timeinfo.tm_hour ,\
timeinfo.tm_min ,\
timeinfo.tm_sec );
}


static const char remote_device_name[] = "M_IZAR_ESP_TEST";//"M_IZAR";//"M_IZAR_ESP_TEST";// "M_IZAR_TEST";// "M_IZAR_ALVIN";//"ESP_GATTS_DEMO";
static bool connect    = false;
static bool get_server = false;
static esp_gattc_char_elem_t *char_elem_result   = NULL;
static esp_gattc_descr_elem_t *descr_elem_result = NULL;

/* 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_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_128,
    .uuid = {.uuid128 = REMOTE_SERVICE_UUID,},
};

static esp_bt_uuid_t remote_filter_char_uuid = {//remote_filter_char_uuid 关注 它 是不是也可以如法炮制把RX拿出来?
    .len = ESP_UUID_LEN_128,
    .uuid = {.uuid128 = REMOTE_NOTIFY_CHAR_UUID,},
};

static esp_bt_uuid_t remote_filter_char_uuid2 = {//remote_filter_char_uuid 关注 它 是不是也可以如法炮制把RX拿出来?
    .len = ESP_UUID_LEN_128,
    .uuid = {.uuid128 = REMOTE_RX_CHAR_UUID,},
};


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

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

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;//RX需要使能的
    uint16_t char_handle2;//增加一个作为TX
    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_event_handler,
        .gattc_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
};

/*KOSON*/


void  ESP_BLE_Send(uint8_t *data,int datalen){

     ESP_LOGE(HCI_TAG, "ESP_BLE_Send:");
     esp_log_buffer_hex(HCI_TAG, data, datalen);

     esp_ble_gattc_write_char( gl_profile_tab[PROFILE_A_APP_ID].gattc_if,
                                  gl_profile_tab[PROFILE_A_APP_ID].conn_id,
                                  gl_profile_tab[PROFILE_A_APP_ID].char_handle2,
                                  datalen,
                                  data,
                                  ESP_GATT_WRITE_TYPE_RSP,
                                  ESP_GATT_AUTH_REQ_NONE);
}   

uint8_t  hex_to_char(uint8_t ucData)
{
    if(ucData < 10){
        return ucData+'0';
    }
    else{
        return ucData-10+'A';
    }
}

unsigned char str_to_int(unsigned char dData)
{      
        unsigned char rst=0;
  if((dData >= '0')&& (dData <= '9'))
          rst = dData-'0';
  else if((dData >= 'A')&&(dData <= 'F'))
          rst =  dData+10-'A';
  else if((dData >= 'a')&&(dData <= 'f'))
          rst =  dData+10-'a';
        else rst = 0;//不是ASCII的char

        return rst;
}

/*"1234"---->0X12 0X34  参数3一般是strlen*/
int memcpy_down( unsigned char *respone, const char *data , int length)
{
     ESP_LOGE(GATTC_TAG, "memcpy_down %s %d",data,length);
    if(length%2 != 0)    return -1;

    for( int i = 0 ; i < length/2 ;i++)
    {
        *respone++ = (((str_to_int(data[i*2])<<4)&0xf0)|(str_to_int(data[i*2+1])&0x0f)); 
    }

    return length/2 ;
}

/*KOSON*/

static void gattc_profile_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_LOGD(HCI_TAG, "ESP_GATTC_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;
    case ESP_GATTC_CONNECT_EVT:{
        ESP_LOGD(GATTC_TAG, "ESP_GATTC_CONNECT_EVT conn_id %d, if %d", p_data->connect.conn_id, gattc_if);
        gl_profile_tab[PROFILE_A_APP_ID].conn_id = p_data->connect.conn_id;
        memcpy(gl_profile_tab[PROFILE_A_APP_ID].remote_bda, p_data->connect.remote_bda, sizeof(esp_bd_addr_t));
        ESP_LOGD(HCI_TAG, "准备连接这个MAC的从机 REMOTE BDA:");
        //esp_log_buffer_hex(GATTC_TAG, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, sizeof(esp_bd_addr_t));

        ESP_LOGI(GATTC_TAG, "ConnectedTarget %s",stringMac(p_data->connect.remote_bda));

        esp_err_t mtu_ret = esp_ble_gattc_send_mtu_req (gattc_if, p_data->connect.conn_id);
        if (mtu_ret){
            ESP_LOGE(GATTC_TAG, "config MTU error, error code = %x", mtu_ret);
        }
        ESP_LOGE(HCI_TAG, " <KK> 设置MTU [定位gattc_if=%d]",gattc_if);//3
       /*测试扫描150次 成功100次 失败50次 所以暂时不设置这个试试  优化 1*/
        break;
    }
    case ESP_GATTC_OPEN_EVT:
        if (param->open.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "open failed, status %d", p_data->open.status);
            break;
        }
        ESP_LOGI(GATTC_TAG, "open success");
        break;
    case ESP_GATTC_DIS_SRVC_CMPL_EVT:
        if (param->dis_srvc_cmpl.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "discover service failed, status %d", param->dis_srvc_cmpl.status);
            break;
        }
        ESP_LOGI(HCI_TAG, "2 discover service complete conn_id %d", param->dis_srvc_cmpl.conn_id);
        esp_ble_gattc_search_service(gattc_if, param->cfg_mtu.conn_id, &remote_filter_service_uuid);
        break;
    case ESP_GATTC_CFG_MTU_EVT:
        if (param->cfg_mtu.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG,"config mtu failed, error status = %x", param->cfg_mtu.status);
        }
        ESP_LOGD(HCI_TAG, "<KK> 设置MTU成功 ESP_GATTC_CFG_MTU_EVT, Status %d, MTU %d, conn_id %d", param->cfg_mtu.status, param->cfg_mtu.mtu, param->cfg_mtu.conn_id);
        break;
    case ESP_GATTC_SEARCH_RES_EVT: {
        ESP_LOGD(GATTC_TAG, "SEARCH RES: conn_id = %x is primary service %d", p_data->search_res.conn_id, p_data->search_res.is_primary);
        ESP_LOGD(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) {
        if (p_data->search_res.srvc_id.uuid.len == ESP_UUID_LEN_128) {
            ESP_LOGI(HCI_TAG, "3 service found");
            get_server = 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;
            ESP_LOGD(GATTC_TAG, "UUID16: %x", p_data->search_res.srvc_id.uuid.uuid.uuid16);
        }
        break;
    }
#if 1
    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(p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_REMOTE_DEVICE) {
            ESP_LOGI(GATTC_TAG, "Get service information from remote device");
        } else if (p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_NVS_FLASH) {
            ESP_LOGI(GATTC_TAG, "Get service information from flash");
        } else {
            ESP_LOGI(GATTC_TAG, "unknown service source");
        }
        ESP_LOGE(HCI_TAG, "4 ESP_GATTC_SEARCH_CMPL_EVT get_server %d",get_server);
        if (get_server){
            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");
            }
            ESP_LOGE(HCI_TAG, "4 ESP_GATTC_SEARCH_CMPL_EVT count %d",count);
            if (count > 0){
                char_elem_result = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * count);
                if (!char_elem_result){
                    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_uuid2,
                                                             char_elem_result,
                                                             &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){
                        gl_profile_tab[PROFILE_A_APP_ID].char_handle2 = char_elem_result[0].char_handle;
                        ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_char_by_uuid count must=1 only one %d 0X%X",count,gl_profile_tab[PROFILE_A_APP_ID].char_handle2);
                      }

//找第二个
                    
                    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,
                                                             &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[0].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY)){
                        gl_profile_tab[PROFILE_A_APP_ID].char_handle = char_elem_result[0].char_handle;
                        esp_ble_gattc_register_for_notify (gattc_if, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, char_elem_result[0].char_handle);
                    
                        ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_char_by_uuid count must=1 only one=== %d 0X%X",count,char_elem_result[0].char_handle);
                      
                    }
                }
                /* free char_elem_result */
                free(char_elem_result);
            }else{
                ESP_LOGE(GATTC_TAG, "no char found");
            }
        }
         break;
#else
        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(p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_REMOTE_DEVICE) {
            ESP_LOGI(GATTC_TAG, "Get service information from remote device");
        } else if (p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_NVS_FLASH) {
            ESP_LOGI(GATTC_TAG, "Get service information from flash");
        } else {
            ESP_LOGI(GATTC_TAG, "unknown service source");
        }
        ESP_LOGD(HCI_TAG, "ESP_GATTC_SEARCH_CMPL_EVT get_server=%d",get_server);
        if (get_server){
            uint16_t count  = 0;
            uint16_t offset = 0;
            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_CHARACTERISTIC,
                                                                        gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
                                                                        gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
                                                                        p_data->reg_for_notify.handle,//??? INVALID_HANDLE,
                                                                        &count);
            if (ret_status != ESP_GATT_OK){
                ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_attr_count error, %d", __LINE__);
            }
        ESP_LOGD(HCI_TAG, "4 ESP_GATTC_SEARCH_CMPL_EVT count=%d",count);
            if (count > 0){
                char_elem_result = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * count);
                if (!char_elem_result){
                    ESP_LOGE(GATTC_TAG, "gattc no mem");
                }else{
                    ret_status = esp_ble_gattc_get_all_char(gattc_if,
                                                            gl_profile_tab[PROFILE_A_APP_ID].conn_id,
                                                            gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
                                                            gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
                                                            char_elem_result,
                                                            &count,
                                                            offset);
                    if (ret_status != ESP_GATT_OK){
                        ESP_LOGE(GATTC_TAG, "esp_ble_gattc_get_all_char error, %d", __LINE__);
                    }
                    if (count > 0){
 
                        for (int i = 0; i < count; ++i)
                        {
                            //if (char_elem_result[i].uuid.len == ESP_UUID_LEN_16 )
                            //{
                            ESP_LOGE(GATTC_TAG, "[count %d]+++%04X+++%d+++%04X+++[是否需要使能%d] uuid如下", i,char_elem_result[i].char_handle,char_elem_result[i].uuid.len,char_elem_result[i].uuid.uuid.uuid16,(char_elem_result[i].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY));
                            esp_log_buffer_hex(GATTC_TAG, char_elem_result[i].uuid.uuid.uuid128, 16);                         
                            if (char_elem_result[i].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY)//TX 
                            {
                                gl_profile_tab[PROFILE_A_APP_ID].char_handle = char_elem_result[i].char_handle;
                                esp_ble_gattc_register_for_notify (gattc_if,
                                gl_profile_tab[PROFILE_A_APP_ID].remote_bda,
                                char_elem_result[i].char_handle);
                                ESP_LOGE(GATTC_TAG, "TX- char_handle-0X%04X", gl_profile_tab[PROFILE_A_APP_ID].char_handle);
                            } else{
			                    gl_profile_tab[PROFILE_A_APP_ID].char_handle2 = char_elem_result[i].char_handle ;
                                ESP_LOGE(GATTC_TAG, "RX- gl_profile_tab[PROFILE_A_APP_ID].char_handle2-0X%04X", gl_profile_tab[PROFILE_A_APP_ID].char_handle2);
			                 }//NUS 需要检出2个句柄 源码只有一个 再结构体里面 我就自己做一个全局的用一下
                
                        }
                    }
                }
                /* free char_elem_result */
                free(char_elem_result);
            }else{
                ESP_LOGE(GATTC_TAG, "no char found");
            }
        }
         break;
#endif
    case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
        ESP_LOGE(HCI_TAG, "ESP_GATTC_REG_FOR_NOTIFY_EVT");
        if (p_data->reg_for_notify.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "REG FOR NOTIFY failed: error status = %d", p_data->reg_for_notify.status);
        }else{
            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");
            }
            ESP_LOGE(HCI_TAG, "ESP_GATTC_REG_FOR_NOTIFY_EVT count=%d",count);
            if (count > 0){
                descr_elem_result = malloc(sizeof(esp_gattc_descr_elem_t) * count);
                if (!descr_elem_result){
                    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,
                                                                         &count);
                    ESP_LOGE(HCI_TAG, "5 esp_ble_gattc_get_descr_by_char_handle ok");
                    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' */
                    //---2902 come here
/*
即将使能CCCD
Send RTC_CODE : B001080016040105012821000D0A
*/
#if 1
   const char *RTC_CODE_string="B001080016050201081E1A000D0A";
   uint8_t RTC_CODE_hex[20]={0};
//B001 0800 16-05-02-[01]-08-1E-1A-00 0D0A
    time_t now;
    struct tm t;
    time(&now);
    localtime_r(&now, &t);
RTC_CODE_hex[4]=t.tm_year-100;
RTC_CODE_hex[5]=t.tm_mon;
RTC_CODE_hex[6]=t.tm_mday;
RTC_CODE_hex[7]=t.tm_wday;
RTC_CODE_hex[8]=t.tm_hour;
RTC_CODE_hex[9]=t.tm_min;
RTC_CODE_hex[10]=t.tm_sec;



   int datalen=memcpy_down(RTC_CODE_hex,RTC_CODE_string,strlen(RTC_CODE_string));
   ESP_BLE_Send(RTC_CODE_hex,datalen);
#endif
                    if (count > 0 && descr_elem_result[0].uuid.len == ESP_UUID_LEN_16 && descr_elem_result[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[0].handle,
                                                                     sizeof(notify_en),
                                                                     (uint8_t *)&notify_en,//1
                                                                     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");
                    }
                    ESP_LOGD(HCI_TAG, "6 esp_ble_gattc_write_char_descr ok 成功使能CCCD"); 
                    /* free descr_elem_result */
                    free(descr_elem_result);
                }
            }
            else{
                ESP_LOGE(GATTC_TAG, "decsr not found");
            }

        }
        break;
    }
    case ESP_GATTC_NOTIFY_EVT:
        //从机数据太多 暂时屏蔽log
        //if (p_data->notify.is_notify){
        //    ESP_LOGI(GATTC_TAG, "ESP_GATTC_NOTIFY_EVT, receive notify value:");
        //}else{
        //    ESP_LOGI(GATTC_TAG, "ESP_GATTC_NOTIFY_EVT, receive indicate value:");
        //}


        rxdatacount ++;
        rxdatanumber += p_data->notify.value_len;
        ESP_LOGD(HCI_TAG, "RX %d rxdatacount=%d",p_data->notify.value_len,rxdatacount);
        //esp_log_buffer_hex(GATTC_TAG, p_data->notify.value, p_data->notify.value_len);
        esp_log_buffer_hex(GATTC_TAG, p_data->notify.value, 16);
#if 1
//根据蓝牙协议回答
/*
协议 https://wiki.xsens.com/pages/viewpage.action?pageId=69604108

Setup Command (0xB00X), without return message.
无需回答
ACK             0xB000
RTC	0           0xB001
DIALOG_CTRL_CMD	0xB003
NODE_STATE	    0xB002
需要回答
HEX_DATA        0xB100
案例
Send RTC_CODE : B001080016040105012821000D0A
Send Ctrl cmd : B003020000000D0A
Send BLE data : B000020000010D0A
Send BLE data : B000 0200 0001 0D0A
*/
   uint8_t Rxdata[150]={0};//28一个 142一个
   uint8_t Rxdatalen=p_data->notify.value_len;
   memcpy(Rxdata,p_data->notify.value,Rxdatalen);
   uint16_t cmd=Rxdata[0]<<8|Rxdata[1];
   ESP_LOGD(HCI_TAG, "CMD 0X%X",cmd);
   if(cmd==0XB002){
       ESP_LOGI(HCI_TAG, "Get Node Status");
   }else if(cmd==0XB100){
       jiucai = 0;
       hexdatacount++;
       ESP_LOGI(HCI_TAG, "Get HEX DATA hexdatacount=%d",hexdatacount);
       if(!timerworking)
       {
           timerworking=1;
           ESP_LOGI(HCI_TAG, "esp_timer_start_periodic");
           esp_timer_start_periodic(timer1, 100e3);
       }
       //const char *ack_string="B000020000010D0A";
       //uint8_t ack_hex[20]={0};
       //int datalen=memcpy_down(ack_hex,ack_string,strlen(ack_string));
       //ESP_BLE_Send(ack_hex,datalen);
   }

#endif
        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_LOGE(GATTC_TAG, "write descr OK");
#if 0   //主机不要发任何消息
        ESP_LOGI(HCI_TAG, "A: write descr success-----esp_ble_gattc_write_char--wait ack----- ");

        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);
#endif
        break;
    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:");
        esp_log_buffer_hex(GATTC_TAG, bda, sizeof(esp_bd_addr_t));
        break;
    }
    case ESP_GATTC_WRITE_CHAR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(HCI_TAG, "A: acked ----311--write char failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGE(GATTC_TAG, "write char success ");
        break;
    case ESP_GATTC_DISCONNECT_EVT://他不是来自GAP啊!!
        connect = false;
        get_server = false;
        ESP_LOGI(HCI_TAG, "ESP_GATTC_DISCONNECT_EVT, reason = 0X%02X", p_data->disconnect.reason);
        
        esp_ble_gap_start_scanning(30);
        scancount++;
        if (p_data->disconnect.reason==0X13)yescount++;
        else nocount++;

        ESP_LOGI(HCI_TAG,"TotalCount=%ld,yes=%ld,fail=%ld,rxdatacount=%d,rxdatanumber=%ld",scancount,yescount,nocount,rxdatacount,rxdatanumber);
        rxdatacount =0;
        rxdatanumber =0;
        ESP_LOGI(HCI_TAG,"===========END=========");
        showtime();
        break;
    default:
        break;
    }
}

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_SCAN_PARAM_SET_COMPLETE_EVT: {
        //the unit of the duration is second
        uint32_t duration = 30;
        ESP_LOGD(HCI_TAG, "ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT 开始扫描");
        ESP_LOGI(HCI_TAG,"ScanStart");
        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_LOGE(GATTC_TAG, "scan start failed, error status = %x", param->scan_start_cmpl.status);
            break;
        }
        ESP_LOGD(HCI_TAG, "scan start success 成功开始扫描");

        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:
            /*这里是扫描的结果 log很多 暂时关闭它*/
            ESP_LOGD(GATTC_TAG, "ScanedTarget %s",stringMac(scan_result->scan_rst.bda));

            //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);
  

#if CONFIG_EXAMPLE_DUMP_ADV_DATA_AND_SCAN_RESP
            if (scan_result->scan_rst.adv_data_len > 0) {
                ESP_LOGI(GATTC_TAG, "adv data:");
                esp_log_buffer_hex(GATTC_TAG, &scan_result->scan_rst.ble_adv[0], scan_result->scan_rst.adv_data_len);
            }
            if (scan_result->scan_rst.scan_rsp_len > 0) {
                ESP_LOGI(GATTC_TAG, "scan resp:");
                esp_log_buffer_hex(GATTC_TAG, &scan_result->scan_rst.ble_adv[scan_result->scan_rst.adv_data_len], scan_result->scan_rst.scan_rsp_len);
            }
#endif

            if (adv_name != NULL) {
                //ESP_LOGI(GATTC_TAG, "searched Device Name Len %d", adv_name_len);  
                //esp_log_buffer_char(GATTC_TAG, adv_name, adv_name_len);
                if (strlen(remote_device_name) == adv_name_len && strncmp((char *)adv_name, remote_device_name, adv_name_len) == 0) {
                    ESP_LOGD(HCI_TAG, "1 searched device %s\n", remote_device_name);
                    ESP_LOGI(HCI_TAG,"ScanedTarget");
                    if (connect == false) {
                        connect = true;
                        ESP_LOGI(HCI_TAG, "ConnectTarget");
                        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);
                    }
                }
            }
            break;
        case ESP_GAP_SEARCH_INQ_CMPL_EVT:
        ESP_LOGI(HCI_TAG, "X ESP_GAP_SEARCH_INQ_CMPL_EVT-->ScanStart");
        esp_ble_gap_start_scanning(30);
            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, error status = %x", param->scan_stop_cmpl.status);
            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, error status = %x", param->adv_stop_cmpl.status);
            break;
        }
        ESP_LOGI(GATTC_TAG, "stop adv successfully");
        break;
    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;
    default:
        break;
    }
}

static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{
    /* 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);
                }
            }
        }
    } while (0);
}


void timer1Interrupt(void *args){

    jiucai++;

    ESP_LOGD(GATTC_TAG,"Timer1 Interrupt, state:periodic------%d",jiucai);
    const char *ack_string="B000020000FF0D0A";
    uint8_t ack_hex[20]={0};
    int datalen = 0;
    if(jiucai>5){//关闭 TX收到的数据 //注意到else执行完毕 回到这里 没事的
        esp_timer_stop(timer1);
        jiucai=0;
        timerworking=0;
        ESP_LOGE(GATTC_TAG,"Timer1 end----------------------%d",jiucai);
        //不能再里面发 因为太多了
        //行 52718: I (248947) KOSON: TotalCount=1,yes=1,fail=0,rxdatacount=5761,rxdatanumber=817948
   
         //最后发一下 必定是<0XFF的
         datalen=memcpy_down(ack_hex,ack_string,strlen(ack_string));
         ack_hex[5]=hexdatacount;
         ESP_BLE_Send(ack_hex,datalen);
         hexdatacount=0;
   
    }else{//中途帮忙TX一下
    #if 1
            if(hexdatacount>=0XFF) 
            {
                 datalen=memcpy_down(ack_hex,ack_string,strlen(ack_string));
                 ESP_BLE_Send(ack_hex,datalen);
                 hexdatacount-=0XFF;
            }
    #else
                if(hexdatacount>=0XF0) 
            {
                 datalen=memcpy_down(ack_hex,ack_string,strlen(ack_string));
                 ack_hex[5]=hexdatacount;//0;
                 ESP_BLE_Send(ack_hex,datalen);
                 hexdatacount=0;
            }
    #endif
    }


}

void timer1Init(void){
    esp_timer_init();
    esp_timer_create_args_t args = {
        .callback = timer1Interrupt,
        .arg = (void*)1,
        .dispatch_method = ESP_TIMER_TASK,
        .name = "Tiemr1",
        .skip_unhandled_events = false,
    };
    esp_timer_create(&args, &timer1);
    esp_timer_start_periodic(timer1, 500e3);//定时时间为500ms(即500e3 微秒)
    //esp_timer_start_once(timer1, 500e3);//定时时间为500ms(即500e3 微秒)
}

void app_main(void)
{
    // Initialize NVS.
    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, "%s gap register failed, error code = %x\n", __func__, 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, "%s gattc register failed, error code = %x\n", __func__, ret);
        return;
    }

    ret = esp_ble_gattc_app_register(PROFILE_A_APP_ID);
    if (ret){
        ESP_LOGE(GATTC_TAG, "%s gattc app register failed, error code = %x\n", __func__, ret);
    }
    esp_err_t local_mtu_ret = esp_ble_gatt_set_local_mtu(500);
    if (local_mtu_ret){
        ESP_LOGE(GATTC_TAG, "set local  MTU failed, error code = %x", local_mtu_ret);
    }

    timer1Init();
    esp_timer_stop(timer1);
    timerworking=0;

    setTime(0,25,21,3,5,2022);


    showtime();
}

 

 

 

### 关于ESP32 P4的技术信息 ESP32-P4 是一款基于 ESP32 芯片设计的模块,支持 Wi-Fi 和蓝牙功能。该模块集成了丰富的外设接口,适用于各种物联网应用开发场景[^1]。 #### 技术文档与教程资源 对于希望深入了解 ESP32-P4 的开发者而言,官方提供了详尽的技术文档和编程指南: - **硬件规格**:包括引脚定义、电气特性以及物理尺寸等重要参数说明。 - **软件开发环境配置**:指导如何安装并设置用于编写固件的应用程序框架——即 ESP-IDF(Espressif IoT Development Framework),这是针对 Espressif 系列芯片优化过的开源 RTOS SDK。 ```bash # 安装依赖项 pip install --upgrade pip setuptools wheel pip install -r $IDF_PATH/requirements.txt ``` - **示例项目**:提供了一系列完整的源码实例来帮助初学者快速上手,涵盖了从基础通信协议到高级传感器数据处理等多个方面。 #### 常见问题解答 一些常见的疑问及其解决办法如下所示: - **连接不上Wi-Fi网络** 如果遇到设备无法成功接入指定 SSID 的情况,建议先确认输入密码无误,并尝试重启路由器或切换至其他可用信道进行测试。 - **BLE广播范围有限** 对于 Bluetooth Low Energy 广播距离较短的问题,可以通过调整发射功率参数 `ble_tx_power` 来改善信号强度,从而扩大覆盖区域。 #### 实际案例分析 当面对具体应用场景中的挑战时,可以参考以下解决方案: - 需要实现低功耗运行模式下定时唤醒执行特定任务的功能,则可利用 Deep-Sleep API 结合 RTC 计时器完成此需求;进入休眠前记得保存必要的状态变量以便恢复工作后继续正常运作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值