2 // Copyright 2016 The Android Open Source Project
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:
8 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "service/low_energy_scanner.h"
19 #include "service/adapter.h"
20 #include "service/logging_helpers.h"
21 #include "stack/include/bt_types.h"
22 #include "stack/include/hcidefs.h"
24 #include <base/bind.h>
25 #include <base/callback.h>
26 #include <base/logging.h>
28 using std::lock_guard;
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;
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|.
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)) {
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
52 CHECK(i + field_len < kScanRecordLength);
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
57 if (field_len == 0) return i;
60 // We have reached the end.
61 return kScanRecordLength;
66 // LowEnergyScanner implementation
67 // ========================================================
69 LowEnergyScanner::LowEnergyScanner(Adapter& adapter, const Uuid& uuid,
72 app_identifier_(uuid),
73 scanner_id_(scanner_id),
77 LowEnergyScanner::~LowEnergyScanner() {
78 // Automatically unregister the scanner.
79 VLOG(1) << "LowEnergyScanner unregistering scanner: " << scanner_id_;
81 // Unregister as observer so we no longer receive any callbacks.
82 hal::BluetoothGattInterface::Get()->RemoveScannerObserver(this);
84 hal::BluetoothGattInterface::Get()->GetScannerHALInterface()->Unregister(
87 // Stop any scans started by this client.
88 if (scan_started_.load()) StopScan();
91 void LowEnergyScanner::SetDelegate(Delegate* delegate) {
92 lock_guard<mutex> lock(delegate_mutex_);
96 bool LowEnergyScanner::StartScan(const ScanSettings& settings,
97 const std::vector<ScanFilter>& filters) {
100 // Cannot start a scan if the adapter is not enabled.
101 if (!adapter_.IsEnabled()) {
102 LOG(ERROR) << "Cannot scan while Bluetooth is disabled";
106 // TODO(jpawlowski): Push settings and filtering logic below the HAL.
108 hal::BluetoothGattInterface::Get()->StartScan(scanner_id_);
109 if (status != BT_STATUS_SUCCESS) {
110 LOG(ERROR) << "Failed to initiate scanning for client: " << scanner_id_;
114 scan_started_ = true;
118 bool LowEnergyScanner::StopScan() {
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.
125 hal::BluetoothGattInterface::Get()->StopScan(scanner_id_);
126 if (status != BT_STATUS_SUCCESS) {
127 LOG(ERROR) << "Failed to stop scan for client: " << scanner_id_;
131 scan_started_ = false;
135 const Uuid& LowEnergyScanner::GetAppIdentifier() const {
136 return app_identifier_;
139 int LowEnergyScanner::GetInstanceId() const { return scanner_id_; }
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;
147 lock_guard<mutex> lock(delegate_mutex_);
148 if (!delegate_) return;
150 // TODO(armansito): Apply software filters here.
152 size_t record_len = GetScanRecordLength(adv_data);
153 std::vector<uint8_t> scan_record(adv_data.begin(),
154 adv_data.begin() + record_len);
156 ScanResult result(BtAddrString(&bda), scan_record, rssi);
158 delegate_->OnScanResult(this, result);
161 // LowEnergyScannerFactory implementation
162 // ========================================================
164 LowEnergyScannerFactory::LowEnergyScannerFactory(Adapter& adapter)
165 : adapter_(adapter) {
166 hal::BluetoothGattInterface::Get()->AddScannerObserver(this);
169 LowEnergyScannerFactory::~LowEnergyScannerFactory() {
170 hal::BluetoothGattInterface::Get()->RemoveScannerObserver(this);
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_);
178 if (pending_calls_.find(uuid) != pending_calls_.end()) {
179 LOG(ERROR) << "Low-Energy scanner with given Uuid already registered - "
180 << "Uuid: " << uuid.ToString();
184 BleScannerInterface* hal_iface =
185 hal::BluetoothGattInterface::Get()->GetScannerHALInterface();
187 hal_iface->RegisterScanner(
188 base::Bind(&LowEnergyScannerFactory::RegisterScannerCallback,
189 base::Unretained(this), callback, uuid));
191 pending_calls_.insert(uuid);
196 void LowEnergyScannerFactory::RegisterScannerCallback(
197 const RegisterCallback& callback, const Uuid& app_uuid, uint8_t scanner_id,
201 VLOG(1) << __func__ << " - Uuid: " << uuid.ToString();
202 lock_guard<mutex> lock(pending_calls_lock_);
204 auto iter = pending_calls_.find(uuid);
205 if (iter == pending_calls_.end()) {
206 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
210 // No need to construct a scanner if the call wasn't successful.
211 std::unique_ptr<LowEnergyScanner> scanner;
212 BLEStatus result = BLE_STATUS_FAILURE;
213 if (status == BT_STATUS_SUCCESS) {
214 scanner.reset(new LowEnergyScanner(adapter_, uuid, scanner_id));
216 hal::BluetoothGattInterface::Get()->AddScannerObserver(scanner.get());
218 result = BLE_STATUS_SUCCESS;
221 // Notify the result via the result callback.
222 callback(result, app_uuid, std::move(scanner));
224 pending_calls_.erase(iter);
227 } // namespace bluetooth