Automated Commit: Committing new LKGM version 6953.0.0 for chromeos.
[chromium-blink-merge.git] / device / bluetooth / bluetooth_adapter.h
blob77c64ee6fe621bbcf025a0eccdcd14af9c907a18
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_audio_sink.h"
18 #include "device/bluetooth/bluetooth_device.h"
19 #include "device/bluetooth/bluetooth_export.h"
21 namespace device {
23 class BluetoothDiscoverySession;
24 class BluetoothGattCharacteristic;
25 class BluetoothGattDescriptor;
26 class BluetoothGattService;
27 class BluetoothSocket;
28 class BluetoothUUID;
29 struct BluetoothAdapterDeleter;
31 // BluetoothAdapter represents a local Bluetooth adapter which may be used to
32 // interact with remote Bluetooth devices. As well as providing support for
33 // determining whether an adapter is present and whether the radio is powered,
34 // this class also provides support for obtaining the list of remote devices
35 // known to the adapter, discovering new devices, and providing notification of
36 // updates to device information.
37 class DEVICE_BLUETOOTH_EXPORT BluetoothAdapter
38 : public base::RefCountedThreadSafe<BluetoothAdapter,
39 BluetoothAdapterDeleter> {
40 public:
41 // Interface for observing changes from bluetooth adapters.
42 class Observer {
43 public:
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,
50 bool present) {}
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
54 // radio is off.
55 virtual void AdapterPoweredChanged(BluetoothAdapter* adapter,
56 bool powered) {}
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,
62 bool discoverable) {}
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
66 // is not.
67 virtual void AdapterDiscoveringChanged(BluetoothAdapter* adapter,
68 bool discovering) {}
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
78 // Bluetooth address.
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
128 // one.
129 virtual void GattCharacteristicAdded(
130 BluetoothAdapter* adapter,
131 BluetoothGattCharacteristic* characteristic) {}
133 // Called when a GATT characteristic |characteristic| has been removed from
134 // the system.
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 {
167 ServiceOptions();
168 ~ServiceOptions();
170 scoped_ptr<int> channel;
171 scoped_ptr<int> psm;
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 // Returns a weak pointer to a new adapter. For platforms with asynchronous
184 // initialization, the returned adapter will run the |init_callback| once
185 // asynchronous initialization is complete.
186 // Caution: The returned pointer also transfers ownership of the adapter. The
187 // caller is expected to call |AddRef()| on the returned pointer, typically by
188 // storing it into a |scoped_refptr|.
189 static base::WeakPtr<BluetoothAdapter> CreateAdapter(
190 const InitCallback& init_callback);
192 // Returns a weak pointer to an existing adapter for testing purposes only.
193 base::WeakPtr<BluetoothAdapter> GetWeakPtrForTesting();
195 #if defined(OS_CHROMEOS)
196 // Shutdown the adapter: tear down and clean up all objects owned by
197 // BluetoothAdapter. After this call, the BluetoothAdapter will behave as if
198 // no Bluetooth controller exists in the local system. |IsPresent| will return
199 // false.
200 virtual void Shutdown();
201 #endif
203 // Adds and removes observers for events on this bluetooth adapter. If
204 // monitoring multiple adapters, check the |adapter| parameter of observer
205 // methods to determine which adapter is issuing the event.
206 virtual void AddObserver(BluetoothAdapter::Observer* observer) = 0;
207 virtual void RemoveObserver(
208 BluetoothAdapter::Observer* observer) = 0;
210 // The address of this adapter. The address format is "XX:XX:XX:XX:XX:XX",
211 // where each XX is a hexadecimal number.
212 virtual std::string GetAddress() const = 0;
214 // The name of the adapter.
215 virtual std::string GetName() const = 0;
217 // Set the human-readable name of the adapter to |name|. On success,
218 // |callback| will be called. On failure, |error_callback| will be called.
219 virtual void SetName(const std::string& name,
220 const base::Closure& callback,
221 const ErrorCallback& error_callback) = 0;
223 // Indicates whether the adapter is initialized and ready to use.
224 virtual bool IsInitialized() const = 0;
226 // Indicates whether the adapter is actually present on the system. For the
227 // default adapter, this indicates whether any adapter is present. An adapter
228 // is only considered present if the address has been obtained.
229 virtual bool IsPresent() const = 0;
231 // Indicates whether the adapter radio is powered.
232 virtual bool IsPowered() const = 0;
234 // Requests a change to the adapter radio power. Setting |powered| to true
235 // will turn on the radio and false will turn it off. On success, |callback|
236 // will be called. On failure, |error_callback| will be called.
237 virtual void SetPowered(bool powered,
238 const base::Closure& callback,
239 const ErrorCallback& error_callback) = 0;
241 // Indicates whether the adapter radio is discoverable.
242 virtual bool IsDiscoverable() const = 0;
244 // Requests that the adapter change its discoverability state. If
245 // |discoverable| is true, then it will be discoverable by other Bluetooth
246 // devices. On successfully changing the adapter's discoverability, |callback|
247 // will be called. On failure, |error_callback| will be called.
248 virtual void SetDiscoverable(bool discoverable,
249 const base::Closure& callback,
250 const ErrorCallback& error_callback) = 0;
252 // Indicates whether the adapter is currently discovering new devices.
253 virtual bool IsDiscovering() const = 0;
255 // Requests the adapter to start a new discovery session. On success, a new
256 // instance of BluetoothDiscoverySession will be returned to the caller via
257 // |callback| and the adapter will be discovering nearby Bluetooth devices.
258 // The returned BluetoothDiscoverySession is owned by the caller and it's the
259 // owner's responsibility to properly clean it up and stop the session when
260 // device discovery is no longer needed.
262 // If clients desire device discovery to run, they should always call this
263 // method and never make it conditional on the value of IsDiscovering(), as
264 // another client might cause discovery to stop unexpectedly. Hence, clients
265 // should always obtain a BluetoothDiscoverySession and call
266 // BluetoothDiscoverySession::Stop when done. When this method gets called,
267 // device discovery may actually be in progress. Clients can call GetDevices()
268 // and check for those with IsPaired() as false to obtain the list of devices
269 // that have been discovered so far. Otherwise, clients can be notified of all
270 // new and lost devices by implementing the Observer methods "DeviceAdded" and
271 // "DeviceRemoved".
272 typedef base::Callback<void(scoped_ptr<BluetoothDiscoverySession>)>
273 DiscoverySessionCallback;
274 virtual void StartDiscoverySession(const DiscoverySessionCallback& callback,
275 const ErrorCallback& error_callback);
277 // Requests the list of devices from the adapter. All devices are returned,
278 // including those currently connected and those paired. Use the returned
279 // device pointers to determine which they are.
280 typedef std::vector<BluetoothDevice*> DeviceList;
281 virtual DeviceList GetDevices();
282 typedef std::vector<const BluetoothDevice*> ConstDeviceList;
283 virtual ConstDeviceList GetDevices() const;
285 // Returns a pointer to the device with the given address |address| or NULL if
286 // no such device is known.
287 virtual BluetoothDevice* GetDevice(const std::string& address);
288 virtual const BluetoothDevice* GetDevice(const std::string& address) const;
290 // Possible priorities for AddPairingDelegate(), low is intended for
291 // permanent UI and high is intended for interactive UI or applications.
292 enum PairingDelegatePriority {
293 PAIRING_DELEGATE_PRIORITY_LOW,
294 PAIRING_DELEGATE_PRIORITY_HIGH
297 // Adds a default pairing delegate with priority |priority|. Method calls
298 // will be made on |pairing_delegate| for incoming pairing requests if the
299 // priority is higher than any other registered; or for those of the same
300 // priority, the first registered.
302 // |pairing_delegate| must not be freed without first calling
303 // RemovePairingDelegate().
304 virtual void AddPairingDelegate(
305 BluetoothDevice::PairingDelegate* pairing_delegate,
306 PairingDelegatePriority priority);
308 // Removes a previously added pairing delegate.
309 virtual void RemovePairingDelegate(
310 BluetoothDevice::PairingDelegate* pairing_delegate);
312 // Returns the first registered pairing delegate with the highest priority,
313 // or NULL if no delegate is registered. Used to select the delegate for
314 // incoming pairing requests.
315 virtual BluetoothDevice::PairingDelegate* DefaultPairingDelegate();
317 // Creates an RFCOMM service on this adapter advertised with UUID |uuid|,
318 // listening on channel |options.channel|, which may be left null to
319 // automatically allocate one. The service will be advertised with
320 // |options.name| as the English name of the service. |callback| will be
321 // called on success with a BluetoothSocket instance that is to be owned by
322 // the received. |error_callback| will be called on failure with a message
323 // indicating the cause.
324 typedef base::Callback<void(scoped_refptr<BluetoothSocket>)>
325 CreateServiceCallback;
326 typedef base::Callback<void(const std::string& message)>
327 CreateServiceErrorCallback;
328 virtual void CreateRfcommService(
329 const BluetoothUUID& uuid,
330 const ServiceOptions& options,
331 const CreateServiceCallback& callback,
332 const CreateServiceErrorCallback& error_callback) = 0;
334 // Creates an L2CAP service on this adapter advertised with UUID |uuid|,
335 // listening on PSM |options.psm|, which may be left null to automatically
336 // allocate one. The service will be advertised with |options.name| as the
337 // English name of the service. |callback| will be called on success with a
338 // BluetoothSocket instance that is to be owned by the received.
339 // |error_callback| will be called on failure with a message indicating the
340 // cause.
341 virtual void CreateL2capService(
342 const BluetoothUUID& uuid,
343 const ServiceOptions& options,
344 const CreateServiceCallback& callback,
345 const CreateServiceErrorCallback& error_callback) = 0;
347 // Creates and registers a BluetoothAudioSink with |options|. If the fields in
348 // |options| are not specified, the default values will be used. |callback|
349 // will be called on success with a BluetoothAudioSink which is to be owned by
350 // the caller of this method. |error_callback| will be called on failure with
351 // a message indicating the cause.
352 typedef base::Callback<void(scoped_refptr<BluetoothAudioSink>)>
353 AcquiredCallback;
354 virtual void RegisterAudioSink(
355 const BluetoothAudioSink::Options& options,
356 const AcquiredCallback& callback,
357 const BluetoothAudioSink::ErrorCallback& error_callback) = 0;
359 protected:
360 friend class base::RefCountedThreadSafe<BluetoothAdapter,
361 BluetoothAdapterDeleter>;
362 friend struct BluetoothAdapterDeleter;
363 friend class BluetoothDiscoverySession;
364 BluetoothAdapter();
365 virtual ~BluetoothAdapter();
367 // Called by RefCountedThreadSafeDeleteOnCorrectThread to destroy this.
368 virtual void DeleteOnCorrectThread() const = 0;
370 // Internal methods for initiating and terminating device discovery sessions.
371 // An implementation of BluetoothAdapter keeps an internal reference count to
372 // make sure that the underlying controller is constantly searching for nearby
373 // devices and retrieving information from them as long as there are clients
374 // who have requested discovery. These methods behave in the following way:
376 // On a call to AddDiscoverySession:
377 // - If there is a pending request to the subsystem, queue this request to
378 // execute once the pending requests are done.
379 // - If the count is 0, issue a request to the subsystem to start
380 // device discovery. On success, increment the count to 1.
381 // - If the count is greater than 0, increment the count and return
382 // success.
383 // As long as the count is non-zero, the underlying controller will be
384 // discovering for devices. This means that Chrome will restart device
385 // scan and inquiry sessions if they ever end, unless these sessions
386 // terminate due to an unexpected reason.
388 // On a call to RemoveDiscoverySession:
389 // - If there is a pending request to the subsystem, queue this request to
390 // execute once the pending requests are done.
391 // - If the count is 0, return failure, as there is no active discovery
392 // session.
393 // - If the count is 1, issue a request to the subsystem to stop device
394 // discovery and decrement the count to 0 on success.
395 // - If the count is greater than 1, decrement the count and return
396 // success.
398 // These methods invoke |callback| for success and |error_callback| for
399 // failures.
400 virtual void AddDiscoverySession(const base::Closure& callback,
401 const ErrorCallback& error_callback) = 0;
402 virtual void RemoveDiscoverySession(const base::Closure& callback,
403 const ErrorCallback& error_callback) = 0;
405 // Called by RemovePairingDelegate() in order to perform any class-specific
406 // internal functionality necessary to remove the pairing delegate, such as
407 // cleaning up ongoing pairings using it.
408 virtual void RemovePairingDelegateInternal(
409 BluetoothDevice::PairingDelegate* pairing_delegate) = 0;
411 // Success callback passed to AddDiscoverySession by StartDiscoverySession.
412 void OnStartDiscoverySession(const DiscoverySessionCallback& callback);
414 // Marks all known DiscoverySession instances as inactive. Called by
415 // BluetoothAdapter in the event that the adapter unexpectedly stops
416 // discovering. This should be called by all platform implementations.
417 void MarkDiscoverySessionsAsInactive();
419 // Removes |discovery_session| from |discovery_sessions_|, if its in there.
420 // Called by DiscoverySession when an instance is destroyed or becomes
421 // inactive.
422 void DiscoverySessionBecameInactive(
423 BluetoothDiscoverySession* discovery_session);
425 // Devices paired with, connected to, discovered by, or visible to the
426 // adapter. The key is the Bluetooth address of the device and the value is
427 // the BluetoothDevice object whose lifetime is managed by the adapter
428 // instance.
429 typedef std::map<const std::string, BluetoothDevice*> DevicesMap;
430 DevicesMap devices_;
432 // Default pairing delegates registered with the adapter.
433 typedef std::pair<BluetoothDevice::PairingDelegate*,
434 PairingDelegatePriority> PairingDelegatePair;
435 std::list<PairingDelegatePair> pairing_delegates_;
437 private:
438 // List of active DiscoverySession objects. This is used to notify sessions to
439 // become inactive in case of an unexpected change to the adapter discovery
440 // state. We keep raw pointers, with the invariant that a DiscoverySession
441 // will remove itself from this list when it gets destroyed or becomes
442 // inactive by calling DiscoverySessionBecameInactive(), hence no pointers to
443 // deallocated sessions are kept.
444 std::set<BluetoothDiscoverySession*> discovery_sessions_;
446 // Note: This should remain the last member so it'll be destroyed and
447 // invalidate its weak pointers before any other members are destroyed.
448 base::WeakPtrFactory<BluetoothAdapter> weak_ptr_factory_;
451 // Trait for RefCountedThreadSafe that deletes BluetoothAdapter.
452 struct BluetoothAdapterDeleter {
453 static void Destruct(const BluetoothAdapter* adapter) {
454 adapter->DeleteOnCorrectThread();
458 } // namespace device
460 #endif // DEVICE_BLUETOOTH_BLUETOOTH_ADAPTER_H_