天天看點

[嵌入式架構][nrf51822][SDK12.3] BLE分層設計 DFU OTA 透傳(NUS) 電量 裝置資訊 BLE_HID

一、 目錄結構如下

将每個功能抽離處理,使檔案起步代碼顯得幹淨清晰。官方提供的檔案,行數1000+起步。
[嵌入式架構][nrf51822][SDK12.3] BLE分層設計 DFU OTA 透傳(NUS) 電量 裝置資訊 BLE_HID
[嵌入式架構][nrf51822][SDK12.3] BLE分層設計 DFU OTA 透傳(NUS) 電量 裝置資訊 BLE_HID

二、 BLE服務建立和事件管理

/********************************************************************************
 * @file    biz_ble_services.c
 * @author  jianqiang.xue
 * @Version V1.0.0
 * @Date    2022-03-15
 * @brief   [業務] ble 服務功能(OTA、透傳、電量、裝置資訊、HID)
 ********************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include <stdint.h>
#include <string.h>

#include "biz_ble_cfg.h"
#include "app_main.h"
#include "business_gpio.h"
#include "business_function.h"
#include "log.h"
#include "os_api.h" // 用于發送信号量,給主線程執行ble事件回調

#include "biz_ble.h"
#include "biz_ble_dfu.h"
#include "biz_ble_nus.h"
#include "biz_ble_hids.h"
#include "biz_ble_bas.h"
/* External Variables --------------------------------------------------------*/
/* Private Includes ----------------------------------------------------------*/
/* Private Define ------------------------------------------------------------*/
/* Private Macro -------------------------------------------------------------*/
/* Private Variables ---------------------------------------------------------*/
#if PEER_MANAGER_ENABLED
static pm_peer_id_t   m_peer_id;
#endif

static const ble_uuid_t m_adv_uuids[] =           /**< 通用唯一的服務辨別符 */
{
#if BLE_HIDS_ENABLED
    {BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE, BLE_UUID_TYPE_BLE},
#endif
#if BLE_NUS_ENABLED
    {BLE_UUID_NUS_SERVICE,                    NUS_SERVICE_UUID_TYPE},
#endif
#if BLE_BAS_ENABLED
    {BLE_UUID_BATTERY_SERVICE,                BLE_UUID_TYPE_BLE},
#endif
    {BLE_UUID_DEVICE_INFORMATION_SERVICE,     BLE_UUID_TYPE_BLE}
};
#if BS_BLE_WHITELIST_SUPPORT
static pm_peer_id_t   m_whitelist_peers[BLE_GAP_WHITELIST_ADDR_MAX_COUNT];  /**< List of peers currently in the whitelist. */
static uint32_t       m_whitelist_peer_cnt;                                 /**< Number of peers currently in the whitelist. */
static bool           m_is_wl_changed;                                      /**< Indicates if the whitelist has been changed since last time it has been updated in the Peer Manager. */
#endif
uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID;    /**< Handle of the current connection. */

uint8_t ble_device_name[] = DEVICE_NAME;

// 0--未連接配接 1--連接配接中
bool g_ble_conn_state               = false;
/* Private Function Prototypes -----------------------------------------------*/
#if BS_BLE_WHITELIST_SUPPORT
/**
 * @brief  擷取對等體管理器對等體id清單。
 * @param  p_peers: 用于存儲對等id清單的緩沖區
 * @param  p_size: In: The size of the @p p_peers buffer.
 *                 Out: The number of peers copied in the buffer.
 */
static void peer_list_get(pm_peer_id_t * p_peers, uint32_t * p_size)
{
    pm_peer_id_t peer_id;
    uint32_t     peers_to_copy;

    peers_to_copy = (*p_size < BLE_GAP_WHITELIST_ADDR_MAX_COUNT) ?
                     *p_size : BLE_GAP_WHITELIST_ADDR_MAX_COUNT;

    peer_id = pm_next_peer_id_get(PM_PEER_ID_INVALID);
    *p_size = 0;

    while ((peer_id != PM_PEER_ID_INVALID) && (peers_to_copy--))
    {
        p_peers[(*p_size)++] = peer_id;
        peer_id = pm_next_peer_id_get(peer_id);
    }
}
#endif
/**
 * @brief  處理廣播錯誤的功能
 * @param  nrf_error: 包含出錯資訊的錯誤代碼
 */
static void ble_advertising_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}

/**
 * @brief  處理廣播事件的功能。
 * @note   上級函數[advertising_init], 利用目前廣播模式,顯示不同燈效。如果不使用燈效,可以忽略
 * @param  ble_adv_evt: 廣播事件
 */
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
    uint32_t err_code;
    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_DIRECTED:
            LOG_I("<INFO> BLE_ADV_EVT_DIRECTED\r\n");
            break;
        case BLE_ADV_EVT_FAST:
            LOG_I("<INFO> BLE_ADV_EVT_FAST\r\n");
            break;
        case BLE_ADV_EVT_SLOW:
            LOG_I("<INFO> BLE_ADV_EVT_SLOW\r\n");
            break;
        case BLE_ADV_EVT_FAST_WHITELIST:
            LOG_I("<INFO> BLE_ADV_EVT_FAST_WHITELIST\r\n");
            break;
        case BLE_ADV_EVT_SLOW_WHITELIST:
            LOG_I("<INFO> BLE_ADV_EVT_SLOW_WHITELIST\r\n");
            err_code = ble_advertising_restart_without_whitelist();
            APP_ERROR_CHECK(err_code);
            break;
        case BLE_ADV_EVT_IDLE:
            // 空閑由主線程決定,該事件可以忽略
            break;
#if BS_BLE_WHITELIST_SUPPORT
        case BLE_ADV_EVT_WHITELIST_REQUEST:
        {
            ble_gap_addr_t whitelist_addrs[BLE_GAP_WHITELIST_ADDR_MAX_COUNT];
            ble_gap_irk_t  whitelist_irks[BLE_GAP_WHITELIST_ADDR_MAX_COUNT];
            uint32_t       addr_cnt = BLE_GAP_WHITELIST_ADDR_MAX_COUNT;
            uint32_t       irk_cnt  = BLE_GAP_WHITELIST_ADDR_MAX_COUNT;

            err_code = pm_whitelist_get(whitelist_addrs, &addr_cnt,
                                        whitelist_irks,  &irk_cnt);
            APP_ERROR_CHECK(err_code);
            LOG_D("<DEBUG> pm_whitelist_get returns %d addr in whitelist and %d irk whitelist\r\n",
                           addr_cnt,
                           irk_cnt);

            // Apply the whitelist.
            err_code = ble_advertising_whitelist_reply(whitelist_addrs, addr_cnt,
                                                       whitelist_irks,  irk_cnt);
            APP_ERROR_CHECK(err_code);
            break;
        }
#endif
#if PEER_MANAGER_ENABLED
        case BLE_ADV_EVT_PEER_ADDR_REQUEST:
        {
            pm_peer_data_bonding_t peer_bonding_data;
            // Only Give peer address if we have a handle to the bonded peer.
            if (m_peer_id != PM_PEER_ID_INVALID)
            {
                err_code = pm_peer_data_bonding_load(m_peer_id, &peer_bonding_data);
                if (err_code != NRF_ERROR_NOT_FOUND)
                {
                    APP_ERROR_CHECK(err_code);
                    ble_gap_addr_t * p_peer_addr = &(peer_bonding_data.peer_ble_id.id_addr_info);
                    err_code = ble_advertising_peer_addr_reply(p_peer_addr);
                    APP_ERROR_CHECK(err_code);
                }
            }
            break;
        }
#endif
        default:
            break;
    }
}

/**
 * @brief  用于初始化廣播功能
 */
