您的位置:首页 > 产品设计 > UI/UE

Bluetooth Low Energy(低功耗蓝牙)-For蓝牙4.x

2014-12-29 19:44 232 查看
此文翻译至Android API里的Bluetooth Low Energy,希望对大家有所帮助。谢谢。

Android4.3(API版本18)介绍了内置平台支持BLE的中心角色,并且提供了相关API,高大尚的程序员们可以使用这些API来扫描设备、查询服务(指服务端进程)、读写特性值(指特定的字符)。与经典蓝牙不同的是,BLE的设计是为了提供显著的低功耗支持。这使得Android应用可以仅需很低的功耗与BLE设备进行通信,心跳频率(不是人的心跳,是指发送心跳包检测设备是否还在),监听适配设备等等。

一、关键术语和概念

这里是关于BLE关键术语和概念的一个总结:

通用属性描述[Generic Attribute Profile](GATT)-GATT是为通过BLE链接发送和接收的短数据(属性值)而做的一个规范描述。现在所有的BLE应用描述都是基于GATT的。

蓝牙SIG(貌似一个组织)为低功耗设备定义了很多描述。一个描述(Profile)是一个设备如何在特定应用中的工作规范。注意一个设备可以实现不止一个(多个)描述。举个例子,一个设备可以包含一个心跳监听的描述和一个电池电量的描述。

属性协议[Attribute Protocol](ATT)-GATT是建立在ATT之上的。它们一起指的是GATT/ATT(类似于TCP/IP的概念)。ATT对在BLE设备上的运行进行优化。为此,它使用尽可能少的字节。每个属性都是由一个全局唯一标识符唯一地标识(UUID),这是一个字符串ID,一个标准的128位格式,用于唯一标识信息。这里的attributes(属性)的传输被ATT格式化为characteristics和services。

特征[Characteristic]-一个characteristic包含一个唯一的值和0到n个描述数来描述characteristic的值。一个characteristic可以被看作一个数据类型,或者一个类。

描述符[Descriptor]-Descriptor被定义为一些属性用来描述一个characteristic的值。例如,一个描述符可能特指为一个只有人才可以读的描述,characteristic的值的一个可接受的范围。或者是characteristic的一个测量单元。

服务[Service]-一个服务是一个characteristic的一个集合。例如,你可以有一个服务叫“心率监测”,包括“心率测量的特点。你可以在bluetooth.org找到一个现有的基于profiles和services的GATT的列表。

二、角色和职责

这里是当一个Anroid设备和一个BLE设备进行交互时的角色和职责:

中心与边缘[Central vs. Peripheral]。这应用在BLE连接它自己。中心角色的设备可以扫描、寻找adertisement,边缘角色是产生adertisement的。

GATT服务端和GATT客户端。这决定两个设备一旦键立连接应该怎么通话。

要明白这两者的区别,例如你有一个Android手机和一个活动的BLE跟踪设备。手机是中心角色;BLE是边缘角色(要建立一个BLE通道,你不能只有中心角色也不能只有边缘角色)。

一旦手机和BLE建立了一个通道,它们就可能向对方传输GATT元数据了。根据它们所传输的数据类型,一个或另一个会作为server。例如,如果一个跟踪BLE设备要向手机传送传感器的数据,那么跟踪BLE设备就要担当为server。如果跟踪BLE设备要接收手机发来的更新数据,那边手机将作为server。

在本文档中使用的示例,Android的应用程序(在Android设备上运行)是GATT的客户端。程序从GATT服务器获取数据,它是一个支持心率检测的心率描述(Heart Rate Profile)。但你也可以设计你的Android应用程序来发挥GATT的服务器角色。更多信息参见BluetoothGattServer。

三、程序实例

1、BLE权限

为了使你的应用可以实现蓝牙,你必需定义蓝牙权限:BLUETOOTH。你可以使用此权限执行任何蓝牙通信,比如,请求一个连接,接受一个连接,或者传输数据。

如果你想让你的App可以扫描蓝牙设备或者是其它蓝牙设置,那么你必需声明BLUETOOTH_ADMIN权限。注意:如果你声明了BLUETOOTH_ADMIN权限,那么你必须声明BLUETOOTH权限。

声明权限:

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

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

如果你想让你的APP只在BLE设备才有效的话,你还需在AndroidManifest.xml里加入此句:

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

