diff --git a/README.md b/README.md index b2496d69..a82adebd 100644 --- a/README.md +++ b/README.md @@ -838,9 +838,14 @@ Function `stopNotification` stops a previously registered notification callback. Reports the connection status. ```javascript +// Callbacks ble.isConnected(device_id, success, failure); -// Or using await with promises -await ble.withPromises.isConnected(device_id); + +// Promises with boolean return +const isConnected = await ble.withPromises.isConnected(device_id, false); + +// Promises with rejection +await ble.withPromises.isConnected(device_id); // throws if not connected ``` ### Description @@ -858,6 +863,7 @@ NOTE that for many apps isConnected is unncessary. The app can track the connect ### Quick Example ```javascript +// Callbacks ble.isConnected( 'FFCA0B09-CB1D-4DC0-A1EF-31AFD3EDFB53', function () { @@ -867,6 +873,22 @@ ble.isConnected( console.log('Peripheral is *not* connected'); } ); + +// Promises with boolean return +const isConnected = await ble.withPromises.isConnected(device_id, false); +if (isConnected) { + console.log('Peripheral is connected'); +} else { + console.log('Peripheral is *not* connected'); +} + +// Promises with rejection +try { + await ble.withPromises.isConnected(device_id); + console.log('Peripheral is connected'); +} catch (e) { + console.log('Peripheral is *not* connected'); +} ``` ## isEnabled diff --git a/types.d.ts b/types.d.ts index 53d12235..78d31a68 100644 --- a/types.d.ts +++ b/types.d.ts @@ -160,9 +160,14 @@ declare namespace BLECentralPlugin { ): Promise; stopNotification(device_id: string, service_uuid: string, characteristic_uuid: string): Promise; - /* Returns a rejected promise if the device is not connected */ + /* Returns a resolved promise if the device is connected, + otherwise returns rejected promise if the device is not connected */ isConnected(device_id: string): Promise; + /* Returns a promise that resolves to true if the device is connected, + otherwise resolves to false if the device is not connected or an error occurs */ + isConnected(device_id: string, rejectWhenDisconnected: false): Promise; + /* Returns a rejected promise if bluetooth is not connected */ isEnabled(): Promise; diff --git a/www/ble.js b/www/ble.js index 0ea06ed0..066731eb 100644 --- a/www/ble.js +++ b/www/ble.js @@ -362,9 +362,17 @@ module.exports.withPromises = { }); }, - isConnected: function (device_id) { + isConnected: function (device_id, rejectWhenDisconnected) { return new Promise(function (resolve, reject) { - module.exports.isConnected(device_id, resolve, reject); + if (rejectWhenDisconnected === false) { + module.exports.isConnected( + device_id, + () => resolve(true), + () => resolve(false) + ); + } else { + module.exports.isConnected(device_id, resolve, reject); + } }); },