blob: 0f1c62698d9d125dbcb1c9bce6a9a44c22bbe500 [file] [log] [blame]
Arman Ugurayc2fc0f22015-09-03 15:09:41 -07001//
2// Copyright (C) 2015 Google, Inc.
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_client.h"
18
19#include <base/logging.h>
20
Arman Uguray12338402015-09-16 18:00:05 -070021#include "stack/include/bt_types.h"
22#include "stack/include/hcidefs.h"
23
Arman Ugurayc2fc0f22015-09-03 15:09:41 -070024using std::lock_guard;
25using std::mutex;
26
27namespace bluetooth {
28
Arman Uguray12338402015-09-16 18:00:05 -070029namespace {
30
31BLEStatus GetBLEStatus(int status) {
32 if (status == BT_STATUS_FAIL)
33 return BLE_STATUS_FAILURE;
34
35 return static_cast<BLEStatus>(status);
36}
37
38// TODO(armansito): BTIF currently expects each advertising field in a
39// specific format passed directly in arguments. We should fix BTIF to accept
40// the advertising data directly instead.
41struct HALAdvertiseData {
42 std::vector<uint8_t> manufacturer_data;
43 std::vector<uint8_t> service_data;
44 std::vector<uint8_t> service_uuid;
45};
46
47bool ProcessAdvertiseData(const AdvertiseData& adv,
48 HALAdvertiseData* out_data) {
49 CHECK(out_data);
50 CHECK(out_data->manufacturer_data.empty());
51 CHECK(out_data->service_data.empty());
52 CHECK(out_data->service_uuid.empty());
53
54 const auto& data = adv.data();
55 size_t len = data.size();
56 for (size_t i = 0, field_len = 0; i < len; i += (field_len + 1)) {
57 // The length byte is the first byte in the adv. "TLV" format.
58 field_len = data[i];
59
60 // The type byte is the next byte in the adv. "TLV" format.
61 uint8_t type = data[i + 1];
62 size_t uuid_len = 0;
63
64 switch (type) {
65 case HCI_EIR_MANUFACTURER_SPECIFIC_TYPE: {
66 // TODO(armansito): BTIF doesn't allow setting more than one
67 // manufacturer-specific data entry. This is something we should fix. For
68 // now, fail if more than one entry was set.
69 if (!out_data->manufacturer_data.empty()) {
70 VLOG(1) << "More than one Manufacturer Specific Data entry not allowed";
71 return false;
72 }
73
74 // The value bytes start at the next byte in the "TLV" format.
75 const uint8_t* mnf_data = data.data() + i + 2;
76 out_data->manufacturer_data.insert(
77 out_data->manufacturer_data.begin(),
78 mnf_data, mnf_data + field_len - 1);
79 break;
80 }
81 // TODO(armansito): Support other fields.
82 default:
83 VLOG(1) << "Unrecognized EIR field: " << type;
84 return false;
85 }
86 }
87
88 return true;
89}
90
91// The Bluetooth Core Specification defines time interval (e.g. Page Scan
92// Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1
93// Baseband slot). The HAL advertising functions expect the interval in this
94// unit. This function maps an AdvertiseSettings::Mode value to the
95// corresponding time unit.
96int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
97 int ms;
98
99 switch (mode) {
100 case AdvertiseSettings::MODE_BALANCED:
101 ms = kAdvertisingIntervalMediumMs;
102 break;
103 case AdvertiseSettings::MODE_LOW_LATENCY:
104 ms = kAdvertisingIntervalLowMs;
105 break;
106 case AdvertiseSettings::MODE_LOW_POWER:
107 // Fall through
108 default:
109 ms = kAdvertisingIntervalHighMs;
110 break;
111 }
112
113 // Convert milliseconds Bluetooth units.
114 return (ms * 1000) / 625;
115}
116
117struct AdvertiseParams {
118 int min_interval;
119 int max_interval;
120 int event_type;
121 int tx_power_level;
122 int timeout_s;
123};
124
125void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
126 AdvertiseParams* out_params) {
127 CHECK(out_params);
128
129 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
130 out_params->max_interval =
131 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
132
133 if (settings.connectable())
134 out_params->event_type = kAdvertisingEventTypeConnectable;
135 else if (has_scan_rsp)
136 out_params->event_type = kAdvertisingEventTypeScannable;
137 else
138 out_params->event_type = kAdvertisingEventTypeNonConnectable;
139
140 out_params->tx_power_level = settings.tx_power_level();
141 out_params->timeout_s = settings.timeout().InSeconds();
142}
143
144} // namespace
145
146// LowEnergyClient implementation
147// ========================================================
148
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700149LowEnergyClient::LowEnergyClient(const UUID& uuid, int client_if)
150 : app_identifier_(uuid),
Arman Uguray12338402015-09-16 18:00:05 -0700151 client_if_(client_if),
152 adv_data_needs_update_(false),
153 scan_rsp_needs_update_(false),
154 is_setting_adv_data_(false),
155 adv_started_(false),
156 adv_start_callback_(nullptr),
157 adv_stop_callback_(nullptr) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700158}
159
160LowEnergyClient::~LowEnergyClient() {
161 // Automatically unregister the client.
162 VLOG(1) << "LowEnergyClient unregistering client: " << client_if_;
Arman Uguray12338402015-09-16 18:00:05 -0700163
164 // Unregister as observer so we no longer receive any callbacks.
165 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
166
167 // Stop advertising and ignore the result.
168 hal::BluetoothGattInterface::Get()->
169 GetClientHALInterface()->multi_adv_disable(client_if_);
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700170 hal::BluetoothGattInterface::Get()->
171 GetClientHALInterface()->unregister_client(client_if_);
172}
173
Arman Uguray12338402015-09-16 18:00:05 -0700174bool LowEnergyClient::StartAdvertising(const AdvertiseSettings& settings,
175 const AdvertiseData& advertise_data,
176 const AdvertiseData& scan_response,
177 const StatusCallback& callback) {
178 VLOG(2) << __func__;
179 lock_guard<mutex> lock(adv_fields_lock_);
180
181 if (IsAdvertisingStarted()) {
182 LOG(WARNING) << "Already advertising";
183 return false;
184 }
185
186 if (IsStartingAdvertising()) {
187 LOG(WARNING) << "StartAdvertising already pending";
188 return false;
189 }
190
191 if (!advertise_data.IsValid()) {
192 LOG(ERROR) << "Invalid advertising data";
193 return false;
194 }
195
196 if (!scan_response.IsValid()) {
197 LOG(ERROR) << "Invalid scan response data";
198 return false;
199 }
200
201 CHECK(!adv_data_needs_update_.load());
202 CHECK(!scan_rsp_needs_update_.load());
203
204 adv_data_ = advertise_data;
205 scan_response_ = scan_response;
206 settings_ = settings;
207
208 AdvertiseParams params;
209 GetAdvertiseParams(settings, !scan_response_.data().empty(), &params);
210
211 bt_status_t status = hal::BluetoothGattInterface::Get()->
212 GetClientHALInterface()->multi_adv_enable(
213 client_if_,
214 params.min_interval,
215 params.max_interval,
216 params.event_type,
217 kAdvertisingChannelAll,
218 params.tx_power_level,
219 params.timeout_s);
220 if (status != BT_STATUS_SUCCESS) {
221 LOG(ERROR) << "Failed to initiate call to enable multi-advertising";
222 return false;
223 }
224
225 // Always update advertising data.
226 adv_data_needs_update_ = true;
227
228 // Update scan response only if it has data, since otherwise we just won't
229 // send ADV_SCAN_IND.
230 if (!scan_response_.data().empty())
231 scan_rsp_needs_update_ = true;
232
233 // OK to set this at the end since we're still holding |adv_fields_lock_|.
234 adv_start_callback_.reset(new StatusCallback(callback));
235
236 return true;
237}
238
239bool LowEnergyClient::StopAdvertising(const StatusCallback& callback) {
240 VLOG(2) << __func__;
241 lock_guard<mutex> lock(adv_fields_lock_);
242
243 if (!IsAdvertisingStarted()) {
244 LOG(ERROR) << "Not advertising";
245 return false;
246 }
247
248 if (IsStoppingAdvertising()) {
249 LOG(ERROR) << "StopAdvertising already pending";
250 return false;
251 }
252
253 CHECK(!adv_start_callback_);
254
255 bt_status_t status = hal::BluetoothGattInterface::Get()->
256 GetClientHALInterface()->multi_adv_disable(client_if_);
257 if (status != BT_STATUS_SUCCESS) {
258 LOG(ERROR) << "Failed to initiate call to disable multi-advertising";
259 return false;
260 }
261
262 // OK to set this at the end since we're still holding |adv_fields_lock_|.
263 adv_stop_callback_.reset(new StatusCallback(callback));
264
265 return true;
266}
267
268bool LowEnergyClient::IsAdvertisingStarted() const {
269 return adv_started_.load();
270}
271
272bool LowEnergyClient::IsStartingAdvertising() const {
273 return !IsAdvertisingStarted() && adv_start_callback_;
274}
275
276bool LowEnergyClient::IsStoppingAdvertising() const {
277 return IsAdvertisingStarted() && adv_stop_callback_;
278}
279
Arman Uguray08f80eb2015-09-21 11:17:07 -0700280const UUID& LowEnergyClient::GetAppIdentifier() const {
281 return app_identifier_;
282}
283
284int LowEnergyClient::GetClientId() const {
285 return client_if_;
286}
287
Arman Uguray12338402015-09-16 18:00:05 -0700288void LowEnergyClient::MultiAdvEnableCallback(
289 hal::BluetoothGattInterface* gatt_iface,
290 int client_if, int status) {
291 if (client_if != client_if_)
292 return;
293
294 lock_guard<mutex> lock(adv_fields_lock_);
295
296 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
297
298 CHECK(adv_start_callback_);
299 CHECK(!adv_stop_callback_);
300
301 // Terminate operation in case of error.
302 if (status != BT_STATUS_SUCCESS) {
303 LOG(ERROR) << "Failed to enable multi-advertising";
304 InvokeAndClearStartCallback(GetBLEStatus(status));
305 return;
306 }
307
308 // Now handle deferred tasks.
309 HandleDeferredAdvertiseData(gatt_iface);
310}
311
312void LowEnergyClient::MultiAdvDataCallback(
313 hal::BluetoothGattInterface* gatt_iface,
314 int client_if, int status) {
315 if (client_if != client_if_)
316 return;
317
318 lock_guard<mutex> lock(adv_fields_lock_);
319
320 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
321
322 is_setting_adv_data_ = false;
323
324 // Terminate operation in case of error.
325 if (status != BT_STATUS_SUCCESS) {
326 LOG(ERROR) << "Failed to set advertising data";
327 InvokeAndClearStartCallback(GetBLEStatus(status));
328 return;
329 }
330
331 // Now handle deferred tasks.
332 HandleDeferredAdvertiseData(gatt_iface);
333}
334
335void LowEnergyClient::MultiAdvDisableCallback(
336 hal::BluetoothGattInterface* /* gatt_iface */,
337 int client_if, int status) {
338 if (client_if != client_if_)
339 return;
340
341 lock_guard<mutex> lock(adv_fields_lock_);
342
343 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
344
345 CHECK(!adv_start_callback_);
346 CHECK(adv_stop_callback_);
347
348 if (status == BT_STATUS_SUCCESS) {
349 VLOG(1) << "Multi-advertising stopped for client_if: " << client_if;
350 adv_started_ = false;
351 } else {
352 LOG(ERROR) << "Failed to stop multi-advertising";
353 }
354
355 InvokeAndClearStopCallback(GetBLEStatus(status));
356}
357
358bt_status_t LowEnergyClient::SetAdvertiseData(
359 hal::BluetoothGattInterface* gatt_iface,
360 const AdvertiseData& data,
361 bool set_scan_rsp) {
362 VLOG(2) << __func__;
363
364 HALAdvertiseData hal_data;
365
366 // TODO(armansito): The stack should check that the length is valid when other
367 // fields inserted by the stack (e.g. flags, device name, tx-power) are taken
368 // into account. At the moment we are skipping this check; this means that if
369 // the given data is too long then the stack will truncate it.
370 if (!ProcessAdvertiseData(data, &hal_data)) {
371 VLOG(1) << "Malformed advertise data given";
372 return BT_STATUS_FAIL;
373 }
374
375 if (is_setting_adv_data_.load()) {
376 VLOG(1) << "Setting advertising data already in progress.";
377 return BT_STATUS_FAIL;
378 }
379
380 // TODO(armansito): The length fields in the BTIF function below are signed
381 // integers so a call to std::vector::size might get capped. This is very
382 // unlikely anyway but it's safer to stop using signed-integer types for
383 // length in APIs, so we should change that.
384 bt_status_t status = gatt_iface->GetClientHALInterface()->
385 multi_adv_set_inst_data(
386 client_if_,
387 set_scan_rsp,
388 data.include_device_name(),
389 data.include_tx_power_level(),
390 0, // This is what Bluetooth.apk current hardcodes for "appearance".
391 hal_data.manufacturer_data.size(),
392 reinterpret_cast<char*>(hal_data.manufacturer_data.data()),
393 0, nullptr, 0, nullptr); // TODO(armansito): Support the rest.
394 if (status != BT_STATUS_SUCCESS) {
395 LOG(ERROR) << "Failed to set instance advertising data.";
396 return status;
397 }
398
399 if (set_scan_rsp)
400 scan_rsp_needs_update_ = false;
401 else
402 adv_data_needs_update_ = false;
403
404 is_setting_adv_data_ = true;
405
406 return status;
407}
408
409void LowEnergyClient::HandleDeferredAdvertiseData(
410 hal::BluetoothGattInterface* gatt_iface) {
411 VLOG(2) << __func__;
412
413 CHECK(!IsAdvertisingStarted());
414 CHECK(!IsStoppingAdvertising());
415 CHECK(IsStartingAdvertising());
416 CHECK(!is_setting_adv_data_.load());
417
418 if (adv_data_needs_update_.load()) {
419 bt_status_t status = SetAdvertiseData(gatt_iface, adv_data_, false);
420 if (status != BT_STATUS_SUCCESS) {
421 LOG(ERROR) << "Failed setting advertisement data";
422 InvokeAndClearStartCallback(GetBLEStatus(status));
423 }
424 return;
425 }
426
427 if (scan_rsp_needs_update_.load()) {
428 bt_status_t status = SetAdvertiseData(gatt_iface, scan_response_, true);
429 if (status != BT_STATUS_SUCCESS) {
430 LOG(ERROR) << "Failed setting scan response data";
431 InvokeAndClearStartCallback(GetBLEStatus(status));
432 }
433 return;
434 }
435
436 // All pending tasks are complete. Report success.
437 adv_started_ = true;
438 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
439}
440
441void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
442 adv_data_needs_update_ = false;
443 scan_rsp_needs_update_ = false;
444
445 // We allow NULL callbacks.
446 if (*adv_start_callback_)
447 (*adv_start_callback_)(status);
448
449 adv_start_callback_ = nullptr;
450}
451
452void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
453 // We allow NULL callbacks.
454 if (*adv_stop_callback_)
455 (*adv_stop_callback_)(status);
456
457 adv_stop_callback_ = nullptr;
458}
459
460// LowEnergyClientFactory implementation
461// ========================================================
462
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700463LowEnergyClientFactory::LowEnergyClientFactory() {
464 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
465}
466
467LowEnergyClientFactory::~LowEnergyClientFactory() {
468 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
469}
470
471bool LowEnergyClientFactory::RegisterClient(const UUID& uuid,
Arman Uguray08f80eb2015-09-21 11:17:07 -0700472 const RegisterCallback& callback) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700473 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
474 lock_guard<mutex> lock(pending_calls_lock_);
475
476 if (pending_calls_.find(uuid) != pending_calls_.end()) {
477 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
478 << "UUID: " << uuid.ToString();
479 return false;
480 }
481
482 const btgatt_client_interface_t* hal_iface =
483 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
484 bt_uuid_t app_uuid = uuid.GetBlueDroid();
485
486 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
487 return false;
488
489 pending_calls_[uuid] = callback;
490
491 return true;
492}
493
494void LowEnergyClientFactory::RegisterClientCallback(
Arman Uguray12338402015-09-16 18:00:05 -0700495 hal::BluetoothGattInterface* gatt_iface,
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700496 int status, int client_if,
497 const bt_uuid_t& app_uuid) {
498 UUID uuid(app_uuid);
499
500 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
501 lock_guard<mutex> lock(pending_calls_lock_);
502
503 auto iter = pending_calls_.find(uuid);
504 if (iter == pending_calls_.end()) {
505 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
506 return;
507 }
508
509 // No need to construct a client if the call wasn't successful.
510 std::unique_ptr<LowEnergyClient> client;
511 BLEStatus result = BLE_STATUS_FAILURE;
512 if (status == BT_STATUS_SUCCESS) {
513 client.reset(new LowEnergyClient(uuid, client_if));
Arman Uguray12338402015-09-16 18:00:05 -0700514
515 // Use the unsafe variant to register this as an observer, since
516 // LowEnergyClient instances only get created by LowEnergyClientCallback
517 // from inside this GATT client observer event, which would otherwise cause
518 // a deadlock.
519 gatt_iface->AddClientObserverUnsafe(client.get());
520
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700521 result = BLE_STATUS_SUCCESS;
522 }
523
Arman Uguray08f80eb2015-09-21 11:17:07 -0700524 // Notify the result via the result callback.
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700525 iter->second(result, uuid, std::move(client));
526
527 pending_calls_.erase(iter);
528}
529
530} // namespace bluetooth