static void advertising_init(void)
{
    uint32_t               err_code;
    ble_advdata_t          advdata;
    ble_adv_modes_config_t options;

    // Build and set advertising data
    memset(&advdata, 0, sizeof(advdata));

    advdata.name_type               = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance      = true;
    advdata.flags                   = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
    advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
    advdata.uuids_complete.p_uuids  = (ble_uuid_t *)m_adv_uuids;

    memset(&options, 0, sizeof(options));
#if BS_BLE_WHITELIST_SUPPORT
    options.ble_adv_whitelist_enabled      = true;
#endif
    options.ble_adv_directed_enabled       = true;
    options.ble_adv_directed_slow_enabled  = false;
    options.ble_adv_directed_slow_interval = 0;
    options.ble_adv_directed_slow_timeout  = 0;
    options.ble_adv_fast_enabled           = true;
    options.ble_adv_fast_interval          = APP_ADV_FAST_INTERVAL;
    options.ble_adv_fast_timeout           = APP_ADV_FAST_TIMEOUT;
    options.ble_adv_slow_enabled           = true;
    options.ble_adv_slow_interval          = APP_ADV_SLOW_INTERVAL;
    options.ble_adv_slow_timeout           = APP_ADV_SLOW_TIMEOUT;

    err_code = ble_advertising_init(&advdata, NULL, &options, on_adv_evt, ble_advertising_error_handler);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for handling an event from the Connection Parameters Module.
 *
 * @details This function will be called for all events in the Connection Parameters Module
 *          which are passed to the application.
 *
 * @note All this function does is to disconnect. This could have been done by simply setting
 *       the disconnect_on_fail config parameter, but instead we use the event handler
 *       mechanism to demonstrate its use.
 *
 * @param[in] p_evt  Event received from the Connection Parameters Module.
 */
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
    uint32_t err_code;

    if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
    {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
    }
}

/**
 * @brief  函數用于處理來自Connection Parameters子產品的錯誤。
 * @param  nrf_error: 包含出錯資訊的錯誤代碼
 */
static void conn_params_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}

/**
 * @brief  用于初始化連接配接參數子產品的函數
 */
static void conn_params_init(void)
{
    uint32_t               err_code;
    ble_conn_params_init_t cp_init;

    memset(&cp_init, 0, sizeof(cp_init));

    cp_init.p_conn_params                  = NULL;
    cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
    cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
    cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
    cp_init.disconnect_on_fail             = false;
    cp_init.evt_handler                    = on_conn_params_evt;
    cp_init.error_handler                  = conn_params_error_handler;

    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}

#if PEER_MANAGER_ENABLED
/**
 * @brief  處理Peer Manager事件。
 * @param  p_evt: 對等管理器事件
 */
static void pm_evt_handler(pm_evt_t const * p_evt)
{
    ret_code_t err_code;

    switch (p_evt->evt_id)
    {
        case PM_EVT_BONDED_PEER_CONNECTED:
            LOG_I("<INFO> Connected to a previously bonded device.\r\n");
            break;
        case PM_EVT_CONN_SEC_SUCCEEDED:
            LOG_I("<INFO> Connection secured. Role: %d. conn_handle: %d, Procedure: %d\r\n",
                         ble_conn_state_role(p_evt->conn_handle),
                         p_evt->conn_handle,
                         p_evt->params.conn_sec_succeeded.procedure);

            m_peer_id = p_evt->peer_id;

            // Note: You should check on what kind of white list policy your application should use.
            if (p_evt->params.conn_sec_succeeded.procedure == PM_LINK_SECURED_PROCEDURE_BONDING)
            {
#if BS_BLE_WHITELIST_SUPPORT
               LOG_I("<INFO> New Bond, add the peer to the whitelist if possible\r\n");
               LOG_I("<INFO> \tm_whitelist_peer_cnt %d, MAX_PEERS_WLIST %d\r\n",
                              m_whitelist_peer_cnt + 1,
                              BLE_GAP_WHITELIST_ADDR_MAX_COUNT);

               if (m_whitelist_peer_cnt < BLE_GAP_WHITELIST_ADDR_MAX_COUNT)
               {
                   // Bonded to a new peer, add it to the whitelist.
                   m_whitelist_peers[m_whitelist_peer_cnt++] = m_peer_id;
                   m_is_wl_changed = true;
               }
#endif
            }
            break;

        case PM_EVT_CONN_SEC_FAILED:
            /* 通常,當保護失敗時,出于安全原因,不應該重新啟動它。 其他時候,可以直接重新開機。
               有時它可以重新啟動,但隻有在改變一些安全參數。 有時,在斷開連接配接并重新連接配接之前,它無法重新啟動。
                有時不可能保證鍊路安全,或者對端裝置不支援。 如何處理這個錯誤高度依賴于應用程式。  */
            break;

        case PM_EVT_CONN_SEC_CONFIG_REQ:
        {
            //  allow_repairing = true 支援已綁定裝置重新配對請求
            pm_conn_sec_config_t conn_sec_config = {.allow_repairing = true};
            pm_conn_sec_config_reply(p_evt->conn_handle, &conn_sec_config);
            break;
        }

        case PM_EVT_STORAGE_FULL:
            // 在flash上運作垃圾收集。
            err_code = fds_gc();
            if (err_code == FDS_ERR_BUSY || err_code == FDS_ERR_NO_SPACE_IN_QUEUES)
            {
            }
            else
            {
                APP_ERROR_CHECK(err_code);
            }
            break;
        case PM_EVT_PEERS_DELETE_SUCCEEDED:
            // 配對資訊清除完畢,重新開啟藍牙廣播
            biz_ble_start();
            break;
        case PM_EVT_LOCAL_DB_CACHE_APPLY_FAILED:
            // The local database has likely changed, send service changed indications.
            pm_local_database_has_changed();
            break;
        case PM_EVT_PEER_DATA_UPDATE_FAILED:
            APP_ERROR_CHECK(p_evt->params.peer_data_update_failed.error);
            break;

        case PM_EVT_PEER_DELETE_FAILED:
            APP_ERROR_CHECK(p_evt->params.peer_delete_failed.error);
            break;

        case PM_EVT_PEERS_DELETE_FAILED:
            APP_ERROR_CHECK(p_evt->params.peers_delete_failed_evt.error);
            break;
        case PM_EVT_ERROR_UNEXPECTED:
            APP_ERROR_CHECK(p_evt->params.error_unexpected.error);
            break;
        case PM_EVT_CONN_SEC_START:
        case PM_EVT_PEER_DATA_UPDATE_SUCCEEDED:
        case PM_EVT_PEER_DELETE_SUCCEEDED:
        case PM_EVT_LOCAL_DB_CACHE_APPLIED:
        case PM_EVT_SERVICE_CHANGED_IND_SENT:
        case PM_EVT_SERVICE_CHANGED_IND_CONFIRMED:
        default:
            break;
    }
}

