【问题标题】:How to add eventListener to web-bluetooth API in JavaScript?如何在 JavaScript 中将 eventListener 添加到 web-bluetooth API?
【发布时间】:2018-04-04 15:28:06
【问题描述】:

我想制作一个小型物理按钮设备来使用网络蓝牙 API 在我的网络应用程序上控制播放 3 个短音频,这意味着单击一次物理按钮,它将播放第一个音频,再次单击,它将播放第二个音频音频..

根据我在tutorial 上阅读的内容,我应该使用自定义特性,这需要设备的整个 UUID。之后,我放了一个事件监听器来调用一个函数来播放音频。但我收到错误消息Cannot read property 'addEventListener' of undefined。我不知道为什么会这样。

我错过了什么吗?还是我的逻辑错了? 请注意,我还没有物理按钮,所以我现在用我的 iPhone 测试蓝牙连接,所以功能测试只是看任何输出。

以下是我所拥有的:

$("#bluetooth").on("click", function(){
        const controlServiceUUID = '00001805-0000-1000-8000-00805f9b34fb'; // Full UUID
        const commandCharacteristicUUID = '00002a0f-0000-1000-8000-00805f9b34fb'; // [READ]
        const commandCharacteristicUUID2 = '00002a0f-0000-1000-8000-00805f9b34fb'; // [READ, NOTIFY]

        console.log('Searching Bluetooth Device...');

        navigator.bluetooth.requestDevice({
            acceptAllDevices: true,
            optionalServices: [controlServiceUUID]
        })

        .then(device => {
            console.log("Got device name: ", device.name);
            console.log("id: ", device.id);
            return device.gatt.connect();
        })

        .then(server => {
            // Step 3: Get the Service
            serverInstance = server;
            return server.getPrimaryService(controlServiceUUID);
            console.log("Getting PrimaryService");
        })

        .then(service => {
            service.getCharacteristic(commandCharacteristicUUID);
            console.log("Getting Characteristic");
        })

        .then(characteristic => {
            // 0x01,3,0x02,0x03,0x01

            characteristic.addEventListener('characteristicvaluechanged', test);             
        })

        .catch(function(error) {
            console.log("Something went wrong. " + error);
        });

       function test(event) {
           let commandValue = event.target.value.getUint8(0);
           console.log("Hello");
       }
   });

【问题讨论】:

    标签: javascript android web-bluetooth


    【解决方案1】:

    您需要返回 Promise 才能使用该特性。见下文。

    .then(service => { console.log("Getting Characteristic"); return service.getCharacteristic(commandCharacteristicUUID); })

    【讨论】:

    • 感谢您的回复。今晚晚些时候我会测试它。我的另一个问题是,我所看到的有关网络蓝牙 API 的示例,大多数人都使用智能手机来控制灯光等硬件。我想反转它,用硬件按钮控制智能手机播放音频。可以吗?顺便说一句,我能认出你:)
    • 您必须将您的硬件按钮与您的网络应用程序与网络蓝牙配对,并简单地“通知”一个 BLE 特性。然后,您的网络应用程序可以简单地侦听此特征通知更改并播放音频文件,例如:googlechrome.github.io/samples/web-bluetooth/notifications.html 请注意,这需要启动您的网络应用程序。
    • 感谢您的回复。我很想尝试一下。我正在尝试配对 RN-42,但它显示 NetworkError: Unsupported device. 不知道会发生什么。是不是因为RN-42不是BLE设备?
    • 我只是查找了更多具有蓝牙低功耗的物理按钮,似乎 FLIC 可以完成这项工作!你怎么看?
    • RN-42 似乎只是蓝牙经典(不是 BLE)。
    猜你喜欢
    • 2014-10-05
    • 1970-01-01
    • 2020-11-22
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2021-10-09
    • 2011-04-23
    相关资源
    最近更新 更多