cylon/lib/cylon.js

125 lines
2.4 KiB
JavaScript
Raw Normal View History

2013-10-25 05:25:42 +08:00
/*
* cylon
* cylonjs.com
*
* Copyright (c) 2013 The Hybrid Group
* Licensed under the Apache 2.0 license.
*/
2014-02-28 05:31:54 +08:00
"use strict";
2013-10-25 05:25:42 +08:00
var Async = require('async');
2014-05-14 10:44:40 +08:00
var Logger = require('./logger'),
Robot = require('./robot'),
Utils = require('./utils');
2014-02-28 05:31:54 +08:00
Logger.setup();
2013-10-25 05:25:42 +08:00
var Cylon = module.exports = {
2014-05-14 10:44:40 +08:00
Logger: Logger,
Driver: require('./driver'),
Adaptor: require('./adaptor'),
Utils: Utils,
IO: {
2014-06-03 04:45:42 +08:00
DigitalPin: require('./io/digital-pin'),
2014-06-03 07:02:02 +08:00
Utils: require('./io/utils')
},
api_instance: null,
2014-07-16 03:27:16 +08:00
robots: {},
commands: {}
};
// Public: Creates a new Robot
//
// opts - hash of Robot attributes
//
// Returns a shiny new Robot
// Examples:
// Cylon.robot
// connection: { name: 'arduino', adaptor: 'firmata' }
// device: { name: 'led', driver: 'led', pin: 13 }
//
// work: (me) ->
// me.led.toggle()
Cylon.robot = function robot(opts) {
var robot = new Robot(opts);
this.robots[robot.name] = robot;
return robot;
};
2014-06-05 02:37:15 +08:00
// Public: Creates a new API based on passed options
//
// opts - object containing API options
//
2014-06-05 02:37:15 +08:00
// Returns nothing
Cylon.api = function api(opts) {
if (opts == null) {
opts = {};
}
var API = require('./api');
2014-02-28 05:31:54 +08:00
2014-06-05 02:37:15 +08:00
this.api_instance = new API(opts);
this.api_instance.listen();
};
// Public: Starts up the API and the robots
//
// Returns nothing
Cylon.start = function start() {
for (var bot in this.robots) {
this.robots[bot].start();
}
};
// Public: Halts the API and the robots
//
// callback - callback to be triggered when Cylon is ready to shutdown
//
// Returns nothing
Cylon.halt = function halt(callback) {
// set a timeout, in case trying to shut everything down nicely doesn't work
Utils.after((1.5).seconds(), callback);
var fns = [];
for (var bot in this.robots) {
var robot = this.robots[bot];
fns.push(robot.halt.bind(robot));
}
Async.parallel(fns, callback);
};
2014-07-16 03:27:16 +08:00
Cylon.toJSON = function() {
var robots = [];
for (var bot in this.robots) {
robots.push(this.robots[bot]);
}
return {
robots: robots,
commands: Object.keys(this.commands)
}
};
if (process.platform === "win32") {
var readline = require("readline"),
io = { input: process.stdin, output: process.stdout };
readline.createInterface(io).on("SIGINT", function() {
process.emit("SIGINT");
});
2014-06-17 04:09:13 +08:00
}
process.on("SIGINT", function() {
Cylon.halt(function() {
process.kill(process.pid);
});
});