77 lines
1.9 KiB
JavaScript
77 lines
1.9 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) => {
|
|
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`;
|
|
console.log("[FluidNC] Jog Command:", cmd);
|
|
this.sendLine(cmd);
|
|
}
|
|
|
|
sendGcode(cmd) {
|
|
this.sendLine(cmd);
|
|
}
|
|
|
|
onMessage(fn) {
|
|
this.on("message", fn);
|
|
}
|
|
}
|
|
|
|
module.exports = FluidNCClient; |