-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
71 lines (63 loc) · 1.85 KB
/
server.js
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
var http = require('http');
var url = require('url');
var fs = require('fs');
var port = process.env.PORT || 1337;
// client ID -> true
var knownClients = {};
// client ID -> command character
var nextCmds = {};
// client ID -> response object
var wantCmds = {};
// Web browser has sent us a command to forward to
// the Arduino client. Try to process it immediately
// or remember it for when the client next connects.
function setNextCmd(req_url, res) {
var id = req_url.query.id;
res.writeHead(200, {'Content-Type': 'text/plain'});
if (knownClients[id]) {
var overrode = !!nextCmds[id];
nextCmds[id] = req_url.query.cmd;
processCmds(id);
res.end('Command ' + (overrode ? 'overridden' : 'accepted') + '.\n');
} else {
res.end('Command ignored (Arduino not listening).\n');
}
}
// If Arduino client asking for command, add the
// response object to be returned later when web
// client has issued command.
function wantCmd(req_url, res) {
var id = req_url.query.id;
knownClients[id] = true;
wantCmds[id] = res;
processCmds(id);
}
// Check if there is a command to send to the client,
// and the client is waiting for a command.
function processCmds(id) {
var cmd = nextCmds[id];
if (cmd) {
var res = wantCmds[id];
if (res) {
delete wantCmds[id];
delete nextCmds[id];
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(cmd + '\n');
}
}
}
http.createServer(function (req, res) {
var req_url = url.parse(req.url, true);
if (req_url.pathname == '/wantCmd')
wantCmd(req_url, res);
else if (req_url.pathname == '/setNextCmd')
setNextCmd(req_url, res);
else if (req_url.pathname == '/')
fs.readFile('./index.html', function(err, data) {
res.end(data);
});
else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not found\n');
}
}).listen(port);