蓝牙测试gatt_clinet esp32作为主机和从机dialog通讯NUS

原始dialog图像

描述一下 当前现在esp主机的错误 

去写

    case ESP_GATTC_WRITE_DESCR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "write descr failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGI(GATTC_TAG, "write descr success-----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,//就是随便搞点东西写过去 这个数组就是123.。。
                                  ESP_GATT_WRITE_TYPE_RSP,
                                  ESP_GATT_AUTH_REQ_NONE);
        break;

从机dialog的返回

       case ESP_GATTC_WRITE_CHAR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "acked ----311--write char failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGI(GATTC_TAG, "write char success ");
        break;

现在LOG显示写错误

看上面的截图 我没有写的权限 我把从机放开一点即可

修改代码113行 增加2个

            [SVC1_IDX_TX_CTRL_VAL]           = {SVC1_TX_CTRL_UUID_128, ATT_UUID_128_LEN, PERM(WR, ENABLE) | PERM(WRITE_REQ, ENABLE) |PERM(RD, ENABLE) | PERM(NTF, ENABLE),
                                            DEF_SVC1_TX_CTRL_CHAR_LEN, 0, NULL},

现在的效果

此时问题解决了 没有ESP的错误log 写对了!!

后面是使能以后从机一直在ack一点东西

 esp32代码

/*
   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/



/****************************************************************************
*
* 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 "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"

#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 PROFILE_NUM      1
#define PROFILE_A_APP_ID 0
#define INVALID_HANDLE   0

static const char remote_device_name[] = "GKOSON";//"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 = {
    .len = ESP_UUID_LEN_128,
    .uuid = {.uuid128 = REMOTE_NOTIFY_CHAR_UUID,},
};

static esp_bt_uuid_t notify_descr_uuid = {
    .len = ESP_UUID_LEN_16,
    .uuid = {.uuid16 = 0x2902,},//手机APP确认 就是使能的它
};

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

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

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

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_LOGI(GATTC_TAG, "REG_EVT");
        esp_err_t scan_ret = esp_ble_gap_set_scan_params(&ble_scan_params);
        if (scan_ret){
            ESP_LOGE(GATTC_TAG, "set scan params error, error code = %x", scan_ret);
        }
        break;
    case ESP_GATTC_CONNECT_EVT:{
        ESP_LOGI(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_LOGI(GATTC_TAG, "REMOTE BDA:");
        esp_log_buffer_hex(GATTC_TAG, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, sizeof(esp_bd_addr_t));
        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);
        }
        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(GATTC_TAG, "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);
      //  https://blog.csdn.net/qq619203312/article/details/116269292
       // esp_ble_gattc_search_service(gattc_if, param->cfg_mtu.conn_id, NULL);
        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_LOGI(GATTC_TAG, "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_LOGI(GATTC_TAG, "SEARCH RES: conn_id = %x is primary service %d", p_data->search_res.conn_id, p_data->search_res.is_primary);
        ESP_LOGI(GATTC_TAG, "start handle %d end handle %d current handle value %d", p_data->search_res.start_handle, p_data->search_res.end_handle, p_data->search_res.srvc_id.inst_id);
        //if (p_data->search_res.srvc_id.uuid.len == ESP_UUID_LEN_16 && p_data->search_res.srvc_id.uuid.uuid.uuid16 == REMOTE_SERVICE_UUID) {
        if (p_data->search_res.srvc_id.uuid.len == ESP_UUID_LEN_128) {
            ESP_LOGI(GATTC_TAG, "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_LOGI(GATTC_TAG, "UUID16: %x", p_data->search_res.srvc_id.uuid.uuid.uuid16);
        }
        break;
    }
    case ESP_GATTC_SEARCH_CMPL_EVT:
        if (p_data->search_cmpl.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "search service failed, error status = %x", p_data->search_cmpl.status);
            break;
        }
        if(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_LOGI(GATTC_TAG, "ESP_GATTC_SEARCH_CMPL_EVT %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");
            }

            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_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);
                    }
                }
                /* free char_elem_result */
                free(char_elem_result);
            }else{
                ESP_LOGE(GATTC_TAG, "no char found");
            }
        }
         break;
    case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
        ESP_LOGI(GATTC_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");
            }
            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(GATTC_TAG, "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
                    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,
                                                                     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_LOGE(GATTC_TAG, "esp_ble_gattc_write_char_descr ok-----------"); 
                    /* free descr_elem_result */
                    free(descr_elem_result);
                }
            }
            else{
                ESP_LOGE(GATTC_TAG, "decsr not found");
            }

        }
        break;
    }
    case ESP_GATTC_NOTIFY_EVT:
        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:");
        }
        esp_log_buffer_hex(GATTC_TAG, p_data->notify.value, p_data->notify.value_len);
        break;
    case ESP_GATTC_WRITE_DESCR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(GATTC_TAG, "write descr failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGI(GATTC_TAG, "write descr success-----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);
        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(GATTC_TAG, "acked ----311--write char failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGI(GATTC_TAG, "write char success ");
        break;
    case ESP_GATTC_DISCONNECT_EVT:
        connect = false;
        get_server = false;
        ESP_LOGI(GATTC_TAG, "ESP_GATTC_DISCONNECT_EVT, reason = %d", p_data->disconnect.reason);
        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_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_LOGI(GATTC_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:
            esp_log_buffer_hex(GATTC_TAG, scan_result->scan_rst.bda, 6);
            ESP_LOGI(GATTC_TAG, "searched Adv Data Len %d, Scan Response Len %d", scan_result->scan_rst.adv_data_len, scan_result->scan_rst.scan_rsp_len);
            adv_name = esp_ble_resolve_adv_data(scan_result->scan_rst.ble_adv,
                                                ESP_BLE_AD_TYPE_NAME_CMPL, &adv_name_len);
            ESP_LOGI(GATTC_TAG, "searched Device Name Len %d", adv_name_len);
            esp_log_buffer_char(GATTC_TAG, adv_name, adv_name_len);

#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
            ESP_LOGI(GATTC_TAG, "\n");

            if (adv_name != NULL) {
                if (strlen(remote_device_name) == adv_name_len && strncmp((char *)adv_name, remote_device_name, adv_name_len) == 0) {
                    ESP_LOGI(GATTC_TAG, "searched device %s\n", remote_device_name);
                    if (connect == false) {
                        connect = true;
                        ESP_LOGI(GATTC_TAG, "connect to the remote device.");
                        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:
            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 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);
    }

}

dialog代码

//*****************************************************************************
//
//! @file main.c
//!
//! @brief Main application file.
//!
//*****************************************************************************

/******************************************************************************
 *** INCLUDE FILES
 *****************************************************************************/
 #include "arch_console.h"
#include "main.h"
#include "rwip_config.h"            //SW configuration
#include "user_periph_setup.h"
#include "user_custs1_def.h"
#include "app_api.h"
#include "battery.h"
#include "gap.h"
#include "prf_utils.h"
#include "rtc.h"
#include "uart.h"
#include "uart_utils.h"
#include "wkupct_quadec.h"
#include "hash.h"
#include "hw_otpc.h"
#include "otp_hdr.h"
#include "otp_cs.h"
#include "rf_531.h"

/** mCube functions includes. */
#include "m_drv_mc36xx.h"
#include "mysentech_temp.h"
#include "mc_fac.h"
#include "mc_led.h"
#include "timer1.h"
#include "crc16.h"

/******************************************************************************
 *** CONFIGURATION
 *****************************************************************************/
#define DEBUG_MODE                      1       //Output UART debug log
#define LED_TEST                        0       //Only works when DISABLE_TOOL is 1
#define FAKE_ENVTEMP                    1      
#define ONCE_DONE                       1  
#define DIALOG_SEND_FIRST               1
static uint16_t txcount=0;
static char count=0;
#define CAS_ENABLE 1
#if CAS_ENABLE
#include "m_lib_CAS_main.h"
extern app_CAS_Data_Read_t *CAS_data;
int16_t SensotData_Acc[3];
#endif
#define TEMP_ENABLE                     1       //Enable or disable temp sensor
#define TEMP_AVERAGE_TIMES              5

/******************************************************************************
 *** DEFINITION
 *****************************************************************************/
#define RUN_TIME_CYC                    4       //4 * 25 = 100Hz
#define MAX_CYC                         15//30//120 对应 Seconds 2min  同理 10min-600 但是硬件TIMER放弃了 我要缩小4倍
//#define MAX_CYC                        150  //10min
#define SYNC_TIME                      60
#define SYNC_CYC                       (SYNC_TIME*RUN_TIME_CYC)      //Seconds, should be less than MAX_CYC
#define TEMP_CYC                       (MAX_CYC*RUN_TIME_CYC/TEMP_AVERAGE_TIMES) // 5 times
#define WAL_ALGO_CYC                   (60 * RUN_TIME_CYC)
#define ACT_DEBOUNCE_NUM                10      //Check 10 seconds result

// Timer1 settings
#define T1_COUNT                        2       //125 ms * N

#define PACK_MAX_AMOUNT                 5
#define PACK_HEADER_LEN                 11
#define PACK_LEN                        37
#define PACK_WITH_CRC_LEN               39//(PACK_LEN + 2)
//#define PACK_WITH_CRC_VERIFY_LEN        (PACK_WITH_CRC_LEN + 3)
#define SYS_VERSION_LEN                 4
#define FLASH_BUFFER_SIZE               (PACK_HEADER_LEN + PACK_WITH_CRC_LEN * PACK_MAX_AMOUNT + 4)
#define FLASH_OFFSET                    SPI_FLASH_SECTOR_SIZE
#define ADDR_START                      0xC000      //after 44k byte (11 sectors <4k bytes>)
#define ADDR_END                        0x1FF000    //end of flash  (2M size - leave last 4KB for safety)
//#define ADDR_END                      0xE000
typedef enum {
    STATE_HISTORY, 
    STATE_PRODUCT,       
    STATE_ADVCE,   
    STATE_SEND, 
    STATE_WAIT_ACK,
    STATE_DISCON,    
    STATE_DONE,  
} KOSON_SYS_STATE;
KOSON_SYS_STATE kstate = STATE_HISTORY;
char input[2]__attribute__((section("retention_mem_area0"), zero_init));

#define CAS_SUM 1
#if CAS_SUM
int oncecasdata[4][25]={0};
static int sum_ave(int *a,char len)
{
    double sum=0;
    for(char i=0;i<len;i++)
      sum+=a[i];
    return sum/len;
}
#endif
/******************************************************************************
 *** VARIABLES
 *****************************************************************************/
/** Motion output buffer structure */
typedef struct
{
    uint16_t  time_diff;
    uint16_t  count;
    uint16_t  duration;
} motion_output_t;

#define KOSONLOG 1

#define MIN(a,b) ((a)<(b))?(a):(b)

#define LEN 10
typedef struct
{
    char     len;
    uint8_t  data[LEN];
} cannot_logout_count;
cannot_logout_count mlogout[3] __attribute__((section("retention_mem_area0"), zero_init)); //@RETENTION MEMORY

static uint8_t ble_mac_addr[6];
static uint8_t nusdata_buf[FLASH_BUFFER_SIZE];
static uint8_t nusdata_buf_len=0;

#if TEMP_ENABLE
static int16_t env_temp_array[TEMP_AVERAGE_TIMES];
static int16_t body_temp_array[TEMP_AVERAGE_TIMES];
#endif
static uint32_t flash_wr_addr     = ADDR_START;
static uint32_t flash_rd_addr     = ADDR_START;
static uint32_t flash_rd_addr_tmp = ADDR_START;
static uint8_t pack_sync_amount   = 0;

uint16_t cyc_counter = 0;                   //100 Hz = 10Hz * 10samples
uint32_t sys_version;
int16_t RawData[M_DRV_MC36XX_FIFO_DEPTH][M_DRV_MC36XX_AXES_NUM];

struct custs1_val_ntf_ind_req *req;

// Configuration struct for SPI FLASH
static const spi_flash_cfg_t spi_flash_cfg = {
    .chip_size = SPI_FLASH_DEV_SIZE,
};

void enable_flash(void);
void enable_accel(uint16_t speed);

/******************************************************************************
 *** MARCOS
 *****************************************************************************/
#define BCD_TO_YEAR(date_bcd)   (((date_bcd & RTC_CAL_Y_T) >> 20) * 10) + ((date_bcd & RTC_CAL_Y_U) >> 16)
#define BCD_TO_MONTH(date_bcd)  (((date_bcd & RTC_CAL_M_T) >> 7) * 10) + ((date_bcd & RTC_CAL_M_U) >> 3)
#define BCD_TO_DAY(date_bcd)    (((date_bcd & RTC_CAL_D_T) >> 12) * 10) + ((date_bcd & RTC_CAL_D_U) >> 8)
#define BCD_TO_HOUR(time_bcd)   (((time_bcd & RTC_TIME_HR_T) >> 28) * 10) + ((time_bcd & RTC_TIME_HR_U) >> 24)
#define BCD_TO_MIN(time_bcd)    (((time_bcd & RTC_TIME_M_T) >> 20) * 10) + ((time_bcd & RTC_TIME_M_U) >> 16)
#define BCD_TO_SEC(time_bcd)    (((time_bcd & RTC_TIME_S_T) >> 12) * 10) + ((time_bcd & RTC_TIME_S_U) >> 8)

#define CODE  1
#define MACTIME  0
#if MACTIME
int macTime[5]={0};
#endif
uint8_t mycode;
#if DEBUG_MODE


#define SHOWME mc_debug("\r\n[--------- %s -------%d--------]\r\n",__FUNCTION__,__LINE__)
#define mc_debug(...)       do {                                            \
                            mcube_printf(__VA_ARGS__);                      \
                            } while (0);
#define mc_debug_num(dec)   do {                                            \
                            mcube_num_printf(dec);                          \
                            } while (0);
