gpt4 book ai didi

android - 在 Android 中连续读取 BLE 的值

转载 作者:行者123 更新时间:2023-11-30 01:16:09 24 4
gpt4 key购买 nike

我正在尝试从 Android 设备与 BLE 交互并读取一些传感器值,我遵循 API 级别 > 21。我设法扫描设备并连接到它。第一个挑战是一次读取所有特征值,有人建议使用优先级队列来做到这一点,我以明智的方式实现并且工作正常。

BluetoothGattCallback gattCallBack = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.d(TAG, "STATE_CONNECTED");
bluetoothGatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.d(TAG, "STATE_DISCONNECTED");
break;
default:
Log.d(TAG, "STATE_OTHER");

}
}

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
final List<BluetoothGattService> services = gatt.getServices();
characteristics = new ArrayList<BluetoothGattCharacteristic>();
characteristics.add(services.get(1).getCharacteristics().get(0));
characteristics.add(services.get(1).getCharacteristics().get(1));
characteristics.add(services.get(1).getCharacteristics().get(2));

characteristics.add(services.get(2).getCharacteristics().get(0));
characteristics.add(services.get(2).getCharacteristics().get(1));
characteristics.add(services.get(2).getCharacteristics().get(2));

characteristics.add(services.get(3).getCharacteristics().get(0));
characteristics.add(services.get(3).getCharacteristics().get(1));
characteristics.add(services.get(3).getCharacteristics().get(2));
requesReadCharacteristics(gatt);
}

public void requesReadCharacteristics(BluetoothGatt gatt) {
gatt.readCharacteristic(characteristics.get(characteristics.size() - 1));
}

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == 0 ) {
Log.d(TAG, "DeviceNameFetchFromDevice: " + characteristic.getValue());
characteristics.remove(characteristics.get(characteristics.size() - 1));

if (characteristics.size() > 0) {
requesReadCharacteristics(gatt);
} else {
gatt.disconnect();
}
}
}

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

现在我需要通过 BLE 设备持续监控读取传感器值(比如每隔 10 秒),所以我需要反复读取特征值并获取它们的值。但是 ble 不允许在第一次调用后调用“readCharacteristic”。

现在我已经实现了它,定期调用 connectDevice(BluetoothDevice),这就像断开与 BLE 设备的现有连接并再次连接它。有什么方法可以让我们反复调用 readCharacteristic 连接到设备。根据我的理解,断开和连接设备并不是那么有效。请让我知道,如果有这样的例子,什么是继续读取设备或分享的正确方法

https://github.com/sandeeptengale/androidble/

最佳答案

首先,你应该打开通知:

mBluetoothLeService.setCharacteristicNotification(characteristic, true);

然后,当数据改变时,你可以在这个方法中读取值:

onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)

关于android - 在 Android 中连续读取 BLE 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37848674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com