首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在JavaScript的web-bluetooth API中添加eventListener?

如何在JavaScript的web-bluetooth API中添加eventListener?
EN

Stack Overflow用户
提问于 2018-04-04 01:57:06
回答 1查看 1.1K关注 0票数 0

我想做一个小的物理按钮设备来控制播放3个简短的音频在我的web应用程序使用web蓝牙API,这意味着点击一次物理按钮,它将播放第一个音频,并再次点击,它将播放第二个音频。

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

我是不是遗漏了什么?或者我的逻辑是错的?请注意,我还没有物理按键,所以我现在用我的iPhone测试蓝牙连接,所以功能测试只是为了查看任何输出。

下面是我所拥有的:

代码语言:javascript
复制
$("#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");
       }
   });
EN

回答 1

Stack Overflow用户

发布于 2018-04-04 15:28:07

您需要返回使用该特征的承诺。见下文。

代码语言:javascript
复制
     `.then(service => {             console.log("Getting Characteristic");             return service.getCharacteristic(commandCharacteristicUUID);         })`
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49636402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档