Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NG Beacon controlling a Magic Blue bulb based on distance
var bulbDevice = null;
var bulbChar = null;
function setColor(r, g, b) {
try {
bulbChar.writeValue(new Uint8Array([0x56, r, g, b, 0, 0xf0, 0xaa]));
} catch (e) {
}
}
function startLoop(char) {
console.log('Connected !');
var samples = [];
bulbDevice.gatt.setRSSIHandler(rssi => {
samples.unshift(rssi);
if (samples.length > 10) {
samples.pop();
}
var avg = -1 * samples.reduce((x,y)=>x+y) / samples.length;
var threshold = 60;
if (avg <= threshold)
setColor(Math.round(threshold - avg) * 4, 0, 0);
else
setColor(0, 0, 0);
});
bulbChar = char;
}
(NRF.requestDevice({ filters: [{ services: ['ffe5'] }] })
.then(device => {
bulbDevice = device;
return device.gatt.connect();
})
.then(gatt => gatt.getPrimaryService('ffe5'))
.then(service => service.getCharacteristic('ffe9'))
.then(startLoop));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment