-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrobo.js
52 lines (45 loc) · 1.34 KB
/
robo.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
const PythonShell = require('python-shell');
const command = require('./robo-commands.js');
const SPEED = 128;
const TURN_SPEED = 128;
const SPEED_MOD = 0.975;
//the time at which the last command was received
var lastCommand = -Infinity;
// runs commands received as messages (on the socket connection in server.js)
function runCommand (msg) {
if (msg.time > lastCommand) {
lastCommand = msg.time;
switch(msg.command) {
case command.FORWARD:
runMotor(1, -SPEED, 2, -SPEED);
break;
case command.REVERSE:
runMotor(1, SPEED, 2, SPEED);
break;
case command.TURN_LEFT:
runMotor(1, -TURN_SPEED, 2, TURN_SPEED);
break;
case command.TURN_RIGHT:
runMotor(1, TURN_SPEED, 2, -TURN_SPEED);
break;
case command.STOP:
runMotor(1, 0, 2, 0);
break;
}
}
}
function runMotor(lmotor, lspeed, rmotor, rspeed) {
var pyshell = new PythonShell('./motorControl.py', {
pythonPath: 'python2',
});
var modspeed = Math.floor(lspeed*SPEED_MOD);
// sends a message to the Python script via stdin
pyshell.send(JSON.stringify({left: {motor: lmotor, speed: modspeed}, right: {motor: rmotor, speed: rspeed}}));
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err) throw err;
});
}
module.exports = {
runCommand: runCommand
}