inthehand / 32feet

Personal Area Networking for .NET. Open source and professionally supported
https://inthehand.com/components/32feet/
MIT License
832 stars 209 forks source link

BluetoothClient.DiscoverDevicesAsync blocks for ever on Android #392

Closed osre77 closed 8 months ago

osre77 commented 9 months ago

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?

peterfoot commented 9 months ago

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

peterfoot commented 8 months ago

Released in 4.1.42