gatts_table_creat_demo.c 44 KB
Newer Older
李俭双's avatar
李俭双 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */

/****************************************************************************
*
* This demo showcases creating a GATT database using a predefined attribute table.
* It acts as a GATT server and can send adv data, be connected by client.
* Run the gatt_client demo, the client demo will automatically connect to the gatt_server_service_table demo.
* Client demo will enable GATT server's notify after connection. The two devices will then exchange
* data.
*
****************************************************************************/

17 18 19 20
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
李俭双's avatar
李俭双 committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_bt.h"

#include "esp_gap_ble_api.h"
#include "esp_gatts_api.h"
#include "esp_bt_main.h"
#include "gatts_table_creat_demo.h"
#include "esp_gatt_common_api.h"

#include "esp_mac.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "driver/uart.h"
#include "string.h"
#include "driver/gpio.h"
44 45 46
#include "Protocol_CRC16.h"
#include "Protocol_Lib.h"
#include "Protocol_User.h"
薛小虎's avatar
薛小虎 committed
47
#include "app_Ble_User.h"
48
#include "MCU_Core_Protocol.h"
49 50

typedef   unsigned char   uint8_t;
李俭双's avatar
李俭双 committed
51 52 53 54 55 56 57 58

unsigned int flag_u;

static const int RX_BUF_SIZE = 1024;

#define TXD_PIN (GPIO_NUM_22)
#define RXD_PIN (GPIO_NUM_26)

59 60 61 62 63 64 65 66
typedef struct
{
    uint16_t Rxlen;
    uint8_t Rxbuff[255];
} _QJ_UART_Ctrl;

_QJ_UART_Ctrl QJ_UARTRX;

67
void init_Uart(void) {
李俭双's avatar
李俭双 committed
68 69 70 71 72 73 74 75 76
    const uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT,
    };
    // We won't use a buffer for sending data.
77
    uart_driver_install(UART_NUM_1, RX_BUF_SIZE * 2, 200, 0, NULL, 0);
李俭双's avatar
李俭双 committed
78 79 80 81
    uart_param_config(UART_NUM_1, &uart_config);
    uart_set_pin(UART_NUM_1, TXD_PIN, RXD_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}

82
int bsp_Uart_Send_Data(uint8_t * data , unsigned int len)
李俭双's avatar
李俭双 committed
83
{
84 85
    int txBytes = uart_write_bytes(UART_NUM_1, data, len);
    uart_wait_tx_idle_polling(UART_NUM_1);
李俭双's avatar
李俭双 committed
86 87 88
    return txBytes;
}

薛小虎's avatar
薛小虎 committed
89

李俭双's avatar
李俭双 committed
90

91
static void Uart_Rx_Task(void *arg)
李俭双's avatar
李俭双 committed
92 93
{
    uint8_t* data = (uint8_t*) malloc(RX_BUF_SIZE+1);
94 95
    while (1) 
    {
96
        const int rxBytes = uart_read_bytes(UART_NUM_1, data, RX_BUF_SIZE, 20);
97
        if (rxBytes < 1000)
98
        {
99 100 101 102
            for (uint16_t i = 0; i < rxBytes; i++)
            {
                UART_Put(data[i]);
            }
李俭双's avatar
李俭双 committed
103
        }
104 105 106 107 108

        if(Wifi_OTA_Request != 0)
        {
            break;
        }
李俭双's avatar
李俭双 committed
109
    }
110
    ESP_LOGW("ota", "vtask del uart rx");
李俭双's avatar
李俭双 committed
111
    free(data);
112
    vTaskDelete(NULL);
李俭双's avatar
李俭双 committed
113 114
}

115 116 117 118
void bsp_Uart_Init(void )
{
    init_Uart();
    Protocol_KL30_Wakeup_Init();
119
    xTaskCreatePinnedToCore(Uart_Rx_Task, "Ble_User", 4096, NULL, 4, NULL, 1);
120 121 122 123
}



124 125 126 127 128





129 130 131 132 133
extern void simple_ota_main(void);
void simple_ota_service(void)
{
    if(Wifi_OTA_Request == 1)
    {
134 135 136
        gatts_Ble_User_Task_Event_Del();
        vTaskDelay(300);
        gatts_App_Ble_DeInit();
137
        simple_ota_main();
138
        Wifi_OTA_Request = 2;
139 140 141 142 143
    }
}



144
int gatts_App_Ble_DeInit(void)
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
{
    esp_err_t err;
    err = esp_bluedroid_disable();
    if (err != ESP_OK) {
        return ESP_FAIL;
    }
    err = esp_bluedroid_deinit();
    if (err != ESP_OK) {
        return err;
    }
    err = esp_bt_controller_disable();
    if (err != ESP_OK) {
        return ESP_FAIL;
    }

    /* The API `esp_bt_controller_deinit` will have to be removed when we add support for
     * `reset to provisioning`
     */
    err = esp_bt_controller_deinit();
    if (err != ESP_OK) {
        return ESP_FAIL;
    }

    return ESP_OK;
}



173 174 175 176 177 178






179
uint8_t BT_Device_Name[14] = "QJViva";
李俭双's avatar
李俭双 committed
180 181 182 183

#define GATTS_TABLE_TAG "GATTS_TABLE_DEMO"

#define PROFILE_NUM                 1
薛小虎's avatar
薛小虎 committed
184

李俭双's avatar
李俭双 committed
185
#define PROFILE_APP_IDX             0
薛小虎's avatar
薛小虎 committed
186

