• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //  Copyright 2016 The Android Open Source Project
3 //
4 //  Licensed under the Apache License, Version 2.0 (the "License");
5 //  you may not use this file except in compliance with the License.
6 //  You may obtain a copy of the License at:
7 //
8 //  http://www.apache.org/licenses/LICENSE-2.0
9 //
10 //  Unless required by applicable law or agreed to in writing, software
11 //  distributed under the License is distributed on an "AS IS" BASIS,
12 //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 //  See the License for the specific language governing permissions and
14 //  limitations under the License.
15 //
16 
17 #include "service/low_energy_scanner.h"
18 
19 #include "service/adapter.h"
20 #include "service/logging_helpers.h"
21 #include "stack/include/bt_types.h"
22 #include "stack/include/hcidefs.h"
23 
24 #include <base/bind.h>
25 #include <base/callback.h>
26 #include <base/logging.h>
27 
28 using std::lock_guard;
29 using std::mutex;
30 
31 namespace bluetooth {
32 
33 namespace {
34 
35 // 31 + 31 for advertising data and scan response. This is the maximum length
36 // TODO(armansito): Fix the HAL to return a concatenated blob that contains the
37 // true length of each field and also provide a length parameter so that we
38 // can support advertising length extensions in the future.
39 const size_t kScanRecordLength = 62;
40 
41 // Returns the length of the given scan record array. We have to calculate this
42 // based on the maximum possible data length and the TLV data. See TODO above
43 // |kScanRecordLength|.
GetScanRecordLength(std::vector<uint8_t> bytes)44 size_t GetScanRecordLength(std::vector<uint8_t> bytes) {
45   for (size_t i = 0, field_len = 0; i < kScanRecordLength;
46        i += (field_len + 1)) {
47     field_len = bytes[i];
48 
49     // Assert here that the data returned from the stack is correctly formatted
50     // in TLV form and that the length of the current field won't exceed the
51     // total data length.
52     CHECK(i + field_len < kScanRecordLength);
53 
54     // If the field length is zero and we haven't reached the maximum length,
55     // then we have found the length, as the stack will pad the data with zeros
56     // accordingly.
57     if (field_len == 0) return i;
58   }
59 
60   // We have reached the end.
61   return kScanRecordLength;
62 }
63 
64 }  // namespace
65 
66 // LowEnergyScanner implementation
67 // ========================================================
68 
LowEnergyScanner(Adapter & adapter,const Uuid & uuid,int scanner_id)69 LowEnergyScanner::LowEnergyScanner(Adapter& adapter, const Uuid& uuid,
70                                    int scanner_id)
71     : adapter_(adapter),
72       app_identifier_(uuid),
73       scanner_id_(scanner_id),
74       scan_started_(false),
75       delegate_(nullptr) {}
76 
~LowEnergyScanner()77 LowEnergyScanner::~LowEnergyScanner() {
78   // Automatically unregister the scanner.
79   VLOG(1) << "LowEnergyScanner unregistering scanner: " << scanner_id_;
80 
81   // Unregister as observer so we no longer receive any callbacks.
82   hal::BluetoothGattInterface::Get()->RemoveScannerObserver(this);
83 
84   hal::BluetoothGattInterface::Get()->GetScannerHALInterface()->Unregister(
85       scanner_id_);
86 
87   // Stop any scans started by this client.
88   if (scan_started_.load()) StopScan();
89 }
90 
SetDelegate(Delegate * delegate)91 void LowEnergyScanner::SetDelegate(Delegate* delegate) {
92   lock_guard<mutex> lock(delegate_mutex_);
93   delegate_ = delegate;
94 }
95 
StartScan(const ScanSettings & settings,const std::vector<ScanFilter> & filters)96 bool LowEnergyScanner::StartScan(const ScanSettings& settings,
97                                  const std::vector<ScanFilter>& filters) {
98   VLOG(2) << __func__;
99 
100   // Cannot start a scan if the adapter is not enabled.
101   if (!adapter_.IsEnabled()) {
102     LOG(ERROR) << "Cannot scan while Bluetooth is disabled";
103     return false;
104   }
105 
106   // TODO(jpawlowski): Push settings and filtering logic below the HAL.
107   bt_status_t status =
108       hal::BluetoothGattInterface::Get()->StartScan(scanner_id_);
109   if (status != BT_STATUS_SUCCESS) {
110     LOG(ERROR) << "Failed to initiate scanning for client: " << scanner_id_;
111     return false;
112   }
113 
114   scan_started_ = true;
115   return true;
116 }
117 
StopScan()118 bool LowEnergyScanner::StopScan() {
119   VLOG(2) << __func__;
120 
121   // TODO(armansito): We don't support batch scanning yet so call
122   // StopRegularScanForClient directly. In the future we will need to
123   // conditionally call a batch scan API here.
124   bt_status_t status =
125       hal::BluetoothGattInterface::Get()->StopScan(scanner_id_);
126   if (status != BT_STATUS_SUCCESS) {
127     LOG(ERROR) << "Failed to stop scan for client: " << scanner_id_;
128     return false;
129   }
130 
131   scan_started_ = false;
132   return true;
133 }
134 
GetAppIdentifier() const135 const Uuid& LowEnergyScanner::GetAppIdentifier() const {
136   return app_identifier_;
137 }
138 
GetInstanceId() const139 int LowEnergyScanner::GetInstanceId() const { return scanner_id_; }
140 
ScanResultCallback(hal::BluetoothGattInterface * gatt_iface,const RawAddress & bda,int rssi,std::vector<uint8_t> adv_data)141 void LowEnergyScanner::ScanResultCallback(
142     hal::BluetoothGattInterface* gatt_iface, const RawAddress& bda, int rssi,
143     std::vector<uint8_t> adv_data) {
144   // Ignore scan results if this client didn't start a scan.
145   if (!scan_started_.load()) return;
146 
147   lock_guard<mutex> lock(delegate_mutex_);
148   if (!delegate_) return;
149 
150   // TODO(armansito): Apply software filters here.
151 
152   size_t record_len = GetScanRecordLength(adv_data);
153   std::vector<uint8_t> scan_record(adv_data.begin(),
154                                    adv_data.begin() + record_len);
155 
156   ScanResult result(BtAddrString(&bda), scan_record, rssi);
157 
158   delegate_->OnScanResult(this, result);
159 }
160 
161 // LowEnergyScannerFactory implementation
162 // ========================================================
163 
LowEnergyScannerFactory(Adapter & adapter)164 LowEnergyScannerFactory::LowEnergyScannerFactory(Adapter& adapter)
165     : adapter_(adapter) {
166   hal::BluetoothGattInterface::Get()->AddScannerObserver(this);
167 }
168 
~LowEnergyScannerFactory()169 LowEnergyScannerFactory::~LowEnergyScannerFactory() {
170   hal::BluetoothGattInterface::Get()->RemoveScannerObserver(this);
171 }
172 
RegisterInstance(const Uuid & uuid,const RegisterCallback & callback)173 bool LowEnergyScannerFactory::RegisterInstance(
174     const Uuid& uuid, const RegisterCallback& callback) {
175   VLOG(1) << __func__ << " - Uuid: " << uuid.ToString();
176   lock_guard<mutex> lock(pending_calls_lock_);
177 
178   if (pending_calls_.find(uuid) != pending_calls_.end()) {
179     LOG(ERROR) << "Low-Energy scanner with given Uuid already registered - "
180                << "Uuid: " << uuid.ToString();
181     return false;
182   }
183 
184   BleScannerInterface* hal_iface =
185       hal::BluetoothGattInterface::Get()->GetScannerHALInterface();
186 
187   Uuid uuid_empty = Uuid::kEmpty;
188 
189   hal_iface->RegisterScanner(
190       uuid_empty, base::Bind(&LowEnergyScannerFactory::RegisterScannerCallback,
191                              base::Unretained(this), callback, uuid));
192 
193   pending_calls_.insert(uuid);
194 
195   return true;
196 }
197 
RegisterScannerCallback(const RegisterCallback & callback,const Uuid & app_uuid,uint8_t scanner_id,uint8_t status)198 void LowEnergyScannerFactory::RegisterScannerCallback(
199     const RegisterCallback& callback, const Uuid& app_uuid, uint8_t scanner_id,
200     uint8_t status) {
201   Uuid uuid(app_uuid);
202 
203   VLOG(1) << __func__ << " - Uuid: " << uuid.ToString();
204   lock_guard<mutex> lock(pending_calls_lock_);
205 
206   auto iter = pending_calls_.find(uuid);
207   if (iter == pending_calls_.end()) {
208     VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
209     return;
210   }
211 
212   // No need to construct a scanner if the call wasn't successful.
213   std::unique_ptr<LowEnergyScanner> scanner;
214   BLEStatus result = BLE_STATUS_FAILURE;
215   if (status == BT_STATUS_SUCCESS) {
216     scanner.reset(new LowEnergyScanner(adapter_, uuid, scanner_id));
217 
218     hal::BluetoothGattInterface::Get()->AddScannerObserver(scanner.get());
219 
220     result = BLE_STATUS_SUCCESS;
221   }
222 
223   // Notify the result via the result callback.
224   callback(result, app_uuid, std::move(scanner));
225 
226   pending_calls_.erase(iter);
227 }
228 
229 }  // namespace bluetooth
230