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