Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android BLE與終端通信(五)——Google官方BLE 4.0文檔解讀與案例實踐

編輯:關於 Android 程式設計

Google API文檔地址:https://developer.android.com/guide/topics/connectivity/bluetooth-le.html

想學好Android技術,Google官方API文檔其實就是最詳盡的指導書,而且通俗易懂。即便英文不太行,借助翻譯工具再結合示例代碼,也能領會個七八分,非常值得一讀。下面我們就直接切入正題來解讀。

一、核心概念概述

在動手寫代碼之前,先把幾個關鍵名詞理清楚。這些概念在之前的篇幅中也曾提及,這裡做個系統梳理。

Generic Attribute Profile(GATT)——GATT配置文件是一套通用規範,用於在BLE鏈路上收發被稱為「屬性」的數據塊。目前所有的BLE應用都建立在GATT之上。藍牙SIG規定了許多面向低功耗設備的配置文件(Profile),它描述的是設備在特定應用場景下如何協同工作。需要注意的是,一個設備可以同時實現多個配置文件,例如既包含心率監測,又包含電量檢測。

Attribute Protocol(ATT)——GATT建立在ATT協議之上,因此也常被合稱為GATT/ATT。ATT針對BLE設備做了深度優化,力求用最少的字節完成通信。每個屬性都由一個唯一的UUID(統一標識符)來標識,採用128位標準格式。屬性在ATT中被組織為characteristics(特徵)和services(服務)。

Characteristic(特徵)——一個特徵包含單一變量以及0到n個用於描述該變量的descriptor。你可以把特徵理解為一種「類型」,有點類似於編程中的類。

Descriptor(描述符)——描述符用來描述特徵變量的屬性。比如,它可以規定一段可讀的描述文本,或標明某個特徵變量的取值範圍,又或者指定該變量的特定測量單位。

Service(服務)——服務是特徵的集合。舉個例子,你可能有一個名為「Heart Rate Monitor(心率監測儀)」的服務,它下面掛著諸如「heart rate measurement(心率測量)」等多個特徵。目前基於GATT的配置文件與服務列表,可以在bluetooth.org上查到。

二、角色與職責

BLE通信中涉及兩組容易混淆的概念:

第一組是中央設備(Central)與外圍設備(Peripheral),它適用於BLE連接本身。中央設備負責掃描、尋找廣播;外圍設備則負責發出廣播。

第二組是GATT服務端與GATT客戶端,它決定了兩個設備在建立連接之後如何彼此通信。

為方便理解,不妨想象這樣一個場景:你手上有一部Android手機和一個用於活動追蹤的BLE設備。手機支持中央角色,活動追蹤器支持外圍角色(要點:只支持外圍的雙方或只支持中央的雙方是無法互相通信的)。

當手機與運動追蹤器建立連接後,它們開始互相傳輸GATT數據。誰充當服務端,取決於傳輸的數據種類。例如,若運動追蹤器要向上報傳感器數據,那麼它是服務端;若運動追蹤器要接收來自手機的更新,那麼手機就成了服務端。

在本例中,運行於Android設備上的App充當GATT客戶端,它從GATT服務端(即支持Heart Rate Profile的BLE心率監測儀)獲取數據。當然,你也可以自行設計App去扮演GATT服務端的角色。

三、案例實踐

Google文檔給出了一個完整示例。使用BLE時,必須先在清單文件中加入以下兩個權限:

 

這其實和傳統藍牙一樣,只要用到藍牙硬件就得聲明這兩個權限。不過Google特別強調了一點:如果你想聲明本軟件僅服務於具備BLE能力的設備,還應該在清單中加入:

 

若把required改為false,則表示普通藍牙設備也能安裝使用。接著我們創建一個名為BLETest的工程。

和傳統藍牙一樣,添加完權限後,先要判斷設備是否支持BLE:

 // 判斷是否支持BLE設備
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, "此設備不支持BLE", Toast.LENGTH_SHORT).show();
    finish();
}

這一步只有在required設置為false時才是必須的;如果設置為true,由於軟件只服務於BLE設備,這個判斷就顯得多餘了。

