60 lines
1.4 KiB
JavaScript
Executable File
60 lines
1.4 KiB
JavaScript
Executable File
const WebSocket = require("ws");
|
|
const EventEmitter = require("events");
|
|
|
|
class FluidNCClient extends EventEmitter {
|
|
constructor(cfg) {
|
|
super();
|
|
|
|
this.host = cfg.host;
|
|
this.port = cfg.port || 81;
|
|
|
|
this.ws = null;
|
|
this.reconnectDelay = 2000;
|
|
|
|
this.connect();
|
|
}
|
|
|
|
connect() {
|
|
const url = `ws://${this.host}:${this.port}`;
|
|
console.log("[FluidNC] Connecting to:", url);
|
|
|
|
this.ws = new WebSocket(url);
|
|
|
|
this.ws.on("open", () => {
|
|
console.log("[FluidNC] Connected (WS)");
|
|
});
|
|
|
|
this.ws.on("message", (msg) => {
|
|
this.emit("message", msg.toString());
|
|
});
|
|
|
|
this.ws.on("close", () => {
|
|
console.log("[FluidNC] Disconnected → retry");
|
|
setTimeout(() => this.connect(), this.reconnectDelay);
|
|
});
|
|
|
|
this.ws.on("error", (err) => {
|
|
console.log("[FluidNC] WS Error:", err.message);
|
|
});
|
|
}
|
|
|
|
sendLine(cmd) {
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
this.ws.send(cmd + "\n");
|
|
}
|
|
}
|
|
|
|
requestStatus() {
|
|
this.sendLine("?");
|
|
}
|
|
|
|
sendGcode(cmd) {
|
|
this.sendLine(cmd);
|
|
}
|
|
|
|
onMessage(fn) {
|
|
this.on("message", fn);
|
|
}
|
|
}
|
|
|
|
module.exports = FluidNCClient; |