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

Getting started with Android BLE

Getting started with Android BLE

2c9f04076de133db434c7d9966ac6f6b?s=128

Paresh Mayani

May 11, 2015
Tweet

More Decks by Paresh Mayani

Other Decks in Technology

Transcript

  1. Getting started with +PareshMayani Android BLE

  2. Sr. Software Engineer @ InfoStretch Manager, GDG Ahmedabad +PareshMayani @pareshmayani

  3. Mobile Enablement + Mobile Quality + Mobile Optimization = InfoStretch

  4. Agenda BLE Opportunities Intro to BLE technology BLE Protocol Stack

    Android BLE Debugging BLE Communication
  5. BLE Opportunities everywhere...

  6. But where are the opportunities? BLE Opportunities everywhere...

  7. Source: http://retaildesignblog.net/wp-content/uploads/2012/03/Puma-store-by-Nathan-Lee-Colkitt-Architects-Ontario.jpg

  8. 40% discount on Jeans 20% sale SALE SALE SALE 40%

    on Jeans 20% on T-shirts
  9. Source: http://lagoonuae.com/lagoonuae/pictures/290720101236133613.JPG

  10. Welcome to Samsung SFO store. Sale on below products: -

    Smart TV - Tablet - Mobile
  11. Source: http://cnet4.cbsistatic.com/hub/i/2014/12/19/b1cf9e10-2ffb-4b28-a259-43c4f54cc529/pivotaltracker1.jpg

  12. Source: http://www.blogcdn.com/www.engadget.com/media/2010/10/mobilephone-1286641368.jpg

  13. Introduction to BLE technology

  14. 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)
  15. 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/
  16. 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)
  17. Bluetooth Smart & Bluetooth Smart Ready

  18. BLE Protocol Stack

  19. 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
  20. 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
  21. 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
  22. Link Layer (LL) LE Physical Layer (PHY) Host Controller Interface

    (HCI) - Processes all communications between the host and controller
  23. - 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)
  24. - 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)
  25. 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)
  26. 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)
  27. 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)
  28. 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)
  29. 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.
  30. Key Terms and Concepts GATT transactions in BLE are based

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

    Characteristic Value Descriptor Descriptor Service Characteristic Value Descriptor Descriptor Characteristic Value Descriptor Descriptor
  32. 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."
  33. 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.
  34. Android BLE

  35. 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
  36. BLE Permissions <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-feature android:name="android.hardware.bluetooth_le"

    android:required="true" /> Declare if you want to make your App available only for BLE capable devices
  37. BLE Permissions if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { // No LE Support }

    To determine whether BLE is supported on the device.
  38. 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();
  39. 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); }
  40. 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);
  41. 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
  42. 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)
  43. 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
  44. Scan for devices - API 21

  45. 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); }});
  46. 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.
  47. 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
  48. BLE Scan Mode ScanSettings.Builder settingBuilder = new ScanSettings.Builder(); settingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY); settingBuilder.setReportDelay(0);

  49. 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.)
  50. 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
  51. 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 } }
  52. 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(); } } } }
  53. 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); } }
  54. 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(); } }
  55. 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);
  56. 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(); } }
  57. Debugging BLE Communication

  58. Why to debug?

  59. Option 1: Wireshark

  60. Option 1: Wireshark 1. Unlock Developer options 2. Enable Bluetooth

    HCI snoop log
  61. Option 2: BLE Sniffer

  62. None
  63. +PareshMayani @pareshmayani TechnoTalkative.com Stay in touch...