blob: 36e681accda914e30f087bded2ee69e74c46967d [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
Jakub Pawlowski60b0e8f2016-01-12 13:51:35 -080021#include "service/adapter.h"
Arman Uguray12338402015-09-16 18:00:05 -070022#include "stack/include/bt_types.h"
23#include "stack/include/hcidefs.h"
24
Arman Ugurayc2fc0f22015-09-03 15:09:41 -070025using std::lock_guard;
26using std::mutex;
27
28namespace bluetooth {
29
Arman Uguray12338402015-09-16 18:00:05 -070030namespace {
31
32BLEStatus GetBLEStatus(int status) {
33 if (status == BT_STATUS_FAIL)
34 return BLE_STATUS_FAILURE;
35
36 return static_cast<BLEStatus>(status);
37}
38
39// TODO(armansito): BTIF currently expects each advertising field in a
40// specific format passed directly in arguments. We should fix BTIF to accept
41// the advertising data directly instead.
42struct HALAdvertiseData {
43 std::vector<uint8_t> manufacturer_data;
44 std::vector<uint8_t> service_data;
45 std::vector<uint8_t> service_uuid;
46};
47
Arman Uguray9fc7d812015-10-14 12:22:27 -070048bool ProcessUUID(const uint8_t* uuid_data, size_t uuid_len, UUID* out_uuid) {
49 // BTIF expects a single 128-bit UUID to be passed in little-endian form, so
50 // we need to convert into that from raw data.
51 // TODO(armansito): We have three repeated if bodies below only because UUID
52 // accepts std::array which requires constexpr lengths. We should just have a
53 // single UUID constructor that takes in an std::vector instead.
54 if (uuid_len == UUID::kNumBytes16) {
55 UUID::UUID16Bit uuid_bytes;
56 for (size_t i = 0; i < uuid_len; ++i)
57 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
58 *out_uuid = UUID(uuid_bytes);
59 } else if (uuid_len == UUID::kNumBytes32) {
60 UUID::UUID32Bit uuid_bytes;
61 for (size_t i = 0; i < uuid_len; ++i)
62 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
63 *out_uuid = UUID(uuid_bytes);
64 } else if (uuid_len == UUID::kNumBytes128) {
65 UUID::UUID128Bit uuid_bytes;
66 for (size_t i = 0; i < uuid_len; ++i)
67 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
68 *out_uuid = UUID(uuid_bytes);
69 } else {
70 LOG(ERROR) << "Invalid UUID length";
71 return false;
72 }
73
74 return true;
75}
76
Ajay Panickerff651b72015-09-30 15:49:47 -070077bool ProcessServiceData(const uint8_t* data,
Arman Uguray9fc7d812015-10-14 12:22:27 -070078 uint8_t uuid_len,
Ajay Panickerff651b72015-09-30 15:49:47 -070079 HALAdvertiseData* out_data){
80 size_t field_len = data[0];
81
82 // Minimum packet size should be equal to the uuid length + 1 to include
83 // the byte for the type of packet
Arman Uguray9fc7d812015-10-14 12:22:27 -070084 if (field_len < uuid_len + 1) {
Ajay Panickerff651b72015-09-30 15:49:47 -070085 // Invalid packet size
86 return false;
87 }
88
89 if (!out_data->service_data.empty()) {
90 // More than one Service Data is not allowed due to the limitations
91 // of the HAL API. We error in order to make sure there
92 // is no ambiguity on which data to send.
93 VLOG(1) << "More than one Service Data entry not allowed";
94 return false;
95 }
96
97 const uint8_t* service_uuid = data + 2;
Arman Uguray9fc7d812015-10-14 12:22:27 -070098 UUID uuid;
99 if (!ProcessUUID(service_uuid, uuid_len, &uuid))
100 return false;
101
102 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
103 const std::vector<uint8_t> temp_uuid(
104 uuid_bytes.data(), uuid_bytes.data() + uuid_bytes.size());
Ajay Panickerff651b72015-09-30 15:49:47 -0700105
106 // This section is to make sure that there is no UUID conflict
107 if (out_data->service_uuid.empty()) {
108 out_data->service_uuid = temp_uuid;
109 } else if (out_data->service_uuid != temp_uuid) {
110 // Mismatch in uuid passed through service data and uuid passed
111 // through uuid field
112 VLOG(1) << "More than one UUID entry not allowed";
113 return false;
114 } // else do nothing as UUID is already properly assigned
115
Arman Uguray9fc7d812015-10-14 12:22:27 -0700116 // Use + uuid_len + 2 here in order to skip over a
Ajay Panickerff651b72015-09-30 15:49:47 -0700117 // uuid contained in the beggining of the field
Arman Uguray9fc7d812015-10-14 12:22:27 -0700118 const uint8_t* srv_data = data + uuid_len + 2;
Ajay Panickerff651b72015-09-30 15:49:47 -0700119
120
121 out_data->service_data.insert(
122 out_data->service_data.begin(),
Arman Uguray9fc7d812015-10-14 12:22:27 -0700123 srv_data, srv_data + field_len - uuid_len - 1);
Ajay Panickerff651b72015-09-30 15:49:47 -0700124
125 return true;
126}
127
Arman Uguray12338402015-09-16 18:00:05 -0700128bool ProcessAdvertiseData(const AdvertiseData& adv,
129 HALAdvertiseData* out_data) {
130 CHECK(out_data);
131 CHECK(out_data->manufacturer_data.empty());
132 CHECK(out_data->service_data.empty());
133 CHECK(out_data->service_uuid.empty());
134
135 const auto& data = adv.data();
136 size_t len = data.size();
137 for (size_t i = 0, field_len = 0; i < len; i += (field_len + 1)) {
138 // The length byte is the first byte in the adv. "TLV" format.
139 field_len = data[i];
140
141 // The type byte is the next byte in the adv. "TLV" format.
142 uint8_t type = data[i + 1];
143 size_t uuid_len = 0;
144
145 switch (type) {
146 case HCI_EIR_MANUFACTURER_SPECIFIC_TYPE: {
147 // TODO(armansito): BTIF doesn't allow setting more than one
148 // manufacturer-specific data entry. This is something we should fix. For
149 // now, fail if more than one entry was set.
150 if (!out_data->manufacturer_data.empty()) {
Arman Uguray9fc7d812015-10-14 12:22:27 -0700151 LOG(ERROR) << "More than one Manufacturer Specific Data entry not allowed";
Arman Uguray12338402015-09-16 18:00:05 -0700152 return false;
153 }
154
155 // The value bytes start at the next byte in the "TLV" format.
156 const uint8_t* mnf_data = data.data() + i + 2;
157 out_data->manufacturer_data.insert(
158 out_data->manufacturer_data.begin(),
159 mnf_data, mnf_data + field_len - 1);
160 break;
161 }
Ajay Panickerff651b72015-09-30 15:49:47 -0700162 case HCI_EIR_MORE_16BITS_UUID_TYPE:
163 case HCI_EIR_COMPLETE_16BITS_UUID_TYPE:
164 case HCI_EIR_MORE_32BITS_UUID_TYPE:
165 case HCI_EIR_COMPLETE_32BITS_UUID_TYPE:
166 case HCI_EIR_MORE_128BITS_UUID_TYPE:
167 case HCI_EIR_COMPLETE_128BITS_UUID_TYPE: {
168 const uint8_t* uuid_data = data.data() + i + 2;
Arman Uguray9fc7d812015-10-14 12:22:27 -0700169 size_t uuid_len = field_len - 1;
170 UUID uuid;
171 if (!ProcessUUID(uuid_data, uuid_len, &uuid))
172 return false;
173
174 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
Ajay Panickerff651b72015-09-30 15:49:47 -0700175
176 if (!out_data->service_uuid.empty() &&
Arman Uguray9fc7d812015-10-14 12:22:27 -0700177 memcmp(out_data->service_uuid.data(),
178 uuid_bytes.data(), uuid_bytes.size()) != 0) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700179 // More than one UUID is not allowed due to the limitations
180 // of the HAL API. We error in order to make sure there
181 // is no ambiguity on which UUID to send. Also makes sure that
182 // UUID Hasn't been set by service data first
Arman Uguray9fc7d812015-10-14 12:22:27 -0700183 LOG(ERROR) << "More than one UUID entry not allowed";
Ajay Panickerff651b72015-09-30 15:49:47 -0700184 return false;
185 }
186
187 out_data->service_uuid.assign(
Arman Uguray9fc7d812015-10-14 12:22:27 -0700188 uuid_bytes.data(), uuid_bytes.data() + UUID::kNumBytes128);
Ajay Panickerff651b72015-09-30 15:49:47 -0700189 break;
190 }
191 case HCI_EIR_SERVICE_DATA_16BITS_UUID_TYPE: {
192 if (!ProcessServiceData(data.data() + i, 2, out_data))
193 return false;
194 break;
195 }
196 case HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE: {
197 if (!ProcessServiceData(data.data() + i, 4, out_data))
198 return false;
199 break;
200 }
201 case HCI_EIR_SERVICE_DATA_128BITS_UUID_TYPE: {
202 if (!ProcessServiceData(data.data() + i, 16, out_data))
203 return false;
204 break;
205 }
Arman Uguray12338402015-09-16 18:00:05 -0700206 // TODO(armansito): Support other fields.
207 default:
208 VLOG(1) << "Unrecognized EIR field: " << type;
209 return false;
210 }
211 }
212
213 return true;
214}
215
216// The Bluetooth Core Specification defines time interval (e.g. Page Scan
217// Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1
218// Baseband slot). The HAL advertising functions expect the interval in this
219// unit. This function maps an AdvertiseSettings::Mode value to the
220// corresponding time unit.
221int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
222 int ms;
223
224 switch (mode) {
225 case AdvertiseSettings::MODE_BALANCED:
226 ms = kAdvertisingIntervalMediumMs;
227 break;
228 case AdvertiseSettings::MODE_LOW_LATENCY:
229 ms = kAdvertisingIntervalLowMs;
230 break;
231 case AdvertiseSettings::MODE_LOW_POWER:
232 // Fall through
233 default:
234 ms = kAdvertisingIntervalHighMs;
235 break;
236 }
237
238 // Convert milliseconds Bluetooth units.
239 return (ms * 1000) / 625;
240}
241
242struct AdvertiseParams {
243 int min_interval;
244 int max_interval;
245 int event_type;
246 int tx_power_level;
247 int timeout_s;
248};
249
250void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
251 AdvertiseParams* out_params) {
252 CHECK(out_params);
253
254 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
255 out_params->max_interval =
256 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
257
258 if (settings.connectable())
259 out_params->event_type = kAdvertisingEventTypeConnectable;
260 else if (has_scan_rsp)
261 out_params->event_type = kAdvertisingEventTypeScannable;
262 else
263 out_params->event_type = kAdvertisingEventTypeNonConnectable;
264
265 out_params->tx_power_level = settings.tx_power_level();
266 out_params->timeout_s = settings.timeout().InSeconds();
267}
268
269} // namespace
270
271// LowEnergyClient implementation
272// ========================================================
273
Jakub Pawlowski60b0e8f2016-01-12 13:51:35 -0800274LowEnergyClient::LowEnergyClient(
275 Adapter& adapter, const UUID& uuid, int client_id)
276 : adapter_(adapter),
277 app_identifier_(uuid),
Arman Uguraybb18c412015-11-12 13:44:31 -0800278 client_id_(client_id),
Arman Uguray12338402015-09-16 18:00:05 -0700279 adv_data_needs_update_(false),
280 scan_rsp_needs_update_(false),
281 is_setting_adv_data_(false),
282 adv_started_(false),
283 adv_start_callback_(nullptr),
284 adv_stop_callback_(nullptr) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700285}
286
287LowEnergyClient::~LowEnergyClient() {
288 // Automatically unregister the client.
Arman Uguraybb18c412015-11-12 13:44:31 -0800289 VLOG(1) << "LowEnergyClient unregistering client: " << client_id_;
Arman Uguray12338402015-09-16 18:00:05 -0700290
291 // Unregister as observer so we no longer receive any callbacks.
292 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
293
294 // Stop advertising and ignore the result.
295 hal::BluetoothGattInterface::Get()->
Arman Uguraybb18c412015-11-12 13:44:31 -0800296 GetClientHALInterface()->multi_adv_disable(client_id_);
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700297 hal::BluetoothGattInterface::Get()->
Arman Uguraybb18c412015-11-12 13:44:31 -0800298 GetClientHALInterface()->unregister_client(client_id_);
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700299}
300
Arman Uguray12338402015-09-16 18:00:05 -0700301bool LowEnergyClient::StartAdvertising(const AdvertiseSettings& settings,
302 const AdvertiseData& advertise_data,
303 const AdvertiseData& scan_response,
304 const StatusCallback& callback) {
305 VLOG(2) << __func__;
306 lock_guard<mutex> lock(adv_fields_lock_);
307
308 if (IsAdvertisingStarted()) {
309 LOG(WARNING) << "Already advertising";
310 return false;
311 }
312
313 if (IsStartingAdvertising()) {
314 LOG(WARNING) << "StartAdvertising already pending";
315 return false;
316 }
317
318 if (!advertise_data.IsValid()) {
319 LOG(ERROR) << "Invalid advertising data";
320 return false;
321 }
322
323 if (!scan_response.IsValid()) {
324 LOG(ERROR) << "Invalid scan response data";
325 return false;
326 }
327
328 CHECK(!adv_data_needs_update_.load());
329 CHECK(!scan_rsp_needs_update_.load());
330
331 adv_data_ = advertise_data;
332 scan_response_ = scan_response;
Jakub Pawlowskid748ef22016-01-12 13:43:33 -0800333 advertise_settings_ = settings;
Arman Uguray12338402015-09-16 18:00:05 -0700334
335 AdvertiseParams params;
336 GetAdvertiseParams(settings, !scan_response_.data().empty(), &params);
337
338 bt_status_t status = hal::BluetoothGattInterface::Get()->
339 GetClientHALInterface()->multi_adv_enable(
Arman Uguraybb18c412015-11-12 13:44:31 -0800340 client_id_,
Arman Uguray12338402015-09-16 18:00:05 -0700341 params.min_interval,
342 params.max_interval,
343 params.event_type,
344 kAdvertisingChannelAll,
345 params.tx_power_level,
346 params.timeout_s);
347 if (status != BT_STATUS_SUCCESS) {
348 LOG(ERROR) << "Failed to initiate call to enable multi-advertising";
349 return false;
350 }
351
352 // Always update advertising data.
353 adv_data_needs_update_ = true;
354
355 // Update scan response only if it has data, since otherwise we just won't
356 // send ADV_SCAN_IND.
357 if (!scan_response_.data().empty())
358 scan_rsp_needs_update_ = true;
359
360 // OK to set this at the end since we're still holding |adv_fields_lock_|.
361 adv_start_callback_.reset(new StatusCallback(callback));
362
363 return true;
364}
365
366bool LowEnergyClient::StopAdvertising(const StatusCallback& callback) {
367 VLOG(2) << __func__;
368 lock_guard<mutex> lock(adv_fields_lock_);
369
370 if (!IsAdvertisingStarted()) {
371 LOG(ERROR) << "Not advertising";
372 return false;
373 }
374
375 if (IsStoppingAdvertising()) {
376 LOG(ERROR) << "StopAdvertising already pending";
377 return false;
378 }
379
380 CHECK(!adv_start_callback_);
381
382 bt_status_t status = hal::BluetoothGattInterface::Get()->
Arman Uguraybb18c412015-11-12 13:44:31 -0800383 GetClientHALInterface()->multi_adv_disable(client_id_);
Arman Uguray12338402015-09-16 18:00:05 -0700384 if (status != BT_STATUS_SUCCESS) {
385 LOG(ERROR) << "Failed to initiate call to disable multi-advertising";
386 return false;
387 }
388
389 // OK to set this at the end since we're still holding |adv_fields_lock_|.
390 adv_stop_callback_.reset(new StatusCallback(callback));
391
392 return true;
393}
394
395bool LowEnergyClient::IsAdvertisingStarted() const {
396 return adv_started_.load();
397}
398
399bool LowEnergyClient::IsStartingAdvertising() const {
400 return !IsAdvertisingStarted() && adv_start_callback_;
401}
402
403bool LowEnergyClient::IsStoppingAdvertising() const {
404 return IsAdvertisingStarted() && adv_stop_callback_;
405}
406
Arman Uguray08f80eb2015-09-21 11:17:07 -0700407const UUID& LowEnergyClient::GetAppIdentifier() const {
408 return app_identifier_;
409}
410
Arman Uguraybb18c412015-11-12 13:44:31 -0800411int LowEnergyClient::GetInstanceId() const {
412 return client_id_;
Arman Uguray08f80eb2015-09-21 11:17:07 -0700413}
414
Arman Uguray12338402015-09-16 18:00:05 -0700415void LowEnergyClient::MultiAdvEnableCallback(
416 hal::BluetoothGattInterface* gatt_iface,
Arman Uguraybb18c412015-11-12 13:44:31 -0800417 int client_id, int status) {
418 if (client_id != client_id_)
Arman Uguray12338402015-09-16 18:00:05 -0700419 return;
420
421 lock_guard<mutex> lock(adv_fields_lock_);
422
Arman Uguraybb18c412015-11-12 13:44:31 -0800423 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
Arman Uguray12338402015-09-16 18:00:05 -0700424
425 CHECK(adv_start_callback_);
426 CHECK(!adv_stop_callback_);
427
428 // Terminate operation in case of error.
429 if (status != BT_STATUS_SUCCESS) {
430 LOG(ERROR) << "Failed to enable multi-advertising";
431 InvokeAndClearStartCallback(GetBLEStatus(status));
432 return;
433 }
434
435 // Now handle deferred tasks.
436 HandleDeferredAdvertiseData(gatt_iface);
437}
438
439void LowEnergyClient::MultiAdvDataCallback(
440 hal::BluetoothGattInterface* gatt_iface,
Arman Uguraybb18c412015-11-12 13:44:31 -0800441 int client_id, int status) {
442 if (client_id != client_id_)
Arman Uguray12338402015-09-16 18:00:05 -0700443 return;
444
445 lock_guard<mutex> lock(adv_fields_lock_);
446
Arman Uguraybb18c412015-11-12 13:44:31 -0800447 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
Arman Uguray12338402015-09-16 18:00:05 -0700448
449 is_setting_adv_data_ = false;
450
451 // Terminate operation in case of error.
452 if (status != BT_STATUS_SUCCESS) {
453 LOG(ERROR) << "Failed to set advertising data";
454 InvokeAndClearStartCallback(GetBLEStatus(status));
455 return;
456 }
457
458 // Now handle deferred tasks.
459 HandleDeferredAdvertiseData(gatt_iface);
460}
461
462void LowEnergyClient::MultiAdvDisableCallback(
463 hal::BluetoothGattInterface* /* gatt_iface */,
Arman Uguraybb18c412015-11-12 13:44:31 -0800464 int client_id, int status) {
465 if (client_id != client_id_)
Arman Uguray12338402015-09-16 18:00:05 -0700466 return;
467
468 lock_guard<mutex> lock(adv_fields_lock_);
469
Arman Uguraybb18c412015-11-12 13:44:31 -0800470 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
Arman Uguray12338402015-09-16 18:00:05 -0700471
472 CHECK(!adv_start_callback_);
473 CHECK(adv_stop_callback_);
474
475 if (status == BT_STATUS_SUCCESS) {
Arman Uguraybb18c412015-11-12 13:44:31 -0800476 VLOG(1) << "Multi-advertising stopped for client_id: " << client_id;
Arman Uguray12338402015-09-16 18:00:05 -0700477 adv_started_ = false;
478 } else {
479 LOG(ERROR) << "Failed to stop multi-advertising";
480 }
481
482 InvokeAndClearStopCallback(GetBLEStatus(status));
483}
484
485bt_status_t LowEnergyClient::SetAdvertiseData(
486 hal::BluetoothGattInterface* gatt_iface,
487 const AdvertiseData& data,
488 bool set_scan_rsp) {
489 VLOG(2) << __func__;
490
491 HALAdvertiseData hal_data;
492
493 // TODO(armansito): The stack should check that the length is valid when other
494 // fields inserted by the stack (e.g. flags, device name, tx-power) are taken
495 // into account. At the moment we are skipping this check; this means that if
496 // the given data is too long then the stack will truncate it.
497 if (!ProcessAdvertiseData(data, &hal_data)) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700498 LOG(ERROR) << "Malformed advertise data given";
Arman Uguray12338402015-09-16 18:00:05 -0700499 return BT_STATUS_FAIL;
500 }
501
502 if (is_setting_adv_data_.load()) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700503 LOG(ERROR) << "Setting advertising data already in progress.";
Arman Uguray12338402015-09-16 18:00:05 -0700504 return BT_STATUS_FAIL;
505 }
506
507 // TODO(armansito): The length fields in the BTIF function below are signed
508 // integers so a call to std::vector::size might get capped. This is very
509 // unlikely anyway but it's safer to stop using signed-integer types for
510 // length in APIs, so we should change that.
511 bt_status_t status = gatt_iface->GetClientHALInterface()->
512 multi_adv_set_inst_data(
Arman Uguraybb18c412015-11-12 13:44:31 -0800513 client_id_,
Arman Uguray12338402015-09-16 18:00:05 -0700514 set_scan_rsp,
515 data.include_device_name(),
516 data.include_tx_power_level(),
517 0, // This is what Bluetooth.apk current hardcodes for "appearance".
518 hal_data.manufacturer_data.size(),
519 reinterpret_cast<char*>(hal_data.manufacturer_data.data()),
Ajay Panickerff651b72015-09-30 15:49:47 -0700520 hal_data.service_data.size(),
521 reinterpret_cast<char*>(hal_data.service_data.data()),
522 hal_data.service_uuid.size(),
523 reinterpret_cast<char*>(hal_data.service_uuid.data()));
524
Arman Uguray12338402015-09-16 18:00:05 -0700525 if (status != BT_STATUS_SUCCESS) {
526 LOG(ERROR) << "Failed to set instance advertising data.";
527 return status;
528 }
529
530 if (set_scan_rsp)
531 scan_rsp_needs_update_ = false;
532 else
533 adv_data_needs_update_ = false;
534
535 is_setting_adv_data_ = true;
536
537 return status;
538}
539
540void LowEnergyClient::HandleDeferredAdvertiseData(
541 hal::BluetoothGattInterface* gatt_iface) {
542 VLOG(2) << __func__;
543
544 CHECK(!IsAdvertisingStarted());
545 CHECK(!IsStoppingAdvertising());
546 CHECK(IsStartingAdvertising());
547 CHECK(!is_setting_adv_data_.load());
548
549 if (adv_data_needs_update_.load()) {
550 bt_status_t status = SetAdvertiseData(gatt_iface, adv_data_, false);
551 if (status != BT_STATUS_SUCCESS) {
552 LOG(ERROR) << "Failed setting advertisement data";
553 InvokeAndClearStartCallback(GetBLEStatus(status));
554 }
555 return;
556 }
557
558 if (scan_rsp_needs_update_.load()) {
559 bt_status_t status = SetAdvertiseData(gatt_iface, scan_response_, true);
560 if (status != BT_STATUS_SUCCESS) {
561 LOG(ERROR) << "Failed setting scan response data";
562 InvokeAndClearStartCallback(GetBLEStatus(status));
563 }
564 return;
565 }
566
567 // All pending tasks are complete. Report success.
568 adv_started_ = true;
569 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
570}
571
572void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
573 adv_data_needs_update_ = false;
574 scan_rsp_needs_update_ = false;
575
576 // We allow NULL callbacks.
577 if (*adv_start_callback_)
578 (*adv_start_callback_)(status);
579
580 adv_start_callback_ = nullptr;
581}
582
583void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
584 // We allow NULL callbacks.
585 if (*adv_stop_callback_)
586 (*adv_stop_callback_)(status);
587
588 adv_stop_callback_ = nullptr;
589}
590
591// LowEnergyClientFactory implementation
592// ========================================================
593
Jakub Pawlowski60b0e8f2016-01-12 13:51:35 -0800594LowEnergyClientFactory::LowEnergyClientFactory(Adapter& adapter)
595 : adapter_(adapter) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700596 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
597}
598
599LowEnergyClientFactory::~LowEnergyClientFactory() {
600 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
601}
602
Arman Uguraybb18c412015-11-12 13:44:31 -0800603bool LowEnergyClientFactory::RegisterInstance(
604 const UUID& uuid,
605 const RegisterCallback& callback) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700606 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
607 lock_guard<mutex> lock(pending_calls_lock_);
608
609 if (pending_calls_.find(uuid) != pending_calls_.end()) {
610 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
611 << "UUID: " << uuid.ToString();
612 return false;
613 }
614
615 const btgatt_client_interface_t* hal_iface =
616 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
617 bt_uuid_t app_uuid = uuid.GetBlueDroid();
618
619 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
620 return false;
621
622 pending_calls_[uuid] = callback;
623
624 return true;
625}
626
627void LowEnergyClientFactory::RegisterClientCallback(
Arman Uguray12338402015-09-16 18:00:05 -0700628 hal::BluetoothGattInterface* gatt_iface,
Arman Uguraybb18c412015-11-12 13:44:31 -0800629 int status, int client_id,
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700630 const bt_uuid_t& app_uuid) {
631 UUID uuid(app_uuid);
632
633 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
634 lock_guard<mutex> lock(pending_calls_lock_);
635
636 auto iter = pending_calls_.find(uuid);
637 if (iter == pending_calls_.end()) {
638 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
639 return;
640 }
641
642 // No need to construct a client if the call wasn't successful.
643 std::unique_ptr<LowEnergyClient> client;
644 BLEStatus result = BLE_STATUS_FAILURE;
645 if (status == BT_STATUS_SUCCESS) {
Jakub Pawlowski60b0e8f2016-01-12 13:51:35 -0800646 client.reset(new LowEnergyClient(adapter_, uuid, client_id));
Arman Uguray12338402015-09-16 18:00:05 -0700647
648 // Use the unsafe variant to register this as an observer, since
649 // LowEnergyClient instances only get created by LowEnergyClientCallback
650 // from inside this GATT client observer event, which would otherwise cause
651 // a deadlock.
652 gatt_iface->AddClientObserverUnsafe(client.get());
653
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700654 result = BLE_STATUS_SUCCESS;
655 }
656
Arman Uguray08f80eb2015-09-21 11:17:07 -0700657 // Notify the result via the result callback.
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700658 iter->second(result, uuid, std::move(client));
659
660 pending_calls_.erase(iter);
661}
662
663} // namespace bluetooth