C#-Windows BluetoothLeAdvertisement不包含Android设备广播的服务uuid

我试图从Windows 10读取Android外围设备广播的ServiceUuid,如下所示:

private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs advertisementArg)
{
    Debug.WriteLine(" serviceUuids for advertisement " + advertisementArg.Advertisement.ServiceUuids.Count);
    foreach(Guid guid in advertisementArg.Advertisement.ServiceUuids)
    {
        Debug.WriteLine("uuid is " + guid.ToString() + " address is " +advertisementArg.BluetoothAddress+ " name is "+ advertisementArg.Advertisement.LocalName);
    }
}

但是,当收到来自Android外围设备的广告时,ServiceUuids列表的大小始终为0.

这很奇怪,因为服务数据已正确放置在广告的BluetoothLeAdvertisementDataSection中:

IList<BluetoothLEAdvertisementDataSection> dataSection = advertisementArg.Advertisement.DataSections;

foreach (BluetoothLEAdvertisementDataSection ad in dataSection)
{
    if (ad.Data.Length > 0)
    {
        DataReader dataReader = DataReader.FromBuffer(ad.Data);
        byte[] bytes = new byte[ad.Data.Length];

        dataReader.ReadBytes(bytes);

        if (bytes.Length > 0)
        {
            string data = System.Text.Encoding.UTF8.GetString(crcBytes, 0, crcBytes.Length);
            Debug.WriteLine("ANDROID DEVICE FOUND " + data);
        }         
    }
}

因此,只是缺少了ServiceUuid.

服务数据像这样在Android外设中添加:

AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
dataBuilder.addServiceData(new ParcelUuid(bluetoothUuid), advertiseData.getBytes());

解决方法:

Android数据是“服务数据”部分类型,而不是“服务UUID列表”部分类型.服务UUIDs属性仅适用于服务UUID列表,不适用于服务数据.

对于蓝牙广告(Beacons)可用于发送包含通用唯一标识符(UUID)的信息包,该包的数据部分可由应用程序开发人员定制.

我们应该能够解析BluetoothLEManufacturerData中的数据以获得UUID.

例如:

private  void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
    var manufacturerSections = eventArgs.Advertisement.ManufacturerData;
    if (manufacturerSections.Count > 0)
    {
        var manufacturerData = manufacturerSections[0];
        var data = new byte[manufacturerData.Data.Length];
        using (var reader = DataReader.FromBuffer(manufacturerData.Data))
        {
            reader.ReadBytes(data);
        }
    }
}

有一个大约BluetoothAdvertisement的官方样本,它显示了如何使用Bluetooth Advertisement API发送和接收Bluetooth Low Energy广告.

上一篇:正确的方法来获取图像的uri作为UWP类库中的资源嵌入


下一篇:c#-根据绑定值更改元素属性