aboutsummaryrefslogtreecommitdiff
path: root/humanbot_server.js
blob: 3f38f66a62144bd8f0e32f3199e0f20479fb7726 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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.");