当日代码存档
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BL</title>
</head>
<body>
<button onclick="cb()">BLE检测连接</div>
</body>
<script>
async function cb() {
navigator.bluetooth
.requestDevice({
filters: [{ namePrefix: "HC" }],
optionalServices: [0xffe0],
})
.then(async (device) => {
console.log("Name: " + device.name, device);
// 连接设备
let server = await device.gatt.connect();
console.log(`server`, server);
let service = await server.getPrimaryService(0xffe0);
console.log(`service`, service);
let characteristic = await service.getCharacteristic(
0xffe1
)
.then(characteristic =>{
console.log(characteristic);
console.log('Reading value...');
return characteristic.readValue();
})
.then(value => {
console.log(value);
value =value.buffer ? value : new DataView(value);
console.log('Received messages:', value.getUint8(0));
});
})
.catch(function (error) {
// 监听错误
console.log("Something went wrong. " + error);
});
}
</script>
</html>
出错代码块
value =value.buffer ? value : new DataView(value);
console.log('Received messages:', value.getUint8(0));
报错
RangeError: Offset is outside the bounds of the DataView
可能的问题点
根据readValue的返回值DataView,发现只有
[[ArrayBufferData]]: 5
其他的都是0.
可能是因为我在32发送的是字符串类型,这里不能按参考文章里的电池那样数字读取。
下一步
学习DataView结构,找对读取格式。