1 //
2 // Copyright 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/adapter.h"
18
19 #include <base/logging.h>
20 #include <base/observer_list.h>
21
22 #include <atomic>
23 #include <mutex>
24 #include <string>
25 #include <unordered_set>
26
27 #include "abstract_observer_list.h"
28 #include "notreached.h"
29 #include "service/a2dp_sink.h"
30 #include "service/a2dp_source.h"
31 #include "service/avrcp_control.h"
32 #include "service/avrcp_target.h"
33 #include "service/common/bluetooth/util/atomic_string.h"
34 #include "service/gatt_client.h"
35 #include "service/gatt_server.h"
36 #include "service/hal/bluetooth_interface.h"
37 #include "service/logging_helpers.h"
38 #include "service/low_energy_advertiser.h"
39 #include "service/low_energy_client.h"
40 #include "service/low_energy_scanner.h"
41 #include "types/raw_address.h"
42
43 using std::lock_guard;
44 using std::mutex;
45
46 namespace bluetooth {
47
48 namespace {
49
ParseRemoteDeviceProps(int num_properties,bt_property_t * properties)50 RemoteDeviceProps ParseRemoteDeviceProps(int num_properties,
51 bt_property_t* properties) {
52 std::string name;
53 std::string address;
54 std::vector<Uuid> service_uuids;
55 int32_t device_class = 0;
56 int32_t device_type = 0;
57 int32_t rssi = 0;
58
59 for (int i = 0; i < num_properties; ++i) {
60 bt_property_t* property = properties + i;
61 switch (property->type) {
62 case BT_PROPERTY_BDNAME: {
63 if (property->len < 0) {
64 NOTREACHED() << "Invalid length for BT_PROPERTY_BDNAME";
65 break;
66 }
67 bt_bdname_t* hal_name = reinterpret_cast<bt_bdname_t*>(property->val);
68 name = reinterpret_cast<char*>(hal_name->name);
69 break;
70 }
71 case BT_PROPERTY_BDADDR: {
72 if (property->len != sizeof(RawAddress)) {
73 NOTREACHED() << "Invalid length for BT_PROPERTY_BDADDR";
74 break;
75 }
76 address = BtAddrString(reinterpret_cast<RawAddress*>(property->val));
77 break;
78 }
79 case BT_PROPERTY_UUIDS: {
80 if (property->len < 0) {
81 NOTREACHED() << "Negative length on BT_PROPERTY_UUIDS:";
82 break;
83 }
84 if (property->len % sizeof(Uuid) != 0) {
85 NOTREACHED() << "Trailing bytes on BT_PROPERTY_UUIDS:";
86 }
87 auto uuids = static_cast<const Uuid*>(property->val);
88
89 for (size_t i = 0; i < property->len / sizeof(Uuid); ++i) {
90 service_uuids.push_back(uuids[i]);
91 }
92 break;
93 }
94 case BT_PROPERTY_CLASS_OF_DEVICE: {
95 if (property->len != sizeof(int32_t)) {
96 NOTREACHED() << "Invalid length for BT_PROPERTY_CLASS_OF_DEVICE";
97 break;
98 }
99 device_class = *reinterpret_cast<const int32_t*>(property->val);
100 break;
101 }
102 case BT_PROPERTY_TYPE_OF_DEVICE: {
103 if (property->len != sizeof(int32_t)) {
104 NOTREACHED() << "Invalid length for BT_PROPERTY_TYPE_OF_DEVICE";
105 break;
106 }
107 device_type = *reinterpret_cast<const int32_t*>(property->val);
108 break;
109 }
110 case BT_PROPERTY_REMOTE_RSSI: {
111 if (property->len != sizeof(int8_t)) {
112 NOTREACHED() << "Invalid length for BT_PROPERTY_REMOTE_RSSI";
113 break;
114 }
115 rssi = *reinterpret_cast<const int8_t*>(property->val);
116 break;
117 }
118 default:
119 VLOG(1) << "Unhandled adapter property: "
120 << BtPropertyText(property->type);
121 break;
122 }
123 }
124
125 return RemoteDeviceProps(name, address, service_uuids, device_class,
126 device_type, rssi);
127 }
128
129 } // namespace
130
131 // static
132 const char Adapter::kDefaultAddress[] = "00:00:00:00:00:00";
133 // static
134 const char Adapter::kDefaultName[] = "not-initialized";
135
136 // TODO(armansito): The following constants come straight from
137 // packages/apps/Bluetooth/src/c/a/b/btservice/AdapterService.java. It would be
138 // nice to know if there were a way to obtain these values from the stack
139 // instead of hardcoding them here.
140
141 // The minimum number of advertising instances required for multi-advertisement
142 // support.
143 const int kMinAdvInstancesForMultiAdv = 5;
144
145 // Used when determining if offloaded scan filtering is supported.
146 const int kMinOffloadedFilters = 10;
147
148 // Used when determining if offloaded scan batching is supported.
149 const int kMinOffloadedScanStorageBytes = 1024;
150
OnAdapterStateChanged(Adapter * adapter,AdapterState prev_state,AdapterState new_state)151 void Adapter::Observer::OnAdapterStateChanged(Adapter* adapter,
152 AdapterState prev_state,
153 AdapterState new_state) {
154 // Default implementation does nothing
155 }
156
OnDeviceConnectionStateChanged(Adapter * adapter,const std::string & device_address,bool connected)157 void Adapter::Observer::OnDeviceConnectionStateChanged(
158 Adapter* adapter, const std::string& device_address, bool connected) {
159 // Default implementation does nothing
160 }
161
OnScanEnableChanged(Adapter * adapter,bool scan_enabled)162 void Adapter::Observer::OnScanEnableChanged(Adapter* adapter,
163 bool scan_enabled) {
164 // Default implementation does nothing
165 }
166
OnSspRequest(Adapter * adapter,const std::string & device_address,const std::string & device_name,int cod,int pairing_variant,int pass_key)167 void Adapter::Observer::OnSspRequest(Adapter* adapter,
168 const std::string& device_address,
169 const std::string& device_name, int cod,
170 int pairing_variant, int pass_key) {
171 // Default implementation does nothing
172 }
173
OnBondStateChanged(Adapter * adapter,int status,const std::string & device_address,int state)174 void Adapter::Observer::OnBondStateChanged(Adapter* adapter, int status,
175 const std::string& device_address,
176 int state) {
177 // Default implementation does nothing
178 }
179
OnGetBondedDevices(Adapter * adapter,int status,const std::vector<std::string> & bonded_devices)180 void Adapter::Observer::OnGetBondedDevices(
181 Adapter* adapter, int status,
182 const std::vector<std::string>& bonded_devices) {
183 // Default implementation does nothing
184 }
185
OnGetRemoteDeviceProperties(Adapter * adapter,int status,const std::string & device_address,const RemoteDeviceProps & properties)186 void Adapter::Observer::OnGetRemoteDeviceProperties(
187 Adapter* adapter, int status, const std::string& device_address,
188 const RemoteDeviceProps& properties) {
189 // Default implementation does nothing
190 }
191
OnDeviceFound(Adapter * adapter,const RemoteDeviceProps & properties)192 void Adapter::Observer::OnDeviceFound(Adapter* adapter,
193 const RemoteDeviceProps& properties) {
194 // Default implementation does nothing
195 }
196
197 // The real Adapter implementation used in production.
198 class AdapterImpl : public Adapter, public hal::BluetoothInterface::Observer {
199 public:
AdapterImpl()200 AdapterImpl()
201 : state_(ADAPTER_STATE_OFF),
202 address_(kDefaultAddress),
203 name_(kDefaultName) {
204 memset(&local_le_features_, 0, sizeof(local_le_features_));
205 hal::BluetoothInterface::Get()->AddObserver(this);
206 a2dp_sink_factory_.reset(new A2dpSinkFactory);
207 a2dp_source_factory_.reset(new A2dpSourceFactory);
208 avrcp_control_factory_.reset(new AvrcpControlFactory);
209 avrcp_target_factory_.reset(new AvrcpTargetFactory);
210 ble_client_factory_.reset(new LowEnergyClientFactory(*this));
211 ble_advertiser_factory_.reset(new LowEnergyAdvertiserFactory());
212 ble_scanner_factory_.reset(new LowEnergyScannerFactory(*this));
213 gatt_client_factory_.reset(new GattClientFactory());
214 gatt_server_factory_.reset(new GattServerFactory());
215 hal::BluetoothInterface::Get()->GetHALInterface()->get_adapter_properties();
216 }
217
218 AdapterImpl(const AdapterImpl&) = delete;
219 AdapterImpl& operator=(const AdapterImpl&) = delete;
220
~AdapterImpl()221 ~AdapterImpl() override {
222 hal::BluetoothInterface::Get()->RemoveObserver(this);
223 }
224
AddObserver(Adapter::Observer * observer)225 void AddObserver(Adapter::Observer* observer) override {
226 lock_guard<mutex> lock(observers_lock_);
227 observers_.AddObserver(observer);
228 }
229
RemoveObserver(Adapter::Observer * observer)230 void RemoveObserver(Adapter::Observer* observer) override {
231 lock_guard<mutex> lock(observers_lock_);
232 observers_.RemoveObserver(observer);
233 }
234
GetState() const235 AdapterState GetState() const override { return state_.load(); }
236
IsEnabled() const237 bool IsEnabled() const override { return state_.load() == ADAPTER_STATE_ON; }
238
Enable()239 bool Enable() override {
240 AdapterState current_state = GetState();
241 if (current_state != ADAPTER_STATE_OFF) {
242 LOG(INFO) << "Adapter not disabled - state: "
243 << AdapterStateToString(current_state);
244 return false;
245 }
246
247 // Set the state before calling enable() as there might be a race between
248 // here and the AdapterStateChangedCallback.
249 state_ = ADAPTER_STATE_TURNING_ON;
250 NotifyAdapterStateChanged(current_state, state_);
251
252 int status = hal::BluetoothInterface::Get()->GetHALInterface()->enable();
253 if (status != BT_STATUS_SUCCESS) {
254 LOG(ERROR) << "Failed to enable Bluetooth - status: "
255 << BtStatusText((const bt_status_t)status);
256 state_ = ADAPTER_STATE_OFF;
257 NotifyAdapterStateChanged(ADAPTER_STATE_TURNING_ON, state_);
258 return false;
259 }
260
261 return true;
262 }
263
Disable()264 bool Disable() override {
265 if (!IsEnabled()) {
266 LOG(INFO) << "Adapter is not enabled";
267 return false;
268 }
269
270 AdapterState current_state = GetState();
271
272 // Set the state before calling enable() as there might be a race between
273 // here and the AdapterStateChangedCallback.
274 state_ = ADAPTER_STATE_TURNING_OFF;
275 NotifyAdapterStateChanged(current_state, state_);
276
277 int status = hal::BluetoothInterface::Get()->GetHALInterface()->disable();
278 if (status != BT_STATUS_SUCCESS) {
279 LOG(ERROR) << "Failed to disable Bluetooth - status: "
280 << BtStatusText((const bt_status_t)status);
281 state_ = current_state;
282 NotifyAdapterStateChanged(ADAPTER_STATE_TURNING_OFF, state_);
283 return false;
284 }
285
286 return true;
287 }
288
GetName() const289 std::string GetName() const override { return name_.Get(); }
290
SetName(const std::string & name)291 bool SetName(const std::string& name) override {
292 bt_bdname_t hal_name;
293 size_t max_name_len = sizeof(hal_name.name);
294
295 // Include the \0 byte in size measurement.
296 if (name.length() >= max_name_len) {
297 LOG(ERROR) << "Given name \"" << name << "\" is larger than maximum"
298 << " allowed size: " << max_name_len;
299 return false;
300 }
301
302 strncpy(reinterpret_cast<char*>(hal_name.name), name.c_str(),
303 name.length() + 1);
304
305 VLOG(1) << "Setting adapter name: " << name;
306
307 if (!SetAdapterProperty(BT_PROPERTY_BDNAME, &hal_name, sizeof(hal_name))) {
308 LOG(ERROR) << "Failed to set adapter name: " << name;
309 return false;
310 }
311
312 return true;
313 }
314
GetAddress() const315 std::string GetAddress() const override { return address_.Get(); }
316
SetScanMode(int scan_mode)317 bool SetScanMode(int scan_mode) override {
318 switch (scan_mode) {
319 case BT_SCAN_MODE_NONE:
320 case BT_SCAN_MODE_CONNECTABLE:
321 case BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE:
322 break;
323 default:
324 LOG(ERROR) << "Unknown scan mode: " << scan_mode;
325 return false;
326 }
327
328 auto bd_scanmode = static_cast<bt_scan_mode_t>(scan_mode);
329
330 if (!SetAdapterProperty(BT_PROPERTY_ADAPTER_SCAN_MODE, &bd_scanmode,
331 sizeof(bd_scanmode))) {
332 LOG(ERROR) << "Failed to set scan mode to : " << scan_mode;
333 return false;
334 }
335
336 return true;
337 }
338
SetScanEnable(bool scan_enable)339 bool SetScanEnable(bool scan_enable) override {
340 if (scan_enable) {
341 int status =
342 hal::BluetoothInterface::Get()->GetHALInterface()->start_discovery();
343 if (status != BT_STATUS_SUCCESS) {
344 LOG(ERROR) << "Failed to enable scanning";
345 return false;
346 }
347 } else {
348 int status =
349 hal::BluetoothInterface::Get()->GetHALInterface()->cancel_discovery();
350 if (status != BT_STATUS_SUCCESS) {
351 LOG(ERROR) << "Failed to disable scanning";
352 return false;
353 }
354 }
355 return true;
356 }
357
SspReply(const std::string & device_address,int variant,bool accept,int32_t pass_key)358 bool SspReply(const std::string& device_address, int variant, bool accept,
359 int32_t pass_key) override {
360 RawAddress addr;
361 if (!RawAddress::FromString(device_address, addr)) {
362 LOG(ERROR) << "Invalid device address given: " << device_address;
363 return false;
364 }
365
366 int status = hal::BluetoothInterface::Get()->GetHALInterface()->ssp_reply(
367 &addr, static_cast<bt_ssp_variant_t>(variant), accept, pass_key);
368 if (status != BT_STATUS_SUCCESS) {
369 LOG(ERROR) << "Failed to send SSP response - status: "
370 << BtStatusText((const bt_status_t)status);
371 return false;
372 }
373
374 return true;
375 }
376
CreateBond(const std::string & device_address,int transport)377 bool CreateBond(const std::string& device_address, int transport) override {
378 RawAddress addr;
379 if (!RawAddress::FromString(device_address, addr)) {
380 LOG(ERROR) << "Invalid device address given: " << device_address;
381 return false;
382 }
383
384 int status = hal::BluetoothInterface::Get()->GetHALInterface()->create_bond(
385 &addr, transport);
386 if (status != BT_STATUS_SUCCESS) {
387 LOG(ERROR) << "Failed to create bond - status: "
388 << BtStatusText((const bt_status_t)status);
389 return false;
390 }
391
392 return true;
393 }
394
IsMultiAdvertisementSupported()395 bool IsMultiAdvertisementSupported() override {
396 lock_guard<mutex> lock(local_le_features_lock_);
397 return local_le_features_.max_adv_instance >= kMinAdvInstancesForMultiAdv;
398 }
399
IsDeviceConnected(const std::string & device_address)400 bool IsDeviceConnected(const std::string& device_address) override {
401 lock_guard<mutex> lock(connected_devices_lock_);
402 return connected_devices_.find(device_address) != connected_devices_.end();
403 }
404
GetTotalNumberOfTrackableAdvertisements()405 int GetTotalNumberOfTrackableAdvertisements() override {
406 lock_guard<mutex> lock(local_le_features_lock_);
407 return local_le_features_.total_trackable_advertisers;
408 }
409
IsOffloadedFilteringSupported()410 bool IsOffloadedFilteringSupported() override {
411 lock_guard<mutex> lock(local_le_features_lock_);
412 return local_le_features_.max_adv_filter_supported >= kMinOffloadedFilters;
413 }
414
IsOffloadedScanBatchingSupported()415 bool IsOffloadedScanBatchingSupported() override {
416 lock_guard<mutex> lock(local_le_features_lock_);
417 return local_le_features_.scan_result_storage_size >=
418 kMinOffloadedScanStorageBytes;
419 }
420
GetBondedDevices()421 bool GetBondedDevices() override {
422 int status =
423 hal::BluetoothInterface::Get()->GetHALInterface()->get_adapter_property(
424 BT_PROPERTY_ADAPTER_BONDED_DEVICES);
425 if (status != BT_STATUS_SUCCESS) {
426 LOG(ERROR) << "Failed to get bonded devices. Status: "
427 << BtStatusText(static_cast<bt_status_t>(status));
428 return false;
429 }
430
431 return true;
432 }
433
RemoveBond(const std::string & device_address)434 bool RemoveBond(const std::string& device_address) override {
435 RawAddress addr;
436 if (!RawAddress::FromString(device_address, addr)) {
437 LOG(ERROR) << "Invalid device address given: " << device_address;
438 return false;
439 }
440
441 int status =
442 hal::BluetoothInterface::Get()->GetHALInterface()->remove_bond(&addr);
443 if (status != BT_STATUS_SUCCESS) {
444 LOG(ERROR) << "Failed to send remove bond - status: "
445 << BtStatusText(static_cast<bt_status_t>(status));
446 return false;
447 }
448
449 return true;
450 }
451
GetRemoteDeviceProperties(const std::string & device_address)452 bool GetRemoteDeviceProperties(const std::string& device_address) override {
453 RawAddress addr;
454 if (!RawAddress::FromString(device_address, addr)) {
455 LOG(ERROR) << "Invalid device address given: " << device_address;
456 return false;
457 }
458
459 int status = hal::BluetoothInterface::Get()
460 ->GetHALInterface()
461 ->get_remote_device_properties(&addr);
462 if (status != BT_STATUS_SUCCESS) {
463 LOG(ERROR) << "Failed to send GetRemoteDeviceProperties - status: "
464 << BtStatusText((const bt_status_t)status);
465 return false;
466 }
467
468 return true;
469 }
470
GetA2dpSinkFactory() const471 A2dpSinkFactory* GetA2dpSinkFactory() const override {
472 return a2dp_sink_factory_.get();
473 }
474
GetA2dpSourceFactory() const475 A2dpSourceFactory* GetA2dpSourceFactory() const override {
476 return a2dp_source_factory_.get();
477 }
478
GetAvrcpControlFactory() const479 AvrcpControlFactory* GetAvrcpControlFactory() const override {
480 return avrcp_control_factory_.get();
481 }
482
GetAvrcpTargetFactory() const483 AvrcpTargetFactory* GetAvrcpTargetFactory() const override {
484 return avrcp_target_factory_.get();
485 }
486
GetLowEnergyClientFactory() const487 LowEnergyClientFactory* GetLowEnergyClientFactory() const override {
488 return ble_client_factory_.get();
489 }
490
GetLeAdvertiserFactory() const491 LowEnergyAdvertiserFactory* GetLeAdvertiserFactory() const override {
492 return ble_advertiser_factory_.get();
493 }
494
GetLeScannerFactory() const495 LowEnergyScannerFactory* GetLeScannerFactory() const override {
496 return ble_scanner_factory_.get();
497 }
498
GetGattClientFactory() const499 GattClientFactory* GetGattClientFactory() const override {
500 return gatt_client_factory_.get();
501 }
502
GetGattServerFactory() const503 GattServerFactory* GetGattServerFactory() const override {
504 return gatt_server_factory_.get();
505 }
506
507 // hal::BluetoothInterface::Observer overrides.
AdapterStateChangedCallback(bt_state_t state)508 void AdapterStateChangedCallback(bt_state_t state) override {
509 LOG(INFO) << "Adapter state changed: " << BtStateText(state);
510
511 AdapterState prev_state = GetState();
512
513 switch (state) {
514 case BT_STATE_OFF:
515 state_ = ADAPTER_STATE_OFF;
516 break;
517
518 case BT_STATE_ON:
519 state_ = ADAPTER_STATE_ON;
520 break;
521
522 default:
523 NOTREACHED();
524 }
525
526 NotifyAdapterStateChanged(prev_state, GetState());
527 }
528
AdapterPropertiesCallback(bt_status_t status,int num_properties,bt_property_t * properties)529 void AdapterPropertiesCallback(bt_status_t status, int num_properties,
530 bt_property_t* properties) override {
531 LOG(INFO) << "Adapter properties changed";
532
533 if (status != BT_STATUS_SUCCESS) {
534 LOG(ERROR) << "status: " << BtStatusText(status);
535
536 for (int i = 0; i < num_properties; ++i) {
537 bt_property_t* property = properties + i;
538 if (property->type == BT_PROPERTY_ADAPTER_BONDED_DEVICES) {
539 lock_guard<mutex> lock(observers_lock_);
540 for (auto& observer : observers_) {
541 observer.OnGetBondedDevices(this, status, {});
542 }
543 }
544 }
545 return;
546 }
547
548 for (int i = 0; i < num_properties; i++) {
549 bt_property_t* property = properties + i;
550 switch (property->type) {
551 case BT_PROPERTY_BDADDR: {
552 std::string address =
553 BtAddrString(reinterpret_cast<RawAddress*>(property->val));
554 LOG(INFO) << "Adapter address changed: " << address;
555 address_.Set(address);
556 break;
557 }
558 case BT_PROPERTY_BDNAME: {
559 bt_bdname_t* hal_name = reinterpret_cast<bt_bdname_t*>(property->val);
560 if (hal_name) {
561 std::string name = reinterpret_cast<char*>(hal_name->name);
562 LOG(INFO) << "Adapter name changed: " << name;
563 name_.Set(name);
564 }
565 break;
566 }
567 case BT_PROPERTY_LOCAL_LE_FEATURES: {
568 lock_guard<mutex> lock(local_le_features_lock_);
569 if (property->len != sizeof(bt_local_le_features_t)) {
570 LOG(WARNING) << "Malformed value received for property: "
571 << "BT_PROPERTY_LOCAL_LE_FEATURES";
572 break;
573 }
574 bt_local_le_features_t* features =
575 reinterpret_cast<bt_local_le_features_t*>(property->val);
576 memcpy(&local_le_features_, features, sizeof(*features));
577 LOG(INFO) << "Supported LE features updated";
578 break;
579 }
580 case BT_PROPERTY_ADAPTER_BONDED_DEVICES: {
581 if (property->len < 0) {
582 NOTREACHED() << "Negative property length";
583 break;
584 }
585 auto addrs = reinterpret_cast<const RawAddress*>(property->val);
586 if (property->len % sizeof(addrs[0]) != 0) {
587 LOG(ERROR) << "Invalid property length: " << property->len;
588 // TODO(bcf): Seems to be a bug where we hit this somewhat
589 // frequently.
590 break;
591 }
592 std::vector<std::string> str_addrs;
593
594 for (size_t i = 0; i < property->len / sizeof(addrs[0]); ++i)
595 str_addrs.push_back(BtAddrString(addrs + i));
596
597 lock_guard<mutex> lock(observers_lock_);
598 for (auto& observer : observers_) {
599 observer.OnGetBondedDevices(this, status, str_addrs);
600 }
601 break;
602 }
603 default:
604 VLOG(1) << "Unhandled adapter property: "
605 << BtPropertyText(property->type);
606 break;
607 }
608
609 // TODO(armansito): notify others of the updated properties
610 }
611 }
612
RemoteDevicePropertiesCallback(bt_status_t status,RawAddress * remote_bdaddr,int num_properties,bt_property_t * properties)613 void RemoteDevicePropertiesCallback(bt_status_t status,
614 RawAddress* remote_bdaddr,
615 int num_properties,
616 bt_property_t* properties) override {
617 std::string device_address = BtAddrString(remote_bdaddr);
618 if (status != BT_STATUS_SUCCESS) {
619 lock_guard<mutex> lock(observers_lock_);
620 for (auto& observer : observers_) {
621 observer.OnGetRemoteDeviceProperties(this, status, device_address,
622 RemoteDeviceProps());
623 }
624 return;
625 }
626
627 RemoteDeviceProps props =
628 ParseRemoteDeviceProps(num_properties, properties);
629
630 std::string address = BtAddrString(remote_bdaddr);
631 props.set_address(address);
632
633 lock_guard<mutex> lock(observers_lock_);
634 for (auto& observer : observers_) {
635 observer.OnGetRemoteDeviceProperties(this, status, device_address, props);
636 }
637 }
638
DeviceFoundCallback(int num_properties,bt_property_t * properties)639 void DeviceFoundCallback(int num_properties,
640 bt_property_t* properties) override {
641 RemoteDeviceProps props =
642 ParseRemoteDeviceProps(num_properties, properties);
643
644 lock_guard<mutex> lock(observers_lock_);
645 for (auto& observer : observers_) {
646 observer.OnDeviceFound(this, props);
647 }
648 }
649
DiscoveryStateChangedCallback(bt_discovery_state_t state)650 void DiscoveryStateChangedCallback(bt_discovery_state_t state) override {
651 bool enabled = false;
652 switch (state) {
653 case BT_DISCOVERY_STOPPED:
654 enabled = false;
655 break;
656 case BT_DISCOVERY_STARTED:
657 enabled = true;
658 break;
659 default:
660 NOTREACHED();
661 }
662
663 for (auto& observer : observers_) {
664 observer.OnScanEnableChanged(this, enabled);
665 }
666 }
667
SSPRequestCallback(RawAddress * remote_bdaddr,bt_bdname_t * bd_name,uint32_t cod,bt_ssp_variant_t pairing_variant,uint32_t pass_key)668 void SSPRequestCallback(RawAddress* remote_bdaddr, bt_bdname_t* bd_name,
669 uint32_t cod, bt_ssp_variant_t pairing_variant,
670 uint32_t pass_key) override {
671 std::string device_address = BtAddrString(remote_bdaddr);
672 std::string name = reinterpret_cast<char*>(bd_name->name);
673
674 lock_guard<mutex> lock(observers_lock_);
675 for (auto& observer : observers_) {
676 observer.OnSspRequest(this, device_address, name, cod, pairing_variant,
677 pass_key);
678 }
679 }
680
BondStateChangedCallback(bt_status_t status,RawAddress * remote_bdaddr,bt_bond_state_t state,int fail_reason)681 void BondStateChangedCallback(bt_status_t status, RawAddress* remote_bdaddr,
682 bt_bond_state_t state,
683 int fail_reason) override {
684 std::string device_address = BtAddrString(remote_bdaddr);
685
686 lock_guard<mutex> lock(observers_lock_);
687 for (auto& observer : observers_) {
688 observer.OnBondStateChanged(this, status, device_address, state);
689 }
690 }
691
AclStateChangedCallback(bt_status_t status,const RawAddress & remote_bdaddr,bt_acl_state_t state,int transport_link_type,bt_hci_error_code_t hci_reason)692 void AclStateChangedCallback(bt_status_t status,
693 const RawAddress& remote_bdaddr,
694 bt_acl_state_t state, int transport_link_type,
695 bt_hci_error_code_t hci_reason) override {
696 std::string device_address = BtAddrString(&remote_bdaddr);
697 bool connected = (state == BT_ACL_STATE_CONNECTED);
698 LOG(INFO) << "ACL state changed: " << device_address
699 << " - connected: " << (connected ? "true" : "false");
700
701 // If this is reported with an error status, I suppose the best thing we can
702 // do is to log it and ignore the event.
703 if (status != BT_STATUS_SUCCESS) {
704 LOG(ERROR) << "status: " << BtStatusText(status);
705 return;
706 }
707
708 // Introduce a scope to manage |connected_devices_lock_| with RAII.
709 {
710 lock_guard<mutex> lock(connected_devices_lock_);
711 if (connected)
712 connected_devices_.insert(device_address);
713 else
714 connected_devices_.erase(device_address);
715 }
716
717 lock_guard<mutex> lock(observers_lock_);
718 for (auto& observer : observers_) {
719 observer.OnDeviceConnectionStateChanged(this, device_address, connected);
720 }
721 }
722
723 // Sends a request to set the given HAL adapter property type and value.
SetAdapterProperty(bt_property_type_t type,void * value,int length)724 bool SetAdapterProperty(bt_property_type_t type, void* value, int length) {
725 CHECK(length > 0);
726 CHECK(value);
727
728 bt_property_t property;
729 property.len = length;
730 property.val = value;
731 property.type = type;
732
733 int status =
734 hal::BluetoothInterface::Get()->GetHALInterface()->set_adapter_property(
735 &property);
736 if (status != BT_STATUS_SUCCESS) {
737 VLOG(1) << "Failed to set property";
738 return false;
739 }
740
741 return true;
742 }
743
744 // Helper for invoking the AdapterStateChanged observer method.
NotifyAdapterStateChanged(AdapterState prev_state,AdapterState new_state)745 void NotifyAdapterStateChanged(AdapterState prev_state,
746 AdapterState new_state) {
747 if (prev_state == new_state) return;
748
749 lock_guard<mutex> lock(observers_lock_);
750 for (auto& observer : observers_) {
751 observer.OnAdapterStateChanged(this, prev_state, new_state);
752 }
753 }
754
755 private:
756 // The current adapter state.
757 std::atomic<AdapterState> state_;
758
759 // The Bluetooth device address of the local adapter in string from
760 // (i.e.. XX:XX:XX:XX:XX:XX)
761 util::AtomicString address_;
762
763 // The current local adapter name.
764 util::AtomicString name_;
765
766 // The current set of supported LE features as obtained from the stack. The
767 // values here are all initially set to 0 and updated when the corresponding
768 // adapter property has been received from the stack.
769 std::mutex local_le_features_lock_;
770 bt_local_le_features_t local_le_features_;
771
772 // List of observers that are interested in notifications from us.
773 std::mutex observers_lock_;
774 btbase::AbstractObserverList<Adapter::Observer> observers_;
775
776 // List of devices addresses that are currently connected.
777 std::mutex connected_devices_lock_;
778 std::unordered_set<std::string> connected_devices_;
779
780 // Factory used to create per-app A2dpSink instances.
781 std::unique_ptr<A2dpSinkFactory> a2dp_sink_factory_;
782
783 // Factory used to create per-app A2dpSource instances.
784 std::unique_ptr<A2dpSourceFactory> a2dp_source_factory_;
785
786 // Factory used to create per-app AvrcpControl instances.
787 std::unique_ptr<AvrcpControlFactory> avrcp_control_factory_;
788
789 // Factory used to create per-app AvrcpTarget instances.
790 std::unique_ptr<AvrcpTargetFactory> avrcp_target_factory_;
791
792 // Factory used to create per-app LowEnergyClient instances.
793 std::unique_ptr<LowEnergyClientFactory> ble_client_factory_;
794
795 // Factory used to create per-app LeAdvertiser instances.
796 std::unique_ptr<LowEnergyAdvertiserFactory> ble_advertiser_factory_;
797
798 // Factory used to create per-app LeScanner instances.
799 std::unique_ptr<LowEnergyScannerFactory> ble_scanner_factory_;
800
801 // Factory used to create per-app GattClient instances.
802 std::unique_ptr<GattClientFactory> gatt_client_factory_;
803
804 // Factory used to create per-app GattServer instances.
805 std::unique_ptr<GattServerFactory> gatt_server_factory_;
806 };
807
808 // static
Create()809 std::unique_ptr<Adapter> Adapter::Create() {
810 return std::unique_ptr<Adapter>(new AdapterImpl());
811 }
812
813 } // namespace bluetooth
814