-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
87 lines (76 loc) · 2.03 KB
/
index.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
var config = {
serialPort: "/dev/cu.wchusbserial1410",
tcpPort: 2947,
context: "vessels.urn:mrn:signalk:uuid:28635A52-CA1B-11E5-BB61-74E35FF10656",
sensors: {
analog0: {
mapping: "electrical.dc.batteries.house.voltage",
transform: function(input) {
return input / 40.92;
}
},
analog1: {
mapping: "electrical.dc.batteries.house.current",
transform: function(input) {
return (input - 512) / 17.066666667;
}
},
analog2: {
mapping: "electrical.dc.batteries.starting.voltage",
transform: function(input) {
return input / 40.92;
}
},
}
};
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
console.error('Connecting to serial port');
var serialPort = new SerialPort(config.serialPort, {
baudrate: 9600,
parser: serialport.parsers.readline("\n")
}, false);
function onOpen() {
console.error('Serial port connected');
serialPort.write('1');
serialPort.on('data', function(data) {
var parsed = data.split(':');
var sensor = parsed[0];
if (config.sensors[sensor]) {
var value = parseInt(parsed[1]);
result = {
"context": config.context,
"updates": [
{
"source": {
"device": config.serialPort,
"timestamp": new Date(),
},
"values": [
{
"path": config.sensors[sensor].mapping,
"value": config.sensors[sensor].transform(value)
},
]
},
]
};
console.log(JSON.stringify(result));
}
});
}
function onError(err) {
console.error('Error connecting, retrying in 5 seconds...');
setTimeout(function() {serialPort.open()}, 5000)
}
function onClose() {
console.error('Connection closed, retrying in 5 seconds...');
setTimeout(openSerial, 5000)
}
function openSerial() {
serialPort.on("open", onOpen);
serialPort.on('error', onError);
serialPort.on('close', onClose);
serialPort.open();
}
openSerial();