zoukankan      html  css  js  c++  java
  • 蓝牙低功耗(Bluetooth Low Energy)

    在 Android 4.3 (API Level 18) 中,引入了以支持蓝牙低功耗为核心的内置平台,并且提供了一些 API,用来搜索设备、查询服务器和读/写属性。和经典蓝牙( Classic Bluetooth)相比,蓝牙低功耗(Bluetooth Low Energy)显著地降低了能源消耗。它允许 Android 应用程序与具有低功耗要求的 BLE 设备进行连接,如接近传感器、心率监视器、健身设备等等。

    关键术语和概念

    以下是 BLE 关键术语和概念的一个总结:
    • 通用属性描述(Generic Attribute Profile (GATT))— GATT是一个通用规范,用于在 BLE 链接上发送和接收被称为“属性”的短数据块。目前所有的低功耗应用程序规范都是基于GATT。蓝牙技术联盟(Bluetooth SIG)为低功耗设备定义了很多规范。一个规范就是对一个设备在特定应用程序上如何运行的具体说明。注意,一个设备可以支持多种规范。例如,一个设备可以包含一个心率检测器和一个电池电压检测器。
    • 属性协议(Attribute Protocol (ATT))—GATT 是建立在 ATT 之上的。它也被称为 GATT/ATT 。ATT在BLE设备上运行表现优异。为此,它尽可能使用少的字节。每个属性(Attribute)都用一个UUID(Universally Unique Idetifier)进行唯一标识。这是一个标准的128位格式字符串ID,用于唯一标识信息。通过 ATT 传送的这些属性(Attribute)被格式化为特性(Characteristics)和服务(Services)。
    • 特性(Characteristic) — 一个特性包含一个单独的值和 0-n 个描述符,这些描述符描述了特性的值。一个特性可以被认为是一个类型,类似于一个类。
    • 描述符(Descriptor)— 描述符被定义为描述一个特性值的属性。例如,一个描述符可能是指定一个人类可读的描述、一个特性值所能接受的范围或一个专门用于特性值的测量单位。
    • 服务(Service)— 一个服务是一些特性的一个集合。例如,你可能会有一个被称为“心率检测器”的服务,它包含如“心率测量”这个特性。

    角色和职责

    以下是当一个 Android 设备与一个 BLE 设备进行交互时,所应用的角色和职责:
    • 中央(Central)与外围设备(Peripheral)。这适用于 BLE 连接本身。中央设备用来浏览、寻找通知(Advertisement),外围设备用来制造通知。
    • GATT 服务器与 GATT 客户端。这将决定,一旦这两个设备建立链接,他们将之间如何相互沟通。
    为了理解这种区别,假设你有一个 Android 手机和一个 BLE 设备的活动跟踪器。手机支持中央角色,活动跟踪器支持外围角色。

    一旦手机和活动跟踪器建立连接,他们就可以将 GATT 元数据传递给另一个。根据他们所传数据类型的不同,一个或另外一个可能充当服务器。例如,如果活动跟踪器想将传感器的数据报告给手机,那么将活动跟踪器当作服务器才可能有意义的;而如果活动跟踪器想要从手机获取更新数据,那么将手机当作服务器才可能有意义。

    在本文档的例子中,Android 应用程序(运行在一个 Android 设备上)是 GATT 客户端。应用程序从 GATT 服务器获取数据,该服务器是一个 BLE 心率检测器,它支持心率规范(Heart Rate Profile)。当然,你也可以选择性地设计你的Android 应用程序来充当 GATT 服务器的角色。更多信息可以查看 BluetoothGattServer

    BLE权限

    为了在你的应用程序中使用蓝牙功能,你必须声明蓝牙权限。执行任何蓝牙通信都需要事先取得蓝牙权限,如请求连接、接收连接和传输数据。

    如果你希望通过应用程序来启动搜索设备功能或操纵蓝牙设置,你也必须先声明 BLUETOOTH_ADMIN 权限。注意:如果你想取得 BULETOOTH_ADMIN 权限,你也必须先取得 BLUETOOTH 权限。

    在你的应用程序manifest 文件中声明蓝牙权限,如下:
    <span style="font-size:18px;"><span style="font-family:SimSun;font-size:18px;"><uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/></span></span>
    如果你想让你的 APP 只对支持 BLE 的设备可用,那么你需要将以下语句添加到你的应用程序manifest文件中:
    <span style="font-size:18px;"><span style="font-family:SimSun;font-size:18px;"><uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/></span></span>
    可是,如果你想让你的 APP 对那些不支持 BLE 的设备可用,你仍然需要将该语句包含在你的应用程序manifest文件中,只不过需要设置required = "false"。然后在运行的时候,你需要通过 PackageManager.hasSystemFeature() 来确认 BLE 的可用性。
    <span style="font-size:18px;"><span style="font-family:SimSun;font-size:18px;">// 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();
    }</span></span>

    BLE设置

    在你的应用程序与 BLE 通信前,你需要确认在你的设备上支持 BLE。如果是这样,确认它被启用了。注意:这种检查只在<uses-feature.../> 被设置为 false 下是必须的。

    如果不支持 BLE,那么你应该优雅地禁用任何 BLE 功能。如果支持 BLE,但是不可用,那么你应该要求用户启用蓝牙。这个设置通过以下两步来完成:
    1.取得BluetoothAdapter
    BluetoothAdapter 是任何和所有蓝牙活动所必需的。BluetoothAdapter代表着该设备自身的蓝牙适配器(蓝牙无线电)。在整个系统中,只有一个蓝牙适配器,并且你的应用程序可以通过这个对象进行交互。下面的片段展示了如何取得适配器。注意:这种方式是通过getSystemService()来返回一个BluetoothManager实例,这个将用来取得适配器。在Android 4.3(API Level 18)中引进了BluetoothManager:
    <span style="font-size:18px;">// Initializes Bluetooth adapter.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();</span>
    2.启用蓝牙
    下一步,你需要确认蓝牙是否启用。调用isEnabled()来检查当前蓝牙是否启用。如果这个方法返回false,则蓝牙未启用。下面的片段用来检查蓝牙是否启用。如果没有,该片段会显示一个错误提示用户去设置启用蓝牙:
    <span style="font-size:18px;">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);
    }</span>

    扫描BLE设备

    可以通过startLeScan()方法来扫描BLE设备。这个方法采用BluetoothAdapter.LeScanCallback作为参数。你必须执行这个回调函数才能知道返回的扫描结果。由于扫描是一个非常耗电的操作,你应该遵循以下规则:
    • 一旦找到所需的设备,停止扫描。
    • 不要一直循环扫描,应该设置一个扫描时间限制。之前可用的设备可能已经移出范围,继续扫描将会消耗电池电量。
    以下片段展示了如何开始和关闭扫描:
    <span style="font-size:18px;">/**
     * 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);
            }
            ...
        }
    ...
    }</span>

    如果你只想扫描特定类型的外围设备,可以改为调用startLeScan(UUID[],BluetoothAdapter.LeScanCallback),提供一个UUID对象的数组,应用程序必须支持其指定的GATT服务。

    下面是一个BluetoothAdapter.LeScanCallback的实现,它是传递BLE扫描结果的接口。
    <span style="font-size:18px;">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();
               }
           });
       }
    };</span>

    注意:你只能扫描BLE设备或经典蓝牙设备,但不能同时扫描。

    连接GATT服务器

    与BLE设备进行交互的第一步就是连接它,进一步的说,就是在设备上连接GATT服务器。为了在BLE设备上连接GATT服务器,需要使用connectGatt()方法。这个方法有三个参数:一个 context对象,autoConnect(布尔值,用来指示一旦设备可用,是否自动连接到BLE装置),一个引用BluetoothGattCallback:
    <span style="font-size:18px;">mBluetoothGatt = device.connectGatt(this, false, mGattCallback);</span>
    这个连接GATT服务器是由BLE设备控制的,它返回一个BluetoothGatt实例,这个后面可以用来进行 GATT客户端操作。呼叫方(Android应用程序)是GATT客户端。BluetoothGattCallback用来将返回结果发送给客户端,如连接状态以及任何进一步的GATT客户端操作。

    在这个例子中,BLE应用程序提供了一个活动(DeviceControlActivity)来进行连接,显示数据和显示设备所支持的GATT服务和特性。基于用户的输入,这个活动与一个被称为BluetoothLeService的服务进行通信,其通过Android BLE API与BLE设备进行交互。
    <span style="font-size:18px;">// 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_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_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_AVAILABLE, characteristic);
                }
            }
         ...
        };
    ...
    }</span>

    当一个特定的回调被触发,它将调用broadcastUpdate()方法。注意:这部分的数据解析与蓝牙心率测量器规范相一致:
    <span style="font-size:18px;">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) + "
    " +
                        stringBuilder.toString());
            }
        }
        sendBroadcast(intent);
    }</span>

    返回到DeviceContorl,这些事件都将被BroadcastReceiver所解决:
    <span style="font-size:18px;">// 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_AVAILABLE: 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_AVAILABLE.equals(action)) {
                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }
        }
    };</span>

    读BLE属性(Attributes)

    一旦你的Android应用程序连接上了一个GATT服务器并发现服务,它就可以读和写属性。例如,下面片段通过服务器的服务和特性进行迭代,并将它们显示在UI上。
    <span style="font-size:18px;">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);
             }
        ...
        }
    ...
    }</span>

    接受GATT通知

    对于BLE应用程序来讲,当设备上的一个特定的特性发生了改变,要求被通知是一件很常见的事情。这个片段展示了如何为一个特性设置通知,用setCharacteristicNotification()方法:
    <span style="font-size:18px;">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);</span>

    一旦一个特性的通知可用,如果远程设备上的特性发生改变,回调函数onCharacteristicChanged()将被触发:
    <span style="font-size:18px;">@Override
    // Characteristic notification
    public void onCharacteristicChanged(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }</span>

    关闭客户端App

    一旦你的app使用完一个BLE设备,应该调用close()将其关闭,以便系统适当的释放资源:
    <span style="font-size:18px;">public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }</span>
  • 相关阅读:
    android编译全过程
    Android APK反编译得到Java源代码和资源文件
    获取Android的Java源代码并在Eclipse中关联查看的最新方法《转载》
    定制ROM,添加apk文件报错。
    Ubuntu下下载编译android源码
    poj 2714 Random Walk
    hdu 3829 Cat VS Dog
    第九场组队赛总结
    2012 MUTC 9 总结
    hdu 1100 Trees Made to Order
  • 原文地址:https://www.cnblogs.com/gongchuangsu/p/4993217.html
Copyright © 2011-2022 走看看