lsongdev / node-bluetooth

:large_blue_diamond:😬Bluetooth serial port communication for Node.js
https://npmjs.org/node-bluetooth
Other
197 stars 56 forks source link

How can I know if the connection is always open ? #30

Open cyberal82 opened 5 years ago

cyberal82 commented 5 years ago

Hi,

For beginning thank you for this node module :).

I have an electron program that open a bluetooth connection and listening the event "data".

How can I know if the connection is always open ?

Before write data I check if the connection is open with connection.isOpen() but this method return true if the connection has been open and lost.

I have try to listen the events "closed", "close", "failure" without any success.

If the connection has been open and lost, when I write data I have an uncatched exception: Error : Error reading from connection.

The calls to the write method is in try/catch block

Node version : v8.12.0 node-bluetooth: v1.2.5

Thank you for your help.

ThomasLaforge commented 4 years ago

@cyberal82 Have you any news on it ?

nipoonp commented 4 years ago

This seemed to work for me:

let bluetoothPrinter;

connection.on("error", (err: any) => {
  console.log("Error: " + err);

  connection.close(() => {
    console.log("Connection closed manually");
  });

  bluetoothPrinter = null;
});

I listen to the connection.on "error" and if that is triggered I manually close the connection and set me global variable for bluetoothPrinter to null.