栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android 蓝牙 搜索周围设备代码流程分析-framework到协议栈流程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 蓝牙 搜索周围设备代码流程分析-framework到协议栈流程

本文详细的将Android 蓝牙扫描周围设备流程进行了梳理,从UI开始扫描到协议栈发送扫描命令到controller,进行了源码分析。

更多源码分析:

android-蓝牙A2dp-avrcp-hfp-opp-配对流程-ble-rfcomm源码流程

Android 蓝牙配对连接源码分析文档大全,非常详细的从btif-bta-btm-hci 数据流程走向 - 点击下载

蓝牙UI开始扫描位于setting的 /packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingDetail.java 中。

BluetoothPairingDetail 是扫描蓝牙设备并配对它们的页面。

    void enableScanning() {
120        // Clear all device states before first scan 清楚所有的设备状态第一次扫描时候
121        if (!mInitialScanStarted) {
122            if (mAvailableDevicesCategory != null) {
123                removeAllDevices(); //移除所有的设备
124            }
125            mLocalManager.getCachedDeviceManager().clearNonBondedDevices();
126            mInitialScanStarted = true;
127        }
128        super.enableScanning();//调用父类 DeviceListPreferenceFragment中的函数
129    }

接下来,调用到父类中DeviceListPreferenceFragment的扫描函数:

/packages/apps/Settings/src/com/android/settings/bluetooth/DeviceListPreferenceFragment.java

   @VisibleForTesting
228    void enableScanning() {
229        // LocalBluetoothAdapter already handles repeated scan requests
230        mLocalAdapter.startScanning(true);//调用到本地适配器中的扫描函数
231        mScanEnabled = true;
232    }

调用到本地适配器中的扫描函数

/frameworks/base/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java

   public void startScanning(boolean force) {
160        // Only start if we're not already scanning
161        if (!mAdapter.isDiscovering()) {
162            if (!force) {
163                // Don't scan more than frequently than SCAN_EXPIRATION_MS,
164                // unless forced
165                if (mLastScan + SCAN_EXPIRATION_MS > System.currentTimeMillis()) {
166                    return;
167                }
168
169                // If we are playing music, don't scan unless forced.
                    如果正在播放音乐,除非强制扫描,否则停止扫描
170                A2dpProfile a2dp = mProfileManager.getA2dpProfile();
171                if (a2dp != null && a2dp.isA2dpPlaying()) {
172                    return;
173                }
174                A2dpSinkProfile a2dpSink = mProfileManager.getA2dpSinkProfile();
175                if ((a2dpSink != null) && (a2dpSink.isA2dpPlaying())){判断a2dp播放音乐情况
176                    return;
177                }
178            }
179
180            if (mAdapter.startDiscovery()) {//调用适配器中的开始发现函数。
181                mLastScan = System.currentTimeMillis();
182            }
183        }
184    }

调用适配器中的开始发现函数。

/frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java

发现过程通常涉及大约12秒查询扫描(具体时间协议栈中设置),然后对每个新设备进行页面扫描以检索其蓝牙名称。这是一个异步调用,它会立即返回。设备发现是一个重量级的过程。新的连接

在发现过程中不应尝试连接远程蓝牙设备。

  public boolean startDiscovery() {
1403        if (getState() != STATE_ON) {
1404            return false;
1405        }
1406        try {
1407            mServiceLock.readLock().lock();
1408            if (mService != null) {
1409                return mService.startDiscovery();//调用适配器服务中开始发现函数
1410            }
1411        } catch (RemoteException e) {
1412            Log.e(TAG, "", e);
1413        } finally {
1414            mServiceLock.readLock().unlock();
1415        }
1416        return false;
1417    }

调用适配器服务中开始发现函数,这里的 service.startDiscovery 属于 aidl 跨进程通信,通过 IBluetooth.aidl 调用远程服务

/packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java

     public boolean startDiscovery() {
958            if (!Utils.checkCaller()) {
959                Log.w(TAG, "startDiscovery() - Not allowed for non-active user");
960                return false;
961            }
962
963            AdapterService service = getService();
964            if (service == null) {
965                return false;
966            }
967            return service.startDiscovery(); 

968        }
    boolean startDiscovery() {
1721        debugLog("startDiscovery");
1722        enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH ADMIN permission");
1723
1724        return startDiscoveryNative(); //开始调用到native层了 
1725    }

这里最终调用tartDiscoveryNative()方法,从 Java 层调到 JNI 层的/packages/apps/Bluetooth/jni/com_android_bluetooth_btservice_AdapterService.cpp文件中的 startDiscoveryNative 方法:

777static jboolean startDiscoveryNative(JNIEnv* env, jobject obj) {
778  ALOGV("%s", __func__);
779
780  if (!sBluetoothInterface) return JNI_FALSE;
781
782  int ret = sBluetoothInterface->start_discovery();//该接口调用到hal层的扫描函数。
783  return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
784}

/system/bt/include/hardware/bluetooth.h

这是hal层,就是从这里调用到了蓝牙协议栈了。

typedef struct {
442  
443  size_t size;
444  
448  int (*init)(bt_callbacks_t* callbacks);
449
450  
451  int (*enable)(bool guest_mode);
452
453  
454  int (*disable)(void);
455
456  
457  void (*cleanup)(void);
458
459  
460  int (*get_adapter_properties)(void);
461
462  
463  int (*get_adapter_property)(bt_property_type_t type);
464
465  
466  
469  int (*set_adapter_property)(const bt_property_t* property);
470
471  
472  int (*get_remote_device_properties)(RawAddress* remote_addr);
473
474  
475  int (*get_remote_device_property)(RawAddress* remote_addr,
476                                    bt_property_type_t type);
477
478  
479  int (*set_remote_device_property)(RawAddress* remote_addr,
480                                    const bt_property_t* property);
481
482  
483  int (*get_remote_service_record)(const RawAddress& remote_addr,
484                                   const bluetooth::Uuid& uuid);
485
486  
487  int (*get_remote_services)(RawAddress* remote_addr);
488
489  
490  int (*start_discovery)(void);
491
492  
493  int (*cancel_discovery)(void);
494
495  
496  int (*create_bond)(const RawAddress* bd_addr, int transport);
497
498  
499  int (*create_bond_out_of_band)(const RawAddress* bd_addr, int transport,
500                                 const bt_out_of_band_data_t* oob_data);
501
502  
503  int (*remove_bond)(const RawAddress* bd_addr);
504
505  
506  int (*cancel_bond)(const RawAddress* bd_addr);
507
508  
513  int (*get_connection_state)(const RawAddress* bd_addr);
514
515  
516  
517  int (*pin_reply)(const RawAddress* bd_addr, uint8_t accept, uint8_t pin_len,
518                   bt_pin_code_t* pin_code);
519
520  
525  int (*ssp_reply)(const RawAddress* bd_addr, bt_ssp_variant_t variant,
526                   uint8_t accept, uint32_t passkey);
527
528  
529  const void* (*get_profile_interface)(const char* profile_id);
530
531  
532  
533  int (*dut_mode_configure)(uint8_t enable);
534
535  
537  int (*dut_mode_send)(uint16_t opcode, uint8_t* buf, uint8_t len);
538  
539  
541  int (*le_test_mode)(uint16_t opcode, uint8_t* buf, uint8_t len);
542
543  
546  int (*set_os_callouts)(bt_os_callouts_t* callouts);
547
548  
552  int (*read_energy_info)();
553
554  
560  void (*dump)(int fd, const char** arguments);
561
562  
568  void (*dumpMetrics)(std::string* output);
569
570  
573  int (*config_clear)(void);
574
575  
578  void (*interop_database_clear)(void);
579
580  
586  void (*interop_database_add)(uint16_t feature, const RawAddress* addr,
587                               size_t len);
588
589  
592  bluetooth::avrcp::ServiceInterface* (*get_avrcp_service)(void);
593} bt_interface_t;


static const bt_interface_t* sBluetoothInterface = NULL;//定义了结构体指针

static const bt_interface_t* sBluetoothInterface = NULL;//定义了结构体指针

sBluetoothInterface->start_discovery() 指向了这个回调函数:那么这个结构体中所有的回调函数在哪里赋值的呢?

是的,在下面这个函数中赋值的:/system/bt/btif/src/bluetooth.cc

432EXPORT_SYMBOL bt_interface_t bluetoothInterface = {
433    sizeof(bluetoothInterface),
434    init,
435    enable,
436    disable,
437    cleanup,
438    get_adapter_properties,
439    get_adapter_property,
440    set_adapter_property,
441    get_remote_device_properties,
442    get_remote_device_property,
443    set_remote_device_property,
444    get_remote_service_record,
445    get_remote_services,
446    start_discovery,
447    cancel_discovery,
448    create_bond,
449    create_bond_out_of_band,
450    remove_bond,
451    cancel_bond,
452    get_connection_state,
453    pin_reply,
454    ssp_reply,
455    get_profile_interface,
456    dut_mode_configure,
457    dut_mode_send,
458    le_test_mode,
459    set_os_callouts,
460    read_energy_info,
461    dump,
462    dumpMetrics,
463    config_clear,
464    interop_database_clear,
465    interop_database_add,
466    get_avrcp_service,
467};
237static int start_discovery(void) {
238  
239  if (!interface_ready()) return BT_STATUS_NOT_READY;
240
241  return btif_dm_start_discovery(); 开始调用到btif层的函数了
242}

/system/bt/btif/src/btif_dm.cc

此时调用到了蓝牙协议栈中btif层了,这个函数的作用是 设备管理相关的函数;

设置扫描参数,并且注册回调函数bte_search_devices_evt()

2129bt_status_t btif_dm_start_discovery(void) {
2130  tBTA_DM_INQ inq_params;
2131  tBTA_SERVICE_MASK services = 0;
2132
2133  BTIF_TRACE_EVENT("%s", __func__);
2134
2135  
2136  do_in_bta_thread(
2137      FROM_HERE,
2138      base::Bind(&BTM_BleAdvFilterParamSetup, BTM_BLE_SCAN_COND_DELETe, 0,
2139                 nullptr, base::Bind(&bte_scan_filt_param_cfg_evt, 0)));
2140
2141  auto adv_filt_param = std::make_unique();
2142   //设置ble广播过滤参数
2143  adv_filt_param->dely_mode = IMMEDIATE_DELY_MODE;
2144  adv_filt_param->feat_seln = ALLOW_ALL_FILTER;
2145  adv_filt_param->filt_logic_type = BTA_DM_BLE_PF_FILT_LOGIC_OR;
2146  adv_filt_param->list_logic_type = BTA_DM_BLE_PF_LIST_LOGIC_OR;
2147  adv_filt_param->rssi_low_thres = LOWEST_RSSI_VALUE;
2148  adv_filt_param->rssi_high_thres = LOWEST_RSSI_VALUE;
2149  do_in_bta_thread(
2150      FROM_HERE, base::Bind(&BTM_BleAdvFilterParamSetup, BTM_BLE_SCAN_COND_ADD,
2151                            0, base::Passed(&adv_filt_param),
2152                            base::Bind(&bte_scan_filt_param_cfg_evt, 0)));
2153
2154  
2155
2156  
2157  inq_params.mode = BTA_DM_GENERAL_INQUIRY | BTA_BLE_GENERAL_INQUIRY;//设置扫描模式
2158  inq_params.duration = BTIF_DM_DEFAULT_INQ_MAX_DURATION;//设置扫描间隔,一般设置为        
                                                               1.28 x 10 = 12.8s
2159
2160  inq_params.max_resps = BTIF_DM_DEFAULT_INQ_MAX_RESULTS; //扫描最大回复数量不限。
2161  inq_params.report_dup = true;
2162
2163  inq_params.filter_type = BTA_DM_INQ_CLR;
2164  
2165
2166  
2167  btif_dm_inquiry_in_progress = false;
2168  
2169  BTA_DmSearch(&inq_params, services, bte_search_devices_evt); //调用到BTA层了,并且注册回调函数bte_search_devices_evt()
2170
2171  return BT_STATUS_SUCCESS;
2172}

/system/bt/bta/dm/bta_dm_api.cc

这是 BTA 设备管理器的 API 实现文件