李俭双's avatar
李俭双 committed
187
#define ESP_APP_ID                  0x55
188
#define SAMPLE_DEVICE_NAME          "QJ-Viva"
李俭双's avatar
李俭双 committed
189
#define SVC_INST_ID                 0
薛小虎's avatar
薛小虎 committed
190
#define SVC_INST_ID1                 1
李俭双's avatar
李俭双 committed
191

薛小虎's avatar
薛小虎 committed
192 193 194

 esp_bd_addr_t rand_addr = {0xC0, 0x30, 0x05, 0x70, 0x09, 0xFA};

李俭双's avatar
李俭双 committed
195 196 197 198 199 200 201 202 203 204 205 206 207
/* The max length of characteristic value. When the GATT client performs a write or prepare write operation,
*  the data length must be less than GATTS_DEMO_CHAR_VAL_LEN_MAX.
*/
#define GATTS_DEMO_CHAR_VAL_LEN_MAX 500
#define PREPARE_BUF_MAX_SIZE        1024
#define CHAR_DECLARATION_SIZE       (sizeof(uint8_t))

#define ADV_CONFIG_FLAG             (1 << 0)
#define SCAN_RSP_CONFIG_FLAG        (1 << 1)

static uint8_t adv_config_done       = 0;

uint16_t heart_rate_handle_table[HRS_IDX_NB];
薛小虎's avatar
薛小虎 committed
208
uint16_t heart_rate_handle_table2[HRS_IDX_NB2];
李俭双's avatar
李俭双 committed
209 210 211 212 213 214 215 216 217 218 219 220

typedef struct {
    uint8_t                 *prepare_buf;
    int                     prepare_len;
} prepare_type_env_t;

static prepare_type_env_t prepare_write_env;

#define CONFIG_SET_RAW_ADV_DATA
#ifdef CONFIG_SET_RAW_ADV_DATA
static uint8_t raw_adv_data[] = {
        0x02, 0x01, 0x02,
薛小虎's avatar
薛小虎 committed
221
        0x03, 0x03, 0x69, 0x67,
薛小虎's avatar
薛小虎 committed
222
        0x09, 0xff, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
223
        0x07, 0x09, 'Q', 'J', '-', 'V', 'i', 'v',   
薛小虎's avatar
薛小虎 committed
224

薛小虎's avatar
薛小虎 committed
225
        // 0x08, 0x16, 0x60, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00,
李俭双's avatar
李俭双 committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
};
static uint8_t raw_scan_rsp_data[] = {
        /* flags */
        0x02, 0x01, 0x02,
        0x02, 0x0a, 0xeb,
        /* service uuid */
        0x03, 0x03, 0x69, 0x67,
};

#else
static uint8_t service_uuid[16] = {
    /* LSB <--------------------------------------------------------------------------------> MSB */
    //first uuid, 16bit, [12],[13] is the value
    0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00,
};

/* The length of adv data must be less than 31 bytes */
static esp_ble_adv_data_t adv_data = {
    .set_scan_rsp        = false,
    .include_name        = true,
    .include_txpower     = true,
    .min_interval        = 0x0006, //slave connection min interval, Time = min_interval * 1.25 msec
    .max_interval        = 0x0010, //slave connection max interval, Time = max_interval * 1.25 msec
    .appearance          = 0x00,
    .manufacturer_len    = 0,    //TEST_MANUFACTURER_DATA_LEN,
    .p_manufacturer_data = NULL, //test_manufacturer,
    .service_data_len    = 0,
    .p_service_data      = NULL,
    .service_uuid_len    = sizeof(service_uuid),
    .p_service_uuid      = service_uuid,
    .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};

// scan response data
static esp_ble_adv_data_t scan_rsp_data = {
    .set_scan_rsp        = true,
    .include_name        = true,
    .include_txpower     = true,
    .min_interval        = 0x0006,
    .max_interval        = 0x0010,
    .appearance          = 0x00,
    .manufacturer_len    = 0, //TEST_MANUFACTURER_DATA_LEN,
    .p_manufacturer_data = NULL, //&test_manufacturer[0],
    .service_data_len    = 0,
    .p_service_data      = NULL,
    .service_uuid_len    = sizeof(service_uuid),
    .p_service_uuid      = service_uuid,
    .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};
#endif /* CONFIG_SET_RAW_ADV_DATA */

static esp_ble_adv_params_t adv_params = {
    .adv_int_min         = 0x20,
    .adv_int_max         = 0x40,
    .adv_type            = ADV_TYPE_IND,
281
    .own_addr_type       = BLE_ADDR_TYPE_PUBLIC,
李俭双's avatar
李俭双 committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    .channel_map         = ADV_CHNL_ALL,
    .adv_filter_policy   = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};

struct gatts_profile_inst {
    esp_gatts_cb_t gatts_cb;
    uint16_t gatts_if;
    uint16_t app_id;
    uint16_t conn_id;
    uint16_t service_handle;
    esp_gatt_srvc_id_t service_id;
    uint16_t char_handle;
    esp_bt_uuid_t char_uuid;
    esp_gatt_perm_t perm;
    esp_gatt_char_prop_t property;
    uint16_t descr_handle;
    esp_bt_uuid_t descr_uuid;
};

static void gatts_profile_event_handler(esp_gatts_cb_event_t event,
					esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);

/* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */
static struct gatts_profile_inst heart_rate_profile_tab[PROFILE_NUM] = {
    [PROFILE_APP_IDX] = {
        .gatts_cb = gatts_profile_event_handler,
        .gatts_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
};

/* Service */
const uint16_t GATTS_SERVICE_UUID_TEST      = 0x00FF;
const uint16_t GATTS_CHAR_UUID_TEST_A       = 0xFF01;
const uint16_t GATTS_CHAR_UUID_TEST_B       = 0xFF02;
const uint16_t GATTS_CHAR_UUID_TEST_C       = 0xFF03;

const uint16_t device_info_service_uuid = ESP_GATT_UUID_DEVICE_INFO_SVC;

const uint16_t primary_service_uuid         = ESP_GATT_UUID_PRI_SERVICE;
const uint16_t character_declaration_uuid   = ESP_GATT_UUID_CHAR_DECLARE;
const uint16_t character_client_config_uuid = ESP_GATT_UUID_CHAR_CLIENT_CONFIG;
const uint8_t char_prop_read                =  ESP_GATT_CHAR_PROP_BIT_READ;
const uint8_t char_prop_write               = ESP_GATT_CHAR_PROP_BIT_WRITE;
薛小虎's avatar
薛小虎 committed
325 326
const uint8_t char_prop_read_write_notify   = 
ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY;
李俭双's avatar
李俭双 committed
327 328 329 330
const uint8_t heart_measurement_ccc[2]      = {0X00, 0X00};
 uint8_t char_value[12]                 = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L' };


331 332 333 334 335 336 337 338 339 340
const uint16_t Dev_Svc_2A29_Str = 0x2A29;
const uint16_t Dev_Svc_2A24_Str = 0x2A24;
const uint16_t Dev_Svc_2A25_Str = 0x2A25;
const uint16_t Dev_Svc_2A27_Str = 0x2A27;
const uint16_t Dev_Svc_2A26_Str = 0x2A26;
const uint16_t Dev_Svc_2A28_Str = 0x2A28;
const uint16_t Dev_Svc_2A23_Str = 0x2A23;
const uint16_t Dev_Svc_2A2A_Str = 0x2A2A;
const uint16_t Dev_Svc_2A50_Str = 0x2A50;

薛小虎's avatar
薛小虎 committed
341 342 343 344 345 346 347 348 349 350

const uint8_t char_prop_write_writenr_notify                =  
ESP_GATT_CHAR_PROP_BIT_WRITE_NR|ESP_GATT_CHAR_PROP_BIT_WRITE|ESP_GATT_CHAR_PROP_BIT_NOTIFY;

static const uint8_t service_1_uuid[16] = 
{0Xbc, 0Xbc, 0Xc6, 0Xbf, 0Xb1, 0Xea, 0Xf0, 0Xbd, 0Xec, 0Xc7, 0Xd8, 0Xd6, 0X60, 0Xb3, 0X00, 0X00};
static const uint8_t char_1_uuid[16] = 
{0Xbc, 0Xbc, 0Xc6, 0Xbf, 0Xb1, 0Xea, 0Xf0, 0Xbd, 0Xec, 0Xc7, 0Xd8, 0Xd6, 0X62, 0Xb3, 0X00, 0X00};


李俭双's avatar
李俭双 committed
351 352 353 354 355 356 357 358
/* Full Database Description - Used to add attributes into the database */
static const esp_gatts_attr_db_t gatt_db[HRS_IDX_NB] =
{
    // Service Declaration
    [IDX_SVC]        =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&primary_service_uuid, ESP_GATT_PERM_READ,
      sizeof(uint16_t), sizeof(device_info_service_uuid), (uint8_t *)&device_info_service_uuid}},

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

    /* Characteristic Declaration */
    [IDX_CHAR_2A29]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A29] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A29_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A29]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},


    /* Characteristic Declaration */
    [IDX_CHAR_2A24]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A24] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A24_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A24]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},



李俭双's avatar
李俭双 committed
393
    /* Characteristic Declaration */
394
    [IDX_CHAR_2A25]     =
李俭双's avatar
李俭双 committed
395 396 397 398
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
399 400
    [IDX_CHAR_VAL_2A25] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A25_Str, ESP_GATT_PERM_READ ,
李俭双's avatar
李俭双 committed
401 402 403
      GATTS_DEMO_CHAR_VAL_LEN_MAX, sizeof(char_value), (uint8_t *)char_value}},

    /* Client Characteristic Configuration Descriptor */
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    [IDX_CHAR_CFG_2A25]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},


    /* Characteristic Declaration */
    [IDX_CHAR_2A27]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A27] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A27_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A27]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},
    

    /* Characteristic Declaration */
    [IDX_CHAR_2A26]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A26] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A26_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A26]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},



    [IDX_CHAR_2A28]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A28] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A28_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A28]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},


    [IDX_CHAR_2A23]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A23] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A23_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A23]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},



    [IDX_CHAR_2A2A]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A2A] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A2A_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A2A]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},


    [IDX_CHAR_2A50]     =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_2A50] =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&Dev_Svc_2A50_Str, ESP_GATT_PERM_READ ,
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_2A50]  =
李俭双's avatar
李俭双 committed
499 500
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},
薛小虎's avatar
薛小虎 committed
501
};
李俭双's avatar
李俭双 committed
502 503


薛小虎's avatar
薛小虎 committed
504 505 506 507 508
/* Full Database Description - Used to add attributes into the database */
static const esp_gatts_attr_db_t gatt_db2[HRS_IDX_NB2] =
{
    // Service Declaration
    [IDX_SVC2]        =
509
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&primary_service_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
薛小虎's avatar
薛小虎 committed
510 511 512 513
      sizeof(uint16_t), sizeof(service_1_uuid), (uint8_t *)&service_1_uuid}},

    /* Characteristic Declaration */
    [IDX_CHAR_A2]     =
514
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
薛小虎's avatar
薛小虎 committed
515 516 517 518
      CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_write_writenr_notify      }},

    /* Characteristic Value */
    [IDX_CHAR_VAL_A2] =
