Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detecting bluetooth device disconnects/crashes #57

Open
chipimix opened this issue Oct 22, 2021 · 1 comment
Open

Detecting bluetooth device disconnects/crashes #57

chipimix opened this issue Oct 22, 2021 · 1 comment

Comments

@chipimix
Copy link

Hi!
I couldn't find a way to detect if a connection has crashed or disconnected so I tried to implement my own.
In lib/connection.js, I noticed that - if I printed the chunks of the read method - they stop printing as soon as I turn off my bluetooth device; after ~20seconds of apparent frozen behavior, this method continued working, printing chunks of zero length buffers.
Thus, I added the following line
if(chunk.length == 0){ self.emit('error')}
in

(function read(){
      self.isOpen() && self.port.read((err, chunk) => {
        process.nextTick(read);
        if(err) return self.emit('error', err);
        self.emit('data', chunk);
        if(chunk.length == 0){ self.emit('error')}
      });
    })();

This allows me to fetch error events like so:

    connect(address, 1, (err, linkage) => {
      if (err) {
        console.log('connection attempt error');
      } else {
        linkage.on('error', (err) => {
          console.log('disconnected!);
        });
      }
    )}

However my approach assumes I won't be receiving zero length buffers when connected which I realize that might not always be true (or not for all devices);
Also, any thoughts on how to detect the disconnect before the ~20seconds pass?
Thanks!

@Taureon
Copy link

Taureon commented Jun 3, 2022

Wouldn't this work?

connect(address, 1, (err, linkage){
    linkage.on('end', () => {
        doStuffWhenConnectionEnds();
    });
});

(I never used node-bluetooth, this is an educational guess I made seen from similar projects)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants