Created
April 24, 2017 11:01
-
-
Save urish/b2a1033441e9e89bca28ef7e5a9c49cc to your computer and use it in GitHub Desktop.
NG Beacon controlling a Magic Blue bulb based on distance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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