-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwodoinco.js
executable file
·64 lines (56 loc) · 1.76 KB
/
wodoinco.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
// https://github.com/EmergingTechnologyAdvisors/node-serialport/blob/3.1.2/README.md
const { SerialPort } = require('serialport')
const { ReadlineParser } = require('@serialport/parser-readline')
/* Hardware:
* /dev/ttyUSB1 for USB UART
*
* not working? See who's using it:
* sudo fuser /dev/ttyUSB1
*
* Try with screen
* screen /dev/ttyUSB1 2400
*/
module.exports = function(comPortName) {
var self = {
_comPortName: comPortName,
_ready: false,
port: undefined,
listeners: [],
receiveSerial: function(data) {
console.log("WoDoInCo: received '" + data + "'")
// data = data.replace(/(\r\n|\n|\r)/gm, "")
var found = false
var oListener = this.listeners.find(value => value.key == data)
if (oListener) {
oListener.callback(data)
} else {
console.log("no listener registered for '" + data + "'")
}
},
send: async function(data) {
await this.port.write(data + '\r\n');
console.log("Wodoinco write: " + data)
return "Wrote " + data
},
init: function() {
this.port = new SerialPort({ path: this._comPortName,
baudRate: 2400,
})
const parser = this.port.pipe(new ReadlineParser())
this.port.on('open', function (data) {
console.log('WoDoInCo: Serial port "' + this._comPortName + '" opened')
this._ready = true
}.bind(this));
this.port.on('error', function (error) {
console.log('WoDoInCo: failed to open serial port ' + this._comPortName + ': ' + error)
this._ready = false
}.bind(this));
parser.on('data', this.receiveSerial.bind(this));
},
addListener: function(key, callback) {
this.listeners.push({ key: key, callback: callback })
}
}
self.init()
return self
}