I am trying to use Shiny.BlueetoothLE for using bluetooth functionality in my .NET MAUI app
MauiProgram.cs
using Microsoft.Extensions.Logging;
using Shiny;
using Shiny.BluetoothLE;
using Shiny.BluetoothLE.Intrastructure;
namespace shinyTest
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseShiny()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
builder.Services.AddBluetoothLE();
#if DEBUG
builder.Logging.AddDebug();
#endif
return builder.Build();
}
}
}
BluePage.xaml.cs
using Shiny;
using Shiny.BluetoothLE;
using System.Collections.Generic;
using System.Reactive.Linq;
namespace shinyTest;
public partial class BluePage : ContentPage
{
private IDisposable _scanSubscription;
private readonly IBleManager _bleManager;
public BluePage()
{
InitializeComponent();
_bleManager = Shiny.Hosting.Host.GetService<IBleManager>();
}
private async void scan_btn_Clicked(object sender, EventArgs e)
{
try
{
if (_bleManager != null)
{
_scanSubscription = _bleManager
.Scan()
.Take(TimeSpan.FromSeconds(10))
.Subscribe(peripheral =>
{
// Handle discovered peripherals (optional)
});
await Task.Delay(TimeSpan.FromSeconds(10));
var connectedPeripherals = _bleManager.GetConnectedPeripherals().ToList();
var connectedDevices = "";
foreach (var peripheral in connectedPeripherals)
{
connectedDevices += peripheral.Name + "n"; // Add newline for each device name
}
if (connectedPeripherals.Count > 0)
{
await DisplayAlert("Connected Devices", $"{connectedDevices}", "Ok");
}
else
{
await DisplayAlert("Connected Devices", "No devices connected.", "Ok");
}
}
else
{
await DisplayAlert("Error", "BluetoothLE manager is not available.", "Ok");
}
}
catch (Exception ex)
{
await DisplayAlert("Exception", $"{ex.Message}", "Ok");
}
}
}
I have installed all the necesarry dependencies as mentioned in the docs.
On pressing the button it scans for 10 seconds and outputs nothing even though I have connected a device using bluetooth to my testing device. It catches an exception stating “No connected devices found”.
Help appreciated!