*******************************************************************************
116 *
117 * Function         BTA_DmSearch
118 *
119 * Description      This function searches for peer Bluetooth devices. It
120 *                  performs an inquiry and gets the remote name for devices.
121 *                  Service discovery is done if services is non zero
122 *
123 *
124 * Returns          void
125 *
126 ******************************************************************************/
127void BTA_DmSearch(tBTA_DM_INQ* p_dm_inq, tBTA_SERVICE_MASK services,
128                  tBTA_DM_SEARCH_CBACK* p_cback) {
129  tBTA_DM_API_SEARCH* p_msg =
130      (tBTA_DM_API_SEARCH*)osi_calloc(sizeof(tBTA_DM_API_SEARCH));
131
132  p_msg->hdr.event = BTA_DM_API_SEARCH_EVT; //发送该消息事件
133  memcpy(&p_msg->inq_params, p_dm_inq, sizeof(tBTA_DM_INQ));
134  p_msg->services = services;
135  p_msg->p_cback = p_cback; //注册回调函数
136  p_msg->rs_res = BTA_DM_RS_NONE;
137
138  bta_sys_sendmsg(p_msg);//通过消息机制进行发送
139}

接下来,探讨下协议栈消息发送机制:

532void bta_sys_sendmsg(void* p_msg) {
533  base::MessageLoop* bta_message_loop = get_message_loop();
534
535  if (!bta_message_loop || !bta_message_loop->task_runner().get()) {
536    APPL_TRACE_ERROR("%s: MessageLooper not initialized", __func__);
537    return;
538  }
539
540  bta_message_loop->task_runner()->PostTask(
541      FROM_HERE, base::Bind(&bta_sys_event, static_cast(p_msg)));
542} 通过线程,会调用到bta_sys_event函数

通过线程,会调用到bta_sys_event函数

*******************************************************************************
445 *
446 * Function         bta_sys_event
447 *
448 * Description      BTA event handler; called from task event handler.
449 *
450 *
451 * Returns          void
452 *
453 ******************************************************************************/
454void bta_sys_event(BT_HDR* p_msg) {
455  uint8_t id;
456  bool freebuf = true;
457
458  APPL_TRACE_EVENT("%s: Event 0x%x", __func__, p_msg->event);
459
460   从发过来的event中获取子系统id.
461  id = (uint8_t)(p_msg->event >> 8);
462
463  
464  if ((id < BTA_ID_MAX) && (bta_sys_cb.reg[id] != NULL)) {
465    freebuf = (*bta_sys_cb.reg[id]->evt_hdlr)(p_msg);
466  } else {
467    APPL_TRACE_WARNING("%s: Received unregistered event id %d", __func__, id);
468  }
469
470  if (freebuf) {
471    osi_free(p_msg);
472  }
473}

(*bta_sys_cb.reg[id]->evt_hdlr)(p_msg);  那这个函数是怎么处理的呢?事件是怎么发送的呢?详细说说:

首先第一个括号中的是一个函数指针名,顾名思义,应该指向一个函数,通过查找,bta_sys_cb是一个结构体变量,访问到里面的成员reg数组,但是reg又是个结构体指针数组,

tBTA_SYS_REG* reg[BTA_ID_MAX]; 继续查看tBTA_SYS_REG这个结构体的成员变量,找到
tBTA_SYS_EVT_HDLR* evt_hdlr,找到这个函数指针变量,那这个函数指针指向哪个函数呢?查找到,
static const tBTA_SYS_REG bta_dm_search_reg = {bta_dm_search_sm_execute,
                                               bta_dm_search_sm_disable};

在这里查找到了赋值的地方。也就是说evt_hdlr 就是bta_dm_search_sm_execute()函数,并且将参数p_msg传了进来。

继续看:/system/bt/bta/dm/​​​​​​bta_dm_main.cc

这是 BTA 设备管理器的主要实现文件。

