2022.12.16 Web Bluetooth API 问题记录——RangeError: Offset is outside the bounds of the DataView

当日代码存档

<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结构,找对读取格式。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值