#define mc_debug_byte(ch) do {                                            \
                            mcube_ch_printf(ch);                            \
                            } while (0);
#define mc_debug_4hex(hex)                                              \
                            do {                                            \
                            mcube_4hex_printf(hex);                         \
                            } while (0);


void showarry(char *name,uint8_t *data,int len,char bt)
{
    //if(name[0]!='v')return;
    if(name) mc_debug("\r\n%s:%d>%d>\r\n",name,len,bt);
    
    uint8_t *datahead=data;
    datahead -= sizeof(uint8_t);
  
    for(int i=1;i<len+1;i++)
    {
        mc_debug("%02X-",datahead[i]);
        if(i%(bt)==0) 
            mc_debug("\r\n");            
    }
    mc_debug("\r\n");
}

typedef union 
{
    struct 
    {
      uint8_t    isflashreading:1; 
      uint8_t    istimesynced:1;
      uint8_t    havepagetoerase:1;
      uint8_t    f4:4;
    } sonflag;
    uint8_t allflag;
}_gflag;
//static
    _gflag gflag ;//__attribute__((section("retention_mem_area0"), zero_init)); //@RETENTION MEMORY
void flag_clear_all(void){gflag.allflag=0;};
void flag_set_havepagetoerase(void){gflag.sonflag.havepagetoerase=1;};
void flag_clear_havepagetoerase(void){gflag.sonflag.havepagetoerase=0;};
char flag_get_havepagetoerase(void){ return gflag.sonflag.havepagetoerase;};
#define flag_get_isflashreading()   gflag.sonflag.isflashreading
#define flag_set_isflashreading()   gflag.sonflag.isflashreading=1;
#define flag_clear_isflashreading() gflag.sonflag.isflashreading=0;
void showflag(void)
{
    mc_debug("\r\nFLAG KING>add=0X%08X gflag=0X%02X:: \
    istimesynced=%d havepagetoerase=%d isflashreading=%d\r\n",\
    &gflag,gflag.allflag,gflag.sonflag.istimesynced,gflag.sonflag.havepagetoerase,flag_get_isflashreading());
}

#else
#define mc_debug(...)
#define mc_debug_num(...)
#define mc_debug_byte(...)
#define mc_debug_4hex(...)
#endif

/******************************************************************************
 *** FUNCTION DEFINITIONS
 *****************************************************************************/

/**
 * @brief Get the version.
 * @return 32 bits value it includes
 *         AlGORITHM_MAJOR(4bits).MINOR(4bits).BUILD(4bits).Reserve(4bits).
 *         INTERFACE_MAJOR(4bits).MINOR(4bits).BUILD(4bits).Reserve(4bits).
 */
uint32_t mc_get_version(void)
{
    return((((uint32_t)VERSION_AlGORITHM_MAJOR) << 28) |
           (((uint32_t)VERSION_AlGORITHM_MINOR) << 24) |
           (((uint32_t)VERSION_AlGORITHM_BUILD) << 20) |
           (((uint32_t)VERSION_INTERFACE_MAJOR) << 12) |
           (((uint32_t)VERSION_INTERFACE_MINOR) << 8) |
           (((uint32_t)VERSION_INTERFACE_BUILD) << 4));
}


void enable_flash(void)
{
    // Configuration struct for SPI
    spi_cfg_t flash_spi_cfg = {
        .spi_ms = SPI_MS_MODE,
        .spi_cp = SPI_CP_MODE,
        .spi_speed = SPI_SPEED_MODE,
        .spi_wsz = SPI_WSZ,
        .spi_cs = SPI_CS,
        .cs_pad.port = SPI_FL_PORT,
        .cs_pad.pin = SPI_FL_PIN,
#if defined (__DA14531__)
        .spi_capture = SPI_EDGE_CAPTURE,
#endif
#if defined (CFG_SPI_DMA_SUPPORT)
        .spi_dma_channel = SPI_DMA_CHANNEL_01,
        .spi_dma_priority = DMA_PRIO_0,
#endif
        };
    spi_initialize(&flash_spi_cfg);

    // Configure SPI Flash environment
    spi_flash_configure_env(&spi_flash_cfg);
}


