forked from Instrument/query-it
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
109 lines (95 loc) · 2.51 KB
/
client.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
var keypress = require('keypress');
var fs = require('fs');
var argv = require('yargs').argv;
var play = require('play');
var Sound = require('node-aplay');
var WebSocket = require('ws');
var ws;
var SOUNDS = require('./src/scripts/events/sounds.js');
var running = '';
var singleCharRegex = new RegExp(/^[a-zA-Z0-9`=-]$/)
var end = false;
var reconnectTimeout;
function playSound(sound) {
sound = __dirname + '/wavs/' + sound + '.wav';
console.log(sound);
if (argv.pi) {
new Sound(sound).play();
} else {
play.sound(sound);
}
}
function connectToServer() {
console.log('trying to connect');
ws = new WebSocket('ws://' + (argv.host || '10.0.0.5') + ':' + (argv.port || '8095'));
ws.on('error', function(e) {
console.log('cant connect');
reconnectTimeout = setTimeout(
connectToServer, 1000
);
});
setupSocket();
}
function setupSocket() {
ws.on('close', function close() {
console.log('disconnected');
running = '';
reconnectTimeout = setTimeout(
connectToServer, 1000
);
});
ws.on('open', function() {
console.log('connected');
clearTimeout(reconnectTimeout);
ws.on('message', function(data) {
var message = JSON.parse(data);
if (message.event === 'clear') {
end = false;
running = '';
} else if (message.event === 'logError') {
fs.appendFile('logs/big-query-errors.txt', data, function(){ console.log('error saved'); });
} else if (message.event === 'sound' && (message.data.clients.indexOf(argv.id) !== -1 || !argv.id)) {
playSound(message.data.sound);
}
});
});
}
connectToServer();
// make `process.stdin` begin emitting "keypress" events
keypress(process.stdin);
// listen for the "keypress" event
process.stdin.on('keypress', function (ch, key) {
if (key) {
if (!end) {
end = (key.name == 'return');
}
if (singleCharRegex.exec(key.name)) {
running += ch;
}
if (key.name == 'space') {
running += ' ';
} else if (key.name == 'backspace') {
running = running.slice(0, running.length - 1);
}
if (end) {
// running = '';
}
if (key && key.ctrl && key.name == 'c') {
process.exit(0);
}
} else if (singleCharRegex.exec(ch)) {
ch = ch.replace('`', '#');
ch = ch.replace('=', '+');
running += ch;
}
ws.send(JSON.stringify({
event: 'playerInput',
data: {
'running': running,
'submitted': end,
'client': argv.id,
}
}));
});
process.stdin.setRawMode(true);
process.stdin.resume();