Last active
August 29, 2015 14:02
-
-
Save myndzi/9c7ff0c58da1bc71a48f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Promise=require('bluebird'); | |
var SerialPort = require("serialport").SerialPort | |
var openedPort=false; | |
var puerto; | |
var Serial = function(puerto) { | |
var self = this; | |
self.openedPort = false; | |
//crea un objeto serialport, abre el puerto | |
this.serialPort = new SerialPort(puerto, { | |
baudrate: 9600 | |
}); | |
this.serialPort.on("open", function () { //cuando se abra el puerto... | |
console.log('\n\nPUERTO '+ puerto+ ' ABIERTO\n\n'); | |
self.openedPort = true; | |
}); | |
}); | |
Serial.prototype.send = function (d){ | |
var p = "\x02"+d+"\x0D";//agrega STX y ETX | |
var deferred = new Promise.defer(); | |
var timeout; | |
var response = '', port = this.serialPort; | |
var handler = function (data) { | |
console.log('RECIBIDO: '+ data ); | |
response += data; | |
if (/[\x0C\x0D]$/.test(data)) { | |
deferred.resolve(data.trim()); | |
} | |
port.removeListener('data', handler); | |
}; | |
port.on('data', handler); | |
console.log("ENVIANDO: "+p+''); | |
this.serialPort.write(p, function (err, results) { | |
if (err) { deferred.reject(new Error(err)) } | |
}); | |
timeout = setTimeout(function(){ | |
//console.log('AGOTADO'.blue) | |
deferred.reject(new Error('Tiempo agotado al enviar paquete, No hubo respuesta'.red)); | |
}, 500); | |
return deferred.promise; | |
}; | |
module.exports = Serial; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment