Skip to content
Permalink
Browse files

refactor to command pattern

  • Loading branch information
ferclaverino committed Dec 3, 2016
1 parent 20be6d4 commit f217cc06bc93f1a3159e5fe8953ca4d69df179d6
Showing with 43 additions and 24 deletions.
  1. +26 −0 manual/keyboardInvoker.js
  2. +17 −24 manual/main.js
@@ -0,0 +1,26 @@
const keypress = require('keypress');

class KeyboardInvoker {
constructor(commands) {
this.commands = commands;
keypress(process.stdin);
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.setRawMode(true);
}

listen() {
process.stdin.on('keypress', (ch, key) => {
this.execute(key.name);
})
}

execute(commandName) {
if (this.commands[commandName]) {
this.commands[commandName]();
}
}

}

module.exports = KeyboardInvoker;
@@ -1,56 +1,49 @@
const { Board, Motor } = require('johnny-five');
const keypress = require('keypress');
const KeyboardInvoker = require('./keyboardInvoker.js');

const board = new Board({
port: '/dev/rfcomm0',
repl: false,
debug: true,
});

keypress(process.stdin);
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.setRawMode(true);

board.on('ready', () => {
const configs = Motor.SHIELD_CONFIGS.ADAFRUIT_V2;
const motorL = new Motor(configs.M2);
const motorR = new Motor(configs.M1);
// set 80% speed
const speed = 255 * 0.8;

process.stdin.on('keypress', (ch, key) => {
if (!key) {
return;
} else if (key.name === 'q') {
process.exit();
} else if (key.name === 'up') {
// forward
const commands = {
'q': () => process.exit(),
'up': () => {
motorL.forward(speed);
motorR.forward(speed);
} else if (key.name === 'down') {
// reverse
},
'down': () => {
motorL.reverse(speed);
motorR.reverse(speed);
} else if (key.name === 'left') {
// left
},
'left': () => {
motorL.reverse(speed);
motorR.forward(speed);
} else if (key.name === 'right') {
// right
},
'right': () => {
motorL.forward(speed);
motorR.reverse(speed);
} else if (key.name === 'space') {
},
'space': () => {
// stop
motorL.stop();
motorR.stop();
}
});
};
const keyboardInvoker = new KeyboardInvoker(commands);

keyboardInvoker.listen();

board.on('exit', () => {
// stop
motorL.stop();
motorR.stop();
keyboardInvoker.execute('space');
});

});

0 comments on commit f217cc0

Please sign in to comment.
You can’t perform that action at this time.