【问题标题】:Writing characteritstic value using Web bluetooth API使用 Web 蓝牙 API 写入特征值
【发布时间】:2020-09-18 14:08:06
【问题描述】:

我需要使用 Web 蓝牙 API 将加密值写入 BLE 设备的特征。我可以记录服务和特性。但我无法写入值。

我们指的是一个可以成功写入特征的python脚本。写入的数据经过加密后转换为字节数组写入特征。

我们正在尝试通过 javascript 将相同的值写入特征,但我们得到 NotSupportedError。

有人可以帮我找出解决方案吗?

代码:

     navigator.bluetooth
      .requestDevice({
        filters: [{ name: deviceName }],
        optionalServices: [GATT_SERVICE], 
      })
      .then((device) => {
        // Step 2: Connect to it
        console.log("device:", device);
        return device.gatt.connect();
      })
      .then((server) => {
        // Step 3: Get the Service
        console.log("server: ", server);
        return server.getPrimaryService(GATT_SERVICE);
      })
      .then((service) => {
        // Step 4: get the Characteristic
        console.log("service: ", service);
        
        return service.getCharacteristic(GATT_CHARACTERISTIC);
      })
      .then((characteristic) => {
       // data contains the value to be written to the BLE device
        writeBuffer(data, 0);

        function writeBuffer(data, start) {
          writeOut(data, start);
        }

        function writeOut(data, start) {
          if (start >= data.length) return;

          characteristic
            .writeValue(
              new TextEncoder().encode(data.substring(start, start + 20))
            )
            .then(() => {
              writeOut(data, start + 20);
            });
        }
     })
      .catch((error) => {
        console.log(error);
      });

由于长度超过 512 个字节,我正在取一个子字符串并尝试写入值。

【问题讨论】:

    标签: bluetooth-lowenergy web-bluetooth


    【解决方案1】:

    writeValue() 已被弃用,取而代之的是更具体的 writeValueWithResponse()writeValueWithoutResponse()。尝试使用其中任何一种,看看是否适合您。

    有关这两个 API 的更多详细信息,您可以查看有关它的 ChromeStatus 条目。

    【讨论】:

    • 您好,我尝试了您指定的两种方法,但出现以下错误:错误错误:未捕获(承诺中):NotSupportedError:GATT 操作因未知原因失败。可能是什么原因?
    • 我试图通过循环定义服务的特征来将值写入各种特征。我还在写入之间添加了 100 毫秒的延迟。然而,它正在抛出 NotSupportedError。我在 Windows 10 上使用 Chrome 浏览器。你能建议吗?
    • 在这种情况下,我不确定可能是什么错误。我在您的代码示例中看不到任何可能出现的情况。我认为您现在最好的选择是使用此代码示例在 crbug.com 提交 Chrome 的错误报告。
    • 我在尝试将数据写入设备时遇到 DOMException 错误。我正在使用 writeValueWithoutResponse 方法,它运行良好。突然它开始抛出 DomException 错误。这可能是什么原因?你能推荐一下吗?
    【解决方案2】:

    如果您在通过网页连接之前手动将您的计算机连接到蓝牙设备,它是否有效?

    如果您使用的是 Chrome(或基于 Chromium 的浏览器),那么这可能是因为 Chrome 不会在所有操作系统上自动配对。要读取/写入加密特征,蓝牙设备必须是bonded 与计算机。 macOS 和 Android 会在必要时绑定,但 Windows/Linux/ChromeOS 不会。这应该希望很快得到纠正。您可以关注https://crbug.com/960258跟踪这项工作的进展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 2012-05-08
      • 2018-05-29
      相关资源
      最近更新 更多