230bool bta_dm_search_sm_execute(BT_HDR* p_msg) {
231  tBTA_DM_ST_TBL state_table;
232  uint8_t action;
233  int i;
234
235  APPL_TRACE_EVENT("bta_dm_search_sm_execute state:%d, event:0x%x",
236                   bta_dm_search_cb.state, p_msg->event);
237
238  
239  state_table = bta_dm_search_st_tbl[bta_dm_search_cb.state];//此时第一个搜索,所以 为 
                                                                   idle状态
240
241  bta_dm_search_cb.state =
242      state_table[p_msg->event & 0x00ff][BTA_DM_SEARCH_NEXT_STATE]; //获取到p_msg->event行,BTA_DM_SERRCH_NEXT_STATE列的状态。
243
244  
245  for (i = 0; i < BTA_DM_SEARCH_ACTIONS; i++) {
246    action = state_table[p_msg->event & 0x00ff][i]; //获取到第p_msg->event行的第一个,第二个action函数。
247    if (action != BTA_DM_SEARCH_IGNORE) {
248      (*bta_dm_search_action[action])((tBTA_DM_MSG*)p_msg); //去执行action函数。并将 
         p_msg参数传进去。
249    } else {
250      break;
251    }
252  }
253  return true;
254}

/system/bt/bta/dm/
bta_dm_act.cc

此文件包含设备管理器状态机的操作函数。

954void bta_dm_search_start(tBTA_DM_MSG* p_data) {
955  tBTM_INQUIRY_CMPL result = {};
956
957  size_t len = sizeof(Uuid) * p_data->search.num_uuid;
958  bta_dm_gattc_register(); //注册gatt clent
959
960  APPL_TRACE_DEBUG("%s avoid_scatter=%d", __func__,
961                   p_bta_dm_cfg->avoid_scatter);
962
963  if (p_bta_dm_cfg->avoid_scatter &&
964      (p_data->search.rs_res == BTA_DM_RS_NONE) &&
965      bta_dm_check_av(BTA_DM_API_SEARCH_EVT)) {
966    LOG(INFO) << __func__ << ": delay search to avoid scatter";
967    memcpy(&bta_dm_cb.search_msg, &p_data->search, sizeof(tBTA_DM_API_SEARCH));
968    return;
969  }
970
971  BTM_ClearInqDb(nullptr);
972  
973  bta_dm_search_cb.p_search_cback = p_data->search.p_cback;//保存回调函数
974  bta_dm_search_cb.services = p_data->search.services;
975
976  osi_free_and_reset((void**)&bta_dm_search_cb.p_srvc_uuid);
977
978  if ((bta_dm_search_cb.num_uuid = p_data->search.num_uuid) != 0 &&
979      p_data->search.p_uuid != nullptr) {
980    bta_dm_search_cb.p_srvc_uuid = (Uuid*)osi_malloc(len);
981    *bta_dm_search_cb.p_srvc_uuid = *p_data->search.p_uuid;
982  }
983  result.status = BTM_StartInquiry((tBTM_INQ_PARMS*)&p_data->search.inq_params,
984                                   bta_dm_inq_results_cb, bta_dm_inq_cmpl_cb);
        //进入btam层发起inquiry,并注册了两个回调函数,结果返回函数,和inquiry完成函数。
985
986  APPL_TRACE_EVENT("%s status=%d", __func__, result.status);
987  if (result.status != BTM_CMD_STARTED) {
988    LOG(ERROR) << __func__ << ": BTM_StartInquiry returned "
989               << std::to_string(result.status);
990    result.num_resp = 0;
991    bta_dm_inq_cmpl_cb((void*)&result);
992  }
993}
 /system/bt/stack/btm/btm_inq.cc

此时调用到了btm层,

