-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathnodejs_serial_connection.js
More file actions
60 lines (45 loc) · 1.58 KB
/
nodejs_serial_connection.js
File metadata and controls
60 lines (45 loc) · 1.58 KB
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
import SerialConnection from "./serial_connection.js";
class NodeJSSerialConnection extends SerialConnection {
/**
* @param path serial port to connect to, e.g: "/dev/ttyACM0" or "/dev/cu.usbmodem14401"
*/
constructor(path) {
super();
this.serialPortPath = path;
}
async connect() {
// note: serialport module is only available in NodeJS, you shouldn't use NodeJSSerialConnection from a web browser
const { SerialPort } = await import('serialport');
// create new serial port
this.serialPort = new SerialPort({
autoOpen: false, // don't auto open, we want to control this manually
path: this.serialPortPath, // e.g: "/dev/ttyACM0" or "/dev/cu.usbmodem14401"
baudRate: 115200,
});
this.serialPort.on("open", async () => {
await this.onConnected();
});
this.serialPort.on("close", () => {
this.onDisconnected();
});
this.serialPort.on("error", function(err) {
console.log("SerialPort Error: ", err.message)
});
this.serialPort.on("data", async (data) => {
await this.onDataReceived(data);
});
// open serial connection
this.serialPort.open();
}
async close() {
try {
await this.serialPort.close();
} catch(e) {
console.log("failed to close serial port, ignoring...", e);
}
}
/* override */ async write(bytes) {
this.serialPort.write(bytes);
}
}
export default NodeJSSerialConnection;