I am looking to create a compact physical button device that can be used to control the playback of 3 short audio clips on my web app through the web Bluetooth API. Essentially, with each click of the physical button, the next audio clip will play.
According to the information I found in this tutorial, it is recommended to utilize a custom characteristic by providing the complete UUID of the device. However, when trying to set up an event listener to trigger the audio playback function, I encountered an error message saying
Cannot read property 'addEventListener' of undefined
. I'm not sure what's causing this issue.
Could there be something crucial that I have overlooked or misunderstood? Please keep in mind that I have yet to acquire the physical button, so for now, I am testing the Bluetooth connection using my iPhone, hence the test function is only intended to check for any output.
Below is the code snippet:
$("#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");
}
});