void enable_accel(uint16_t speed)
{
    // Configuration struct for SPI
    spi_cfg_t acc_spi_cfg = {
        .spi_ms = SPI_MS_MODE_MASTER,
        .spi_cp = SPI_CP_MODE_3,
        .spi_speed = (SPI_SPEED_MODE_CFG)speed,
        .spi_wsz = SPI_MODE_16BIT,
        .spi_cs = SPI_CS_1,
        .cs_pad.port = SPI_EN_PORT,
        .cs_pad.pin = SPI_EN_PIN,
#if defined (__DA14531__)
        .spi_capture = SPI_EDGE_CAPTURE,
#endif
#if defined (CFG_SPI_DMA_SUPPORT)
        .spi_dma_channel = SPI_DMA_CHANNEL_01,
        .spi_dma_priority = DMA_PRIO_0,
#endif
    };
    spi_initialize(&acc_spi_cfg);
}


/******************************************************************************
 *** RELATED FUNCTIONS
 *****************************************************************************/
void spi_erase_page(void)
{
    SHOWME
    mc_debug("spi_erase_page:0X%0X\r\n",flash_wr_addr);
    enable_flash();

    spi_flash_release_from_power_down();

    spi_cs_low();
    spi_cs_high();

    spi_flash_block_erase(flash_wr_addr, SPI_FLASH_OP_SE);

    spi_flash_power_down();
}


int8_t spi_read_buf(uint8_t * rd_buf, uint16_t size)
{
    uint32_t actual_size;
    uint32_t address = flash_rd_addr;
    enable_flash();

    spi_flash_release_from_power_down();

    spi_cs_low();
    spi_cs_high();

    int8_t err = spi_flash_read_data_buffer(rd_buf, address, size, &actual_size);

    mc_debug("\n\rRead ");
    mc_debug_num(actual_size);
    mc_debug(" Addr ");
    mc_debug_4hex(address);
    mc_debug(" Err ");
    mc_debug_num(err);

    spi_flash_power_down();
    return err;
}

int8_t spi_erase_write_page(uint8_t * wr_buf,  uint8_t size)
{
    uint32_t address = flash_wr_addr;
    int8_t err =0;
//暂时不要了
    showarry("wr_buf",     wr_buf,     size, size); 
#if CODE 
    for(char i=0;i<size;i++)
       wr_buf[i]^=BTCODE[0];//mycode;//macTime[1];
#endif
    
    mc_debug("spi_write_page:0X%0X\r\n",flash_wr_addr);
    showarry("wr_buf",     wr_buf,     size, size);  

    enable_flash();
    spi_flash_release_from_power_down();
    spi_flash_wait_till_ready();

    err = spi_flash_page_program_buffer(wr_buf, address, size);

    if(err != 0){
        mc_debug("\n\rWrite err %d\r\n",err);
        return err;
    }
    spi_flash_power_down();
    
#if 0   
//测试读一下
uint32_t actual_size=0;
uint8_t temp_buf[PACK_WITH_CRC_LEN]={0};
int8_t status;
enable_flash();
spi_flash_release_from_power_down();
spi_cs_low();
spi_cs_high();
memset(temp_buf, 0, sizeof(temp_buf));
spi_flash_wait_till_ready();
status=spi_flash_read_data_buffer(temp_buf, address, sizeof(temp_buf), &actual_size);
spi_flash_power_down();
showarry("rd_buf",     temp_buf,     actual_size, actual_size);
if(status != 0){
    mc_debug("\n\rd_buf err %d\r\n",err);
    return err;
}
#endif
return err;
}

void gflash_erase_page(void)
{
    if(ADDR_END == flash_wr_addr){flash_wr_addr = ADDR_START;mc_debug("\r\n BACK flash_wr_addr\r\n");}
    spi_erase_page();
};

void gflash_write_page(uint8_t * wr_buf,  uint8_t size)
{
   spi_erase_write_page(wr_buf,size);//写一个page 数组在 SPI_FLASH_PAGE_SIZE 以内
   flash_wr_addr += SPI_FLASH_PAGE_SIZE;//写地址直接增加
   if(0==flash_wr_addr%SPI_FLASH_SECTOR_SIZE)//做一个逻辑 看看是否需要擦除下一页
   {
      mc_debug("\n\rgflash_write_page jump flash_wr_addr=0x%X\r\n",flash_wr_addr);
      //测试假数据就不要 擦除了 因为我只有一个页面 这个擦后面不能读了 
      gflash_erase_page();
   }
};
#if 1 //这里面读了 单数读失败!!!!
//目的是读数据到全部的buf里面
int8_t gflash_read_buf_tx(void)
{
    uint32_t actual_size=0,flag=0;
    uint8_t temp_buf[PACK_WITH_CRC_LEN]={0};
    int8_t status;
    enable_flash();
    spi_flash_release_from_power_down();
    spi_cs_low();
    spi_cs_high();
//开始读取
//flash_rd_addr_tmp == flash_wr_addr 表示生产的数据全部读出来了
//pack_sync_amount == PACK_MAX_AMOUNT 表示生产的数据我已经竭尽所能读了 可能还有数据 但是我读到不能在读了
//没有必要进去 while包含了if的含义
    flash_rd_addr_tmp = flash_rd_addr;
    while(flash_rd_addr_tmp != flash_wr_addr && pack_sync_amount < PACK_MAX_AMOUNT){
        flag=1;
        memset(temp_buf, 0, sizeof(temp_buf));
        //读取一次
        do{
            spi_flash_wait_till_ready();
            status=spi_flash_read_data_buffer(temp_buf, flash_rd_addr_tmp, sizeof(temp_buf), &actual_size);
            mc_debug("read address %x actual_size=%d status=%x\r\n",flash_rd_addr_tmp,actual_size,status);
        }while(status!=SPI_FLASH_ERR_OK);
        //读出来以后的处理
        memcpy(&nusdata_buf[PACK_HEADER_LEN + pack_sync_amount * PACK_WITH_CRC_LEN],temp_buf,PACK_WITH_CRC_LEN);
        pack_sync_amount++; 
        flash_rd_addr_tmp+=SPI_FLASH_PAGE_SIZE;

        if(ADDR_END == flash_rd_addr_tmp){flash_rd_addr_tmp = ADDR_START;mc_debug("BACK flash_rd_addr_tmp\r\n");}//增加循环逻辑 
    }
     spi_flash_power_down();
     mc_debug("while beark reason: flash_rd_addr_tmp=%x,flash_wr_addr=%x,pack_sync_amount=%d\r\n",flash_rd_addr_tmp,flash_wr_addr,pack_sync_amount);

     return 0;
}
#else //这里没有读 百分比成功
//目的是读数据到全部的buf里面
int8_t gflash_read_buf_tx(void)
{
    while(flash_rd_addr_tmp != flash_wr_addr && pack_sync_amount < PACK_MAX_AMOUNT){
        //读出来以后的处理
        memcpy(&nusdata_buf[PACK_HEADER_LEN + pack_sync_amount * PACK_WITH_CRC_LEN],pack_buf,PACK_WITH_CRC_LEN);
        pack_sync_amount++; 
        flash_rd_addr_tmp+=SPI_FLASH_PAGE_SIZE;

        pack_buf[10]++;
        uint16_t crc16 = crc16_calculate(pack_buf,PACK_LEN);
        memcpy(&pack_buf[PACK_LEN],&crc16,sizeof(uint16_t));
    }
     mc_debug("while beark reason: flash_rd_addr_tmp :%x,flash_wr_addr=%x,[flash_rd_addr=%x]pack_sync_amount=%d\r\n",flash_rd_addr_tmp,flash_wr_addr,flash_rd_addr,pack_sync_amount);
     return 0;
}
#endif

bool gflash_read_buf_rx(void)
{
    if(pack_sync_amount == PACK_MAX_AMOUNT)//说明是TX的时候读满了 我还要继续读的
    {
    }
    if(flash_rd_addr_tmp == flash_wr_addr)//说明是TX的时候是读完了 可以结束了
    {
    }
    flash_rd_addr = flash_rd_addr_tmp;
    pack_sync_amount=0;

    mc_debug("\r\nrx flash_rd_addr%x flash_wr_addr%x\r\n",flash_rd_addr,flash_wr_addr);

    return flash_rd_addr==flash_wr_addr;//1---表示没有了 全部干净了 0--表示还有的              
}

uint16_t UPCOUNT=0;
uint8_t  open=0;
uint8_t batt_test(void)
{
    static uint8_t lastvue = 0;
    uint8_t vue = 0;

    if (GetBits16(ANA_STATUS_REG, BOOST_SELECTED) != 0x1) {
        vue = battery_get_lvl(BATT_CR2032);
    } else {
        vue = battery_get_lvl(BATT_ALKALINE);
    }
    if(lastvue >= vue){if((lastvue - vue)>10) vue = lastvue;}
    else if(lastvue < vue) {vue = lastvue ? lastvue : vue;};
    lastvue = vue;
    return vue;
}

/******************************************************************************
 *** BLE FUNCTIONS
 *****************************************************************************/
void user_app_generate_static_random_addr(struct bd_addr *addr)
{
    // Check if the static random address is already generated.
    // If it is already generated the two MSB are equal to '1'
    if (!(addr->addr[BD_ADDR_LEN - 1] & GAP_STATIC_ADDR))
    {
        uint8_t package;
        uint32_t val1, val2;
        uint32_t timestamp;
        uint32_t tester, position, adc_single, adc_diff;

        // Initialize OTP controller
        hw_otpc_init();
        hw_otpc_enter_mode(HW_OTPC_MODE_READ);

        package = (GetWord32(OTP_HDR_PACKAGE_ADDR) & 0x000000FF);
        position = GetWord32(OTP_HDR_POSITION_ADDR);
        tester = (GetWord32(OTP_HDR_TESTER_ADDR) & 0x00FFFFFF);
        timestamp = GetWord32(OTP_HDR_TIMESTAMP_ADDR);

        adc_single = (otp_cs_get_adc_single_offset() << 16) | otp_cs_get_adc_single_ge();
        adc_diff = (otp_cs_get_adc_diff_offset() << 16) | otp_cs_get_adc_diff_ge();

        val1 = timestamp ^ position ^ adc_single;
        val2 = tester ^ package ^ adc_diff;
        mycode = timestamp ^adc_diff;
        hw_otpc_disable();
#if MACTIME
        addr->addr[0] =  macTime[4];
        addr->addr[1] =  macTime[3];
        addr->addr[2] =  macTime[2];
        addr->addr[3] =  macTime[1];/
        addr->addr[4] =  macTime[0];
        //addr->addr[5] =  0XFF;
        addr->addr[BD_ADDR_LEN - 1] =0Xea;
 
#else        
       // Shuffle the bits to 'look' more random
        val1 = hash(val1);
        val2 = hash(val2);

        // Assign unique address
        addr->addr[0] = val1 & 0xFF;
        addr->addr[1] = (val1 >> 8) & 0xFF;
        addr->addr[2] = (val1 >> 16) & 0xFF;
        addr->addr[3] = (val1 >> 24) & 0xFF;
        addr->addr[4] = val2 & 0xFF;
        addr->addr[5] = val2 >> 8;

        // The two MSB shall be equal to '1'
        addr->addr[BD_ADDR_LEN - 1] |= GAP_STATIC_ADDR;
#endif        
    }

    mc_debug("\r\n[CODE]%02X\r\n[MAC]:",mycode);
    memcpy(&ble_mac_addr, &addr->addr, BD_ADDR_LEN*sizeof(uint8_t));

    for (int8_t mac_addr_cnt = (BD_ADDR_LEN-1);mac_addr_cnt >= 0;mac_addr_cnt--) {
        mc_debug_byte(ble_mac_addr[mac_addr_cnt]);
        if (mac_addr_cnt > 0)
            mc_debug(":");
    }
}

void user_on_connection(uint8_t connection_idx, struct gapc_connection_req_ind const *param)
{
    mc_debug("\n\r user_on_connection STATE_SEND[%d]",app_env[connection_idx].conidx);
    default_app_on_connection(connection_idx, param);
    mlogout[2].len=1;
    mlogout[2].data[0]=app_env[connection_idx].conidx;
}

void user_on_disconnect( struct gapc_disconnect_ind const *param )
{
    mc_debug("\n\r user_on_disconnect ");
    default_app_on_disconnect(param);
    mlogout[1].len=3;
    kstate=STATE_HISTORY;
}

void user_app_adv_undirect_complete(uint8_t status){
//    mlogout[0].len=1;
//    mc_debug("\n\r user_app_adv_undirect_complete");
    app_easy_gap_advertise_with_timeout_stop();
}

void user_adv_timeout_cb(void){
    mlogout[1].len=1; 
    mc_debug("\r\n user_adv_timeout_cb");         
}

void user_svc1_rest_att_info_req_handler(ke_msg_id_t const msgid,
                                            struct custs1_att_info_req const *param,
                                            ke_task_id_t const dest_id,
                                            ke_task_id_t const src_id)
{
    struct custs1_att_info_rsp *rsp = KE_MSG_ALLOC(CUSTS1_ATT_INFO_RSP,
                                                   src_id,
                                                   dest_id,
                                                   custs1_att_info_rsp);
    // Provide the connection index.
    rsp->conidx  = app_env[param->conidx].conidx;
    // Provide the attribute index.
    rsp->att_idx = param->att_idx;
    // Force current length to zero.
    rsp->length  = 0;
    // Provide the ATT error code.
    rsp->status  = ATT_ERR_WRITE_NOT_PERMITTED;

    ke_msg_send(rsp);
}


void user_svc1_code_ntf_cfg_ind_handler(ke_msg_id_t const msgid,
                                            struct custs1_val_write_ind const *param,
                                            ke_task_id_t const dest_id,
                                            ke_task_id_t const src_id)
{

}

void user_svc1_tx_ntf_cfg_ind_handler(ke_msg_id_t const msgid,
                                            struct custs1_val_write_ind const *param,
                                            ke_task_id_t const dest_id,
                                            ke_task_id_t const src_id)
{                                      
    mlogout[2].len=param->length;
    memcpy(&mlogout[2].data,(uint8_t *)param->value,MIN(LEN,param->length));         
    uint8_t val = 0;
    memcpy(&val, &param->value[0], param->length);
    if (val != 0x00) 
    {
#if DIALOG_SEND_FIRST
        if(flash_rd_addr!=flash_wr_addr) 
            kstate = STATE_SEND;   
        else
            kstate = STATE_SEND;  
#else
      
#endif        
      mc_debug("\r\nuser_svc1_tx_ntf_cfg_ind_handler  --open\r\n");      
    } else {
    
       mc_debug("\r\nuser_svc1_tx_ntf_cfg_ind_handler  --close\r\n");     
    }   
}

void user_svc1_code_wr_ind_handler(ke_msg_id_t const msgid,
                                      struct custs1_val_write_ind const *param,
                                      ke_task_id_t const dest_id,
                                      ke_task_id_t const src_id)
{   
}


void send_flashdata_timer_cb(void)
{
    SHOWME   
    memset(nusdata_buf,0,sizeof(nusdata_buf)); 
    static char fake =0;
#if 1    
    gflash_read_buf_tx();

    nusdata_buf[0] = 'M';
    nusdata_buf[1] = 'Q';
    nusdata_buf[2] = 'B';
    nusdata_buf[3] = fake++;
    nusdata_buf[10] = pack_sync_amount;

    memcpy(&nusdata_buf[4], &ble_mac_addr, BD_ADDR_LEN*sizeof(uint8_t)); 
    memcpy(&nusdata_buf[PACK_HEADER_LEN+ nusdata_buf[10]* PACK_WITH_CRC_LEN ], &sys_version, sizeof(uint32_t));

    if (req !=NULL)
    KE_MSG_FREE(req);
    
    req = KE_MSG_ALLOC_DYN(CUSTS1_VAL_NTF_REQ,
    prf_get_task_from_id(TASK_ID_CUSTS1),
    TASK_APP,
    custs1_val_ntf_ind_req,
    DEF_SVC1_TX_CTRL_CHAR_LEN);
    req->handle = SVC1_IDX_TX_CTRL_VAL;
    req->length = PACK_HEADER_LEN+ nusdata_buf[10]*PACK_WITH_CRC_LEN + SYS_VERSION_LEN;
    req->notification = true;
    memcpy(req->value, nusdata_buf, sizeof(uint8_t)* req->length );

    ke_msg_send(req);
#else                   //头         //长度          //01 00表示总包数目  0x0001  后面0200是数据
    uint8_t mydata[] = {0x11,0x11,   0x00,0x04,     0x00,0x00,0x02,0X00,   0x0D,0x0A};
    memcpy(nusdata_buf,mydata,sizeof(mydata));

    

    //SetBits16(SYS_CTRL_REG, SW_RESET, 1);
    if (req !=NULL)
    KE_MSG_FREE(req);
    
    req = KE_MSG_ALLOC_DYN(CUSTS1_VAL_NTF_REQ,
    prf_get_task_from_id(TASK_ID_CUSTS1),
    TASK_APP,
    custs1_val_ntf_ind_req,
    DEF_SVC1_TX_CTRL_CHAR_LEN);
    req->handle = SVC1_IDX_TX_CTRL_VAL;
    req->length = sizeof(mydata);
    req->notification = true;
    memcpy(req->value, nusdata_buf, sizeof(uint8_t)* req->length );

    ke_msg_send(req);

#endif
}


