Bluetooth Low Energy——藍牙低功耗

Android4.3(API級別18)引入內置平臺支持BLE的central角色,同時提供API和app應用程序用來發現設備,查詢服務,和讀/寫characteristics。與傳統藍牙(ClassicBluetooth)不一樣,藍牙低功耗(BLE)的目的是提供更顯著的低功耗。這使得Android應用程序能夠和具備低功耗的要求BLE設備,如接近傳感器,心臟速率監視器,健身設備等進行通訊。html

 關鍵術語和概念java

下面是關鍵BLE術語和概念的總結:android

通用屬性規範(GATT)—GATTprofile是一個通用規範用於在BLE鏈路發送和接收被稱爲「屬性(attributes)」的數據片。目前全部的低功耗應用 profile都是基於GATT。服務器

藍牙SIG定義了許多profile用於低功耗設備。Profile(配置文件)是一個規範,規範了設備如何工做在一個特定的應用場景。注意:一個設備能夠實現多個profile。例如,一個設備能夠包含一個心臟監測儀和電池電平檢測器。app

 屬性協議( ATT )—GATT是創建在屬性協議( ATT )的頂層,一般也被稱爲GATT/ ATT 。 ATT進行了優化用於在BLE設備上運行。爲此,它採用儘量少的字節越好。每一個attribute屬性被UUID(通用惟一標識符)惟一標識 ,UUID是標準128-bit格式的ID用來惟一標識信息。attributes 被 ATT 格式化characteristics和services形式進行傳送。ide

特徵(Characteristics)— 一個characteristics包含一個單獨的value值和0 –n個用來描述characteristic 值(value)的descriptors。一個characteristics能夠被認爲是一種類型的,相似於一個類。函數

描述符(descriptor)—descriptor是被定義的attributes,用來描述一個characteristic的值。例如,一個descriptor能夠指定一我的類可讀的描述中,在可接受的範圍裏characteristic值,或者是測量單位,用來明確characteristic的值。oop

服務(service)—service是characteristic的集合。例如,你能夠有一個所謂的「Heart RateMonitor」service,其中包括characteristic,如「heart rate measurement 」。你能夠在 bluetooth.org找到關於一系列基於GATT的profile和service。post

 角色和職責優化

如下是適用於當一個Android設備與BLE設備交互的角色和責任:

中心設備(central)與外圍設備(peripheral)。這也適用於BLE鏈接自己。Central設備進行掃描,尋找advertisenment,peripheral設備發出advertisement。

GATT server(服務器)與GATTclient(客戶端)。這決定了兩個設備創建鏈接後如何互相交互。 

 

要了解它們的區別,假設你有一個Android手機和活動跟蹤器,活動跟蹤器是一個BLE裝置。這款手機扮演central角色;活動跟蹤器扮演peripheral角色(創建一個BLE鏈接,必須具有二者。若是兩個設備只支持central角色或peripheral角色,不能跟對方創建一個BLE鏈接)。

 一旦手機與活動跟蹤器已經創建鏈接,他們開始相互傳送GATT數據。根據它們傳送數據的種類,其中一個可能做爲 GATT server。例如,若是該活動跟蹤器將傳感器數據彙報到手機上,活動跟蹤器做爲server。若是活動跟蹤器想要從手機接收更新,那麼手機做爲server。

 在本文檔中使用的示例中,Android應用程序(在Android設備上運行)是GATT client。該應用從GATT server 獲取數據,server是一款支持 HeartRate Profile的BLE心臟速率監測儀。但你能夠設計​​你的Andr​​oid應用程序,做爲GATT server角色。見BluetoothGattServer 獲取更多信息。

 

BLE權限

爲了使用應用程序中的藍牙功能,你必須聲明藍牙權限BLUETOOTH。你須要這個權限執行任意藍牙通信,如請求鏈接,接受鏈接,傳輸數據。

若是你但願你的應用程序啓動設備發現或操縱藍牙設置,還必須聲明BLUETOOTH_ADMIN權限。注意:若是您使用BLUETOOTH_ADMIN權限,那麼你還必須有BLUETOOTH權限。

 聲明藍牙權限在你的應用程序清單(manifest)文件。例如:

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

若是你想聲明,你的應用程序是隻提供給BLE功能的設備,在您的應用程序的清單包括以下語句:

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

