来自Xamarin的蓝牙LE特征Android
问题描述:
我想从Xamarin Android应用程序中读取蓝牙LE特征。来自Xamarin的蓝牙LE特征Android
m_characteristicReady = new SemaphoreSlim(1);
m_characteristicChanged = new SemaphoreSlim(1);
public async Task<BluetoothGattCharacteristic> GetCharecteristic(int timeout,BluetoothGattCharacteristic characteristic)
{
EnableCharacteristicNotification(characteristic);
//Once notifications are enabled for a characteristic,
//an onCharacteristicChanged() callback is triggered if the characteristic changes on the remote device:
m_characteristicChanged.Wait();
//We serialize all requests and timeout only on requests themself cand not their predesesors
m_characteristicReady.Wait();
//todo check result ???
m_gatt.ReadCharacteristic(characteristic);
if (await m_characteristicReady.WaitAsync(timeout) == true ||
await m_characteristicChanged.WaitAsync(timeout) == true)
{
m_characteristicChanged.Release();
m_characteristicReady.Release();
return m_characteristic;
}
return null;
}
public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, [Android.Runtime.GeneratedEnum] GattStatus status)
{
m_characteristic = characteristic;
m_characteristicReady.Release();
}
public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
{
m_characteristic = characteristic;
m_characteristicChanged.Release();
}
我的问题是我的public async Task<BluetoothGattCharacteristic> GetCharecteristic(int timeout,BluetoothGattCharacteristic characteristic)
功能
1)is there a possiblity of a deadlock?
2)Is there a way for me to check if the attribute is (notifiable) before enabling notification
答
有死锁的方法可行里面?
如果同时调用m_gatt.readCharacteristic(gattCharacteristic);
和m_gatt.writeCharacteristic(gattCharacteristic);
方法,则可能导致死锁。因为您可以使用两个SemaphoreSlim
同时更改m_characteristic
。使用一个SemaphoreSlim
可以解决死锁如下面的代码:
public async Task<BluetoothGattCharacteristic> GetCharecteristic(int timeout, BluetoothGattCharacteristic characteristic)
{
EnableCharacteristicNotification(characteristic);
m_gatt.ReadCharacteristic(characteristic);
return m_characteristic;
}
public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, [Android.Runtime.GeneratedEnum] GattStatus status)
{
m_SemaphoreSlim.Wait();
m_characteristic = characteristic;
m_SemaphoreSlim.Release();
}
public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
{
m_SemaphoreSlim.Wait();
m_characteristic = characteristic;
m_SemaphoreSlim.Release();
}
有没有为我检查,如果该属性是(法定)启用通知
可以使用返回之前的方式检查的setCharacteristicNotification
值如下的代码,如果该属性是(法定):
boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
if (isEnableNotification)
{
//.....
}
但你打电话之前setCharacte ristic通知没有方法检查属性是否(通知)。