Showing posts with label example code.Node.js. Show all posts
Showing posts with label example code.Node.js. Show all posts

Wednesday, September 3, 2014

Node.js Chat Server on RPi, send msg to Arduino Uno, display on LCD Module

This example combine the last post of "Node.js Chat application using socket.io, run on Raspberry Pi", and "Node.js send string to Arduino Uno" in my another blog for Arduino. To create a Chat server, and send the received messages to USB connected Arduino Uno board, then display on the equipped 2x16 LCD Module on Arduino.


In order to use serialport in Node.js to send message to serial port, enter the command on Raspberry Pi command line to install serialport.
$ npm install serialport

Modify index.js in last post to add handles for serialport.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyACM0', 
    {   baudrate: 9600
    });
    
serialPort.on("open", function () {
    console.log('open');
});

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
    
    serialPort.write(msg, function(err, results) {
            console.log('err ' + err);
            console.log('results ' + results);
        });
    
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

For the sketch on Arduino Uno, refer to the post "Read from Arduino Serial port, and write to 2x16 LCD".

Node.js Chat application using socket.io, run on Raspberry Pi

The tutorial Get Started: Chat application describe how to create a basic chat application on Node.js using socket.io.

This video show how I following the tutorial to do the job on Raspberry Pi:

The next post show how to send the received messages to USB connected Arduino Uno using serialport, and display on LCD Module.


Wednesday, July 16, 2014

Node.js to read Raspberry Pi temperature

Last post show that we can get Raspberry Pi temperature via /sys/class/thermal/thermal_zone0/temp. This example show how to read it in Node.js.




var http = require("http");
var fs =  require("fs");

var server = http.createServer(function(request, response) {
    
    var temp = fs.readFileSync("/sys/class/thermal/thermal_zone0/temp");
    var temp_c = temp/1000;
    
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Raspberry Pi cpu temperature: ");
    response.write("\n" + temp);
    response.write("\n" + temp_c);
    response.end();
});
server.listen(8080);


Tuesday, April 15, 2014

Upload file using Node.js with formidable

This example implement web app using Node.js with formidable. formidable is a node.js module for parsing form data, especially file uploads. By default, the uploaded file will be aved in /tmp directory.

To install formidable, run the command in your working directory:
$ npm install formidable

Example code, app.js (tested on Raspberry Pi and Ubuntu):
// run the command to install formidable
// $ npm install formidable
var formidable = require('formidable');
var http = require('http');
var util = require('util');
var fs = require('fs');
var os = require('os');

var app = http.createServer(
 function(req, res){
  switch(req.method){
   case 'GET':
    showPage(req, res);
    break;
   case 'POST':
    upload(req, res);
    break;
  }
 }
);
app.listen(8080);

//Display my IP
var networkInterfaces=os.networkInterfaces();

for (var interface in networkInterfaces) {
    
    networkInterfaces[interface].forEach(
        function(details){
            
            if (details.family=='IPv4' 
                && details.internal==false) {
                    console.log(interface, details.address);  
        }
    });
}

function showPage(req, res){
 fs.readFile(__dirname + '/index.html',
  function (err, data) {
   if (err) {
    res.writeHead(500);
    return res.end('Error loading index.html');
   }
  
   res.writeHead(200);
   res.end(data); 
  });
}

function upload(req, res){

 var form = new formidable.IncomingForm();
 
 form.parse(req, function(err, fields, files) {
  res.writeHead(200, {'content-type': 'text/plain'});
  res.end('File uploaded!');
  console.log("Upload completed");
  console.log(util.inspect(files));
 });
 
}

index.html
<html>
<head></head>
<body>
<h1>Upload file</h1>
<h1>Test Node.js with formidable</h1>
<div>
<form action="/https/helloraspberrypi.blogspot.com/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"><br>
<input type="submit" value="Upload">
</form>
</div>

</body>
</html>

Upload file using Node.js with formidable, tested on Raspberry Pi.

Monday, March 24, 2014

Bi-directional control between Raspberry Pi + Node.js + Arduino

This example show how to pass data between Node.js client, Node.js server running on Raspberry Pi, and Arduino, bi-directionally. A Arduino Esplora is connected to Raspberry Pi, with Node.js running up a simple web app. Client can load the web app with Pi's IP and port 8080.

the tablet in the video for demo only.

From Node.js clients to server to Arduino:
- User can toggle the button to set Arduino LED ON/OFF.
- User can select color from of Arduino LCD color.

