cylon/examples/api/api.markdown

70 lines
1.9 KiB
Markdown
Raw Normal View History

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:
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`.
Cylon.config({
api: { host: '0.0.0.0', port: '8080' }
});
Cylon.api();
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-09-30 06:15:42 +08:00
connection: { name: '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-09-30 06:15:42 +08:00
device: { name: '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!
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`.