From 3d909529d4f56efab36a1be66abc598123156314 Mon Sep 17 00:00:00 2001 From: nitriques Date: Thu, 30 Oct 2014 00:29:11 -0400 Subject: [PATCH] better debug info --- lib/tosr0x.js | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/lib/tosr0x.js b/lib/tosr0x.js index c45bd1d..d15c399 100644 --- a/lib/tosr0x.js +++ b/lib/tosr0x.js @@ -48,6 +48,20 @@ var resolved = function (err, rej, callback) { return !err; }; +var log = function (t, cmd, msg) { + if (!t._options.debug) { + return; + } + if (!msg) { + msg = cmd; + cmd = 'log'; + } + if (cmd !== 'dir') { + msg = '[Tosr0x] ' + msg; + } + console[cmd](msg); +}; + var T = exports.Tosr0x = function (uri, options) { this._serial = null; this._uri = uri || '/dev/ttyUSB0'; @@ -115,7 +129,7 @@ T.create = function (port, options) { if (!port) { return T.fromPortScan(options); } else { - return new Promise(function (res) { + return p(function (res) { process.nextTick(function () { res(new T(port, options)); }); @@ -139,10 +153,9 @@ var bufferIsNullTerminated = function (buffer) { var dataListener = function (t) { return function dataListener(data) { var newReads = []; - console.dir(data); - console.dir(t.reads); t.buffer += data.toString(); + log(t, 'Received ' + data.toString('hex')); _.forEach(t.reads, function (r) { var callR = function (data) { @@ -157,24 +170,20 @@ var dataListener = function (t) { callR(t.buffer); } } else { + t.buffer = ''; callR(data); } }); - console.dir(t.reads); t.reads = newReads; if (bufferIsNullTerminated(t.buffer)) { t.buffer = ''; } - - console.dir(t.reads); }; }; var errorListener = function (t) { return function errorListener(err) { - //t._serial = null; - //t._state = {}; throw err; }; }; @@ -184,7 +193,7 @@ var closeListener = function (t) { t._serial = null; t._state = {}; t.reads = []; - console.log('Port closed.'); + log(t, 'Port closed.'); }; }; @@ -228,7 +237,7 @@ T.prototype.close = function (callback) { var t = this; return p(function close(res, rej) { if (!t._serial) { - console.error('Already closed.'); + log(t, 'error', 'Already closed.'); // soft fail call(callback, null, t); res(t); @@ -264,10 +273,9 @@ T.prototype.send = function (cmd, callback) { var t = this; var s = this._serial; return ptime(function send(res, rej) { - console.log('------------------------------'); - console.log('Sending ' + cmd); + log(t, '------------------------------'); + log(t, 'Sending ' + cmd); s.write(cmd, function (err, bytesWritten) { - console.log(bytesWritten + ' bytes sent'); if (resolved(err, rej, callback)) { s.drain(function (err) { if (resolved(err, rej, callback)) {