无法读取从一个BLE设备发送到其他

时间:2018-02-16 04:04:59

标签: java android bluetooth-lowenergy beacon

我正在使用Android应用程序发送一个字符串,通过BLE设想“Hello World”。当我从其他BLE扫描仪扫描时,我在扫描仪应用程序上获得了服务和特征名称,但无法读取“Hello World”特征的实际值。

以下是代码片段: - UUID

public static final String UUID_SENSOR_SERVICE = "0000180f-0000-1000-8000-00805f9b34fb";
public static final String UUID_SENSORS_LEVEL = "00002a19-0000-1000-8000-00805f9b34fb";

创建BluetoothGattService

private BluetoothGattService createService() {
        Log.d(TAG, "createService: ");
        BluetoothGattService service = new BluetoothGattService(UUID.fromString(SimpleGattAtributes.UUID_SENSOR_SERVICE), SERVICE_TYPE_PRIMARY);

        // Counter characteristic (read-only, supports subscriptions)
        BluetoothGattCharacteristic data = new BluetoothGattCharacteristic(UUID.fromString(SimpleGattAtributes.UUID_SENSORS_LEVEL), PROPERTY_READ , PERMISSION_READ);
        service.addCharacteristic(data);
        return service;
    }

启动GattServer

private void startGattServer(Context mContext){
        Log.d(TAG, "startGattServer: ");

        BluetoothGattServerCallback mGattServerCallback =   new BluetoothGattServerCallback() {

            @Override
            public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
                if (SimpleGattAtributes.UUID_SENSORS_LEVEL.equals(characteristic.getUuid())) {
                    Log.d(TAG, "onCharacteristicReadRequest: I am here");
                    byte[] value = "HelloWorld".getBytes(Charset.forName("UTF-8"));


                    mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, value);
                }
            }
        };


        mGattServer = bluetoothManager.openGattServer(mContext, mGattServerCallback);
        mGattServer.addService(createService());


    }

运行上面的代码后,当我打开Scanner应用程序时,我的应用程序广播了BLE信标。但是,当我试图阅读我的“Hellow World”的特征价值时。我没理得。

在Android手机上测试

enter image description here

尝试阅读特征值

enter image description here

任何人都可以帮助我吗?我使用日志,我看到的是当我点击“阅读”按钮时 BluetoothGattServerCallback 没有触发。它必须被触发。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。感谢@davidgyoung

使用断点我发现 BluetoothGattServerCallback 中的条件总是评估为 false

如果条件是我正在将 UUID 字符串进行比较,我总是评估错误。

我必须将 UUID UUID 进行比较。

更正了条件

(size of destination buffer) - (the length of the destination string) - 1

我已经检查过并且效果很好。

相关问题