我正在尝试从BLE设备读取值。我遵循的步骤:
我用于读写的函数如下:
a)阅读功能:
public void readCharacteristic(BluetoothGattCharacteristic characteristic)
{
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
boolean status;
Log.w(TAG, "SCBABLe: Writing BLuetooth");
status=mBluetoothGatt.readCharacteristic(characteristic);
if(status) {
Log.w(TAG, "Read Successfully");
}
else
{
Log.w(TAG, "Read Unsuccessfully");
}
}
b)写功能
public void writeCharacteristic(BluetoothGattCharacteristic characteristic)
{
if (mBluetoothAdapter == null || mBluetoothGatt == null)
{
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
boolean status;
Log.w(TAG, "SCBABLe: Writing BLuetooth");
status=mBluetoothGatt.writeCharacteristic(characteristic);
if(status) {
Log.w(TAG, "Write Successfully");
}
else
{
Log.w(TAG, "Write Unuccessfully");
}
}
在获得所需特征(通过匹配UUID)后,我从不同的活动中调用上述两个。
//Current Activity Name: DeviceControlActivity
//BluetoothLeService is the other activity where Read and write are defined
private static final DeviceControlActivity holder1 = new DeviceControlActivity();
public BluetoothGattCharacteristic reqChar;
public BluetoothLeService reqService;
private BluetoothLeService mBluetoothLeService;
private void displayGattServices(List<BluetoothGattService> gattServices)
{
if (gattServices == null) return;
String uuid = null;
for (BluetoothGattService gattService : gattServices)
{
uuid = gattService.getUuid().toString();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics)
{
uuid = gattCharacteristic.getUuid().toString();
//SampleGattAttributes.UNKNOWN_CHARACTERISTIC is the hardcoded uuid against which i am checking
if((uuid.equals((SampleGattAttributes.UNKNOWN_CHARACTERISTIC))))
{
holder1.reqChar = gattCharacteristic;
holder1.reqService = mBluetoothLeService;
//Call for write
byte [] byte1= {0x01, 0x10};
holder1.reqChar.setValue(byte1);
holder1.reqService.writeCharacteristic(holder1.reqChar);
//Call for read
holder1.reqService.readCharacteristic(holder1.reqChar);
结果:读取函数返回false并且写入函数返回true,因此成功写入了所需特征的值。(已验证)
请,任何人都可以帮忙并告诉为什么读取没有被执行?当它具有Read作为属性并且定义了适当的值时,为什么它仍然返回false?
答案 0 :(得分:2)
问题在于以下几行。
holder1.reqService.writeCharacteristic(holder1.reqChar);
//Call for read
holder1.reqService.readCharacteristic(holder1.reqChar);
调用writeCharacteristic后,如果你做任何额外的读/写/等。 ,调用将不会执行并返回false。在进一步操作之前,您必须等待BluetoothGattCallback.onCharacteristicWrite。
答案 1 :(得分:0)
在Android BLE实现中,需要对gatt操作调用进行排队,以便一次只有一个操作(读取,写入等)生效。因此,例如,在调用gatt.readCharacteristic(characteristicX)
之后,您需要等待gatt回调BluetoothGattCallback.onCharacteristicRead()
以指示读取已完成。如果在前一个gatt.readCharacteristic()操作完成之前启动第二个gatt.readCharacteristic()操作,则第二个操作将失败(返回false)这适用于所有gatt.XXX()操作。
它有点工作,但我认为最好的解决方案是为所有gatt操作创建一个命令队列,并一次运行一个。您可以使用命令模式来完成此任务。