aboutsummaryrefslogtreecommitdiff
path: root/humanbot_server.js
diff options
context:
space:
mode:
Diffstat (limited to 'humanbot_server.js')
-rwxr-xr-xhumanbot_server.js74
1 files changed, 74 insertions, 0 deletions
diff --git a/humanbot_server.js b/humanbot_server.js
new file mode 100755
index 0000000..3f38f66
--- /dev/null
+++ b/humanbot_server.js
@@ -0,0 +1,74 @@
+#!/usr/bin/env node
+var http=require("http"),fs=require("fs");
+var PORT=+process.argv[2];
+var movequeue=[];
+var httpserver=http.createServer(function(req,res){
+ var reqbody="";
+ console.log("req: "+req.url);
+ if(req.url=="/othermove"){
+ if(movequeue.length){
+ res.writeHead(200,{"Content-Type":"application/json"});
+ res.end(movequeue.shift());
+ } else {
+ res.writeHead(503,{"Content-Type":"text/plain"});
+ res.end("No move to unqueue");
+ }
+ } else if(req.url=="/mynewmove"){
+ req.on("data",function(data){reqbody+=data;});
+ req.on("end",function(){
+ var mv;
+ console.log("mynewmove: reqbody = "+reqbody);
+ try {mv=JSON.parse(reqbody);}
+ catch(e){mv=null;}
+ if(mv==null||
+ !Array.isArray(mv)||
+ mv.length!=3||
+ !mv.map(function(v){
+ return typeof(v)=="number"&&v%1==0;
+ }).reduce(function(a,b){return a&&b;})
+ ){
+ res.writeHead(400,{"Content-Type":"text/plain"});
+ res.end("400 Bad request");
+ return;
+ }
+ mynewmovefifo.write(mv.join(" ")+"\n",function(){
+ console.log("server: ACTUALLY written new move to fifo");
+ });
+ res.writeHead(200,{"Content-Type":"text/plain"});
+ res.end("true");
+ });
+ } else if(req.url=="/"){
+ res.writeHead(200,{"Content-Type":"text/html"});
+ res.end(String(fs.readFileSync("humanbot_index.html")));
+ } else {
+ res.writeHead(404,{"Content-Type":"text/plain"});
+ res.end("Nothing here...");
+ }
+});
+var httpserverlisteninterval=setInterval(function(){
+ try {
+ httpserver.listen(PORT);
+ console.log("Server running at port "+PORT+". (http://localhost:"+PORT+")");
+ clearInterval(httpserverlisteninterval);
+ } catch(e){}
+},10);
+
+var othermovefifo,mynewmovefifo,othermovefifo_buffer="";
+othermovefifo=fs.createReadStream(".humanbot__.__othermove.fifo");
+othermovefifo.on("data",function(data){
+ var idx,v;
+ othermovefifo_buffer+=data;
+ idx=othermovefifo_buffer.indexOf("\n");
+ if(idx!=-1){
+ v=othermovefifo_buffer.slice(0,idx);
+ if(v!="go"&&v!="nogo")v="["+v.replace(/ /g,",")+"]";
+ movequeue.push(v);
+ othermovefifo_buffer=othermovefifo_buffer.slice(idx+1);
+ }
+});
+othermovefifo.on("end",function(){
+ console.log("othermovefifo closed. Exiting.");
+ process.exit();
+});
+mynewmovefifo=fs.createWriteStream(".humanbot__.__mynewmove.fifo",{flags:"a"});
+console.log("Fifo's opened.");