我想制作一个小型物理按钮设备来控制使用网络蓝牙 API 在我的网络应用程序上播放 3 个短音频,这意味着单击一次物理按钮,它将播放第一个音频,再次单击,它将播放第二个音频..
根据我在教程上阅读的内容,我应该使用自定义特征,这需要设备的整个 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");
}
});