forked from serialport/node-serialport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.js
58 lines (50 loc) · 1.73 KB
/
logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
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) {
if (!active) {
fs.stat(port, function (err, stats) {
if (!err) {
active = true;
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);
});
}