shiny.BluetoothLE 不显示任何已连接的设备,即使设备已连接 .NET MAUI

问题描述 投票:0回答:1

我正在尝试使用 Shiny.BlueetoothLE 在我的 .NET MAUI 应用程序中使用蓝牙功能

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");
        }
    }
}

我已经安装了文档中提到的所有必需的依赖项。

按下按钮后,它会扫描 10 秒,并且不会输出任何内容,即使我已使用蓝牙将设备连接到我的测试设备。它捕获一个异常,指出“未找到连接的设备”。

帮助表示赞赏!

android .net xamarin bluetooth-lowenergy maui
1个回答
0
投票

我可以使用此代码列出外围设备。不过,我不知道为什么有些外设没有名字。

ListPeripheralPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="BluetoothMauiApp1.ListPeripheralPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    Title="ListPeripheralPage">
    <VerticalStackLayout>
        <Label
            HorizontalOptions="Center"
            Text="List Peripheral"
            VerticalOptions="Center" />

        <Button
            x:Name="ListPeripheralBtn"
            Clicked="OnListPeripheralClicked"
            HorizontalOptions="Fill"
            SemanticProperties.Hint="Counts the number of times you click"
            Text="List Peripheral" />

        <!--  ListView to display scanned peripherals  -->
        <ListView x:Name="PeripheralListView">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Detail="{Binding Uuid}" Text="{Binding Name}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </VerticalStackLayout>
</ContentPage>

ListPeripheralPage.xaml.cs

using Shiny;
using Shiny.BluetoothLE;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
namespace BluetoothMauiApp1;

public partial class ListPeripheralPage : ContentPage
{
    private readonly IBleManager _bleManager;
    private ObservableCollection<IPeripheral> _peripherals;

    public ListPeripheralPage()
    {
        InitializeComponent();
        _bleManager = Shiny.Hosting.Host.GetService<IBleManager>();
        _peripherals = new ObservableCollection<IPeripheral>();
        PeripheralListView.ItemsSource = _peripherals;
    }

    private async void OnListPeripheralClicked(object sender, EventArgs e)
    {
        try
        {
            if (_bleManager != null)
            {
                var access = await _bleManager.RequestAccessAsync();

                if (access != AccessState.Available)
                {
                    await DisplayAlert("Bluetooth", "Bluetooth is not available", "OK");
                    return;
                }

                if (_bleManager.IsScanning)
                {
                    _bleManager.StopScan();
                }

                _peripherals.Clear();

                var scanner = _bleManager.Scan().Subscribe(scanResult =>
                {
                    var peripheral = scanResult.Peripheral;
                    if (peripheral != null && !_peripherals.Contains(peripheral))
                    {
                        _peripherals.Add(peripheral);
                        Console.WriteLine($"Peripheral Found: {peripheral.Name} - {peripheral.Uuid}");
                    }
                });

                // Scan for a specific duration (e.g., 10 seconds)
                await Task.Delay(10000);
                scanner.Dispose();

                // Display the list of found peripherals
                foreach (var peripheral in _peripherals)
                {
                    var name = string.IsNullOrEmpty(peripheral.Name) ? "Unknown" : peripheral.Name;

                    Console.WriteLine($"Peripheral: {name} - {peripheral.Uuid}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }

        Console.WriteLine("##### Connection button clicked");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.