Files
appRobotControlScara/server/fluidnc/FluidNCClient.js
2026-04-22 22:06:45 +02:00

84 lines
2.5 KiB
JavaScript

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) => {
// console.log("[FluidNC] Received from FluidNC:", msg.toString());
// ExampleMessgae: <Idle|MPos:0.000,0.000,0.000|FS:0,0|Pn:P|WCO:0.000,0.000,-70.000>
// <Idle|MPos:0.000,0.000,0.000|FS:0,0|Pn:P>
if (!msg.toString().includes("<Idle|MPos:") && msg.toString() != "ok") {
console.log("[FluidNC] Received from FluidNC:", msg.toString());
}
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);
});
this.ws.on("unexpected-response", (req, res) => {
console.log("[FluidNC] WS Unexpected Response:", res.statusCode, res.statusMessage);
});
this.ws.on("disconnect", () => {
console.log("[FluidNC] WS Disconnected");
});
}
sendLine(cmd) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(cmd + "\n");
}
}
requestStatus() {
this.sendLine("?");
}
jog(relative, axis, value) {
// $J= um den Befehl als Jog zu kennzeichnen
// G91 für relative Bewegungen (G90 für absolute)
// G1 Linearbewegung
//const cmd = relative? `$J=G91 G1 ${axis}${value} F2000\r\n`: `$J=G90 G1 ${axis}${value} F2000\r\n`;
const cmd = relative? `G91 G1 ${axis}${value} F2000\r\n`: `G90 G1 ${axis}${value} F2000\r\n`;
console.log("[FluidNC] Jog Command:", cmd);
this.sendLine(cmd);
}
sendGcode(cmd) {
this.sendLine(cmd);
}
onMessage(fn) {
this.on("message", fn);
}
}
module.exports = FluidNCClient;