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

Android BLE 開發入門:手機與 BLE 終端裝置的通信全流程

編輯:關於 Android 開發

Android BLE 開發入門:手機與 BLE 終端裝置的通信全流程


本文以官方 BLE Demo 為基礎,記錄第一次把手機和 BLE 終端裝置連起來的過程。硬體環境是一部 MX5 手機搭配一台農藥殘留檢測儀(BLE 終端裝置),目標是讓手機能控制儀器,例如發送列印指令讓儀器執行列印。

關於如何開啟藍牙、配置權限、掃描 BLE 裝置等前置步驟,網路上資料很多,這裡不贅述,重點放在通信本身。要特別留意:掃描結果是異步透過 BluetoothAdapter.LeScanCallback 回傳的,而且掃描過程相當耗電,因此最好加上逾時機制,例如掃描 10 秒後自動停止。

在理解通信流程之前,先認識幾個關鍵類別:

BluetoothGatt:最常用也最重要,可以把它想成手機與 BLE 終端之間的一條「管道」,有了它才具備通信的前提。

BluetoothGattService:代表裝置提供的服務,好比「班級」。一台 BLE 終端(學校)可以有多個服務(班級),彼此以 UUID 區分。

BluetoothGattCharacteristic:每個服務底下的特徵值,是手機與終端交換資料的關鍵,我們最終要拿到的就是它。好比「學生」,一個班級有多個學生,同樣以 UUID 區分。

總結:要讓手機和 BLE 裝置通信,其實就像要找某個學生對話。先搭好管道(取得 BluetoothGatt),接著知道他屬於哪個班級、學號是多少,也就是 serviceUUID 與 characteristicUUID。找到之後並不是直接對話,他更像一個仲介:手機發出的資料先交給他,再由他轉給 BLE 裝置;裝置回傳的資料也是先到他這裡,手機再從他身上讀取。

所有通信結果都以回撥形式返回,以下是幾個常見回撥(可參考官方 Demo 的 BluetoothLeService 類別):

private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    // 連接狀態改變的回撥
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // 連接成功後啟動服務發現
            Log.e("AAAAAAAA", "啟動服務發現:" + mBluetoothGatt.discoverServices());
        }
    };
    // 發現服務的回撥
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "成功發現服務");
        } else {
            Log.e(TAG, "服務發現失敗,錯誤碼為:" + status);
        }
    };
    // 寫操作的回撥
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "寫入成功" + characteristic.getValue());
        }
    };
    // 讀操作的回撥
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "讀取成功" + characteristic.getValue());
        }
    }
    // 資料返回的回撥(此處接收 BLE 裝置返回資料)
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    };
}

一、連接 BLE 終端裝置

掃描到目標裝置後,一句程式碼即可完成連接。呼叫時系統會直接回傳一個 BluetoothGatt 物件,也就是前面說的那條「管道」。

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

三個參數分別是:上下文物件、是否自動連接(此處設為 false)、以及上面的回撥方法。連不連得上,都會透過下面的回撥告知:

@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    // 代表連接成功,此處可發送一個廣播通知 Activity 已成功連接
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.e("AAAAAAAA", "啟動服務發現:" + mBluetoothGatt.discoverServices());
    }
}

二、啟動服務發現

連接成功後,接著要找我們需要的服務,一行即可啟動發現:

mBluetoothGatt.discoverServices();

結果同樣透過回撥返回,這裡可以取得裝置所有服務,並印出每個服務及其底下特徵值的 UUID:

public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> supportedGattServices = mBluetoothGatt.getServices();
        for (int i = 0; i < supportedGattServices.size(); i++) {
            Log.e("AAAAA", "1:BluetoothGattService UUID=:" + supportedGattServices.get(i).getUuid());
            List<BluetoothGattCharacteristic> listGattCharacteristic = supportedGattServices.get(i).getCharacteristics();
            for (int j = 0; j < listGattCharacteristic.size(); j++) {
                Log.e("a", "2: BluetoothGattCharacteristic UUID=:" + listGattCharacteristic.get(j).getUuid());
            }
        }
    } else {
        Log.e("AAAAA", "onservicesdiscovered收到: " + status);
    }
}

也可以遍歷每個特徵值,判斷它是可讀、可寫,還是具備通知功能:

for (BluetoothGattService gattService : supportedGattServices) {
    List<BluetoothGattCharacteristic> gattCharacteristics = supportedGattServices.getCharacteristics();
    for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
        int charaProp = gattCharacteristic.getProperties();
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) { /* 可讀 */ }
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) { /* 可寫 */ }
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { /* 具備通知屬性 */ }
    }
}

三、取得 Characteristic

我們最終目的是拿到 Characteristic 來通信。一般可以向硬體工程師索取 serviceUUID 與 characteristicUUID(也就是班級號與學號),但若拿不到,也能用上一節的方法把全部特徵印出來,再挑出要用的那個。這次實作就是這樣找到的:雖然每個特徵都標示為可讀可寫可通知,但實際上只有 0000ffe1-0000-1000-8000-00805f9b34fb 這個特徵能真正通信,對應的 serviceUUID 是 0000ffe0-0000-1000-8000-00805f9b34fb。既然有一個能用就先用了。已知兩個 UUID 時,取得特徵值的寫法如下:

BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));

四、開始通信

拿到特徵值後,就能進行讀寫操作。

a. 讀操作:把特徵值傳入即可讀出資料。

mBluetoothGatt.readCharacteristic(characteristic);

讀取結果透過 onCharacteristicRead 回撥返回,用 characteristic.getValue() 取出即可。

b. 寫操作:這才是重點。透過向特徵值寫入指令,就能達到控制 BLE 終端的目的:

// 將指令放置進特徵中
characteristic.setValue(new byte[] {0x7e, 0x14, 0x00, 0x00, 0x00, (byte) 0xaa});
// 設置回覆形式
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
// 開始寫資料
mBluetoothGatt.writeCharacteristic(characteristic);

注意:與儀器通信時發送的是 16 進位資料,需要先裝進 byte[] 陣列。例如要發送 7e 14 00 00 00 aa,就要寫成 new byte[] {0x7e, 0x14, 0x00, 0x00, 0x00, (byte) 0xaa}。由於 BLE 每次最多只能傳 20 個位元組,若指令超過 20 位元組必須分包:先 write 前 20 位元組,開執行緒 sleep 幾十毫秒後,再 write 剩下的部分。

五、BLE 終端返回資料

寫入成功且指令正確時,裝置會回傳對應的響應,透過下面的回撥即可取得(用 characteristic.getValue() 取出):

public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    Log.e("AAAAAAAA", characteristic.getValue());
};

能收到回傳的前提,是該特徵已開啟 Notification 功能,因此完整的寫操作流程應該是(設置 Notification 要放在最前面):

mBluetoothGatt.setCharacteristicNotification(characteristic, true);
// 將指令放置進來
characteristic.setValue(new byte[] {0x7e, 0x14, 0x00, 0x00, 0x00, (byte) 0xaa});
// 設置回覆形式
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
// 開始寫資料
mBluetoothGatt.writeCharacteristic(characteristic);

以上就是自己對 Android 手機與 BLE 裝置通信的初步理解,若有描述不精確之處,歡迎指正。

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