From Arduino to Node.js server to clients.
- When the Slider on Esplora changed, the setting will be sent to Node.js server to clients' progress bar on page.


Node.js code, app.js
var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app), 
    fs = require('fs'),
    os = require('os'),
    sp = require("serialport");
    
//All clients have a common status
var commonStatus = 'ON';
var commonColor = 0xffffff;
var commonSldValue = 0;
  
//init for SerialPort connected to Arduino
var SerialPort = sp.SerialPort
var serialPort = new SerialPort('/dev/ttyACM0', 
    {   baudrate: 9600,
        dataBits: 8,
        parity: 'none',
        stopBits: 1,
        flowControl: false
    });
    
var receivedData = "";
    
serialPort.on("open", function () {
    console.log('serialPort open');
    serialPort.write("LEDOFF\n");
    
    //handle data receive from Arduino
    serialPort.on('data', function(data) {
  receivedData += data.toString();
  if (receivedData.indexOf("SLD#") >= 0 
   && receivedData.indexOf("\n") >= 0) {
    
   sldValue = receivedData.substring(
    receivedData.indexOf("SLD#")+4, 
    receivedData.indexOf("\n"));
    
   receivedData = "";
   
   if ((sldValue.length == 1)
    || (sldValue.length == 2)){
    commonSldValue = parseInt("0x"+sldValue); 
    io.sockets.emit('update slider', 
       { value: commonSldValue});
    console.log('update slider: ' + commonSldValue);
   } 
  }
 });
    
});
    
//Display my IP
var networkInterfaces=os.networkInterfaces();

for (var interface in networkInterfaces) {
    
    networkInterfaces[interface].forEach(
        function(details){
            
            if (details.family=='IPv4' 
                && details.internal==false) {
                    console.log(interface, details.address);  
        }
    });
}

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    
    //Send client with his socket id
    socket.emit('your id', 
        { id: socket.id});
    
    //Info all clients a new client caaonnected
    io.sockets.emit('on connection', 
        { client: socket.id,
          clientCount: io.sockets.clients().length,
        });
        
    //Set the current common status to the new client
    socket.emit('ack button status', { status: commonStatus });
    socket.emit('ack color', { color: commonColor });
    socket.emit('update slider', { value: commonSldValue});
    
    socket.on('button update event', function (data) {
        console.log(data.status);
        
        //acknowledge with inverted status, 
        //to toggle button text in client
        if(data.status == 'ON'){
            console.log("ON->OFF");
            commonStatus = 'OFF';
            serialPort.write("LEDON\n");
        }else{
            console.log("OFF->ON");
            commonStatus = 'ON';
            serialPort.write("LEDOFF\n");
        }
        io.sockets.emit('ack button status', 
            { status: commonStatus,
              by: socket.id
            });
    });
    
    socket.on('update color', function (data) {
  commonColor = data.color;
  console.log("set color: " + commonColor);
  var stringColorHex = "COL" + commonColor.toString(16);
  console.log("stringColorHex: " + stringColorHex);
  
  serialPort.write(stringColorHex + "\n");
  
  io.sockets.emit('ack color', 
   { color: data.color,
     by: socket.id
   });
 });
    
    //Info all clients if this client disconnect
    socket.on('disconnect', function () {
        io.sockets.emit('on disconnect', 
            { client: socket.id,
              clientCount: io.sockets.clients().length-1,
            });
    });
});

index.html
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, user-scalable=no">
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
       onclick="toggle(this);">
</form>
<br/>
Select color: <br/>
<input id="colorpick" type="color" name="favcolor" 
 onchange="JavaScript:colorchanged()"><br>
<br/>
<progress id="progressbar" max="255"><span>0</span>%</progress>


<script src="/https/helloraspberrypi.blogspot.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);
var myId;

socket.on('update slider', function (data) {
    console.log("update slider: " + data.value);
    document.getElementById("progressbar").value = data.value;
});