/**@brief 對等管理器初始化功能。
 * @param[in] erase_bonds  Indicates whether bonding information should be cleared from
 *                         persistent storage during initialization of the Peer Manager.
 */
static void peer_manager_init(void)
{
    ble_gap_sec_params_t sec_param;
    ret_code_t           err_code;

    err_code = pm_init();
    APP_ERROR_CHECK(err_code);

    memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));

    // 所有安全程式都要使用安全參數。
    sec_param.bond           = SEC_PARAM_BOND;
    sec_param.mitm           = SEC_PARAM_MITM;
    sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
    sec_param.oob            = SEC_PARAM_OOB;
    sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
    sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
    sec_param.kdist_own.enc  = 1;
    sec_param.kdist_own.id   = 1;
    sec_param.kdist_peer.enc = 1;
    sec_param.kdist_peer.id  = 1;

    err_code = pm_sec_params_set(&sec_param);
    APP_ERROR_CHECK(err_code);

    err_code = pm_register(pm_evt_handler);
    APP_ERROR_CHECK(err_code);
}

#endif

/**
 * @brief  用于GAP初始化的函數。
 * @note   此函數将設定裝置所有必要的GAP(通用通路配置檔案)參數。 它還設定權限和外觀
 */
static void gap_params_init(void)
{
    uint32_t                err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;

    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);

    // 設定ble名稱(如果flash沒有存儲,則使用預設名稱)
    err_code = sd_ble_gap_device_name_set(&sec_mode,
                                          (const uint8_t *) ble_device_name,
                                          strlen((char *)ble_device_name));
    APP_ERROR_CHECK(err_code);

    memset(&gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;

    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);
}

/**
 * @brief  處理藍牙事件(連接配接狀态)
 * @param  p_ble_evt: 協定棧事件
 */
