adapter.cc 26 KB

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