然而,如果你想让你的APP不支持BLE那边你也需加入:<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>然后你可以在程序运行时检测是否支持BLE:

// Use this check to determine whether BLE is 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();

}

2、设置BLE

在你的程序可以能过BLE通道通信之前,你需要先验证是否支持BLE,还有是否可开。注意,检测只在<uses-feature.../>设置为false时需要。

如果BLE不支持,很遗憾你不能使用BLE的特性。如果支持BLE但是没有打开,那么你需要请求用户打开。这个可以通过两个步骤完成,使用BluetoothAdapter。

1)获得BluetoothAdapter

BluetoothAdapter可以为所有Bluetooth activity所申请。BluetoothAdapter代表一个设备(本机设备)。对于整个系统只有一个BluetoothAdapter,你的应用程序可以使用它进行交互。下面是如何申请一个BluetoothAdapter。参见Android4.3(API Level 18)关于BluetoothManager的详细介绍:

// Initializes Bluetooth adapter.

final BluetoothManager bluetoothManager =

(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

mBluetoothAdapter = bluetoothManager.getAdapter();

2)打开蓝牙

下一步你需要检测你的蓝牙是否打开。用isEnabled进行检测。如果false则是关闭,相反已经打开。代码如下:

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 || !mBluetoothAdapter.isEnabled()) {

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

3、查找BLE设备

为了查找BLE设备,你可以使用startLeScan()方法。这个方法需要一个BluetoothAdapter.LeScanCallback作为参数。你必需实现callback,这是为了接收查找到的蓝牙设备的回调函数。因为查找很耗电,所以你必须遵循下面的规则:

a、一找到你需要的设备就要停止

b、不要在一个循环里进行扫描,要设一个扫描时间限制。如果一个设备移动超过范围,就要根据电量许可继续扫描。

下面是开始和关闭扫描的步骤:

/**

* Activity for scanning and displaying available BLE devices.

*/

public class DeviceScanActivity extends ListActivity {

private BluetoothAdapter mBluetoothAdapter;

private boolean mScanning;

private Handler mHandler;

// Stops scanning after 10 seconds.

private static final long SCAN_PERIOD = 10000;

...

private void scanLeDevice(final boolean enable) {

if (enable) {

// Stops scanning after a pre-defined scan period.

mHandler.postDelayed(new Runnable() {

@Override

public void run() {

mScanning = false;

mBluetoothAdapter.stopLeScan(mLeScanCallback);

}

}, SCAN_PERIOD);

mScanning = true;

mBluetoothAdapter.startLeScan(mLeScanCallback);

} else {

mScanning = false;

mBluetoothAdapter.stopLeScan(mLeScanCallback);

}

...

}

...

}

如果你只想扫描特定的设备,你可以用startLeScan(UUID[],BluetoothAdapter.LeScanCallback)方法代替前面的方法,需要提供一个UUID对角数据给GATT服务端。

下面是BluetoothAdapter.LeScanCallback的实现代码:

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

}

});

}

};

注意:你只能扫描BLE设备或者传统蓝牙设备,但是不能同时扫描两种设备。

4、连接GATT服务器

与BLE设备交互的第一步是与它建立连接,其实就是连接上GATT服务器。为了连接BLE设备上的GATT服务端,你可以使用connectGatt()方法。这个方法需要3个参数:一个Context对象,autoConnect(boolean)(此参数是为了可以立即与可用BLE设备连接),还有一个BluetoothGattCallback:

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

这个连接GATT服务器会返回一个BluetoothGatt对象实例,接下来你可以用此实例进行GATT客户端操作。BluetoothGattCallback是为了向客户端传输结果用的,有连接状态或其它高级的数据。

在本例子中,BLE App提供一个activity(DeviceControlActivity)来连接,显示灵气,显示GATT服务和characteristics。基于用户输入,这个activity与一个Service进行交互,这个Service是BluetoothService,它用来能过Android BLE API与BLE设备进行交互:

// 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_DISCOVERED";

public final static String ACTION_DATA_***AILABLE =

"com.example.bluetooth.le.ACTION_DATA_***AILABLE";

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

// Various callback methods defined by the BLE API.

private final BluetoothGattCallback mGattCallback =

new BluetoothGattCallback() {

@Override

public void onConnectionStateChange(BluetoothGatt gatt, int status,

int newState) {

String intentAction;

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

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

} else {

Log.w(TAG, "onServicesDiscovered received: " + status);

}

}

@Override

// Result of a characteristic read operation

public void onCharacteristicRead(BluetoothGatt gatt,

BluetoothGattCharacteristic characteristic,

int status) {

if (status == BluetoothGatt.GATT_SUCCESS) {

broadcastUpdate(ACTION_DATA_***AILABLE, characteristic);

}

}

...

};

...

}

当一个特定的callback被触发里,它会调用合适的broadcastUpdate()来发出一个广播。注意在本文出现的这些数据是参考Bluetooth Heart Rate的度量profile specifications:

private void broadcastUpdate(final String action) {

final Intent intent = new Intent(action);

sendBroadcast(intent);

}

private void broadcastUpdate(final String action,

final BluetoothGattCharacteristic characteristic) {

final Intent intent = new Intent(action);

// This is 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.length);

for(byte byteChar : data)

stringBuilder.append(String.format("%02X ", byteChar));

intent.putExtra(EXTRA_DATA, new String(data) + "\n" +

stringBuilder.toString());

}

}

sendBroadcast(intent);

}

回到DeviceControlActivity,这个事件是被一个BroadcastReceiver来处理的:

// Handles various events fired by the Service.

// ACTION_GATT_CONNECTED: connected to a GATT server.

// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.

// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.

// ACTION_DATA_***AILABLE: received data from the device. This can be a

// result of read or notification operations.

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

final String action = intent.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_***AILABLE.equals(action)) {

displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));

}

}

};

5、读BLE的Attributes

一旦你的Android App连接上一个GATT服务器并且发现services,它就可以读写attributes了,只要是支持的数据。例如,你可以读取这些数据或属性显示到UI上:

public class DeviceControlActivity extends Activity {

...

// Demonstrates how to iterate through the supported GATT

// Services/Characteristics.

// In this sample, we populate the data structure that 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<HashMap<String, String>> gattServiceData =

new ArrayList<HashMap<String, String>>();

ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData

= new ArrayList<ArrayList<HashMap<String, String>>>();

mGattCharacteristics =

new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

// Loops through available GATT Services.

for (BluetoothGattService gattService : gattServices) {

HashMap<String, String> currentServiceData =

new HashMap<String, String>();

uuid = gattService.getUuid().toString();

currentServiceData.put(

LIST_NAME, SampleGattAttributes.

lookup(uuid, unknownServiceString));

currentServiceData.put(LIST_UUID, uuid);

gattServiceData.add(currentServiceData);

ArrayList<HashMap<String, String>> gattCharacteristicGroupData =

new ArrayList<HashMap<String, String>>();

List<BluetoothGattCharacteristic> gattCharacteristics =

gattService.getCharacteristics();

ArrayList<BluetoothGattCharacteristic> charas =

new ArrayList<BluetoothGattCharacteristic>();

// Loops through available Characteristics.

for (BluetoothGattCharacteristic gattCharacteristic :

gattCharacteristics) {

charas.add(gattCharacteristic);

HashMap<String, String> currentCharaData =

new HashMap<String, String>();

uuid = gattCharacteristic.getUuid().toString();

currentCharaData.put(

LIST_NAME, SampleGattAttributes.lookup(uuid,

unknownCharaString));

currentCharaData.put(LIST_UUID, uuid);

gattCharacteristicGroupData.add(currentCharaData);

}

mGattCharacteristics.add(charas);

gattCharacteristicData.add(gattCharacteristicGroupData);

}

...

}

...

}

6、接收GATT通知

这是很常见的,BLE apps可以询问是否可以被通知当设备上的一个特定的characteristic发生改变时。下面是如何实现接收此通知,使用setCharateristicNotification()方法:

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

只要notifications是可用的,一个onCharacteristicChangetd()将被回调来触发改变远程设备:

@Override

// Characteristic notification

public void onCharacteristicChanged(BluetoothGatt gatt,

BluetoothGattCharacteristic characteristic) {

broadcastUpdate(ACTION_DATA_***AILABLE, characteristic);

}

7、最后请关闭客户端App

只要你的App使用完毕BLE设备,你应该调用close来关闭它们,让系统释放资源:

public void close() {

if (mBluetoothGatt == null) {

return;

}

mBluetoothGatt.close();

mBluetoothGatt = null;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: