2013-11-27 08:02:12 +08:00
|
|
|
# API
|
|
|
|
|
|
|
|
In this Cylon example, we'll be demonstrating the HTTP API that Cylon spins up
|
|
|
|
when it starts.
|
|
|
|
|
|
|
|
This example involves two Spheros, so before you start make sure you have the
|
|
|
|
`cylon-sphero` module installed.
|
|
|
|
|
|
|
|
First, let's import Cylon:
|
|
|
|
|
2014-03-29 01:42:20 +08:00
|
|
|
var Cylon = require('../..');
|
2013-11-27 08:02:12 +08:00
|
|
|
|
|
|
|
Next up, we'll configure the API Cylon will serve, telling it to serve on port
|
|
|
|
`8080`.
|
|
|
|
|
2015-01-13 00:58:41 +08:00
|
|
|
// ensure you install the API plugin first:
|
|
|
|
// $ npm install cylon-api-http
|
2014-11-26 01:45:20 +08:00
|
|
|
Cylon.api({
|
|
|
|
host: '0.0.0.0',
|
|
|
|
port: '8080'
|
2014-09-20 02:59:11 +08:00
|
|
|
});
|
|
|
|
|
2013-11-27 08:02:12 +08:00
|
|
|
Since we're making two very similar robots (Spheros, in this case), let's put
|
|
|
|
the different parts of each robot in objects so we can initialize them later.
|
|
|
|
The only differences between the bots are their names and the port they'll be
|
|
|
|
using.
|
|
|
|
|
2014-09-30 06:15:42 +08:00
|
|
|
var bots = {
|
|
|
|
'Thelma': '/dev/rfcomm0',
|
|
|
|
'Louise': '/dev/rfcomm1'
|
|
|
|
};
|
2013-11-27 08:02:12 +08:00
|
|
|
|
|
|
|
Now we can define the basic robot both of our Sphero robots will be based on.
|
|
|
|
|
2014-09-30 06:15:42 +08:00
|
|
|
Object.keys(bots).forEach(function(name) {
|
|
|
|
var port = bots[name];
|
|
|
|
|
|
|
|
Cylon.robot({
|
|
|
|
name: name,
|
2013-11-27 08:02:12 +08:00
|
|
|
|
|
|
|
Both robots will be connecting to Spheros, and so using the cylon-sphero
|
|
|
|
adaptor:
|
|
|
|
|
2014-11-26 08:01:31 +08:00
|
|
|
connections: {
|
|
|
|
sphero: { adaptor: 'sphero', port: port }
|
|
|
|
},
|
2013-11-27 08:02:12 +08:00
|
|
|
|
|
|
|
And both will be connecting to the same kind of device (you guessed it,
|
|
|
|
a Sphero).
|
|
|
|
|
2014-11-26 08:01:31 +08:00
|
|
|
devices: {
|
|
|
|
sphero: { driver: 'sphero' }
|
|
|
|
},
|
2013-11-27 08:02:12 +08:00
|
|
|
|
|
|
|
Both robots will be performing the same kind of work as well. Every second,
|
|
|
|
they'll print their name to the console, set themselves to a random color, and
|
|
|
|
roll in a random direction.
|
|
|
|
|
2014-09-30 06:15:42 +08:00
|
|
|
work: function(my) {
|
|
|
|
every((1).seconds(), function() {
|
|
|
|
console.log(my.name);
|
|
|
|
my.sphero.setRandomColor();
|
|
|
|
my.sphero.roll(60, Math.floor(Math.random() * 360));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
2013-11-27 08:02:12 +08:00
|
|
|
|
|
|
|
And now that Cylon has all the robots we're intending to give it, let's get
|
|
|
|
started!
|
|
|
|
|
2014-03-27 07:25:09 +08:00
|
|
|
Cylon.start();
|
2013-11-27 08:02:12 +08:00
|
|
|
|
|
|
|
Now Cylon will start up the robots and their devices, as well as an API server
|
|
|
|
listening on `0.0.0.0:8080`.
|