var startTime = Date.now() ; console.log("Meine Document-Location: " + document.location); var lastPingRequest; // Use explicit '/echo' path and a small wrapper to guard sends from other modules var socketUrl = (location.protocol === 'https:' ? 'wss://' : 'ws://') + window.location.host + '/echo'; console.log("WebSocket URL: " + socketUrl); // socket wrapper keeps the same global identifier but guards sends when underlying ws is not open var socket = { _ws: null, send: function(msg) { if (this._ws && this._ws.readyState === WebSocket.OPEN) { this._ws.send(msg); console.log('Sent message with WebSocket.OPEN:', msg); } else { console.warn('Socket not open, dropping message:', msg); } } }; let pingIntervalId = null; let reconnectDelay = 1000; function connect() { const ws = new WebSocket(socketUrl); socket._ws = ws; ws.onopen = () => { console.log('Connected to WS Server'); reconnectDelay = 1000; if (pingIntervalId) clearInterval(pingIntervalId); pingIntervalId = setInterval(() => { if (socket._ws && socket._ws.readyState === WebSocket.OPEN) { lastPingRequest = Date.now(); socket.send('Ping'); } }, 5000); }; ws.onclose = (event) => { console.log((event.wasClean) ? 'Disconnected' : 'Connection break: ' + (event.reason || event.code)); if (pingIntervalId) { clearInterval(pingIntervalId); pingIntervalId = null; } setTimeout(() => { console.log('Reconnecting...'); connect(); }, reconnectDelay); reconnectDelay = Math.min(30000, reconnectDelay * 2); }; ws.onmessage = (event) => { if(event.data == 'Ping'){ console.log('Ping: ' + (Date.now() - lastPingRequest).toString() + ' ms'); } else if(event.data.toString().includes('position')){ console.log('Position: ' + event.data); } else if(event.data.toString().includes('XYZ__FShow__XYZ')){ const content = event.data.toString().split('XYZ__FShow__XYZ')[1]; console.log('File Content: ' + content); const el = document.querySelector('textarea#GCodeWindow.editor-look'); if (el) el.value = content; } else{ console.log('DATA SinceStartup: ' + (Date.now() - startTime).toString() +': ', event.data); } }; ws.onerror = (err) => console.error('WebSocket error:', err || err.message); } connect();