socket.on('on connection', function (data) {
    console.log("on connection: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('on disconnect',function(data) {
    console.log("on disconnect: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('your id',function(data) {
    console.log("your id: " + data.id);
    myId = data.id;
});

socket.on('ack button status', function (data) {
    console.log("status: " + data.status);
    
    if(myId==data.by){
        console.log("by YOU");
    }else{
        console.log("by: " + data.by);
    }
    
    if(data.status =='ON'){
        document.getElementById("buttonToggle").value="ON";
    }else{
        document.getElementById("buttonToggle").value="OFF";
    }
});

socket.on('ack color', function (data) {
    console.log("ack color: " + data.color);
    document.body.style.background = data.color;
    if(myId==data.by){
        console.log("by YOU");
    }else{
        console.log("by: " + data.by);
    }
});

function toggle(button)
{
 if(document.getElementById("buttonToggle").value=="OFF"){
  socket.emit('button update event', { status: 'OFF' });
 }
 else if(document.getElementById("buttonToggle").value=="ON"){
  socket.emit('button update event', { status: 'ON' });
 }
}

function colorchanged()
{
 //console.log("colorchanged()");
 var colorval = document.getElementById("colorpick").value;
 console.log("colorchanged(): " + colorval);
 //document.body.style.background = colorval;
 socket.emit('update color', { color: colorval });
}

</script>

</body>
</html>

Arduino code:
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

int MAX_CMD_LENGTH = 10;
char cmd[10];
int cmdIndex;
char incomingByte;

int prevSlider = 0;

void setup() {
  
    EsploraTFT.begin();  
    EsploraTFT.background(0,0,0);
    EsploraTFT.stroke(255,255,255);  //preset stroke color
     
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    
    //indicate start
    Esplora.writeRGB(255, 255, 255);
    delay(250);
    Esplora.writeRGB(0, 0, 0);
    
    cmdIndex = 0;
    
}
 
void loop() {
    
    if (incomingByte=Serial.available()>0) {
      
      char byteIn = Serial.read();
      cmd[cmdIndex] = byteIn;
      
      if(byteIn=='\n'){
        //command finished
        cmd[cmdIndex] = '\0';
        //Serial.println(cmd);
        cmdIndex = 0;
        
        String stringCmd = String(cmd);
        
        if(strcmp(cmd, "LEDON")  == 0){
          //Serial.println("Command received: LEDON");
          Esplora.writeRGB(255, 255, 255);
        }else if (strcmp(cmd, "LEDOFF")  == 0) {
          //Serial.println("Command received: LEDOFF");
          Esplora.writeRGB(0, 0, 0);
        }else if(stringCmd.substring(0,4)="COL#"){
          //Serial.println("Command received: COL#");
          if(stringCmd.length()==10){
            char * pEnd;
            long int rgb = strtol(&cmd[4], &pEnd, 16);
            int r = (rgb & 0xff0000) >> 16;
            int g = (rgb & 0xff00) >> 8;
            int b = rgb & 0xff;
            //Serial.println(r);
            //Serial.println(g);
            //Serial.println(b);
            EsploraTFT.background(b,g,r);
          }
        }else{
          //Serial.println("Command received: unknown!");
        }
        
      }else{
        if(cmdIndex++ >= MAX_CMD_LENGTH){
          cmdIndex = 0;
        }
      }
    }
    
    //Read Slider
    int slider = Esplora.readSlider();
    //convert slider value from [0-1023] to [0x00-0xFF]
    slider = slider>>2 & 0xff;
    
    if(slider!=prevSlider){
      prevSlider = slider;
      
      String stringSlider = String(slider, HEX);
      Serial.println("SLD#" + stringSlider +"\n");
    }
    
}

Cross post with Arduino-er, same code run on PC running Ubuntu Linux.

Thursday, March 20, 2014

Node.js+socket.io+serialport = web app to control Pi connected Arduino

This is a example to implement a web app with Node.js running on Raspberry Pi, to receive command from client, and control connected Arduino Esplora's LED. All clients share a common hardware: when a client toggle the LED, all clients will be updated accordingly.


This example should be run on any other Node.js supported platform, with changing SerialPort name. The tablet is used to log-in Raspberry Pi to start the app, for demonstrate only, not a part of the example.

You have to install socket.io and serialport modules for Node.js:
$ npm install socket.io
$ npm install serialport

app.js
var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app), 
    fs = require('fs'),
    os = require('os'),
    sp = require("serialport");
  
//init for SerialPort connected to Arduino
var SerialPort = sp.SerialPort
var serialPort = new SerialPort('/dev/ttyACM0', 
    {   baudrate: 9600,
        dataBits: 8,
        parity: 'none',
        stopBits: 1,
        flowControl: false
    });
    
serialPort.on("open", function () {
    console.log('serialPort open');
    serialPort.write("LEDOFF\n");
});
    
//Display my IP
var networkInterfaces=os.networkInterfaces();

for (var interface in networkInterfaces) {
    
    networkInterfaces[interface].forEach(
        function(details){
            
            if (details.family=='IPv4' 
                && details.internal==false) {
                    console.log(interface, details.address);  
        }
    });
}

//All clients have a common status
var commonStatus = 'ON';

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    
    //Send client with his socket id
    socket.emit('your id', 
        { id: socket.id});
    
    //Info all clients a new client caaonnected
    io.sockets.emit('on connection', 
        { client: socket.id,
          clientCount: io.sockets.clients().length,
        });
        
    //Set the current common status to the new client
    socket.emit('ack button status', { status: commonStatus });
    
    socket.on('button update event', function (data) {
        console.log(data.status);
        
        //acknowledge with inverted status, 
        //to toggle button text in client
        if(data.status == 'ON'){
            console.log("ON->OFF");
            commonStatus = 'OFF';
            serialPort.write("LEDON\n");
        }else{
            console.log("OFF->ON");
            commonStatus = 'ON';
            serialPort.write("LEDOFF\n");
        }
        io.sockets.emit('ack button status', 
            { status: commonStatus,
              by: socket.id
            });
    });
    
    //Info all clients if this client disconnect
    socket.on('disconnect', function () {
        io.sockets.emit('on disconnect', 
            { client: socket.id,
              clientCount: io.sockets.clients().length-1,
            });
    });
});

index.html
<html>
<meta name="viewport" content="width=device-width, user-scalable=no">
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
       onclick="toggle(this);">
</form>
<script src="/https/helloraspberrypi.blogspot.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);
var myId;

socket.on('on connection', function (data) {
    console.log("on connection: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('on disconnect',function(data) {
    console.log("on disconnect: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('your id',function(data) {
    console.log("your id: " + data.id);
    myId = data.id;
});

socket.on('ack button status', function (data) {
    console.log("status: " + data.status);
    
    if(myId==data.by){
        console.log("by YOU");
    }else{
        console.log("by: " + data.by);
    }
    
    if(data.status =='ON'){
        document.getElementById("buttonToggle").value="ON";
    }else{
        document.getElementById("buttonToggle").value="OFF";
    }
});

function toggle(button)
{
 if(document.getElementById("buttonToggle").value=="OFF"){
  socket.emit('button update event', { status: 'OFF' });
 }
 else if(document.getElementById("buttonToggle").value=="ON"){
  socket.emit('button update event', { status: 'ON' });
 }
}
</script>

</body>
</html>

Arduino code
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

int MAX_CMD_LENGTH = 10;
char cmd[10];
int cmdIndex;
char incomingByte;

void setup() {
  
    EsploraTFT.begin();  
    EsploraTFT.background(0,0,0);
    EsploraTFT.stroke(255,255,255);  //preset stroke color
     
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    
    //indicate start
    Esplora.writeRGB(255, 255, 255);
    delay(250);
    Esplora.writeRGB(0, 0, 0);
    
    cmdIndex = 0;
    
}
 
void loop() {
    
    if (incomingByte=Serial.available()>0) {
      
      char byteIn = Serial.read();
      cmd[cmdIndex] = byteIn;
      
      if(byteIn=='\n'){
        //command finished
        cmd[cmdIndex] = '\0';
        Serial.println(cmd);
        cmdIndex = 0;
        
        if(strcmp(cmd, "LEDON")  == 0){
          Serial.println("Command received: LEDON");
          Esplora.writeRGB(255, 255, 255);
        }else if (strcmp(cmd, "LEDOFF")  == 0) {
          Serial.println("Command received: LEDOFF");
          Esplora.writeRGB(0, 0, 0);
        }else{
          Serial.println("Command received: unknown!");
        }
        
      }else{
        if(cmdIndex++ >= MAX_CMD_LENGTH){
          cmdIndex = 0;
        }
      }
    }
    
}

Cross post with Arduino-er

Next: Bi-directional control between Raspberry Pi + Node.js + Arduino

Sunday, March 16, 2014

Node.js + Socket.IO: share common status for all clients

Last post have individual status for each client. In this example, all client share one common status, that means client A click to change status, not only his button text will change, but also all other clients will change.


In this example:
  • All clients share a common status, commonStatus.
  • Will info new client his id, socket.id.
  • Server will broadcast all clients if any new client connected, io.sockets.emit(). Also info the number of client connected, io.sockets.clients().length.
  • Info the current common status to new connected client.
  • Info all clients if a client disconnected, socket.on('disconnect', function).
app.js
//$ npm install socket.io

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

//All clients have a common status
var commonStatus = 'ON';

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    
    //Send client with his socket id
    socket.emit('your id', 
        { id: socket.id});
    
    //Info all clients a new client caaonnected
    io.sockets.emit('on connection', 
        { client: socket.id,
          clientCount: io.sockets.clients().length,
        });
        
    //Set the current common status to the new client
    socket.emit('ack button status', { status: commonStatus });
    
    socket.on('button update event', function (data) {
        console.log(data.status);
        
        //acknowledge with inverted status, 
        //to toggle button text in client
        if(data.status == 'ON'){
            console.log("ON->OFF");
            commonStatus = 'OFF';
            
        }else{
            console.log("OFF->ON");
            commonStatus = 'ON';
        }
        io.sockets.emit('ack button status', 
            { status: commonStatus,
              by: socket.id
            });
    });
    
    //Info all clients if this client disconnect
    socket.on('disconnect', function () {
        io.sockets.emit('on disconnect', 
            { client: socket.id,
              clientCount: io.sockets.clients().length-1,
            });
    });
});

index.html
<html>
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
       onclick="toggle(this);">
</form>
<script src="/https/helloraspberrypi.blogspot.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);
var myId;

socket.on('on connection', function (data) {
    console.log("on connection: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('on disconnect',function(data) {
    console.log("on disconnect: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('your id',function(data) {
    console.log("your id: " + data.id);
    myId = data.id;
});

socket.on('ack button status', function (data) {
    console.log("status: " + data.status);
    
    if(myId==data.by){
        console.log("by YOU");
    }else{
        console.log("by: " + data.by);
    }
    
    if(data.status =='ON'){
        document.getElementById("buttonToggle").value="ON";
    }else{
        document.getElementById("buttonToggle").value="OFF";
    }
});

function toggle(button)
{
 if(document.getElementById("buttonToggle").value=="OFF"){
  socket.emit('button update event', { status: 'OFF' });
 }
 else if(document.getElementById("buttonToggle").value=="ON"){
  socket.emit('button update event', { status: 'ON' });
 }
}
</script>

</body>
</html>

Node.js + Socket.IO: acknowledge from server

Last example send button status to server from client, and toggle button status in client side without acknowledge from server. It is modified to send back acknowledge from server with inverted status, and update button status in client once acknowledge received.


app.js
//$ npm install socket.io

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    socket.on('button update event', function (data) {
        console.log(data.status);
        
        //acknowledge with inverted status, 
        //to toggle button text in client
        if(data.status == 'ON'){
            console.log("ON->OFF");
            socket.emit('ack button status', { status: 'OFF' });
        }else{
            console.log("OFF->ON");
            socket.emit('ack button status', { status: 'ON' });
        }
                    
        
    });
});

index.html
<html>
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
       onclick="toggle(this);">
</form>
<script src="/https/helloraspberrypi.blogspot.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);

socket.on('ack button status', function (data) {
    console.log(data.status);
    if(data.status =='ON'){
        document.getElementById("buttonToggle").value="ON";
    }else{
        document.getElementById("buttonToggle").value="OFF";
    }
});

function toggle(button)
{
 if(document.getElementById("buttonToggle").value=="OFF"){
  socket.emit('button update event', { status: 'OFF' });
 }
 else if(document.getElementById("buttonToggle").value=="ON"){
  socket.emit('button update event', { status: 'ON' });
 }
}
</script>

</body>
</html>

Next: Share common status for all clients

Node.js app using Socket.IO

Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It's care-free realtime 100% in JavaScript.

This example create a simple web app to receive the status of a toggle button from client.


Before using Socket.IO on your Node.js app, run the command to install:
$ npm install socket.io

app.js run in server side:
//$ npm install socket.io

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.on('button update event', function (data) {
    console.log(data.status);
  });
});

index.html, it will be sent to and run on client side.
<html>
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
       onclick="toggle(this);">
</form>
<script src="/https/helloraspberrypi.blogspot.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);