static void on_ble_evt(ble_evt_t * p_ble_evt)
{
    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
            if (m_conn_handle != BLE_CONN_HANDLE_INVALID)
            {
                set_ble_conn_state(true);
                LOG_I("<INFO> BLE Connected\r\n");
                if (!get_sys_state())
                {
                    main_send_signal(SIGNAL_SYS_POWER_ON);
                }
            }
            else
            {
                LOG_E("<ERR> BLE Connected Fail\r\n");
            }
            break; // BLE_GAP_EVT_CONNECTED
        case BLE_GAP_EVT_DISCONNECTED:
            LOG_I("<INFO> Disconnected\r\n");
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
            set_ble_conn_state(false);
#if BS_BLE_WHITELIST_SUPPORT
            if (m_is_wl_changed)
            {
                // The whitelist has been modified, update it in the Peer Manager.
                err_code = pm_whitelist_set(m_whitelist_peers, m_whitelist_peer_cnt);
                APP_ERROR_CHECK(err_code);

                err_code = pm_device_identities_list_set(m_whitelist_peers, m_whitelist_peer_cnt);
                if (err_code != NRF_ERROR_NOT_SUPPORTED)
                {
                    APP_ERROR_CHECK(err_code);
                }
                m_is_wl_changed = false;
            }
#endif
            break; // BLE_GAP_EVT_DISCONNECTED
        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
            LOG_D("<DEBUG> GATT Client Timeout.\r\n");
            sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            break; // BLE_GATTC_EVT_TIMEOUT
        case BLE_GATTS_EVT_TIMEOUT:
            // Disconnect on GATT Server timeout event.
            LOG_D("<DEBUG> GATT Server Timeout.\r\n");
            sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            break; // BLE_GATTS_EVT_TIMEOUT
        case BLE_EVT_USER_MEM_REQUEST:
            sd_ble_user_mem_reply(m_conn_handle, NULL);
            break; // BLE_EVT_USER_MEM_REQUEST
        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
        {
            ble_gatts_evt_rw_authorize_request_t  req;
            ble_gatts_rw_authorize_reply_params_t auth_reply;
            req = p_ble_evt->evt.gatts_evt.params.authorize_request;
            if (req.type != BLE_GATTS_AUTHORIZE_TYPE_INVALID)
            {
                if ((req.request.write.op == BLE_GATTS_OP_PREP_WRITE_REQ)     ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
                {
                    if (req.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
                    }
                    else
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_READ;
                    }
                    auth_reply.params.write.gatt_status = APP_FEATURE_NOT_SUPPORTED;
                    sd_ble_gatts_rw_authorize_reply(m_conn_handle,&auth_reply);
                }
            }
            break; // BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST
        }
#if (NRF_SD_BLE_API_VERSION == 3)
        case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
            err_code = sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gatts_evt.conn_handle,
                                                       NRF_BLE_MAX_MTU_SIZE);
            APP_ERROR_CHECK(err_code);
            break; // BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST
#endif
        default:
            break;
    }
}

/**
 * @brief  将協定棧事件分派給具有協定棧事件處理程式的子產品
 * @note   這個函數在接收到協定棧事件後從協定棧事件中斷處理程式中調用[注意:本函數在中斷中執行,不可進行耗時操作]
 * @param  p_ble_evt: 協定棧事件
 */
static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
{
#if BLE_DFU_ENABLED
    ble_dfu_on_ble_evt(&m_dfus, p_ble_evt);
#endif
#if BLE_NUS_ENABLED
    ble_nus_on_ble_evt(&m_nus, p_ble_evt);
#endif
#if BLE_BAS_ENABLED
    ble_bas_on_ble_evt(&m_bas, p_ble_evt);
#endif
#if PEER_MANAGER_ENABLED
    pm_on_ble_evt(p_ble_evt);
    ble_conn_state_on_ble_evt(p_ble_evt);
#endif
    ble_conn_params_on_ble_evt(p_ble_evt);
    ble_advertising_on_ble_evt(p_ble_evt);
    on_ble_evt(p_ble_evt);
    // 判斷是否修改藍牙名稱
    if (p_ble_evt->evt.gatts_evt.params.write.uuid.uuid == BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME &&
        p_ble_evt->header.evt_id == BLE_GATTS_EVT_WRITE)
    {
        LOG_D("ble_name:%s\r\n", p_ble_evt->evt.gatts_evt.params.write.data);
        // 記錄name,然後空閑時,通過fds寫入flash(暫時不寫)
    }
}

/**@brief Function for initializing services that will be used by the application.
 */
static void services_init(void)
{
    uint32_t       err_code;
#if BLE_DFU_ENABLED
    biz_ble_dfu_init();
#endif
#if BLE_BAS_ENABLED
    biz_ble_bas_init();
#endif
#if BLE_DIS_ENABLED
    /**** DIS 裝置資訊服務 ****/
    ble_dis_init_t dis_init;
    memset(&dis_init, 0, sizeof(dis_init));
    ble_srv_ascii_to_utf8(&dis_init.manufact_name_str, (char *)MANUFACTURER_NAME);
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&dis_init.dis_attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&dis_init.dis_attr_md.write_perm);
    err_code = ble_dis_init(&dis_init);
    APP_ERROR_CHECK(err_code);
