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

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

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

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

相关推荐

  • android线程实现多任务并发执行

    示例示例Android线程是指在Android应用程序中使用的线程。它们可以被用来执行后台任务,而不会影响主线程的性能。Android线程有两种实现方式:…

    2023-01-20 04:28:32
    0 22 66
  • android progressbar 样式:栏

    示例示例Android 样式主要有三种:水平进度条:…

    2023-01-08 05:19:47
    0 45 44
  • android ijkplayer使用:如何使用Android IjkPlayer快速构建视频播放应用

    导入库在项目的build.gradle文件中添加如下依赖:…

    2022-12-31 09:19:12
    0 62 77
  • android 投屏软件轻松实现多屏互动

    Android 投屏软件是一种应用程序,可以将 Android 设备的屏幕内容投射到其他设备上,如电视、投影机或电脑显示器。它可以帮助用户在不同的设备之间共享屏幕内容,从而节省时间和精力。下面是一段示例代码,用于演示如何使用 Android 投屏软件:…

    2023-01-10 10:50:42
    0 32 86
  • android studio 分割线:Android Studio 开发指南

    android studio 分割线是一种在 Android 应用中用于分隔不同部分的视觉元素。它可以帮助用户更好地理解应用中的内容,并使用户更容易浏览和理解应用中的内容。…

    2023-01-01 06:46:30
    0 40 51
  • android studio的sdk构建高效的 Android 应用

    Android Studio SDK(Software Development Kit)是一套用于开发Android应用的工具集。它包括了一系列的API、库文件、编译器、调试器等,可以帮助开发者快速构建出高质量的Android应用。…

    2023-01-12 10:31:16
    0 57 83
  • android go在哪下载:在Google Play上下载Android Go应用程序

    Android Go是Google推出的一款轻量级操作系统,用于低端手机。它可以在Google Play商店中下载,也可以从Google官方网站上下载,地址为:https://developer.android.com/go/index.html 。 也可以使用以下代码来下载:…

    2023-01-17 16:01:56
    0 35 92
  • android 官网让您的应用变得更好

    Android 官网是一个宣传 Android 操作系统的官方网站,由 Google 运营。该网站提供了有关 Android 的最新信息,包括新闻、论坛、文档、开发者资源以及其他相关信息。此外,它还提供了一些常见问题的回答,以及有关如何使用 Android 的指南。String query = "android news";…

    2023-02-01 09:57:29
    0 43 69

发表评论

登录 后才能评论

评论列表(65条)