緊接著,我們還要判斷藍牙是否已開啟,若未開啟則引導用戶開啟。這裡同樣通過BluetoothAdapter獲取適配器,但引入了新類BluetoothManager,先完成初始化:

 // 初始化藍牙適配器
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

然後再判斷並開啟:

 // 打開藍牙
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

這裡的REQUEST_ENABLE_BT只是一個回調標識常量,無需過多理會:

 public static final int REQUEST_ENABLE_BT = 0;

加上這段邏輯後,當藍牙未開啟時,系統就會友好地提示用戶去開啟。

接下來是設備搜索。通過scanLeDevice方法啟動或停止掃描:

 // 搜索設備
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void scanLeDevice(final boolean enable) {
    if (enable) {
        // 經過預定掃描期後停止掃描
        mHandler.postDelayed(new Runnable() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void run() {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }, SCAN_PERIOD);
        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
}

接收到搜索設備的回調後,便可將設備添加到Adapter中展示。以下依然是Google提供的Demo思路。

 // 搜索設備的回調
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();
            }
        });
    }
};

連接GATT服務端

搜索到設備只是第一步。要讓BLE展現真正的實力,還得連上它的GATT服務端:

 /**
 * 1. 上下文
 * 2. 是否自動連接
 * 3. BluetoothGattCallback 回調
 */
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

連接到GATT服務端時,BLE設備作為主機,方法會返回一個BluetoothGatt實例,後續所有GATT客戶端操作都基於這個實例展開。發起方(軟件)即為GATT客戶端,而BluetoothGattCallback則負責把結果(如連接狀態及後續操作結果)回傳給調用方。

在本例中,BLE App提供了一個DeviceControlActivity,用於連接設備、展示數據,並列出該設備支持的GATT服務與特徵。根據用戶操作,這個Activity通過BluetoothLeService與BLE設備交互。核心的服務類大致如下:

 public class BluetoothLeService extends Service {
    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);

    // 通過 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
        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
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }
    };
}

當特定回調被觸發時,它會調用相應的broadcastUpdate()輔助方法把數據廣播出去。需要注意的是,本節中的數據解析遵循藍牙心率測量概要文件的規範。

 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);
    // 針對心率測量 profile 的專門處理,數據解析按照 profile 規範進行
    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 {
        // 其他 profile 則以 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統一處理。

 // 處理 Service 觸發的各類事件
// ACTION_GATT_CONNECTED:連接到 GATT 服務端
// ACTION_GATT_DISCONNECTED:從 GATT 服務端斷開
// ACTION_GATT_SERVICES_DISCOVERED:發現了 GATT 服務
// ACTION_DATA_AVAILABLE:從設備接收到數據(讀取或通知結果)
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)) {
            displayGattServices(mBluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

讀取BLE特徵

當App完成與GATT服務端的連接並發現服務之後,就能讀寫對應的特徵了。下面這段代碼通過遍歷服務端的services和characteristics,把它們展示到界面上:

 public class DeviceControlActivity extends Activity {
    ...
    // 演示如何遍歷支持的 GATT Services / Characteristics
    private void displayGattServices(List 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> gattServiceData = new ArrayList>();
        ArrayList>> gattCharacteristicData = new ArrayList>>();
        mGattCharacteristics = new ArrayList>();

        for (BluetoothGattService gattService : gattServices) {
            HashMap currentServiceData = new HashMap();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList> gattCharacteristicGroupData = new ArrayList>();
            List gattCharacteristics = gattService.getCharacteristics();
            ArrayList charas = new ArrayList();
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap currentCharaData = new HashMap();
                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通知

當設備上的特徵發生變化時,會主動通知BLE應用。下面這段代碼演示如何用setCharacteristicNotification()為某個特徵開啟通知:

 // GATT 服務端
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);

一旦對某個特徵啟用了通知,當遠程藍牙設備的特徵發生變化時,回調函數onCharacteristicChanged()便會被觸發。

 @Override
// 廣播更新
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

釋放資源,關閉客戶端

當App不再使用BLE設備時,應調用close(),讓系統及時回收占用的資源:

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

以上代碼片段相對零散,感興趣的讀者可以參考Google官方Demo進行完整測試與驗證。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved