bluetooth_adapter_mac.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // Copyright 2013 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. #ifndef DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_MAC_H_
  5. #define DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_MAC_H_
  6. #include <IOKit/IOReturn.h>
  7. #include <map>
  8. #include <memory>
  9. #include <string>
  10. #include <unordered_map>
  11. #include <vector>
  12. #include "base/mac/scoped_nsobject.h"
  13. #include "base/memory/ref_counted.h"
  14. #include "base/memory/weak_ptr.h"
  15. #include "base/task/single_thread_task_runner.h"
  16. #include "device/bluetooth/bluetooth_adapter.h"
  17. #include "device/bluetooth/bluetooth_discovery_manager_mac.h"
  18. #include "device/bluetooth/bluetooth_export.h"
  19. #include "device/bluetooth/bluetooth_low_energy_advertisement_manager_mac.h"
  20. #include "device/bluetooth/bluetooth_low_energy_device_mac.h"
  21. #include "device/bluetooth/bluetooth_low_energy_device_watcher_mac.h"
  22. #include "device/bluetooth/bluetooth_low_energy_discovery_manager_mac.h"
  23. #include "device/bluetooth/public/cpp/bluetooth_uuid.h"
  24. @class CBUUID;
  25. @class IOBluetoothDevice;
  26. @class NSArray;
  27. @class NSDate;
  28. @class BluetoothAdvertisementMac;
  29. @class BluetoothLowEnergyCentralManagerDelegate;
  30. @class BluetoothLowEnergyPeripheralManagerDelegate;
  31. namespace device {
  32. class DEVICE_BLUETOOTH_EXPORT BluetoothAdapterMac
  33. : public BluetoothAdapter,
  34. public BluetoothDiscoveryManagerMac::Observer,
  35. public BluetoothLowEnergyDiscoveryManagerMac::Observer {
  36. public:
  37. static scoped_refptr<BluetoothAdapterMac> CreateAdapter();
  38. static scoped_refptr<BluetoothAdapterMac> CreateAdapterForTest(
  39. std::string name,
  40. std::string address,
  41. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner);
  42. BluetoothAdapterMac(const BluetoothAdapterMac&) = delete;
  43. BluetoothAdapterMac& operator=(const BluetoothAdapterMac&) = delete;
  44. // Converts CBUUID into BluetoothUUID
  45. static BluetoothUUID BluetoothUUIDWithCBUUID(CBUUID* UUID);
  46. // Converts NSError to string for logging.
  47. static std::string String(NSError* error);
  48. // BluetoothAdapter overrides:
  49. std::string GetAddress() const override;
  50. std::string GetName() const override;
  51. void SetName(const std::string& name,
  52. base::OnceClosure callback,
  53. ErrorCallback error_callback) override;
  54. bool IsInitialized() const override;
  55. bool IsPresent() const override;
  56. bool IsPowered() const override;
  57. PermissionStatus GetOsPermissionStatus() const override;
  58. bool IsDiscoverable() const override;
  59. void SetDiscoverable(bool discoverable,
  60. base::OnceClosure callback,
  61. ErrorCallback error_callback) override;
  62. bool IsDiscovering() const override;
  63. std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet>
  64. RetrieveGattConnectedDevicesWithDiscoveryFilter(
  65. const BluetoothDiscoveryFilter& discovery_filter) override;
  66. UUIDList GetUUIDs() const override;
  67. void CreateRfcommService(const BluetoothUUID& uuid,
  68. const ServiceOptions& options,
  69. CreateServiceCallback callback,
  70. CreateServiceErrorCallback error_callback) override;
  71. void CreateL2capService(const BluetoothUUID& uuid,
  72. const ServiceOptions& options,
  73. CreateServiceCallback callback,
  74. CreateServiceErrorCallback error_callback) override;
  75. void RegisterAdvertisement(
  76. std::unique_ptr<BluetoothAdvertisement::Data> advertisement_data,
  77. CreateAdvertisementCallback callback,
  78. AdvertisementErrorCallback error_callback) override;
  79. BluetoothLocalGattService* GetGattService(
  80. const std::string& identifier) const override;
  81. DeviceList GetDevices() override;
  82. ConstDeviceList GetDevices() const override;
  83. // BluetoothDiscoveryManagerMac::Observer overrides:
  84. void ClassicDeviceFound(IOBluetoothDevice* device) override;
  85. void ClassicDiscoveryStopped(bool unexpected) override;
  86. // Registers that a new |device| has connected to the local host.
  87. void DeviceConnected(IOBluetoothDevice* device);
  88. // Creates a GATT connection by calling CoreBluetooth APIs.
  89. void CreateGattConnection(BluetoothLowEnergyDeviceMac* device_mac);
  90. // Closes the GATT connection by calling CoreBluetooth APIs.
  91. void DisconnectGatt(BluetoothLowEnergyDeviceMac* device_mac);
  92. // Methods called from CBCentralManager delegate.
  93. void DidConnectPeripheral(CBPeripheral* peripheral);
  94. void DidFailToConnectPeripheral(CBPeripheral* peripheral, NSError* error);
  95. void DidDisconnectPeripheral(CBPeripheral* peripheral, NSError* error);
  96. bool IsBluetoothLowEnergyDeviceSystemPaired(
  97. base::StringPiece device_identifier) const;
  98. protected:
  99. using GetDevicePairedStatusCallback =
  100. base::RepeatingCallback<bool(const std::string& address)>;
  101. // BluetoothAdapter override:
  102. base::WeakPtr<BluetoothAdapter> GetWeakPtr() override;
  103. bool SetPoweredImpl(bool powered) override;
  104. void RemovePairingDelegateInternal(
  105. device::BluetoothDevice::PairingDelegate* pairing_delegate) override;
  106. void UpdateKnownLowEnergyDevices(
  107. std::map<std::string, std::string> updated_low_energy_device_info);
  108. private:
  109. // Struct bundling information about the state of the HostController.
  110. struct HostControllerState {
  111. bool is_present = false;
  112. bool classic_powered = false;
  113. std::string address;
  114. };
  115. // Typedef for function returning the state of the HostController.
  116. using HostControllerStateFunction =
  117. base::RepeatingCallback<HostControllerState()>;
  118. // Type of the underlying implementation of SetPowered(). It takes an int
  119. // instead of a bool, since the production code calls into a C API that does
  120. // not know about bool.
  121. using SetControllerPowerStateFunction = base::RepeatingCallback<void(int)>;
  122. // Performs initialization steps which touch the Bluetooth API and might
  123. // trigger a Bluetooth permission prompt.
  124. void LazyInitialize();
  125. // Queries the state of the IOBluetoothHostController.
  126. HostControllerState GetHostControllerState();
  127. // Allows configuring whether the adapter is present when running in a test
  128. // configuration.
  129. void SetPresentForTesting(bool present);
  130. // Resets |low_energy_central_manager_| to |central_manager| and sets
  131. // |low_energy_central_manager_delegate_| as the manager's delegate. Should
  132. // be called only when |IsLowEnergyAvailable()|.
  133. void SetCentralManagerForTesting(CBCentralManager* central_manager);
  134. // Returns the CBCentralManager instance.
  135. CBCentralManager* GetCentralManager();
  136. // Returns the CBPeripheralManager instance.
  137. CBPeripheralManager* GetPeripheralManager();
  138. // Allow the mocking out of getting the HostController state for testing.
  139. void SetHostControllerStateFunctionForTesting(
  140. HostControllerStateFunction controller_state_function);
  141. // Allow the mocking out of setting the controller power state for testing.
  142. void SetPowerStateFunctionForTesting(
  143. SetControllerPowerStateFunction power_state_function);
  144. // Allow the mocking out of BluetoothLowEnergyDeviceWatcher for testing.
  145. void SetLowEnergyDeviceWatcherForTesting(
  146. scoped_refptr<BluetoothLowEnergyDeviceWatcherMac> watcher);
  147. // Allow the mocking of out GetDevicePairedStatusCallback for testing.
  148. void SetGetDevicePairedStatusCallbackForTesting(
  149. GetDevicePairedStatusCallback callback);
  150. // The length of time that must elapse since the last Inquiry response (on
  151. // Classic devices) or call to BluetoothLowEnergyDevice::Update() (on Low
  152. // Energy) before a discovered device is considered to be no longer available.
  153. const static NSTimeInterval kDiscoveryTimeoutSec;
  154. friend class BluetoothTestMac;
  155. friend class BluetoothAdapterMacTest;
  156. friend class BluetoothLowEnergyCentralManagerBridge;
  157. friend class BluetoothLowEnergyPeripheralManagerBridge;
  158. BluetoothAdapterMac();
  159. ~BluetoothAdapterMac() override;
  160. // BluetoothAdapter overrides:
  161. void StartScanWithFilter(
  162. std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
  163. DiscoverySessionResultCallback callback) override;
  164. void UpdateFilter(
  165. std::unique_ptr<device::BluetoothDiscoveryFilter> discovery_filter,
  166. DiscoverySessionResultCallback callback) override;
  167. void StopScan(DiscoverySessionResultCallback callback) override;
  168. // Start classic and/or low energy discovery sessions, according to the
  169. // filter. If a discovery session is already running the filter is updated.
  170. bool StartDiscovery(BluetoothDiscoveryFilter* discovery_filter);
  171. void Initialize(base::OnceClosure callback) override;
  172. void InitForTest(scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner);
  173. void PollAdapter();
  174. // Registers that a new |device| has replied to an Inquiry, is paired, or has
  175. // connected to the local host.
  176. void ClassicDeviceAdded(IOBluetoothDevice* device);
  177. // Checks if the low energy central manager is powered on. Returns false if
  178. // BLE is not available.
  179. bool IsLowEnergyPowered() const;
  180. // BluetoothLowEnergyDiscoveryManagerMac::Observer override:
  181. void LowEnergyDeviceUpdated(CBPeripheral* peripheral,
  182. NSDictionary* advertisement_data,
  183. int rssi) override;
  184. // Updates |devices_| when there is a change to the CBCentralManager's state.
  185. void LowEnergyCentralManagerUpdatedState();
  186. // Updates |advertisements_| when there is a change to the
  187. // CBPeripheralManager's state.
  188. void LowEnergyPeripheralManagerUpdatedState();
  189. // Updates |devices_| to include the currently paired devices and notifies
  190. // observers.
  191. void AddPairedDevices();
  192. // Returns the list of devices that are connected by other applications than
  193. // Chromium, based on a service UUID. If no uuid is given, generic access
  194. // service (1800) is used (since CoreBluetooth requires to use a service).
  195. std::vector<BluetoothDevice*> RetrieveGattConnectedDevicesWithService(
  196. const BluetoothUUID* uuid);
  197. // Returns the BLE device associated with the CoreBluetooth peripheral.
  198. BluetoothLowEnergyDeviceMac* GetBluetoothLowEnergyDeviceMac(
  199. CBPeripheral* peripheral);
  200. // Returns true if a new device collides with an existing device.
  201. bool DoesCollideWithKnownDevice(CBPeripheral* peripheral,
  202. BluetoothLowEnergyDeviceMac* device_mac);
  203. // The Initialize() method intentionally does not initialize
  204. // |low_energy_central_manager_| or |low_energy_peripheral_manager_| because
  205. // Chromium might not have permission to access the Bluetooth adapter.
  206. // Methods which require these to be initialized must call LazyInitialize()
  207. // first.
  208. bool lazy_initialized_ = false;
  209. std::string address_;
  210. bool classic_powered_ = false;
  211. absl::optional<bool> is_present_for_testing_;
  212. // Function returning the state of the HostController. Can be overridden for
  213. // tests.
  214. HostControllerStateFunction controller_state_function_;
  215. // SetPowered() implementation and callbacks.
  216. SetControllerPowerStateFunction power_state_function_;
  217. std::unique_ptr<SetPoweredCallbacks> set_powered_callbacks_;
  218. // Cached name. Updated in GetName if should_update_name_ is true.
  219. //
  220. // For performance reasons, cache the adapter's name. It's not uncommon for
  221. // a call to [controller nameAsString] to take tens of milliseconds. Note
  222. // that this caching strategy might result in clients receiving a stale
  223. // name. If this is a significant issue, then some more sophisticated
  224. // workaround for the performance bottleneck will be needed. For additional
  225. // context, see http://crbug.com/461181 and http://crbug.com/467316
  226. mutable std::string name_;
  227. // True if the name hasn't been acquired yet, the last acquired name is empty
  228. // or the address has changed indicating the name might have changed.
  229. mutable bool should_update_name_ = true;
  230. // Discovery manager for Bluetooth Classic.
  231. std::unique_ptr<BluetoothDiscoveryManagerMac> classic_discovery_manager_;
  232. // Discovery manager for Bluetooth Low Energy.
  233. std::unique_ptr<BluetoothLowEnergyDiscoveryManagerMac>
  234. low_energy_discovery_manager_;
  235. // Advertisement manager for Bluetooth Low Energy.
  236. std::unique_ptr<BluetoothLowEnergyAdvertisementManagerMac>
  237. low_energy_advertisement_manager_;
  238. // Underlying CoreBluetooth CBCentralManager and its delegate.
  239. base::scoped_nsobject<CBCentralManager> low_energy_central_manager_;
  240. base::scoped_nsobject<BluetoothLowEnergyCentralManagerDelegate>
  241. low_energy_central_manager_delegate_;
  242. // Underlying CoreBluetooth CBPeripheralManager and its delegate.
  243. base::scoped_nsobject<CBPeripheralManager> low_energy_peripheral_manager_;
  244. base::scoped_nsobject<BluetoothLowEnergyPeripheralManagerDelegate>
  245. low_energy_peripheral_manager_delegate_;
  246. GetDevicePairedStatusCallback device_paired_status_callback_;
  247. // Watches system file /Library/Preferences/com.apple.Bluetooth.plist to
  248. // obtain information about system paired bluetooth devices.
  249. scoped_refptr<BluetoothLowEnergyDeviceWatcherMac>
  250. bluetooth_low_energy_device_watcher_;
  251. // Map of UUID formatted device identifiers of paired Bluetooth devices and
  252. // corresponding device address.
  253. std::map<std::string, std::string> low_energy_devices_info_;
  254. base::WeakPtrFactory<BluetoothAdapterMac> weak_ptr_factory_{this};
  255. };
  256. } // namespace device
  257. #endif // DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_MAC_H_