Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Bluetooth in your Application

Dave Smith
November 12, 2013

Bluetooth in your Application

Overview of the Bluetooth accessory APIs available in Android.

Dave Smith

November 12, 2013
Tweet

More Decks by Dave Smith

Other Decks in Programming

Transcript

  1. Talk to Your Toaster: Bluetooth In Your Applica6on Dave Smith

    @devunwired Get the Examples: h.p://github.com/devunwired/accessory-samples
  2. Bluetooth “Classic” Basics 3 • Device Discovery – Search field

    of range for discoverable devices – Discoverable devices can be queried for name, class, list of services • Pairing/Bonding – Before a connec6on can be established – As of Bluetooth 2.1, authen6ca6on is op6onal using Secure Simple Pairing (SSP) – Pairing is the process that leads to a two devices being bonded • Protocols and Profiles – Devices implement profiles, built on top of protocols, to provide services to clients – Logical Link Control and Adapta6on Protocol (L2CAP) • Advanced Audio Distribu6on Profile (A2DP) • Human Interface Device (HID) – Radio Frequency Communica6ons (RFCOMM) • Serial Port Profile (SPP) – Service Discovery Protocol (SDP) • Client/Server Model – Servers "have" data, clients "access" data. Mobile device typically the client.
  3. Bluetooth Services • Each device publishes one or more services

    available to connect with • Iden6fied by a UUID – Standard services are 16-bit added to a common 128-bit base: • 00000000-0000-1000-8000-00805F9B34FB – Custom services can be any generated UUID • Common Service UUIDs – RFCOMM: 0x0003 – L2CAP: 0x0100 – Serial Port (SPP): 0x1101 – A2DP AudioSource: 0x110A – A2DP AudioSink: 0x110B • Full SPP UUID = 00001101-0000-1000-8000-00805F9B34FB 4
  4. Bluetooth LE 6 • Bluetooth 4.0 (Bluetooth Smart) – Uses

    the General Aeributes (GATT) profile, built on the Aeributes (ATT) protocol – S6ll runs on top of L2CAP protocol • Server (accessory) devices adver6se presence – Contrast with listeners in BT Classic • Client devices scan for adver6sement packets • Device Roles – Central (client) – Peripheral (server) – Broadcaster (server) – Observer (client) • Central and Observer roles only in the current APIs
  5. GATT Profile Service <16-bit AssignedNumber> Service <UUID> GATT Peripheral 7

    Characteris6c Proper6es Value Characteris6c Proper6es Value Characteris6c Proper6es Value Characteris6c Proper6es Value Characteris6c Proper6es Value Characteris6c Proper6es Value Characteris6c Proper6es Value Characteris6c Proper6es Value
  6. Visualizing the Stack 8 RF Radio Link Layer L2CAP Protocol

    RFCOMM Protocol Serial Port Profile RF Radio Link Layer L2CAP Protocol Attribute Protocol GATT Profile Bluetooth 2.1 BR/EDR Bluetooth 4.0 LE • Bluetooth Classic – Single mode – No BLE support • Bluetooth Smart – Single mode – BLE only • Bluetooth Smart Ready – Dual mode
  7. Bluetooth APIs 9 2.0 2.3.3 3.0 RFCOMM Support Insecure RFCOMM

    (SSP) Classic Profile Support A2DP HFP HDP
  8. BluetoothDevice BluetoothAdapter getBondedDevices() getRemoteDevice(ADDRESS) Async Scan Broadcast ACTION_FOUND Broadcast ACTION_DISCOVERY_FINISHED

    startDiscovery() cancelDiscovery() Discovering Classic Devices 10 BluetoothDevice BluetoothAdapter
  9. Service UUID Discovery (Op6onal) Class cl = Class.forName("android.bluetooth.BluetoothDevice");
 Class[] par

    = {};
 Method method = cl.getMethod("getUuids", par);
 Object[] args = {};
 ParcelUuid[] retval = (ParcelUuid[]) method.invoke(device, args);
 String uuid = retval[0].toString(); • Public APIs to discover service UUIDs added in 4.0.3 (API 15) • For earlier versions BluetoothDevice Async Scan ParcelUuid fetchUuidsWithSdp() getUuids() Broadcast ACTION_UUID
  10. RFCOMM Connec6ons 12 BluetoothAdapter BluetoothDevice BluetoothSocket BluetoothServerSocket createRfcommSocketToServiceRecord(UUID) createInsecureRfcommSocketToServiceRecord(UUID) accept()

    BluetoothSocket connect() listenUsingRfcommWithServiceRecord(UUID) listenUsingInsecureRfcommWithServiceRecord(UUID) getOutputStream() getInputStream()
  11. GATT Discovery 13 BluetoothDevice BluetoothAdapter BluetoothGatt Async Scan startLeScan(ScanCallback) stopLeScan()

    ScanCallback.onLeScan() connectGatt(GattCallback) BluetoothGattCallback BluetoothGatt BluetoothGattService BluetoothGattCharacteristic BluetoothGattDescriptor discoverServices() onServicesDiscovered() getServices() getService(UUID) getCharacteristics() getCharacteristic(UUID) getDescriptors() getDescriptor(UUID)
  12. GATT Transac6ons 14 BluetoothGattCallback BluetoothGattCharacteristic BluetoothGattDescriptor BluetoothGatt readCharacteristic() writeCharacteristic() readDescriptor()

    writeDescriptor() setCharacteristicNotification() onCharacteristicRead() onCharacteristicWrite() onCharacteristicChanged() onDescriptorRead() onDescriptorWrite()
  13. LE Tips • Wait for read/write callbacks – Don't queue

    up mul6ple commands • Post your results – Callbacks aren't on the main thread • No6fica6ons have to be set local and remote – setCharacteris6cNo6fica6on() for local – writeCharacteris6c() for remote • Max 4 simultaneous ac6ve no6fica6ons • Ensure device has LE support – <uses-feature> in AndroidManifest.xml • "android.hardware.bluetooth_le" – PackageManager.hasSystemFeature() 15
  14. LE Broadcasters • Non-connectable adver6sing devices • Also known as

    beacons • Provides all service data in the adver6sement – Adver6sement Data (AD) Structure – Packet contains collec6on of AD Structures • onLeScan() provides AD collec6on from raw scan record. • Faster access to data – No connec6on overhead • Simpler accessory stack implementa6on 16
  15. Adver6sement Data 17 AD Length AD Type AD Payload AD

    Structure AD Structure AD Structure ... AD Structure AD Structure AD Structure AD Structure ... AD Structure public void onLeScan(BluetoothDevice, int rssi, byte[] scanRecord) Type Iden6fiers are Assigned Numbers by the Bluetooth SIG Device Name, Service UUIDs, Service Data, TX Power, etc. heps://www.bluetooth.org/en-us/specifica6on/assigned-numbers/generic-access-profile
  16. Profile Connec6ons • Android 3.0+ supports connec6ng to certain Bluetooth

    device classes • BluetoothProfile – Common interface for all supported device profiles – Reports connec6on status of any devices matching the profile – Profile-specific ac6ons implemented in subclasses • Use BluetoothAdapter.getProfileProxy() to register a ServiceListener callback for connec6on events – Binder Proxy to control device's Bluetooth Service • ServiceListener is passed an instance of the profile when a device matching it is connected. 18
  17. Headset Example BluetoothHeadset mBluetoothHeadset;
 BluetoothDevice mDevice;
 // Get the default

    adapter
 BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
 private BluetoothProfile.ServiceListener mProfileListener =
 new BluetoothProfile.ServiceListener() {
 public void onServiceConnected(int profile, BluetoothProfile proxy) {
 if (profile == BluetoothProfile.HEADSET) {
 mBluetoothHeadset = (BluetoothHeadset) proxy;
 }
 }
 
 public void onServiceDisconnected(int profile) {
 if (profile == BluetoothProfile.HEADSET) {
 mBluetoothHeadset = null;
 }
 }
 }; // Establish connection to the proxy.
 mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
 
 mDevice = mBluetoothHeadset.getConnectedDevices().get(0);
 mBluetoothHeadset.startVoiceRecognition(mDevice);
 
 // Close proxy connection
 mBluetoothHeadset.stopVoiceRecognition(mDevice);
 mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset); 19
  18. Come Find Me! 21 • Dave Smith • Twieer/App.Net: @devunwired

    • Google+: hep://plus.google.com/+DaveSmithDev • Blog: hep://wiresareobsolete.com • Our Work: hep://www.doubleencore.com • Beacon Hardware – hep://www.kstechnologies.com/ • Samples – hep://www.github.com/devunwired/accessory-samples