-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arduino.js
54 lines (45 loc) · 1.15 KB
/
Arduino.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
const EventEmitter = require('events').EventEmitter;
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
class Arduino extends EventEmitter {
constructor(path) {
super();
this.serialIsOpened = false;
this.parser = new Readline({ delimiter: '\n' });
this.port = new SerialPort(path, {
baudRate: 115200,
autoOpen: true
});
this.port.on('open', () => {
console.log('Port :', path, 'is openned');
this.serialIsOpened = true;
this.port.pipe(this.parser);
this.port.on('error', (err)=>{
console.log('Error : ', err.message);
});
this.port.on('close', ()=>{
console.log('Port closed.');
});
this.parser.on('data', (data)=>{
this.parse(data, (command, args )=> {
this.emit(command, args);
});
});
});
}
parse(data, next) {
let splitedData = data.trim().split(':');
let command = splitedData.shift();
next(command, {args: splitedData});
}
writeSerial(message, next) {
if(this.serialIsOpened) {
this.port.write(message+"\n", 'ascii', next);
}
else {
let err = new Error('Serial port not openned');
next(err);
}
}
}
module.exports = Arduino;