bluetooth_device_winrt.cc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "device/bluetooth/bluetooth_device_winrt.h"
  5. #include <windows.devices.enumeration.h>
  6. #include <windows.foundation.h>
  7. #include <utility>
  8. #include "base/bind.h"
  9. #include "base/callback_helpers.h"
  10. #include "base/logging.h"
  11. #include "base/strings/string_piece.h"
  12. #include "base/strings/stringprintf.h"
  13. #include "base/win/core_winrt_util.h"
  14. #include "base/win/post_async_results.h"
  15. #include "base/win/scoped_hstring.h"
  16. #include "components/device_event_log/device_event_log.h"
  17. #include "device/bluetooth/bluetooth_adapter_winrt.h"
  18. #include "device/bluetooth/bluetooth_gatt_discoverer_winrt.h"
  19. #include "device/bluetooth/bluetooth_pairing_winrt.h"
  20. #include "device/bluetooth/bluetooth_remote_gatt_service_winrt.h"
  21. #include "device/bluetooth/event_utils_winrt.h"
  22. #include "device/bluetooth/public/cpp/bluetooth_address.h"
  23. #include "device/bluetooth/public/cpp/bluetooth_uuid.h"
  24. namespace device {
  25. namespace {
  26. using ABI::Windows::Devices::Bluetooth::BluetoothConnectionStatus;
  27. using ABI::Windows::Devices::Bluetooth::BluetoothConnectionStatus_Connected;
  28. using ABI::Windows::Devices::Bluetooth::BluetoothError;
  29. using ABI::Windows::Devices::Bluetooth::BluetoothError_Success;
  30. using ABI::Windows::Devices::Bluetooth::BluetoothLEDevice;
  31. using ABI::Windows::Devices::Bluetooth::IBluetoothDeviceId;
  32. using ABI::Windows::Devices::Bluetooth::IBluetoothDeviceIdStatics;
  33. using ABI::Windows::Devices::Bluetooth::IBluetoothLEDevice;
  34. using ABI::Windows::Devices::Bluetooth::IBluetoothLEDevice2;
  35. using ABI::Windows::Devices::Bluetooth::IBluetoothLEDevice4;
  36. using ABI::Windows::Devices::Bluetooth::IBluetoothLEDeviceStatics;
  37. using ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession;
  38. using ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::
  39. GattSessionStatus;
  40. using ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::
  41. GattSessionStatus_Active;
  42. using ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::
  43. GattSessionStatus_Closed;
  44. using ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::IGattSession;
  45. using ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::
  46. IGattSessionStatics;
  47. using ABI::Windows::Devices::Enumeration::IDeviceInformation;
  48. using ABI::Windows::Devices::Enumeration::IDeviceInformation2;
  49. using ABI::Windows::Devices::Enumeration::IDeviceInformationCustomPairing;
  50. using ABI::Windows::Devices::Enumeration::IDeviceInformationPairing;
  51. using ABI::Windows::Devices::Enumeration::IDeviceInformationPairing2;
  52. using ABI::Windows::Foundation::IAsyncOperation;
  53. using ABI::Windows::Foundation::IClosable;
  54. using Microsoft::WRL::ComPtr;
  55. void PostTask(BluetoothPairingWinrt::ConnectCallback callback,
  56. absl::optional<BluetoothDevice::ConnectErrorCode> error_code) {
  57. base::ThreadTaskRunnerHandle::Get()->PostTask(
  58. FROM_HERE, base::BindOnce(std::move(callback), error_code));
  59. }
  60. ComPtr<IDeviceInformationPairing> GetDeviceInformationPairing(
  61. ComPtr<IBluetoothLEDevice> ble_device) {
  62. if (!ble_device) {
  63. BLUETOOTH_LOG(DEBUG) << "No BLE device instance present.";
  64. return nullptr;
  65. }
  66. ComPtr<IBluetoothLEDevice2> ble_device_2;
  67. HRESULT hr = ble_device.As(&ble_device_2);
  68. if (FAILED(hr)) {
  69. BLUETOOTH_LOG(DEBUG) << "Obtaining IBluetoothLEDevice2 failed: "
  70. << logging::SystemErrorCodeToString(hr);
  71. return nullptr;
  72. }
  73. ComPtr<IDeviceInformation> device_information;
  74. hr = ble_device_2->get_DeviceInformation(&device_information);
  75. if (FAILED(hr)) {
  76. BLUETOOTH_LOG(DEBUG) << "Getting Device Information failed: "
  77. << logging::SystemErrorCodeToString(hr);
  78. return nullptr;
  79. }
  80. ComPtr<IDeviceInformation2> device_information_2;
  81. hr = device_information.As(&device_information_2);
  82. if (FAILED(hr)) {
  83. BLUETOOTH_LOG(DEBUG) << "Obtaining IDeviceInformation2 failed: "
  84. << logging::SystemErrorCodeToString(hr);
  85. return nullptr;
  86. }
  87. ComPtr<IDeviceInformationPairing> pairing;
  88. hr = device_information_2->get_Pairing(&pairing);
  89. if (FAILED(hr)) {
  90. BLUETOOTH_LOG(DEBUG) << "DeviceInformation::get_Pairing() failed: "
  91. << logging::SystemErrorCodeToString(hr);
  92. return nullptr;
  93. }
  94. return pairing;
  95. }
  96. void CloseDevice(ComPtr<IBluetoothLEDevice> ble_device) {
  97. if (!ble_device)
  98. return;
  99. ComPtr<IClosable> closable;
  100. HRESULT hr = ble_device.As(&closable);
  101. if (FAILED(hr)) {
  102. BLUETOOTH_LOG(DEBUG) << "As IClosable failed: "
  103. << logging::SystemErrorCodeToString(hr);
  104. return;
  105. }
  106. hr = closable->Close();
  107. if (FAILED(hr)) {
  108. BLUETOOTH_LOG(DEBUG) << "IClosable::Close() failed: "
  109. << logging::SystemErrorCodeToString(hr);
  110. }
  111. }
  112. void CloseGattSession(ComPtr<IGattSession> gatt_session) {
  113. if (!gatt_session)
  114. return;
  115. ComPtr<IClosable> closable;
  116. HRESULT hr = gatt_session.As(&closable);
  117. if (FAILED(hr)) {
  118. BLUETOOTH_LOG(DEBUG) << "As IClosable failed: "
  119. << logging::SystemErrorCodeToString(hr);
  120. return;
  121. }
  122. hr = closable->Close();
  123. if (FAILED(hr)) {
  124. BLUETOOTH_LOG(DEBUG) << "IClosable::Close() failed: "
  125. << logging::SystemErrorCodeToString(hr);
  126. }
  127. }
  128. void RemoveConnectionStatusHandler(IBluetoothLEDevice* ble_device,
  129. EventRegistrationToken token) {
  130. HRESULT hr = ble_device->remove_ConnectionStatusChanged(token);
  131. if (FAILED(hr)) {
  132. BLUETOOTH_LOG(DEBUG) << "Removing ConnectionStatus Handler failed: "
  133. << logging::SystemErrorCodeToString(hr);
  134. }
  135. }
  136. void RemoveGattSessionStatusHandler(IGattSession* gatt_session,
  137. EventRegistrationToken token) {
  138. HRESULT hr = gatt_session->remove_SessionStatusChanged(token);
  139. if (FAILED(hr)) {
  140. BLUETOOTH_LOG(DEBUG) << "Removing ConnectionStatus Handler failed: "
  141. << logging::SystemErrorCodeToString(hr);
  142. }
  143. }
  144. void RemoveGattServicesChangedHandler(IBluetoothLEDevice* ble_device,
  145. EventRegistrationToken token) {
  146. HRESULT hr = ble_device->remove_GattServicesChanged(token);
  147. if (FAILED(hr)) {
  148. BLUETOOTH_LOG(DEBUG) << "Removing Gatt Services Changed Handler failed: "
  149. << logging::SystemErrorCodeToString(hr);
  150. }
  151. }
  152. void RemoveNameChangedHandler(IBluetoothLEDevice* ble_device,
  153. EventRegistrationToken token) {
  154. HRESULT hr = ble_device->remove_NameChanged(token);
  155. if (FAILED(hr)) {
  156. BLUETOOTH_LOG(DEBUG) << "Removing NameChanged Handler failed: "
  157. << logging::SystemErrorCodeToString(hr);
  158. }
  159. }
  160. } // namespace
  161. BluetoothDeviceWinrt::BluetoothDeviceWinrt(BluetoothAdapterWinrt* adapter,
  162. uint64_t raw_address)
  163. : BluetoothDevice(adapter),
  164. raw_address_(raw_address),
  165. address_(CanonicalizeAddress(raw_address)) {
  166. supports_service_specific_discovery_ = true;
  167. }
  168. BluetoothDeviceWinrt::~BluetoothDeviceWinrt() {
  169. CloseGattSession(gatt_session_);
  170. CloseDevice(ble_device_);
  171. ClearEventRegistrations();
  172. }
  173. uint32_t BluetoothDeviceWinrt::GetBluetoothClass() const {
  174. // No logging - called too frequenty.
  175. return 0;
  176. }
  177. std::string BluetoothDeviceWinrt::GetAddress() const {
  178. return address_;
  179. }
  180. BluetoothDevice::AddressType BluetoothDeviceWinrt::GetAddressType() const {
  181. NOTIMPLEMENTED();
  182. return ADDR_TYPE_UNKNOWN;
  183. }
  184. BluetoothDevice::VendorIDSource BluetoothDeviceWinrt::GetVendorIDSource()
  185. const {
  186. NOTIMPLEMENTED();
  187. return VendorIDSource();
  188. }
  189. uint16_t BluetoothDeviceWinrt::GetVendorID() const {
  190. NOTIMPLEMENTED();
  191. return 0;
  192. }
  193. uint16_t BluetoothDeviceWinrt::GetProductID() const {
  194. NOTIMPLEMENTED();
  195. return 0;
  196. }
  197. uint16_t BluetoothDeviceWinrt::GetDeviceID() const {
  198. NOTIMPLEMENTED();
  199. return 0;
  200. }
  201. uint16_t BluetoothDeviceWinrt::GetAppearance() const {
  202. // No logging - called too frequenty.
  203. return 0;
  204. }
  205. absl::optional<std::string> BluetoothDeviceWinrt::GetName() const {
  206. if (!ble_device_)
  207. return local_name_;
  208. HSTRING name;
  209. HRESULT hr = ble_device_->get_Name(&name);
  210. if (FAILED(hr)) {
  211. BLUETOOTH_LOG(DEBUG) << "Getting Name failed: "
  212. << logging::SystemErrorCodeToString(hr);
  213. return local_name_;
  214. }
  215. // Prefer returning |local_name_| over an empty string.
  216. if (!name)
  217. return local_name_;
  218. return base::win::ScopedHString(name).GetAsUTF8();
  219. }
  220. bool BluetoothDeviceWinrt::IsPaired() const {
  221. ComPtr<IDeviceInformationPairing> pairing =
  222. GetDeviceInformationPairing(ble_device_);
  223. if (!pairing) {
  224. BLUETOOTH_LOG(DEBUG) << "Failed to get DeviceInformationPairing.";
  225. return false;
  226. }
  227. boolean is_paired;
  228. HRESULT hr = pairing->get_IsPaired(&is_paired);
  229. if (FAILED(hr)) {
  230. BLUETOOTH_LOG(DEBUG) << "DeviceInformationPairing::get_IsPaired() failed: "
  231. << logging::SystemErrorCodeToString(hr);
  232. return false;
  233. }
  234. BLUETOOTH_LOG(DEBUG) << "BluetoothDeviceWinrt::IsPaired(): "
  235. << (is_paired ? "True" : "False");
  236. return is_paired;
  237. }
  238. bool BluetoothDeviceWinrt::IsConnected() const {
  239. return ble_device_ &&
  240. connection_status_ == BluetoothConnectionStatus_Connected;
  241. }
  242. bool BluetoothDeviceWinrt::IsGattConnected() const {
  243. if (!observe_gatt_session_status_change_events_)
  244. return IsConnected();
  245. return gatt_session_ && gatt_session_status_ == GattSessionStatus_Active;
  246. }
  247. bool BluetoothDeviceWinrt::IsConnectable() const {
  248. NOTIMPLEMENTED();
  249. return false;
  250. }
  251. bool BluetoothDeviceWinrt::IsConnecting() const {
  252. NOTIMPLEMENTED();
  253. return false;
  254. }
  255. bool BluetoothDeviceWinrt::ExpectingPinCode() const {
  256. return pairing_ && pairing_->ExpectingPinCode();
  257. }
  258. bool BluetoothDeviceWinrt::ExpectingPasskey() const {
  259. NOTIMPLEMENTED();
  260. return false;
  261. }
  262. bool BluetoothDeviceWinrt::ExpectingConfirmation() const {
  263. NOTIMPLEMENTED();
  264. return false;
  265. }
  266. void BluetoothDeviceWinrt::GetConnectionInfo(ConnectionInfoCallback callback) {
  267. NOTIMPLEMENTED();
  268. }
  269. void BluetoothDeviceWinrt::SetConnectionLatency(
  270. ConnectionLatency connection_latency,
  271. base::OnceClosure callback,
  272. ErrorCallback error_callback) {
  273. NOTIMPLEMENTED();
  274. }
  275. void BluetoothDeviceWinrt::Connect(PairingDelegate* pairing_delegate,
  276. ConnectCallback callback) {
  277. NOTIMPLEMENTED();
  278. }
  279. void BluetoothDeviceWinrt::Pair(PairingDelegate* pairing_delegate,
  280. ConnectCallback callback) {
  281. BLUETOOTH_LOG(DEBUG) << "BluetoothDeviceWinrt::Pair()";
  282. if (pairing_) {
  283. BLUETOOTH_LOG(DEBUG) << "Another Pair Operation is already in progress.";
  284. PostTask(std::move(callback), ERROR_INPROGRESS);
  285. return;
  286. }
  287. ComPtr<IDeviceInformationPairing> pairing =
  288. GetDeviceInformationPairing(ble_device_);
  289. if (!pairing) {
  290. BLUETOOTH_LOG(DEBUG) << "Failed to get DeviceInformationPairing.";
  291. PostTask(std::move(callback), ERROR_UNKNOWN);
  292. return;
  293. }
  294. ComPtr<IDeviceInformationPairing2> pairing_2;
  295. HRESULT hr = pairing.As(&pairing_2);
  296. if (FAILED(hr)) {
  297. BLUETOOTH_LOG(DEBUG) << "Obtaining IDeviceInformationPairing2 failed: "
  298. << logging::SystemErrorCodeToString(hr);
  299. PostTask(std::move(callback), ERROR_UNKNOWN);
  300. return;
  301. }
  302. ComPtr<IDeviceInformationCustomPairing> custom;
  303. hr = pairing_2->get_Custom(&custom);
  304. if (FAILED(hr)) {
  305. BLUETOOTH_LOG(DEBUG) << "DeviceInformationPairing::get_Custom() failed: "
  306. << logging::SystemErrorCodeToString(hr);
  307. PostTask(std::move(callback), ERROR_UNKNOWN);
  308. return;
  309. }
  310. // Wrap callback, so that it cleans up the pairing object when run.
  311. auto wrapped_callback = base::BindOnce(
  312. [](base::WeakPtr<BluetoothDeviceWinrt> device, ConnectCallback callback,
  313. absl::optional<ConnectErrorCode> error_code) {
  314. if (device)
  315. device->pairing_.reset();
  316. std::move(callback).Run(error_code);
  317. },
  318. weak_ptr_factory_.GetWeakPtr(), std::move(callback));
  319. pairing_ = std::make_unique<BluetoothPairingWinrt>(
  320. this, pairing_delegate, std::move(custom), std::move(wrapped_callback));
  321. pairing_->StartPairing();
  322. }
  323. void BluetoothDeviceWinrt::SetPinCode(const std::string& pincode) {
  324. if (pairing_)
  325. pairing_->SetPinCode(pincode);
  326. }
  327. void BluetoothDeviceWinrt::SetPasskey(uint32_t passkey) {
  328. NOTIMPLEMENTED();
  329. }
  330. void BluetoothDeviceWinrt::ConfirmPairing() {
  331. if (pairing_)
  332. pairing_->ConfirmPairing();
  333. }
  334. void BluetoothDeviceWinrt::RejectPairing() {
  335. if (pairing_)
  336. pairing_->RejectPairing();
  337. }
  338. void BluetoothDeviceWinrt::CancelPairing() {
  339. if (pairing_)
  340. pairing_->CancelPairing();
  341. }
  342. void BluetoothDeviceWinrt::Disconnect(base::OnceClosure callback,
  343. ErrorCallback error_callback) {
  344. NOTIMPLEMENTED();
  345. }
  346. void BluetoothDeviceWinrt::Forget(base::OnceClosure callback,
  347. ErrorCallback error_callback) {
  348. NOTIMPLEMENTED();
  349. }
  350. void BluetoothDeviceWinrt::ConnectToService(
  351. const BluetoothUUID& uuid,
  352. ConnectToServiceCallback callback,
  353. ConnectToServiceErrorCallback error_callback) {
  354. NOTIMPLEMENTED();
  355. }
  356. void BluetoothDeviceWinrt::ConnectToServiceInsecurely(
  357. const device::BluetoothUUID& uuid,
  358. ConnectToServiceCallback callback,
  359. ConnectToServiceErrorCallback error_callback) {
  360. NOTIMPLEMENTED();
  361. }
  362. // static
  363. std::string BluetoothDeviceWinrt::CanonicalizeAddress(uint64_t address) {
  364. std::string bluetooth_address =
  365. CanonicalizeBluetoothAddress(base::StringPrintf("%012llX", address));
  366. DCHECK(!bluetooth_address.empty());
  367. return bluetooth_address;
  368. }
  369. void BluetoothDeviceWinrt::UpdateLocalName(
  370. absl::optional<std::string> local_name) {
  371. if (!local_name)
  372. return;
  373. local_name_ = std::move(local_name);
  374. }
  375. void BluetoothDeviceWinrt::CreateGattConnectionImpl(
  376. absl::optional<BluetoothUUID> service_uuid) {
  377. ComPtr<IBluetoothLEDeviceStatics> device_statics;
  378. HRESULT hr = GetBluetoothLEDeviceStaticsActivationFactory(&device_statics);
  379. if (FAILED(hr)) {
  380. BLUETOOTH_LOG(DEBUG)
  381. << "GetBluetoothLEDeviceStaticsActivationFactory failed: "
  382. << logging::SystemErrorCodeToString(hr);
  383. NotifyGattConnectFailure();
  384. return;
  385. }
  386. // Note: Even though we might have obtained a BluetoothLEDevice instance in
  387. // the past, we need to request a new instance as the old device might have
  388. // been closed. See also
  389. // https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/gatt-client#connecting-to-the-device
  390. ComPtr<IAsyncOperation<BluetoothLEDevice*>> from_bluetooth_address_op;
  391. hr = device_statics->FromBluetoothAddressAsync(raw_address_,
  392. &from_bluetooth_address_op);
  393. if (FAILED(hr)) {
  394. BLUETOOTH_LOG(DEBUG)
  395. << "BluetoothLEDevice::FromBluetoothAddressAsync failed: "
  396. << logging::SystemErrorCodeToString(hr);
  397. NotifyGattConnectFailure();
  398. return;
  399. }
  400. hr = base::win::PostAsyncResults(
  401. std::move(from_bluetooth_address_op),
  402. base::BindOnce(
  403. &BluetoothDeviceWinrt::OnBluetoothLEDeviceFromBluetoothAddress,
  404. weak_ptr_factory_.GetWeakPtr()));
  405. if (FAILED(hr)) {
  406. BLUETOOTH_LOG(DEBUG) << "PostAsyncResults failed: "
  407. << logging::SystemErrorCodeToString(hr);
  408. NotifyGattConnectFailure();
  409. return;
  410. }
  411. target_uuid_ = std::move(service_uuid);
  412. pending_gatt_service_discovery_start_ = true;
  413. }
  414. void BluetoothDeviceWinrt::NotifyGattConnectFailure() {
  415. // Reset |pending_gatt_service_discovery_start_| so that
  416. // UpgradeToFullDiscovery() doesn't mistakenly believe GATT discovery is
  417. // imminent and therefore avoids starting one itself.
  418. pending_gatt_service_discovery_start_ = false;
  419. base::ThreadTaskRunnerHandle::Get()->PostTask(
  420. FROM_HERE, base::BindOnce(&BluetoothDeviceWinrt::DidConnectGatt,
  421. weak_ptr_factory_.GetWeakPtr(),
  422. ConnectErrorCode::ERROR_FAILED));
  423. }
  424. void BluetoothDeviceWinrt::UpgradeToFullDiscovery() {
  425. // |CreateGattConnectionImpl| has been called previously but having a specific
  426. // |target_uuid_| was too optimistic and now a complete enumeration of
  427. // services is needed.
  428. target_uuid_.reset();
  429. if (pending_gatt_service_discovery_start_) {
  430. // There is an imminent call to StartDiscovery(). Resetting |target_uuid_|
  431. // now will be sufficient to change the discovery that will be started.
  432. return;
  433. }
  434. DCHECK(ble_device_);
  435. DCHECK(!observe_gatt_session_status_change_events_ || IsGattConnected());
  436. // Restart discovery.
  437. StartGattDiscovery();
  438. }
  439. void BluetoothDeviceWinrt::DisconnectGatt() {
  440. // Closing the device and disposing of all references will trigger a Gatt
  441. // Disconnection after a short timeout. Since the Gatt Services store a
  442. // reference to |ble_device_| as well, we need to clear them to drop all
  443. // remaining references, so that the OS disconnects.
  444. // Reference:
  445. // - https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/gatt-client
  446. CloseGattSession(gatt_session_);
  447. CloseDevice(ble_device_);
  448. ClearGattServices();
  449. // Stop any pending Gatt Discovery sessions and report an error. This will
  450. // destroy |gatt_discoverer_| and release remaining references the discoverer
  451. // might have hold.
  452. if (gatt_discoverer_)
  453. OnGattDiscoveryComplete(false);
  454. }
  455. HRESULT BluetoothDeviceWinrt::GetBluetoothLEDeviceStaticsActivationFactory(
  456. IBluetoothLEDeviceStatics** statics) const {
  457. return base::win::GetActivationFactory<
  458. IBluetoothLEDeviceStatics,
  459. RuntimeClass_Windows_Devices_Bluetooth_BluetoothLEDevice>(statics);
  460. }
  461. HRESULT BluetoothDeviceWinrt::GetGattSessionStaticsActivationFactory(
  462. IGattSessionStatics** statics) const {
  463. return base::win::GetActivationFactory<
  464. IGattSessionStatics,
  465. RuntimeClass_Windows_Devices_Bluetooth_GenericAttributeProfile_GattSession>(
  466. statics);
  467. }
  468. void BluetoothDeviceWinrt::OnBluetoothLEDeviceFromBluetoothAddress(
  469. ComPtr<IBluetoothLEDevice> ble_device) {
  470. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  471. if (!ble_device) {
  472. BLUETOOTH_LOG(DEBUG) << "Getting Device From Bluetooth Address failed.";
  473. NotifyGattConnectFailure();
  474. return;
  475. }
  476. // As we are about to replace |ble_device_| with |ble_device| existing event
  477. // handlers need to be unregistered. New ones will be added below.
  478. ClearEventRegistrations();
  479. ble_device_ = std::move(ble_device);
  480. ble_device_->get_ConnectionStatus(&connection_status_);
  481. connection_changed_token_ = AddTypedEventHandler(
  482. ble_device_.Get(), &IBluetoothLEDevice::add_ConnectionStatusChanged,
  483. base::BindRepeating(&BluetoothDeviceWinrt::OnConnectionStatusChanged,
  484. weak_ptr_factory_.GetWeakPtr()));
  485. name_changed_token_ = AddTypedEventHandler(
  486. ble_device_.Get(), &IBluetoothLEDevice::add_NameChanged,
  487. base::BindRepeating(&BluetoothDeviceWinrt::OnNameChanged,
  488. weak_ptr_factory_.GetWeakPtr()));
  489. if (!observe_gatt_session_status_change_events_) {
  490. // GattSession SessionStatusChanged events can not be observed on
  491. // 1703 (RS2) because BluetoothLEDevice::GetDeviceId() is not
  492. // available. Instead, initiate GATT discovery which should result
  493. // in a GATT connection attempt as well and trigger
  494. // OnConnectionStatusChanged on success.
  495. if (IsGattConnected()) {
  496. DidConnectGatt(/*error_code=*/absl::nullopt);
  497. }
  498. StartGattDiscovery();
  499. return;
  500. }
  501. // Next, obtain a GattSession so we can tell the OS to maintain a GATT
  502. // connection with |ble_device_|.
  503. // BluetoothLEDevice::GetDeviceId()
  504. ComPtr<IBluetoothLEDevice4> ble_device_4;
  505. HRESULT hr = ble_device_.As(&ble_device_4);
  506. if (FAILED(hr)) {
  507. BLUETOOTH_LOG(DEBUG) << "Obtaining IBluetoothLEDevice4 failed: "
  508. << logging::SystemErrorCodeToString(hr);
  509. NotifyGattConnectFailure();
  510. return;
  511. }
  512. ComPtr<IBluetoothDeviceId> bluetooth_device_id;
  513. hr = ble_device_4->get_BluetoothDeviceId(&bluetooth_device_id);
  514. if (FAILED(hr)) {
  515. BLUETOOTH_LOG(DEBUG) << "BluetoothDeviceId::FromId failed: "
  516. << logging::SystemErrorCodeToString(hr);
  517. NotifyGattConnectFailure();
  518. return;
  519. }
  520. // GattSession::FromDeviceIdAsync()
  521. IGattSessionStatics* gatt_session_statics = nullptr;
  522. hr = GetGattSessionStaticsActivationFactory(&gatt_session_statics);
  523. if (FAILED(hr)) {
  524. BLUETOOTH_LOG(DEBUG) << "GetGattSessionStaticsActivationFactory() failed: "
  525. << logging::SystemErrorCodeToString(hr);
  526. NotifyGattConnectFailure();
  527. return;
  528. }
  529. ComPtr<IAsyncOperation<GattSession*>> gatt_session_from_device_id_async_op;
  530. hr = gatt_session_statics->FromDeviceIdAsync(
  531. bluetooth_device_id.Get(), &gatt_session_from_device_id_async_op);
  532. if (FAILED(hr)) {
  533. BLUETOOTH_LOG(DEBUG) << "GattSession::FromDeviceId failed: "
  534. << logging::SystemErrorCodeToString(hr);
  535. NotifyGattConnectFailure();
  536. return;
  537. }
  538. hr = base::win::PostAsyncResults(
  539. std::move(gatt_session_from_device_id_async_op),
  540. base::BindOnce(&BluetoothDeviceWinrt::OnGattSessionFromDeviceId,
  541. weak_ptr_factory_.GetWeakPtr()));
  542. if (FAILED(hr)) {
  543. BLUETOOTH_LOG(DEBUG) << "PostAsyncResults failed: "
  544. << logging::SystemErrorCodeToString(hr);
  545. NotifyGattConnectFailure();
  546. return;
  547. }
  548. }
  549. void BluetoothDeviceWinrt::OnGattSessionFromDeviceId(
  550. ComPtr<IGattSession> gatt_session) {
  551. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  552. DCHECK(observe_gatt_session_status_change_events_);
  553. if (!gatt_session) {
  554. BLUETOOTH_LOG(DEBUG) << "Getting GattSession failed";
  555. NotifyGattConnectFailure();
  556. return;
  557. }
  558. gatt_session_ = std::move(gatt_session);
  559. // Tell the OS to automatically establish and maintain a GATT connection.
  560. HRESULT hr = gatt_session_->put_MaintainConnection(true);
  561. if (FAILED(hr)) {
  562. BLUETOOTH_LOG(DEBUG) << "Setting GattSession.MaintainConnection failed: "
  563. << logging::SystemErrorCodeToString(hr);
  564. NotifyGattConnectFailure();
  565. return;
  566. }
  567. // Observe GattSessionStatus changes.
  568. gatt_session_->get_SessionStatus(&gatt_session_status_);
  569. gatt_session_status_changed_token_ = AddTypedEventHandler(
  570. gatt_session_.Get(), &IGattSession::add_SessionStatusChanged,
  571. base::BindRepeating(&BluetoothDeviceWinrt::OnGattSessionStatusChanged,
  572. weak_ptr_factory_.GetWeakPtr()));
  573. // Check whether we missed the initial GattSessionStatus change notification
  574. // because the OS had already established a connection.
  575. if (IsGattConnected()) {
  576. DidConnectGatt(/*error_code=*/absl::nullopt);
  577. StartGattDiscovery();
  578. }
  579. }
  580. void BluetoothDeviceWinrt::OnGattSessionStatusChanged(
  581. IGattSession* gatt_session,
  582. ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::
  583. IGattSessionStatusChangedEventArgs* event_args) {
  584. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  585. DCHECK(observe_gatt_session_status_change_events_);
  586. DCHECK_EQ(gatt_session_.Get(), gatt_session);
  587. GattSessionStatus old_status = gatt_session_status_;
  588. event_args->get_Status(&gatt_session_status_);
  589. BluetoothError error;
  590. event_args->get_Error(&error);
  591. BLUETOOTH_LOG(DEBUG) << "OnGattSessionStatusChanged() status="
  592. << gatt_session_status_ << ", error=" << error;
  593. if (pending_gatt_service_discovery_start_ &&
  594. error != BluetoothError_Success) {
  595. NotifyGattConnectFailure();
  596. return;
  597. }
  598. // Spurious status change notifications may occur.
  599. if (old_status == gatt_session_status_) {
  600. return;
  601. }
  602. if (IsGattConnected()) {
  603. DidConnectGatt(/*error_code=*/absl::nullopt);
  604. StartGattDiscovery();
  605. } else {
  606. gatt_discoverer_.reset();
  607. ClearGattServices();
  608. DidDisconnectGatt();
  609. }
  610. }
  611. void BluetoothDeviceWinrt::OnConnectionStatusChanged(
  612. IBluetoothLEDevice* ble_device,
  613. IInspectable* object) {
  614. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  615. BluetoothConnectionStatus old_status = connection_status_;
  616. ble_device->get_ConnectionStatus(&connection_status_);
  617. BLUETOOTH_LOG(DEBUG) << "OnConnectionStatusChanged() status="
  618. << connection_status_;
  619. // Spurious status change notifications may occur.
  620. if (old_status == connection_status_) {
  621. return;
  622. }
  623. if (observe_gatt_session_status_change_events_) {
  624. return;
  625. }
  626. if (IsGattConnected()) {
  627. DidConnectGatt(/*error_code=*/absl::nullopt);
  628. } else {
  629. gatt_discoverer_.reset();
  630. ClearGattServices();
  631. DidDisconnectGatt();
  632. }
  633. }
  634. void BluetoothDeviceWinrt::OnGattServicesChanged(IBluetoothLEDevice* ble_device,
  635. IInspectable* object) {
  636. BLUETOOTH_LOG(DEBUG) << "OnGattServicesChanged()";
  637. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  638. // TODO(crbug/1085596): This event fires once for every newly discovered GATT
  639. // service. Hence, the initial GATT service discovery aborts and restarts
  640. // itself here once for every service discovered, which is unnecessary and
  641. // slow.
  642. // We don't clear out |gatt_services_| here, as we don't want to break
  643. // existing references to Gatt Services that did not change.
  644. device_uuids_.ClearServiceUUIDs();
  645. SetGattServicesDiscoveryComplete(false);
  646. adapter_->NotifyDeviceChanged(this);
  647. if (IsGattConnected()) {
  648. // In order to stop a potential ongoing GATT discovery, the GattDiscoverer
  649. // is reset and a new discovery is initiated.
  650. BLUETOOTH_LOG(DEBUG) << "Discovering GATT services anew";
  651. StartGattDiscovery();
  652. }
  653. }
  654. void BluetoothDeviceWinrt::OnNameChanged(IBluetoothLEDevice* ble_device,
  655. IInspectable* object) {
  656. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  657. adapter_->NotifyDeviceChanged(this);
  658. }
  659. void BluetoothDeviceWinrt::StartGattDiscovery() {
  660. BLUETOOTH_LOG(DEBUG) << "StartGattDiscovery()";
  661. pending_gatt_service_discovery_start_ = false;
  662. if (!gatt_services_changed_token_) {
  663. gatt_services_changed_token_ = AddTypedEventHandler(
  664. ble_device_.Get(), &IBluetoothLEDevice::add_GattServicesChanged,
  665. base::BindRepeating(&BluetoothDeviceWinrt::OnGattServicesChanged,
  666. weak_ptr_factory_.GetWeakPtr()));
  667. }
  668. gatt_discoverer_ =
  669. std::make_unique<BluetoothGattDiscovererWinrt>(ble_device_, target_uuid_);
  670. gatt_discoverer_->StartGattDiscovery(
  671. base::BindOnce(&BluetoothDeviceWinrt::OnGattDiscoveryComplete,
  672. weak_ptr_factory_.GetWeakPtr()));
  673. }
  674. void BluetoothDeviceWinrt::OnGattDiscoveryComplete(bool success) {
  675. BLUETOOTH_LOG(DEBUG) << "OnGattDiscoveryComplete() success=" << success;
  676. if (!success) {
  677. if (!IsGattConnected()) {
  678. NotifyGattConnectFailure();
  679. }
  680. gatt_discoverer_.reset();
  681. return;
  682. }
  683. // Instead of clearing out |gatt_services_| and creating each service from
  684. // scratch, we create a new map and move already existing services into it in
  685. // order to preserve pointer stability.
  686. GattServiceMap gatt_services;
  687. for (const auto& gatt_service : gatt_discoverer_->GetGattServices()) {
  688. auto gatt_service_winrt =
  689. BluetoothRemoteGattServiceWinrt::Create(this, gatt_service);
  690. if (!gatt_service_winrt)
  691. continue;
  692. std::string identifier = gatt_service_winrt->GetIdentifier();
  693. auto iter = gatt_services_.find(identifier);
  694. if (iter != gatt_services_.end()) {
  695. iter = gatt_services.emplace(std::move(*iter)).first;
  696. } else {
  697. iter = gatt_services
  698. .emplace(std::move(identifier), std::move(gatt_service_winrt))
  699. .first;
  700. }
  701. static_cast<BluetoothRemoteGattServiceWinrt*>(iter->second.get())
  702. ->UpdateCharacteristics(gatt_discoverer_.get());
  703. }
  704. std::swap(gatt_services, gatt_services_);
  705. device_uuids_.ReplaceServiceUUIDs(gatt_services_);
  706. SetGattServicesDiscoveryComplete(true);
  707. adapter_->NotifyGattServicesDiscovered(this);
  708. adapter_->NotifyDeviceChanged(this);
  709. gatt_discoverer_.reset();
  710. }
  711. void BluetoothDeviceWinrt::ClearGattServices() {
  712. // Clearing |gatt_services_| can trigger callbacks. Move the existing
  713. // objects into a local variable to avoid re-entrancy into clear().
  714. GattServiceMap temp_gatt_services;
  715. temp_gatt_services.swap(gatt_services_);
  716. temp_gatt_services.clear();
  717. device_uuids_.ClearServiceUUIDs();
  718. SetGattServicesDiscoveryComplete(false);
  719. }
  720. void BluetoothDeviceWinrt::ClearEventRegistrations() {
  721. if (connection_changed_token_) {
  722. RemoveConnectionStatusHandler(ble_device_.Get(),
  723. *connection_changed_token_);
  724. }
  725. if (gatt_session_status_changed_token_) {
  726. RemoveGattSessionStatusHandler(gatt_session_.Get(),
  727. *gatt_session_status_changed_token_);
  728. }
  729. if (gatt_services_changed_token_) {
  730. RemoveGattServicesChangedHandler(ble_device_.Get(),
  731. *gatt_services_changed_token_);
  732. }
  733. if (name_changed_token_)
  734. RemoveNameChangedHandler(ble_device_.Get(), *name_changed_token_);
  735. }
  736. } // namespace device