initial
This commit is contained in:
88
network/TelnetConnection.js
Normal file
88
network/TelnetConnection.js
Normal file
@@ -0,0 +1,88 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user