问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/50937923/writing-multiple-commands-to-characteristic