【问题标题】:Can't find GATT service找不到 GATT 服务
【发布时间】:2019-04-08 21:10:41
【问题描述】:

在我的 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?

【问题讨论】:

  • 我找不到是什么意思?是否发生错误?或者执行在哪里跳过其余代码?
  • 方法ConvertFromInteger 很可能不正确。请改用GattDeviceService.ConvertShortIdToUuid,例如GattDeviceService.ConvertShortIdToUuid(0x1800).
  • 就是这样。尽管有人建议我改用BluetoothUuidHelper.FromShortId,因为GattDeviceService.ConvertShortIdToUuid 已过时。如果您将其发布为答案,我会接受。

标签: uwp bluetooth-lowenergy


【解决方案1】:

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

为了将 16 位转换为 128 位 UUID,必须在字节 2 和 3 处将 16 位值填充到以下 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 值。

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 2015-02-17
    • 2020-05-19
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    相关资源
    最近更新 更多