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

Getting started with Android BLE

Getting started with Android BLE

Paresh Mayani

May 11, 2015
Tweet

More Decks by Paresh Mayani

Other Decks in Technology

Transcript

  1. What is BLE? Bluetooth Low Energy Optimized for small burst

    of data Very short wake-up/connection time Improved battery life (Lower power consumption) Short range Coin-cell battery (Ideal for sensors and beacons)
  2. Difference between classic BT and BLE Classic Bluetooth technology Bluetooth

    Low Energy technology Data payload throughput 2 Mbps ~ 100 kbps Connection set-up speed Weak Strong Range 300m 250m Power consumption High Low Large scale network Weak Good Source: http://www.connectblue.com/technologies/bluetooth-low-energy-technology/
  3. Difference between NFC and BLE NFC BLE Setup Time <0.1

    ms ~ 6 seconds Range Up to 10 cm Up to 250 m Usability Human centric easy, intuitive, fast Data centric medium Security High Low Connection Point to Point (P2P) Personal area network (WPAN)
  4. Application (App) Generic Access Profile (GAP) Security Manager Protocol (SMP)

    Logical Link Control and Application Protocol (L2CAP) Generic Attribute Profile (GATT) Attribute Protocol (ATT) Link Layer (LL) LE Physical Layer (PHY) Host Controller Interface (HCI) Application Host Controller
  5. Link Layer (LL) LE Physical Layer (PHY) - Contains the

    analog communications circuitry (Transmits and receives packets over the physical channel) - Modulating and demodulating analog signal and transforming them into the digital symbols
  6. Link Layer (LL) LE Physical Layer (PHY) - Combination of

    custom hardware and software - Controls the state of the transceiver, determining whether it’s advertising, scanning, initiating, connected, or standing by
  7. Link Layer (LL) LE Physical Layer (PHY) Host Controller Interface

    (HCI) - Processes all communications between the host and controller
  8. - Provides data encapsulation services for the upper layers. -

    Takes large packets from the upper layers and breaks them into chunks Generic Access Profile (GAP) Security Manager Protocol (SMP) Generic Attribute Profile (GATT) Attribute Protocol (ATT) Logical Link Control and Application Protocol (L2CAP)
  9. - Generates, manages, and stores encryption & identity keys to

    enable two devices to communicate securely over a dedicated L2CAP channel. Generic Access Profile (GAP) Security Manager Protocol (SMP) Generic Attribute Profile (GATT) Attribute Protocol (ATT) Logical Link Control and Application Protocol (L2CAP)
  10. Generic Attribute Profile (GATT) - Enables a device to reveal

    certain of its attributes to another device - Each attribute is uniquely identified by a Universally Unique Identifier (UUID) - The ATT block sets up peer-to-peer communication between an attribute server and a client to be able to exchange this information over a dedicated L2CAP channel Generic Access Profile (GAP) Attribute Protocol (ATT) Logical Link Control and Application Protocol (L2CAP) Security Manager Protocol (SMP)
  11. Generic Attribute Profile (GATT) - Provides the interface between the

    application and Bluetooth profiles and handles device discovery, connection, and services, including security procedures. Generic Access Profile (GAP) Attribute Protocol (ATT) Logical Link Control and Application Protocol (L2CAP) Security Manager Protocol (SMP)
  12. Generic Attribute Profile (GATT) - Builds on the ATT and

    adds a hierarchy and data abstraction model on top of it. - It’s backbone of BLE data transfer because it defines how to exchange all profile and user data over a BLE connection Generic Access Profile (GAP) Attribute Protocol (ATT) Logical Link Control and Application Protocol (L2CAP) Security Manager Protocol (SMP)
  13. GATT - Generic Attribute Profile (GAT) - Defines the way

    that two Bluetooth Low Energy devices transfer data back and forth - Uses concepts of Services and Characteristics - Makes use of Attribute Protocol (ATT)
  14. GATT Transactions/Role GATT Server GATT Client The peripheral, which holds

    the ATT lookup data, service and characteristics definitions The phone/tablet, which sends requests to GATT server All transactions are started by the master device, the GATT Client, which receives response from the slave device, the GATT Server.
  15. Key Terms and Concepts GATT transactions in BLE are based

    on high-level, nested objects called Profiles, Services and Characteristics
  16. Key Terms and Concepts Profile Service Characteristic Value Descriptor Descriptor

    Characteristic Value Descriptor Descriptor Service Characteristic Value Descriptor Descriptor Characteristic Value Descriptor Descriptor
  17. Key Terms and Concepts Services Profiles Pre-defined collection of Services

    e.g. Heart Rate Profile A service is a collection of characteristics. For example, you could have a service called "Heart Rate Monitor" that includes characteristics such as "heart rate measurement."
  18. Key Terms and Concepts Characteristics A characteristic is a data

    value transferred between the client and the server. For example, in addition to the heart rate measurement, a heart rate monitor can also report its current battery voltage, device name, or serial number.
  19. Android BLE - Introduced in Android 4.3 (API 18) -

    Since Android 4.3, support for Bluetooth Low Energy (Bluetooth LE) in the central role - Since Android 5.0, an Android device can now act as a Bluetooth LE peripheral device
  20. BluetoothAdapter - Represents the local device Bluetooth adapter - It

    allows you to perform fundamental Bluetooth tasks, such as initiate device discovery, query a list of connected devices final BluetoothManager bluetoothManager = (BluetoothManager)context.getSystemService (Context.BLUETOOTH_SERVICE); m_BluetoothAdapter = bluetoothManager.getAdapter();
  21. Enable Bluetooth Ensure that Bluetooth is enabled private BluetoothAdapter mBluetoothAdapter;

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
  22. Scan for devices To find BLE devices, you use the

    startLeScan() method. This method takes a BluetoothAdapter.LeScanCallback as a parameter. mBluetoothAdapter.startLeScan(mLeScanCallback); mBluetoothAdapter.stopLeScan(mLeScanCallback);
  23. Scan for devices To find BLE devices, you use the

    startLeScan() method. This method takes a BluetoothAdapter.LeScanCallback as a parameter. mBluetoothAdapter.startLeScan(mLeScanCallback); mBluetoothAdapter.stopLeScan(mLeScanCallback); Deprecated
  24. Scan for particular type of peripherals To find BLE devices,

    you use the startLeScan() method. This method takes a BluetoothAdapter.LeScanCallback as a parameter. public boolean startLeScan (UUID[] serviceUuids, BluetoothAdapter.LeScanCallback callback)
  25. Scan for particular type of peripherals To find BLE devices,

    you use the startLeScan() method. This method takes a BluetoothAdapter.LeScanCallback as a parameter. public boolean startLeScan (UUID[] serviceUuids, BluetoothAdapter.LeScanCallback callback) Deprecated
  26. Scan for devices - API 21 m_BluetoothAdapter.getBluetoothLeScanner().startScan(null, settings, new ScanCallback()

    { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); // do whatever you want to do with ScanResult object // result.getDevice() which returns BluetoothDevice // result.getDevice().getAddress(); } @Override public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); }});
  27. BLE Scan Mode BALANCED LOW_LATENCY LOW_POWER Recommended to only use

    this mode when the application is running in the foreground Scan results are returned at a rate that provides a good trade-off between scan frequency and power consumption. Default scan mode as it consumes the least power.
  28. BLE Scan Mode BALANCED LOW_LATENCY LOW_POWER Recommended to only use

    this mode when the application is running in the foreground Scan results are returned at a rate that provides a good trade-off between scan frequency and power consumption. Default scan mode as it consumes the least power. Improved Battery Life
  29. Connecting BLE Device - The first step in interacting with

    a BLE device - Established by connecting to the GATT server on the device mBluetoothGatt = bluetoothDevice.connectGatt(this, false, mGattCallback); You can use `mBluetoothGatt` object to conduct GATT client operations. (FYI, the caller (the Android app) is the GATT client.)
  30. Connecting BLE Device - The first step in interacting with

    a BLE device - Established by connecting to the GATT server on the device mBluetoothGatt = bluetoothDevice.connectGatt(this, false, mGattCallback); Context boolean autoconnect BluetoothGattCallback
  31. Connecting BLE Device - BluetoothGattCallback private final BluetoothGattCallback mGattCallback =

    new BluetoothGattCallback() { @Override public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { // this will get called anytime you perform a read or write characteristic operation } @Override public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) { // this will get called when a device connects or disconnects } @Override public void onServicesDiscovered(final BluetoothGatt gatt, final int status) { // this will get called after the client initiates a BluetoothGatt.discoverServices() call } }
  32. Connection & discovery private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback()

    { @Override public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) { // this will get called when a device connects or disconnects if (status == BluetoothGatt.GATT_SUCCESS) { if(newState == BluetoothGatt.STATE_CONNECTED) { boolean isServiceDiscovered = bluetoothGattClient.discoverServices(); if (!isServiceDiscovered) bluetoothGattClient.close(); } } } }
  33. Characteristics @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { //

    get service if (status == BluetoothGatt.GATT_SUCCESS) { BluetoothGattService service = gatt.getService(MY_PERIPHERAL_SERVICE_UUID); // get references to read and write characteristics if (service != null) { BluetoothGattCharacteristic characteristic = service .getCharacteristic(MY_PERIPHERAL_SERVICE_READ_CHAR_UUID); } }
  34. Characteristics @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int Status)

    { if (characteristic.getUuid().compareTo(MY_PERIPHERAL_SERVICE_READ_CHAR_UUID) == 0){ byte[] data = characteristic.getValue(); } }
  35. Configure Descriptor for Notify private BluetoothGatt mBluetoothGatt; BluetoothGattCharacteristic characteristic; boolean

    enabled; ... mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); ... BluetoothGattDescriptor descriptor = characteristic.getDescriptor( UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG)); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mBluetoothGatt.writeDescriptor(descriptor);
  36. Receive Notifications @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

    if (characteristic.getUuid().compareTo(MY_PERIPHERAL_SERVICE_READ_CHAR_UUID) == 0){ byte[] data = characteristic.getValue(); } }