Web Bluetooth / Automatic Reconnect Sample
Available in Chrome 52+ |
View on GitHub |
Browse Samples
The Web Bluetooth
API lets websites discover and communicate with devices over the
Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT). It is
currently partially implemented in Android M, Chrome OS, Mac, and Windows 10.
This sample illustrates the use of the Web Bluetooth API to reconnect to a
disconnected Bluetooth device using a simple exponential backoff
algorithm . You may want to check out the Automatic Reconnect (Async Await) sample.
Live Output
JavaScript Snippet
var bluetoothDevice ;
function onButtonClick () {
bluetoothDevice = null ;
log ( ' Requesting any Bluetooth Device... ' );
navigator . bluetooth . requestDevice ({
// filters: [...] <- Prefer filters to save energy & show relevant devices.
acceptAllDevices : true })
. then ( device => {
bluetoothDevice = device ;
bluetoothDevice . addEventListener ( ' gattserverdisconnected ' , onDisconnected );
connect ();
})
. catch ( error => {
log ( ' Argh! ' + error );
});
}
function connect () {
exponentialBackoff ( 3 /* max retries */ , 2 /* seconds delay */ ,
function toTry () {
time ( ' Connecting to Bluetooth Device... ' );
return bluetoothDevice . gatt . connect ();
},
function success () {
log ( ' > Bluetooth Device connected. Try disconnect it now. ' );
},
function fail () {
time ( ' Failed to reconnect. ' );
});
}
function onDisconnected () {
log ( ' > Bluetooth Device disconnected ' );
connect ();
}
/* Utils */
// This function keeps calling "toTry" until promise resolves or has
// retried "max" number of times. First retry has a delay of "delay" seconds.
// "success" is called upon success.
function exponentialBackoff ( max , delay , toTry , success , fail ) {
toTry (). then ( result => success ( result ))
. catch ( _ => {
if ( max === 0 ) {
return fail ();
}
time ( ' Retrying in ' + delay + ' s... ( ' + max + ' tries left) ' );
setTimeout ( function () {
exponentialBackoff ( -- max , delay * 2 , toTry , success , fail );
}, delay * 1000 );
});
}
function time ( text ) {
log ( ' [ ' + new Date (). toJSON (). substr ( 11 , 8 ) + ' ] ' + text );
}