首页 > 解决方案 > 无法使用 UWP API 将大字节数组写入 BLE 设备 - 例如将值写入异步

问题描述

我正在使用 Windows 10 内部版本 14393.2156。蓝牙适配器 LMP 版本为 6.X(蓝牙版本 4.0)。我无法写入长度为 350 的字节数组数据。但是,我可以写入长度为 60 左右的字节数组数据并从 BLE 设备获取预期数据。当我写入大长度的字节数组时,例如 350,我得到 windows 异常:“异常:指定的服务器无法执行请求的操作。(来自 HRESULT 的异常:0x8007003A)”。以下是代码:

private async Task CoreWrite(byte[] data)
    {
        var writeBuffer = CryptographicBuffer.CreateFromByteArray(data);
        var result = await _txCharacteristic.WriteValueAsync(writeBuffer);
        if (result != GattCommunicationStatus.Success)
        {
            throw new IOException($"Failed to write to bluetooth device. Status: {nameof(result)}");
        }
    }

请注意,设备已经配对。是否有任何有效负载限制可能会影响蓝牙 4.0 与 4.2 规范中有效负载长度的限制。或者您建议使用更新的蓝牙 LMP 8.X 构建更高版本的 Windows 10 应该有助于解决该问题。感谢任何建议或帮助。

非常感谢。

标签: c#arraysuwpbluetooth-lowenergy

解决方案


令人惊讶的是,我们发现特征的属性数据长度被限制在 244 字节。因此,我无法写入任何超过 244 字节的数据。但是,一次执行 244 字节的多次写入确实可以解决此问题。我可以看到 BLE 设备的预期响应。

例子:

int offset = 0;
int AttributeDataLen = 244;
while (offset < data.Length)
{
   int length = data.Length - offset;
   if (length > AttributeDataLen)
   {
      length = AttributeDataLen;
   }

   byte[] subset = new byte[length];

   Array.Copy(data, offset, subset, 0, length);
   offset += length;

   var writeBuffer = CryptographicBuffer.CreateFromByteArray(subset);
   var result = await _txCharacteristic.WriteValueAsync(writeBuffer);
   if (result != GattCommunicationStatus.Success)
   {
      throw new IOException(
        $"Failed to write to bluetooth device. Status: {nameof(result)}");
   }
}

推荐阅读