薛小虎's avatar
薛小虎 committed
519
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_128, (uint8_t *)&char_1_uuid,  ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE ,
薛小虎's avatar
薛小虎 committed
520 521 522 523 524 525
      GATTS_DEMO_CHAR_VAL_LEN_MAX, 0, (uint8_t *)((void *)0)}},

    /* Client Characteristic Configuration Descriptor */
    [IDX_CHAR_CFG_A2]  =
    {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
      sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}},
李俭双's avatar
李俭双 committed
526 527
};

薛小虎's avatar
薛小虎 committed
528 529


530
int bsp_Ble_Gatts_Send_Indicate( uint8_t len, uint8_t *data)
薛小虎's avatar
薛小虎 committed
531
{
532 533 534
    int err = ESP_FAIL;
    uint8_t retry = 5;

535
    if(Ble_User.Ble_Sts != Ble_Idle)
薛小虎's avatar
薛小虎 committed
536
    {
537
        while(retry -- )
薛小虎's avatar
薛小虎 committed
538
        {
539
            if(err != ESP_OK)
540
            {
541 542 543 544
                err = esp_ble_gatts_send_indicate(heart_rate_profile_tab[0].gatts_if, 
                                heart_rate_profile_tab[0].conn_id, 
                                heart_rate_handle_table2[IDX_CHAR_VAL_A2],
                                len, data, false);
李俭双's avatar
李俭双 committed
545
            }
546
            else
李俭双's avatar
李俭双 committed
547
            {
548
                break;
李俭双's avatar
李俭双 committed
549
            }
550
        }
551

552 553 554
        if(err != ESP_OK)
        {
            ESP_LOGE("GATTS", "ble trans fail!!");
李俭双's avatar
李俭双 committed
555 556
        }
    }
557 558

    return err;
李俭双's avatar
李俭双 committed
559 560
}

561

李俭双's avatar
李俭双 committed
562 563 564 565 566 567 568 569
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
    switch (event) {
    #ifdef CONFIG_SET_RAW_ADV_DATA
        case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT:
            adv_config_done &= (~ADV_CONFIG_FLAG);
            if (adv_config_done == 0){
                esp_ble_gap_start_advertising(&adv_params);
薛小虎's avatar
薛小虎 committed
570

571
                // printf("adv 1\r\n");
李俭双's avatar
李俭双 committed
572 573 574 575 576 577
            }
            break;
        case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT:
            adv_config_done &= (~SCAN_RSP_CONFIG_FLAG);
            if (adv_config_done == 0){
                esp_ble_gap_start_advertising(&adv_params);
薛小虎's avatar
薛小虎 committed
578

579
                // printf("adv 2\r\n");
李俭双's avatar
李俭双 committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
            }
            break;
    #else
        case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
            adv_config_done &= (~ADV_CONFIG_FLAG);
            if (adv_config_done == 0){
                esp_ble_gap_start_advertising(&adv_params);
            }
            break;
        case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT:
            adv_config_done &= (~SCAN_RSP_CONFIG_FLAG);
            if (adv_config_done == 0){
                esp_ble_gap_start_advertising(&adv_params);
            }
            break;
    #endif
        case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
            /* advertising start complete event to indicate advertising start successfully or failed */
            if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
                ESP_LOGE(GATTS_TABLE_TAG, "advertising start failed");
            }else{
                ESP_LOGI(GATTS_TABLE_TAG, "advertising start successfully");
            }
            break;
        case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT:
            if (param->adv_stop_cmpl.status != ESP_BT_STATUS_SUCCESS) {
                ESP_LOGE(GATTS_TABLE_TAG, "Advertising stop failed");
            }
            else {
                ESP_LOGI(GATTS_TABLE_TAG, "Stop adv successfully\n");
            }
            break;
        case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT:
            ESP_LOGI(GATTS_TABLE_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;
    }
}

void example_prepare_write_event_env(esp_gatt_if_t gatts_if, prepare_type_env_t *prepare_write_env, esp_ble_gatts_cb_param_t *param)
{
    ESP_LOGI(GATTS_TABLE_TAG, "prepare write, handle = %d, value len = %d", param->write.handle, param->write.len);
    esp_gatt_status_t status = ESP_GATT_OK;
    if (param->write.offset > PREPARE_BUF_MAX_SIZE) {
        status = ESP_GATT_INVALID_OFFSET;
    } else if ((param->write.offset + param->write.len) > PREPARE_BUF_MAX_SIZE) {
        status = ESP_GATT_INVALID_ATTR_LEN;
    }
    if (status == ESP_GATT_OK && prepare_write_env->prepare_buf == NULL) {
        prepare_write_env->prepare_buf = (uint8_t *)malloc(PREPARE_BUF_MAX_SIZE * sizeof(uint8_t));
        prepare_write_env->prepare_len = 0;
        if (prepare_write_env->prepare_buf == NULL) {
            ESP_LOGE(GATTS_TABLE_TAG, "%s, Gatt_server prep no mem", __func__);
            status = ESP_GATT_NO_RESOURCES;
        }
    }

    /*send response when param->write.need_rsp is true */
    if (param->write.need_rsp){
        esp_gatt_rsp_t *gatt_rsp = (esp_gatt_rsp_t *)malloc(sizeof(esp_gatt_rsp_t));
        if (gatt_rsp != NULL){
            gatt_rsp->attr_value.len = param->write.len;
            gatt_rsp->attr_value.handle = param->write.handle;
            gatt_rsp->attr_value.offset = param->write.offset;
            gatt_rsp->attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
            memcpy(gatt_rsp->attr_value.value, param->write.value, param->write.len);
            esp_err_t response_err = esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, status, gatt_rsp);
            if (response_err != ESP_OK) {
               ESP_LOGE(GATTS_TABLE_TAG, "Send response error");
            }
            free(gatt_rsp);
        }else{
            ESP_LOGE(GATTS_TABLE_TAG, "%s, malloc failed", __func__);
        }
    }
    if (status != ESP_GATT_OK){
        return;
    }
    memcpy(prepare_write_env->prepare_buf + param->write.offset,
           param->write.value,
           param->write.len);
    prepare_write_env->prepare_len += param->write.len;

}

