2 // Copyright (C) 2015 Google, Inc.
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_client.h"
19 #include <base/logging.h>
21 #include "stack/include/bt_types.h"
22 #include "stack/include/hcidefs.h"
24 using std::lock_guard;
31 BLEStatus GetBLEStatus(int status) {
32 if (status == BT_STATUS_FAIL)
33 return BLE_STATUS_FAILURE;
35 return static_cast<BLEStatus>(status);
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.
41 struct HALAdvertiseData {
42 std::vector<uint8_t> manufacturer_data;
43 std::vector<uint8_t> service_data;
44 std::vector<uint8_t> service_uuid;
47 bool ProcessUUID(const uint8_t* uuid_data, size_t uuid_len, UUID* out_uuid) {
48 // BTIF expects a single 128-bit UUID to be passed in little-endian form, so
49 // we need to convert into that from raw data.
50 // TODO(armansito): We have three repeated if bodies below only because UUID
51 // accepts std::array which requires constexpr lengths. We should just have a
52 // single UUID constructor that takes in an std::vector instead.
53 if (uuid_len == UUID::kNumBytes16) {
54 UUID::UUID16Bit uuid_bytes;
55 for (size_t i = 0; i < uuid_len; ++i)
56 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
57 *out_uuid = UUID(uuid_bytes);
58 } else if (uuid_len == UUID::kNumBytes32) {
59 UUID::UUID32Bit uuid_bytes;
60 for (size_t i = 0; i < uuid_len; ++i)
61 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
62 *out_uuid = UUID(uuid_bytes);
63 } else if (uuid_len == UUID::kNumBytes128) {
64 UUID::UUID128Bit uuid_bytes;
65 for (size_t i = 0; i < uuid_len; ++i)
66 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
67 *out_uuid = UUID(uuid_bytes);
69 LOG(ERROR) << "Invalid UUID length";
76 bool ProcessServiceData(const uint8_t* data,
78 HALAdvertiseData* out_data){
79 size_t field_len = data[0];
81 // Minimum packet size should be equal to the uuid length + 1 to include
82 // the byte for the type of packet
83 if (field_len < uuid_len + 1) {
84 // Invalid packet size
88 if (!out_data->service_data.empty()) {
89 // More than one Service Data is not allowed due to the limitations
90 // of the HAL API. We error in order to make sure there
91 // is no ambiguity on which data to send.
92 VLOG(1) << "More than one Service Data entry not allowed";
96 const uint8_t* service_uuid = data + 2;
98 if (!ProcessUUID(service_uuid, uuid_len, &uuid))
101 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
102 const std::vector<uint8_t> temp_uuid(
103 uuid_bytes.data(), uuid_bytes.data() + uuid_bytes.size());
105 // This section is to make sure that there is no UUID conflict
106 if (out_data->service_uuid.empty()) {
107 out_data->service_uuid = temp_uuid;
108 } else if (out_data->service_uuid != temp_uuid) {
109 // Mismatch in uuid passed through service data and uuid passed
110 // through uuid field
111 VLOG(1) << "More than one UUID entry not allowed";
113 } // else do nothing as UUID is already properly assigned
115 // Use + uuid_len + 2 here in order to skip over a
116 // uuid contained in the beggining of the field
117 const uint8_t* srv_data = data + uuid_len + 2;
120 out_data->service_data.insert(
121 out_data->service_data.begin(),
122 srv_data, srv_data + field_len - uuid_len - 1);
127 bool ProcessAdvertiseData(const AdvertiseData& adv,
128 HALAdvertiseData* out_data) {
130 CHECK(out_data->manufacturer_data.empty());
131 CHECK(out_data->service_data.empty());
132 CHECK(out_data->service_uuid.empty());
134 const auto& data = adv.data();
135 size_t len = data.size();
136 for (size_t i = 0, field_len = 0; i < len; i += (field_len + 1)) {
137 // The length byte is the first byte in the adv. "TLV" format.
140 // The type byte is the next byte in the adv. "TLV" format.
141 uint8_t type = data[i + 1];
145 case HCI_EIR_MANUFACTURER_SPECIFIC_TYPE: {
146 // TODO(armansito): BTIF doesn't allow setting more than one
147 // manufacturer-specific data entry. This is something we should fix. For
148 // now, fail if more than one entry was set.
149 if (!out_data->manufacturer_data.empty()) {
150 LOG(ERROR) << "More than one Manufacturer Specific Data entry not allowed";
154 // The value bytes start at the next byte in the "TLV" format.
155 const uint8_t* mnf_data = data.data() + i + 2;
156 out_data->manufacturer_data.insert(
157 out_data->manufacturer_data.begin(),
158 mnf_data, mnf_data + field_len - 1);
161 case HCI_EIR_MORE_16BITS_UUID_TYPE:
162 case HCI_EIR_COMPLETE_16BITS_UUID_TYPE:
163 case HCI_EIR_MORE_32BITS_UUID_TYPE:
164 case HCI_EIR_COMPLETE_32BITS_UUID_TYPE:
165 case HCI_EIR_MORE_128BITS_UUID_TYPE:
166 case HCI_EIR_COMPLETE_128BITS_UUID_TYPE: {
167 const uint8_t* uuid_data = data.data() + i + 2;
168 size_t uuid_len = field_len - 1;
170 if (!ProcessUUID(uuid_data, uuid_len, &uuid))
173 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
175 if (!out_data->service_uuid.empty() &&
176 memcmp(out_data->service_uuid.data(),
177 uuid_bytes.data(), uuid_bytes.size()) != 0) {
178 // More than one UUID is not allowed due to the limitations
179 // of the HAL API. We error in order to make sure there
180 // is no ambiguity on which UUID to send. Also makes sure that
181 // UUID Hasn't been set by service data first
182 LOG(ERROR) << "More than one UUID entry not allowed";
186 out_data->service_uuid.assign(
187 uuid_bytes.data(), uuid_bytes.data() + UUID::kNumBytes128);
190 case HCI_EIR_SERVICE_DATA_16BITS_UUID_TYPE: {
191 if (!ProcessServiceData(data.data() + i, 2, out_data))
195 case HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE: {
196 if (!ProcessServiceData(data.data() + i, 4, out_data))
200 case HCI_EIR_SERVICE_DATA_128BITS_UUID_TYPE: {
201 if (!ProcessServiceData(data.data() + i, 16, out_data))
205 // TODO(armansito): Support other fields.
207 VLOG(1) << "Unrecognized EIR field: " << type;
215 // The Bluetooth Core Specification defines time interval (e.g. Page Scan
216 // Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1
217 // Baseband slot). The HAL advertising functions expect the interval in this
218 // unit. This function maps an AdvertiseSettings::Mode value to the
219 // corresponding time unit.
220 int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
224 case AdvertiseSettings::MODE_BALANCED:
225 ms = kAdvertisingIntervalMediumMs;
227 case AdvertiseSettings::MODE_LOW_LATENCY:
228 ms = kAdvertisingIntervalLowMs;
230 case AdvertiseSettings::MODE_LOW_POWER:
233 ms = kAdvertisingIntervalHighMs;
237 // Convert milliseconds Bluetooth units.
238 return (ms * 1000) / 625;
241 struct AdvertiseParams {
249 void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
250 AdvertiseParams* out_params) {
253 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
254 out_params->max_interval =
255 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
257 if (settings.connectable())
258 out_params->event_type = kAdvertisingEventTypeConnectable;
259 else if (has_scan_rsp)
260 out_params->event_type = kAdvertisingEventTypeScannable;
262 out_params->event_type = kAdvertisingEventTypeNonConnectable;
264 out_params->tx_power_level = settings.tx_power_level();
265 out_params->timeout_s = settings.timeout().InSeconds();
270 // LowEnergyClient implementation
271 // ========================================================
273 LowEnergyClient::LowEnergyClient(const UUID& uuid, int client_if)
274 : app_identifier_(uuid),
275 client_if_(client_if),
276 adv_data_needs_update_(false),
277 scan_rsp_needs_update_(false),
278 is_setting_adv_data_(false),
280 adv_start_callback_(nullptr),
281 adv_stop_callback_(nullptr) {
284 LowEnergyClient::~LowEnergyClient() {
285 // Automatically unregister the client.
286 VLOG(1) << "LowEnergyClient unregistering client: " << client_if_;
288 // Unregister as observer so we no longer receive any callbacks.
289 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
291 // Stop advertising and ignore the result.
292 hal::BluetoothGattInterface::Get()->
293 GetClientHALInterface()->multi_adv_disable(client_if_);
294 hal::BluetoothGattInterface::Get()->
295 GetClientHALInterface()->unregister_client(client_if_);
298 bool LowEnergyClient::StartAdvertising(const AdvertiseSettings& settings,
299 const AdvertiseData& advertise_data,
300 const AdvertiseData& scan_response,
301 const StatusCallback& callback) {
303 lock_guard<mutex> lock(adv_fields_lock_);
305 if (IsAdvertisingStarted()) {
306 LOG(WARNING) << "Already advertising";
310 if (IsStartingAdvertising()) {
311 LOG(WARNING) << "StartAdvertising already pending";
315 if (!advertise_data.IsValid()) {
316 LOG(ERROR) << "Invalid advertising data";
320 if (!scan_response.IsValid()) {
321 LOG(ERROR) << "Invalid scan response data";
325 CHECK(!adv_data_needs_update_.load());
326 CHECK(!scan_rsp_needs_update_.load());
328 adv_data_ = advertise_data;
329 scan_response_ = scan_response;
330 settings_ = settings;
332 AdvertiseParams params;
333 GetAdvertiseParams(settings, !scan_response_.data().empty(), ¶ms);
335 bt_status_t status = hal::BluetoothGattInterface::Get()->
336 GetClientHALInterface()->multi_adv_enable(
341 kAdvertisingChannelAll,
342 params.tx_power_level,
344 if (status != BT_STATUS_SUCCESS) {
345 LOG(ERROR) << "Failed to initiate call to enable multi-advertising";
349 // Always update advertising data.
350 adv_data_needs_update_ = true;
352 // Update scan response only if it has data, since otherwise we just won't
353 // send ADV_SCAN_IND.
354 if (!scan_response_.data().empty())
355 scan_rsp_needs_update_ = true;
357 // OK to set this at the end since we're still holding |adv_fields_lock_|.
358 adv_start_callback_.reset(new StatusCallback(callback));
363 bool LowEnergyClient::StopAdvertising(const StatusCallback& callback) {
365 lock_guard<mutex> lock(adv_fields_lock_);
367 if (!IsAdvertisingStarted()) {
368 LOG(ERROR) << "Not advertising";
372 if (IsStoppingAdvertising()) {
373 LOG(ERROR) << "StopAdvertising already pending";
377 CHECK(!adv_start_callback_);
379 bt_status_t status = hal::BluetoothGattInterface::Get()->
380 GetClientHALInterface()->multi_adv_disable(client_if_);
381 if (status != BT_STATUS_SUCCESS) {
382 LOG(ERROR) << "Failed to initiate call to disable multi-advertising";
386 // OK to set this at the end since we're still holding |adv_fields_lock_|.
387 adv_stop_callback_.reset(new StatusCallback(callback));
392 bool LowEnergyClient::IsAdvertisingStarted() const {
393 return adv_started_.load();
396 bool LowEnergyClient::IsStartingAdvertising() const {
397 return !IsAdvertisingStarted() && adv_start_callback_;
400 bool LowEnergyClient::IsStoppingAdvertising() const {
401 return IsAdvertisingStarted() && adv_stop_callback_;
404 const UUID& LowEnergyClient::GetAppIdentifier() const {
405 return app_identifier_;
408 int LowEnergyClient::GetClientId() const {
412 void LowEnergyClient::MultiAdvEnableCallback(
413 hal::BluetoothGattInterface* gatt_iface,
414 int client_if, int status) {
415 if (client_if != client_if_)
418 lock_guard<mutex> lock(adv_fields_lock_);
420 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
422 CHECK(adv_start_callback_);
423 CHECK(!adv_stop_callback_);
425 // Terminate operation in case of error.
426 if (status != BT_STATUS_SUCCESS) {
427 LOG(ERROR) << "Failed to enable multi-advertising";
428 InvokeAndClearStartCallback(GetBLEStatus(status));
432 // Now handle deferred tasks.
433 HandleDeferredAdvertiseData(gatt_iface);
436 void LowEnergyClient::MultiAdvDataCallback(
437 hal::BluetoothGattInterface* gatt_iface,
438 int client_if, int status) {
439 if (client_if != client_if_)
442 lock_guard<mutex> lock(adv_fields_lock_);
444 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
446 is_setting_adv_data_ = false;
448 // Terminate operation in case of error.
449 if (status != BT_STATUS_SUCCESS) {
450 LOG(ERROR) << "Failed to set advertising data";
451 InvokeAndClearStartCallback(GetBLEStatus(status));
455 // Now handle deferred tasks.
456 HandleDeferredAdvertiseData(gatt_iface);
459 void LowEnergyClient::MultiAdvDisableCallback(
460 hal::BluetoothGattInterface* /* gatt_iface */,
461 int client_if, int status) {
462 if (client_if != client_if_)
465 lock_guard<mutex> lock(adv_fields_lock_);
467 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
469 CHECK(!adv_start_callback_);
470 CHECK(adv_stop_callback_);
472 if (status == BT_STATUS_SUCCESS) {
473 VLOG(1) << "Multi-advertising stopped for client_if: " << client_if;
474 adv_started_ = false;
476 LOG(ERROR) << "Failed to stop multi-advertising";
479 InvokeAndClearStopCallback(GetBLEStatus(status));
482 bt_status_t LowEnergyClient::SetAdvertiseData(
483 hal::BluetoothGattInterface* gatt_iface,
484 const AdvertiseData& data,
488 HALAdvertiseData hal_data;
490 // TODO(armansito): The stack should check that the length is valid when other
491 // fields inserted by the stack (e.g. flags, device name, tx-power) are taken
492 // into account. At the moment we are skipping this check; this means that if
493 // the given data is too long then the stack will truncate it.
494 if (!ProcessAdvertiseData(data, &hal_data)) {
495 LOG(ERROR) << "Malformed advertise data given";
496 return BT_STATUS_FAIL;
499 if (is_setting_adv_data_.load()) {
500 LOG(ERROR) << "Setting advertising data already in progress.";
501 return BT_STATUS_FAIL;
504 // TODO(armansito): The length fields in the BTIF function below are signed
505 // integers so a call to std::vector::size might get capped. This is very
506 // unlikely anyway but it's safer to stop using signed-integer types for
507 // length in APIs, so we should change that.
508 bt_status_t status = gatt_iface->GetClientHALInterface()->
509 multi_adv_set_inst_data(
512 data.include_device_name(),
513 data.include_tx_power_level(),
514 0, // This is what Bluetooth.apk current hardcodes for "appearance".
515 hal_data.manufacturer_data.size(),
516 reinterpret_cast<char*>(hal_data.manufacturer_data.data()),
517 hal_data.service_data.size(),
518 reinterpret_cast<char*>(hal_data.service_data.data()),
519 hal_data.service_uuid.size(),
520 reinterpret_cast<char*>(hal_data.service_uuid.data()));
522 if (status != BT_STATUS_SUCCESS) {
523 LOG(ERROR) << "Failed to set instance advertising data.";
528 scan_rsp_needs_update_ = false;
530 adv_data_needs_update_ = false;
532 is_setting_adv_data_ = true;
537 void LowEnergyClient::HandleDeferredAdvertiseData(
538 hal::BluetoothGattInterface* gatt_iface) {
541 CHECK(!IsAdvertisingStarted());
542 CHECK(!IsStoppingAdvertising());
543 CHECK(IsStartingAdvertising());
544 CHECK(!is_setting_adv_data_.load());
546 if (adv_data_needs_update_.load()) {
547 bt_status_t status = SetAdvertiseData(gatt_iface, adv_data_, false);
548 if (status != BT_STATUS_SUCCESS) {
549 LOG(ERROR) << "Failed setting advertisement data";
550 InvokeAndClearStartCallback(GetBLEStatus(status));
555 if (scan_rsp_needs_update_.load()) {
556 bt_status_t status = SetAdvertiseData(gatt_iface, scan_response_, true);
557 if (status != BT_STATUS_SUCCESS) {
558 LOG(ERROR) << "Failed setting scan response data";
559 InvokeAndClearStartCallback(GetBLEStatus(status));
564 // All pending tasks are complete. Report success.
566 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
569 void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
570 adv_data_needs_update_ = false;
571 scan_rsp_needs_update_ = false;
573 // We allow NULL callbacks.
574 if (*adv_start_callback_)
575 (*adv_start_callback_)(status);
577 adv_start_callback_ = nullptr;
580 void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
581 // We allow NULL callbacks.
582 if (*adv_stop_callback_)
583 (*adv_stop_callback_)(status);
585 adv_stop_callback_ = nullptr;
588 // LowEnergyClientFactory implementation
589 // ========================================================
591 LowEnergyClientFactory::LowEnergyClientFactory() {
592 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
595 LowEnergyClientFactory::~LowEnergyClientFactory() {
596 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
599 bool LowEnergyClientFactory::RegisterClient(const UUID& uuid,
600 const RegisterCallback& callback) {
601 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
602 lock_guard<mutex> lock(pending_calls_lock_);
604 if (pending_calls_.find(uuid) != pending_calls_.end()) {
605 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
606 << "UUID: " << uuid.ToString();
610 const btgatt_client_interface_t* hal_iface =
611 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
612 bt_uuid_t app_uuid = uuid.GetBlueDroid();
614 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
617 pending_calls_[uuid] = callback;
622 void LowEnergyClientFactory::RegisterClientCallback(
623 hal::BluetoothGattInterface* gatt_iface,
624 int status, int client_if,
625 const bt_uuid_t& app_uuid) {
628 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
629 lock_guard<mutex> lock(pending_calls_lock_);
631 auto iter = pending_calls_.find(uuid);
632 if (iter == pending_calls_.end()) {
633 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
637 // No need to construct a client if the call wasn't successful.
638 std::unique_ptr<LowEnergyClient> client;
639 BLEStatus result = BLE_STATUS_FAILURE;
640 if (status == BT_STATUS_SUCCESS) {
641 client.reset(new LowEnergyClient(uuid, client_if));
643 // Use the unsafe variant to register this as an observer, since
644 // LowEnergyClient instances only get created by LowEnergyClientCallback
645 // from inside this GATT client observer event, which would otherwise cause
647 gatt_iface->AddClientObserverUnsafe(client.get());
649 result = BLE_STATUS_SUCCESS;
652 // Notify the result via the result callback.
653 iter->second(result, uuid, std::move(client));
655 pending_calls_.erase(iter);
658 } // namespace bluetooth