Created
August 25, 2016 07:44
-
-
Save tnoborio/02dcc5229f23bfac4e45afa70b39e285 to your computer and use it in GitHub Desktop.
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 noble = require('noble') | |
var player = require('play-sound')(opts = {}) | |
var serviceUuid = '713d0000503e4c75ba943148f18d941e'; | |
var characteristicUuid = '713d0002503e4c75ba943148f18d941e'; | |
var service = null; | |
var rxCharacteristic = null; | |
var lastSoundAt = null; | |
noble.on('stateChange', function(state) { | |
if (state === 'poweredOn') { | |
console.log('scanning...'); | |
noble.startScanning([serviceUuid], false); | |
} | |
else { | |
noble.stopScanning(); | |
} | |
}) | |
function play() { | |
if (!lastSoundAt || (new Date() - lastSoundAt) > 5000) { | |
lastSoundAt = new Date(); | |
player.play('urameshi.m4a', function(err){}) | |
} | |
} | |
noble.on('discover', function(peripheral) { | |
noble.stopScanning(); | |
console.log('found peripheral:', peripheral.advertisement); | |
peripheral.connect(function(err) { | |
peripheral.discoverServices([serviceUuid], function(err, services) { | |
services.forEach(function(service) { | |
console.log('found service:', service.uuid); | |
service.discoverCharacteristics([], function(err, characteristics) { | |
characteristics.forEach(function(characteristic) { | |
console.log('found characteristic:', characteristic.uuid); | |
if (characteristicUuid == characteristic.uuid) { | |
rxCharacteristic = characteristic; | |
} | |
}) | |
if (rxCharacteristic) { | |
console.log("set read"); | |
rxCharacteristic.on("read", function(data, isNotify) { | |
var result = data.readUInt8(1); | |
if (result > 0) { | |
console.log("on"); | |
play() | |
} | |
}); | |
rxCharacteristic.subscribe(function(err) { | |
console.log("subs: " + err); | |
}); | |
} | |
else { | |
console.log('missing characteristics'); | |
} | |
}) | |
}) | |
}) | |
}) | |
}) | |
function sendMessage() { | |
var data = new Buffer(2); | |
data.writeUInt8(0x2, 0); | |
data.writeUInt8(Math.ceil((new Date().getSeconds() % 2) * 255), 1); | |
txCharacteristic.write(data, true, function(err) { | |
console.log("err: " + err); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment