-
Notifications
You must be signed in to change notification settings - Fork 2
/
serial.js
99 lines (88 loc) · 2.28 KB
/
serial.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
var serialport = require("serialport"),
SerialPort = serialport.SerialPort,
fs = require('fs'),
port = null;
var search_for_interface = function () {
var possible_names = [
'/dev/tty.usbserial-DA01ID01',
'/dev/tty.usbserial-DA01ID0U',
'/dev/ttyUSB0',
'/dev/ttyUSB1',
'/dev/ttyUSB2',
'/dev/ttyUSB3',
'/dev/ttyUSB4',
'/dev/ttyUSB5',
'/dev/ttyUSB6',
'/dev/ttyUSB7',
'/dev/ttyUSB8',
'/dev/ttyUSB9',
'/dev/ttyUSB10'
];
for (var i = 0; i < possible_names.length; i++) {
try {
fs.accessSync(possible_names[i]);
return possible_names[i];
} catch (err) {
console.log("Nope: " + possible_names[i]);
}
}
console.log("No radio device found");
return null;
};
function makeParser(cb) {
var lineBuffer = {timings: [], bits: [], empty: true};
return function parseLine(line) {
// TODO: track line numbers
if (line.toLowerCase().indexOf('start') != -1) {
return false;
} else if (line.toLowerCase().indexOf('end') != -1) {
if (!lineBuffer.empty) {
cb(lineBuffer);
}
lineBuffer = {timings: [], bits: [], empty: true};
} else {
var arr = line.split(' ');
if (arr.length > 2) {
lineBuffer.bits.push(arr[1].trim());
lineBuffer.timings.push(arr[2].trim());
lineBuffer.empty = false;
}
}
};
}
exports.start = function (onChange) {
if (!port) {
var port_file_name = search_for_interface();
if (!port_file_name) {
return;
}
console.log("SERIAL: Opening " + port_file_name);
port = new SerialPort(port_file_name, {
baudrate: 115200,
databits: 8,
stopbits: 1,
parity: 'none',
parser: serialport.parsers.readline('\n'),
platformOptions: {
vmin: 0
}
});
}
port.on("open", function (error) {
if (error) {
console.log('SERIAL: Failed to open port: ' + error);
process.exit(23);
} else {
console.log('SERIAL: Port opened (' + port.isOpen() + ')');
port.on('data', makeParser(onChange));
}
});
port.on('error', function (error) {
console.log('SERIAL ERROR: ' + error);
});
};
exports.send = function (data) {
console.log("SERIAL: Sending data ...");
var toSend = data.join(",");
port.write("P" + toSend + ",S");
};