An example dealing with multiple write requests would be very helpful
Hi, I am a JS noob and would really appreciate a sample demonstrating how to implement queuing or retries for writeValue requests. I get "NetworkError: GATT operation already in progress." (i.e. https://github.com/WebBluetoothCG/web-bluetooth/issues/188) when trying to write a non-trivial app that has user driven writes.
Hello @DanielO, here's below some JS snippet that might help you.
navigator.bluetooth.requestDevice({filters: [{services: ['heart_rate']}]})
.then(device => device.gatt.connect())
.then(server => server.getPrimaryService('heart_rate'))
.then(service => service.getCharacteristic('heart_rate_control_point'))
.then(characteristic => resetEnergy(characteristic, 3 /* tries */)))
.then(_ => {
console.log('Energy expended has been reset.');
})
.catch(error => {
log('Argh! ' + error);
});
function resetEnergy(characteristic, leftTries) {
// Writing 1 is the signal to reset energy expended.
let resetEnergyExpended = Uint8Array.of(1);
return characteristic.writeValue(resetEnergyExpended)
.catch(error => {
leftTries--;
if (leftTries > 0) {
return resetEnergy(characteristic, leftTries);
}
return Promise.reject(error);
});
}
Ahh, that looks good thanks!
I actually ended up creating a message queue using https://github.com/d3/d3-queue which is probably overkill..
Do you think it's worth adding to the docs? Or is it there and I missed it? (quite possible :)
This example shows how to retry one write over and over. I'm struggling to see how to queue up multiple writes. Any chance of any updated example?
@hardillb It's been a while so I've paged this out but my code is at https://bitbucket.org/DJOConnor/mooshiweb/src/default/ if you want to poke around.
I'm facing the same problem, need to do a lot write operations and getting this error
ERROR Error: Uncaught (in promise): NetworkError: GATT operation already in progress.
@DanielO The link is broken, could you share the code again ?
How about - https://hg.sr.ht/~darius/mooshiweb/browse
I manage doing it with a simple array and promises, thanks
tasks: Function[] = [];
async addTask(task) {
const previousTaskCount = this.tasks.length;
this.tasks.push(task);
if (previousTaskCount === 0) {
this.runTasks();
}
}
async runTasks() {
if (this.tasks.length <= 0) {
return true;
}
while(this.tasks.length > 0) {
const task: Function = this.tasks[0];
try {
await task.call(this);
this.tasks.shift();
} catch (error) {
console.log("Error:", error);
}
}
}