bluetooth_devices_observer.cc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 "ash/bluetooth_devices_observer.h"
  5. #include "base/bind.h"
  6. #include "device/bluetooth/bluetooth_adapter_factory.h"
  7. namespace ash {
  8. BluetoothDevicesObserver::BluetoothDevicesObserver(
  9. const AdapterOrDeviceChangedCallback& device_changed_callback)
  10. : adapter_or_device_changed_callback_(device_changed_callback) {
  11. if (device::BluetoothAdapterFactory::IsBluetoothSupported()) {
  12. device::BluetoothAdapterFactory::Get()->GetAdapter(
  13. base::BindOnce(&BluetoothDevicesObserver::InitializeOnAdapterReady,
  14. weak_factory_.GetWeakPtr()));
  15. } else {
  16. adapter_or_device_changed_callback_.Run(/*device=*/nullptr);
  17. }
  18. }
  19. BluetoothDevicesObserver::~BluetoothDevicesObserver() {
  20. if (bluetooth_adapter_)
  21. bluetooth_adapter_->RemoveObserver(this);
  22. }
  23. void BluetoothDevicesObserver::AdapterPresentChanged(
  24. device::BluetoothAdapter* adapter,
  25. bool present) {
  26. adapter_or_device_changed_callback_.Run(/*device=*/nullptr);
  27. }
  28. void BluetoothDevicesObserver::AdapterPoweredChanged(
  29. device::BluetoothAdapter* adapter,
  30. bool powered) {
  31. adapter_or_device_changed_callback_.Run(/*device=*/nullptr);
  32. }
  33. void BluetoothDevicesObserver::DeviceChanged(device::BluetoothAdapter* adapter,
  34. device::BluetoothDevice* device) {
  35. adapter_or_device_changed_callback_.Run(device);
  36. }
  37. void BluetoothDevicesObserver::InitializeOnAdapterReady(
  38. scoped_refptr<device::BluetoothAdapter> adapter) {
  39. bluetooth_adapter_ = std::move(adapter);
  40. bluetooth_adapter_->AddObserver(this);
  41. }
  42. bool BluetoothDevicesObserver::IsConnectedBluetoothDevice(
  43. const ui::InputDevice& input_device) const {
  44. if (!bluetooth_adapter_ || !bluetooth_adapter_->IsPresent() ||
  45. !bluetooth_adapter_->IsInitialized() ||
  46. !bluetooth_adapter_->IsPowered()) {
  47. return false;
  48. }
  49. // Since there is no map from an InputDevice to a BluetoothDevice. We just
  50. // comparing their vendor id and product id to guess a match.
  51. for (auto* device : bluetooth_adapter_->GetDevices()) {
  52. if (!device->IsConnected())
  53. continue;
  54. if (device->GetVendorID() == input_device.vendor_id &&
  55. device->GetProductID() == input_device.product_id) {
  56. return true;
  57. }
  58. }
  59. return false;
  60. }
  61. } // namespace ash