Created
December 16, 2014 05:35
-
-
Save soldair/5101257d7491b6a1302d to your computer and use it in GitHub Desktop.
stand alone pinoccio server with http
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
var server = require('pinoccio-server'); | |
// you would use an array to support multiple troops | |
var troop; | |
server(function(t){ | |
troop = t; | |
troop.command(1,'led.red',function(err,data){ | |
console.log('i set the led to red',data); | |
}); | |
troop.on('end',cleanup).on('error',cleanup); | |
function cleanup(){ | |
if(t === troop) troop = false; | |
} | |
}); | |
// this is what your own custom logic might look like. | |
var http = require('http'); | |
var url = require('url'); | |
var httpServer = http.createServer(function(req,res){ | |
// simple access log | |
console.log((new Date())+'',req.method,req.url); | |
// | |
// if you send an http request with curl like | |
// | |
// curl http://localhost:8080/cmd?cmd=led.cyan&scout=2 | |
// | |
// the command will be sent the the scout and the response returned as json | |
// | |
// curl http://localhost:8080/events | |
// | |
// and any reports sent by your troop will be sent as output streaming to stdout of the curl command as fast as they hit the server! | |
// | |
if(req.url.indexOf('/cmd') === 0){ | |
var parsed = url.parse(req.url,true); | |
var query = parsed.query||{}; | |
if(!troop) return respond(res,"no troop connected."); | |
troop.command(query.scout,query.cmd,function(err,data){ | |
respond(res,err,data); | |
}); | |
} else if(req.url.indexOf('/events') === 0) { | |
if(!troop) return respond(res,"no troop connected."); | |
var t = troop; | |
t.on('end',function(){ | |
// if troop disconnects end the stream | |
res.end(); | |
}); | |
var datahandler = function(data){ | |
res.write(JSON.stringify(data)+"\n"); | |
} | |
troop.on('data',datahandler); | |
res.on('close',function(){ | |
t.removeEventListener('data',datahandler); | |
}); | |
} else { | |
res.end('nope'); | |
} | |
}).listen(8080); | |
function respond(res,err,data){ | |
res.end(JSON.stringify({error:(err?err+'':false),data:data})+"\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment