RXAndroidBLE fail to scan devices and read characteristic

669 Views Asked by At

I am trying to scan devices with RxAndroidBLE but scanning stops immeediately with no scanresult. Here is my code:

                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();

My peripheral device is an Arduino Board, and it can be scanned with standard BLE scanners like "LikeBlue" Here is my 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#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.

So what is wrong here ? I have tried with or without timeout, with or without scanfilter but nothing works. My Arduino has fixed macaddress, so I tried to connect and read characteristic anyway:

                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();

This gives no error, but known characteristic is not read, here is 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

There are 2 best solutions below

2
Dariusz Seweryn On

The issue you are facing is immediate disposal of the subscription. You should call disposable.dispose() after you are done with the scan/connection (hence // When done, just dispose. – most probably after you get your result or when no longer interested in it.

0
Heikki On

and thanks for you help. I got the scan working now, but the documentation and examples (RxAndroidBLE) are REALLY misleading at least for newbies in RXJava, like me ! Here is working code for the scan:

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

So disposing right after scanresult and saving the scanned device. I then tried read a characteristic with this code:

                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
                                                               }
                    );

But this fails with the error in 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'}

It appears that I have to do service discovery first, but how ?