blob: 43d8d101b31b0cd0fbad1f67846dde511bd50b42 [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
Ajay Panickerff651b72015-09-30 15:49:47 -070047bool ProcessServiceData(const uint8_t* data,
48 uint8_t uuidlen,
49 HALAdvertiseData* out_data){
50 size_t field_len = data[0];
51
52 // Minimum packet size should be equal to the uuid length + 1 to include
53 // the byte for the type of packet
54 if (field_len < uuidlen + 1) {
55 // Invalid packet size
56 return false;
57 }
58
59 if (!out_data->service_data.empty()) {
60 // More than one Service Data is not allowed due to the limitations
61 // of the HAL API. We error in order to make sure there
62 // is no ambiguity on which data to send.
63 VLOG(1) << "More than one Service Data entry not allowed";
64 return false;
65 }
66
67 const uint8_t* service_uuid = data + 2;
68 const std::vector<uint8_t> temp_uuid(service_uuid, service_uuid + uuidlen);
69
70 // This section is to make sure that there is no UUID conflict
71 if (out_data->service_uuid.empty()) {
72 out_data->service_uuid = temp_uuid;
73 } else if (out_data->service_uuid != temp_uuid) {
74 // Mismatch in uuid passed through service data and uuid passed
75 // through uuid field
76 VLOG(1) << "More than one UUID entry not allowed";
77 return false;
78 } // else do nothing as UUID is already properly assigned
79
80 // Use + uuidlen + 2 here in order to skip over a
81 // uuid contained in the beggining of the field
82 const uint8_t* srv_data = data + uuidlen + 2;
83
84
85 out_data->service_data.insert(
86 out_data->service_data.begin(),
87 srv_data, srv_data + field_len - uuidlen - 1);
88
89 return true;
90}
91
Arman Uguray12338402015-09-16 18:00:05 -070092bool ProcessAdvertiseData(const AdvertiseData& adv,
93 HALAdvertiseData* out_data) {
94 CHECK(out_data);
95 CHECK(out_data->manufacturer_data.empty());
96 CHECK(out_data->service_data.empty());
97 CHECK(out_data->service_uuid.empty());
98
99 const auto& data = adv.data();
100 size_t len = data.size();
101 for (size_t i = 0, field_len = 0; i < len; i += (field_len + 1)) {
102 // The length byte is the first byte in the adv. "TLV" format.
103 field_len = data[i];
104
105 // The type byte is the next byte in the adv. "TLV" format.
106 uint8_t type = data[i + 1];
107 size_t uuid_len = 0;
108
109 switch (type) {
110 case HCI_EIR_MANUFACTURER_SPECIFIC_TYPE: {
111 // TODO(armansito): BTIF doesn't allow setting more than one
112 // manufacturer-specific data entry. This is something we should fix. For
113 // now, fail if more than one entry was set.
114 if (!out_data->manufacturer_data.empty()) {
115 VLOG(1) << "More than one Manufacturer Specific Data entry not allowed";
116 return false;
117 }
118
119 // The value bytes start at the next byte in the "TLV" format.
120 const uint8_t* mnf_data = data.data() + i + 2;
121 out_data->manufacturer_data.insert(
122 out_data->manufacturer_data.begin(),
123 mnf_data, mnf_data + field_len - 1);
124 break;
125 }
Ajay Panickerff651b72015-09-30 15:49:47 -0700126 case HCI_EIR_MORE_16BITS_UUID_TYPE:
127 case HCI_EIR_COMPLETE_16BITS_UUID_TYPE:
128 case HCI_EIR_MORE_32BITS_UUID_TYPE:
129 case HCI_EIR_COMPLETE_32BITS_UUID_TYPE:
130 case HCI_EIR_MORE_128BITS_UUID_TYPE:
131 case HCI_EIR_COMPLETE_128BITS_UUID_TYPE: {
132 const uint8_t* uuid_data = data.data() + i + 2;
133
134 if (!out_data->service_uuid.empty() &&
135 memcmp(out_data->service_uuid.data(), uuid_data, field_len - 1) != 0) {
136 // More than one UUID is not allowed due to the limitations
137 // of the HAL API. We error in order to make sure there
138 // is no ambiguity on which UUID to send. Also makes sure that
139 // UUID Hasn't been set by service data first
140 VLOG(1) << "More than one UUID entry not allowed";
141 return false;
142 }
143
144 out_data->service_uuid.assign(
145 uuid_data, uuid_data + field_len - 1);
146 break;
147 }
148 case HCI_EIR_SERVICE_DATA_16BITS_UUID_TYPE: {
149 if (!ProcessServiceData(data.data() + i, 2, out_data))
150 return false;
151 break;
152 }
153 case HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE: {
154 if (!ProcessServiceData(data.data() + i, 4, out_data))
155 return false;
156 break;
157 }
158 case HCI_EIR_SERVICE_DATA_128BITS_UUID_TYPE: {
159 if (!ProcessServiceData(data.data() + i, 16, out_data))
160 return false;
161 break;
162 }
Arman Uguray12338402015-09-16 18:00:05 -0700163 // TODO(armansito): Support other fields.
164 default:
165 VLOG(1) << "Unrecognized EIR field: " << type;
166 return false;
167 }
168 }
169
170 return true;
171}
172
173// The Bluetooth Core Specification defines time interval (e.g. Page Scan
174// Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1
175// Baseband slot). The HAL advertising functions expect the interval in this
176// unit. This function maps an AdvertiseSettings::Mode value to the
177// corresponding time unit.
178int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
179 int ms;
180
181 switch (mode) {
182 case AdvertiseSettings::MODE_BALANCED:
183 ms = kAdvertisingIntervalMediumMs;
184 break;
185 case AdvertiseSettings::MODE_LOW_LATENCY:
186 ms = kAdvertisingIntervalLowMs;
187 break;
188 case AdvertiseSettings::MODE_LOW_POWER:
189 // Fall through
190 default:
191 ms = kAdvertisingIntervalHighMs;
192 break;
193 }
194
195 // Convert milliseconds Bluetooth units.
196 return (ms * 1000) / 625;
197}
198
199struct AdvertiseParams {
200 int min_interval;
201 int max_interval;
202 int event_type;
203 int tx_power_level;
204 int timeout_s;
205};
206
207void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
208 AdvertiseParams* out_params) {
209 CHECK(out_params);
210
211 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
212 out_params->max_interval =
213 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
214
215 if (settings.connectable())
216 out_params->event_type = kAdvertisingEventTypeConnectable;
217 else if (has_scan_rsp)
218 out_params->event_type = kAdvertisingEventTypeScannable;
219 else
220 out_params->event_type = kAdvertisingEventTypeNonConnectable;
221
222 out_params->tx_power_level = settings.tx_power_level();
223 out_params->timeout_s = settings.timeout().InSeconds();
224}
225
226} // namespace
227
228// LowEnergyClient implementation
229// ========================================================
230
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700231LowEnergyClient::LowEnergyClient(const UUID& uuid, int client_if)
232 : app_identifier_(uuid),
Arman Uguray12338402015-09-16 18:00:05 -0700233 client_if_(client_if),
234 adv_data_needs_update_(false),
235 scan_rsp_needs_update_(false),
236 is_setting_adv_data_(false),
237 adv_started_(false),
238 adv_start_callback_(nullptr),
239 adv_stop_callback_(nullptr) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700240}
241
242LowEnergyClient::~LowEnergyClient() {
243 // Automatically unregister the client.
244 VLOG(1) << "LowEnergyClient unregistering client: " << client_if_;
Arman Uguray12338402015-09-16 18:00:05 -0700245
246 // Unregister as observer so we no longer receive any callbacks.
247 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
248
249 // Stop advertising and ignore the result.
250 hal::BluetoothGattInterface::Get()->
251 GetClientHALInterface()->multi_adv_disable(client_if_);
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700252 hal::BluetoothGattInterface::Get()->
253 GetClientHALInterface()->unregister_client(client_if_);
254}
255
Arman Uguray12338402015-09-16 18:00:05 -0700256bool LowEnergyClient::StartAdvertising(const AdvertiseSettings& settings,
257 const AdvertiseData& advertise_data,
258 const AdvertiseData& scan_response,
259 const StatusCallback& callback) {
260 VLOG(2) << __func__;
261 lock_guard<mutex> lock(adv_fields_lock_);
262
263 if (IsAdvertisingStarted()) {
264 LOG(WARNING) << "Already advertising";
265 return false;
266 }
267
268 if (IsStartingAdvertising()) {
269 LOG(WARNING) << "StartAdvertising already pending";
270 return false;
271 }
272
273 if (!advertise_data.IsValid()) {
274 LOG(ERROR) << "Invalid advertising data";
275 return false;
276 }
277
278 if (!scan_response.IsValid()) {
279 LOG(ERROR) << "Invalid scan response data";
280 return false;
281 }
282
283 CHECK(!adv_data_needs_update_.load());
284 CHECK(!scan_rsp_needs_update_.load());
285
286 adv_data_ = advertise_data;
287 scan_response_ = scan_response;
288 settings_ = settings;
289
290 AdvertiseParams params;
291 GetAdvertiseParams(settings, !scan_response_.data().empty(), &params);
292
293 bt_status_t status = hal::BluetoothGattInterface::Get()->
294 GetClientHALInterface()->multi_adv_enable(
295 client_if_,
296 params.min_interval,
297 params.max_interval,
298 params.event_type,
299 kAdvertisingChannelAll,
300 params.tx_power_level,
301 params.timeout_s);
302 if (status != BT_STATUS_SUCCESS) {
303 LOG(ERROR) << "Failed to initiate call to enable multi-advertising";
304 return false;
305 }
306
307 // Always update advertising data.
308 adv_data_needs_update_ = true;
309
310 // Update scan response only if it has data, since otherwise we just won't
311 // send ADV_SCAN_IND.
312 if (!scan_response_.data().empty())
313 scan_rsp_needs_update_ = true;
314
315 // OK to set this at the end since we're still holding |adv_fields_lock_|.
316 adv_start_callback_.reset(new StatusCallback(callback));
317
318 return true;
319}
320
321bool LowEnergyClient::StopAdvertising(const StatusCallback& callback) {
322 VLOG(2) << __func__;
323 lock_guard<mutex> lock(adv_fields_lock_);
324
325 if (!IsAdvertisingStarted()) {
326 LOG(ERROR) << "Not advertising";
327 return false;
328 }
329
330 if (IsStoppingAdvertising()) {
331 LOG(ERROR) << "StopAdvertising already pending";
332 return false;
333 }
334
335 CHECK(!adv_start_callback_);
336
337 bt_status_t status = hal::BluetoothGattInterface::Get()->
338 GetClientHALInterface()->multi_adv_disable(client_if_);
339 if (status != BT_STATUS_SUCCESS) {
340 LOG(ERROR) << "Failed to initiate call to disable multi-advertising";
341 return false;
342 }
343
344 // OK to set this at the end since we're still holding |adv_fields_lock_|.
345 adv_stop_callback_.reset(new StatusCallback(callback));
346
347 return true;
348}
349
350bool LowEnergyClient::IsAdvertisingStarted() const {
351 return adv_started_.load();
352}
353
354bool LowEnergyClient::IsStartingAdvertising() const {
355 return !IsAdvertisingStarted() && adv_start_callback_;
356}
357
358bool LowEnergyClient::IsStoppingAdvertising() const {
359 return IsAdvertisingStarted() && adv_stop_callback_;
360}
361
Arman Uguray08f80eb2015-09-21 11:17:07 -0700362const UUID& LowEnergyClient::GetAppIdentifier() const {
363 return app_identifier_;
364}
365
366int LowEnergyClient::GetClientId() const {
367 return client_if_;
368}
369
Arman Uguray12338402015-09-16 18:00:05 -0700370void LowEnergyClient::MultiAdvEnableCallback(
371 hal::BluetoothGattInterface* gatt_iface,
372 int client_if, int status) {
373 if (client_if != client_if_)
374 return;
375
376 lock_guard<mutex> lock(adv_fields_lock_);
377
378 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
379
380 CHECK(adv_start_callback_);
381 CHECK(!adv_stop_callback_);
382
383 // Terminate operation in case of error.
384 if (status != BT_STATUS_SUCCESS) {
385 LOG(ERROR) << "Failed to enable multi-advertising";
386 InvokeAndClearStartCallback(GetBLEStatus(status));
387 return;
388 }
389
390 // Now handle deferred tasks.
391 HandleDeferredAdvertiseData(gatt_iface);
392}
393
394void LowEnergyClient::MultiAdvDataCallback(
395 hal::BluetoothGattInterface* gatt_iface,
396 int client_if, int status) {
397 if (client_if != client_if_)
398 return;
399
400 lock_guard<mutex> lock(adv_fields_lock_);
401
402 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
403
404 is_setting_adv_data_ = false;
405
406 // Terminate operation in case of error.
407 if (status != BT_STATUS_SUCCESS) {
408 LOG(ERROR) << "Failed to set advertising data";
409 InvokeAndClearStartCallback(GetBLEStatus(status));
410 return;
411 }
412
413 // Now handle deferred tasks.
414 HandleDeferredAdvertiseData(gatt_iface);
415}
416
417void LowEnergyClient::MultiAdvDisableCallback(
418 hal::BluetoothGattInterface* /* gatt_iface */,
419 int client_if, int status) {
420 if (client_if != client_if_)
421 return;
422
423 lock_guard<mutex> lock(adv_fields_lock_);
424
425 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
426
427 CHECK(!adv_start_callback_);
428 CHECK(adv_stop_callback_);
429
430 if (status == BT_STATUS_SUCCESS) {
431 VLOG(1) << "Multi-advertising stopped for client_if: " << client_if;
432 adv_started_ = false;
433 } else {
434 LOG(ERROR) << "Failed to stop multi-advertising";
435 }
436
437 InvokeAndClearStopCallback(GetBLEStatus(status));
438}
439
440bt_status_t LowEnergyClient::SetAdvertiseData(
441 hal::BluetoothGattInterface* gatt_iface,
442 const AdvertiseData& data,
443 bool set_scan_rsp) {
444 VLOG(2) << __func__;
445
446 HALAdvertiseData hal_data;
447
448 // TODO(armansito): The stack should check that the length is valid when other
449 // fields inserted by the stack (e.g. flags, device name, tx-power) are taken
450 // into account. At the moment we are skipping this check; this means that if
451 // the given data is too long then the stack will truncate it.
452 if (!ProcessAdvertiseData(data, &hal_data)) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700453 LOG(ERROR) << "Malformed advertise data given";
Arman Uguray12338402015-09-16 18:00:05 -0700454 return BT_STATUS_FAIL;
455 }
456
457 if (is_setting_adv_data_.load()) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700458 LOG(ERROR) << "Setting advertising data already in progress.";
Arman Uguray12338402015-09-16 18:00:05 -0700459 return BT_STATUS_FAIL;
460 }
461
462 // TODO(armansito): The length fields in the BTIF function below are signed
463 // integers so a call to std::vector::size might get capped. This is very
464 // unlikely anyway but it's safer to stop using signed-integer types for
465 // length in APIs, so we should change that.
466 bt_status_t status = gatt_iface->GetClientHALInterface()->
467 multi_adv_set_inst_data(
468 client_if_,
469 set_scan_rsp,
470 data.include_device_name(),
471 data.include_tx_power_level(),
472 0, // This is what Bluetooth.apk current hardcodes for "appearance".
473 hal_data.manufacturer_data.size(),
474 reinterpret_cast<char*>(hal_data.manufacturer_data.data()),
Ajay Panickerff651b72015-09-30 15:49:47 -0700475 hal_data.service_data.size(),
476 reinterpret_cast<char*>(hal_data.service_data.data()),
477 hal_data.service_uuid.size(),
478 reinterpret_cast<char*>(hal_data.service_uuid.data()));
479
Arman Uguray12338402015-09-16 18:00:05 -0700480 if (status != BT_STATUS_SUCCESS) {
481 LOG(ERROR) << "Failed to set instance advertising data.";
482 return status;
483 }
484
485 if (set_scan_rsp)
486 scan_rsp_needs_update_ = false;
487 else
488 adv_data_needs_update_ = false;
489
490 is_setting_adv_data_ = true;
491
492 return status;
493}
494
495void LowEnergyClient::HandleDeferredAdvertiseData(
496 hal::BluetoothGattInterface* gatt_iface) {
497 VLOG(2) << __func__;
498
499 CHECK(!IsAdvertisingStarted());
500 CHECK(!IsStoppingAdvertising());
501 CHECK(IsStartingAdvertising());
502 CHECK(!is_setting_adv_data_.load());
503
504 if (adv_data_needs_update_.load()) {
505 bt_status_t status = SetAdvertiseData(gatt_iface, adv_data_, false);
506 if (status != BT_STATUS_SUCCESS) {
507 LOG(ERROR) << "Failed setting advertisement data";
508 InvokeAndClearStartCallback(GetBLEStatus(status));
509 }
510 return;
511 }
512
513 if (scan_rsp_needs_update_.load()) {
514 bt_status_t status = SetAdvertiseData(gatt_iface, scan_response_, true);
515 if (status != BT_STATUS_SUCCESS) {
516 LOG(ERROR) << "Failed setting scan response data";
517 InvokeAndClearStartCallback(GetBLEStatus(status));
518 }
519 return;
520 }
521
522 // All pending tasks are complete. Report success.
523 adv_started_ = true;
524 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
525}
526
527void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
528 adv_data_needs_update_ = false;
529 scan_rsp_needs_update_ = false;
530
531 // We allow NULL callbacks.
532 if (*adv_start_callback_)
533 (*adv_start_callback_)(status);
534
535 adv_start_callback_ = nullptr;
536}
537
538void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
539 // We allow NULL callbacks.
540 if (*adv_stop_callback_)
541 (*adv_stop_callback_)(status);
542
543 adv_stop_callback_ = nullptr;
544}
545
546// LowEnergyClientFactory implementation
547// ========================================================
548
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700549LowEnergyClientFactory::LowEnergyClientFactory() {
550 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
551}
552
553LowEnergyClientFactory::~LowEnergyClientFactory() {
554 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
555}
556
557bool LowEnergyClientFactory::RegisterClient(const UUID& uuid,
Arman Uguray08f80eb2015-09-21 11:17:07 -0700558 const RegisterCallback& callback) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700559 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
560 lock_guard<mutex> lock(pending_calls_lock_);
561
562 if (pending_calls_.find(uuid) != pending_calls_.end()) {
563 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
564 << "UUID: " << uuid.ToString();
565 return false;
566 }
567
568 const btgatt_client_interface_t* hal_iface =
569 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
570 bt_uuid_t app_uuid = uuid.GetBlueDroid();
571
572 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
573 return false;
574
575 pending_calls_[uuid] = callback;
576
577 return true;
578}
579
580void LowEnergyClientFactory::RegisterClientCallback(
Arman Uguray12338402015-09-16 18:00:05 -0700581 hal::BluetoothGattInterface* gatt_iface,
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700582 int status, int client_if,
583 const bt_uuid_t& app_uuid) {
584 UUID uuid(app_uuid);
585
586 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
587 lock_guard<mutex> lock(pending_calls_lock_);
588
589 auto iter = pending_calls_.find(uuid);
590 if (iter == pending_calls_.end()) {
591 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
592 return;
593 }
594
595 // No need to construct a client if the call wasn't successful.
596 std::unique_ptr<LowEnergyClient> client;
597 BLEStatus result = BLE_STATUS_FAILURE;
598 if (status == BT_STATUS_SUCCESS) {
599 client.reset(new LowEnergyClient(uuid, client_if));
Arman Uguray12338402015-09-16 18:00:05 -0700600
601 // Use the unsafe variant to register this as an observer, since
602 // LowEnergyClient instances only get created by LowEnergyClientCallback
603 // from inside this GATT client observer event, which would otherwise cause
604 // a deadlock.
605 gatt_iface->AddClientObserverUnsafe(client.get());
606
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700607 result = BLE_STATUS_SUCCESS;
608 }
609
Arman Uguray08f80eb2015-09-21 11:17:07 -0700610 // Notify the result via the result callback.
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700611 iter->second(result, uuid, std::move(client));
612
613 pending_calls_.erase(iter);
614}
615
616} // namespace bluetooth