From 69b86527d5e1807cb9b7dc7e72d0d6d6216895c2 Mon Sep 17 00:00:00 2001 From: Stefan Sterz Date: Sat, 16 Jan 2016 21:58:47 +0100 Subject: [PATCH] event emmiter based connect Now with event emitter to divide code more easily. --- nodejs/ar-com/arduino.js | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/nodejs/ar-com/arduino.js b/nodejs/ar-com/arduino.js index e3abf4f..5f5335a 100644 --- a/nodejs/ar-com/arduino.js +++ b/nodejs/ar-com/arduino.js @@ -6,14 +6,18 @@ var events = require('events'), var Arduino = function (baudrate) { this.baudrate = baudrate && baudrate || 9600; this.writeBuffer = []; - this.success; } +util.inherits(Arduino, events.EventEmitter); + +Arduino.prototype.HIGH = '255'; +Arduino.prototype.LOW = '000'; + Arduino.prototype.setup = function () { var self = this; 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); buff = buff.slice(0, buff.indexOf('\n')); @@ -26,24 +30,31 @@ Arduino.prototype.setup = function () { self.serial.open(function (error) { if ( error ) { - console.log('Please check arduino!') - return self.success = false; + console.log('Please check arduino!'); + 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) { - console.log('sending '+m); - this.serial.write(m); + console.log('sending '+message); + this.serial.write(message); } else { - this.writeBuffer.push(m); + this.writeBuffer.push(message); console.log('Board isn\'t available (yet?).') } }