731tBTM_STATUS BTM_StartInquiry(tBTM_INQ_PARMS* p_inqparms,
732                             tBTM_INQ_RESULTS_CB* p_results_cb,
733                             tBTM_CMPL_CB* p_cmpl_cb) {
734  tBTM_INQUIRY_VAR_ST* p_inq = &btm_cb.btm_inq_vars;
735
736  BTM_TRACE_API("BTM_StartInquiry: mode: %d, dur: %d, rsps: %d, flt: %d",
737                p_inqparms->mode, p_inqparms->duration, p_inqparms->max_resps,
738                p_inqparms->filter_cond_type);
739
740  
742  if (p_inq->inq_active || p_inq->inqfilt_active) {
743    
744    if (p_inq->scan_type == INQ_LE_OBSERVE &&
745        p_inq->p_inq_ble_results_cb != nullptr) {
746      BTM_TRACE_API("BTM_StartInquiry: LE observe in progress");
747      p_inq->scan_type = INQ_GENERAL;
748      p_inq->inq_active = BTM_INQUIRY_INACTIVE;
749      btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE;
750      btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE);
751    } else {
752      LOG(ERROR) << __func__ << ": BTM_BUSY";
753      return (BTM_BUSY);
754    }
755  } else {
756    p_inq->scan_type = INQ_GENERAL;
757  }
758
759  
760  if (!BTM_IsDeviceUp()) {
761    LOG(ERROR) << __func__ << ": adapter is not up";
762    return BTM_WRONG_MODE;
763  }
764
765  if ((p_inqparms->mode & BTM_BR_INQUIRY_MASK) != BTM_GENERAL_INQUIRY &&
766      (p_inqparms->mode & BTM_BR_INQUIRY_MASK) != BTM_LIMITED_INQUIRY &&
767      (p_inqparms->mode & BTM_BLE_INQUIRY_MASK) != BTM_BLE_GENERAL_INQUIRY &&
768      (p_inqparms->mode & BTM_BLE_INQUIRY_MASK) != BTM_BLE_LIMITED_INQUIRY) {
769    LOG(ERROR) << __func__ << ": illegal inquiry mode "
770               << std::to_string(p_inqparms->mode);
771    return (BTM_ILLEGAL_VALUE);
772  }
773
774  
776  p_inq->inqparms = *p_inqparms;
777
778  
779  p_inq->state = BTM_INQ_ACTIVE_STATE;
780  p_inq->p_inq_cmpl_cb = p_cmpl_cb;
781  p_inq->p_inq_results_cb = p_results_cb;
782  p_inq->inq_cmpl_info.num_resp = 0; 
783  p_inq->inq_active = p_inqparms->mode;
784
785  BTM_TRACE_DEBUG("BTM_StartInquiry: p_inq->inq_active = 0x%02x",
786                  p_inq->inq_active);
787
788  tBTM_STATUS status = BTM_CMD_STARTED;
789  
790  if ((p_inqparms->mode & BTM_BLE_INQUIRY_MASK)) {
791    if (!controller_get_interface()->supports_ble()) {
792      LOG(ERROR) << __func__ << ": trying to do LE scan on a non-LE adapter";
793      p_inq->inqparms.mode &= ~BTM_BLE_INQUIRY_MASK;
794      status = BTM_ILLEGAL_VALUE;
795    } else {
796      
797      status = btm_ble_start_inquiry(
798          (uint8_t)(p_inqparms->mode & BTM_BLE_INQUIRY_MASK),
799          p_inqparms->duration);
800      if (status != BTM_CMD_STARTED) {
801        LOG(ERROR) << __func__ << ": Error Starting LE Inquiry";
802        p_inq->inqparms.mode &= ~BTM_BLE_INQUIRY_MASK;
803      }
804    }
805    p_inqparms->mode &= ~BTM_BLE_INQUIRY_MASK;
806
807    BTM_TRACE_DEBUG("BTM_StartInquiry: mode = %02x", p_inqparms->mode);
808  }
809
810  
811  if ((p_inqparms->mode & BTM_BR_INQUIRY_MASK) == BTM_INQUIRY_NONE) {
812    return status;
813  }
814
815  
816  
822  switch (p_inqparms->filter_cond_type) {
823    case BTM_CLR_INQUIRY_FILTER:
824      p_inq->state = BTM_INQ_SET_FILT_STATE;
825      break;
826
827    case BTM_FILTER_COND_DEVICE_CLASS:
828    case BTM_FILTER_COND_BD_ADDR:
829      
831      p_inq->state = BTM_INQ_CLR_FILT_STATE;
832      p_inqparms->filter_cond_type = BTM_CLR_INQUIRY_FILTER;
833      
834      break;
835
836    default:
837      LOG(ERROR) << __func__ << ": invalid filter condition type "
838                 << std::to_string(p_inqparms->filter_cond_type);
839      return (BTM_ILLEGAL_VALUE);
840    }
841
842    
844    status = btm_set_inq_event_filter(p_inqparms->filter_cond_type,
845                                      &p_inqparms->filter_cond);
846    if (status != BTM_CMD_STARTED) {
847      LOG(ERROR) << __func__ << ": failed to set inquiry event filter";
848      p_inq->state = BTM_INQ_INACTIVE_STATE;
849    }
850
851    return (status);
852}
853
1378static tBTM_STATUS btm_set_inq_event_filter(uint8_t filter_cond_type,
1379                                            tBTM_INQ_FILT_COND* p_filt_cond) {
1380  uint8_t condition_length = DEV_CLASS_LEN * 2;
1381  uint8_t condition_buf[DEV_CLASS_LEN * 2];
1382  uint8_t* p_cond = condition_buf; 
1383
1384#if (BTM_INQ_DEBUG == TRUE)
1385  BTM_TRACE_DEBUG(
1386      "btm_set_inq_event_filter: filter type %d [Clear-0, COD-1, BDADDR-2]",
1387      filter_cond_type);
1388  VLOG(2) << "condition " << p_filt_cond->bdaddr_cond;
1389#endif
1390
1391  
1392  switch (filter_cond_type) {
1393    case BTM_FILTER_COND_DEVICE_CLASS:
1394      
1396      memcpy(condition_buf, p_filt_cond->cod_cond.dev_class, DEV_CLASS_LEN);
1397      memcpy(&condition_buf[DEV_CLASS_LEN],
1398             p_filt_cond->cod_cond.dev_class_mask, DEV_CLASS_LEN);
1399
1400      
1401      break;
1402
1403    case BTM_FILTER_COND_BD_ADDR:
1404      p_cond = (uint8_t*)&p_filt_cond->bdaddr_cond;
1405
1406      
1407      break;
1408
1409    case BTM_CLR_INQUIRY_FILTER:
1410      condition_length = 0;
1411      break;
1412
1413    default:
1414      return (BTM_ILLEGAL_VALUE); 
1415  }
1416
1417  btm_cb.btm_inq_vars.inqfilt_active = true;
1418
1419  
1420  btsnd_hcic_set_event_filter(HCI_FILTER_INQUIRY_RESULT, filter_cond_type,
1421                              p_cond, condition_length); //从这里发送hci命令
1422  return (BTM_CMD_STARTED);
1423}

