Created
August 15, 2017 16:45
-
-
Save coderbyheart/42944dd01980826dad4974f3213e517e to your computer and use it in GitHub Desktop.
Thingy Disco
This file contains 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
const noble = require('noble') | |
const thingyServiceUUID = 'ef6801009b3549339b1052ffa9740042' | |
const UserInterfaceServiceUUID = 'ef6803009b3549339b1052ffa9740042' | |
const ButtonCharacteristicUUID = 'ef6803029b3549339b1052ffa9740042' | |
const LEDCharacteristicUUID = 'ef6803019b3549339b1052ffa9740042' | |
noble.on('stateChange', state => { | |
if (state === 'poweredOn') { | |
console.log('scanning for Thingy') | |
noble.startScanning([thingyServiceUUID], false) | |
} else { | |
noble.stopScanning() | |
} | |
}) | |
let led, button | |
noble.on('discover', peripheral => { | |
noble.stopScanning() | |
peripheral.connect(err => { | |
if (err !== null) console.error(err) | |
peripheral.discoverServices([UserInterfaceServiceUUID], (err, [service]) => { | |
service.discoverCharacteristics([ButtonCharacteristicUUID, LEDCharacteristicUUID], (err, characteristics) => { | |
characteristics.forEach(characteristic => { | |
switch(characteristic.uuid) { | |
case LEDCharacteristicUUID: | |
led = characteristic | |
break | |
case ButtonCharacteristicUUID: | |
button = characteristic | |
break | |
} | |
if (led && button) run(); | |
}) | |
}) | |
}) | |
}) | |
}) | |
const run = () => { | |
button.discoverDescriptors((err, [descriptor]) => { | |
const b = new Buffer(2) | |
b.writeUInt8(1, 0) | |
descriptor.writeValue(b, err => { | |
if (err !== null) { | |
console.error(`Failed to enable notifiy: ${err}`) | |
} else { | |
console.log('Listening for button press ...') | |
} | |
}) | |
}) | |
button.on('data', (data, isNotification) => { | |
if (!isNotification) return | |
if (data.toString('hex') !== '01') return | |
const b = new Buffer(4) | |
b.writeUInt8(1, 0) | |
b.writeUInt8(Math.round(Math.random() * 255), 1) | |
b.writeUInt8(Math.round(Math.random() * 255), 2) | |
b.writeUInt8(Math.round(Math.random() * 255), 3) | |
led.write(b, false, err => { | |
if (err !== null) console.error(err) | |
console.log(`Color set to: #${b.toString('hex').substr(2)}`) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment