BLE设备不响应​​命令

时间:2019-04-04 07:43:10

标签: java android bluetooth bluetooth-lowenergy

我有一些特定的BLE设备,它通过两个特性(写和读)来模拟套接字连接。因此,如果您为“写入”特征编写任何命令,则“读取”特征将通过通知为您提供答案。

当我使用蓝牙终端nRF Connect时,它的工作方式正确。但是,当我尝试使用Android API重复该操作时,设备不会响应命令。

我创建了BluetoothGattCallback对象并开始与设备连接:

BluetoothGattCallback callback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            gatt.discoverServices();
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        BluetoothGattService cccdService = gatt.getService(UUID.fromString("00001801-0000-1000-8000-00805f9b34fb"));
        BluetoothGattCharacteristic cccdCharacteristic = cccdService.getCharacteristic(UUID.fromString("00002a05-0000-1000-8000-00805f9b34fb"));
        BluetoothGattService deviceService = gatt.getService(UUID.fromString("569a1101-b87f-490c-92cb-11ba5ea5167c"));
        BluetoothGattCharacteristic writeCharacteristic = deviceService.getCharacteristic(UUID.fromString("569a2001-b87f-490c-92cb-11ba5ea5167c"));
        BluetoothGattCharacteristic readCharacteristic = deviceService.getCharacteristic(UUID.fromString("569a2000-b87f-490c-92cb-11ba5ea5167c"));
        BluetoothGattCharacteristic c2002 = deviceService.getCharacteristic(UUID.fromString("569a2002-b87f-490c-92cb-11ba5ea5167c"));

        gatt.setCharacteristicNotification(cccdCharacteristic, true);
        gatt.setCharacteristicNotification(readCharacteristic, true);
        gatt.setCharacteristicNotification(c2002, true);
        gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);

        // makeHeader is method that create byte request
        writeCharacteristic.setValue(makeHeader((byte) 1, (byte) 1, MemoConstDdin.DATA, (short) 1000));
        gatt.writeCharacteristic(writeCharacteristic);
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);
        displayResponse(characteristic);
    }
};
gatt = device.connectGatt(this, false, callback);

连接成功。找到服务。启用通知。写特征成功。但。永远不会调用方法onCharacteristicChanged来获取“读取”特征。

此代码或我有什么问题? 任何想法。 谢谢!

1 个答案:

答案 0 :(得分:3)

您还应该启用指示或通知值。

发现与您的特征相对应的描述符。然后

adescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(adescriptor);