关于蓝牙绑定后定向广播我有点疑惑。我是这样实现的。
首先在example_ble_sec_gatts_demo的基础上实现了对端蓝牙的绑定,绑定成功后,我将param->ble_security.auth_cmpl.bd_addr存在nvs分区,
当断开连接或者系统重启的时候判断NVS是否存了param->ble_security.auth_cmpl.bd_addr(绑定的对端蓝牙mac地址),如果nvs存储了就修改 adv_params.adv_type = ADV_TYPE_DIRECT_IND_LOW adv_params.peer_addr= nvs分区里面对的MAC地址,定向广播,如果没有存储就正常广播。
在定向广播时,我用手机蓝牙调试软件nRF Connect找不到我的广播设备,我想问一下这个是我广播的问题,还是我的手机端(对端设备),要对绑定后的定向广播包做特殊处理,才能扫描到设备连接。
这个是我的广播信息参数
static esp_ble_adv_params_t adv_params = {
.adv_int_min = 0x100,
.adv_int_max = 0x100,
.adv_type = ADV_TYPE_IND,
.own_addr_type = BLE_ADDR_TYPE_PUBLIC,
.channel_map = ADV_CHNL_ALL,
.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
.peer_addr_type = BLE_ADDR_TYPE_PUBLIC,
};
这个当绑定成功触发ESP_GAP_BLE_AUTH_CMPL_EVT事件,保存对端蓝牙MAC地址的代码
case ESP_GAP_BLE_AUTH_CMPL_EVT:
{
esp_bd_addr_t bd_addr;
memcpy(bd_addr, param->ble_security.auth_cmpl.bd_addr, sizeof(esp_bd_addr_t));
ESP_LOGI(GATTS_TAG, "----------->remote BD_ADDR: %08x%04x",\
(bd_addr[0] << 24) + (bd_addr[1] << 16) + (bd_addr[2] << 8) + bd_addr[3],
(bd_addr[4] << 8) + bd_addr[5]);
save_bound_device(bd_addr);//保存在NVS分区
ESP_LOGI(GATTS_TAG, "address type = %d", param->ble_security.auth_cmpl.addr_type);
ESP_LOGI(GATTS_TAG, "pair status = %s",param->ble_security.auth_cmpl.success ? "success" : "fail");
if(!param->ble_security.auth_cmpl.success)
{
ESP_LOGI(GATTS_TAG, "fail reason = 0x%x",param->ble_security.auth_cmpl.fail_reason);
}
else
{
ESP_LOGI(GATTS_TAG, "auth mode = %s",esp_auth_req_to_str(param->ble_security.auth_cmpl.auth_mode));
}
show_bonded_devices();
break;
}
这个是定向广播和非定向广播的代码
/* @brief 启动广告*/
void start_advertising(bool is_directed, const esp_bd_addr_t *target_mac)
{
if (is_directed)
{
adv_params.adv_type = ADV_TYPE_DIRECT_IND_LOW; // 定向广告
memcpy(adv_params.peer_addr, target_mac, sizeof(esp_bd_addr_t));
printf("----------------------------------->");
esp_log_buffer_hex(GATTS_TAG, adv_params.peer_addr, 6);
}
else
{
adv_params.adv_type = ADV_TYPE_IND; // 非定向广告
}
esp_err_t ret = esp_ble_gap_start_advertising(&adv_params);
if (ret)
{
ESP_LOGI(GATTS_TAG, "start advertising failed: %s", esp_err_to_name(ret));
}
else
{
ESP_LOGI(GATTS_TAG, "advertising started with type: %s",is_directed ? "Directed" : "Undirected");
}
}
感谢佬们的帮助!