[英]Bluetooth LE characteristic from Xamarin Android
我正在嘗試從Xamarin Android應用程序讀取Bluetooth LE特性。
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)
{
//.....
}
但是,在調用setCharacteristicNotification之前,沒有方法可以檢查該屬性是否為(可通知的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.