2025-04-08 12:14:04 +12:00
|
|
|
import SerialConnection from "./serial_connection.js";
|
|
|
|
|
|
|
|
|
|
class NodeJSSerialConnection extends SerialConnection {
|
|
|
|
|
|
|
|
|
|
/**
|
2026-02-18 05:49:46 -03:00
|
|
|
* @param {string} path serial port to connect to, e.g: "/dev/ttyACM0" or "/dev/cu.usbmodem14401"
|
2025-04-08 12:14:04 +12:00
|
|
|
*/
|
2025-04-08 12:18:12 +12:00
|
|
|
constructor(path) {
|
|
|
|
|
super();
|
2026-02-18 05:49:46 -03:00
|
|
|
/** @type {string} */
|
2025-04-08 12:18:12 +12:00
|
|
|
this.serialPortPath = path;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-18 05:49:46 -03:00
|
|
|
/** @returns {Promise<void>} */
|
2025-04-08 12:18:12 +12:00
|
|
|
async connect() {
|
2025-04-08 12:14:04 +12:00
|
|
|
|
|
|
|
|
// 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
|
2025-04-08 12:18:12 +12:00
|
|
|
path: this.serialPortPath, // e.g: "/dev/ttyACM0" or "/dev/cu.usbmodem14401"
|
2025-04-08 12:14:04 +12:00
|
|
|
baudRate: 115200,
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-08 12:36:42 +12:00
|
|
|
this.serialPort.on("open", async () => {
|
|
|
|
|
await this.onConnected();
|
2025-04-08 12:14:04 +12:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-18 05:49:46 -03:00
|
|
|
/** @returns {Promise<void>} */
|
2025-04-08 12:14:04 +12:00
|
|
|
async close() {
|
|
|
|
|
try {
|
|
|
|
|
await this.serialPort.close();
|
|
|
|
|
} catch(e) {
|
|
|
|
|
console.log("failed to close serial port, ignoring...", e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-18 05:49:46 -03:00
|
|
|
/**
|
|
|
|
|
* @param {Uint8Array} bytes
|
|
|
|
|
* @returns {Promise<void>}
|
|
|
|
|
*/
|
2025-04-08 12:14:04 +12:00
|
|
|
/* override */ async write(bytes) {
|
|
|
|
|
this.serialPort.write(bytes);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default NodeJSSerialConnection;
|