藍牙MCU開發之旅:使用宏來簡化在Nordic 的sdk中添加藍牙Service和attribute

        Nordic的SDK做的很好,但是他們一副生怕有什麼地方做的不到位一樣, 很多簡單的功能代碼卻寫的很複雜,如果是java還好,但是C語言實現起來,很多地方的代碼讀起來特別費勁。我在添加自己的服務的時候,沒有仿照他們的示例格式去定義,而是重新處理了一下,由於複用了大量的代碼,比示例程序更容易理解和閱讀。

        核心代碼使用兩個宏來定義,一個是向Service添加attribute,一個是authorize reply,就是client端對於某個attr 進行 read的回調。這裏添加屬性的話,爲了省一個參數,所有的write操作我這裏都定義爲既可以write request也可以write command(兩者的區別是client端進行write操作的時候一個可以得到回調一個不會得到回調),如果希望區分開這兩類寫操作,可以再新增一個參數。然後,每個屬性的value可以在初始化的時候指定一個值,我們沒有這個需求,如果你需要指定的話,可以擴充這個宏。

#define CHAR_HND_ADD(att_uuid,base_uuid_type,uuid_val_len,perm,p_handler)						\
do{																								\
	ble_add_char_params_t add_char_params;														\
    memset(&add_char_params, 0, sizeof(add_char_params));										\
	add_char_params.uuid_type=base_uuid_type;													\
    add_char_params.uuid              = att_uuid;												\
    add_char_params.max_len           = uuid_val_len;											\
	if(((perm)&PERM_READ)==PERM_READ){															\
		add_char_params.char_props.read=true;													\
		add_char_params.read_access =SEC_OPEN;													\
		add_char_params.is_defered_read=true;													\
	}																							\
	if(((perm)&PERM_WRITE)==PERM_WRITE){														\
		add_char_params.char_props.write=true;													\
		add_char_params.char_props.write_wo_resp=true;											\
		add_char_params.write_access =SEC_OPEN;													\
	}																							\
	if(((perm)&PERM_NTF)==PERM_NTF){															\
		add_char_params.char_props.notify =true;												\
		add_char_params.cccd_write_access =SEC_OPEN;											\
	}																							\
    APP_ERROR_CHECK(characteristic_add(BLE_GATT_HANDLE_INVALID,&add_char_params,p_handler)); 	\
}while(0)

#define AUTHORIZE_READ_REPLY(reply_len,p_reply_data)											\
do{																								\
	ble_gatts_rw_authorize_reply_params_t m_rw_authorize_reply_params={							\
				.type=BLE_GATTS_AUTHORIZE_TYPE_READ,											\
				.params.read.gatt_status=BLE_GATT_STATUS_SUCCESS,								\
				.params.read.offset=0,															\
				.params.read.update=1,															\
				.params.read.len=reply_len,														\
				.params.read.p_data=(uint8_t *)p_reply_data,									\
				};																				\
	sd_ble_gatts_rw_authorize_reply(get_conn_handle(),&m_rw_authorize_reply_params);			\
}while(0)

        定義一個handle用來保存各種handle value,主要用於在client訪問的時候,知道是針對的哪個屬性。實際上,不論是ble_gatts_evt_read_t 還是 ble_gatts_evt_write_t,這兩個ble訪問的回調中都帶有uuid參數,如果不想定義handle,下邊這個struct不用定義,使用uuid來來判斷也是可以的。

typedef struct {
    uint16_t                    service_handle;      /**< Handle of LED Button Service (as provided by the BLE stack). */
//    uint16_t                    conn_handle;         /**< Handle of the current connection (as provided by the BLE stack). BLE_CONN_HANDLE_INVALID if not in a connection. */
    ble_gatts_char_handles_t    char_utc_time_handle;
    ble_gatts_char_handles_t    char_record_index_handle;
    ble_gatts_char_handles_t    char_last_record_handle;
    ble_gatts_char_handles_t    char_record_ntf_handle;
    ble_gatts_char_handles_t    char_temp_unit_handle;
    ble_gatts_char_handles_t    char_ntf_size_handle;
    ble_gatts_char_handles_t    char_batt_handle;
    ble_gatts_char_handles_t    char_profile_manager_handle;
    ble_gatts_char_handles_t    char_profile_content_handle;
    ble_gatts_char_handles_t    char_profile_series_handle;
} ble_mmc_main_s;

然後就是添加服務和屬性了:

uint32_t mmc_main_service_init(void) {
    static uint32_t   err_code;
    ble_uuid_t      service_uuid;
    // Add service

    uint8_t base_svc_uuid_type;

    ble_uuid128_t base_uuid = MMC_BASE_UUID;
    err_code = sd_ble_uuid_vs_add(&base_uuid, &base_svc_uuid_type);
    APP_ERROR_CHECK(err_code);
    service_uuid.type = base_svc_uuid_type;
    service_uuid.uuid = MMC_SVC_UUID;

//    BLE_UUID_BLE_ASSIGN(service_uuid, MMC_SVC_UUID);
    err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &service_uuid, &g_ble_mmc_s.service_handle);
    APP_ERROR_CHECK(err_code);
    // Add characteristics.
    CHAR_HND_ADD(UTC_TIME_UUID,base_svc_uuid_type,CHAR_UTC_TIME_LEN,PERM_READ|PERM_WRITE,&g_ble_mmc_s.char_utc_time_handle);
    CHAR_HND_ADD(RECORD_INDEX_UUID,base_svc_uuid_type,CHAR_RECORD_INDEX_LEN,PERM_READ|PERM_WRITE,&g_ble_mmc_s.char_record_index_handle);
    CHAR_HND_ADD(LAST_RECORD_UUID,base_svc_uuid_type,CHAR_RECORD_LEN,PERM_READ,&g_ble_mmc_s.char_last_record_handle);
    CHAR_HND_ADD(RECORD_NTF_UUID,base_svc_uuid_type,CHAR_RECORD_LEN,PERM_NTF,&g_ble_mmc_s.char_record_ntf_handle);
    CHAR_HND_ADD(TEMP_UNIT_UUID,base_svc_uuid_type,CHAR_TEMP_UNIT_LEN,PERM_READ|PERM_WRITE,&g_ble_mmc_s.char_temp_unit_handle);
    CHAR_HND_ADD(NTF_SIZE_UUID,base_svc_uuid_type,CHAR_NTF_SIZE_LEN,PERM_WRITE,&g_ble_mmc_s.char_ntf_size_handle);
    CHAR_HND_ADD(BATT_UUID,base_svc_uuid_type,CHAR_BATT_LEN,PERM_READ,&g_ble_mmc_s.char_batt_handle);
    CHAR_HND_ADD(PROFILE_MANAGER_UUID,base_svc_uuid_type,CHAR_PROFILE_MANAGER_LEN,PERM_WRITE,&g_ble_mmc_s.char_profile_manager_handle);
    CHAR_HND_ADD(PROFILE_CONTENT_UUID,base_svc_uuid_type,CHAR_PROFILE_CONTENT_LEN,PERM_READ|PERM_WRITE,&g_ble_mmc_s.char_profile_content_handle);
    CHAR_HND_ADD(PROFILE_SERIES_UUID,base_svc_uuid_type,CHAR_PROFILE_SERIES_LEN,PERM_READ,&g_ble_mmc_s.char_profile_series_handle);

    return NRF_SUCCESS;
}

        就這樣,我們使用上邊這麼短的代碼添加了一個服務和十個屬性!主要的複用部分在和 宏 CHAR_HND_ADD 和AUTHORIZE_READ_REPLY 。前者負責根據參數添加attribute,後者負責處理ble的訪問!這裏write操作不需要應用層處理返回值的問題,所以只需要定義 read reply。

       處理讀寫操作的回調示例:

void mmc_client_on_ble_evt( ble_evt_t const * p_ble_evt,void * p_context) {
    switch (p_ble_evt->header.evt_id) {
    case BLE_GATTS_EVT_WRITE: {
    //...
    }
    break;
    case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST: {
        if(p_ble_evt->evt.gap_evt.conn_handle!=get_conn_handle()) {
            return;
        }
        const ble_gatts_evt_rw_authorize_request_t * p_auth_req =&p_ble_evt->evt.gatts_evt.params.authorize_request;
        if(p_auth_req->type==BLE_GATTS_AUTHORIZE_TYPE_READ) {
            if(p_auth_req->request.read.uuid.uuid==UTC_TIME_UUID) {
                uint32_t rtc_time;
                get_time(&rtc_time);
                AUTHORIZE_READ_REPLY(CHAR_UTC_TIME_LEN,&rtc_time);
            } 
    }
    break;
    default:
        // No implementation needed.
        break;
    }
}

        如上邊貼出來的代碼,由於可以複用的兩個宏的存在,服務中添加多少個藍牙屬性都手到擒來,幾行代碼就能搞定,花費的時間代價幾乎是0。如果你的藍牙協議中有定義多個service,多到你不想寫了,也可以仿照上邊的示例來複用service的定義。

 

        這裏也貼出Nordic官方SDK裏邊定義ble_bas 服務(Battery Service)的部分代碼,下邊的代碼中,添加了一個service和一個attribute。不能說我這個一定就比nordic的源碼中寫的好,他們的定義會更嚴謹一些,但是從新手學習的角度和快捷開發的需求上出發,我這個肯定更省事兒一些。

/**@brief Macro for defining a ble_bas instance.
 *
 * @param   _name  Name of the instance.
 * @hideinitializer
 */
#define BLE_BAS_DEF(_name)                          \
    static ble_bas_t _name;                         \
    NRF_SDH_BLE_OBSERVER(_name ## _obs,             \
                         BLE_BAS_BLE_OBSERVER_PRIO, \
                         ble_bas_on_ble_evt,        \
                         &_name)

/**@brief Battery Service event type. */
typedef enum
{
    BLE_BAS_EVT_NOTIFICATION_ENABLED, /**< Battery value notification enabled event. */
    BLE_BAS_EVT_NOTIFICATION_DISABLED /**< Battery value notification disabled event. */
} ble_bas_evt_type_t;

/**@brief Battery Service event. */
typedef struct
{
    ble_bas_evt_type_t evt_type;    /**< Type of event. */
    uint16_t           conn_handle; /**< Connection handle. */
} ble_bas_evt_t;

// Forward declaration of the ble_bas_t type.
typedef struct ble_bas_s ble_bas_t;

/**@brief Battery Service event handler type. */
typedef void (* ble_bas_evt_handler_t) (ble_bas_t * p_bas, ble_bas_evt_t * p_evt);

/**@brief Battery Service init structure. This contains all options and data needed for
 *        initialization of the service.*/
typedef struct
{
    ble_bas_evt_handler_t  evt_handler;                    /**< Event handler to be called for handling events in the Battery Service. */
    bool                   support_notification;           /**< TRUE if notification of Battery Level measurement is supported. */
    ble_srv_report_ref_t * p_report_ref;                   /**< If not NULL, a Report Reference descriptor with the specified value will be added to the Battery Level characteristic */
    uint8_t                initial_batt_level;             /**< Initial battery level */
    security_req_t         bl_rd_sec;                      /**< Security requirement for reading the BL characteristic value. */
    security_req_t         bl_cccd_wr_sec;                 /**< Security requirement for writing the BL characteristic CCCD. */
    security_req_t         bl_report_rd_sec;               /**< Security requirement for reading the BL characteristic descriptor. */
} ble_bas_init_t;

/**@brief Battery Service structure. This contains various status information for the service. */
struct ble_bas_s
{
    ble_bas_evt_handler_t    evt_handler;               /**< Event handler to be called for handling events in the Battery Service. */
    uint16_t                 service_handle;            /**< Handle of Battery Service (as provided by the BLE stack). */
    ble_gatts_char_handles_t battery_level_handles;     /**< Handles related to the Battery Level characteristic. */
    uint16_t                 report_ref_handle;         /**< Handle of the Report Reference descriptor. */
    uint8_t                  battery_level_last;        /**< Last Battery Level measurement passed to the Battery Service. */
    bool                     is_notification_supported; /**< TRUE if notification of Battery Level is supported. */
};

上邊是各種struct定義,再看看如何添加:

/**@brief Function for initializing the Battery Service.
 */
static void bas_init(void)
{
    ret_code_t     err_code;
    ble_bas_init_t bas_init_obj;

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

    bas_init_obj.evt_handler          = on_bas_evt;
    bas_init_obj.support_notification = true;
    bas_init_obj.p_report_ref         = NULL;
    bas_init_obj.initial_batt_level   = 100;

    bas_init_obj.bl_rd_sec        = SEC_OPEN;
    bas_init_obj.bl_cccd_wr_sec   = SEC_OPEN;
    bas_init_obj.bl_report_rd_sec = SEC_OPEN;

    err_code = ble_bas_init(&m_bas, &bas_init_obj);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for adding the Battery Level characteristic.
 *
 * @param[in]   p_bas        Battery Service structure.
 * @param[in]   p_bas_init   Information needed to initialize the service.
 *
 * @return      NRF_SUCCESS on success, otherwise an error code.
 */
static ret_code_t battery_level_char_add(ble_bas_t * p_bas, const ble_bas_init_t * p_bas_init)
{
    ret_code_t             err_code;
    ble_add_char_params_t  add_char_params;
    ble_add_descr_params_t add_descr_params;
    uint8_t                initial_battery_level;
    uint8_t                init_len;
    uint8_t                encoded_report_ref[BLE_SRV_ENCODED_REPORT_REF_LEN];

    // Add battery level characteristic
    initial_battery_level = p_bas_init->initial_batt_level;

    memset(&add_char_params, 0, sizeof(add_char_params));
    add_char_params.uuid              = BLE_UUID_BATTERY_LEVEL_CHAR;
    add_char_params.max_len           = sizeof(uint8_t);
    add_char_params.init_len          = sizeof(uint8_t);
    add_char_params.p_init_value      = &initial_battery_level;
    add_char_params.char_props.notify = p_bas->is_notification_supported;
    add_char_params.char_props.read   = 1;
    add_char_params.cccd_write_access = p_bas_init->bl_cccd_wr_sec;
    add_char_params.read_access       = p_bas_init->bl_rd_sec;

    err_code = characteristic_add(p_bas->service_handle,
                                  &add_char_params,
                                  &(p_bas->battery_level_handles));
    if (err_code != NRF_SUCCESS)
    {
        return err_code;
    }

    if (p_bas_init->p_report_ref != NULL)
    {
        // Add Report Reference descriptor
        init_len = ble_srv_report_ref_encode(encoded_report_ref, p_bas_init->p_report_ref);

        memset(&add_descr_params, 0, sizeof(add_descr_params));
        add_descr_params.uuid        = BLE_UUID_REPORT_REF_DESCR;
        add_descr_params.read_access = p_bas_init->bl_report_rd_sec;
        add_descr_params.init_len    = init_len;
        add_descr_params.max_len     = add_descr_params.init_len;
        add_descr_params.p_value     = encoded_report_ref;

        err_code = descriptor_add(p_bas->battery_level_handles.value_handle,
                                  &add_descr_params,
                                  &p_bas->report_ref_handle);
        return err_code;
    }
    else
    {
        p_bas->report_ref_handle = BLE_GATT_HANDLE_INVALID;
    }

    return NRF_SUCCESS;
}


ret_code_t ble_bas_init(ble_bas_t * p_bas, const ble_bas_init_t * p_bas_init)
{
    if (p_bas == NULL || p_bas_init == NULL)
    {
        return NRF_ERROR_NULL;
    }

    ret_code_t err_code;
    ble_uuid_t ble_uuid;

    // Initialize service structure
    p_bas->evt_handler               = p_bas_init->evt_handler;
    p_bas->is_notification_supported = p_bas_init->support_notification;
    p_bas->battery_level_last        = INVALID_BATTERY_LEVEL;

    // Add service
    BLE_UUID_BLE_ASSIGN(ble_uuid, BLE_UUID_BATTERY_SERVICE);

    err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &ble_uuid, &p_bas->service_handle);
    VERIFY_SUCCESS(err_code);

    // Add battery level characteristic
    err_code = battery_level_char_add(p_bas, p_bas_init);
    return err_code;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章