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

The function writeValueWithoutResponse to write data to a BLE pheripheral doesn't exist

我正在尝试通过 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,r, g,b ]);

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

script.js:29 未捕获(承诺)TypeError: characteristic.writeValueWithoutResponse 不是 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, 0x00]));
}```

作为service.getCharacteristic() returns一个承诺,你必须在那里使用await。请注意 writeValueWithoutResponse 也是 returns 一个承诺。

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

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

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

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

找到更多文档