ev3js
Version:
LEGO Mindstorms EV3 API for Node.js
104 lines (92 loc) • 3.38 kB
JavaScript
var fs = require('fs'),
EventEmitter = require('events').EventEmitter;
var Device = function(){};
Device.prototype = new EventEmitter();
(function(){
var cast = {
str2num: function(n){return +n},
strnum2bool: function(b){return !!+b;},
bool2num: function(b){return +!!b;},
str2onoff: function(b){return b === 'on';},
onoff2str: function(b){return b ? 'on' : 'off';},
};
this.path = '/sys/bus/legoev3/devices/';
this.polling = [];
this.read = function(file, callback){
if(typeof callback === 'function'){
return fs.readFile(this.path + file, {encoding: 'utf8'}, callback);
} else {
return fs.readFileSync(this.path + file, {encoding: 'utf8'});
}
};
this.write = function(file, value, callback){
if(typeof callback === 'function'){
fs.writeFile(this.path + file, value, callback);
} else {
fs.writeFileSync(this.path + file, value);
}
};
this.search = function(name){
var ports = fs.readdirSync(this.path);
for(var i = 0; i < ports.length; i++){
var port = ports[i];
var portName = fs.readFileSync([this.path, port, 'port_name'].join('/'), {encoding: 'utf8'});
if(portName.match(name)){
return port;
}
}
};
this.accessor = function(name, getter, setter){
this[name.replace(/_(\w)/g, function(a, b){return b.toUpperCase();})] = function(value, callback){
if(getter && (arguments.length === 0 || (arguments.length === 1 && typeof value === 'function'))){
callback = value;
value = this.read(name, callback);
if(typeof getter === 'string'){
getter = cast[getter];
}
if(typeof getter === 'function'){
value = getter(value);
}
return value;
} else if(setter && arguments.length >= 1){
if(typeof setter === 'string'){
setter = cast[setter];
}
if(typeof setter === 'function'){
value = setter(value);
}
this.write(name, value, callback);
}
};
};
this.poll = function(property, callback, interval){
var id = this.polling.length;
this.polling[id] = true;
fs.open(this.path + property, 'r', function(err, fd){
if(err){
throw new Error(err);
}
(function(){
var buf = new Buffer(64);
var len = fs.readSync(fd, buf, 0, 64, 0);
this.polling[id] = callback(buf.toString('utf8', 0, len - 1));
if(this.polling[id] !== false){
setTimeout(arguments.callee.bind(this), interval || 1);
} else {
fs.close(fd);
}
}.bind(this))();
}.bind(this));
return id;
};
this.abort = function(id){
if(arguments.length){
this.polling[id] = false;
} else {
this.polling = this.polling.map(function(){
return false;
});
}
};
}.bind(Device.prototype))();
module.exports = Device;