#endif
#if BLE_NUS_ENABLED
    biz_ble_nus_init();
#endif
#if BLE_HIDS_ENABLED
    biz_ble_hids_init();
#endif
}

/**
 * @brief  函數用于将系統事件分派給需要的回調函數,如Flash操作
 * @note   從系統事件中斷處理程式調用事件 [注意:這是中斷回調,不要執行耗時操作]
 * @param  sys_evt: 系統堆棧事件
 */
static void sys_evt_dispatch(uint32_t sys_evt)
{
    // 将系統事件分派到fstorage子產品,在那裡它将被分派到Flash Data Storage (FDS)子產品。
    fs_sys_event_handler(sys_evt);
    // 最後排程到Advertising子產品,因為它将檢查fstorage中是否有任何挂起的flash操作。
    // 讓fstorage先處理系統事件,這樣它就可以正确地報告給Advertising子產品。
    ble_advertising_on_sys_evt(sys_evt);
}

/**
 * @brief Event handler for new BLE events
 * This function is called from the SoftDevice handler.
 * It is called from interrupt level.
 * @return The returned value is checked in the softdevice_handler module,
 *         using the APP_ERROR_CHECK macro.
 */
static uint32_t ble_new_event_handler(void)
{
    main_send_signal(SIGNAL_BLE_EVENT);
    return NRF_SUCCESS;
}

/**
 * @brief  初始化協定棧和BLE事件中斷
 */
static void ble_stack_init(void)
{
    uint32_t err_code;
    nrf_clock_lf_cfg_t clock_lf_cfg = NRF_CLOCK_LFCLKSRC;

    // 初始化SoftDevice處理程式子產品。(協定棧事件上抛信号)
    SOFTDEVICE_HANDLER_INIT(&clock_lf_cfg, ble_new_event_handler);

    ble_enable_params_t ble_enable_params;
    err_code = softdevice_enable_get_default_config(CENTRAL_LINK_COUNT,
                                                    PERIPHERAL_LINK_COUNT,
                                                    &ble_enable_params);
    APP_ERROR_CHECK(err_code);

    // 根據使用的連結數量檢查記憶體設定 
    CHECK_RAM_START_ADDR(CENTRAL_LINK_COUNT, PERIPHERAL_LINK_COUNT);

    // 啟動協定棧功能(開始分時複用,并通過[ble_new_event_handler],通知事件)
#if (NRF_SD_BLE_API_VERSION == 3)
    ble_enable_params.gatt_enable_params.att_mtu = NRF_BLE_MAX_MTU_SIZE;
#endif
    err_code = softdevice_enable(&ble_enable_params);
    APP_ERROR_CHECK(err_code);

    // 向SoftDevice處理程式子產品注冊BLE事件,如藍牙連接配接狀态,服務通知資料等
    err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
    APP_ERROR_CHECK(err_code);

    // 向SoftDevice處理程式子產品注冊IO操作事件,如操作flash,
    err_code = softdevice_sys_evt_handler_set(sys_evt_dispatch);
    APP_ERROR_CHECK(err_code);
}
/* Public Function Prototypes ------------------------------------------------*/
void set_ble_conn_state(bool state)
{
    g_ble_conn_state = state;
}

bool get_ble_conn_state(void)
{
    return g_ble_conn_state;
}

void biz_ble_start(void)
{
    ret_code_t err_code = 1;
#if BS_BLE_WHITELIST_SUPPORT
    memset(m_whitelist_peers, PM_PEER_ID_INVALID, sizeof(m_whitelist_peers));
    m_whitelist_peer_cnt = (sizeof(m_whitelist_peers) / sizeof(pm_peer_id_t));
    peer_list_get(m_whitelist_peers, &m_whitelist_peer_cnt);
    err_code = pm_whitelist_set(m_whitelist_peers, m_whitelist_peer_cnt);
    APP_ERROR_CHECK(err_code);
    // 設定裝置辨別清單,部分軟裝置不支援此功能
    err_code = pm_device_identities_list_set(m_whitelist_peers, m_whitelist_peer_cnt);
    if (err_code != NRF_ERROR_NOT_SUPPORTED)
    {
        APP_ERROR_CHECK(err_code);
    }

    m_is_wl_changed = false;
#endif
//    if (dongle_mac_is_valid())
    {  
        err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
    }
    LOG_D("biz_ble_start:%x\n", err_code);
}