void example_exec_write_event_env(prepare_type_env_t *prepare_write_env, esp_ble_gatts_cb_param_t *param){
    if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC && prepare_write_env->prepare_buf){
        esp_log_buffer_hex(GATTS_TABLE_TAG, prepare_write_env->prepare_buf, prepare_write_env->prepare_len);
    }else{
        ESP_LOGI(GATTS_TABLE_TAG,"ESP_GATT_PREP_WRITE_CANCEL");
    }
    if (prepare_write_env->prepare_buf) {
        free(prepare_write_env->prepare_buf);
        prepare_write_env->prepare_buf = NULL;
    }
    prepare_write_env->prepare_len = 0;
}

薛小虎's avatar
薛小虎 committed
685 686
bool create_tab1 = false;

李俭双's avatar
李俭双 committed
687 688 689 690
static void gatts_profile_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_REG_EVT:{
691
            // esp_ble_gap_set_rand_addr(rand_addr);
692
            esp_err_t set_dev_name_ret = esp_ble_gap_set_device_name((const char *)BT_Device_Name);
李俭双's avatar
李俭双 committed
693 694 695 696 697 698 699 700 701
            if (set_dev_name_ret){
                ESP_LOGE(GATTS_TABLE_TAG, "set device name failed, error code = %x", set_dev_name_ret);
            }
    #ifdef CONFIG_SET_RAW_ADV_DATA
            esp_err_t raw_adv_ret = esp_ble_gap_config_adv_data_raw(raw_adv_data, sizeof(raw_adv_data));
            if (raw_adv_ret){
                ESP_LOGE(GATTS_TABLE_TAG, "config raw adv data failed, error code = %x ", raw_adv_ret);
            }
            adv_config_done |= ADV_CONFIG_FLAG;
702 703 704 705 706
            esp_err_t raw_scan_ret = esp_ble_gap_config_scan_rsp_data_raw(raw_scan_rsp_data, sizeof(raw_scan_rsp_data));
            if (raw_scan_ret){
                ESP_LOGE(GATTS_TABLE_TAG, "config raw scan rsp data failed, error code = %x", raw_scan_ret);
            }
            adv_config_done |= SCAN_RSP_CONFIG_FLAG;
李俭双's avatar
李俭双 committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
    #else
            //config adv data
            esp_err_t ret = esp_ble_gap_config_adv_data(&adv_data);
            if (ret){
                ESP_LOGE(GATTS_TABLE_TAG, "config adv data failed, error code = %x", ret);
            }
            adv_config_done |= ADV_CONFIG_FLAG;
            //config scan response data
            ret = esp_ble_gap_config_adv_data(&scan_rsp_data);
            if (ret){
                ESP_LOGE(GATTS_TABLE_TAG, "config scan response data failed, error code = %x", ret);
            }
            adv_config_done |= SCAN_RSP_CONFIG_FLAG;
    #endif
            esp_err_t create_attr_ret = esp_ble_gatts_create_attr_tab(gatt_db, gatts_if, HRS_IDX_NB, SVC_INST_ID);
            if (create_attr_ret){
                ESP_LOGE(GATTS_TABLE_TAG, "create attr table failed, error code = %x", create_attr_ret);
            }
薛小虎's avatar
薛小虎 committed
725 726

            ESP_LOGI(GATTS_TABLE_TAG,"create attr table!!!!!!!!!!!!!!!!!!!!");
李俭双's avatar
李俭双 committed
727 728 729 730
        }
       	    break;
        case ESP_GATTS_READ_EVT:

王金亮's avatar
王金亮 committed
731

李俭双's avatar
李俭双 committed
732 733 734 735 736 737 738
            ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_READ_EVT");
       	    break;
        case ESP_GATTS_WRITE_EVT:
            if (!param->write.is_prep){
                // the data length of gattc write  must be less than GATTS_DEMO_CHAR_VAL_LEN_MAX.
                ESP_LOGI(GATTS_TABLE_TAG, "GATT_WRITE_EVT, handle = %d, value len = %d, value :", param->write.handle, param->write.len);
                esp_log_buffer_hex(GATTS_TABLE_TAG, param->write.value, param->write.len);
薛小虎's avatar
薛小虎 committed
739 740 741 742 743 744 745 746 747 748

                // printf("descr_value = %d\r\n", heart_rate_handle_table[IDX_CHAR_CFG_A2]);
                // printf("handle = %d\r\n", param->write.handle);

                if (heart_rate_handle_table2[IDX_CHAR_VAL_A2] == param->write.handle)
                {
                    Get_Ble_Raw_Data(param->write.value, param->write.len);
                }

                if (heart_rate_handle_table2[IDX_CHAR_CFG_A2] == param->write.handle && param->write.len == 2){
李俭双's avatar
李俭双 committed
749
                    uint16_t descr_value = param->write.value[1]<<8 | param->write.value[0];
薛小虎's avatar
薛小虎 committed
750 751 752

                    

李俭双's avatar
李俭双 committed
753 754
                    if (descr_value == 0x0001){
                        ESP_LOGI(GATTS_TABLE_TAG, "notify enable");
755 756 757 758 759 760 761 762
                        // uint8_t notify_data[15];
                        // for (int i = 0; i < sizeof(notify_data); ++i)
                        // {
                        //     notify_data[i] = i % 0xff;
                        // }
                        // //the size of notify_data[] need less than MTU size
                        // esp_ble_gatts_send_indicate(gatts_if, param->write.conn_id, heart_rate_handle_table2[IDX_CHAR_CFG_A2],
                        //                         sizeof(notify_data), notify_data, false);
李俭双's avatar
李俭双 committed
763
                    }else if (descr_value == 0x0002){
764 765 766 767 768 769
                        // ESP_LOGI(GATTS_TABLE_TAG, "indicate enable");
                        // uint8_t indicate_data[15];
                        // for (int i = 0; i < sizeof(indicate_data); ++i)
                        // {
                        //     indicate_data[i] = i % 0xff;
                        // }
李俭双's avatar
李俭双 committed
770

771 772
                        // // if want to change the value in server database, call:
                        // // esp_ble_gatts_set_attr_value(heart_rate_handle_table[IDX_CHAR_VAL_2A25], sizeof(indicate_data), indicate_data);
李俭双's avatar
李俭双 committed
773 774


775 776 777
                        // //the size of indicate_data[] need less than MTU size
                        // esp_ble_gatts_send_indicate(gatts_if, param->write.conn_id, heart_rate_handle_table2[IDX_CHAR_CFG_A2],
                        //                     sizeof(indicate_data), indicate_data, true);
李俭双's avatar
李俭双 committed
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
                    }
                    else if (descr_value == 0x0000){
                        ESP_LOGI(GATTS_TABLE_TAG, "notify/indicate disable ");
                    }else{
                        ESP_LOGE(GATTS_TABLE_TAG, "unknown descr value");
                        esp_log_buffer_hex(GATTS_TABLE_TAG, param->write.value, param->write.len);
                    }

                }
                /* send response when param->write.need_rsp is true*/
                if (param->write.need_rsp){
                    esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, NULL);
                }
            }else{
                /* handle prepare write */
                example_prepare_write_event_env(gatts_if, &prepare_write_env, param);
            }
      	    break;
        case ESP_GATTS_EXEC_WRITE_EVT:
            // the length of gattc prepare write data must be less than GATTS_DEMO_CHAR_VAL_LEN_MAX.
            ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_EXEC_WRITE_EVT");
            example_exec_write_event_env(&prepare_write_env, param);
            break;
        case ESP_GATTS_MTU_EVT:
            ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_MTU_EVT, MTU %d", param->mtu.mtu);
            break;
        case ESP_GATTS_CONF_EVT:
            ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_CONF_EVT, status = %d, attr_handle %d", param->conf.status, param->conf.handle);
            break;
        case ESP_GATTS_START_EVT:
薛小虎's avatar
薛小虎 committed
808 809 810 811 812 813 814 815 816 817
            if(create_tab1 == false) {
                ESP_LOGI(GATTS_TABLE_TAG, "SERVICE_START_EVT1, status %d, service_handle %d", param->start.status, param->start.service_handle);
                esp_err_t create_attr_ret1 = esp_ble_gatts_create_attr_tab(gatt_db2, gatts_if, HRS_IDX_NB2, SVC_INST_ID1);
                if (create_attr_ret1){
                    ESP_LOGE(GATTS_TABLE_TAG, "create attr table2 failed, error code = %x", create_attr_ret1);
                }
                create_tab1 = true;
            } else {
                ESP_LOGI(GATTS_TABLE_TAG, "SERVICE_START_EVT2, status %d, service_handle %d", param->start.status, param->start.service_handle);
            }
李俭双's avatar
李俭双 committed
818 819
            break;
        case ESP_GATTS_CONNECT_EVT:
820 821

            Ble_Connect_Event_Pro();
李俭双's avatar
李俭双 committed
822 823 824 825 826 827 828 829 830 831 832
            ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_CONNECT_EVT, conn_id = %d", param->connect.conn_id);
            esp_log_buffer_hex(GATTS_TABLE_TAG, param->connect.remote_bda, 6);
            esp_ble_conn_update_params_t conn_params = {0};
            memcpy(conn_params.bda, param->connect.remote_bda, sizeof(esp_bd_addr_t));
            /* For the iOS system, please refer to Apple official documents about the BLE connection parameters restrictions. */
            conn_params.latency = 0;
            conn_params.max_int = 0x20;    // max_int = 0x20*1.25ms = 40ms
            conn_params.min_int = 0x10;    // min_int = 0x10*1.25ms = 20ms
            conn_params.timeout = 400;    // timeout = 400*10ms = 4000ms
            //start sent the update connection parameters to the peer device.
            esp_ble_gap_update_conn_params(&conn_params);
833

李俭双's avatar
李俭双 committed
834 835
            break;
        case ESP_GATTS_DISCONNECT_EVT:
836 837

            Ble_DisConnect_Event_Pro();
李俭双's avatar
李俭双 committed
838 839
            ESP_LOGI(GATTS_TABLE_TAG, "ESP_GATTS_DISCONNECT_EVT, reason = 0x%x", param->disconnect.reason);
            esp_ble_gap_start_advertising(&adv_params);
840

