将数据写入 BLE 外设的函数 writeValueWithoutResponse 不存在

问题描述

我正在尝试通过 chrome 与 BLE 设备进行通信,我正在关注此视频:

https://youtu.be/XDc5HUVMI5U?t=1023

一切正常,直到他说使用该方法

characteristic.writeValue(new Uint8Array[ 0x00,r,g,b ]);

我查了一下,它已被弃用:https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTCharacteristic/writeValue

相反,您应该使用:

characteristic.writeValueWithoutResponse(new Uint8Array[ 0x00,b ]);

问题是这也不起作用。它说:

script.js:29 Uncaught (in promise) TypeError:characteristic.writeValueWithoutResponse is not a function at HTMLButtonElement.setupBLE (script.js:29)

有谁知道我可能做错了什么?到目前为止,这是我的所有代码

button.onclick = setupBLE;
let options = {
filters: [
{ services: ['19b10000-e8f2-537e-4f6c-d104768a1214'] },{ name: 'Stepper motor control' }
]
};
async function setupBLE() {
console.log("test");
let device = await navigator.bluetooth.requestDevice(options);
let server = await device.gatt.connect();
let service = await server.getPrimaryService("19b10000-e8f2-537e-4f6c-d104768a1214");

//Same name but with 19b10001 instead of 19b10000
let characteristic = service.getCharacteristic("19b10001-e8f2-537e-4f6c-d104768a1214");
console.log(characteristic);
characteristic.writeValueWithoutResponse(new Uint8Array([0x00,0x00,0x00]));
}```

解决方法

service.getCharacteristic() 返回一个 promise,你必须在那里使用 await。请注意,writeValueWithoutResponse 也会返回一个承诺。

const characteristicUuid = "19b10001-e8f2-537e-4f6c-d104768a1214";
const characteristic = await service.getCharacteristic(characteristicUuid);

const value = new Uint8Array([0x00,0x00,0x00]);
await characteristic.writeValueWithoutResponse(value);

console.log("wrote value to characteristic");

您可以在 https://web.dev/bluetooth/#write

找到更多文档