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 ProcessAdvertiseData(const AdvertiseData& adv,
48 HALAdvertiseData* out_data) {
50 CHECK(out_data->manufacturer_data.empty());
51 CHECK(out_data->service_data.empty());
52 CHECK(out_data->service_uuid.empty());
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.
60 // The type byte is the next byte in the adv. "TLV" format.
61 uint8_t type = data[i + 1];
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";
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);
81 // TODO(armansito): Support other fields.
83 VLOG(1) << "Unrecognized EIR field: " << type;
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.
96 int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
100 case AdvertiseSettings::MODE_BALANCED:
101 ms = kAdvertisingIntervalMediumMs;
103 case AdvertiseSettings::MODE_LOW_LATENCY:
104 ms = kAdvertisingIntervalLowMs;
106 case AdvertiseSettings::MODE_LOW_POWER:
109 ms = kAdvertisingIntervalHighMs;
113 // Convert milliseconds Bluetooth units.
114 return (ms * 1000) / 625;
117 struct AdvertiseParams {
125 void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
126 AdvertiseParams* out_params) {
129 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
130 out_params->max_interval =
131 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
133 if (settings.connectable())
134 out_params->event_type = kAdvertisingEventTypeConnectable;
135 else if (has_scan_rsp)
136 out_params->event_type = kAdvertisingEventTypeScannable;
138 out_params->event_type = kAdvertisingEventTypeNonConnectable;
140 out_params->tx_power_level = settings.tx_power_level();
141 out_params->timeout_s = settings.timeout().InSeconds();
146 // LowEnergyClient implementation
147 // ========================================================
149 LowEnergyClient::LowEnergyClient(const UUID& uuid, int client_if)
150 : app_identifier_(uuid),
151 client_if_(client_if),
152 adv_data_needs_update_(false),
153 scan_rsp_needs_update_(false),
154 is_setting_adv_data_(false),
156 adv_start_callback_(nullptr),
157 adv_stop_callback_(nullptr) {
160 LowEnergyClient::~LowEnergyClient() {
161 // Automatically unregister the client.
162 VLOG(1) << "LowEnergyClient unregistering client: " << client_if_;
164 // Unregister as observer so we no longer receive any callbacks.
165 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
167 // Stop advertising and ignore the result.
168 hal::BluetoothGattInterface::Get()->
169 GetClientHALInterface()->multi_adv_disable(client_if_);
170 hal::BluetoothGattInterface::Get()->
171 GetClientHALInterface()->unregister_client(client_if_);
174 bool LowEnergyClient::StartAdvertising(const AdvertiseSettings& settings,
175 const AdvertiseData& advertise_data,
176 const AdvertiseData& scan_response,
177 const StatusCallback& callback) {
179 lock_guard<mutex> lock(adv_fields_lock_);
181 if (IsAdvertisingStarted()) {
182 LOG(WARNING) << "Already advertising";
186 if (IsStartingAdvertising()) {
187 LOG(WARNING) << "StartAdvertising already pending";
191 if (!advertise_data.IsValid()) {
192 LOG(ERROR) << "Invalid advertising data";
196 if (!scan_response.IsValid()) {
197 LOG(ERROR) << "Invalid scan response data";
201 CHECK(!adv_data_needs_update_.load());
202 CHECK(!scan_rsp_needs_update_.load());
204 adv_data_ = advertise_data;
205 scan_response_ = scan_response;
206 settings_ = settings;
208 AdvertiseParams params;
209 GetAdvertiseParams(settings, !scan_response_.data().empty(), ¶ms);
211 bt_status_t status = hal::BluetoothGattInterface::Get()->
212 GetClientHALInterface()->multi_adv_enable(
217 kAdvertisingChannelAll,
218 params.tx_power_level,
220 if (status != BT_STATUS_SUCCESS) {
221 LOG(ERROR) << "Failed to initiate call to enable multi-advertising";
225 // Always update advertising data.
226 adv_data_needs_update_ = true;
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;
233 // OK to set this at the end since we're still holding |adv_fields_lock_|.
234 adv_start_callback_.reset(new StatusCallback(callback));
239 bool LowEnergyClient::StopAdvertising(const StatusCallback& callback) {
241 lock_guard<mutex> lock(adv_fields_lock_);
243 if (!IsAdvertisingStarted()) {
244 LOG(ERROR) << "Not advertising";
248 if (IsStoppingAdvertising()) {
249 LOG(ERROR) << "StopAdvertising already pending";
253 CHECK(!adv_start_callback_);
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";
262 // OK to set this at the end since we're still holding |adv_fields_lock_|.
263 adv_stop_callback_.reset(new StatusCallback(callback));
268 bool LowEnergyClient::IsAdvertisingStarted() const {
269 return adv_started_.load();
272 bool LowEnergyClient::IsStartingAdvertising() const {
273 return !IsAdvertisingStarted() && adv_start_callback_;
276 bool LowEnergyClient::IsStoppingAdvertising() const {
277 return IsAdvertisingStarted() && adv_stop_callback_;
280 const UUID& LowEnergyClient::GetAppIdentifier() const {
281 return app_identifier_;
284 int LowEnergyClient::GetClientId() const {
288 void LowEnergyClient::MultiAdvEnableCallback(
289 hal::BluetoothGattInterface* gatt_iface,
290 int client_if, int status) {
291 if (client_if != client_if_)
294 lock_guard<mutex> lock(adv_fields_lock_);
296 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
298 CHECK(adv_start_callback_);
299 CHECK(!adv_stop_callback_);
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));
308 // Now handle deferred tasks.
309 HandleDeferredAdvertiseData(gatt_iface);
312 void LowEnergyClient::MultiAdvDataCallback(
313 hal::BluetoothGattInterface* gatt_iface,
314 int client_if, int status) {
315 if (client_if != client_if_)
318 lock_guard<mutex> lock(adv_fields_lock_);
320 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
322 is_setting_adv_data_ = false;
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));
331 // Now handle deferred tasks.
332 HandleDeferredAdvertiseData(gatt_iface);
335 void LowEnergyClient::MultiAdvDisableCallback(
336 hal::BluetoothGattInterface* /* gatt_iface */,
337 int client_if, int status) {
338 if (client_if != client_if_)
341 lock_guard<mutex> lock(adv_fields_lock_);
343 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
345 CHECK(!adv_start_callback_);
346 CHECK(adv_stop_callback_);
348 if (status == BT_STATUS_SUCCESS) {
349 VLOG(1) << "Multi-advertising stopped for client_if: " << client_if;
350 adv_started_ = false;
352 LOG(ERROR) << "Failed to stop multi-advertising";
355 InvokeAndClearStopCallback(GetBLEStatus(status));
358 bt_status_t LowEnergyClient::SetAdvertiseData(
359 hal::BluetoothGattInterface* gatt_iface,
360 const AdvertiseData& data,
364 HALAdvertiseData hal_data;
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;
375 if (is_setting_adv_data_.load()) {
376 VLOG(1) << "Setting advertising data already in progress.";
377 return BT_STATUS_FAIL;
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(
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.";
400 scan_rsp_needs_update_ = false;
402 adv_data_needs_update_ = false;
404 is_setting_adv_data_ = true;
409 void LowEnergyClient::HandleDeferredAdvertiseData(
410 hal::BluetoothGattInterface* gatt_iface) {
413 CHECK(!IsAdvertisingStarted());
414 CHECK(!IsStoppingAdvertising());
415 CHECK(IsStartingAdvertising());
416 CHECK(!is_setting_adv_data_.load());
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));
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));
436 // All pending tasks are complete. Report success.
438 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
441 void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
442 adv_data_needs_update_ = false;
443 scan_rsp_needs_update_ = false;
445 // We allow NULL callbacks.
446 if (*adv_start_callback_)
447 (*adv_start_callback_)(status);
449 adv_start_callback_ = nullptr;
452 void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
453 // We allow NULL callbacks.
454 if (*adv_stop_callback_)
455 (*adv_stop_callback_)(status);
457 adv_stop_callback_ = nullptr;
460 // LowEnergyClientFactory implementation
461 // ========================================================
463 LowEnergyClientFactory::LowEnergyClientFactory() {
464 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
467 LowEnergyClientFactory::~LowEnergyClientFactory() {
468 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
471 bool LowEnergyClientFactory::RegisterClient(const UUID& uuid,
472 const RegisterCallback& callback) {
473 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
474 lock_guard<mutex> lock(pending_calls_lock_);
476 if (pending_calls_.find(uuid) != pending_calls_.end()) {
477 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
478 << "UUID: " << uuid.ToString();
482 const btgatt_client_interface_t* hal_iface =
483 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
484 bt_uuid_t app_uuid = uuid.GetBlueDroid();
486 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
489 pending_calls_[uuid] = callback;
494 void LowEnergyClientFactory::RegisterClientCallback(
495 hal::BluetoothGattInterface* gatt_iface,
496 int status, int client_if,
497 const bt_uuid_t& app_uuid) {
500 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
501 lock_guard<mutex> lock(pending_calls_lock_);
503 auto iter = pending_calls_.find(uuid);
504 if (iter == pending_calls_.end()) {
505 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
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));
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
519 gatt_iface->AddClientObserverUnsafe(client.get());
521 result = BLE_STATUS_SUCCESS;
524 // Notify the result via the result callback.
525 iter->second(result, uuid, std::move(client));
527 pending_calls_.erase(iter);
530 } // namespace bluetooth