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