2

I'm new to javascript so i might have some unconventional way of programming. That said, I'm working on a project where I need to read and write data to a custom BLE device. I'm using the gatt server protocol for the connection. I'm able to make a connection with the device but now i'm trying to read data from the registers.

I looked trough the web samples from google as well as the web bluetooth github but I cant make any sense of it. The code below is my current attempt to break this. earlier tries had me get stuck on the fact that the value that I got was an object or a promise object.

function readFromPcb() {
    let p2 = new Promise((resolve, reject) => {
        if (device.connected === false) {
            reject('network Error');
        }
    })
        .then(characteristic => {
            readValue = characteristic.readValue();
            console.log('data is: ' + readValue);
        })
        .catch(error => {
            console.log('error: ' + error + DOMException.name);
        });
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • This question looks very similar to the one you posted earlier: https://stackoverflow.com/questions/57968195/web-bluetooth-with-promises Are you sure that these are 2 different questions? – Dharman Sep 17 '19 at 22:51

2 Answers2

0

I don't know much about Web Bluetooth, but I notice your top promise never resolves. It either rejects if the device is not connected, or else... does nothing. If you want the then callbacks to run, you need to call resolve() at some point in your main promise. That said, since you explicitly constructed this promise, the value it resolves with will just be whatever argument you pass into resolve() yourself; that doesn't sound like what you want. What function is supposed to give you the "characteristic"? That's the one that probably returns a promise and you don't need to construct one yourself, you can just chain the other then callbacks onto the promise it returns for you.

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26
  • I get my "characteristic" from my connect function, the one that makes the initial connection. Could you maybe explain how i can use that promise as a call back for this function? I don't have a full understanding of promises so I try my best. –  Sep 17 '19 at 14:23
  • A quick skim of the MDN docs says that a GATT server's `connect` function returns a promise. So you should just be chaining your `.then` callbacks onto the end of the connect function, not making your own Promise. – IceMetalPunk Sep 17 '19 at 14:25
0

I made it work! I needed to access web bluetooth's characteristic level. After that I could use the promise of my connect function to chain the .then to my read function.

thanks for the help.

function readFromPcb() {
    prom.then(_ => {
        console.log('getting data...');
        gattChar.readValue();
    })
        .catch(error => {
            console.log('error: ' + error + ' ' + DOMException.name);
        });
}