-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgateway.js
121 lines (100 loc) · 2.32 KB
/
gateway.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
119
120
'use strict';
process.on('unhandledRejection', console.dir);
const mqtt = require('mqtt');
const MQTT_HOST = 'mqtt://localhost:1883';
const client = mqtt.connect(MQTT_HOST);
const minimist = require('minimist');
var args = minimist(process.argv.slice(2), {
default: {
p: 0,
i: 0,
f: false,
_: []
},
});
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const PORT = '/dev/ttyUSB' + args.p;
const sid = args.i
const data = args._
const port = new SerialPort(PORT, {
baudRate: 9600
},
err => {
if (err) {
return console.log('Error:', err.message);
}
});
function write(data) {
port.write(data);
port.drain();
}
function init() {
write('@ons\n');
write('@i' + sid + '\n');
if (args.f) {
write('@m0' + 0b01100000000 + '\n');
write('@m1' + 0b01100000000 + '\n');
write('@f0' + 0b01100000000 + '\n');
write('@f1' + 0b01000000000 + '\n');
} else {
write('@m00\n');
write('@m10\n');
write('@f00\n');
write('@f10\n');
write('@f20\n');
write('@f30\n');
write('@f40\n');
write('@f50\n');
}
}
port.on('open', () => {
init();
});
var parser = new Readline('\n');
port.pipe(parser);
function timestamp() {
return new Date().getTime();
}
client.on('connect', () => {
client.subscribe('+/tx');
client.subscribe('+/rx');
parser.on('data', (data) => {
data = data.toString().split(',');
let sid = data[0];
let topic;
if ((sid & 0b00100000000) > 0) {
topic = sid + '/rx';
} else {
topic = sid + '/tx';
}
let payload = JSON.stringify({
timestamp: timestamp(),
data: data[1]
});
client.publish(topic, payload);
console.log('topic: ' + topic + ', payload: ' + payload);
});
});
rl.on('line', (input) => {
write(input+'\n');
});
client.on('message', (topic, message) => {
console.log('topic: ' + topic + ', message: ' + message);
message = JSON.parse(message);
topic = topic.split('/');
let txrx = topic[1];
let sid;
if (txrx == 'tx') {
sid = topic[0];
} else if (txrx == 'rx') {
sid = (Number(topic[0]) | 0b00100000000).toString();
}
write('@i' + sid + '\n');
write(message.data + '\n');
});