Bluetooth low energy--bluetooth® lower power

Source: Internet
Author: User

Android4.3 (API level 18) introduces a built-in platform to support the central role of BLE, while providing APIs and app applications for discovering devices, querying services, and reading/writing characteristics. Unlike traditional Bluetooth (Classicbluetooth), Bluetooth low power (BLE) is designed to provide more significant low power consumption. This allows Android applications to communicate with low power requirements for BLE devices such as proximity sensors, heart rate monitors, fitness devices, etc.

Key terminology and concepts

Here is a summary of key BLE terms and concepts:

The Universal Attribute specification (GATT)-gattprofile is a generic specification used to send and receive data slices called "attributes (attributes)" on a ble link. All current low-power application profiles are based on GATT.

The Bluetooth SIG defines many profiles for low-power devices. Profile is a specification that regulates how a device works in a particular application scenario. Note: A device can implement multiple profiles. For example, a device can contain a heart monitor and a battery level detector.

The property Protocol (ATT)-gatt is built on top of the attribute protocol (ATT) and is also commonly referred to as Gatt/att. ATT is optimized for running on BLE devices. To do this, it takes as few bytes as possible to do better. Each attribute property is uniquely identified by the UUID (Universal unique Identifier), and the UUID is the ID of the standard 128-bit format used to uniquely identify the information. Attributes is transmitted by ATT formatted characteristics and services.

Feature (characteristics)-a characteristics contains a separate value and 0–n descriptors that describes the characteristic value. A characteristics can be thought of as a type, similar to a class.

The descriptor (descriptor)-descriptor is a defined attributes used to describe a characteristic value. For example, a descriptor can specify a human-readable description, characteristic a value in an acceptable range, or a unit of measure, to clarify the value of characteristic.

The service-service is a collection of characteristic. For example, you can have a so-called "heart Ratemonitor" service, which includes characteristic, such as "heart rate measurement". You can find a series of profiles and service based on GATT in bluetooth.org.

Roles and Responsibilities

Here are the roles and responsibilities that apply when an Android device interacts with a BLE device:

Center Device (Central) with peripheral devices (peripheral). This also applies to the BLE connection itself. The central device is scanned for advertisenment,peripheral devices to emit advertisement.

GATT Server (server) and gattclient (client). This determines how two devices interact with each other after establishing a connection.

To understand their differences, suppose you have an Android phone and an activity tracker, the activity tracker is a BLE device. The phone plays the central role; the activity tracker plays the peripheral role (setting up a BLE connection must have both.) If two devices support only the central role or the peripheral role, you cannot establish a BLE connection with each other.

Once the phone is connected to the activity tracker, they begin to transfer GATT data to each other. Depending on the kind of data they transmit, one of them may be used as the GATT server. For example, if the Activity tracker reports sensor data to the phone, the activity tracker acts as a server. If the activity tracker wants to receive updates from the phone, then the phone acts as a server.

In the example used in this document, the Android application (running on an Android device) is the GATT client. The application obtains data from the GATT server, a ble heart rate monitor that supports heartrate profile. But you can design?? Your Android? OID application, as the GATT server role. See Bluetoothgattserver for more information.

BLE permissions

In order to use the Bluetooth feature in the app, you must declare Bluetooth permissions to Bluetooth. You need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transmitting data.

If you want your application to launch devices to discover or manipulate Bluetooth settings, you must also declare bluetooth_admin permissions. Note: If you use bluetooth_admin permissions, you must also have Bluetooth permissions.

Declare the Bluetooth permissions in your application manifest (manifest) file. For example:

<uses-permission android:name= "Android.permission.BLUETOOTH"/><uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/>

If you want to declare that your application is only available to the BLE feature device, the manifest in your application includes the following statement:

<uses-feature android:name= "Android.hardware.bluetooth_le" android:required= "true"/>

However, if you want to make your application available to those that do not support BLE devices, you should still include this above statement in your application's manifest, but set required= "false". The BLE availability can then be determined at run time by using Packagemanager.hassystemfeature ():

Use this check to determine whether BLE are supported on the device. then//You can selectively disable ble-related Features.if (!getpackagemanager (). Hassystemfeature ( Packagemanager.feature_bluetooth_le) {Toast.maketext (this, r.string.ble_not_supported, Toast.LENGTH_SHORT). Show ( );    Finish ();}

