Created
January 3, 2012 15:16
-
-
Save voodootikigod/1555300 to your computer and use it in GitHub Desktop.
Log all output from a serial port connection to a log file.
This file contains 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
/* | |
Simple example that takes a command line provided serial port destination and routes the output to a file of the same name with .log appended to the port name. | |
usage: node logger.js /dev/tty.usbserial <baudrate> | |
*/ | |
var SerialPort = require("serialport"); | |
var fs = require("fs"); | |
var port = process.argv[2]; | |
var baudrate = process.argv[3]; | |
var active = false; | |
function attemptLogging(fd, port, baudrate) { | |
var serialPort = new SerialPort.SerialPort(port, { | |
baudrate: baudrate | |
}); | |
fs.write(fd, "\n------------------------------------------------------------\nOpening SerialPort: "+target+" at "+Date.now()+"\n------------------------------------------------------------\n"); | |
serialPort.on("data", function (data) { | |
fs.write(fd, data.toString()); | |
}); | |
serialPort.on("close", function (data) { | |
active = false; | |
fs.write(fd, "\n------------------------------------------------------------\nClosing SerialPort: "+target+" at "+Date.now()+"\n------------------------------------------------------------\n"); | |
}); | |
} | |
if (!port) { | |
console.log("You must specify a serial port location."); | |
} else { | |
var target = port.split("/"); | |
target = target[target.length-1]+".log"; | |
if (!baudrate) { | |
baudrate = 115200; | |
} | |
fs.open("./"+target, 'w', function (err, fd) { | |
setInterval(function () { | |
if (!active) { | |
try { | |
attemptLogging(fd, port, baudrate); | |
} catch (e) { | |
// Error means port is not available for listening. | |
active = false; | |
} | |
} | |
}, 1000); | |
}); | |
} | |
old techniques die hard, good call.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could use
Date.now()
instead of+(new Date())
; it’s much more efficient.