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_
14 #include "base/callback.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/weak_ptr.h"
17 #include "device/bluetooth/bluetooth_audio_sink.h"
18 #include "device/bluetooth/bluetooth_device.h"
19 #include "device/bluetooth/bluetooth_export.h"
23 class BluetoothDiscoveryFilter
;
24 class BluetoothDiscoverySession
;
25 class BluetoothGattCharacteristic
;
26 class BluetoothGattDescriptor
;
27 class BluetoothGattService
;
28 class BluetoothSocket
;
30 struct BluetoothAdapterDeleter
;
32 // BluetoothAdapter represents a local Bluetooth adapter which may be used to
33 // interact with remote Bluetooth devices. As well as providing support for
34 // determining whether an adapter is present and whether the radio is powered,
35 // this class also provides support for obtaining the list of remote devices
36 // known to the adapter, discovering new devices, and providing notification of
37 // updates to device information.
38 class DEVICE_BLUETOOTH_EXPORT BluetoothAdapter
39 : public base::RefCounted
<BluetoothAdapter
> {
41 // Interface for observing changes from bluetooth adapters.
44 virtual ~Observer() {}
46 // Called when the presence of the adapter |adapter| changes. When |present|
47 // is true the adapter is now present, false means the adapter has been
48 // removed from the system.
49 virtual void AdapterPresentChanged(BluetoothAdapter
* adapter
,
52 // Called when the radio power state of the adapter |adapter| changes. When
53 // |powered| is true the adapter radio is powered, false means the adapter
55 virtual void AdapterPoweredChanged(BluetoothAdapter
* adapter
,
58 // Called when the discoverability state of the adapter |adapter| changes.
59 // When |discoverable| is true the adapter is discoverable by other devices,
60 // false means the adapter is not discoverable.
61 virtual void AdapterDiscoverableChanged(BluetoothAdapter
* adapter
,
64 // Called when the discovering state of the adapter |adapter| changes. When
65 // |discovering| is true the adapter is seeking new devices, false means it
67 virtual void AdapterDiscoveringChanged(BluetoothAdapter
* adapter
,
70 // Called when a new device |device| is added to the adapter |adapter|,
71 // either because it has been discovered or a connection made. |device|
72 // should not be cached. Instead, copy its Bluetooth address.
73 virtual void DeviceAdded(BluetoothAdapter
* adapter
,
74 BluetoothDevice
* device
) {}
76 // Called when properties of the device |device| known to the adapter
77 // |adapter| change. |device| should not be cached. Instead, copy its
79 virtual void DeviceChanged(BluetoothAdapter
* adapter
,
80 BluetoothDevice
* device
) {}
82 // Called when the device |device| is removed from the adapter |adapter|,
83 // either as a result of a discovered device being lost between discovering
84 // phases or pairing information deleted. |device| should not be
85 // cached. Instead, copy its Bluetooth address.
86 virtual void DeviceRemoved(BluetoothAdapter
* adapter
,
87 BluetoothDevice
* device
) {}
89 // Called when a new GATT service |service| is added to the device |device|,
90 // as the service is received from the device. Don't cache |service|. Store
91 // its identifier instead (i.e. BluetoothGattService::GetIdentifier).
92 virtual void GattServiceAdded(BluetoothAdapter
* adapter
,
93 BluetoothDevice
* device
,
94 BluetoothGattService
* service
) {}
96 // Called when the GATT service |service| is removed from the device
97 // |device|. This can happen if the attribute database of the remote device
98 // changes or when |device| gets removed.
99 virtual void GattServiceRemoved(BluetoothAdapter
* adapter
,
100 BluetoothDevice
* device
,
101 BluetoothGattService
* service
) {}
103 // Called when all characteristic and descriptor discovery procedures are
104 // known to be completed for the GATT service |service|. This method will be
105 // called after the initial discovery of a GATT service and will usually be
106 // preceded by calls to GattCharacteristicAdded and GattDescriptorAdded.
107 virtual void GattDiscoveryCompleteForService(
108 BluetoothAdapter
* adapter
,
109 BluetoothGattService
* service
) {}
111 // Called when properties of the remote GATT service |service| have changed.
112 // This will get called for properties such as UUID, as well as for changes
113 // to the list of known characteristics and included services. Observers
114 // should read all GATT characteristic and descriptors objects and do any
115 // necessary set up required for a changed service.
116 virtual void GattServiceChanged(BluetoothAdapter
* adapter
,
117 BluetoothGattService
* service
) {}
119 // Called when the remote GATT characteristic |characteristic| has been
120 // discovered. Use this to issue any initial read/write requests to the
121 // characteristic but don't cache the pointer as it may become invalid.
122 // Instead, use the specially assigned identifier to obtain a characteristic
123 // and cache that identifier as necessary, as it can be used to retrieve the
124 // characteristic from its GATT service. The number of characteristics with
125 // the same UUID belonging to a service depends on the particular profile
126 // the remote device implements, hence the client of a GATT based profile
127 // will usually operate on the whole set of characteristics and not just
129 virtual void GattCharacteristicAdded(
130 BluetoothAdapter
* adapter
,
131 BluetoothGattCharacteristic
* characteristic
) {}
133 // Called when a GATT characteristic |characteristic| has been removed from
135 virtual void GattCharacteristicRemoved(
136 BluetoothAdapter
* adapter
,
137 BluetoothGattCharacteristic
* characteristic
) {}
139 // Called when the remote GATT characteristic descriptor |descriptor| has
140 // been discovered. Don't cache the arguments as the pointers may become
141 // invalid. Instead, use the specially assigned identifier to obtain a
142 // descriptor and cache that identifier as necessary.
143 virtual void GattDescriptorAdded(BluetoothAdapter
* adapter
,
144 BluetoothGattDescriptor
* descriptor
) {}
146 // Called when a GATT characteristic descriptor |descriptor| has been
147 // removed from the system.
148 virtual void GattDescriptorRemoved(BluetoothAdapter
* adapter
,
149 BluetoothGattDescriptor
* descriptor
) {}
151 // Called when the value of a characteristic has changed. This might be a
152 // result of a read/write request to, or a notification/indication from, a
153 // remote GATT characteristic.
154 virtual void GattCharacteristicValueChanged(
155 BluetoothAdapter
* adapter
,
156 BluetoothGattCharacteristic
* characteristic
,
157 const std::vector
<uint8
>& value
) {}
159 // Called when the value of a characteristic descriptor has been updated.
160 virtual void GattDescriptorValueChanged(BluetoothAdapter
* adapter
,
161 BluetoothGattDescriptor
* descriptor
,
162 const std::vector
<uint8
>& value
) {}
165 // Used to configure a listening servie.
166 struct DEVICE_BLUETOOTH_EXPORT ServiceOptions
{
170 scoped_ptr
<int> channel
;
172 scoped_ptr
<std::string
> name
;
175 // The ErrorCallback is used for methods that can fail in which case it is
176 // called, in the success case the callback is simply not called.
177 typedef base::Closure ErrorCallback
;
179 // The InitCallback is used to trigger a callback after asynchronous
180 // initialization, if initialization is asynchronous on the platform.
181 typedef base::Callback
<void()> InitCallback
;
183 typedef base::Callback
<void(scoped_ptr
<BluetoothDiscoverySession
>)>
184 DiscoverySessionCallback
;
185 typedef std::vector
<BluetoothDevice
*> DeviceList
;
186 typedef std::vector
<const BluetoothDevice
*> ConstDeviceList
;
187 typedef base::Callback
<void(scoped_refptr
<BluetoothSocket
>)>
188 CreateServiceCallback
;
189 typedef base::Callback
<void(const std::string
& message
)>
190 CreateServiceErrorCallback
;
191 typedef base::Callback
<void(scoped_refptr
<BluetoothAudioSink
>)>
194 // Returns a weak pointer to a new adapter. For platforms with asynchronous
195 // initialization, the returned adapter will run the |init_callback| once
196 // asynchronous initialization is complete.
197 // Caution: The returned pointer also transfers ownership of the adapter. The
198 // caller is expected to call |AddRef()| on the returned pointer, typically by
199 // storing it into a |scoped_refptr|.
200 static base::WeakPtr
<BluetoothAdapter
> CreateAdapter(
201 const InitCallback
& init_callback
);
203 // Returns a weak pointer to an existing adapter for testing purposes only.
204 base::WeakPtr
<BluetoothAdapter
> GetWeakPtrForTesting();
206 #if defined(OS_CHROMEOS)
207 // Shutdown the adapter: tear down and clean up all objects owned by
208 // BluetoothAdapter. After this call, the BluetoothAdapter will behave as if
209 // no Bluetooth controller exists in the local system. |IsPresent| will return
211 virtual void Shutdown();
214 // Adds and removes observers for events on this bluetooth adapter. If
215 // monitoring multiple adapters, check the |adapter| parameter of observer
216 // methods to determine which adapter is issuing the event.
217 virtual void AddObserver(BluetoothAdapter::Observer
* observer
);
218 virtual void RemoveObserver(BluetoothAdapter::Observer
* observer
);
220 // The address of this adapter. The address format is "XX:XX:XX:XX:XX:XX",
221 // where each XX is a hexadecimal number.
222 virtual std::string
GetAddress() const = 0;
224 // The name of the adapter.
225 virtual std::string
GetName() const = 0;
227 // Set the human-readable name of the adapter to |name|. On success,
228 // |callback| will be called. On failure, |error_callback| will be called.
229 virtual void SetName(const std::string
& name
,
230 const base::Closure
& callback
,
231 const ErrorCallback
& error_callback
) = 0;
233 // Indicates whether the adapter is initialized and ready to use.
234 virtual bool IsInitialized() const = 0;
236 // Indicates whether the adapter is actually present on the system. For the
237 // default adapter, this indicates whether any adapter is present. An adapter
238 // is only considered present if the address has been obtained.
239 virtual bool IsPresent() const = 0;
241 // Indicates whether the adapter radio is powered.
242 virtual bool IsPowered() const = 0;
244 // Requests a change to the adapter radio power. Setting |powered| to true
245 // will turn on the radio and false will turn it off. On success, |callback|
246 // will be called. On failure, |error_callback| will be called.
247 virtual void SetPowered(bool powered
,
248 const base::Closure
& callback
,
249 const ErrorCallback
& error_callback
) = 0;
251 // Indicates whether the adapter radio is discoverable.
252 virtual bool IsDiscoverable() const = 0;
254 // Requests that the adapter change its discoverability state. If
255 // |discoverable| is true, then it will be discoverable by other Bluetooth
256 // devices. On successfully changing the adapter's discoverability, |callback|
257 // will be called. On failure, |error_callback| will be called.
258 virtual void SetDiscoverable(bool discoverable
,
259 const base::Closure
& callback
,
260 const ErrorCallback
& error_callback
) = 0;
262 // Indicates whether the adapter is currently discovering new devices.
263 virtual bool IsDiscovering() const = 0;
265 // Requests the adapter to start a new discovery session. On success, a new
266 // instance of BluetoothDiscoverySession will be returned to the caller via
267 // |callback| and the adapter will be discovering nearby Bluetooth devices.
268 // The returned BluetoothDiscoverySession is owned by the caller and it's the
269 // owner's responsibility to properly clean it up and stop the session when
270 // device discovery is no longer needed.
272 // If clients desire device discovery to run, they should always call this
273 // method and never make it conditional on the value of IsDiscovering(), as
274 // another client might cause discovery to stop unexpectedly. Hence, clients
275 // should always obtain a BluetoothDiscoverySession and call
276 // BluetoothDiscoverySession::Stop when done. When this method gets called,
277 // device discovery may actually be in progress. Clients can call GetDevices()
278 // and check for those with IsPaired() as false to obtain the list of devices
279 // that have been discovered so far. Otherwise, clients can be notified of all
280 // new and lost devices by implementing the Observer methods "DeviceAdded" and
282 virtual void StartDiscoverySession(const DiscoverySessionCallback
& callback
,
283 const ErrorCallback
& error_callback
);
284 virtual void StartDiscoverySessionWithFilter(
285 scoped_ptr
<BluetoothDiscoveryFilter
> discovery_filter
,
286 const DiscoverySessionCallback
& callback
,
287 const ErrorCallback
& error_callback
);
289 // Return all discovery filters assigned to this adapter merged together.
290 scoped_ptr
<BluetoothDiscoveryFilter
> GetMergedDiscoveryFilter() const;
292 // Works like GetMergedDiscoveryFilter, but doesn't take |masked_filter| into
293 // account. |masked_filter| is compared by pointer, and must be a member of
295 scoped_ptr
<BluetoothDiscoveryFilter
> GetMergedDiscoveryFilterMasked(
296 BluetoothDiscoveryFilter
* masked_filter
) const;
298 // Requests the list of devices from the adapter. All devices are returned,
299 // including those currently connected and those paired. Use the returned
300 // device pointers to determine which they are.
301 virtual DeviceList
GetDevices();
302 virtual ConstDeviceList
GetDevices() const;
304 // Returns a pointer to the device with the given address |address| or NULL if
305 // no such device is known.
306 virtual BluetoothDevice
* GetDevice(const std::string
& address
);
307 virtual const BluetoothDevice
* GetDevice(const std::string
& address
) const;
309 // Possible priorities for AddPairingDelegate(), low is intended for
310 // permanent UI and high is intended for interactive UI or applications.
311 enum PairingDelegatePriority
{
312 PAIRING_DELEGATE_PRIORITY_LOW
,
313 PAIRING_DELEGATE_PRIORITY_HIGH
316 // Adds a default pairing delegate with priority |priority|. Method calls
317 // will be made on |pairing_delegate| for incoming pairing requests if the
318 // priority is higher than any other registered; or for those of the same
319 // priority, the first registered.
321 // |pairing_delegate| must not be freed without first calling
322 // RemovePairingDelegate().
323 virtual void AddPairingDelegate(
324 BluetoothDevice::PairingDelegate
* pairing_delegate
,
325 PairingDelegatePriority priority
);
327 // Removes a previously added pairing delegate.
328 virtual void RemovePairingDelegate(
329 BluetoothDevice::PairingDelegate
* pairing_delegate
);
331 // Returns the first registered pairing delegate with the highest priority,
332 // or NULL if no delegate is registered. Used to select the delegate for
333 // incoming pairing requests.
334 virtual BluetoothDevice::PairingDelegate
* DefaultPairingDelegate();
336 // Creates an RFCOMM service on this adapter advertised with UUID |uuid|,
337 // listening on channel |options.channel|, which may be left null to
338 // automatically allocate one. The service will be advertised with
339 // |options.name| as the English name of the service. |callback| will be
340 // called on success with a BluetoothSocket instance that is to be owned by
341 // the received. |error_callback| will be called on failure with a message
342 // indicating the cause.
343 virtual void CreateRfcommService(
344 const BluetoothUUID
& uuid
,
345 const ServiceOptions
& options
,
346 const CreateServiceCallback
& callback
,
347 const CreateServiceErrorCallback
& error_callback
) = 0;
349 // Creates an L2CAP service on this adapter advertised with UUID |uuid|,
350 // listening on PSM |options.psm|, which may be left null to automatically
351 // allocate one. The service will be advertised with |options.name| as the
352 // English name of the service. |callback| will be called on success with a
353 // BluetoothSocket instance that is to be owned by the received.
354 // |error_callback| will be called on failure with a message indicating the
356 virtual void CreateL2capService(
357 const BluetoothUUID
& uuid
,
358 const ServiceOptions
& options
,
359 const CreateServiceCallback
& callback
,
360 const CreateServiceErrorCallback
& error_callback
) = 0;
362 // Creates and registers a BluetoothAudioSink with |options|. If the fields in
363 // |options| are not specified, the default values will be used. |callback|
364 // will be called on success with a BluetoothAudioSink which is to be owned by
365 // the caller of this method. |error_callback| will be called on failure with
366 // a message indicating the cause.
367 virtual void RegisterAudioSink(
368 const BluetoothAudioSink::Options
& options
,
369 const AcquiredCallback
& callback
,
370 const BluetoothAudioSink::ErrorCallback
& error_callback
) = 0;
373 friend class base::RefCounted
<BluetoothAdapter
>;
374 friend class BluetoothDiscoverySession
;
376 typedef std::map
<const std::string
, BluetoothDevice
*> DevicesMap
;
377 typedef std::pair
<BluetoothDevice::PairingDelegate
*, PairingDelegatePriority
>
381 virtual ~BluetoothAdapter();
383 // Internal methods for initiating and terminating device discovery sessions.
384 // An implementation of BluetoothAdapter keeps an internal reference count to
385 // make sure that the underlying controller is constantly searching for nearby
386 // devices and retrieving information from them as long as there are clients
387 // who have requested discovery. These methods behave in the following way:
389 // On a call to AddDiscoverySession:
390 // - If there is a pending request to the subsystem, queue this request to
391 // execute once the pending requests are done.
392 // - If the count is 0, issue a request to the subsystem to start
393 // device discovery. On success, increment the count to 1.
394 // - If the count is greater than 0, increment the count and return
396 // As long as the count is non-zero, the underlying controller will be
397 // discovering for devices. This means that Chrome will restart device
398 // scan and inquiry sessions if they ever end, unless these sessions
399 // terminate due to an unexpected reason.
401 // On a call to RemoveDiscoverySession:
402 // - If there is a pending request to the subsystem, queue this request to
403 // execute once the pending requests are done.
404 // - If the count is 0, return failure, as there is no active discovery
406 // - If the count is 1, issue a request to the subsystem to stop device
407 // discovery and decrement the count to 0 on success.
408 // - If the count is greater than 1, decrement the count and return
411 // |discovery_filter| passed to AddDiscoverySession and RemoveDiscoverySession
412 // is owned by other objects and shall not be freed.
414 // These methods invoke |callback| for success and |error_callback| for
416 virtual void AddDiscoverySession(BluetoothDiscoveryFilter
* discovery_filter
,
417 const base::Closure
& callback
,
418 const ErrorCallback
& error_callback
) = 0;
419 virtual void RemoveDiscoverySession(
420 BluetoothDiscoveryFilter
* discovery_filter
,
421 const base::Closure
& callback
,
422 const ErrorCallback
& error_callback
) = 0;
423 virtual void SetDiscoveryFilter(
424 scoped_ptr
<BluetoothDiscoveryFilter
> discovery_filter
,
425 const base::Closure
& callback
,
426 const ErrorCallback
& error_callback
) = 0;
428 // Called by RemovePairingDelegate() in order to perform any class-specific
429 // internal functionality necessary to remove the pairing delegate, such as
430 // cleaning up ongoing pairings using it.
431 virtual void RemovePairingDelegateInternal(
432 BluetoothDevice::PairingDelegate
* pairing_delegate
) = 0;
434 // Success callback passed to AddDiscoverySession by StartDiscoverySession.
435 void OnStartDiscoverySession(
436 scoped_ptr
<BluetoothDiscoveryFilter
> discovery_filter
,
437 const DiscoverySessionCallback
& callback
);
439 // Marks all known DiscoverySession instances as inactive. Called by
440 // BluetoothAdapter in the event that the adapter unexpectedly stops
441 // discovering. This should be called by all platform implementations.
442 void MarkDiscoverySessionsAsInactive();
444 // Removes |discovery_session| from |discovery_sessions_|, if its in there.
445 // Called by DiscoverySession when an instance is destroyed or becomes
447 void DiscoverySessionBecameInactive(
448 BluetoothDiscoverySession
* discovery_session
);
450 // Observers of BluetoothAdapter, notified from implementation subclasses.
451 ObserverList
<device::BluetoothAdapter::Observer
> observers_
;
453 // Devices paired with, connected to, discovered by, or visible to the
454 // adapter. The key is the Bluetooth address of the device and the value is
455 // the BluetoothDevice object whose lifetime is managed by the adapter
459 // Default pairing delegates registered with the adapter.
460 std::list
<PairingDelegatePair
> pairing_delegates_
;
463 // Return all discovery filters assigned to this adapter merged together.
464 // If |omit| is true, |discovery_filter| will not be processed.
465 scoped_ptr
<BluetoothDiscoveryFilter
> GetMergedDiscoveryFilterHelper(
466 const BluetoothDiscoveryFilter
* discovery_filter
,
469 // List of active DiscoverySession objects. This is used to notify sessions to
470 // become inactive in case of an unexpected change to the adapter discovery
471 // state. We keep raw pointers, with the invariant that a DiscoverySession
472 // will remove itself from this list when it gets destroyed or becomes
473 // inactive by calling DiscoverySessionBecameInactive(), hence no pointers to
474 // deallocated sessions are kept.
475 std::set
<BluetoothDiscoverySession
*> discovery_sessions_
;
477 // Note: This should remain the last member so it'll be destroyed and
478 // invalidate its weak pointers before any other members are destroyed.
479 base::WeakPtrFactory
<BluetoothAdapter
> weak_ptr_factory_
;
482 } // namespace device
484 #endif // DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_H_