将多个命令写入特性

Writing multiple commands to characteristic

我刚刚发现 rxandroidble 并且可以在连接后可靠地向 BLE 设备发送单个命令

但是我正在努力寻找编写命令链的最佳方法,即如果我有一系列 3 个命令需要发送

当然这可以通过嵌套发送来完成,但我相信有更好的方法!!

单条指令发送码为

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

发送一系列 say 5 命令的最佳方式是什么?

您可以像这样连接所有要写入的内容:

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

我鼓励您查看此站点上已经询问过的其他 questions regarding "multiple writes" with RxAndroidBle。有些帖子可以给你 hints/ideas.

附带说明:最好创建仅使用单个 .subscribe() 的代码,因为这样您需要自己管理的状态最少。