使用宏来简化在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;
}

 

你可能感兴趣的:(#,BLE,物联网)