在我的UWP应用中,能够发现运行在设备上的Android应用并读取其device name characteristic
有效。但是在同一个Android应用程序中,我有一个自定义服务,该服务已添加到GATT中,具有读取功能。我可以在另一个Android应用程序中找到我的服务,但是在我的UWP应用程序中却找不到。这是我的代码:
if (ulong.TryParse(deviceAddress, out ulong address))
{
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(address);
// the name of the device of bluetoothLeDevice matches my device, so I know I have the right address
var serviceId = new Guid(myCustomServiceId);
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(serviceId);
var q = await bluetoothLeDevice.GetGattServicesAsync();
if (q?.Status == GattCommunicationStatus.Success)
{
foreach (var x in q.Services) // q.Services is empty
{
// never comes in here
}
}
}
知道为什么吗?
答案 0 :(得分:2)
您是否已在Package.appxmanifest中设置ble功能?
如果您使用的是Visual Studio,请找到Package.appxmanifest并双击它。
转到选项卡功能,然后检查蓝牙并保存。
您也可以使用xml编辑器来修改Package.appxmanifest。
添加:
<Capabilities>
<DeviceCapability Name="bluetooth" />
</Capabilities>
如果您已经设置了功能,请查看我的SimpleBleExample_by_Devicename
在Github上:
https://github.com/GrooverFromHolland/SimpleBleExample_by_Devicename
没有控制使其保持尽可能简单。所有结果都显示在调试输出窗口中。
答案 1 :(得分:0)
为我解决的是,与其尝试在按钮单击回调中查找我的服务/特性,不如在myBluetoothLEAdvertisementWatcher.Received
回调中找到它们:
private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
bool isMyDevice = false;
// figure out if isMyDevice should be true by checking the advertised service uuids
if (isMyDevice)
{
var bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
var serviceId = new Guid(My_Service_UUID);
var result = await bluetoothLeDevice.GetGattServicesForUuidAsync(serviceId);
if (result?.Status == GattCommunicationStatus.Success)
{
var service = result.Services.FirstOrDefault(s => s.Uuid == serviceId);
if (service != null)
{
Log?.Invoke("service found!");
var characteristicId = new Guid(My_Characteristic_UUID);
var characteristic = await service.GetCharacteristicsForUuidAsync(characteristicId);
if (characteristic?.Status == GattCommunicationStatus.Success)
{
var c = characteristic.Characteristics.FirstOrDefault(x => x.Uuid == characteristicId);
if (c != null)
{
Log?.Invoke("characteristic found");
var v = await c.ReadValueAsync();
if (v?.Status == GattCommunicationStatus.Success)
{
var reader = DataReader.FromBuffer(v.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
// Utilize the data as needed
string str = System.Text.Encoding.Default.GetString(input);
Log?.Invoke(str);
}
}
}
}
}
}
}
该工具对于使用BLE开发的其他人也非常有用:
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BluetoothLE
它使您可以阅读附近任何BLE设备的服务/特性。可以对测试有很大帮助。 nRF Connect 应用程序也可以很好地进行测试。