This repository has been archived on 2024-01-30. You can view files and clone it, but cannot push or open issues or pull requests.
trev/nodejs/ar-com/arduino.js

55 lines
1.5 KiB
JavaScript
Raw Normal View History

var events = require('events'),
child = require('child_process'),
util = require('util'),
serial = require("serialport").SerialPort;
var Arduino = function (baudrate) {
this.baudrate = baudrate && baudrate || 9600;
this.writeBuffer = [];
this.success;
}
Arduino.prototype.setup = function () {
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 this.success = false;}
var buff = stdout.slice(stdout.indexOf('Guessing serial port ... ')+25);
buff = buff.slice(0, buff.indexOf('\n'));
console.log('Guessing serial port ... ' + buff);
this.serial = new serial(buff, {
baudrate: this.baudrate,
parser: serial.parsers.readline('\n')
}, false);
this.serial.open(function (error) {
if ( error ) {
console.log('Please check arduino!')
return this.success = false;
}
serialPort.write(new Buffer('00000000'));
});
this.success = true;
this.processWriteBuffer();
});
}
Arduino.prototype.write = function (m) {
if (this.success) {
this.serial.write(m);
} else {
this.writeBuffer.push(m);
console.log('Board isn\'t available (yet?).')
}
}
Arduino.prototype.processWriteBuffer = function () {
while (this.writeBuffer.length > 0) {
this.write(this.writeBuffer.shift());
}
}
module.exports = Arduino;