-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialportTerminal.js
executable file
·101 lines (87 loc) · 1.91 KB
/
serialportTerminal.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env node
var redis = require("redis"),
client = redis.createClient();
var serialport = require('serialport')
var SerialPort = serialport.SerialPort;
var optimist = require('optimist');
var args = optimist
.alias('h', 'help')
.alias('h', '?')
.options('portname', {
alias: 'p',
describe: 'Name of serial port. See serialPortList.js for open serial ports.'
})
.options('baud', {
describe: 'Baud rate.',
default: 9600
})
.options('databits', {
describe: 'Data bits.',
default: 8
})
.options('parity', {
describe: 'Parity.',
default: 'none'
})
.options('stopbits', {
describe: 'Stop bits.',
default: 1
})
.options('localecho', {
describe: 'Enable local echo.',
boolean: true
})
.argv;
if (args.help) {
optimist.showHelp();
return process.exit(-1);
}
if (!args.portname) {
console.error("Serial port name is required.");
return process.exit(-1);
}
process.stdin.resume();
process.stdin.setRawMode(true);
process.stdin.on('data', function (s) {
if (s[0] === 0x03) {
port.close();
process.exit(0);
}
if (args.localecho) {
if (s[0] === 0x0d) {
process.stdout.write('\n');
} else {
process.stdout.write(s);
}
}
port.write(s, function (err) {
if (err) {
console.log(err);
}
});
});
var openOptions = {
baudRate: args.baud,
dataBits: args.databits,
parity: args.parity,
stopBits: args.stopbits,
parser: serialport.parsers.readline('\r')
};
var knownIDs = [];
var port = new SerialPort(args.portname, openOptions);
port.on('data', function (data) {
var s = data.toString('binary');
var id = s.slice(0,4);
if(knownIDs.indexOf(id)<0) {
knownIDs.push(id);
}
process.stdout.write(s);
client.publish('obd:'+id, s);
console.log('\n')
});
setInterval(function () {
client.publish('ids', knownIDs.join(','));
}, 1000)
port.on('error', function (err) {
console.log(err);
});