不過,若是你想使你的應用程序提供給那些不支持BLE設備,你仍然應該在您的應用程序的清單包含這個上述語句,但設置required="false"。而後在運行時能夠經過使用 PackageManager.hasSystemFeature()肯定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();
}

設置BLE

在你的應用程序能夠進行BLE通訊以前 ,你須要驗證這個設備上BLE是否被支持,若是支持,請確保它已啓用。請注意,若是<uses-feature.../>設置爲false,這個檢查纔是必需的。

若是不支持BLE ,那麼你應該適當地禁用任何BLE功能。若是BLE支持,但被禁用,那麼你能夠要求用戶啓動藍牙時不要離開應用程序。這種設置兩個步驟完成,使用 BluetoothAdapter.

 

1.獲取BluetoothAdapter

BluetoothAdapter是全部的藍牙活動所必需的。該BluetoothAdapter表明設備自身的藍牙適配器(藍牙無線電)。只有一個藍牙適配器用於整個系統,而且你的應用程序可使用該對象進行交互。下面的代碼片斷顯示瞭如何獲取適配器。注意,該方法使用getSystemService() 返回BluetoothManager的一個實例, 用於獲取適配器。Android 4.3 ( API級別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);
 }
複製代碼

查找BLE設備

爲了找到BLE設備,您可使用startLeScan() 方法。此方法須要一個BluetoothAdapter.LeScanCallback做爲參數。你必須實現這個回調,由於它決定掃描結果如何返回。由於掃描耗電量大,你應當遵照如下準則:

1)只要你找到所需的設備,中止掃描。

2)不要掃描一個循環,並設置您的掃描時間限制。之前可用的設備可能已經移出範圍,繼續掃描消耗電池電量。

下面的代碼片斷顯示瞭如何啓動和中止掃描:

複製代碼
/**
 * 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);
        }
        ...
    }
...
}
複製代碼

如何你想要掃描指定類型的peripheral設備,你能夠用 startLeScan(UUID[],BluetoothAdapter.LeScanCallback)取代, 它提供了一組UUID對象用於說明你的應用程序支持的GATT services .

下面是用於傳送BLE掃描結果的接口函數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設備或傳統藍牙設備,就像Bluetooth描述那樣。你不能夠同時掃描BLE設備和傳統藍牙設備。

 

鏈接到GATT server

在和一個BLE設備交互的第一步是鏈接到它,更具體地,鏈接到所述裝置上的GATT server。要鏈接到一個BLE設備上的GATT server,您可使用connectGatt()方法。這個方法有三個參數:一個Context 對象,一個autoConnect(布爾值,表示是否自動鏈接到BLE裝置)和BluetoothGattCallback:

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

 

這個函數鏈接到由BLE設備上的GATTserver,並返回一個BluetoothGatt實例,您可使用它來進行GATT client操做。調用者(Android應用程序)是GATT client。該BluetoothGattCallback是用來提供結果給client,如鏈接狀態,以及任何進一步的GATT client操做。

 

在這個例子中,BLE應用程序提供了一個活動(DeviceControlActivity)鏈接,顯示數據,和顯示該設備支持的GATTservices和characteristics。根據用戶的輸入,這一活動與一個叫BluetoothLeService的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_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);
            }
        }
     ...
    };
...
}
複製代碼

當一個特定的回調被觸發時,它會調用相應的broadcastUpdate()輔助方法並傳遞給它一個動做。注意,在該部分中的數據解析參照 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 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_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));
        }
    }
};
複製代碼

讀取BLE屬性

一旦你的Android應用程序已鏈接到GATTserver和discoveriable service,它能夠讀取和寫入支持的attributes。例如,經過server的service和characteristic這個片斷進行迭代,在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);
         }
    ...
    }
...
}
複製代碼

接收GATT通知 (Notifications)

這是常見的設備上的BLE應用程序要求被通知,當一個特定characteristic改變時。這段代碼顯示瞭如何使用 setCharacteristicNotification()方法設置一個Notifications用於characteristic:

複製代碼
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 for acharacteristic),若是在遠程設備上characteristic 發生改變,onCharacteristicChanged() 回調函數將被啓動。

@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
        BluetoothGattCharacteristic characteristic) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

關閉Client應用程序

一旦你的應用程序已經使用BLE裝置完成後,應該調用close(),這樣系統就能夠適當地釋放資源:

複製代碼
public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}
複製代碼
相關文章
相關標籤/搜索