Create a gist now

Instantly share code, notes, and snippets.

SerialPort TCP/IP Host server
var net = require('net');
var SerialPort = require('serialport').SerialPort;
//possibly something like COM1 on windows
var SERIAL_PORT = process.env.SERIAL_PORT || '/dev/tty.usbmodem1421';
var PORT = process.env.PORT || 3001;
var serialPort = new SerialPort(SERIAL_PORT,{
baudrate: 57600,
buffersize: 1
});
var clients = {};
serialPort.on('data', function(data){
for(var id in clients){
try{
clients[id].write(data);
}catch(exp){
console.log('error writing to client', id, exp);
}
}
});
var server = net.createServer(function(c) {
c.id = 'c' + Math.random() + '_' + Date.now();
clients[c.id] = c;
console.log('client connected', c.id);
c.on('end', function() {
console.log('client disconnected', c.id);
delete clients[c.id];
});
c.on('data', function(data){
serialPort.write(data);
});
});
server.listen(PORT, function() {
console.log('server bound to port: ' + PORT);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment