Skip to content

Commit

Permalink
Merge pull request #7 from mintuz/express
Browse files Browse the repository at this point in the history
ExpressJS action
  • Loading branch information
mintuz committed Jan 24, 2016
2 parents 82ed900 + cf0b9c9 commit 66516c3
Show file tree
Hide file tree
Showing 7 changed files with 230 additions and 19 deletions.
84 changes: 83 additions & 1 deletion README.md
@@ -1,5 +1,5 @@
# BB8 Commander
A Node CLI Tool for Sphero BB8 Robot.
A Node CLI Tool for Sphero BB8 Robot using the [Sphero Javascript SDK](http://sdk.sphero.com/community-apis/javascript-sdk/)

![BB8 Rolling like he's owning](http://i.imgur.com/00sZIf3.gif)

Expand All @@ -20,6 +20,88 @@ Not yet on npm so you'll have to do it the good'ol fasioned way with a cheeky gi
* `node index.js disco` - Command to turn your BB8 Unit into a shining disco ball in the night
* `node index.js weather --city="manchester" --country="uk" --api-key="ABCD"` - Command to turn your BB8 Unit into your very own weather reporter, uses OpenWeather so be sure to get your own API key
* `node index.js tweet --hash-tag="bb8" --delay=5000` - Command to search twitter and run the first hashtag it finds as a command. Eg a tweet "#disco #bb8" would run the `disco` command --consumer-key xxx --consumer-secret xxx --access-token-key xxx --access-token-secret xxx
* `node index.js express --port=4000` - Command to run an express server which has a single POST endpoint which you can send a JSON object to. See below for more details.

### Express Server

Having the ability to run an Express server to issue commands to the BB8 unit opens up a bunch of possibilities. One of the main benefits of having an Express server is that you can integrate into [IFTTT](https://ifttt.com/) and at that point, you have entered the Internet of things.

To get started is really easy, all you need to do is run `node index.js express --port=4000` adn once your BB8 is connected, an Express server will be started.

You can then send commands directly to it via a POST request. It supports any SpheroSDK command as well as custom commands we have created. See below for some examples.

### Native Commands

With native commands, the response body will include information the BB8 exposes once that command has been executed. Read the Sphero documentation on what data it returns. http://sdk.sphero.com/community-apis/javascript-sdk/

#### Running the `color` command

Post Request - localhost:3000/

Request Body

```
{
"mode":"sphero",
"command":"color",
"value": "yellow"
}
```

#### Running the `roll` command

Post Request - localhost:3000/

Request Body

```
{
"mode":"sphero",
"command":"roll",
"value": [130, 50]
}
```

With this request, we are passing an array and that's because the roll command in Sphero SDK requires multiple parameters. This is just a simple way to pass those values to that command.

### Custom Commands

#### Running the `disco` command

Post Request - localhost:3000/

Request Body

```
{
"mode":"custom",
"command":"disco"
}
```

#### Running the `tweet` command

POST Request - localhost:3000/

Request Body

```
{
"mode":"custom",
"command":"tweet",
"value": {
"delay": 30,
"consumerKey": "YOUR_CONSUMER_KEY",
"consumerSecret": "YOUR_CONSUMER_SECRET",
"accessTokenKey": "YOUR_ACCESS_TOKEN_KEY",
"accessTokenSecret": "YOUR_ACCESS_TOKEN_SECRET"
}
}
```

Obviously you wouldn’t pass your OAuth information like this (BB8 Commander supports environment variables for secure data) but the important thing to note here is, anything that can be passed to the CLI tool can also be passed into the express server endpoint.

A suite difference between native commands and custom commands is that native commands that require multiple parameters will be passed as an array whilst custom commands will be objects. The reason for this is custom commands are key value pairs due to them sharing the same code as the CLI tool.

# Contributors
* [@mintuz](http://twitter.com/mintuz)
Expand Down
78 changes: 78 additions & 0 deletions commands/express.js
@@ -0,0 +1,78 @@
var bb8 = require('../libs/bb8-instance')(),
config = require('../libs/bb8-instance').config,
expressInstance = require('../libs/express'),
executeCustomCommand = require('../libs/execute-command'),
_ = require('lodash');

var callbackFactory = function(res){
return function(err, data){
if(!err) {
res.send({data: data});
} else {
res.send({error: err});
}
};
};

var spheroCommandExecuter = function(bb8, requestBody, res) {

if(_.isString(requestBody.value)) {

bb8[requestBody.action](requestBody.value, callbackFactory(res));

} else if(_.isArray(requestBody.value)) {

requestBody.value.push(callbackFactory(res));

bb8[requestBody.action].apply(this, requestBody.value);

} else {

bb8[requestBody.action](callbackFactory(res));

}

};

var customCommandExecuter = function(bb8, requestBody, res){

if(_.isString(requestBody.value) || _.isObject(requestBody.value)) {

executeCustomCommand.alreadyConnectedSingleValue(bb8, requestBody.action, requestBody.value);

} else if(_.isArray(requestBody.value)) {

executeCustomCommand.alreadyConnectedMultipleValues(bb8, requestBody.action, requestBody.value);

} else {

executeCustomCommand.alreadyConnectedSingleValue(bb8, requestBody.action, {});

}

res.send('Command Executed - ' + requestBody.action);

};

module.exports = function(bb8, options) {

expressInstance(function (req, res) {

var requestBody = req.body;

if(requestBody.action && requestBody.mode === 'sphero') {

spheroCommandExecuter(bb8, req.body, res);

} else if(requestBody.action && requestBody.mode === 'custom') {

customCommandExecuter(bb8, req.body, res);

} else {

res.send('Command is invalid');

}

}, options);
};
2 changes: 1 addition & 1 deletion commands/tweet.js
Expand Up @@ -22,7 +22,7 @@ function getLatestStatus(tweets) {
}

var executeTwitterCommand = function (bb8, options) {

var twitter = TwitterClient(options),
hashTag = options.hashTag || 'bb8code';

Expand Down
33 changes: 16 additions & 17 deletions index.js
@@ -1,15 +1,6 @@
var program = require('commander');
var packageFile = require('./package.json');
var bb8 = require('./libs/bb8-instance')();
var config = require('./libs/bb8-instance').config;

var executeCommand = function (command, options) {
if (bb8) {
bb8.connect(function () {
require(command)(bb8, options)
});
}
};
var program = require('commander'),
packageFile = require('./package.json'),
executeCommand = require('./libs/execute-command');

program.version(packageFile.version);

Expand All @@ -33,7 +24,7 @@ program
.command('disco')
.description('Command to make your BB8 Unit A disco ball')
.action(function () {
executeCommand('./commands/disco');
executeCommand('disco');
});

program
Expand All @@ -43,20 +34,20 @@ program
.option('-cc, --country <country>', 'Country name such as uk')
.option('-t, --access-token <accessToken>', 'API Key')
.action(function(options) {
executeCommand('./commands/weather', options);
executeCommand('weather', options);
});

program
.command('github')
.description('Command to get notifications of new issues and PRs')
.option('-t, --access-token <accessToken>', 'API Key')
.action(require('./commands/github'));
.action(require('github'));

program
.command('roll')
.description('BB8 will roll!')
.action(function () {
executeCommand('./commands/roll');
executeCommand('roll');
});


Expand All @@ -70,9 +61,17 @@ program
.option('--access-token-key <accessTokenKey>', 'Twitter api access token key')
.option('--access-token-secret <accessTokenSecret>', 'Twitter api access token secret')
.action(function (options) {
executeCommand('./commands/tweet', options)
executeCommand('tweet', options)
});

program
.command('express')
.description('Command to setup express server')
.option('-p, --port <port>', 'Port to run express on. Defaults to 3000')
.action(function (options) {
executeCommand('express', options);
});

try {
program.parse(process.argv);
} catch (e) {
Expand Down
32 changes: 32 additions & 0 deletions libs/execute-command.js
@@ -0,0 +1,32 @@
var bb8 = require('./bb8-instance')(),
appRootPath = require('app-root-path'),
_ = require('lodash');

module.exports = function (command, options) {
if (bb8) {
bb8.connect(function () {
require(appRootPath + '/commands/' + command)(bb8, options);
});
}
};

module.exports.alreadyConnected = function(bb8, command) {
if (bb8) {
require(appRootPath + '/commands/' + command)(bb8);
}
}

module.exports.alreadyConnectedSingleValue = function(bb8, command, options) {
if (bb8) {
require(appRootPath + '/commands/' + command)(bb8, options);
}
};

module.exports.alreadyConnectedMultipleValues = function(bb8, command, options) {

if (bb8) {
var parameters = _.union([bb8], options);
require(appRootPath + '/commands/' + command).apply(this, parameters);
}

};
17 changes: 17 additions & 0 deletions libs/express.js
@@ -0,0 +1,17 @@
var express = require('express'),
app = express(),
bodyParser = require('body-parser');

module.exports = function(callback, options) {

var port = options.port || 3000;

app.use(bodyParser.json());

app.post('/', callback);

app.listen(port, function () {
console.log( 'Server listening on port ' + port );
});

}
3 changes: 3 additions & 0 deletions package.json
Expand Up @@ -19,7 +19,10 @@
},
"homepage": "https://github.com/mintuz/bb8-commander#readme",
"dependencies": {
"app-root-path": "^1.0.0",
"body-parser": "^1.14.2",
"commander": "^2.9.0",
"express": "^4.13.4",
"github": "^0.2.4",
"home-config": "^0.1.0",
"lodash": "^4.0.0",
Expand Down

0 comments on commit 66516c3

Please sign in to comment.