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