找不到GATT服务

时间:2019-04-08 21:10:41

标签: uwp bluetooth-lowenergy

在我的UWP应用中,我想读取其他BLE设备的设备名称。因此,我正在尝试从设备中读取this特征。我可以找到设备的广告UUID和蓝牙地址,但是无法从中找到默认的GATT服务。这是我获得服务的代码:

if (ulong.TryParse(deviceAddress, out ulong address))
{
    BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(address);

    var genericAccessId = ConvertFromInteger(0x1800);

    GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesForUuidAsync(genericAccessId);

    if (result?.Status == GattCommunicationStatus.Success)
    {
        var genericAccess = result.Services.FirstOrDefault(s => s.Uuid == genericAccessId);

        // genericAccess is always null
        if (genericAccess != null)
        {
            var deviceNameId = ConvertFromInteger(0x2A00);
            var deviceName = await genericAccess.GetCharacteristicsForUuidAsync(deviceNameId);

            if (deviceName?.Status == GattCommunicationStatus.Success)
            {
                var c = deviceName.Characteristics.FirstOrDefault(x => x.Uuid == deviceNameId);

                if (c != null)
                {
                    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);
                    }
                }
            }
        }
    }
}

public static Guid ConvertFromInteger(int i)
{
    byte[] bytes = new byte[16];
    BitConverter.GetBytes(i).CopyTo(bytes, 0);
    return new Guid(bytes);
}

Any idea where the problem is?

1 个答案:

答案 0 :(得分:1)

BLE设备,服务和特性具有用于识别的128位UUID。对于标准化服务和特性,还有一个16位的简短版本,例如Generic Access为0x1800。

为了将16位转换为128位UUID,必须将16位值填充到字节2和3中的以下UUID中(按小端顺序:

0000xxxx-0000-1000-8000-00805F9B34FB

因此0x1800转换为:

00000018-0000-1000-8000-00805F9B34FB

Windows具有为您执行此操作的功能:BluetoothUuidHelper.FromShortId

var uuid = BluetoothUuidHelper.FromShortId(0x1800);

在以前的Windows版本中,您将改为使用GattDeviceService.ConvertShortIdToUuid

因此,将函数ConvertFromInteger替换为上面的函数。您的函数将填充所有0而不是上面的UUID值。