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