QUIC - cleanup changes to sync chromium tree with internal source.
[chromium-blink-merge.git] / device / bluetooth / bluetooth_adapter.h
blob3c74ff9ad69f67ecbcd1449612c143b238bb1ac7
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.
5 #ifndef DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_H_
6 #define DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_H_
8 #include <list>
9 #include <map>
10 #include <set>
11 #include <string>
12 #include <utility>
14 #include "base/callback.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/weak_ptr.h"
17 #include "device/bluetooth/bluetooth_advertisement.h"
18 #include "device/bluetooth/bluetooth_audio_sink.h"
19 #include "device/bluetooth/bluetooth_device.h"
20 #include "device/bluetooth/bluetooth_export.h"
22 namespace device {
24 class BluetoothAdvertisement;
25 class BluetoothDiscoveryFilter;
26 class BluetoothDiscoverySession;
27 class BluetoothGattCharacteristic;
28 class BluetoothGattDescriptor;
29 class BluetoothGattService;
30 class BluetoothSocket;
31 class BluetoothUUID;
32 struct BluetoothAdapterDeleter;
33 enum class UMABluetoothDiscoverySessionOutcome;
35 // BluetoothAdapter represents a local Bluetooth adapter which may be used to
36 // interact with remote Bluetooth devices. As well as providing support for
37 // determining whether an adapter is present and whether the radio is powered,
38 // this class also provides support for obtaining the list of remote devices
39 // known to the adapter, discovering new devices, and providing notification of
40 // updates to device information.
41 class DEVICE_BLUETOOTH_EXPORT BluetoothAdapter
42 : public base::RefCounted<BluetoothAdapter> {
43 public:
44 // Interface for observing changes from bluetooth adapters.
45 class DEVICE_BLUETOOTH_EXPORT Observer {
46 public:
47 virtual ~Observer() {}
49 // Called when the presence of the adapter |adapter| changes. When |present|
50 // is true the adapter is now present, false means the adapter has been
51 // removed from the system.
52 virtual void AdapterPresentChanged(BluetoothAdapter* adapter,
53 bool present) {}
55 // Called when the radio power state of the adapter |adapter| changes. When
56 // |powered| is true the adapter radio is powered, false means the adapter
57 // radio is off.
58 virtual void AdapterPoweredChanged(BluetoothAdapter* adapter,
59 bool powered) {}
61 // Called when the discoverability state of the adapter |adapter| changes.
62 // When |discoverable| is true the adapter is discoverable by other devices,
63 // false means the adapter is not discoverable.
64 virtual void AdapterDiscoverableChanged(BluetoothAdapter* adapter,
65 bool discoverable) {}
67 // Called when the discovering state of the adapter |adapter| changes. When
68 // |discovering| is true the adapter is seeking new devices, false means it
69 // is not.
70 virtual void AdapterDiscoveringChanged(BluetoothAdapter* adapter,
71 bool discovering) {}
73 // Called when a new device |device| is added to the adapter |adapter|,
74 // either because it has been discovered or a connection made. |device|
75 // should not be cached. Instead, copy its Bluetooth address.
76 virtual void DeviceAdded(BluetoothAdapter* adapter,
77 BluetoothDevice* device) {}
79 // Called when properties of the device |device| known to the adapter
80 // |adapter| change. |device| should not be cached. Instead, copy its
81 // Bluetooth address.
82 virtual void DeviceChanged(BluetoothAdapter* adapter,
83 BluetoothDevice* device) {}
85 // Called when the device |device| is removed from the adapter |adapter|,
86 // either as a result of a discovered device being lost between discovering
87 // phases or pairing information deleted. |device| should not be
88 // cached. Instead, copy its Bluetooth address.
89 virtual void DeviceRemoved(BluetoothAdapter* adapter,
90 BluetoothDevice* device) {}
92 // Called when a new GATT service |service| is added to the device |device|,
93 // as the service is received from the device. Don't cache |service|. Store
94 // its identifier instead (i.e. BluetoothGattService::GetIdentifier).
95 virtual void GattServiceAdded(BluetoothAdapter* adapter,
96 BluetoothDevice* device,
97 BluetoothGattService* service) {}
99 // Called when the GATT service |service| is removed from the device
100 // |device|. This can happen if the attribute database of the remote device
101 // changes or when |device| gets removed.
102 virtual void GattServiceRemoved(BluetoothAdapter* adapter,
103 BluetoothDevice* device,
104 BluetoothGattService* service) {}
106 // Called when all characteristic and descriptor discovery procedures are
107 // known to be completed for the GATT service |service|. This method will be
108 // called after the initial discovery of a GATT service and will usually be
109 // preceded by calls to GattCharacteristicAdded and GattDescriptorAdded.
110 virtual void GattDiscoveryCompleteForService(
111 BluetoothAdapter* adapter,
112 BluetoothGattService* service) {}
114 // Called when properties of the remote GATT service |service| have changed.
115 // This will get called for properties such as UUID, as well as for changes
116 // to the list of known characteristics and included services. Observers
117 // should read all GATT characteristic and descriptors objects and do any
118 // necessary set up required for a changed service.
119 virtual void GattServiceChanged(BluetoothAdapter* adapter,
120 BluetoothGattService* service) {}
122 // Called when the remote GATT characteristic |characteristic| has been
123 // discovered. Use this to issue any initial read/write requests to the
124 // characteristic but don't cache the pointer as it may become invalid.
125 // Instead, use the specially assigned identifier to obtain a characteristic
126 // and cache that identifier as necessary, as it can be used to retrieve the
127 // characteristic from its GATT service. The number of characteristics with
128 // the same UUID belonging to a service depends on the particular profile
129 // the remote device implements, hence the client of a GATT based profile
130 // will usually operate on the whole set of characteristics and not just
131 // one.
132 virtual void GattCharacteristicAdded(
133 BluetoothAdapter* adapter,
134 BluetoothGattCharacteristic* characteristic) {}
136 // Called when a GATT characteristic |characteristic| has been removed from
137 // the system.
138 virtual void GattCharacteristicRemoved(
139 BluetoothAdapter* adapter,
140 BluetoothGattCharacteristic* characteristic) {}
142 // Called when the remote GATT characteristic descriptor |descriptor| has
143 // been discovered. Don't cache the arguments as the pointers may become
144 // invalid. Instead, use the specially assigned identifier to obtain a
145 // descriptor and cache that identifier as necessary.
146 virtual void GattDescriptorAdded(BluetoothAdapter* adapter,
147 BluetoothGattDescriptor* descriptor) {}
149 // Called when a GATT characteristic descriptor |descriptor| has been
150 // removed from the system.
151 virtual void GattDescriptorRemoved(BluetoothAdapter* adapter,
152 BluetoothGattDescriptor* descriptor) {}
154 // Called when the value of a characteristic has changed. This might be a
155 // result of a read/write request to, or a notification/indication from, a
156 // remote GATT characteristic.
157 virtual void GattCharacteristicValueChanged(
158 BluetoothAdapter* adapter,
159 BluetoothGattCharacteristic* characteristic,
160 const std::vector<uint8>& value) {}
162 // Called when the value of a characteristic descriptor has been updated.
163 virtual void GattDescriptorValueChanged(BluetoothAdapter* adapter,
164 BluetoothGattDescriptor* descriptor,
165 const std::vector<uint8>& value) {}
168 // Used to configure a listening servie.
169 struct DEVICE_BLUETOOTH_EXPORT ServiceOptions {
170 ServiceOptions();
171 ~ServiceOptions();
173 scoped_ptr<int> channel;
174 scoped_ptr<int> psm;
175 scoped_ptr<std::string> name;
178 // The ErrorCallback is used for methods that can fail in which case it is
179 // called, in the success case the callback is simply not called.
180 typedef base::Closure ErrorCallback;
182 // The InitCallback is used to trigger a callback after asynchronous
183 // initialization, if initialization is asynchronous on the platform.
184 typedef base::Callback<void()> InitCallback;
186 typedef base::Callback<void(scoped_ptr<BluetoothDiscoverySession>)>
187 DiscoverySessionCallback;
188 typedef std::vector<BluetoothDevice*> DeviceList;
189 typedef std::vector<const BluetoothDevice*> ConstDeviceList;
190 typedef base::Callback<void(scoped_refptr<BluetoothSocket>)>
191 CreateServiceCallback;
192 typedef base::Callback<void(const std::string& message)>
193 CreateServiceErrorCallback;
194 typedef base::Callback<void(scoped_refptr<BluetoothAudioSink>)>
195 AcquiredCallback;
196 typedef base::Callback<void(scoped_refptr<BluetoothAdvertisement>)>
197 CreateAdvertisementCallback;
198 typedef base::Callback<void(BluetoothAdvertisement::ErrorCode)>
199 CreateAdvertisementErrorCallback;
201 // Returns a weak pointer to a new adapter. For platforms with asynchronous
202 // initialization, the returned adapter will run the |init_callback| once
203 // asynchronous initialization is complete.
204 // Caution: The returned pointer also transfers ownership of the adapter. The
205 // caller is expected to call |AddRef()| on the returned pointer, typically by
206 // storing it into a |scoped_refptr|.
207 static base::WeakPtr<BluetoothAdapter> CreateAdapter(
208 const InitCallback& init_callback);
210 // Returns a weak pointer to an existing adapter for testing purposes only.
211 base::WeakPtr<BluetoothAdapter> GetWeakPtrForTesting();
213 #if defined(OS_CHROMEOS)
214 // Shutdown the adapter: tear down and clean up all objects owned by
215 // BluetoothAdapter. After this call, the BluetoothAdapter will behave as if
216 // no Bluetooth controller exists in the local system. |IsPresent| will return
217 // false.
218 virtual void Shutdown();
219 #endif
221 // Adds and removes observers for events on this bluetooth adapter. If
222 // monitoring multiple adapters, check the |adapter| parameter of observer
223 // methods to determine which adapter is issuing the event.
224 virtual void AddObserver(BluetoothAdapter::Observer* observer);
225 virtual void RemoveObserver(BluetoothAdapter::Observer* observer);
227 // The address of this adapter. The address format is "XX:XX:XX:XX:XX:XX",
228 // where each XX is a hexadecimal number.
229 virtual std::string GetAddress() const = 0;
231 // The name of the adapter.
232 virtual std::string GetName() const = 0;
234 // Set the human-readable name of the adapter to |name|. On success,
235 // |callback| will be called. On failure, |error_callback| will be called.
236 virtual void SetName(const std::string& name,
237 const base::Closure& callback,
238 const ErrorCallback& error_callback) = 0;
240 // Indicates whether the adapter is initialized and ready to use.
241 virtual bool IsInitialized() const = 0;
243 // Indicates whether the adapter is actually present on the system. For the
244 // default adapter, this indicates whether any adapter is present. An adapter
245 // is only considered present if the address has been obtained.
246 virtual bool IsPresent() const = 0;
248 // Indicates whether the adapter radio is powered.
249 virtual bool IsPowered() const = 0;
251 // Requests a change to the adapter radio power. Setting |powered| to true
252 // will turn on the radio and false will turn it off. On success, |callback|
253 // will be called. On failure, |error_callback| will be called.
254 virtual void SetPowered(bool powered,
255 const base::Closure& callback,
256 const ErrorCallback& error_callback) = 0;
258 // Indicates whether the adapter radio is discoverable.
259 virtual bool IsDiscoverable() const = 0;
261 // Requests that the adapter change its discoverability state. If
262 // |discoverable| is true, then it will be discoverable by other Bluetooth
263 // devices. On successfully changing the adapter's discoverability, |callback|
264 // will be called. On failure, |error_callback| will be called.
265 virtual void SetDiscoverable(bool discoverable,
266 const base::Closure& callback,
267 const ErrorCallback& error_callback) = 0;
269 // Indicates whether the adapter is currently discovering new devices.
270 virtual bool IsDiscovering() const = 0;
272 // Requests the adapter to start a new discovery session. On success, a new
273 // instance of BluetoothDiscoverySession will be returned to the caller via
274 // |callback| and the adapter will be discovering nearby Bluetooth devices.
275 // The returned BluetoothDiscoverySession is owned by the caller and it's the
276 // owner's responsibility to properly clean it up and stop the session when
277 // device discovery is no longer needed.
279 // If clients desire device discovery to run, they should always call this
280 // method and never make it conditional on the value of IsDiscovering(), as
281 // another client might cause discovery to stop unexpectedly. Hence, clients
282 // should always obtain a BluetoothDiscoverySession and call
283 // BluetoothDiscoverySession::Stop when done. When this method gets called,
284 // device discovery may actually be in progress. Clients can call GetDevices()
285 // and check for those with IsPaired() as false to obtain the list of devices
286 // that have been discovered so far. Otherwise, clients can be notified of all
287 // new and lost devices by implementing the Observer methods "DeviceAdded" and
288 // "DeviceRemoved".
289 virtual void StartDiscoverySession(const DiscoverySessionCallback& callback,
290 const ErrorCallback& error_callback);
291 virtual void StartDiscoverySessionWithFilter(
292 scoped_ptr<BluetoothDiscoveryFilter> discovery_filter,
293 const DiscoverySessionCallback& callback,
294 const ErrorCallback& error_callback);
296 // Return all discovery filters assigned to this adapter merged together.
297 scoped_ptr<BluetoothDiscoveryFilter> GetMergedDiscoveryFilter() const;
299 // Works like GetMergedDiscoveryFilter, but doesn't take |masked_filter| into
300 // account. |masked_filter| is compared by pointer, and must be a member of
301 // active session.
302 scoped_ptr<BluetoothDiscoveryFilter> GetMergedDiscoveryFilterMasked(
303 BluetoothDiscoveryFilter* masked_filter) const;
305 // Requests the list of devices from the adapter. All devices are returned,
306 // including those currently connected and those paired. Use the returned
307 // device pointers to determine which they are.
308 virtual DeviceList GetDevices();
309 virtual ConstDeviceList GetDevices() const;
311 // Returns a pointer to the device with the given address |address| or NULL if
312 // no such device is known.
313 virtual BluetoothDevice* GetDevice(const std::string& address);
314 virtual const BluetoothDevice* GetDevice(const std::string& address) const;
316 // Possible priorities for AddPairingDelegate(), low is intended for
317 // permanent UI and high is intended for interactive UI or applications.
318 enum PairingDelegatePriority {
319 PAIRING_DELEGATE_PRIORITY_LOW,
320 PAIRING_DELEGATE_PRIORITY_HIGH
323 // Adds a default pairing delegate with priority |priority|. Method calls
324 // will be made on |pairing_delegate| for incoming pairing requests if the
325 // priority is higher than any other registered; or for those of the same
326 // priority, the first registered.
328 // |pairing_delegate| must not be freed without first calling
329 // RemovePairingDelegate().
330 virtual void AddPairingDelegate(
331 BluetoothDevice::PairingDelegate* pairing_delegate,
332 PairingDelegatePriority priority);
334 // Removes a previously added pairing delegate.
335 virtual void RemovePairingDelegate(
336 BluetoothDevice::PairingDelegate* pairing_delegate);
338 // Returns the first registered pairing delegate with the highest priority,
339 // or NULL if no delegate is registered. Used to select the delegate for
340 // incoming pairing requests.
341 virtual BluetoothDevice::PairingDelegate* DefaultPairingDelegate();
343 // Creates an RFCOMM service on this adapter advertised with UUID |uuid|,
344 // listening on channel |options.channel|, which may be left null to
345 // automatically allocate one. The service will be advertised with
346 // |options.name| as the English name of the service. |callback| will be
347 // called on success with a BluetoothSocket instance that is to be owned by
348 // the received. |error_callback| will be called on failure with a message
349 // indicating the cause.
350 virtual void CreateRfcommService(
351 const BluetoothUUID& uuid,
352 const ServiceOptions& options,
353 const CreateServiceCallback& callback,
354 const CreateServiceErrorCallback& error_callback) = 0;
356 // Creates an L2CAP service on this adapter advertised with UUID |uuid|,
357 // listening on PSM |options.psm|, which may be left null to automatically
358 // allocate one. The service will be advertised with |options.name| as the
359 // English name of the service. |callback| will be called on success with a
360 // BluetoothSocket instance that is to be owned by the received.
361 // |error_callback| will be called on failure with a message indicating the
362 // cause.
363 virtual void CreateL2capService(
364 const BluetoothUUID& uuid,
365 const ServiceOptions& options,
366 const CreateServiceCallback& callback,
367 const CreateServiceErrorCallback& error_callback) = 0;
369 // Creates and registers a BluetoothAudioSink with |options|. If the fields in
370 // |options| are not specified, the default values will be used. |callback|
371 // will be called on success with a BluetoothAudioSink which is to be owned by
372 // the caller of this method. |error_callback| will be called on failure with
373 // a message indicating the cause.
374 virtual void RegisterAudioSink(
375 const BluetoothAudioSink::Options& options,
376 const AcquiredCallback& callback,
377 const BluetoothAudioSink::ErrorCallback& error_callback) = 0;
379 // Creates and registers an advertisement for broadcast over the LE channel.
380 // The created advertisement will be returned via the success callback.
381 virtual void RegisterAdvertisement(
382 scoped_ptr<BluetoothAdvertisement::Data> advertisement_data,
383 const CreateAdvertisementCallback& callback,
384 const CreateAdvertisementErrorCallback& error_callback) = 0;
386 protected:
387 friend class base::RefCounted<BluetoothAdapter>;
388 friend class BluetoothDiscoverySession;
390 typedef std::map<const std::string, BluetoothDevice*> DevicesMap;
391 typedef std::pair<BluetoothDevice::PairingDelegate*, PairingDelegatePriority>
392 PairingDelegatePair;
393 typedef base::Callback<void(UMABluetoothDiscoverySessionOutcome)>
394 DiscoverySessionErrorCallback;
396 BluetoothAdapter();
397 virtual ~BluetoothAdapter();
399 // Internal methods for initiating and terminating device discovery sessions.
400 // An implementation of BluetoothAdapter keeps an internal reference count to
401 // make sure that the underlying controller is constantly searching for nearby
402 // devices and retrieving information from them as long as there are clients
403 // who have requested discovery. These methods behave in the following way:
405 // On a call to AddDiscoverySession:
406 // - If there is a pending request to the subsystem, queue this request to
407 // execute once the pending requests are done.
408 // - If the count is 0, issue a request to the subsystem to start
409 // device discovery. On success, increment the count to 1.
410 // - If the count is greater than 0, increment the count and return
411 // success.
412 // As long as the count is non-zero, the underlying controller will be
413 // discovering for devices. This means that Chrome will restart device
414 // scan and inquiry sessions if they ever end, unless these sessions
415 // terminate due to an unexpected reason.
417 // On a call to RemoveDiscoverySession:
418 // - If there is a pending request to the subsystem, queue this request to
419 // execute once the pending requests are done.
420 // - If the count is 0, return failure, as there is no active discovery
421 // session.
422 // - If the count is 1, issue a request to the subsystem to stop device
423 // discovery and decrement the count to 0 on success.
424 // - If the count is greater than 1, decrement the count and return
425 // success.
427 // |discovery_filter| passed to AddDiscoverySession and RemoveDiscoverySession
428 // is owned by other objects and shall not be freed. When the count is
429 // greater than 0 and AddDiscoverySession or RemoveDiscoverySession is called
430 // the filter being used by the underlying controller must be updated.
432 // These methods invoke |callback| for success and |error_callback| for
433 // failures.
434 virtual void AddDiscoverySession(
435 BluetoothDiscoveryFilter* discovery_filter,
436 const base::Closure& callback,
437 const DiscoverySessionErrorCallback& error_callback) = 0;
438 virtual void RemoveDiscoverySession(
439 BluetoothDiscoveryFilter* discovery_filter,
440 const base::Closure& callback,
441 const DiscoverySessionErrorCallback& error_callback) = 0;
443 // Used to set and update the discovery filter used by the underlying
444 // Bluetooth controller.
445 virtual void SetDiscoveryFilter(
446 scoped_ptr<BluetoothDiscoveryFilter> discovery_filter,
447 const base::Closure& callback,
448 const DiscoverySessionErrorCallback& error_callback) = 0;
450 // Called by RemovePairingDelegate() in order to perform any class-specific
451 // internal functionality necessary to remove the pairing delegate, such as
452 // cleaning up ongoing pairings using it.
453 virtual void RemovePairingDelegateInternal(
454 BluetoothDevice::PairingDelegate* pairing_delegate) = 0;
456 // Success callback passed to AddDiscoverySession by StartDiscoverySession.
457 void OnStartDiscoverySession(
458 scoped_ptr<BluetoothDiscoveryFilter> discovery_filter,
459 const DiscoverySessionCallback& callback);
461 // Error callback passed to AddDiscoverySession by StartDiscoverySession.
462 void OnStartDiscoverySessionError(
463 const ErrorCallback& callback,
464 UMABluetoothDiscoverySessionOutcome outcome);
466 // Marks all known DiscoverySession instances as inactive. Called by
467 // BluetoothAdapter in the event that the adapter unexpectedly stops
468 // discovering. This should be called by all platform implementations.
469 void MarkDiscoverySessionsAsInactive();
471 // Removes |discovery_session| from |discovery_sessions_|, if its in there.
472 // Called by DiscoverySession when an instance is destroyed or becomes
473 // inactive.
474 void DiscoverySessionBecameInactive(
475 BluetoothDiscoverySession* discovery_session);
477 // Observers of BluetoothAdapter, notified from implementation subclasses.
478 base::ObserverList<device::BluetoothAdapter::Observer> observers_;
480 // Devices paired with, connected to, discovered by, or visible to the
481 // adapter. The key is the Bluetooth address of the device and the value is
482 // the BluetoothDevice object whose lifetime is managed by the adapter
483 // instance.
484 DevicesMap devices_;
486 // Default pairing delegates registered with the adapter.
487 std::list<PairingDelegatePair> pairing_delegates_;
489 private:
490 // Histograms the result of StartDiscoverySession.
491 static void RecordBluetoothDiscoverySessionStartOutcome(
492 UMABluetoothDiscoverySessionOutcome outcome);
494 // Histograms the result of BluetoothDiscoverySession::Stop.
495 static void RecordBluetoothDiscoverySessionStopOutcome(
496 UMABluetoothDiscoverySessionOutcome outcome);
498 // Return all discovery filters assigned to this adapter merged together.
499 // If |omit| is true, |discovery_filter| will not be processed.
500 scoped_ptr<BluetoothDiscoveryFilter> GetMergedDiscoveryFilterHelper(
501 const BluetoothDiscoveryFilter* discovery_filter,
502 bool omit) const;
504 // List of active DiscoverySession objects. This is used to notify sessions to
505 // become inactive in case of an unexpected change to the adapter discovery
506 // state. We keep raw pointers, with the invariant that a DiscoverySession
507 // will remove itself from this list when it gets destroyed or becomes
508 // inactive by calling DiscoverySessionBecameInactive(), hence no pointers to
509 // deallocated sessions are kept.
510 std::set<BluetoothDiscoverySession*> discovery_sessions_;
512 // Note: This should remain the last member so it'll be destroyed and
513 // invalidate its weak pointers before any other members are destroyed.
514 base::WeakPtrFactory<BluetoothAdapter> weak_ptr_factory_;
517 } // namespace device
519 #endif // DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_H_