Thursday, March 27, 2014

Getting Started with JavaFX Embedded on a Raspberry Pi

Learn how to quickly get a JavaFX simple application up and running on a Raspberry Pi development board.

Java 8 on the Raspberry Pi

Watch how a full version of Java SE & JavaFX run 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="/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.

Saturday, March 22, 2014

Video playlist - IoT and Java

Playlist for IoT and Java, include the following title:
  • Introduction to the Internet of Things
    What are some of the applications and devices in IoT space? In which industries are we seeing innovations? What kind of hardware can you use? What do you need to create your own project?
  • Java and the Internet of Things
    An Overview of the Java Embedded Platform, including Java SE Embedded, Java ME Embedded, and more.
  • Introduction to Raspberry Pi
    What is the Raspberry Pi? What do you need to install?
  • Java Embedded and Raspberry Pi - Part 1
  • Java Embedded and Raspberry Pi - Part 2
  • Gemalto Board Demo
    Build a Gemalto app and submit it to IoT Developer Challenge 

Enter the IoT Developer Challenge by May 30th, 2014 www.java.net/challenge.

Thursday, March 20, 2014

Raspberry Pi Starter Pack


Raspberry Pi Starter Pack
  • 512MB Raspberry Pi Model B with 8GB pre-loaded SD card
  • Adafruit Pi Cobbler Breakout Kit and Acrylic Case
  • 2A USB Wall Charger, USB Cable and HDMI Cable
  • Deluxe full-sized Breadboard and Jumper Wires
  • Mintronics Survival Pack Guts with 60+ Components -Includes Resistors, Capacitors, and More
By now you've probably heard of the Raspberry Pi -- the credit card-sized computer that runs Linux. It has many of the capabilities of a traditional PC and can be used for word processing, spreadsheets, and games. It can even play high-definition video and hook up to a TV or monitor. The Pi has been called many things (cheap, small, hackable, educational), but people seem to shy away from calling it "plug and play." That's because the Pi is not a consumer device as such, even though it's pretty easy to get something up and running on you TV. That's where our Raspberry Pi Starter Kit comes in: we've sourced all the proper peripherals and add-ons to get you up and running in all sorts of maker applications. The board was developed by the Raspberry Pi Foundation with the intention of bringing low cost, easy to program computers to young people all over the world. Once you get the "Raspbian" operating system loaded onto the kit's SD card, you can start programming right out of the box. The kit's selection of prototyping tools will also help you use the input and output capabilities of the Pi from your onboard programs. You'll still need to add your own USB keyboard and mouse, but otherwise, the Raspberry Pi Starter Kit includes all of the necessary cables (USB and HDMI), Adafruit's Cobbler GPIO (General Purpose Input/Output) breakout, a custom enclosure, a 8GB SD card, a breadboard for electronics prototyping, and plenty of common components to get you started. Includes a print copy of the Getting Started with Raspberry Pi book by Shawn Wallace and Matt Richardson.

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="/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

Wednesday, March 19, 2014

Build GTK+ Project using Code::Blocks on Raspberry Pi

In the Project Wizard of Code::Blocks, GTK+ Project is supported. But it cannot be compiled, because of lack of options for GTK+.

Prepare:

Create GTK+ Project with File > New > Project...
Select GTK+ project, with the auto-generated source code.

Set Build Options:
Project > Build options...
- In Compiler settings > Other options, add `pkg-config --cflags gtk+-3.0`.

Compiler settings > Other options
- In Linker settings > Other linker options, add `pkg-config --libs gtk+-3.0`.

Linker settings > Other linker options
Build and Run:
helloGtk

Install Code::Blocks on Raspberry Pi

Code::Blocks is a open source, cross platform, free C, C++ and Fortran IDE.

To install Code::Blocks on Raspberry Pi, enter the command:
sudo apt-get install codeblocks

Current installed version is 10.05.
Code::Blocks
Code::Blocks installed on Raspberry Pi
Once installed, Code::Blocks can be start by enter the command:
codeblocks

Or click Start in X-Window > Programming > Code::Blocks IDE


Tuesday, March 18, 2014

Install Oracle JDK 8 on Raspberry Pi

This post show how to download Oracle JDK 8 on a host PC running Ubuntu Linux, copy to, install and set default java and javac on Raspberry Pi.


Visit http://www.oracle.com/technetwork/java/javase/downloads/index.html, click the download button of Java Platform (JDK) 8. Click to Accept License Agreement, download jdk-8-linux-arm-vfp-hflt.tar.gz for Linux ARM v6/v7 Hard Float ABI.

Open terminal, enter the command to copy the download file to Raspberry Pi using scp.
$ scp jdk-8-linux-arm-vfp-hflt.tar.gz pi@<Raspberry Pi>:

Log-in Raspberry Pi, enter the command to extract jdk-8-linux-arm-vfp-hflt.tar.gz to /opt directory.
$ sudo tar zxvf jdk-8-linux-arm-vfp-hflt.tar.gz -C /opt

Set default java and javac to the new installed jdk8.
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0/bin/javac 1
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0/bin/java 1

$ sudo update-alternatives --config javac
$ sudo update-alternatives --config java

After all, verify with the commands with -verion option.
$ java -version
$ javac -version

BeagleBone Black vs Raspberry Pi

The video introduce the BeagleBone Black and compare it with Raspberry Pi. It go through the pros and cons of each device, show you how you can use them as well as show you footage of both the Black and the Pi working next to each other!


