Skip to content

Instantly share code, notes, and snippets.

@rahedges
Forked from remydavid/gist:d3d2cec640d290e2ca44
Created August 25, 2014 11:08
Show Gist options
  • Save rahedges/2075bdf77539fc744cf2 to your computer and use it in GitHub Desktop.
Save rahedges/2075bdf77539fc744cf2 to your computer and use it in GitHub Desktop.
var bleno = require('bleno');
var noble = require('noble');
var currentPeripheral = null;
noble.on('stateChange', function(state) {
console.log("stateChange " + state);
if (state === 'poweredOn') {
console.log("start peripheral discovery");
noble.startScanning();
startIBeaconAdvertising();
} else {
noble.stopScanning();
bleno.stopAdvertising();
}
});
function startIBeaconAdvertising(){
console.log("start IBeacon advertising");
var beacon = {
uuid:'3fe1d0c5-a0b2-4458-8b0a-b4da152e9c56',
major: 0,
minor: 0,
measuredPower : -59
}
bleno.startAdvertisingIBeacon(beacon.uuid, beacon.major,beacon.minor,beacon.measuredPower, function(error){
if(error)
console.log(error);
else console.log("ibeacon advertising: success");
});
}
noble.on('discover', function(peripheral) {
console.log("peripheral discovered");
currentPeripheral = peripheral;
bleno.stopAdvertising();
// when we will disconnect, start again ibeacon advertising
peripheral.on('disconnect', function(){
console.log("disconnected");
startIBeaconAdvertising(); // NOT WORKING HERE (unless we delay the call by ~10 seconds with a setTimeout), but won't throw an error
console.log("BUT WE ARE NOT ADVERTISING ANYMORE :(");
});
});
bleno.on('advertisingStop', function(){
console.log("advertisingStop");
// once ibeacon advertising is stopped, we connect to the peripheral
currentPeripheral.connect(function(error){
if(error){
console.log(error);
}else{
console.log("connected, discover services...");
// ... do stuff with services & charateristics, then disconnect
currentPeripheral.disconnect();
}
});
});
// logs...
bleno.on('advertisingStart', function(error) {
console.log('service advertisingStart: ' + (error ? 'error ' + error : 'success'));
});
bleno.on('advertisingStartError', function(error){
console.log("advertising start error " + error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment