blob: b3f9d64e8c0d385f168559b3b117c4167dee8d39 [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 Uguray82ea72f2015-12-02 17:29:27 -080022#include "service/logging_helpers.h"
Arman Uguray12338402015-09-16 18:00:05 -070023#include "stack/include/bt_types.h"
24#include "stack/include/hcidefs.h"
25
Arman Ugurayc2fc0f22015-09-03 15:09:41 -070026using std::lock_guard;
27using std::mutex;
28
29namespace bluetooth {
30
Arman Uguray12338402015-09-16 18:00:05 -070031namespace {
32
Arman Uguray82ea72f2015-12-02 17:29:27 -080033// 31 + 31 for advertising data and scan response. This is the maximum length
34// TODO(armansito): Fix the HAL to return a concatenated blob that contains the
35// true length of each field and also provide a length parameter so that we
36// can support advertising length extensions in the future.
37const size_t kScanRecordLength = 62;
38
Arman Uguray12338402015-09-16 18:00:05 -070039BLEStatus GetBLEStatus(int status) {
40 if (status == BT_STATUS_FAIL)
41 return BLE_STATUS_FAILURE;
42
43 return static_cast<BLEStatus>(status);
44}
45
Arman Uguray82ea72f2015-12-02 17:29:27 -080046// Returns the length of the given scan record array. We have to calculate this
47// based on the maximum possible data length and the TLV data. See TODO above
48// |kScanRecordLength|.
49size_t GetScanRecordLength(uint8_t* bytes) {
50 for (size_t i = 0, field_len = 0; i < kScanRecordLength;
51 i += (field_len + 1)) {
52 field_len = bytes[i];
53
54 // Assert here that the data returned from the stack is correctly formatted
55 // in TLV form and that the length of the current field won't exceed the
56 // total data length.
57 CHECK(i + field_len < kScanRecordLength);
58
59 // If the field length is zero and we haven't reached the maximum length,
60 // then we have found the length, as the stack will pad the data with zeros
61 // accordingly.
62 if (field_len == 0)
63 return i;
64 }
65
66 // We have reached the end.
67 return kScanRecordLength;
68}
69
Arman Uguray12338402015-09-16 18:00:05 -070070// TODO(armansito): BTIF currently expects each advertising field in a
71// specific format passed directly in arguments. We should fix BTIF to accept
72// the advertising data directly instead.
73struct HALAdvertiseData {
74 std::vector<uint8_t> manufacturer_data;
75 std::vector<uint8_t> service_data;
76 std::vector<uint8_t> service_uuid;
77};
78
Arman Uguray9fc7d812015-10-14 12:22:27 -070079bool ProcessUUID(const uint8_t* uuid_data, size_t uuid_len, UUID* out_uuid) {
80 // BTIF expects a single 128-bit UUID to be passed in little-endian form, so
81 // we need to convert into that from raw data.
82 // TODO(armansito): We have three repeated if bodies below only because UUID
83 // accepts std::array which requires constexpr lengths. We should just have a
84 // single UUID constructor that takes in an std::vector instead.
85 if (uuid_len == UUID::kNumBytes16) {
86 UUID::UUID16Bit uuid_bytes;
87 for (size_t i = 0; i < uuid_len; ++i)
88 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
89 *out_uuid = UUID(uuid_bytes);
90 } else if (uuid_len == UUID::kNumBytes32) {
91 UUID::UUID32Bit uuid_bytes;
92 for (size_t i = 0; i < uuid_len; ++i)
93 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
94 *out_uuid = UUID(uuid_bytes);
95 } else if (uuid_len == UUID::kNumBytes128) {
96 UUID::UUID128Bit uuid_bytes;
97 for (size_t i = 0; i < uuid_len; ++i)
98 uuid_bytes[uuid_len - i - 1] = uuid_data[i];
99 *out_uuid = UUID(uuid_bytes);
100 } else {
101 LOG(ERROR) << "Invalid UUID length";
102 return false;
103 }
104
105 return true;
106}
107
Ajay Panickerff651b72015-09-30 15:49:47 -0700108bool ProcessServiceData(const uint8_t* data,
Arman Uguray9fc7d812015-10-14 12:22:27 -0700109 uint8_t uuid_len,
Ajay Panickerff651b72015-09-30 15:49:47 -0700110 HALAdvertiseData* out_data){
111 size_t field_len = data[0];
112
113 // Minimum packet size should be equal to the uuid length + 1 to include
114 // the byte for the type of packet
Arman Uguray9fc7d812015-10-14 12:22:27 -0700115 if (field_len < uuid_len + 1) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700116 // Invalid packet size
117 return false;
118 }
119
120 if (!out_data->service_data.empty()) {
121 // More than one Service Data is not allowed due to the limitations
122 // of the HAL API. We error in order to make sure there
123 // is no ambiguity on which data to send.
124 VLOG(1) << "More than one Service Data entry not allowed";
125 return false;
126 }
127
128 const uint8_t* service_uuid = data + 2;
Arman Uguray9fc7d812015-10-14 12:22:27 -0700129 UUID uuid;
130 if (!ProcessUUID(service_uuid, uuid_len, &uuid))
131 return false;
132
133 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
134 const std::vector<uint8_t> temp_uuid(
135 uuid_bytes.data(), uuid_bytes.data() + uuid_bytes.size());
Ajay Panickerff651b72015-09-30 15:49:47 -0700136
137 // This section is to make sure that there is no UUID conflict
138 if (out_data->service_uuid.empty()) {
139 out_data->service_uuid = temp_uuid;
140 } else if (out_data->service_uuid != temp_uuid) {
141 // Mismatch in uuid passed through service data and uuid passed
142 // through uuid field
143 VLOG(1) << "More than one UUID entry not allowed";
144 return false;
145 } // else do nothing as UUID is already properly assigned
146
Arman Uguray9fc7d812015-10-14 12:22:27 -0700147 // Use + uuid_len + 2 here in order to skip over a
Ajay Panickerff651b72015-09-30 15:49:47 -0700148 // uuid contained in the beggining of the field
Arman Uguray9fc7d812015-10-14 12:22:27 -0700149 const uint8_t* srv_data = data + uuid_len + 2;
Ajay Panickerff651b72015-09-30 15:49:47 -0700150
151
152 out_data->service_data.insert(
153 out_data->service_data.begin(),
Arman Uguray9fc7d812015-10-14 12:22:27 -0700154 srv_data, srv_data + field_len - uuid_len - 1);
Ajay Panickerff651b72015-09-30 15:49:47 -0700155
156 return true;
157}
158
Arman Uguray12338402015-09-16 18:00:05 -0700159bool ProcessAdvertiseData(const AdvertiseData& adv,
160 HALAdvertiseData* out_data) {
161 CHECK(out_data);
162 CHECK(out_data->manufacturer_data.empty());
163 CHECK(out_data->service_data.empty());
164 CHECK(out_data->service_uuid.empty());
165
166 const auto& data = adv.data();
167 size_t len = data.size();
168 for (size_t i = 0, field_len = 0; i < len; i += (field_len + 1)) {
169 // The length byte is the first byte in the adv. "TLV" format.
170 field_len = data[i];
171
172 // The type byte is the next byte in the adv. "TLV" format.
173 uint8_t type = data[i + 1];
174 size_t uuid_len = 0;
175
176 switch (type) {
177 case HCI_EIR_MANUFACTURER_SPECIFIC_TYPE: {
178 // TODO(armansito): BTIF doesn't allow setting more than one
179 // manufacturer-specific data entry. This is something we should fix. For
180 // now, fail if more than one entry was set.
181 if (!out_data->manufacturer_data.empty()) {
Arman Uguray9fc7d812015-10-14 12:22:27 -0700182 LOG(ERROR) << "More than one Manufacturer Specific Data entry not allowed";
Arman Uguray12338402015-09-16 18:00:05 -0700183 return false;
184 }
185
186 // The value bytes start at the next byte in the "TLV" format.
187 const uint8_t* mnf_data = data.data() + i + 2;
188 out_data->manufacturer_data.insert(
189 out_data->manufacturer_data.begin(),
190 mnf_data, mnf_data + field_len - 1);
191 break;
192 }
Ajay Panickerff651b72015-09-30 15:49:47 -0700193 case HCI_EIR_MORE_16BITS_UUID_TYPE:
194 case HCI_EIR_COMPLETE_16BITS_UUID_TYPE:
195 case HCI_EIR_MORE_32BITS_UUID_TYPE:
196 case HCI_EIR_COMPLETE_32BITS_UUID_TYPE:
197 case HCI_EIR_MORE_128BITS_UUID_TYPE:
198 case HCI_EIR_COMPLETE_128BITS_UUID_TYPE: {
199 const uint8_t* uuid_data = data.data() + i + 2;
Arman Uguray9fc7d812015-10-14 12:22:27 -0700200 size_t uuid_len = field_len - 1;
201 UUID uuid;
202 if (!ProcessUUID(uuid_data, uuid_len, &uuid))
203 return false;
204
205 UUID::UUID128Bit uuid_bytes = uuid.GetFullLittleEndian();
Ajay Panickerff651b72015-09-30 15:49:47 -0700206
207 if (!out_data->service_uuid.empty() &&
Arman Uguray9fc7d812015-10-14 12:22:27 -0700208 memcmp(out_data->service_uuid.data(),
209 uuid_bytes.data(), uuid_bytes.size()) != 0) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700210 // More than one UUID is not allowed due to the limitations
211 // of the HAL API. We error in order to make sure there
212 // is no ambiguity on which UUID to send. Also makes sure that
213 // UUID Hasn't been set by service data first
Arman Uguray9fc7d812015-10-14 12:22:27 -0700214 LOG(ERROR) << "More than one UUID entry not allowed";
Ajay Panickerff651b72015-09-30 15:49:47 -0700215 return false;
216 }
217
218 out_data->service_uuid.assign(
Arman Uguray9fc7d812015-10-14 12:22:27 -0700219 uuid_bytes.data(), uuid_bytes.data() + UUID::kNumBytes128);
Ajay Panickerff651b72015-09-30 15:49:47 -0700220 break;
221 }
222 case HCI_EIR_SERVICE_DATA_16BITS_UUID_TYPE: {
223 if (!ProcessServiceData(data.data() + i, 2, out_data))
224 return false;
225 break;
226 }
227 case HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE: {
228 if (!ProcessServiceData(data.data() + i, 4, out_data))
229 return false;
230 break;
231 }
232 case HCI_EIR_SERVICE_DATA_128BITS_UUID_TYPE: {
233 if (!ProcessServiceData(data.data() + i, 16, out_data))
234 return false;
235 break;
236 }
Arman Uguray12338402015-09-16 18:00:05 -0700237 // TODO(armansito): Support other fields.
238 default:
239 VLOG(1) << "Unrecognized EIR field: " << type;
240 return false;
241 }
242 }
243
244 return true;
245}
246
247// The Bluetooth Core Specification defines time interval (e.g. Page Scan
248// Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1
249// Baseband slot). The HAL advertising functions expect the interval in this
250// unit. This function maps an AdvertiseSettings::Mode value to the
251// corresponding time unit.
252int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
253 int ms;
254
255 switch (mode) {
256 case AdvertiseSettings::MODE_BALANCED:
257 ms = kAdvertisingIntervalMediumMs;
258 break;
259 case AdvertiseSettings::MODE_LOW_LATENCY:
260 ms = kAdvertisingIntervalLowMs;
261 break;
262 case AdvertiseSettings::MODE_LOW_POWER:
263 // Fall through
264 default:
265 ms = kAdvertisingIntervalHighMs;
266 break;
267 }
268
269 // Convert milliseconds Bluetooth units.
270 return (ms * 1000) / 625;
271}
272
273struct AdvertiseParams {
274 int min_interval;
275 int max_interval;
276 int event_type;
277 int tx_power_level;
278 int timeout_s;
279};
280
281void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
282 AdvertiseParams* out_params) {
283 CHECK(out_params);
284
285 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
286 out_params->max_interval =
287 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
288
289 if (settings.connectable())
290 out_params->event_type = kAdvertisingEventTypeConnectable;
291 else if (has_scan_rsp)
292 out_params->event_type = kAdvertisingEventTypeScannable;
293 else
294 out_params->event_type = kAdvertisingEventTypeNonConnectable;
295
296 out_params->tx_power_level = settings.tx_power_level();
297 out_params->timeout_s = settings.timeout().InSeconds();
298}
299
300} // namespace
301
302// LowEnergyClient implementation
303// ========================================================
304
Jakub Pawlowski60b0e8f2016-01-12 13:51:35 -0800305LowEnergyClient::LowEnergyClient(
306 Adapter& adapter, const UUID& uuid, int client_id)
307 : adapter_(adapter),
308 app_identifier_(uuid),
Arman Uguraybb18c412015-11-12 13:44:31 -0800309 client_id_(client_id),
Arman Uguray12338402015-09-16 18:00:05 -0700310 adv_data_needs_update_(false),
311 scan_rsp_needs_update_(false),
312 is_setting_adv_data_(false),
313 adv_started_(false),
314 adv_start_callback_(nullptr),
Arman Uguray480174f2015-11-30 15:36:17 -0800315 adv_stop_callback_(nullptr),
316 scan_started_(false) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700317}
318
319LowEnergyClient::~LowEnergyClient() {
320 // Automatically unregister the client.
Arman Uguraybb18c412015-11-12 13:44:31 -0800321 VLOG(1) << "LowEnergyClient unregistering client: " << client_id_;
Arman Uguray12338402015-09-16 18:00:05 -0700322
323 // Unregister as observer so we no longer receive any callbacks.
324 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
325
326 // Stop advertising and ignore the result.
327 hal::BluetoothGattInterface::Get()->
Arman Uguraybb18c412015-11-12 13:44:31 -0800328 GetClientHALInterface()->multi_adv_disable(client_id_);
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700329 hal::BluetoothGattInterface::Get()->
Arman Uguraybb18c412015-11-12 13:44:31 -0800330 GetClientHALInterface()->unregister_client(client_id_);
Arman Uguray480174f2015-11-30 15:36:17 -0800331
332 // Stop any scans started by this client.
333 if (scan_started_.load())
334 StopScan();
335}
336
Arman Uguray82ea72f2015-12-02 17:29:27 -0800337void LowEnergyClient::SetDelegate(Delegate* delegate) {
338 lock_guard<mutex> lock(delegate_mutex_);
339 delegate_ = delegate;
340}
341
Arman Uguray480174f2015-11-30 15:36:17 -0800342bool LowEnergyClient::StartScan(const ScanSettings& settings,
343 const std::vector<ScanFilter>& filters) {
344 VLOG(2) << __func__;
345
346 // Cannot start a scan if the adapter is not enabled.
347 if (!adapter_.IsEnabled()) {
348 LOG(ERROR) << "Cannot scan while Bluetooth is disabled";
349 return false;
350 }
351
352 // TODO(jpawlowski): Push settings and filtering logic below the HAL.
353 bt_status_t status = hal::BluetoothGattInterface::Get()->
354 StartScan(client_id_);
355 if (status != BT_STATUS_SUCCESS) {
356 LOG(ERROR) << "Failed to initiate scanning for client: " << client_id_;
357 return false;
358 }
359
360 scan_started_ = true;
361 return true;
362}
363
364bool LowEnergyClient::StopScan() {
365 VLOG(2) << __func__;
366
367 // TODO(armansito): We don't support batch scanning yet so call
368 // StopRegularScanForClient directly. In the future we will need to
369 // conditionally call a batch scan API here.
370 bt_status_t status = hal::BluetoothGattInterface::Get()->
371 StopScan(client_id_);
372 if (status != BT_STATUS_SUCCESS) {
373 LOG(ERROR) << "Failed to stop scan for client: " << client_id_;
374 return false;
375 }
376
377 scan_started_ = false;
378 return true;
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700379}
380
Arman Uguray12338402015-09-16 18:00:05 -0700381bool LowEnergyClient::StartAdvertising(const AdvertiseSettings& settings,
382 const AdvertiseData& advertise_data,
383 const AdvertiseData& scan_response,
384 const StatusCallback& callback) {
385 VLOG(2) << __func__;
386 lock_guard<mutex> lock(adv_fields_lock_);
387
388 if (IsAdvertisingStarted()) {
389 LOG(WARNING) << "Already advertising";
390 return false;
391 }
392
393 if (IsStartingAdvertising()) {
394 LOG(WARNING) << "StartAdvertising already pending";
395 return false;
396 }
397
398 if (!advertise_data.IsValid()) {
399 LOG(ERROR) << "Invalid advertising data";
400 return false;
401 }
402
403 if (!scan_response.IsValid()) {
404 LOG(ERROR) << "Invalid scan response data";
405 return false;
406 }
407
408 CHECK(!adv_data_needs_update_.load());
409 CHECK(!scan_rsp_needs_update_.load());
410
411 adv_data_ = advertise_data;
412 scan_response_ = scan_response;
Jakub Pawlowskid748ef22016-01-12 13:43:33 -0800413 advertise_settings_ = settings;
Arman Uguray12338402015-09-16 18:00:05 -0700414
415 AdvertiseParams params;
416 GetAdvertiseParams(settings, !scan_response_.data().empty(), &params);
417
418 bt_status_t status = hal::BluetoothGattInterface::Get()->
419 GetClientHALInterface()->multi_adv_enable(
Arman Uguraybb18c412015-11-12 13:44:31 -0800420 client_id_,
Arman Uguray12338402015-09-16 18:00:05 -0700421 params.min_interval,
422 params.max_interval,
423 params.event_type,
424 kAdvertisingChannelAll,
425 params.tx_power_level,
426 params.timeout_s);
427 if (status != BT_STATUS_SUCCESS) {
428 LOG(ERROR) << "Failed to initiate call to enable multi-advertising";
429 return false;
430 }
431
432 // Always update advertising data.
433 adv_data_needs_update_ = true;
434
435 // Update scan response only if it has data, since otherwise we just won't
436 // send ADV_SCAN_IND.
437 if (!scan_response_.data().empty())
438 scan_rsp_needs_update_ = true;
439
440 // OK to set this at the end since we're still holding |adv_fields_lock_|.
441 adv_start_callback_.reset(new StatusCallback(callback));
442
443 return true;
444}
445
446bool LowEnergyClient::StopAdvertising(const StatusCallback& callback) {
447 VLOG(2) << __func__;
448 lock_guard<mutex> lock(adv_fields_lock_);
449
450 if (!IsAdvertisingStarted()) {
451 LOG(ERROR) << "Not advertising";
452 return false;
453 }
454
455 if (IsStoppingAdvertising()) {
456 LOG(ERROR) << "StopAdvertising already pending";
457 return false;
458 }
459
460 CHECK(!adv_start_callback_);
461
462 bt_status_t status = hal::BluetoothGattInterface::Get()->
Arman Uguraybb18c412015-11-12 13:44:31 -0800463 GetClientHALInterface()->multi_adv_disable(client_id_);
Arman Uguray12338402015-09-16 18:00:05 -0700464 if (status != BT_STATUS_SUCCESS) {
465 LOG(ERROR) << "Failed to initiate call to disable multi-advertising";
466 return false;
467 }
468
469 // OK to set this at the end since we're still holding |adv_fields_lock_|.
470 adv_stop_callback_.reset(new StatusCallback(callback));
471
472 return true;
473}
474
475bool LowEnergyClient::IsAdvertisingStarted() const {
476 return adv_started_.load();
477}
478
479bool LowEnergyClient::IsStartingAdvertising() const {
480 return !IsAdvertisingStarted() && adv_start_callback_;
481}
482
483bool LowEnergyClient::IsStoppingAdvertising() const {
484 return IsAdvertisingStarted() && adv_stop_callback_;
485}
486
Arman Uguray08f80eb2015-09-21 11:17:07 -0700487const UUID& LowEnergyClient::GetAppIdentifier() const {
488 return app_identifier_;
489}
490
Arman Uguraybb18c412015-11-12 13:44:31 -0800491int LowEnergyClient::GetInstanceId() const {
492 return client_id_;
Arman Uguray08f80eb2015-09-21 11:17:07 -0700493}
494
Arman Uguray82ea72f2015-12-02 17:29:27 -0800495void LowEnergyClient::ScanResultCallback(
496 hal::BluetoothGattInterface* gatt_iface,
497 const bt_bdaddr_t& bda, int rssi, uint8_t* adv_data) {
498 // Ignore scan results if this client didn't start a scan.
499 if (!scan_started_.load())
500 return;
501
502 lock_guard<mutex> lock(delegate_mutex_);
503 if (!delegate_)
504 return;
505
506 // TODO(armansito): Apply software filters here.
507
508 size_t record_len = GetScanRecordLength(adv_data);
509 std::vector<uint8_t> scan_record(adv_data, adv_data + record_len);
510
511 ScanResult result(BtAddrString(&bda), scan_record, rssi);
512
513 delegate_->OnScanResult(this, result);
514}
515
Arman Uguray12338402015-09-16 18:00:05 -0700516void LowEnergyClient::MultiAdvEnableCallback(
517 hal::BluetoothGattInterface* gatt_iface,
Arman Uguraybb18c412015-11-12 13:44:31 -0800518 int client_id, int status) {
519 if (client_id != client_id_)
Arman Uguray12338402015-09-16 18:00:05 -0700520 return;
521
522 lock_guard<mutex> lock(adv_fields_lock_);
523
Arman Uguraybb18c412015-11-12 13:44:31 -0800524 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
Arman Uguray12338402015-09-16 18:00:05 -0700525
526 CHECK(adv_start_callback_);
527 CHECK(!adv_stop_callback_);
528
529 // Terminate operation in case of error.
530 if (status != BT_STATUS_SUCCESS) {
531 LOG(ERROR) << "Failed to enable multi-advertising";
532 InvokeAndClearStartCallback(GetBLEStatus(status));
533 return;
534 }
535
536 // Now handle deferred tasks.
537 HandleDeferredAdvertiseData(gatt_iface);
538}
539
540void LowEnergyClient::MultiAdvDataCallback(
541 hal::BluetoothGattInterface* gatt_iface,
Arman Uguraybb18c412015-11-12 13:44:31 -0800542 int client_id, int status) {
543 if (client_id != client_id_)
Arman Uguray12338402015-09-16 18:00:05 -0700544 return;
545
546 lock_guard<mutex> lock(adv_fields_lock_);
547
Arman Uguraybb18c412015-11-12 13:44:31 -0800548 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
Arman Uguray12338402015-09-16 18:00:05 -0700549
550 is_setting_adv_data_ = false;
551
552 // Terminate operation in case of error.
553 if (status != BT_STATUS_SUCCESS) {
554 LOG(ERROR) << "Failed to set advertising data";
555 InvokeAndClearStartCallback(GetBLEStatus(status));
556 return;
557 }
558
559 // Now handle deferred tasks.
560 HandleDeferredAdvertiseData(gatt_iface);
561}
562
563void LowEnergyClient::MultiAdvDisableCallback(
564 hal::BluetoothGattInterface* /* gatt_iface */,
Arman Uguraybb18c412015-11-12 13:44:31 -0800565 int client_id, int status) {
566 if (client_id != client_id_)
Arman Uguray12338402015-09-16 18:00:05 -0700567 return;
568
569 lock_guard<mutex> lock(adv_fields_lock_);
570
Arman Uguraybb18c412015-11-12 13:44:31 -0800571 VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status;
Arman Uguray12338402015-09-16 18:00:05 -0700572
573 CHECK(!adv_start_callback_);
574 CHECK(adv_stop_callback_);
575
576 if (status == BT_STATUS_SUCCESS) {
Arman Uguraybb18c412015-11-12 13:44:31 -0800577 VLOG(1) << "Multi-advertising stopped for client_id: " << client_id;
Arman Uguray12338402015-09-16 18:00:05 -0700578 adv_started_ = false;
579 } else {
580 LOG(ERROR) << "Failed to stop multi-advertising";
581 }
582
583 InvokeAndClearStopCallback(GetBLEStatus(status));
584}
585
586bt_status_t LowEnergyClient::SetAdvertiseData(
587 hal::BluetoothGattInterface* gatt_iface,
588 const AdvertiseData& data,
589 bool set_scan_rsp) {
590 VLOG(2) << __func__;
591
592 HALAdvertiseData hal_data;
593
594 // TODO(armansito): The stack should check that the length is valid when other
595 // fields inserted by the stack (e.g. flags, device name, tx-power) are taken
596 // into account. At the moment we are skipping this check; this means that if
597 // the given data is too long then the stack will truncate it.
598 if (!ProcessAdvertiseData(data, &hal_data)) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700599 LOG(ERROR) << "Malformed advertise data given";
Arman Uguray12338402015-09-16 18:00:05 -0700600 return BT_STATUS_FAIL;
601 }
602
603 if (is_setting_adv_data_.load()) {
Ajay Panickerff651b72015-09-30 15:49:47 -0700604 LOG(ERROR) << "Setting advertising data already in progress.";
Arman Uguray12338402015-09-16 18:00:05 -0700605 return BT_STATUS_FAIL;
606 }
607
608 // TODO(armansito): The length fields in the BTIF function below are signed
609 // integers so a call to std::vector::size might get capped. This is very
610 // unlikely anyway but it's safer to stop using signed-integer types for
611 // length in APIs, so we should change that.
612 bt_status_t status = gatt_iface->GetClientHALInterface()->
613 multi_adv_set_inst_data(
Arman Uguraybb18c412015-11-12 13:44:31 -0800614 client_id_,
Arman Uguray12338402015-09-16 18:00:05 -0700615 set_scan_rsp,
616 data.include_device_name(),
617 data.include_tx_power_level(),
618 0, // This is what Bluetooth.apk current hardcodes for "appearance".
619 hal_data.manufacturer_data.size(),
620 reinterpret_cast<char*>(hal_data.manufacturer_data.data()),
Ajay Panickerff651b72015-09-30 15:49:47 -0700621 hal_data.service_data.size(),
622 reinterpret_cast<char*>(hal_data.service_data.data()),
623 hal_data.service_uuid.size(),
624 reinterpret_cast<char*>(hal_data.service_uuid.data()));
625
Arman Uguray12338402015-09-16 18:00:05 -0700626 if (status != BT_STATUS_SUCCESS) {
627 LOG(ERROR) << "Failed to set instance advertising data.";
628 return status;
629 }
630
631 if (set_scan_rsp)
632 scan_rsp_needs_update_ = false;
633 else
634 adv_data_needs_update_ = false;
635
636 is_setting_adv_data_ = true;
637
638 return status;
639}
640
641void LowEnergyClient::HandleDeferredAdvertiseData(
642 hal::BluetoothGattInterface* gatt_iface) {
643 VLOG(2) << __func__;
644
645 CHECK(!IsAdvertisingStarted());
646 CHECK(!IsStoppingAdvertising());
647 CHECK(IsStartingAdvertising());
648 CHECK(!is_setting_adv_data_.load());
649
650 if (adv_data_needs_update_.load()) {
651 bt_status_t status = SetAdvertiseData(gatt_iface, adv_data_, false);
652 if (status != BT_STATUS_SUCCESS) {
653 LOG(ERROR) << "Failed setting advertisement data";
654 InvokeAndClearStartCallback(GetBLEStatus(status));
655 }
656 return;
657 }
658
659 if (scan_rsp_needs_update_.load()) {
660 bt_status_t status = SetAdvertiseData(gatt_iface, scan_response_, true);
661 if (status != BT_STATUS_SUCCESS) {
662 LOG(ERROR) << "Failed setting scan response data";
663 InvokeAndClearStartCallback(GetBLEStatus(status));
664 }
665 return;
666 }
667
668 // All pending tasks are complete. Report success.
669 adv_started_ = true;
670 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
671}
672
673void LowEnergyClient::InvokeAndClearStartCallback(BLEStatus status) {
674 adv_data_needs_update_ = false;
675 scan_rsp_needs_update_ = false;
676
677 // We allow NULL callbacks.
678 if (*adv_start_callback_)
679 (*adv_start_callback_)(status);
680
681 adv_start_callback_ = nullptr;
682}
683
684void LowEnergyClient::InvokeAndClearStopCallback(BLEStatus status) {
685 // We allow NULL callbacks.
686 if (*adv_stop_callback_)
687 (*adv_stop_callback_)(status);
688
689 adv_stop_callback_ = nullptr;
690}
691
692// LowEnergyClientFactory implementation
693// ========================================================
694
Jakub Pawlowski60b0e8f2016-01-12 13:51:35 -0800695LowEnergyClientFactory::LowEnergyClientFactory(Adapter& adapter)
696 : adapter_(adapter) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700697 hal::BluetoothGattInterface::Get()->AddClientObserver(this);
698}
699
700LowEnergyClientFactory::~LowEnergyClientFactory() {
701 hal::BluetoothGattInterface::Get()->RemoveClientObserver(this);
702}
703
Arman Uguraybb18c412015-11-12 13:44:31 -0800704bool LowEnergyClientFactory::RegisterInstance(
705 const UUID& uuid,
706 const RegisterCallback& callback) {
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700707 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
708 lock_guard<mutex> lock(pending_calls_lock_);
709
710 if (pending_calls_.find(uuid) != pending_calls_.end()) {
711 LOG(ERROR) << "Low-Energy client with given UUID already registered - "
712 << "UUID: " << uuid.ToString();
713 return false;
714 }
715
716 const btgatt_client_interface_t* hal_iface =
717 hal::BluetoothGattInterface::Get()->GetClientHALInterface();
718 bt_uuid_t app_uuid = uuid.GetBlueDroid();
719
720 if (hal_iface->register_client(&app_uuid) != BT_STATUS_SUCCESS)
721 return false;
722
723 pending_calls_[uuid] = callback;
724
725 return true;
726}
727
728void LowEnergyClientFactory::RegisterClientCallback(
Arman Uguray12338402015-09-16 18:00:05 -0700729 hal::BluetoothGattInterface* gatt_iface,
Arman Uguraybb18c412015-11-12 13:44:31 -0800730 int status, int client_id,
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700731 const bt_uuid_t& app_uuid) {
732 UUID uuid(app_uuid);
733
734 VLOG(1) << __func__ << " - UUID: " << uuid.ToString();
735 lock_guard<mutex> lock(pending_calls_lock_);
736
737 auto iter = pending_calls_.find(uuid);
738 if (iter == pending_calls_.end()) {
739 VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString();
740 return;
741 }
742
743 // No need to construct a client if the call wasn't successful.
744 std::unique_ptr<LowEnergyClient> client;
745 BLEStatus result = BLE_STATUS_FAILURE;
746 if (status == BT_STATUS_SUCCESS) {
Jakub Pawlowski60b0e8f2016-01-12 13:51:35 -0800747 client.reset(new LowEnergyClient(adapter_, uuid, client_id));
Arman Uguray12338402015-09-16 18:00:05 -0700748
749 // Use the unsafe variant to register this as an observer, since
750 // LowEnergyClient instances only get created by LowEnergyClientCallback
751 // from inside this GATT client observer event, which would otherwise cause
752 // a deadlock.
753 gatt_iface->AddClientObserverUnsafe(client.get());
754
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700755 result = BLE_STATUS_SUCCESS;
756 }
757
Arman Uguray08f80eb2015-09-21 11:17:07 -0700758 // Notify the result via the result callback.
Arman Ugurayc2fc0f22015-09-03 15:09:41 -0700759 iter->second(result, uuid, std::move(client));
760
761 pending_calls_.erase(iter);
762}
763
764} // namespace bluetooth