How to get sensor data over TCP/IP in nodejs?

14,478

I have a decent hack that is working right now, for which I request the readers to comment on....


var net = require('net'),
http = require('http'),
port = 7700,                    // Datalogger port
host = '172.16.103.32',         // Datalogger IP address
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
    socket.emit('welcome', { message: 'Welcome!' });

    socket.on('i am client', console.log);
});

//Create a TCP socket to read data from datalogger
var socket = net.createConnection(port, host);

socket.on('error', function(error) {
  console.log("Error Connecting");
});

socket.on('connect', function(connect) {

  console.log('connection established');

  socket.setEncoding('ascii');

});

socket.on('data', function(data) {

  console.log('DATA ' + socket.remoteAddress + ': ' + data);
  io.sockets.emit('livedata', { livedata: data });        //This is where data is being sent to html file 

});

socket.on('end', function() {
  console.log('socket closing...');
});

app.listen(3000);

References:

  1. Socket.io Website - www.socket.io - Its the buzzword now.
  2. TCP Socket Programming
  3. Nodejs "net" module
  4. Simplest possible socket.io example.
Share:
14,478
Chintan Pathak
Author by

Chintan Pathak

Updated on June 04, 2022

Comments

  • Chintan Pathak
    Chintan Pathak almost 2 years

    I have a nodejs app with socket.io. To test this, save the below listing as app.js. Install node, then npm install socket.io and finally run on command prompt: node app.js

    var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');
    
    // Send index.html to all requests
    var app = http.createServer(function(req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(index);
    });
    
    // Socket.io server listens to our app
    var io = require('socket.io').listen(app);
    
    // Send current time to all connected clients
    function sendTime() {
        io.sockets.emit('time', { time: new Date().toJSON() });
    }
    
    // Send current time every 10 secs
    setInterval(sendTime, 5000);
    
    // Emit welcome message on connection
    io.sockets.on('connection', function(socket) {
        socket.emit('welcome', { message: 'Welcome!' });
    
        socket.on('i am client', console.log);
    });
    
    app.listen(3000);
    

    This code sends data to the file index.html. After running the app.js, open this file in your browser.

    <!doctype html>
    <html>
        <head>
            <script src='http://code.jquery.com/jquery-1.7.2.min.js'></script>
            <script src='http://localhost:3000/socket.io/socket.io.js'></script>
            <script>
                var socket = io.connect('//localhost:3000');
    
                socket.on('welcome', function(data) {
                    $('#messages').html(data.message);
    
                    socket.emit('i am client', {data: 'foo!'});
                });
                socket.on('time', function(data) {
                    console.log(data);
                    $('#messages').html(data.time);
                });
                socket.on('error', function() { console.error(arguments) });
                socket.on('message', function() { console.log(arguments) });
            </script>
        </head>
        <body>
            <p id='messages'></p>
        </body>
    </html>
    

    The data sent right now is the current time and index.html works fine, updates the time every five seconds.

    I want to modify the code so that, it reads my sensor data over TCP. My sensors are connected thru a data acquisition system and relays the sensor data over IP: 172.16.103.32 port:7700. (This is over LAN, so will not the accessible to you.)

    How can this be implemented in nodejs?

    Is SensorMonkey a viable alternative ? If so, any pointers on how to go about using it?

  • Shivasurya
    Shivasurya over 8 years
    hello,may i know how to handle event abruptly network error or ethernet power shutdown in TCP communication ? callbacks on error event listener aren't called appropriately when there is network error,how to handle that situation,Please help me - this is one of my issue in project
  • Chintan Pathak
    Chintan Pathak over 8 years
    As per my understanding NodeJS would only be able to 'catch' those errors that are reported to it, so network failure down the line is something that would not be handled as any different than Ethernet power shutdown. You may add a new question regarding this. What I generally do in cases like this is, restart the server if it crashes.
  • Shivasurya
    Shivasurya over 8 years
    Node.js notifies the error when connection reset or something like that or ends the connection if FIN packet is sent by server or client - what i did was to ping for certain intervals and make sure everything is online(solution for now) if any exception i reconnected/notified the admin