bluetooth_adapter.h 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. // Copyright (c) 2012 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_H_
  5. #define DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_H_
  6. #include <stdint.h>
  7. #include <list>
  8. #include <memory>
  9. #include <set>
  10. #include <string>
  11. #include <unordered_map>
  12. #include <utility>
  13. #include <vector>
  14. #include "base/callback.h"
  15. #include "base/containers/queue.h"
  16. #include "base/memory/ref_counted.h"
  17. #include "base/memory/weak_ptr.h"
  18. #include "base/observer_list.h"
  19. #include "base/time/time.h"
  20. #include "build/build_config.h"
  21. #include "build/chromeos_buildflags.h"
  22. #include "device/bluetooth/bluetooth_advertisement.h"
  23. #include "device/bluetooth/bluetooth_device.h"
  24. #include "device/bluetooth/bluetooth_discovery_filter.h"
  25. #include "device/bluetooth/bluetooth_export.h"
  26. #include "third_party/abseil-cpp/absl/types/optional.h"
  27. #if BUILDFLAG(IS_CHROMEOS)
  28. #include "device/bluetooth/bluetooth_low_energy_scan_session.h"
  29. #endif // BUILDFLAG(IS_CHROMEOS)
  30. namespace base {
  31. class SingleThreadTaskRunner;
  32. } // namespace base
  33. namespace device {
  34. class BluetoothAdvertisement;
  35. class BluetoothDiscoveryFilter;
  36. class BluetoothDiscoverySession;
  37. class BluetoothLocalGattService;
  38. #if BUILDFLAG(IS_CHROMEOS)
  39. class BluetoothLowEnergyScanFilter;
  40. #endif // BUILDFLAG(IS_CHROMEOS)
  41. class BluetoothRemoteGattCharacteristic;
  42. class BluetoothRemoteGattDescriptor;
  43. class BluetoothRemoteGattService;
  44. class BluetoothSocket;
  45. class BluetoothUUID;
  46. enum class UMABluetoothDiscoverySessionOutcome;
  47. // BluetoothAdapter represents a local Bluetooth adapter which may be used to
  48. // interact with remote Bluetooth devices. As well as providing support for
  49. // determining whether an adapter is present and whether the radio is powered,
  50. // this class also provides support for obtaining the list of remote devices
  51. // known to the adapter, discovering new devices, and providing notification of
  52. // updates to device information.
  53. class DEVICE_BLUETOOTH_EXPORT BluetoothAdapter
  54. : public base::RefCounted<BluetoothAdapter> {
  55. public:
  56. #if BUILDFLAG(IS_CHROMEOS)
  57. enum class LowEnergyScanSessionHardwareOffloadingStatus {
  58. kUndetermined = 0,
  59. kNotSupported,
  60. kSupported
  61. };
  62. #endif // BUILDFLAG(IS_CHROMEOS)
  63. // Interface for observing changes from bluetooth adapters.
  64. class DEVICE_BLUETOOTH_EXPORT Observer {
  65. public:
  66. virtual ~Observer() {}
  67. // Called when the presence of the adapter |adapter| changes. When |present|
  68. // is true the adapter is now present, false means the adapter has been
  69. // removed from the system.
  70. virtual void AdapterPresentChanged(BluetoothAdapter* adapter,
  71. bool present) {}
  72. // Called when the radio power state of the adapter |adapter| changes. When
  73. // |powered| is true the adapter radio is powered, false means the adapter
  74. // radio is off.
  75. virtual void AdapterPoweredChanged(BluetoothAdapter* adapter,
  76. bool powered) {}
  77. // Called when the discoverability state of the adapter |adapter| changes.
  78. // When |discoverable| is true the adapter is discoverable by other devices,
  79. // false means the adapter is not discoverable.
  80. virtual void AdapterDiscoverableChanged(BluetoothAdapter* adapter,
  81. bool discoverable) {}
  82. // Called when the discovering state of the adapter |adapter| changes. When
  83. // |discovering| is true the adapter is seeking new devices, false means it
  84. // is not.
  85. virtual void AdapterDiscoveringChanged(BluetoothAdapter* adapter,
  86. bool discovering) {}
  87. // Called when a new device |device| is added to the adapter |adapter|,
  88. // either because it has been discovered or a connection made. |device|
  89. // should not be cached. Instead, copy its Bluetooth address.
  90. virtual void DeviceAdded(BluetoothAdapter* adapter,
  91. BluetoothDevice* device) {}
  92. // Called when the adapter |DiscoveryChangeComplete| is finished
  93. virtual void DiscoveryChangeCompletedForTesting() {}
  94. // Called when the result of one of the following methods of the device
  95. // |device| changes:
  96. // * GetAddress()
  97. // * GetAppearance()
  98. // * GetName() (Chrome OS and Windows only)
  99. // * GetBluetoothClass()
  100. // * GetInquiryRSSI()
  101. // * GetInquiryTxPower()
  102. // * GetUUIDs()
  103. // * GetServiceData()
  104. // * GetServiceDataUUIDs()
  105. // * GetServiceDataForUUID()
  106. // * GetManufacturerData()
  107. // * GetManufacturerDataIDs()
  108. // * GetManufacturerDataForID()
  109. // * GetAdvertisingDataFlags()
  110. // * IsConnectable()
  111. // * IsConnected()
  112. // * IsConnecting()
  113. // * IsGattConnected()
  114. // * IsPaired()
  115. //
  116. // On Android and MacOS this method is called for each advertisement packet
  117. // received. On Chrome OS and Linux, we can't guarantee that this method
  118. // will be called for each Adv. Packet received but, because the RSSI is
  119. // always changing, it's very likely this method will be called for each
  120. // Adv. Packet.
  121. // |device| should not be cached. Instead, copy its Bluetooth address.
  122. virtual void DeviceChanged(BluetoothAdapter* adapter,
  123. BluetoothDevice* device) {}
  124. // Called when address property of the device |device| known to the adapter
  125. // |adapter| change due to pairing.
  126. virtual void DeviceAddressChanged(BluetoothAdapter* adapter,
  127. BluetoothDevice* device,
  128. const std::string& old_address) {}
  129. // Called when advertisement is received.
  130. //
  131. // Override this function to observe LE advertisements. This function
  132. // returns the raw values that have been parsed from EIR.
  133. virtual void DeviceAdvertisementReceived(
  134. const std::string& device_address,
  135. const absl::optional<std::string>& device_name,
  136. const absl::optional<std::string>& advertisement_name,
  137. absl::optional<int8_t> rssi,
  138. absl::optional<int8_t> tx_power,
  139. absl::optional<uint16_t> appearance,
  140. const BluetoothDevice::UUIDList& advertised_uuids,
  141. const BluetoothDevice::ServiceDataMap& service_data_map,
  142. const BluetoothDevice::ManufacturerDataMap& manufacturer_data_map) {}
  143. #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
  144. // Called when paired property of the device |device| known to the adapter
  145. // |adapter| changed.
  146. virtual void DevicePairedChanged(BluetoothAdapter* adapter,
  147. BluetoothDevice* device,
  148. bool new_paired_status) {}
  149. // Called when the MTU |mtu| (Bluetooth Spec Vol 3, Part F, 3.4.2) used in
  150. // ATT communication with device |device| known to the adapter |adapter|
  151. // changed.
  152. virtual void DeviceMTUChanged(BluetoothAdapter* adapter,
  153. BluetoothDevice* device,
  154. uint16_t mtu) {}
  155. // Called when advertisement is received from |device|. |eir| is the
  156. // extended inquiry response specified in Bluetooth Core Spec, Vol 3,
  157. // Part C, Section 11.
  158. //
  159. // Override this function to observe LE advertisements. Whenever |rssi| of
  160. // |device| changes, this function is called with the latest |eir| from
  161. // |device|. This function is never called on classic |device|.
  162. virtual void DeviceAdvertisementReceived(BluetoothAdapter* adapter,
  163. BluetoothDevice* device,
  164. int16_t rssi,
  165. const std::vector<uint8_t>& eir) {}
  166. // Called when |device|'s state has changed from connected to not connected
  167. // or vice versa.
  168. virtual void DeviceConnectedStateChanged(BluetoothAdapter* adapter,
  169. BluetoothDevice* device,
  170. bool is_now_connected) {}
  171. // Called when blocked by policy property of the |device| known to the
  172. // |adapter| changes.
  173. virtual void DeviceBlockedByPolicyChanged(BluetoothAdapter* adapter,
  174. BluetoothDevice* device,
  175. bool new_blocked_status) {}
  176. #endif
  177. #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
  178. // Called when the device battery info with |type| has been updated.
  179. virtual void DeviceBatteryChanged(BluetoothAdapter* adapter,
  180. BluetoothDevice* device,
  181. BluetoothDevice::BatteryType type) {}
  182. #endif
  183. // Called when the device |device| is removed from the adapter |adapter|,
  184. // either as a result of a discovered device being lost between discovering
  185. // phases or pairing information deleted. |device| should not be
  186. // cached. Instead, copy its Bluetooth address.
  187. virtual void DeviceRemoved(BluetoothAdapter* adapter,
  188. BluetoothDevice* device) {}
  189. // Deprecated GATT Added/Removed Events NOTE:
  190. //
  191. // The series of Observer methods for Service, Characteristic, & Descriptor
  192. // Added/Removed events should be removed. They are rarely used and add
  193. // API & implementation complexity. They are not reliable for cross
  194. // platform use, and devices that modify their attribute table have not been
  195. // tested or supported.
  196. //
  197. // New code should use Observer::GattServicesDiscovered and then call
  198. // GetGattService(s)
  199. // GetCharacteristic(s)
  200. // GetDescriptor(s)
  201. //
  202. // TODO(710352): Remove Service, Characteristic, & Descriptor Added/Removed.
  203. // See "Deprecated GATT Added/Removed Events NOTE" above.
  204. //
  205. // Called when a new GATT service |service| is added to the device |device|,
  206. // as the service is received from the device. Don't cache |service|. Store
  207. // its identifier instead (i.e. BluetoothRemoteGattService::GetIdentifier).
  208. virtual void GattServiceAdded(BluetoothAdapter* adapter,
  209. BluetoothDevice* device,
  210. BluetoothRemoteGattService* service) {}
  211. // See "Deprecated GATT Added/Removed Events NOTE" above.
  212. //
  213. // Called when the GATT service |service| is removed from the device
  214. // |device|. This can happen if the attribute database of the remote device
  215. // changes or when |device| gets removed.
  216. virtual void GattServiceRemoved(BluetoothAdapter* adapter,
  217. BluetoothDevice* device,
  218. BluetoothRemoteGattService* service) {}
  219. // Called when the GATT discovery process has completed for all services,
  220. // characteristics, and descriptors in |device|.
  221. virtual void GattServicesDiscovered(BluetoothAdapter* adapter,
  222. BluetoothDevice* device) {}
  223. // TODO(782494): Deprecated & not functional on all platforms. Use
  224. // GattServicesDiscovered.
  225. //
  226. // Called when all characteristic and descriptor discovery procedures are
  227. // known to be completed for the GATT service |service|. This method will be
  228. // called after the initial discovery of a GATT service and will usually be
  229. // preceded by calls to GattCharacteristicAdded and GattDescriptorAdded.
  230. virtual void GattDiscoveryCompleteForService(
  231. BluetoothAdapter* adapter,
  232. BluetoothRemoteGattService* service) {}
  233. // See "Deprecated GATT Added/Removed Events NOTE" above.
  234. //
  235. // Called when properties of the remote GATT service |service| have changed.
  236. // This will get called for properties such as UUID, as well as for changes
  237. // to the list of known characteristics and included services. Observers
  238. // should read all GATT characteristic and descriptors objects and do any
  239. // necessary set up required for a changed service.
  240. virtual void GattServiceChanged(BluetoothAdapter* adapter,
  241. BluetoothRemoteGattService* service) {}
  242. // See "Deprecated GATT Added/Removed Events NOTE" above.
  243. //
  244. // Called when the remote GATT characteristic |characteristic| has been
  245. // discovered. Use this to issue any initial read/write requests to the
  246. // characteristic but don't cache the pointer as it may become invalid.
  247. // Instead, use the specially assigned identifier to obtain a characteristic
  248. // and cache that identifier as necessary, as it can be used to retrieve the
  249. // characteristic from its GATT service. The number of characteristics with
  250. // the same UUID belonging to a service depends on the particular profile
  251. // the remote device implements, hence the client of a GATT based profile
  252. // will usually operate on the whole set of characteristics and not just
  253. // one.
  254. virtual void GattCharacteristicAdded(
  255. BluetoothAdapter* adapter,
  256. BluetoothRemoteGattCharacteristic* characteristic) {}
  257. // See "Deprecated GATT Added/Removed Events NOTE" above.
  258. //
  259. // Called when a GATT characteristic |characteristic| has been removed from
  260. // the system.
  261. virtual void GattCharacteristicRemoved(
  262. BluetoothAdapter* adapter,
  263. BluetoothRemoteGattCharacteristic* characteristic) {}
  264. // See "Deprecated GATT Added/Removed Events NOTE" above.
  265. //
  266. // Called when the remote GATT characteristic descriptor |descriptor| has
  267. // been discovered. Don't cache the arguments as the pointers may become
  268. // invalid. Instead, use the specially assigned identifier to obtain a
  269. // descriptor and cache that identifier as necessary.
  270. virtual void GattDescriptorAdded(
  271. BluetoothAdapter* adapter,
  272. BluetoothRemoteGattDescriptor* descriptor) {}
  273. // See "Deprecated GATT Added/Removed Events NOTE" above.
  274. //
  275. // Called when a GATT characteristic descriptor |descriptor| has been
  276. // removed from the system.
  277. virtual void GattDescriptorRemoved(
  278. BluetoothAdapter* adapter,
  279. BluetoothRemoteGattDescriptor* descriptor) {}
  280. // Called when the value of a characteristic has changed. This might be a
  281. // result of a read/write request to, or a notification/indication from, a
  282. // remote GATT characteristic.
  283. virtual void GattCharacteristicValueChanged(
  284. BluetoothAdapter* adapter,
  285. BluetoothRemoteGattCharacteristic* characteristic,
  286. const std::vector<uint8_t>& value) {}
  287. // Called when the value of a characteristic descriptor has been updated.
  288. virtual void GattDescriptorValueChanged(
  289. BluetoothAdapter* adapter,
  290. BluetoothRemoteGattDescriptor* descriptor,
  291. const std::vector<uint8_t>& value) {}
  292. #if BUILDFLAG(IS_CHROMEOS)
  293. // Called when the low energy scanning hardware offloading support state
  294. // changes.
  295. virtual void LowEnergyScanSessionHardwareOffloadingStatusChanged(
  296. LowEnergyScanSessionHardwareOffloadingStatus status) {}
  297. #endif // BUILDFLAG(IS_CHROMEOS)
  298. };
  299. // Used to configure a listening service.
  300. struct DEVICE_BLUETOOTH_EXPORT ServiceOptions {
  301. ServiceOptions();
  302. ~ServiceOptions();
  303. absl::optional<int> channel;
  304. absl::optional<int> psm;
  305. absl::optional<std::string> name;
  306. // Clients can configure this option to choose if they want to enforce
  307. // bonding with remote devices that connect to this device. Options:
  308. // * Unset: bonding is not enforced by the local device, and the remote
  309. // device can choose if they want to enforce bonding.
  310. // * Set to false: bonding is prevented by the local device. Clients which
  311. // use this are responsible for securing their communication at the
  312. // application level.
  313. // * Set to true: bonding is enforced by the local device.
  314. absl::optional<bool> require_authentication;
  315. };
  316. // The ErrorCallback is used for methods that can fail in which case it is
  317. // called, in the success case the callback is simply not called.
  318. using ErrorCallback = base::OnceClosure;
  319. using DiscoverySessionCallback =
  320. base::OnceCallback<void(std::unique_ptr<BluetoothDiscoverySession>)>;
  321. using DeviceList = std::vector<BluetoothDevice*>;
  322. using ConstDeviceList = std::vector<const BluetoothDevice*>;
  323. using UUIDList = std::vector<BluetoothUUID>;
  324. using CreateServiceCallback =
  325. base::OnceCallback<void(scoped_refptr<BluetoothSocket>)>;
  326. using CreateServiceErrorCallback =
  327. base::OnceCallback<void(const std::string& message)>;
  328. using CreateAdvertisementCallback =
  329. base::OnceCallback<void(scoped_refptr<BluetoothAdvertisement>)>;
  330. using AdvertisementErrorCallback = BluetoothAdvertisement::ErrorCallback;
  331. using ConnectDeviceCallback = base::OnceCallback<void(BluetoothDevice*)>;
  332. using DiscoverySessionErrorCallback =
  333. base::OnceCallback<void(UMABluetoothDiscoverySessionOutcome)>;
  334. // The is_error bool is a flag to indicate if the result is an error(true)
  335. // or a success(false)
  336. // The Session Outcome is the result which could be success or some sort of
  337. // error. However, this variable is ignored when the bool is false
  338. using DiscoverySessionResultCallback =
  339. base::OnceCallback<void(/*is_error*/ bool,
  340. UMABluetoothDiscoverySessionOutcome)>;
  341. enum class DiscoveryState {
  342. kStarting = 0,
  343. kStopping,
  344. kDiscovering,
  345. kIdle,
  346. };
  347. enum class PermissionStatus { kUndetermined = 0, kDenied, kAllowed };
  348. // Creates a new adapter. Initialize() must be called before the adapter can
  349. // be used.
  350. static scoped_refptr<BluetoothAdapter> CreateAdapter();
  351. virtual void Initialize(base::OnceClosure callback) = 0;
  352. // Returns a weak pointer to an existing adapter for testing purposes only.
  353. base::WeakPtr<BluetoothAdapter> GetWeakPtrForTesting();
  354. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  355. // Shutdown the adapter: tear down and clean up all objects owned by
  356. // BluetoothAdapter. After this call, the BluetoothAdapter will behave as if
  357. // no Bluetooth controller exists in the local system. |IsPresent| will return
  358. // false.
  359. virtual void Shutdown();
  360. #endif
  361. // Adds and removes observers for events on this bluetooth adapter. If
  362. // monitoring multiple adapters, check the |adapter| parameter of observer
  363. // methods to determine which adapter is issuing the event.
  364. virtual void AddObserver(BluetoothAdapter::Observer* observer);
  365. virtual void RemoveObserver(BluetoothAdapter::Observer* observer);
  366. virtual bool HasObserver(BluetoothAdapter::Observer* observer);
  367. // The address of this adapter. The address format is "XX:XX:XX:XX:XX:XX",
  368. // where each XX is a hexadecimal number.
  369. virtual std::string GetAddress() const = 0;
  370. // The name of the adapter.
  371. virtual std::string GetName() const = 0;
  372. // The Bluetooth system name. Implementations may return an informational name
  373. // "BlueZ 5.54" on Chrome OS.
  374. virtual std::string GetSystemName() const;
  375. // Set the human-readable name of the adapter to |name|. On success,
  376. // |callback| will be called. On failure, |error_callback| will be called.
  377. // TODO(crbug.com/1117654): Implement a mechanism to request this resource
  378. // before being able to use it.
  379. virtual void SetName(const std::string& name,
  380. base::OnceClosure callback,
  381. ErrorCallback error_callback) = 0;
  382. // Indicates whether the adapter is initialized and ready to use.
  383. virtual bool IsInitialized() const = 0;
  384. // Indicates whether the adapter is actually present on the system. For the
  385. // default adapter, this indicates whether any adapter is present. An adapter
  386. // is only considered present if the address has been obtained.
  387. virtual bool IsPresent() const = 0;
  388. // Indicates whether the adapter radio can be powered. Defaults to
  389. // IsPresent(). Currently only overridden on Windows, where the adapter can be
  390. // present, but we might fail to get access to the underlying radio.
  391. virtual bool CanPower() const;
  392. // Indicates whether the adapter radio is powered.
  393. virtual bool IsPowered() const = 0;
  394. // Returns the status of the browser's Bluetooth permission status.
  395. virtual PermissionStatus GetOsPermissionStatus() const;
  396. // Requests a change to the adapter radio power. Setting |powered| to true
  397. // will turn on the radio and false will turn it off. On success, |callback|
  398. // will be called. On failure, |error_callback| will be called.
  399. //
  400. // The default implementation is meant for platforms that don't have a
  401. // callback based API. It will store pending callbacks in
  402. // |set_powered_callbacks_| and invoke SetPoweredImpl(bool) which these
  403. // platforms need to implement. Pending callbacks are only run when
  404. // RunPendingPowerCallbacks() is invoked.
  405. //
  406. // Platforms that natively support a callback based API (e.g. BlueZ and Win)
  407. // should override this method and provide their own implementation instead.
  408. //
  409. // Due to an issue with non-native APIs on Windows 10, both IsPowered() and
  410. // SetPowered() don't work correctly when run from a x86 Chrome on a x64 CPU.
  411. // See https://github.com/Microsoft/cppwinrt/issues/47 for more details.
  412. virtual void SetPowered(bool powered,
  413. base::OnceClosure callback,
  414. ErrorCallback error_callback);
  415. // Indicates whether the adapter support the LowEnergy peripheral role.
  416. virtual bool IsPeripheralRoleSupported() const;
  417. // Indicates whether the adapter radio is discoverable.
  418. virtual bool IsDiscoverable() const = 0;
  419. // Requests that the adapter change its discoverability state. If
  420. // |discoverable| is true, then it will be discoverable by other Bluetooth
  421. // devices. On successfully changing the adapter's discoverability, |callback|
  422. // will be called. On failure, |error_callback| will be called.
  423. virtual void SetDiscoverable(bool discoverable,
  424. base::OnceClosure callback,
  425. ErrorCallback error_callback) = 0;
  426. // Indicates whether the adapter is currently discovering new devices.
  427. virtual bool IsDiscovering() const = 0;
  428. // Inserts all the devices that are connected by the operating system, and not
  429. // being connected by Chromium, into |devices_|. This method is useful since
  430. // a discovery session cannot find devices that are already connected to the
  431. // computer.
  432. // TODO(crbug.com/653032): Needs to be implemented for Android and Windows.
  433. virtual std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet>
  434. RetrieveGattConnectedDevicesWithDiscoveryFilter(
  435. const BluetoothDiscoveryFilter& discovery_filter);
  436. // Requests the adapter to start a new discovery session. On success, a new
  437. // instance of BluetoothDiscoverySession will be returned to the caller via
  438. // |callback| and the adapter will be discovering nearby Bluetooth devices.
  439. // The returned BluetoothDiscoverySession is owned by the caller and it's the
  440. // owner's responsibility to properly clean it up and stop the session when
  441. // device discovery is no longer needed.
  442. //
  443. // If clients desire device discovery to run, they should always call this
  444. // method and never make it conditional on the value of IsDiscovering(), as
  445. // another client might cause discovery to stop unexpectedly. Hence, clients
  446. // should always obtain a BluetoothDiscoverySession and call
  447. // BluetoothDiscoverySession::Stop when done. When this method gets called,
  448. // device discovery may actually be in progress. Clients can call GetDevices()
  449. // and check for those with IsPaired() as false to obtain the list of devices
  450. // that have been discovered so far. Otherwise, clients can be notified of all
  451. // new and lost devices by implementing the Observer methods "DeviceAdded" and
  452. // "DeviceRemoved".
  453. //
  454. // |client_name|: The name of the application using this scan session. This
  455. // field is for logging purposes and does not affect any scanning logic, so
  456. // the value can be freely defined by the caller.
  457. void StartDiscoverySession(const std::string& client_name,
  458. DiscoverySessionCallback callback,
  459. ErrorCallback error_callback);
  460. void StartDiscoverySessionWithFilter(
  461. std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
  462. const std::string& client_name,
  463. DiscoverySessionCallback callback,
  464. ErrorCallback error_callback);
  465. // Return all discovery filters assigned to this adapter merged together.
  466. std::unique_ptr<BluetoothDiscoveryFilter> GetMergedDiscoveryFilter() const;
  467. // Requests the list of devices from the adapter. All devices are returned,
  468. // including those currently connected, those paired and all devices returned
  469. // by RetrieveGattConnectedDevicesWithDiscoveryFilter() (from the previous
  470. // call). Use the returned device pointers to determine which they are.
  471. virtual DeviceList GetDevices();
  472. virtual ConstDeviceList GetDevices() const;
  473. // Returns a pointer to the device with the given address |address| or NULL if
  474. // no such device is known.
  475. virtual BluetoothDevice* GetDevice(const std::string& address);
  476. virtual const BluetoothDevice* GetDevice(const std::string& address) const;
  477. // Returns a list of UUIDs for services registered on this adapter.
  478. // This may include UUIDs from standard profiles (e.g. A2DP) as well
  479. // as those created by CreateRfcommService and CreateL2capService.
  480. virtual UUIDList GetUUIDs() const = 0;
  481. // Possible priorities for AddPairingDelegate(), low is intended for
  482. // permanent UI and high is intended for interactive UI or applications.
  483. enum PairingDelegatePriority {
  484. PAIRING_DELEGATE_PRIORITY_LOW,
  485. PAIRING_DELEGATE_PRIORITY_HIGH
  486. };
  487. // Adds a default pairing delegate with priority |priority|. Method calls
  488. // will be made on |pairing_delegate| for incoming pairing requests if the
  489. // priority is higher than any other registered; or for those of the same
  490. // priority, the first registered.
  491. //
  492. // |pairing_delegate| must not be freed without first calling
  493. // RemovePairingDelegate().
  494. virtual void AddPairingDelegate(
  495. BluetoothDevice::PairingDelegate* pairing_delegate,
  496. PairingDelegatePriority priority);
  497. // Removes a previously added pairing delegate.
  498. virtual void RemovePairingDelegate(
  499. BluetoothDevice::PairingDelegate* pairing_delegate);
  500. // Returns the first registered pairing delegate with the highest priority,
  501. // or NULL if no delegate is registered. Used to select the delegate for
  502. // incoming pairing requests.
  503. virtual BluetoothDevice::PairingDelegate* DefaultPairingDelegate();
  504. // Creates an RFCOMM service on this adapter advertised with UUID |uuid|,
  505. // listening on channel |options.channel|, which may be left null to
  506. // automatically allocate one. The service will be advertised with
  507. // |options.name| as the English name of the service. |callback| will be
  508. // called on success with a BluetoothSocket instance that is to be owned by
  509. // the received. |error_callback| will be called on failure with a message
  510. // indicating the cause.
  511. virtual void CreateRfcommService(
  512. const BluetoothUUID& uuid,
  513. const ServiceOptions& options,
  514. CreateServiceCallback callback,
  515. CreateServiceErrorCallback error_callback) = 0;
  516. // Creates an L2CAP service on this adapter advertised with UUID |uuid|,
  517. // listening on PSM |options.psm|, which may be left null to automatically
  518. // allocate one. The service will be advertised with |options.name| as the
  519. // English name of the service. |callback| will be called on success with a
  520. // BluetoothSocket instance that is to be owned by the received.
  521. // |error_callback| will be called on failure with a message indicating the
  522. // cause.
  523. virtual void CreateL2capService(
  524. const BluetoothUUID& uuid,
  525. const ServiceOptions& options,
  526. CreateServiceCallback callback,
  527. CreateServiceErrorCallback error_callback) = 0;
  528. // Creates and registers an advertisement for broadcast over the LE channel.
  529. // The created advertisement will be returned via the success callback. An
  530. // advertisement can unregister itself at any time by calling its unregister
  531. // function.
  532. virtual void RegisterAdvertisement(
  533. std::unique_ptr<BluetoothAdvertisement::Data> advertisement_data,
  534. CreateAdvertisementCallback callback,
  535. AdvertisementErrorCallback error_callback) = 0;
  536. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  537. // Sets the interval between two consecutive advertisements. Valid ranges
  538. // for the interval are from 20ms to 10.24 seconds, with min <= max.
  539. // Note: This is a best effort. The actual interval may vary non-trivially
  540. // from the requested intervals. On some hardware, there is a minimum
  541. // interval of 100ms. The minimum and maximum values are specified by the
  542. // Core 4.2 Spec, Vol 2, Part E, Section 7.8.5.
  543. virtual void SetAdvertisingInterval(
  544. const base::TimeDelta& min,
  545. const base::TimeDelta& max,
  546. base::OnceClosure callback,
  547. AdvertisementErrorCallback error_callback) = 0;
  548. // Resets advertising on this adapter. This will unregister all existing
  549. // advertisements and will stop advertising them.
  550. virtual void ResetAdvertising(base::OnceClosure callback,
  551. AdvertisementErrorCallback error_callback) = 0;
  552. // Connect to a device with |address| that is either undiscovered or not
  553. // previously paired or connected. Callers are responsible for ensuring that
  554. // the device with |address| is available and nearby via their own out-of-band
  555. // mechanism, and should not call this method if GetDevice(address) returns
  556. // a valid reference (in which case this method will fail).
  557. virtual void ConnectDevice(
  558. const std::string& address,
  559. const absl::optional<BluetoothDevice::AddressType>& address_type,
  560. ConnectDeviceCallback callback,
  561. ErrorCallback error_callback) = 0;
  562. #endif
  563. // Returns the list of pending advertisements that are not registered yet.
  564. virtual std::vector<BluetoothAdvertisement*>
  565. GetPendingAdvertisementsForTesting() const;
  566. // Returns the local GATT services associated with this adapter with the
  567. // given identifier. Returns NULL if the service doesn't exist.
  568. virtual BluetoothLocalGattService* GetGattService(
  569. const std::string& identifier) const = 0;
  570. // The following methods are used to send various events to observers.
  571. void NotifyAdapterPresentChanged(bool present);
  572. void NotifyAdapterPoweredChanged(bool powered);
  573. void NotifyDeviceChanged(BluetoothDevice* device);
  574. void NotifyAdapterDiscoveryChangeCompletedForTesting();
  575. #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
  576. void NotifyDevicePairedChanged(BluetoothDevice* device,
  577. bool new_paired_status);
  578. void NotifyDeviceConnectedStateChanged(BluetoothDevice* device,
  579. bool is_connected);
  580. #endif
  581. #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
  582. void NotifyDeviceBatteryChanged(BluetoothDevice* device,
  583. BluetoothDevice::BatteryType type);
  584. #endif
  585. #if BUILDFLAG(IS_CHROMEOS)
  586. void NotifyDeviceIsBlockedByPolicyChanged(BluetoothDevice* device,
  587. bool new_blocked_status);
  588. #endif
  589. void NotifyGattServiceAdded(BluetoothRemoteGattService* service);
  590. void NotifyGattServiceRemoved(BluetoothRemoteGattService* service);
  591. void NotifyGattServiceChanged(BluetoothRemoteGattService* service);
  592. void NotifyGattServicesDiscovered(BluetoothDevice* device);
  593. void NotifyGattDiscoveryComplete(BluetoothRemoteGattService* service);
  594. void NotifyGattCharacteristicAdded(
  595. BluetoothRemoteGattCharacteristic* characteristic);
  596. void NotifyGattCharacteristicRemoved(
  597. BluetoothRemoteGattCharacteristic* characteristic);
  598. void NotifyGattDescriptorAdded(BluetoothRemoteGattDescriptor* descriptor);
  599. void NotifyGattDescriptorRemoved(BluetoothRemoteGattDescriptor* descriptor);
  600. void NotifyGattCharacteristicValueChanged(
  601. BluetoothRemoteGattCharacteristic* characteristic,
  602. const std::vector<uint8_t>& value);
  603. void NotifyGattDescriptorValueChanged(
  604. BluetoothRemoteGattDescriptor* descriptor,
  605. const std::vector<uint8_t>& value);
  606. #if BUILDFLAG(IS_CHROMEOS)
  607. void NotifyLowEnergyScanSessionHardwareOffloadingStatusChanged(
  608. LowEnergyScanSessionHardwareOffloadingStatus status);
  609. // Set a service allowlist by specifying services UUIDs. When this is called,
  610. // existing connections will be disconnected and services not in the allowlist
  611. // will be blocked. Device property |IsBlockedByPolicy| will be True if some
  612. // of the auto-connect services are blocked, False otherwise.
  613. virtual void SetServiceAllowList(const UUIDList& uuids,
  614. base::OnceClosure callback,
  615. ErrorCallback error_callback) = 0;
  616. // Returns |kSupported| if the device supports the offloading of filtering and
  617. // other scanning logic to the Bluetooth hardware. This brings the benefit of
  618. // reduced power consumption for BluetoothLowEnergyScanSession. Returns
  619. // |kNotSupported| if hardware offloading is not available, in which case
  620. // BluetoothLowEnergyScanSession will operate with higher power
  621. // consumption. |kUndetermined| indicates the status can not currently be
  622. // determined (such as when the adapter is not present), and the client should
  623. // retry.
  624. //
  625. // Consumers should check this value before
  626. // creating a BluetoothLowEnergyScanSession and consider ways to mitigate
  627. // power usage, especially if the scan session is intended to be long-running.
  628. virtual LowEnergyScanSessionHardwareOffloadingStatus
  629. GetLowEnergyScanSessionHardwareOffloadingStatus() = 0;
  630. // Starts a low energy scanning session that will notify the client on session
  631. // started, session invalidated, device found and device lost events via the
  632. // |delegate|.
  633. //
  634. // The client controls the lifetime of the session (except on unexpected
  635. // invalidation, see below). The client ends a scan session by destroying the
  636. // returned instance.
  637. //
  638. // A session cannot recover once the
  639. // BluetoothLowEnergyScanSession::Delegate::OnSessionInvalidated() callback
  640. // has been invoked. Invalidation can happen if the platform unexpectedly
  641. // cleans up the scan session due to a firmware crash, etc.. If a client wants
  642. // an identical scanning session, it should discard its newly invalidated
  643. // BluetoothLowEnergyScanSession and create a new one by calling
  644. // StartLowEnergyScanSession() again.
  645. virtual std::unique_ptr<BluetoothLowEnergyScanSession>
  646. StartLowEnergyScanSession(
  647. std::unique_ptr<BluetoothLowEnergyScanFilter> filter,
  648. base::WeakPtr<BluetoothLowEnergyScanSession::Delegate> delegate) = 0;
  649. #endif // BUILDFLAG(IS_CHROMEOS)
  650. #if BUILDFLAG(IS_CHROMEOS_ASH)
  651. // Set the adapter name to one chosen from the system information. Only Ash
  652. // needs to do this.
  653. virtual void SetStandardChromeOSAdapterName() = 0;
  654. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  655. // The timeout in seconds used by RemoveTimedOutDevices.
  656. static const base::TimeDelta timeoutSec;
  657. // This struct is meant to hold any possible callback from a discovery
  658. // request. The purpose of this is to consolidate all discovery request
  659. // callbacks into one array that can be handled all at once when the state
  660. // desired from all requests is achieved or an error is thrown.
  661. struct StartOrStopDiscoveryCallback {
  662. StartOrStopDiscoveryCallback(base::OnceClosure start_callback,
  663. ErrorCallback start_error_callback);
  664. StartOrStopDiscoveryCallback(
  665. base::OnceClosure stop_callback,
  666. DiscoverySessionErrorCallback stop_error_callback);
  667. ~StartOrStopDiscoveryCallback();
  668. // The success callback for a start discovery request.
  669. base::OnceClosure start_callback;
  670. // The success callback for a stop discovery request.
  671. base::OnceClosure stop_callback;
  672. // The error callback for a start discovery request.
  673. ErrorCallback start_error_callback;
  674. // The error callback for a stop discovery request.
  675. DiscoverySessionErrorCallback stop_error_callback;
  676. };
  677. protected:
  678. friend class base::RefCounted<BluetoothAdapter>;
  679. friend class BluetoothAdapterFactory;
  680. friend class BluetoothDiscoverySession;
  681. friend class BluetoothTestBase;
  682. using DevicesMap =
  683. std::unordered_map<std::string, std::unique_ptr<BluetoothDevice>>;
  684. using PairingDelegatePair =
  685. std::pair<BluetoothDevice::PairingDelegate*, PairingDelegatePriority>;
  686. using CallbackQueue =
  687. base::queue<std::unique_ptr<StartOrStopDiscoveryCallback>>;
  688. // Implementations on Android and macOS need to store pending SetPowered()
  689. // callbacks until an appropriate event is received, due to a lack of blocking
  690. // or callback supporting platform APIs. Declaring the struct here allows
  691. // Android and macOS to share the implementation.
  692. struct SetPoweredCallbacks {
  693. SetPoweredCallbacks();
  694. ~SetPoweredCallbacks();
  695. bool powered = false;
  696. base::OnceClosure callback;
  697. ErrorCallback error_callback;
  698. };
  699. BluetoothAdapter();
  700. virtual ~BluetoothAdapter();
  701. virtual base::WeakPtr<BluetoothAdapter> GetWeakPtr() = 0;
  702. // This method calls into platform specific logic on macOS and Android where
  703. // pending SetPowered() callbacks need to be stored explicitly.
  704. virtual bool SetPoweredImpl(bool powered) = 0;
  705. // Called by macOS, Android and WinRT once the specific powered state events
  706. // are received or an error occurred. Clears out pending callbacks.
  707. void RunPendingPowerCallbacks();
  708. // Internal methods for initiating and terminating device discovery sessions.
  709. // An implementation of BluetoothAdapter keeps an internal reference count to
  710. // make sure that the underlying controller is constantly searching for nearby
  711. // devices and retrieving information from them as long as there are clients
  712. // who have requested discovery. These methods behave in the following way:
  713. //
  714. // On a call to StartScanWithFilter:
  715. // - This should only be called when we get the first request to start the
  716. // scan with only the initial filter in that request.
  717. // - This function should do the OS specific things to get the filter
  718. // started.
  719. // - When finished it should callback with success or the appropriate
  720. // Output for an error.
  721. // On a call to UpdateFilter:
  722. // - The scan should already be started or at least starting.
  723. // - This function takes in a filter and should do all the OS specifics
  724. // needed to update the scan with the new filter.
  725. // - When finished it should call the callback with success or the
  726. // appropriate output for an error
  727. //
  728. // On a call to StopScan:
  729. // - Make a request to the physical adapter that we no longer needs to
  730. // be scanning
  731. // - When finished it should callback with success. If an error is thrown
  732. // we still return success to the user and update our internal state to
  733. // say that we are not discovering.
  734. virtual void StartScanWithFilter(
  735. std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
  736. DiscoverySessionResultCallback callback) = 0;
  737. virtual void UpdateFilter(
  738. std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
  739. DiscoverySessionResultCallback callback) = 0;
  740. virtual void StopScan(DiscoverySessionResultCallback callback) = 0;
  741. // Removes the |discovery_session| from |discovery_sessions_| and updates
  742. // accordingly
  743. void RemoveDiscoverySession(BluetoothDiscoverySession* discovery_session,
  744. base::OnceClosure callback,
  745. DiscoverySessionErrorCallback error_callback);
  746. // Helper function that short circuits a successful callback if the filter is
  747. // the same as the current filter.
  748. void MaybeUpdateFilter(
  749. std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
  750. DiscoverySessionResultCallback callback);
  751. // Called by RemovePairingDelegate() in order to perform any class-specific
  752. // internal functionality necessary to remove the pairing delegate, such as
  753. // cleaning up ongoing pairings using it.
  754. virtual void RemovePairingDelegateInternal(
  755. BluetoothDevice::PairingDelegate* pairing_delegate) = 0;
  756. // Marks all known DiscoverySession instances as inactive. Called by
  757. // BluetoothAdapter in the event that the adapter unexpectedly stops
  758. // discovering. This should be called by all platform implementations.
  759. void MarkDiscoverySessionsAsInactive();
  760. void DeleteDeviceForTesting(const std::string& address);
  761. // Removes from |devices_| any previously paired, connected or seen
  762. // devices which are no longer present. Notifies observers. Note:
  763. // this is only used by platforms where there is no notification of
  764. // lost devices.
  765. void RemoveTimedOutDevices();
  766. int NumDiscoverySessions() const;
  767. // Number of DiscoverySessions with the status of SCANNING.
  768. int NumScanningDiscoverySessions() const;
  769. // UI thread task runner.
  770. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
  771. // Observers of BluetoothAdapter, notified from implementation subclasses.
  772. base::ObserverList<device::BluetoothAdapter::Observer>::Unchecked observers_;
  773. // Devices paired with, connected to, discovered by, or visible to the
  774. // adapter. The key is the Bluetooth address of the device and the value is
  775. // the BluetoothDevice object whose lifetime is managed by the adapter
  776. // instance.
  777. DevicesMap devices_;
  778. // Default pairing delegates registered with the adapter.
  779. std::list<PairingDelegatePair> pairing_delegates_;
  780. // SetPowered() callbacks, only relevant for macOS and Android.
  781. std::unique_ptr<SetPoweredCallbacks> set_powered_callbacks_;
  782. // List of active DiscoverySession objects. This is used to notify sessions to
  783. // become inactive in case of an unexpected change to the adapter discovery
  784. // state. We keep raw pointers, with the invariant that a DiscoverySession
  785. // will remove itself from this list when it gets destroyed or becomes
  786. // inactive by calling DiscoverySessionBecameInactive(), hence no pointers to
  787. // deallocated sessions are kept.
  788. std::set<BluetoothDiscoverySession*> discovery_sessions_;
  789. private:
  790. // This is the callback for all OS level calls to StartScanWithFilter,
  791. // UpdateFilter, and StopScan. It updates the state accordingly, calls all
  792. // appropriate callbacks, and calls ProcessDiscoveryQueue().
  793. void OnDiscoveryChangeComplete(bool is_error,
  794. UMABluetoothDiscoverySessionOutcome outcome);
  795. // This method processes all queued requests that have been waiting for a
  796. // process to finish.
  797. void ProcessDiscoveryQueue();
  798. // Utility method used to call all callbacks in the case of an error in a
  799. // process
  800. void NotifyDiscoveryError(CallbackQueue queue);
  801. // Utility function to update our internal state after a process has
  802. // completed(example: kStarting -> kDiscovering)
  803. void UpdateDiscoveryState(bool is_error);
  804. // List of callbacks for requests that have been queued up and are awaiting a
  805. // process to finish before they can begin the request
  806. CallbackQueue discovery_callback_queue_;
  807. // List of callbacks whose requests are currently being processed by the OS
  808. // level adapter
  809. CallbackQueue callbacks_awaiting_response_;
  810. // Discovery filter currently being used by the adapter
  811. device::BluetoothDiscoveryFilter current_discovery_filter_;
  812. // Discovery filter that is about to be set in the OS level adapter. After
  813. // the process that is implementing this feature is finished this will become
  814. // the |current_discovery_filter_|.
  815. device::BluetoothDiscoveryFilter filter_being_set_;
  816. // True, if there is a pending request to start or stop discovery.
  817. bool discovery_request_pending_ = false;
  818. // enum used to track our internal discovery state.
  819. DiscoveryState internal_discovery_state_ = DiscoveryState::kIdle;
  820. };
  821. } // namespace device
  822. #endif // DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_H_