fibaro-beacon-scanner
Version:
Node.js beacon scanner based on noble that speaks to Fibaro
76 lines (63 loc) • 2.71 kB
JavaScript
/*
Continously scans for peripherals and prints out message when they enter/exit
In range criteria: RSSI < threshold
Out of range criteria: lastSeen > grace period
based on code provided by: Mattias Ask (http://www.dittlof.com)
*/
var noble = require('noble');
var Fibaro = require('fibaro-api');
var fibaro = new Fibaro('10.0.1.5', 'jacgalka@icloud.com', 'J3bimnuC12a');
var RSSI_THRESHOLD = -100000;
var EXIT_GRACE_PERIOD = 15000; // milliseconds
var inRange = [];
noble.on('discover', function(peripheral) {
if (peripheral.rssi < RSSI_THRESHOLD) {
// ignore
return;
}
var id = peripheral.id;
var entered = !inRange[id];
if (entered) {
inRange[id] = {
peripheral: peripheral
};
if (peripheral.id == "e690ac024a80") {
peripheral.advertisement.localName = "Black";
console.log('"' + peripheral.advertisement.localName + ' with address ' + peripheral.address + '" entered (RSSI ' + peripheral.rssi + ') ' + new Date());
}else if (peripheral.id == "d6feeec61549") {
peripheral.advertisement.localName = "Green";
console.log('"' + peripheral.advertisement.localName + ' with address ' + peripheral.address + '" entered (RSSI ' + peripheral.rssi + ') ' + new Date());
fibaro.api.devices.turnOn(31, function(err, newVal) {
console.log(err);
console.log(newVal);
});
}
}
inRange[id].lastSeen = Date.now();
});
setInterval(function() {
for (var id in inRange) {
if (inRange[id].lastSeen < (Date.now() - EXIT_GRACE_PERIOD)) {
var peripheral = inRange[id].peripheral;
if (peripheral.id == "e690ac024a80") {
peripheral.advertisement.localName = "Black";
console.log('"' + peripheral.advertisement.localName + ' with address ' + peripheral.address + '" exited (RSSI ' + peripheral.rssi + ') ' + new Date());
} else if (peripheral.id == "d6feeec61549") {
peripheral.advertisement.localName = "Green";
console.log('"' + peripheral.advertisement.localName + ' with address ' + peripheral.address + '" exited (RSSI ' + peripheral.rssi + ') ' + new Date());
fibaro.api.devices.turnOff(31, function(err, newVal) {
console.log(err);
console.log(newVal);
});
}
delete inRange[id];
}
}
}, EXIT_GRACE_PERIOD / 2);
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
noble.startScanning([], true);
} else {
noble.stopScanning();
}
});