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 "service/adapter.h"
22 #include "service/common/bluetooth/util/address_helper.h"
23 #include "service/logging_helpers.h"
24 #include "stack/include/bt_types.h"
25 #include "stack/include/hcidefs.h"
27 using std::lock_guard;
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;
40 BLEStatus GetBLEStatus(int status) {
41 if (status == BT_STATUS_FAIL)
42 return BLE_STATUS_FAILURE;
44 return static_cast<BLEStatus>(status);
47 // Returns the length of the given scan record array. We have to calculate this
48 // based on the maximum possible data length and the TLV data. See TODO above
49 // |kScanRecordLength|.
50 size_t GetScanRecordLength(uint8_t* bytes) {
51 for (size_t i = 0, field_len = 0; i < kScanRecordLength;
52 i += (field_len + 1)) {
55 // Assert here that the data returned from the stack is correctly formatted
56 // in TLV form and that the length of the current field won't exceed the
58 CHECK(i + field_len < kScanRecordLength);
60 // If the field length is zero and we haven't reached the maximum length,
61 // then we have found the length, as the stack will pad the data with zeros
67 // We have reached the end.
68 return kScanRecordLength;
71 // TODO(armansito): BTIF currently expects each advertising field in a
72 // specific format passed directly in arguments. We should fix BTIF to accept
73 // the advertising data directly instead.
74 struct HALAdvertiseData {
75 std::vector<uint8_t> manufacturer_data;
76 std::vector<uint8_t> service_data;
77 std::vector<uint8_t> service_uuid;
80 bool ProcessUUID(const uint8_t* uuid_data, size_t uuid_len, UUID* out_uuid) {
81 // BTIF expects a single 128-bit UUID to be passed in little-endian form, so
82 // we need to convert into that from raw data.
83 // TODO(armansito): We have three repeated if bodies below only because UUID
84 // accepts std::array which requires constexpr lengths. We should just have a
85 // single UUID constructor that takes in an std::vector instead.
86 if (uuid_len == UUID::kNumBytes16) {
87 UUID::UUID16Bit uuid_bytes;
88 for (size_t i = 0; i < uuid_len; ++i)
89 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
90 *out_uuid = UUID(uuid_bytes);
91 } else if (uuid_len == UUID::kNumBytes32) {
92 UUID::UUID32Bit uuid_bytes;
93 for (size_t i = 0; i < uuid_len; ++i)
94 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
95 *out_uuid = UUID(uuid_bytes);
96 } else if (uuid_len == UUID::kNumBytes128) {
97 UUID::UUID128Bit uuid_bytes;
98 for (size_t i = 0; i < uuid_len; ++i)
99 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
100 *out_uuid = UUID(uuid_bytes);
102 LOG(ERROR) << "Invalid UUID length";
109 bool ProcessServiceData(const uint8_t* data,
111 HALAdvertiseData* out_data) {
112 size_t field_len = data[0];
114 // Minimum packet size should be equal to the uuid length + 1 to include
115 // the byte for the type of packet
116 if (field_len < uuid_len + 1) {
117 // Invalid packet size
121 if (!out_data->service_data.empty()) {
122 // More than one Service Data is not allowed due to the limitations
123 // of the HAL API. We error in order to make sure there
124 // is no ambiguity on which data to send.
125 VLOG(1) << "More than one Service Data entry not allowed";
129 const uint8_t* service_uuid = data + 2;
131 if (!ProcessUUID(service_uuid, uuid_len, &uuid))
134 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
135 const std::vector<uint8_t> temp_uuid(
136 uuid_bytes.data(), uuid_bytes.data() + uuid_bytes.size());
138 // This section is to make sure that there is no UUID conflict
139 if (out_data->service_uuid.empty()) {
140 out_data->service_uuid = temp_uuid;
141 } else if (out_data->service_uuid != temp_uuid) {
142 // Mismatch in uuid passed through service data and uuid passed
143 // through uuid field
144 VLOG(1) << "More than one UUID entry not allowed";
146 } // else do nothing as UUID is already properly assigned
148 // Use + uuid_len + 2 here in order to skip over a
149 // uuid contained in the beggining of the field
150 const uint8_t* srv_data = data + uuid_len + 2;
153 out_data->service_data.insert(
154 out_data->service_data.begin(),
155 srv_data, srv_data + field_len - uuid_len - 1);
160 bool ProcessAdvertiseData(const AdvertiseData& adv,
161 HALAdvertiseData* out_data) {
163 CHECK(out_data->manufacturer_data.empty());
164 CHECK(out_data->service_data.empty());
165 CHECK(out_data->service_uuid.empty());
167 const auto& data = adv.data();
168 size_t len = data.size();
169 for (size_t i = 0, field_len = 0; i < len; i += (field_len + 1)) {
170 // The length byte is the first byte in the adv. "TLV" format.
173 // The type byte is the next byte in the adv. "TLV" format.
174 uint8_t type = data[i + 1];
178 case HCI_EIR_MANUFACTURER_SPECIFIC_TYPE: {
179 // TODO(armansito): BTIF doesn't allow setting more than one
180 // manufacturer-specific data entry. This is something we should fix. For
181 // now, fail if more than one entry was set.
182 if (!out_data->manufacturer_data.empty()) {
183 LOG(ERROR) << "More than one Manufacturer Specific Data entry not allowed";
187 // The value bytes start at the next byte in the "TLV" format.
188 const uint8_t* mnf_data = data.data() + i + 2;
189 out_data->manufacturer_data.insert(
190 out_data->manufacturer_data.begin(),
191 mnf_data, mnf_data + field_len - 1);
194 case HCI_EIR_MORE_16BITS_UUID_TYPE:
195 case HCI_EIR_COMPLETE_16BITS_UUID_TYPE:
196 case HCI_EIR_MORE_32BITS_UUID_TYPE:
197 case HCI_EIR_COMPLETE_32BITS_UUID_TYPE:
198 case HCI_EIR_MORE_128BITS_UUID_TYPE:
199 case HCI_EIR_COMPLETE_128BITS_UUID_TYPE: {
200 const uint8_t* uuid_data = data.data() + i + 2;
201 size_t uuid_len = field_len - 1;
203 if (!ProcessUUID(uuid_data, uuid_len, &uuid))
206 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
208 if (!out_data->service_uuid.empty() &&
209 memcmp(out_data->service_uuid.data(),
210 uuid_bytes.data(), uuid_bytes.size()) != 0) {
211 // More than one UUID is not allowed due to the limitations
212 // of the HAL API. We error in order to make sure there
213 // is no ambiguity on which UUID to send. Also makes sure that
214 // UUID Hasn't been set by service data first
215 LOG(ERROR) << "More than one UUID entry not allowed";
219 out_data->service_uuid.assign(
220 uuid_bytes.data(), uuid_bytes.data() + UUID::kNumBytes128);
223 case HCI_EIR_SERVICE_DATA_16BITS_UUID_TYPE: {
224 if (!ProcessServiceData(data.data() + i, 2, out_data))
228 case HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE: {
229 if (!ProcessServiceData(data.data() + i, 4, out_data))
233 case HCI_EIR_SERVICE_DATA_128BITS_UUID_TYPE: {
234 if (!ProcessServiceData(data.data() + i, 16, out_data))
238 // TODO(armansito): Support other fields.
240 VLOG(1) << "Unrecognized EIR field: " << type;
248 // The Bluetooth Core Specification defines time interval (e.g. Page Scan
249 // Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1
250 // Baseband slot). The HAL advertising functions expect the interval in this
251 // unit. This function maps an AdvertiseSettings::Mode value to the
252 // corresponding time unit.
253 int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
257 case AdvertiseSettings::MODE_BALANCED:
258 ms = kAdvertisingIntervalMediumMs;
260 case AdvertiseSettings::MODE_LOW_LATENCY:
261 ms = kAdvertisingIntervalLowMs;
263 case AdvertiseSettings::MODE_LOW_POWER:
266 ms = kAdvertisingIntervalHighMs;
270 // Convert milliseconds Bluetooth units.
271 return (ms * 1000) / 625;
274 struct AdvertiseParams {
282 void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
283 AdvertiseParams* out_params) {
286 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
287 out_params->max_interval =
288 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
290 if (settings.connectable())
291 out_params->event_type = kAdvertisingEventTypeConnectable;
292 else if (has_scan_rsp)
293 out_params->event_type = kAdvertisingEventTypeScannable;
295 out_params->event_type = kAdvertisingEventTypeNonConnectable;
297 out_params->tx_power_level = settings.tx_power_level();
298 out_params->timeout_s = settings.timeout().InSeconds();
303 // LowEnergyClient implementation
304 // ========================================================
306 LowEnergyClient::LowEnergyClient(
307 Adapter& adapter, const UUID& uuid, int client_id)
309 app_identifier_(uuid),
310 client_id_(client_id),
311 adv_data_needs_update_(false),
312 scan_rsp_needs_update_(false),
313 is_setting_adv_data_(false),
315 adv_start_callback_(nullptr),
316 adv_stop_callback_(nullptr),
317 scan_started_(false) {
320 LowEnergyClient::~LowEnergyClient() {
321 // Automatically unregister the client.
322 VLOG(1) << "LowEnergyClient unregistering client: " << client_id_;
324 // Unregister as observer so we no longer receive any callbacks.
325 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
327 // Stop advertising and ignore the result.
328 hal::BluetoothGattInterface::Get()->
329 GetClientHALInterface()->multi_adv_disable(client_id_);
330 hal::BluetoothGattInterface::Get()->
331 GetClientHALInterface()->unregister_client(client_id_);
333 // Stop any scans started by this client.
334 if (scan_started_.load())
338 bool LowEnergyClient::Connect(std::string address, bool is_direct) {
339 VLOG(2) << __func__ << "Address: " << address << " is_direct: " << is_direct;
342 util::BdAddrFromString(address, &bda);
344 bt_status_t status = hal::BluetoothGattInterface::Get()->
345 GetClientHALInterface()->connect(client_id_, &bda, is_direct,
347 if (status != BT_STATUS_SUCCESS) {
348 LOG(ERROR) << "HAL call to connect failed";
355 bool LowEnergyClient::Disconnect(std::string address) {
356 VLOG(2) << __func__ << "Address: " << address;
359 util::BdAddrFromString(address, &bda);
361 std::map<const bt_bdaddr_t, int>::iterator conn_id;
363 lock_guard<mutex> lock(connection_fields_lock_);
364 conn_id = connection_ids_.find(bda);
365 if (conn_id == connection_ids_.end()) {
366 LOG(WARNING) << "Can't disconnect, no existing connection to " << address;
371 bt_status_t status = hal::BluetoothGattInterface::Get()->
372 GetClientHALInterface()->disconnect(client_id_, &bda, conn_id->second);
373 if (status != BT_STATUS_SUCCESS) {
374 LOG(ERROR) << "HAL call to disconnect failed";
381 bool LowEnergyClient::SetMtu(std::string address, int mtu) {
382 VLOG(2) << __func__ << "Address: " << address
386 util::BdAddrFromString(address, &bda);
388 std::map<const bt_bdaddr_t, int>::iterator conn_id;
390 lock_guard<mutex> lock(connection_fields_lock_);
391 conn_id = connection_ids_.find(bda);
392 if (conn_id == connection_ids_.end()) {
393 LOG(WARNING) << "Can't set MTU, no existing connection to " << address;
398 bt_status_t status = hal::BluetoothGattInterface::Get()->
399 GetClientHALInterface()->configure_mtu(conn_id->second, mtu);
400 if (status != BT_STATUS_SUCCESS) {
401 LOG(ERROR) << "HAL call to set MTU failed";
408 void LowEnergyClient::SetDelegate(Delegate* delegate) {
409 lock_guard<mutex> lock(delegate_mutex_);
410 delegate_ = delegate;
413 bool LowEnergyClient::StartScan(const ScanSettings& settings,
414 const std::vector<ScanFilter>& filters) {
417 // Cannot start a scan if the adapter is not enabled.
418 if (!adapter_.IsEnabled()) {
419 LOG(ERROR) << "Cannot scan while Bluetooth is disabled";
423 // TODO(jpawlowski): Push settings and filtering logic below the HAL.
424 bt_status_t status = hal::BluetoothGattInterface::Get()->
425 StartScan(client_id_);
426 if (status != BT_STATUS_SUCCESS) {
427 LOG(ERROR) << "Failed to initiate scanning for client: " << client_id_;
431 scan_started_ = true;
435 bool LowEnergyClient::StopScan() {
438 // TODO(armansito): We don't support batch scanning yet so call
439 // StopRegularScanForClient directly. In the future we will need to
440 // conditionally call a batch scan API here.
441 bt_status_t status = hal::BluetoothGattInterface::Get()->
442 StopScan(client_id_);
443 if (status != BT_STATUS_SUCCESS) {
444 LOG(ERROR) << "Failed to stop scan for client: " << client_id_;
448 scan_started_ = false;
452 bool LowEnergyClient::StartAdvertising(const AdvertiseSettings& settings,
453 const AdvertiseData& advertise_data,
454 const AdvertiseData& scan_response,
455 const StatusCallback& callback) {
457 lock_guard<mutex> lock(adv_fields_lock_);
459 if (IsAdvertisingStarted()) {
460 LOG(WARNING) << "Already advertising";
464 if (IsStartingAdvertising()) {
465 LOG(WARNING) << "StartAdvertising already pending";
469 if (!advertise_data.IsValid()) {
470 LOG(ERROR) << "Invalid advertising data";
474 if (!scan_response.IsValid()) {
475 LOG(ERROR) << "Invalid scan response data";
479 CHECK(!adv_data_needs_update_.load());
480 CHECK(!scan_rsp_needs_update_.load());
482 adv_data_ = advertise_data;
483 scan_response_ = scan_response;
484 advertise_settings_ = settings;
486 AdvertiseParams params;
487 GetAdvertiseParams(settings, !scan_response_.data().empty(), ¶ms);
489 bt_status_t status = hal::BluetoothGattInterface::Get()->
490 GetClientHALInterface()->multi_adv_enable(
495 kAdvertisingChannelAll,
496 params.tx_power_level,
498 if (status != BT_STATUS_SUCCESS) {
499 LOG(ERROR) << "Failed to initiate call to enable multi-advertising";
503 // Always update advertising data.
504 adv_data_needs_update_ = true;
506 // Update scan response only if it has data, since otherwise we just won't
507 // send ADV_SCAN_IND.
508 if (!scan_response_.data().empty())
509 scan_rsp_needs_update_ = true;
511 // OK to set this at the end since we're still holding |adv_fields_lock_|.
512 adv_start_callback_.reset(new StatusCallback(callback));
517 bool LowEnergyClient::StopAdvertising(const StatusCallback& callback) {
519 lock_guard<mutex> lock(adv_fields_lock_);
521 if (!IsAdvertisingStarted()) {
522 LOG(ERROR) << "Not advertising";
526 if (IsStoppingAdvertising()) {
527 LOG(ERROR) << "StopAdvertising already pending";
531 CHECK(!adv_start_callback_);
533 bt_status_t status = hal::BluetoothGattInterface::Get()->
534 GetClientHALInterface()->multi_adv_disable(client_id_);
535 if (status != BT_STATUS_SUCCESS) {
536 LOG(ERROR) << "Failed to initiate call to disable multi-advertising";
540 // OK to set this at the end since we're still holding |adv_fields_lock_|.
541 adv_stop_callback_.reset(new StatusCallback(callback));
546 bool LowEnergyClient::IsAdvertisingStarted() const {
547 return adv_started_.load();
550 bool LowEnergyClient::IsStartingAdvertising() const {
551 return !IsAdvertisingStarted() && adv_start_callback_;
554 bool LowEnergyClient::IsStoppingAdvertising() const {
555 return IsAdvertisingStarted() && adv_stop_callback_;
558 const UUID& LowEnergyClient::GetAppIdentifier() const {
559 return app_identifier_;
562 int LowEnergyClient::GetInstanceId() const {
566 void LowEnergyClient::ScanResultCallback(
567 hal::BluetoothGattInterface* gatt_iface,
568 const bt_bdaddr_t& bda, int rssi, uint8_t* adv_data) {
569 // Ignore scan results if this client didn't start a scan.
570 if (!scan_started_.load())
573 lock_guard<mutex> lock(delegate_mutex_);
577 // TODO(armansito): Apply software filters here.
579 size_t record_len = GetScanRecordLength(adv_data);
580 std::vector<uint8_t> scan_record(adv_data, adv_data + record_len);
582 ScanResult result(BtAddrString(&bda), scan_record, rssi);
584 delegate_->OnScanResult(this, result);
587 void LowEnergyClient::ConnectCallback(
588 hal::BluetoothGattInterface* gatt_iface, int conn_id, int status,
589 int client_id, const bt_bdaddr_t& bda) {
590 if (client_id != client_id_)
593 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
596 lock_guard<mutex> lock(connection_fields_lock_);
597 auto success = connection_ids_.emplace(bda, conn_id);
598 if (!success.second) {
599 LOG(ERROR) << __func__ << " Insertion into connection_ids_ failed!";
604 delegate_->OnConnectionState(this, status, BtAddrString(&bda).c_str(),
608 void LowEnergyClient::DisconnectCallback(
609 hal::BluetoothGattInterface* gatt_iface, int conn_id, int status,
610 int client_id, const bt_bdaddr_t& bda) {
611 if (client_id != client_id_)
614 VLOG(1) << __func__ << " client_id: " << client_id << " status: " << status;
616 lock_guard<mutex> lock(connection_fields_lock_);
617 if (!connection_ids_.erase(bda)) {
618 LOG(ERROR) << __func__ << " Erasing from connection_ids_ failed!";
623 delegate_->OnConnectionState(this, status, BtAddrString(&bda).c_str(),
627 void LowEnergyClient::MtuChangedCallback(
628 hal::BluetoothGattInterface* gatt_iface, int conn_id, int status,
630 VLOG(1) << __func__ << " conn_id: " << conn_id << " status: " << status
633 const bt_bdaddr_t *bda = nullptr;
635 lock_guard<mutex> lock(connection_fields_lock_);
636 for (auto& connection: connection_ids_) {
637 if (connection.second == conn_id) {
638 bda = &connection.first;
647 const char *addr = BtAddrString(bda).c_str();
649 delegate_->OnMtuChanged(this, status, addr, mtu);
652 void LowEnergyClient::MultiAdvEnableCallback(
653 hal::BluetoothGattInterface* gatt_iface,
654 int client_id, int status) {
655 if (client_id != client_id_)
658 lock_guard<mutex> lock(adv_fields_lock_);
660 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
662 CHECK(adv_start_callback_);
663 CHECK(!adv_stop_callback_);
665 // Terminate operation in case of error.
666 if (status != BT_STATUS_SUCCESS) {
667 LOG(ERROR) << "Failed to enable multi-advertising";
668 InvokeAndClearStartCallback(GetBLEStatus(status));
672 // Now handle deferred tasks.
673 HandleDeferredAdvertiseData(gatt_iface);
676 void LowEnergyClient::MultiAdvDataCallback(
677 hal::BluetoothGattInterface* gatt_iface,
678 int client_id, int status) {
679 if (client_id != client_id_)
682 lock_guard<mutex> lock(adv_fields_lock_);
684 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
686 is_setting_adv_data_ = false;
688 // Terminate operation in case of error.
689 if (status != BT_STATUS_SUCCESS) {
690 LOG(ERROR) << "Failed to set advertising data";
691 InvokeAndClearStartCallback(GetBLEStatus(status));
695 // Now handle deferred tasks.
696 HandleDeferredAdvertiseData(gatt_iface);
699 void LowEnergyClient::MultiAdvDisableCallback(
700 hal::BluetoothGattInterface* /* gatt_iface */,
701 int client_id, int status) {
702 if (client_id != client_id_)
705 lock_guard<mutex> lock(adv_fields_lock_);
707 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
709 CHECK(!adv_start_callback_);
710 CHECK(adv_stop_callback_);
712 if (status == BT_STATUS_SUCCESS) {
713 VLOG(1) << "Multi-advertising stopped for client_id: " << client_id;
714 adv_started_ = false;
716 LOG(ERROR) << "Failed to stop multi-advertising";
719 InvokeAndClearStopCallback(GetBLEStatus(status));
722 bt_status_t LowEnergyClient::SetAdvertiseData(
723 hal::BluetoothGattInterface* gatt_iface,
724 const AdvertiseData& data,
728 HALAdvertiseData hal_data;
730 // TODO(armansito): The stack should check that the length is valid when other
731 // fields inserted by the stack (e.g. flags, device name, tx-power) are taken
732 // into account. At the moment we are skipping this check; this means that if
733 // the given data is too long then the stack will truncate it.
734 if (!ProcessAdvertiseData(data, &hal_data)) {
735 LOG(ERROR) << "Malformed advertise data given";
736 return BT_STATUS_FAIL;
739 if (is_setting_adv_data_.load()) {
740 LOG(ERROR) << "Setting advertising data already in progress.";
741 return BT_STATUS_FAIL;
744 // TODO(armansito): The length fields in the BTIF function below are signed
745 // integers so a call to std::vector::size might get capped. This is very
746 // unlikely anyway but it's safer to stop using signed-integer types for
747 // length in APIs, so we should change that.
748 bt_status_t status = gatt_iface->GetClientHALInterface()->
749 multi_adv_set_inst_data(
752 data.include_device_name(),
753 data.include_tx_power_level(),
754 0, // This is what Bluetooth.apk current hardcodes for "appearance".
755 hal_data.manufacturer_data.size(),
756 reinterpret_cast<char*>(hal_data.manufacturer_data.data()),
757 hal_data.service_data.size(),
758 reinterpret_cast<char*>(hal_data.service_data.data()),
759 hal_data.service_uuid.size(),
760 reinterpret_cast<char*>(hal_data.service_uuid.data()));
762 if (status != BT_STATUS_SUCCESS) {
763 LOG(ERROR) << "Failed to set instance advertising data.";
768 scan_rsp_needs_update_ = false;
770 adv_data_needs_update_ = false;
772 is_setting_adv_data_ = true;
777 void LowEnergyClient::HandleDeferredAdvertiseData(
778 hal::BluetoothGattInterface* gatt_iface) {
781 CHECK(!IsAdvertisingStarted());
782 CHECK(!IsStoppingAdvertising());
783 CHECK(IsStartingAdvertising());
784 CHECK(!is_setting_adv_data_.load());
786 if (adv_data_needs_update_.load()) {
787 bt_status_t status = SetAdvertiseData(gatt_iface, adv_data_, false);
788 if (status != BT_STATUS_SUCCESS) {
789 LOG(ERROR) << "Failed setting advertisement data";
790 InvokeAndClearStartCallback(GetBLEStatus(status));
795 if (scan_rsp_needs_update_.load()) {
796 bt_status_t status = SetAdvertiseData(gatt_iface, scan_response_, true);
797 if (status != BT_STATUS_SUCCESS) {
798 LOG(ERROR) << "Failed setting scan response data";
799 InvokeAndClearStartCallback(GetBLEStatus(status));
804 // All pending tasks are complete. Report success.
806 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
809 void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
810 adv_data_needs_update_ = false;
811 scan_rsp_needs_update_ = false;
813 // We allow NULL callbacks.
814 if (*adv_start_callback_)
815 (*adv_start_callback_)(status);
817 adv_start_callback_ = nullptr;
820 void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
821 // We allow NULL callbacks.
822 if (*adv_stop_callback_)
823 (*adv_stop_callback_)(status);
825 adv_stop_callback_ = nullptr;
828 // LowEnergyClientFactory implementation
829 // ========================================================
831 LowEnergyClientFactory::LowEnergyClientFactory(Adapter& adapter)
832 : adapter_(adapter) {
833 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
836 LowEnergyClientFactory::~LowEnergyClientFactory() {
837 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
840 bool LowEnergyClientFactory::RegisterInstance(
842 const RegisterCallback& callback) {
843 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
844 lock_guard<mutex> lock(pending_calls_lock_);
846 if (pending_calls_.find(uuid) != pending_calls_.end()) {
847 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
848 << "UUID: " << uuid.ToString();
852 const btgatt_client_interface_t* hal_iface =
853 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
854 bt_uuid_t app_uuid = uuid.GetBlueDroid();
856 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
859 pending_calls_[uuid] = callback;
864 void LowEnergyClientFactory::RegisterClientCallback(
865 hal::BluetoothGattInterface* gatt_iface,
866 int status, int client_id,
867 const bt_uuid_t& app_uuid) {
870 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
871 lock_guard<mutex> lock(pending_calls_lock_);
873 auto iter = pending_calls_.find(uuid);
874 if (iter == pending_calls_.end()) {
875 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
879 // No need to construct a client if the call wasn't successful.
880 std::unique_ptr<LowEnergyClient> client;
881 BLEStatus result = BLE_STATUS_FAILURE;
882 if (status == BT_STATUS_SUCCESS) {
883 client.reset(new LowEnergyClient(adapter_, uuid, client_id));
885 gatt_iface->AddClientObserver(client.get());
887 result = BLE_STATUS_SUCCESS;
890 // Notify the result via the result callback.
891 iter->second(result, uuid, std::move(client));
893 pending_calls_.erase(iter);
896 } // namespace bluetooth