Set ble

Before your application can make BLE communication, you need to verify that BLE is supported on this device, and if so, make sure it is enabled. Please note that this check is required if <uses-feature.../> is set to false.

If BLE is not supported, then you should disable any BLE function appropriately. If BLE is supported but disabled, then you can ask the user to start Bluetooth without leaving the app. This setup is done in two steps, using Bluetoothadapter.

1. Get Bluetoothadapter

The bluetoothadapter is required for all Bluetooth activities. The bluetoothadapter represents the device's own Bluetooth adapter (Bluetooth radio). Only one Bluetooth adapter is used for the entire system, and your application can interact with that object. The following code snippet shows how to get the adapter. Note that this method uses Getsystemservice () to return an instance of the Bluetoothmanager used to get the adapter. Android 4.3 (API level 18) introduces Bluetoothmanager:

Initializes Bluetooth adapter. Final Bluetoothmanager bluetoothmanager=        (Bluetoothmanager) Getsystemservice (Context.bluetooth_service); Mbluetoothadapter = Bluetoothmanager.getadapter ();

2. Enable Bluetooth

Next, you need to make sure that Bluetooth is enabled. Use IsEnabled () to check whether Bluetooth is currently enabled. If this method returns false, then Bluetooth is disabled. The following code snippet checks if Bluetooth is turned on. If not, the fragment will display an error prompting the user to set to enable Bluetooth:

Private Bluetoothadapter mbluetoothadapter;...//ensures Bluetooth is available on the device and it is enabled. If not,//displays a dialog requesting user permission to enable bluetooth.if (Mbluetoothadapter = null | |!mbluetoothada Pter.isenabled ()) {Intent enablebtintent = new Intent (bluetoothadapter.action_request_enable);    Startactivityforresult (ENABLEBTINTENT,REQUEST_ENABLE_BT); }

Find a BLE device

In order to find the BLE device, you can use the Startlescan () method. This method requires a bluetoothadapter.lescancallback as a parameter. You must implement this callback because it determines how the scan results are returned. Because the scanning power consumption is large, you should abide by the following guidelines:

1) As soon as you find the desired device, stop the scan.

2) do not scan a loop and set your scan time limit. Previously available devices may have moved out of range and continue scanning to drain battery power.

The following code snippet shows how to start and stop a scan:

/** * Activity for scanning and displaying available BLE devices. */public class Devicescanactivity extends Listactiv    ity {private Bluetoothadapter mbluetoothadapter;    Private Boolean mscanning;    Private Handler Mhandler;    Stops scanning after ten seconds.    Private static final Long scan_period = 10000; ... private void Scanledevice (final Boolean enable) {if (enable) {//Stops scanning after a pre-def            ined Scan period. Mhandler.postdelayed (New Runnable () {@Override public void run () {MScan                    ning = false;                Mbluetoothadapter.stoplescan (Mlescancallback);            }}, Scan_period);            Mscanning = true;        Mbluetoothadapter.startlescan (Mlescancallback);            } else {mscanning = false;        Mbluetoothadapter.stoplescan (Mlescancallback); }        ...    } ...}

How do you want to scan a specified type of peripheral device, you can replace it with Startlescan (Uuid[],bluetoothadapter.lescancallback), It provides a set of UUID objects that describe the GATT services that your application supports.

The following is a specific implementation of the interface function Bluetoothadapter.lescancallback for transmitting BLE scan results:

Private Ledevicelistadapter mledevicelistadapter;...//Device scan callback.private bluetoothadapter.lescancallback Mlescancallback =        New Bluetoothadapter.lescancallback () {    @Override public    void Onlescan (final Bluetoothdevice device, int rssi,            byte[] scanrecord) {        runonuithread (new Runnable () {           @Override           public void Run () {               mledevicelistadapter.adddevice (device);               Mledevicelistadapter.notifydatasetchanged ();}});}   ;

Note: You can scan only ble devices or traditional Bluetooth devices, just like Bluetooth describes. You can not scan both BLE devices and traditional Bluetooth devices at the same time.

Connecting to the GATT server

The first step in interacting with a BLE device is to connect to it, more specifically, to the GATT server on the device. To connect to the GATT server on a BLE device, you can use the Connectgatt () method. This method has three parameters: a Context object, a AutoConnect (Boolean value that indicates whether it is automatically connected to the BLE device), and Bluetoothgattcallback:

Mbluetoothgatt = Device.connectgatt (This,false, mgattcallback);

This function connects to the Gattserver on the BLE device and returns a Bluetoothgatt instance that you can use to perform the GATT client operation. The caller (Android application) is the GATT client. The bluetoothgattcallback is used to provide results to the client, such as the connection status, as well as any further GATT client operations.

In this example, the BLE application provides an active (devicecontrolactivity) connection, displays the data, and displays the gattservices and characteristics supported by the device. Depending on the user's input, this activity interacts with a service called Bluetoothleservice, Bluetoothservice interacts with the BLE device via the Android BLE API:

A service that interacts with the BLE device via the Android BLE Api.public class Bluetoothleservice extends service {    Private final static String TAG = BluetoothLeService.class.getSimpleName ();    Private Bluetoothmanager Mbluetoothmanager;    Private Bluetoothadapter Mbluetoothadapter;    Private String mbluetoothdeviceaddress;    Private Bluetoothgatt Mbluetoothgatt;    private int mconnectionstate = state_disconnected;    private static final int state_disconnected = 0;    private static final int state_connecting = 1;    private static final int state_connected = 2;    Public final static String action_gatt_connected = "Com.example.bluetooth.le.ACTION_GATT_CONNECTED";    Public final static String action_gatt_disconnected = "Com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"; Public final static String action_gatt_services_discovered = "Com.example.bluetooth.le.ACTION_GATT_SERVICES_DIS    COVERED "; Public final static String Action_data_available = "Com.example.bluetooth.le.ACTION_DATA_AVAILABLE";    Public final static String Extra_data = "Com.example.bluetooth.le.EXTRA_DATA"; Public final static UUID uuid_heart_rate_measurement = Uuid.fromstring (samplegattattributes.heart_rate_measurem    ENT);    Various callback methods defined by the BLE API. Private final Bluetoothgattcallback mgattcallback = new Bluetoothgattcallback () {@Override publi c void Onconnectionstatechange (Bluetoothgatt gatt, int status, int newstate) {String intentacti            On                if (newstate = = bluetoothprofile.state_connected) {intentaction = action_gatt_connected;                Mconnectionstate = state_connected;                Broadcastupdate (intentaction);                LOG.I (TAG, "Connected to GATT server.");    LOG.I (TAG, "attempting to start service discovery:" + mbluetoothgatt.discoverservices ());        } else if (newstate = = bluetoothprofile.state_disconnected) {intentaction = Action_gatt_disconnect                ED;                Mconnectionstate = state_disconnected;                LOG.I (TAG, "Disconnected from GATT server.");            Broadcastupdate (intentaction); }} @Override//New services discovered public void onservicesdiscovered (Bluetoothgatt GATT, int status) {if (status = = Bluetoothgatt.gatt_success) {broadcastupdate (action_gatt_services_d            iscovered);            } else {LOG.W (TAG, "onservicesdiscovered Received:" + status); }} @Override//Result of a characteristic read operation public void Oncharacteristicread (Bl Uetoothgatt GATT, bluetoothgattcharacteristic characteristic, int status) {if (s Tatus = = bluetoothgatt.gatt_success) {broadcastupdate (action_data_available, CharactEristic); }        }     ...    }; ...}

When a particular callback is triggered, it invokes the corresponding broadcastupdate () helper method and passes it an action. Note that the data in this section is parsed by referring to the Bluetooth heart rate measurement profilespecifications.

private void Broadcastupdate (final String action) {final Intent Intent = new Intent (action); Sendbroadcast (intent);} private void Broadcastupdate (final String action, final bluetoothgattcharacteristic Characteri    Stic) {final Intent Intent = new Intent (action); This was special handling for the heart rate, measurement profile.    Data//parsing is carried out as per profile specifications.        if (Uuid_heart_rate_measurement.equals (Characteristic.getuuid ())) {int flag = characteristic.getproperties ();        int format =-1;            if (flag & 0x01)! = 0) {format = bluetoothgattcharacteristic.format_uint16;        LOG.D (TAG, "heart rate format UINT16.");            } else {format = bluetoothgattcharacteristic.format_uint8;        LOG.D (TAG, "heart rate format UINT8.");        } final int heartrate = characteristic.getintvalue (format, 1); LOG.D (TAG, String.Format ("Received heart rate:%d", hearTrate));    Intent.putextra (Extra_data, string.valueof (heartrate));        } else {//For all other profiles, writes the data formatted in HEX.        Final byte[] data = Characteristic.getvalue (); if (data! = null && data.length > 0) {final StringBuilder StringBuilder = new StringBuilder (data.le            Ngth);            for (byte bytechar:data) stringbuilder.append (String.Format ("%02x", Bytechar));        Intent.putextra (Extra_data, New String (DATA) + "\ n" + stringbuilder.tostring ()); }} sendbroadcast (intent);}

As early as the devicecontrolactivity, these events were handled by a broadcastreceiver:

Handles various events fired by the service.//action_gatt_connected:connected to a GATT server.//action_gatt_disconn Ected:disconnected from a GATT server.//action_gatt_services_discovered:discovered GATT services.//ACTION_DATA_ available:received data from the device. This can a//result of read or notification operations.private final broadcastreceiver mgattupdatereceiver = new BROADC Astreceiver () {@Override public void onreceive (context context, Intent Intent) {final String action = Inten        T.getaction ();            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals (ACTION)) {mconnected = true;            Updateconnectionstate (r.string.connected);        Invalidateoptionsmenu ();            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals (ACTION)) {mconnected = false;            Updateconnectionstate (r.string.disconnected);            Invalidateoptionsmenu ();        Clearui ();         } else if (Bluetoothleservice.       Action_gatt_services_discovered.equals (Action)) {//Show all the supported SERVICES and characteristics            On the//user interface.        Displaygattservices (Mbluetoothleservice.getsupportedgattservices ()); } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals (ACTION)) {Displaydata (Intent.getstringextra (Bluetoo        Thleservice.extra_data)); }    }};

Read the Ble property

Once your Android application is connected to the Gattserver and discoveriable service, it can read and write to the supported attributes. For example, by iterating through the server's service and characteristic this fragment, display them on the UI:

public class Devicecontrolactivity extends Activity {...//demonstrates how to iterate through the supported GATT    Services/characteristics.    In this sample, we populate the data structure, which is bound to the//Expandablelistview on the UI.         private void Displaygattservices (list<bluetoothgattservice> gattservices) {if (gattservices = = null) return;        String uuid = null;                String unknownservicestring = Getresources ().        GetString (R.string.unknown_service);                String unknowncharastring = Getresources ().        GetString (r.string.unknown_characteristic); arraylist

Receiving the GATT notice (notifications)

This is a common device on which the BLE application requirements are notified when a specific characteristic is changed. This code shows how to use the Setcharacteristicnotification () method to set a notifications for characteristic:

Private Bluetoothgatt Mbluetoothgatt; Bluetoothgattcharacteristic Characteristic;boolean Enabled;...mbluetoothgatt.setcharacteristicnotification ( characteristic, enabled);.. Bluetoothgattdescriptor descriptor = characteristic.getdescriptor (        uuid.fromstring ( samplegattattributes.client_characteristic_config));d Escriptor.setvalue (bluetoothgattdescriptor.enable_ Notification_value); Mbluetoothgatt.writedescriptor (descriptor);

Once the property notification is started (notifications for acharacteristic), the oncharacteristicchanged () callback function is started if characteristic changes on the remote device.

@Override//characteristic notificationpublic void oncharacteristicchanged (Bluetoothgatt GATT,        Bluetoothgattcharacteristic characteristic) {    broadcastupdate (action_data_available, characteristic);}

Close the client application

Once your application has been completed using the BLE appliance, you should call Close () so that the system can dispose of the resources appropriately:

public void Close () {    if (Mbluetoothgatt = = null) {        return;    }    Mbluetoothgatt.close ();    Mbluetoothgatt = null;}

Bluetooth low energy--bluetooth® lower power

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.