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

我试图用 RxAndroidBLE 扫描设备,但扫描停止 immeediately 没有扫描结果。这是我的代码:

我试图用 RxAndroidBLE 扫描设备,但扫描停止 immeediately 没有扫描结果。这是我的代码:

                Disposable flowDisposable = rxBle.observeStateChanges()
                        .startWith(rxBle.getState())
                        .switchMap(state -> { // switchMap makes sure that if the state will change the rxBle.scanBleDevices() will dispose and thus end the scan
                            switch (state) {
                                case READY:
                                    // everything should work
                                    Log.d("rxble","READY scan start:" );
                                    return rxBle.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_AILABLE:
                                    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”这是我的 logcat:

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#OperationQueue: QUEUED   ScanOperationApi21(144257920)
2021-06-21 19:29:11.455 3853-10348/heikki.fi.bttest D/RxBle#OperationQueue: STARTED  ScanOperationApi21(144257920)
2021-06-21 19:29:11.483 3853-10348/heikki.fi.bttest I/RxBle#OperationQueue: 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#OperationQueue: 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.

那么这里有什么问题?我已经尝试了有或没有超时,有或没有 scanfilter 但没有任何作品。我的 Arduino 有固定的 macaddress,所以我试图连接和读取特征无论如何:

                String macAddress = "84:CC:A8:2E:24:6A";
                RxBleDevice device = rxBle.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#OperationQueue: QUEUED   ConnectOperation(156775354)
2021-06-21 19:52:25.683 3853-10348/heikki.fi.bttest D/RxBle#OperationQueue: STARTED  ConnectOperation(156775354)
2021-06-21 19:52:25.705 3853-10348/heikki.fi.bttest I/RxBle#OperationQueue: 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#OperationQueue: 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#OperationQueue: 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#OperationQueue: STARTED  DisconnectOperation(170873441)
2021-06-21 19:52:26.973 3853-10348/heikki.fi.bttest I/RxBle#OperationQueue: RUNNING  DisconnectOperation{MAC='XX:XX:XX:XX:XX:XX'}
2021-06-21 19:52:27.061 3853-10348/heikki.fi.bttest D/RxBle#OperationQueue: FINISHED DisconnectOperation(170873441) in 128 ms
1

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

0

并感谢您的帮助。我现在得到了扫描工作,但文档和示例 (RxAndroidBLE) 至少对 RXJava 中的新手来说真的是误导性的,就像我一样!这里是扫描的工作代码:

enter code here
            if (flowDisposable!=null) // dispose first if not disposed
                if (!flowDisposable.isDisposed())
                    flowDisposable.dispose();
            flowDisposable = rxBle.observeStateChanges()
                    .startWith(rxBle.getState())
                    .switchMap(state -> { // switchMap makes sure that if the state will change the rxBle.scanBleDevices() will dispose and thus end the scan
                        switch (state) {
                            case READY:
                                // everything should work
                                Log.d("rxble","READY scan start:" );
                                return rxBle.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_AILABLE:
                                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

所以在 scanresult 之后处理并保存扫描的设备。然后我试着用这个代码读取一个特性:

                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'}

看来我必须先做服务发现,但如何?

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(504)
无法运行 istio-ingressgateway 获得就绪探测失败:连接被拒绝
上一篇
iOSWidget在WidgetSearch中不可用(仅适用于 50%的用户)
下一篇

相关推荐

  • android 自定义viewgroup:栏```xml ```

    Android 自定义 ViewGroup 是指在 Android 开发中,通过继承 ViewGroup 类来实现自定义 ViewGroup 的功能。…

    2023-06-12 11:57:26
    0 44 94
  • linux 安装android sdk:Linux下安装Android SDK的步骤

    下载Android SDK:从官网下载Android SDK,地址:https://.android.google.cn/studio/解压安装包:将下载的文件解压到指定的目录,比如/opt/android-sdk…

    2023-06-05 01:41:10
    0 25 46
  • android系统自己跑流量:如何让Android系统更有效地管理流量

    Android系统自己跑流量的原理是:Android系统本身拥有一个网络连接管理器,它可以检测用户手机的网络状态,当网络状态发生变化时,它会自动启动相应的网络连接,从而让用户可以访问网络。…

    2023-05-30 15:37:34
    0 32 52
  • android 源码下载构建强大的跨平台应用程序

    Android 源码下载是指从官方网站下载 Android 操作系统的源代码。Android 源码可以帮助开发者了解 Android 内部的工作原理,并可以用来修改和定制 Android 系统。要下载 Android 源码,首先需要访问 Android 开发者网站(https://developer.android.com/),然后在页面上找到“下载”选项,点击进入,选择“源代码”选项,然后根据自己想要下载的 Android 版本,选择对应的源代码下载链接,下载源代码文件即可。…

    2023-03-31 06:46:57
    0 41 97
  • android图片框架:如何使用Android图片框架来创建高性能的图像应用

    Android图片框架是一种用于处理和显示图片的软件库,它可以帮助开发者快速、高效地实现图片处理和显示的功能。它可以提供丰富的图片处理功能,如图片缩放、旋转、裁剪、压缩等,还可以提供图片加载和缓存功能,以及图片显示和动画效果等。…

    2024-01-30 06:17:25
    0 28 99
  • zip android 应用解压缩文件快速简便

    Zip Android 应用是一种压缩应用,它可以帮助用户将文件和文件夹压缩到一个zip文件中。它还可以解压缩zip文件,并提供一个简单的界面来浏览压缩文件内容。…

    2023-10-13 08:00:25
    0 56 87
  • androidstudio更新提升开发效率,助力应用创新

    Android Studio有两种更新方式:直接从Android Studio的内部更新:…

    2023-12-20 08:02:33
    0 53 34
  • android 弹幕:解锁Android弹幕的秘密!

    Android 弹幕是一种在视频、游戏等应用中,用户可以发送文本或图像弹幕的功能。它可以使用户在不影响他人体验的情况下,对视频、游戏等进行互动,增加用户体验。…

    2024-01-05 08:46:54
    0 27 92

发表评论

登录 后才能评论

评论列表(81条)