在 Android 中写入 GATT 后的 BLE 回答

Posted

技术标签:

【中文标题】在 Android 中写入 GATT 后的 BLE 回答【英文标题】:BLE Answer after writing over GATT in Android 【发布时间】:2014-01-10 12:07:52 【问题描述】:

android中通过低功耗蓝牙编写十六进制命令后,有没有办法得到答案?我在 gatt 上写了 hex 命令,这是我的写函数:

/* set new value for particular characteristic */
public void writeDataToCharacteristic(final BluetoothGattCharacteristic ch, final byte[] dataToWrite) 
    if (mBluetoothAdapter == null || mBluetoothGatt == null || ch == null) return;

    // first set it locally....
    ch.setValue(dataToWrite);
    // ... and then "commit" changes to the peripheral
    mBluetoothGatt.writeCharacteristic(ch);

写入完成后,回调只告诉我它是成功还是失败,但接收者会发回一个答案。目前只有检查成功与否,但我不想显示接收者的答案。有没有办法显示答案?

    /*The callback function*/
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) 
        String deviceName = gatt.getDevice().getName();
        String serviceName = BleNamesResolver.resolveServiceName(characteristic.getService().getUuid().toString().toLowerCase(Locale.getDefault()));
        String charName = BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString().toLowerCase(Locale.getDefault()));
        String description = "Device: " + deviceName + " Service: " + serviceName + " Characteristic: " + charName;

        // we got response regarding our request to write new value to the characteristic
        // let see if it failed or not
        if(status == BluetoothGatt.GATT_SUCCESS) 
             mUiCallback.uiSuccessfulWrite(mBluetoothGatt, mBluetoothDevice, mBluetoothSelectedService, characteristic, description);
        
        else 
             mUiCallback.uiFailedWrite(mBluetoothGatt, mBluetoothDevice, mBluetoothSelectedService, characteristic, description + " STATUS = " + status);
        
    ;

【问题讨论】:

【参考方案1】:

在你的回调中你试过了吗

characteristic.getValue() ?

如果此值与您设置和发送的值不同,则可能是您正在寻找的响应。

另外,请确保您正在写入的 Characteristic 具有可读取或可通知的属性。你可以这样做:

int props = characteristic.getProperties();
String propertiesString = String.format("0x%04X ", props);
if((props & BluetoothGattCharacteristic.PROPERTY_READ) != 0) propertiesString += "read ";
if((props & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) propertiesString += "write ";
if((props & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) propertiesString += "notify ";
if((props & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) propertiesString += "indicate ";

服务可能有两个特征 - 一个是可写的(用于发送数据),另一个是可通知的用于接收数据。这使得接收方可以进行异步处理。确保服务中没有其他可通知或可读的特征

【讨论】:

以上是关于在 Android 中写入 GATT 后的 BLE 回答的主要内容,如果未能解决你的问题,请参考以下文章

Android BLE Gatt 连接更改状态

Android BLE 无法从设备接收 Gatt 特性通知

BLE GATT 上传数据 - Android

如何在Android中为BLE编写快速稳定的特性?

BlueZ BLE GATT 写入请求 (0x12) 而不是 (0x16)

在 GATT Android 中获取 BLE 特性的值