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_DEVICE_H_
6 #define DEVICE_BLUETOOTH_BLUETOOTH_DEVICE_H_
13 #include "base/callback.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/strings/string16.h"
16 #include "device/bluetooth/bluetooth_export.h"
17 #include "device/bluetooth/bluetooth_uuid.h"
18 #include "net/log/net_log.h"
26 class BluetoothAdapter
;
27 class BluetoothGattConnection
;
28 class BluetoothGattService
;
29 class BluetoothSocket
;
32 // BluetoothDevice represents a remote Bluetooth device, both its properties and
33 // capabilities as discovered by a local adapter and actions that may be
34 // performed on the remove device such as pairing, connection and disconnection.
36 // The class is instantiated and managed by the BluetoothAdapter class
37 // and pointers should only be obtained from that class and not cached,
38 // instead use the GetAddress() method as a unique key for a device.
40 // Since the lifecycle of BluetoothDevice instances is managed by
41 // BluetoothAdapter, that class rather than this provides observer methods
42 // for devices coming and going, as well as properties being updated.
43 class DEVICE_BLUETOOTH_EXPORT BluetoothDevice
{
45 // Possible values that may be returned by GetVendorIDSource(),
46 // indicating different organisations that allocate the identifiers returned
52 VENDOR_ID_MAX_VALUE
= VENDOR_ID_USB
55 // Possible values that may be returned by GetDeviceType(), representing
56 // different types of bluetooth device that we support or are aware of
57 // decoded from the bluetooth class information.
72 DEVICE_KEYBOARD_MOUSE_COMBO
75 // The value returned if the RSSI or transmit power cannot be read.
76 static const int kUnknownPower
= 127;
78 struct DEVICE_BLUETOOTH_EXPORT ConnectionInfo
{
81 int max_transmit_power
;
84 ConnectionInfo(int rssi
, int transmit_power
, int max_transmit_power
);
88 // Possible errors passed back to an error callback function in case of a
89 // failed call to Connect().
90 enum ConnectErrorCode
{
98 ERROR_UNSUPPORTED_DEVICE
101 typedef std::vector
<BluetoothUUID
> UUIDList
;
103 // Interface for negotiating pairing of bluetooth devices.
104 class PairingDelegate
{
106 virtual ~PairingDelegate() {}
108 // This method will be called when the Bluetooth daemon requires a
109 // PIN Code for authentication of the device |device|, the delegate should
110 // obtain the code from the user and call SetPinCode() on the device to
111 // provide it, or RejectPairing() or CancelPairing() to reject or cancel
114 // PIN Codes are generally required for Bluetooth 2.0 and earlier devices
115 // for which there is no automatic pairing or special handling.
116 virtual void RequestPinCode(BluetoothDevice
* device
) = 0;
118 // This method will be called when the Bluetooth daemon requires a
119 // Passkey for authentication of the device |device|, the delegate should
120 // obtain the passkey from the user (a numeric in the range 0-999999) and
121 // call SetPasskey() on the device to provide it, or RejectPairing() or
122 // CancelPairing() to reject or cancel the request.
124 // Passkeys are generally required for Bluetooth 2.1 and later devices
125 // which cannot provide input or display on their own, and don't accept
126 // passkey-less pairing.
127 virtual void RequestPasskey(BluetoothDevice
* device
) = 0;
129 // This method will be called when the Bluetooth daemon requires that the
130 // user enter the PIN code |pincode| into the device |device| so that it
131 // may be authenticated.
133 // This is used for Bluetooth 2.0 and earlier keyboard devices, the
134 // |pincode| will always be a six-digit numeric in the range 000000-999999
135 // for compatibility with later specifications.
136 virtual void DisplayPinCode(BluetoothDevice
* device
,
137 const std::string
& pincode
) = 0;
139 // This method will be called when the Bluetooth daemon requires that the
140 // user enter the Passkey |passkey| into the device |device| so that it
141 // may be authenticated.
143 // This is used for Bluetooth 2.1 and later devices that support input
144 // but not display, such as keyboards. The Passkey is a numeric in the
145 // range 0-999999 and should be always presented zero-padded to six
147 virtual void DisplayPasskey(BluetoothDevice
* device
,
150 // This method will be called when the Bluetooth daemon gets a notification
151 // of a key entered on the device |device| while pairing with the device
152 // using a PIN code or a Passkey.
154 // This method will be called only after DisplayPinCode() or
155 // DisplayPasskey() method is called, but is not warranted to be called
156 // on every pairing process that requires a PIN code or a Passkey because
157 // some device may not support this feature.
159 // The |entered| value describes the number of keys entered so far,
160 // including the last [enter] key. A first call to KeysEntered() with
161 // |entered| as 0 will be sent when the device supports this feature.
162 virtual void KeysEntered(BluetoothDevice
* device
,
165 // This method will be called when the Bluetooth daemon requires that the
166 // user confirm that the Passkey |passkey| is displayed on the screen
167 // of the device |device| so that it may be authenticated. The delegate
168 // should display to the user and ask for confirmation, then call
169 // ConfirmPairing() on the device to confirm, RejectPairing() on the device
170 // to reject or CancelPairing() on the device to cancel authentication
171 // for any other reason.
173 // This is used for Bluetooth 2.1 and later devices that support display,
174 // such as other computers or phones. The Passkey is a numeric in the
175 // range 0-999999 and should be always present zero-padded to six
177 virtual void ConfirmPasskey(BluetoothDevice
* device
,
180 // This method will be called when the Bluetooth daemon requires that a
181 // pairing request, usually only incoming, using the just-works model is
182 // authorized. The delegate should decide whether the user should confirm
183 // or not, then call ConfirmPairing() on the device to confirm the pairing
184 // (whether by user action or by default), RejectPairing() on the device to
185 // reject or CancelPairing() on the device to cancel authorization for
187 virtual void AuthorizePairing(BluetoothDevice
* device
) = 0;
190 virtual ~BluetoothDevice();
192 // Returns the Bluetooth class of the device, used by GetDeviceType()
193 // and metrics logging,
194 virtual uint32
GetBluetoothClass() const = 0;
196 // Returns the identifier of the bluetooth device.
197 virtual std::string
GetIdentifier() const;
199 // Returns the Bluetooth of address the device. This should be used as
200 // a unique key to identify the device and copied where needed.
201 virtual std::string
GetAddress() const = 0;
203 // Returns the allocation source of the identifier returned by GetVendorID(),
204 // where available, or VENDOR_ID_UNKNOWN where not.
205 virtual VendorIDSource
GetVendorIDSource() const = 0;
207 // Returns the Vendor ID of the device, where available.
208 virtual uint16
GetVendorID() const = 0;
210 // Returns the Product ID of the device, where available.
211 virtual uint16
GetProductID() const = 0;
213 // Returns the Device ID of the device, typically the release or version
214 // number in BCD format, where available.
215 virtual uint16
GetDeviceID() const = 0;
217 // Returns the name of the device suitable for displaying, this may
218 // be a synthesized string containing the address and localized type name
219 // if the device has no obtained name.
220 virtual base::string16
GetName() const;
222 // Returns the type of the device, limited to those we support or are
223 // aware of, by decoding the bluetooth class information. The returned
224 // values are unique, and do not overlap, so DEVICE_KEYBOARD is not also
225 // DEVICE_PERIPHERAL.
226 DeviceType
GetDeviceType() const;
228 // Indicates whether the device is known to support pairing based on its
229 // device class and address.
230 bool IsPairable() const;
232 // Indicates whether the device is paired with the adapter.
233 virtual bool IsPaired() const = 0;
235 // Indicates whether the device is currently connected to the adapter.
236 // Note that if IsConnected() is true, does not imply that the device is
237 // connected to any application or service. If the device is not paired, it
238 // could be still connected to the adapter for other reason, for example, to
239 // request the adapter's SDP records. The same holds for paired devices, since
240 // they could be connected to the adapter but not to an application.
241 virtual bool IsConnected() const = 0;
243 // Indicates whether an active GATT connection exists to the device.
244 virtual bool IsGattConnected() const = 0;
246 // Indicates whether the paired device accepts connections initiated from the
247 // adapter. This value is undefined for unpaired devices.
248 virtual bool IsConnectable() const = 0;
250 // Indicates whether there is a call to Connect() ongoing. For this attribute,
251 // we consider a call is ongoing if none of the callbacks passed to Connect()
252 // were called after the corresponding call to Connect().
253 virtual bool IsConnecting() const = 0;
255 // Indicates whether the device can be trusted, based on device properties,
256 // such as vendor and product id.
257 bool IsTrustable() const;
259 // Returns the set of UUIDs that this device supports. For classic Bluetooth
260 // devices this data is collected from both the EIR data and SDP tables,
261 // for Low Energy devices this data is collected from AD and GATT primary
262 // services, for dual mode devices this may be collected from both./
263 virtual UUIDList
GetUUIDs() const = 0;
265 // The received signal strength, in dBm. This field is avaliable and valid
266 // only during discovery. If not during discovery, or RSSI wasn't reported,
267 // this method will return |kUnknownPower|.
268 virtual int16
GetInquiryRSSI() const = 0;
270 // The transmitted power level. This field is avaliable only for LE devices
271 // that include this field in AD. It is avaliable and valid only during
272 // discovery. If not during discovery, or TxPower wasn't reported, this
273 // method will return |kUnknownPower|.
274 virtual int16
GetInquiryTxPower() const = 0;
276 // The ErrorCallback is used for methods that can fail in which case it
277 // is called, in the success case the callback is simply not called.
278 typedef base::Callback
<void()> ErrorCallback
;
280 // The ConnectErrorCallback is used for methods that can fail with an error,
281 // passed back as an error code argument to this callback.
282 // In the success case this callback is not called.
283 typedef base::Callback
<void(enum ConnectErrorCode
)> ConnectErrorCallback
;
285 typedef base::Callback
<void(const ConnectionInfo
&)> ConnectionInfoCallback
;
287 // Indicates whether the device is currently pairing and expecting a
288 // PIN Code to be returned.
289 virtual bool ExpectingPinCode() const = 0;
291 // Indicates whether the device is currently pairing and expecting a
292 // Passkey to be returned.
293 virtual bool ExpectingPasskey() const = 0;
295 // Indicates whether the device is currently pairing and expecting
296 // confirmation of a displayed passkey.
297 virtual bool ExpectingConfirmation() const = 0;
299 // Returns the RSSI and TX power of the active connection to the device:
301 // The RSSI indicates the power present in the received radio signal, measured
302 // in dBm, to a resolution of 1dBm. Larger (typically, less negative) values
303 // indicate a stronger signal.
305 // The transmit power indicates the strength of the signal broadcast from the
306 // host's Bluetooth antenna when communicating with the device, measured in
307 // dBm, to a resolution of 1dBm. Larger (typically, less negative) values
308 // indicate a stronger signal.
310 // If the device isn't connected, then the ConnectionInfo struct passed into
311 // the callback will be populated with |kUnknownPower|.
312 virtual void GetConnectionInfo(const ConnectionInfoCallback
& callback
) = 0;
314 // Initiates a connection to the device, pairing first if necessary.
316 // Method calls will be made on the supplied object |pairing_delegate|
317 // to indicate what display, and in response should make method calls
318 // back to the device object. Not all devices require user responses
319 // during pairing, so it is normal for |pairing_delegate| to receive no
320 // calls. To explicitly force a low-security connection without bonding,
321 // pass NULL, though this is ignored if the device is already paired.
323 // If the request fails, |error_callback| will be called; otherwise,
324 // |callback| is called when the request is complete.
325 // After calling Connect, CancelPairing should be called to cancel the pairing
326 // process and release the pairing delegate if user cancels the pairing and
327 // closes the pairing UI.
328 virtual void Connect(PairingDelegate
* pairing_delegate
,
329 const base::Closure
& callback
,
330 const ConnectErrorCallback
& error_callback
) = 0;
332 // Sends the PIN code |pincode| to the remote device during pairing.
334 // PIN Codes are generally required for Bluetooth 2.0 and earlier devices
335 // for which there is no automatic pairing or special handling.
336 virtual void SetPinCode(const std::string
& pincode
) = 0;
338 // Sends the Passkey |passkey| to the remote device during pairing.
340 // Passkeys are generally required for Bluetooth 2.1 and later devices
341 // which cannot provide input or display on their own, and don't accept
342 // passkey-less pairing, and are a numeric in the range 0-999999.
343 virtual void SetPasskey(uint32 passkey
) = 0;
345 // Confirms to the remote device during pairing that a passkey provided by
346 // the ConfirmPasskey() delegate call is displayed on both devices.
347 virtual void ConfirmPairing() = 0;
349 // Rejects a pairing or connection request from a remote device.
350 virtual void RejectPairing() = 0;
352 // Cancels a pairing or connection attempt to a remote device, releasing
353 // the pairing delegate.
354 virtual void CancelPairing() = 0;
356 // Disconnects the device, terminating the low-level ACL connection
357 // and any application connections using it. Link keys and other pairing
358 // information are not discarded, and the device object is not deleted.
359 // If the request fails, |error_callback| will be called; otherwise,
360 // |callback| is called when the request is complete.
361 virtual void Disconnect(const base::Closure
& callback
,
362 const ErrorCallback
& error_callback
) = 0;
364 // Disconnects the device, terminating the low-level ACL connection
365 // and any application connections using it, and then discards link keys
366 // and other pairing information. The device object remains valid until
367 // returning from the calling function, after which it should be assumed to
368 // have been deleted. If the request fails, |error_callback| will be called.
369 // There is no callback for success because this object is often deleted
370 // before that callback would be called.
371 virtual void Forget(const ErrorCallback
& error_callback
) = 0;
373 // Attempts to initiate an outgoing L2CAP or RFCOMM connection to the
374 // advertised service on this device matching |uuid|, performing an SDP lookup
375 // if necessary to determine the correct protocol and channel for the
376 // connection. |callback| will be called on a successful connection with a
377 // BluetoothSocket instance that is to be owned by the receiver.
378 // |error_callback| will be called on failure with a message indicating the
380 typedef base::Callback
<void(scoped_refptr
<BluetoothSocket
>)>
381 ConnectToServiceCallback
;
382 typedef base::Callback
<void(const std::string
& message
)>
383 ConnectToServiceErrorCallback
;
384 virtual void ConnectToService(
385 const BluetoothUUID
& uuid
,
386 const ConnectToServiceCallback
& callback
,
387 const ConnectToServiceErrorCallback
& error_callback
) = 0;
389 // Attempts to initiate an insecure outgoing L2CAP or RFCOMM connection to the
390 // advertised service on this device matching |uuid|, performing an SDP lookup
391 // if necessary to determine the correct protocol and channel for the
392 // connection. Unlike ConnectToService, the outgoing connection will request
393 // no bonding rather than general bonding. |callback| will be called on a
394 // successful connection with a BluetoothSocket instance that is to be owned
395 // by the receiver. |error_callback| will be called on failure with a message
396 // indicating the cause.
397 virtual void ConnectToServiceInsecurely(
398 const device::BluetoothUUID
& uuid
,
399 const ConnectToServiceCallback
& callback
,
400 const ConnectToServiceErrorCallback
& error_callback
) = 0;
402 // Opens a new GATT connection to this device. On success, a new
403 // BluetoothGattConnection will be handed to the caller via |callback|. On
404 // error, |error_callback| will be called. The connection will be kept alive,
405 // as long as there is at least one active GATT connection. In the case that
406 // the underlying connection gets terminated, either due to a call to
407 // BluetoothDevice::Disconnect or other unexpected circumstances, the
408 // returned BluetoothGattConnection will be automatically marked as inactive.
409 // To monitor the state of the connection, observe the
410 // BluetoothAdapter::Observer::DeviceChanged method.
411 typedef base::Callback
<void(scoped_ptr
<BluetoothGattConnection
>)>
412 GattConnectionCallback
;
413 virtual void CreateGattConnection(const GattConnectionCallback
& callback
,
414 const ConnectErrorCallback
& error_callback
);
416 // Returns the list of discovered GATT services.
417 virtual std::vector
<BluetoothGattService
*> GetGattServices() const;
419 // Returns the GATT service with device-specific identifier |identifier|.
420 // Returns NULL, if no such service exists.
421 virtual BluetoothGattService
* GetGattService(
422 const std::string
& identifier
) const;
424 // Returns service data of a service given its UUID.
425 virtual base::BinaryValue
* GetServiceData(BluetoothUUID serviceUUID
) const;
427 // Returns the list UUIDs of services that have service data.
428 virtual UUIDList
GetServiceDataUUIDs() const;
430 // Returns the |address| in the canonical format: XX:XX:XX:XX:XX:XX, where
431 // each 'X' is a hex digit. If the input |address| is invalid, returns an
433 static std::string
CanonicalizeAddress(const std::string
& address
);
436 // BluetoothGattConnection is a friend to call Add/RemoveGattConnection.
437 friend BluetoothGattConnection
;
439 BluetoothDevice(BluetoothAdapter
* adapter
);
441 // Returns the internal name of the Bluetooth device, used by GetName().
442 virtual std::string
GetDeviceName() const = 0;
444 // Implements platform specific operations to initiate a GATT connection.
445 // Subclasses must also call DidConnectGatt, DidFailToConnectGatt, or
446 // DidDisconnectGatt immediately or asynchronously as the connection state
448 virtual void CreateGattConnectionImpl() = 0;
450 // Disconnects GATT connection on platforms that maintain a specific GATT
452 virtual void DisconnectGatt() = 0;
454 // Calls any pending callbacks for CreateGattConnection based on result of
455 // subclasses actions initiated in CreateGattConnectionImpl or related
456 // disconnection events. These may be called at any time, even multiple times,
457 // to ensure a change in platform state is correctly tracked.
459 // Under normal behavior it is expected that after CreateGattConnectionImpl
460 // an platform will call DidConnectGatt or DidFailToConnectGatt, but not
461 // DidDisconnectGatt.
462 void DidConnectGatt();
463 void DidFailToConnectGatt(ConnectErrorCode
);
464 void DidDisconnectGatt();
466 // Tracks BluetoothGattConnection instances that act as a reference count
467 // keeping the GATT connection open. Instances call Add/RemoveGattConnection
468 // at creation & deletion.
469 void AddGattConnection(BluetoothGattConnection
*);
470 void RemoveGattConnection(BluetoothGattConnection
*);
472 // Clears the list of service data.
473 void ClearServiceData();
475 // Set the data of a given service designated by its UUID.
476 void SetServiceData(BluetoothUUID serviceUUID
, const char* buffer
,
479 // Raw pointer to adapter owning this device object. Subclasses use platform
480 // specific pointers via adapter_.
481 BluetoothAdapter
* adapter_
;
483 // Callbacks for pending success and error result of CreateGattConnection.
484 std::vector
<GattConnectionCallback
> create_gatt_connection_success_callbacks_
;
485 std::vector
<ConnectErrorCallback
> create_gatt_connection_error_callbacks_
;
487 // BluetoothGattConnection objects keeping the GATT connection alive.
488 std::set
<BluetoothGattConnection
*> gatt_connections_
;
490 // Mapping from the platform-specific GATT service identifiers to
491 // BluetoothGattService objects.
492 typedef std::map
<std::string
, BluetoothGattService
*> GattServiceMap
;
493 GattServiceMap gatt_services_
;
495 // Mapping from service UUID represented as a std::string of a bluetooth
497 // the specific data. The data is stored as BinaryValue.
498 scoped_ptr
<base::DictionaryValue
> services_data_
;
501 // Returns a localized string containing the device's bluetooth address and
502 // a device type for display when |name_| is empty.
503 base::string16
GetAddressWithLocalizedDeviceTypeName() const;
506 } // namespace device
508 #endif // DEVICE_BLUETOOTH_BLUETOOTH_DEVICE_H_