void send_ack(void)
{
    SHOWME
    if (req !=NULL)
    KE_MSG_FREE(req);
    
    req = KE_MSG_ALLOC_DYN(CUSTS1_VAL_NTF_REQ,
    prf_get_task_from_id(TASK_ID_CUSTS1),
    TASK_APP,
    custs1_val_ntf_ind_req,
    DEF_SVC1_TX_CTRL_CHAR_LEN);
    req->handle = SVC1_IDX_TX_CTRL_VAL;
    req->length = nusdata_buf_len;
    req->notification = true;
    memcpy(req->value, nusdata_buf, sizeof(uint8_t)* req->length );

    ke_msg_send(req);
}



void G_1byteTo2str(uint8_t* strings,uint8_t* bytes,char len)
{
	uint8_t StrRefer[]="0123456789ABCDEF";
	#define GET_MSB_STR(x) (StrRefer[((x>>4)&0x0f)])
	#define GET_LSB_STR(x) (StrRefer[(x&0x0f)])
	for(char i=0,j=0;i<len;i++,j+=2)
	{
		strings[j]  =GET_MSB_STR(bytes[i]);
		strings[j+1]=GET_LSB_STR(bytes[i]);
	}
}

void user_svc1_rx_wr_ind_handler(ke_msg_id_t const msgid,
                                      struct custs1_val_write_ind const *param,
                                      ke_task_id_t const dest_id,
                                      ke_task_id_t const src_id)
{
    //showarry("rx",(uint8_t *)param->value,param->length,param->length);
    mc_debug("rx:%s\r\n",(char *)param->value);     
    mlogout[0].len=param->length; 
    memcpy(&mlogout[0].data,(uint8_t *)param->value,MIN(LEN,param->length)); 
    //开始下一次发送
    kstate = STATE_SEND;
    //直接发送回去
#if !DIALOG_SEND_FIRST    
    memset(nusdata_buf,0,sizeof(nusdata_buf));
    nusdata_buf_len=0;
    
    uint8_t strmac[12];
	G_1byteTo2str(strmac,ble_mac_addr,6);
    
    memcpy(&nusdata_buf[nusdata_buf_len],strmac,12);
    nusdata_buf_len+=12;  
    
    nusdata_buf[nusdata_buf_len]='-'; 
    nusdata_buf_len++;
    
    memcpy(&nusdata_buf[nusdata_buf_len],(uint8_t *)param->value,param->length); 
    nusdata_buf_len+=param->length;

    nusdata_buf[nusdata_buf_len]='-'; 
    nusdata_buf_len++;
    
    uint8_t cntdata[5]={0}; sprintf((char *)&cntdata, "%05d", txcount);txcount++;
    memcpy(&nusdata_buf[nusdata_buf_len],cntdata,5);
    nusdata_buf_len+=5;
    
    nusdata_buf[nusdata_buf_len++]='\r';
    nusdata_buf[nusdata_buf_len++]='\n';
    
    //showarry("tx",(uint8_t *)nusdata_buf,nusdata_buf_len,nusdata_buf_len);
    mc_debug("tx:[%d]%s\r\n",txcount,(char *)nusdata_buf)
    send_ack(); //不需要状态机在RTC等待 可以直接马上回答
    //kstate = STATE_DISCON;  主动断开 1
    count=0;
    kstate = STATE_WAIT_ACK;//不主动断开 1
#endif
}

void user_catch_rest_hndl(ke_msg_id_t const msgid,
                          void const *param,
                          ke_task_id_t const dest_id,
                          ke_task_id_t const src_id)
{
    switch(msgid)
    {
        case CUSTS1_VAL_WRITE_IND:
        {
            struct custs1_val_write_ind const *msg_param = (struct custs1_val_write_ind const *)(param);

            switch (msg_param->handle)
            {
                case SVC1_IDX_RX_CONTROL_VAL:
                    user_svc1_rx_wr_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;
                case SVC1_IDX_TX_CTRL_NTF_CFG:
                    user_svc1_tx_ntf_cfg_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;                   
                case SVC1_IDX_CODE_NTF_CFG:
                    user_svc1_code_ntf_cfg_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;
                case SVC1_IDX_CODE_VAL:
                    user_svc1_code_wr_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;
                default:
                    break;
            }
        } break;

        case CUSTS1_VAL_NTF_CFM:
        {
            struct custs1_val_ntf_cfm const *msg_param = (struct custs1_val_ntf_cfm const *)(param);

            switch (msg_param->handle)
            {
                case SVC1_IDX_TX_CTRL_VAL:
                    break;
                default:
                    break;
            }
        } break;

        case CUSTS1_VAL_IND_CFM:
        {
            struct custs1_val_ind_cfm const *msg_param = (struct custs1_val_ind_cfm const *)(param);

            switch (msg_param->handle)
            {
                default:
                    break;
             }
        } break;

        case CUSTS1_ATT_INFO_REQ:
        {
            struct custs1_att_info_req const *msg_param = (struct custs1_att_info_req const *)param;

            switch (msg_param->att_idx)
            {
                default:
                    user_svc1_rest_att_info_req_handler(msgid, msg_param, dest_id, src_id);
                    break;
             }
        } break;

        case GAPC_PARAM_UPDATED_IND:
        {
            struct gapc_param_updated_ind const *msg_param = (struct gapc_param_updated_ind const *)(param);

            if ((msg_param->con_interval >= user_connection_param_conf.intv_min) &&
                (msg_param->con_interval <= user_connection_param_conf.intv_max) &&
                (msg_param->con_latency == user_connection_param_conf.latency) &&
                (msg_param->sup_to == user_connection_param_conf.time_out))
            {
            }
        } break;

        case CUSTS1_VALUE_REQ_IND:
        {
            struct custs1_value_req_ind const *msg_param = (struct custs1_value_req_ind const *) param;

            switch (msg_param->att_idx)
            {
                default:
                {
                    struct custs1_value_req_rsp *rsp = KE_MSG_ALLOC(CUSTS1_VALUE_REQ_RSP,
                                                                    src_id,
                                                                    dest_id,
                                                                    custs1_value_req_rsp);

                    // Provide the connection index.
                    rsp->conidx  = app_env[msg_param->conidx].conidx;
                    // Provide the attribute index.
                    rsp->att_idx = msg_param->att_idx;
                    // Force current length to zero.
                    rsp->length = 0;
                    // Set Error status
                    rsp->status  = ATT_ERR_APP_ERROR;
                    // Send message
                    ke_msg_send(rsp);
                } break;
             }
        } break;

        default:
            break;
    }
}

/******************************************************************************
 *** CALLBACK FUNCTIONS
 *****************************************************************************/
/******************************************************************************
 * @brief Timer1 interrupt handler routine for wakeup.
 *****************************************************************************/
