32feet icon indicating copy to clipboard operation
32feet copied to clipboard

BluetoothClient.DiscoverDevicesAsync blocks for ever on Android

Open osre77 opened this issue 1 year ago • 1 comments

I have a .NET8 MAUI project (Target SDK 34, min SDK 31). Package references:

<PackageReference Include="InTheHand.Bluetooth.Permissions" Version="7.0.1" />
<PackageReference Include="InTheHand.Net.Bluetooth" Version="4.1.40" />

When I want to enumerate the discovered devices, the app blocks forever.

// get permissions
var status = await Permissions.RequestAsync<Permissions.Bluetooth>();
if (status != PermissionStatus.Granted) return;

var client = new BluetoothClient();
// Output window: [BluetoothAdapter] BluetoothAdapter() : osre.nanodog.control

var deviceEnumerator = client.DiscoverDevicesAsync(cancellationToken).GetAsyncEnumerator(cancellationToken);
while (await deviceEnumerator.MoveNextAsync())
// Output window: [BluetoothAdapter] startDiscovery
// now execution is blocked, deviceEnumerator.MoveNextAsync() never returns
{
    var device = deviceEnumerator.Current;
}

my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="osre.nanodog.control" android:versionCode="1" android:versionName="V1">
	<application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true" android:label="NanoDog.Control"></application>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.BLUETOOTH" />
	<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
	<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
	<uses-sdk android:minSdkVersion="31" android:targetSdkVersion="34" />
</manifest>

But if I use the BluetoothDevicePicker everything works and I can communicate with my device:

var picker = new BluetoothDevicePicker();
picker.ClassOfDevices.Add(new ClassOfDevice(DeviceClass.Uncategorized, ServiceClass.None));
_device = await picker.PickSingleDeviceAsync();

if (_device != null)
{
   if (!_device.Authenticated)
   {
      bool paired = BluetoothSecurity.PairRequest(_device.DeviceAddress, DevicePin);
      if (!paired) return;
   }
   await _client.ConnectAsync(_device.DeviceAddress, BluetoothService.SerialPort);
}

Any ideas what I am doing wrong here?

osre77 avatar Jan 27 '24 11:01 osre77

I've checked a fix into the code for DiscoverDevicesAsync, but haven't released a new NuGet package yet.

peterfoot avatar Jan 28 '24 12:01 peterfoot

Released in 4.1.42

peterfoot avatar Mar 10 '24 17:03 peterfoot