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); }); } // --- BASIC COMMANDS --- sendLine(cmd) { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(cmd + "\n"); } } requestStatus() { this.sendLine("?"); } jog(axis, value) { const cmd = `$J=G91 ${axis}${value} F2000`; this.sendLine(cmd); } sendGcode(cmd) { this.sendLine(cmd); } setZero() { this.sendLine("G92 X0 Y0 Z0"); } onMessage(fn) { this.on("message", fn); } } module.exports = FluidNCClient;