function toggle(button)
{
 if(document.getElementById("buttonToggle").value=="OFF"){
  document.getElementById("buttonToggle").value="ON";
  socket.emit('button update event', { status: 'OFF' });
 }
 else if(document.getElementById("buttonToggle").value=="ON"){
  document.getElementById("buttonToggle").value="OFF";
  socket.emit('button update event', { status: 'ON' });
 }
}
</script>

</body>
</html>

Run the app.js in server:
$ node app

Visit <server IP>:8080 with browser in client side.


Next: Acknowledge from server

Monday, March 10, 2014

Communication between Raspberry Pi and Arduino, using Node.js

The 'serialport' module for Node.js provide basic building block to make Node.js communication with serial port. Here is a simple example to send data between Raspberry Pi and Arduino Esplora board via USB, using Node.js.

Cross-post with Arduino-er: Arduino + Raspberry Pi + Node.js



node_arduino.js, Node.js script run on Raspberry Pi side.
//To install 'serialport' locally, enter the command:
//$ npm install serialport
//Otherwise, Error: Cannot find module 'serialport' will reported

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyACM0', 
    {   baudrate: 9600,
        dataBits: 8,
        parity: 'none',
        stopBits: 1,
        flowControl: false
    });

serialPort.on("open", function () {
    console.log('open');
    serialPort.on('data', function(data) {
        console.log('data received: ' + data);
        });
    serialPort.write("Hello from Raspberry Pi\n", function(err, results) {
        console.log('err ' + err);
        console.log('results ' + results);
        });
});

The code in Arduino Esplora board.
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>
 
int prevSw1 = HIGH;
int incomingByte = 0;
String charsIn = "";
char printout[20];  //max char to print: 20
  
void setup() {
   
    EsploraTFT.begin();  
    EsploraTFT.background(0,0,0);
    EsploraTFT.stroke(255,255,255);  //preset stroke color
      
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
     
    //indicate start
    Esplora.writeRGB(255, 255, 255);
    delay(250);
    Esplora.writeRGB(0, 0, 0);
     
}
  
void loop() {
    int sw1 = Esplora.readButton(SWITCH_1);
    if(sw1 != prevSw1){
      if(sw1 == LOW){
        Serial.println("Hello from Arduino Esplora");
      }
      prevSw1 = sw1;
    }
     
    while (Serial.available()) {
      char charRead = Serial.read();
      charsIn.concat(charRead);
    }
    if(charsIn != ""){
      Serial.println("How are you, " + charsIn);
      charsIn.toCharArray(printout, 21);
      EsploraTFT.background(0,0,0);
      EsploraTFT.text(printout, 0, 10);
      charsIn = "";
    }
}

Tuesday, March 4, 2014

Node.js example: get command line arguments

The array process.argv will be passed containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

Example:
console.log('process.argv[0]: ' + process.argv[0]);
console.log('process.argv[1]: ' + process.argv[1]);
console.log('process.argv[2]: ' + process.argv[2]);

console.log("process.argv.length: " + process.argv.length);

process.argv.forEach(function(val, index, array) {
    console.log(index + ': ' + val);
});

Node.js example: get command line arguments
Node.js example: get command line arguments

Node.js server and client, run on Raspberry Pi

Last post implement Node.js net server side, connected with client in Android device. This post show the client side implemented in Node.js.



node_client.js
var net = require('net');

var client = net.connect({port: 8081, host: '192.168.1.105'},
                function() {
                    console.log('connected');
                    client.write('world!\r\n');
                });

client.on('data', 
    function(data) {
        console.log(data.toString());
        client.end();
    }
);

client.on('end', 
    function() {
        console.log('client disconnected');
    }
);


node_server.js (same as in last post)
var os=require('os');
var net=require('net');

var networkInterfaces=os.networkInterfaces();

var port = 8081;
var count = 1;

function callback_server_connection(socket){
    var remoteAddress = socket.remoteAddress;
    var remotePort = socket.remotePort;
    socket.setNoDelay(true);
    console.log("connected: ", remoteAddress, " : ", remotePort);
    
    var msg = 'Hello ' + remoteAddress + ' : ' +  remotePort + '\r\n'
        + "You are #" + count + '\r\n';
    count++;

    socket.end(msg);
    
    socket.on('data', function (data) {
        console.log(data.toString());
    });
    
    socket.on('end', function () {
        console.log("ended: ", remoteAddress, " : ", remotePort);
    });
}

console.log("http://android-er.blogspot.com/");
console.log("http://helloraspberrypi.blogspot.com/");

