// server/InputWS.js const fs = require('fs'); const WebSocket = require('ws'); function initInputWS(server, robot, GCode, sharedState) { const wss = new WebSocket.Server({ server }); wss.on('connection', (ws) => { console.log("WebSocket Input connected"); const clientIP = ws._socket.remoteAddress || 'unknown'; sharedState.connectedClients.push(clientIP); ws.on('close', () => { sharedState.connectedClients = sharedState.connectedClients.filter(ip => ip !== clientIP); }); ws.on('message', (msg) => { const message = msg.toString(); /* ---------- Ping ---------- */ if (message === "Ping") { logPing(sharedState, clientIP); broadcast(wss, message); return; } /* ---------- GCode ---------- */ if (GCode.containsCommand(message)) { logCommand(sharedState, clientIP, message); GCode.receiveGCode(robot, message); broadcast(wss, GCode.getM114(robot)); return; } /* ---------- File Commands ---------- */ if (GCode.ContainsFilesCommand(message)) { logCommand(sharedState, clientIP, message); broadcast(wss, GCode.receiveFC(robot, message)); return; } /* ---------- Status ---------- */ if (message === "M114") { logCommand(sharedState, clientIP, message); broadcast(wss, GCode.getM114(robot)); } }); }); return wss; } /* ---------- Helpers ---------- */ function broadcast(wss, payload) { wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(payload); } }); } function logCommand(state, ip, message) { fs.appendFileSync( './logs/gcode_commands.log', `${new Date().toISOString()} ${ip}: ${message}\n` ); state.lastCommands.push(`${new Date().toISOString()}: ${message}`); if (state.lastCommands.length > 10) state.lastCommands.shift(); } function logPing(state, ip) { fs.appendFileSync( './logs/pings.log', `${new Date().toISOString()} ${ip}: Ping\n` ); state.lastPings.push(`${new Date().toISOString()}: Ping`); if (state.lastPings.length > 10) state.lastPings.shift(); } module.exports = initInputWS;