Jud*_*ham 4 c# bluetooth-lowenergy xamarin.forms
我正在后台连接我的蓝牙 BLE 设备。因此,我需要在后面的代码中获取蓝牙 mac 地址,就像我们在 XAML 中显示 mac 地址一样。
ListView x:Name="lv" ItemSelected="lv_ItemSelected" BackgroundColor="White" SeparatorColor="Aqua">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label TextColor="Black" Text="{Binding NativeDevice.Address}"/>
<Label TextColor="Black" Text="{Binding NativeDevice.Name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Run Code Online (Sandbox Code Playgroud)
所以在我们的 xaml 中,我能够在 NativeDevice.Address 中获取 mac 地址。因此,我需要以同样的方式将其放入我的 xaml.cs 中。我可以通过这种方法获取mac地址
var vailditems = adapter.DiscoveredDevices.Where(i => i.NativeDevice.ToString()
Run Code Online (Sandbox Code Playgroud)
但这不是一个好方法,我需要像我的 xaml 一样获取 NativeDevice.Address 中的 mac 地址。我尝试了这种方法,但它给出的地址为空。
public class NativeDevice
{
public string Name { get; set; }
public string Address { get; set; }
}
NativeDevice V = new NativeDevice();
Baddress = V.Address;
Run Code Online (Sandbox Code Playgroud)
供您参考,mac 地址可在预定义的 IDevice 接口中访问。所以在IDevice接口中我需要访问NativeDevice对象。这是界面。
public interface IDevice : IDisposable
{
Guid Id { get; }
string Name { get; }
int Rssi { get; }
object NativeDevice { get; }
DeviceState State { get; }
IList<AdvertisementRecord> AdvertisementRecords { get; }
Task<IService> GetServiceAsync(Guid id, CancellationToken cancellationToken = default);
Task<IList<IService>> GetServicesAsync(CancellationToken cancellationToken = default);
Task<bool> UpdateRssiAsync();
}
Run Code Online (Sandbox Code Playgroud)
所以我需要访问该接口并在后面的代码中获取 NativeDevice.address 。我将删除 XAML 部分,这样我也不需要 ListView 的 itemsource 中的 mac 地址。如果您想查看我的完整源代码,这是我用来实现 BLE 应用程序的 github 插件。这是我访问 BLE 对象的代码。
public IDevice device;
var obj = device.NativeDevice;
Run Code Online (Sandbox Code Playgroud)
IDevice 接口的代码在哪里
public interface IDevice : IDisposable
{
Guid Id { get; }
string Name { get; }
Plugin.BLE.Abstractions.Contracts.IDevice.UpdateRssiAsync.
int Rssi { get; }
DeviceState State { get; }
object NativeDevice { get; }
Task<IList<IService>> GetServicesAsync(CancellationToken cancellationToken = default);
Task<int> RequestMtuAsync(int requestValue);
Task<bool> UpdateRssiAsync();
}
Run Code Online (Sandbox Code Playgroud)
我对此没有任何线索。有什么建议么?
// this assumes that you already have the BLE object
// from the BLE plugin
var obj = myBLEobject.NativeDevice;
// we want the "Address" property
PropertyInfo propInfo = obj.GetType().GetProperty("Address");
string address = (string)propInfo.GetValue(obj, null);
Run Code Online (Sandbox Code Playgroud)