console.log("node.js net server is waiting:");
for (var interface in networkInterfaces) {

    networkInterfaces[interface].forEach(function(details){
        
        if ((details.family=='IPv4') && !details.internal) {
            console.log(interface, details.address);  
        }
    });
}

console.log("port: ", port);

var netServer = net.createServer(callback_server_connection);
netServer.listen(port);


Sunday, March 2, 2014

Create TCP server using Node,js with net module, run on Raspberry Pi, connected with Android

This example create TCP server with Node.js using net module, run on Raspberry Pi. To test it with Android client side app, refer to the example at Android Server/Client example - client side using Socket.
Server side implemented with Node.js, run on Raspberry Pi.
Server side implemented with Node.js, run on Raspberry Pi.

Client side run on Android
Client side run on Android
When the Node.js program run, it list it's own IP address and assigned port, and wait for client. In client side running on Android, enter the server IP and port, and connect. When client connect to server, server side will send back a message and end the connection.


Node.js code in server side.
var os=require('os');
var net=require('net');

var networkInterfaces=os.networkInterfaces();

var port = 8081;
var count = 1;

function callback_server_connection(socket){
    var remoteAddress = socket.remoteAddress;
    var remotePort = socket.remotePort;
    socket.setNoDelay(true);
    console.log("connected: ", remoteAddress, " : ", remotePort);
    
    var msg = 'Hello ' + remoteAddress + ' : ' +  remotePort + '\r\n'
        + "You are #" + count + '\r\n';
    count++;

    socket.end(msg);
    
    socket.on('data', function (data) {
        console.log(data.toString());
    });
    
    socket.on('end', function () {
        console.log("ended: ", remoteAddress, " : ", remotePort);
    });
}

console.log("http://android-er.blogspot.com/");
console.log("http://helloraspberrypi.blogspot.com/");

console.log("node.js net server is waiting:");
for (var interface in networkInterfaces) {

    networkInterfaces[interface].forEach(function(details){
        
        if ((details.family=='IPv4') && !details.internal) {
            console.log(interface, details.address);  
        }
    });
}

console.log("port: ", port);

var netServer = net.createServer(callback_server_connection);
netServer.listen(port);


Next:
- Node.js server and client, run on Raspberry Pi


Node.js: get my IP address

This example list my IP address, coded in Node.js, with module os, run on Raspberry Pi.

list my IP address
list my IP address

var os=require('os');

var networkInterfaces=os.networkInterfaces();

for (var interface in networkInterfaces) {
    
    networkInterfaces[interface].forEach(function(details){
        
        if (details.family=='IPv4') {
            console.log(interface, details.address, 
                        " internal: ", details.internal);  
        }
    });
}

Node.js: get OS info

The Node.js core module "os" provide some info of the system operating system.

Here is example to list os info of Raspberry Pi, coded with Node.js.

Get os info in Node.js
Node.js to read OS info

var os= require("os");

console.log("\nhttp://helloraspberrypi.blogspot.com/\n");

console.log("os.tmpdir(): ", os.tmpdir());

console.log("os.endianness()= ", os.endianness());
console.log("os.hostname()= ", os.hostname());
console.log("os.type()= ", os.type());
console.log("os.platform()= ", os.platform());
console.log("os.arch(): ", os.arch());
console.log("os.release()= ", os.release());
console.log("os.uptime()= ", os.uptime());
console.log("os.loadavg()= ", os.loadavg());
console.log("os.totalmem()= ", os.totalmem());
console.log("os.freemem()= ", os.freemem());
console.log("os.cpus()= \n", os.cpus());
console.log("os.networkInterfaces()= \n", os.networkInterfaces());
console.log("os.EOL= ", os.EOL);

Saturday, December 21, 2013

"Hello World" Node.js on Raspberry Pi

This post create a Node.js code on Raspberry Pi, to run a http server on port 8081, it can be visit by other PC.
"Hello World" Node.js on Raspberry Pi
"Hello World" Node.js on Raspberry Pi
To create a "Hello World" of Node.js, create hellonode.js, enter the code:
var http = require("http");

var server = http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World of Node.js, on Raspberry Pi");
    response.end();
});
server.listen(8081);

This code setup a http server to monitor port 8081, using node.

Run node in Terminal:
$ node hellonode.js
or
$ node hellonode

From another PC in the network, open a browser and vist <Pi IP address>:8081 to visit the node's http server.



Related: Install Node.js on Raspberry Pi