Monday, March 17, 2014

Cross compile Raspberry Pi kernel to inslude tsc2007.ko

As tsc2007 is included in the source tree of Raspberry Pi source, this post show how to download (git clone) Raspberry Pi source and cross-compile on another host PC running Ubuntu. Setup .config to include tsc2007 module with menuconfig option in make.


Please note:


Create our working directory, raspberrypi:
  • $ mkdir raspberrypi
  • cd raspberrypi
Before start our works, install the necessary tools and source code of Raspberry Pi linux:
  • $ git clone https://github.com/raspberrypi/tools.git
  • $ git clone https://github.com/raspberrypi/linux.git
  • $ cd linux
(For default setup) Prepare the .config file from pre-packaged config, bcmrpi_cutdown_defconfig:
  • $ make ARCH=arm CROSS_COMPILE=/usr/bin/arm-linux-gnueabi- bcmrpi_cutdown_defconfig
To generate .config with tsc2007 menu, run with menuconfig option:
  • $ make ARCH=arm CROSS_COMPILE=/usr/bin/arm-linux-gnueabi- menuconfig
You can find the following code will be added in the generated .config.

CONFIG_TOUCHSCREEN_TSC2007=m



Build kernel:
  • $ make ARCH=arm CROSS_COMPILE=/usr/bin/arm-linux-gnueabi-
  • $ mkdir ../modules
  • $ make modules_install ARCH=arm CROSS_COMPILE=/usr/bin/arm-linux-gnueabi- INSTALL_MOD_PATH=../modules/
  • $ cd ../tools/mkimage/
  • $ ./imagetool-uncompressed.py ../../linux/arch/arm/boot/Image


Now insert a Raspbian installed SD Card, and run the command:
  • $ sudo rm /media/<boot-partition>/kernel.img
  • $ sudo mv kernel.img /media/<boot-partition>/
  • $ sudo rm -rf /media/<rootfs-partition>/lib/modules/
  • $ sudo rm -rf /media/<rootfs-partition>/lib/firmware/
  • $ cd ../../modules/
  • $ sudo cp -a lib/modules/ /media/<rootfs-partition>/lib/
  • $ sudo cp -a lib/firmware/ /media/<rootfs-partition>/lib/
  • $ sync



Now you can run Raspberry Pi with this new build Image. tsc2007.ko is included, but not yet run. The following steps set it run in power up. Because tsc2007 is controlled with i2c bus, so it will be enabled also.

By default, i2c is disabled in Raspbian. To run tsc2007 and i2c modules, follow the step:
  • $ sudo nano /etc/modules
    add the lines:
    i2c-bcm2708
    i2c-dev
    tsc2007

  • $ sudo nano /etc/modprobe.d/raspi-blacklist.conf
    comment the line of
    #blacklist i2c-bcm2708
  • install i2c-tools for testing
    $ sudo apt-get install i2c-tools
  • reboot
  • After reboot, run i2c-tools to test
    run the command with -1 option for rev 2 board, or -0 for rev 1 board.
    $ sudo i2cdetect -y 1
    sudo i2cdetect -y 0





You can verify tsc2007 is running by lsmod command. But I don't know any more is needed to make the touch part of "Tontec 2.4-inch TFT LCD 240x320 RGB Pixels Touch Screen Display Monitor" to work!

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="/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="/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="/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

Friday, March 14, 2014

Kano OS for Raspberry Pi

Kano OS is another operating system for Raspberry Pi, based on Debian Linux with a simple interface, seamless setup, automagic WiFi and Updater, and fantastic coding projects for all ages. Make and play in Minecraft, Pong, Snake, Scratch, and more.

Get the OS and Books: http://www.kano.me/downloads

Introducing Kano OS -- Beta beauty for Raspberry Pi

Install Express for Node on Raspberry Pi

Express is a web application framework for Node.js. This post show how to install Express on Raspberry Pi, locally in working directory, and generate a app.

Express for node

It's assumed you have installed Node.js on your Raspberry Pi board.

- Make a working directory, for example helloExpress.
$ mkdir helloExpress
$ cd helloExpress

- Install Express locally
$ npm install express

- Because our Express installed locally without path setting, express have to be run with path node_modules/express/bin/express. To create our Hello World, myApp. Run:
$ node_modules/express/bin/express myApp

- Then change to the created directory myApp.
$ cd myApp

- Install with npm
$ npm install

- Run the app:
$ node app

Then you can visit your express web app at port 3000 of your Pi's IP address.


Monday, March 10, 2014

FREE Oracle Online Course: Develop Java Embedded Applications Using a Raspberry Pi

The FREE Oracle Massive Open Online Course: Develop Java Embedded Applications Using a Raspberry Pi is now open for enrollment, will start March 31st!

Java Embedded leverages your experience with Java to open the world of the Internet of Things by providing direct access to electronic sensors and mechanical devices.

This free course, designed for Java developers, is delivered over 5-weeks. Take the course at your own pace - weekly we will add new lessons, quizzes and homework assignments.

You will work on a real-world application to:

  • Read input data from switches and drive LED's using the GPIO interface
  • Read temperature and barometric pressure from an I2C device
  • Read the device's current location using a GPS UART device
  • Store and manage data collected
  • Report data to a client through a variety of communication options
  • And more!

To Enroll...

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);