char data_input(void)
{
//体温
 if( (cyc_counter % TEMP_CYC) == 2){
        char arrayindex = (cyc_counter-2) / TEMP_CYC;
        mc_debug("\r\n Data Acquisition ing  cyc_counter:%d   arrayindex:%d\r\n",cyc_counter,arrayindex)
        env_temp_array[arrayindex]  = mc_read_raw_temp(ENV_TEMP_PIN);
        body_temp_array[arrayindex] = mc_read_raw_temp(BODY_TEMP_PIN);
    }

//运动
    int8_t single_count = M_DRV_MC36XX_ReadRawData(RawData, FIFO_THRESHOLD);
    //mc_debug("\r\n single_count:%d  \r\n",single_count)//25

#if CAS_ENABLE
    for (uint8_t i = 0; i< 25; i++ ) { // div 100hz data for 25hz algorithm
        SensotData_Acc[0] = RawData[i][0];
        SensotData_Acc[1] = RawData[i][1];
        SensotData_Acc[2] = RawData[i][2];
        
        CAS_Main_Process(SensotData_Acc);
#if CAS_SUM
        oncecasdata[0][i] = CAS_data->Activity_Score_1min;
        oncecasdata[1][i] = CAS_data->Activity_Score_10min;
        oncecasdata[2][i] = CAS_data->Activity_Score_1hr;
        oncecasdata[3][i] = CAS_data->Activity_Score_24hr;        
#endif 
    }  
    #if 0 //    
    mc_debug("CAS_Main_Process x:%d   y:%d  z:%d\r\n",SensotData_Acc[0],SensotData_Acc[1],SensotData_Acc[2])
    mc_debug("FreeAcc=%d ", CAS_data->FreeAcc);
    mc_debug("gVar=%d ", CAS_data->gVar);

    mc_debug("1min=%d ",  CAS_data->Activity_Score_1min);
    mc_debug("2min=%d ",  CAS_data->Activity_Score_2min);
    mc_debug("20min=%d ",  CAS_data->Activity_Score_20min);
    mc_debug("1h=%d ",  CAS_data->Activity_Score_1hr);
    mc_debug("6h=%d ",  CAS_data->Activity_Score_6hr);
    mc_debug("24h=%d ",  CAS_data->Activity_Score_24hr);
    mc_debug("\r\n");
    #endif //
#endif
 
//全局逻辑 
    cyc_counter++;
    if (cyc_counter == MAX_CYC*RUN_TIME_CYC) {
        mc_debug("\r\n Data Acquisition done cyc_counter max:%d \r\n",cyc_counter)
        uint8_t pack_buf[PACK_WITH_CRC_LEN];
        uint32_t curr_date_bcd, curr_time_bcd;
        curr_date_bcd = rtc_get_clndr_bcd();
        curr_time_bcd = rtc_get_time_bcd();
        memset(pack_buf, 0, sizeof(pack_buf));

        int16_t body_temp,raw_env_temp,raw_body_temp;
        raw_env_temp = mc_temp_average(env_temp_array,TEMP_AVERAGE_TIMES);
        raw_body_temp = mc_temp_average(body_temp_array,TEMP_AVERAGE_TIMES);
        body_temp = bodyTempCal(raw_env_temp, raw_body_temp);
#if FAKE_ENVTEMP
        raw_env_temp = UPCOUNT++;
        raw_env_temp = raw_env_temp*256;
        mc_debug("raw_env_temp %04X", raw_env_temp);
#endif
        pack_buf[0] = body_temp>>8;
        pack_buf[1] = body_temp&0xFF;
        pack_buf[2] = raw_body_temp >> 8;
        pack_buf[3] = raw_body_temp & 0xFF;
        pack_buf[4] = raw_env_temp >> 8;
        pack_buf[5] = raw_env_temp & 0xFF;

        pack_buf[7] = BCD_TO_YEAR(curr_date_bcd);            //YY
        pack_buf[8] = BCD_TO_MONTH(curr_date_bcd);           //MM
        pack_buf[9] = BCD_TO_DAY(curr_date_bcd);            //DD
        pack_buf[10] = BCD_TO_HOUR(curr_time_bcd);             //HH
        pack_buf[11] = BCD_TO_MIN(curr_time_bcd);           //MM
        pack_buf[12] = BCD_TO_SEC(curr_time_bcd);              //SS

#if CAS_SUM
        CAS_data->Activity_Score_1min   = sum_ave(&oncecasdata[0][0],25);
        CAS_data->Activity_Score_10min  = sum_ave(&oncecasdata[1][0],25);
        CAS_data->Activity_Score_1hr    = sum_ave(&oncecasdata[2][0],25);
        CAS_data->Activity_Score_24hr   = sum_ave(&oncecasdata[3][0],25);       
#endif 
        memcpy(&pack_buf[13+0*6], &CAS_data->Activity_Score_1min,  sizeof(int));
        memcpy(&pack_buf[13+1*6], &CAS_data->Activity_Score_10min, sizeof(int));
        memcpy(&pack_buf[13+2*6], &CAS_data->Activity_Score_1hr,   sizeof(int));
        memcpy(&pack_buf[13+3*6], &CAS_data->Activity_Score_24hr,   sizeof(int));
        mc_debug("[%d-",  CAS_data->Activity_Score_1min);
        mc_debug("%d-",  CAS_data->Activity_Score_10min);
        mc_debug("%d-",  CAS_data->Activity_Score_1hr);
        mc_debug("%d]",  CAS_data->Activity_Score_6hr);
        mc_debug("[%d]",  CAS_data->Activity_Score_24hr);
        mc_debug("\r\n");        

        pack_buf[6] = 0;
        uint16_t crc16 = crc16_calculate(pack_buf,PACK_LEN);// pack_buf[10] is package_amount
        memcpy(&pack_buf[PACK_LEN],&crc16,sizeof(uint16_t)); // pack_buf[10] is package_amount

        /************* END TO PACK DATA *************/
        
        cyc_counter = 0;
        gflash_write_page(pack_buf, sizeof(pack_buf));  
        return 1;
      }        
    return 0;
}

static void app_data_handler(void)
{
    //static char count=0,giveupcnt=0;
    static char giveupcnt=0;
    switch(kstate)
    {
        case STATE_HISTORY:
               //mc_debug("\r\n STATE_HISTORY ");  
               if(count==0) {
                   app_easy_gap_undirected_advertise_with_timeout_start(user_default_hnd_conf.advertise_period, user_adv_timeout_cb);
                   mc_debug("\r\n ADV STARTING ");  
               }   
               if(++count==10)count=0; //因为advertise_period是20S完成一个广播 下一个广播30S以后吧 如果比20小的话比如10那就发了2个广播 到时候停止的时候需要停止2个 一个会导致问题                      
               break;
        case STATE_PRODUCT:
               mc_debug("\r\n STATE_PRODUCT "); 
               enable_accel(SPI_SPEED_MODE_4MHz);
               if(data_input())
               kstate=STATE_ADVCE;
               break;
        case STATE_ADVCE:   
               mc_debug("\r\n STATE_ADVCE ");            
               if(++count==30) {count=0; 
               if(++giveupcnt==2){
               mc_debug("\r\n NO GW GIVE UP STATE_ADVCE");giveupcnt=0;kstate=STATE_PRODUCT; break;};              
                   app_easy_gap_undirected_advertise_with_timeout_start(user_default_hnd_conf.advertise_period, user_adv_timeout_cb);
                   mc_debug("\r\n ADV STARTING ");  
               } 
               break;
               
        case STATE_SEND:  
#if DIALOG_SEND_FIRST        
              send_flashdata_timer_cb(); 
               
#else
              //send_ack(); 
#endif        
              mc_debug("\r\n TX DONE "); 
              //kstate=STATE_WAIT_ACK;
              count=0;
              break;
        case STATE_WAIT_ACK:  
             mc_debug("\r\n STATE_WAIT_ACK %d ",count); 
             if(++count==5) kstate=STATE_HISTORY;
             break;  
        
        case STATE_DISCON:  
             mc_debug("\r\n STATE_DISCON %d ",app_env[0].conidx);              
             app_easy_gap_disconnect(app_env[0].conidx);
             //kstate=STATE_PRODUCT;
             //回答消息以后就再次广播
             count=1;
             kstate=STATE_HISTORY;
             break;
        case STATE_DONE:        
             mc_debug("\r\n never done ");
             //SetBits16(SYS_CTRL_REG, SW_RESET, 0);
             kstate=STATE_HISTORY;
             break;        
    }
  
#if 0// KOSONLOG
        uint8_t i=0,num=0,j=0;
        if(mlogout[0].len)
        {
            mc_debug("\r\n******\r\nflag 0 [%d]:",mlogout[0].len);
            num=MIN(mlogout[0].len,LEN);
            for(i=0;i<num;i++)mc_debug("%02x-",mlogout[0].data[i]);
            j++;
        } 
        if(mlogout[1].len)
        {
            mc_debug("\r\nflag 1 [%d]:",mlogout[1].len);
            num=MIN(mlogout[1].len,LEN);
            for(i=0;i<num;i++)mc_debug("%02x-",mlogout[1].data[i]);
            j++;
        }    
        if(mlogout[2].len)
        {
            mc_debug("\r\nflag 2 [%d]:",mlogout[2].len);
            num=MIN(mlogout[2].len,LEN);
            for(i=0;i<num;i++)mc_debug("%02x-",mlogout[2].data[i]);
            j++;
        }      
       if(j) mc_debug("\r\nflag all num %d\r\n******\r\n",j);
       memset(mlogout,0,sizeof(mlogout));
#endif
}

static void rtc_interrupt_cb(uint8_t event)
{
#if 0//DEBUG_MODE
//      showarry("cannot_logout_count",cannot_logout_count,sizeof(cannot_logout_count),sizeof(cannot_logout_count));
    uint32_t debug_curr_time_bcd = rtc_get_time_bcd();
//    mc_debug("%lx<>",debug_curr_time_bcd);
    mc_debug_num(BCD_TO_HOUR(debug_curr_time_bcd));
    mc_debug(":");
    mc_debug_num(BCD_TO_MIN(debug_curr_time_bcd));
    mc_debug(":");
    mc_debug_num(BCD_TO_SEC(debug_curr_time_bcd));
    mc_debug("[%d]-[%d]",input[0],input[1]);
    mc_debug("\r\n");   
#endif
    app_data_handler();
}

void user_app_run_before_sleep(void)
{
//mc_debug("\n\r user_app_run_before_sleep %d\r\n",kstate);
}


/******************************************************************************
 *** INIT FUNCTIONS
 *****************************************************************************/
static void configure_rtc(void)
{
    // Init RTC
    rtc_reset();

    // Configure the RTC clock; RCX is the RTC clock source (14420 Hz)
    rtc_clk_config(RTC_DIV_DENOM_1000, 15020);
    rtc_clock_enable();

    rtc_config_t cfg = {.hour_clk_mode = RTC_HOUR_MODE_24H, .keep_rtc = 0};

    rtc_time_t time = {.hour_mode = RTC_HOUR_MODE_24H, .pm_flag = 0, .hour = 0,
                       .minute = 0, .sec = 0, .hsec = 0};
    rtc_calendar_t calendar = {.year = 2021, .month = 1, .mday = 18, .wday = 1};

    // Initialize RTC, set time and data, register interrupt handler callback function and enable seconds interrupt
    rtc_init(&cfg);
    rtc_register_intr(rtc_interrupt_cb, RTC_EVENT_SEC);

    // Start RTC
    rtc_set_time_clndr(&time, &calendar);

    // Clear pending interrupts
    rtc_get_event_flags();
}

