| 930 |
user890104 |
1 |
/*
|
|
|
2 |
|
|
|
3 |
Copyright 2014 user890104
|
|
|
4 |
|
|
|
5 |
|
|
|
6 |
This file is part of fmibot.
|
|
|
7 |
|
|
|
8 |
fmibot is free software: you can redistribute it and/or
|
|
|
9 |
modify it under the terms of the GNU General Public License as
|
|
|
10 |
published by the Free Software Foundation, either version 2 of the
|
|
|
11 |
License, or (at your option) any later version.
|
|
|
12 |
|
|
|
13 |
fmibot is distributed in the hope that it will be useful,
|
|
|
14 |
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
15 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
|
|
16 |
See the GNU General Public License for more details.
|
|
|
17 |
|
|
|
18 |
You should have received a copy of the GNU General Public License along
|
|
|
19 |
with fmibot. If not, see <http://www.gnu.org/licenses/>.
|
|
|
20 |
|
|
|
21 |
*/
|
|
|
22 |
|
|
|
23 |
var net = require('net');
|
|
|
24 |
var fs = require('fs');
|
|
|
25 |
|
|
|
26 |
function Socket(path, successCallback, cmdCallback) {
|
|
|
27 |
var server = net.createServer();
|
|
|
28 |
|
|
|
29 |
server.on('connection', function(connection) {
|
|
|
30 |
console.info('CONTROL: Socket open');
|
|
|
31 |
|
|
|
32 |
connection.on('end', function() {
|
|
|
33 |
console.info('CONTROL: Socket closed');
|
|
|
34 |
});
|
|
|
35 |
|
|
|
36 |
connection.on('data', function(data) {
|
|
|
37 |
//console.log('CONTROL: Got raw data:', data);
|
|
|
38 |
var text = data.toString();
|
|
|
39 |
|
|
|
40 |
var lines = text.split('\n').filter(function(val, idx, arr) {
|
|
|
41 |
return !!val;
|
|
|
42 |
});
|
|
|
43 |
|
|
|
44 |
//console.log(lines);
|
|
|
45 |
|
|
|
46 |
var i, len = lines.length;
|
|
|
47 |
|
|
|
48 |
for (i = 0; i < len; ++i) {
|
|
|
49 |
console.log('CONTROL: Got data:', lines[i]);
|
|
|
50 |
cmdCallback(lines[i]);
|
|
|
51 |
}
|
|
|
52 |
});
|
|
|
53 |
});
|
|
|
54 |
|
|
|
55 |
server.on('listening', function() {
|
|
|
56 |
console.info('CONTROL: Socket bound');
|
|
|
57 |
|
|
|
58 |
fs.chmod(path, 0775, successCallback);
|
|
|
59 |
});
|
|
|
60 |
|
|
|
61 |
server.on('error', function (e) {
|
|
|
62 |
switch (e.code) {
|
|
|
63 |
case 'EADDRINUSE':
|
|
|
64 |
console.warn('CONTROL: Socket in use, retrying...');
|
|
|
65 |
fs.unlink(path, bindSocket);
|
|
|
66 |
break;
|
|
|
67 |
default:
|
|
|
68 |
throw e;
|
|
|
69 |
break;
|
|
|
70 |
}
|
|
|
71 |
});
|
|
|
72 |
|
|
|
73 |
function bindSocket() {
|
|
|
74 |
console.info('CONTROL: Attempting to bind socket...');
|
|
|
75 |
server.listen(path);
|
|
|
76 |
}
|
|
|
77 |
|
|
|
78 |
bindSocket();
|
|
|
79 |
}
|
|
|
80 |
|
|
|
81 |
exports.Socket = Socket;
|