SlideShare a Scribd company logo
A brief overview
of BLE on Android
Luka Bašek, Android engineer @ Ars Futura
Scope
1. Internet of Things
2. Bluetooth Low Energy
3. BLE on Android
4. Showcase
5. Tips
6. Resources
1. Internet of Things
System of devices embedded with sensors, software,
electronics and connectivity to allow it to perform exchanging
information with other connected devices or networks.
IoT Features
• Connectivity
• Data
• Communication Protocols
• Analyzing
• Intelligence
• Action
Communication protocols
Source: industrytoday.com
2. Bluetooth Low Energy
• WPAN
• 100m range
• Low power and long life span devices
• Easy connection - communication
• Small amount of data
Device Roles
• Peripheral (Server)
• Data provider
• Responds to commands
• BLE device (e.g. Smartwatch)
• Central (Client)
• Data consumer
• Send commands
• Mobile device
Peripheral
(GATT Server)
Profile
Services
Characteristics
Central
Connect peripheral to
Read/Write
attributes
Generic Attribute Profile (GATT)
• Define how to exchange data using
predefined attributes
• Peripheral side
• Service - a group of one or more
Characteristics
• Characteristics - represents a
piece of information/data that a
server wants to expose to a client
• Operation: Read, Write and Subscribe
• Descriptor - metadata
• Each property has its own UUID
Profile
Service Service
Characteristics
Characteristics
Characteristics
Characteristics
Value
Descriptor
Descriptor
Value
Descriptor
Descriptor
Value
Descriptor
Descriptor
Value
Descriptor
Descriptor
Weather station GATT- Example
Weather Station Profile
SERVICE_SENSOR
UUID: ("4fafc201-1fb5-459e-8fcc-c5c9c331914b”)
CHARACTERISTIC_TEMPERATURE
UUID: ("97ac5581-dc51-4408-869b-f672b46025b4”)
PROPERTY_READ + PROPERTY_NOTIFY
CHARACTERISTIC_HUMIDITY
UUID: ("186457ad-2bea-408e-8616-f978a2b0c2ef”)
PROPERTY_READ + PROPERTY_NOTIFY
3. BLE on Android
Preconditions
• Minimum API level: 18 (Android 4.3)
• Permissions - AndroidManifest.xml
• System feature – BLE
AndroidManifest.xml
<!--Permissions-->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<!--Play Store feature-based filtering-->
<!--Optional-->
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
System Feature - BLE
// Check if Bluetooth adapter enabled
fun isBluetoothEnabled(): Boolean =
(getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter.isEnabled
// Check if Bluetooth Low Energy feature available
fun isBleSupported(): Boolean =
(getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter != null &&
packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
Scanning
// Start BLE Scanner
bluetoothAdapter.bluetoothLeScanner.startScan(
listOf(scanFilter), // Criteria for filtering results from Bluetooth LE scans
scanSettings, // Bluetooth LE scan settings
object : ScanCallback() { // Processing scan results or errors
override fun onScanResult(callbackType: Int, result: ScanResult) {}
override fun onBatchScanResults(results: MutableList<ScanResult>) {}
override fun onScanFailed(errorCode: Int) {}
})
Scanning
2019-10-09 15:26:14.777 27927-27941/co.arsfutura.ble.test W/Binder: Caught a RuntimeException
from the binder stub implementation.
java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION
permission to get scan results
😧 Location permission? 😧
<!--Optional-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location" android:required="true"/>
Scanning
• Be aware about:
• Bluetooth Adapter must be ON
• Location Permission must be granted
• Location Service must be ON
• Scanning must be stopped manually
• bluetoothAdapter.bluetoothLeScanner.stopScan(callback)
GATT Workflow
1. Connect to GATT
2. Discover Services
3. Enable Characteristics notifications
4. Start Communicating
• Read/Write Characteristics values
• Read/Write Descriptor values
• Subscribe on Characteristics changes
Connecting
fun connectToDevice(context: Context, bluetoothDevice: BluetoothDevice){
// Do not use autoConnect = true
bluetoothDevice.connectGatt(context, false, bluetoothGattCallback)
}
Bluetooth GATT Callback
val bluetoothGattCallback : BluetoothGattCallback = object: BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {}
override fun onCharacteristicRead(gatt: BluetoothGatt, char: BluetoothGattCharacteristic, status: Int) {}
override fun onCharacteristicWrite(gatt: BluetoothGatt, char : BluetoothGattCharacteristic, status: Int){}
override fun onCharacteristicChanged(gatt: BluetoothGatt, char : BluetoothGattCharacteristic) {}
override fun onDescriptorWrite(gatt: BluetoothGatt, desc: BluetoothGattDescriptor, status: Int) {}
override fun onDescriptorRead(gatt: BluetoothGatt, desc: BluetoothGattDescriptor, status: Int) {}
}
Discover Services
• Call on newState == BluetoothProfile.STATE_CONNECTED
when(newState){
BluetoothProfile.STATE_CONNECTING -> {}
BluetoothProfile.STATE_CONNECTED -> {
gatt.discoverServices()
}
BluetoothProfile.STATE_DISCONNECTING -> {}
BluetoothProfile.STATE_DISCONNECTED -> {}
}
Enable Characteristics notifications
// Check if Characteristic notifiable
fun isCharacteristicNotifiable(characteristic: BluetoothGattCharacteristic): Boolean {
return characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0
}
// Subscribe on Characteristic change
fun enableNotification(characteristic: BluetoothGattCharacteristic?) {
characteristic?.getDescriptor(SENSOR_DESCRIPTOR_UUID)?.run {
value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt?.writeDescriptor(this)
gatt?.setCharacteristicNotification(characteristic, true)
}
}
😨
Enable Characteristics notifications
override fun onDescriptorWrite(
gatt: BluetoothGatt,
descriptor: BluetoothGattDescriptor,
status: Int ) {
val characteristic = gatt.getService(SERVICE_UUID).getCharacteristic(CHARACTERISTIC_UUID)
characteristic.value = byteArrayOf(1, 1)
gatt.writeCharacteristic(characteristic)
}
🤯
Read/Write Characteristics
fun readDataFromCharacteristic(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic ){
gatt.readCharacteristic(characteristic)
}
fun writeDataToCharacteristic(
gatt: BluetoothGatt,
char: BluetoothGattCharacteristic,
data: ByteArray ) {
char.value = data
gatt.writeCharacteristic(char)
}
Limitations
• Central can be connected to 7 peripherals at a time
• Max 15 characteristics can be observed per peripheral
• Transfer data packet can contain maximum of 20 bytes
(MTU!)
4. Showcase
• ESP32 + BME280
• Temperature + Humidity
• github.com/lbasek/ble-weather-station
5. Tips
• Use a blocking screen if the application requires some of
permissions or location service
• Do every GATT operation serially - Command Queue
• Retry Mechanism - Unstable connection $
• GATT_ERROR : 133 🤬
Libraries
• RxAndroidBle - github.com/Polidea/RxAndroidBle
• BleGattCoroutines - github.com/Beepiz/BleGattCoroutines
• Sweetblue - sweetblue.io
• Android-BLE-Library - github.com/NordicSemiconductor/Android-
BLE-Library
Tools
• nRF Connect for Mobile
• play.google.com
6. Resources
• Bluetooth low energy overview - Official Android Documentation
• Bluetooth Low Energy on Android – Top Tips for the Tricky Bits, Stuart Kent
• Android BLE, Andrew Lunsford
• Practical Bluetooth Low Energy on Android, Erik Hellman
• Getting Started with Bluetooth Low Energy, Kevin Townsend, Carles
Cufí, Akiba, Robert Davidson, O'Reilly Media

More Related Content

What's hot

Bluetooth low energy(ble) wireless technology
Bluetooth low energy(ble) wireless technologyBluetooth low energy(ble) wireless technology
Bluetooth low energy(ble) wireless technology
Lin Steven
 
Advanced ClearPass Workshop
Advanced ClearPass WorkshopAdvanced ClearPass Workshop
Advanced ClearPass Workshop
Aruba, a Hewlett Packard Enterprise company
 
Inter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCInter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPC
Shiju Varghese
 
MP BGP-EVPN 실전기술-1편(개념잡기)
MP BGP-EVPN 실전기술-1편(개념잡기)MP BGP-EVPN 실전기술-1편(개념잡기)
MP BGP-EVPN 실전기술-1편(개념잡기)
JuHwan Lee
 
[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...
[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...
[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...
Jung Hyun Nam
 
Guest Access with ArubaOS
Guest Access with ArubaOSGuest Access with ArubaOS
Actix analyzer lte training
Actix analyzer lte trainingActix analyzer lte training
Actix analyzer lte training
Toi La Toi
 
Evolution of API-driven architectures
Evolution of API-driven architecturesEvolution of API-driven architectures
Evolution of API-driven architectures
Sven Bernhardt
 
Bringing up Aruba Mobility Master, Managed Device & Access Point
Bringing up Aruba Mobility Master, Managed Device & Access PointBringing up Aruba Mobility Master, Managed Device & Access Point
Bringing up Aruba Mobility Master, Managed Device & Access Point
Aruba, a Hewlett Packard Enterprise company
 
Clear pass policy manager advanced_ashwath murthy
Clear pass policy manager advanced_ashwath murthyClear pass policy manager advanced_ashwath murthy
Clear pass policy manager advanced_ashwath murthy
Aruba, a Hewlett Packard Enterprise company
 
Introduction to the new MediaTek LinkIt™ Development Platform for RTOS
Introduction to the new MediaTek LinkIt™ Development Platform for RTOSIntroduction to the new MediaTek LinkIt™ Development Platform for RTOS
Introduction to the new MediaTek LinkIt™ Development Platform for RTOS
MediaTek Labs
 
グレープシティのMicrosoft Azure対応への取り組み
グレープシティのMicrosoft Azure対応への取り組みグレープシティのMicrosoft Azure対応への取り組み
グレープシティのMicrosoft Azure対応への取り組み
Developer Solutions事業部 メシウス株式会社 (旧グレープシティ株式会社)
 
Getting the most out of the aruba policy enforcement firewall
Getting the most out of the aruba policy enforcement firewallGetting the most out of the aruba policy enforcement firewall
Getting the most out of the aruba policy enforcement firewall
Aruba, a Hewlett Packard Enterprise company
 
Cloud computing reference architecture from nist and ibm
Cloud computing reference architecture from nist and ibmCloud computing reference architecture from nist and ibm
Cloud computing reference architecture from nist and ibm
Richard Kuo
 
Ccnp3 lab 3_4_en
Ccnp3 lab 3_4_enCcnp3 lab 3_4_en
Ccnp3 lab 3_4_en
Omar Herrera
 
MTU (maximum transmission unit) & MRU (maximum receive unit)
MTU (maximum transmission unit) & MRU (maximum receive unit)MTU (maximum transmission unit) & MRU (maximum receive unit)
MTU (maximum transmission unit) & MRU (maximum receive unit)
NetProtocol Xpert
 
Airheads Tech Talks: Understanding ClearPass OnGuard Agents
Airheads Tech Talks: Understanding ClearPass OnGuard AgentsAirheads Tech Talks: Understanding ClearPass OnGuard Agents
Airheads Tech Talks: Understanding ClearPass OnGuard Agents
Aruba, a Hewlett Packard Enterprise company
 
FlexVPN
FlexVPNFlexVPN
FlexVPN
Cisco Russia
 
20121120 handover in lte
20121120 handover in lte20121120 handover in lte
20121120 handover in lte
srikrishna krishna
 
EMEA Airheads- ArubaOS - Understanding Control-Plane-Security
EMEA Airheads-  ArubaOS - Understanding Control-Plane-SecurityEMEA Airheads-  ArubaOS - Understanding Control-Plane-Security
EMEA Airheads- ArubaOS - Understanding Control-Plane-Security
Aruba, a Hewlett Packard Enterprise company
 

What's hot (20)

Bluetooth low energy(ble) wireless technology
Bluetooth low energy(ble) wireless technologyBluetooth low energy(ble) wireless technology
Bluetooth low energy(ble) wireless technology
 
Advanced ClearPass Workshop
Advanced ClearPass WorkshopAdvanced ClearPass Workshop
Advanced ClearPass Workshop
 
Inter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCInter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPC
 
MP BGP-EVPN 실전기술-1편(개념잡기)
MP BGP-EVPN 실전기술-1편(개념잡기)MP BGP-EVPN 실전기술-1편(개념잡기)
MP BGP-EVPN 실전기술-1편(개념잡기)
 
[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...
[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...
[THR20007] WSL v2와 Rancher K3S로 빠르게 로컬 쿠버네티스 클러스터 만들기 / Quickly create a loca...
 
Guest Access with ArubaOS
Guest Access with ArubaOSGuest Access with ArubaOS
Guest Access with ArubaOS
 
Actix analyzer lte training
Actix analyzer lte trainingActix analyzer lte training
Actix analyzer lte training
 
Evolution of API-driven architectures
Evolution of API-driven architecturesEvolution of API-driven architectures
Evolution of API-driven architectures
 
Bringing up Aruba Mobility Master, Managed Device & Access Point
Bringing up Aruba Mobility Master, Managed Device & Access PointBringing up Aruba Mobility Master, Managed Device & Access Point
Bringing up Aruba Mobility Master, Managed Device & Access Point
 
Clear pass policy manager advanced_ashwath murthy
Clear pass policy manager advanced_ashwath murthyClear pass policy manager advanced_ashwath murthy
Clear pass policy manager advanced_ashwath murthy
 
Introduction to the new MediaTek LinkIt™ Development Platform for RTOS
Introduction to the new MediaTek LinkIt™ Development Platform for RTOSIntroduction to the new MediaTek LinkIt™ Development Platform for RTOS
Introduction to the new MediaTek LinkIt™ Development Platform for RTOS
 
グレープシティのMicrosoft Azure対応への取り組み
グレープシティのMicrosoft Azure対応への取り組みグレープシティのMicrosoft Azure対応への取り組み
グレープシティのMicrosoft Azure対応への取り組み
 
Getting the most out of the aruba policy enforcement firewall
Getting the most out of the aruba policy enforcement firewallGetting the most out of the aruba policy enforcement firewall
Getting the most out of the aruba policy enforcement firewall
 
Cloud computing reference architecture from nist and ibm
Cloud computing reference architecture from nist and ibmCloud computing reference architecture from nist and ibm
Cloud computing reference architecture from nist and ibm
 
Ccnp3 lab 3_4_en
Ccnp3 lab 3_4_enCcnp3 lab 3_4_en
Ccnp3 lab 3_4_en
 
MTU (maximum transmission unit) & MRU (maximum receive unit)
MTU (maximum transmission unit) & MRU (maximum receive unit)MTU (maximum transmission unit) & MRU (maximum receive unit)
MTU (maximum transmission unit) & MRU (maximum receive unit)
 
Airheads Tech Talks: Understanding ClearPass OnGuard Agents
Airheads Tech Talks: Understanding ClearPass OnGuard AgentsAirheads Tech Talks: Understanding ClearPass OnGuard Agents
Airheads Tech Talks: Understanding ClearPass OnGuard Agents
 
FlexVPN
FlexVPNFlexVPN
FlexVPN
 
20121120 handover in lte
20121120 handover in lte20121120 handover in lte
20121120 handover in lte
 
EMEA Airheads- ArubaOS - Understanding Control-Plane-Security
EMEA Airheads-  ArubaOS - Understanding Control-Plane-SecurityEMEA Airheads-  ArubaOS - Understanding Control-Plane-Security
EMEA Airheads- ArubaOS - Understanding Control-Plane-Security
 

Similar to A brief overview of BLE on Android

Eddystone beacons demo
Eddystone beacons demoEddystone beacons demo
Eddystone beacons demo
Angelo Rüggeberg
 
Android & Beacons
Android & Beacons Android & Beacons
Android & Beacons
Tushar Choudhary
 
JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)
SMIJava
 
MCE^3 - Dariusz Seweryn, Paweł Urban - Demystifying Android's Bluetooth Low ...
MCE^3 - Dariusz Seweryn, Paweł Urban -  Demystifying Android's Bluetooth Low ...MCE^3 - Dariusz Seweryn, Paweł Urban -  Demystifying Android's Bluetooth Low ...
MCE^3 - Dariusz Seweryn, Paweł Urban - Demystifying Android's Bluetooth Low ...
PROIDEA
 
Demystifying Android's Bluetooth Low Energy at MCE^3 Conf
Demystifying Android's Bluetooth Low Energy at MCE^3 ConfDemystifying Android's Bluetooth Low Energy at MCE^3 Conf
Demystifying Android's Bluetooth Low Energy at MCE^3 Conf
Pawel Urban
 
A Brief Introduction to Bluetooth Low Energy (BLE) on iOS
A Brief Introduction to Bluetooth Low Energy (BLE) on iOSA Brief Introduction to Bluetooth Low Energy (BLE) on iOS
A Brief Introduction to Bluetooth Low Energy (BLE) on iOS
Matt Whitlock
 
HyWAI Web Bluetooth API
HyWAI Web Bluetooth APIHyWAI Web Bluetooth API
HyWAI Web Bluetooth API
Jonathan Jeon
 
Da Arduino ad Android_ illumina il Natale con il BLE
Da Arduino ad Android_ illumina il Natale con il BLEDa Arduino ad Android_ illumina il Natale con il BLE
Da Arduino ad Android_ illumina il Natale con il BLE
infogdgmi
 
Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇
Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇
Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇
Johnny Sung
 
Everything About Bluetooth (淺談藍牙 4.0) - Central 篇
Everything About Bluetooth (淺談藍牙 4.0) - Central 篇Everything About Bluetooth (淺談藍牙 4.0) - Central 篇
Everything About Bluetooth (淺談藍牙 4.0) - Central 篇
Johnny Sung
 
Ble overview and_implementation
Ble overview and_implementationBle overview and_implementation
Ble overview and_implementation
Stanley Chang
 
Assistive Technology_Research
Assistive Technology_ResearchAssistive Technology_Research
Assistive Technology_Research
Meng Kry
 
Core Bluetooth and BLE 101
Core Bluetooth and BLE 101Core Bluetooth and BLE 101
Core Bluetooth and BLE 101
Li Lin
 
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Jakub Botwicz
 
Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01
ramaswamireddy challa
 
Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01
nagapriyanka
 
Control Pc Via Bluetooth Enable Mobile
Control Pc Via Bluetooth Enable MobileControl Pc Via Bluetooth Enable Mobile
Control Pc Via Bluetooth Enable Mobile
Samiul Hoque
 
Esp32 bluetooth networking_user_guide_en
Esp32 bluetooth networking_user_guide_enEsp32 bluetooth networking_user_guide_en
Esp32 bluetooth networking_user_guide_en
Shubham Jaiswal
 
Fiware IoT Proposal & Community
Fiware IoT Proposal & Community Fiware IoT Proposal & Community
Fiware IoT Proposal & Community
TIDChile
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
John Lewis
 

Similar to A brief overview of BLE on Android (20)

Eddystone beacons demo
Eddystone beacons demoEddystone beacons demo
Eddystone beacons demo
 
Android & Beacons
Android & Beacons Android & Beacons
Android & Beacons
 
JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)
 
MCE^3 - Dariusz Seweryn, Paweł Urban - Demystifying Android's Bluetooth Low ...
MCE^3 - Dariusz Seweryn, Paweł Urban -  Demystifying Android's Bluetooth Low ...MCE^3 - Dariusz Seweryn, Paweł Urban -  Demystifying Android's Bluetooth Low ...
MCE^3 - Dariusz Seweryn, Paweł Urban - Demystifying Android's Bluetooth Low ...
 
Demystifying Android's Bluetooth Low Energy at MCE^3 Conf
Demystifying Android's Bluetooth Low Energy at MCE^3 ConfDemystifying Android's Bluetooth Low Energy at MCE^3 Conf
Demystifying Android's Bluetooth Low Energy at MCE^3 Conf
 
A Brief Introduction to Bluetooth Low Energy (BLE) on iOS
A Brief Introduction to Bluetooth Low Energy (BLE) on iOSA Brief Introduction to Bluetooth Low Energy (BLE) on iOS
A Brief Introduction to Bluetooth Low Energy (BLE) on iOS
 
HyWAI Web Bluetooth API
HyWAI Web Bluetooth APIHyWAI Web Bluetooth API
HyWAI Web Bluetooth API
 
Da Arduino ad Android_ illumina il Natale con il BLE
Da Arduino ad Android_ illumina il Natale con il BLEDa Arduino ad Android_ illumina il Natale con il BLE
Da Arduino ad Android_ illumina il Natale con il BLE
 
Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇
Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇
Everything About Bluetooth (淺談藍牙 4.0) - Peripheral 篇
 
Everything About Bluetooth (淺談藍牙 4.0) - Central 篇
Everything About Bluetooth (淺談藍牙 4.0) - Central 篇Everything About Bluetooth (淺談藍牙 4.0) - Central 篇
Everything About Bluetooth (淺談藍牙 4.0) - Central 篇
 
Ble overview and_implementation
Ble overview and_implementationBle overview and_implementation
Ble overview and_implementation
 
Assistive Technology_Research
Assistive Technology_ResearchAssistive Technology_Research
Assistive Technology_Research
 
Core Bluetooth and BLE 101
Core Bluetooth and BLE 101Core Bluetooth and BLE 101
Core Bluetooth and BLE 101
 
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
Cotopaxi - IoT testing toolkit (Black Hat Asia 2019 Arsenal)
 
Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01
 
Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01Controlpcviabluetoothenablemobile 091028150632-phpapp01
Controlpcviabluetoothenablemobile 091028150632-phpapp01
 
Control Pc Via Bluetooth Enable Mobile
Control Pc Via Bluetooth Enable MobileControl Pc Via Bluetooth Enable Mobile
Control Pc Via Bluetooth Enable Mobile
 
Esp32 bluetooth networking_user_guide_en
Esp32 bluetooth networking_user_guide_enEsp32 bluetooth networking_user_guide_en
Esp32 bluetooth networking_user_guide_en
 
Fiware IoT Proposal & Community
Fiware IoT Proposal & Community Fiware IoT Proposal & Community
Fiware IoT Proposal & Community
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 

Recently uploaded

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLESINTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
anfaltahir1010
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
ISH Technologies
 

Recently uploaded (20)

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLESINTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
 

A brief overview of BLE on Android

  • 1. A brief overview of BLE on Android Luka Bašek, Android engineer @ Ars Futura
  • 2. Scope 1. Internet of Things 2. Bluetooth Low Energy 3. BLE on Android 4. Showcase 5. Tips 6. Resources
  • 3. 1. Internet of Things System of devices embedded with sensors, software, electronics and connectivity to allow it to perform exchanging information with other connected devices or networks.
  • 4. IoT Features • Connectivity • Data • Communication Protocols • Analyzing • Intelligence • Action
  • 6. 2. Bluetooth Low Energy • WPAN • 100m range • Low power and long life span devices • Easy connection - communication • Small amount of data
  • 7. Device Roles • Peripheral (Server) • Data provider • Responds to commands • BLE device (e.g. Smartwatch) • Central (Client) • Data consumer • Send commands • Mobile device Peripheral (GATT Server) Profile Services Characteristics Central Connect peripheral to Read/Write attributes
  • 8. Generic Attribute Profile (GATT) • Define how to exchange data using predefined attributes • Peripheral side • Service - a group of one or more Characteristics • Characteristics - represents a piece of information/data that a server wants to expose to a client • Operation: Read, Write and Subscribe • Descriptor - metadata • Each property has its own UUID Profile Service Service Characteristics Characteristics Characteristics Characteristics Value Descriptor Descriptor Value Descriptor Descriptor Value Descriptor Descriptor Value Descriptor Descriptor
  • 9. Weather station GATT- Example Weather Station Profile SERVICE_SENSOR UUID: ("4fafc201-1fb5-459e-8fcc-c5c9c331914b”) CHARACTERISTIC_TEMPERATURE UUID: ("97ac5581-dc51-4408-869b-f672b46025b4”) PROPERTY_READ + PROPERTY_NOTIFY CHARACTERISTIC_HUMIDITY UUID: ("186457ad-2bea-408e-8616-f978a2b0c2ef”) PROPERTY_READ + PROPERTY_NOTIFY
  • 10. 3. BLE on Android
  • 11. Preconditions • Minimum API level: 18 (Android 4.3) • Permissions - AndroidManifest.xml • System feature – BLE
  • 12. AndroidManifest.xml <!--Permissions--> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <!--Play Store feature-based filtering--> <!--Optional--> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
  • 13. System Feature - BLE // Check if Bluetooth adapter enabled fun isBluetoothEnabled(): Boolean = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter.isEnabled // Check if Bluetooth Low Energy feature available fun isBleSupported(): Boolean = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter != null && packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
  • 14. Scanning // Start BLE Scanner bluetoothAdapter.bluetoothLeScanner.startScan( listOf(scanFilter), // Criteria for filtering results from Bluetooth LE scans scanSettings, // Bluetooth LE scan settings object : ScanCallback() { // Processing scan results or errors override fun onScanResult(callbackType: Int, result: ScanResult) {} override fun onBatchScanResults(results: MutableList<ScanResult>) {} override fun onScanFailed(errorCode: Int) {} })
  • 15. Scanning 2019-10-09 15:26:14.777 27927-27941/co.arsfutura.ble.test W/Binder: Caught a RuntimeException from the binder stub implementation. java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results 😧 Location permission? 😧 <!--Optional--> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-feature android:name="android.hardware.location" android:required="true"/>
  • 16. Scanning • Be aware about: • Bluetooth Adapter must be ON • Location Permission must be granted • Location Service must be ON • Scanning must be stopped manually • bluetoothAdapter.bluetoothLeScanner.stopScan(callback)
  • 17. GATT Workflow 1. Connect to GATT 2. Discover Services 3. Enable Characteristics notifications 4. Start Communicating • Read/Write Characteristics values • Read/Write Descriptor values • Subscribe on Characteristics changes
  • 18. Connecting fun connectToDevice(context: Context, bluetoothDevice: BluetoothDevice){ // Do not use autoConnect = true bluetoothDevice.connectGatt(context, false, bluetoothGattCallback) }
  • 19. Bluetooth GATT Callback val bluetoothGattCallback : BluetoothGattCallback = object: BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {} override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {} override fun onCharacteristicRead(gatt: BluetoothGatt, char: BluetoothGattCharacteristic, status: Int) {} override fun onCharacteristicWrite(gatt: BluetoothGatt, char : BluetoothGattCharacteristic, status: Int){} override fun onCharacteristicChanged(gatt: BluetoothGatt, char : BluetoothGattCharacteristic) {} override fun onDescriptorWrite(gatt: BluetoothGatt, desc: BluetoothGattDescriptor, status: Int) {} override fun onDescriptorRead(gatt: BluetoothGatt, desc: BluetoothGattDescriptor, status: Int) {} }
  • 20. Discover Services • Call on newState == BluetoothProfile.STATE_CONNECTED when(newState){ BluetoothProfile.STATE_CONNECTING -> {} BluetoothProfile.STATE_CONNECTED -> { gatt.discoverServices() } BluetoothProfile.STATE_DISCONNECTING -> {} BluetoothProfile.STATE_DISCONNECTED -> {} }
  • 21. Enable Characteristics notifications // Check if Characteristic notifiable fun isCharacteristicNotifiable(characteristic: BluetoothGattCharacteristic): Boolean { return characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0 } // Subscribe on Characteristic change fun enableNotification(characteristic: BluetoothGattCharacteristic?) { characteristic?.getDescriptor(SENSOR_DESCRIPTOR_UUID)?.run { value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE gatt?.writeDescriptor(this) gatt?.setCharacteristicNotification(characteristic, true) } } 😨
  • 22. Enable Characteristics notifications override fun onDescriptorWrite( gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int ) { val characteristic = gatt.getService(SERVICE_UUID).getCharacteristic(CHARACTERISTIC_UUID) characteristic.value = byteArrayOf(1, 1) gatt.writeCharacteristic(characteristic) } 🤯
  • 23. Read/Write Characteristics fun readDataFromCharacteristic( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic ){ gatt.readCharacteristic(characteristic) } fun writeDataToCharacteristic( gatt: BluetoothGatt, char: BluetoothGattCharacteristic, data: ByteArray ) { char.value = data gatt.writeCharacteristic(char) }
  • 24. Limitations • Central can be connected to 7 peripherals at a time • Max 15 characteristics can be observed per peripheral • Transfer data packet can contain maximum of 20 bytes (MTU!)
  • 25. 4. Showcase • ESP32 + BME280 • Temperature + Humidity • github.com/lbasek/ble-weather-station
  • 26. 5. Tips • Use a blocking screen if the application requires some of permissions or location service • Do every GATT operation serially - Command Queue • Retry Mechanism - Unstable connection $ • GATT_ERROR : 133 🤬
  • 27. Libraries • RxAndroidBle - github.com/Polidea/RxAndroidBle • BleGattCoroutines - github.com/Beepiz/BleGattCoroutines • Sweetblue - sweetblue.io • Android-BLE-Library - github.com/NordicSemiconductor/Android- BLE-Library
  • 28. Tools • nRF Connect for Mobile • play.google.com
  • 29. 6. Resources • Bluetooth low energy overview - Official Android Documentation • Bluetooth Low Energy on Android – Top Tips for the Tricky Bits, Stuart Kent • Android BLE, Andrew Lunsford • Practical Bluetooth Low Energy on Android, Erik Hellman • Getting Started with Bluetooth Low Energy, Kevin Townsend, Carles Cufí, Akiba, Robert Davidson, O'Reilly Media