Skip to content

Detecting bluetooth device disconnects/crashes #57

@chipimix

Description

@chipimix

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions