blob: f85d8b9004b2e14ee128891fe8c225ea74abed83 [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
280void LowEnergyClient::MultiAdvEnableCallback(
281 hal::BluetoothGattInterface* gatt_iface,
282 int client_if, int status) {
283 if (client_if != client_if_)
284 return;
285
286 lock_guard<mutex> lock(adv_fields_lock_);
287
288 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
289
290 CHECK(adv_start_callback_);
291 CHECK(!adv_stop_callback_);
292
293 // Terminate operation in case of error.
294 if (status != BT_STATUS_SUCCESS) {
295 LOG(ERROR) << "Failed to enable multi-advertising";
296 InvokeAndClearStartCallback(GetBLEStatus(status));
297 return;
298 }
299
300 // Now handle deferred tasks.
301 HandleDeferredAdvertiseData(gatt_iface);
302}
303
304void LowEnergyClient::MultiAdvDataCallback(
305 hal::BluetoothGattInterface* gatt_iface,
306 int client_if, int status) {
307 if (client_if != client_if_)
308 return;
309
310 lock_guard<mutex> lock(adv_fields_lock_);
311
312 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
313
314 is_setting_adv_data_ = false;
315
316 // Terminate operation in case of error.
317 if (status != BT_STATUS_SUCCESS) {
318 LOG(ERROR) << "Failed to set advertising data";
319 InvokeAndClearStartCallback(GetBLEStatus(status));
320 return;
321 }
322
323 // Now handle deferred tasks.
324 HandleDeferredAdvertiseData(gatt_iface);
325}
326
327void LowEnergyClient::MultiAdvDisableCallback(
328 hal::BluetoothGattInterface* /* gatt_iface */,
329 int client_if, int status) {
330 if (client_if != client_if_)
331 return;
332
333 lock_guard<mutex> lock(adv_fields_lock_);
334
335 VLOG(1) << __func__ << "client_if: " << client_if << " status: " << status;
336
337 CHECK(!adv_start_callback_);
338 CHECK(adv_stop_callback_);
339
340 if (status == BT_STATUS_SUCCESS) {
341 VLOG(1) << "Multi-advertising stopped for client_if: " << client_if;
342 adv_started_ = false;
343 } else {
344 LOG(ERROR) << "Failed to stop multi-advertising";
345 }
346
347 InvokeAndClearStopCallback(GetBLEStatus(status));
348}
349
350bt_status_t LowEnergyClient::SetAdvertiseData(
351 hal::BluetoothGattInterface* gatt_iface,
352 const AdvertiseData& data,
353 bool set_scan_rsp) {
354 VLOG(2) << __func__;
355
356 HALAdvertiseData hal_data;
357
358 // TODO(armansito): The stack should check that the length is valid when other
359 // fields inserted by the stack (e.g. flags, device name, tx-power) are taken
360 // into account. At the moment we are skipping this check; this means that if
361 // the given data is too long then the stack will truncate it.
362 if (!ProcessAdvertiseData(data, &hal_data)) {
363 VLOG(1) << "Malformed advertise data given";
364 return BT_STATUS_FAIL;
365 }
366
367 if (is_setting_adv_data_.load()) {
368 VLOG(1) << "Setting advertising data already in progress.";
369 return BT_STATUS_FAIL;
370 }
371
372 // TODO(armansito): The length fields in the BTIF function below are signed
373 // integers so a call to std::vector::size might get capped. This is very
374 // unlikely anyway but it's safer to stop using signed-integer types for
375 // length in APIs, so we should change that.
376 bt_status_t status = gatt_iface->GetClientHALInterface()->
377 multi_adv_set_inst_data(
378 client_if_,
379 set_scan_rsp,
380 data.include_device_name(),
381 data.include_tx_power_level(),
382 0, // This is what Bluetooth.apk current hardcodes for "appearance".
383 hal_data.manufacturer_data.size(),
384 reinterpret_cast<char*>(hal_data.manufacturer_data.data()),
385 0, nullptr, 0, nullptr); // TODO(armansito): Support the rest.
386 if (status != BT_STATUS_SUCCESS) {
387 LOG(ERROR) << "Failed to set instance advertising data.";
388 return status;
389 }
390
391 if (set_scan_rsp)
392 scan_rsp_needs_update_ = false;
393 else
394 adv_data_needs_update_ = false;
395
396 is_setting_adv_data_ = true;
397
398 return status;
399}
400
401void LowEnergyClient::HandleDeferredAdvertiseData(
402 hal::BluetoothGattInterface* gatt_iface) {
403 VLOG(2) << __func__;
404
405 CHECK(!IsAdvertisingStarted());
406 CHECK(!IsStoppingAdvertising());
407 CHECK(IsStartingAdvertising());
408 CHECK(!is_setting_adv_data_.load());
409
410 if (adv_data_needs_update_.load()) {
411 bt_status_t status = SetAdvertiseData(gatt_iface, adv_data_, false);
412 if (status != BT_STATUS_SUCCESS) {
413 LOG(ERROR) << "Failed setting advertisement data";
414 InvokeAndClearStartCallback(GetBLEStatus(status));
415 }
416 return;
417 }
418
419 if (scan_rsp_needs_update_.load()) {
420 bt_status_t status = SetAdvertiseData(gatt_iface, scan_response_, true);
421 if (status != BT_STATUS_SUCCESS) {
422 LOG(ERROR) << "Failed setting scan response data";
423 InvokeAndClearStartCallback(GetBLEStatus(status));
424 }
425 return;
426 }
427
428 // All pending tasks are complete. Report success.
429 adv_started_ = true;
430 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
431}
432
433void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
434 adv_data_needs_update_ = false;
435 scan_rsp_needs_update_ = false;
436
437 // We allow NULL callbacks.
438 if (*adv_start_callback_)
439 (*adv_start_callback_)(status);
440
441 adv_start_callback_ = nullptr;
442}
443
444void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
445 // We allow NULL callbacks.
446 if (*adv_stop_callback_)
447 (*adv_stop_callback_)(status);
448
449 adv_stop_callback_ = nullptr;
450}
451
452// LowEnergyClientFactory implementation
453// ========================================================
454
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700455LowEnergyClientFactory::LowEnergyClientFactory() {
456 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
457}
458
459LowEnergyClientFactory::~LowEnergyClientFactory() {
460 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
461}
462
463bool LowEnergyClientFactory::RegisterClient(const UUID& uuid,
464 const ClientCallback& callback) {
465 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
466 lock_guard<mutex> lock(pending_calls_lock_);
467
468 if (pending_calls_.find(uuid) != pending_calls_.end()) {
469 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
470 << "UUID: " << uuid.ToString();
471 return false;
472 }
473
474 const btgatt_client_interface_t* hal_iface =
475 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
476 bt_uuid_t app_uuid = uuid.GetBlueDroid();
477
478 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
479 return false;
480
481 pending_calls_[uuid] = callback;
482
483 return true;
484}
485
486void LowEnergyClientFactory::RegisterClientCallback(
Arman Uguray12338402015-09-16 18:00:05 -0700487 hal::BluetoothGattInterface* gatt_iface,
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700488 int status, int client_if,
489 const bt_uuid_t& app_uuid) {
490 UUID uuid(app_uuid);
491
492 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
493 lock_guard<mutex> lock(pending_calls_lock_);
494
495 auto iter = pending_calls_.find(uuid);
496 if (iter == pending_calls_.end()) {
497 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
498 return;
499 }
500
501 // No need to construct a client if the call wasn't successful.
502 std::unique_ptr<LowEnergyClient> client;
503 BLEStatus result = BLE_STATUS_FAILURE;
504 if (status == BT_STATUS_SUCCESS) {
505 client.reset(new LowEnergyClient(uuid, client_if));
Arman Uguray12338402015-09-16 18:00:05 -0700506
507 // Use the unsafe variant to register this as an observer, since
508 // LowEnergyClient instances only get created by LowEnergyClientCallback
509 // from inside this GATT client observer event, which would otherwise cause
510 // a deadlock.
511 gatt_iface->AddClientObserverUnsafe(client.get());
512
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700513 result = BLE_STATUS_SUCCESS;
514 }
515
516 // Notify the result via the success callback.
517 iter->second(result, uuid, std::move(client));
518
519 pending_calls_.erase(iter);
520}
521
522} // namespace bluetooth