/******************************************************************************
 *** MAIN USER APPLICATIONS
 *****************************************************************************/
#if MACTIME
#include <stdio.h>

static uint8_t all_comp(char* a,char* b,uint8_t len)
{
  uint8_t i;
  for(i=0;i<len;i++)
    if(a[i]!=b[i]) return 1;
  return 0;
}

//static 
    char get_month(char *pDest)//它的调用者是static 它如果没有static会死机
{  
    char * sMonthBank[12] = { "Jan", "Feb", "Mar", "Apr","May","Jun","Jul", "Aug", "Sep","Oct","Nov","Dec"};
    for(char i=0;i<12;i++)
        if(all_comp(sMonthBank[i],pDest,3) == 0)return 1+i;
    return 0; 
}

static void time_to_mac(void)
{
    char arrTime[20]={0}; 

    sprintf(arrTime,"%s",__TIME__);
    sscanf( (const char*)arrTime,"%x:%x:%x",&macTime[2],&macTime[3],&macTime[4]) ;

    char sMonth[3];
    char nMonth;
    int nDay;
    sprintf(arrTime,"%-20s",__DATE__);
    sscanf( (const char*)arrTime,"%s%x",sMonth,&nDay) ;
    nMonth = get_month(sMonth);
    macTime[0]= nMonth;
    macTime[1]= nDay;
}

#endif
static void timer1_interrupt_hdlr(void)
{
    enable_accel(SPI_SPEED_MODE_4MHz);;
}

void configure_timer(void)
{
    
    timer1_count_options_t count_options = {.input_clk = TIM1_CLK_SRC_LP,
                                            .free_run = TIM1_FREE_RUN_OFF,
                                            .irq_mask = TIM1_IRQ_MASK_OFF,
                                            .count_dir = TIM1_CNT_DIR_UP,
                                            .reload_val = 1908,
    };
    // Enable Timer1 interrupt
    timer1_enable_irq();
    timer1_count_config(&count_options, timer1_interrupt_hdlr);
}

void user_app_init(void)
{
#if DISABLE_TOOL
    SetBits16(SYS_CTRL_REG, DEBUGGER_ENABLE, 0);    // disable debugger
    GPIO_ConfigurePin(FAC_PORT, FAC_PIN, INPUT, PID_GPIO, false);   //Pull high to trigger FAC
#endif
    mc_debug("\r\n\r\n\r\n\r\n\r\n\r\n[Begin...]");
    mc_debug("\r\n[Version]:");
    sys_version = mc_get_version();
    mc_debug_4hex(sys_version);
    mc_debug("\r\n");
    mc_debug(__DATE__);
    mc_debug("\r\n");
    mc_debug(__TIME__);
#if MACTIME
    time_to_mac();
#endif    
    //mc_debug("\r\n[DEFAULT TX LEVEL]:");
    //mc_debug_num(rf_pa_pwr_get());

    rf_pa_pwr_set(RF_TX_PWR_LVL_PLUS_2d5);

    //mc_debug("\r\n[TX LEVEL]:");
    //mc_debug_num(rf_pa_pwr_get());

    SetBits16(POWER_CTRL_REG,LDO_CORE_RET_ENABLE,1);
    SetBits16(POWER_CTRL_REG,CMP_VBAT_HIGH_OK_ENABLE,1);
    SetBits16(POWER_AON_CTRL_REG,VBAT_HL_CONNECT_RES_CTRL,3);
    SetBits16(PMU_SLEEP_REG,0xFFF,1);
    syscntl_dcdc_set_level(SYSCNTL_DCDC_LEVEL_1V9); // setting the voltage of system
    SetBits16(DCDC_CTRL_REG, DCDC_ENABLE, 1);// enable boost mode
    mcube_delay_ms(20);
    set_pad_functions();//it's second time to run this funtion, for enable

//    if (GPIO_GetPinStatus(FAC_PORT, FAC_PIN)) {
//        struct bd_addr addr;
//        user_app_generate_static_random_addr(&addr);
//        m_sys_fac_result result = SYS_FAC_PASS;
//        wdg_freeze();
//        result = mc_fac_run(ble_mac_addr);
//        wdg_resume();
//        if (result) {
//            printf_string(UART2,"\r\nFAC pass\r\n");
//        } else {
//            printf_string(UART2,"\r\nFAC fail\r\n");
//        }
//        while(1){//wait for watchdog reset
//            mcube_delay_ms(1000);
//        }
//    }
    // Ensure PD_TIM is open
    SetBits16(PMU_CTRL_REG, TIM_SLEEP, 0);
    // Wait until PD_TIM is opened
    while ((GetWord16(SYS_STAT_REG) & TIM_IS_UP) != TIM_IS_UP);

    // Enable FLASH and SPI
    enable_flash();

    uint16_t man_dev_id;
    uint8_t dev_id;

    // Release Flash from power down
    spi_flash_release_from_power_down();
    // Try to auto-detect the device
    spi_flash_auto_detect(&dev_id);

    spi_cs_low();
    spi_cs_high();

    // Read SPI Flash Manufacturer/Device ID
    spi_flash_read_rems_id(&man_dev_id);
    // Flash power down
    spi_flash_power_down();
    //Accel Interrupt handler
    //GPIO_RegisterCallback(GPIO0_IRQn, sensor_int);
    mcube_delay_ms(1000);

    enable_accel(SPI_SPEED_MODE_2MHz);
    //Inital mCube sensor
    if (M_DRV_MC36XX_RETCODE_SUCCESS == M_DRV_MC36XX_Init()) {
        M_DRV_MC36XX_SPIHSMode();
        enable_accel(SPI_SPEED_MODE_4MHz);
        M_DRV_MC36XX_SetMode(E_M_DRV_MC36XX_MODE_STANDBY);
        M_DRV_MC36XX_ConfigINT(0,0,0,0,0);
        M_DRV_MC36XX_EnableFIFO(E_M_DRV_MC36XX_FIFO_CTL_ENABLE,
            E_M_DRV_MC36XX_FIFO_MODE_WATERMARK, FIFO_THRESHOLD);
        M_DRV_MC36XX_SetMode(E_M_DRV_MC36XX_MODE_CWAKE);
        mcube_delay_ms(1000);     //Collect 1st sec data
        mc_debug("\r\nAccel ready!");
    } else {
        mc_debug("\r\nAccel no response.");
    }
#if CAS_ENABLE
    CAS_init(ChickenActivity_Score);
#endif    
    //configure_timer();// can change to app_easy_timer to wake system if running in 25hz
    configure_rtc();
    default_app_on_init();
    gflash_erase_page();
    memset(mlogout,0,sizeof(mlogout));
    flag_clear_all();           
    arch_printf("\r\n arch_printf %s\r\n",USER_DEVICE_NAME );//协议栈里面也是无法打印
    mc_debug("\r\n-----------%s----------\r\n",USER_DEVICE_NAME );
//复位 它不会回到init的值 需要再次赋值  复位的必须操作
    flash_wr_addr     = ADDR_START;
    flash_rd_addr     = ADDR_START;
    flash_rd_addr_tmp = ADDR_START;
    pack_sync_amount   = 0;
    txcount =0;
}
/// @} APP

+++++++++++++++++继续看 那么ESP32发过来的消息 从机怎么办

A----ESP32不发了 以前我们没有这个逻辑

B---从机接受这个消息 修改从机dialog代码

走B路   既然是写 那就是这里

void user_catch_rest_hndl(ke_msg_id_t const msgid,
                          void const *param,
                          ke_task_id_t const dest_id,
                          ke_task_id_t const src_id)
{
    switch(msgid)
    {
        case CUSTS1_VAL_WRITE_IND:
        {
            struct custs1_val_write_ind const *msg_param = (struct custs1_val_write_ind const *)(param);

            switch (msg_param->handle)
            {
                case SVC1_IDX_RX_CONTROL_VAL:
                    user_svc1_rx_wr_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;
                case SVC1_IDX_TX_CTRL_NTF_CFG:
                    user_svc1_tx_ntf_cfg_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;                   
                case SVC1_IDX_CODE_NTF_CFG:
                    user_svc1_code_ntf_cfg_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;
                case SVC1_IDX_CODE_VAL:
                    user_svc1_code_wr_ind_handler(msgid, msg_param, dest_id, src_id);
                    break;
                case SVC1_IDX_TX_CTRL_VAL:
                    showarry("esp com",(uint8_t *)msg_param->value,msg_param->length,msg_param->length);
                    break;
                default:
                    break;
            }
        } break;

测试 如下图 可以看到成功了

+++++++++++++继续做出RX TX

在esp收到从机消息以后 发消息回去

    case ESP_GATTC_NOTIFY_EVT:
        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:");
        }
        esp_log_buffer_hex(GATTC_TAG, p_data->notify.value, p_data->notify.value_len);
        uint8_t write_char_data_test[]={"HAHA"};
        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_test),
                                  write_char_data_test,
                                  ESP_GATT_WRITE_TYPE_RSP,
                                  ESP_GATT_AUTH_REQ_NONE);

        break;

