简体   繁体   中英

Writing multiple commands to characteristic

I am just discovering rxandroidble and can reliably send a single command to the BLE device after connection

However I am struggling to find the best way to write a chain of commands, ie if I have a series of 3 commands that need to be sent

Of course this can be done by nesting the sends, but Im sure there is a better approach!!

Single command send code is

rxBleMainConection.writeCharacteristic(COMS_WRITE_CHAR_UUID,bytes).toObservable()
.subscribe(
                    characteristicValue -> {
                        // Written characteristic value.
                        Log.d(TAG,"Written command: " + Arrays.toString(characteristicValue));

                    },
                    throwable -> {
                        // Handle an error here.
                        Log.d(TAG,"Error writing command");
                        throwable.printStackTrace();
                    }
            );

What is the best way to send a series of say 5 commands?

You could concatenate all the writes you want to make like this:

Single.concat(Arrays.asList(
        rxBleMainConnection.writeCharacteristic(COMS_WRITE_CHAR_UUID, bytes0),
        rxBleMainConnection.writeCharacteristic(COMS_WRITE_CHAR_UUID, bytes1),
        rxBleMainConnection.writeCharacteristic(COMS_WRITE_CHAR_UUID, bytes2),
        rxBleMainConnection.writeCharacteristic(COMS_WRITE_CHAR_UUID, bytes3),
        // ...
        rxBleMainConnection.writeCharacteristic(COMS_WRITE_CHAR_UUID, bytesn)
))
        .subscribe(
                characteristicValue -> {
                    // Written characteristic value.
                    Log.d(TAG, "Written command: " + Arrays.toString(characteristicValue));
                },
                throwable -> {
                    // Handle an error here.
                    Log.d(TAG, "Error writing command");
                    throwable.printStackTrace();
                },
                () -> {
                    Log.d(TAG, "All writes completed");
                }
        );

I would encourage you to take a look on other questions regarding "multiple writes" with RxAndroidBle that were already asked on this site. There are some posts that could give you hints/ideas.

As a side note: it is best to create code that uses only a single .subscribe() as then you have the least state you need to manage by yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM