-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrfcom.js
100 lines (83 loc) · 2.33 KB
/
rfcom.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
"use strict";
var SerialPort = require("serialport");
var Readline = require("@serialport/parser-readline");
class RfCom {
constructor(path) {
this.path = path;
this.hold = false;
this.queue = [];
this.buffer = "";
}
open() {
return new Promise((resolve, reject) => {
var self = this;
var port = new SerialPort(this.path, {
baud: 115200
});
this.port = port;
const parser = port.pipe(new Readline({delimiter: '\r\n'}));
port.on("open", (err) => {
if(err) {
console.log("Error opening", err.message);
return;
}
setTimeout(() => {
this.command("json").then(() => resolve());
}, 2000);
});
port.on('error', function(err) {
console.log('Error: ', err.message);
});
parser.on("data", (data) => {
if(data != 'RfCom 0.1') {
this._handle(data);
}
});
});
}
command(cmd) {
return new Promise((resolve, reject) => {
this.queue.push({
cmd: cmd,
resolve: resolve,
reject: reject
});
if(!this.hold) {
this.hold = true;
this._sendNext();
}
});
}
_sendNext() {
var next = this.queue[0].cmd;
console.log("Writing next command " + next);
this.port.write(next + "\r\n", (err) => {
if(err) {
console.log(err);
}
});
this.hold = true;
}
_handle(line) {
let cmd = this.queue.shift();
console.log("Received " + line + " in response to " + cmd.cmd);
if(this.queue.length == 0) {
this.hold = false;
} else {
this._sendNext();
}
let data = JSON.parse(line);
if(data.success === false) {
cmd.reject(data);
} else {
cmd.resolve(data);
}
}
send(id, command) {
return this.command(`send ${id} ${command}`);
}
listDevices() {
return this.command('list_devices');
}
}
module.exports = RfCom;