-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
118 lines (93 loc) · 2.63 KB
/
main.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
var EventEmitter = require('events');
var util = require('util');
var serialPort = require('serialport');
var serialPortUsed = false;
var availablePorts = [];
var constructor;
var timer;
var deviceAwake = false;
var parsePacket = require('./lib/parsePacket');
var debug = require('./lib/debug');
var config = require('./config/config.json');
function DavisReader(options) {
if (typeof options !== 'object') {
options = {};
}
debug.setDebugMode(options.debug);
constructor = this;
EventEmitter.call(this);
// Either force a specific port or automatically discover it
if (options && options.serialPort) {
availablePorts[0] = options.serialPort;
_setupSerialConnection();
} else {
serialPort.list(function (err, ports) {
if (err) {
throw new Error('Serialports could not be listed: ' + err);
}
debug.logAvailablePorts(ports);
for (var i = 0; i < ports.length; i++) {
availablePorts[i] = ports[i].comName;
}
_setupSerialConnection();
});
}
}
util.inherits(DavisReader, EventEmitter);
/**
* Retrieve the name of the serial port being used
*/
DavisReader.prototype.getSerialPort = function () {
return serialPortUsed;
};
module.exports = DavisReader;
/**
* Setup serial port connection
*/
function _setupSerialConnection() {
var port = availablePorts[0];
debug.log('Trying to connect to Davis VUE via port: ' + port);
// Open serial port connection
var sp = new serialPort(port, config.serialPort);
var received = '';
sp.on('open', function () {
debug.log('Serial connection established, waking up device.');
sp.write('\n', function(err) {
if (err) {
return constructor.emit('Error on write: ', err.message);
}
});
sp.on('data', function (data) {
if (!deviceAwake){
if (data.toString() === '\n\r'){
debug.log('Device is awake');
serialPortUsed = port;
constructor.emit('connected', port);
sp.write('LOOP 1\n');
return;
}
}
debug.log("Received data, length:" + data.length);
if (data.length == 100){
// remove ack
data = data.slice(1);
}
var parsedData = parsePacket(data);
constructor.emit('data', parsedData);
setTimeout(function () {
sp.write('LOOP 1\n');
}, 2000);
});
});
sp.on('error', function (error) {
constructor.emit('error', error);
// Reject this port if we haven't found the correct port yet
if (!serialPortUsed) {
_tryNextSerialPort();
}
});
sp.on('close', function () {
deviceAwake = false;
constructor.emit('close');
});
}