88 lines
1.5 KiB
JavaScript
88 lines
1.5 KiB
JavaScript
const net = require("net");
|
|
|
|
class TelnetConnection {
|
|
|
|
constructor(config){
|
|
|
|
this.host = config.host;
|
|
this.port = config.port;
|
|
this.reconnectDelay = config.reconnectDelay || 30000;
|
|
|
|
this.socket = null;
|
|
|
|
this.dataListeners = [];
|
|
this.connectionListeners = [];
|
|
|
|
this.connect();
|
|
}
|
|
|
|
connect(){
|
|
|
|
console.log("Connecting to FluidNC:", this.host);
|
|
|
|
this.socket = net.createConnection({
|
|
host: this.host,
|
|
port: this.port
|
|
});
|
|
|
|
this.socket.on("connect",()=>{
|
|
|
|
console.log("FluidNC connected");
|
|
|
|
this.connectionListeners.forEach(fn=>fn(true));
|
|
|
|
});
|
|
|
|
this.socket.on("data",(data)=>{
|
|
|
|
const msg = data.toString();
|
|
|
|
this.dataListeners.forEach(fn=>fn(msg));
|
|
|
|
});
|
|
|
|
this.socket.on("close",()=>{
|
|
|
|
console.log("FluidNC disconnected");
|
|
|
|
this.connectionListeners.forEach(fn=>fn(false));
|
|
|
|
setTimeout(()=>{
|
|
this.connect();
|
|
}, this.reconnectDelay);
|
|
|
|
});
|
|
|
|
this.socket.on("error",(err)=>{
|
|
console.log("Telnet error:",err.message);
|
|
});
|
|
|
|
}
|
|
|
|
send(cmd){
|
|
|
|
if(!this.socket) return;
|
|
|
|
this.socket.write(cmd+"\n");
|
|
|
|
}
|
|
|
|
realtime(cmd){
|
|
|
|
if(!this.socket) return;
|
|
|
|
this.socket.write(cmd);
|
|
|
|
}
|
|
|
|
onData(fn){
|
|
this.dataListeners.push(fn);
|
|
}
|
|
|
|
onConnection(fn){
|
|
this.connectionListeners.push(fn);
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = TelnetConnection; |