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

Android BLE 開發實錄(二):從 GATT 協議到 notify 數據接收

編輯:關於 Android 程式設計

上一篇提到會貼出自己的代碼,這篇就正式進入數據傳輸環節。要談傳輸,得先從 GATT 說起。

什麼是 GATT?

GATT 全名是 Generic Attribute Profile,可以譯作「通用屬性協議」。它定義了兩個 BLE 設備如何透過 Service 與 Characteristic 這兩種結構進行通信。

GATT 建立在 ATT(Attribute Protocol)協議之上。ATT 把 Service、Characteristic 及各自的數據組織在一張查找表中,每個條目以 16 bit ID 作為索引。兩個設備一旦建立連接,GATT 就開始發揮作用——而這意味著你必須先走完 GAP 流程。

實務上有個容易混淆的地方:Android 開發時我們可以直接拿設備 MAC 地址發起連接,跳過掃描步驟。但這並不代表繞過了 GAP,實際上芯片層已經代勞了——藍牙芯片發起連接時,一定是先掃描、掃到目標才會連接。

關於 GATT 連接,有一點必須牢記:GATT 連接是獨占的。一個 BLE 外設在同一時間只能被一個中心設備連接。外設一旦被連接,會立即停止廣播,對其他設備不可見;直到連接斷開才恢復廣播。也就是說,中心設備與外設之間唯一的雙向通信途徑,就是建立 GATT 連接。

從上圖可以梳理出這套層級關係:

一個 BLE 設備可以包含多個 Profile;一個 Profile 下有多個 Service,透過 UUID 定位;一個 Service 下有多個 Characteristic,同樣靠 UUID 定位;而每個 Characteristic 包含一個 value 與若干 Descriptor。

這張圖很重要,後面開啟 notify 時我們會再回來看它。

如何開發 BLE?

整個開發過程中我借用了成熟的第三方庫來輔助,開發效率提升明顯,接入也不算複雜。

1. 準備工作

首先是聲明權限:

<!-- 使用藍牙 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 掃描藍牙設備、操作藍牙設定 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

接著把 lite-ble-0.9.2.jar 加入工程,這一步就不贅述了。

然後檢測設備是否支持並開啟藍牙,同時建立操作對象:

private LiteBluetooth liteBluetooth;

// 檢查當前手機是否支持 BLE
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, "ble_not_supported", Toast.LENGTH_SHORT).show();
}

// 獲取 BluetoothAdapter(需要 API 18 及以上)
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

if (mBluetoothAdapter == null) {
    Toast.makeText(this, "ble_not_supported", Toast.LENGTH_SHORT).show();
    return;
}

// 建立 LiteBluetooth 單例(BleUtil 是自己封裝的單例工具類)
if (liteBluetooth == null) {
    liteBluetooth = BleUtil.getInstance(getApplicationContext());
}

// 若藍牙未啟用,可彈出對話框引導用戶授權開啟
// liteBluetooth.enableBluetoothIfDisabled(activity, REQUEST_ENABLE_BT);

2. 搜索設備

private void scanDevicesPeriod() {
    liteBluetooth.startLeScan(new PeriodScanCallback(SCAN_PERIOD) {
        @Override
        public void onScanTimeout() {
            // 搜索超時後的處理
        }

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (Math.abs(rssi) <= 90) {   // 過濾信號強度小於 -90 的設備
                Log.i("test scan", "device: " + device.getName()
                        + " mac: " + device.getAddress()
                        + " rssi: " + rssi
                        + " scanRecord: " + DeviceBytes.byte2hex(scanRecord));
            }
        }
    });
}

幾個要點:SCAN_PERIOD 是搜索時長,單位毫秒;設備 MAC 透過 device.getAddress() 取得;scanRecord 是 BLE 的廣播數據,用自寫的 DeviceBytes 工具類轉成十六進制可讀形式。

到這裡設備就掃到並打印出來了。

3. 連接設備(首次連接)

拿到 GATT 的 Services 之後,就能讀寫它們的屬性了。

private void connect(final BluetoothDevice device) {
    liteBluetooth.connect(device, false, new LiteBleGattCallback() {

        @Override
        public void onConnectSuccess(BluetoothGatt bluetoothGatt, int status) {
            bluetoothGatt.discoverServices();   // 連接成功後還需發現服務
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int status) {
            BluetoothUtil.printServices(bluetoothGatt);   // 打印服務列表
            // 服務發現成功後,才能進行讀寫、開啟 notify 等操作
        }

        @Override
        public void onConnectFailure(BleException e) {
            bleExceptionHandler.handleException(e);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            // 開啟 notify 後,設備主動上報的數據在這裡接收
            // 項目中這裡還需要做分包重組,本文暫不展開
            Log.i("notify", "onCharacteristicChanged: "
                    + DeviceBytes.byte2hex(characteristic.getValue()));
            super.onCharacteristicChanged(gatt, characteristic);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic,
                                          int status) {
            Log.i("test", "onCharacteristicWrite: "
                    + DeviceBytes.byte2hex(characteristic.getValue()));
            super.onCharacteristicWrite(gatt, characteristic, status);
        }
    });
}

4. 連接設備(二次重連)

二次重連很簡單:第一次連接成功時把設備 MAC 保存下來,重連時直接傳入即可。

private void scanAndConnect(final String mac) {
    liteBluetooth.scanAndConnect(mac, false, new LiteBleGattCallback() {
        // 預設搜索 20 秒,其餘回調與首次連接一致
        @Override
        public void onConnectSuccess(BluetoothGatt bluetoothGatt, int status) {
            bluetoothGatt.discoverServices();
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int status) {
            BluetoothUtil.printServices(bluetoothGatt);
        }

        @Override
        public void onConnectFailure(BleException e) {
            bleExceptionHandler.handleException(e);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            Log.i("notify", "onCharacteristicChanged: "
                    + DeviceBytes.byte2hex(characteristic.getValue()));
            super.onCharacteristicChanged(gatt, characteristic);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic,
                                          int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
        }
    });
}

5. 開啟 notify 接收數據

如果設備需要主動給手機推送信息,最合適的方式是 notification——手機不必輪詢去讀設備,設備值一變化就會觸發 onCharacteristicChanged() 回調。

我原本嘗試直接調用庫裡提供的方法開啟 notify,但始終沒成功,索然自己實現了一份。原理並不難,就是沿著 UUID 一層層往下找:先定位 Service,再在 Service 裡找 Characteristic,最後找到 Descriptor。是不是有點眼熟?正是文章開頭那張圖。

// 以下 UUID 僅作示例,需替換為項目實際使用的值
private static final String serviceid = "0000fee7-0000-1000-8000-00805f9b34fb";
private static final String charaid   = "0000feaa-0000-1000-8000-00805f9b34fb";
private static final String notifyid  = "00001202-0000-1000-8000-00805f9b34fb";

private void enableNotificationOfCharacteristic(final boolean enable) {
    UUID serviceUUID = UUID.fromString(serviceid);
    UUID charaUUID   = UUID.fromString(charaid);

    if (mBluetoothGatt == null) return;

    BluetoothGattService service = mBluetoothGatt.getService(serviceUUID);
    if (service == null) return;

    BluetoothGattCharacteristic chara = service.getCharacteristic(charaUUID);
    if (chara == null) return;

    boolean success = mBluetoothGatt.setCharacteristicNotification(chara, enable);
    Log.i("success", "setCharactNotify: " + success);

    BluetoothGattDescriptor descriptor = chara.getDescriptor(UUID.fromString(notifyid));
    if (descriptor != null) {
        if (enable) {
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        } else {
            descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        }
        SystemClock.sleep(200);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}

6. 寫入數據

private void writeDataToCharacteristic(byte[] value) {
    if (!liteBluetooth.isServiceDiscoered()) return;

    LiteBleConnector connector = liteBluetooth.newBleConnector();
    connector.withUUIDString(serviceid, get_write_charaid, null)
            .writeCharacteristic(connector.getCharacteristic(), value,
                    new BleCharactCallback() {
                        @Override
                        public void onSuccess(BluetoothGattCharacteristic characteristic) {
                            // 寫入成功
                        }

                        @Override
                        public void onFailure(BleException exception) {
                            bleExceptionHandler.handleException(exception);
                        }
                    });
}

7. 關閉連接

if (liteBluetooth.isConnectingOrConnected()) {
    liteBluetooth.closeBluetoothGatt();
}

數據格式轉換工具類

藍牙收發幾乎全程以 byte[] 進行,調試時經常要與其他格式互轉。下面是我項目裡累積的幾個方法。

1. 兩個 byte 轉 int

private int byteToInt(byte b, byte c) {
    short s0 = (short) (c & 0xff);   // 低八位
    short s1 = (short) (b & 0xff);
    s1 <<= 8;
    return (short) (s0 | s1);
}

2. int 轉兩個 byte

private byte[] int2byte(int res) {
    byte[] targets = new byte[2];
    targets[1] = (byte) (res & 0xff);        // 最低位
    targets[0] = (byte) ((res >> 8) & 0xff); // 次低位
    return targets;
}

3. 十六進制字符串轉 byte[]

public static byte[] hexStringToByte(String hex) {
    int len = hex.length() / 2;
    byte[] result = new byte[len];
    char[] achar = hex.toCharArray();
    for (int i = 0; i < len; i++) {
        int pos = i * 2;
        result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
    }
    return result;
}

private static byte toByte(char c) {
    return (byte) "0123456789ABCDEF".indexOf(c);
}

4. byte[] 轉十六進制字符串

public static String byte2hex(byte[] buffer) {
    String h = "";
    for (int i = 0; i < buffer.length; i++) {
        String temp = Integer.toHexString(buffer[i] & 0xFF);
        if (temp.length() == 1) {
            temp = "0" + temp;
        }
        h = h + temp;
    }
    return h;
}

BLE 的基本操作大致就是這些。下一篇會聊聊低功耗藍牙的空中升級(OTA),網上流傳的 demo 往往過於龐大,我會分享自己精簡後的實現版本。另外數據分包重組那部分,如果有需要也可以在評論裡告訴我。

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