Skip to content

Instantly share code, notes, and snippets.

@don
Last active June 9, 2018 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save don/e423ed19f16e1367b96d04ecf51533cc to your computer and use it in GitHub Desktop.
Save don/e423ed19f16e1367b96d04ecf51533cc to your computer and use it in GitHub Desktop.
Cordova - automatically connect to a Bluetooth device by name
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
// Auto connect whenever the device is in range
const MAC_ADDRESS = 'E4:86:1E:4E:5A:FB';
ble.autoConnect(MAC_ADDRESS, app.onConnected, app.onDisconnected);
},
onConnected: function(peripheral) {
console.log(`Connected to peripheral ${peripheral.name} ${peripheral.id}`);
// additional logic here
},
onDisconnected: function(peripheral) {
if (peripheral.name) {
console.log(`Peripheral ${peripheral.name} disconnected`);
} else { // sometimes it's just an error message
console.log(peripheral);
}
}
};
app.initialize();
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
// connect by MAC address on startup
const MAC_ADDRESS = 'E4:86:1E:4E:5A:FB';
ble.connect(MAC_ADDRESS, app.onConnected, app.onDisconnected);
},
onConnected: function(peripheral) {
console.log(`Connected to peripheral ${peripheral.name} ${peripheral.id}`);
// additional logic here
},
onDisconnected: function(peripheral) {
if (peripheral.name) {
console.log(`Peripheral ${peripheral.name} disconnected`);
} else { // sometimes it's just an error message
console.log(peripheral);
}
}
};
app.initialize();
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
this.connectByName('microbit');
},
connectByName: function(name) {
let scanning = true;
ble.startScan([], device => {
if (device.name === name) {
ble.stopScan();
scanning = false;
ble.connect(device.id, app.onConnected, app.onDisconnected);
} else {
console.log(`Skipping ${device.name} ${device.id}`);
}
});
// set timer to stop the scan after a while
setTimeout(() => {
if (scanning) {
ble.stopScan();
console.log(`Couldn't find device ${name}`);
}
}, 5000);
},
onConnected: function(peripheral) {
console.log(`Connected to peripheral ${peripheral.name} ${peripheral.id}`);
// additional logic here
},
onDisconnected: function(peripheral) {
if (peripheral.name) {
console.log(`Peripheral ${peripheral.name} disconnected`);
} else { // sometimes it's just an error message
console.log(peripheral);
}
}
};
app.initialize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment