0

[解释 IRC 对话]

试图用ardunio和一个DHT11传感器和一个HM10蓝牙传感器构建一个温度传感器。使用网络蓝牙获取温度值但似乎没有触发characteristicvaluechanged事件。它只给出初始值。

document.querySelector('button')
    .addEventListener('click', connectBluetooth)


function connectBluetooth() {
    navigator.bluetooth
        .requestDevice({
            optionalServices: [ 0xffe0 ],
            acceptAllDevices: true
        })
        .then(device => device.gatt.connect())
        .then(server => server.getPrimaryService(0xffe0))
        .then(service => service.getCharacteristic(0xffe1))
        .then(characteristic => {
            characteristic.addEventListener('characteristicvaluechanged',
                                            handleValueChanged)

            return characteristic.readValue()
        })
        .catch(err => console.error(err))
}

function handleValueChanged(event) {
    console.log('Handling...')
    let value = event.target.value.getUint8(0)

    console.log(`The value is: ${value}`)
}
4

1 回答 1

0

您从未订阅过通知。有关示例,请参见https://googlechrome.github.io/samples/web-bluetooth/notifications.html 。注册事件监听器是不够的,还必须调用characteristic.startNotifications(). 正在返回一个结果,因此只需将其readValue替换为startNotifications.

于 2017-07-21T21:25:23.467 回答