Slide 1

Slide 1 text

Getting started with +PareshMayani Android BLE

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

Mobile Enablement + Mobile Quality + Mobile Optimization = InfoStretch

Slide 4

Slide 4 text

Agenda BLE Opportunities Intro to BLE technology BLE Protocol Stack Android BLE Debugging BLE Communication

Slide 5

Slide 5 text

BLE Opportunities everywhere...

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

40% discount on Jeans 20% sale SALE SALE SALE 40% on Jeans 20% on T-shirts

Slide 9

Slide 9 text

Source: http://lagoonuae.com/lagoonuae/pictures/290720101236133613.JPG

Slide 10

Slide 10 text

Welcome to Samsung SFO store. Sale on below products: - Smart TV - Tablet - Mobile

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

Introduction to BLE technology

Slide 14

Slide 14 text

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)

Slide 15

Slide 15 text

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/

Slide 16

Slide 16 text

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)

Slide 17

Slide 17 text

Bluetooth Smart & Bluetooth Smart Ready

Slide 18

Slide 18 text

BLE Protocol Stack

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

Link Layer (LL) LE Physical Layer (PHY) Host Controller Interface (HCI) - Processes all communications between the host and controller

Slide 23

Slide 23 text

- 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)

Slide 24

Slide 24 text

- 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)

Slide 25

Slide 25 text

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)

Slide 26

Slide 26 text

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)

Slide 27

Slide 27 text

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)

Slide 28

Slide 28 text

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)

Slide 29

Slide 29 text

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.

Slide 30

Slide 30 text

Key Terms and Concepts GATT transactions in BLE are based on high-level, nested objects called Profiles, Services and Characteristics

Slide 31

Slide 31 text

Key Terms and Concepts Profile Service Characteristic Value Descriptor Descriptor Characteristic Value Descriptor Descriptor Service Characteristic Value Descriptor Descriptor Characteristic Value Descriptor Descriptor

Slide 32

Slide 32 text

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."

Slide 33

Slide 33 text

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.

Slide 34

Slide 34 text

Android BLE

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

BLE Permissions Declare if you want to make your App available only for BLE capable devices

Slide 37

Slide 37 text

BLE Permissions if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { // No LE Support } To determine whether BLE is supported on the device.

Slide 38

Slide 38 text

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();

Slide 39

Slide 39 text

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); }

Slide 40

Slide 40 text

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);

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

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)

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

Scan for devices - API 21

Slide 45

Slide 45 text

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 results) { super.onBatchScanResults(results); } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); }});

Slide 46

Slide 46 text

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.

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

BLE Scan Mode ScanSettings.Builder settingBuilder = new ScanSettings.Builder(); settingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY); settingBuilder.setReportDelay(0);

Slide 49

Slide 49 text

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.)

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

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 } }

Slide 52

Slide 52 text

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(); } } } }

Slide 53

Slide 53 text

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); } }

Slide 54

Slide 54 text

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(); } }

Slide 55

Slide 55 text

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);

Slide 56

Slide 56 text

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(); } }

Slide 57

Slide 57 text

Debugging BLE Communication

Slide 58

Slide 58 text

Why to debug?

Slide 59

Slide 59 text

Option 1: Wireshark

Slide 60

Slide 60 text

Option 1: Wireshark 1. Unlock Developer options 2. Enable Bluetooth HCI snoop log

Slide 61

Slide 61 text

Option 2: BLE Sniffer

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

+PareshMayani @pareshmayani TechnoTalkative.com Stay in touch...