RxAndroidBLE 的使用

pic
pic

GitHub

RxAndroidBLE

介紹

開發(fā)Android的BLE很痛苦,RxAndroidBLE可以極大的減輕您這方面的苦惱(手動滑稽)。
它依賴于RxJava,將 BLE 相關(guān)的復(fù)雜的Api轉(zhuǎn)變?yōu)?可交互性的observables
它為你提供了以下特色:

  1. 漂亮的異步操作支持(讀,寫,通知)
  2. Android下的線程管理(主線程,后臺線程。。。)。
  3. 連接與操作的失敗處理。

使用

a. 獲得 client

你需要維護(hù)一個client的單例:

RxBleClient rxBleClient = RxBleClient.create(context);

b. 發(fā)現(xiàn)設(shè)備

在一定的區(qū)域內(nèi)掃描設(shè)備:

Subscription scanSubscription = rxBleClient.scanBleDevices()
    .subscribe(rxBleScanResult -> {
        // Process scan result here.
    });


// When done, just unsubscribe.(掃描設(shè)備 結(jié)束后,取消訂閱)
scanSubscription.unsubscribe();

c. 連接

連接完成后,才能進(jìn)行讀寫操作。所以連接是必須的:

String macAddress = "AA:BB:CC:DD:EE:FF";
RxBleDevice device = rxBleClient.getBleDevice(macAddress);

Subscription subscription = device.establishConnection(context, false) // <-- autoConnect flag(自動連接的標(biāo)志)
    .subscribe(rxBleConnection -> {
        // All GATT operations are done through the rxBleConnection.
    });

// When done... unsubscribe and forget about connection teardown :)
subscription.unsubscribe();

說一下 自動連接

  1. 官網(wǎng):
    [https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context), boolean, android.bluetooth.BluetoothGattCallback):
    autoConnect boolean: Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true).
    (直接連接:false,自動連接:true---》只要遠(yuǎn)處設(shè)備可見(可用)就自動連接上設(shè)備)

  2. 作者說:
    自動連接這個概念,第一眼看上去,讓人充滿了誤解。
    設(shè)置 autoconnect flag 為false:若外圍藍(lán)牙設(shè)備不再廣播,RxBleDevice#establishConnection 方法會被調(diào)用,一個error將被提交。這個時間大概在10s左右。
    設(shè)置 autoconnect flag 為true:允許你等待,直到 ble的設(shè)備被發(fā)現(xiàn)可用。直到連接成功以后,RxBleConnection的實例才會提交。它也持有了 wake 鎖,等到連接被建立了以后,android的設(shè)備也將會被喚醒。但這個特色在將來也許會變。
    (原文:From experience it also handles acquiring wake locks, so it's safe to assume that your Android device will be woken up after the connection has been established - but it is not a documented feature and may change in the future system releases.)

  3. 注意:不要過度使用 自動連接,這是有負(fù)面影響的:初始連接的速度很慢。原因:因為優(yōu)化的原因,后臺的掃描間隔比較慢,所以它要花費(fèi)更多的時間去建立連接。
    (原文:Scanning window and interval is lowered as it is optimized for background use and depending on Bluetooth parameters it may (and usually do) take more time to establish the connection.)

d. 讀寫操作

device.establishConnection(context, false)
    .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUUID))
    .subscribe(characteristicValue -> {
        // Read characteristic value.
    });
device.establishConnection(context, false)
    .flatMap(rxBleConnection -> rxBleConnection.writeCharacteristic(characteristicUUID, bytesToWrite))
    .subscribe(characteristicValue -> {
        // Characteristic value confirmed.
    });
  1. 多個 讀
 device.establishConnection(context, false)
    .flatMap(rxBleConnection -> Observable.combineLatest(
        rxBleConnection.readCharacteristic(firstUUID),
        rxBleConnection.readCharacteristic(secondUUID),
        YourModelCombiningTwoValues::new
    ))
    .subscribe(model -> {
        // Process your model.
    });
  1. 讀寫結(jié)合
 device.establishConnection(context, false)
    .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUuid)
        .doOnNext(bytes -> {
            // Process read data.
        })
        .flatMap(bytes -> rxBleConnection.writeCharacteristic(characteristicUuid, bytesToWrite)))
    .subscribe(writeBytes -> {
        // Written data.
    });

e. 改變通知

device.establishConnection(context, false)
    .flatMap(rxBleConnection -> rxBleConnection.setupNotification(characteristicUuid))
    .doOnNext(notificationObservable -> {
        // Notification has been set up
    })
    .flatMap(notificationObservable -> notificationObservable) // <-- Notification has been set up, now observe value changes.
    .subscribe(bytes -> {
        // Given characteristic has been changes, here is the value.
    });

f. 觀察連接狀態(tài)

當(dāng)你想觀察設(shè)備的連接狀態(tài),做如下訂閱:

device.observeConnectionStateChanges()
    .subscribe(connectionState -> {
        // Process your way.
    });

g. 日志

為了連接調(diào)試,你可以使用拓展的日志:

RxBleClient.setLogLevel(RxBleLog.DEBUG);

l. 錯誤處理

當(dāng)你遇到錯誤的時候,你會得到 onError 這個callback,每個公共的方法上有JavaDoc 來解釋可能存在的錯誤。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容