李俭双's avatar
李俭双 committed
841 842
            break;
        case ESP_GATTS_CREAT_ATTR_TAB_EVT:{
薛小虎's avatar
薛小虎 committed
843 844 845 846 847 848 849 850 851 852 853 854 855
            if(create_tab1 == false) {
                if (param->add_attr_tab.status != ESP_GATT_OK){
                    ESP_LOGE(GATTS_TABLE_TAG, "create attribute table failed, error code=0x%x", param->add_attr_tab.status);
                }
                else if (param->add_attr_tab.num_handle != HRS_IDX_NB){
                    ESP_LOGE(GATTS_TABLE_TAG, "create attribute table abnormally, num_handle (%d) \
                            doesn't equal to HRS_IDX_NB(%d)", param->add_attr_tab.num_handle, HRS_IDX_NB);
                }
                else {
                    ESP_LOGI(GATTS_TABLE_TAG, "create attribute table successfully, the number handle = %d\n",param->add_attr_tab.num_handle);
                    memcpy(heart_rate_handle_table, param->add_attr_tab.handles, sizeof(heart_rate_handle_table));
                    esp_ble_gatts_start_service(heart_rate_handle_table[IDX_SVC]);

856 857 858 859
                    // for(int ii = 0; ii<4; ii++)
                    // {
                    //     printf("heart_rate_handle_table[%d] = %d\r\n", ii, heart_rate_handle_table[ii]);
                    // }
薛小虎's avatar
薛小虎 committed
860 861 862 863 864 865 866 867 868 869 870 871 872 873
                }
            } else {
                if (param->add_attr_tab.status != ESP_GATT_OK){
                    ESP_LOGE(GATTS_TABLE_TAG, "create attribute table failed, error code=0x%x", param->add_attr_tab.status);
                }
                else if (param->add_attr_tab.num_handle != HRS_IDX_NB2){
                    ESP_LOGE(GATTS_TABLE_TAG, "create attribute table abnormally, num_handle (%d) \
                            doesn't equal to HRS_IDX_NB(%d)", param->add_attr_tab.num_handle, HRS_IDX_NB2);
                }
                else {
                    ESP_LOGI(GATTS_TABLE_TAG, "create attribute table successfully, the number handle = %d\n",param->add_attr_tab.num_handle);
                    memcpy(heart_rate_handle_table2, param->add_attr_tab.handles, sizeof(heart_rate_handle_table2));
                    esp_ble_gatts_start_service(heart_rate_handle_table2[IDX_SVC2]);

874 875 876 877
                    // for(int ii = 0; ii<4; ii++)
                    // {
                    //     printf("heart_rate_handle_table2[%d] = %d\r\n", ii, heart_rate_handle_table2[ii]);
                    // }
薛小虎's avatar
薛小虎 committed
878
                }  
李俭双's avatar
李俭双 committed
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
            }
            break;
        }
        case ESP_GATTS_STOP_EVT:
        case ESP_GATTS_OPEN_EVT:
        case ESP_GATTS_CANCEL_OPEN_EVT:
        case ESP_GATTS_CLOSE_EVT:
        case ESP_GATTS_LISTEN_EVT:
        case ESP_GATTS_CONGEST_EVT:
        case ESP_GATTS_UNREG_EVT:
        case ESP_GATTS_DELETE_EVT:
        default:
            break;
    }
}