可以看到成功了

每次从机LOG都可以看到

但是和我们以前不一样 以前是  有函数对应的 

这么解决这个问题

现在全局整理一下流程

ESP32学习笔记(34)——BLE一主多从连接_Leung的博客-CSDN博客

ESP32蓝牙的Gatt Client的例子演练_小锋学长生活大爆炸-CSDN博客

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ESP32蓝牙启动流程如下: 1. 初始化蓝牙协议栈 2. 配置蓝牙参数,如设备名称、服务UUID等 3. 注册蓝牙事件回调函数 4. 启动蓝牙广播 5. 开启蓝牙可见性 6. 等待连接 以下是一个简单的ESP32蓝牙串口调试的示例: ```C #include "esp_bt.h" #include "esp_bt_main.h" #include "esp_gap_ble_api.h" #define GATTS_TAG "GATTS_DEMO" #define TEST_DEVICE_NAME "ESP32_BLE_UART" #define TEST_MANUFACTURER_DATA_LEN 17 /* The max length of characteristic value. When the gatt client write or prepare write, * the data length must be less than MAX_VALUE_LENGTH. */ #define MAX_VALUE_LENGTH 500 /* Declare global variable */ static uint8_t test_manufacturer[TEST_MANUFACTURER_DATA_LEN] = {0x4c, 0x00, 0x02, 0x15, 0xE2, 0x0A, 0x39, 0xF4, 0x73, 0xF5, 0x4B, 0xC4, 0xA1, 0x2F, 0x17, 0xD1, 0xAD}; static uint8_t test_service_uuid128[32] = { /* LSB <--------------------------------------------------------------------------------> MSB */ //first uuid, 16bit, [12],[13] is the value 0x13, 0x2B, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB, //second uuid, 32bit, [12], [13], [14], [15] is the value 0x14, 0x2B, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB, }; static uint8_t test_service_uuid[16] = { /* LSB <--------------------------------------------------------------------------------> MSB */ //first uuid, 16bit, [12],[13] is the value 0x01, 0x2B, //second uuid, 32bit, [12], [13], [14], [15] is the value 0x01, 0x2B, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB, }; static uint8_t test_char_uuid[16] = { /* LSB <--------------------------------------------------------------------------------> MSB */ //first uuid, 16bit, [12],[13] is the value 0x02, 0x2B, //second uuid, 32bit, [12], [13], [14], [15] is the value 0x02, 0x2B, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB, }; static esp_gatt_char_prop_t test_property = 0; static uint8_t char1_str[] = {0x11,0x22,0x33}; static esp_attr_value_t gatts_demo_char1_val = { .attr_max_len = MAX_VALUE_LENGTH, .attr_len = sizeof(char1_str), .attr_value = char1_str, }; static uint16_t gatts_demo_handle_table[3]; /* 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(test_service_uuid), sizeof(test_service_uuid), (uint8_t *)&test_service_uuid}, ESP_GATT_UUID_PRI_SERVICE, ESP_GATT_PERM_READ, sizeof(test_service_uuid), sizeof(test_service_uuid), (uint8_t *)&test_service_uuid, 0 }, /* Characteristic Declaration */ [IDX_CHAR_READ] = { {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 *)&test_property}, ESP_GATT_UUID_CHAR_DECLARE, ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&test_property, 0 }, /* Characteristic Value */ [IDX_CHAR_VAL_READ] = { {ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_128, (uint8_t *)&test_char_uuid, ESP_GATT_PERM_READ, MAX_VALUE_LENGTH, sizeof(gatts_demo_char1_val), gatts_demo_char1_val.attr_value}, ESP_UUID_LEN_128, ESP_GATT_PERM_READ, MAX_VALUE_LENGTH, sizeof(gatts_demo_char1_val), gatts_demo_char1_val.attr_value, 0 }, }; static esp_ble_adv_data_t adv_data = { .set_scan_rsp = false, .include_name = true, .include_txpower = true, .min_interval = 0x20, .max_interval = 0x40, .appearance = 0x00, .manufacturer_len = TEST_MANUFACTURER_DATA_LEN, .p_manufacturer_data = test_manufacturer, .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(test_service_uuid), .p_service_uuid = test_service_uuid, .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT), }; static esp_ble_adv_params_t adv_params = { .adv_int_min = 0x20, .adv_int_max = 0x40, .adv_type = ADV_TYPE_IND, .own_addr_type = BLE_ADDR_TYPE_PUBLIC, .peer_addr = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, .peer_addr_type = BLE_ADDR_TYPE_PUBLIC, .channel_map = ADV_CHNL_ALL, .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { switch (event) { case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: esp_ble_gap_start_advertising(&adv_params); break; case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) { ESP_LOGE(GATTS_TAG, "advertising start failed"); } break; 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) { switch (event) { case ESP_GATTS_REG_EVT: esp_ble_gap_set_device_name(TEST_DEVICE_NAME); esp_ble_gap_config_adv_data(&adv_data); break; case ESP_GATTS_CREAT_ATTR_TAB_EVT: if (param->add_attr_tab.status != ESP_GATT_OK){ ESP_LOGE(GATTS_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_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_TAG, "create attribute table successfully, the number handle = %d\n",param->add_attr_tab.num_handle); memcpy(gatts_demo_handle_table, param->add_attr_tab.handles, sizeof(gatts_demo_handle_table)); esp_ble_gatts_start_service(gatts_demo_handle_table[IDX_SVC]); } break; case ESP_GATTS_CONNECT_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_CONNECT_EVT"); break; case ESP_GATTS_DISCONNECT_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_DISCONNECT_EVT"); esp_ble_gap_start_advertising(&adv_params); break; case ESP_GATTS_WRITE_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_WRITE_EVT"); break; case ESP_GATTS_MTU_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_MTU_EVT, MTU %d", param->mtu.mtu); break; case ESP_GATTS_CONF_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_CONF_EVT"); break; case ESP_GATTS_EXEC_WRITE_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_EXEC_WRITE_EVT"); break; case ESP_GATTS_START_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_START_EVT"); break; case ESP_GATTS_STOP_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_STOP_EVT"); break; case ESP_GATTS_OPEN_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_OPEN_EVT"); break; case ESP_GATTS_CANCEL_OPEN_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_CANCEL_OPEN_EVT"); break; case ESP_GATTS_CLOSE_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_CLOSE_EVT"); break; case ESP_GATTS_LISTEN_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_LISTEN_EVT"); break; case ESP_GATTS_CONGEST_EVT: ESP_LOGI(GATTS_TAG, "ESP_GATTS_CONGEST_EVT"); break; case ESP_GATTS_UNREG_EVT: case ESP_GATTS_DELETE_EVT: default: break; } } void app_main() { esp_err_t ret; ESP_LOGI(GATTS_TAG, "ESP_BLUETOOTH_BLE example started."); esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); ret = esp_bt_controller_init(&bt_cfg); if (ret) { ESP_LOGE(GATTS_TAG, "%s initialize controller failed\n", __func__); return; } ret = esp_bt_controller_enable(ESP_BT_MODE_BLE); if (ret) { ESP_LOGE(GATTS_TAG, "%s enable controller failed\n", __func__); return; } ret = esp_bluedroid_init(); if (ret) { ESP_LOGE(GATTS_TAG, "%s init bluetooth failed\n", __func__); return; } ret = esp_bluedroid_enable(); if (ret) { ESP_LOGE(GATTS_TAG, "%s enable bluetooth failed\n", __func__); return; } ret = esp_ble_gatts_register_callback(gatts_event_handler); if (ret){ ESP_LOGE(GATTS_TAG, "gatts register error, error code = %x", ret); return; } ret = esp_ble_gap_register_callback(gap_event_handler); if (ret){ ESP_LOGE(GATTS_TAG, "gap register error, error code = %x", ret); return; } ret = esp_ble_gatts_app_register(ESP_APP_ID); if (ret){ ESP_LOGE(GATTS_TAG, "gatts app register error, error code = %x", ret); return; } esp_err_t local_mtu_ret = esp_ble_gatt_set_local_mtu(500); if (local_mtu_ret){ ESP_LOGE(GATTS_TAG, "set local MTU failed, error code = %x", local_mtu_ret); } ret = esp_ble_gatts_create_attr_tab(gatt_db, gatts_if, HRS_IDX_NB, ESP_APP_ID); if (ret){ ESP_LOGE(GATTS_TAG, "create attr table failed, error code = %x", ret); } } ``` 在这个示例中,我们使用了ESP-IDF提供的蓝牙协议栈和GATT Server框架,实现了一个简单的GATT Server,并且开启了蓝牙广播和可见性,使得其他蓝牙设备可以扫描到并连接我们的设备。在连接建立后,我们可以向GATT Server中的特定Characteristic写入数据,也可以从特定Characteristic读取数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值