void biz_ble_stop(void)
{
    if (m_conn_handle != BLE_CONN_HANDLE_INVALID)
    {
        sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
    }
}

#if PEER_MANAGER_ENABLED
/**
 * @brief  [對端管理器] 從flash中清除所有綁定資訊
 */
void peer_manager_clear_all(void)
{
    ret_code_t err_code;
    err_code = pm_peers_delete();
    APP_ERROR_CHECK(err_code);
}

/**
 * @brief  [對端管理器] 從flash中清除指定綁定資訊
 * @param  peer_id: 綁定ID号
 * @retval 錯誤碼
 */
uint32_t peer_manager_clear_single(uint16_t peer_id)
{
    ret_code_t err_code;
    err_code = pm_peer_delete(peer_id);
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }
    return NRF_SUCCESS;
}
#endif


// ble 協定棧初始化
void biz_ble_init(void)
{
    ble_stack_init();   // 協定棧初始化,使能藍牙協定棧,并對其配置
#if PEER_MANAGER_ENABLED
    peer_manager_init();
#endif
    gap_params_init();  // gap參數初始化
    services_init();    // 添加藍牙服務和characteristic
    conn_params_init(); // 初始化連接配接參數子產品
    advertising_init(); // 初始化廣播功能

    biz_ble_start();
    //whitelist_set_addr(); // 設定白名單
}      
/********************************************************************************
* @file    biz_ble_cfg.c
* @author  jianqiang.xue
* @Version V1.0.0
* @Date    2022-03-15
* @brief   [業務] ble相關配置參數
********************************************************************************/

#ifndef __BIZ_BLE_CFG_H
#define __BIZ_BLE_CFG_H
/* Includes ------------------------------------------------------------------*/
#include "nordic_common.h"
#include "nrf.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "softdevice_handler.h"
#include "ble_gatts.h"
#include "app_timer.h"
#include "ble_nus.h"
#include "ble_bas.h"
#include "ble_hids.h"
#include "ble_dis.h"
#include "ble_dfu.h"
#include "app_util_platform.h"
#include "boards.h"
#include "fds.h"
#include "fstorage.h"

#if PEER_MANAGER_ENABLED
#include "ble_conn_state.h"
#include "peer_manager.h"
#endif

#include "biz_ble_nus.h"
#include "biz_ble_hids.h"
#include "biz_ble_dfu.h"
#include "biz_ble_bas.h"
/* Define --------------------------------------------------------------------*/
#define IS_SRVC_CHANGED_CHARACT_PRESENT 0                                           /**< Include the service_changed characteristic. If not enabled, the server's database cannot be changed for the lifetime of the device. */

#if (NRF_SD_BLE_API_VERSION == 3)
#define NRF_BLE_MAX_MTU_SIZE            GATT_MTU_SIZE_DEFAULT                       /**< MTU size used in the softdevice enabling and to reply to a BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST event. */
#endif

#define APP_FEATURE_NOT_SUPPORTED       BLE_GATT_STATUS_ATTERR_APP_BEGIN + 2        /**< Reply when unsupported features are requested. */

#define CENTRAL_LINK_COUNT              0                                           /**< Number of central links used by the application. When changing this number remember to adjust the RAM settings*/
#define PERIPHERAL_LINK_COUNT           1                                           /**< Number of peripheral links used by the application. When changing this number remember to adjust the RAM settings*/

#define DEVICE_NAME                     "Front_Lamp"                                /**< Name of device. Will be included in the advertising data. */
#define MANUFACTURER_NAME               "LiSun"                                     /**< Manufacturer. Will be passed to Device Information Service. */
#define NUS_SERVICE_UUID_TYPE           BLE_UUID_TYPE_BLE                           /**< UUID type for the Nordic UART Service (vendor specific). */

#define APP_ADV_INTERVAL                64                                          /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
#define APP_ADV_TIMEOUT_IN_SECONDS      0                                           /**< The advertising timeout (in units of seconds). */