/system/bt/stack/hcic/hcicmds.cc

此时通过HCI将扫描命令发送给了Controller

void btsnd_hcic_set_event_filter(uint8_t filt_type, uint8_t filt_cond_type,
658                                 uint8_t* filt_cond, uint8_t filt_cond_len) {
659  BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE);
660  uint8_t* pp = (uint8_t*)(p + 1);
661
662  p->offset = 0;
663
664  UINT16_TO_STREAM(pp, HCI_SET_EVENT_FILTER);
665
666  if (filt_type) {
667    p->len = (uint16_t)(HCIC_PREAMBLE_SIZE + 2 + filt_cond_len);
668    UINT8_TO_STREAM(pp, (uint8_t)(2 + filt_cond_len));
669
670    UINT8_TO_STREAM(pp, filt_type);
671    UINT8_TO_STREAM(pp, filt_cond_type);
672
673    if (filt_cond_type == HCI_FILTER_COND_DEVICE_CLASS) {
674      DEVCLASS_TO_STREAM(pp, filt_cond);
675      filt_cond += DEV_CLASS_LEN;
676      DEVCLASS_TO_STREAM(pp, filt_cond);
677      filt_cond += DEV_CLASS_LEN;
678
679      filt_cond_len -= (2 * DEV_CLASS_LEN);
680    } else if (filt_cond_type == HCI_FILTER_COND_BD_ADDR) {
681      BDADDR_TO_STREAM(pp, *((RawAddress*)filt_cond));
682      filt_cond += BD_ADDR_LEN;
683
684      filt_cond_len -= BD_ADDR_LEN;
685    }
686
687    if (filt_cond_len) ARRAY_TO_STREAM(pp, filt_cond, filt_cond_len);
688  } else {
689    p->len = (uint16_t)(HCIC_PREAMBLE_SIZE + 1);
690    UINT8_TO_STREAM(pp, 1);
691
692    UINT8_TO_STREAM(pp, filt_type);
693  }
694
695  btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
696}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/867073.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号