Android蓝牙LE - 读取浮动特征

时间:2017-02-08 13:05:24

标签: android bluetooth-lowenergy android-bluetooth gatt

我正在尝试读取连接的蓝牙LE设备(Genuino 101)的浮动特性。出于测试目的,该设备提供FloatCharacteristic,其中包含硬编码值55.3''虽然我能够收到一个类似于浮点数的字符串,但我无法读取实际的浮点值 这是处理字符串的代码片段:

// For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
        }

直接从android开发者主页的https://developer.android.com/samples/BluetoothLeGatt/index.html BLE演示项目中复制。 然后由此代码段处理意图:

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("Broadcast received");
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {

        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {

        } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {

        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
           displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

private void displayData(String data) {
    if (data != null) {
        System.out.println("Data Received: " + data);
    }
}

导致输出

I/System.out: Data Received: 33]B 
I/System.out: 33 33 5D 42

因此,抛开交换的字节序,这是55.3f的正确十六进制值。
但是,如果我尝试使用characteristic.getFloatValue(),我只会得到垃圾。以下是我试图找出如何获得实际浮动的方法:

final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            for (int i = 0; i< 333; i++) {
                try {
                    final float fData = characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_FLOAT, i);
                    System.out.println("Offset = "+ i + ". Data that gets sent: " + fData + "/Data that we would expect: " + 55.3f);
                } catch (Exception e) {
                    System.out.println("Exception at offset " + i);
                }
            }
        }

输出始终为

I/System.out: Offset = 0. Data that gets sent: Infinity/Data that we would expect: 55.3
I/System.out: Exception at offset 1
I/System.out: Exception at offset 2
...

这里我的错误是什么?另外,我不确定应该如何理解Offset参数。它是以位为单位的偏移量,以字节为单位吗?来自LSB的MSB计数? 此外,getFloatValue()声明&#34;的文档返回float - 给定偏移处的特征的缓存值,如果请求的偏移超过值大小,则返回null。 &#34 ;.但是上面的代码段大大超过了任何gatt特性的最大大小,但是不是返回&#39; null&#39;,方法调用抛出异常。 那么在这里获得浮动的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

目前,我通过使用

格式化数据来帮助自己
 float f1 = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getFloa‌​t();

相关问题