#define APP_TIMER_PRESCALER             0                                           /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_OP_QUEUE_SIZE         4                                           /**< Size of timer operation queues. */

#define MIN_CONN_INTERVAL               MSEC_TO_UNITS(7.5, UNIT_1_25_MS)            /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL               MSEC_TO_UNITS(15, UNIT_1_25_MS)             /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
#define SLAVE_LATENCY                   0                                           /**< Slave latency. */
#define CONN_SUP_TIMEOUT                MSEC_TO_UNITS(4000, UNIT_10_MS)             /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY  APP_TIMER_TICKS(5000, APP_TIMER_PRESCALER)  /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(30000, APP_TIMER_PRESCALER) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT    3                                           /**< Number of attempts before giving up the connection parameter negotiation. */

#define APP_ADV_FAST_INTERVAL           0x0028                                      /**< Fast advertising interval (in units of 0.625 ms. This value corresponds to 25 ms.). */
#define APP_ADV_SLOW_INTERVAL           0x0C80                                      /**< Slow advertising interval (in units of 0.625 ms. This value corrsponds to 2 seconds). */

#define APP_ADV_FAST_TIMEOUT            30                                          /**< The duration of the fast advertising period (in seconds). */
#define APP_ADV_SLOW_TIMEOUT            0                                           /**< The duration of the slow advertising period (in seconds). */

#if PEER_MANAGER_ENABLED
#define SEC_PARAM_BOND                  1                                           /**< Perform bonding. */
#define SEC_PARAM_MITM                  0                                           /**< Man In The Middle protection not required. */
#define SEC_PARAM_LESC                  0                                           /**< LE Secure Connections not enabled. */
#define SEC_PARAM_KEYPRESS              0                                           /**< Keypress notifications not enabled. */
#define SEC_PARAM_IO_CAPABILITIES       BLE_GAP_IO_CAPS_NONE                        /**< No I/O capabilities. */
#define SEC_PARAM_OOB                   0                                           /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE          7                                           /**< Minimum encryption key size. */
#define SEC_PARAM_MAX_KEY_SIZE          16                                          /**< Maximum encryption key size. */
#endif

#define DEAD_BEEF                       0xDEADBEEF                                  /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */

#if BLE_HIDS_ENABLED
#define MOVEMENT_SPEED                  5                                           /**< Number of pixels by which the cursor is moved each time a button is pushed. */
#define INPUT_REPORT_COUNT              3                                           /**< Number of input reports in this application. */
#define INPUT_REP_BUTTONS_LEN           3                                           /**< Length of Mouse Input Report containing button data. */
#define INPUT_REP_MOVEMENT_LEN          3                                           /**< Length of Mouse Input Report containing movement data. */
#define INPUT_REP_MEDIA_PLAYER_LEN      1                                           /**< Length of Mouse Input Report containing media player data. */
#define INPUT_REP_BUTTONS_INDEX         0                                           /**< Index of Mouse Input Report containing button data. */
#define INPUT_REP_MOVEMENT_INDEX        1                                           /**< Index of Mouse Input Report containing movement data. */
#define INPUT_REP_MPLAYER_INDEX         2                                           /**< Index of Mouse Input Report containing media player data. */
#define INPUT_REP_REF_BUTTONS_ID        1                                           /**< Id of reference to Mouse Input Report containing button data. */
#define INPUT_REP_REF_MOVEMENT_ID       2                                           /**< Id of reference to Mouse Input Report containing movement data. */
#define INPUT_REP_REF_MPLAYER_ID        3                                           /**< Id of reference to Mouse Input Report containing media player data. */

#define BASE_USB_HID_SPEC_VERSION       0x0101                                      /**< Version number of base USB HID Specification implemented by this application. */
#endif

#if BLE_NUS_ENABLED
// 消息隊列
#define BLE_BUFF_Q_ITEM_CNT             (3)
#define BLE_BUFF_Q_ITEM_SIZE            (20)
// 如果發送失敗,則組合上次資料一并發送。最大程度利用帶寬,降低資料延時性。
#define BLE_BUFF_SEND_MAX_SIZE          ((BLE_NUS_MAX_DATA_LEN / BLE_BUFF_Q_ITEM_SIZE) * BLE_BUFF_Q_ITEM_SIZE)
#endif
#endif      

繼續閱讀