static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{

    /* 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) {
            heart_rate_profile_tab[PROFILE_APP_IDX].gatts_if = gatts_if;
        } else {
            ESP_LOGE(GATTS_TABLE_TAG, "reg app failed, app_id %04x, status %d",
                    param->reg.app_id,
                    param->reg.status);
            return;
        }
    }
    do {
        int idx;
        for (idx = 0; idx < PROFILE_NUM; idx++) {
            /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
            if (gatts_if == ESP_GATT_IF_NONE || gatts_if == heart_rate_profile_tab[idx].gatts_if) {
                if (heart_rate_profile_tab[idx].gatts_cb) {
                    heart_rate_profile_tab[idx].gatts_cb(event, gatts_if, param);
                }
            }
        }
    } while (0);
}

薛小虎's avatar
薛小虎 committed
923 924


李俭双's avatar
李俭双 committed
925 926 927 928 929 930
void Get_Mac_Init(void )
{
    uint8_t ble_mac[10] = {0};
    char temp[10] = {0};
    char temp1[20] = {0};
    esp_read_mac(ble_mac, ESP_MAC_BT);
931
  //  printf("%d\n",temp);
李俭双's avatar
李俭双 committed
932

933 934 935 936 937 938 939 940 941 942 943 944 945 946
  //  sprintf(temp, "%02X%02X", ble_mac[4], ble_mac[5]);
    int g;
    for(g=0;g<6;g++)
    {
        srand ((int)ble_mac[g]);
        if(g == 0)
        {
            temp[g] = (char)rand()%5;
        }
        else
        {
            temp[g] = (char)rand()%10;
            temp[g] += 48;
        }
chen's avatar
chen committed
947
     //   printf("%d  ",temp[g]);
948 949 950
       // printf("%d\n",);
    //printf("%d  ",ble_mac[g]);
    }
chen's avatar
chen committed
951
 //   printf("\n");
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
    if(temp[0] == 0)
    {
        temp[0] += 69;
    }
    else if(temp[0] == 1)
    {
        temp[0] = 70;
    }
    else if(temp[0] == 2)
    {
        temp[0] = 72;
    }
    else if(temp[0] == 3)
    {
        temp[0] = 73;
    }
    else if(temp[0] == 4)
    {
        temp[0] = 85;
    }
   // srand (ble_mac[0]);

    raw_adv_data[sizeof(raw_adv_data) - 6] = temp[0];
    raw_adv_data[sizeof(raw_adv_data) - 5] = temp[1];
    raw_adv_data[sizeof(raw_adv_data) - 4] = temp[2];
    raw_adv_data[sizeof(raw_adv_data) - 3] = temp[3];
    raw_adv_data[sizeof(raw_adv_data) - 2] = temp[4];
    raw_adv_data[sizeof(raw_adv_data) - 1] = temp[5];
李俭双's avatar
李俭双 committed
980 981 982
    // ESP_LOGW(GATTS_TABLE_TAG, "BLE_MAC IS %s : ",
    //                 &raw_adv_data[11]);
    // ESP_LOGW(GATTS_TABLE_TAG, "BLE_MAC IS %s : ",
983 984
    //                 temp);      

985
    // printf("My MAC:\n");
986
    esp_log_buffer_hex(GATTS_TABLE_TAG, ble_mac, 6);          
李俭双's avatar
李俭双 committed
987

988 989 990 991 992 993 994
    BT_Device_Name[sizeof(BT_Device_Name) - 14] = temp[0];
    BT_Device_Name[sizeof(BT_Device_Name) - 13] = temp[1];
    BT_Device_Name[sizeof(BT_Device_Name) - 12] = temp[2];
    BT_Device_Name[sizeof(BT_Device_Name) - 11] = temp[3];
    BT_Device_Name[sizeof(BT_Device_Name) - 10] = temp[4];
    BT_Device_Name[sizeof(BT_Device_Name) - 9] = temp[5];
    
李俭双's avatar
李俭双 committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    raw_adv_data[11] = ble_mac[0];
    raw_adv_data[12] = ble_mac[1];
    raw_adv_data[13] = ble_mac[2];
    raw_adv_data[14] = ble_mac[3];
    raw_adv_data[15] = ble_mac[4];
    raw_adv_data[16] = ble_mac[5];

    sprintf(temp1, "%02X%02X%02X%02X%02X%02X", ble_mac[0], ble_mac[1], ble_mac[2], ble_mac[3], ble_mac[4], ble_mac[5]);


    for(int i=0; i<12; i++)
    {
        char_value[i] = temp1[i];
    }
}

王金亮's avatar
王金亮 committed
1011

1012
void bsp_Ble_Init(void)
李俭双's avatar
李俭双 committed
1013 1014 1015
{
    esp_err_t ret;

1016 1017
    // Get_Mac_Init();

李俭双's avatar
李俭双 committed
1018 1019

    /* Initialize NVS. */
薛小虎's avatar
薛小虎 committed
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    // 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(GATTS_TABLE_TAG, "%s enable controller failed: %s", __func__, esp_err_to_name(ret));
    //     return;
    // }

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

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

    // ret = esp_bluedroid_enable();
    // if (ret) {
    //     ESP_LOGE(GATTS_TABLE_TAG, "%s enable bluetooth failed: %s", __func__, esp_err_to_name(ret));
    //     return;
    // }
李俭双's avatar
李俭双 committed
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

    ret = esp_ble_gatts_register_callback(gatts_event_handler);
    if (ret){
        ESP_LOGE(GATTS_TABLE_TAG, "gatts register error, error code = %x", ret);
        return;
    }

    ret = esp_ble_gap_register_callback(gap_event_handler);
    if (ret){
        ESP_LOGE(GATTS_TABLE_TAG, "gap register error, error code = %x", ret);
        return;
    }

    ret = esp_ble_gatts_app_register(ESP_APP_ID);
    if (ret){
        ESP_LOGE(GATTS_TABLE_TAG, "gatts app register error, error code = %x", ret);
        return;
    }

薛小虎's avatar
薛小虎 committed
1072

李俭双's avatar
李俭双 committed
1073 1074 1075 1076 1077 1078
    esp_err_t local_mtu_ret = esp_ble_gatt_set_local_mtu(500);
    if (local_mtu_ret){
        ESP_LOGE(GATTS_TABLE_TAG, "set local  MTU failed, error code = %x", local_mtu_ret);
    }


1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    // /* set the security iocap & auth_req & key size & init key response key parameters to the stack*/
    // esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND;     //bonding with peer device after authentication
    // esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE;           //set the IO capability to No output No input
    // uint8_t key_size = 16;      //the key size should be 7~16 bytes
    // uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
    // uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
    // uint8_t oob_support = ESP_BLE_OOB_DISABLE;
    // esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_OOB_SUPPORT, &oob_support, sizeof(uint8_t));
    // /* If your BLE device act as a Slave, the init_key means you hope which types of key of the master should distribute to you,
    // and the response key means which key you can distribute to the Master;
    // If your BLE device act as a master, the response key means you hope which types of key of the slave should distribute to you,
    // and the init key means which key you can distribute to the slave. */
    // esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t));
    // esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t));





    /* set the security iocap & auth_req & key size & init key response key parameters to the stack*/
薛小虎's avatar
薛小虎 committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    // esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND;     //bonding with peer device after authentication
    // esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE;           //set the IO capability to No output No input
    // uint8_t key_size = 16;      //the key size should be 7~16 bytes
    // uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
    // uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;
    // //set static passkey
    // uint32_t passkey = 123456;
    // uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE;
    // uint8_t oob_support = ESP_BLE_OOB_DISABLE;
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_OOB_SUPPORT, &oob_support, sizeof(uint8_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
    // /* If your BLE device acts as a Slave, the init_key means you hope which types of key of the master should distribute to you,
    // and the response key means which key you can distribute to the master;
    // If your BLE device acts as a master, the response key means you hope which types of key of the slave should distribute to you,
    // and the init key means which key you can distribute to the slave. */
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
    // ret = esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t));
    // if(ret)
    // {
    //     printf("!!!!!!!!!!!!!!\r\n");
    // }
李俭双's avatar
李俭双 committed
1155
}