RXAndroidBLE 无法扫描设备并读取特性

时间:2021-06-21 16:57:10

标签: rxandroidble

我正在尝试使用 RxAndroidBLE 扫描设备,但扫描立即停止且没有扫描结果。这是我的代码:

                Disposable flowDisposable = rxBleClient.observeStateChanges()
                        .startWith(rxBleClient.getState())
                        .switchMap(state -> { // switchMap makes sure that if the state will change the rxBleClient.scanBleDevices() will dispose and thus end the scan
                            switch (state) {

                                case READY:
                                    // everything should work
                                    Log.d("rxble","READY scan start:" );
                                    return rxBleClient.scanBleDevices(
                                            new ScanSettings.Builder()
                                                    .setScanMode(ScanSettings.SCAN_MODE_BALANCED) // change if needed
                                                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
                                                    .build(),
                                            new ScanFilter.Builder()
                                                    .setDeviceName("localname")
                                                    .build()
                                    );
                                case BLUETOOTH_NOT_AVAILABLE:
                                    Log.d("rxble","no Bluetooth" );
                                    // basically no functionality will work here
                                case LOCATION_PERMISSION_NOT_GRANTED:
                                    // scanning and connecting will not work
                                    Log.d("rxble","no locate permission" );
                                case BLUETOOTH_NOT_ENABLED:
                                    // scanning and connecting will not work
                                    Log.d("rxble","Bluetooth not enabled" );
                                case LOCATION_SERVICES_NOT_ENABLED:
                                    // scanning will not work
                                    Log.d("rxble","location services not enabled" );
                                default:
                                    return Observable.empty();
                            }
                        })
                        .timeout(10, TimeUnit.SECONDS)
                        .subscribe(
                                rxBleScanResult -> {
                                    String sc = rxBleScanResult.toString();
                                    Log.d("rxble","scan result:" + sc);                                    // Process scan result here.
                                },
                                throwable -> {
                                    // Handle an error here.
                                    Log.d("rxble","scan error" + throwable.getMessage());
                                }
                        );

// When done, just dispose.
                flowDisposable.dispose();

我的外围设备是一个 Arduino 板,它可以使用标准的 BLE 扫描仪(如“LikeBlue”)进行扫描 这是我的日志:

2021-06-21 19:29:11.272 3853-3853/heikki.fi.bttest D/rxble: READY scan start:
2021-06-21 19:29:11.411 3853-3853/heikki.fi.bttest D/RxBle#ClientOperationQueue: QUEUED   ScanOperationApi21(144257920)
2021-06-21 19:29:11.455 3853-10348/heikki.fi.bttest D/RxBle#ClientOperationQueue: STARTED  ScanOperationApi21(144257920)
2021-06-21 19:29:11.483 3853-10348/heikki.fi.bttest I/RxBle#ClientOperationQueue: RUNNING  ScanOperationApi21{ANY_MUST_MATCH -> nativeFilters=[BluetoothLeScanFilter [mDeviceName=localname, MAC=null, mUuid=null, mUuidMask=null, mSolicitedUuid=null, mSolicitedUuidMask=null, mServiceDataUuid=null, mServiceData=null, mServiceDataMask=null, mManufacturerId=-1, mManufacturerData=null, mManufacturerDataMask=null]]}
2021-06-21 19:29:11.506 3853-11095/heikki.fi.bttest I/RxBle#QueueOperation: Scan operation is requested to start.
2021-06-21 19:29:11.513 3853-11095/heikki.fi.bttest D/RxBle#ScanOperationApi21: No library side filtering —> debug logs of scanned devices disabled
2021-06-21 19:29:11.668 3853-10348/heikki.fi.bttest D/RxBle#ClientOperationQueue: FINISHED ScanOperationApi21(144257920) in 227 ms
2021-06-21 19:29:12.018 3853-11095/heikki.fi.bttest I/RxBle#CancellableDisposable: Scan operation is requested to stop.

所以这里有什么问题? 我试过有或没有超时,有或没有扫描过滤器,但没有任何效果。 我的 Arduino 有固定的 macaddress,所以我还是尝试连接和读取特性:

                String macAddress = "84:CC:A8:2E:24:6A";
                RxBleDevice device = rxBleClient.getBleDevice(macAddress);

                Log.d("rxble","trying to read characteristic" );
                Disposable disposable =device.establishConnection(false)
                        .flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(PIN_UUID)))
 //                      .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                characteristicValue -> {
                                    // Read characteristic value.
                                    Log.d("rxble","read value:" + new String(characteristicValue));
 //                                   rtext.setText(new String(characteristicValue));
                                },
                                throwable -> {
                                    Log.d("rxble","read error" + throwable.getMessage());
                                    // Handle an error here.
                                }
                        );
                disposable.dispose();

这不会出错,但不会读取已知特征,这里是 logcat:

2021-06-21 19:52:25.542 3853-3853/heikki.fi.bttest D/rxble: trying to read characteristic
2021-06-21 19:52:25.646 3853-24305/heikki.fi.bttest D/RxBle#ClientOperationQueue: QUEUED   ConnectOperation(156775354)
2021-06-21 19:52:25.683 3853-10348/heikki.fi.bttest D/RxBle#ClientOperationQueue: STARTED  ConnectOperation(156775354)
2021-06-21 19:52:25.705 3853-10348/heikki.fi.bttest I/RxBle#ClientOperationQueue: RUNNING  ConnectOperation{MAC='XX:XX:XX:XX:XX:XX', autoConnect=true}
2021-06-21 19:52:25.815 3853-11095/heikki.fi.bttest V/RxBle#BleConnectionCompat: Connecting without reflection
2021-06-21 19:52:25.878 3853-10348/heikki.fi.bttest D/RxBle#ClientOperationQueue: FINISHED ConnectOperation(156775354) in 195 ms
2021-06-21 19:52:26.888 3853-24305/heikki.fi.bttest D/RxBle#ConnectionOperationQueue: Connection operations queue to be terminated (MAC='XX:XX:XX:XX:XX:XX')
    com.polidea.rxandroidble2.exceptions.BleDisconnectedException: Disconnected from MAC='XX:XX:XX:XX:XX:XX' with status -1 (UNKNOWN)
        at com.polidea.rxandroidble2.internal.serialization.ConnectionOperationQueueImpl.onConnectionUnsubscribed(ConnectionOperationQueueImpl.java:162)
        at com.polidea.rxandroidble2.internal.connection.ConnectorImpl$1$1.run(ConnectorImpl.java:65)
        at io.reactivex.internal.operators.observable.ObservableDoFinally$DoFinallyObserver.runFinally(ObservableDoFinally.java:142)
        at io.reactivex.internal.operators.observable.ObservableDoFinally$DoFinallyObserver.dispose(ObservableDoFinally.java:98)
        at io.reactivex.internal.disposables.DisposableHelper.dispose(DisposableHelper.java:124)
        at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeOnObserver.dispose(ObservableSubscribeOn.java:73)
        at io.reactivex.internal.operators.observable.ObservableUnsubscribeOn$UnsubscribeObserver$DisposeTask.run(ObservableUnsubscribeOn.java:95)
        at io.reactivex.internal.schedulers.ScheduledDirectTask.call(ScheduledDirectTask.java:38)
        at io.reactivex.internal.schedulers.ScheduledDirectTask.call(ScheduledDirectTask.java:26)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
2021-06-21 19:52:26.914 3853-24305/heikki.fi.bttest D/RxBle#ClientOperationQueue: QUEUED   DisconnectOperation(170873441)
2021-06-21 19:52:26.927 3853-24304/heikki.fi.bttest V/RxBle#Executors: Terminated (MAC='XX:XX:XX:XX:XX:XX')
2021-06-21 19:52:26.950 3853-10348/heikki.fi.bttest D/RxBle#ClientOperationQueue: STARTED  DisconnectOperation(170873441)
2021-06-21 19:52:26.973 3853-10348/heikki.fi.bttest I/RxBle#ClientOperationQueue: RUNNING  DisconnectOperation{MAC='XX:XX:XX:XX:XX:XX'}
2021-06-21 19:52:27.061 3853-10348/heikki.fi.bttest D/RxBle#ClientOperationQueue: FINISHED DisconnectOperation(170873441) in 128 ms

2 个答案:

答案 0 :(得分:0)

您面临的问题是立即处理订阅。您应该在完成扫描/连接后调用 disposable.dispose() (因此 // When done, just dispose. – 很可能是在您获得结果后或不再感兴趣时。

答案 1 :(得分:0)

感谢您的帮助。我现在可以进行扫描了,但是文档和示例(RxAndroidBLE)至少对于像我这样的 RXJava 新手来说确实具有误导性! 这是扫描的工作代码:

enter code here

            if (flowDisposable!=null) // dispose first if not disposed
                if (!flowDisposable.isDisposed())
                    flowDisposable.dispose();
            flowDisposable = rxBleClient.observeStateChanges()
                    .startWith(rxBleClient.getState())
                    .switchMap(state -> { // switchMap makes sure that if the state will change the rxBleClient.scanBleDevices() will dispose and thus end the scan
                        switch (state) {

                            case READY:
                                // everything should work
                                Log.d("rxble","READY scan start:" );
                                return rxBleClient.scanBleDevices(
                                        new ScanSettings.Builder()
                                                .setScanMode(ScanSettings.SCAN_MODE_BALANCED) // change if needed
                                                .setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH) // change if needed
                                                .build(),
                                        new ScanFilter.Builder()
                                                .setDeviceName("localname")
                                                .build()
                                );
                            case BLUETOOTH_NOT_AVAILABLE:
                                Log.d("rxble","no Bluetooth" );
                                // basically no functionality will work here
                            case LOCATION_PERMISSION_NOT_GRANTED:
                                // scanning and connecting will not work
                                Log.d("rxble","no locate permission" );
                            case BLUETOOTH_NOT_ENABLED:
                                // scanning and connecting will not work
                                Log.d("rxble","Bluetooth not enabled" );
                            case LOCATION_SERVICES_NOT_ENABLED:
                                // scanning will not work
                                Log.d("rxble","location services not enabled" );
                            default:
                                return Observable.empty();
                        }
                    })
                    .timeout(10, TimeUnit.SECONDS)
                    .subscribe(
                            rxBleScanResult -> {
                                device = rxBleScanResult.getBleDevice(); // get device to use later
                                String sc = rxBleScanResult.toString();
                                Log.d("rxble","scan result:"+rxBleScanResult.getBleDevice().getMacAddress()+" " + sc);                                    // Process scan result here.
                                flowDisposable.dispose(); // dispose after use
                            },
                            throwable -> {
                                // Handle an error here.
                                Log.d("rxble","scan error" + throwable.getMessage());
                                flowDisposable.dispose(); // dispose after error
                            }
                    );
enter code here

因此在扫描结果后立即处理并保存扫描的设备。然后我尝试使用以下代码读取特征:

                UUID uuid = UUID.fromString(PIN_UUID);
            Log.d("rxble","trying to read characteristic:"+uuid );
            if (disposable!=null) // dispose first if was not disposed
              if (!disposable.isDisposed()) {
                  disposable.dispose();
              }
            disposable = device.establishConnection(false)
                    .flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(uuid))

                    .subscribe(
                            characteristicValue -> {
                                // Read characteristic value.
                                Log.d("rxble","read value:" + new String(characteristicValue));
                                disposable.dispose(); //dispose after use
                            },
                            throwable -> {
                                Log.d("rxble","read error" + throwable.getMessage());
                                disposable.dispose(); // dispose after error
                                                               }
                    );

但是这失败了,并在 logcat 中出现错误:

2021-06-22 11:54:55.495 25353-26152/heikki.fi.bttest D/rxble: read errorGATT exception from MAC address 84:CC:A8:2E:24:6A, with type BleGattOperation{description='SERVICE_DISCOVERY'}

看来我必须先做服务发现,但是怎么做?