Skip to content

Instantly share code, notes, and snippets.

@kidapu
Last active August 29, 2015 14:20
Show Gist options
  • Save kidapu/40dcce9e18ec4e6ece1f to your computer and use it in GitHub Desktop.
Save kidapu/40dcce9e18ec4e6ece1f to your computer and use it in GitHub Desktop.
nobleでkonashi(koshian)のanalog readの値を読む
// 参考:http://konashi.ux-xu.com/documents/
var noble = require('noble');
var co = require('co');
noble.on('stateChange', function(state)
{
console.log( "state change:", state );
if (state === 'poweredOn') noble.startScanning();
else noble.stopScanning();
});
function getCharacteristics(characteristics, charaId)
{
return new Promise(function(resolve){
characteristics[ charaId ].read( function(err, data) {
if(data)
{
var accel_data = data[1] + data[0]*256;
resolve( accel_data );
}
});
});
}
noble.on('discover', function(peripheral) {
noble.stopScanning();
console.log('peripheral with UUID ' + peripheral.uuid + ' found');
var advertisement = peripheral.advertisement;
var localName = advertisement.localName;
if (localName)
{
console.log('Local Name = ' + localName);
}
peripheral.connect(function(error){
if(error) console.log('connect error: ' + error);
console.log('connected to ' + peripheral.uuid);
peripheral.discoverServices(['229BFF0003FB40DA98A7B0DEF65C2D4B'], function (error, services){ // 0xff00=KONASHI_SERVICE_UUID
//peripheral.discoverServices([ peripheral.uuid ], function (error, services){ // 0xff00=KONASHI_SERVICE_UUID
if(error) console.log('discoverServices error: ' + error);
console.log('services.length: ' + services.length);
// console.log(services);
if( services.length == 0 )
{
console.log("serviceがありません。さようなら。");
return;
}
var konashiService = services[0];
konashiService.discoverCharacteristics(['229B300803FB40DA98A7B0DEF65C2D4B','229B300903FB40DA98A7B0DEF65C2D4B','229B300A03FB40DA98A7B0DEF65C2D4B'], function(error, characteristics){
if(error) console.log('discoverCharacteristics error: ' + error);
console.log('characteristics.length: ' + characteristics.length);
setInterval(function(){
co(function *() {
var accelX = yield getCharacteristics(characteristics, 0 );
var accelY = yield getCharacteristics(characteristics, 1 );
var accelZ = yield getCharacteristics(characteristics, 2 );
console.log( accelX + "," + accelY + "," + accelZ );
});
}, 75);
});
});
});
});
//iojs+coでyeild的に非同期処理を書く時のテンプレ
var co = require('co');
function doA() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log('A done');
resolve("A");
}, 1000);
});
}
function doB() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log('B done');
resolve("B");
}, 1000);
});
}
function doC() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log('C done');
resolve("C");
}, 1000);
});
}
co(function *() {
var a = yield doA();
var b = yield doB();
var c = yield doC();
console.log(a + b + c);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment