RxAndroidBLE 的使用

pic
pic

GitHub

RxAndroidBLE

介紹

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

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

使用

a. 獲得 client

你需要維護(hù)一個(gè)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(自動(dòng)連接的標(biāo)志)
    .subscribe(rxBleConnection -> {
        // All GATT operations are done through the rxBleConnection.
    });

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

說(shuō)一下 自動(dòng)連接

  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,自動(dòng)連接:true---》只要遠(yuǎn)處設(shè)備可見(可用)就自動(dòng)連接上設(shè)備)

  2. 作者說(shuō):
    自動(dòng)連接這個(gè)概念,第一眼看上去,讓人充滿了誤解。
    設(shè)置 autoconnect flag 為false:若外圍藍(lán)牙設(shè)備不再?gòu)V播,RxBleDevice#establishConnection 方法會(huì)被調(diào)用,一個(gè)error將被提交。這個(gè)時(shí)間大概在10s左右。
    設(shè)置 autoconnect flag 為true:允許你等待,直到 ble的設(shè)備被發(fā)現(xiàn)可用。直到連接成功以后,RxBleConnection的實(shí)例才會(huì)提交。它也持有了 wake 鎖,等到連接被建立了以后,android的設(shè)備也將會(huì)被喚醒。但這個(gè)特色在將來(lái)也許會(huì)變。
    (原文: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. 注意:不要過(guò)度使用 自動(dòng)連接,這是有負(fù)面影響的:初始連接的速度很慢。原因:因?yàn)閮?yōu)化的原因,后臺(tái)的掃描間隔比較慢,所以它要花費(fèi)更多的時(shí)間去建立連接。
    (原文: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. 多個(gè) 讀
 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. 錯(cuò)誤處理

當(dāng)你遇到錯(cuò)誤的時(shí)候,你會(huì)得到 onError 這個(gè)callback,每個(gè)公共的方法上有JavaDoc 來(lái)解釋可能存在的錯(cuò)誤。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容