What is “reliable write” in BLE?

2020-02-12 01:41发布

问题:

In Android's BLE API (BluetoothGatt) there are methods that deal with reliable writes:

public boolean beginReliableWrite ()

public void abortReliableWrite (BluetoothDevice mDevice)

public boolean executeReliableWrite ()

There is also a Callback for it (in BluetoothGattCallback):

public void onReliableWriteCompleted (BluetoothGatt gatt, int status)

I can't find any documentation on that. What is it? How is it different from "normal" (unreliable?) writes?

回答1:

Reliable write allows checking back transmitted values and atomic execution of one or mutliple transmitted messages.

A good explaination of the reliable write procedure can be found in the BLE part of Mozillas Boot 2 Gecko Project documentation. Even though it's meant for JavaScript the description of beginReliableWrite() in particular is very helpful for understanding the process:

Once a reliable write transaction has been initiated, all calls to characteristic.writeValue() are sent to the remote device for verification and queued up for atomic execution. An Promise that carries the written value is returned in response to every characteristic.writeValue() call and the application is responsible for verifying whether the value has been transmitted accurately. After all characteristics have been queued up and verified, executeReliableWrite() will execute all writes. If a characteristic was not written correctly, calling abortReliableWrite() will cancel the current transaction without committing any values on the remote LE device.

You begin the reliable write,

gatt.beginReliableWrite();

set the value of the characteristic and write it.

characteristic.setValue(value);
gatt.writeCharacteristic(characteristic);

The writeCharacteristic() call will trigger its 'normal' callback. The parameter characteristic contains the actual, written value which can be verified:

@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic, 
                int status) {
    ...

    if(characteristic.getValue() != value) { 
        gatt.abortReliableWrite();
    } else {
        gatt.executeReliableWrite();
    }

    ...
}

Executing the reliable write will trigger the onReliableWriteCompleted(BluetoothGatt gatt, int status) callback.