event emmiter based connect

Now with event emitter to divide code more easily.
This commit is contained in:
Shannon Sterz 2016-01-16 21:58:47 +01:00
parent b398d4e6e2
commit 69b86527d5

View file

@ -6,14 +6,18 @@ var events = require('events'),
var Arduino = function (baudrate) { var Arduino = function (baudrate) {
this.baudrate = baudrate && baudrate || 9600; this.baudrate = baudrate && baudrate || 9600;
this.writeBuffer = []; this.writeBuffer = [];
this.success;
} }
util.inherits(Arduino, events.EventEmitter);
Arduino.prototype.HIGH = '255';
Arduino.prototype.LOW = '000';
Arduino.prototype.setup = function () { Arduino.prototype.setup = function () {
var self = this; var self = this;
child.exec('cd ../arduino && ino build && ino upload', function(err, stdout, stderr){ child.exec('cd ../arduino && ino build && ino upload', function(err, stdout, stderr){
if(err){console.log('Please install the ino utility and connect arduino!\nIf there are other open programs that communicate with the arduino, close them!'); return self.success = false;} if(err){console.log('Please install the ino utility and connect arduino!\nIf there are other open programs that communicate with the arduino, close them!'); return;}
var buff = stdout.slice(stdout.indexOf('Guessing serial port ... ')+25); var buff = stdout.slice(stdout.indexOf('Guessing serial port ... ')+25);
buff = buff.slice(0, buff.indexOf('\n')); buff = buff.slice(0, buff.indexOf('\n'));
@ -26,24 +30,31 @@ Arduino.prototype.setup = function () {
self.serial.open(function (error) { self.serial.open(function (error) {
if ( error ) { if ( error ) {
console.log('Please check arduino!') console.log('Please check arduino!');
return self.success = false; return;
} }
self.serial.write(new Buffer('00000000'));
self.success = true;
self.processWriteBuffer();
}); });
serial.on('open', setTimout(function () {
self.serial.write(new Buffer('00000000'));
self.emit('success');
self.serial.on('data', function(data){
self.emit('data', data);
});
self.processWriteBuffer();
}), 500);
}); });
} }
Arduino.prototype.write = function (m) { Arduino.prototype.write = function (message) {
if (this.serial) { if (this.serial) {
console.log('sending '+m); console.log('sending '+message);
this.serial.write(m); this.serial.write(message);
} else { } else {
this.writeBuffer.push(m); this.writeBuffer.push(message);
console.log('Board isn\'t available (yet?).') console.log('Board isn\'t available (yet?).')
} }
} }