Home | History | Annotate | Download | only in src
      1 /******************************************************************************
      2  *
      3  *  Copyright 2016 The Android Open Source Project
      4  *
      5  *  Licensed under the Apache License, Version 2.0 (the "License");
      6  *  you may not use this file except in compliance with the License.
      7  *  You may obtain a copy of the License at:
      8  *
      9  *  http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  *
     17  ******************************************************************************/
     18 
     19 #define LOG_TAG "bt_btif_scanner"
     20 
     21 #include <base/bind.h>
     22 #include <base/threading/thread.h>
     23 #include <errno.h>
     24 #include <hardware/bluetooth.h>
     25 #include <stdio.h>
     26 #include <stdlib.h>
     27 #include <string.h>
     28 #include <unordered_set>
     29 #include "device/include/controller.h"
     30 
     31 #include "btif_common.h"
     32 #include "btif_util.h"
     33 
     34 #include <hardware/bt_gatt.h>
     35 
     36 #include "advertise_data_parser.h"
     37 #include "bta_api.h"
     38 #include "bta_closure_api.h"
     39 #include "bta_gatt_api.h"
     40 #include "btif_config.h"
     41 #include "btif_dm.h"
     42 #include "btif_gatt.h"
     43 #include "btif_gatt_util.h"
     44 #include "btif_storage.h"
     45 #include "osi/include/log.h"
     46 #include "vendor_api.h"
     47 
     48 using base::Bind;
     49 using base::Owned;
     50 using std::vector;
     51 using RegisterCallback = BleScannerInterface::RegisterCallback;
     52 
     53 extern const btgatt_callbacks_t* bt_gatt_callbacks;
     54 
     55 #define SCAN_CBACK_IN_JNI(P_CBACK, ...)                              \
     56   do {                                                               \
     57     if (bt_gatt_callbacks && bt_gatt_callbacks->scanner->P_CBACK) {  \
     58       BTIF_TRACE_API("HAL bt_gatt_callbacks->client->%s", #P_CBACK); \
     59       do_in_jni_thread(                                              \
     60           Bind(bt_gatt_callbacks->scanner->P_CBACK, __VA_ARGS__));   \
     61     } else {                                                         \
     62       ASSERTC(0, "Callback is NULL", 0);                             \
     63     }                                                                \
     64   } while (0)
     65 
     66 namespace {
     67 
     68 // all access to this variable should be done on the jni thread
     69 std::set<RawAddress> remote_bdaddr_cache;
     70 std::queue<RawAddress> remote_bdaddr_cache_ordered;
     71 const size_t remote_bdaddr_cache_max_size = 1024;
     72 
     73 void btif_gattc_add_remote_bdaddr(const RawAddress& p_bda, uint8_t addr_type) {
     74   // Remove the oldest entries
     75   while (remote_bdaddr_cache.size() >= remote_bdaddr_cache_max_size) {
     76     const RawAddress& raw_address = remote_bdaddr_cache_ordered.front();
     77     remote_bdaddr_cache.erase(raw_address);
     78     remote_bdaddr_cache_ordered.pop();
     79   }
     80   remote_bdaddr_cache.insert(p_bda);
     81   remote_bdaddr_cache_ordered.push(p_bda);
     82 }
     83 
     84 bool btif_gattc_find_bdaddr(const RawAddress& p_bda) {
     85   return (remote_bdaddr_cache.find(p_bda) != remote_bdaddr_cache.end());
     86 }
     87 
     88 void btif_gattc_init_dev_cb(void) {
     89   remote_bdaddr_cache.clear();
     90   remote_bdaddr_cache_ordered = {};
     91 }
     92 
     93 void bta_batch_scan_threshold_cb(tBTM_BLE_REF_VALUE ref_value) {
     94   SCAN_CBACK_IN_JNI(batchscan_threshold_cb, ref_value);
     95 }
     96 
     97 void bta_batch_scan_reports_cb(int client_id, tBTA_STATUS status,
     98                                uint8_t report_format, uint8_t num_records,
     99                                std::vector<uint8_t> data) {
    100   SCAN_CBACK_IN_JNI(batchscan_reports_cb, client_id, status, report_format,
    101                     num_records, std::move(data));
    102 }
    103 
    104 void bta_scan_results_cb_impl(RawAddress bd_addr, tBT_DEVICE_TYPE device_type,
    105                               int8_t rssi, uint8_t addr_type,
    106                               uint16_t ble_evt_type, uint8_t ble_primary_phy,
    107                               uint8_t ble_secondary_phy,
    108                               uint8_t ble_advertising_sid, int8_t ble_tx_power,
    109                               uint16_t ble_periodic_adv_int,
    110                               vector<uint8_t> value) {
    111   uint8_t remote_name_len;
    112   bt_device_type_t dev_type;
    113   bt_property_t properties;
    114 
    115   const uint8_t* p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
    116       value, BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
    117 
    118   if (p_eir_remote_name == NULL) {
    119     p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
    120         value, BT_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
    121   }
    122 
    123   if ((addr_type != BLE_ADDR_RANDOM) || (p_eir_remote_name)) {
    124     if (!btif_gattc_find_bdaddr(bd_addr)) {
    125       btif_gattc_add_remote_bdaddr(bd_addr, addr_type);
    126 
    127       if (p_eir_remote_name) {
    128         if (remote_name_len > BD_NAME_LEN + 1 ||
    129             (remote_name_len == BD_NAME_LEN + 1 &&
    130              p_eir_remote_name[BD_NAME_LEN] != '\0')) {
    131           LOG_INFO(LOG_TAG,
    132                    "%s dropping invalid packet - device name too long: %d",
    133                    __func__, remote_name_len);
    134           return;
    135         }
    136 
    137         bt_bdname_t bdname;
    138         memcpy(bdname.name, p_eir_remote_name, remote_name_len);
    139         if (remote_name_len < BD_NAME_LEN + 1)
    140           bdname.name[remote_name_len] = '\0';
    141 
    142         LOG_VERBOSE(LOG_TAG, "%s BLE device name=%s len=%d dev_type=%d",
    143                     __func__, bdname.name, remote_name_len, device_type);
    144         btif_dm_update_ble_remote_properties(bd_addr, bdname.name, device_type);
    145       }
    146     }
    147   }
    148 
    149   dev_type = (bt_device_type_t)device_type;
    150   BTIF_STORAGE_FILL_PROPERTY(&properties, BT_PROPERTY_TYPE_OF_DEVICE,
    151                              sizeof(dev_type), &dev_type);
    152   btif_storage_set_remote_device_property(&(bd_addr), &properties);
    153 
    154   btif_storage_set_remote_addr_type(&bd_addr, addr_type);
    155   HAL_CBACK(bt_gatt_callbacks, scanner->scan_result_cb, ble_evt_type, addr_type,
    156             &bd_addr, ble_primary_phy, ble_secondary_phy, ble_advertising_sid,
    157             ble_tx_power, rssi, ble_periodic_adv_int, std::move(value));
    158 }
    159 
    160 void bta_scan_results_cb(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) {
    161   uint8_t len;
    162 
    163   if (event == BTA_DM_INQ_CMPL_EVT) {
    164     BTIF_TRACE_DEBUG("%s  BLE observe complete. Num Resp %d", __func__,
    165                      p_data->inq_cmpl.num_resps);
    166     return;
    167   }
    168 
    169   if (event != BTA_DM_INQ_RES_EVT) {
    170     BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __func__, event);
    171     return;
    172   }
    173 
    174   vector<uint8_t> value;
    175   if (p_data->inq_res.p_eir) {
    176     value.insert(value.begin(), p_data->inq_res.p_eir,
    177                  p_data->inq_res.p_eir + p_data->inq_res.eir_len);
    178 
    179     if (AdvertiseDataParser::GetFieldByType(
    180             value, BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &len)) {
    181       p_data->inq_res.remt_name_not_required = true;
    182     }
    183   }
    184 
    185   tBTA_DM_INQ_RES* r = &p_data->inq_res;
    186   do_in_jni_thread(Bind(bta_scan_results_cb_impl, r->bd_addr, r->device_type,
    187                         r->rssi, r->ble_addr_type, r->ble_evt_type,
    188                         r->ble_primary_phy, r->ble_secondary_phy,
    189                         r->ble_advertising_sid, r->ble_tx_power,
    190                         r->ble_periodic_adv_int, std::move(value)));
    191 }
    192 
    193 void bta_track_adv_event_cb(tBTM_BLE_TRACK_ADV_DATA* p_track_adv_data) {
    194   btgatt_track_adv_info_t* btif_scan_track_cb = new btgatt_track_adv_info_t;
    195 
    196   BTIF_TRACE_DEBUG("%s", __func__);
    197   btif_gatt_move_track_adv_data(btif_scan_track_cb,
    198                                 (btgatt_track_adv_info_t*)p_track_adv_data);
    199 
    200   SCAN_CBACK_IN_JNI(track_adv_event_cb, Owned(btif_scan_track_cb));
    201 }
    202 
    203 void bta_cback(tBTA_GATTC_EVT, tBTA_GATTC*) {}
    204 
    205 class BleScannerInterfaceImpl : public BleScannerInterface {
    206   ~BleScannerInterfaceImpl(){};
    207 
    208   void RegisterScanner(RegisterCallback cb) override {
    209     do_in_bta_thread(FROM_HERE,
    210                      Bind(
    211                          [](RegisterCallback cb) {
    212                            BTA_GATTC_AppRegister(
    213                                bta_cback,
    214                                jni_thread_wrapper(FROM_HERE, std::move(cb)));
    215                          },
    216                          std::move(cb)));
    217   }
    218 
    219   void Unregister(int scanner_id) override {
    220     do_in_bta_thread(FROM_HERE, Bind(&BTA_GATTC_AppDeregister, scanner_id));
    221   }
    222 
    223   void Scan(bool start) override {
    224     do_in_jni_thread(Bind(
    225         [](bool start) {
    226           if (!start) {
    227             do_in_bta_thread(FROM_HERE,
    228                              Bind(&BTA_DmBleObserve, false, 0, nullptr));
    229             return;
    230           }
    231 
    232           btif_gattc_init_dev_cb();
    233           do_in_bta_thread(
    234               FROM_HERE, Bind(&BTA_DmBleObserve, true, 0, bta_scan_results_cb));
    235         },
    236         start));
    237   }
    238 
    239   void ScanFilterParamSetup(
    240       uint8_t client_if, uint8_t action, uint8_t filt_index,
    241       std::unique_ptr<btgatt_filt_param_setup_t> filt_param,
    242       FilterParamSetupCallback cb) override {
    243     BTIF_TRACE_DEBUG("%s", __func__);
    244 
    245     if (filt_param && filt_param->dely_mode == 1) {
    246       do_in_bta_thread(
    247           FROM_HERE, base::Bind(BTM_BleTrackAdvertiser, bta_track_adv_event_cb,
    248                                 client_if));
    249     }
    250 
    251     do_in_bta_thread(FROM_HERE,
    252                      base::Bind(&BTM_BleAdvFilterParamSetup, action, filt_index,
    253                                 base::Passed(&filt_param),
    254                                 jni_thread_wrapper(FROM_HERE, std::move(cb))));
    255   }
    256 
    257   void ScanFilterAdd(int filter_index, std::vector<ApcfCommand> filters,
    258                      FilterConfigCallback cb) override {
    259     BTIF_TRACE_DEBUG("%s: %d", __func__, filter_index);
    260 
    261     do_in_bta_thread(
    262         FROM_HERE,
    263         base::Bind(
    264             &BTM_LE_PF_set, filter_index, std::move(filters),
    265             jni_thread_wrapper(
    266                 FROM_HERE,
    267                 Bind(std::move(cb),
    268                      0 /*TODO: this used to be filter type, unused ?*/))));
    269   }
    270 
    271   void ScanFilterClear(int filter_index, FilterConfigCallback cb) override {
    272     BTIF_TRACE_DEBUG("%s: filter_index: %d", __func__, filter_index);
    273     do_in_bta_thread(FROM_HERE,
    274                      base::Bind(&BTM_LE_PF_clear, filter_index,
    275                                 jni_thread_wrapper(
    276                                     FROM_HERE, Bind(cb, BTM_BLE_PF_TYPE_ALL))));
    277   }
    278 
    279   void ScanFilterEnable(bool enable, EnableCallback cb) override {
    280     BTIF_TRACE_DEBUG("%s: enable: %d", __func__, enable);
    281 
    282     uint8_t action = enable ? 1 : 0;
    283     do_in_bta_thread(FROM_HERE,
    284                      base::Bind(&BTM_BleEnableDisableFilterFeature, action,
    285                                 jni_thread_wrapper(FROM_HERE, std::move(cb))));
    286   }
    287 
    288   void SetScanParameters(int scan_interval, int scan_window,
    289                          Callback cb) override {
    290     do_in_bta_thread(
    291         FROM_HERE, base::Bind(&BTM_BleSetScanParams, scan_interval, scan_window,
    292                               BTM_BLE_SCAN_MODE_ACTI,
    293                               jni_thread_wrapper(FROM_HERE, std::move(cb))));
    294   }
    295 
    296   void BatchscanConfigStorage(int client_if, int batch_scan_full_max,
    297                               int batch_scan_trunc_max,
    298                               int batch_scan_notify_threshold,
    299                               Callback cb) override {
    300     do_in_bta_thread(
    301         FROM_HERE,
    302         base::Bind(&BTM_BleSetStorageConfig, (uint8_t)batch_scan_full_max,
    303                    (uint8_t)batch_scan_trunc_max,
    304                    (uint8_t)batch_scan_notify_threshold,
    305                    jni_thread_wrapper(FROM_HERE, cb),
    306                    bta_batch_scan_threshold_cb, (tBTM_BLE_REF_VALUE)client_if));
    307   }
    308 
    309   void BatchscanEnable(int scan_mode, int scan_interval, int scan_window,
    310                        int addr_type, int discard_rule, Callback cb) override {
    311     do_in_bta_thread(
    312         FROM_HERE, base::Bind(&BTM_BleEnableBatchScan, scan_mode, scan_interval,
    313                               scan_window, discard_rule, addr_type,
    314                               jni_thread_wrapper(FROM_HERE, cb)));
    315   }
    316 
    317   void BatchscanDisable(Callback cb) override {
    318     do_in_bta_thread(FROM_HERE, base::Bind(&BTM_BleDisableBatchScan,
    319                                            jni_thread_wrapper(FROM_HERE, cb)));
    320   }
    321 
    322   void BatchscanReadReports(int client_if, int scan_mode) override {
    323     do_in_bta_thread(FROM_HERE,
    324                      base::Bind(&BTM_BleReadScanReports, (uint8_t)scan_mode,
    325                                 Bind(bta_batch_scan_reports_cb, client_if)));
    326   }
    327 
    328   void StartSync(uint8_t sid, RawAddress address, uint16_t skip,
    329                  uint16_t timeout, StartSyncCb start_cb, SyncReportCb report_cb,
    330                  SyncLostCb lost_cb) override {}
    331 
    332   void StopSync(uint16_t handle) override {}
    333 };
    334 
    335 BleScannerInterface* btLeScannerInstance = nullptr;
    336 
    337 }  // namespace
    338 
    339 BleScannerInterface* get_ble_scanner_instance() {
    340   if (btLeScannerInstance == nullptr)
    341     btLeScannerInstance = new BleScannerInterfaceImpl();
    342 
    343   return btLeScannerInstance;
    344 }
    345